Skip to main content

rff_cli/
args.rs

1//! FFmpeg-compatible argument parsing.
2//!
3//! FFmpeg's CLI is not a flat flag list — it's a small grammar:
4//!
5//! ```text
6//!   ffmpeg [global opts] {[input opts] -i INPUT}... {[output opts] OUTPUT}...
7//! ```
8//!
9//! Options can carry a *stream specifier* after a colon — `-c:v libx264` means
10//! "codec, video stream". This module parses that grammar into a neutral
11//! [`Cli`] and, for transcode invocations, builds an [`rff::transcode::TranscodeSpec`].
12//!
13//! This is a deliberately pragmatic subset: the common options people actually
14//! type. Unknown options are skipped with a warning rather than aborting, and
15//! the recognised set is easy to extend — add an arm to the match in [`parse`].
16//! A codec name is different: an unknown `-c` value is an error, because
17//! ignoring it would silently encode with something else.
18
19use std::path::PathBuf;
20
21use rff::transcode::{InputSpec, MapSelector, MapSpec, OutputSpec, StreamCodec, TranscodeSpec};
22use rff_core::{CodecId, Dictionary, MediaType, PixelFormat};
23
24/// Parse a `-map` value like `0`, `0:v`, `0:a`, or `0:2`.
25fn 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
38/// What the user actually asked `ffmpeg` to do. Informational sub-commands
39/// (`-version`, `-codecs`, ...) short-circuit a transcode.
40pub enum Action {
41    Version,
42    Help,
43    ListCodecs,
44    ListFormats,
45    Transcode(TranscodeSpec),
46}
47
48/// A fully parsed command line.
49pub struct Cli {
50    pub hide_banner: bool,
51    pub loglevel: Option<String>,
52    /// Non-fatal parse notes (unknown options, ignored values) to print to stderr.
53    pub warnings: Vec<String>,
54    pub action: Action,
55}
56
57/// Parse `args` (everything after the program name) into a [`Cli`].
58///
59/// Returns `Err` only for hard syntax errors (e.g. an option missing its
60/// required value); soft problems become [`Cli::warnings`].
61pub 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    // Informational sub-commands win over a transcode if present.
67    let mut action_override: Option<Action> = None;
68
69    // --- transcode accumulators ---
70    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    // Sample format pinned by the codec NAME (`-c:a pcm_s16le`) or by an
77    // explicit `-sample_fmt`. Kept separate from the codec id, which is
78    // format-agnostic by design.
79    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    // Options given WITHOUT a `:v`/`:a` stream specifier that more than one
83    // codec kind understands (FFmpeg treats `-compression_level` this way).
84    // Held aside and attached after parsing, once we know which codecs actually
85    // exist — attaching eagerly to both made every `-compression_level` on an
86    // image encode emit a spurious "audio options given without -c:a" warning.
87    let mut shared_opts = Dictionary::new();
88    let mut max_video_frames: Option<u64> = None;
89    let mut video_filters: Option<String> = None;
90    // `-pix_fmt`: the encoder's input pixel format (an output option, so it
91    // applies whether or not `-c:v` names the encoder).
92    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    // Trim window: -ss (start), -t (duration), -to (absolute end).
100    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        // A bare `-` is stdout (FFmpeg's pipe spelling), not an option.
114        let Some(opt) = arg.strip_prefix('-').filter(|_| arg != "-") else {
115            // A bare token is a positional argument: the output file.
116            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        // Split an option into its base name and optional stream specifier:
127        // `c:v:0` -> ("c", Some("v:0")).
128        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` applies to the next input if we haven't reached outputs yet,
152            // otherwise to the output.
153            "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            // Codec selection: -c / -codec (optionally :v / :a), and the legacy
163            // -vcodec / -acodec aliases.
164            "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            // Stream disabling: -vn / -an / -sn / -dn drop every video /
214            // audio / subtitle / data stream from the output, mapped or not.
215            "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            // Stream selection: -map INPUT[:v|:a|:N] (repeatable).
221            "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            // Video filter graph: -vf / -filter:v. Audio: -af / -filter:a.
230            "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            // Multi-input filter graph: -filter_complex / -lavfi.
240            "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            // Trim window: -ss START, -t DURATION, -to END (`HH:MM:SS.mmm` or
251            // seconds). Applied to the output: decode-and-discard, so it is
252            // frame-accurate for transcodes and keyframe-cut for -c copy.
253            "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 RATE: constant output frame rate (25, 29.97, 30000/1001).
258            "r" | "framerate" => frame_rate = Some(parse_rate(&take_value(args, &mut i, arg)?)?),
259
260            // -s WxH: shorthand for a trailing scale filter.
261            "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 RATE / -ac CHANNELS: audio output rate and channel count.
275            "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 segmenting: -hls_time SECONDS. (-hls_list_size shapes LIVE
293            // sliding-window playlists; our HLS output is VOD, so say so.)
294            "hls_time" => {
295                let value = take_value(args, &mut i, arg)?;
296                format_options.set("hls_time", value);
297            }
298            // DASH segmenting: -seg_duration SECONDS (FFmpeg's dash option).
299            "seg_duration" => {
300                let value = take_value(args, &mut i, arg)?;
301                format_options.set("seg_duration", value);
302            }
303            // MP4/MOV flags: `-movflags +faststart` puts `moov` first.
304            "movflags" => {
305                let value = take_value(args, &mut i, arg)?;
306                format_options.set("movflags", value);
307            }
308            // Which input the chapters come from (-1: none).
309            "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 key=value (repeatable).
319            "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            // Bitrate: -b:v / -b:a (bare -b defaults to video).
328            "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            // Rate control / tuning (video by default; `:a` targets audio):
337            // -crf / -qp / -q / -qscale (quality), -preset (speed<->quality), -pass (1|2),
338            // -cpu-used / -speed (VP9 speed preset 0 best..4 fastest),
339            // -profile (h264: baseline|main|high), -g (keyframe interval).
340            // `-frames:v N` / `-frames N` — stop after N video frames. Needed for
341            // any rate-vs-quality measurement over a clip prefix: without it a
342            // harness silently encodes the whole input while scoring a prefix.
343            "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            // JPEG/MJPEG private options default to video (an image codec has no
352            // audio side): -jpeg_quality 1..100, -sampling 444|440|422|420|411,
353            // -progressive, -optimize_huffman, -restart_interval, -trellis.
354            // `-pred` is PNG's filter/prediction knob (none/sub/up/avg/paeth/
355            // mixed), spelled as FFmpeg's PNG encoder spells it. It is video-only
356            // by nature — there is no audio codec that takes it.
357            "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` is not audio-only: FFmpeg treats it as a
374            // generic codec option, and PNG uses it (0..9) exactly as Opus does
375            // (0..10). Unscoped it therefore has to reach BOTH dictionaries, or
376            // `rff -i in.png -c:v png -compression_level 9 out.png` silently
377            // encodes at the default — which is what it used to do. `:v` / `:a`
378            // still target one side.
379            "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            // Codec private / tuning options forwarded to the encoder's
389            // `configure` Dictionary (audio by default; `:v` targets video).
390            // Includes Opus: -application, -vbr, and the R1 frame-parallel
391            // controls -opus_parallel / -opus_warmup / -threads.
392            "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            // Anything else: accept gracefully. Best-effort consume a trailing
401            // value so we don't mistake it for the output path — but never the
402            // last argument, which is where the output path goes.
403            _ => {
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    // Attach the unscoped shared options to whichever codecs are actually
424    // present. An explicit `:v`/`:a` value already set above wins over these.
425    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    // Warn about codec options that have no codec to attach to.
435    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    // Re-encode-only options on a stream-copy: say so instead of silence.
442    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    // `-vf fps=N` is the same CFR stage as `-r`: lift it out of the chain.
449    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    // -ss/-t/-to resolve to an absolute [start, end) window; -to wins over -t
470    // only when both name the same bound (FFmpeg takes the earlier end).
471    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
522/// Consume and return the value following an option, advancing the cursor.
523fn 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
530/// Parse an FFmpeg time value: plain seconds (`12.5`) or `[HH:]MM:SS[.mmm]`.
531fn 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
548/// Parse a frame rate: integer (`25`), decimal (`29.97`), or fraction
549/// (`30000/1001`). Decimals become exact fractions over a power of ten.
550fn 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/// Resolve a codec name to an id (treating `copy` as "no re-encode" → `None`)
582/// and assign it to the slot selected by the stream specifier. An unknown
583/// name is an error, as FFmpeg's "Unknown encoder" is: leaving the slot unset
584/// would stream-copy or default-encode instead of what the command names.
585#[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        // Stream copy: leave the slot unset; the pipeline will passthrough.
597        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    // `pcm_s16le` vs `pcm_f32le` differ only in the name; keep what it pins.
605    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        // No specifier: apply to whichever media type this codec is.
619        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        // Still consumes a value that is not the last argument.
682        let (out, _) = output(&["-i", "src.mp4", "-tune", "film", "out.mp4"]);
683        assert_eq!(out.path, PathBuf::from("out.mp4"));
684    }
685
686    /// `-pix_fmt` is an output option: parsed with or without `-c:v` (#179).
687    #[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}