1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum TrackCodec {
25 H264,
27 Hevc,
29 Vp9,
31 Av1,
33}
34
35#[derive(Debug, Clone, Copy)]
37pub struct Sample {
38 pub offset: u64,
40 pub size: u32,
42 pub duration: u32,
44 pub dts: i64,
47 pub pts: i64,
54 pub sync: bool,
57}
58
59#[derive(Debug, Clone)]
61pub struct VideoTrack {
62 pub codec: TrackCodec,
64 pub width: u32,
66 pub height: u32,
68 pub config: Vec<u8>,
73 pub timescale: u32,
75 pub samples: Vec<Sample>,
78}
79
80impl VideoTrack {
81 pub fn presentation_order(&self) -> Vec<usize> {
89 let mut idx: Vec<usize> = (0..self.samples.len()).collect();
90 idx.sort_by_key(|&i| self.samples[i].pts);
91 idx
92 }
93
94 pub fn max_reorder(&self) -> usize {
97 let order = self.presentation_order();
98 order
99 .iter()
100 .enumerate()
101 .map(|(shown, &decoded)| decoded.saturating_sub(shown))
102 .max()
103 .unwrap_or(0)
104 }
105
106 pub fn fps(&self) -> Option<f64> {
109 let ticks: u64 = self.samples.iter().map(|s| s.duration as u64).sum();
110 if ticks == 0 || self.samples.is_empty() {
111 return None;
112 }
113 Some(self.samples.len() as f64 * self.timescale as f64 / ticks as f64)
114 }
115}
116
117pub(crate) fn boxes<'a>(data: &'a [u8], mut f: impl FnMut(&[u8; 4], &'a [u8])) {
123 let mut off = 0usize;
124 while off + 8 <= data.len() {
125 let size32 = u32::from_be_bytes(data[off..off + 4].try_into().unwrap()) as usize;
126 let ty: [u8; 4] = data[off + 4..off + 8].try_into().unwrap();
127 let (header, size) = match size32 {
128 0 => (8, data.len() - off),
129 1 => {
130 if off + 16 > data.len() {
131 return;
132 }
133 let s = u64::from_be_bytes(data[off + 8..off + 16].try_into().unwrap()) as usize;
134 (16, s)
135 }
136 n => (8, n),
137 };
138 if size < header || off + size > data.len() {
139 return;
140 }
141 f(&ty, &data[off + header..off + size]);
142 off += size;
143 }
144}
145
146pub(crate) fn find<'a>(data: &'a [u8], want: &[u8; 4]) -> Option<&'a [u8]> {
147 let mut hit = None;
148 boxes(data, |ty, body| {
149 if ty == want && hit.is_none() {
150 hit = Some(body);
151 }
152 });
153 hit
154}
155
156pub(crate) fn u32at(b: &[u8], i: usize) -> u32 {
157 u32::from_be_bytes(b[i..i + 4].try_into().unwrap())
158}
159
160pub fn demux_video(data: &[u8]) -> Result<VideoTrack, String> {
164 if find(data, b"moof").is_some() {
165 return Err("fragmented MP4 (moof) is not supported".into());
166 }
167 let moov = find(data, b"moov").ok_or("no moov box — not an MP4?")?;
168
169 let mut video_stbl: Option<&[u8]> = None;
171 let mut timescale = 0u32;
172 boxes(moov, |ty, trak| {
173 if ty != b"trak" || video_stbl.is_some() {
174 return;
175 }
176 let Some(mdia) = find(trak, b"mdia") else { return };
177 let is_video = find(mdia, b"hdlr")
178 .map(|h| h.len() >= 12 && &h[8..12] == b"vide")
179 .unwrap_or(false);
180 if !is_video {
181 return;
182 }
183 if let Some(mdhd) = find(mdia, b"mdhd") {
184 timescale = match mdhd.first() {
187 Some(1) if mdhd.len() >= 24 => u32at(mdhd, 20),
188 _ if mdhd.len() >= 16 => u32at(mdhd, 12),
189 _ => 0,
190 };
191 }
192 video_stbl = find(mdia, b"minf").and_then(|m| find(m, b"stbl"));
193 });
194 let stbl = video_stbl.ok_or("no video track")?;
195 if timescale == 0 {
196 return Err("video track has no timescale".into());
197 }
198
199 let stsd = find(stbl, b"stsd").ok_or("no stsd")?;
201 if stsd.len() < 8 {
202 return Err("stsd too short".into());
203 }
204 if u32at(stsd, 4) != 1 {
205 return Err("more than one sample description is not supported".into());
206 }
207 let entry = &stsd[8..];
208 if entry.len() < 86 {
209 return Err("sample entry too short".into());
210 }
211 let format: [u8; 4] = entry[4..8].try_into().unwrap();
212 let codec = match &format {
213 b"avc1" | b"avc3" => TrackCodec::H264,
214 b"hvc1" | b"hev1" => TrackCodec::Hevc,
215 b"vp09" => TrackCodec::Vp9,
216 b"av01" => TrackCodec::Av1,
217 other => {
218 return Err(format!(
219 "unsupported sample format {:?} — only H.264, HEVC, VP9 and AV1",
220 String::from_utf8_lossy(other)
221 ))
222 }
223 };
224 let width = u16::from_be_bytes(entry[32..34].try_into().unwrap()) as u32;
225 let height = u16::from_be_bytes(entry[34..36].try_into().unwrap()) as u32;
226 let want_cfg: &[u8; 4] = match codec {
228 TrackCodec::H264 => b"avcC",
229 TrackCodec::Hevc => b"hvcC",
230 TrackCodec::Vp9 => b"vpcC",
231 TrackCodec::Av1 => b"av1C",
232 };
233 let config = find(&entry[86..], want_cfg)
234 .ok_or_else(|| format!("no {} in the sample entry", String::from_utf8_lossy(want_cfg)))?
235 .to_vec();
236
237 let stts = find(stbl, b"stts").ok_or("no stts")?;
239 let mut durations: Vec<u32> = Vec::new();
240 if stts.len() >= 8 {
241 let n = u32at(stts, 4) as usize;
242 for i in 0..n {
243 let o = 8 + i * 8;
244 if o + 8 > stts.len() {
245 break;
246 }
247 let count = u32at(stts, o);
248 let delta = u32at(stts, o + 4);
249 durations.extend(std::iter::repeat_n(delta, count as usize));
250 }
251 }
252
253 let mut offsets: Vec<i32> = Vec::new();
259 if let Some(ctts) = find(stbl, b"ctts") {
260 if ctts.len() >= 8 {
261 let n = u32at(ctts, 4) as usize;
262 for i in 0..n {
263 let o = 8 + i * 8;
264 if o + 8 > ctts.len() {
265 break;
266 }
267 let count = u32at(ctts, o) as usize;
268 let off = u32at(ctts, o + 4) as i32;
269 offsets.extend(std::iter::repeat_n(off, count));
270 }
271 }
272 }
273
274 let stsz = find(stbl, b"stsz").ok_or("no stsz")?;
276 if stsz.len() < 12 {
277 return Err("stsz too short".into());
278 }
279 let uniform = u32at(stsz, 4);
280 let count = u32at(stsz, 8) as usize;
281 let sizes: Vec<u32> = if uniform != 0 {
282 vec![uniform; count]
283 } else {
284 (0..count)
285 .map(|i| {
286 let o = 12 + i * 4;
287 if o + 4 <= stsz.len() {
288 u32at(stsz, o)
289 } else {
290 0
291 }
292 })
293 .collect()
294 };
295
296 let stsc = find(stbl, b"stsc").ok_or("no stsc")?;
298 let mut runs: Vec<(u32, u32)> = Vec::new(); if stsc.len() >= 8 {
300 let n = u32at(stsc, 4) as usize;
301 for i in 0..n {
302 let o = 8 + i * 12;
303 if o + 12 > stsc.len() {
304 break;
305 }
306 runs.push((u32at(stsc, o), u32at(stsc, o + 4)));
307 }
308 }
309 let chunk_offsets: Vec<u64> = if let Some(co64) = find(stbl, b"co64") {
310 let n = u32at(co64, 4) as usize;
311 (0..n)
312 .map(|i| {
313 let o = 8 + i * 8;
314 if o + 8 <= co64.len() {
315 u64::from_be_bytes(co64[o..o + 8].try_into().unwrap())
316 } else {
317 0
318 }
319 })
320 .collect()
321 } else {
322 let stco = find(stbl, b"stco").ok_or("no stco or co64")?;
323 let n = u32at(stco, 4) as usize;
324 (0..n)
325 .map(|i| {
326 let o = 8 + i * 4;
327 if o + 4 <= stco.len() {
328 u32at(stco, o) as u64
329 } else {
330 0
331 }
332 })
333 .collect()
334 };
335
336 let sync: Option<std::collections::HashSet<u32>> = find(stbl, b"stss").map(|stss| {
338 let n = if stss.len() >= 8 { u32at(stss, 4) as usize } else { 0 };
339 (0..n)
340 .filter_map(|i| {
341 let o = 8 + i * 4;
342 (o + 4 <= stss.len()).then(|| u32at(stss, o))
343 })
344 .collect()
345 });
346
347 let mut samples = Vec::with_capacity(sizes.len());
349 let mut idx = 0usize;
350 let mut dts = 0i64;
351 for (ci, &chunk_off) in chunk_offsets.iter().enumerate() {
352 let chunk = ci as u32 + 1;
353 let per = runs
355 .iter()
356 .rev()
357 .find(|(first, _)| *first <= chunk)
358 .map(|(_, n)| *n)
359 .unwrap_or(0);
360 let mut at = chunk_off;
361 for _ in 0..per {
362 if idx >= sizes.len() {
363 break;
364 }
365 let duration = durations.get(idx).copied().unwrap_or(0);
366 samples.push(Sample {
367 offset: at,
368 size: sizes[idx],
369 duration,
370 dts,
371 pts: dts + offsets.get(idx).copied().unwrap_or(0) as i64,
372 sync: sync
374 .as_ref()
375 .map(|s| s.contains(&(idx as u32 + 1)))
376 .unwrap_or(true),
377 });
378 at += sizes[idx] as u64;
379 dts += duration as i64;
380 idx += 1;
381 }
382 }
383 if samples.is_empty() {
384 return Err("the video track has no samples".into());
385 }
386
387 Ok(VideoTrack {
388 codec,
389 width,
390 height,
391 config,
392 timescale,
393 samples,
394 })
395}