1pub mod adts;
8
9mod import;
10
11pub use import::*;
12
13use bytes::{Buf, Bytes};
14
15#[derive(Debug, Clone, thiserror::Error)]
17#[non_exhaustive]
18pub enum Error {
19 #[error("AudioSpecificConfig must be at least 2 bytes")]
21 ConfigTooShort,
22
23 #[error("extended audioObjectType requires 2 additional bytes")]
25 ExtendedConfigTooShort,
26
27 #[error("AudioSpecificConfig incomplete")]
29 IncompleteConfig,
30
31 #[error("explicit sample rate requires 3 additional bytes")]
33 ExplicitSampleRateTooShort,
34
35 #[error("unsupported sample rate index: {0}")]
37 UnsupportedSampleRateIndex(u8),
38
39 #[error("reserved channelConfiguration: {0}")]
41 ReservedChannelConfig(u8),
42
43 #[error("cannot pick a channelConfiguration for {0} channels")]
50 UnsupportedChannelCount(u32),
51
52 #[error("channelConfiguration 0 is unsupported for audioObjectType {0}")]
54 ProgramConfigUnsupported(u8),
55
56 #[error("channelConfiguration 0 without a program config element leading the first raw data block")]
58 ProgramConfigMissing,
59
60 #[error("program config element truncated")]
62 ProgramConfigTruncated,
63
64 #[error("program config element declares no channels")]
66 ProgramConfigEmpty,
67
68 #[error("raw AAC publication requires an AudioSpecificConfig description")]
70 MissingDescription,
71
72 #[error("unsupported AudioSpecificConfig: {0}")]
75 UnsupportedConfig(&'static str),
76
77 #[error("{0} bytes after the AudioSpecificConfig")]
79 TrailingBytes(usize),
80
81 #[error("adts: {0}")]
83 Adts(#[from] adts::Error),
84}
85
86pub type Result<T> = std::result::Result<T, Error>;
88
89#[non_exhaustive]
94pub struct Config {
95 pub profile: u8,
97 pub sample_rate: u32,
99 pub channel_count: u32,
101}
102
103impl Config {
104 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 pub fn parse<T: Buf>(buf: &mut T) -> Result<Self> {
128 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 let _ = Self::read_rest(&mut reader, len, &mut config, fields);
137 Ok(config)
138 }
139
140 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 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 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 read(3)?;
180 }
181 if extension {
182 match core {
183 22 => _ = read(16)?,
185 17 | 19 | 20 | 23 => _ = read(3)?,
187 _ => {}
188 }
189 if read(1)? == 1 {
190 return Err(Error::UnsupportedConfig("extensionFlag3"));
191 }
192 }
193 if matches!(core, 17 | 19..=23) && read(2)? >= 2 {
196 return Err(Error::UnsupportedConfig("ErrorProtectionSpecificConfig"));
197 }
198
199 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 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 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 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 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 pub fn encode(&self) -> Result<Bytes> {
272 let profile = self.profile;
273
274 let mut out = BitWriter::default();
275 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 out.write(3, 0);
298 Ok(Bytes::from(out.bytes))
299 }
300}
301
302struct Fields {
304 object_type: u8,
305 core: u8,
307 channel_config: u8,
308 extension: Option<bool>,
310}
311
312const CONFIG_MAX_BITS: usize = 43 + 43 + 17 + 2440 + 23 + 2 + 63;
319
320pub(crate) const CONFIG_MAX_LEN: usize = CONFIG_MAX_BITS.div_ceil(8);
322
323pub(crate) fn frame_clock(asc: &[u8]) -> Option<(u32, u32)> {
327 Config::parse(&mut &asc[..]).ok()?;
329 let mut asc = asc;
330 let mut reader = BitReader::new(&mut asc);
331 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 let samples = match reader.read(1, Error::IncompleteConfig).ok()? {
341 0 => 1024,
342 _ => 960,
343 };
344 Some((samples, rate))
345}
346
347fn 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 let channel_config = reader.read(4, Error::IncompleteConfig)? as u8;
359 Ok((object_type, sample_rate, channel_config))
360}
361
362fn 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 reader.read(4, Error::IncompleteConfig)?;
373 }
374 Ok((core, output_rate))
375}
376
377fn 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
392fn 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
403fn 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 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
419pub(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 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
441pub(crate) fn leads_with_program_config(block: &[u8]) -> bool {
443 block.first().is_some_and(|&byte| u32::from(byte >> 5) == ID_PCE)
444}
445
446pub(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 out.write(3, 0);
461
462 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#[derive(Clone, Debug, PartialEq)]
477pub(crate) struct InBand {
478 pub object_type: u8,
481 pub sample_rate: u32,
483 pub channel_config: u8,
484 pub program_config: Option<Bytes>,
487}
488
489pub(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
517const OBJECT_TYPE_LC: u8 = 2;
519const OBJECT_TYPE_SBR: u8 = 5;
520const OBJECT_TYPE_PS: u8 = 29;
521
522const ID_PCE: u32 = 5;
524
525const GENERAL_AUDIO: [u8; 12] = [1, 2, 3, 4, 6, 7, 17, 19, 20, 21, 22, 23];
528
529const SYNC_EXTENSION_SBR: u32 = 0x2b7;
531const SYNC_EXTENSION_PS: u32 = 0x548;
532
533fn 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
542fn program_config<T: Buf>(reader: &mut BitReader<T>) -> Result<u32> {
547 let mut read = |n| reader.read(n, Error::ProgramConfigTruncated);
548
549 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 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 channels += 1 + read(1)?;
564 read(4)?;
565 }
566 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
586const SAMPLE_RATES: [u32; 13] = [
589 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
590];
591
592struct BitReader<'a, T: Buf> {
599 bits: bitstream_io::BitReader<bytes::buf::Reader<&'a mut T>, bitstream_io::BigEndian>,
600 record: Option<BitWriter>,
602 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 fn position(&self) -> usize {
617 self.position
618 }
619
620 fn remaining(&mut self) -> Option<usize> {
622 Some(self.bits.reader()?.get_ref().remaining())
623 }
624
625 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 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#[derive(Default)]
647struct BitWriter {
648 bytes: Vec<u8>,
649 used: u8,
651}
652
653impl BitWriter {
654 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 fn align(&mut self) {
668 self.used = 0;
669 }
670}
671
672fn 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
686fn 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 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 assert_eq!(frame_clock(&[0x17, 0x80, 0x56, 0x22, 0x94]), Some((960, 44_101)));
721 assert_eq!(frame_clock(&[0x09, 0x90]), None);
723 assert_eq!(frame_clock(&[0x2b, 0x11, 0x84, 0x00]), None);
724 }
725
726 #[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 let cfg = Config {
738 profile: 2,
739 sample_rate: 44_056, 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 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 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 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 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 fn write_pce(out: &mut BitWriter, front: &[bool], side: &[bool], back: &[bool], lfe: u32) {
802 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 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 out.write(8, 1);
824 out.write(8, b'x'.into());
825 }
826
827 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 let asc = pce_asc(2, &[false, true], &[], &[true], 1);
850 assert_eq!(Config::parse(&mut asc.as_slice()).unwrap().channel_count, 6);
851
852 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 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 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 assert_eq!(micros(&[0x12, 0x10]), Some(23_219));
889 assert_eq!(micros(&FDKAAC_HE_AAC), Some(42_666));
891 assert_eq!(micros(&FDKAAC_HE_AAC_V2), Some(42_666));
892 assert_eq!(micros(&[0x2B, 0x11, 0x8A, 0x00]), Some(40_000));
894 assert_eq!(micros(&[0xB9, 0x90, 0x00]), Some(10_666));
896 assert_eq!(micros(&[0xB9, 0x94, 0x00]), Some(10_000));
897 assert_eq!(micros(&[0x89, 0x91, 0x00]), Some(21_333));
899 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 out.write(1, 0);
1161 out.write(1, 1);
1162 out.write(14, 0);
1163 out.write(1, 1);
1164 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 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 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 #[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 #[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 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 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 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}