Skip to main content

rff/
probe.rs

1//! Media inspection — the engine side of `ffprobe`.
2//!
3//! [`probe`] opens an input, identifies its container, reads the stream
4//! headers, and returns a structured [`MediaInfo`]. The CLI's `ffprobe` and the
5//! server's `POST /v1/probe` both call straight into this.
6
7use std::io::Read;
8use std::path::Path;
9
10use rff_core::{CodecId, Dictionary, Error, MediaType, Rational, Result};
11use rff_format::Chapter;
12
13use crate::Engine;
14
15/// Everything we learned about an input.
16#[derive(Debug, Clone)]
17pub struct MediaInfo {
18    /// Short name of the detected container format (e.g. `avi`).
19    pub format_name: String,
20    /// One entry per elementary stream.
21    pub streams: Vec<StreamInfo>,
22}
23
24/// Summary of one elementary stream.
25#[derive(Debug, Clone)]
26pub struct StreamInfo {
27    pub index: usize,
28    pub media_type: MediaType,
29    pub codec_id: CodecId,
30    pub time_base: Rational,
31    pub width: u32,
32    pub height: u32,
33    pub sample_rate: u32,
34    pub channels: u16,
35}
36
37/// Probe a media file at `path`.
38///
39/// The container is currently chosen by file extension; content-sniffing
40/// (reading magic bytes) is a planned upgrade. Reading the header itself relies
41/// on the corresponding demuxer, which is still scaffolded — so today this
42/// resolves the format and then surfaces the demuxer's
43/// [`Unimplemented`](rff_core::Error::Unimplemented) state. The plumbing is
44/// real; only the per-format parsing is pending.
45pub fn probe(engine: &Engine, path: impl AsRef<Path>) -> Result<MediaInfo> {
46    probe_with_metadata(engine, path).map(|(info, _)| info)
47}
48
49/// [`probe`], plus each stream's own metadata, in stream order (an empty
50/// [`Dictionary`] for a stream that has none) — the JPEG MPF demuxer's
51/// `mpf_type` (`primary`, `gain_map`, ...), for one. `ffprobe` prints it as
52/// the stream's `Metadata:` / `tags`.
53pub fn probe_with_metadata(
54    engine: &Engine,
55    path: impl AsRef<Path>,
56) -> Result<(MediaInfo, Vec<Dictionary>)> {
57    probe_with_chapters(engine, path).map(|(info, tags, _)| (info, tags))
58}
59
60/// [`probe_with_metadata`], plus the file's chapters
61/// ([`Demuxer::chapters`](rff_format::Demuxer::chapters)).
62pub fn probe_with_chapters(
63    engine: &Engine,
64    path: impl AsRef<Path>,
65) -> Result<(MediaInfo, Vec<Dictionary>, Vec<Chapter>)> {
66    let path = path.as_ref();
67    let path_str = path
68        .to_str()
69        .ok_or_else(|| Error::Option("input path is not valid UTF-8".into()))?;
70    let (format_name, source) = open_source(engine, path_str, None)?;
71    let mut demuxer = source.open_demuxer(engine, &format_name)?;
72
73    let streams = demuxer.read_header()?;
74    let metadata = (0..streams.len())
75        .map(|i| demuxer.stream_metadata(i).cloned().unwrap_or_default())
76        .collect();
77    let streams = streams
78        .into_iter()
79        .map(|s| StreamInfo {
80            index: s.index,
81            media_type: s.media_type,
82            codec_id: s.codec_id,
83            time_base: s.time_base,
84            width: s.width,
85            height: s.height,
86            sample_rate: s.sample_rate,
87            channels: s.channels,
88        })
89        .collect();
90
91    Ok((
92        MediaInfo {
93            format_name,
94            streams,
95        },
96        metadata,
97        demuxer.chapters().to_vec(),
98    ))
99}
100
101/// Decide which container a path should be read as: an explicit `-f` override
102/// wins; otherwise sniff the file's leading bytes (content beats filename);
103/// otherwise fall back to the extension. Shared by [`probe`] and the transcode
104/// input path so both detect formats the same way.
105pub(crate) fn detect_input_format(
106    engine: &Engine,
107    path: &Path,
108    forced: Option<&str>,
109) -> Result<String> {
110    if let Some(name) = forced {
111        return Ok(name.to_string());
112    }
113    // Content sniff (best effort — an unreadable head just falls through).
114    if let Ok(head) = read_head(path, 4096) {
115        if let Some(format) = engine.formats.probe(&head) {
116            return Ok(format.name.to_string());
117        }
118    }
119    // Filename fallback.
120    let ext = path
121        .extension()
122        .and_then(|e| e.to_str())
123        .unwrap_or_default();
124    engine
125        .formats
126        .by_extension(ext)
127        .map(|f| f.name.to_string())
128        .ok_or_else(|| Error::DemuxerNotFound(path.display().to_string()))
129}
130
131/// Read up to `max` leading bytes of a file for content sniffing.
132fn read_head(path: &Path, max: usize) -> std::io::Result<Vec<u8>> {
133    let file = std::fs::File::open(path)?;
134    let mut buf = Vec::new();
135    file.take(max as u64).read_to_end(&mut buf)?;
136    Ok(buf)
137}
138
139/// An opened input. A local file stays seekable, so demuxers that can (MP4)
140/// read only their index and fetch payload on demand; everything else is a
141/// one-way byte stream.
142pub(crate) enum Source {
143    File(rff_format::SeekInput),
144    Stream(Box<dyn Read + Send>),
145}
146
147impl Source {
148    /// Open the demuxer for `format` over this source — the seek-aware one for
149    /// a file, when the format registered one.
150    pub(crate) fn open_demuxer(
151        self,
152        engine: &Engine,
153        format: &str,
154    ) -> Result<Box<dyn rff_format::Demuxer>> {
155        match self {
156            Source::File(file) => engine.formats.open_demuxer_seekable(format, file),
157            Source::Stream(stream) => engine.formats.open_demuxer(format, stream),
158        }
159    }
160}
161
162/// Open a path-or-URL as a [`Source`] and decide its container format.
163///
164/// Local files keep the read-twice (sniff then open) path and are opened
165/// buffered and seekable. Streams (URLs,
166/// pipes, UDP) are opened once, their head peeked for content sniffing, then
167/// chained back in front so the demuxer sees the whole stream from byte 0.
168/// HLS playlists (`-f hls`, an `.m3u8` name, or `#EXTM3U` content) expand to
169/// one chained stream over their TS segments first. Shared by [`probe`]
170/// (ffprobe) and the transcode input path (ffmpeg).
171pub(crate) fn open_source(
172    engine: &Engine,
173    path: &str,
174    forced: Option<&str>,
175) -> Result<(String, Source)> {
176    let stem = path.split(['?', '#']).next().unwrap_or(path);
177    if forced == Some("hls") || stem.to_ascii_lowercase().ends_with(".m3u8") {
178        let reader = rff_format_hls::open_input(path)?;
179        return sniff_stream(engine, reader, None, path);
180    }
181    if !rff_io::is_stream(path) {
182        let format = detect_input_format(engine, Path::new(path), forced)?;
183        let file = std::io::BufReader::new(std::fs::File::open(path)?);
184        return Ok((format, Source::File(Box::new(file))));
185    }
186    // RTP has no container to sniff: the reader classifies the stream by its
187    // payload type on the first packet and names the format itself.
188    if rff_io::is_rtp(path) {
189        let reader = rff_io::RtpReader::bind(path)?;
190        let format = forced
191            .map(str::to_string)
192            .unwrap_or_else(|| reader.format_name().to_string());
193        return Ok((format, Source::Stream(Box::new(reader))));
194    }
195    let reader = rff_io::open(path)?;
196    sniff_stream(engine, reader, forced, path)
197}
198
199/// Peek a stream's head, pick its format (forced > content sniff > URL
200/// extension), and hand back head+rest chained. An `#EXTM3U` head re-opens the
201/// source as HLS input (possible for URLs/files; a pipe can't be re-read).
202fn sniff_stream(
203    engine: &Engine,
204    mut reader: Box<dyn Read + Send>,
205    forced: Option<&str>,
206    path: &str,
207) -> Result<(String, Source)> {
208    let mut head = vec![0u8; 4096];
209    let n = read_some(&mut reader, &mut head)?;
210    head.truncate(n);
211    if forced.is_none() && head.starts_with(b"#EXTM3U") {
212        if rff_io::is_pipe(path) {
213            return Err(Error::unsupported(
214                "hls input from a pipe (the playlist's segments cannot be fetched relative to stdin)",
215            ));
216        }
217        let reader = rff_format_hls::open_input(path)?;
218        return sniff_stream(engine, reader, None, path);
219    }
220    let format = match forced {
221        Some(f) => f.to_string(),
222        None => engine
223            .formats
224            .probe(&head)
225            .map(|f| f.name.to_string())
226            .or_else(|| url_extension_format(engine, path))
227            .ok_or_else(|| Error::DemuxerNotFound(format!("{path} (pass -f)")))?,
228    };
229    let chained: Box<dyn Read + Send> = Box::new(std::io::Cursor::new(head).chain(reader));
230    Ok((format, Source::Stream(chained)))
231}
232
233/// Read up to `buf.len()` bytes, tolerating short reads (network streams arrive
234/// in pieces); stops at EOF.
235fn read_some(reader: &mut dyn Read, buf: &mut [u8]) -> Result<usize> {
236    let mut filled = 0;
237    while filled < buf.len() {
238        match reader.read(&mut buf[filled..]) {
239            Ok(0) => break,
240            Ok(n) => filled += n,
241            Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
242            Err(e) => return Err(e.into()),
243        }
244    }
245    Ok(filled)
246}
247
248/// Guess a container from a URL's extension (after the last `.`, ignoring any
249/// `?query`/`#fragment`).
250fn url_extension_format(engine: &Engine, url: &str) -> Option<String> {
251    let stem = url.split(['?', '#']).next().unwrap_or(url);
252    let ext = stem.rsplit('.').next().unwrap_or("");
253    engine.formats.by_extension(ext).map(|f| f.name.to_string())
254}