use crate::mp4_demux::AacTrackConfig;
use crate::{Error, ErrorKind, Result};
const AOT_LC: u8 = 2;
const AOT_SBR: u8 = 5;
const AOT_PS: u8 = 29;
const SBR_SYNC: u32 = 0x2b7;
const PS_SYNC: u32 = 0x548;
const FREQUENCIES: [u32; 13] = [
96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000, 12_000, 11_025, 8_000,
7_350,
];
const MAX_IMPLICIT_SBR_CORE_RATE: u32 = 24_000;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct AudioSpecificConfig {
pub core_object_type: u8,
pub core_sample_rate: u32,
pub channel_config: u8,
pub sbr_sample_rate: Option<u32>,
pub ps: bool,
}
impl AudioSpecificConfig {
pub(crate) fn parse(bytes: &[u8]) -> Result<Self> {
let mut bits = AscBits::new(bytes);
let mut object_type = read_object_type(&mut bits)?;
let core_sample_rate = read_frequency(&mut bits)?;
let channel_config = bits.read(4)? as u8;
let mut sbr_sample_rate = None;
let mut ps = false;
if matches!(object_type, AOT_SBR | AOT_PS) {
ps = object_type == AOT_PS;
sbr_sample_rate = Some(read_frequency(&mut bits)?);
object_type = read_object_type(&mut bits)?;
}
if channel_config == 0 || channel_config > 7 {
return Err(unsupported(
"AAC program-config-element channel layouts are unsupported",
));
}
let mut config = Self {
core_object_type: object_type,
core_sample_rate,
channel_config,
sbr_sample_rate,
ps,
};
if object_type != AOT_LC {
return Ok(config);
}
bits.read(1)?;
if bits.read(1)? == 1 {
bits.read(14)?;
}
bits.read(1)?;
if sbr_sample_rate.is_none() && bits.remaining() >= 16 {
let _ = config.read_sync_extension(&mut bits);
}
Ok(config)
}
fn read_sync_extension(&mut self, bits: &mut AscBits) -> Result<()> {
if bits.read(11)? != SBR_SYNC {
return Ok(());
}
let Ok(extension_type) = read_object_type(bits) else {
return Ok(());
};
if extension_type != AOT_SBR {
return Ok(());
}
if bits.read(1)? == 0 {
return Ok(());
}
let Ok(sbr_sample_rate) = read_frequency(bits) else {
return Ok(());
};
self.sbr_sample_rate = Some(sbr_sample_rate);
if bits.remaining() >= 12 && bits.read(11)? == PS_SYNC {
self.ps = bits.read(1)? == 1;
}
Ok(())
}
pub(crate) fn is_aac_lc_core(&self) -> bool {
self.core_object_type == AOT_LC
}
pub(crate) fn resolve(
mut self,
asc: &[u8],
entry_rate: u32,
entry_channels: u16,
) -> Result<AacTrackConfig> {
let core_channels = u16::from(self.channel_config);
let mut audio_specific_config = asc.to_vec();
if self.sbr_sample_rate.is_none()
&& self.core_sample_rate <= MAX_IMPLICIT_SBR_CORE_RATE
&& Some(entry_rate) == self.core_sample_rate.checked_mul(2)
{
self.sbr_sample_rate = Some(entry_rate);
self.ps = core_channels == 1 && entry_channels == 2;
audio_specific_config = explicit_sbr_config(asc, &self)?;
}
self.ps &= core_channels == 1;
let sample_rate = self.sbr_sample_rate.unwrap_or(self.core_sample_rate);
let channels = if self.ps { 2 } else { core_channels };
if entry_rate != sample_rate && entry_rate != self.core_sample_rate {
return Err(malformed(
"AAC AudioSpecificConfig sample rate disagrees with mp4a",
));
}
if entry_channels != channels && entry_channels != core_channels {
return Err(malformed(
"AAC AudioSpecificConfig channel count disagrees with mp4a",
));
}
Ok(AacTrackConfig {
audio_object_type: self.signaled_object_type(),
sample_rate,
channels,
audio_specific_config,
})
}
fn signaled_object_type(&self) -> u8 {
match (self.sbr_sample_rate, self.ps) {
(Some(_), true) => AOT_PS,
(Some(_), false) => AOT_SBR,
(None, _) => self.core_object_type,
}
}
}
fn explicit_sbr_config(asc: &[u8], config: &AudioSpecificConfig) -> Result<Vec<u8>> {
let mut bits = AscBits::new(asc);
read_object_type(&mut bits)?;
read_frequency(&mut bits)?;
bits.read(4)?;
bits.read(1)?;
if bits.read(1)? == 1 {
bits.read(14)?;
}
bits.read(1)?;
let core_bits = bits.position;
let mut writer = BitWriter::default();
let mut reader = AscBits::new(asc);
for _ in 0..core_bits {
writer.write(reader.read(1)?, 1);
}
writer.write(SBR_SYNC, 11);
writer.write(u32::from(AOT_SBR), 5);
writer.write(1, 1);
let rate = config.sbr_sample_rate.expect("an SBR configuration");
match FREQUENCIES.iter().position(|&frequency| frequency == rate) {
Some(index) => writer.write(index as u32, 4),
None => {
writer.write(15, 4);
writer.write(rate, 24);
}
}
if config.ps {
writer.write(PS_SYNC, 11);
writer.write(1, 1);
}
Ok(writer.finish())
}
fn read_object_type(bits: &mut AscBits) -> Result<u8> {
let object_type = bits.read(5)? as u8;
if object_type == 31 {
return Ok(32 + bits.read(6)? as u8);
}
Ok(object_type)
}
fn read_frequency(bits: &mut AscBits) -> Result<u32> {
let index = bits.read(4)? as usize;
if index == 15 {
return bits.read(24);
}
FREQUENCIES
.get(index)
.copied()
.ok_or_else(|| malformed("AAC AudioSpecificConfig has an invalid sample rate"))
}
struct AscBits<'a> {
bytes: &'a [u8],
position: usize,
}
impl<'a> AscBits<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self { bytes, position: 0 }
}
fn remaining(&self) -> usize {
self.bytes.len() * 8 - self.position
}
fn read(&mut self, count: usize) -> Result<u32> {
if count > 32 || count > self.remaining() {
return Err(malformed("truncated AAC AudioSpecificConfig"));
}
let mut value = 0_u32;
for _ in 0..count {
value = (value << 1)
| u32::from((self.bytes[self.position / 8] >> (7 - self.position % 8)) & 1);
self.position += 1;
}
Ok(value)
}
}
#[derive(Default)]
struct BitWriter {
bytes: Vec<u8>,
bits: usize,
}
impl BitWriter {
fn write(&mut self, value: u32, count: usize) {
for shift in (0..count).rev() {
if self.bits % 8 == 0 {
self.bytes.push(0);
}
let bit = ((value >> shift) & 1) as u8;
*self.bytes.last_mut().expect("a byte was pushed") |= bit << (7 - self.bits % 8);
self.bits += 1;
}
}
fn finish(self) -> Vec<u8> {
self.bytes
}
}
fn malformed(message: impl Into<String>) -> Error {
Error::new(ErrorKind::MalformedMedia, message)
}
fn unsupported(message: impl Into<String>) -> Error {
Error::new(ErrorKind::Unsupported, message)
}
#[cfg(test)]
mod tests {
use super::*;
fn resolve(asc: &[u8], rate: u32, channels: u16) -> Result<AacTrackConfig> {
AudioSpecificConfig::parse(asc)?.resolve(asc, rate, channels)
}
fn resolved(asc: &[u8], rate: u32, channels: u16) -> AacTrackConfig {
resolve(asc, rate, channels).unwrap()
}
#[test]
fn plain_aac_lc_is_decoded_at_its_own_rate() {
let config = resolved(&[0x11, 0x90], 48_000, 2);
assert_eq!(
(
config.audio_object_type,
config.sample_rate,
config.channels
),
(2, 48_000, 2)
);
assert_eq!(config.audio_specific_config, [0x11, 0x90]);
}
#[test]
fn a_disabled_backward_compatible_sbr_extension_stays_aac_lc() {
let config = resolved(&[0x11, 0x90, 0x56, 0xe5, 0x00], 48_000, 2);
assert_eq!((config.audio_object_type, config.sample_rate), (2, 48_000));
}
#[test]
fn backward_compatible_he_aac_v1_decodes_at_the_sbr_rate() {
let asc = [0x13, 0x90, 0x56, 0xe5, 0xa0];
for rate in [22_050, 44_100] {
let config = resolved(&asc, rate, 2);
assert_eq!(
(
config.audio_object_type,
config.sample_rate,
config.channels
),
(5, 44_100, 2)
);
assert_eq!(config.audio_specific_config, asc);
}
}
#[test]
fn backward_compatible_he_aac_v2_decodes_a_mono_core_to_stereo() {
let asc = [0x13, 0x88, 0x56, 0xe5, 0xa5, 0x48, 0x80];
for (rate, channels) in [(22_050, 2), (44_100, 2), (44_100, 1)] {
let config = resolved(&asc, rate, channels);
assert_eq!(
(
config.audio_object_type,
config.sample_rate,
config.channels
),
(29, 44_100, 2)
);
}
}
#[test]
fn hierarchical_signaling_names_the_core_after_the_extension() {
let mut writer = BitWriter::default();
for (value, count) in [(29, 5), (7, 4), (1, 4), (4, 4), (2, 5), (0, 3)] {
writer.write(value, count);
}
let config = resolved(&writer.finish(), 44_100, 2);
assert_eq!(
(
config.audio_object_type,
config.sample_rate,
config.channels
),
(29, 44_100, 2)
);
}
#[test]
fn implicit_sbr_is_made_explicit_from_the_sample_entry() {
let config = resolved(&[0x13, 0x90], 44_100, 2);
assert_eq!(
(
config.audio_object_type,
config.sample_rate,
config.channels
),
(5, 44_100, 2)
);
assert_eq!(config.audio_specific_config, [0x13, 0x90, 0x56, 0xe5, 0xa0]);
let reparsed = AudioSpecificConfig::parse(&config.audio_specific_config).unwrap();
assert_eq!(reparsed.sbr_sample_rate, Some(44_100));
assert!(!reparsed.ps);
}
#[test]
fn implicit_ps_is_made_explicit_from_a_stereo_entry_over_a_mono_core() {
let config = resolved(&[0x13, 0x88], 44_100, 2);
assert_eq!(
(
config.audio_object_type,
config.sample_rate,
config.channels
),
(29, 44_100, 2)
);
assert_eq!(
config.audio_specific_config,
[0x13, 0x88, 0x56, 0xe5, 0xa5, 0x48, 0x80]
);
}
#[test]
fn an_entry_at_twice_a_high_core_rate_is_not_taken_for_sbr() {
let error = resolve(&[0x11, 0x88], 96_000, 1).unwrap_err();
assert_eq!(error.kind(), ErrorKind::MalformedMedia);
}
#[test]
fn mismatched_entries_and_other_object_types_are_reported() {
assert_eq!(
resolve(&[0x11, 0x90], 44_100, 2).unwrap_err().kind(),
ErrorKind::MalformedMedia
);
assert_eq!(
resolve(&[0x11, 0x90], 48_000, 1).unwrap_err().kind(),
ErrorKind::MalformedMedia
);
let main = AudioSpecificConfig::parse(&[0x09, 0x90]).unwrap();
assert!(!main.is_aac_lc_core());
assert_eq!(main.core_object_type, 1);
}
}