1use std::path::PathBuf;
20
21use rff::transcode::{InputSpec, MapSelector, MapSpec, OutputSpec, StreamCodec, TranscodeSpec};
22use rff_core::{CodecId, Dictionary, MediaType};
23
24fn parse_map(spec: &str) -> Option<MapSpec> {
26 let mut parts = spec.split(':');
27 let input: usize = parts.next()?.parse().ok()?;
28 let selector = match parts.next() {
29 None => MapSelector::All,
30 Some("v") | Some("V") => MapSelector::Kind(MediaType::Video),
31 Some("a") => MapSelector::Kind(MediaType::Audio),
32 Some(idx) => MapSelector::Index(idx.parse().ok()?),
33 };
34 Some(MapSpec { input, selector })
35}
36
37pub enum Action {
40 Version,
41 Help,
42 ListCodecs,
43 ListFormats,
44 Transcode(TranscodeSpec),
45}
46
47pub struct Cli {
49 pub hide_banner: bool,
50 pub loglevel: Option<String>,
51 pub warnings: Vec<String>,
53 pub action: Action,
54}
55
56pub fn parse(args: &[String]) -> Result<Cli, String> {
61 let mut hide_banner = false;
62 let mut loglevel = None;
63 let mut warnings = Vec::new();
64
65 let mut action_override: Option<Action> = None;
67
68 let mut inputs: Vec<InputSpec> = Vec::new();
70 let mut pending_input_format: Option<String> = None;
71 let mut out_format: Option<String> = None;
72 let mut video_codec: Option<CodecId> = None;
73 let mut audio_codec: Option<CodecId> = None;
74 let mut subtitle_codec: Option<CodecId> = None;
75 let mut audio_sample_format: Option<rff_core::SampleFormat> = None;
79 let mut video_opts = Dictionary::new();
80 let mut audio_opts = Dictionary::new();
81 let mut shared_opts = Dictionary::new();
87 let mut max_video_frames: Option<u64> = None;
88 let mut video_filters: Option<String> = None;
89 let mut audio_filters: Option<String> = None;
90 let mut filter_complex: Option<String> = None;
91 let mut maps: Vec<MapSpec> = Vec::new();
92 let mut disabled: Vec<MediaType> = Vec::new();
93 let mut overwrite = false;
94 let mut output_path: Option<PathBuf> = None;
95 let mut trim_start: Option<f64> = None;
97 let mut trim_duration: Option<f64> = None;
98 let mut trim_to: Option<f64> = None;
99 let mut frame_rate: Option<(u32, u32)> = None;
100 let mut audio_rate: Option<u32> = None;
101 let mut audio_channels: Option<u16> = None;
102 let mut metadata = Dictionary::new();
103 let mut format_options = Dictionary::new();
104
105 let mut i = 0;
106 while i < args.len() {
107 let arg = &args[i];
108
109 let Some(opt) = arg.strip_prefix('-').filter(|_| arg != "-") else {
111 if output_path.is_some() {
113 warnings.push(format!(
114 "multiple output files given; using the last (`{arg}`)"
115 ));
116 }
117 output_path = Some(PathBuf::from(arg));
118 i += 1;
119 continue;
120 };
121
122 let (base, spec) = match opt.split_once(':') {
125 Some((b, s)) => (b, Some(s)),
126 None => (opt, None),
127 };
128
129 match base {
130 "version" => action_override = Some(Action::Version),
131 "h" | "help" | "?" => action_override = Some(Action::Help),
132 "codecs" | "encoders" | "decoders" => action_override = Some(Action::ListCodecs),
133 "formats" | "muxers" | "demuxers" => action_override = Some(Action::ListFormats),
134 "hide_banner" => hide_banner = true,
135 "y" => overwrite = true,
136 "n" => overwrite = false,
137 "loglevel" | "v" => loglevel = Some(take_value(args, &mut i, arg)?),
138
139 "i" => {
140 let path = take_value(args, &mut i, arg)?;
141 inputs.push(InputSpec {
142 path: PathBuf::from(path),
143 format: pending_input_format.take(),
144 });
145 }
146
147 "f" => {
150 let fmt = take_value(args, &mut i, arg)?;
151 if inputs.is_empty() {
152 pending_input_format = Some(fmt);
153 } else {
154 out_format = Some(fmt);
155 }
156 }
157
158 "c" | "codec" => {
161 let name = take_value(args, &mut i, arg)?;
162 apply_codec(
163 spec,
164 &name,
165 &mut video_codec,
166 &mut audio_codec,
167 &mut subtitle_codec,
168 &mut audio_sample_format,
169 &mut warnings,
170 )?;
171 }
172 "vcodec" => {
173 let name = take_value(args, &mut i, arg)?;
174 apply_codec(
175 Some("v"),
176 &name,
177 &mut video_codec,
178 &mut audio_codec,
179 &mut subtitle_codec,
180 &mut audio_sample_format,
181 &mut warnings,
182 )?;
183 }
184 "acodec" => {
185 let name = take_value(args, &mut i, arg)?;
186 apply_codec(
187 Some("a"),
188 &name,
189 &mut video_codec,
190 &mut audio_codec,
191 &mut subtitle_codec,
192 &mut audio_sample_format,
193 &mut warnings,
194 )?;
195 }
196 "scodec" => {
197 let name = take_value(args, &mut i, arg)?;
198 apply_codec(
199 Some("s"),
200 &name,
201 &mut video_codec,
202 &mut audio_codec,
203 &mut subtitle_codec,
204 &mut audio_sample_format,
205 &mut warnings,
206 )?;
207 }
208
209 "vn" => disabled.push(MediaType::Video),
212 "an" => disabled.push(MediaType::Audio),
213 "sn" => disabled.push(MediaType::Subtitle),
214 "dn" => disabled.push(MediaType::Data),
215
216 "map" => {
218 let value = take_value(args, &mut i, arg)?;
219 match parse_map(&value) {
220 Some(m) => maps.push(m),
221 None => warnings.push(format!("ignoring invalid -map `{value}`")),
222 }
223 }
224
225 "vf" => video_filters = Some(take_value(args, &mut i, arg)?),
227 "af" => audio_filters = Some(take_value(args, &mut i, arg)?),
228 "filter_complex" | "lavfi" => filter_complex = Some(take_value(args, &mut i, arg)?),
230 "filter" => {
231 let value = take_value(args, &mut i, arg)?;
232 match spec {
233 Some(s) if s.starts_with('v') => video_filters = Some(value),
234 Some(s) if s.starts_with('a') => audio_filters = Some(value),
235 _ => warnings.push(format!("ignoring filter spec `{value}`")),
236 }
237 }
238
239 "ss" => trim_start = Some(parse_time(&take_value(args, &mut i, arg)?)?),
243 "t" => trim_duration = Some(parse_time(&take_value(args, &mut i, arg)?)?),
244 "to" => trim_to = Some(parse_time(&take_value(args, &mut i, arg)?)?),
245
246 "r" | "framerate" => frame_rate = Some(parse_rate(&take_value(args, &mut i, arg)?)?),
248
249 "s" | "video_size" => {
251 let value = take_value(args, &mut i, arg)?;
252 let (w, h) = value
253 .split_once(['x', 'X'])
254 .and_then(|(w, h)| Some((w.parse::<u32>().ok()?, h.parse::<u32>().ok()?)))
255 .ok_or_else(|| format!("-s: expected WxH, got `{value}`"))?;
256 let scale = format!("scale={w}:{h}");
257 video_filters = Some(match video_filters.take() {
258 Some(chain) => format!("{chain},{scale}"),
259 None => scale,
260 });
261 }
262
263 "ar" => {
265 let value = take_value(args, &mut i, arg)?;
266 audio_rate = Some(
267 value
268 .parse()
269 .map_err(|_| format!("-ar: bad sample rate `{value}`"))?,
270 );
271 }
272 "ac" => {
273 let value = take_value(args, &mut i, arg)?;
274 audio_channels = Some(
275 value
276 .parse()
277 .map_err(|_| format!("-ac: bad channel count `{value}`"))?,
278 );
279 }
280
281 "hls_time" => {
284 let value = take_value(args, &mut i, arg)?;
285 format_options.set("hls_time", value);
286 }
287 "seg_duration" => {
289 let value = take_value(args, &mut i, arg)?;
290 format_options.set("seg_duration", value);
291 }
292 "movflags" => {
294 let value = take_value(args, &mut i, arg)?;
295 format_options.set("movflags", value);
296 }
297 "hls_list_size" => {
298 let _ = take_value(args, &mut i, arg)?;
299 warnings.push("-hls_list_size: HLS output is a VOD playlist; ignored".into());
300 }
301
302 "metadata" => {
304 let value = take_value(args, &mut i, arg)?;
305 match value.split_once('=') {
306 Some((k, v)) => metadata.set(k.trim(), v),
307 None => warnings.push(format!("-metadata: expected key=value, got `{value}`")),
308 }
309 }
310
311 "b" => {
313 let value = take_value(args, &mut i, arg)?;
314 match spec {
315 Some(s) if s.starts_with('a') => audio_opts.set("b", value),
316 _ => video_opts.set("b", value),
317 }
318 }
319
320 "frames" | "vframes" => {
328 let value = take_value(args, &mut i, arg)?;
329 match value.parse::<u64>() {
330 Ok(n) => max_video_frames = Some(n),
331 Err(_) => warnings.push(format!("ignoring non-numeric -{arg} {value}")),
332 }
333 }
334
335 "crf" | "qp" | "preset" | "profile" | "g" | "pass" | "q" | "qscale" | "cpu-used"
342 | "speed" | "lag" | "lag-in-frames" | "arnr-strength" | "dispatch-budget"
343 | "jpeg_quality" | "sampling" | "jpeg_sampling" | "progressive"
344 | "optimize_huffman" | "restart_interval" | "trellis" | "pred" | "png_auto_type"
345 | "png_auto_config" => {
346 let value = take_value(args, &mut i, arg)?;
347 if base == "pass" && value != "1" {
348 warnings
349 .push("two-pass (-pass 2) is parsed but runs single-pass for now".into());
350 }
351 match spec {
352 Some(s) if s.starts_with('a') => audio_opts.set(base, value),
353 _ => video_opts.set(base, value),
354 }
355 }
356
357 "compression_level" | "threads" => {
364 let value = take_value(args, &mut i, arg)?;
365 match spec {
366 Some(s) if s.starts_with('v') => video_opts.set(base, value),
367 Some(s) if s.starts_with('a') => audio_opts.set(base, value),
368 _ => shared_opts.set(base, value),
369 }
370 }
371
372 "application" | "vbr" | "opus_parallel" | "opus_warmup" | "frame_duration" => {
377 let value = take_value(args, &mut i, arg)?;
378 match spec {
379 Some(s) if s.starts_with('v') => video_opts.set(base, value),
380 _ => audio_opts.set(base, value),
381 }
382 }
383
384 _ => {
388 warnings.push(format!("unrecognized option `-{opt}` (ignored)"));
389 if i + 2 < args.len() && !args[i + 1].starts_with('-') {
390 i += 1;
391 }
392 }
393 }
394
395 i += 1;
396 }
397
398 if let Some(action) = action_override {
399 return Ok(Cli {
400 hide_banner,
401 loglevel,
402 warnings,
403 action,
404 });
405 }
406
407 for (key, value) in shared_opts.iter() {
410 if video_codec.is_some() && video_opts.get(key).is_none() {
411 video_opts.set(key, value);
412 }
413 if audio_codec.is_some() && audio_opts.get(key).is_none() {
414 audio_opts.set(key, value);
415 }
416 }
417
418 if !video_opts.is_empty() && video_codec.is_none() {
420 warnings.push("video options given without -c:v; ignored".into());
421 }
422 if !audio_opts.is_empty() && audio_codec.is_none() {
423 warnings.push("audio options given without -c:a; ignored".into());
424 }
425 if audio_codec.is_none()
427 && (audio_filters.is_some() || audio_rate.is_some() || audio_channels.is_some())
428 {
429 warnings.push("-af/-ar/-ac need a re-encode; pass -c:a (ignored on stream copy)".into());
430 }
431
432 if let Some(vf) = &video_filters {
434 let mut kept: Vec<&str> = Vec::new();
435 for token in vf.split(',') {
436 match token.trim().strip_prefix("fps=") {
437 Some(rate) => match parse_rate(rate) {
438 Ok(r) => frame_rate = Some(r),
439 Err(e) => warnings.push(e),
440 },
441 None => kept.push(token),
442 }
443 }
444 if kept.len() != vf.split(',').count() {
445 let kept = kept.join(",");
446 video_filters = (!kept.trim().is_empty()).then_some(kept);
447 }
448 }
449 if frame_rate.is_some() && video_codec.is_none() {
450 warnings.push("-r/-vf fps= need a re-encode; pass -c:v (ignored on stream copy)".into());
451 }
452
453 let trim_end = match (trim_to, trim_duration) {
456 (Some(to), Some(t)) => Some(to.min(trim_start.unwrap_or(0.0) + t)),
457 (Some(to), None) => Some(to),
458 (None, Some(t)) => Some(trim_start.unwrap_or(0.0) + t),
459 (None, None) => None,
460 };
461
462 let output = output_path.map(|path| OutputSpec {
463 path,
464 format: out_format,
465 video_codec: video_codec.map(|codec| StreamCodec {
466 codec,
467 options: video_opts,
468 sample_format: None,
469 }),
470 audio_codec: audio_codec.map(|codec| StreamCodec {
471 codec,
472 options: audio_opts,
473 sample_format: audio_sample_format,
474 }),
475 subtitle_codec,
476 video_filters,
477 filter_complex,
478 max_video_frames,
479 maps,
480 disabled,
481 overwrite,
482 trim_start,
483 trim_end,
484 frame_rate,
485 audio_rate,
486 audio_channels,
487 audio_filters,
488 metadata,
489 format_options,
490 });
491
492 let spec = TranscodeSpec {
493 inputs,
494 outputs: output.into_iter().collect(),
495 };
496
497 Ok(Cli {
498 hide_banner,
499 loglevel,
500 warnings,
501 action: Action::Transcode(spec),
502 })
503}
504
505fn take_value(args: &[String], i: &mut usize, opt: &str) -> Result<String, String> {
507 *i += 1;
508 args.get(*i)
509 .cloned()
510 .ok_or_else(|| format!("option `{opt}` requires an argument"))
511}
512
513fn parse_time(value: &str) -> Result<f64, String> {
515 let value = value.trim();
516 let bad = || format!("bad time `{value}` (want seconds or [HH:]MM:SS[.mmm])");
517 if !value.contains(':') {
518 return value.parse::<f64>().map_err(|_| bad());
519 }
520 let parts: Vec<&str> = value.split(':').collect();
521 if parts.len() > 3 || parts.is_empty() {
522 return Err(bad());
523 }
524 let mut seconds = 0.0;
525 for p in &parts {
526 seconds = seconds * 60.0 + p.parse::<f64>().map_err(|_| bad())?;
527 }
528 Ok(seconds)
529}
530
531fn parse_rate(value: &str) -> Result<(u32, u32), String> {
534 let value = value.trim();
535 let bad = || format!("bad frame rate `{value}`");
536 if let Some((n, d)) = value.split_once('/') {
537 let (n, d) = (
538 n.trim().parse::<u32>().map_err(|_| bad())?,
539 d.trim().parse::<u32>().map_err(|_| bad())?,
540 );
541 if n == 0 || d == 0 {
542 return Err(bad());
543 }
544 return Ok((n, d));
545 }
546 if let Some((int, frac)) = value.split_once('.') {
547 let digits = frac.len().min(3) as u32;
548 let den = 10u32.pow(digits);
549 let int: u32 = int.parse().map_err(|_| bad())?;
550 let frac: u32 = frac[..digits as usize].parse().map_err(|_| bad())?;
551 let num = int * den + frac;
552 if num == 0 {
553 return Err(bad());
554 }
555 return Ok((num, den));
556 }
557 let n: u32 = value.parse().map_err(|_| bad())?;
558 if n == 0 {
559 return Err(bad());
560 }
561 Ok((n, 1))
562}
563
564#[allow(clippy::too_many_arguments)]
569fn apply_codec(
570 spec: Option<&str>,
571 name: &str,
572 video: &mut Option<CodecId>,
573 audio: &mut Option<CodecId>,
574 subtitle: &mut Option<CodecId>,
575 audio_format: &mut Option<rff_core::SampleFormat>,
576 warnings: &mut Vec<String>,
577) -> Result<(), String> {
578 if name == "copy" {
579 return Ok(());
581 }
582 let Some(id) = CodecId::from_name(name) else {
583 return Err(format!(
584 "unknown encoder `{name}` (`rff -codecs` lists the supported ones)"
585 ));
586 };
587 let pinned = CodecId::sample_format_from_name(name);
589 match spec {
590 Some(s) if s.starts_with('v') => *video = Some(id),
591 Some(s) if s.starts_with('a') => {
592 *audio = Some(id);
593 if pinned.is_some() {
594 *audio_format = pinned;
595 }
596 }
597 Some(s) if s.starts_with('s') => match id.media_type() {
598 rff_core::MediaType::Subtitle => *subtitle = Some(id),
599 _ => warnings.push(format!("-c:s: `{name}` is not a subtitle codec (ignored)")),
600 },
601 None => match id.media_type() {
603 rff_core::MediaType::Video => *video = Some(id),
604 rff_core::MediaType::Audio => {
605 *audio = Some(id);
606 if pinned.is_some() {
607 *audio_format = pinned;
608 }
609 }
610 rff_core::MediaType::Subtitle => *subtitle = Some(id),
611 _ => {}
612 },
613 _ => {}
614 }
615 Ok(())
616}
617
618#[cfg(test)]
619mod tests {
620 use super::*;
621
622 fn output(args: &[&str]) -> (OutputSpec, Vec<String>) {
623 let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
624 let cli = parse(&args).expect("parses");
625 let Action::Transcode(mut spec) = cli.action else {
626 panic!("expected a transcode");
627 };
628 (spec.outputs.remove(0), cli.warnings)
629 }
630
631 #[test]
632 fn vn_and_an_disable_stream_kinds() {
633 let (out, warnings) = output(&["-i", "src.mp4", "-vn", "-c:a", "opus", "out.m4a"]);
634 assert_eq!(out.disabled, vec![MediaType::Video]);
635 assert_eq!(out.path, PathBuf::from("out.m4a"));
636 assert!(warnings.is_empty(), "{warnings:?}");
637
638 let (out, _) = output(&["-i", "src.mp4", "-c:v", "h264", "-an", "out.mp4"]);
639 assert_eq!(out.disabled, vec![MediaType::Audio]);
640 assert_eq!(out.path, PathBuf::from("out.mp4"));
641 }
642
643 #[test]
644 fn unknown_encoder_is_an_error_naming_it() {
645 for name in ["libsvtav1", "nonexistentcodec"] {
646 let args: Vec<String> = ["-i", "src.mp4", "-c:v", name, "out.mkv"]
647 .iter()
648 .map(|s| s.to_string())
649 .collect();
650 let err = parse(&args).err().expect("unknown encoder must fail");
651 assert!(err.contains(name), "{err}");
652 }
653 let (out, _) = output(&["-i", "src.mp4", "-c:v", "libx265", "out.mkv"]);
654 assert_eq!(out.video_codec.map(|c| c.codec), Some(CodecId::Hevc));
655 let (out, _) = output(&["-i", "src.mp4", "-c:v", "copy", "out.mkv"]);
656 assert!(out.video_codec.is_none());
657 }
658
659 #[test]
660 fn unknown_option_never_takes_the_output_path() {
661 let (out, warnings) = output(&["-i", "src.mp4", "-bogus", "out.mp4"]);
662 assert_eq!(out.path, PathBuf::from("out.mp4"));
663 assert_eq!(warnings.len(), 1);
664 let (out, _) = output(&["-i", "src.mp4", "-pix_fmt", "yuv420p", "out.mp4"]);
666 assert_eq!(out.path, PathBuf::from("out.mp4"));
667 }
668}