Skip to main content

rff_cli/
ffprobe.rs

1//! The `ffprobe` binary's logic: inspect one input and print its container +
2//! streams, in human-readable form or as JSON (`-of json`).
3//!
4//! `-show_targets` adds the other half of the question: not just what the file
5//! *is*, but every format this build can convert it *into*, and what each
6//! conversion would cost. It is computed from the engine's own registries by
7//! `rff::targets`, so it never promises an output the transcoder would refuse.
8
9use std::process::ExitCode;
10
11use rff::probe::MediaInfo;
12use rff::Engine;
13use rff_core::Dictionary;
14
15/// Entry point used by `src/bin/ffprobe.rs`.
16pub fn run(args: Vec<String>) -> ExitCode {
17    let mut hide_banner = false;
18    let mut want_version = false;
19    let mut as_json = false;
20    let mut show_targets = false;
21    let mut input: Option<String> = None;
22
23    let mut i = 0;
24    while i < args.len() {
25        let arg = &args[i];
26        match arg.as_str() {
27            "-hide_banner" => hide_banner = true,
28            "-version" => want_version = true,
29            // Presence-only flags we accept for compatibility.
30            "-show_format" | "-show_streams" | "-show_entries" => {}
31            "-show_targets" => show_targets = true,
32            "-of" | "-print_format" => {
33                i += 1;
34                as_json = args.get(i).map(|v| v == "json").unwrap_or(false);
35            }
36            "-v" | "-loglevel" => {
37                i += 1; // consume and ignore the level
38            }
39            "-i" => {
40                i += 1;
41                input = args.get(i).cloned();
42            }
43            other if !other.starts_with('-') => input = Some(other.to_string()),
44            other => eprintln!("[warning] unrecognized option `{other}` (ignored)"),
45        }
46        i += 1;
47    }
48
49    if !hide_banner {
50        eprint!("{}", crate::ffmpeg::banner());
51    }
52    if want_version {
53        crate::ffmpeg::print_version();
54        return ExitCode::SUCCESS;
55    }
56
57    let Some(input) = input else {
58        eprintln!("[error] no input file specified. Usage: ffprobe [options] INPUT");
59        return ExitCode::FAILURE;
60    };
61
62    let engine = Engine::new();
63    if show_targets {
64        return match rff::targets::targets(&engine, &input) {
65            Ok(plan) => {
66                if as_json {
67                    println!("{}", plan.to_json());
68                } else {
69                    print_targets(&input, &plan);
70                }
71                ExitCode::SUCCESS
72            }
73            Err(err) => {
74                eprintln!("[error] {input}: {err}");
75                ExitCode::FAILURE
76            }
77        };
78    }
79    match rff::probe::probe_with_metadata(&engine, &input) {
80        Ok((info, tags)) => {
81            if as_json {
82                print_json(&input, &info, &tags);
83            } else {
84                print_human(&input, &info, &tags);
85            }
86            ExitCode::SUCCESS
87        }
88        Err(err) => {
89            eprintln!("[error] {input}: {err}");
90            ExitCode::FAILURE
91        }
92    }
93}
94
95/// `-show_targets`: every output this build can write for the input, grouped by
96/// kind, with the command that produces each one.
97///
98/// `!` lines are the caveats (a dropped stream, a second lossy generation);
99/// `$` lines are runnable as printed.
100fn print_targets(input: &str, plan: &rff::targets::Plan) {
101    let stem = std::path::Path::new(input)
102        .file_stem()
103        .and_then(|s| s.to_str())
104        .unwrap_or("out");
105
106    println!(
107        "Input #0, {}, from '{input}':",
108        plan.source_format.as_deref().unwrap_or("?")
109    );
110    for s in &plan.source {
111        println!("  Stream #0:{}: {}: {}", s.index, s.media_type, s.codec_id);
112    }
113
114    println!(
115        "
116Convert to ({} targets):",
117        plan.targets.len()
118    );
119    let mut kind = None;
120    for t in &plan.targets {
121        if kind != Some(t.kind) {
122            println!(
123                "
124  {}",
125                t.kind
126            );
127            kind = Some(t.kind);
128        }
129        println!(
130            "    .{:<6} {:<9} {}",
131            t.extension,
132            t.fidelity,
133            t.stream_summary()
134        );
135        for note in &t.notes {
136            println!("               ! {note}");
137        }
138        println!("               $ {}", t.command(input, stem));
139    }
140}
141
142/// FFprobe-style human output.
143fn print_human(input: &str, info: &MediaInfo, tags: &[Dictionary]) {
144    println!("Input #0, {}, from '{}':", info.format_name, input);
145    for stream in &info.streams {
146        let detail = match stream.media_type {
147            rff_core::MediaType::Video => {
148                format!(
149                    "Video: {}, {}x{}",
150                    stream.codec_id, stream.width, stream.height
151                )
152            }
153            rff_core::MediaType::Audio => format!(
154                "Audio: {}, {} Hz, {} ch",
155                stream.codec_id, stream.sample_rate, stream.channels
156            ),
157            other => format!("{other}: {}", stream.codec_id),
158        };
159        println!("  Stream #0:{}: {detail}", stream.index);
160        if let Some(md) = tags.get(stream.index).filter(|d| !d.is_empty()) {
161            println!("    Metadata:");
162            for (k, v) in md.iter() {
163                println!("      {k:<16}: {v}");
164            }
165        }
166    }
167}
168
169/// Minimal JSON output (hand-rolled to keep the CLI dependency-light).
170fn print_json(input: &str, info: &MediaInfo, tags: &[Dictionary]) {
171    println!("{{");
172    println!("  \"format\": {{");
173    println!("    \"filename\": {},", json_str(input));
174    println!("    \"format_name\": {},", json_str(&info.format_name));
175    println!("    \"nb_streams\": {}", info.streams.len());
176    println!("  }},");
177    println!("  \"streams\": [");
178    for (idx, stream) in info.streams.iter().enumerate() {
179        let comma = if idx + 1 < info.streams.len() {
180            ","
181        } else {
182            ""
183        };
184        println!("    {{");
185        println!("      \"index\": {},", stream.index);
186        println!(
187            "      \"codec_type\": {},",
188            json_str(&stream.media_type.to_string())
189        );
190        println!(
191            "      \"codec_name\": {},",
192            json_str(stream.codec_id.name())
193        );
194        println!("      \"width\": {},", stream.width);
195        println!("      \"height\": {},", stream.height);
196        println!("      \"sample_rate\": {},", stream.sample_rate);
197        match tags.get(stream.index).filter(|d| !d.is_empty()) {
198            Some(md) => {
199                println!("      \"channels\": {},", stream.channels);
200                println!("      \"tags\": {{");
201                let n = md.len();
202                for (i, (k, v)) in md.iter().enumerate() {
203                    let sep = if i + 1 < n { "," } else { "" };
204                    println!("        {}: {}{sep}", json_str(k), json_str(v));
205                }
206                println!("      }}");
207            }
208            None => println!("      \"channels\": {}", stream.channels),
209        }
210        println!("    }}{comma}");
211    }
212    println!("  ]");
213    println!("}}");
214}
215
216/// Escape a string as a JSON string literal (quotes + backslashes).
217fn json_str(s: &str) -> String {
218    let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
219    format!("\"{escaped}\"")
220}