Skip to main content

yaiko_core/
media_processing.rs

1//! Safe media-processing specifications for FFmpeg-backed workers.
2//!
3//! This module only builds typed process arguments. Callers should execute the
4//! returned program and arguments with `tokio::process::Command`, never through
5//! a shell.
6
7use std::path::{Component, Path, PathBuf};
8use std::time::Duration;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum MediaError {
12    EmptyPath,
13    AbsolutePath,
14    Traversal,
15    UnsupportedExtension,
16    InvalidText,
17    InvalidDuration,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct MediaPath(PathBuf);
22
23impl MediaPath {
24    pub fn new(path: impl Into<PathBuf>) -> Result<Self, MediaError> {
25        let path = path.into();
26        if path.as_os_str().is_empty() {
27            return Err(MediaError::EmptyPath);
28        }
29        if path.is_absolute() {
30            return Err(MediaError::AbsolutePath);
31        }
32        if path.components().any(|component| {
33            matches!(
34                component,
35                Component::ParentDir | Component::RootDir | Component::Prefix(_)
36            )
37        }) {
38            return Err(MediaError::Traversal);
39        }
40        Ok(Self(path))
41    }
42    pub fn as_path(&self) -> &Path {
43        &self.0
44    }
45    pub fn display(&self) -> String {
46        self.0.to_string_lossy().into_owned()
47    }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct CaptionTrack {
52    pub file: MediaPath,
53    pub language: Option<String>,
54}
55
56impl CaptionTrack {
57    pub fn new(file: impl Into<PathBuf>, language: Option<String>) -> Result<Self, MediaError> {
58        let file = MediaPath::new(file)?;
59        if !matches!(
60            file.as_path().extension().and_then(|v| v.to_str()),
61            Some("srt" | "vtt" | "ass")
62        ) {
63            return Err(MediaError::UnsupportedExtension);
64        }
65        if language.as_deref().is_some_and(|value| {
66            value.is_empty()
67                || value.len() > 16
68                || !value
69                    .chars()
70                    .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
71        }) {
72            return Err(MediaError::InvalidText);
73        }
74        Ok(Self { file, language })
75    }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct MusicTrack {
80    pub file: MediaPath,
81    pub volume_percent: u8,
82}
83
84impl MusicTrack {
85    pub fn new(file: impl Into<PathBuf>, volume_percent: u8) -> Result<Self, MediaError> {
86        let file = MediaPath::new(file)?;
87        if !matches!(
88            file.as_path().extension().and_then(|v| v.to_str()),
89            Some("mp3" | "wav" | "m4a" | "aac" | "ogg")
90        ) {
91            return Err(MediaError::UnsupportedExtension);
92        }
93        Ok(Self {
94            file,
95            volume_percent,
96        })
97    }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct FfmpegJobSpec {
102    pub input: MediaPath,
103    pub output: MediaPath,
104    pub captions: Vec<CaptionTrack>,
105    pub music: Option<MusicTrack>,
106    pub max_duration: Option<Duration>,
107}
108
109impl FfmpegJobSpec {
110    pub fn new(input: impl Into<PathBuf>, output: impl Into<PathBuf>) -> Result<Self, MediaError> {
111        let input = MediaPath::new(input)?;
112        let output = MediaPath::new(output)?;
113        if !matches!(
114            input.as_path().extension().and_then(|v| v.to_str()),
115            Some("mp4" | "mov" | "webm" | "mkv")
116        ) || !matches!(
117            output.as_path().extension().and_then(|v| v.to_str()),
118            Some("mp4" | "webm" | "mkv")
119        ) {
120            return Err(MediaError::UnsupportedExtension);
121        }
122        Ok(Self {
123            input,
124            output,
125            captions: Vec::new(),
126            music: None,
127            max_duration: None,
128        })
129    }
130    pub fn with_caption(mut self, caption: CaptionTrack) -> Self {
131        self.captions.push(caption);
132        self
133    }
134    pub fn with_music(mut self, music: MusicTrack) -> Self {
135        self.music = Some(music);
136        self
137    }
138    pub fn max_duration(mut self, duration: Duration) -> Result<Self, MediaError> {
139        if duration.is_zero() || duration > Duration::from_secs(86_400) {
140            return Err(MediaError::InvalidDuration);
141        }
142        self.max_duration = Some(duration);
143        Ok(self)
144    }
145    pub fn command_line(&self) -> Vec<String> {
146        let mut args = vec![
147            "-hide_banner".into(),
148            "-nostdin".into(),
149            "-y".into(),
150            "-i".into(),
151            self.input.display(),
152        ];
153        if let Some(music) = &self.music {
154            args.extend([
155                "-stream_loop".into(),
156                "-1".into(),
157                "-i".into(),
158                music.file.display(),
159            ]);
160        }
161        if !self.captions.is_empty() {
162            args.extend([
163                "-vf".into(),
164                self.captions
165                    .iter()
166                    .map(|c| format!("subtitles={}", escape_filter_path(&c.file.display())))
167                    .collect::<Vec<_>>()
168                    .join(","),
169            ]);
170        }
171        if let Some(music) = &self.music {
172            args.extend([
173                "-map".into(),
174                "0:v:0".into(),
175                "-map".into(),
176                "1:a:0".into(),
177                "-af".into(),
178                format!("volume={:.2}", f32::from(music.volume_percent) / 100.0),
179                "-shortest".into(),
180            ]);
181        }
182        args.extend(["-c:v".into(), "libx264".into(), "-c:a".into(), "aac".into()]);
183        if let Some(duration) = self.max_duration {
184            args.extend(["-t".into(), duration.as_secs().to_string()]);
185        }
186        args.push(self.output.display());
187        args
188    }
189}
190
191fn escape_filter_path(path: &str) -> String {
192    path.replace('\\', "\\\\")
193        .replace(':', "\\:")
194        .replace('\'', "\\'")
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    #[test]
201    fn rejects_unsafe_paths_and_extensions() {
202        assert_eq!(MediaPath::new("../secret"), Err(MediaError::Traversal));
203        assert_eq!(
204            MediaPath::new("/tmp/video.mp4"),
205            Err(MediaError::AbsolutePath)
206        );
207        assert_eq!(
208            MusicTrack::new("audio.exe", 100),
209            Err(MediaError::UnsupportedExtension)
210        );
211    }
212    #[test]
213    fn builds_composition_without_shell_interpolation() {
214        let spec = FfmpegJobSpec::new("uploads/input.mp4", "renders/output.mp4")
215            .unwrap()
216            .with_caption(CaptionTrack::new("uploads/captions.srt", Some("en-US".into())).unwrap())
217            .with_music(MusicTrack::new("uploads/music.mp3", 50).unwrap());
218        let args = spec.command_line();
219        assert!(args.windows(2).any(|v| v == ["-map", "0:v:0"]));
220        assert!(args.iter().any(|v| v == "volume=0.50"));
221        assert!(!args.join(" ").contains("|"));
222    }
223    #[test]
224    fn enforces_duration_bounds() {
225        let spec = FfmpegJobSpec::new("input.mp4", "output.mp4").unwrap();
226        assert_eq!(
227            spec.clone().max_duration(Duration::ZERO),
228            Err(MediaError::InvalidDuration)
229        );
230        assert!(spec
231            .max_duration(Duration::from_secs(60))
232            .unwrap()
233            .max_duration
234            .is_some());
235    }
236}