Skip to main content

oa/video/
mux.rs

1//! Streaming ISO-BMFF/MP4 video muxing.
2
3pub use crate::video::types::{VideoMuxerAudioConfig, VideoMuxerConfig};
4use std::{
5	fs::File,
6	io::{Seek, SeekFrom, Write},
7	path::Path,
8};
9
10use crate::{Error, Result, audio::EncodedAudioPacket};
11
12use super::{VideoCodec, VideoTimeBase};
13
14const STREAM_HEADER_BYTES: u64 = 32;
15
16impl Default for VideoMuxerAudioConfig {
17	fn default() -> Self {
18		Self {
19			sample_rate: 48_000,
20			channel_count: 2,
21			priming_frames: 0,
22		}
23	}
24}
25
26impl VideoMuxerConfig {
27	/// Construct the default 30-fps, 90-kHz video-only profile.
28	///
29	/// # Errors
30	///
31	/// Returns an error when the coded extent is zero.
32	pub fn new(codec: VideoCodec, width: u32, height: u32) -> Result<Self> {
33		if width == 0 || height == 0 {
34			return Err(Error::invalid_argument(
35				"video muxer coded extent must be non-zero",
36			));
37		}
38		Ok(Self {
39			codec,
40			width,
41			height,
42			frame_rate: 30,
43			time_base: VideoTimeBase::new(1, 90_000)?,
44			audio: None,
45		})
46	}
47}
48
49/// One owned Annex-B video access unit with microsecond presentation timing.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct EncodedVideoPacket {
52	bitstream: Vec<u8>,
53	presentation_timestamp_micros: u64,
54	decode_timestamp_micros: u64,
55	keyframe: bool,
56}
57
58impl EncodedVideoPacket {
59	/// Construct a non-empty encoded access unit.
60	///
61	/// # Errors
62	///
63	/// Returns an error when `bitstream` is empty. The muxer validates Annex-B
64	/// framing when the packet is written.
65	pub fn new(
66		bitstream: Vec<u8>,
67		presentation_timestamp_micros: u64,
68		keyframe: bool,
69	) -> Result<Self> {
70		if bitstream.is_empty() {
71			return Err(Error::invalid_argument(
72				"encoded video packet bitstream is empty",
73			));
74		}
75		Ok(Self {
76			bitstream,
77			presentation_timestamp_micros,
78			decode_timestamp_micros: presentation_timestamp_micros,
79			keyframe,
80		})
81	}
82
83	/// Construct an access unit with distinct presentation and decode timing.
84	///
85	/// Packets are written in decode order. Presentation timestamps may reorder;
86	/// decode timestamps must increase when packets enter a muxer.
87	///
88	/// # Errors
89	///
90	/// Returns an error when `bitstream` is empty.
91	pub fn new_with_timestamps(
92		bitstream: Vec<u8>,
93		presentation_timestamp_micros: u64,
94		decode_timestamp_micros: u64,
95		keyframe: bool,
96	) -> Result<Self> {
97		let mut packet = Self::new(bitstream, presentation_timestamp_micros, keyframe)?;
98		packet.decode_timestamp_micros = decode_timestamp_micros;
99		Ok(packet)
100	}
101
102	/// Borrow the encoded Annex-B access unit.
103	pub fn bitstream(&self) -> &[u8] {
104		&self.bitstream
105	}
106
107	/// Return the presentation timestamp in microseconds.
108	pub const fn presentation_timestamp_micros(&self) -> u64 {
109		self.presentation_timestamp_micros
110	}
111
112	/// Return the decode timestamp in microseconds.
113	pub const fn decode_timestamp_micros(&self) -> u64 {
114		self.decode_timestamp_micros
115	}
116
117	/// Return whether this packet is a random-access point.
118	pub const fn is_keyframe(&self) -> bool {
119		self.keyframe
120	}
121
122	/// Consume the packet and return its encoded bytes.
123	pub fn into_bitstream(self) -> Vec<u8> {
124		self.bitstream
125	}
126}
127
128/// Stateful streaming MP4 muxer for H.264/H.265 and optional PCM-S16 audio.
129///
130/// Media payload is written as packets arrive. [`finalize`](Self::finalize)
131/// appends the movie sample tables and closes the file. [`close`](Self::close)
132/// deliberately abandons an unfinished file. Drop only releases the open file
133/// handle; it never manufactures a movie trailer or reports success.
134pub struct VideoMuxer {
135	file: Option<File>,
136	config: VideoMuxerConfig,
137	mdat_payload_bytes: u64,
138	video_offsets: Vec<u64>,
139	video_sizes: Vec<u32>,
140	video_presentation_timestamps_micros: Vec<u64>,
141	video_decode_timestamps_micros: Vec<u64>,
142	video_keyframes: Vec<bool>,
143	audio_offsets: Vec<u64>,
144	audio_durations: Vec<u32>,
145	vps: Vec<u8>,
146	sps: Vec<u8>,
147	pps: Vec<u8>,
148	finalized: bool,
149}
150
151impl VideoMuxer {
152	/// Create a new streaming MP4 file and write its fixed header.
153	///
154	/// # Errors
155	///
156	/// Returns an error for an empty path, invalid or unsupported configuration,
157	/// an unrepresentable MP4 field, or a file create/write failure.
158	pub fn new(path: impl AsRef<Path>, config: VideoMuxerConfig) -> Result<Self> {
159		let path = path.as_ref();
160		validate_config(path, config)?;
161		let mut file = File::create(path).map_err(|source| Error::io("MP4 output create", source))?;
162		file
163			.write_all(&stream_header())
164			.map_err(|source| Error::io("MP4 stream header write", source))?;
165		Ok(Self {
166			file: Some(file),
167			config,
168			mdat_payload_bytes: 0,
169			video_offsets: Vec::new(),
170			video_sizes: Vec::new(),
171			video_presentation_timestamps_micros: Vec::new(),
172			video_decode_timestamps_micros: Vec::new(),
173			video_keyframes: Vec::new(),
174			audio_offsets: Vec::new(),
175			audio_durations: Vec::new(),
176			vps: Vec::new(),
177			sps: Vec::new(),
178			pps: Vec::new(),
179			finalized: false,
180		})
181	}
182
183	/// Install one AVC SPS/PPS pair, without Annex-B start codes.
184	///
185	/// # Errors
186	///
187	/// Returns an error for the wrong muxer codec, empty/oversized records, or
188	/// records whose NAL unit types are not SPS and PPS.
189	pub fn set_h264_codec_config(&mut self, sps: &[u8], pps: &[u8]) -> Result<()> {
190		self.require_open()?;
191		if self.config.codec != VideoCodec::H264 {
192			return Err(Error::failed_precondition(
193				"H.264 codec configuration requires an H.264 muxer",
194			));
195		}
196		validate_nal_record(sps, 7, false, "H.264 SPS")?;
197		validate_nal_record(pps, 8, false, "H.264 PPS")?;
198		self.sps = copy_bytes(sps, "H.264 SPS")?;
199		self.pps = copy_bytes(pps, "H.264 PPS")?;
200		self.vps.clear();
201		Ok(())
202	}
203
204	/// Install one HEVC VPS/SPS/PPS set, without Annex-B start codes.
205	///
206	/// # Errors
207	///
208	/// Returns an error for the wrong muxer codec, empty/oversized records, or
209	/// records whose NAL unit types are not VPS, SPS, and PPS.
210	pub fn set_h265_codec_config(&mut self, vps: &[u8], sps: &[u8], pps: &[u8]) -> Result<()> {
211		self.require_open()?;
212		if self.config.codec != VideoCodec::H265 {
213			return Err(Error::failed_precondition(
214				"H.265 codec configuration requires an H.265 muxer",
215			));
216		}
217		validate_nal_record(vps, 32, true, "H.265 VPS")?;
218		validate_nal_record(sps, 33, true, "H.265 SPS")?;
219		validate_nal_record(pps, 34, true, "H.265 PPS")?;
220		self.vps = copy_bytes(vps, "H.265 VPS")?;
221		self.sps = copy_bytes(sps, "H.265 SPS")?;
222		self.pps = copy_bytes(pps, "H.265 PPS")?;
223		Ok(())
224	}
225
226	/// Stream one encoded video access unit into the MP4 media-data box.
227	///
228	/// # Errors
229	///
230	/// Returns an error after close/finalize, for malformed Annex-B input,
231	/// non-increasing timestamps, metadata overflow/allocation failure, or I/O
232	/// failure. An I/O failure closes and poisons this session.
233	pub fn write_packet(&mut self, packet: &EncodedVideoPacket) -> Result<()> {
234		self.require_open()?;
235		if self
236			.video_decode_timestamps_micros
237			.last()
238			.is_some_and(|last| packet.decode_timestamp_micros <= *last)
239		{
240			return Err(Error::invalid_argument(
241				"video packet decode timestamps must be strictly increasing",
242			));
243		}
244		let sample = validate_annex_b_sample(&packet.bitstream)?;
245		let sample_size = sample.size;
246		let offset = STREAM_HEADER_BYTES
247			.checked_add(self.mdat_payload_bytes)
248			.ok_or_else(|| Error::out_of_range("MP4 video sample offset exceeds u64"))?;
249		let next_payload = self
250			.mdat_payload_bytes
251			.checked_add(u64::from(sample_size))
252			.ok_or_else(|| Error::out_of_range("MP4 media-data size exceeds u64"))?;
253		reserve_one(&mut self.video_offsets, "MP4 video offset table")?;
254		reserve_one(&mut self.video_sizes, "MP4 video size table")?;
255		reserve_one(
256			&mut self.video_presentation_timestamps_micros,
257			"MP4 video presentation timestamp table",
258		)?;
259		reserve_one(
260			&mut self.video_decode_timestamps_micros,
261			"MP4 video decode timestamp table",
262		)?;
263		reserve_one(&mut self.video_keyframes, "MP4 video keyframe table")?;
264		let write_result =
265			write_length_prefixed_sample(self.file.as_mut().ok_or_else(closed_error)?, &sample.units);
266		if let Err(source) = write_result {
267			self.file = None;
268			return Err(Error::io("MP4 video sample write", source));
269		}
270		self.video_offsets.push(offset);
271		self.video_sizes.push(sample_size);
272		self
273			.video_presentation_timestamps_micros
274			.push(packet.presentation_timestamp_micros);
275		self
276			.video_decode_timestamps_micros
277			.push(packet.decode_timestamp_micros);
278		self.video_keyframes.push(packet.keyframe);
279		self.mdat_payload_bytes = next_payload;
280		Ok(())
281	}
282
283	/// Stream one native PCM-S16 audio packet into the optional audio track.
284	///
285	/// # Errors
286	///
287	/// Returns an error after close/finalize, when no audio track was configured,
288	/// for an inconsistent packet duration/byte count, overflow/allocation
289	/// failure, or I/O failure. An I/O failure closes and poisons this session.
290	pub fn write_audio_packet(&mut self, packet: &EncodedAudioPacket) -> Result<()> {
291		self.require_open()?;
292		let audio = self.config.audio.ok_or_else(|| {
293			Error::failed_precondition("video muxer was not created with an audio track")
294		})?;
295		if packet.duration_frames == 0 {
296			return Err(Error::invalid_argument(
297				"audio packet duration must be non-zero",
298			));
299		}
300		let expected = u64::from(packet.duration_frames)
301			.checked_mul(u64::from(audio.channel_count))
302			.and_then(|frames| frames.checked_mul(2))
303			.ok_or_else(|| Error::out_of_range("PCM-S16 packet byte count exceeds u64"))?;
304		if u64::try_from(packet.bitstream.len()).ok() != Some(expected) {
305			return Err(Error::invalid_argument(
306				"PCM-S16 packet byte count does not match duration and channel count",
307			));
308		}
309		let offset = STREAM_HEADER_BYTES
310			.checked_add(self.mdat_payload_bytes)
311			.ok_or_else(|| Error::out_of_range("MP4 audio sample offset exceeds u64"))?;
312		let next_payload = self
313			.mdat_payload_bytes
314			.checked_add(expected)
315			.ok_or_else(|| Error::out_of_range("MP4 media-data size exceeds u64"))?;
316		reserve_one(&mut self.audio_offsets, "MP4 audio offset table")?;
317		reserve_one(&mut self.audio_durations, "MP4 audio duration table")?;
318		if let Err(source) = self
319			.file
320			.as_mut()
321			.ok_or_else(closed_error)?
322			.write_all(&packet.bitstream)
323		{
324			self.file = None;
325			return Err(Error::io("MP4 audio packet write", source));
326		}
327		self.audio_offsets.push(offset);
328		self.audio_durations.push(packet.duration_frames);
329		self.mdat_payload_bytes = next_payload;
330		Ok(())
331	}
332
333	/// Finalize sample tables, append the movie box, flush, and close the file.
334	///
335	/// # Errors
336	///
337	/// Returns an error after close/finalize, for an empty stream, absent codec
338	/// configuration, an unrepresentable sample table, allocation failure, or
339	/// seek/write/flush failure. A finalization I/O failure closes the session.
340	pub fn finalize(&mut self) -> Result<()> {
341		self.require_open()?;
342		if self.video_sizes.is_empty() {
343			return Err(Error::failed_precondition("cannot finalize an empty video"));
344		}
345		if self.sps.is_empty()
346			|| self.pps.is_empty()
347			|| (self.config.codec == VideoCodec::H265 && self.vps.is_empty())
348		{
349			return Err(Error::failed_precondition(match self.config.codec {
350				VideoCodec::H264 => "H.264 MP4 requires SPS and PPS codec configuration",
351				VideoCodec::H265 => "H.265 MP4 requires VPS, SPS and PPS codec configuration",
352				_ => "MP4 muxer codec is unsupported",
353			}));
354		}
355		let moov = self.build_moov()?;
356		let mdat_size = self
357			.mdat_payload_bytes
358			.checked_add(16)
359			.ok_or_else(|| Error::out_of_range("MP4 mdat size exceeds u64"))?;
360		let mut file = self.file.take().ok_or_else(closed_error)?;
361		let io_result = (|| -> std::io::Result<()> {
362			file.seek(SeekFrom::Start(24))?;
363			file.write_all(&mdat_size.to_be_bytes())?;
364			file.seek(SeekFrom::End(0))?;
365			file.write_all(&moov)?;
366			file.flush()
367		})();
368		if let Err(source) = io_result {
369			return Err(Error::io("MP4 finalization", source));
370		}
371		self.finalized = true;
372		Ok(())
373	}
374
375	/// Abandon the current output without adding a movie trailer.
376	///
377	/// A second close is idempotent. The incomplete output file is retained so
378	/// callers can inspect or remove it explicitly.
379	pub fn close(&mut self) {
380		self.file = None;
381	}
382
383	/// Return the checked session configuration.
384	pub const fn config(&self) -> &VideoMuxerConfig {
385		&self.config
386	}
387
388	/// Return the number of video packets written so far.
389	pub fn packet_count(&self) -> usize {
390		self.video_sizes.len()
391	}
392
393	/// Return whether finalization completed successfully.
394	pub const fn is_finalized(&self) -> bool {
395		self.finalized
396	}
397
398	fn require_open(&self) -> Result<()> {
399		if self.finalized {
400			return Err(Error::failed_precondition("video muxer is finalized"));
401		}
402		if self.file.is_none() {
403			return Err(closed_error());
404		}
405		Ok(())
406	}
407
408	fn build_moov(&self) -> Result<Vec<u8>> {
409		let timescale = self.config.time_base.denominator();
410		let deltas = sample_deltas(
411			&self.video_decode_timestamps_micros,
412			timescale,
413			self.config.frame_rate,
414		)?;
415		let composition_offsets = composition_offsets(
416			&self.video_presentation_timestamps_micros,
417			&self.video_decode_timestamps_micros,
418			timescale,
419		)?;
420		let video_duration = deltas.iter().try_fold(0_u32, |total, delta| {
421			total
422				.checked_add(*delta)
423				.ok_or_else(|| Error::out_of_range("MP4 video duration exceeds u32"))
424		})?;
425		let audio_frames = self
426			.audio_durations
427			.iter()
428			.try_fold(0_u64, |total, value| {
429				total
430					.checked_add(u64::from(*value))
431					.ok_or_else(|| Error::out_of_range("MP4 audio duration exceeds u64"))
432			})?;
433		let audio_duration = if let Some(audio) = self.config.audio {
434			let audible = audio_frames.saturating_sub(u64::from(audio.priming_frames));
435			let ticks = audible
436				.checked_mul(u64::from(timescale))
437				.and_then(|value| value.checked_add(u64::from(audio.sample_rate / 2)))
438				.ok_or_else(|| Error::out_of_range("MP4 audio movie duration exceeds u64"))?
439				/ u64::from(audio.sample_rate);
440			u32::try_from(ticks)
441				.map_err(|_| Error::out_of_range("MP4 audio movie duration exceeds u32"))?
442		} else {
443			0
444		};
445		let mut payload = Vec::new();
446		append(
447			&mut payload,
448			&movie_header(
449				timescale,
450				video_duration.max(audio_duration),
451				!self.audio_offsets.is_empty(),
452			)?,
453		)?;
454		append(
455			&mut payload,
456			&self.build_video_track(video_duration, &deltas, &composition_offsets)?,
457		)?;
458		if !self.audio_offsets.is_empty() {
459			append(
460				&mut payload,
461				&build_audio_track(
462					self
463						.config
464						.audio
465						.ok_or_else(|| Error::internal("audio samples lost their track configuration"))?,
466					&self.audio_offsets,
467					&self.audio_durations,
468					timescale,
469				)?,
470			)?;
471		}
472		make_box(*b"moov", &payload)
473	}
474
475	fn build_video_track(
476		&self,
477		duration: u32,
478		deltas: &[u32],
479		composition_offsets: &[i32],
480	) -> Result<Vec<u8>> {
481		let mut track = Vec::new();
482		append(
483			&mut track,
484			&video_track_header(self.config.width, self.config.height, duration)?,
485		)?;
486
487		let mut media = Vec::new();
488		append(
489			&mut media,
490			&media_header(self.config.time_base.denominator(), duration)?,
491		)?;
492		append(&mut media, &handler_box(*b"vide", b"VideoHandler\0")?)?;
493
494		let mut information = Vec::new();
495		append(&mut information, &video_media_header()?)?;
496		append(
497			&mut information,
498			&self.build_video_sample_table(deltas, composition_offsets)?,
499		)?;
500		append(&mut media, &make_box(*b"minf", &information)?)?;
501		append(&mut track, &make_box(*b"mdia", &media)?)?;
502		make_box(*b"trak", &track)
503	}
504
505	fn build_video_sample_table(
506		&self,
507		deltas: &[u32],
508		composition_offsets: &[i32],
509	) -> Result<Vec<u8>> {
510		let mut table = Vec::new();
511		append(&mut table, &self.video_sample_description()?)?;
512		append(&mut table, &time_to_sample(deltas)?)?;
513		if composition_offsets.iter().any(|offset| *offset != 0) {
514			append(
515				&mut table,
516				&composition_time_to_sample(composition_offsets)?,
517			)?;
518		}
519		append(&mut table, &one_sample_per_chunk()?)?;
520		append(&mut table, &sample_sizes(&self.video_sizes)?)?;
521		append(&mut table, &chunk_offsets(&self.video_offsets)?)?;
522		if self.video_keyframes.iter().any(|keyframe| *keyframe) {
523			append(&mut table, &sync_samples(&self.video_keyframes)?)?;
524		}
525		make_box(*b"stbl", &table)
526	}
527
528	fn video_sample_description(&self) -> Result<Vec<u8>> {
529		let codec_box = match self.config.codec {
530			VideoCodec::H264 => build_avcc(&self.sps, &self.pps)?,
531			VideoCodec::H265 => build_hvcc(&self.vps, &self.sps, &self.pps)?,
532			_ => {
533				return Err(Error::internal(
534					"unsupported codec reached MP4 sample description",
535				));
536			}
537		};
538		let size = 86_usize
539			.checked_add(codec_box.len())
540			.ok_or_else(|| Error::out_of_range("MP4 video sample entry exceeds usize"))?;
541		let mut entry = zeroed(size, "MP4 video sample entry")?;
542		put_u32(&mut entry, 0, checked_u32(size, "MP4 video sample entry")?);
543		entry[4..8].copy_from_slice(match self.config.codec {
544			VideoCodec::H264 => b"avc1",
545			VideoCodec::H265 => b"hvc1",
546			_ => {
547				return Err(Error::internal(
548					"unsupported codec reached MP4 sample entry",
549				));
550			}
551		});
552		put_u16(&mut entry, 14, 1);
553		put_u16(
554			&mut entry,
555			32,
556			checked_u16(self.config.width, "MP4 video width")?,
557		);
558		put_u16(
559			&mut entry,
560			34,
561			checked_u16(self.config.height, "MP4 video height")?,
562		);
563		put_u32(&mut entry, 36, 0x0048_0000);
564		put_u32(&mut entry, 40, 0x0048_0000);
565		put_u16(&mut entry, 48, 1);
566		put_u16(&mut entry, 82, 0x18);
567		put_u16(&mut entry, 84, u16::MAX);
568		entry[86..].copy_from_slice(&codec_box);
569
570		let mut payload = zeroed(8, "MP4 stsd prefix")?;
571		put_u32(&mut payload, 4, 1);
572		append(&mut payload, &entry)?;
573		make_box(*b"stsd", &payload)
574	}
575}
576
577fn validate_config(path: &Path, config: VideoMuxerConfig) -> Result<()> {
578	if path.as_os_str().is_empty() {
579		return Err(Error::invalid_argument("video muxer path is empty"));
580	}
581	if config.width == 0 || config.height == 0 || config.frame_rate == 0 {
582		return Err(Error::invalid_argument(
583			"video muxer requires a non-zero extent and frame rate",
584		));
585	}
586	checked_u16(config.width, "MP4 video width")?;
587	checked_u16(config.height, "MP4 video height")?;
588	if config.time_base.numerator() != 1 {
589		return Err(Error::invalid_argument(
590			"MP4 video time-base numerator must currently be one",
591		));
592	}
593	if !matches!(config.codec, VideoCodec::H264 | VideoCodec::H265) {
594		return Err(Error::missing_capability(
595			"MP4 muxing is implemented only for H.264 and H.265",
596		));
597	}
598	if let Some(audio) = config.audio
599		&& (audio.sample_rate == 0
600			|| audio.sample_rate > u16::MAX.into()
601			|| !(1..=8).contains(&audio.channel_count))
602	{
603		return Err(Error::invalid_argument(
604			"MP4 PCM-S16 audio requires sample rate 1..=65535 and 1..=8 channels",
605		));
606	}
607	Ok(())
608}
609
610fn closed_error() -> Error {
611	Error::failed_precondition("video muxer is closed")
612}
613
614fn stream_header() -> [u8; STREAM_HEADER_BYTES as usize] {
615	let mut header = [0_u8; STREAM_HEADER_BYTES as usize];
616	put_u32(&mut header, 0, 16);
617	header[4..8].copy_from_slice(b"ftyp");
618	header[8..12].copy_from_slice(b"isom");
619	put_u32(&mut header, 12, 512);
620	put_u32(&mut header, 16, 1);
621	header[20..24].copy_from_slice(b"mdat");
622	header
623}
624
625struct Mp4Nal<'a> {
626	length: u32,
627	payload: &'a [u8],
628}
629
630struct ValidatedMp4Sample<'a> {
631	units: Vec<Mp4Nal<'a>>,
632	size: u32,
633}
634
635fn validate_annex_b_sample(bytes: &[u8]) -> Result<ValidatedMp4Sample<'_>> {
636	let parsed = super::parse_nal_annex_b(bytes);
637	if parsed.is_empty() {
638		return Err(Error::data_loss(
639			"MP4 video packet is not Annex-B framed or contains no NAL units",
640		));
641	}
642	let mut units = Vec::new();
643	units
644		.try_reserve_exact(parsed.len())
645		.map_err(|_| Error::resource_exhausted("MP4 NAL descriptor allocation failed"))?;
646	let mut total = 0_usize;
647	for unit in parsed {
648		let payload = trim_annex_b_trailing_zeroes(unit.payload());
649		let length = u32::try_from(payload.len())
650			.map_err(|_| Error::out_of_range("video NAL exceeds MP4 length field"))?;
651		if length == 0 {
652			return Err(Error::data_loss(
653				"video access unit contains an empty NAL unit",
654			));
655		}
656		total = total
657			.checked_add(4)
658			.and_then(|value| value.checked_add(payload.len()))
659			.ok_or_else(|| Error::out_of_range("MP4 video sample exceeds usize"))?;
660		units.push(Mp4Nal { length, payload });
661	}
662	let size =
663		u32::try_from(total).map_err(|_| Error::out_of_range("MP4 video sample exceeds u32"))?;
664	Ok(ValidatedMp4Sample { units, size })
665}
666
667fn write_length_prefixed_sample(
668	output: &mut impl Write,
669	units: &[Mp4Nal<'_>],
670) -> std::io::Result<()> {
671	for unit in units {
672		output.write_all(&unit.length.to_be_bytes())?;
673		output.write_all(unit.payload)?;
674	}
675	Ok(())
676}
677
678fn trim_annex_b_trailing_zeroes(mut payload: &[u8]) -> &[u8] {
679	while payload.last() == Some(&0) {
680		payload = &payload[..payload.len() - 1];
681	}
682	payload
683}
684
685fn validate_nal_record(bytes: &[u8], expected_type: u8, h265: bool, label: &str) -> Result<()> {
686	if bytes.is_empty() || bytes.len() > usize::from(u16::MAX) {
687		return Err(Error::invalid_argument(format!(
688			"{label} must contain 1..=65535 bytes"
689		)));
690	}
691	let nal_type = if h265 {
692		(bytes[0] >> 1) & 0x3f
693	} else {
694		bytes[0] & 0x1f
695	};
696	if nal_type != expected_type {
697		return Err(Error::invalid_argument(format!(
698			"{label} has the wrong NAL unit type"
699		)));
700	}
701	Ok(())
702}
703
704fn copy_bytes(bytes: &[u8], label: &str) -> Result<Vec<u8>> {
705	let mut output = Vec::new();
706	output
707		.try_reserve_exact(bytes.len())
708		.map_err(|_| Error::resource_exhausted(format!("{label} allocation failed")))?;
709	output.extend_from_slice(bytes);
710	Ok(output)
711}
712
713fn sample_deltas(timestamps: &[u64], timescale: u32, frame_rate: u32) -> Result<Vec<u32>> {
714	let nominal = (timescale / frame_rate).max(1);
715	let mut ticks = Vec::new();
716	ticks
717		.try_reserve_exact(timestamps.len())
718		.map_err(|_| Error::resource_exhausted("MP4 timestamp conversion allocation failed"))?;
719	for timestamp in timestamps {
720		ticks.push(timestamp_to_ticks(*timestamp, timescale)?);
721	}
722	let mut deltas = Vec::new();
723	deltas
724		.try_reserve_exact(ticks.len())
725		.map_err(|_| Error::resource_exhausted("MP4 sample delta allocation failed"))?;
726	for pair in ticks.windows(2) {
727		deltas.push(
728			pair[1]
729				.checked_sub(pair[0])
730				.filter(|delta| *delta > 0)
731				.ok_or_else(|| {
732					Error::invalid_argument("video timestamps collapse in the configured MP4 time base")
733				})?,
734		);
735	}
736	if !timestamps.is_empty() {
737		deltas.push(deltas.last().copied().unwrap_or(nominal));
738	}
739	Ok(deltas)
740}
741
742fn composition_offsets(
743	presentation_timestamps: &[u64],
744	decode_timestamps: &[u64],
745	timescale: u32,
746) -> Result<Vec<i32>> {
747	if presentation_timestamps.len() != decode_timestamps.len() {
748		return Err(Error::internal(
749			"MP4 presentation and decode timestamp tables differ in length",
750		));
751	}
752	let mut offsets = Vec::new();
753	offsets
754		.try_reserve_exact(presentation_timestamps.len())
755		.map_err(|_| Error::resource_exhausted("MP4 composition offset allocation failed"))?;
756	for (presentation, decode) in presentation_timestamps.iter().zip(decode_timestamps) {
757		let presentation = i64::from(timestamp_to_ticks(*presentation, timescale)?);
758		let decode = i64::from(timestamp_to_ticks(*decode, timescale)?);
759		offsets.push(
760			i32::try_from(presentation - decode)
761				.map_err(|_| Error::out_of_range("MP4 composition offset exceeds i32"))?,
762		);
763	}
764	Ok(offsets)
765}
766
767fn timestamp_to_ticks(timestamp_micros: u64, timescale: u32) -> Result<u32> {
768	let value = timestamp_micros
769		.checked_mul(u64::from(timescale))
770		.and_then(|value| value.checked_add(500_000))
771		.ok_or_else(|| Error::out_of_range("MP4 video timestamp conversion exceeds u64"))?
772		/ 1_000_000;
773	u32::try_from(value)
774		.map_err(|_| Error::out_of_range("MP4 video timestamp exceeds version-zero time domain"))
775}
776
777fn movie_header(timescale: u32, duration: u32, has_audio: bool) -> Result<Vec<u8>> {
778	let mut box_data = zeroed(108, "MP4 movie header")?;
779	write_box_header(&mut box_data, *b"mvhd")?;
780	put_u32(&mut box_data, 20, timescale);
781	put_u32(&mut box_data, 24, duration);
782	put_u32(&mut box_data, 28, 0x0001_0000);
783	put_u16(&mut box_data, 32, 0x0100);
784	put_identity_matrix(&mut box_data, 44);
785	put_u32(&mut box_data, 104, if has_audio { 3 } else { 2 });
786	Ok(box_data)
787}
788
789fn video_track_header(width: u32, height: u32, duration: u32) -> Result<Vec<u8>> {
790	let mut box_data = zeroed(92, "MP4 video track header")?;
791	write_box_header(&mut box_data, *b"tkhd")?;
792	put_u32(&mut box_data, 8, 7);
793	put_u32(&mut box_data, 20, 1);
794	put_u32(&mut box_data, 28, duration);
795	put_identity_matrix(&mut box_data, 48);
796	put_u32(
797		&mut box_data,
798		84,
799		width
800			.checked_shl(16)
801			.ok_or_else(|| Error::out_of_range("MP4 fixed-point width exceeds u32"))?,
802	);
803	put_u32(
804		&mut box_data,
805		88,
806		height
807			.checked_shl(16)
808			.ok_or_else(|| Error::out_of_range("MP4 fixed-point height exceeds u32"))?,
809	);
810	Ok(box_data)
811}
812
813fn media_header(timescale: u32, duration: u32) -> Result<Vec<u8>> {
814	let mut box_data = zeroed(32, "MP4 media header")?;
815	write_box_header(&mut box_data, *b"mdhd")?;
816	put_u32(&mut box_data, 20, timescale);
817	put_u32(&mut box_data, 24, duration);
818	put_u16(&mut box_data, 28, 0x55c4);
819	Ok(box_data)
820}
821
822fn handler_box(kind: [u8; 4], name: &[u8]) -> Result<Vec<u8>> {
823	let size = 32_usize
824		.checked_add(name.len())
825		.ok_or_else(|| Error::out_of_range("MP4 handler box exceeds usize"))?;
826	let mut box_data = zeroed(size, "MP4 handler box")?;
827	write_box_header(&mut box_data, *b"hdlr")?;
828	box_data[16..20].copy_from_slice(&kind);
829	box_data[32..].copy_from_slice(name);
830	Ok(box_data)
831}
832
833fn video_media_header() -> Result<Vec<u8>> {
834	let mut box_data = zeroed(20, "MP4 video media header")?;
835	write_box_header(&mut box_data, *b"vmhd")?;
836	put_u32(&mut box_data, 8, 1);
837	Ok(box_data)
838}
839
840fn build_avcc(sps: &[u8], pps: &[u8]) -> Result<Vec<u8>> {
841	let payload_size = 11_usize
842		.checked_add(sps.len())
843		.and_then(|value| value.checked_add(pps.len()))
844		.ok_or_else(|| Error::out_of_range("avcC size exceeds usize"))?;
845	let mut payload = zeroed(payload_size, "avcC payload")?;
846	payload[0] = 1;
847	if sps.len() >= 4 {
848		payload[1..4].copy_from_slice(&sps[1..4]);
849	} else {
850		payload[1..4].copy_from_slice(&[0x42, 0xe0, 0x1e]);
851	}
852	payload[4] = 0xff;
853	payload[5] = 0xe1;
854	put_u16(&mut payload, 6, checked_u16_len(sps.len(), "H.264 SPS")?);
855	payload[8..8 + sps.len()].copy_from_slice(sps);
856	let pps_offset = 8 + sps.len();
857	payload[pps_offset] = 1;
858	put_u16(
859		&mut payload,
860		pps_offset + 1,
861		checked_u16_len(pps.len(), "H.264 PPS")?,
862	);
863	payload[pps_offset + 3..].copy_from_slice(pps);
864	make_box(*b"avcC", &payload)
865}
866
867fn build_hvcc(vps: &[u8], sps: &[u8], pps: &[u8]) -> Result<Vec<u8>> {
868	let arrays_size = [vps, sps, pps].iter().try_fold(0_usize, |total, nal| {
869		total
870			.checked_add(5)
871			.and_then(|value| value.checked_add(nal.len()))
872			.ok_or_else(|| Error::out_of_range("hvcC arrays exceed usize"))
873	})?;
874	let mut payload = zeroed(
875		23_usize
876			.checked_add(arrays_size)
877			.ok_or_else(|| Error::out_of_range("hvcC payload exceeds usize"))?,
878		"hvcC payload",
879	)?;
880	payload[0] = 1;
881	payload[1] = 1;
882	put_u32(&mut payload, 2, 0x6000_0000);
883	payload[12] = 123;
884	payload[13] = 0xf0;
885	payload[15] = 0xfc;
886	payload[16] = 0xfd;
887	payload[17] = 0xf8;
888	payload[18] = 0xf8;
889	payload[21] = 0x0f;
890	payload[22] = 3;
891	let mut offset = 23;
892	for (nal_type, nal) in [(32_u8, vps), (33, sps), (34, pps)] {
893		payload[offset] = 0x80 | nal_type;
894		put_u16(&mut payload, offset + 1, 1);
895		put_u16(
896			&mut payload,
897			offset + 3,
898			checked_u16_len(nal.len(), "H.265 parameter set")?,
899		);
900		payload[offset + 5..offset + 5 + nal.len()].copy_from_slice(nal);
901		offset += 5 + nal.len();
902	}
903	make_box(*b"hvcC", &payload)
904}
905
906fn time_to_sample(deltas: &[u32]) -> Result<Vec<u8>> {
907	let mut runs: Vec<(u32, u32)> = Vec::new();
908	for delta in deltas {
909		if let Some((count, previous)) = runs.last_mut()
910			&& previous == delta
911		{
912			*count = count
913				.checked_add(1)
914				.ok_or_else(|| Error::out_of_range("MP4 stts run count exceeds u32"))?;
915		} else {
916			reserve_one(&mut runs, "MP4 stts runs")?;
917			runs.push((1, *delta));
918		}
919	}
920	let mut payload = zeroed(
921		8_usize
922			.checked_add(
923				runs
924					.len()
925					.checked_mul(8)
926					.ok_or_else(|| Error::out_of_range("MP4 stts size exceeds usize"))?,
927			)
928			.ok_or_else(|| Error::out_of_range("MP4 stts size exceeds usize"))?,
929		"MP4 stts",
930	)?;
931	put_u32(
932		&mut payload,
933		4,
934		checked_u32(runs.len(), "MP4 stts run count")?,
935	);
936	for (index, (count, delta)) in runs.iter().enumerate() {
937		put_u32(&mut payload, 8 + index * 8, *count);
938		put_u32(&mut payload, 12 + index * 8, *delta);
939	}
940	make_box(*b"stts", &payload)
941}
942
943fn composition_time_to_sample(offsets: &[i32]) -> Result<Vec<u8>> {
944	let mut runs: Vec<(u32, i32)> = Vec::new();
945	for offset in offsets {
946		if let Some((count, previous)) = runs.last_mut()
947			&& previous == offset
948		{
949			*count = count
950				.checked_add(1)
951				.ok_or_else(|| Error::out_of_range("MP4 ctts run count exceeds u32"))?;
952		} else {
953			reserve_one(&mut runs, "MP4 ctts runs")?;
954			runs.push((1, *offset));
955		}
956	}
957	let mut payload = zeroed(
958		8_usize
959			.checked_add(
960				runs
961					.len()
962					.checked_mul(8)
963					.ok_or_else(|| Error::out_of_range("MP4 ctts size exceeds usize"))?,
964			)
965			.ok_or_else(|| Error::out_of_range("MP4 ctts size exceeds usize"))?,
966		"MP4 ctts",
967	)?;
968	payload[0] = 1;
969	put_u32(
970		&mut payload,
971		4,
972		checked_u32(runs.len(), "MP4 ctts run count")?,
973	);
974	for (index, (count, offset)) in runs.iter().enumerate() {
975		put_u32(&mut payload, 8 + index * 8, *count);
976		put_u32(
977			&mut payload,
978			12 + index * 8,
979			u32::from_be_bytes(offset.to_be_bytes()),
980		);
981	}
982	make_box(*b"ctts", &payload)
983}
984
985fn one_sample_per_chunk() -> Result<Vec<u8>> {
986	let mut payload = zeroed(20, "MP4 stsc")?;
987	put_u32(&mut payload, 4, 1);
988	put_u32(&mut payload, 8, 1);
989	put_u32(&mut payload, 12, 1);
990	put_u32(&mut payload, 16, 1);
991	make_box(*b"stsc", &payload)
992}
993
994fn sample_sizes(sizes: &[u32]) -> Result<Vec<u8>> {
995	let mut payload = zeroed(
996		12_usize
997			.checked_add(
998				sizes
999					.len()
1000					.checked_mul(4)
1001					.ok_or_else(|| Error::out_of_range("MP4 stsz exceeds usize"))?,
1002			)
1003			.ok_or_else(|| Error::out_of_range("MP4 stsz exceeds usize"))?,
1004		"MP4 stsz",
1005	)?;
1006	put_u32(
1007		&mut payload,
1008		8,
1009		checked_u32(sizes.len(), "MP4 video sample count")?,
1010	);
1011	for (index, size) in sizes.iter().enumerate() {
1012		put_u32(&mut payload, 12 + index * 4, *size);
1013	}
1014	make_box(*b"stsz", &payload)
1015}
1016
1017fn chunk_offsets(offsets: &[u64]) -> Result<Vec<u8>> {
1018	let wide = offsets.iter().any(|offset| *offset > u64::from(u32::MAX));
1019	let stride = if wide { 8 } else { 4 };
1020	let mut payload = zeroed(
1021		8_usize
1022			.checked_add(
1023				offsets
1024					.len()
1025					.checked_mul(stride)
1026					.ok_or_else(|| Error::out_of_range("MP4 offset table exceeds usize"))?,
1027			)
1028			.ok_or_else(|| Error::out_of_range("MP4 offset table exceeds usize"))?,
1029		"MP4 offset table",
1030	)?;
1031	put_u32(
1032		&mut payload,
1033		4,
1034		checked_u32(offsets.len(), "MP4 chunk count")?,
1035	);
1036	for (index, offset) in offsets.iter().enumerate() {
1037		if wide {
1038			put_u64(&mut payload, 8 + index * 8, *offset);
1039		} else {
1040			put_u32(
1041				&mut payload,
1042				8 + index * 4,
1043				u32::try_from(*offset)
1044					.map_err(|_| Error::internal("32-bit MP4 chunk selection lost range"))?,
1045			);
1046		}
1047	}
1048	make_box(if wide { *b"co64" } else { *b"stco" }, &payload)
1049}
1050
1051fn sync_samples(keyframes: &[bool]) -> Result<Vec<u8>> {
1052	let count = keyframes.iter().filter(|keyframe| **keyframe).count();
1053	let mut payload = zeroed(
1054		8_usize
1055			.checked_add(
1056				count
1057					.checked_mul(4)
1058					.ok_or_else(|| Error::out_of_range("MP4 stss exceeds usize"))?,
1059			)
1060			.ok_or_else(|| Error::out_of_range("MP4 stss exceeds usize"))?,
1061		"MP4 stss",
1062	)?;
1063	put_u32(
1064		&mut payload,
1065		4,
1066		checked_u32(count, "MP4 sync sample count")?,
1067	);
1068	let mut output = 0;
1069	for (index, keyframe) in keyframes.iter().enumerate() {
1070		if *keyframe {
1071			put_u32(
1072				&mut payload,
1073				8 + output * 4,
1074				checked_u32(index + 1, "MP4 sync sample index")?,
1075			);
1076			output += 1;
1077		}
1078	}
1079	make_box(*b"stss", &payload)
1080}
1081
1082fn build_audio_track(
1083	config: VideoMuxerAudioConfig,
1084	offsets: &[u64],
1085	durations: &[u32],
1086	movie_timescale: u32,
1087) -> Result<Vec<u8>> {
1088	let media_duration_u64 = durations.iter().try_fold(0_u64, |total, duration| {
1089		total
1090			.checked_add(u64::from(*duration))
1091			.ok_or_else(|| Error::out_of_range("MP4 audio media duration exceeds u64"))
1092	})?;
1093	let media_duration = u32::try_from(media_duration_u64)
1094		.map_err(|_| Error::out_of_range("MP4 audio media duration exceeds u32"))?;
1095	let audible = media_duration_u64.saturating_sub(u64::from(config.priming_frames));
1096	let movie_duration = audible
1097		.checked_mul(u64::from(movie_timescale))
1098		.and_then(|value| value.checked_add(u64::from(config.sample_rate / 2)))
1099		.ok_or_else(|| Error::out_of_range("MP4 audio track duration exceeds u64"))?
1100		/ u64::from(config.sample_rate);
1101	let movie_duration = u32::try_from(movie_duration)
1102		.map_err(|_| Error::out_of_range("MP4 audio track duration exceeds u32"))?;
1103
1104	let mut track = Vec::new();
1105	let mut tkhd = zeroed(92, "MP4 audio track header")?;
1106	write_box_header(&mut tkhd, *b"tkhd")?;
1107	put_u32(&mut tkhd, 8, 7);
1108	put_u32(&mut tkhd, 20, 2);
1109	put_u32(&mut tkhd, 28, movie_duration);
1110	put_u16(&mut tkhd, 44, 0x0100);
1111	put_identity_matrix(&mut tkhd, 48);
1112	append(&mut track, &tkhd)?;
1113
1114	if config.priming_frames > 0 {
1115		let mut edit_payload = zeroed(20, "MP4 edit list")?;
1116		put_u32(&mut edit_payload, 4, 1);
1117		put_u32(&mut edit_payload, 8, movie_duration);
1118		put_u32(&mut edit_payload, 12, config.priming_frames);
1119		put_u16(&mut edit_payload, 16, 1);
1120		append(
1121			&mut track,
1122			&make_box(*b"edts", &make_box(*b"elst", &edit_payload)?)?,
1123		)?;
1124	}
1125
1126	let mut media = Vec::new();
1127	append(
1128		&mut media,
1129		&media_header(config.sample_rate, media_duration)?,
1130	)?;
1131	append(&mut media, &handler_box(*b"soun", b"SoundHandler\0")?)?;
1132	let mut information = Vec::new();
1133	let mut smhd = zeroed(16, "MP4 sound media header")?;
1134	write_box_header(&mut smhd, *b"smhd")?;
1135	append(&mut information, &smhd)?;
1136	append(
1137		&mut information,
1138		&build_audio_sample_table(config, offsets, durations, media_duration)?,
1139	)?;
1140	append(&mut media, &make_box(*b"minf", &information)?)?;
1141	append(&mut track, &make_box(*b"mdia", &media)?)?;
1142	make_box(*b"trak", &track)
1143}
1144
1145fn build_audio_sample_table(
1146	config: VideoMuxerAudioConfig,
1147	offsets: &[u64],
1148	durations: &[u32],
1149	media_duration: u32,
1150) -> Result<Vec<u8>> {
1151	let mut table = Vec::new();
1152	let mut entry = zeroed(50, "MP4 ipcm sample entry")?;
1153	put_u32(&mut entry, 0, 50);
1154	entry[4..8].copy_from_slice(b"ipcm");
1155	put_u16(&mut entry, 14, 1);
1156	put_u16(
1157		&mut entry,
1158		24,
1159		checked_u16(config.channel_count, "MP4 audio channel count")?,
1160	);
1161	put_u16(&mut entry, 26, 16);
1162	put_u32(
1163		&mut entry,
1164		32,
1165		config
1166			.sample_rate
1167			.checked_shl(16)
1168			.ok_or_else(|| Error::out_of_range("MP4 fixed-point audio rate exceeds u32"))?,
1169	);
1170	put_u32(&mut entry, 36, 14);
1171	entry[40..44].copy_from_slice(b"pcmC");
1172	entry[48] = 1;
1173	entry[49] = 16;
1174	let mut stsd_payload = zeroed(8, "MP4 audio stsd prefix")?;
1175	put_u32(&mut stsd_payload, 4, 1);
1176	append(&mut stsd_payload, &entry)?;
1177	append(&mut table, &make_box(*b"stsd", &stsd_payload)?)?;
1178
1179	let mut stts_payload = zeroed(16, "MP4 audio stts")?;
1180	put_u32(&mut stts_payload, 4, 1);
1181	put_u32(&mut stts_payload, 8, media_duration);
1182	put_u32(&mut stts_payload, 12, 1);
1183	append(&mut table, &make_box(*b"stts", &stts_payload)?)?;
1184
1185	let mut runs: Vec<(u32, u32)> = Vec::new();
1186	for (index, duration) in durations.iter().enumerate() {
1187		if runs
1188			.last()
1189			.is_some_and(|(_, previous)| previous == duration)
1190		{
1191			continue;
1192		}
1193		reserve_one(&mut runs, "MP4 audio chunk runs")?;
1194		runs.push((checked_u32(index + 1, "MP4 audio chunk index")?, *duration));
1195	}
1196	let mut stsc_payload = zeroed(
1197		8_usize
1198			.checked_add(
1199				runs
1200					.len()
1201					.checked_mul(12)
1202					.ok_or_else(|| Error::out_of_range("MP4 audio stsc exceeds usize"))?,
1203			)
1204			.ok_or_else(|| Error::out_of_range("MP4 audio stsc exceeds usize"))?,
1205		"MP4 audio stsc",
1206	)?;
1207	put_u32(
1208		&mut stsc_payload,
1209		4,
1210		checked_u32(runs.len(), "MP4 audio stsc run count")?,
1211	);
1212	for (index, (first_chunk, samples)) in runs.iter().enumerate() {
1213		put_u32(&mut stsc_payload, 8 + index * 12, *first_chunk);
1214		put_u32(&mut stsc_payload, 12 + index * 12, *samples);
1215		put_u32(&mut stsc_payload, 16 + index * 12, 1);
1216	}
1217	append(&mut table, &make_box(*b"stsc", &stsc_payload)?)?;
1218
1219	let mut stsz_payload = zeroed(12, "MP4 audio stsz")?;
1220	put_u32(
1221		&mut stsz_payload,
1222		4,
1223		config
1224			.channel_count
1225			.checked_mul(2)
1226			.ok_or_else(|| Error::out_of_range("MP4 PCM frame size exceeds u32"))?,
1227	);
1228	put_u32(&mut stsz_payload, 8, media_duration);
1229	append(&mut table, &make_box(*b"stsz", &stsz_payload)?)?;
1230	append(&mut table, &chunk_offsets(offsets)?)?;
1231	make_box(*b"stbl", &table)
1232}
1233
1234fn make_box(kind: [u8; 4], payload: &[u8]) -> Result<Vec<u8>> {
1235	let size = payload
1236		.len()
1237		.checked_add(8)
1238		.ok_or_else(|| Error::out_of_range("MP4 box size exceeds usize"))?;
1239	let mut output = Vec::new();
1240	output
1241		.try_reserve_exact(size)
1242		.map_err(|_| Error::resource_exhausted("MP4 box allocation failed"))?;
1243	output.extend_from_slice(&checked_u32(size, "MP4 box size")?.to_be_bytes());
1244	output.extend_from_slice(&kind);
1245	output.extend_from_slice(payload);
1246	Ok(output)
1247}
1248
1249fn write_box_header(bytes: &mut [u8], kind: [u8; 4]) -> Result<()> {
1250	put_u32(bytes, 0, checked_u32(bytes.len(), "MP4 box size")?);
1251	bytes[4..8].copy_from_slice(&kind);
1252	Ok(())
1253}
1254
1255fn append(output: &mut Vec<u8>, bytes: &[u8]) -> Result<()> {
1256	output
1257		.try_reserve(bytes.len())
1258		.map_err(|_| Error::resource_exhausted("MP4 metadata allocation failed"))?;
1259	output.extend_from_slice(bytes);
1260	Ok(())
1261}
1262
1263fn zeroed(size: usize, label: &str) -> Result<Vec<u8>> {
1264	let mut output = Vec::new();
1265	output
1266		.try_reserve_exact(size)
1267		.map_err(|_| Error::resource_exhausted(format!("{label} allocation failed")))?;
1268	output.resize(size, 0);
1269	Ok(output)
1270}
1271
1272fn reserve_one<T>(values: &mut Vec<T>, label: &str) -> Result<()> {
1273	values
1274		.try_reserve(1)
1275		.map_err(|_| Error::resource_exhausted(format!("{label} allocation failed")))
1276}
1277
1278fn checked_u16(value: u32, label: &str) -> Result<u16> {
1279	u16::try_from(value).map_err(|_| Error::out_of_range(format!("{label} exceeds u16")))
1280}
1281
1282fn checked_u16_len(value: usize, label: &str) -> Result<u16> {
1283	u16::try_from(value).map_err(|_| Error::out_of_range(format!("{label} exceeds u16")))
1284}
1285
1286fn checked_u32(value: usize, label: &str) -> Result<u32> {
1287	u32::try_from(value).map_err(|_| Error::out_of_range(format!("{label} exceeds u32")))
1288}
1289
1290fn put_u16(bytes: &mut [u8], offset: usize, value: u16) {
1291	bytes[offset..offset + 2].copy_from_slice(&value.to_be_bytes());
1292}
1293
1294fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
1295	bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes());
1296}
1297
1298fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
1299	bytes[offset..offset + 8].copy_from_slice(&value.to_be_bytes());
1300}
1301
1302fn put_identity_matrix(bytes: &mut [u8], offset: usize) {
1303	put_u32(bytes, offset, 0x0001_0000);
1304	put_u32(bytes, offset + 16, 0x0001_0000);
1305	put_u32(bytes, offset + 32, 0x4000_0000);
1306}