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 "hls_list_size" => {
293 let _ = take_value(args, &mut i, arg)?;
294 warnings.push("-hls_list_size: HLS output is a VOD playlist; ignored".into());
295 }
296
297 "metadata" => {
299 let value = take_value(args, &mut i, arg)?;
300 match value.split_once('=') {
301 Some((k, v)) => metadata.set(k.trim(), v),
302 None => warnings.push(format!("-metadata: expected key=value, got `{value}`")),
303 }
304 }
305
306 "b" => {
308 let value = take_value(args, &mut i, arg)?;
309 match spec {
310 Some(s) if s.starts_with('a') => audio_opts.set("b", value),
311 _ => video_opts.set("b", value),
312 }
313 }
314
315 "frames" | "vframes" => {
323 let value = take_value(args, &mut i, arg)?;
324 match value.parse::<u64>() {
325 Ok(n) => max_video_frames = Some(n),
326 Err(_) => warnings.push(format!("ignoring non-numeric -{arg} {value}")),
327 }
328 }
329
330 "crf" | "qp" | "preset" | "profile" | "g" | "pass" | "q" | "qscale" | "cpu-used"
337 | "speed" | "lag" | "lag-in-frames" | "arnr-strength" | "dispatch-budget"
338 | "jpeg_quality" | "sampling" | "jpeg_sampling" | "progressive"
339 | "optimize_huffman" | "restart_interval" | "trellis" | "pred" | "png_auto_type"
340 | "png_auto_config" => {
341 let value = take_value(args, &mut i, arg)?;
342 if base == "pass" && value != "1" {
343 warnings
344 .push("two-pass (-pass 2) is parsed but runs single-pass for now".into());
345 }
346 match spec {
347 Some(s) if s.starts_with('a') => audio_opts.set(base, value),
348 _ => video_opts.set(base, value),
349 }
350 }
351
352 "compression_level" | "threads" => {
359 let value = take_value(args, &mut i, arg)?;
360 match spec {
361 Some(s) if s.starts_with('v') => video_opts.set(base, value),
362 Some(s) if s.starts_with('a') => audio_opts.set(base, value),
363 _ => shared_opts.set(base, value),
364 }
365 }
366
367 "application" | "vbr" | "opus_parallel" | "opus_warmup" | "frame_duration" => {
372 let value = take_value(args, &mut i, arg)?;
373 match spec {
374 Some(s) if s.starts_with('v') => video_opts.set(base, value),
375 _ => audio_opts.set(base, value),
376 }
377 }
378
379 _ => {
383 warnings.push(format!("unrecognized option `-{opt}` (ignored)"));
384 if i + 2 < args.len() && !args[i + 1].starts_with('-') {
385 i += 1;
386 }
387 }
388 }
389
390 i += 1;
391 }
392
393 if let Some(action) = action_override {
394 return Ok(Cli {
395 hide_banner,
396 loglevel,
397 warnings,
398 action,
399 });
400 }
401
402 for (key, value) in shared_opts.iter() {
405 if video_codec.is_some() && video_opts.get(key).is_none() {
406 video_opts.set(key, value);
407 }
408 if audio_codec.is_some() && audio_opts.get(key).is_none() {
409 audio_opts.set(key, value);
410 }
411 }
412
413 if !video_opts.is_empty() && video_codec.is_none() {
415 warnings.push("video options given without -c:v; ignored".into());
416 }
417 if !audio_opts.is_empty() && audio_codec.is_none() {
418 warnings.push("audio options given without -c:a; ignored".into());
419 }
420 if audio_codec.is_none()
422 && (audio_filters.is_some() || audio_rate.is_some() || audio_channels.is_some())
423 {
424 warnings.push("-af/-ar/-ac need a re-encode; pass -c:a (ignored on stream copy)".into());
425 }
426
427 if let Some(vf) = &video_filters {
429 let mut kept: Vec<&str> = Vec::new();
430 for token in vf.split(',') {
431 match token.trim().strip_prefix("fps=") {
432 Some(rate) => match parse_rate(rate) {
433 Ok(r) => frame_rate = Some(r),
434 Err(e) => warnings.push(e),
435 },
436 None => kept.push(token),
437 }
438 }
439 if kept.len() != vf.split(',').count() {
440 let kept = kept.join(",");
441 video_filters = (!kept.trim().is_empty()).then_some(kept);
442 }
443 }
444 if frame_rate.is_some() && video_codec.is_none() {
445 warnings.push("-r/-vf fps= need a re-encode; pass -c:v (ignored on stream copy)".into());
446 }
447
448 let trim_end = match (trim_to, trim_duration) {
451 (Some(to), Some(t)) => Some(to.min(trim_start.unwrap_or(0.0) + t)),
452 (Some(to), None) => Some(to),
453 (None, Some(t)) => Some(trim_start.unwrap_or(0.0) + t),
454 (None, None) => None,
455 };
456
457 let output = output_path.map(|path| OutputSpec {
458 path,
459 format: out_format,
460 video_codec: video_codec.map(|codec| StreamCodec {
461 codec,
462 options: video_opts,
463 sample_format: None,
464 }),
465 audio_codec: audio_codec.map(|codec| StreamCodec {
466 codec,
467 options: audio_opts,
468 sample_format: audio_sample_format,
469 }),
470 subtitle_codec,
471 video_filters,
472 filter_complex,
473 max_video_frames,
474 maps,
475 disabled,
476 overwrite,
477 trim_start,
478 trim_end,
479 frame_rate,
480 audio_rate,
481 audio_channels,
482 audio_filters,
483 metadata,
484 format_options,
485 });
486
487 let spec = TranscodeSpec {
488 inputs,
489 outputs: output.into_iter().collect(),
490 };
491
492 Ok(Cli {
493 hide_banner,
494 loglevel,
495 warnings,
496 action: Action::Transcode(spec),
497 })
498}
499
500fn take_value(args: &[String], i: &mut usize, opt: &str) -> Result<String, String> {
502 *i += 1;
503 args.get(*i)
504 .cloned()
505 .ok_or_else(|| format!("option `{opt}` requires an argument"))
506}
507
508fn parse_time(value: &str) -> Result<f64, String> {
510 let value = value.trim();
511 let bad = || format!("bad time `{value}` (want seconds or [HH:]MM:SS[.mmm])");
512 if !value.contains(':') {
513 return value.parse::<f64>().map_err(|_| bad());
514 }
515 let parts: Vec<&str> = value.split(':').collect();
516 if parts.len() > 3 || parts.is_empty() {
517 return Err(bad());
518 }
519 let mut seconds = 0.0;
520 for p in &parts {
521 seconds = seconds * 60.0 + p.parse::<f64>().map_err(|_| bad())?;
522 }
523 Ok(seconds)
524}
525
526fn parse_rate(value: &str) -> Result<(u32, u32), String> {
529 let value = value.trim();
530 let bad = || format!("bad frame rate `{value}`");
531 if let Some((n, d)) = value.split_once('/') {
532 let (n, d) = (
533 n.trim().parse::<u32>().map_err(|_| bad())?,
534 d.trim().parse::<u32>().map_err(|_| bad())?,
535 );
536 if n == 0 || d == 0 {
537 return Err(bad());
538 }
539 return Ok((n, d));
540 }
541 if let Some((int, frac)) = value.split_once('.') {
542 let digits = frac.len().min(3) as u32;
543 let den = 10u32.pow(digits);
544 let int: u32 = int.parse().map_err(|_| bad())?;
545 let frac: u32 = frac[..digits as usize].parse().map_err(|_| bad())?;
546 let num = int * den + frac;
547 if num == 0 {
548 return Err(bad());
549 }
550 return Ok((num, den));
551 }
552 let n: u32 = value.parse().map_err(|_| bad())?;
553 if n == 0 {
554 return Err(bad());
555 }
556 Ok((n, 1))
557}
558
559#[allow(clippy::too_many_arguments)]
564fn apply_codec(
565 spec: Option<&str>,
566 name: &str,
567 video: &mut Option<CodecId>,
568 audio: &mut Option<CodecId>,
569 subtitle: &mut Option<CodecId>,
570 audio_format: &mut Option<rff_core::SampleFormat>,
571 warnings: &mut Vec<String>,
572) -> Result<(), String> {
573 if name == "copy" {
574 return Ok(());
576 }
577 let Some(id) = CodecId::from_name(name) else {
578 return Err(format!(
579 "unknown encoder `{name}` (`rff -codecs` lists the supported ones)"
580 ));
581 };
582 let pinned = CodecId::sample_format_from_name(name);
584 match spec {
585 Some(s) if s.starts_with('v') => *video = Some(id),
586 Some(s) if s.starts_with('a') => {
587 *audio = Some(id);
588 if pinned.is_some() {
589 *audio_format = pinned;
590 }
591 }
592 Some(s) if s.starts_with('s') => match id.media_type() {
593 rff_core::MediaType::Subtitle => *subtitle = Some(id),
594 _ => warnings.push(format!("-c:s: `{name}` is not a subtitle codec (ignored)")),
595 },
596 None => match id.media_type() {
598 rff_core::MediaType::Video => *video = Some(id),
599 rff_core::MediaType::Audio => {
600 *audio = Some(id);
601 if pinned.is_some() {
602 *audio_format = pinned;
603 }
604 }
605 rff_core::MediaType::Subtitle => *subtitle = Some(id),
606 _ => {}
607 },
608 _ => {}
609 }
610 Ok(())
611}
612
613#[cfg(test)]
614mod tests {
615 use super::*;
616
617 fn output(args: &[&str]) -> (OutputSpec, Vec<String>) {
618 let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
619 let cli = parse(&args).expect("parses");
620 let Action::Transcode(mut spec) = cli.action else {
621 panic!("expected a transcode");
622 };
623 (spec.outputs.remove(0), cli.warnings)
624 }
625
626 #[test]
627 fn vn_and_an_disable_stream_kinds() {
628 let (out, warnings) = output(&["-i", "src.mp4", "-vn", "-c:a", "opus", "out.m4a"]);
629 assert_eq!(out.disabled, vec![MediaType::Video]);
630 assert_eq!(out.path, PathBuf::from("out.m4a"));
631 assert!(warnings.is_empty(), "{warnings:?}");
632
633 let (out, _) = output(&["-i", "src.mp4", "-c:v", "h264", "-an", "out.mp4"]);
634 assert_eq!(out.disabled, vec![MediaType::Audio]);
635 assert_eq!(out.path, PathBuf::from("out.mp4"));
636 }
637
638 #[test]
639 fn unknown_encoder_is_an_error_naming_it() {
640 for name in ["libsvtav1", "nonexistentcodec"] {
641 let args: Vec<String> = ["-i", "src.mp4", "-c:v", name, "out.mkv"]
642 .iter()
643 .map(|s| s.to_string())
644 .collect();
645 let err = parse(&args).err().expect("unknown encoder must fail");
646 assert!(err.contains(name), "{err}");
647 }
648 let (out, _) = output(&["-i", "src.mp4", "-c:v", "libx265", "out.mkv"]);
649 assert_eq!(out.video_codec.map(|c| c.codec), Some(CodecId::Hevc));
650 let (out, _) = output(&["-i", "src.mp4", "-c:v", "copy", "out.mkv"]);
651 assert!(out.video_codec.is_none());
652 }
653
654 #[test]
655 fn unknown_option_never_takes_the_output_path() {
656 let (out, warnings) = output(&["-i", "src.mp4", "-bogus", "out.mp4"]);
657 assert_eq!(out.path, PathBuf::from("out.mp4"));
658 assert_eq!(warnings.len(), 1);
659 let (out, _) = output(&["-i", "src.mp4", "-pix_fmt", "yuv420p", "out.mp4"]);
661 assert_eq!(out.path, PathBuf::from("out.mp4"));
662 }
663}