1use std::io::Read;
8use std::path::Path;
9
10use rff_core::{CodecId, Dictionary, Error, MediaType, Rational, Result};
11
12use crate::Engine;
13
14#[derive(Debug, Clone)]
16pub struct MediaInfo {
17 pub format_name: String,
19 pub streams: Vec<StreamInfo>,
21}
22
23#[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
36pub fn probe(engine: &Engine, path: impl AsRef<Path>) -> Result<MediaInfo> {
45 probe_with_metadata(engine, path).map(|(info, _)| info)
46}
47
48pub 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
90pub(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 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 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
120fn 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
128pub(crate) enum Source {
132 File(rff_format::SeekInput),
133 Stream(Box<dyn Read + Send>),
134}
135
136impl Source {
137 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
151pub(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 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
188fn 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
222fn 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
237fn 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}