1use std::io::Read;
8use std::path::Path;
9
10use rff_core::{CodecId, 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 let path = path.as_ref();
46 let path_str = path
47 .to_str()
48 .ok_or_else(|| Error::Option("input path is not valid UTF-8".into()))?;
49 let (format_name, reader) = open_source(engine, path_str, None)?;
50 let mut demuxer = engine.formats.open_demuxer(&format_name, reader)?;
51
52 let streams = demuxer.read_header()?;
53 let streams = streams
54 .into_iter()
55 .map(|s| StreamInfo {
56 index: s.index,
57 media_type: s.media_type,
58 codec_id: s.codec_id,
59 time_base: s.time_base,
60 width: s.width,
61 height: s.height,
62 sample_rate: s.sample_rate,
63 channels: s.channels,
64 })
65 .collect();
66
67 Ok(MediaInfo {
68 format_name,
69 streams,
70 })
71}
72
73pub(crate) fn detect_input_format(
78 engine: &Engine,
79 path: &Path,
80 forced: Option<&str>,
81) -> Result<String> {
82 if let Some(name) = forced {
83 return Ok(name.to_string());
84 }
85 if let Ok(head) = read_head(path, 4096) {
87 if let Some(format) = engine.formats.probe(&head) {
88 return Ok(format.name.to_string());
89 }
90 }
91 let ext = path
93 .extension()
94 .and_then(|e| e.to_str())
95 .unwrap_or_default();
96 engine
97 .formats
98 .by_extension(ext)
99 .map(|f| f.name.to_string())
100 .ok_or_else(|| Error::DemuxerNotFound(path.display().to_string()))
101}
102
103fn read_head(path: &Path, max: usize) -> std::io::Result<Vec<u8>> {
105 let file = std::fs::File::open(path)?;
106 let mut buf = Vec::new();
107 file.take(max as u64).read_to_end(&mut buf)?;
108 Ok(buf)
109}
110
111pub(crate) fn open_source(
120 engine: &Engine,
121 path: &str,
122 forced: Option<&str>,
123) -> Result<(String, Box<dyn Read + Send>)> {
124 let stem = path.split(['?', '#']).next().unwrap_or(path);
125 if forced == Some("hls") || stem.to_ascii_lowercase().ends_with(".m3u8") {
126 let reader = rff_format_hls::open_input(path)?;
127 return sniff_stream(engine, reader, None, path);
128 }
129 if !rff_io::is_stream(path) {
130 let format = detect_input_format(engine, Path::new(path), forced)?;
131 return Ok((format, Box::new(std::fs::File::open(path)?)));
132 }
133 let reader = rff_io::open(path)?;
134 sniff_stream(engine, reader, forced, path)
135}
136
137fn sniff_stream(
141 engine: &Engine,
142 mut reader: Box<dyn Read + Send>,
143 forced: Option<&str>,
144 path: &str,
145) -> Result<(String, Box<dyn Read + Send>)> {
146 let mut head = vec![0u8; 4096];
147 let n = read_some(&mut reader, &mut head)?;
148 head.truncate(n);
149 if forced.is_none() && head.starts_with(b"#EXTM3U") {
150 if rff_io::is_pipe(path) {
151 return Err(Error::unsupported(
152 "hls input from a pipe (the playlist's segments cannot be fetched relative to stdin)",
153 ));
154 }
155 let reader = rff_format_hls::open_input(path)?;
156 return sniff_stream(engine, reader, None, path);
157 }
158 let format = match forced {
159 Some(f) => f.to_string(),
160 None => engine
161 .formats
162 .probe(&head)
163 .map(|f| f.name.to_string())
164 .or_else(|| url_extension_format(engine, path))
165 .ok_or_else(|| Error::DemuxerNotFound(format!("{path} (pass -f)")))?,
166 };
167 let chained: Box<dyn Read + Send> = Box::new(std::io::Cursor::new(head).chain(reader));
168 Ok((format, chained))
169}
170
171fn read_some(reader: &mut dyn Read, buf: &mut [u8]) -> Result<usize> {
174 let mut filled = 0;
175 while filled < buf.len() {
176 match reader.read(&mut buf[filled..]) {
177 Ok(0) => break,
178 Ok(n) => filled += n,
179 Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
180 Err(e) => return Err(e.into()),
181 }
182 }
183 Ok(filled)
184}
185
186fn url_extension_format(engine: &Engine, url: &str) -> Option<String> {
189 let stem = url.split(['?', '#']).next().unwrap_or(url);
190 let ext = stem.rsplit('.').next().unwrap_or("");
191 engine.formats.by_extension(ext).map(|f| f.name.to_string())
192}