1use std::process::ExitCode;
11
12use rff::format::Chapter;
13use rff::probe::MediaInfo;
14use rff::Engine;
15use rff_core::Dictionary;
16
17pub fn run(args: Vec<String>) -> ExitCode {
19 let mut hide_banner = false;
20 let mut want_version = false;
21 let mut as_json = false;
22 let mut show_targets = false;
23 let mut show_chapters = false;
24 let mut input: Option<String> = None;
25
26 let mut i = 0;
27 while i < args.len() {
28 let arg = &args[i];
29 match arg.as_str() {
30 "-hide_banner" => hide_banner = true,
31 "-version" => want_version = true,
32 "-show_format" | "-show_streams" | "-show_entries" => {}
34 "-show_targets" => show_targets = true,
35 "-show_chapters" => show_chapters = true,
36 "-of" | "-print_format" => {
37 i += 1;
38 as_json = args.get(i).map(|v| v == "json").unwrap_or(false);
39 }
40 "-v" | "-loglevel" => {
41 i += 1; }
43 "-i" => {
44 i += 1;
45 input = args.get(i).cloned();
46 }
47 other if !other.starts_with('-') => input = Some(other.to_string()),
48 other => eprintln!("[warning] unrecognized option `{other}` (ignored)"),
49 }
50 i += 1;
51 }
52
53 if !hide_banner {
54 eprint!("{}", crate::ffmpeg::banner());
55 }
56 if want_version {
57 crate::ffmpeg::print_version();
58 return ExitCode::SUCCESS;
59 }
60
61 let Some(input) = input else {
62 eprintln!("[error] no input file specified. Usage: ffprobe [options] INPUT");
63 return ExitCode::FAILURE;
64 };
65
66 let engine = Engine::new();
67 if show_targets {
68 return match rff::targets::targets(&engine, &input) {
69 Ok(plan) => {
70 if as_json {
71 println!("{}", plan.to_json());
72 } else {
73 print_targets(&input, &plan);
74 }
75 ExitCode::SUCCESS
76 }
77 Err(err) => {
78 eprintln!("[error] {input}: {err}");
79 ExitCode::FAILURE
80 }
81 };
82 }
83 match rff::probe::probe_with_chapters(&engine, &input) {
84 Ok((info, tags, chapters)) => {
85 let chapters = show_chapters.then_some(&chapters[..]);
86 if as_json {
87 print_json(&input, &info, &tags, chapters);
88 } else {
89 print_human(&input, &info, &tags, chapters);
90 }
91 ExitCode::SUCCESS
92 }
93 Err(err) => {
94 eprintln!("[error] {input}: {err}");
95 ExitCode::FAILURE
96 }
97 }
98}
99
100fn print_targets(input: &str, plan: &rff::targets::Plan) {
106 let stem = std::path::Path::new(input)
107 .file_stem()
108 .and_then(|s| s.to_str())
109 .unwrap_or("out");
110
111 println!(
112 "Input #0, {}, from '{input}':",
113 plan.source_format.as_deref().unwrap_or("?")
114 );
115 for s in &plan.source {
116 println!(" Stream #0:{}: {}: {}", s.index, s.media_type, s.codec_id);
117 }
118
119 println!(
120 "
121Convert to ({} targets):",
122 plan.targets.len()
123 );
124 let mut kind = None;
125 for t in &plan.targets {
126 if kind != Some(t.kind) {
127 println!(
128 "
129 {}",
130 t.kind
131 );
132 kind = Some(t.kind);
133 }
134 println!(
135 " .{:<6} {:<9} {}",
136 t.extension,
137 t.fidelity,
138 t.stream_summary()
139 );
140 for note in &t.notes {
141 println!(" ! {note}");
142 }
143 println!(" $ {}", t.command(input, stem));
144 }
145}
146
147fn print_human(input: &str, info: &MediaInfo, tags: &[Dictionary], chapters: Option<&[Chapter]>) {
149 println!("Input #0, {}, from '{}':", info.format_name, input);
150 if let Some(list) = chapters.filter(|c| !c.is_empty()) {
151 println!(" Chapters:");
152 for (i, c) in list.iter().enumerate() {
153 let (start, end) = (seconds(c.start, c), seconds(c.end, c));
154 println!(" Chapter #0:{i}: start {start}, end {end}");
155 if !c.metadata.is_empty() {
156 println!(" Metadata:");
157 for (k, v) in c.metadata.iter() {
158 println!(" {k:<16}: {v}");
159 }
160 }
161 }
162 }
163 for stream in &info.streams {
164 let detail = match stream.media_type {
165 rff_core::MediaType::Video => {
166 format!(
167 "Video: {}, {}x{}",
168 stream.codec_id, stream.width, stream.height
169 )
170 }
171 rff_core::MediaType::Audio => format!(
172 "Audio: {}, {} Hz, {} ch",
173 stream.codec_id, stream.sample_rate, stream.channels
174 ),
175 other => format!("{other}: {}", stream.codec_id),
176 };
177 println!(" Stream #0:{}: {detail}", stream.index);
178 if let Some(md) = tags.get(stream.index).filter(|d| !d.is_empty()) {
179 println!(" Metadata:");
180 for (k, v) in md.iter() {
181 println!(" {k:<16}: {v}");
182 }
183 }
184 }
185}
186
187fn print_json(input: &str, info: &MediaInfo, tags: &[Dictionary], chapters: Option<&[Chapter]>) {
189 println!("{{");
190 println!(" \"format\": {{");
191 println!(" \"filename\": {},", json_str(input));
192 println!(" \"format_name\": {},", json_str(&info.format_name));
193 println!(" \"nb_streams\": {}", info.streams.len());
194 println!(" }},");
195 println!(" \"streams\": [");
196 for (idx, stream) in info.streams.iter().enumerate() {
197 let comma = if idx + 1 < info.streams.len() {
198 ","
199 } else {
200 ""
201 };
202 println!(" {{");
203 println!(" \"index\": {},", stream.index);
204 println!(
205 " \"codec_type\": {},",
206 json_str(&stream.media_type.to_string())
207 );
208 println!(
209 " \"codec_name\": {},",
210 json_str(stream.codec_id.name())
211 );
212 println!(" \"width\": {},", stream.width);
213 println!(" \"height\": {},", stream.height);
214 println!(" \"sample_rate\": {},", stream.sample_rate);
215 match tags.get(stream.index).filter(|d| !d.is_empty()) {
216 Some(md) => {
217 println!(" \"channels\": {},", stream.channels);
218 println!(" \"tags\": {{");
219 let n = md.len();
220 for (i, (k, v)) in md.iter().enumerate() {
221 let sep = if i + 1 < n { "," } else { "" };
222 println!(" {}: {}{sep}", json_str(k), json_str(v));
223 }
224 println!(" }}");
225 }
226 None => println!(" \"channels\": {}", stream.channels),
227 }
228 println!(" }}{comma}");
229 }
230 match chapters {
231 Some(list) => {
232 println!(" ],");
233 print_json_chapters(list);
234 }
235 None => println!(" ]"),
236 }
237 println!("}}");
238}
239
240fn print_json_chapters(list: &[Chapter]) {
242 println!(" \"chapters\": [");
243 for (i, c) in list.iter().enumerate() {
244 println!(" {{");
245 println!(" \"id\": {},", c.id as i64);
247 println!(
248 " \"time_base\": \"{}/{}\",",
249 c.time_base.num, c.time_base.den
250 );
251 println!(" \"start\": {},", c.start);
252 println!(" \"start_time\": \"{}\",", seconds(c.start, c));
253 println!(" \"end\": {},", c.end);
254 print!(" \"end_time\": \"{}\"", seconds(c.end, c));
255 if c.metadata.is_empty() {
256 println!();
257 } else {
258 println!(",\n \"tags\": {{");
259 let n = c.metadata.len();
260 for (k, (key, value)) in c.metadata.iter().enumerate() {
261 let sep = if k + 1 < n { "," } else { "" };
262 println!(" {}: {}{sep}", json_str(key), json_str(value));
263 }
264 println!(" }}");
265 }
266 println!(" }}{}", if i + 1 < list.len() { "," } else { "" });
267 }
268 println!(" ]");
269}
270
271fn seconds(v: i64, c: &Chapter) -> String {
273 format!("{:.6}", v as f64 * c.time_base.as_f64())
274}
275
276fn json_str(s: &str) -> String {
279 let mut out = String::with_capacity(s.len() + 2);
280 out.push('"');
281 for c in s.chars() {
282 match c {
283 '"' => out.push_str("\\\""),
284 '\\' => out.push_str("\\\\"),
285 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
286 c => out.push(c),
287 }
288 }
289 out.push('"');
290 out
291}