Skip to main content

moq_mux/codec/
annexb.rs

1mod export;
2
3pub(crate) use export::{Codec, Convert, Export};
4
5use std::collections::BTreeMap;
6
7use bytes::{Buf, Bytes, BytesMut};
8
9/// A bit reader over an H.264 or H.265 parameter set or SEI NAL unit's RBSP: the bytes after its
10/// `header`-byte NAL header, with emulation prevention removed as they are read.
11///
12/// These NAL units end in `rbsp_trailing_bits`, so a trailing zero byte is Annex B's
13/// `trailing_zero_8bits` left behind by the splitter, and is dropped rather than refused as an
14/// emulated start code.
15pub(crate) fn rbsp(nal: &[u8], header: usize) -> h264_reader::rbsp::BitReader<h264_reader::rbsp::ByteReader<&[u8]>> {
16	h264_reader::rbsp::BitReader::new(rbsp_bytes_reader(nal, header))
17}
18
19/// The RBSP bytes of an H.264 or H.265 parameter set or SEI NAL unit, as [`rbsp`] reads them.
20/// `None` when the payload holds a byte sequence emulation prevention forbids.
21pub(crate) fn rbsp_bytes(nal: &[u8], header: usize) -> Option<Vec<u8>> {
22	use std::io::Read;
23
24	let mut out = Vec::with_capacity(nal.len());
25	rbsp_bytes_reader(nal, header).read_to_end(&mut out).ok()?;
26	Some(out)
27}
28
29/// The `(payloadType, payload)` of each message in an H.264 or H.265 SEI RBSP, which share the
30/// `sei_message` syntax. A malformed message ends the iteration. Unlike h264-reader's
31/// `SeiReader`, a payload of any size is skipped without a copy.
32pub(crate) fn sei_messages(rbsp: &[u8]) -> impl Iterator<Item = (u32, &[u8])> {
33	let mut buf = rbsp;
34	std::iter::from_fn(move || {
35		// Each message needs at least a type and size byte; the last byte is the RBSP stop bit.
36		if buf.len() <= 2 {
37			return None;
38		}
39		let kind = sei_value(&mut buf)?;
40		let size = sei_value(&mut buf)?;
41		let (payload, rest) = buf.split_at_checked(size as usize)?;
42		buf = rest;
43		Some((kind, payload))
44	})
45}
46
47/// An SEI `payloadType` or `payloadSize`: a run of 0xFF bytes, each adding 255, then the remainder.
48fn sei_value(buf: &mut &[u8]) -> Option<u32> {
49	let mut value = 0u32;
50	loop {
51		let (&byte, rest) = buf.split_first()?;
52		*buf = rest;
53		value = value.checked_add(byte.into())?;
54		if byte != 0xFF {
55			return Some(value);
56		}
57	}
58}
59
60fn rbsp_bytes_reader(nal: &[u8], header: usize) -> h264_reader::rbsp::ByteReader<&[u8]> {
61	let payload = nal.get(header..).unwrap_or_default();
62	let end = payload.iter().rposition(|&b| b != 0).map_or(0, |last| last + 1);
63	h264_reader::rbsp::ByteReader::without_skip(&payload[..end])
64}
65
66/// The four-byte Annex B start code preceding a NAL unit.
67pub const START_CODE: Bytes = Bytes::from_static(&[0, 0, 0, 1]);
68
69/// Annex B parsing errors.
70#[derive(Debug, Clone, thiserror::Error)]
71#[non_exhaustive]
72pub enum Error {
73	/// The buffer does not begin with an Annex B start code.
74	#[error("missing Annex B start code")]
75	MissingStartCode,
76
77	/// The start code has an invalid byte sequence.
78	#[error("invalid Annex B start code")]
79	InvalidStartCode,
80
81	/// The NAL length prefix size is outside one through four bytes.
82	#[error("invalid avc1/hvc1 length size {0}")]
83	InvalidLengthSize(usize),
84
85	/// A NAL length prefix or payload extends past the buffer.
86	#[error("truncated length-prefixed NAL unit")]
87	Truncated,
88
89	/// The NAL payload length does not fit a four-byte prefix.
90	#[error("NAL too large for a 4-byte length prefix")]
91	NalTooLarge,
92
93	/// A keyframe has neither an inline nor a retained parameter set of the named type.
94	#[error("keyframe has no {0}, in the access unit or earlier in the track")]
95	MissingParameterSet(&'static str),
96
97	/// A parameter set NAL of this type ends before the id it defines.
98	#[error("parameter set NAL type {0} has no readable id")]
99	ParameterSetId(u8),
100}
101
102/// A result using this module's error type.
103pub type Result<T> = std::result::Result<T, Error>;
104
105/// True when the buffer is an out-of-band config record (avcC / hvcC) rather than an
106/// Annex-B elementary stream: a 3- or 4-byte start code means Annex-B, anything else
107/// non-empty is a config record. An empty buffer is Annex-B, since there's no record to
108/// parse and the in-band shapes self-initialize from the first keyframe (e.g. moqsink
109/// hands an empty init for inline-parameter-set streams).
110pub(crate) fn is_config_record(bytes: &[u8]) -> bool {
111	!(bytes.is_empty() || matches!(bytes, [0, 0, 1, ..]) || matches!(bytes, [0, 0, 0, 1, ..]))
112}
113
114/// Iterate the NAL units of a length-prefixed (avc1 / hvc1) access unit, where each NAL
115/// is preceded by a `length_size`-byte big-endian length.
116///
117/// Yields [`Error::Truncated`] as the final item when a prefix or length runs past the end
118/// of the buffer: callers that must reject a malformed AU propagate it, while a lenient
119/// scan can stop at it (`.map_while(Result::ok)`).
120pub(crate) fn length_prefixed_nals(data: &[u8], length_size: usize) -> Result<LengthPrefixedNals<'_>> {
121	if !(1..=4).contains(&length_size) {
122		return Err(Error::InvalidLengthSize(length_size));
123	}
124	Ok(LengthPrefixedNals { data, length_size })
125}
126
127/// The iterator [`length_prefixed_nals`] returns.
128#[derive(Clone)]
129pub(crate) struct LengthPrefixedNals<'a> {
130	data: &'a [u8],
131	length_size: usize,
132}
133
134impl<'a> LengthPrefixedNals<'a> {
135	/// Take a leading access unit delimiter, which must stay ahead of injected parameter sets.
136	pub(crate) fn take_delimiter(&mut self, codec: InBandCodec) -> Result<Option<&'a [u8]>> {
137		if let Some(nal) = self.clone().next().transpose()?
138			&& !nal.is_empty()
139			&& codec.nal_type(nal) == codec.delimiter()
140		{
141			return self.next().transpose();
142		}
143		Ok(None)
144	}
145}
146
147impl<'a> Iterator for LengthPrefixedNals<'a> {
148	type Item = Result<&'a [u8]>;
149
150	fn next(&mut self) -> Option<Self::Item> {
151		if self.data.is_empty() {
152			return None;
153		}
154		if self.data.len() < self.length_size {
155			self.data = &[];
156			return Some(Err(Error::Truncated));
157		}
158		let (prefix, rest) = self.data.split_at(self.length_size);
159		let len = prefix.iter().fold(0usize, |acc, &byte| (acc << 8) | byte as usize);
160		if rest.len() < len {
161			self.data = &[];
162			return Some(Err(Error::Truncated));
163		}
164		let (nal, rest) = rest.split_at(len);
165		self.data = rest;
166		Some(Ok(nal))
167	}
168}
169
170/// Convert a length-prefixed NALU payload (avc1 / hvc1 wire shape) to Annex-B,
171/// injecting `prefix` bytes (typically VPS/SPS/PPS NAL units already in Annex-B
172/// form) after a leading access unit delimiter, or before the other NAL units.
173pub fn from_length_prefixed(payload: &[u8], length_size: usize, prefix: Option<&[u8]>) -> Result<Bytes> {
174	let mut out = BytesMut::with_capacity(payload.len() + prefix.map(|p| p.len()).unwrap_or(0) + 16);
175	let mut nals = length_prefixed_nals(payload, length_size)?;
176	if let Some(prefix) = prefix {
177		let codec = after_start_code(prefix)
178			.ok()
179			.flatten()
180			.and_then(|start| prefix.get(start))
181			.and_then(|&header| InBandCodec::of_parameter_set(header));
182		if let Some(codec) = codec
183			&& let Some(aud) = nals.take_delimiter(codec)?
184		{
185			out.extend_from_slice(&START_CODE);
186			out.extend_from_slice(aud);
187		}
188		out.extend_from_slice(prefix);
189	}
190	for nal in nals {
191		out.extend_from_slice(&START_CODE);
192		out.extend_from_slice(nal?);
193	}
194	Ok(out.freeze())
195}
196
197/// Concatenate `start_code | nal` for every NAL in `nals` and freeze the
198/// result. Used to build a keyframe parameter-set prefix for an Annex-B
199/// elementary stream.
200pub fn build_prefix<'a, I: IntoIterator<Item = &'a Bytes>>(nals: I) -> Bytes {
201	let nals: Vec<&Bytes> = nals.into_iter().collect();
202	let total: usize = nals.iter().map(|n| n.len() + START_CODE.len()).sum();
203	let mut out = BytesMut::with_capacity(total);
204	for nal in nals {
205		out.extend_from_slice(&START_CODE);
206		out.extend_from_slice(nal);
207	}
208	out.freeze()
209}
210
211/// Parameter sets of one type keyed by the layer (H.265 `nuh_layer_id`, always 0 for H.264) and
212/// id they define, base layer first and then in id order.
213///
214/// A later set with a layer and id replaces the earlier one, as it does in a decoder, so a source
215/// may define several (e.g. two PPS that slices reference by id) and a repeated or redefined id
216/// costs one entry rather than a growing list. Each layer numbers its own sets, so an enhancement
217/// layer's never replaces the base layer's.
218pub(crate) type ParameterSets = BTreeMap<(u8, u32), Bytes>;
219
220/// Adopt the parameter sets of one type that an access unit or init defined: each layer it
221/// defined any for replaces that layer's retained sets, dropping ids the new configuration no
222/// longer uses, while every other layer keeps its own. An empty `sets` changes nothing.
223pub(crate) fn adopt_parameter_sets(retained: &mut ParameterSets, mut sets: ParameterSets) {
224	let defined = layers(&sets);
225	retained.retain(|&(layer, _), _| defined & 1 << layer == 0);
226	// Appending to an emptied map moves `sets` in rather than inserting each set.
227	retained.append(&mut sets);
228}
229
230/// The layers `sets` holds any for, as a bitmask: `nuh_layer_id` has six bits.
231fn layers(sets: &ParameterSets) -> u64 {
232	sets.keys().fold(0, |mask, &(layer, _)| mask | 1 << layer)
233}
234
235/// The NAL syntax an [`InBand`] transform reads.
236#[derive(Debug, Clone, Copy)]
237pub(crate) enum InBandCodec {
238	H264,
239	H265,
240}
241
242impl InBandCodec {
243	/// The parameter-set NAL types, each referencing only those before it.
244	fn parameter_sets(self) -> &'static [(u8, &'static str)] {
245		match self {
246			Self::H264 => &[(7, "SPS"), (8, "PPS")],
247			Self::H265 => &[(32, "VPS"), (33, "SPS"), (34, "PPS")],
248		}
249	}
250
251	/// The codec whose parameter-set NAL begins with `header`.
252	///
253	/// NAL headers overlap between codecs (an H.265 slice can look like an H.264 AUD), so
254	/// only a parameter set identifies one.
255	fn of_parameter_set(header: u8) -> Option<Self> {
256		match (header & 0x1f, (header >> 1) & 0x3f) {
257			(7 | 8, _) => Some(Self::H264),
258			(_, 32..=34) => Some(Self::H265),
259			_ => None,
260		}
261	}
262
263	/// Insert parameter set `nal` (header included) under the layer and id it defines, replacing
264	/// any earlier set with both.
265	pub(crate) fn insert_parameter_set(self, sets: &mut ParameterSets, nal: &Bytes) -> Result<()> {
266		use h264_reader::rbsp::BitRead;
267
268		let nal_type = self.nal_type(nal);
269		let (header, layer) = match self {
270			Self::H264 => (1, 0),
271			Self::H265 => (
272				2,
273				crate::codec::h265::layer_id(nal).ok_or(Error::ParameterSetId(nal_type))?,
274			),
275		};
276		let r = &mut rbsp(nal, header);
277		let id = match (self, nal_type) {
278			// seq_parameter_set_id follows profile_idc, the constraint flags, and level_idc.
279			(Self::H264, 7) => r
280				.skip(24, "profile_idc..level_idc")
281				.and_then(|()| r.read_ue("seq_parameter_set_id")),
282			// pic_parameter_set_id opens a PPS in both codecs.
283			(Self::H264, 8) | (Self::H265, 34) => r.read_ue("pic_parameter_set_id"),
284			(Self::H265, 32) => r.read::<4, u32>("vps_video_parameter_set_id"),
285			(Self::H265, 33) => crate::codec::h265::sps_id(r, layer),
286			_ => return Err(Error::ParameterSetId(nal_type)),
287		};
288		sets.insert((layer, id.map_err(|_| Error::ParameterSetId(nal_type))?), nal.clone());
289		Ok(())
290	}
291
292	/// Replace each `retained` parameter-set type, in VPS, SPS, PPS order, with the sets a complete
293	/// Annex-B init defines. A type the init omits keeps its retained sets.
294	///
295	/// Each init replaces the last one's sets rather than accumulating onto them, as a keyframe's
296	/// inline sets do in [`reconcile_keyframe_params`].
297	pub(crate) fn adopt_init(self, data: &[u8], retained: &mut [&mut ParameterSets]) -> Result<()> {
298		let types = self.parameter_sets();
299		debug_assert_eq!(types.len(), retained.len());
300		let mut sets = vec![ParameterSets::new(); types.len()];
301		for nal in complete_nals(data)? {
302			if nal.is_empty() {
303				continue;
304			}
305			let nal_type = self.nal_type(&nal);
306			if let Some(index) = types.iter().position(|&(ty, _)| ty == nal_type) {
307				self.insert_parameter_set(&mut sets[index], &nal)?;
308			}
309		}
310		for (retained, set) in retained.iter_mut().zip(sets) {
311			adopt_parameter_sets(retained, set);
312		}
313		Ok(())
314	}
315
316	fn delimiter(self) -> u8 {
317		match self {
318			Self::H264 => 9,
319			Self::H265 => 35,
320		}
321	}
322
323	fn nal_type(self, nal: &[u8]) -> u8 {
324		match self {
325			Self::H264 => nal[0] & 0x1f,
326			Self::H265 => (nal[0] >> 1) & 0x3f,
327		}
328	}
329
330	/// A coded slice, so the access unit is a picture.
331	fn is_vcl(self, nal: &[u8]) -> bool {
332		match self {
333			Self::H264 => (1..=5).contains(&self.nal_type(nal)),
334			Self::H265 => self.nal_type(nal) < 32,
335		}
336	}
337}
338
339/// Length-prefixes Annex-B access units with their parameter sets kept in the
340/// sample, for an avc3 or hev1 track whose sample entry lists none.
341///
342/// A keyframe is the only place a receiver can join, so it always carries every
343/// parameter-set type, in dependency order (VPS, SPS, PPS) right after any access
344/// unit delimiter. A type or layer the access unit omitted is the last one seen. A type
345/// it carried replaces every cached set of that type in each layer it carried, so a
346/// source that spreads several PPS ids across access units keeps only the last.
347pub(crate) struct InBand {
348	codec: InBandCodec,
349	/// The active sets of each type, in [`InBandCodec::parameter_sets`] order.
350	active: [ParameterSets; 3],
351}
352
353impl InBand {
354	pub fn new(codec: InBandCodec) -> Self {
355		Self {
356			codec,
357			active: Default::default(),
358		}
359	}
360
361	/// Returns `None` for an access unit with no coded slice, as `Avc1` and `Hvc1`
362	/// do; its parameter sets are kept for the next keyframe.
363	pub fn transform(&mut self, payload: Bytes, keyframe: bool) -> Result<Option<Bytes>> {
364		let codec = self.codec;
365		let kinds = codec.parameter_sets();
366		let mut buf = payload;
367		let mut iter = NalIterator::new(&mut buf);
368		let mut nals = Vec::new();
369		while let Some(nal) = iter.next().transpose()? {
370			nals.push(nal);
371		}
372		nals.extend(iter.flush()?);
373		nals.retain(|nal| !nal.is_empty());
374
375		let kind = |nal: &Bytes| {
376			let nal_type = codec.nal_type(nal);
377			kinds.iter().position(|(t, _)| *t == nal_type)
378		};
379		let mut sets: [ParameterSets; 3] = Default::default();
380		for nal in &nals {
381			if let Some(index) = kind(nal) {
382				codec.insert_parameter_set(&mut sets[index], nal)?;
383			}
384		}
385		for (active, set) in self.active.iter_mut().zip(sets) {
386			adopt_parameter_sets(active, set);
387		}
388		if !nals.iter().any(|nal| codec.is_vcl(nal)) {
389			return Ok(None);
390		}
391
392		let mut out = BytesMut::with_capacity(nals.iter().map(|nal| nal.len() + 4).sum());
393		if !keyframe {
394			for nal in &nals {
395				length_prefix(&mut out, nal)?;
396			}
397			return Ok(Some(out.freeze()));
398		}
399
400		let delimiter = codec.delimiter();
401		for nal in nals.iter().filter(|nal| codec.nal_type(nal) == delimiter) {
402			length_prefix(&mut out, nal)?;
403		}
404		for ((_, name), active) in kinds.iter().zip(&self.active) {
405			if active.is_empty() {
406				return Err(Error::MissingParameterSet(name));
407			}
408			for nal in active.values() {
409				length_prefix(&mut out, nal)?;
410			}
411		}
412		for nal in nals
413			.iter()
414			.filter(|nal| kind(nal).is_none() && codec.nal_type(nal) != delimiter)
415		{
416			length_prefix(&mut out, nal)?;
417		}
418		Ok(Some(out.freeze()))
419	}
420}
421
422fn length_prefix(out: &mut BytesMut, nal: &[u8]) -> Result<()> {
423	let len = u32::try_from(nal.len()).map_err(|_| Error::NalTooLarge)?;
424	out.extend_from_slice(&len.to_be_bytes());
425	out.extend_from_slice(nal);
426	Ok(())
427}
428
429/// Reconcile the retained parameter sets with what a keyframe access unit carried
430/// inline, called when the keyframe slice is reached or, to see every inline set, when
431/// the access unit closes. `retained` and `seen` hold
432/// each parameter-set type in dependency order (VPS, SPS, PPS).
433///
434/// - Each type and layer the AU presented sets for adopts them as its retained
435///   sets, dropping any the new GOP no longer uses (a mid-stream reinit).
436/// - When any retained type or layer is missing from the AU, its parameter sets are
437///   rewritten as every retained set in dependency order, at the first inline one or
438///   before the first slice, so a receiver tuning in at this keyframe still gets them all
439///   and each after those it references.
440///
441/// `seen` is this AU's inline NALs (already appended to `chunks`); `retained` is
442/// the cross-GOP set re-injected on bare keyframes.
443pub(crate) fn reconcile_keyframe_params(
444	codec: InBandCodec,
445	chunks: &mut BytesMut,
446	retained: &mut [&mut ParameterSets],
447	seen: &mut [&mut ParameterSets],
448) -> Result<()> {
449	let mut missing = false;
450	for (retained, seen) in retained.iter_mut().zip(seen.iter_mut()) {
451		missing |= layers(retained) & !layers(seen) != 0;
452		adopt_parameter_sets(retained, std::mem::take(*seen));
453		seen.clone_from(retained);
454	}
455	if !missing {
456		return Ok(());
457	}
458
459	let block = build_prefix(retained.iter().flat_map(|sets| sets.values()));
460	let types = codec.parameter_sets();
461	let au = std::mem::take(chunks);
462	let mut injected = false;
463	for nal in complete_nals(&au)? {
464		if nal.is_empty() {
465			continue;
466		}
467		let set = types.iter().any(|&(ty, _)| ty == codec.nal_type(&nal));
468		if (set || codec.is_vcl(&nal)) && !std::mem::replace(&mut injected, true) {
469			chunks.extend_from_slice(&block);
470		}
471		if set {
472			continue;
473		}
474		chunks.extend_from_slice(&START_CODE);
475		chunks.extend_from_slice(&nal);
476	}
477	if !injected {
478		chunks.extend_from_slice(&block);
479	}
480	Ok(())
481}
482
483/// Every NAL in a complete Annex-B buffer, including the final one that no start code terminates.
484pub(crate) fn complete_nals(data: &[u8]) -> Result<Vec<Bytes>> {
485	let mut buf = Bytes::copy_from_slice(data);
486	let mut iter = NalIterator::new(&mut buf);
487	let mut nals = iter.by_ref().collect::<Result<Vec<_>>>()?;
488	nals.extend(iter.flush()?);
489	Ok(nals)
490}
491
492/// Iterates complete Annex B NAL units, leaving an unterminated final unit for `flush`.
493pub struct NalIterator<'a, T: Buf + AsRef<[u8]> + 'a> {
494	buf: &'a mut T,
495	start: Option<usize>,
496}
497
498impl<'a, T: Buf + AsRef<[u8]> + 'a> NalIterator<'a, T> {
499	/// Read NAL units from a buffer that begins with an Annex B start code.
500	pub fn new(buf: &'a mut T) -> Self {
501		Self { buf, start: None }
502	}
503
504	/// Assume the buffer ends with a NAL unit and flush it.
505	/// This is more efficient because we cache the last "start" code position.
506	pub fn flush(self) -> Result<Option<Bytes>> {
507		let start = match self.start {
508			Some(start) => start,
509			None => {
510				let Some(start) = after_start_code(self.buf.as_ref())? else {
511					return Ok(None);
512				};
513				start
514			}
515		};
516
517		self.buf.advance(start);
518
519		let nal = self.buf.copy_to_bytes(self.buf.remaining());
520		Ok(Some(nal))
521	}
522}
523
524impl<'a, T: Buf + AsRef<[u8]> + 'a> Iterator for NalIterator<'a, T> {
525	type Item = Result<Bytes>;
526
527	fn next(&mut self) -> Option<Self::Item> {
528		let start = match self.start {
529			Some(start) => start,
530			None => match after_start_code(self.buf.as_ref()).transpose()? {
531				Ok(start) => start,
532				Err(err) => return Some(Err(err)),
533			},
534		};
535
536		let (size, new_start) = find_start_code(&self.buf.as_ref()[start..])?;
537		self.buf.advance(start);
538
539		let nal = self.buf.copy_to_bytes(size);
540		self.start = Some(new_start);
541		Some(Ok(nal))
542	}
543}
544
545/// Rewrite a length-prefixed NALU buffer (avc1/hvc1 sample, each NAL preceded
546/// by a `length_size`-byte big-endian length) into Annex-B by replacing every
547/// length prefix with a 4-byte start code. This is the inverse of the
548/// length-prefixing done by [`crate::codec::h264::Avc1`] / [`crate::codec::h265::Hvc1`].
549pub fn length_prefixed_to_annexb(data: &[u8], length_size: usize, out: &mut Vec<u8>) -> Result<()> {
550	for nal in length_prefixed_nals(data, length_size)? {
551		out.extend_from_slice(&START_CODE);
552		out.extend_from_slice(nal?);
553	}
554	Ok(())
555}
556
557/// Return the leading start code size, or `None` if more bytes are needed.
558pub fn after_start_code(b: &[u8]) -> Result<Option<usize>> {
559	if b.len() < 3 {
560		return Ok(None);
561	}
562
563	// NOTE: We have to check every byte, so the `find_start_code` optimization doesn't matter.
564	if b[0] != 0 || b[1] != 0 {
565		return Err(Error::MissingStartCode);
566	}
567
568	match b[2] {
569		0 if b.len() < 4 => Ok(None),
570		0 if b[3] != 1 => Err(Error::MissingStartCode),
571		0 => Ok(Some(4)),
572		1 => Ok(Some(3)),
573		_ => Err(Error::InvalidStartCode),
574	}
575}
576
577/// Return the byte offset and size of the first start code in the buffer.
578//
579// Both forms share the `0 0 1` suffix (3-byte is `0 0 1`, 4-byte is `0 0 0 1`), so a single
580// SIMD-accelerated substring search for `0 0 1` finds the core. We then peek one byte back to
581// decide whether a leading zero promotes it to a 4-byte code.
582pub fn find_start_code(b: &[u8]) -> Option<(usize, usize)> {
583	let core = memchr::memmem::find(b, &[0, 0, 1])?;
584	if core > 0 && b[core - 1] == 0 {
585		Some((core - 1, 4))
586	} else {
587		Some((core, 3))
588	}
589}
590
591#[cfg(test)]
592mod tests {
593	use super::*;
594
595	// Tests for from_length_prefixed - converts avc1/hvc1 to Annex-B,
596	// with optional SPS/PPS prefix injection on keyframes.
597
598	#[test]
599	fn from_length_prefixed_no_prefix() {
600		// One 4-byte length, then 2-byte NAL `0x65 0x88` (an H.264 IDR slice).
601		let payload = &[0, 0, 0, 2, 0x65, 0x88];
602		let out = from_length_prefixed(payload, 4, None).unwrap();
603		assert_eq!(out.as_ref(), &[0, 0, 0, 1, 0x65, 0x88]);
604	}
605
606	#[test]
607	fn from_length_prefixed_with_prefix_injects_verbatim() {
608		// SPS+PPS prefix built by `build_prefix` (start_code + sps_nal + start_code + pps_nal).
609		let sps = Bytes::from_static(&[0x67, 0x42, 0xc0, 0x1f]);
610		let pps = Bytes::from_static(&[0x68, 0xce, 0x3c, 0x80]);
611		let prefix = build_prefix([&sps, &pps]);
612		assert_eq!(
613			prefix.as_ref(),
614			&[
615				0, 0, 0, 1, 0x67, 0x42, 0xc0, 0x1f, // start_code + SPS
616				0, 0, 0, 1, 0x68, 0xce, 0x3c, 0x80, // start_code + PPS
617			]
618		);
619
620		// One length-prefixed IDR slice.
621		let payload = &[0, 0, 0, 2, 0x65, 0x88];
622		let out = from_length_prefixed(payload, 4, Some(&prefix)).unwrap();
623
624		// Output must start with the prefix byte-for-byte, then the slice in Annex-B form.
625		assert_eq!(&out[..prefix.len()], prefix.as_ref());
626		assert_eq!(&out[prefix.len()..], &[0, 0, 0, 1, 0x65, 0x88]);
627	}
628
629	#[test]
630	fn from_length_prefixed_keeps_aud_first() {
631		for (params, aud, slice) in [
632			(
633				vec![vec![0x67, 0x42], vec![0x68, 0xce]],
634				vec![0x09, 0x10],
635				vec![0x65, 0x88],
636			),
637			(
638				vec![vec![0x40, 1], vec![0x42, 1], vec![0x44, 1]],
639				vec![0x46, 1, 0x10],
640				vec![0x26, 1, 0x88],
641			),
642		] {
643			let params: Vec<Bytes> = params.into_iter().map(Bytes::from).collect();
644			let prefix = build_prefix(&params);
645			for length_size in 1..=4 {
646				for leading in [None, Some(aud.as_slice())] {
647					let mut payload = Vec::new();
648					for nal in leading.into_iter().chain([slice.as_slice()]) {
649						payload.extend_from_slice(&(nal.len() as u32).to_be_bytes()[4 - length_size..]);
650						payload.extend_from_slice(nal);
651					}
652					let mut expected = Vec::new();
653					if let Some(aud) = leading {
654						expected.extend_from_slice(&START_CODE);
655						expected.extend_from_slice(aud);
656					}
657					expected.extend_from_slice(&prefix);
658					expected.extend_from_slice(&START_CODE);
659					expected.extend_from_slice(&slice);
660					let out = from_length_prefixed(&payload, length_size, Some(&prefix)).unwrap();
661					assert_eq!(out.as_ref(), expected.as_slice());
662					let mut without_prefix = Vec::new();
663					for nal in leading.into_iter().chain([slice.as_slice()]) {
664						without_prefix.extend_from_slice(&START_CODE);
665						without_prefix.extend_from_slice(nal);
666					}
667					assert_eq!(
668						from_length_prefixed(&payload, length_size, None).unwrap(),
669						without_prefix
670					);
671				}
672			}
673		}
674	}
675
676	#[test]
677	fn from_length_prefixed_distinguishes_codec_headers() {
678		// H.265 TSA_N with nuh_layer_id 32 has the same first byte as an H.264 AUD.
679		let prefix = build_prefix([&Bytes::from_static(&[0x40, 1])]);
680		let payload = &[0, 0, 0, 3, 0x09, 1, 0x80];
681		let mut expected = prefix.to_vec();
682		expected.extend_from_slice(&[0, 0, 0, 1, 0x09, 1, 0x80]);
683		assert_eq!(from_length_prefixed(payload, 4, Some(&prefix)).unwrap(), expected);
684	}
685
686	#[test]
687	fn length_prefixed_to_annexb_rewrites_prefixes() {
688		// Two 4-byte-length-prefixed NALs -> two start-code-delimited NALs.
689		let input = [0, 0, 0, 2, 0x67, 0x42, 0, 0, 0, 3, 0x68, 0xce, 0x3c];
690		let mut out = Vec::new();
691		length_prefixed_to_annexb(&input, 4, &mut out).unwrap();
692		assert_eq!(out, vec![0, 0, 0, 1, 0x67, 0x42, 0, 0, 0, 1, 0x68, 0xce, 0x3c]);
693	}
694
695	#[test]
696	fn length_prefixed_to_annexb_rejects_truncated() {
697		// Declared length (5) overruns the buffer.
698		let input = [0, 0, 0, 5, 0x67];
699		let mut out = Vec::new();
700		assert!(length_prefixed_to_annexb(&input, 4, &mut out).is_err());
701	}
702
703	// Tests for after_start_code - validates and measures start code at buffer beginning
704
705	#[test]
706	fn test_after_start_code_3_byte() {
707		let buf = &[0, 0, 1, 0x67];
708		assert_eq!(after_start_code(buf).unwrap(), Some(3));
709	}
710
711	#[test]
712	fn test_after_start_code_4_byte() {
713		let buf = &[0, 0, 0, 1, 0x67];
714		assert_eq!(after_start_code(buf).unwrap(), Some(4));
715	}
716
717	#[test]
718	fn test_after_start_code_too_short() {
719		let buf = &[0, 0];
720		assert_eq!(after_start_code(buf).unwrap(), None);
721	}
722
723	#[test]
724	fn test_after_start_code_incomplete_4_byte() {
725		let buf = &[0, 0, 0];
726		assert_eq!(after_start_code(buf).unwrap(), None);
727	}
728
729	#[test]
730	fn test_after_start_code_invalid_first_byte() {
731		let buf = &[1, 0, 1];
732		assert!(after_start_code(buf).is_err());
733	}
734
735	#[test]
736	fn test_after_start_code_invalid_second_byte() {
737		let buf = &[0, 1, 1];
738		assert!(after_start_code(buf).is_err());
739	}
740
741	#[test]
742	fn test_after_start_code_invalid_third_byte() {
743		let buf = &[0, 0, 2];
744		assert!(after_start_code(buf).is_err());
745	}
746
747	#[test]
748	fn test_after_start_code_invalid_4_byte_pattern() {
749		let buf = &[0, 0, 0, 2];
750		assert!(after_start_code(buf).is_err());
751	}
752
753	// Tests for find_start_code - finds next start code in NAL data
754
755	#[test]
756	fn test_find_start_code_3_byte() {
757		let buf = &[0x67, 0x42, 0x00, 0x1f, 0, 0, 1];
758		assert_eq!(find_start_code(buf), Some((4, 3)));
759	}
760
761	#[test]
762	fn test_find_start_code_4_byte() {
763		// Should detect 4-byte start code at beginning
764		let buf = &[0, 0, 0, 1, 0x67];
765		assert_eq!(find_start_code(buf), Some((0, 4)));
766	}
767
768	#[test]
769	fn test_find_start_code_4_byte_after_data() {
770		// Should detect 4-byte start code after NAL data
771		let buf = &[0x67, 0x42, 0xff, 0x1f, 0, 0, 0, 1];
772		assert_eq!(find_start_code(buf), Some((4, 4)));
773	}
774
775	#[test]
776	fn test_find_start_code_at_start_3_byte() {
777		let buf = &[0, 0, 1, 0x67];
778		assert_eq!(find_start_code(buf), Some((0, 3)));
779	}
780
781	#[test]
782	fn test_find_start_code_none() {
783		let buf = &[0x67, 0x42, 0x00, 0x1f, 0xff];
784		assert_eq!(find_start_code(buf), None);
785	}
786
787	#[test]
788	fn test_find_start_code_trailing_zeros() {
789		let buf = &[0x67, 0x42, 0x00, 0x1f, 0, 0];
790		assert_eq!(find_start_code(buf), None);
791	}
792
793	#[test]
794	fn test_find_start_code_edge_case_3_byte() {
795		let buf = &[0xff, 0, 0, 1];
796		assert_eq!(find_start_code(buf), Some((1, 3)));
797	}
798
799	#[test]
800	fn test_find_start_code_false_positive_avoidance() {
801		// Pattern like: x 0 0 y (where y != 1) - should skip ahead
802		let buf = &[0xff, 0, 0, 0xff, 0, 0, 1];
803		assert_eq!(find_start_code(buf), Some((4, 3)));
804	}
805
806	#[test]
807	fn test_find_start_code_4_byte_after_nonzero() {
808		// Critical edge case: x 0 0 0 1 should find 4-byte start code at position 1
809		// This tests that we only skip 1 byte when seeing ? ? 0 0
810		let buf = &[0xff, 0, 0, 0, 1];
811		assert_eq!(find_start_code(buf), Some((1, 4)));
812	}
813
814	#[test]
815	fn test_find_start_code_consecutive_zeros() {
816		// Multiple consecutive zeros before the 1
817		let buf = &[0xff, 0, 0, 0, 0, 0, 1];
818		// Should skip past leading zeros and find the start code
819		let result = find_start_code(buf);
820		assert!(result.is_some());
821		let (pos, size) = result.unwrap();
822		// The exact position depends on the algorithm, but it should find a valid start code
823		assert!(size == 3 || size == 4);
824		assert!(pos < buf.len());
825	}
826
827	// Tests for NalIterator - iterates over NAL units in Annex B format
828
829	#[test]
830	fn test_nal_iterator_simple_3_byte() {
831		let mut data = Bytes::from(vec![0, 0, 1, 0x67, 0x42, 0, 0, 1]);
832		let mut iter = NalIterator::new(&mut data);
833
834		let nal = iter.next().unwrap().unwrap();
835		assert_eq!(nal.as_ref(), &[0x67, 0x42]);
836		assert!(iter.next().is_none());
837
838		// Make sure the trailing 001 is still in the buffer.
839		assert_eq!(data.as_ref(), &[0, 0, 1]);
840	}
841
842	#[test]
843	fn test_nal_iterator_simple_4_byte() {
844		let mut data = Bytes::from(vec![0, 0, 0, 1, 0x67, 0x42, 0, 0, 0, 1]);
845		let mut iter = NalIterator::new(&mut data);
846
847		let nal = iter.next().unwrap().unwrap();
848		assert_eq!(nal.as_ref(), &[0x67, 0x42]);
849		assert!(iter.next().is_none());
850
851		// Make sure the trailing 0001 is still in the buffer.
852		assert_eq!(data.as_ref(), &[0, 0, 0, 1]);
853	}
854
855	#[test]
856	fn test_nal_iterator_multiple_nals() {
857		let mut data = Bytes::from(vec![0, 0, 0, 1, 0x67, 0x42, 0, 0, 0, 1, 0x68, 0xce, 0, 0, 0, 1]);
858		let mut iter = NalIterator::new(&mut data);
859
860		let nal1 = iter.next().unwrap().unwrap();
861		assert_eq!(nal1.as_ref(), &[0x67, 0x42]);
862
863		let nal2 = iter.next().unwrap().unwrap();
864		assert_eq!(nal2.as_ref(), &[0x68, 0xce]);
865
866		assert!(iter.next().is_none());
867
868		// Make sure the trailing 0001 is still in the buffer.
869		assert_eq!(data.as_ref(), &[0, 0, 0, 1]);
870	}
871
872	#[test]
873	fn test_nal_iterator_realistic_h264() {
874		// A realistic H.264 stream with SPS, PPS, and IDR
875		let mut data = Bytes::from(vec![
876			0, 0, 0, 1, 0x67, 0x42, 0x00, 0x1f, // SPS NAL
877			0, 0, 0, 1, 0x68, 0xce, 0x3c, 0x80, // PPS NAL
878			0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00, // IDR slice
879			// Trailing start code (needed to detect the end of the last NAL)
880			0, 0, 0, 1,
881		]);
882		let mut iter = NalIterator::new(&mut data);
883
884		let sps = iter.next().unwrap().unwrap();
885		assert_eq!(sps[0] & 0x1f, 7); // SPS type
886		assert_eq!(sps.as_ref(), &[0x67, 0x42, 0x00, 0x1f]);
887
888		let pps = iter.next().unwrap().unwrap();
889		assert_eq!(pps[0] & 0x1f, 8); // PPS type
890		assert_eq!(pps.as_ref(), &[0x68, 0xce, 0x3c, 0x80]);
891
892		let idr = iter.next().unwrap().unwrap();
893		assert_eq!(idr[0] & 0x1f, 5); // IDR type
894		assert_eq!(idr.as_ref(), &[0x65, 0x88, 0x84, 0x00]);
895
896		assert!(iter.next().is_none());
897
898		// Make sure the trailing 0001 is still in the buffer.
899		assert_eq!(data.as_ref(), &[0, 0, 0, 1]);
900	}
901
902	#[test]
903	fn test_nal_iterator_realistic_h265() {
904		// A realistic H.265 stream with VPS, SPS, PPS, and IDR
905		let mut data = Bytes::from(vec![
906			0, 0, 0, 1, 0x40, 0x01, 0x0c, 0x01, // VPS NAL
907			0, 0, 0, 1, 0x42, 0x01, 0x01, 0x60, // SPS NAL
908			0, 0, 0, 1, 0x44, 0x01, 0xc0, 0xf1, // PPS NAL
909			0, 0, 0, 1, 0x26, 0x01, 0x9a, 0x20, // IDR_W_RADL slice
910			// Trailing start code (needed to detect the end of the last NAL)
911			0, 0, 0, 1,
912		]);
913		let mut iter = NalIterator::new(&mut data);
914
915		let vps = iter.next().unwrap().unwrap();
916		assert_eq!((vps[0] >> 1) & 0x3f, 32); // VPS type
917		assert_eq!(vps.as_ref(), &[0x40, 0x01, 0x0c, 0x01]);
918
919		let sps = iter.next().unwrap().unwrap();
920		assert_eq!((sps[0] >> 1) & 0x3f, 33); // SPS type
921		assert_eq!(sps.as_ref(), &[0x42, 0x01, 0x01, 0x60]);
922
923		let pps = iter.next().unwrap().unwrap();
924		assert_eq!((pps[0] >> 1) & 0x3f, 34); // PPS type
925		assert_eq!(pps.as_ref(), &[0x44, 0x01, 0xc0, 0xf1]);
926
927		let idr = iter.next().unwrap().unwrap();
928		assert_eq!((idr[0] >> 1) & 0x3f, 19); // IDR slice type (IDR_W_RADL)
929		assert_eq!(idr.as_ref(), &[0x26, 0x01, 0x9a, 0x20]);
930
931		assert!(iter.next().is_none());
932
933		// Make sure the trailing 0001 is still in the buffer.
934		assert_eq!(data.as_ref(), &[0, 0, 0, 1]);
935	}
936
937	#[test]
938	fn test_nal_iterator_invalid_start() {
939		let mut data = Bytes::from(vec![1, 0, 1, 0x67]);
940		let mut iter = NalIterator::new(&mut data);
941
942		assert!(iter.next().unwrap().is_err());
943
944		// Make sure the data is still in the buffer.
945		assert_eq!(data.as_ref(), &[1, 0, 1, 0x67]);
946	}
947
948	#[test]
949	fn test_nal_iterator_empty_nal() {
950		// Two consecutive start codes create an empty NAL
951		let mut data = Bytes::from(vec![0, 0, 1, 0, 0, 1, 0x67, 0, 0, 1]);
952		let mut iter = NalIterator::new(&mut data);
953
954		let nal1 = iter.next().unwrap().unwrap();
955		assert_eq!(nal1.len(), 0);
956
957		let nal2 = iter.next().unwrap().unwrap();
958		assert_eq!(nal2.as_ref(), &[0x67]);
959
960		assert!(iter.next().is_none());
961
962		// Make sure the data is still in the buffer.
963		assert_eq!(data.as_ref(), &[0, 0, 1]);
964	}
965
966	#[test]
967	fn test_nal_iterator_nal_with_embedded_zeros() {
968		// NAL data that contains zeros (but not a start code pattern)
969		let mut data = Bytes::from(vec![
970			0, 0, 1, 0x67, 0x00, 0x00, 0x00, 0xff, // NAL with embedded zeros
971			0, 0, 1, 0x68, // Next NAL
972			0, 0, 1,
973		]);
974		let mut iter = NalIterator::new(&mut data);
975
976		let nal1 = iter.next().unwrap().unwrap();
977		assert_eq!(nal1.as_ref(), &[0x67, 0x00, 0x00, 0x00, 0xff]);
978
979		let nal2 = iter.next().unwrap().unwrap();
980		assert_eq!(nal2.as_ref(), &[0x68]);
981
982		assert!(iter.next().is_none());
983
984		// Make sure the data is still in the buffer.
985		assert_eq!(data.as_ref(), &[0, 0, 1]);
986	}
987
988	// Tests for flush - extracts final NAL without trailing start code
989
990	#[test]
991	fn test_flush_after_iteration() {
992		// Normal case: iterate over NALs, then flush the final one
993		let mut data = Bytes::from(vec![
994			0, 0, 0, 1, 0x67, 0x42, // First NAL
995			0, 0, 0, 1, 0x68, 0xce, 0x3c, 0x80, // Second NAL (final, no trailing start code)
996		]);
997		let mut iter = NalIterator::new(&mut data);
998
999		let nal1 = iter.next().unwrap().unwrap();
1000		assert_eq!(nal1.as_ref(), &[0x67, 0x42]);
1001
1002		assert!(iter.next().is_none());
1003
1004		let final_nal = iter.flush().unwrap().unwrap();
1005		assert_eq!(final_nal.as_ref(), &[0x68, 0xce, 0x3c, 0x80]);
1006	}
1007
1008	#[test]
1009	fn test_flush_single_nal() {
1010		// Buffer contains only a single NAL with no trailing start code
1011		let mut data = Bytes::from(vec![0, 0, 1, 0x67, 0x42, 0x00, 0x1f]);
1012		let iter = NalIterator::new(&mut data);
1013
1014		let final_nal = iter.flush().unwrap().unwrap();
1015		assert_eq!(final_nal.as_ref(), &[0x67, 0x42, 0x00, 0x1f]);
1016	}
1017
1018	#[test]
1019	fn test_flush_4_byte_start_code() {
1020		// Test flush with 4-byte start code
1021		let mut data = Bytes::from(vec![0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00, 0xff]);
1022		let iter = NalIterator::new(&mut data);
1023
1024		let final_nal = iter.flush().unwrap().unwrap();
1025		assert_eq!(final_nal.as_ref(), &[0x65, 0x88, 0x84, 0x00, 0xff]);
1026	}
1027
1028	#[test]
1029	fn test_flush_no_start_code() {
1030		// Buffer doesn't start with a start code and has no cached start position
1031		let mut data = Bytes::from(vec![0x67, 0x42, 0x00, 0x1f]);
1032		let iter = NalIterator::new(&mut data);
1033
1034		let result = iter.flush();
1035		assert!(result.is_err());
1036	}
1037
1038	#[test]
1039	fn test_flush_empty_buffer() {
1040		// Empty buffer should return None
1041		let mut data = Bytes::from(vec![]);
1042		let iter = NalIterator::new(&mut data);
1043
1044		let result = iter.flush().unwrap();
1045		assert!(result.is_none());
1046	}
1047
1048	#[test]
1049	fn test_flush_incomplete_start_code() {
1050		// Buffer has incomplete start code (not enough bytes)
1051		let mut data = Bytes::from(vec![0, 0]);
1052		let iter = NalIterator::new(&mut data);
1053
1054		let result = iter.flush().unwrap();
1055		assert!(result.is_none());
1056	}
1057
1058	#[test]
1059	fn test_flush_multiple_nals_then_flush() {
1060		// Iterate over multiple NALs, then flush the final one
1061		let mut data = Bytes::from(vec![
1062			0, 0, 0, 1, 0x67, 0x42, // SPS
1063			0, 0, 0, 1, 0x68, 0xce, // PPS
1064			0, 0, 0, 1, 0x65, 0x88, 0x84, // IDR (final NAL)
1065		]);
1066		let mut iter = NalIterator::new(&mut data);
1067
1068		let sps = iter.next().unwrap().unwrap();
1069		assert_eq!(sps.as_ref(), &[0x67, 0x42]);
1070
1071		let pps = iter.next().unwrap().unwrap();
1072		assert_eq!(pps.as_ref(), &[0x68, 0xce]);
1073
1074		assert!(iter.next().is_none());
1075
1076		let idr = iter.flush().unwrap().unwrap();
1077		assert_eq!(idr.as_ref(), &[0x65, 0x88, 0x84]);
1078	}
1079
1080	#[test]
1081	fn test_flush_empty_final_nal() {
1082		// Edge case: final NAL is empty (just a start code with no data)
1083		let mut data = Bytes::from(vec![
1084			0, 0, 0, 1, 0x67, 0x42, // First NAL
1085			0, 0, 0, 1, // Second NAL (empty)
1086		]);
1087		let mut iter = NalIterator::new(&mut data);
1088
1089		let nal1 = iter.next().unwrap().unwrap();
1090		assert_eq!(nal1.as_ref(), &[0x67, 0x42]);
1091
1092		assert!(iter.next().is_none());
1093
1094		let final_nal = iter.flush().unwrap().unwrap();
1095		assert_eq!(final_nal.len(), 0);
1096	}
1097
1098	fn annexb(nals: &[&[u8]]) -> Bytes {
1099		build_prefix(
1100			nals.iter()
1101				.map(|nal| Bytes::copy_from_slice(nal))
1102				.collect::<Vec<_>>()
1103				.iter(),
1104		)
1105	}
1106
1107	fn length_prefixed(nals: &[&[u8]]) -> Vec<u8> {
1108		let mut out = Vec::new();
1109		for nal in nals {
1110			out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
1111			out.extend_from_slice(nal);
1112		}
1113		out
1114	}
1115
1116	#[test]
1117	fn in_band_h264_keyframes_carry_sps_then_pps() {
1118		let aud = &[0x09, 0xf0][..];
1119		let sps = &[0x67, 0x42, 0xc0, 0x1f, 0xde][..];
1120		let pps = &[0x68, 0xce, 0x3c, 0x80][..];
1121		let idr = &[0x65, 0x88, 0x84, 0x21][..];
1122		let sei = &[0x06, 0x05, 0xff][..];
1123		let sps2 = &[0x67, 0x42, 0xc0, 0x1f, 0xaa][..];
1124		let delta = &[0x61, 0xe0, 0x12][..];
1125
1126		let mut tx = InBand::new(InBandCodec::H264);
1127		assert!(tx.transform(annexb(&[aud, sps, pps]), true).unwrap().is_none());
1128		let full = tx.transform(annexb(&[sps, pps, idr]), true).unwrap().unwrap();
1129		assert_eq!(full.as_ref(), length_prefixed(&[sps, pps, idr]));
1130
1131		// A partial keyframe gets the cached sets, never a PPS ahead of its SPS.
1132		let pps_only = tx.transform(annexb(&[pps, idr]), true).unwrap().unwrap();
1133		assert_eq!(pps_only.as_ref(), length_prefixed(&[sps, pps, idr]));
1134		let reordered = tx.transform(annexb(&[pps, sps2, idr]), true).unwrap().unwrap();
1135		assert_eq!(reordered.as_ref(), length_prefixed(&[sps2, pps, idr]));
1136
1137		// The delimiter stays first, and SEI follows the sets it may reference.
1138		let sei_first = tx.transform(annexb(&[aud, sei, idr]), true).unwrap().unwrap();
1139		assert_eq!(sei_first.as_ref(), length_prefixed(&[aud, sps2, pps, sei, idr]));
1140
1141		// Delta frames are not given parameter sets.
1142		let delta_out = tx.transform(annexb(&[delta]), false).unwrap().unwrap();
1143		assert_eq!(delta_out.as_ref(), length_prefixed(&[delta]));
1144	}
1145
1146	#[test]
1147	fn in_band_h265_keyframes_carry_vps_sps_pps() {
1148		use crate::codec::h265::fixtures::{PPS, SPS, SPS_PYRAMID, VPS};
1149		let (vps, sps, pps, sps2) = (VPS, SPS, PPS, SPS_PYRAMID);
1150		let idr = &[0x26, 0x01, 0xaa][..];
1151		let sei = &[0x4e, 0x01, 0x05][..];
1152
1153		// An access unit with no slice is not a sample; its sets wait for the next keyframe.
1154		let mut tx = InBand::new(InBandCodec::H265);
1155		assert!(tx.transform(annexb(&[vps, sps, pps]), true).unwrap().is_none());
1156		assert!(tx.transform(annexb(&[sei]), true).unwrap().is_none());
1157		let bare = tx.transform(annexb(&[idr]), true).unwrap().unwrap();
1158		assert_eq!(bare.as_ref(), length_prefixed(&[vps, sps, pps, idr]));
1159
1160		// A new SPS alone still follows the VPS it references.
1161		let replaced = tx.transform(annexb(&[sps2, idr]), true).unwrap().unwrap();
1162		assert_eq!(replaced.as_ref(), length_prefixed(&[vps, sps2, pps, idr]));
1163
1164		let sei_first = tx.transform(annexb(&[sei, idr]), true).unwrap().unwrap();
1165		assert_eq!(sei_first.as_ref(), length_prefixed(&[vps, sps2, pps, sei, idr]));
1166	}
1167
1168	/// An access unit redefining only an enhancement layer's sets keeps the base layer's.
1169	#[test]
1170	fn in_band_h265_keeps_the_base_layer_beside_an_enhancement_update() {
1171		use crate::codec::h265::fixtures::{MV_PPS_LAYER1, MV_SPS_LAYER1, PPS, SPS, VPS};
1172		let idr = &[0x26, 0x01, 0xaa][..];
1173
1174		let mut tx = InBand::new(InBandCodec::H265);
1175		let first = tx.transform(annexb(&[VPS, SPS, PPS, idr]), true).unwrap().unwrap();
1176		assert_eq!(first.as_ref(), length_prefixed(&[VPS, SPS, PPS, idr]));
1177		let update = tx
1178			.transform(annexb(&[MV_SPS_LAYER1, MV_PPS_LAYER1, idr]), true)
1179			.unwrap()
1180			.unwrap();
1181		assert_eq!(
1182			update.as_ref(),
1183			length_prefixed(&[VPS, SPS, MV_SPS_LAYER1, PPS, MV_PPS_LAYER1, idr])
1184		);
1185	}
1186
1187	/// A parameter set keys by the id it defines, so a stream redefining ids holds one entry
1188	/// per id, the last, however many sets it sends. A set too short for its id is refused.
1189	#[test]
1190	fn parameter_sets_key_by_id() {
1191		use crate::codec::h265::fixtures::{PPS, SPS, SPS_PYRAMID, VPS};
1192
1193		let mut sets = ParameterSets::new();
1194		for last in 0..=u8::MAX {
1195			// pic_parameter_set_id is ue(v): `1` is id 0, `010` is id 1.
1196			for head in [0xce, 0x4e] {
1197				let pps = Bytes::copy_from_slice(&[0x68, head, 0x3c, last]);
1198				InBandCodec::H264.insert_parameter_set(&mut sets, &pps).unwrap();
1199			}
1200		}
1201		assert_eq!(sets.len(), 2);
1202		assert_eq!(sets[&(0, 0)].as_ref(), [0x68, 0xce, 0x3c, 0xff]);
1203		assert_eq!(sets[&(0, 1)].as_ref(), [0x68, 0x4e, 0x3c, 0xff]);
1204
1205		for nal in [VPS, SPS, SPS_PYRAMID, PPS] {
1206			let mut sets = ParameterSets::new();
1207			InBandCodec::H265
1208				.insert_parameter_set(&mut sets, &Bytes::from_static(nal))
1209				.unwrap();
1210			assert_eq!(sets.keys().collect::<Vec<_>>(), [&(0, 0)]);
1211		}
1212
1213		let truncated = Bytes::from_static(&[0x67, 0x42, 0xc0]);
1214		let err = InBandCodec::H264.insert_parameter_set(&mut ParameterSets::new(), &truncated);
1215		assert!(matches!(err, Err(Error::ParameterSetId(7))), "{err:?}");
1216	}
1217
1218	#[test]
1219	fn in_band_keyframe_without_parameter_sets_fails() {
1220		use crate::codec::h265::fixtures::{PPS, SPS};
1221		let (sps, pps) = (SPS, PPS);
1222		let idr = &[0x26, 0x01, 0xaa][..];
1223
1224		let mut tx = InBand::new(InBandCodec::H265);
1225		let err = tx.transform(annexb(&[sps, pps, idr]), true).unwrap_err();
1226		assert!(matches!(err, Error::MissingParameterSet("VPS")), "{err}");
1227
1228		let mut tx = InBand::new(InBandCodec::H264);
1229		let err = tx.transform(annexb(&[&[0x65, 0x88][..]]), true).unwrap_err();
1230		assert!(matches!(err, Error::MissingParameterSet("SPS")), "{err}");
1231	}
1232}