suno_core/ffmpeg.rs
1//! The ffmpeg port: transcode WAV bytes to FLAC bytes, and MP4 video previews
2//! to animated WebP cover bytes.
3//!
4//! The lossless download path renders a clip to WAV, then re-encodes it to
5//! FLAC. The animated-cover path fetches a clip's MP4 preview and re-encodes it
6//! to a small looping WebP. Both are the engine's only calls into ffmpeg, so
7//! they sit behind this trait: the CLI adapter wraps a child process (with a
8//! hard timeout), while tests use a stub that returns canned bytes. The steps
9//! only re-encode media; tagging is the pure tagger's job.
10
11use std::future::Future;
12
13use crate::vocab::{AudioFormat, WebpEncodeSettings};
14
15/// Why an ffmpeg transcode failed, so the executor can treat a full scratch
16/// disk as a systemic abort rather than a skippable per-clip fault.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum FfmpegErrorKind {
19 /// The scratch device or quota ran out of space.
20 OutOfSpace,
21 /// Any other failure (bad input, missing binary, encode error).
22 Other,
23}
24
25/// An ffmpeg transcode failure, carrying a kind and a human-readable,
26/// secret-free reason.
27#[derive(Debug, thiserror::Error)]
28#[error("{reason}")]
29pub struct FfmpegError {
30 kind: FfmpegErrorKind,
31 reason: String,
32}
33
34impl FfmpegError {
35 /// Build an [`FfmpegError`] of kind [`FfmpegErrorKind::Other`] from any
36 /// displayable cause.
37 pub fn new(reason: impl Into<String>) -> Self {
38 Self {
39 kind: FfmpegErrorKind::Other,
40 reason: reason.into(),
41 }
42 }
43
44 /// Build an out-of-space [`FfmpegError`] (kind [`FfmpegErrorKind::OutOfSpace`]).
45 pub fn out_of_space(reason: impl Into<String>) -> Self {
46 Self {
47 kind: FfmpegErrorKind::OutOfSpace,
48 reason: reason.into(),
49 }
50 }
51
52 /// The failure kind.
53 pub fn kind(&self) -> FfmpegErrorKind {
54 self.kind
55 }
56
57 /// Whether this failure was a full scratch disk or exhausted quota.
58 pub fn is_out_of_space(&self) -> bool {
59 self.kind == FfmpegErrorKind::OutOfSpace
60 }
61}
62
63/// The ffmpeg port the executor transcodes through.
64///
65/// Async so the adapter can offload the blocking child process without stalling
66/// the runtime; tests resolve immediately.
67pub trait Ffmpeg {
68 /// Transcode `wav` to the given lossless `format`'s bytes.
69 fn wav_to_lossless(
70 &self,
71 wav: &[u8],
72 format: AudioFormat,
73 ) -> impl Future<Output = Result<Vec<u8>, FfmpegError>> + Send;
74
75 /// Transcode an MP4 video preview to animated WebP bytes under `settings`.
76 ///
77 /// Used to derive a clip's `cover.webp` sidecar from its `video_cover_url`
78 /// MP4. Like [`wav_to_lossless`](Ffmpeg::wav_to_lossless) the adapter offloads
79 /// the blocking child process; tests resolve immediately.
80 fn mp4_to_webp(
81 &self,
82 mp4: &[u8],
83 settings: WebpEncodeSettings,
84 ) -> impl Future<Output = Result<Vec<u8>, FfmpegError>> + Send;
85}