Skip to main content

moq_mux/codec/h265/
mod.rs

1//! H.265 / HEVC.
2//!
3//! The H.265 analogue of [`crate::codec::h264`]. Parses SPS NAL units
4//! and HEVCDecoderConfigurationRecord blobs. The [`Hvc1`] transmuxer
5//! rewrites Annex-B input (inline VPS/SPS/PPS) as length-prefixed NALU
6//! + out-of-band hvcC. [`Export`] is the single-rendition Annex-B
7//!   exporter; [`Import`] takes either shape, driven by a
8//!   [`Split`] for hev1 or by `hvc1_frame` for hvc1.
9
10mod export;
11mod import;
12mod split;
13mod sps;
14
15pub use export::*;
16pub use import::*;
17pub use split::*;
18pub use sps::{Sps, VideoSignal};
19
20use bytes::{Buf, Bytes, BytesMut};
21
22use crate::codec::annexb::{InBandCodec, ParameterSets};
23pub(crate) use sps::id as sps_id;
24
25/// Wrap one hvc1 (length-prefixed NALU) access unit as a single
26/// [`Frame`](crate::container::Frame), with the keyframe flag set when it
27/// carries an IRAP NAL.
28///
29/// hvc1 is not a stream: each access unit arrives whole with its NALU
30/// `length_size` known out-of-band from the hvcC (`super::Hvcc::parse(hvcc).length_size`).
31/// The payload is passed through verbatim.
32pub(crate) fn hvc1_frame(
33	data: impl moq_net::IntoBytes,
34	length_size: usize,
35	pts: moq_net::Timestamp,
36) -> crate::Result<crate::container::Frame> {
37	let keyframe = hvc1_is_keyframe(data.as_ref(), length_size);
38	Ok(crate::container::Frame {
39		timestamp: pts,
40		decode: None,
41		payload: data.into_bytes(),
42		keyframe,
43		duration: None,
44	})
45}
46
47/// Detect whether an hvc1-shaped (length-prefixed) buffer contains an IRAP slice.
48fn hvc1_is_keyframe(data: &[u8], length_size: usize) -> bool {
49	let Ok(nals) = crate::codec::annexb::length_prefixed_nals(data, length_size) else {
50		return false;
51	};
52	nals.map_while(std::result::Result::ok)
53		.any(|nal| nal.first().is_some_and(|header| NalType::of(*header).is_irap()))
54}
55
56/// Whether an hvc1-shaped (length-prefixed) access unit is a RADL picture: one that leads its
57/// IRAP but references only it, so it decodes wherever that IRAP does (H.265 8.1.2).
58pub(crate) fn hvc1_is_radl(data: &[u8], length_size: usize) -> bool {
59	let Ok(nals) = crate::codec::annexb::length_prefixed_nals(data, length_size) else {
60		return false;
61	};
62	// RADL_N and RADL_R; types below 32 are slices.
63	let mut slices = (nals.map_while(std::result::Result::ok))
64		.filter_map(|nal| nal.first().map(|header| (header >> 1) & 0x3f))
65		.filter(|kind| *kind < 32)
66		.peekable();
67	slices.peek().is_some() && slices.all(|kind| matches!(kind, 6 | 7))
68}
69
70/// A NAL unit's `nuh_layer_id`, the six bits across both header bytes; `None` when it is shorter
71/// than its header.
72pub(crate) fn layer_id(nal: &[u8]) -> Option<u8> {
73	match nal {
74		[first, second, ..] => Some(((first & 0x01) << 5) | (second >> 3)),
75		_ => None,
76	}
77}
78
79/// True for a base-layer NAL unit (`nuh_layer_id` 0). An enhancement layer's SPS (MV-HEVC,
80/// SHVC) has another layout (H.265 F.7.3.2.2.1), so only the base layer's configures a rendition.
81pub(crate) fn is_base_layer(nal: &[u8]) -> bool {
82	layer_id(nal) == Some(0)
83}
84
85/// The first base-layer SPS among a stream's or record's SPS NAL units: `None` when there are
86/// none, and an error when every one is an enhancement layer's.
87pub(crate) fn base_sps<'a, T: AsRef<[u8]> + ?Sized + 'a>(
88	sps: impl IntoIterator<Item = &'a T>,
89) -> Result<Option<&'a T>> {
90	let mut any = false;
91	for nal in sps {
92		if is_base_layer(nal.as_ref()) {
93			return Ok(Some(nal));
94		}
95		any = true;
96	}
97	match any {
98		true => Err(Error::NoBaseLayerSps),
99		false => Ok(None),
100	}
101}
102
103/// An H.265 `nal_unit_type` (ITU-T H.265 Table 7-1).
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub(crate) struct NalType(pub u8);
106
107impl NalType {
108	pub const VPS: Self = Self(32);
109	pub const SPS: Self = Self(33);
110	pub const PPS: Self = Self(34);
111	pub const AUD: Self = Self(35);
112	pub const PREFIX_SEI: Self = Self(39);
113	pub const SUFFIX_SEI: Self = Self(40);
114
115	/// The type in a NAL unit's first header byte, after the forbidden zero bit.
116	pub fn of(header: u8) -> Self {
117		Self((header >> 1) & 0x3f)
118	}
119
120	/// True for the IRAP (intra random access point) types, the ones that open a group: BLA,
121	/// IDR, and CRA, without the reserved IRAP types. HEVC random access is broader than H.264's
122	/// single IDR type.
123	pub fn is_irap(self) -> bool {
124		(16..=21).contains(&self.0)
125	}
126}
127
128/// H.265 parsing and transform errors.
129#[derive(Debug, Clone, thiserror::Error)]
130#[non_exhaustive]
131pub enum Error {
132	/// The NAL unit ends before its required header or slice fields.
133	#[error("NAL unit is too short")]
134	NalTooShort,
135
136	/// The named parameter set length exceeds the hvcC length field.
137	#[error("{0} too large for hvcC length field ({1} > {max})", max = u16::MAX)]
138	NalTooLargeForHvcc(&'static str, usize),
139
140	/// The number of parameter sets of the named type exceeds the hvcC limit.
141	#[error("too many {0} for hvcC ({1} > {max})", max = u16::MAX)]
142	TooManyNals(&'static str, usize),
143
144	/// The NAL payload length does not fit a four-byte prefix.
145	#[error("NAL too large for 4-byte length prefix")]
146	NalTooLarge,
147
148	/// The SPS NAL could not be parsed.
149	#[error("failed to parse SPS NAL unit")]
150	SpsParse,
151
152	/// The SPS does not declare a level_idc.
153	#[error("missing level_idc in SPS")]
154	MissingLevelIdc,
155
156	/// The NAL header sets the forbidden_zero_bit.
157	#[error("forbidden zero bit is not zero")]
158	ForbiddenZeroBit,
159
160	/// The stream has not supplied its decoder configuration.
161	#[error("not initialized")]
162	NotInitialized,
163
164	/// A frame arrived before the SPS.
165	#[error("expected SPS before any frames")]
166	MissingSps,
167
168	/// The access unit has no timestamp.
169	#[error("missing timestamp")]
170	MissingTimestamp,
171
172	/// The HEVCDecoderConfigurationRecord is shorter than its required header.
173	#[error("HEVCDecoderConfigurationRecord too short")]
174	HvccTooShort,
175
176	/// The HEVCDecoderConfigurationRecord ends before its declared parameter sets.
177	#[error("HEVCDecoderConfigurationRecord truncated")]
178	HvccTruncated,
179
180	/// The named hvc1 rendition lacks a VPS, SPS, or PPS in its description.
181	#[error("hvc1 description for rendition {name:?} is missing VPS, SPS, or PPS (vps={vps}, sps={sps}, pps={pps})")]
182	MissingParamSets {
183		/// The rendition name.
184		name: String,
185		/// The number of VPS NAL units in the description.
186		vps: usize,
187		/// The number of SPS NAL units in the description.
188		sps: usize,
189		/// The number of PPS NAL units in the description.
190		pps: usize,
191	},
192
193	/// Parsing or transforming the Annex B stream failed.
194	#[error("annexb: {0}")]
195	Annexb(#[from] crate::codec::annexb::Error),
196
197	/// Every SPS belongs to an enhancement layer (`nuh_layer_id` > 0); only the base layer imports.
198	#[error("no base-layer SPS: every SPS has nuh_layer_id > 0")]
199	NoBaseLayerSps,
200}
201
202/// A result using this module's error type.
203pub type Result<T> = std::result::Result<T, Error>;
204
205/// The parameter sets carried out-of-band in an HEVCDecoderConfigurationRecord,
206/// split by NAL type.
207#[derive(Debug, Clone)]
208#[non_exhaustive]
209pub struct Hvcc {
210	/// NALU length size in bytes (typically 4).
211	pub length_size: usize,
212	/// VPS NAL units carried out-of-band in the record.
213	pub vps: Vec<Bytes>,
214	/// SPS NAL units carried out-of-band in the record.
215	pub sps: Vec<Bytes>,
216	/// PPS NAL units carried out-of-band in the record.
217	pub pps: Vec<Bytes>,
218}
219
220impl Hvcc {
221	/// Parse an HEVCDecoderConfigurationRecord, sorting the VPS/SPS/PPS NAL units
222	/// by type. The HEVC analogue of [`super::h264::Avcc::parse`].
223	pub fn parse(hvcc: &[u8]) -> Result<Self> {
224		let record = decode_hvcc(hvcc)?;
225
226		let mut vps = Vec::new();
227		let mut sps = Vec::new();
228		let mut pps = Vec::new();
229		for array in record.arrays {
230			let list = match NalType(array.nal_unit_type) {
231				NalType::VPS => &mut vps,
232				NalType::SPS => &mut sps,
233				NalType::PPS => &mut pps,
234				_ => continue,
235			};
236			list.extend(array.nalus.into_iter().map(Bytes::from));
237		}
238
239		Ok(Self {
240			length_size: usize::from(record.length_size_minus_one) + 1,
241			vps,
242			sps,
243			pps,
244		})
245	}
246}
247
248/// Build a catalog [`VideoConfig`](hang::catalog::VideoConfig) for the `hvc1`
249/// shape from an HEVCDecoderConfigurationRecord (hvcC).
250///
251/// The H.265 analogue of [`crate::codec::h264::Avcc::parse`] feeding a
252/// `VideoConfig`. Used by the enhanced-RTMP / FLV importer, where the hvcC
253/// arrives out of band in the sequence-header tag and the coded samples are
254/// already length-prefixed NALU, so the record passes straight through as the
255/// catalog `description` (`in_band: false`).
256pub(crate) fn config_from_hvcc(hvcc: &[u8]) -> Result<hang::catalog::VideoConfig> {
257	let params = Hvcc::parse(hvcc)?;
258	let sps_nal = base_sps(&params.sps)?.ok_or(Error::MissingSps)?;
259	let mut config = config_from_sps(sps_nal, false)?;
260	config.description = Some(Bytes::copy_from_slice(hvcc));
261	Ok(config)
262}
263
264/// Copy the frame rate, display aspect, colour, and reorder depth from a decoded hvcC's first
265/// base-layer SPS.
266///
267/// An hev1 record may list no SPS, leaving them unset.
268pub(crate) fn apply_hvcc_sps(hvcc: &mp4_atom::Hvcc, config: &mut hang::catalog::VideoConfig) -> Result<()> {
269	let sps = hvcc
270		.arrays
271		.iter()
272		.filter(|array| NalType(array.nal_unit_type) == NalType::SPS)
273		.flat_map(|array| &array.nalus);
274	let Some(sps) = base_sps(sps)? else {
275		return Ok(());
276	};
277	let metadata = config_from_sps(sps, false)?;
278	config.framerate = metadata.framerate;
279	config.display_aspect_width = metadata.display_aspect_width;
280	config.display_aspect_height = metadata.display_aspect_height;
281	config.color = metadata.color;
282	config.reorder = metadata.reorder;
283	Ok(())
284}
285
286/// Resolve either sample framing from the same SPS dimensions and VUI metadata.
287pub(crate) fn config_from_sps(sps_nal: &[u8], in_band: bool) -> Result<hang::catalog::VideoConfig> {
288	let sps = Sps::parse_or_head(sps_nal)?;
289	let color = sps.color();
290	let Sps { head, tail } = sps;
291	let mut config = hang::catalog::VideoConfig::new(hang::catalog::H265 {
292		in_band,
293		profile_space: head.profile_space,
294		profile_idc: head.profile_idc,
295		profile_compatibility_flags: head.profile_compatibility_flags,
296		tier_flag: head.tier_flag,
297		level_idc: head.level_idc,
298		constraint_flags: head.constraint_flags,
299	});
300	config.coded_width = Some(head.width);
301	config.coded_height = Some(head.height);
302	let vui = tail.as_ref().map(|tail| &tail.vui);
303	config.framerate = vui
304		.and_then(sps::Vui::period)
305		.map(|(units, scale)| scale as f64 / units as f64);
306	let display_aspect = vui
307		.and_then(|vui| vui.sample_aspect)
308		.and_then(|sample| crate::codec::video::display_aspect(head.width, head.height, sample));
309	config.display_aspect_width = display_aspect.map(|(width, _)| width);
310	config.display_aspect_height = display_aspect.map(|(_, height)| height);
311	config.color = color;
312	config.reorder = tail
313		.and_then(|tail| u8::try_from(tail.max_num_reorder_pics).ok())
314		.filter(|depth| u32::from(*depth) <= crate::codec::video::max_reorder(&config));
315	Ok(config)
316}
317
318/// The picture size an SPS NAL (header included) declares, inside its conformance window. `None`
319/// when it fails to parse.
320pub(crate) fn sps_size(nal: &[u8]) -> Option<(u32, u32)> {
321	let head = Sps::parse_or_head(nal).ok()?.head;
322	Some((head.width, head.height))
323}
324
325/// The reordering an SPS NAL unit declares for its highest sub-layer: `sps_max_num_reorder_pics`,
326/// and the picture period when the VUI's HRD parameters fix the picture rate within the CVS
327/// (ITU-T H.265 E.3.2).
328///
329/// `None` when the SPS fails to parse.
330pub(crate) fn sps_reorder(nal: &[u8]) -> Option<crate::codec::video::Reorder> {
331	let tail = Sps::parse(nal).ok()?.tail?;
332	Some(crate::codec::video::Reorder {
333		depth: tail.max_num_reorder_pics,
334		period: tail.vui.period(),
335	})
336}
337
338/// The HRD an SPS NAL unit's VUI declares at its highest sub-layer, when it carries one: the
339/// NAL HRD's last schedule, or the VCL HRD's when that is all there is.
340pub(crate) fn sps_hrd(nal: &[u8]) -> Option<crate::codec::video::Hrd> {
341	Sps::parse(nal).ok()?.tail?.vui.timing?.hrd?.schedule
342}
343
344/// Annex-B → length-prefixed transmuxer; the H.265 analogue of
345/// [`crate::codec::h264::Avc1`].
346///
347/// The active VPS/SPS/PPS set is scoped to the latest keyframe: a frame that
348/// carries parameter sets redefines those of each layer it carries them for, so
349/// a mid-stream reconfiguration drops the superseded ones instead of
350/// accumulating them forever.
351pub struct Hvc1 {
352	hvcc: Option<Bytes>,
353	/// The active VPS NALs (from the most recent keyframe that carried them).
354	vps: ParameterSets,
355	/// The active SPS NALs.
356	sps: ParameterSets,
357	/// The active PPS NALs.
358	pps: ParameterSets,
359}
360
361impl Default for Hvc1 {
362	fn default() -> Self {
363		Self::new()
364	}
365}
366
367impl Hvc1 {
368	/// Build a new transform for a hev1 source.
369	pub fn new() -> Self {
370		Self {
371			hvcc: None,
372			vps: ParameterSets::new(),
373			sps: ParameterSets::new(),
374			pps: ParameterSets::new(),
375		}
376	}
377
378	/// The HEVCDecoderConfigurationRecord, available once VPS+SPS+PPS have been observed.
379	pub fn hvcc(&self) -> Option<&Bytes> {
380		self.hvcc.as_ref()
381	}
382
383	/// Convert one decoded frame's payload to the hvc1 wire shape.
384	///
385	/// Returns:
386	/// - `Ok(Some(payload))` if a length-prefixed sample is ready to emit.
387	/// - `Ok(None)` if the input contained only parameter sets and the
388	///   transform is still waiting for slice NALs (hvcC may have been
389	///   built as a side effect).
390	pub fn transform(&mut self, payload: Bytes) -> Result<Option<Bytes>> {
391		let mut buf = payload.clone();
392		let mut nal_iter = crate::codec::annexb::NalIterator::new(&mut buf);
393
394		let mut out = BytesMut::with_capacity(payload.remaining());
395		let mut frame_vps = ParameterSets::new();
396		let mut frame_sps = ParameterSets::new();
397		let mut frame_pps = ParameterSets::new();
398		let mut emitted_any_slice = false;
399
400		loop {
401			let nal = match nal_iter.next() {
402				Some(Ok(n)) => n,
403				Some(Err(e)) => return Err(e.into()),
404				None => break,
405			};
406			if process_nal(&nal, &mut out, &mut frame_vps, &mut frame_sps, &mut frame_pps)? {
407				emitted_any_slice = true;
408			}
409		}
410
411		if let Some(nal) = nal_iter.flush()?
412			&& process_nal(&nal, &mut out, &mut frame_vps, &mut frame_sps, &mut frame_pps)?
413		{
414			emitted_any_slice = true;
415		}
416
417		// A frame that carries parameter sets (a keyframe) redefines the active
418		// set; adopt it so a superseded configuration's VPS/SPS/PPS are dropped
419		// rather than lingering in the hvcC. Per type and layer, so a frame that
420		// updates only one kind or layer keeps the others.
421		let mut changed = false;
422		for (active, frame) in [
423			(&mut self.vps, frame_vps),
424			(&mut self.sps, frame_sps),
425			(&mut self.pps, frame_pps),
426		] {
427			let before = active.clone();
428			crate::codec::annexb::adopt_parameter_sets(active, frame);
429			changed |= *active != before;
430		}
431		if changed {
432			self.rebuild_hvcc()?;
433		}
434
435		if !emitted_any_slice {
436			return Ok(None);
437		}
438
439		Ok(Some(out.freeze()))
440	}
441
442	fn rebuild_hvcc(&mut self) -> Result<()> {
443		if self.vps.is_empty() || self.sps.is_empty() || self.pps.is_empty() {
444			return Ok(());
445		}
446		let [vps, sps, pps] = [&self.vps, &self.sps, &self.pps].map(|sets| sets.values().cloned().collect::<Vec<_>>());
447		self.hvcc = Some(build_hvcc(&vps, &sps, &pps)?);
448		Ok(())
449	}
450}
451
452/// Process one NAL: VPS/SPS/PPS are collected by id into this frame's
453/// sets, everything else is length-prefixed and appended to `out`. Returns true
454/// if the NAL was a slice (i.e. produced sample bytes).
455fn process_nal(
456	nal: &Bytes,
457	out: &mut BytesMut,
458	frame_vps: &mut ParameterSets,
459	frame_sps: &mut ParameterSets,
460	frame_pps: &mut ParameterSets,
461) -> Result<bool> {
462	if nal.is_empty() {
463		return Ok(false);
464	}
465	// HEVC NAL header is 2 bytes; type is bits 1..=6 of byte 0.
466	match NalType::of(nal[0]) {
467		NalType::VPS => {
468			InBandCodec::H265.insert_parameter_set(frame_vps, nal)?;
469			Ok(false)
470		}
471		NalType::SPS => {
472			InBandCodec::H265.insert_parameter_set(frame_sps, nal)?;
473			Ok(false)
474		}
475		NalType::PPS => {
476			InBandCodec::H265.insert_parameter_set(frame_pps, nal)?;
477			Ok(false)
478		}
479		_ => {
480			let len = u32::try_from(nal.len()).map_err(|_| Error::NalTooLarge)?;
481			out.extend_from_slice(&len.to_be_bytes());
482			out.extend_from_slice(nal);
483			Ok(true)
484		}
485	}
486}
487
488/// Build an HEVCDecoderConfigurationRecord (ISO/IEC 14496-15 §8.3.3).
489/// Each NAL array (VPS, SPS, PPS) carries every distinct parameter set the
490/// stream defined, in the order given; the profile/tier fields are read from
491/// the first base-layer SPS.
492pub(crate) fn build_hvcc(vps_nals: &[Bytes], sps_nals: &[Bytes], pps_nals: &[Bytes]) -> Result<Bytes> {
493	let first_sps = base_sps(sps_nals)?.ok_or(Error::MissingSps)?;
494	// mp4-atom truncates the counts and lengths rather than refusing them.
495	for (label, nals) in [("VPS", vps_nals), ("SPS", sps_nals), ("PPS", pps_nals)] {
496		if nals.len() > u16::MAX as usize {
497			return Err(Error::TooManyNals(label, nals.len()));
498		}
499		for nal in nals {
500			if nal.len() > u16::MAX as usize {
501				return Err(Error::NalTooLargeForHvcc(label, nal.len()));
502			}
503		}
504	}
505
506	let sps = Sps::parse_or_head(first_sps)?.head;
507	let arrays = [
508		(NalType::VPS, vps_nals),
509		(NalType::SPS, sps_nals),
510		(NalType::PPS, pps_nals),
511	]
512	.into_iter()
513	.map(|(nal_type, nals)| mp4_atom::HvcCArray {
514		completeness: true,
515		nal_unit_type: nal_type.0,
516		nalus: nals.iter().map(|nal| nal.to_vec()).collect(),
517	})
518	.collect();
519
520	Ok(encode_hvcc(&mp4_atom::Hvcc {
521		configuration_version: 1,
522		general_profile_space: sps.profile_space,
523		general_tier_flag: sps.tier_flag,
524		general_profile_idc: sps.profile_idc,
525		general_profile_compatibility_flags: sps.profile_compatibility_flags,
526		general_constraint_indicator_flags: sps.constraint_flags,
527		general_level_idc: sps.level_idc,
528		min_spatial_segmentation_idc: 0, // unknown
529		parallelism_type: 0,             // mixed
530		chroma_format_idc: sps.chroma_format_idc,
531		bit_depth_luma_minus8: sps.bit_depth_luma_minus8,
532		bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8,
533		avg_frame_rate: 0, // unspecified
534		constant_frame_rate: 0,
535		num_temporal_layers: sps.max_sub_layers_minus1 + 1,
536		temporal_id_nested: sps.temporal_id_nesting_flag,
537		length_size_minus_one: 3,
538		arrays,
539	}))
540}
541
542/// An hvcC whose parameter sets will arrive in the samples, from a catalog codec
543/// string that already fixes the record.
544///
545/// Main and Main Still Picture are 8-bit 4:2:0. Main 10's depth is 8 or 10, and
546/// any other profile or profile space is not fixed by the codec string.
547pub(crate) fn catalog_hvcc(h265: &hang::catalog::H265) -> Option<Bytes> {
548	if !h265.in_band || h265.profile_space != 0 || !matches!(h265.profile_idc, 1 | 3) {
549		return None;
550	}
551
552	Some(encode_hvcc(&mp4_atom::Hvcc {
553		configuration_version: 1,
554		general_profile_space: h265.profile_space,
555		general_tier_flag: h265.tier_flag,
556		general_profile_idc: h265.profile_idc,
557		general_profile_compatibility_flags: h265.profile_compatibility_flags,
558		general_constraint_indicator_flags: h265.constraint_flags,
559		general_level_idc: h265.level_idc,
560		chroma_format_idc: 1, // 4:2:0
561		// numTemporalLayers 0 leaves temporalIdNested ignored.
562		length_size_minus_one: 3,
563		..Default::default()
564	}))
565}
566
567/// Encode a record whose counts and lengths the caller has already bounded.
568fn encode_hvcc(record: &mp4_atom::Hvcc) -> Bytes {
569	use mp4_atom::Atom;
570	let mut out = BytesMut::new();
571	record
572		.encode_body(&mut out)
573		.expect("mp4-atom masks every hvcC field to its width");
574	out.freeze()
575}
576
577/// Extract the parameter-set NALs (VPS, SPS, PPS in array order) and the NALU
578/// length size from an HEVCDecoderConfigurationRecord. The inverse of
579/// [`build_hvcc`]; used to re-emit out-of-band hvc1 parameter sets as inline
580/// Annex-B (e.g. for MPEG-TS).
581pub(crate) fn hvcc_params(hvcc: &[u8]) -> Result<(usize, Vec<Bytes>)> {
582	let record = decode_hvcc(hvcc)?;
583	let params = record
584		.arrays
585		.into_iter()
586		.flat_map(|array| array.nalus)
587		.map(Bytes::from)
588		.collect();
589	Ok((usize::from(record.length_size_minus_one) + 1, params))
590}
591
592/// Decode an HEVCDecoderConfigurationRecord body with mp4-atom.
593fn decode_hvcc(hvcc: &[u8]) -> Result<mp4_atom::Hvcc> {
594	use mp4_atom::Atom;
595	if hvcc.len() < 23 {
596		return Err(Error::HvccTooShort);
597	}
598	mp4_atom::Hvcc::decode_body(&mut &hvcc[..]).map_err(|_| Error::HvccTruncated)
599}
600
601/// Real parameter sets, mostly from a single-frame x265 encode (1280x720, Main profile),
602/// for tests that need an SPS rather than hand-built bytes, and the fuzz seeds.
603#[cfg(any(test, feature = "fuzz"))]
604#[cfg_attr(
605	not(test),
606	allow(dead_code, reason = "the fuzz seeds use only the Main parameter sets")
607)]
608pub(crate) mod fixtures {
609	use bytes::Bytes;
610
611	pub(crate) const VPS: &[u8] = &[
612		0x40, 0x01, 0x0c, 0x01, 0xff, 0xff, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00,
613		0x03, 0x00, 0x5d, 0x95, 0x98, 0x09,
614	];
615	pub(crate) const SPS: &[u8] = &[
616		0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x5d,
617		0xa0, 0x02, 0x80, 0x80, 0x2d, 0x16, 0x59, 0x59, 0xa4, 0x93, 0x2b, 0xc0, 0x5a, 0x02, 0x00, 0x00, 0x03, 0x00,
618		0x02, 0x00, 0x00, 0x03, 0x00, 0x3c, 0x10,
619	];
620	pub(crate) const PPS: &[u8] = &[0x44, 0x01, 0xc1, 0x72, 0xb4, 0x62, 0x40];
621
622	/// The base-layer SPS from a 128x64 two-view MV-HEVC x265 4.2 encode (`--num-views 2 --format 1`).
623	pub(crate) const MV_SPS: &[u8] = &[
624		0x42, 0x01, 0x01, 0x04, 0x08, 0x00, 0x00, 0x03, 0x00, 0x9f, 0xa8, 0x00, 0x00, 0x03, 0x00, 0x00, 0x1e, 0xa0,
625		0x10, 0x20, 0x41, 0x65, 0xba, 0x92, 0x4c, 0xae, 0x01, 0x00, 0x00, 0x03, 0x03, 0xe8, 0x00, 0x00, 0x61, 0xa8,
626		0x14, 0x04,
627	];
628	/// The same encode's second-view SPS: `nuh_layer_id` 1, `sps_seq_parameter_set_id` 1, and the
629	/// multi-layer layout (`sps_ext_or_max_sub_layers_minus1` 7), which the base layout misreads.
630	pub(crate) const MV_SPS_LAYER1: &[u8] = &[0x42, 0x09, 0x0e, 0x85, 0x92, 0x4c, 0xae, 0x00, 0x50, 0x30];
631	/// The same encode's second-view PPS (`nuh_layer_id` 1, `pps_pic_parameter_set_id` 1).
632	pub(crate) const MV_PPS_LAYER1: &[u8] = &[0x44, 0x09, 0x48, 0x57, 0x2b, 0x02, 0x2a, 0x01, 0x40];
633
634	/// SPS from a 64x64 Main 10 x265 encode with `colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc`.
635	pub(crate) const SPS_HDR10: &[u8] = &[
636		0x42, 0x01, 0x01, 0x02, 0x20, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x1e,
637		0xa0, 0x20, 0x81, 0x04, 0xd9, 0x65, 0x65, 0x4a, 0x4c, 0x2f, 0x01, 0x6a, 0x12, 0x20, 0x12, 0x08, 0x00, 0x00,
638		0x03, 0x00, 0x08, 0x00, 0x00, 0x03, 0x00, 0xc8, 0x40,
639	];
640	/// The same encode's `max-cll=1000,400` prefix SEI.
641	pub(crate) const SEI_CONTENT_LIGHT: &[u8] = &[0x4e, 0x01, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80];
642	/// The same encode's `master-display` prefix SEI: a 1000-nit BT.2020 display with a D65 white point.
643	pub(crate) const SEI_MASTERING: &[u8] = &[
644		0x4e, 0x01, 0x89, 0x18, 0x21, 0x34, 0x9b, 0xaa, 0x19, 0x96, 0x08, 0xfc, 0x8a, 0x48, 0x39, 0x08, 0x3d, 0x13,
645		0x40, 0x42, 0x00, 0x98, 0x96, 0x80, 0x00, 0x00, 0x03, 0x00, 0x32, 0x80,
646	];
647	/// SPS from a 64x64, 25 fps x265 encode with `bframes=3:b-pyramid=1` and HRD signalling
648	/// (`sps_max_num_reorder_pics` 2).
649	pub(crate) const SPS_PYRAMID: &[u8] = &[
650		0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x3c,
651		0xa0, 0x20, 0x81, 0x05, 0x96, 0x56, 0x59, 0x24, 0xca, 0xf0, 0x16, 0x80, 0x80, 0x00, 0x00, 0x03, 0x00, 0x80,
652		0x00, 0x00, 0x0c, 0xb0, 0x0a, 0x48, 0x2f, 0x00, 0x07, 0xa1, 0x20, 0x00, 0xf4, 0x24, 0x40,
653	];
654
655	/// SPS from a Viewtron IP-PTZ-440 (1920x1080 Main@L5.0, 10 fps). Its VUI sets
656	/// `colour_description_present_flag` with `colour_primaries`, `transfer_characteristics`
657	/// and `matrix_coeffs` all 0 on a 4:2:0 stream. ITU-T H.265 E.3.1 forbids `matrix_coeffs`
658	/// 0 there, so the SPS parser keeps only its head; libavcodec and GStreamer accept it.
659	pub(crate) const SPS_ZERO_COLOUR: &[u8] = &[
660		0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00,
661		0x96, 0xa0, 0x03, 0xc0, 0x80, 0x11, 0x07, 0xcb, 0x8a, 0xad, 0x3b, 0xa2, 0x4b, 0xb9, 0x08, 0x00, 0x00, 0x03,
662		0x00, 0x20, 0x05, 0x26, 0x5c, 0x00, 0x33, 0x7f, 0x98, 0x01,
663	];
664
665	/// SPS from a 1280x720, 60 fps hevc_nvenc encode (`p1`, `ull`), the desktop host's shape. Its VUI
666	/// sets `aspect_ratio_idc` 1: square samples.
667	pub(crate) const SPS_NVENC: &[u8] = &[
668		0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x78,
669		0xa0, 0x02, 0x80, 0x80, 0x2e, 0x1f, 0x13, 0x96, 0x5d, 0x29, 0x08, 0x46, 0x45, 0xd5, 0x0c, 0x04, 0x04, 0x00,
670		0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xf1, 0x80, 0x17, 0x79, 0x44, 0x00, 0x02, 0xdc, 0x6c, 0x00,
671		0x00, 0x2d, 0xc6, 0xc0, 0x40,
672	];
673
674	/// SPS from a 1440x1080 hevc_nvenc encode with 4:3 samples (`setsar=4/3`), shown 16:9.
675	pub(crate) const SPS_ANAMORPHIC: &[u8] = &[
676		0x42, 0x01, 0x01, 0x01, 0x60, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x78,
677		0xa0, 0x02, 0xd0, 0x80, 0x11, 0x07, 0xcb, 0x96, 0x5d, 0x29, 0x08, 0x46, 0x45, 0xd5, 0x0c, 0x38, 0x04, 0x00,
678		0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0x79, 0x80, 0x17, 0x79, 0x44, 0x00, 0x02, 0xdc, 0x6c, 0x00,
679		0x00, 0xf4, 0x24, 0x04,
680	];
681
682	/// An hvcC record built from the real parameter sets (4-byte NALU lengths).
683	pub(crate) fn hvcc() -> Bytes {
684		super::build_hvcc(
685			&[Bytes::from_static(VPS)],
686			&[Bytes::from_static(SPS)],
687			&[Bytes::from_static(PPS)],
688		)
689		.expect("real parameter sets must build an hvcC")
690	}
691}
692
693#[cfg(test)]
694mod tests {
695	use super::*;
696	use bytes::BufMut;
697
698	/// Length-prefix each NAL with a 4-byte big-endian length, the hvc1 wire shape.
699	fn length_prefixed(nals: &[&[u8]]) -> Vec<u8> {
700		let mut au = Vec::new();
701		for nal in nals {
702			au.extend_from_slice(&(nal.len() as u32).to_be_bytes());
703			au.extend_from_slice(nal);
704		}
705		au
706	}
707
708	fn ts() -> moq_net::Timestamp {
709		moq_net::Timestamp::from_micros(0).unwrap()
710	}
711
712	#[test]
713	fn sps_reorder_reads_the_highest_sub_layer() {
714		let reorder = sps_reorder(fixtures::SPS_PYRAMID).unwrap();
715		assert_eq!(reorder.depth, 2);
716		assert_eq!(reorder.period, Some((1, 25)));
717		assert_eq!(sps_reorder(&fixtures::SPS[..8]), None);
718	}
719
720	/// A keyframe redefining only an enhancement layer's sets keeps the base layer's in the hvcC.
721	#[test]
722	fn hvc1_keeps_the_base_layer_beside_an_enhancement_update() {
723		let annexb = |nals: &[&[u8]]| {
724			let mut buf = BytesMut::new();
725			for nal in nals {
726				buf.extend_from_slice(&[0, 0, 0, 1]);
727				buf.extend_from_slice(nal);
728			}
729			buf.freeze()
730		};
731		let idr: &[u8] = &[0x26, 0x01, 0x80, 0xaa];
732		let mut hvc1 = Hvc1::new();
733		hvc1.transform(annexb(&[fixtures::VPS, fixtures::MV_SPS, fixtures::PPS, idr]))
734			.unwrap();
735		hvc1.transform(annexb(&[fixtures::MV_SPS_LAYER1, fixtures::MV_PPS_LAYER1, idr]))
736			.unwrap();
737		let params = Hvcc::parse(hvc1.hvcc().unwrap()).unwrap();
738		assert_eq!(params.sps, [fixtures::MV_SPS, fixtures::MV_SPS_LAYER1]);
739		assert_eq!(params.pps, [fixtures::PPS, fixtures::MV_PPS_LAYER1]);
740	}
741
742	/// hvc1: a length-prefixed access unit with an IDR slice wraps as one keyframe;
743	/// the payload is passed through verbatim. The leading prefix-SEI NAL exercises
744	/// the walk past non-slice NALs.
745	#[test]
746	fn hvc1_frame_keyframe() {
747		let sei: &[u8] = &[0x4e, 0x01, 0x05, 0xff]; // PrefixSeiNut (39)
748		let idr: &[u8] = &[0x26, 0x01, 0x80, 0xaa]; // IdrWRadl (19)
749		let au = length_prefixed(&[sei, idr]);
750
751		let frame = hvc1_frame(&au, 4, ts()).unwrap();
752		assert!(frame.keyframe);
753		assert_eq!(frame.payload, au);
754	}
755
756	/// hvc1: CRA opens a group too; HEVC random access is broader than IDR.
757	#[test]
758	fn hvc1_frame_cra_keyframe() {
759		let cra: &[u8] = &[0x2a, 0x01, 0x80, 0x55]; // CraNut (21)
760		let au = length_prefixed(&[cra]);
761
762		let frame = hvc1_frame(&au, 4, ts()).unwrap();
763		assert!(frame.keyframe);
764	}
765
766	/// hvc1: a trailing delta slice is not a keyframe.
767	#[test]
768	fn hvc1_frame_delta() {
769		let trail: &[u8] = &[0x02, 0x01, 0x80, 0x33]; // TrailR (1)
770		let au = length_prefixed(&[trail]);
771
772		let frame = hvc1_frame(&au, 4, ts()).unwrap();
773		assert!(!frame.keyframe);
774	}
775
776	/// hvc1: a NAL header whose low five bits read as an H.264 IDR (0x05) is a
777	/// TsaN delta slice under the 2-byte HEVC header and must not be flagged a
778	/// keyframe.
779	#[test]
780	fn hvc1_frame_tsa_delta_not_h264_idr() {
781		let tsa: &[u8] = &[0x05, 0x01, 0x80, 0x33]; // TsaN (2)
782		let au = length_prefixed(&[tsa]);
783
784		let frame = hvc1_frame(&au, 4, ts()).unwrap();
785		assert!(!frame.keyframe);
786	}
787
788	/// The real-SPS fixture resolves a full out-of-band config: dimensions from
789	/// the parsed SPS and the hvcC itself as the catalog `description`.
790	/// The hvcC's SPS signals the colour; a refused SPS signals none rather than failing.
791	#[test]
792	fn hvcc_config_reads_the_sps_colour() {
793		let hvcc = |sps: &'static [u8]| {
794			build_hvcc(
795				&[Bytes::from_static(fixtures::VPS)],
796				&[Bytes::from_static(sps)],
797				&[Bytes::from_static(fixtures::PPS)],
798			)
799			.unwrap()
800		};
801		let color = config_from_hvcc(&hvcc(fixtures::SPS_HDR10)).unwrap().color.unwrap();
802		assert_eq!(
803			(color.primaries, color.transfer, color.matrix, color.range),
804			(Some(9), Some(16), Some(9), Some(hang::catalog::ColorRange::Limited))
805		);
806		assert_eq!(config_from_hvcc(&hvcc(fixtures::SPS)).unwrap().color, None);
807		assert_eq!(config_from_hvcc(&hvcc(fixtures::SPS_ZERO_COLOUR)).unwrap().color, None);
808	}
809
810	#[test]
811	fn config_from_hvcc_resolves_real_sps() {
812		let hvcc = fixtures::hvcc();
813		let config = config_from_hvcc(&hvcc).unwrap();
814
815		let hang::catalog::VideoCodec::H265(h265) = &config.codec else {
816			panic!("expected H.265 codec")
817		};
818		assert!(!h265.in_band, "hvcC config is out-of-band");
819		assert_eq!(config.coded_width, Some(1280));
820		assert_eq!(config.coded_height, Some(720));
821		assert_eq!(config.description.as_deref(), Some(hvcc.as_ref()));
822	}
823
824	/// Hand-build an hvcC (the layout `build_hvcc` emits) and assert the
825	/// parameter sets and length size are recovered. Built by hand rather than
826	/// via `build_hvcc` so it doesn't need a real, parseable HEVC SPS.
827	#[test]
828	fn hvcc_params_parses_vps_sps_pps() {
829		let vps = &[0x40, 0x01, 0x0c][..]; // NAL type 32
830		let sps = &[0x42, 0x01, 0x01, 0x60][..]; // NAL type 33
831		let pps = &[0x44, 0x01, 0xc0][..]; // NAL type 34
832
833		let mut hvcc = BytesMut::new();
834		hvcc.extend_from_slice(&[0u8; 21]); // fixed fields up to (but not including) byte 21
835		hvcc.put_u8(0xfc | 0x03); // byte 21: ...| lengthSizeMinusOne = 3 -> length_size 4
836		hvcc.put_u8(3); // numOfArrays
837		for (nal_type, nal) in [(NalType::VPS.0, vps), (NalType::SPS.0, sps), (NalType::PPS.0, pps)] {
838			hvcc.put_u8(0x80 | (nal_type & 0x3f));
839			hvcc.put_u16(1); // numNalus
840			hvcc.put_u16(nal.len() as u16);
841			hvcc.put_slice(nal);
842		}
843
844		let (length_size, params) = hvcc_params(&hvcc).unwrap();
845		assert_eq!(length_size, 4);
846		assert_eq!(params.len(), 3);
847		assert_eq!(params[0].as_ref(), vps);
848		assert_eq!(params[1].as_ref(), sps);
849		assert_eq!(params[2].as_ref(), pps);
850	}
851
852	/// hev1: an inline SPS whose VUI carries zeroed colour fields on 4:2:0 still configures the
853	/// rendition from the fields before the VUI.
854	#[test]
855	fn hev1_config_tolerates_zeroed_colour_description() {
856		let mut annexb = Vec::new();
857		for nal in [fixtures::VPS, fixtures::SPS_ZERO_COLOUR, fixtures::PPS] {
858			annexb.extend_from_slice(&[0, 0, 0, 1]);
859			annexb.extend_from_slice(nal);
860		}
861		let config = config(&annexb).expect("the SPS head is well-formed");
862		let hang::catalog::VideoCodec::H265(h265) = &config.codec else {
863			panic!("expected H.265 codec")
864		};
865		assert!(h265.in_band);
866		assert_eq!(h265.to_string(), "hev1.1.6.L150");
867		assert_eq!((config.coded_width, config.coded_height), (Some(1920), Some(1080)));
868	}
869
870	/// hvc1: the same SPS builds an hvcC and resolves an out-of-band config. The record header
871	/// matches, byte for byte, the one GStreamer's h265parse builds from this SPS.
872	#[test]
873	fn hvcc_tolerates_zeroed_colour_description() {
874		let hvcc = build_hvcc(
875			&[Bytes::from_static(fixtures::VPS)],
876			&[Bytes::from_static(fixtures::SPS_ZERO_COLOUR)],
877			&[Bytes::from_static(fixtures::PPS)],
878		)
879		.expect("the SPS head is well-formed");
880		assert_eq!(
881			&hvcc[..23],
882			&[
883				0x01, 0x01, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x96, 0xf0, 0x00, 0xfc, 0xfd,
884				0xf8, 0xf8, 0x00, 0x00, 0x0f, 0x03,
885			]
886		);
887		let config = config_from_hvcc(&hvcc).unwrap();
888		assert_eq!((config.coded_width, config.coded_height), (Some(1920), Some(1080)));
889	}
890
891	/// The SPS and catalog paths keep `profile_compatibility_flags` as raw
892	/// big-endian bytes, including across codec-string formatting and parsing.
893	#[test]
894	fn bitstream_and_catalog_paths_agree() {
895		use std::str::FromStr;
896
897		let config = config_from_hvcc(&fixtures::hvcc()).unwrap();
898		let hang::catalog::VideoCodec::H265(h265) = &config.codec else {
899			panic!("expected H.265 codec")
900		};
901
902		// x265 Main profile: general_profile_compatibility_flag[1] and [2] set.
903		assert_eq!(h265.profile_compatibility_flags, [0x60, 0, 0, 0]);
904
905		let encoded = h265.to_string();
906		assert_eq!(encoded, "hvc1.1.6.L93.90");
907
908		let parsed = hang::catalog::H265::from_str(&encoded).unwrap();
909		assert_eq!(parsed.profile_compatibility_flags, h265.profile_compatibility_flags);
910	}
911
912	fn hevc(profile_idc: u8, in_band: bool, profile_space: u8) -> hang::catalog::H265 {
913		hang::catalog::H265 {
914			in_band,
915			profile_space,
916			profile_idc,
917			profile_compatibility_flags: [0x60, 0, 0, 0],
918			tier_flag: false,
919			level_idc: 93,
920			constraint_flags: [0x90, 0, 0, 0, 0, 0],
921		}
922	}
923
924	fn decode_hvcc(bytes: &Bytes) -> mp4_atom::Hvcc {
925		use mp4_atom::Atom;
926		mp4_atom::Hvcc::decode_body(&mut std::io::Cursor::new(bytes.as_ref())).unwrap()
927	}
928
929	#[test]
930	fn catalog_hvcc_main_and_still_picture_round_trip() {
931		for profile_idc in [1, 3] {
932			let hvcc = decode_hvcc(&catalog_hvcc(&hevc(profile_idc, true, 0)).unwrap());
933			assert_eq!(hvcc.general_profile_idc, profile_idc);
934			assert_eq!(hvcc.general_profile_space, 0);
935			assert!(!hvcc.general_tier_flag);
936			assert_eq!(hvcc.general_profile_compatibility_flags, [0x60, 0, 0, 0]);
937			assert_eq!(hvcc.general_constraint_indicator_flags, [0x90, 0, 0, 0, 0, 0]);
938			assert_eq!(hvcc.general_level_idc, 93);
939			assert_eq!(hvcc.chroma_format_idc, 1);
940			assert_eq!(hvcc.bit_depth_luma_minus8, 0);
941			assert_eq!(hvcc.bit_depth_chroma_minus8, 0);
942			assert_eq!(hvcc.length_size_minus_one, 3);
943			assert_eq!(hvcc.num_temporal_layers, 0);
944			assert!(!hvcc.temporal_id_nested);
945			assert!(hvcc.arrays.is_empty());
946		}
947	}
948
949	#[test]
950	fn catalog_hvcc_refuses_profiles_the_string_cannot_describe() {
951		assert!(catalog_hvcc(&hevc(2, true, 0)).is_none(), "Main 10");
952		assert!(catalog_hvcc(&hevc(1, true, 1)).is_none(), "profile space");
953		assert!(catalog_hvcc(&hevc(1, false, 0)).is_none(), "out of band");
954	}
955
956	/// An hvcC listing an SPS for each view, the enhancement layer's first: the catalog reads the
957	/// base layer's, an hvcC listing only the enhancement layer's is refused, and one listing no
958	/// SPS leaves the config to the in-band SPS.
959	#[test]
960	fn hvcc_reads_only_the_base_layer_sps() {
961		let layered = build_hvcc(
962			&[Bytes::from_static(fixtures::VPS)],
963			&[
964				Bytes::from_static(fixtures::MV_SPS_LAYER1),
965				Bytes::from_static(fixtures::MV_SPS),
966			],
967			&[Bytes::from_static(fixtures::PPS)],
968		)
969		.unwrap();
970		let config = config_from_hvcc(&layered).unwrap();
971		assert_eq!((config.coded_width, config.coded_height), (Some(128), Some(64)));
972		let mut applied = config.clone();
973		applied.reorder = Some(9);
974		apply_hvcc_sps(&decode_hvcc(&layered), &mut applied).unwrap();
975		assert_eq!(applied.reorder, config.reorder);
976
977		let mut record = decode_hvcc(&layered);
978		let with_sps = |record: &mp4_atom::Hvcc, sps: Vec<Vec<u8>>| {
979			let mut record = record.clone();
980			for array in &mut record.arrays {
981				if NalType(array.nal_unit_type) == NalType::SPS {
982					array.nalus = sps.clone();
983				}
984			}
985			record
986		};
987		let enhancement = with_sps(&record, vec![fixtures::MV_SPS_LAYER1.to_vec()]);
988		assert!(matches!(
989			config_from_hvcc(&encode_hvcc(&enhancement)),
990			Err(Error::NoBaseLayerSps)
991		));
992		assert!(matches!(
993			apply_hvcc_sps(&enhancement, &mut config.clone()),
994			Err(Error::NoBaseLayerSps)
995		));
996		assert!(matches!(
997			build_hvcc(
998				&[Bytes::from_static(fixtures::VPS)],
999				&[Bytes::from_static(fixtures::MV_SPS_LAYER1)],
1000				&[Bytes::from_static(fixtures::PPS)],
1001			),
1002			Err(Error::NoBaseLayerSps)
1003		));
1004
1005		record
1006			.arrays
1007			.retain(|array| NalType(array.nal_unit_type) != NalType::SPS);
1008		let mut untouched = config.clone();
1009		apply_hvcc_sps(&record, &mut untouched).unwrap();
1010		assert_eq!(untouched, config);
1011	}
1012}