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