Skip to main content

moq_mux/codec/h264/
mod.rs

1//! H.264 / AVC.
2//!
3//! Parses SPS NAL units and AVCDecoderConfigurationRecord blobs into
4//! catalog-ready fields. The [`Avc1`] transmuxer rewrites Annex-B input
5//! (inline SPS/PPS) as length-prefixed NALU + out-of-band avcC, which is
6//! what every CMAF and MKV consumer expects. [`Export`] subscribes to a
7//! catalog-narrowed H.264 rendition and emits an Annex-B elementary
8//! stream; [`Split`] does the byte-level framing of an Annex-B stream and
9//! [`Import`] is the pure frame publisher that resolves the catalog.
10//! Length-prefixed NALU has no stream framing; wrap one access unit with
11//! `avc1_frame`.
12//!
13//! The catalog's `description` decides the framing (an avcC means
14//! length-prefixed, none means Annex-B); avc1 and avc3 only say whether the
15//! parameter sets may also ride in band.
16
17mod export;
18mod import;
19mod split;
20
21pub use export::*;
22pub use import::*;
23pub use split::*;
24
25use bytes::{Buf, Bytes, BytesMut};
26use h264_reader::nal::sps::{FrameMbsFlags, SeqParameterSet};
27use h264_reader::rbsp::{BitRead, BitReaderError};
28
29use crate::codec::annexb::{InBandCodec, ParameterSets};
30
31// H.264 NAL unit types (ISO/IEC 14496-10 §7.4.1).
32const NAL_TYPE_SEI: u8 = 6;
33const NAL_TYPE_SPS: u8 = 7;
34const NAL_TYPE_PPS: u8 = 8;
35
36/// Wrap one avc1 (length-prefixed NALU) access unit as a single
37/// [`Frame`](crate::container::Frame), with the keyframe flag set when it
38/// carries an IDR slice (NAL type 5).
39///
40/// avc1 is not a stream: each access unit arrives whole with its NALU
41/// `length_size` known out-of-band from the avcC (`super::Avcc::parse(avcc).length_size`).
42/// The payload is passed through verbatim.
43pub(crate) fn avc1_frame(
44	data: impl moq_net::IntoBytes,
45	length_size: usize,
46	pts: moq_net::Timestamp,
47) -> crate::Result<crate::container::Frame> {
48	let keyframe = avc1_is_keyframe(data.as_ref(), length_size);
49	Ok(crate::container::Frame {
50		timestamp: pts,
51		decode: None,
52		payload: data.into_bytes(),
53		keyframe,
54		duration: None,
55	})
56}
57
58/// Detect whether an avc1-shaped (length-prefixed) buffer contains an IDR slice.
59fn avc1_is_keyframe(data: &[u8], length_size: usize) -> bool {
60	let Ok(nals) = crate::codec::annexb::length_prefixed_nals(data, length_size) else {
61		return false;
62	};
63	nals.map_while(std::result::Result::ok)
64		.any(|nal| nal.first().is_some_and(|header| header & 0x1f == 5))
65}
66
67/// H.264 parsing and transform errors.
68#[derive(Debug, Clone, thiserror::Error)]
69#[non_exhaustive]
70pub enum Error {
71	/// The SPS NAL is shorter than its required header.
72	#[error("SPS NAL too short")]
73	SpsTooShort,
74
75	/// The SPS NAL could not be parsed.
76	#[error("failed to parse SPS")]
77	SpsParse,
78
79	/// The AVCDecoderConfigurationRecord is shorter than its required header.
80	#[error("AVCDecoderConfigurationRecord too short")]
81	AvccTooShort,
82
83	/// The AVCDecoderConfigurationRecord ends before its declared parameter sets.
84	#[error("AVCDecoderConfigurationRecord truncated")]
85	AvccTruncated,
86
87	/// The AVCDecoderConfigurationRecord declares a configurationVersion other than 1.
88	#[error("unsupported AVCDecoderConfigurationRecord version {0}")]
89	AvccVersion(u8),
90
91	/// The named avc1 rendition lacks an SPS or PPS in its description.
92	#[error("avc1 description for rendition {name:?} is missing SPS or PPS (sps={sps}, pps={pps})")]
93	MissingParamSets {
94		/// The rendition name.
95		name: String,
96		/// The number of SPS NAL units in the description.
97		sps: usize,
98		/// The number of PPS NAL units in the description.
99		pps: usize,
100	},
101
102	/// The SPS length does not fit the avcC length field.
103	#[error("SPS too large for avcC length field ({0} > {max})", max = u16::MAX)]
104	SpsTooLarge(usize),
105
106	/// The PPS length does not fit the avcC length field.
107	#[error("PPS too large for avcC length field ({0} > {max})", max = u16::MAX)]
108	PpsTooLarge(usize),
109
110	/// No SPS is available to configure the stream.
111	#[error("avcC requires at least one SPS")]
112	MissingSps,
113
114	/// The number of SPS NAL units exceeds the avcC limit of 31.
115	#[error("too many SPS for avcC ({0} > 31)")]
116	TooManySps(usize),
117
118	/// The number of PPS NAL units exceeds the avcC limit of 255.
119	#[error("too many PPS for avcC ({0} > 255)")]
120	TooManyPps(usize),
121
122	/// The NAL payload length does not fit a four-byte prefix.
123	#[error("NAL too large for 4-byte length prefix")]
124	NalTooLarge,
125
126	/// The NAL unit ends before its required header or slice fields.
127	#[error("NAL unit is too short")]
128	NalTooShort,
129
130	/// The NAL header sets the forbidden_zero_bit.
131	#[error("forbidden zero bit is not zero")]
132	ForbiddenZeroBit,
133
134	/// The stream has not supplied its decoder configuration.
135	#[error("not initialized")]
136	NotInitialized,
137
138	/// The avc3 track has not been created.
139	#[error("avc3 track not created")]
140	Avc3TrackNotCreated,
141
142	/// The access unit has no timestamp.
143	#[error("missing timestamp")]
144	MissingTimestamp,
145
146	/// Parsing or transforming the Annex B stream failed.
147	#[error("annexb: {0}")]
148	Annexb(#[from] crate::codec::annexb::Error),
149}
150
151/// A result using this module's error type.
152pub type Result<T> = std::result::Result<T, Error>;
153
154/// Parsed H.264 SPS (Sequence Parameter Set) NAL.
155///
156/// Reads the SPS with [`h264_reader`] and keeps the codec-config fields that the hang
157/// catalog records: profile_idc, level_idc, and the packed constraint_set
158/// flags. The first byte of `nal` must be the NAL header.
159#[derive(Debug, Clone)]
160pub struct Sps {
161	/// The SPS profile_idc.
162	pub profile: u8,
163	/// The packed SPS constraint_set flags.
164	pub constraints: u8,
165	/// The SPS level_idc.
166	pub level: u8,
167	/// The coded picture width in pixels.
168	pub coded_width: u32,
169	/// The coded picture height in pixels.
170	pub coded_height: u32,
171}
172
173impl Sps {
174	/// Parse an SPS NAL unit.
175	pub fn parse(nal: &[u8]) -> Result<Self> {
176		if nal.len() < 4 {
177			return Err(Error::SpsTooShort);
178		}
179		let sps = read_sps(nal).ok_or(Error::SpsParse)?;
180		let (coded_width, coded_height) = sps.pixel_dimensions().map_err(|_| Error::SpsParse)?;
181		// A crop that removes the whole picture leaves nothing to decode.
182		if coded_width == 0 || coded_height == 0 {
183			return Err(Error::SpsParse);
184		}
185		Ok(Self {
186			profile: sps.profile_idc.into(),
187			// constraint_set0..5_flag; the two reserved bits after them stay clear.
188			constraints: u8::from(sps.constraint_flags) & 0xfc,
189			level: sps.level_idc,
190			coded_width,
191			coded_height,
192		})
193	}
194}
195
196/// Parse an SPS NAL unit (header included), `None` when it is malformed.
197///
198/// h264-reader refuses the whole SPS when its VUI is cut short or breaks a constraint, but the
199/// codec string and coded size only need the fields before it. So a refused SPS is read again
200/// without its VUI, as though `vui_parameters_present_flag` were 0, and declares nothing the VUI
201/// would have.
202fn read_sps(nal: &[u8]) -> Option<SeqParameterSet> {
203	use crate::codec::annexb::rbsp;
204
205	SeqParameterSet::from_bits(rbsp(nal, 1)).ok().or_else(|| {
206		let sps = SeqParameterSet::from_bits(WithoutVui(rbsp(nal, 1))).ok()?;
207		tracing::debug!("H.264 SPS VUI refused by h264-reader; using the SPS without it");
208		Some(sps)
209	})
210}
211
212/// A reader that reports `vui_parameters_present_flag` as 0 and leaves the rest of the RBSP
213/// unread, so h264-reader parses an SPS up to its VUI.
214struct WithoutVui<R>(R);
215
216impl<R: BitRead> BitRead for WithoutVui<R> {
217	fn read_ue(&mut self, name: &'static str) -> std::result::Result<u32, BitReaderError> {
218		self.0.read_ue(name)
219	}
220
221	fn read_se(&mut self, name: &'static str) -> std::result::Result<i32, BitReaderError> {
222		self.0.read_se(name)
223	}
224
225	fn read_bit(&mut self, name: &'static str) -> std::result::Result<bool, BitReaderError> {
226		match name {
227			"vui_parameters_present_flag" => Ok(false),
228			_ => self.0.read_bit(name),
229		}
230	}
231
232	fn read<const BITS: u32, I: h264_reader::rbsp::Integer>(
233		&mut self,
234		name: &'static str,
235	) -> std::result::Result<I, BitReaderError> {
236		self.0.read::<BITS, I>(name)
237	}
238
239	fn read_var<I: h264_reader::rbsp::Integer>(
240		&mut self,
241		bit_count: u32,
242		name: &'static str,
243	) -> std::result::Result<I, BitReaderError> {
244		self.0.read_var(bit_count, name)
245	}
246
247	fn read_to<V: h264_reader::rbsp::Primitive>(
248		&mut self,
249		name: &'static str,
250	) -> std::result::Result<V, BitReaderError> {
251		self.0.read_to(name)
252	}
253
254	fn skip(&mut self, bit_count: u32, name: &'static str) -> std::result::Result<(), BitReaderError> {
255		self.0.skip(bit_count, name)
256	}
257
258	fn byte_aligned(&self) -> bool {
259		self.0.byte_aligned()
260	}
261
262	fn has_more_rbsp_data(&mut self, name: &'static str) -> std::result::Result<bool, BitReaderError> {
263		self.0.has_more_rbsp_data(name)
264	}
265
266	/// The VUI and the trailing bits after it go unread.
267	fn finish_rbsp(self) -> std::result::Result<(), BitReaderError> {
268		Ok(())
269	}
270
271	fn finish_sei_payload(self) -> std::result::Result<(), BitReaderError> {
272		self.0.finish_sei_payload()
273	}
274}
275
276/// The reordering an SPS NAL unit declares in its VUI: `max_num_reorder_frames` from the
277/// bitstream restriction, and the frame period when `fixed_frame_rate_flag` is set.
278///
279/// `None` when the SPS carries no VUI or no bitstream restriction, or fails to parse.
280pub(crate) fn sps_reorder(nal: &[u8]) -> Option<crate::codec::video::Reorder> {
281	let vui = sps_vui(nal)?;
282	Some(crate::codec::video::Reorder {
283		depth: vui.depth?,
284		period: vui.period,
285	})
286}
287
288/// The NAL HRD an SPS NAL unit's VUI declares, when it carries one.
289pub(crate) fn sps_hrd(nal: &[u8]) -> Option<crate::codec::video::Hrd> {
290	sps_vui(nal)?.hrd
291}
292
293/// Whether an SPS NAL unit codes field pictures or field macroblock pairs (`frame_mbs_only_flag` 0).
294pub(crate) fn sps_interlaced(nal: &[u8]) -> Option<bool> {
295	let sps = read_sps(nal)?;
296	Some(!matches!(sps.frame_mbs_flags, FrameMbsFlags::Frames))
297}
298
299/// What an SPS VUI declares about picture timing, sample shape, and colour.
300struct Vui {
301	/// The sample aspect, when the VUI specifies one.
302	sample_aspect: Option<(u32, u32)>,
303	/// The video signal type's range and colour description, unspecified fields absent.
304	color: Option<hang::catalog::Color>,
305	/// `frame_mbs_only_flag`: every picture is a frame, so two ticks are one frame.
306	frame_only: bool,
307	/// One frame's duration as `(units, scale)` when `fixed_frame_rate_flag` is set.
308	period: Option<(u64, u64)>,
309	/// `max_num_reorder_frames`, when the bitstream restriction is present.
310	depth: Option<u32>,
311	/// The NAL HRD, when present.
312	hrd: Option<crate::codec::video::Hrd>,
313}
314
315impl Vui {
316	/// Read the VUI of a parsed SPS (ITU-T H.264 E.1.1), `None` when it carries none.
317	fn new(sps: &SeqParameterSet) -> Option<Self> {
318		let vui = sps.vui_parameters.as_ref()?;
319		let sample_aspect = vui
320			.aspect_ratio_info
321			.as_ref()
322			.and_then(|info| info.get())
323			.map(|(width, height)| (u32::from(width), u32::from(height)));
324		let color = vui.video_signal_type.as_ref().and_then(|signal| {
325			let (primaries, transfer, matrix) = match &signal.colour_description {
326				Some(c) => (c.colour_primaries, c.transfer_characteristics, c.matrix_coefficients),
327				None => (2, 2, 2),
328			};
329			crate::codec::color::cicp(primaries, transfer, matrix, Some(signal.video_full_range_flag))
330		});
331		// With a fixed rate, a frame lasts two ticks (E.2.1).
332		let period = vui
333			.timing_info
334			.as_ref()
335			.filter(|t| t.fixed_frame_rate_flag && t.num_units_in_tick > 0 && t.time_scale > 0)
336			.map(|t| (2 * u64::from(t.num_units_in_tick), u64::from(t.time_scale)));
337		// The last schedule is the one a decoder conforms to (E.2.2).
338		let hrd = vui.nal_hrd_parameters.as_ref().and_then(|hrd| {
339			let spec = hrd.cpb_specs.last()?;
340			Some(crate::codec::video::Hrd {
341				bit_rate: (u64::from(spec.bit_rate_value_minus1) + 1) << (6 + hrd.bit_rate_scale),
342				cpb_size: (u64::from(spec.cpb_size_value_minus1) + 1) << (4 + hrd.cpb_size_scale),
343			})
344		});
345		Some(Self {
346			sample_aspect,
347			color,
348			frame_only: matches!(sps.frame_mbs_flags, FrameMbsFlags::Frames),
349			period,
350			depth: vui.bitstream_restrictions.as_ref().map(|b| b.max_num_reorder_frames),
351			hrd,
352		})
353	}
354
355	/// Only a fixed frame rate on a frame-only SPS fixes the picture period; field pictures
356	/// need their slice header's `pic_struct` (ITU-T H.264 E.2.1, Table E-6).
357	fn framerate(&self) -> Option<f64> {
358		if !self.frame_only {
359			return None;
360		}
361		let (units, scale) = self.period?;
362		Some(scale as f64 / units as f64)
363	}
364
365	fn apply(&self, config: &mut hang::catalog::VideoConfig) {
366		config.framerate = self.framerate();
367		let display_aspect = match (config.coded_width, config.coded_height, self.sample_aspect) {
368			(Some(width), Some(height), Some(sample)) => crate::codec::video::display_aspect(width, height, sample),
369			_ => None,
370		};
371		config.display_aspect_width = display_aspect.map(|(width, _)| width);
372		config.display_aspect_height = display_aspect.map(|(_, height)| height);
373		config.color = self.color.clone();
374		// A field picture counts as half a frame, so only a frame-only SPS declares in frames.
375		config.reorder = self
376			.depth
377			.filter(|depth| self.frame_only && *depth <= crate::codec::video::max_reorder(config))
378			.and_then(|depth| u8::try_from(depth).ok());
379	}
380}
381
382/// `None` when the SPS carries no VUI or fails to parse.
383fn sps_vui(nal: &[u8]) -> Option<Vui> {
384	Vui::new(&read_sps(nal)?)
385}
386
387/// Parsed AVCDecoderConfigurationRecord (ISO/IEC 14496-15 §5.3.3.1.2).
388///
389/// Just the codec-config fields that the hang catalog records. The original
390/// avcC bytes are still what gets stored as the catalog `description`; this
391/// struct is for the field extraction.
392#[derive(Debug, Clone)]
393#[non_exhaustive]
394pub struct Avcc {
395	/// AVC profile indication (`profile_idc`) from the record.
396	pub profile: u8,
397	/// Packed constraint-set flags byte from the record.
398	pub constraints: u8,
399	/// AVC level indication (`level_idc`) from the record.
400	pub level: u8,
401	/// NALU length size in bytes (typically 4).
402	pub length_size: usize,
403	/// SPS NAL units carried out-of-band in the record.
404	pub sps: Vec<Bytes>,
405	/// PPS NAL units carried out-of-band in the record.
406	pub pps: Vec<Bytes>,
407	/// Picture width in pixels from the embedded SPS, if available.
408	pub coded_width: Option<u32>,
409	/// Picture height in pixels from the embedded SPS, if available.
410	pub coded_height: Option<u32>,
411}
412
413/// The largest AVCDecoderConfigurationRecord its count fields allow (ISO/IEC 14496-15 §5.3.3.1.2):
414/// 6 fixed bytes, up to 31 SPS, a count byte, up to 255 PPS, then the High-profile extension's 4
415/// bytes and up to 255 SPS extensions, each parameter set a `u16` length and up to 64 KiB.
416pub(crate) const AVCC_MAX_LEN: usize = 6 + 1 + 4 + (31 + 255 + 255) * (2 + u16::MAX as usize);
417
418impl Avcc {
419	/// Parse an AVCDecoderConfigurationRecord buffer.
420	pub fn parse(avcc: &[u8]) -> Result<Self> {
421		if avcc.len() < 7 {
422			return Err(Error::AvccTooShort);
423		}
424
425		let record = decode_avcc(avcc)?;
426		let sps: Vec<Bytes> = record.sequence_parameter_sets.into_iter().map(Bytes::from).collect();
427		let pps = record.picture_parameter_sets.into_iter().map(Bytes::from).collect();
428
429		// Resolution from the first parseable SPS.
430		let parsed = sps.iter().find_map(|nal| Sps::parse(nal).ok());
431		let coded_width = parsed.as_ref().map(|sps| sps.coded_width);
432		let coded_height = parsed.as_ref().map(|sps| sps.coded_height);
433
434		Ok(Self {
435			profile: record.avc_profile_indication,
436			constraints: record.profile_compatibility,
437			level: record.avc_level_indication,
438			length_size: record.length_size.into(),
439			sps,
440			pps,
441			coded_width,
442			coded_height,
443		})
444	}
445}
446
447/// Decode an AVCDecoderConfigurationRecord body with mp4-atom.
448///
449/// Stricter than a bare scan of the parameter-set arrays: the record must be version 1,
450/// and any bytes after the PPS array must form a whole High-profile extension.
451fn decode_avcc(avcc: &[u8]) -> Result<mp4_atom::Avcc> {
452	use mp4_atom::Atom;
453	mp4_atom::Avcc::decode_body(&mut &avcc[..]).map_err(|err| match err {
454		mp4_atom::Error::UnknownVersion(version) => Error::AvccVersion(version),
455		_ => Error::AvccTruncated,
456	})
457}
458
459/// Encode a record whose fields the caller has already bounded.
460fn encode_avcc(record: &mp4_atom::Avcc) -> Bytes {
461	use mp4_atom::Atom;
462	let mut out = BytesMut::new();
463	record
464		.encode_body(&mut out)
465		.expect("a length size of 4 and an 8-bit 4:2:0 extension encode");
466	out.freeze()
467}
468
469/// Build an AVCDecoderConfigurationRecord (ISO/IEC 14496-15 §5.3.3.1.2) from the
470/// given SPS and PPS NALs. At least one SPS is required; the profile/level fields
471/// are read from the first SPS. A stream may legitimately carry several distinct
472/// SPS/PPS (slices reference them by id), so the record holds an ordered list of
473/// each rather than a single one.
474pub(crate) fn build_avcc(sps_nals: &[Bytes], pps_nals: &[Bytes]) -> Result<Bytes> {
475	let first_sps = sps_nals.first().ok_or(Error::MissingSps)?;
476	if first_sps.len() < 4 {
477		return Err(Error::SpsTooShort);
478	}
479	// numOfSequenceParameterSets is a 5-bit field, numOfPictureParameterSets a byte;
480	// mp4-atom truncates the counts and lengths rather than refusing them.
481	if sps_nals.len() > 0x1f {
482		return Err(Error::TooManySps(sps_nals.len()));
483	}
484	if pps_nals.len() > u8::MAX as usize {
485		return Err(Error::TooManyPps(pps_nals.len()));
486	}
487	for sps in sps_nals {
488		if sps.len() > u16::MAX as usize {
489			return Err(Error::SpsTooLarge(sps.len()));
490		}
491	}
492	for pps in pps_nals {
493		if pps.len() > u16::MAX as usize {
494			return Err(Error::PpsTooLarge(pps.len()));
495		}
496	}
497
498	Ok(encode_avcc(&mp4_atom::Avcc {
499		configuration_version: 1,
500		avc_profile_indication: first_sps[1],
501		profile_compatibility: first_sps[2],
502		avc_level_indication: first_sps[3],
503		length_size: 4,
504		sequence_parameter_sets: sps_nals.iter().map(|nal| nal.to_vec()).collect(),
505		picture_parameter_sets: pps_nals.iter().map(|nal| nal.to_vec()).collect(),
506		ext: None,
507	}))
508}
509
510/// An avcC whose parameter sets will arrive in the samples, from a catalog codec
511/// string that already fixes the record.
512///
513/// Baseline, Main, and Extended carry no avcC extension. High is 8-bit and declared
514/// 4:2:0, which the extension must state when the SPS is absent; a monochrome High
515/// stream is rare enough to accept that mismatch, and its in-band SPS still governs
516/// decoding. Every other profile leaves chroma format or bit depth to the SPS, so the
517/// record has to wait for one.
518pub(crate) fn catalog_avcc(h264: &hang::catalog::H264) -> Option<Bytes> {
519	if !h264.inline {
520		return None;
521	}
522	let ext = match h264.profile {
523		66 | 77 | 88 => None,
524		// The default extension is 8-bit 4:2:0 with no SPS extensions.
525		100 => Some(mp4_atom::AvccExt::default()),
526		_ => return None,
527	};
528
529	Some(encode_avcc(&mp4_atom::Avcc {
530		configuration_version: 1,
531		avc_profile_indication: h264.profile,
532		profile_compatibility: h264.constraints,
533		avc_level_indication: h264.level,
534		length_size: 4,
535		sequence_parameter_sets: Vec::new(),
536		picture_parameter_sets: Vec::new(),
537		ext,
538	}))
539}
540
541/// Extract the parameter-set NALs (SPS then PPS) and the NALU length size from
542/// an AVCDecoderConfigurationRecord. The inverse of [`build_avcc`]; used to
543/// re-emit out-of-band avc1 parameter sets as inline Annex-B (e.g. for MPEG-TS).
544pub(crate) fn avcc_params(avcc: &[u8]) -> Result<(usize, Vec<Bytes>)> {
545	let record = decode_avcc(avcc)?;
546	let params = record
547		.sequence_parameter_sets
548		.into_iter()
549		.chain(record.picture_parameter_sets)
550		.map(Bytes::from)
551		.collect();
552	Ok((record.length_size.into(), params))
553}
554
555/// Transform H.264 frames from Annex-B (inline SPS/PPS) to length-prefixed
556/// NALU with an out-of-band AVCDecoderConfigurationRecord ("avc1").
557///
558/// The avcC is synthesized from the active SPS+PPS and exposed via
559/// [`Self::avcc`]. Once it returns `Some`, all subsequent calls to
560/// [`Self::transform`] return length-prefixed sample data suitable for an avc1
561/// container (e.g. MKV `V_MPEG4/ISO/AVC` with the avcC in CodecPrivate).
562///
563/// The active set is scoped to the latest keyframe: a frame that carries
564/// parameter sets redefines them, so a mid-stream reconfiguration drops the
565/// superseded SPS/PPS instead of accumulating them forever.
566pub struct Avc1 {
567	avcc: Option<Bytes>,
568	/// The active SPS NALs (from the most recent keyframe that carried them).
569	sps: Vec<Bytes>,
570	/// The active PPS NALs.
571	pps: Vec<Bytes>,
572}
573
574impl Default for Avc1 {
575	fn default() -> Self {
576		Self::new()
577	}
578}
579
580impl Avc1 {
581	/// Build a new transform for an avc3 source.
582	pub fn new() -> Self {
583		Self {
584			avcc: None,
585			sps: Vec::new(),
586			pps: Vec::new(),
587		}
588	}
589
590	/// The AVCDecoderConfigurationRecord, available once SPS+PPS have been observed.
591	pub fn avcc(&self) -> Option<&Bytes> {
592		self.avcc.as_ref()
593	}
594
595	/// Convert one decoded frame's payload to the avc1 wire shape.
596	///
597	/// Returns:
598	/// - `Ok(Some(payload))` if a length-prefixed sample is ready to emit.
599	/// - `Ok(None)` if the input contained only parameter sets and the
600	///   transform is still waiting for slice NALs (avcC may have been built
601	///   as a side effect).
602	pub fn transform(&mut self, payload: Bytes) -> Result<Option<Bytes>> {
603		// Parse Annex-B NALs, collect this frame's SPS/PPS, length-prefix the
604		// rest. NalIterator advances the Bytes cursor; the trailing NAL has to be
605		// pulled separately via flush().
606		let mut buf = payload.clone();
607		let mut nal_iter = crate::codec::annexb::NalIterator::new(&mut buf);
608
609		let mut out = BytesMut::with_capacity(payload.remaining());
610		let mut frame_sps = ParameterSets::new();
611		let mut frame_pps = ParameterSets::new();
612		let mut emitted_any_slice = false;
613
614		loop {
615			let nal = match nal_iter.next() {
616				Some(Ok(n)) => n,
617				Some(Err(e)) => return Err(e.into()),
618				None => break,
619			};
620			if process_nal(&nal, &mut out, &mut frame_sps, &mut frame_pps)? {
621				emitted_any_slice = true;
622			}
623		}
624
625		if let Some(nal) = nal_iter.flush()?
626			&& process_nal(&nal, &mut out, &mut frame_sps, &mut frame_pps)?
627		{
628			emitted_any_slice = true;
629		}
630
631		// A frame that carries parameter sets (a keyframe) redefines the active
632		// set; adopt it so SPS/PPS from a superseded configuration are dropped
633		// rather than lingering in the avcC. Per type, so a frame that updates only
634		// one of SPS/PPS keeps the other.
635		let mut changed = false;
636		let frame_sps: Vec<Bytes> = frame_sps.into_values().collect();
637		if !frame_sps.is_empty() && frame_sps != self.sps {
638			self.sps = frame_sps;
639			changed = true;
640		}
641		let frame_pps: Vec<Bytes> = frame_pps.into_values().collect();
642		if !frame_pps.is_empty() && frame_pps != self.pps {
643			self.pps = frame_pps;
644			changed = true;
645		}
646		if changed {
647			self.rebuild_avcc()?;
648		}
649
650		if !emitted_any_slice {
651			return Ok(None);
652		}
653
654		Ok(Some(out.freeze()))
655	}
656
657	fn rebuild_avcc(&mut self) -> Result<()> {
658		if self.sps.is_empty() || self.pps.is_empty() {
659			return Ok(());
660		}
661		self.avcc = Some(build_avcc(&self.sps, &self.pps)?);
662		Ok(())
663	}
664}
665
666/// Process one NAL: SPS/PPS are collected by id into this frame's sets,
667/// everything else is length-prefixed and appended to `out`. Returns true if the
668/// NAL was a slice (i.e. produced sample bytes).
669fn process_nal(
670	nal: &Bytes,
671	out: &mut BytesMut,
672	frame_sps: &mut ParameterSets,
673	frame_pps: &mut ParameterSets,
674) -> Result<bool> {
675	if nal.is_empty() {
676		return Ok(false);
677	}
678	match nal[0] & 0x1f {
679		NAL_TYPE_SPS => {
680			InBandCodec::H264.insert_parameter_set(frame_sps, nal)?;
681			Ok(false)
682		}
683		NAL_TYPE_PPS => {
684			InBandCodec::H264.insert_parameter_set(frame_pps, nal)?;
685			Ok(false)
686		}
687		_ => {
688			let len = u32::try_from(nal.len()).map_err(|_| Error::NalTooLarge)?;
689			out.extend_from_slice(&len.to_be_bytes());
690			out.extend_from_slice(nal);
691			Ok(true)
692		}
693	}
694}
695
696/// Real SPS NAL units from 64x64, 25 fps x264 encodes (High profile, 50 Hz VUI tick), for
697/// tests that need a VUI with a bitstream restriction.
698#[cfg(test)]
699pub(crate) mod fixtures {
700	/// A 1440x1080 x264 encode with `setsar=4/3` and `force-cfr=1`, shown 16:9.
701	pub(crate) const SPS_ANAMORPHIC: &[u8] = &[
702		0x67, 0x64, 0x00, 0x28, 0xac, 0xd9, 0x40, 0x5a, 0x02, 0x27, 0xe5, 0xc3, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
703		0x00, 0x00, 0x03, 0x00, 0xca, 0x3c, 0x60, 0xc6, 0x58,
704	];
705	/// A 64x48 x264 encode with extended 7:5 SAR, shown 28:15.
706	pub(crate) const SPS_EXTENDED_SAR: &[u8] = &[
707		0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x44, 0x7b, 0xff, 0x00, 0x07, 0x00, 0x05, 0x10, 0x00, 0x00, 0x03, 0x00,
708		0x10, 0x00, 0x00, 0x03, 0x03, 0x28, 0xf1, 0x22, 0x59, 0x60,
709	];
710	/// `bframes=1:force-cfr=1`: one B-frame per reference (`max_num_reorder_frames` 1) with
711	/// `fixed_frame_rate_flag` set.
712	pub(crate) const SPS_IPB: &[u8] = &[
713		0x67, 0x64, 0x00, 0x0a, 0xac, 0xe4, 0x10, 0x9b, 0x01, 0x10, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03,
714		0x03, 0x28, 0xf1, 0x22, 0x51, 0x20,
715	];
716	/// `bframes=3:b-pyramid=2:force-cfr=1`: a B-pyramid (`max_num_reorder_frames` 2) with
717	/// `fixed_frame_rate_flag` set.
718	pub(crate) const SPS_PYRAMID: &[u8] = &[
719		0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, 0x44, 0x26, 0xc0, 0x44, 0x00, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03,
720		0x00, 0xca, 0x3c, 0x48, 0x96, 0x58,
721	];
722	/// `bframes=1` at x264's default: `max_num_reorder_frames` 1 without `fixed_frame_rate_flag`.
723	pub(crate) const SPS_IPB_VARIABLE: &[u8] = &[
724		0x67, 0x64, 0x00, 0x0a, 0xac, 0xe4, 0x10, 0x9b, 0x01, 0x10, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03,
725		0x03, 0x20, 0xf1, 0x22, 0x51, 0x20,
726	];
727	/// `interlaced=1:tff=1:bframes=0` at 320x240, with `fixed_frame_rate_flag` forced on: the same
728	/// 50 Hz tick, but `frame_mbs_only_flag` 0 leaves `pic_struct` to the slice header.
729	pub(crate) const SPS_FIELD: &[u8] = &[
730		0x67, 0xf4, 0x00, 0x15, 0x91, 0x9d, 0x02, 0x82, 0x1f, 0x89, 0xc0, 0x44, 0x00, 0x00, 0x03, 0x00, 0x04, 0x00,
731		0x00, 0x03, 0x00, 0xca, 0x7c, 0x50, 0xaa, 0x80,
732	];
733	/// `bframes=1:force-cfr=1:nal-hrd=cbr:bitrate=9000:vbv-maxrate=9000:vbv-bufsize=9000`: a
734	/// contribution encoder's 9 Mbit CBR NAL HRD at 9 Mb/s, one second of buffer delay.
735	pub(crate) const SPS_HRD: &[u8] = &[
736		0x67, 0x64, 0x00, 0x1e, 0xac, 0xe4, 0x10, 0x9b, 0x01, 0x10, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03,
737		0x03, 0x2e, 0x04, 0x00, 0x00, 0x89, 0x54, 0x40, 0x00, 0x11, 0x2a, 0x8e, 0x4c, 0x30, 0x07, 0x8b, 0x16, 0x89,
738	];
739	pub(crate) const PPS: &[u8] = &[0x68, 0xeb, 0xe3, 0xcb, 0x22, 0xc0];
740	/// `colorprim=bt709:transfer=bt709:colormatrix=bt709:range=tv` on a Baseline encode: an SDR
741	/// video signal type with a full colour description.
742	pub(crate) const SPS_BT709: &[u8] = &[
743		0x67, 0x42, 0xc0, 0x0a, 0xda, 0x10, 0x9b, 0x01, 0x6a, 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x03, 0x00, 0x80,
744		0x00, 0x00, 0x19, 0x07, 0x89, 0x13, 0x50,
745	];
746	/// The same encode signalling BT.2020 primaries, PQ, and the BT.2020 non-constant matrix.
747	pub(crate) const SPS_HDR10: &[u8] = &[
748		0x67, 0x42, 0xc0, 0x0a, 0xda, 0x10, 0x9b, 0x01, 0x6a, 0x12, 0x20, 0x12, 0x80, 0x00, 0x00, 0x03, 0x00, 0x80,
749		0x00, 0x00, 0x19, 0x07, 0x89, 0x13, 0x50,
750	];
751	/// x264's `mastering-display` SEI for a 1000-nit BT.2020 display with a D65 white point; its
752	/// minimum luminance needs emulation prevention.
753	pub(crate) const SEI_MASTERING: &[u8] = &[
754		0x06, 0x89, 0x18, 0x21, 0x34, 0x9b, 0xaa, 0x19, 0x96, 0x08, 0xfc, 0x8a, 0x48, 0x39, 0x08, 0x3d, 0x13, 0x40,
755		0x42, 0x00, 0x98, 0x96, 0x80, 0x00, 0x00, 0x03, 0x00, 0x32, 0x80,
756	];
757	/// x264's `cll=1000,400` SEI.
758	pub(crate) const SEI_CONTENT_LIGHT: &[u8] = &[0x06, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80];
759}
760
761#[cfg(test)]
762mod tests {
763	use super::*;
764
765	/// Only a VUI with a video signal type adds colour, and its colour description is read whole.
766	#[test]
767	fn sps_color_reads_the_video_signal_type() {
768		let sps_color = |nal: &[u8]| sps_vui(nal)?.color;
769		let sdr = sps_color(fixtures::SPS_BT709).unwrap();
770		assert_eq!(
771			(sdr.primaries, sdr.transfer, sdr.matrix, sdr.range),
772			(Some(1), Some(1), Some(1), Some(hang::catalog::ColorRange::Limited))
773		);
774		let hdr = sps_color(fixtures::SPS_HDR10).unwrap();
775		assert_eq!(
776			(hdr.primaries, hdr.transfer, hdr.matrix, hdr.range),
777			(Some(9), Some(16), Some(9), Some(hang::catalog::ColorRange::Limited))
778		);
779		assert_eq!(sps_color(fixtures::SPS_IPB), None, "a VUI without a video signal type");
780	}
781
782	/// An SPS whose VUI ends early still yields its codec string and size, and declares no VUI.
783	#[test]
784	fn sps_with_a_short_vui_keeps_the_fields_before_it() {
785		let sps: &[u8] = &[
786			0x67, 0x42, 0xc0, 0x1f, 0xda, 0x01, 0x40, 0x16, 0xe9, 0xb8, 0x08, 0x08, 0x0a, 0x00, 0x00, 0x07, 0xd0, 0x00,
787			0x01, 0xd4, 0xc0, 0x80,
788		];
789		assert!(SeqParameterSet::from_bits(crate::codec::annexb::rbsp(sps, 1)).is_err());
790		let parsed = Sps::parse(sps).unwrap();
791		assert_eq!((parsed.profile, parsed.constraints, parsed.level), (0x42, 0xc0, 0x1f));
792		assert_eq!((parsed.coded_width, parsed.coded_height), (1280, 720));
793		assert!(sps_vui(sps).is_none());
794		assert_eq!(sps_interlaced(sps), Some(false));
795	}
796
797	/// Annex B's `trailing_zero_8bits` left on an SPS is not an emulated start code.
798	#[test]
799	fn sps_ignores_trailing_zero_bytes() {
800		let mut padded = fixtures::SPS_IPB.to_vec();
801		padded.extend_from_slice(&[0, 0, 0, 0]);
802		assert_eq!(sps_reorder(&padded), sps_reorder(fixtures::SPS_IPB));
803		assert!(sps_reorder(&padded).is_some());
804	}
805
806	const SC4: &[u8] = &[0, 0, 0, 1];
807
808	#[test]
809	fn sps_reorder_reads_the_vui() {
810		use crate::codec::video::Reorder;
811
812		let fixed = Some((2, 50));
813		assert_eq!(
814			sps_reorder(fixtures::SPS_IPB),
815			Some(Reorder {
816				depth: 1,
817				period: fixed
818			})
819		);
820		assert_eq!(
821			sps_reorder(fixtures::SPS_PYRAMID),
822			Some(Reorder {
823				depth: 2,
824				period: fixed
825			})
826		);
827		assert_eq!(
828			sps_reorder(fixtures::SPS_IPB_VARIABLE),
829			Some(Reorder { depth: 1, period: None })
830		);
831		// The field-capable SPS still declares its depth and tick; only the frame rate needs
832		// `pic_struct` to read it.
833		assert_eq!(
834			sps_reorder(fixtures::SPS_FIELD),
835			Some(Reorder {
836				depth: 0,
837				period: Some((2, 50))
838			})
839		);
840		// Baseline with no VUI declares nothing.
841		assert_eq!(sps_reorder(&[0x67, 0x42, 0xc0, 0x1f, 0xde]), None);
842		// A VUI cut short is no declaration rather than a wrong one.
843		assert_eq!(sps_reorder(&fixtures::SPS_IPB[..fixtures::SPS_IPB.len() - 3]), None);
844	}
845
846	#[test]
847	fn sps_framerate_needs_a_fixed_rate() {
848		assert_eq!(sps_vui(fixtures::SPS_IPB).unwrap().framerate(), Some(25.0));
849		// The same 50 Hz tick without `fixed_frame_rate_flag` is only a ceiling.
850		assert_eq!(sps_vui(fixtures::SPS_IPB_VARIABLE).unwrap().framerate(), None);
851		// A field-capable SPS makes the tick a field or a frame depending on `pic_struct`.
852		assert_eq!(sps_vui(fixtures::SPS_FIELD).unwrap().framerate(), None);
853		assert!(sps_vui(&[0x67, 0x42, 0xc0, 0x1f, 0xde]).is_none());
854	}
855
856	#[test]
857	fn sps_hrd_reads_the_nal_hrd() {
858		use crate::codec::video::{Hrd, Reorder};
859
860		assert_eq!(
861			sps_hrd(fixtures::SPS_HRD),
862			Some(Hrd {
863				bit_rate: 9_000_000,
864				cpb_size: 9_000_000
865			})
866		);
867		// The bitstream restriction follows the HRD in the VUI, so it still reads past it.
868		assert_eq!(
869			sps_reorder(fixtures::SPS_HRD),
870			Some(Reorder {
871				depth: 1,
872				period: Some((2, 50))
873			})
874		);
875		assert_eq!(sps_hrd(fixtures::SPS_IPB), None);
876	}
877
878	fn annexb_frame(nals: &[&[u8]]) -> Bytes {
879		let mut buf = BytesMut::new();
880		for nal in nals {
881			buf.extend_from_slice(SC4);
882			buf.extend_from_slice(nal);
883		}
884		buf.freeze()
885	}
886
887	/// avc1: a length-prefixed access unit with an IDR slice wraps as one keyframe;
888	/// the payload is passed through verbatim.
889	#[test]
890	fn avc1_frame_keyframe() {
891		let idr: &[u8] = &[0x65, 0x88, 0x84, 0x21];
892		let mut au = BytesMut::new();
893		au.extend_from_slice(&(idr.len() as u32).to_be_bytes());
894		au.extend_from_slice(idr);
895
896		let frame = avc1_frame(&au, 4, moq_net::Timestamp::from_micros(0).unwrap()).unwrap();
897		assert!(frame.keyframe);
898		assert_eq!(frame.payload[4..], *idr);
899	}
900
901	/// avc1: a length-prefixed access unit with a non-IDR slice is a delta frame.
902	#[test]
903	fn avc1_frame_delta() {
904		let pslice: &[u8] = &[0x61, 0xe0, 0x12, 0x34];
905		let mut au = BytesMut::new();
906		au.extend_from_slice(&(pslice.len() as u32).to_be_bytes());
907		au.extend_from_slice(pslice);
908
909		let frame = avc1_frame(&au, 4, moq_net::Timestamp::from_micros(0).unwrap()).unwrap();
910		assert!(!frame.keyframe);
911	}
912
913	#[test]
914	fn avc3_strips_sps_pps_and_builds_avcc() {
915		let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
916		let pps = &[0x68, 0xce, 0x3c, 0x80][..];
917		let idr = &[0x65, 0x88, 0x84, 0x21][..];
918
919		let mut tx = Avc1::new();
920		assert!(tx.avcc().is_none());
921
922		let frame = annexb_frame(&[sps, pps, idr]);
923		let out = tx.transform(frame).expect("transform").expect("expected output");
924
925		let avcc = tx.avcc().expect("avcC available").clone();
926		assert_eq!(avcc[0], 1);
927		assert_eq!(avcc[1], sps[1]);
928		assert_eq!(avcc[3], sps[3]);
929
930		let mut expected = BytesMut::new();
931		expected.extend_from_slice(&(idr.len() as u32).to_be_bytes());
932		expected.extend_from_slice(idr);
933		assert_eq!(out.as_ref(), expected.as_ref());
934	}
935
936	#[test]
937	fn avcc_params_roundtrips_build_avcc() {
938		let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f, 0xde]);
939		let pps = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
940
941		let avcc = build_avcc(std::slice::from_ref(&sps), std::slice::from_ref(&pps)).unwrap();
942		let (length_size, params) = avcc_params(&avcc).unwrap();
943
944		assert_eq!(length_size, 4);
945		assert_eq!(params.len(), 2);
946		assert_eq!(params[0], sps);
947		assert_eq!(params[1], pps);
948	}
949
950	#[test]
951	fn build_avcc_layout_is_unchanged() {
952		let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f, 0xde]);
953		let pps = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
954
955		let avcc = build_avcc(std::slice::from_ref(&sps), std::slice::from_ref(&pps)).unwrap();
956		assert_eq!(
957			avcc.as_ref(),
958			&[
959				0x01, 0x42, 0xc0, 0x1f, 0xff, 0xe1, 0x00, 0x05, 0x67, 0x42, 0xc0, 0x1f, 0xde, 0x01, 0x00, 0x04, 0x68,
960				0xce, 0x3c, 0x80,
961			]
962		);
963	}
964
965	#[test]
966	fn avcc_parse_reads_past_the_high_extension() {
967		let sps = fixtures::SPS_ANAMORPHIC;
968		let avcc = encode_avcc(&mp4_atom::Avcc {
969			configuration_version: 1,
970			avc_profile_indication: sps[1],
971			profile_compatibility: sps[2],
972			avc_level_indication: sps[3],
973			length_size: 4,
974			sequence_parameter_sets: vec![sps.to_vec()],
975			picture_parameter_sets: vec![fixtures::PPS.to_vec()],
976			ext: Some(mp4_atom::AvccExt::default()),
977		});
978
979		let parsed = Avcc::parse(&avcc).unwrap();
980		assert_eq!(parsed.profile, 100);
981		assert_eq!(parsed.length_size, 4);
982		assert_eq!(parsed.sps, vec![Bytes::from_static(sps)]);
983		assert_eq!(parsed.pps, vec![Bytes::from_static(fixtures::PPS)]);
984		assert_eq!((parsed.coded_width, parsed.coded_height), (Some(1440), Some(1080)));
985	}
986
987	#[test]
988	fn avcc_parse_refuses_other_versions_and_partial_extensions() {
989		let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f, 0xde]);
990		let pps = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
991		let avcc = build_avcc(std::slice::from_ref(&sps), std::slice::from_ref(&pps)).unwrap();
992
993		let mut version = avcc.to_vec();
994		version[0] = 0;
995		assert!(matches!(Avcc::parse(&version), Err(Error::AvccVersion(0))));
996
997		// One trailing byte cannot be the 4-byte High-profile extension.
998		let mut partial = avcc.to_vec();
999		partial.push(0xfd);
1000		assert!(matches!(Avcc::parse(&partial), Err(Error::AvccTruncated)));
1001
1002		assert!(matches!(
1003			Avcc::parse(&avcc[..avcc.len() - 1]),
1004			Err(Error::AvccTruncated)
1005		));
1006		assert!(matches!(Avcc::parse(&avcc[..6]), Err(Error::AvccTooShort)));
1007	}
1008
1009	#[test]
1010	fn build_avcc_carries_multiple_pps() {
1011		// A source with one SPS and two PPS (ids 0 and 1): the avcC must keep both,
1012		// in order, so slices referencing either id stay decodable.
1013		let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f, 0xde]);
1014		let pps0 = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
1015		let pps1 = Bytes::from_static(&[0x68, 0x4e, 0x3c, 0x80]);
1016
1017		let avcc = build_avcc(std::slice::from_ref(&sps), &[pps0.clone(), pps1.clone()]).unwrap();
1018		// numOfSequenceParameterSets is the low 5 bits of byte 5.
1019		assert_eq!(avcc[5] & 0x1f, 1);
1020
1021		let (_, params) = avcc_params(&avcc).unwrap();
1022		assert_eq!(params, vec![sps, pps0, pps1]);
1023	}
1024
1025	#[test]
1026	fn avc3_keyframe_with_two_pps_keeps_both() {
1027		// One keyframe carrying both PPS: the synthesized avcC keeps both, in order.
1028		let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1029		let pps0 = &[0x68, 0xce, 0x3c, 0x80][..];
1030		let pps1 = &[0x68, 0x4e, 0x3c, 0x80][..];
1031		let idr = &[0x65, 0x88][..];
1032
1033		let mut tx = Avc1::new();
1034		tx.transform(annexb_frame(&[sps, pps0, pps1, idr])).unwrap();
1035
1036		let avcc = tx.avcc().expect("avcC available");
1037		let (_, params) = avcc_params(avcc).unwrap();
1038		assert_eq!(
1039			params.iter().map(|p| p.as_ref()).collect::<Vec<_>>(),
1040			vec![sps, pps0, pps1]
1041		);
1042	}
1043
1044	#[test]
1045	fn avc3_reinit_drops_superseded_pps() {
1046		// A later keyframe presents a different PPS set: the avcC adopts the new set
1047		// and drops the old one rather than accumulating both forever.
1048		let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1049		let pps0 = &[0x68, 0xce, 0x3c, 0x80][..];
1050		let pps1 = &[0x68, 0x4e, 0x3c, 0x80][..];
1051		let idr = &[0x65, 0x88][..];
1052
1053		let mut tx = Avc1::new();
1054		tx.transform(annexb_frame(&[sps, pps0, idr])).unwrap();
1055		tx.transform(annexb_frame(&[sps, pps1, idr])).unwrap();
1056
1057		let avcc = tx.avcc().expect("avcC available");
1058		let (_, params) = avcc_params(avcc).unwrap();
1059		assert_eq!(
1060			params.iter().map(|p| p.as_ref()).collect::<Vec<_>>(),
1061			vec![sps, pps1],
1062			"reinit must drop the superseded PPS"
1063		);
1064	}
1065
1066	#[test]
1067	fn avc3_repeated_pps_id_keeps_the_last() {
1068		// Two PPS defining id 0 in one keyframe: the later replaces the earlier, as in a decoder.
1069		let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1070		let pps_a = &[0x68, 0xce, 0x3c, 0x80][..];
1071		let pps_b = &[0x68, 0xce, 0x38, 0x80][..];
1072		let idr = &[0x65, 0x88][..];
1073
1074		let mut tx = Avc1::new();
1075		tx.transform(annexb_frame(&[sps, pps_a, pps_b, idr])).unwrap();
1076
1077		let (_, params) = avcc_params(tx.avcc().expect("avcC available")).unwrap();
1078		assert_eq!(params.iter().map(|p| p.as_ref()).collect::<Vec<_>>(), vec![sps, pps_b]);
1079	}
1080
1081	#[test]
1082	fn avc3_parameter_only_frame_returns_none() {
1083		let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1084		let pps = &[0x68, 0xce, 0x3c, 0x80][..];
1085
1086		let mut tx = Avc1::new();
1087		let frame = annexb_frame(&[sps, pps]);
1088		assert!(tx.transform(frame).unwrap().is_none());
1089		assert!(tx.avcc().is_some());
1090	}
1091
1092	#[test]
1093	fn avc3_subsequent_frame_uses_cached_avcc() {
1094		let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1095		let pps = &[0x68, 0xce, 0x3c, 0x80][..];
1096		let idr = &[0x65, 0x88][..];
1097		let p = &[0x61, 0xe0, 0x12][..];
1098
1099		let mut tx = Avc1::new();
1100		tx.transform(annexb_frame(&[sps, pps, idr])).unwrap();
1101		let avcc_v1 = tx.avcc().unwrap().clone();
1102
1103		let out = tx.transform(annexb_frame(&[p])).unwrap().unwrap();
1104		assert_eq!(tx.avcc().unwrap(), &avcc_v1);
1105		let mut expected = BytesMut::new();
1106		expected.extend_from_slice(&(p.len() as u32).to_be_bytes());
1107		expected.extend_from_slice(p);
1108		assert_eq!(out.as_ref(), expected.as_ref());
1109	}
1110
1111	fn decode_avcc(bytes: &Bytes) -> mp4_atom::Avcc {
1112		use mp4_atom::Atom;
1113		mp4_atom::Avcc::decode_body(&mut std::io::Cursor::new(bytes.as_ref())).unwrap()
1114	}
1115
1116	#[test]
1117	fn catalog_avcc_baseline_has_no_extension() {
1118		let h264 = hang::catalog::H264 {
1119			profile: 0x42,
1120			constraints: 0xc0,
1121			level: 0x1f,
1122			inline: true,
1123		};
1124		let avcc = decode_avcc(&catalog_avcc(&h264).unwrap());
1125		assert_eq!(avcc.avc_profile_indication, 0x42);
1126		assert_eq!(avcc.profile_compatibility, 0xc0);
1127		assert_eq!(avcc.avc_level_indication, 0x1f);
1128		assert_eq!(avcc.length_size, 4);
1129		assert!(avcc.sequence_parameter_sets.is_empty());
1130		assert!(avcc.picture_parameter_sets.is_empty());
1131		assert!(avcc.ext.is_none());
1132	}
1133
1134	#[test]
1135	fn catalog_avcc_high_states_420_8bit() {
1136		let h264 = hang::catalog::H264 {
1137			profile: 100,
1138			constraints: 0,
1139			level: 0x28,
1140			inline: true,
1141		};
1142		let avcc = decode_avcc(&catalog_avcc(&h264).unwrap());
1143		assert_eq!(avcc.avc_profile_indication, 100);
1144		assert!(avcc.sequence_parameter_sets.is_empty());
1145		assert_eq!(
1146			avcc.ext,
1147			Some(mp4_atom::AvccExt {
1148				chroma_format: 1,
1149				bit_depth_luma: 8,
1150				bit_depth_chroma: 8,
1151				sequence_parameter_sets_ext: Vec::new(),
1152			})
1153		);
1154	}
1155
1156	#[test]
1157	fn catalog_avcc_refuses_profiles_the_string_cannot_describe() {
1158		for profile in [110, 122, 244, 44, 144] {
1159			let h264 = hang::catalog::H264 {
1160				profile,
1161				constraints: 0,
1162				level: 0x1f,
1163				inline: true,
1164			};
1165			assert!(catalog_avcc(&h264).is_none(), "profile {profile}");
1166		}
1167		let out_of_band = hang::catalog::H264 {
1168			profile: 0x42,
1169			constraints: 0xc0,
1170			level: 0x1f,
1171			inline: false,
1172		};
1173		assert!(catalog_avcc(&out_of_band).is_none());
1174	}
1175}