1use 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#[derive(Debug, Clone)]
17pub struct MediaInfo {
18 pub format_name: String,
20 pub streams: Vec<StreamInfo>,
22}
23
24#[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
37pub fn probe(engine: &Engine, path: impl AsRef<Path>) -> Result<MediaInfo> {
46 probe_with_metadata(engine, path).map(|(info, _)| info)
47}
48
49pub 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
60pub 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
101pub(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 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 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
131fn 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
139pub(crate) enum Source {
143 File(rff_format::SeekInput),
144 Stream(Box<dyn Read + Send>),
145}
146
147impl Source {
148 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
162pub(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 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
199fn 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
233fn 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
248fn 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}