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