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(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    // `-pix_fmt`: the encoder's input pixel format (an output option, so it
90    // applies whether or not `-c:v` names the encoder).
91    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    // Trim window: -ss (start), -t (duration), -to (absolute end).
99    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        // A bare `-` is stdout (FFmpeg's pipe spelling), not an option.
113        let Some(opt) = arg.strip_prefix('-').filter(|_| arg != "-") else {
114            // A bare token is a positional argument: the output file.
115            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        // Split an option into its base name and optional stream specifier:
126        // `c:v:0` -> ("c", Some("v:0")).
127        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` applies to the next input if we haven't reached outputs yet,
151            // otherwise to the output.
152            "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            // Codec selection: -c / -codec (optionally :v / :a), and the legacy
162            // -vcodec / -acodec aliases.
163            "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            // Stream disabling: -vn / -an / -sn / -dn drop every video /
213            // audio / subtitle / data stream from the output, mapped or not.
214            "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            // Stream selection: -map INPUT[:v|:a|:N] (repeatable).
220            "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            // Video filter graph: -vf / -filter:v. Audio: -af / -filter:a.
229            "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            // Multi-input filter graph: -filter_complex / -lavfi.
239            "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            // Trim window: -ss START, -t DURATION, -to END (`HH:MM:SS.mmm` or
250            // seconds). Applied to the output: decode-and-discard, so it is
251            // frame-accurate for transcodes and keyframe-cut for -c copy.
252            "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 RATE: constant output frame rate (25, 29.97, 30000/1001).
257            "r" | "framerate" => frame_rate = Some(parse_rate(&take_value(args, &mut i, arg)?)?),
258
259            // -s WxH: shorthand for a trailing scale filter.
260            "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 RATE / -ac CHANNELS: audio output rate and channel count.
274            "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 segmenting: -hls_time SECONDS. (-hls_list_size shapes LIVE
292            // sliding-window playlists; our HLS output is VOD, so say so.)
293            "hls_time" => {
294                let value = take_value(args, &mut i, arg)?;
295                format_options.set("hls_time", value);
296            }
297            // DASH segmenting: -seg_duration SECONDS (FFmpeg's dash option).
298            "seg_duration" => {
299                let value = take_value(args, &mut i, arg)?;
300                format_options.set("seg_duration", value);
301            }
302            // MP4/MOV flags: `-movflags +faststart` puts `moov` first.
303            "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 key=value (repeatable).
313            "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            // Bitrate: -b:v / -b:a (bare -b defaults to video).
322            "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            // Rate control / tuning (video by default; `:a` targets audio):
331            // -crf / -qp / -q / -qscale (quality), -preset (speed<->quality), -pass (1|2),
332            // -cpu-used / -speed (VP9 speed preset 0 best..4 fastest),
333            // -profile (h264: baseline|main|high), -g (keyframe interval).
334            // `-frames:v N` / `-frames N` — stop after N video frames. Needed for
335            // any rate-vs-quality measurement over a clip prefix: without it a
336            // harness silently encodes the whole input while scoring a prefix.
337            "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            // JPEG/MJPEG private options default to video (an image codec has no
346            // audio side): -jpeg_quality 1..100, -sampling 444|440|422|420|411,
347            // -progressive, -optimize_huffman, -restart_interval, -trellis.
348            // `-pred` is PNG's filter/prediction knob (none/sub/up/avg/paeth/
349            // mixed), spelled as FFmpeg's PNG encoder spells it. It is video-only
350            // by nature — there is no audio codec that takes it.
351            "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` is not audio-only: FFmpeg treats it as a
368            // generic codec option, and PNG uses it (0..9) exactly as Opus does
369            // (0..10). Unscoped it therefore has to reach BOTH dictionaries, or
370            // `rff -i in.png -c:v png -compression_level 9 out.png` silently
371            // encodes at the default — which is what it used to do. `:v` / `:a`
372            // still target one side.
373            "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            // Codec private / tuning options forwarded to the encoder's
383            // `configure` Dictionary (audio by default; `:v` targets video).
384            // Includes Opus: -application, -vbr, and the R1 frame-parallel
385            // controls -opus_parallel / -opus_warmup / -threads.
386            "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            // Anything else: accept gracefully. Best-effort consume a trailing
395            // value so we don't mistake it for the output path — but never the
396            // last argument, which is where the output path goes.
397            _ => {
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    // Attach the unscoped shared options to whichever codecs are actually
418    // present. An explicit `:v`/`:a` value already set above wins over these.
419    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    // Warn about codec options that have no codec to attach to.
429    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    // Re-encode-only options on a stream-copy: say so instead of silence.
436    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    // `-vf fps=N` is the same CFR stage as `-r`: lift it out of the chain.
443    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    // -ss/-t/-to resolve to an absolute [start, end) window; -to wins over -t
464    // only when both name the same bound (FFmpeg takes the earlier end).
465    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
516/// Consume and return the value following an option, advancing the cursor.
517fn 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
524/// Parse an FFmpeg time value: plain seconds (`12.5`) or `[HH:]MM:SS[.mmm]`.
525fn 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
542/// Parse a frame rate: integer (`25`), decimal (`29.97`), or fraction
543/// (`30000/1001`). Decimals become exact fractions over a power of ten.
544fn 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/// Resolve a codec name to an id (treating `copy` as "no re-encode" → `None`)
576/// and assign it to the slot selected by the stream specifier. An unknown
577/// name is an error, as FFmpeg's "Unknown encoder" is: leaving the slot unset
578/// would stream-copy or default-encode instead of what the command names.
579#[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        // Stream copy: leave the slot unset; the pipeline will passthrough.
591        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    // `pcm_s16le` vs `pcm_f32le` differ only in the name; keep what it pins.
599    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        // No specifier: apply to whichever media type this codec is.
613        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        // Still consumes a value that is not the last argument.
676        let (out, _) = output(&["-i", "src.mp4", "-tune", "film", "out.mp4"]);
677        assert_eq!(out.path, PathBuf::from("out.mp4"));
678    }
679
680    /// `-pix_fmt` is an output option: parsed with or without `-c:v` (#179).
681    #[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}