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};
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(idx) => MapSelector::Index(idx.parse().ok()?),
33    };
34    Some(MapSpec { input, selector })
35}
36
37/// What the user actually asked `ffmpeg` to do. Informational sub-commands
38/// (`-version`, `-codecs`, ...) short-circuit a transcode.
39pub enum Action {
40    Version,
41    Help,
42    ListCodecs,
43    ListFormats,
44    Transcode(TranscodeSpec),
45}
46
47/// A fully parsed command line.
48pub struct Cli {
49    pub hide_banner: bool,
50    pub loglevel: Option<String>,
51    /// Non-fatal parse notes (unknown options, ignored values) to print to stderr.
52    pub warnings: Vec<String>,
53    pub action: Action,
54}
55
56/// Parse `args` (everything after the program name) into a [`Cli`].
57///
58/// Returns `Err` only for hard syntax errors (e.g. an option missing its
59/// required value); soft problems become [`Cli::warnings`].
60pub 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    // Informational sub-commands win over a transcode if present.
66    let mut action_override: Option<Action> = None;
67
68    // --- transcode accumulators ---
69    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    // Sample format pinned by the codec NAME (`-c:a pcm_s16le`) or by an
76    // explicit `-sample_fmt`. Kept separate from the codec id, which is
77    // format-agnostic by design.
78    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    // Options given WITHOUT a `:v`/`:a` stream specifier that more than one
82    // codec kind understands (FFmpeg treats `-compression_level` this way).
83    // Held aside and attached after parsing, once we know which codecs actually
84    // exist — attaching eagerly to both made every `-compression_level` on an
85    // image encode emit a spurious "audio options given without -c:a" warning.
86    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    // Trim window: -ss (start), -t (duration), -to (absolute end).
96    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        // A bare `-` is stdout (FFmpeg's pipe spelling), not an option.
110        let Some(opt) = arg.strip_prefix('-').filter(|_| arg != "-") else {
111            // A bare token is a positional argument: the output file.
112            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        // Split an option into its base name and optional stream specifier:
123        // `c:v:0` -> ("c", Some("v:0")).
124        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` applies to the next input if we haven't reached outputs yet,
148            // otherwise to the output.
149            "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            // Codec selection: -c / -codec (optionally :v / :a), and the legacy
159            // -vcodec / -acodec aliases.
160            "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            // Stream disabling: -vn / -an / -sn / -dn drop every video /
210            // audio / subtitle / data stream from the output, mapped or not.
211            "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            // Stream selection: -map INPUT[:v|:a|:N] (repeatable).
217            "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            // Video filter graph: -vf / -filter:v. Audio: -af / -filter:a.
226            "vf" => video_filters = Some(take_value(args, &mut i, arg)?),
227            "af" => audio_filters = Some(take_value(args, &mut i, arg)?),
228            // Multi-input filter graph: -filter_complex / -lavfi.
229            "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            // Trim window: -ss START, -t DURATION, -to END (`HH:MM:SS.mmm` or
240            // seconds). Applied to the output: decode-and-discard, so it is
241            // frame-accurate for transcodes and keyframe-cut for -c copy.
242            "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 RATE: constant output frame rate (25, 29.97, 30000/1001).
247            "r" | "framerate" => frame_rate = Some(parse_rate(&take_value(args, &mut i, arg)?)?),
248
249            // -s WxH: shorthand for a trailing scale filter.
250            "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 RATE / -ac CHANNELS: audio output rate and channel count.
264            "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 segmenting: -hls_time SECONDS. (-hls_list_size shapes LIVE
282            // sliding-window playlists; our HLS output is VOD, so say so.)
283            "hls_time" => {
284                let value = take_value(args, &mut i, arg)?;
285                format_options.set("hls_time", value);
286            }
287            // DASH segmenting: -seg_duration SECONDS (FFmpeg's dash option).
288            "seg_duration" => {
289                let value = take_value(args, &mut i, arg)?;
290                format_options.set("seg_duration", value);
291            }
292            // MP4/MOV flags: `-movflags +faststart` puts `moov` first.
293            "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 key=value (repeatable).
303            "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            // Bitrate: -b:v / -b:a (bare -b defaults to video).
312            "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            // Rate control / tuning (video by default; `:a` targets audio):
321            // -crf / -qp / -q / -qscale (quality), -preset (speed<->quality), -pass (1|2),
322            // -cpu-used / -speed (VP9 speed preset 0 best..4 fastest),
323            // -profile (h264: baseline|main|high), -g (keyframe interval).
324            // `-frames:v N` / `-frames N` — stop after N video frames. Needed for
325            // any rate-vs-quality measurement over a clip prefix: without it a
326            // harness silently encodes the whole input while scoring a prefix.
327            "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            // JPEG/MJPEG private options default to video (an image codec has no
336            // audio side): -jpeg_quality 1..100, -sampling 444|440|422|420|411,
337            // -progressive, -optimize_huffman, -restart_interval, -trellis.
338            // `-pred` is PNG's filter/prediction knob (none/sub/up/avg/paeth/
339            // mixed), spelled as FFmpeg's PNG encoder spells it. It is video-only
340            // by nature — there is no audio codec that takes it.
341            "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` is not audio-only: FFmpeg treats it as a
358            // generic codec option, and PNG uses it (0..9) exactly as Opus does
359            // (0..10). Unscoped it therefore has to reach BOTH dictionaries, or
360            // `rff -i in.png -c:v png -compression_level 9 out.png` silently
361            // encodes at the default — which is what it used to do. `:v` / `:a`
362            // still target one side.
363            "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            // Codec private / tuning options forwarded to the encoder's
373            // `configure` Dictionary (audio by default; `:v` targets video).
374            // Includes Opus: -application, -vbr, and the R1 frame-parallel
375            // controls -opus_parallel / -opus_warmup / -threads.
376            "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            // Anything else: accept gracefully. Best-effort consume a trailing
385            // value so we don't mistake it for the output path — but never the
386            // last argument, which is where the output path goes.
387            _ => {
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    // Attach the unscoped shared options to whichever codecs are actually
408    // present. An explicit `:v`/`:a` value already set above wins over these.
409    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    // Warn about codec options that have no codec to attach to.
419    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    // Re-encode-only options on a stream-copy: say so instead of silence.
426    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    // `-vf fps=N` is the same CFR stage as `-r`: lift it out of the chain.
433    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    // -ss/-t/-to resolve to an absolute [start, end) window; -to wins over -t
454    // only when both name the same bound (FFmpeg takes the earlier end).
455    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
505/// Consume and return the value following an option, advancing the cursor.
506fn 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
513/// Parse an FFmpeg time value: plain seconds (`12.5`) or `[HH:]MM:SS[.mmm]`.
514fn 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
531/// Parse a frame rate: integer (`25`), decimal (`29.97`), or fraction
532/// (`30000/1001`). Decimals become exact fractions over a power of ten.
533fn 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/// Resolve a codec name to an id (treating `copy` as "no re-encode" → `None`)
565/// and assign it to the slot selected by the stream specifier. An unknown
566/// name is an error, as FFmpeg's "Unknown encoder" is: leaving the slot unset
567/// would stream-copy or default-encode instead of what the command names.
568#[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        // Stream copy: leave the slot unset; the pipeline will passthrough.
580        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    // `pcm_s16le` vs `pcm_f32le` differ only in the name; keep what it pins.
588    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        // No specifier: apply to whichever media type this codec is.
602        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        // Still consumes a value that is not the last argument.
665        let (out, _) = output(&["-i", "src.mp4", "-pix_fmt", "yuv420p", "out.mp4"]);
666        assert_eq!(out.path, PathBuf::from("out.mp4"));
667    }
668}