1use serde::{Deserialize, Serialize};
5
6#[non_exhaustive]
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub enum VideoCodec {
12 H264,
14 H265,
16 Mpeg4,
18}
19
20#[derive(Clone, Debug, PartialEq)]
22pub(crate) struct Probe {
23 pub mime_type: &'static str,
24 pub codec: VideoCodec,
25 pub width: u32,
26 pub height: u32,
27 pub duration_ms: u64,
28 pub frames: u64,
29}
30
31struct Atom<'a> {
33 kind: [u8; 4],
34 body: &'a [u8],
35}
36
37fn atoms(mut data: &[u8]) -> Result<Vec<Atom<'_>>, String> {
39 let mut out = Vec::new();
40 while !data.is_empty() {
41 if data.len() < 8 {
42 return Err(format!("{} trailing bytes are not a box", data.len()));
43 }
44 let size32 = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
45 let kind = [data[4], data[5], data[6], data[7]];
46 let (header, size) = match size32 {
47 0 => (8, data.len() as u64),
48 1 => {
49 let large = data.get(8..16).ok_or("a 64-bit box size is cut short")?;
50 (16, u64::from_be_bytes(large.try_into().map_err(|_| "bad box size")?))
51 }
52 n => (8, u64::from(n)),
53 };
54 let size = usize::try_from(size).map_err(|_| "a box is larger than memory")?;
55 if size < header || size > data.len() {
56 return Err(format!(
57 "box `{}` claims {size} bytes where {} remain",
58 String::from_utf8_lossy(&kind),
59 data.len()
60 ));
61 }
62 out.push(Atom { kind, body: &data[header..size] });
63 data = &data[size..];
64 }
65 Ok(out)
66}
67
68fn child<'a>(atoms: &'a [Atom<'a>], kind: &[u8; 4]) -> Option<&'a Atom<'a>> {
69 atoms.iter().find(|a| &a.kind == kind)
70}
71
72fn be32(data: &[u8], at: usize) -> Result<u32, String> {
73 data.get(at..at + 4)
74 .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
75 .ok_or_else(|| "a box is cut short".to_string())
76}
77
78fn be64(data: &[u8], at: usize) -> Result<u64, String> {
79 data.get(at..at + 8)
80 .map(|b| u64::from_be_bytes(b.try_into().unwrap_or([0; 8])))
81 .ok_or_else(|| "a box is cut short".to_string())
82}
83
84fn timing(body: &[u8]) -> Result<(u32, u64), String> {
86 match body.first() {
87 Some(1) => Ok((be32(body, 20)?, be64(body, 24)?)),
88 Some(_) => Ok((be32(body, 12)?, u64::from(be32(body, 16)?))),
89 None => Err("an empty header box".into()),
90 }
91}
92
93fn millis(timescale: u32, duration: u64) -> u64 {
94 if timescale == 0 {
95 return 0;
96 }
97 u64::try_from(u128::from(duration) * 1_000 / u128::from(timescale)).unwrap_or(u64::MAX)
98}
99
100struct VideoTrack {
102 id: u32,
103 codec: VideoCodec,
104 width: u32,
105 height: u32,
106 media_ms: u64,
108 edited: Option<u64>,
110 frames: u64,
111}
112
113fn edit_duration(elst: &[u8]) -> Result<u64, String> {
115 let version = *elst.first().ok_or("an empty `elst`")?;
116 let count = be32(elst, 4)? as usize;
117 let entry = if version == 1 { 20 } else { 12 };
118 (0..count.min(1_024)).try_fold(0u64, |total, i| {
119 let at = 8 + i * entry;
120 let duration = if version == 1 { be64(elst, at)? } else { u64::from(be32(elst, at)?) };
121 Ok(total.saturating_add(duration))
122 })
123}
124
125fn video_track(trak: &[u8]) -> Result<Option<VideoTrack>, String> {
126 let trak = atoms(trak)?;
127 let Some(mdia) = child(&trak, b"mdia") else { return Ok(None) };
128 let mdia = atoms(mdia.body)?;
129 let handler = child(&mdia, b"hdlr").map(|h| h.body.get(8..12).unwrap_or_default());
130 if handler != Some(b"vide".as_slice()) {
131 return Ok(None);
132 }
133 let id = child(&trak, b"tkhd")
134 .map(|t| if t.body.first() == Some(&1) { be32(t.body, 20) } else { be32(t.body, 12) })
135 .transpose()?
136 .unwrap_or(0);
137 let (scale, duration) =
138 child(&mdia, b"mdhd").map(|m| timing(m.body)).transpose()?.unwrap_or((0, 0));
139 let minf = atoms(child(&mdia, b"minf").ok_or("a video track has no `minf`")?.body)?;
140 let stbl = atoms(child(&minf, b"stbl").ok_or("a video track has no `stbl`")?.body)?;
141 let stsd = child(&stbl, b"stsd").ok_or("a video track has no `stsd`")?.body;
142 let entry = stsd.get(8..).ok_or("an empty `stsd`")?;
143 let format: [u8; 4] =
144 entry.get(4..8).and_then(|f| f.try_into().ok()).ok_or("an empty `stsd`")?;
145 let codec = match &format {
146 b"avc1" | b"avc3" => VideoCodec::H264,
147 b"hvc1" | b"hev1" => VideoCodec::H265,
148 b"mp4v" => VideoCodec::Mpeg4,
149 other => {
150 return Err(format!(
151 "the video is `{}`; only H.264, H.265 and MPEG-4 are accepted (VP9, AV1 and \
152 ProRes are not) — re-encode with `ffmpeg -i in -c:v libx264 out.mp4`",
153 String::from_utf8_lossy(other).trim()
154 ));
155 }
156 };
157 let width = entry.get(32..34).map_or(0, |b| u32::from(u16::from_be_bytes([b[0], b[1]])));
158 let height = entry.get(34..36).map_or(0, |b| u32::from(u16::from_be_bytes([b[0], b[1]])));
159 let frames = child(&stbl, b"stsz").map(|s| be32(s.body, 8)).transpose()?.unwrap_or(0);
160 let edited = match child(&trak, b"edts") {
161 Some(edts) => atoms(edts.body)?
162 .iter()
163 .find(|a| &a.kind == b"elst")
164 .map(|elst| edit_duration(elst.body))
165 .transpose()?,
166 None => None,
167 };
168 Ok(Some(VideoTrack {
169 id,
170 codec,
171 width,
172 height,
173 media_ms: millis(scale, duration),
174 edited: edited.filter(|d| *d > 0),
175 frames: u64::from(frames),
176 }))
177}
178
179fn fragment_frames(top: &[Atom<'_>], track: u32) -> Result<u64, String> {
181 let mut frames = 0u64;
182 for moof in top.iter().filter(|a| &a.kind == b"moof") {
183 for traf in atoms(moof.body)?.iter().filter(|a| &a.kind == b"traf") {
184 let traf = atoms(traf.body)?;
185 let id = child(&traf, b"tfhd").map(|t| be32(t.body, 4)).transpose()?;
186 if id.is_some_and(|id| id != track && track != 0) {
187 continue;
188 }
189 for trun in traf.iter().filter(|a| &a.kind == b"trun") {
190 frames += u64::from(be32(trun.body, 4)?);
191 }
192 }
193 }
194 Ok(frames)
195}
196
197pub(crate) fn probe(bytes: &[u8]) -> Result<Probe, String> {
204 let top = atoms(bytes).map_err(|e| format!("not an MP4 or MOV file: {e}"))?;
205 let brand = child(&top, b"ftyp").and_then(|f| f.body.get(0..4));
206 let mime_type = match brand {
207 Some(b"qt ") => "video/quicktime",
208 Some(_) => "video/mp4",
209 None if top.iter().any(|a| &a.kind == b"moov") => "video/quicktime",
211 None => return Err("not an MP4 or MOV file: no `ftyp` or `moov` box".into()),
212 };
213 let moov = child(&top, b"moov").ok_or("the file has no `moov` box")?;
214 let moov = atoms(moov.body)?;
215 let mut track = None;
216 for trak in moov.iter().filter(|a| &a.kind == b"trak") {
217 if let Some(found) = video_track(trak.body)? {
218 track = Some(found);
219 break;
220 }
221 }
222 let VideoTrack { id, codec, width, height, media_ms, edited, mut frames } =
223 track.ok_or("the file has no video track")?;
224 let movie = child(&moov, b"mvhd").map(|m| timing(m.body)).transpose()?;
225 let mut duration_ms = match (edited, movie) {
228 (Some(edited), Some((scale, _))) => millis(scale, edited),
229 _ => media_ms,
230 };
231 if duration_ms == 0 {
232 duration_ms = movie.map_or(0, |(scale, d)| millis(scale, d));
233 }
234 if frames == 0 {
235 frames = fragment_frames(&top, id)?;
236 }
237 if duration_ms == 0 {
238 let mehd = child(&moov, b"mvex")
239 .map(|m| atoms(m.body))
240 .transpose()?
241 .and_then(|mvex| {
242 child(&mvex, b"mehd").map(|m| {
243 if m.body.first() == Some(&1) {
244 be64(m.body, 4)
245 } else {
246 be32(m.body, 4).map(u64::from)
247 }
248 })
249 })
250 .transpose()?;
251 let scale = child(&moov, b"mvhd").map(|m| timing(m.body)).transpose()?.map_or(0, |t| t.0);
252 duration_ms = mehd.map_or(0, |d| millis(scale, d));
253 }
254 if duration_ms == 0 || frames == 0 || width == 0 || height == 0 {
255 return Err(format!(
256 "the video track states {frames} frames, {duration_ms} ms and {width}x{height}; \
257 remux it with `ffmpeg -i in.mp4 -c copy -movflags +faststart out.mp4`"
258 ));
259 }
260 Ok(Probe { mime_type, codec, width, height, duration_ms, frames })
261}
262
263#[cfg(test)]
264pub(crate) mod tests {
265 use super::*;
266
267 fn atom(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
268 let mut out = ((body.len() + 8) as u32).to_be_bytes().to_vec();
269 out.extend_from_slice(kind);
270 out.extend_from_slice(body);
271 out
272 }
273
274 pub(crate) fn mp4(
277 codec: &[u8; 4],
278 width: u16,
279 height: u16,
280 duration_ms: u32,
281 frames: u32,
282 payload: usize,
283 ) -> Vec<u8> {
284 let mut mdhd = vec![0u8; 4];
285 mdhd.extend_from_slice(&[0; 8]);
286 mdhd.extend_from_slice(&1_000u32.to_be_bytes());
287 mdhd.extend_from_slice(&duration_ms.to_be_bytes());
288 mdhd.extend_from_slice(&[0; 4]);
289 let mut hdlr = vec![0u8; 8];
290 hdlr.extend_from_slice(b"vide");
291 hdlr.extend_from_slice(&[0; 12]);
292 let mut entry = vec![0u8; 24];
293 entry.extend_from_slice(&width.to_be_bytes());
294 entry.extend_from_slice(&height.to_be_bytes());
295 entry.extend_from_slice(&[0; 50]);
296 let mut stsd = vec![0u8, 0, 0, 0, 0, 0, 0, 1];
297 stsd.extend(atom(codec, &entry));
298 let mut stsz = vec![0u8; 8];
299 stsz.extend_from_slice(&frames.to_be_bytes());
300 let stbl = [atom(b"stsd", &stsd), atom(b"stsz", &stsz)].concat();
301 let minf = atom(b"stbl", &stbl);
302 let mdia = [atom(b"mdhd", &mdhd), atom(b"hdlr", &hdlr), atom(b"minf", &minf)].concat();
303 let mut tkhd = vec![0u8; 12];
304 tkhd.extend_from_slice(&1u32.to_be_bytes());
305 tkhd.extend_from_slice(&[0; 64]);
306 let trak = [atom(b"tkhd", &tkhd), atom(b"mdia", &mdia)].concat();
307 let moov = atom(b"trak", &trak);
308 [
309 atom(b"ftyp", b"isom\0\0\x02\0isomiso2avc1mp41"),
310 atom(b"moov", &moov),
311 atom(b"mdat", &vec![0u8; payload]),
312 ]
313 .concat()
314 }
315
316 #[test]
317 fn a_video_track_is_read_from_its_boxes() {
318 let probe = probe(&mp4(b"avc1", 640, 360, 20_000, 600, 32)).unwrap();
319 assert_eq!(
320 probe,
321 Probe {
322 mime_type: "video/mp4",
323 codec: VideoCodec::H264,
324 width: 640,
325 height: 360,
326 duration_ms: 20_000,
327 frames: 600,
328 }
329 );
330 }
331
332 #[test]
333 fn other_codecs_and_files_are_refused() {
334 let vp9 = probe(&mp4(b"vp09", 640, 360, 1_000, 30, 0)).unwrap_err();
335 assert!(vp9.contains("vp09"), "{vp9}");
336 assert!(probe(b"\x89PNG\r\n\x1a\n").is_err());
337 assert!(probe(&atom(b"ftyp", b"isom")).unwrap_err().contains("moov"));
338 let mut cut = mp4(b"avc1", 640, 360, 1_000, 30, 0);
339 cut.truncate(cut.len() - 20);
340 assert!(probe(&cut).is_err());
341 assert!(probe(&mp4(b"hvc1", 640, 360, 0, 30, 0)).unwrap_err().contains("faststart"));
342 }
343}