Skip to main content

moq_mux/codec/aac/
mod.rs

1//! AAC.
2//!
3//! ISO 14496-3 AudioSpecificConfig parse and encode lives in [`Config`].
4//! [`Import`] publishes raw AAC frames (not ADTS) to a moq broadcast.
5
6/// ADTS framing for AAC packets without an AudioSpecificConfig.
7pub mod adts;
8
9mod import;
10
11pub use import::*;
12
13use bytes::{Buf, Bytes};
14
15/// AAC parsing errors.
16#[derive(Debug, Clone, thiserror::Error)]
17#[non_exhaustive]
18pub enum Error {
19	/// The AudioSpecificConfig is shorter than its two-byte minimum.
20	#[error("AudioSpecificConfig must be at least 2 bytes")]
21	ConfigTooShort,
22
23	/// The extended audioObjectType is truncated.
24	#[error("extended audioObjectType requires 2 additional bytes")]
25	ExtendedConfigTooShort,
26
27	/// The AudioSpecificConfig ends before its required fields.
28	#[error("AudioSpecificConfig incomplete")]
29	IncompleteConfig,
30
31	/// The explicit sample rate is truncated.
32	#[error("explicit sample rate requires 3 additional bytes")]
33	ExplicitSampleRateTooShort,
34
35	/// The sample rate index is unsupported.
36	#[error("unsupported sample rate index: {0}")]
37	UnsupportedSampleRateIndex(u8),
38
39	/// The channelConfiguration is a reserved value (8, 9, 10, or 15).
40	#[error("reserved channelConfiguration: {0}")]
41	ReservedChannelConfig(u8),
42
43	/// A channel count that does not pick a channelConfiguration on its own.
44	///
45	/// Counts 1 through 6 are that configuration, and 8 channels are configuration 7 (7.1).
46	/// Seven channels (6.1, or configuration 11) and 24 (22.2, configuration 13) have a
47	/// configuration but also program config element layouts, so the speaker positions are
48	/// not guessed. Every other count has no configuration at all.
49	#[error("cannot pick a channelConfiguration for {0} channels")]
50	UnsupportedChannelCount(u32),
51
52	/// A program config element is used with an object type that has no GASpecificConfig.
53	#[error("channelConfiguration 0 is unsupported for audioObjectType {0}")]
54	ProgramConfigUnsupported(u8),
55
56	/// ADTS signals a program config element, but none leads the first raw data block.
57	#[error("channelConfiguration 0 without a program config element leading the first raw data block")]
58	ProgramConfigMissing,
59
60	/// The program config element ends before its declared fields.
61	#[error("program config element truncated")]
62	ProgramConfigTruncated,
63
64	/// The program config element declares zero channels.
65	#[error("program config element declares no channels")]
66	ProgramConfigEmpty,
67
68	/// Raw AAC publication needs an AudioSpecificConfig in the catalog.
69	#[error("raw AAC publication requires an AudioSpecificConfig description")]
70	MissingDescription,
71
72	/// The AudioSpecificConfig carries syntax an exact parse does not read, such as another object
73	/// type's specific config.
74	#[error("unsupported AudioSpecificConfig: {0}")]
75	UnsupportedConfig(&'static str),
76
77	/// Whole bytes follow the AudioSpecificConfig's last field.
78	#[error("{0} bytes after the AudioSpecificConfig")]
79	TrailingBytes(usize),
80
81	/// An ADTS header or frame is invalid, or cannot carry the frame.
82	#[error("adts: {0}")]
83	Adts(#[from] adts::Error),
84}
85
86/// A result using this module's error type.
87pub type Result<T> = std::result::Result<T, Error>;
88
89/// Typed AAC configuration mirroring the relevant fields of an
90/// AudioSpecificConfig.
91///
92/// Marked `#[non_exhaustive]`: build one with [`new`](Self::new) or [`parse`](Self::parse).
93#[non_exhaustive]
94pub struct Config {
95	/// The leading audioObjectType: 2 for AAC-LC, 5 for HE-AAC (SBR), 29 for HE-AACv2 (PS).
96	pub profile: u8,
97	/// The decoded output rate: under SBR, the extension rate rather than the core's.
98	pub sample_rate: u32,
99	/// The decoded output channels: two under PS, which a mono core carries.
100	pub channel_count: u32,
101}
102
103impl Config {
104	/// A config for `profile` (the audioObjectType) at the decoded `sample_rate` and `channel_count`.
105	pub fn new(profile: u8, sample_rate: u32, channel_count: u32) -> Self {
106		Self {
107			profile,
108			sample_rate,
109			channel_count,
110		}
111	}
112
113	/// Parse an AudioSpecificConfig buffer.
114	///
115	/// Handles basic formats (object_type < 31), extended formats
116	/// (object_type == 31), and explicit sample rates (freq_index == 15). The
117	/// fields are bit-packed and not byte-aligned, so a bit reader is required:
118	/// with an explicit 24-bit rate the channelConfiguration lands mid-byte after
119	/// it. A channelConfiguration of 0 takes the count from the program config element
120	/// that follows, and a reserved one is refused.
121	///
122	/// Explicit SBR and PS report what the stream plays as, the extension rate and stereo, not
123	/// their AAC-LC core, whether signaled hierarchically (audioObjectType 5 or 29) or by a
124	/// backward-compatible sync extension, which then reports profile 5 or 29 too. Implicit SBR,
125	/// found only in band, reports the core, as does a sync extension behind fields this parser
126	/// doesn't follow. The whole buffer is consumed.
127	pub fn parse<T: Buf>(buf: &mut T) -> Result<Self> {
128		// The whole buffer is the config, extensions included, so it is consumed.
129		let data = buf.copy_to_bytes(buf.remaining());
130		let mut asc = data.as_ref();
131		let len = asc.len();
132		let mut reader = BitReader::new(&mut asc);
133		let (mut config, fields) = Self::read(&mut reader)?;
134		// Whatever the later fields recognized before one this parser doesn't follow still holds,
135		// so SBR found ahead of an unknown field isn't lost to the core.
136		let _ = Self::read_rest(&mut reader, len, &mut config, fields);
137		Ok(config)
138	}
139
140	/// Parse an AudioSpecificConfig that spans `asc`, at most [`CONFIG_MAX_LEN`] bytes.
141	///
142	/// Unlike [`parse`](Self::parse), every field is read: a GASpecificConfig's (the AAC object
143	/// types), any error resilience `epConfig` without its protection config, and the
144	/// backward-compatible SBR and PS signaling of a sync extension. Another object type's specific
145	/// config, or any whole byte past the last field, is refused.
146	pub(crate) fn parse_exact(mut asc: &[u8]) -> Result<Self> {
147		let len = asc.len();
148		let mut reader = BitReader::new(&mut asc);
149		let (mut config, fields) = Self::read(&mut reader)?;
150		Self::read_rest(&mut reader, len, &mut config, fields)?;
151		match len - reader.position().div_ceil(8) {
152			0 => Ok(config),
153			trailing => Err(Error::TrailingBytes(trailing)),
154		}
155	}
156
157	/// Read the fields after [`read`](Self::read)'s, in a config `len` bytes long: the rest of
158	/// the specific config, then any sync extension, which names what an SBR or PS decoder
159	/// plays the core as: the extension rate, and stereo under PS, as explicit signaling would.
160	/// Each finding updates `config` whole as soon as it is read, so an error after one keeps it.
161	fn read_rest<T: Buf>(reader: &mut BitReader<T>, len: usize, config: &mut Self, fields: Fields) -> Result<()> {
162		let Fields {
163			object_type,
164			core,
165			channel_config,
166			extension,
167		} = fields;
168
169		// The rest of the GASpecificConfig: channelConfiguration 0 already read through its
170		// program config element.
171		let extension = match (channel_config, extension) {
172			(0, extension) => extension.expect("a program config follows a GASpecificConfig"),
173			_ if GENERAL_AUDIO.contains(&core) => read_general_audio(reader, core)?,
174			_ => return Err(Error::UnsupportedConfig("specific config of a non-AAC object type")),
175		};
176		let mut read = |n| reader.read(n, Error::IncompleteConfig);
177		if matches!(core, 6 | 20) {
178			// layerNr.
179			read(3)?;
180		}
181		if extension {
182			match core {
183				// numOfSubFrame and layer_length.
184				22 => _ = read(16)?,
185				// The section, scalefactor, and spectral data resilience flags.
186				17 | 19 | 20 | 23 => _ = read(3)?,
187				_ => {}
188			}
189			if read(1)? == 1 {
190				return Err(Error::UnsupportedConfig("extensionFlag3"));
191			}
192		}
193		// The error resilient AAC object types' epConfig, whose values 2 and 3 add an
194		// ErrorProtectionSpecificConfig.
195		if matches!(core, 17 | 19..=23) && read(2)? >= 2 {
196			return Err(Error::UnsupportedConfig("ErrorProtectionSpecificConfig"));
197		}
198
199		// A sync extension signals SBR and PS behind a core that older decoders play alone.
200		if !matches!(object_type, OBJECT_TYPE_SBR | OBJECT_TYPE_PS) && len * 8 - reader.position() >= 16 {
201			if reader.read(11, Error::IncompleteConfig)? != SYNC_EXTENSION_SBR {
202				return Err(Error::UnsupportedConfig("sync extension"));
203			}
204			let extension = read_object_type(reader)?;
205			if !matches!(extension, OBJECT_TYPE_SBR | 22) {
206				return Err(Error::UnsupportedConfig("sync extension object type"));
207			}
208			// sbrPresentFlag, then the extension rate.
209			let sbr = reader.read(1, Error::IncompleteConfig)? == 1;
210			if sbr {
211				config.sample_rate = read_sample_rate(reader)?;
212				if extension == OBJECT_TYPE_SBR {
213					config.profile = OBJECT_TYPE_SBR;
214				}
215			}
216			if extension == 22 {
217				// extensionChannelConfiguration.
218				reader.read(4, Error::IncompleteConfig)?;
219			} else if sbr && len * 8 - reader.position() >= 12 {
220				if reader.read(11, Error::IncompleteConfig)? != SYNC_EXTENSION_PS {
221					return Err(Error::UnsupportedConfig("sync extension"));
222				}
223				// psPresentFlag.
224				if reader.read(1, Error::IncompleteConfig)? == 1 {
225					config.profile = OBJECT_TYPE_PS;
226					config.channel_count = 2;
227				}
228			}
229		}
230		Ok(())
231	}
232
233	/// Read the fields up to a channelConfiguration 0's program config element, which gives the
234	/// channel count.
235	fn read<T: Buf>(reader: &mut BitReader<T>) -> Result<(Self, Fields)> {
236		let (object_type, core_rate, channel_config) = read_header(reader)?;
237		let (core, sample_rate) = read_core(reader, object_type, core_rate)?;
238		let (channel_count, extension) = match channel_config {
239			0 => {
240				let extension = read_general_audio(reader, core)?;
241				(program_config(reader)?, Some(extension))
242			}
243			_ => (channel_count_from_config(channel_config)?, None),
244		};
245		let channel_count = if object_type == OBJECT_TYPE_PS {
246			2
247		} else {
248			channel_count
249		};
250
251		let config = Self {
252			profile: object_type,
253			sample_rate,
254			channel_count,
255		};
256		let fields = Fields {
257			object_type,
258			core,
259			channel_config,
260			extension,
261		};
262		Ok((config, fields))
263	}
264
265	/// Encode this configuration as an AudioSpecificConfig (ISO 14496-3 §1.6.2.1).
266	///
267	/// Standard sample rates produce 2 bytes; non-standard rates fall back to
268	/// the 5-byte form with an explicit 24-bit frequency. SBR and PS are signaled explicitly
269	/// over an AAC-LC core at half the output rate, mono under PS. A channel count that does
270	/// not pick a channelConfiguration is refused rather than written as another layout.
271	pub fn encode(&self) -> Result<Bytes> {
272		let profile = self.profile;
273
274		let mut out = BitWriter::default();
275		// audioObjectType 32 and above escapes the 5-bit field with 31 and a 6-bit extension.
276		if profile >= 32 {
277			out.write(5, 31);
278			out.write(6, u32::from(profile - 32));
279		} else {
280			out.write(5, profile.into());
281		}
282		if matches!(profile, OBJECT_TYPE_SBR | OBJECT_TYPE_PS) {
283			let channel_count = if profile == OBJECT_TYPE_PS {
284				1
285			} else {
286				self.channel_count
287			};
288			write_sample_rate(&mut out, self.sample_rate / 2);
289			out.write(4, channel_config_from_count(channel_count)?.into());
290			write_sample_rate(&mut out, self.sample_rate);
291			out.write(5, OBJECT_TYPE_LC.into());
292		} else {
293			write_sample_rate(&mut out, self.sample_rate);
294			out.write(4, channel_config_from_count(self.channel_count)?.into());
295		}
296		// GASpecificConfig: frameLengthFlag, dependsOnCoreCoder, and extensionFlag, all clear.
297		out.write(3, 0);
298		Ok(Bytes::from(out.bytes))
299	}
300}
301
302/// What [`Config::read`] leaves for [`Config::parse_exact`] to finish with.
303struct Fields {
304	object_type: u8,
305	/// The object type of the specific config: under explicit SBR or PS, their core's.
306	core: u8,
307	channel_config: u8,
308	/// The GASpecificConfig's extensionFlag, when it was read for a program config element.
309	extension: Option<bool>,
310}
311
312/// The longest AudioSpecificConfig [`Config::parse_exact`] accepts, in bits, summing each field's
313/// maximum: an escaped object type, explicit rate, and channelConfiguration (43); explicit SBR or
314/// PS (43); a GASpecificConfig's flags and core coder delay (17); a program config element with 15
315/// front, side, back, and coupling elements, 3 LFE, 7 data elements, every mixdown, alignment, and
316/// a 255-byte comment (2440); layerNr and the extension fields (23); `epConfig` (2); and a sync
317/// extension with SBR and PS (63).
318const CONFIG_MAX_BITS: usize = 43 + 43 + 17 + 2440 + 23 + 2 + 63;
319
320/// The longest AudioSpecificConfig [`Config::parse_exact`] accepts, in bytes.
321pub(crate) const CONFIG_MAX_LEN: usize = CONFIG_MAX_BITS.div_ceil(8);
322
323/// The samples each frame of an AAC-LC core codes, 960 or 1024 by its frameLengthFlag, and the
324/// rate it codes them at, which SBR may double on output. `None` for another core, or a config
325/// that doesn't parse.
326pub(crate) fn frame_clock(asc: &[u8]) -> Option<(u32, u32)> {
327	// Refuses what the exact walk below doesn't check, such as a reserved channelConfiguration.
328	Config::parse(&mut &asc[..]).ok()?;
329	let mut asc = asc;
330	let mut reader = BitReader::new(&mut asc);
331	// The leading rate is the core's: explicit SBR and PS name their output rate after it.
332	let (object_type, rate, _) = read_header(&mut reader).ok()?;
333	if !matches!(object_type, OBJECT_TYPE_LC | OBJECT_TYPE_SBR | OBJECT_TYPE_PS) {
334		return None;
335	}
336	if read_core(&mut reader, object_type, rate).ok()?.0 != OBJECT_TYPE_LC {
337		return None;
338	}
339	// The GASpecificConfig's first field, ahead of any program config element.
340	let samples = match reader.read(1, Error::IncompleteConfig).ok()? {
341		0 => 1024,
342		_ => 960,
343	};
344	Some((samples, rate))
345}
346
347/// Read an AudioSpecificConfig's leading fields: the audioObjectType, sample rate, and
348/// channelConfiguration.
349fn read_header<T: Buf>(reader: &mut BitReader<T>) -> Result<(u8, u32, u8)> {
350	if reader.remaining().is_none_or(|remaining| remaining < 2) {
351		return Err(Error::ConfigTooShort);
352	}
353	let object_type = read_object_type(reader)?;
354
355	let sample_rate = read_sample_rate(reader)?;
356
357	// channelConfiguration: 4 bits, immediately after the (possibly explicit) rate.
358	let channel_config = reader.read(4, Error::IncompleteConfig)? as u8;
359	Ok((object_type, sample_rate, channel_config))
360}
361
362/// Read the core audioObjectType and the output rate, which explicit SBR and PS name ahead of
363/// their core. Any other object type is its own core at the leading `sample_rate`.
364fn read_core<T: Buf>(reader: &mut BitReader<T>, object_type: u8, sample_rate: u32) -> Result<(u8, u32)> {
365	if !matches!(object_type, OBJECT_TYPE_SBR | OBJECT_TYPE_PS) {
366		return Ok((object_type, sample_rate));
367	}
368	let output_rate = read_sample_rate(reader)?;
369	let core = read_object_type(reader)?;
370	if core == 22 {
371		// extensionChannelConfiguration, only for ER BSAC.
372		reader.read(4, Error::IncompleteConfig)?;
373	}
374	Ok((core, output_rate))
375}
376
377/// Read a samplingFrequencyIndex, escaped to an explicit 24-bit rate when it reads 15.
378fn read_sample_rate<T: Buf>(reader: &mut BitReader<T>) -> Result<u32> {
379	let index = reader.read(4, Error::IncompleteConfig)? as u8;
380	if index == 15 {
381		return match reader.read(24, Error::ExplicitSampleRateTooShort)? {
382			0 => Err(Error::UnsupportedConfig("an explicit sample rate of zero")),
383			rate => Ok(rate),
384		};
385	}
386	SAMPLE_RATES
387		.get(index as usize)
388		.copied()
389		.ok_or(Error::UnsupportedSampleRateIndex(index))
390}
391
392/// Write a samplingFrequencyIndex, or the escape and the low 24 bits of a rate the table lacks.
393fn write_sample_rate(out: &mut BitWriter, sample_rate: u32) {
394	match SAMPLE_RATES.iter().position(|&rate| rate == sample_rate) {
395		Some(index) => out.write(4, index as u32),
396		None => {
397			out.write(4, 15);
398			out.write(24, sample_rate);
399		}
400	}
401}
402
403/// Read a GASpecificConfig up to the program config element that a channelConfiguration of 0
404/// puts next, refusing a `core` object type whose specific config is something else. Returns its
405/// extensionFlag.
406fn read_general_audio<T: Buf>(reader: &mut BitReader<T>, core: u8) -> Result<bool> {
407	if !GENERAL_AUDIO.contains(&core) {
408		return Err(Error::ProgramConfigUnsupported(core));
409	}
410
411	// frameLengthFlag, dependsOnCoreCoder (then a 14-bit coreCoderDelay), and extensionFlag.
412	reader.read(1, Error::IncompleteConfig)?;
413	if reader.read(1, Error::IncompleteConfig)? == 1 {
414		reader.read(14, Error::IncompleteConfig)?;
415	}
416	Ok(reader.read(1, Error::IncompleteConfig)? == 1)
417}
418
419/// How long one access unit of the AudioSpecificConfig `asc` plays: 1024 core samples, or 960 by
420/// its frameLengthFlag (512 or 480 for low delay), at the core's rate, which SBR and PS double
421/// along with the samples. `None` for an object type that codes frames of another length, or a
422/// config that doesn't parse.
423pub(crate) fn frame_duration(mut asc: &[u8]) -> Option<moq_net::Timestamp> {
424	let mut reader = BitReader::new(&mut asc);
425	let (object_type, core_rate, _) = read_header(&mut reader).ok()?;
426	let (core, _) = read_core(&mut reader, object_type, core_rate).ok()?;
427	// Main, LC, SSR, LTP, scalable, and their error-resilient forms, and ER AAC LD and ELD; the
428	// GASpecificConfig or ELDSpecificConfig leads with frameLengthFlag.
429	let (long, short) = match core {
430		1..=4 | 6 | 17 | 19 | 20 => (1024, 960),
431		23 | 39 => (512, 480),
432		_ => return None,
433	};
434	let samples = match reader.read(1, Error::IncompleteConfig).ok()? {
435		0 => long,
436		_ => short,
437	};
438	moq_net::Timestamp::from_scale(samples, core_rate.into()).ok()
439}
440
441/// Whether the raw data block `block` leads with a program config element.
442pub(crate) fn leads_with_program_config(block: &[u8]) -> bool {
443	block.first().is_some_and(|&byte| u32::from(byte >> 5) == ID_PCE)
444}
445
446/// Build the AudioSpecificConfig for a stream that signals its fields per frame, as ADTS does.
447///
448/// A `channel_config` of 0 means a program config element leads `block`, the stream's first raw
449/// data block; it moves into the config, so the config describes the channels on its own, and
450/// `block` advances past it. Any other value leaves `block` untouched. An element placed anywhere
451/// else is refused: reaching past the channel data needs a full Huffman decode.
452pub(crate) fn in_band_config(profile: u8, sample_rate: u32, channel_config: u8, block: &mut &[u8]) -> Result<Bytes> {
453	let mut out = BitWriter::default();
454	out.write(5, u32::from(profile & 0x1F));
455	write_sample_rate(&mut out, sample_rate);
456	out.write(4, u32::from(channel_config));
457
458	if channel_config == 0 {
459		// GASpecificConfig: frameLengthFlag, dependsOnCoreCoder, and extensionFlag, all clear.
460		out.write(3, 0);
461
462		// The element ends byte aligned to the block, so the reader stops exactly past it.
463		let mut reader = BitReader::new(block);
464		if reader.read(3, Error::ProgramConfigMissing)? != ID_PCE {
465			return Err(Error::ProgramConfigMissing);
466		}
467		reader.record = Some(out);
468		program_config(&mut reader)?;
469		out = reader.record.take().expect("recording set above");
470	}
471
472	Ok(Bytes::from(out.bytes))
473}
474
475/// The fields a stream that signals its config per frame, as ADTS does, carries in each header.
476#[derive(Clone, Debug, PartialEq)]
477pub(crate) struct InBand {
478	/// The core audioObjectType. Explicit SBR and PS name it under their own, and a decoder finds
479	/// them again in band, as it would in a stream that never signaled them (implicit signaling).
480	pub object_type: u8,
481	/// The core's sample rate, which SBR doubles on output.
482	pub sample_rate: u32,
483	pub channel_config: u8,
484	/// When `channel_config` is 0, the program config element framed to lead a raw data block:
485	/// its element ID, then the element aligned to the block.
486	pub program_config: Option<Bytes>,
487}
488
489/// Split an AudioSpecificConfig into what a stream that carries it per frame signals, as ADTS
490/// does; the inverse of [`in_band_config`].
491pub(crate) fn in_band(asc: &[u8]) -> Result<InBand> {
492	let mut asc = asc;
493	let mut reader = BitReader::new(&mut asc);
494	let (object_type, sample_rate, channel_config) = read_header(&mut reader)?;
495	let (core, _) = read_core(&mut reader, object_type, sample_rate)?;
496
497	let program_config = match channel_config {
498		0 => {
499			read_general_audio(&mut reader, core)?;
500			let mut out = BitWriter::default();
501			out.write(3, ID_PCE);
502			reader.record = Some(out);
503			program_config(&mut reader)?;
504			Some(Bytes::from(reader.record.take().expect("recording set above").bytes))
505		}
506		_ => None,
507	};
508
509	Ok(InBand {
510		object_type: core,
511		sample_rate,
512		channel_config,
513		program_config,
514	})
515}
516
517/// The audioObjectTypes of AAC-LC, of SBR (HE-AAC), and of SBR with PS (HE-AACv2).
518const OBJECT_TYPE_LC: u8 = 2;
519const OBJECT_TYPE_SBR: u8 = 5;
520const OBJECT_TYPE_PS: u8 = 29;
521
522/// The raw data block element ID of a program config element (ISO 14496-3 Table 4.85).
523const ID_PCE: u32 = 5;
524
525/// The audioObjectTypes whose specific config is a GASpecificConfig (ISO 14496-3 §1.6.2.1), the
526/// only ones where channelConfiguration 0 means a program config element follows.
527const GENERAL_AUDIO: [u8; 12] = [1, 2, 3, 4, 6, 7, 17, 19, 20, 21, 22, 23];
528
529/// The syncExtensionTypes that signal SBR, then PS, after the specific config.
530const SYNC_EXTENSION_SBR: u32 = 0x2b7;
531const SYNC_EXTENSION_PS: u32 = 0x548;
532
533/// Read an audioObjectType: 5 bits, escaped to 6 more when it reads 31.
534fn read_object_type<T: Buf>(reader: &mut BitReader<T>) -> Result<u8> {
535	let object_type = reader.read(5, Error::ConfigTooShort)? as u8;
536	if object_type == 31 {
537		return Ok(32 + reader.read(6, Error::ExtendedConfigTooShort)? as u8);
538	}
539	Ok(object_type)
540}
541
542/// Walk a program_config_element (ISO 14496-3 Table 4.2) to the number of channels it outputs.
543///
544/// Its byte alignment is relative to where the reader started: the AudioSpecificConfig, or the
545/// raw data block.
546fn program_config<T: Buf>(reader: &mut BitReader<T>) -> Result<u32> {
547	let mut read = |n| reader.read(n, Error::ProgramConfigTruncated);
548
549	// element_instance_tag, object_type, sampling_frequency_index.
550	read(10)?;
551	let (front, side, back) = (read(4)?, read(4)?, read(4)?);
552	let (lfe, assoc, cc) = (read(2)?, read(3)?, read(4)?);
553	// Mono and stereo mixdowns each name an element; a matrix mixdown an index and a flag.
554	for bits in [4, 4, 3] {
555		if read(1)? == 1 {
556			read(bits)?;
557		}
558	}
559
560	let mut channels = lfe;
561	for _ in 0..front + side + back {
562		// A channel pair element carries two channels, a single channel element one.
563		channels += 1 + read(1)?;
564		read(4)?;
565	}
566	// Tags of the LFE and data elements, then each coupling channel element's switch flag and tag.
567	for _ in 0..lfe + assoc {
568		read(4)?;
569	}
570	for _ in 0..cc {
571		read(5)?;
572	}
573
574	reader.align();
575	let comment = reader.read(8, Error::ProgramConfigTruncated)?;
576	for _ in 0..comment {
577		reader.read(8, Error::ProgramConfigTruncated)?;
578	}
579
580	if channels == 0 {
581		return Err(Error::ProgramConfigEmpty);
582	}
583	Ok(channels)
584}
585
586/// The 13 standard AAC sampling frequencies, indexed by samplingFrequencyIndex
587/// (ISO 14496-3 Table 1.18). Index 15 is the escape for an explicit 24-bit rate.
588const SAMPLE_RATES: [u32; 13] = [
589	96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
590];
591
592/// MSB-first bit reader that pulls bytes from a [`Buf`] on demand, so the buffer advances only
593/// past the bytes it reads.
594///
595/// AudioSpecificConfig is bit-packed: an explicit 24-bit sample rate pushes the
596/// following channelConfiguration off byte boundaries, so the fields can't be
597/// read a whole byte at a time.
598struct BitReader<'a, T: Buf> {
599	bits: bitstream_io::BitReader<bytes::buf::Reader<&'a mut T>, bitstream_io::BigEndian>,
600	/// Every bit read is copied here when set, with alignment redone on the writer's own bytes.
601	record: Option<BitWriter>,
602	/// Bits read or skipped so far.
603	position: usize,
604}
605
606impl<'a, T: Buf> BitReader<'a, T> {
607	fn new(buf: &'a mut T) -> Self {
608		Self {
609			bits: bitstream_io::BitReader::new(buf.reader()),
610			record: None,
611			position: 0,
612		}
613	}
614
615	/// Bits read or skipped so far.
616	fn position(&self) -> usize {
617		self.position
618	}
619
620	/// Bytes left in the buffer, `None` partway through one.
621	fn remaining(&mut self) -> Option<usize> {
622		Some(self.bits.reader()?.get_ref().remaining())
623	}
624
625	/// Skip to the next byte boundary.
626	fn align(&mut self) {
627		bitstream_io::BitRead::byte_align(&mut self.bits);
628		self.position = self.position.next_multiple_of(8);
629		if let Some(record) = &mut self.record {
630			record.align();
631		}
632	}
633
634	/// Read `n` bits (n <= 32) MSB-first, returning `short` if the buffer runs dry.
635	fn read(&mut self, n: u8, short: Error) -> Result<u32> {
636		let value = bitstream_io::BitRead::read_var(&mut self.bits, n.into()).map_err(|_| short)?;
637		self.position += usize::from(n);
638		if let Some(record) = &mut self.record {
639			record.write(n, value);
640		}
641		Ok(value)
642	}
643}
644
645/// MSB-first bit writer, the inverse of [`BitReader`].
646#[derive(Default)]
647struct BitWriter {
648	bytes: Vec<u8>,
649	/// Bits used in the last byte; 0 when the next write starts a new one.
650	used: u8,
651}
652
653impl BitWriter {
654	/// Write the low `n` bits (n <= 32) of `value`, MSB-first.
655	fn write(&mut self, n: u8, value: u32) {
656		for i in (0..n).rev() {
657			if self.used == 0 {
658				self.bytes.push(0);
659			}
660			let bit = ((value >> i) & 1) as u8;
661			*self.bytes.last_mut().expect("pushed above") |= bit << (7 - self.used);
662			self.used = (self.used + 1) % 8;
663		}
664	}
665
666	/// Pad the last byte with zeros.
667	fn align(&mut self) {
668		self.used = 0;
669	}
670}
671
672/// Map an AAC `channel_config` (ISO 14496-3 Table 1.19) to its channel count, for every value but
673/// 0, which a program config element describes instead. Configs 1..=6 are identity. 7, 12, and 14
674/// are 8 channels (7.1 with wide fronts, rear surrounds, or front heights), 11 is 6.1, and 13 is
675/// 22.2. The rest are reserved.
676fn channel_count_from_config(channel_config: u8) -> Result<u32> {
677	match channel_config {
678		1..=6 => Ok(channel_config as u32),
679		7 | 12 | 14 => Ok(8),
680		11 => Ok(7),
681		13 => Ok(24),
682		_ => Err(Error::ReservedChannelConfig(channel_config)),
683	}
684}
685
686/// Inverse of [`channel_count_from_config`] for the configurations a bare count names.
687///
688/// Counts 1 through 6 are that configuration. Eight channels are configuration 7, the
689/// 7.1 layout, so a configuration 12 or 14 source keeps its layout only through its
690/// verbatim AudioSpecificConfig. Any other count is refused rather than guessing speaker
691/// positions, including 7 and 24, which configurations 11 and 13 name alongside program
692/// config element layouts.
693fn channel_config_from_count(channel_count: u32) -> Result<u8> {
694	match channel_count {
695		1..=6 => Ok(channel_count as u8),
696		8 => Ok(7),
697		_ => Err(Error::UnsupportedChannelCount(channel_count)),
698	}
699}
700
701#[cfg(test)]
702mod tests {
703	use super::*;
704
705	#[test]
706	fn parses_standard_2_byte_config() {
707		// AAC-LC (profile=2), 44100 Hz (freq_index=4), stereo (channels=2).
708		// b0 = 0x12 (00010 0100b → object_type=2, freq_index high 3 bits=010)
709		// b1 = 0x10 (0001 0000b → freq_index low bit=0, channel_config=2, padding=000)
710		let buf = vec![0x12, 0x10];
711		let cfg = Config::parse(&mut buf.as_slice()).unwrap();
712		assert_eq!(cfg.profile, 2);
713		assert_eq!(cfg.sample_rate, 44100);
714		assert_eq!(cfg.channel_count, 2);
715	}
716
717	#[test]
718	fn frame_clock_reads_an_aac_lc_cores_frame_length() {
719		// frameLengthFlag lands mid-byte after an explicit 44101 Hz rate.
720		assert_eq!(frame_clock(&[0x17, 0x80, 0x56, 0x22, 0x94]), Some((960, 44_101)));
721		// AAC Main, alone and as an explicit SBR core, codes other frames.
722		assert_eq!(frame_clock(&[0x09, 0x90]), None);
723		assert_eq!(frame_clock(&[0x2b, 0x11, 0x84, 0x00]), None);
724	}
725
726	/// An explicit rate of zero, escape index 15 then 24 zero bits, describes no audio.
727	#[test]
728	fn explicit_zero_sample_rate_is_refused() {
729		assert!(Config::parse(&mut [0x17u8, 0x80, 0x00, 0x00, 0x10].as_slice()).is_err());
730	}
731
732	#[test]
733	fn round_trip_explicit_sample_rate() {
734		// A non-standard rate (no freq_index) forces the explicit 24-bit form, where
735		// channelConfiguration lands mid-byte after the rate. A byte-aligned parser
736		// misreads both fields; the bit reader round-trips them.
737		let cfg = Config {
738			profile: 2,
739			sample_rate: 44_056, // not in the standard table
740			channel_count: 2,
741		};
742		let encoded = cfg.encode().unwrap();
743		assert_eq!(encoded.len(), 5, "explicit-rate config is 5 bytes");
744
745		let parsed = Config::parse(&mut encoded.as_ref()).unwrap();
746		assert_eq!(parsed.profile, 2);
747		assert_eq!(parsed.sample_rate, 44_056);
748		assert_eq!(parsed.channel_count, 2);
749	}
750
751	#[test]
752	fn parses_extended_object_type() {
753		// audioObjectType 31 escapes to a 6-bit extended type. Bytes encode
754		// AOT=31, ext=4 (-> object_type 36), freq_index=3 (48000), channel_config=2,
755		// which straddle byte boundaries: 11111 000100 0011 0010 + padding.
756		let buf: [u8; 3] = [0xF8, 0x86, 0x40];
757		let cfg = Config::parse(&mut buf.as_slice()).unwrap();
758		assert_eq!(cfg.profile, 36);
759		assert_eq!(cfg.sample_rate, 48_000);
760		assert_eq!(cfg.channel_count, 2);
761		let encoded = cfg.encode().unwrap();
762		assert_eq!(Config::parse(&mut encoded.as_ref()).unwrap().profile, 36);
763	}
764
765	#[test]
766	fn round_trip_5_1_channels() {
767		// 5.1 surround: config=6, 6 channels.
768		let cfg = Config {
769			profile: 2,
770			sample_rate: 48000,
771			channel_count: 6,
772		};
773		let encoded = cfg.encode().unwrap();
774		let parsed = Config::parse(&mut encoded.as_ref()).unwrap();
775		assert_eq!(parsed.channel_count, 6);
776	}
777
778	#[test]
779	fn round_trip_7_1_channels() {
780		// 7.1 surround: config=7, but 8 channels.
781		let cfg = Config {
782			profile: 2,
783			sample_rate: 48000,
784			channel_count: 8,
785		};
786		let encoded = cfg.encode().unwrap();
787		let parsed = Config::parse(&mut encoded.as_ref()).unwrap();
788		assert_eq!(parsed.channel_count, 8, "7.1 surround should round-trip as 8 channels");
789	}
790
791	/// The AudioSpecificConfig ffmpeg 9.0.1 writes for quad (`-af pan=quad|...`, native `aac`
792	/// encoder, `.m4a`): channelConfiguration 0 and a program config element with two channel
793	/// pair elements, front and back, then a "Lavc63.1.101" comment and an SBR sync extension.
794	const FFMPEG_QUAD_ASC: [u8; 24] = [
795		0x11, 0x80, 0x04, 0xC4, 0x04, 0x00, 0x21, 0x10, 0x0C, 0x4C, 0x61, 0x76, 0x63, 0x36, 0x33, 0x2E, 0x31, 0x2E,
796		0x31, 0x30, 0x31, 0x56, 0xE5, 0x00,
797	];
798
799	/// Write a program config element with `front`, `side`, and `back` elements (true for a
800	/// channel pair) and `lfe` LFE elements, starting at the writer's position.
801	fn write_pce(out: &mut BitWriter, front: &[bool], side: &[bool], back: &[bool], lfe: u32) {
802		// element_instance_tag, object_type (LC), sampling_frequency_index (48 kHz).
803		out.write(4, 0);
804		out.write(2, 1);
805		out.write(4, 3);
806		out.write(4, front.len() as u32);
807		out.write(4, side.len() as u32);
808		out.write(4, back.len() as u32);
809		out.write(2, lfe);
810		// No data or coupling elements, and no mixdowns.
811		out.write(3, 0);
812		out.write(4, 0);
813		out.write(3, 0);
814		for (tag, &cpe) in front.iter().chain(side).chain(back).enumerate() {
815			out.write(1, cpe.into());
816			out.write(4, tag as u32);
817		}
818		for tag in 0..lfe {
819			out.write(4, tag);
820		}
821		out.align();
822		// A one-byte comment.
823		out.write(8, 1);
824		out.write(8, b'x'.into());
825	}
826
827	/// An AudioSpecificConfig with channelConfiguration 0 around [`write_pce`]'s element.
828	fn pce_asc(object_type: u8, front: &[bool], side: &[bool], back: &[bool], lfe: u32) -> Vec<u8> {
829		let mut out = BitWriter::default();
830		out.write(5, object_type.into());
831		out.write(4, 3);
832		out.write(4, 0);
833		out.write(3, 0);
834		write_pce(&mut out, front, side, back, lfe);
835		out.bytes
836	}
837
838	#[test]
839	fn parses_ffmpeg_program_config_element() {
840		let cfg = Config::parse(&mut FFMPEG_QUAD_ASC.as_slice()).unwrap();
841		assert_eq!(cfg.profile, 2);
842		assert_eq!(cfg.sample_rate, 48_000);
843		assert_eq!(cfg.channel_count, 4, "two channel pair elements");
844	}
845
846	#[test]
847	fn parses_program_config_element_counts() {
848		// 5.1: a single and a pair in front, a pair in back, and an LFE.
849		let asc = pce_asc(2, &[false, true], &[], &[true], 1);
850		assert_eq!(Config::parse(&mut asc.as_slice()).unwrap().channel_count, 6);
851
852		// Side elements count too: 3/2/2 with no LFE.
853		let asc = pce_asc(2, &[false, true], &[true], &[true], 0);
854		assert_eq!(Config::parse(&mut asc.as_slice()).unwrap().channel_count, 7);
855	}
856
857	/// audioObjectType 5 (SBR), 24 kHz core, channelConfiguration 0, a 48 kHz extension rate,
858	/// then the core type (LC) whose GASpecificConfig carries a front and back pair.
859	fn sbr_pce_asc() -> Vec<u8> {
860		let mut out = BitWriter::default();
861		out.write(5, 5);
862		out.write(4, 6);
863		out.write(4, 0);
864		out.write(4, 3);
865		out.write(5, 2);
866		out.write(3, 0);
867		write_pce(&mut out, &[true], &[], &[true], 0);
868		out.bytes
869	}
870
871	#[test]
872	fn parses_program_config_element_behind_explicit_sbr() {
873		let cfg = Config::parse(&mut sbr_pce_asc().as_slice()).unwrap();
874		assert_eq!(cfg.profile, 5);
875		assert_eq!(cfg.sample_rate, 48_000, "the extension rate");
876		assert_eq!(cfg.channel_count, 4);
877	}
878
879	/// GStreamer 1.28 `fdkaacenc` at 48 kHz stereo: HE-AAC is SBR over a 24 kHz stereo LC core, and
880	/// HE-AACv2 is PS over a mono one.
881	const FDKAAC_HE_AAC: [u8; 4] = [0x2B, 0x11, 0x88, 0x00];
882	const FDKAAC_HE_AAC_V2: [u8; 4] = [0xEB, 0x09, 0x88, 0x00];
883
884	#[test]
885	fn frame_duration_counts_core_samples_at_the_core_rate() {
886		let micros = |asc: &[u8]| frame_duration(asc).map(|d| std::time::Duration::try_from(d).unwrap().as_micros());
887		// AAC-LC at 44.1 kHz: 1024 samples.
888		assert_eq!(micros(&[0x12, 0x10]), Some(23_219));
889		// SBR and PS over a 24 kHz core: 2048 samples at 48 kHz.
890		assert_eq!(micros(&FDKAAC_HE_AAC), Some(42_666));
891		assert_eq!(micros(&FDKAAC_HE_AAC_V2), Some(42_666));
892		// The same SBR config with frameLengthFlag set: 960 core samples.
893		assert_eq!(micros(&[0x2B, 0x11, 0x8A, 0x00]), Some(40_000));
894		// ER AAC LD at 48 kHz: 512 samples, or 480 with frameLengthFlag set.
895		assert_eq!(micros(&[0xB9, 0x90, 0x00]), Some(10_666));
896		assert_eq!(micros(&[0xB9, 0x94, 0x00]), Some(10_000));
897		// ER AAC LC at 48 kHz: 1024 samples.
898		assert_eq!(micros(&[0x89, 0x91, 0x00]), Some(21_333));
899		// ER BSAC codes frames of another length.
900		assert_eq!(micros(&[0xB0, 0x90, 0x00]), None);
901	}
902
903	#[test]
904	fn explicit_sbr_and_ps_parse_as_their_output() {
905		for (asc, profile) in [(FDKAAC_HE_AAC, 5), (FDKAAC_HE_AAC_V2, 29)] {
906			let cfg = Config::parse(&mut asc.as_slice()).unwrap();
907			assert_eq!(cfg.profile, profile);
908			assert_eq!(cfg.sample_rate, 48_000, "the output rate, not the 24 kHz core");
909			assert_eq!(cfg.channel_count, 2, "stereo, including over a mono PS core");
910			assert_eq!(cfg.encode().unwrap(), asc.as_slice(), "encode writes the core back");
911		}
912
913		// A config naming SBR or PS but stopping before its extension rate has no output to name.
914		for truncated in [[0x2A, 0x10], [0xEA, 0x08]] {
915			assert!(matches!(
916				Config::parse(&mut truncated.as_slice()),
917				Err(Error::IncompleteConfig)
918			));
919		}
920	}
921
922	#[test]
923	fn refuses_bad_program_config_elements() {
924		let asc = pce_asc(2, &[], &[], &[], 0);
925		assert!(matches!(
926			Config::parse(&mut asc.as_slice()),
927			Err(Error::ProgramConfigEmpty)
928		));
929
930		let asc = pce_asc(2, &[true], &[], &[], 0);
931		assert!(matches!(
932			Config::parse(&mut &asc[..asc.len() - 1]),
933			Err(Error::ProgramConfigTruncated)
934		));
935
936		// ALS (36) describes its channels in its own specific config, not a PCE.
937		let mut out = BitWriter::default();
938		out.write(5, 31);
939		out.write(6, 4);
940		out.write(4, 3);
941		out.write(4, 0);
942		out.write(8, 0);
943		assert!(matches!(
944			Config::parse(&mut out.bytes.as_slice()),
945			Err(Error::ProgramConfigUnsupported(36))
946		));
947	}
948
949	#[test]
950	fn channel_config_dispositions() {
951		let expected = [1, 2, 3, 4, 5, 6, 8];
952		for (config, count) in (1..=7).zip(expected) {
953			let asc = [0x11, 0x80 | (config << 3)];
954			assert_eq!(Config::parse(&mut asc.as_slice()).unwrap().channel_count, count);
955		}
956
957		for (config, count) in [(11, 7), (12, 8), (13, 24), (14, 8)] {
958			let asc = [0x11, 0x80 | (config << 3)];
959			assert_eq!(Config::parse(&mut asc.as_slice()).unwrap().channel_count, count);
960		}
961
962		for config in [8, 9, 10, 15] {
963			let asc = [0x11, 0x80 | (config << 3)];
964			assert!(matches!(
965				Config::parse(&mut asc.as_slice()),
966				Err(Error::ReservedChannelConfig(c)) if c == config
967			));
968		}
969	}
970
971	#[test]
972	fn in_band_config_moves_the_program_config_element() {
973		// A raw data block leading with ID_PCE, which puts the element 3 bits off the byte grid
974		// the AudioSpecificConfig puts it on, so the copy has to redo the alignment.
975		let mut block = BitWriter::default();
976		block.write(3, ID_PCE);
977		write_pce(&mut block, &[false, true], &[], &[true], 1);
978		let pce = block.bytes.clone();
979		// The channel elements that follow are never read.
980		block.write(8, 0xFF);
981
982		let mut rest = block.bytes.as_slice();
983		let asc = in_band_config(2, 48_000, 0, &mut rest).unwrap();
984		assert_eq!(asc, pce_asc(2, &[false, true], &[], &[true], 1));
985		assert_eq!(Config::parse(&mut asc.as_ref()).unwrap().channel_count, 6);
986		assert_eq!(rest, [0xFF], "the element moves out of the block");
987
988		// And back: the element leads the block again, byte for byte.
989		let in_band = in_band(&asc).unwrap();
990		assert_eq!(in_band.channel_config, 0);
991		assert_eq!(in_band.program_config, Some(Bytes::from(pce)));
992	}
993
994	#[test]
995	fn in_band_of_ffmpeg_program_config_element() {
996		// Round trip ffmpeg's own element through a raw data block and back into a config. The
997		// trailing SBR sync extension is not part of the element, so it drops.
998		let in_band = in_band(&FFMPEG_QUAD_ASC).unwrap();
999		assert_eq!(in_band.channel_config, 0);
1000		let pce = in_band.program_config.unwrap();
1001		let mut block = pce.as_ref();
1002		let asc = in_band_config(2, 48_000, 0, &mut block).unwrap();
1003		assert!(block.is_empty(), "the element is all that was framed");
1004		assert_eq!(asc, FFMPEG_QUAD_ASC[..FFMPEG_QUAD_ASC.len() - 3]);
1005	}
1006
1007	#[test]
1008	fn in_band_without_a_program_config_element() {
1009		let stereo = in_band(&[0x11, 0x90]).unwrap();
1010		assert_eq!((stereo.channel_config, stereo.program_config), (2, None));
1011		assert_eq!(in_band(&[0x11, 0xE0]).unwrap().channel_config, 12);
1012	}
1013
1014	#[test]
1015	fn in_band_of_explicit_sbr_is_its_lc_core() {
1016		for (asc, channel_config) in [(FDKAAC_HE_AAC, 2), (FDKAAC_HE_AAC_V2, 1)] {
1017			let expected = InBand {
1018				object_type: 2,
1019				sample_rate: 24_000,
1020				channel_config,
1021				program_config: None,
1022			};
1023			assert_eq!(in_band(&asc).unwrap(), expected);
1024		}
1025
1026		// A config naming SBR but stopping before its core has no core to name.
1027		assert!(matches!(in_band(&[0x2A, 0x10]), Err(Error::IncompleteConfig)));
1028	}
1029
1030	#[test]
1031	fn in_band_of_explicit_sbr_keeps_its_program_config_element() {
1032		let in_band = in_band(&sbr_pce_asc()).unwrap();
1033		assert_eq!(in_band.object_type, 2);
1034		assert_eq!(in_band.sample_rate, 24_000);
1035		assert_eq!(in_band.channel_config, 0);
1036		let pce = in_band.program_config.expect("a program config element");
1037		let mut block = pce.as_ref();
1038		let asc = in_band_config(2, 24_000, 0, &mut block).unwrap();
1039		assert_eq!(Config::parse(&mut asc.as_ref()).unwrap().channel_count, 4);
1040	}
1041
1042	#[test]
1043	fn in_band_config_refuses_a_block_without_a_leading_pce() {
1044		// ID_CPE first: any element past the channel data is out of reach.
1045		assert!(matches!(
1046			in_band_config(2, 48_000, 0, &mut [0x20, 0x00].as_slice()),
1047			Err(Error::ProgramConfigMissing)
1048		));
1049		assert!(matches!(
1050			in_band_config(2, 48_000, 0, &mut [].as_slice()),
1051			Err(Error::ProgramConfigMissing)
1052		));
1053	}
1054
1055	#[test]
1056	fn in_band_config_matches_encode() {
1057		// Without a PCE the block is unread and the config is the plain two-byte form.
1058		let asc = in_band_config(2, 44_100, 2, &mut [].as_slice()).unwrap();
1059		let encoded = Config {
1060			profile: 2,
1061			sample_rate: 44_100,
1062			channel_count: 2,
1063		}
1064		.encode()
1065		.unwrap();
1066		assert_eq!(asc, encoded);
1067	}
1068
1069	#[test]
1070	fn encode_names_only_channel_configurations() {
1071		// 48 kHz AAC-LC. Frequency index 3's low bit sits in the second byte, then the
1072		// channelConfiguration, so that byte is 0x80 plus the configuration shifted by 3.
1073		for count in 1..=8 {
1074			let encoded = Config {
1075				profile: 2,
1076				sample_rate: 48_000,
1077				channel_count: count,
1078			}
1079			.encode();
1080			let config = match count {
1081				1..=6 => count as u8,
1082				8 => 7,
1083				_ => {
1084					assert!(matches!(encoded, Err(Error::UnsupportedChannelCount(got)) if got == count));
1085					continue;
1086				}
1087			};
1088			let encoded = encoded.unwrap();
1089			assert_eq!(encoded.as_ref(), &[0x11, 0x80 | (config << 3)], "{count} channels");
1090			assert_eq!(Config::parse(&mut encoded.as_ref()).unwrap().channel_count, count);
1091		}
1092
1093		// One past the configurations a count names, plus zero and 22.2 (configuration 13).
1094		for count in [0, 9, 24] {
1095			assert!(matches!(
1096				Config {
1097					profile: 2,
1098					sample_rate: 48_000,
1099					channel_count: count,
1100				}
1101				.encode(),
1102				Err(Error::UnsupportedChannelCount(got)) if got == count
1103			));
1104		}
1105	}
1106
1107	#[test]
1108	fn catalog_synthesis_refuses_an_unnameable_count() {
1109		let err = hang::catalog::AudioConfig::try_from(Config {
1110			profile: 2,
1111			sample_rate: 48_000,
1112			channel_count: 7,
1113		})
1114		.unwrap_err();
1115		assert!(matches!(err, Error::UnsupportedChannelCount(7)));
1116	}
1117
1118	#[test]
1119	fn verbatim_config_keeps_a_program_config_element() {
1120		// Encode refuses seven channels. Import keeps the element instead of re-encoding.
1121		let asc = pce_asc(2, &[false, true], &[true], &[true], 0);
1122		let audio = config(&asc).unwrap();
1123		assert_eq!(audio.channel_count, 7);
1124		assert_eq!(audio.description.as_deref(), Some(asc.as_slice()));
1125	}
1126
1127	/// AAC-LC at 48 kHz stereo with a GASpecificConfig whose flags are all clear.
1128	fn lc_writer() -> BitWriter {
1129		let mut out = BitWriter::default();
1130		out.write(5, 2);
1131		out.write(4, 3);
1132		out.write(4, 2);
1133		out.write(3, 0);
1134		out
1135	}
1136
1137	/// [`lc_writer`]'s config, then a sync extension signaling SBR at 48 kHz, and PS when `ps`.
1138	fn sync_extension_asc(ps: bool) -> Vec<u8> {
1139		let mut out = lc_writer();
1140		out.write(11, SYNC_EXTENSION_SBR);
1141		out.write(5, OBJECT_TYPE_SBR.into());
1142		out.write(1, 1);
1143		out.write(4, 3);
1144		if ps {
1145			out.write(11, SYNC_EXTENSION_PS);
1146			out.write(1, 1);
1147		}
1148		out.bytes
1149	}
1150
1151	/// The largest config `parse_exact` reads: explicit rates, a coded core delay, a program config
1152	/// element with every element and a 255-byte comment, and a sync extension with SBR and PS.
1153	fn largest_asc() -> Vec<u8> {
1154		let mut out = BitWriter::default();
1155		out.write(5, 2);
1156		out.write(4, 15);
1157		out.write(24, 44_056);
1158		out.write(4, 0);
1159		// frameLengthFlag, dependsOnCoreCoder with its coreCoderDelay, and extensionFlag.
1160		out.write(1, 0);
1161		out.write(1, 1);
1162		out.write(14, 0);
1163		out.write(1, 1);
1164		// The program config element: tag, object type, rate, then the element counts.
1165		out.write(10, 0);
1166		for (bits, count) in [(4, 15), (4, 15), (4, 15), (2, 3), (3, 7), (4, 15)] {
1167			out.write(bits, count);
1168		}
1169		// Every mixdown, then each element's tag.
1170		for bits in [4, 4, 3] {
1171			out.write(1, 1);
1172			out.write(bits, 0);
1173		}
1174		for _ in 0..45 + 15 {
1175			out.write(5, 0b10000);
1176		}
1177		for _ in 0..3 + 7 {
1178			out.write(4, 0);
1179		}
1180		out.align();
1181		out.write(8, 255);
1182		for _ in 0..255 {
1183			out.write(8, b'x'.into());
1184		}
1185		// extensionFlag3.
1186		out.write(1, 0);
1187		out.write(11, SYNC_EXTENSION_SBR);
1188		out.write(5, OBJECT_TYPE_SBR.into());
1189		out.write(1, 1);
1190		out.write(4, 15);
1191		out.write(24, 88_112);
1192		out.write(11, SYNC_EXTENSION_PS);
1193		out.write(1, 1);
1194		out.bytes
1195	}
1196
1197	/// A backward-compatible sync extension names what an SBR or PS decoder plays: a 24 kHz
1198	/// mono core plays at 48 kHz, and in stereo under PS, as hierarchical signaling would say.
1199	#[test]
1200	fn a_sync_extension_reports_the_decoded_output() {
1201		for (ps, expected) in [(false, (5, 48_000, 1)), (true, (29, 48_000, 2))] {
1202			let mut out = BitWriter::default();
1203			out.write(5, 2);
1204			out.write(4, 6);
1205			out.write(4, 1);
1206			out.write(3, 0);
1207			out.write(11, SYNC_EXTENSION_SBR);
1208			out.write(5, OBJECT_TYPE_SBR.into());
1209			out.write(1, 1);
1210			out.write(4, 3);
1211			if ps {
1212				out.write(11, SYNC_EXTENSION_PS);
1213				out.write(1, 1);
1214			}
1215			for config in [
1216				Config::parse(&mut out.bytes.as_slice()).unwrap(),
1217				Config::parse_exact(&out.bytes).unwrap(),
1218			] {
1219				assert_eq!(
1220					(config.profile, config.sample_rate, config.channel_count),
1221					expected,
1222					"ps={ps}"
1223				);
1224			}
1225		}
1226	}
1227
1228	/// SBR a sync extension names holds when the bits after it are not the PS sync extension:
1229	/// padding there fails `parse_exact`, but `parse` still reports the SBR output.
1230	#[test]
1231	fn sbr_survives_an_unknown_field_after_it() {
1232		let asc = [0x12, 0x10, 0x56, 0xE5, 0x98, 0x00, 0x00];
1233		let config = Config::parse(&mut asc.as_slice()).unwrap();
1234		assert_eq!(
1235			(config.profile, config.sample_rate, config.channel_count),
1236			(5, 48_000, 2)
1237		);
1238		assert!(Config::parse_exact(&asc).is_err());
1239	}
1240
1241	#[test]
1242	fn parse_exact_reads_every_field() {
1243		// ER AAC-LD with an epConfig of 0.
1244		let mut ld = BitWriter::default();
1245		ld.write(5, 23);
1246		ld.write(4, 3);
1247		ld.write(4, 1);
1248		ld.write(3, 0);
1249		ld.write(2, 0);
1250		let largest = largest_asc();
1251		assert!(largest.len() <= CONFIG_MAX_LEN, "{} > {CONFIG_MAX_LEN}", largest.len());
1252		for asc in [
1253			vec![0x12, 0x10],
1254			// ffmpeg's native encoder signals SBR absent in a sync extension.
1255			vec![0x11, 0x90, 0x56, 0xE5, 0x00],
1256			FFMPEG_QUAD_ASC.to_vec(),
1257			FDKAAC_HE_AAC.to_vec(),
1258			FDKAAC_HE_AAC_V2.to_vec(),
1259			sbr_pce_asc(),
1260			sync_extension_asc(false),
1261			sync_extension_asc(true),
1262			ld.bytes,
1263			largest,
1264		] {
1265			let exact = Config::parse_exact(&asc).unwrap_or_else(|err| panic!("{asc:02x?}: {err}"));
1266			let parsed = Config::parse(&mut asc.as_slice()).unwrap();
1267			assert_eq!(
1268				(exact.profile, exact.sample_rate, exact.channel_count),
1269				(parsed.profile, parsed.sample_rate, parsed.channel_count)
1270			);
1271		}
1272	}
1273
1274	#[test]
1275	fn parse_exact_refuses_what_it_does_not_read() {
1276		let mut unknown_sync = lc_writer();
1277		unknown_sync.write(11, 0x123);
1278		unknown_sync.write(5, 0);
1279		let mut unknown_extension = lc_writer();
1280		unknown_extension.write(11, SYNC_EXTENSION_SBR);
1281		unknown_extension.write(5, 2);
1282		let mut extension3 = BitWriter::default();
1283		extension3.write(5, 2);
1284		extension3.write(4, 3);
1285		extension3.write(4, 2);
1286		extension3.write(3, 0b001);
1287		extension3.write(1, 1);
1288		let mut protected = BitWriter::default();
1289		protected.write(5, 23);
1290		protected.write(4, 3);
1291		protected.write(4, 1);
1292		protected.write(3, 0);
1293		protected.write(2, 2);
1294		protected.write(8, 0);
1295		for asc in [
1296			unknown_sync.bytes,
1297			unknown_extension.bytes,
1298			extension3.bytes,
1299			protected.bytes,
1300			// ALS, whose specific config is not read.
1301			vec![0xF8, 0x86, 0x40],
1302		] {
1303			assert!(
1304				matches!(Config::parse_exact(&asc), Err(Error::UnsupportedConfig(_))),
1305				"{asc:02x?}"
1306			);
1307		}
1308
1309		for asc in [
1310			vec![0x12, 0x10, 0x00],
1311			vec![0x11, 0x90, 0x56, 0xE5, 0x00, 0x00],
1312			[sync_extension_asc(true), vec![0]].concat(),
1313		] {
1314			assert!(
1315				matches!(Config::parse_exact(&asc), Err(Error::TrailingBytes(1))),
1316				"{asc:02x?}"
1317			);
1318		}
1319		assert!(Config::parse_exact(&[0x12]).is_err());
1320	}
1321}