Skip to main content

oa/video/
demux.rs

1//! Bounded local video packet demuxing.
2
3pub(super) mod edits;
4mod fragmented;
5mod mkv;
6mod mpegts;
7
8pub use crate::video::types::VideoContainerInfo;
9use std::{
10	collections::BTreeSet,
11	fs::File,
12	io::{Read, Seek, SeekFrom},
13	path::Path,
14};
15
16use crate::{Error, Result};
17
18use super::{
19	Av1Profile, H264PictureLayout, H264Profile, H265Profile, VideoChromaSubsampling,
20	VideoComponentBitDepth, VideoDecodeProfile, Vp9Profile,
21};
22
23const MAX_MP4_TABLE_ENTRIES: usize = 8 * 1024 * 1024;
24const MAX_MOOV_BYTES: usize = 256 * 1024 * 1024;
25const MAX_PACKET_BYTES: usize = 256 * 1024 * 1024;
26
27/// Compressed video codec carried by a stream.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum VideoCodec {
30	/// Advanced Video Coding / H.264.
31	H264,
32	/// High Efficiency Video Coding / H.265.
33	H265,
34	/// AV1.
35	Av1,
36	/// VP9.
37	Vp9,
38}
39
40/// Container kind recognized by the current demux boundary.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum VideoContainerKind {
43	/// ISO Base Media File Format / MP4.
44	Mp4,
45	/// Matroska EBML container.
46	Matroska,
47	/// WebM EBML subset.
48	WebM,
49	/// MPEG-2 Transport Stream.
50	MpegTs,
51}
52
53/// Rational stream time base measured in seconds per timestamp tick.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub struct VideoTimeBase {
56	numerator: u32,
57	denominator: u32,
58}
59
60impl VideoTimeBase {
61	/// Construct a non-zero rational time base.
62	///
63	/// # Errors
64	///
65	/// Returns an error when either component is zero.
66	pub fn new(numerator: u32, denominator: u32) -> Result<Self> {
67		if numerator == 0 || denominator == 0 {
68			return Err(Error::invalid_argument(
69				"video time-base numerator and denominator must be non-zero",
70			));
71		}
72		Ok(Self {
73			numerator,
74			denominator,
75		})
76	}
77
78	/// Return the numerator in seconds per tick.
79	pub const fn numerator(self) -> u32 {
80		self.numerator
81	}
82
83	/// Return the denominator in seconds per tick.
84	pub const fn denominator(self) -> u32 {
85		self.denominator
86	}
87}
88
89impl VideoContainerInfo {
90	/// Return the container kind.
91	pub const fn kind(self) -> VideoContainerKind {
92		self.kind
93	}
94
95	/// Return the selected video codec.
96	pub const fn codec(self) -> VideoCodec {
97		self.codec
98	}
99
100	/// Return the coded width.
101	pub const fn width(self) -> u32 {
102		self.width
103	}
104
105	/// Return the coded height.
106	pub const fn height(self) -> u32 {
107		self.height
108	}
109
110	/// Return the selected track time base.
111	pub const fn time_base(self) -> VideoTimeBase {
112		self.time_base
113	}
114
115	/// Return the track duration in time-base ticks, or zero when unknown.
116	pub const fn duration(self) -> u64 {
117		self.duration
118	}
119
120	/// Return the selected track sample count, or zero for streaming MPEG-TS.
121	pub const fn sample_count(self) -> u32 {
122		self.sample_count
123	}
124
125	/// Return the selected container track identifier.
126	pub const fn track_id(self) -> u32 {
127		self.track_id
128	}
129
130	/// Return the number of tracks declared by the movie box.
131	pub const fn track_count(self) -> u32 {
132		self.track_count
133	}
134
135	/// Return the exact Vulkan-queryable stream profile when representable.
136	///
137	/// Codec profiles outside the current Vulkan standard-video binding return
138	/// `None`; this does not mean the container or bitstream is invalid.
139	pub const fn decode_profile(self) -> Option<VideoDecodeProfile> {
140		self.decode_profile
141	}
142
143	/// Return the average frame rate derived from samples and track duration.
144	pub fn frame_rate(self) -> f64 {
145		if self.duration == 0 {
146			return 0.0;
147		}
148		f64::from(self.sample_count) * f64::from(self.time_base.denominator)
149			/ (self.duration as f64 * f64::from(self.time_base.numerator))
150	}
151}
152
153/// One owned compressed video access unit in the selected track time base.
154#[derive(Clone, Debug, PartialEq, Eq)]
155pub struct VideoPacket {
156	data: Vec<u8>,
157	presentation_timestamp: u64,
158	decode_timestamp: u64,
159	duration: u32,
160	keyframe: bool,
161	track_id: u32,
162}
163
164impl VideoPacket {
165	/// Borrow Annex-B H.264/H.265 or native AV1/VP9 access-unit bytes.
166	pub fn data(&self) -> &[u8] {
167		&self.data
168	}
169
170	/// Consume the packet and return its owned bytes.
171	pub fn into_data(self) -> Vec<u8> {
172		self.data
173	}
174
175	/// Return the presentation timestamp in track time-base ticks.
176	pub const fn presentation_timestamp(&self) -> u64 {
177		self.presentation_timestamp
178	}
179
180	/// Return the decode timestamp in track time-base ticks.
181	pub const fn decode_timestamp(&self) -> u64 {
182		self.decode_timestamp
183	}
184
185	/// Return the sample duration in track time-base ticks.
186	pub const fn duration(&self) -> u32 {
187		self.duration
188	}
189
190	/// Return whether this sample is a random-access point.
191	pub const fn is_keyframe(&self) -> bool {
192		self.keyframe
193	}
194
195	/// Return the source container track identifier.
196	pub const fn track_id(&self) -> u32 {
197		self.track_id
198	}
199}
200
201/// Stateful packet source for one local video track.
202///
203/// Metadata is bounded and validated at open. Indexed containers read only
204/// the current compressed sample; MPEG-TS assembles one bounded PES at a time.
205/// H.264/H.265 length-prefixed samples are normalized to Annex-B and codec
206/// parameter sets are prepended to the first keyframe after open or seek.
207pub struct VideoDemuxer {
208	file: Option<File>,
209	info: VideoContainerInfo,
210	samples: Vec<Sample>,
211	current_sample: usize,
212	keyframes: Vec<usize>,
213	nal_length_size: Option<usize>,
214	codec_config: Vec<u8>,
215	need_codec_config: bool,
216	eos: bool,
217	ts: Option<mpegts::TsState>,
218}
219
220impl VideoDemuxer {
221	/// Open and validate one local MP4, Matroska, WebM, or MPEG-TS video track.
222	///
223	/// # Errors
224	///
225	/// Returns an error for an empty or unreadable path, a malformed or
226	/// unsupported container/codec, hostile table sizes, inconsistent sample
227	/// metadata, timestamp overflow, or allocation failure.
228	pub fn open(path: impl AsRef<Path>) -> Result<Self> {
229		let path = path.as_ref();
230		if path.as_os_str().is_empty() {
231			return Err(Error::invalid_argument("VideoDemuxer path is empty"));
232		}
233		let mut file = File::open(path).map_err(|source| Error::io("video file open", source))?;
234		let file_size = file
235			.metadata()
236			.map_err(|source| Error::io("video file metadata", source))?
237			.len();
238		let mut magic = [0_u8; 4];
239		file
240			.read_exact(&mut magic)
241			.map_err(|source| Error::io("video container signature read", source))?;
242		file
243			.seek(SeekFrom::Start(0))
244			.map_err(|source| Error::io("video container rewind", source))?;
245		let (parsed, ts) = if magic == [0x1a, 0x45, 0xdf, 0xa3] {
246			(mkv::parse(&mut file, file_size, path)?, None)
247		} else if magic[0] == 0x47 && file_size >= 188 {
248			let (info, state) = mpegts::open(&mut file, file_size)?;
249			(
250				ParsedMovie {
251					info,
252					samples: Vec::new(),
253					nal_length_size: None,
254					codec_config: Vec::new(),
255				},
256				Some(state),
257			)
258		} else {
259			let moov = read_moov(&mut file, file_size)?;
260			let mut parsed = parse_moov(&moov, file_size)?;
261			if parsed.samples.is_empty() {
262				fragmented::append(&mut file, file_size, &moov, &mut parsed)?;
263			}
264			(parsed, None)
265		};
266		let mut keyframes = Vec::new();
267		keyframes
268			.try_reserve_exact(
269				parsed
270					.samples
271					.iter()
272					.filter(|sample| sample.keyframe)
273					.count(),
274			)
275			.map_err(|_| Error::resource_exhausted("video keyframe index allocation failed"))?;
276		keyframes.extend(
277			parsed
278				.samples
279				.iter()
280				.enumerate()
281				.filter_map(|(index, sample)| sample.keyframe.then_some(index)),
282		);
283		keyframes.sort_unstable_by_key(|&index| (parsed.samples[index].pts, index));
284		Ok(Self {
285			file: Some(file),
286			info: parsed.info,
287			samples: parsed.samples,
288			current_sample: 0,
289			keyframes,
290			nal_length_size: parsed.nal_length_size,
291			codec_config: parsed.codec_config,
292			need_codec_config: true,
293			eos: false,
294			ts,
295		})
296	}
297
298	/// Return selected-track metadata.
299	pub const fn info(&self) -> VideoContainerInfo {
300		self.info
301	}
302
303	/// Return whether the source has reached end of stream.
304	pub const fn is_eos(&self) -> bool {
305		self.eos
306	}
307
308	/// Return the zero-based index of the next sample.
309	pub const fn current_sample_index(&self) -> usize {
310		self.current_sample
311	}
312
313	pub(crate) fn presentation_timestamps(&self) -> Result<(Vec<u64>, u64)> {
314		if self.ts.is_some() {
315			return Err(Error::missing_capability(
316				"MPEG-TS does not expose a display-order frame index",
317			));
318		}
319		let mut timestamps = Vec::new();
320		timestamps
321			.try_reserve_exact(self.samples.len())
322			.map_err(|_| Error::resource_exhausted("video timestamp index allocation failed"))?;
323		let mut end = self.info.duration;
324		for sample in &self.samples {
325			timestamps.push(sample.pts);
326			end = end.max(
327				sample
328					.pts
329					.checked_add(u64::from(sample.duration))
330					.ok_or_else(|| Error::data_loss("video presentation end overflows its time base"))?,
331			);
332		}
333		timestamps.sort_unstable();
334		Ok((timestamps, end))
335	}
336
337	/// Read the next compressed access unit, or `None` at end of stream.
338	///
339	/// # Errors
340	///
341	/// Returns an error after close or when seeking, allocation, reading, or NAL
342	/// normalization fails.
343	pub fn read_next_packet(&mut self) -> Result<Option<VideoPacket>> {
344		let file = self
345			.file
346			.as_mut()
347			.ok_or_else(|| Error::failed_precondition("VideoDemuxer is closed"))?;
348		if let Some(ts) = self.ts.as_mut() {
349			let packet = ts.read_next(file)?;
350			self.eos = packet.is_none();
351			if packet.is_some() {
352				self.current_sample += 1;
353			}
354			return Ok(packet);
355		}
356		let Some(sample) = self.samples.get(self.current_sample).copied() else {
357			self.eos = true;
358			return Ok(None);
359		};
360		let size = usize::try_from(sample.size)
361			.map_err(|_| Error::out_of_range("video packet size exceeds usize"))?;
362		if size == 0 || size > MAX_PACKET_BYTES {
363			return Err(Error::data_loss(
364				"video packet size is zero or exceeds the safety bound",
365			));
366		}
367		let mut encoded = Vec::new();
368		encoded
369			.try_reserve_exact(size)
370			.map_err(|_| Error::resource_exhausted("video packet allocation failed"))?;
371		encoded.resize(size, 0);
372		file
373			.seek(SeekFrom::Start(sample.offset))
374			.map_err(|source| Error::io("video packet seek", source))?;
375		file
376			.read_exact(&mut encoded)
377			.map_err(|source| Error::io("video packet read", source))?;
378
379		let mut data = if let Some(length_size) = self.nal_length_size {
380			length_prefixed_to_annex_b(&encoded, length_size)?
381		} else {
382			encoded
383		};
384		if sample.keyframe && self.need_codec_config && !self.codec_config.is_empty() {
385			let capacity = self
386				.codec_config
387				.len()
388				.checked_add(data.len())
389				.ok_or_else(|| Error::out_of_range("video packet plus codec config overflows usize"))?;
390			let mut prefixed = Vec::new();
391			prefixed
392				.try_reserve_exact(capacity)
393				.map_err(|_| Error::resource_exhausted("video packet prefix allocation failed"))?;
394			prefixed.extend_from_slice(&self.codec_config);
395			prefixed.append(&mut data);
396			data = prefixed;
397			self.need_codec_config = false;
398		}
399		self.current_sample += 1;
400		Ok(Some(VideoPacket {
401			data,
402			presentation_timestamp: sample.pts,
403			decode_timestamp: sample.dts,
404			duration: sample.duration,
405			keyframe: sample.keyframe,
406			track_id: self.info.track_id,
407		}))
408	}
409
410	/// Seek to the closest preceding indexed keyframe by presentation timestamp.
411	/// MPEG-TS supports only rewind to zero.
412	///
413	/// # Errors
414	///
415	/// Returns an error after close or when the stream contains no keyframe.
416	pub fn seek(&mut self, presentation_timestamp: u64) -> Result<()> {
417		let file = self
418			.file
419			.as_mut()
420			.ok_or_else(|| Error::failed_precondition("VideoDemuxer is closed"))?;
421		if let Some(ts) = self.ts.as_mut() {
422			if presentation_timestamp != 0 {
423				return Err(Error::missing_capability(
424					"MPEG-TS seek supports rewind to zero only",
425				));
426			}
427			file
428				.seek(SeekFrom::Start(0))
429				.map_err(|source| Error::io("MPEG-TS rewind", source))?;
430			ts.reset();
431			self.current_sample = 0;
432			self.eos = false;
433			return Ok(());
434		}
435		let (preceding, _) = self.keyframes.split_at(
436			self
437				.keyframes
438				.partition_point(|&index| self.samples[index].pts <= presentation_timestamp),
439		);
440		let index = preceding
441			.last()
442			.or_else(|| self.keyframes.iter().min())
443			.copied()
444			.ok_or_else(|| Error::data_loss("video track has no random-access sample"))?;
445		self.current_sample = index;
446		self.need_codec_config = true;
447		self.eos = false;
448		Ok(())
449	}
450
451	/// Close this demuxer and discard unread packet state.
452	///
453	/// A second close is idempotent. Drop performs no I/O beyond releasing the
454	/// already-open read-only file handle.
455	pub fn close(&mut self) {
456		self.file = None;
457		self.ts = None;
458		self.eos = true;
459	}
460}
461
462/// Convert an MP4 length-prefixed H.264/H.265 sample into Annex-B NAL units.
463///
464/// # Errors
465///
466/// Returns an error for a length width other than 1, 2, or 4, a truncated
467/// length field, a zero-sized NAL unit, arithmetic overflow, or payload overrun.
468pub fn length_prefixed_to_annex_b(sample: &[u8], length_size: usize) -> Result<Vec<u8>> {
469	if !matches!(length_size, 1 | 2 | 4) {
470		return Err(Error::invalid_argument(
471			"NAL length-field size must be 1, 2, or 4 bytes",
472		));
473	}
474	let mut cursor = 0_usize;
475	let mut output = Vec::new();
476	while cursor < sample.len() {
477		let length_end = cursor
478			.checked_add(length_size)
479			.ok_or_else(|| Error::data_loss("NAL length-field offset overflows usize"))?;
480		let length_bytes = sample
481			.get(cursor..length_end)
482			.ok_or_else(|| Error::data_loss("truncated NAL length field"))?;
483		let mut length = 0_usize;
484		for byte in length_bytes {
485			length = length
486				.checked_mul(256)
487				.and_then(|value| value.checked_add(usize::from(*byte)))
488				.ok_or_else(|| Error::data_loss("NAL payload length overflows usize"))?;
489		}
490		if length == 0 {
491			return Err(Error::data_loss("zero-sized NAL unit"));
492		}
493		let payload_end = length_end
494			.checked_add(length)
495			.ok_or_else(|| Error::data_loss("NAL payload end overflows usize"))?;
496		let payload = sample
497			.get(length_end..payload_end)
498			.ok_or_else(|| Error::data_loss("NAL payload exceeds the MP4 sample"))?;
499		output
500			.try_reserve(4 + payload.len())
501			.map_err(|_| Error::resource_exhausted("Annex-B packet allocation failed"))?;
502		output.extend_from_slice(&[0, 0, 0, 1]);
503		output.extend_from_slice(payload);
504		cursor = payload_end;
505	}
506	if output.is_empty() {
507		return Err(Error::data_loss("MP4 sample contains no NAL units"));
508	}
509	Ok(output)
510}
511
512#[derive(Clone, Copy)]
513struct Sample {
514	offset: u64,
515	size: u32,
516	dts: u64,
517	pts: u64,
518	duration: u32,
519	keyframe: bool,
520}
521
522struct ParsedMovie {
523	info: VideoContainerInfo,
524	samples: Vec<Sample>,
525	nal_length_size: Option<usize>,
526	codec_config: Vec<u8>,
527}
528
529struct ParsedTrack {
530	track_id: u32,
531	codec: VideoCodec,
532	width: u32,
533	height: u32,
534	timescale: u32,
535	duration: u64,
536	samples: Vec<Sample>,
537	nal_length_size: Option<usize>,
538	codec_config: Vec<u8>,
539	decode_profile: Option<VideoDecodeProfile>,
540}
541
542fn read_moov(file: &mut File, file_size: u64) -> Result<Vec<u8>> {
543	let mut offset = 0_u64;
544	let mut saw_ftyp = false;
545	while offset < file_size {
546		file
547			.seek(SeekFrom::Start(offset))
548			.map_err(|source| Error::io("MP4 box seek", source))?;
549		let header = read_file_box_header(file, offset, file_size)?;
550		if header.kind == *b"ftyp" {
551			saw_ftyp = true;
552		}
553		if header.kind == *b"moov" {
554			if !saw_ftyp {
555				return Err(Error::data_loss(
556					"MP4 movie box precedes or lacks file-type box",
557				));
558			}
559			let payload_len = usize::try_from(header.payload_size)
560				.map_err(|_| Error::out_of_range("MP4 movie box exceeds usize"))?;
561			if payload_len > MAX_MOOV_BYTES {
562				return Err(Error::resource_exhausted(
563					"MP4 movie box exceeds the metadata bound",
564				));
565			}
566			let mut payload = Vec::new();
567			payload
568				.try_reserve_exact(payload_len)
569				.map_err(|_| Error::resource_exhausted("MP4 movie box allocation failed"))?;
570			payload.resize(payload_len, 0);
571			file
572				.read_exact(&mut payload)
573				.map_err(|source| Error::io("MP4 movie box read", source))?;
574			return Ok(payload);
575		}
576		offset = header.end;
577	}
578	Err(Error::data_loss("MP4 file has no movie box"))
579}
580
581struct FileBoxHeader {
582	kind: [u8; 4],
583	payload_size: u64,
584	end: u64,
585}
586
587fn read_file_box_header(file: &mut File, offset: u64, limit: u64) -> Result<FileBoxHeader> {
588	let mut bytes = [0_u8; 8];
589	file
590		.read_exact(&mut bytes)
591		.map_err(|source| Error::io("MP4 box header read", source))?;
592	let size32 = u32::from_be_bytes(
593		bytes[..4]
594			.try_into()
595			.map_err(|_| Error::internal("fixed MP4 box-size slice conversion failed"))?,
596	);
597	let kind = bytes[4..8]
598		.try_into()
599		.map_err(|_| Error::internal("fixed MP4 box-type slice conversion failed"))?;
600	let (size, header_size) = if size32 == 1 {
601		let mut extended = [0_u8; 8];
602		file
603			.read_exact(&mut extended)
604			.map_err(|source| Error::io("MP4 extended box header read", source))?;
605		(u64::from_be_bytes(extended), 16_u64)
606	} else if size32 == 0 {
607		(
608			limit
609				.checked_sub(offset)
610				.ok_or_else(|| Error::data_loss("MP4 box offset exceeds file"))?,
611			8,
612		)
613	} else {
614		(u64::from(size32), 8)
615	};
616	if size < header_size {
617		return Err(Error::data_loss("MP4 box is smaller than its header"));
618	}
619	let end = offset
620		.checked_add(size)
621		.ok_or_else(|| Error::data_loss("MP4 box end overflows u64"))?;
622	if end > limit {
623		return Err(Error::data_loss("MP4 box exceeds its containing file"));
624	}
625	Ok(FileBoxHeader {
626		kind,
627		payload_size: size - header_size,
628		end,
629	})
630}
631
632fn parse_moov(data: &[u8], file_size: u64) -> Result<ParsedMovie> {
633	let mut tracks = Vec::new();
634	let mut track_count = 0_u32;
635	for child in boxes(data)? {
636		if child.kind == *b"trak" {
637			track_count = track_count
638				.checked_add(1)
639				.ok_or_else(|| Error::out_of_range("MP4 track count exceeds u32"))?;
640			if let Some(track) = parse_trak(child.payload, file_size)? {
641				tracks.push(track);
642			}
643		}
644	}
645	let track = tracks
646		.into_iter()
647		.next()
648		.ok_or_else(|| Error::data_loss("MP4 contains no supported video track"))?;
649	let sample_count = u32::try_from(track.samples.len())
650		.map_err(|_| Error::out_of_range("MP4 sample count exceeds u32"))?;
651	let time_base = VideoTimeBase::new(1, track.timescale)?;
652	Ok(ParsedMovie {
653		info: VideoContainerInfo {
654			kind: VideoContainerKind::Mp4,
655			codec: track.codec,
656			width: track.width,
657			height: track.height,
658			time_base,
659			duration: track.duration,
660			sample_count,
661			track_id: track.track_id,
662			track_count,
663			decode_profile: track.decode_profile,
664		},
665		samples: track.samples,
666		nal_length_size: track.nal_length_size,
667		codec_config: track.codec_config,
668	})
669}
670
671fn parse_trak(data: &[u8], file_size: u64) -> Result<Option<ParsedTrack>> {
672	let mut track_id = None;
673	let mut mdia = None;
674	for child in boxes(data)? {
675		match &child.kind {
676			b"tkhd" => track_id = parse_tkhd_track_id(child.payload),
677			b"mdia" => mdia = Some(child.payload),
678			_ => {}
679		}
680	}
681	let Some(mdia) = mdia else {
682		return Ok(None);
683	};
684	let mut handler_is_video = false;
685	let mut timescale_duration = None;
686	let mut minf = None;
687	for child in boxes(mdia)? {
688		match &child.kind {
689			b"hdlr" => handler_is_video = child.payload.get(8..12) == Some(b"vide"),
690			b"mdhd" => timescale_duration = parse_mdhd(child.payload),
691			b"minf" => minf = Some(child.payload),
692			_ => {}
693		}
694	}
695	if !handler_is_video {
696		return Ok(None);
697	}
698	let (timescale, duration) = timescale_duration
699		.ok_or_else(|| Error::data_loss("MP4 video track lacks a valid media header"))?;
700	let stbl = find_descendant(
701		minf.ok_or_else(|| Error::data_loss("MP4 video track lacks media info"))?,
702		b"stbl",
703	)?
704	.ok_or_else(|| Error::data_loss("MP4 video track lacks a sample table"))?;
705	let tables = parse_sample_table(stbl, file_size)?;
706	Ok(Some(ParsedTrack {
707		track_id: track_id.ok_or_else(|| Error::data_loss("MP4 video track lacks a valid track id"))?,
708		codec: tables.codec,
709		width: tables.width,
710		height: tables.height,
711		timescale,
712		duration,
713		samples: tables.samples,
714		nal_length_size: tables.nal_length_size,
715		codec_config: tables.codec_config,
716		decode_profile: tables.decode_profile,
717	}))
718}
719
720fn parse_tkhd_track_id(data: &[u8]) -> Option<u32> {
721	match *data.first()? {
722		0 => read_u32(data, 12).ok().filter(|value| *value != 0),
723		1 => read_u32(data, 20).ok().filter(|value| *value != 0),
724		_ => None,
725	}
726}
727
728fn parse_mdhd(data: &[u8]) -> Option<(u32, u64)> {
729	let (timescale, duration) = match *data.first()? {
730		0 => (
731			read_u32(data, 12).ok()?,
732			u64::from(read_u32(data, 16).ok()?),
733		),
734		1 => (read_u32(data, 20).ok()?, read_u64(data, 24).ok()?),
735		_ => return None,
736	};
737	(timescale != 0).then_some((timescale, duration))
738}
739
740struct SampleTables {
741	codec: VideoCodec,
742	width: u32,
743	height: u32,
744	nal_length_size: Option<usize>,
745	codec_config: Vec<u8>,
746	decode_profile: Option<VideoDecodeProfile>,
747	samples: Vec<Sample>,
748}
749
750fn parse_sample_table(data: &[u8], file_size: u64) -> Result<SampleTables> {
751	let mut description = None;
752	let mut durations = None;
753	let mut composition_offsets = None;
754	let mut chunk_map = None;
755	let mut sizes = None;
756	let mut chunks = None;
757	let mut sync_samples = None;
758	for child in boxes(data)? {
759		match &child.kind {
760			b"stsd" => description = Some(parse_stsd(child.payload)?),
761			b"stts" => durations = Some(parse_stts(child.payload)?),
762			b"ctts" => composition_offsets = Some(parse_ctts(child.payload)?),
763			b"stsc" => chunk_map = Some(parse_stsc(child.payload)?),
764			b"stsz" => sizes = Some(parse_stsz(child.payload)?),
765			b"stco" => chunks = Some(parse_stco(child.payload)?),
766			b"co64" => chunks = Some(parse_co64(child.payload)?),
767			b"stss" => sync_samples = Some(parse_stss(child.payload)?),
768			_ => {}
769		}
770	}
771	let description = description.ok_or_else(|| Error::data_loss("MP4 sample table lacks stsd"))?;
772	let durations = durations.ok_or_else(|| Error::data_loss("MP4 sample table lacks stts"))?;
773	let chunk_map = chunk_map.ok_or_else(|| Error::data_loss("MP4 sample table lacks stsc"))?;
774	let sizes = sizes.ok_or_else(|| Error::data_loss("MP4 sample table lacks stsz"))?;
775	let chunks = chunks.ok_or_else(|| Error::data_loss("MP4 sample table lacks stco/co64"))?;
776	let offsets = if sizes.is_empty() {
777		Vec::new()
778	} else {
779		build_sample_offsets(&sizes, &chunks, &chunk_map, file_size)?
780	};
781	if durations.len() != sizes.len() {
782		return Err(Error::data_loss("MP4 stts count does not match stsz"));
783	}
784	let composition_offsets = composition_offsets.unwrap_or_else(|| vec![0; sizes.len()]);
785	if composition_offsets.len() != sizes.len() {
786		return Err(Error::data_loss("MP4 ctts count does not match stsz"));
787	}
788	let all_sync = sync_samples.is_none();
789	let sync_samples = sync_samples.unwrap_or_default();
790	let mut dts = 0_u64;
791	let mut samples = Vec::new();
792	samples
793		.try_reserve_exact(sizes.len())
794		.map_err(|_| Error::resource_exhausted("MP4 sample index allocation failed"))?;
795	for index in 0..sizes.len() {
796		let pts = checked_signed_add(dts, composition_offsets[index])?;
797		let sample_number =
798			u32::try_from(index + 1).map_err(|_| Error::out_of_range("MP4 sample number exceeds u32"))?;
799		samples.push(Sample {
800			offset: offsets[index],
801			size: sizes[index],
802			dts,
803			pts,
804			duration: durations[index],
805			keyframe: all_sync || sync_samples.contains(&sample_number),
806		});
807		dts = dts
808			.checked_add(u64::from(durations[index]))
809			.ok_or_else(|| Error::data_loss("MP4 decode timestamp overflows u64"))?;
810	}
811	Ok(SampleTables {
812		codec: description.codec,
813		width: description.width,
814		height: description.height,
815		nal_length_size: description.nal_length_size,
816		codec_config: description.codec_config,
817		decode_profile: description.decode_profile,
818		samples,
819	})
820}
821
822struct SampleDescription {
823	codec: VideoCodec,
824	width: u32,
825	height: u32,
826	nal_length_size: Option<usize>,
827	codec_config: Vec<u8>,
828	decode_profile: Option<VideoDecodeProfile>,
829}
830
831fn parse_stsd(data: &[u8]) -> Result<SampleDescription> {
832	let count = usize::try_from(read_u32(data, 4)?)
833		.map_err(|_| Error::out_of_range("MP4 stsd entry count exceeds usize"))?;
834	if count == 0 || count > 64 {
835		return Err(Error::data_loss(
836			"MP4 stsd has no entries or exceeds the safety bound",
837		));
838	}
839	let entries = data
840		.get(8..)
841		.ok_or_else(|| Error::data_loss("truncated MP4 stsd header"))?;
842	for entry in boxes(entries)?.into_iter().take(count) {
843		let codec = match &entry.kind {
844			b"avc1" | b"avc3" => VideoCodec::H264,
845			b"hvc1" | b"hev1" => VideoCodec::H265,
846			b"av01" => VideoCodec::Av1,
847			b"vp09" => VideoCodec::Vp9,
848			_ => continue,
849		};
850		let width = u32::from(read_u16(entry.payload, 24)?);
851		let height = u32::from(read_u16(entry.payload, 26)?);
852		if width == 0 || height == 0 {
853			return Err(Error::data_loss(
854				"MP4 video sample entry has zero dimensions",
855			));
856		}
857		let children = entry
858			.payload
859			.get(78..)
860			.ok_or_else(|| Error::data_loss("truncated MP4 visual sample entry"))?;
861		let mut nal_length_size = None;
862		let mut codec_config = Vec::new();
863		let mut decode_profile = None;
864		for child in boxes(children)? {
865			match (&codec, &child.kind) {
866				(VideoCodec::H264, b"avcC") => {
867					let parsed = parse_avcc(child.payload)?;
868					nal_length_size = Some(parsed.0);
869					codec_config = parsed.1;
870					decode_profile = parsed.2;
871				}
872				(VideoCodec::H265, b"hvcC") => {
873					let parsed = parse_hvcc(child.payload)?;
874					nal_length_size = Some(parsed.0);
875					codec_config = parsed.1;
876					decode_profile = parsed.2;
877				}
878				(VideoCodec::Av1, b"av1C") => {
879					decode_profile = parse_av1c_profile(child.payload)?;
880					codec_config = child.payload.get(4..).unwrap_or_default().to_vec();
881				}
882				(VideoCodec::Vp9, b"vpcC") => {
883					decode_profile = parse_vpcc_profile(child.payload)?;
884				}
885				_ => {}
886			}
887		}
888		if matches!(codec, VideoCodec::H264 | VideoCodec::H265) && nal_length_size.is_none() {
889			return Err(Error::data_loss(
890				"MP4 AVC/HEVC sample entry lacks codec configuration",
891			));
892		}
893		return Ok(SampleDescription {
894			codec,
895			width,
896			height,
897			nal_length_size,
898			codec_config,
899			decode_profile,
900		});
901	}
902	Err(Error::data_loss(
903		"MP4 stsd contains no supported video sample entry",
904	))
905}
906
907fn parse_avcc(data: &[u8]) -> Result<(usize, Vec<u8>, Option<VideoDecodeProfile>)> {
908	let length_size = usize::from(
909		*data
910			.get(4)
911			.ok_or_else(|| Error::data_loss("truncated avcC"))?
912			& 3,
913	) + 1;
914	if !matches!(length_size, 1 | 2 | 4) {
915		return Err(Error::data_loss(
916			"avcC declares an unsupported NAL length width",
917		));
918	}
919	let sps_count = usize::from(
920		*data
921			.get(5)
922			.ok_or_else(|| Error::data_loss("truncated avcC"))?
923			& 0x1f,
924	);
925	let mut cursor = 6_usize;
926	let mut config = Vec::new();
927	for _ in 0..sps_count {
928		append_config_nal(data, &mut cursor, &mut config)?;
929	}
930	let pps_count = usize::from(
931		*data
932			.get(cursor)
933			.ok_or_else(|| Error::data_loss("truncated avcC PPS count"))?,
934	);
935	cursor += 1;
936	for _ in 0..pps_count {
937		append_config_nal(data, &mut cursor, &mut config)?;
938	}
939	let decode_profile = h264_profile_from_config(&config)?;
940	Ok((length_size, config, decode_profile))
941}
942
943fn parse_hvcc(data: &[u8]) -> Result<(usize, Vec<u8>, Option<VideoDecodeProfile>)> {
944	let length_size = usize::from(
945		*data
946			.get(21)
947			.ok_or_else(|| Error::data_loss("truncated hvcC"))?
948			& 3,
949	) + 1;
950	if !matches!(length_size, 1 | 2 | 4) {
951		return Err(Error::data_loss(
952			"hvcC declares an unsupported NAL length width",
953		));
954	}
955	let arrays = usize::from(
956		*data
957			.get(22)
958			.ok_or_else(|| Error::data_loss("truncated hvcC"))?,
959	);
960	let mut cursor = 23_usize;
961	let mut config = Vec::new();
962	for _ in 0..arrays {
963		cursor = cursor
964			.checked_add(1)
965			.ok_or_else(|| Error::data_loss("hvcC array offset overflows usize"))?;
966		let nal_count = usize::from(read_u16(data, cursor)?);
967		cursor += 2;
968		for _ in 0..nal_count {
969			append_config_nal(data, &mut cursor, &mut config)?;
970		}
971	}
972	let decode_profile = h265_profile_from_hvcc(data)?;
973	Ok((length_size, config, decode_profile))
974}
975
976fn h265_profile_from_hvcc(data: &[u8]) -> Result<Option<VideoDecodeProfile>> {
977	let profile = match data
978		.get(1)
979		.ok_or_else(|| Error::data_loss("truncated hvcC profile"))?
980		& 0x1f
981	{
982		1 => H265Profile::Main,
983		2 => H265Profile::Main10,
984		3 => H265Profile::MainStillPicture,
985		4 => H265Profile::FormatRangeExtensions,
986		9 => H265Profile::ScreenContentCodingExtensions,
987		_ => return Ok(None),
988	};
989	let chroma = parse_chroma(u32::from(
990		*data
991			.get(16)
992			.ok_or_else(|| Error::data_loss("truncated hvcC chroma format"))?
993			& 3,
994	))?;
995	let luma = parse_bit_depth(
996		u32::from(
997			*data
998				.get(17)
999				.ok_or_else(|| Error::data_loss("truncated hvcC luma depth"))?
1000				& 7,
1001		) + 8,
1002	)?;
1003	let chroma_depth = parse_bit_depth(
1004		u32::from(
1005			*data
1006				.get(18)
1007				.ok_or_else(|| Error::data_loss("truncated hvcC chroma depth"))?
1008				& 7,
1009		) + 8,
1010	)?;
1011	Ok(Some(VideoDecodeProfile::H265 {
1012		profile,
1013		chroma_subsampling: chroma,
1014		luma_bit_depth: luma,
1015		chroma_bit_depth: chroma_depth,
1016	}))
1017}
1018
1019fn parse_av1c_profile(data: &[u8]) -> Result<Option<VideoDecodeProfile>> {
1020	let profile_byte = *data
1021		.get(1)
1022		.ok_or_else(|| Error::data_loss("truncated av1C profile"))?;
1023	let format_byte = *data
1024		.get(2)
1025		.ok_or_else(|| Error::data_loss("truncated av1C format"))?;
1026	let profile = match profile_byte >> 5 {
1027		0 => Av1Profile::Main,
1028		1 => Av1Profile::High,
1029		2 => Av1Profile::Professional,
1030		_ => return Ok(None),
1031	};
1032	let monochrome = format_byte & 0x10 != 0;
1033	let chroma = if monochrome {
1034		VideoChromaSubsampling::Monochrome
1035	} else {
1036		match ((format_byte >> 3) & 1, (format_byte >> 2) & 1) {
1037			(1, 1) => VideoChromaSubsampling::Yuv420,
1038			(1, 0) => VideoChromaSubsampling::Yuv422,
1039			(0, 0) => VideoChromaSubsampling::Yuv444,
1040			_ => return Ok(None),
1041		}
1042	};
1043	let depth = if format_byte & 0x40 == 0 {
1044		VideoComponentBitDepth::Eight
1045	} else if format_byte & 0x20 == 0 {
1046		VideoComponentBitDepth::Ten
1047	} else {
1048		VideoComponentBitDepth::Twelve
1049	};
1050	Ok(Some(VideoDecodeProfile::Av1 {
1051		profile,
1052		film_grain_support: false,
1053		chroma_subsampling: chroma,
1054		luma_bit_depth: depth,
1055		chroma_bit_depth: depth,
1056	}))
1057}
1058
1059fn parse_vpcc_profile(data: &[u8]) -> Result<Option<VideoDecodeProfile>> {
1060	// `vpcC` is a FullBox. Its four-byte version/flags prefix is followed by
1061	// profile, level, and packed bit-depth/chroma/range metadata.
1062	let profile = match *data
1063		.get(4)
1064		.ok_or_else(|| Error::data_loss("truncated vpcC profile"))?
1065	{
1066		0 => Vp9Profile::Profile0,
1067		1 => Vp9Profile::Profile1,
1068		2 => Vp9Profile::Profile2,
1069		3 => Vp9Profile::Profile3,
1070		_ => return Ok(None),
1071	};
1072	let format = *data
1073		.get(6)
1074		.ok_or_else(|| Error::data_loss("truncated vpcC format"))?;
1075	let depth = parse_bit_depth(u32::from(format >> 4))?;
1076	let chroma = match format & 7 {
1077		3 => VideoChromaSubsampling::Yuv422,
1078		4 => VideoChromaSubsampling::Yuv444,
1079		_ => VideoChromaSubsampling::Yuv420,
1080	};
1081	Ok(Some(VideoDecodeProfile::Vp9 {
1082		profile,
1083		chroma_subsampling: chroma,
1084		luma_bit_depth: depth,
1085		chroma_bit_depth: depth,
1086	}))
1087}
1088
1089fn h264_profile_from_config(config: &[u8]) -> Result<Option<VideoDecodeProfile>> {
1090	let Some(sps) = super::parse_nal_annex_b(config).into_iter().find(|nal| {
1091		nal
1092			.payload()
1093			.first()
1094			.is_some_and(|header| header & 0x1f == 7)
1095	}) else {
1096		return Ok(None);
1097	};
1098	h264_profile_from_sps(sps.payload())
1099}
1100
1101fn h264_profile_from_sps(nal: &[u8]) -> Result<Option<VideoDecodeProfile>> {
1102	let sps = super::parse_h264_sps(nal)?;
1103	let profile = match sps.profile_idc {
1104		66 => H264Profile::Baseline,
1105		77 => H264Profile::Main,
1106		100 => H264Profile::High,
1107		110 => H264Profile::High10,
1108		244 => H264Profile::High444Predictive,
1109		_ => return Ok(None),
1110	};
1111	Ok(Some(VideoDecodeProfile::H264 {
1112		profile,
1113		picture_layout: if sps.frame_mbs_only {
1114			H264PictureLayout::Progressive
1115		} else {
1116			H264PictureLayout::InterlacedInterleavedLines
1117		},
1118		chroma_subsampling: parse_chroma(sps.chroma_format_idc)?,
1119		luma_bit_depth: parse_bit_depth(sps.bit_depth_luma_minus_8 + 8)?,
1120		chroma_bit_depth: parse_bit_depth(sps.bit_depth_chroma_minus_8 + 8)?,
1121	}))
1122}
1123
1124fn parse_chroma(value: u32) -> Result<VideoChromaSubsampling> {
1125	match value {
1126		0 => Ok(VideoChromaSubsampling::Monochrome),
1127		1 => Ok(VideoChromaSubsampling::Yuv420),
1128		2 => Ok(VideoChromaSubsampling::Yuv422),
1129		3 => Ok(VideoChromaSubsampling::Yuv444),
1130		_ => Err(Error::data_loss(
1131			"codec configuration has invalid chroma format",
1132		)),
1133	}
1134}
1135
1136fn parse_bit_depth(value: u32) -> Result<VideoComponentBitDepth> {
1137	match value {
1138		8 => Ok(VideoComponentBitDepth::Eight),
1139		10 => Ok(VideoComponentBitDepth::Ten),
1140		12 => Ok(VideoComponentBitDepth::Twelve),
1141		_ => Err(Error::data_loss(
1142			"codec configuration has unsupported bit depth",
1143		)),
1144	}
1145}
1146
1147fn append_config_nal(data: &[u8], cursor: &mut usize, output: &mut Vec<u8>) -> Result<()> {
1148	let length = usize::from(read_u16(data, *cursor)?);
1149	*cursor = cursor
1150		.checked_add(2)
1151		.ok_or_else(|| Error::data_loss("codec-config NAL offset overflows usize"))?;
1152	if length == 0 {
1153		return Err(Error::data_loss(
1154			"codec configuration contains an empty NAL unit",
1155		));
1156	}
1157	let end = cursor
1158		.checked_add(length)
1159		.ok_or_else(|| Error::data_loss("codec-config NAL end overflows usize"))?;
1160	let payload = data
1161		.get(*cursor..end)
1162		.ok_or_else(|| Error::data_loss("codec-config NAL exceeds its box"))?;
1163	output
1164		.try_reserve(4 + length)
1165		.map_err(|_| Error::resource_exhausted("codec-config allocation failed"))?;
1166	output.extend_from_slice(&[0, 0, 0, 1]);
1167	output.extend_from_slice(payload);
1168	*cursor = end;
1169	Ok(())
1170}
1171
1172fn parse_stts(data: &[u8]) -> Result<Vec<u32>> {
1173	let entries = table_count(data, 8, "stts")?;
1174	let mut values = Vec::new();
1175	for index in 0..entries {
1176		let offset = 8 + index * 8;
1177		let count = usize::try_from(read_u32(data, offset)?)
1178			.map_err(|_| Error::out_of_range("stts sample count exceeds usize"))?;
1179		let delta = read_u32(data, offset + 4)?;
1180		if delta == 0
1181			|| values
1182				.len()
1183				.checked_add(count)
1184				.is_none_or(|len| len > MAX_MP4_TABLE_ENTRIES)
1185		{
1186			return Err(Error::data_loss(
1187				"MP4 stts expansion is invalid or exceeds the safety bound",
1188			));
1189		}
1190		values
1191			.try_reserve(count)
1192			.map_err(|_| Error::resource_exhausted("MP4 stts allocation failed"))?;
1193		values.extend(std::iter::repeat_n(delta, count));
1194	}
1195	Ok(values)
1196}
1197
1198fn parse_ctts(data: &[u8]) -> Result<Vec<i64>> {
1199	let version = *data
1200		.first()
1201		.ok_or_else(|| Error::data_loss("truncated ctts"))?;
1202	if version > 1 {
1203		return Err(Error::data_loss("unsupported MP4 ctts version"));
1204	}
1205	let entries = table_count(data, 8, "ctts")?;
1206	let mut values = Vec::new();
1207	for index in 0..entries {
1208		let offset = 8 + index * 8;
1209		let count = usize::try_from(read_u32(data, offset)?)
1210			.map_err(|_| Error::out_of_range("ctts sample count exceeds usize"))?;
1211		let raw = read_u32(data, offset + 4)?;
1212		let value = if version == 1 {
1213			i64::from(i32::from_be_bytes(raw.to_be_bytes()))
1214		} else {
1215			i64::from(raw)
1216		};
1217		if values
1218			.len()
1219			.checked_add(count)
1220			.is_none_or(|len| len > MAX_MP4_TABLE_ENTRIES)
1221		{
1222			return Err(Error::data_loss(
1223				"MP4 ctts expansion exceeds the safety bound",
1224			));
1225		}
1226		values
1227			.try_reserve(count)
1228			.map_err(|_| Error::resource_exhausted("MP4 ctts allocation failed"))?;
1229		values.extend(std::iter::repeat_n(value, count));
1230	}
1231	Ok(values)
1232}
1233
1234#[derive(Clone, Copy)]
1235struct SampleToChunk {
1236	first_chunk: u32,
1237	samples_per_chunk: u32,
1238}
1239
1240fn parse_stsc(data: &[u8]) -> Result<Vec<SampleToChunk>> {
1241	let entries = table_count(data, 12, "stsc")?;
1242	let mut values = Vec::new();
1243	values
1244		.try_reserve_exact(entries)
1245		.map_err(|_| Error::resource_exhausted("MP4 stsc allocation failed"))?;
1246	for index in 0..entries {
1247		let offset = 8 + index * 12;
1248		let first_chunk = read_u32(data, offset)?;
1249		let samples_per_chunk = read_u32(data, offset + 4)?;
1250		if first_chunk == 0 || samples_per_chunk == 0 || (index == 0 && first_chunk != 1) {
1251			return Err(Error::data_loss("MP4 stsc contains invalid chunk mapping"));
1252		}
1253		if values
1254			.last()
1255			.is_some_and(|previous: &SampleToChunk| previous.first_chunk >= first_chunk)
1256		{
1257			return Err(Error::data_loss(
1258				"MP4 stsc first_chunk values are not increasing",
1259			));
1260		}
1261		values.push(SampleToChunk {
1262			first_chunk,
1263			samples_per_chunk,
1264		});
1265	}
1266	Ok(values)
1267}
1268
1269fn parse_stsz(data: &[u8]) -> Result<Vec<u32>> {
1270	let constant = read_u32(data, 4)?;
1271	let count = bounded_count(read_u32(data, 8)?, "stsz")?;
1272	if constant != 0 {
1273		return Ok(vec![constant; count]);
1274	}
1275	ensure_table(data, 12, count, 4, "stsz")?;
1276	(0..count)
1277		.map(|index| read_u32(data, 12 + index * 4))
1278		.collect()
1279}
1280
1281fn parse_stco(data: &[u8]) -> Result<Vec<u64>> {
1282	let count = table_count(data, 4, "stco")?;
1283	(0..count)
1284		.map(|index| read_u32(data, 8 + index * 4).map(u64::from))
1285		.collect()
1286}
1287
1288fn parse_co64(data: &[u8]) -> Result<Vec<u64>> {
1289	let count = table_count(data, 8, "co64")?;
1290	(0..count)
1291		.map(|index| read_u64(data, 8 + index * 8))
1292		.collect()
1293}
1294
1295fn parse_stss(data: &[u8]) -> Result<BTreeSet<u32>> {
1296	let count = table_count(data, 4, "stss")?;
1297	let mut values = BTreeSet::new();
1298	for index in 0..count {
1299		let sample = read_u32(data, 8 + index * 4)?;
1300		if sample == 0 {
1301			return Err(Error::data_loss("MP4 stss contains sample zero"));
1302		}
1303		values.insert(sample);
1304	}
1305	Ok(values)
1306}
1307
1308fn build_sample_offsets(
1309	sizes: &[u32],
1310	chunks: &[u64],
1311	map: &[SampleToChunk],
1312	file_size: u64,
1313) -> Result<Vec<u64>> {
1314	if sizes.is_empty() || chunks.is_empty() || map.is_empty() {
1315		return Err(Error::data_loss("MP4 sample/chunk tables are empty"));
1316	}
1317	let mut offsets = Vec::new();
1318	offsets
1319		.try_reserve_exact(sizes.len())
1320		.map_err(|_| Error::resource_exhausted("MP4 sample-offset allocation failed"))?;
1321	let mut sample_index = 0_usize;
1322	let mut map_index = 0_usize;
1323	for (chunk_index, chunk_offset) in chunks.iter().copied().enumerate() {
1324		let chunk_number = u32::try_from(chunk_index + 1)
1325			.map_err(|_| Error::out_of_range("MP4 chunk number exceeds u32"))?;
1326		while map_index + 1 < map.len() && map[map_index + 1].first_chunk <= chunk_number {
1327			map_index += 1;
1328		}
1329		let mut offset = chunk_offset;
1330		for _ in 0..map[map_index].samples_per_chunk {
1331			let size = *sizes
1332				.get(sample_index)
1333				.ok_or_else(|| Error::data_loss("MP4 chunks reference too many samples"))?;
1334			let end = offset
1335				.checked_add(u64::from(size))
1336				.ok_or_else(|| Error::data_loss("MP4 sample end overflows u64"))?;
1337			if size == 0 || end > file_size {
1338				return Err(Error::data_loss("MP4 sample is empty or exceeds the file"));
1339			}
1340			offsets.push(offset);
1341			offset = end;
1342			sample_index += 1;
1343		}
1344	}
1345	if sample_index != sizes.len() {
1346		return Err(Error::data_loss("MP4 chunks do not cover every sample"));
1347	}
1348	Ok(offsets)
1349}
1350
1351struct SliceBox<'a> {
1352	kind: [u8; 4],
1353	payload: &'a [u8],
1354}
1355
1356fn boxes(mut data: &[u8]) -> Result<Vec<SliceBox<'_>>> {
1357	let mut output = Vec::new();
1358	while !data.is_empty() {
1359		if data.len() < 8 {
1360			return Err(Error::data_loss("truncated MP4 child-box header"));
1361		}
1362		let size32 = read_u32(data, 0)?;
1363		let kind = data[4..8]
1364			.try_into()
1365			.map_err(|_| Error::internal("fixed MP4 child-box type conversion failed"))?;
1366		let (size, header) = if size32 == 1 {
1367			(
1368				usize::try_from(read_u64(data, 8)?)
1369					.map_err(|_| Error::out_of_range("MP4 child box exceeds usize"))?,
1370				16,
1371			)
1372		} else if size32 == 0 {
1373			(data.len(), 8)
1374		} else {
1375			(
1376				usize::try_from(size32).map_err(|_| Error::out_of_range("MP4 child box exceeds usize"))?,
1377				8,
1378			)
1379		};
1380		if size < header || size > data.len() {
1381			return Err(Error::data_loss("MP4 child box exceeds its parent"));
1382		}
1383		output.push(SliceBox {
1384			kind,
1385			payload: &data[header..size],
1386		});
1387		data = &data[size..];
1388	}
1389	Ok(output)
1390}
1391
1392fn find_descendant<'a>(data: &'a [u8], kind: &[u8; 4]) -> Result<Option<&'a [u8]>> {
1393	Ok(
1394		boxes(data)?
1395			.into_iter()
1396			.find(|child| &child.kind == kind)
1397			.map(|child| child.payload),
1398	)
1399}
1400
1401fn table_count(data: &[u8], stride: usize, name: &'static str) -> Result<usize> {
1402	let count = bounded_count(read_u32(data, 4)?, name)?;
1403	ensure_table(data, 8, count, stride, name)?;
1404	Ok(count)
1405}
1406
1407fn bounded_count(count: u32, name: &'static str) -> Result<usize> {
1408	let count = usize::try_from(count)
1409		.map_err(|_| Error::out_of_range(format!("MP4 {name} count exceeds usize")))?;
1410	if count > MAX_MP4_TABLE_ENTRIES {
1411		return Err(Error::resource_exhausted(format!(
1412			"MP4 {name} count exceeds the safety bound"
1413		)));
1414	}
1415	Ok(count)
1416}
1417
1418fn ensure_table(
1419	data: &[u8],
1420	header: usize,
1421	count: usize,
1422	stride: usize,
1423	name: &'static str,
1424) -> Result<()> {
1425	let bytes = count
1426		.checked_mul(stride)
1427		.and_then(|value| header.checked_add(value))
1428		.ok_or_else(|| Error::data_loss(format!("MP4 {name} table size overflows usize")))?;
1429	if bytes > data.len() {
1430		return Err(Error::data_loss(format!("truncated MP4 {name} table")));
1431	}
1432	Ok(())
1433}
1434
1435fn read_u16(data: &[u8], offset: usize) -> Result<u16> {
1436	let bytes = data
1437		.get(offset..offset.saturating_add(2))
1438		.ok_or_else(|| Error::data_loss("truncated MP4 u16 field"))?;
1439	Ok(u16::from_be_bytes(bytes.try_into().map_err(|_| {
1440		Error::internal("fixed MP4 u16 conversion failed")
1441	})?))
1442}
1443
1444fn read_u32(data: &[u8], offset: usize) -> Result<u32> {
1445	let bytes = data
1446		.get(offset..offset.saturating_add(4))
1447		.ok_or_else(|| Error::data_loss("truncated MP4 u32 field"))?;
1448	Ok(u32::from_be_bytes(bytes.try_into().map_err(|_| {
1449		Error::internal("fixed MP4 u32 conversion failed")
1450	})?))
1451}
1452
1453fn read_u64(data: &[u8], offset: usize) -> Result<u64> {
1454	let bytes = data
1455		.get(offset..offset.saturating_add(8))
1456		.ok_or_else(|| Error::data_loss("truncated MP4 u64 field"))?;
1457	Ok(u64::from_be_bytes(bytes.try_into().map_err(|_| {
1458		Error::internal("fixed MP4 u64 conversion failed")
1459	})?))
1460}
1461
1462fn checked_signed_add(value: u64, offset: i64) -> Result<u64> {
1463	if offset >= 0 {
1464		value
1465			.checked_add(
1466				u64::try_from(offset).map_err(|_| Error::data_loss("positive ctts conversion failed"))?,
1467			)
1468			.ok_or_else(|| Error::data_loss("video presentation timestamp overflows u64"))
1469	} else {
1470		value
1471			.checked_sub(offset.unsigned_abs())
1472			.ok_or_else(|| Error::data_loss("video presentation timestamp is negative"))
1473	}
1474}