1use crate::media_processing::MediaPath;
4use std::path::PathBuf;
5use std::time::Duration;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum ExportError {
9 UnsafePath,
10 UnsupportedContainer,
11 IncompatibleCodec,
12 InvalidResolution,
13 InvalidBitrate,
14 InvalidDuration,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum VideoCodec {
19 H264,
20 H265,
21 Vp9,
22 Av1,
23}
24impl VideoCodec {
25 fn argument(self) -> &'static str {
26 match self {
27 Self::H264 => "libx264",
28 Self::H265 => "libx265",
29 Self::Vp9 => "libvpx-vp9",
30 Self::Av1 => "libaom-av1",
31 }
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum AudioCodec {
37 Aac,
38 Opus,
39}
40impl AudioCodec {
41 fn argument(self) -> &'static str {
42 match self {
43 Self::Aac => "aac",
44 Self::Opus => "libopus",
45 }
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Container {
51 Mp4,
52 Webm,
53 Mkv,
54}
55impl Container {
56 fn extension(self) -> &'static str {
57 match self {
58 Self::Mp4 => "mp4",
59 Self::Webm => "webm",
60 Self::Mkv => "mkv",
61 }
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct ExportProfile {
67 pub output: MediaPath,
68 pub width: u16,
69 pub height: u16,
70 pub video_bitrate_kbps: u32,
71 pub audio_bitrate_kbps: u32,
72 pub video_codec: VideoCodec,
73 pub audio_codec: AudioCodec,
74 pub container: Container,
75 pub duration: Option<Duration>,
76}
77
78impl ExportProfile {
79 #[allow(clippy::too_many_arguments)]
80 pub fn new(
81 output: impl Into<PathBuf>,
82 width: u16,
83 height: u16,
84 video_bitrate_kbps: u32,
85 audio_bitrate_kbps: u32,
86 video_codec: VideoCodec,
87 audio_codec: AudioCodec,
88 container: Container,
89 ) -> Result<Self, ExportError> {
90 let output = MediaPath::new(output).map_err(|_| ExportError::UnsafePath)?;
91 if output.as_path().extension().and_then(|v| v.to_str()) != Some(container.extension()) {
92 return Err(ExportError::UnsupportedContainer);
93 }
94 if !(16..=7680).contains(&width)
95 || !(16..=4320).contains(&height)
96 || !width.is_multiple_of(2)
97 || !height.is_multiple_of(2)
98 {
99 return Err(ExportError::InvalidResolution);
100 }
101 if !(100..=100_000).contains(&video_bitrate_kbps)
102 || !(16..=1_024).contains(&audio_bitrate_kbps)
103 {
104 return Err(ExportError::InvalidBitrate);
105 }
106 if !compatible(video_codec, audio_codec, container) {
107 return Err(ExportError::IncompatibleCodec);
108 }
109 Ok(Self {
110 output,
111 width,
112 height,
113 video_bitrate_kbps,
114 audio_bitrate_kbps,
115 video_codec,
116 audio_codec,
117 container,
118 duration: None,
119 })
120 }
121 pub fn duration(mut self, duration: Duration) -> Result<Self, ExportError> {
122 if duration.is_zero() || duration > Duration::from_secs(86_400) {
123 return Err(ExportError::InvalidDuration);
124 }
125 self.duration = Some(duration);
126 Ok(self)
127 }
128 pub fn command_line(&self) -> Vec<String> {
129 let mut args = vec![
130 "-hide_banner".into(),
131 "-nostdin".into(),
132 "-y".into(),
133 "-vf".into(),
134 format!("scale={}:{}", self.width, self.height),
135 "-c:v".into(),
136 self.video_codec.argument().into(),
137 "-b:v".into(),
138 format!("{}k", self.video_bitrate_kbps),
139 "-c:a".into(),
140 self.audio_codec.argument().into(),
141 "-b:a".into(),
142 format!("{}k", self.audio_bitrate_kbps),
143 "-movflags".into(),
144 "+faststart".into(),
145 ];
146 if let Some(duration) = self.duration {
147 args.extend(["-t".into(), duration.as_secs_f64().to_string()]);
148 }
149 args.push(self.output.display());
150 args
151 }
152}
153
154fn compatible(video: VideoCodec, audio: AudioCodec, container: Container) -> bool {
155 match container {
156 Container::Mp4 => {
157 matches!(video, VideoCodec::H264 | VideoCodec::H265) && matches!(audio, AudioCodec::Aac)
158 }
159 Container::Webm => {
160 matches!(video, VideoCodec::Vp9 | VideoCodec::Av1) && matches!(audio, AudioCodec::Opus)
161 }
162 Container::Mkv => {
163 matches!(
164 video,
165 VideoCodec::H264 | VideoCodec::H265 | VideoCodec::Vp9 | VideoCodec::Av1
166 ) && matches!(audio, AudioCodec::Aac | AudioCodec::Opus)
167 }
168 }
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174 #[test]
175 fn builds_mp4_export_profile() {
176 let profile = ExportProfile::new(
177 "renders/final.mp4",
178 1920,
179 1080,
180 8000,
181 192,
182 VideoCodec::H264,
183 AudioCodec::Aac,
184 Container::Mp4,
185 )
186 .unwrap()
187 .duration(Duration::from_secs(60))
188 .unwrap();
189 let args = profile.command_line();
190 assert!(args.iter().any(|arg| arg == "scale=1920:1080"));
191 assert!(args.iter().any(|arg| arg == "8000k"));
192 assert!(args.iter().any(|arg| arg == "libx264"));
193 assert!(args.iter().any(|arg| arg == "+faststart"));
194 }
195 #[test]
196 fn validates_compatibility_resolution_bitrate_and_paths() {
197 assert_eq!(
198 ExportProfile::new(
199 "out.webm",
200 1920,
201 1080,
202 8000,
203 128,
204 VideoCodec::H264,
205 AudioCodec::Aac,
206 Container::Webm
207 ),
208 Err(ExportError::IncompatibleCodec)
209 );
210 assert_eq!(
211 ExportProfile::new(
212 "../out.mp4",
213 1920,
214 1080,
215 8000,
216 128,
217 VideoCodec::H264,
218 AudioCodec::Aac,
219 Container::Mp4
220 ),
221 Err(ExportError::UnsafePath)
222 );
223 assert_eq!(
224 ExportProfile::new(
225 "out.mp4",
226 1919,
227 1080,
228 8000,
229 128,
230 VideoCodec::H264,
231 AudioCodec::Aac,
232 Container::Mp4
233 ),
234 Err(ExportError::InvalidResolution)
235 );
236 assert_eq!(
237 ExportProfile::new(
238 "out.mp4",
239 1920,
240 1080,
241 99,
242 128,
243 VideoCodec::H264,
244 AudioCodec::Aac,
245 Container::Mp4
246 ),
247 Err(ExportError::InvalidBitrate)
248 );
249 }
250 #[test]
251 fn supports_webm_and_mkv_and_rejects_duration_overflow() {
252 assert!(ExportProfile::new(
253 "out.webm",
254 1280,
255 720,
256 3000,
257 128,
258 VideoCodec::Vp9,
259 AudioCodec::Opus,
260 Container::Webm
261 )
262 .is_ok());
263 assert!(ExportProfile::new(
264 "out.mkv",
265 1280,
266 720,
267 3000,
268 128,
269 VideoCodec::Av1,
270 AudioCodec::Aac,
271 Container::Mkv
272 )
273 .is_ok());
274 let profile = ExportProfile::new(
275 "out.mp4",
276 1280,
277 720,
278 3000,
279 128,
280 VideoCodec::H264,
281 AudioCodec::Aac,
282 Container::Mp4,
283 )
284 .unwrap();
285 assert_eq!(
286 profile.duration(Duration::from_secs(86_401)),
287 Err(ExportError::InvalidDuration)
288 );
289 }
290}