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