use super::descriptor_body;
use crate::error::{Error, Result};
use broadcast_core::len::{need_in, need_out};
use broadcast_core::reserved::ReservedZero;
use broadcast_core::{Parse, Serialize};
pub const TAG: u8 = 0x7C;
const HEADER_LEN: usize = 2;
const FLAG_AAC_TYPE: u8 = 0x80;
const FLAG_SAOC_DE: u8 = 0x40;
pub const RESERVED_FUTURE_USE_BITS: u32 = 6;
pub const RESERVED_ZERO_FUTURE_USE_DEFAULT: ReservedZero<RESERVED_FUTURE_USE_BITS> =
ReservedZero::<RESERVED_FUTURE_USE_BITS>::FILL;
const AAC_TYPE_SAOC_DE: u8 = 0xA0;
const AAC_TYPE_V2_STEREO_FIRST: u8 = 0x43;
const AAC_TYPE_V2_STEREO_LAST: u8 = 0x46;
const AAC_TYPE_V2_RECEIVER_MIX_FIRST: u8 = 0x49;
const AAC_TYPE_V2_RECEIVER_MIX_LAST: u8 = 0x4A;
const AAC_TYPE_RECEIVER_MIX_VISUALLY_IMPAIRED: u8 = 0x47;
const AAC_TYPE_RECEIVER_MIX_SUPPLEMENTARY: u8 = 0x48;
const PROFILE_AND_LEVEL_OFFSET: usize = 0;
const FLAGS_OFFSET: usize = 1;
const EXTENSION_OFFSET: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AacComponentType {
pub mono: bool,
pub stereo: bool,
pub surround: bool,
pub visually_impaired: bool,
pub hard_of_hearing: bool,
pub supplementary: bool,
pub v2: bool,
pub saoc_de: bool,
}
impl AacComponentType {
#[must_use]
pub fn name(&self) -> &'static str {
match (
self.mono,
self.stereo,
self.surround,
self.visually_impaired,
self.hard_of_hearing,
self.supplementary,
self.v2,
self.saoc_de,
) {
(true, false, false, false, false, false, false, false) => {
"HE-AAC audio, single mono channel"
}
(false, true, false, false, false, false, false, false) => "HE-AAC audio, stereo",
(false, false, true, false, false, false, false, false) => {
"HE-AAC audio, surround sound"
}
(_, _, _, true, false, false, false, false) => {
"HE-AAC audio description for the visually impaired"
}
(_, _, _, false, true, false, false, false) => "HE-AAC audio for the hard of hearing",
(_, _, _, false, false, true, false, false) => {
"HE-AAC receiver-mix supplementary audio"
}
(false, true, false, false, false, false, true, false) => "HE-AAC v2 audio, stereo",
(_, _, _, true, false, false, true, false) => {
"HE-AAC v2 audio description for the visually impaired"
}
(_, _, _, false, true, false, true, false) => "HE-AAC v2 audio for the hard of hearing",
(_, _, _, false, false, true, true, false) => {
"HE-AAC v2 receiver-mix supplementary audio"
}
(_, _, _, true, false, true, false, false) => {
"HE-AAC receiver-mix audio description for the visually impaired"
}
(_, _, _, true, false, true, true, false) => {
"HE-AAC v2 receiver-mix audio description for the visually impaired"
}
(_, _, _, _, _, _, _, true) => "HE-AAC or HE-AAC v2 with SAOC-DE ancillary data",
_ => "unknown HE-AAC component type",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
#[non_exhaustive]
pub struct AacExtension<'a> {
pub saoc_de_flag: bool,
pub reserved_zero_future_use: ReservedZero<RESERVED_FUTURE_USE_BITS>,
pub aac_type: Option<u8>,
pub additional_info: &'a [u8],
}
impl<'a> AacExtension<'a> {
#[must_use]
pub const fn new(saoc_de_flag: bool, aac_type: Option<u8>, additional_info: &'a [u8]) -> Self {
Self {
saoc_de_flag,
reserved_zero_future_use: RESERVED_ZERO_FUTURE_USE_DEFAULT,
aac_type,
additional_info,
}
}
}
impl AacExtension<'_> {
#[must_use]
pub fn decoded_component_type(&self) -> Option<AacComponentType> {
let ct = self.aac_type?;
let saoc_de = self.saoc_de_flag;
if ct == AAC_TYPE_SAOC_DE {
return Some(AacComponentType {
mono: false,
stereo: false,
surround: false,
visually_impaired: false,
hard_of_hearing: false,
supplementary: false,
v2: false,
saoc_de: true,
});
}
let v2 = matches!(
ct,
AAC_TYPE_V2_STEREO_FIRST..=AAC_TYPE_V2_STEREO_LAST
| AAC_TYPE_V2_RECEIVER_MIX_FIRST..=AAC_TYPE_V2_RECEIVER_MIX_LAST
);
let result = match ct {
0x01 => AacComponentType {
mono: true,
stereo: false,
surround: false,
visually_impaired: false,
hard_of_hearing: false,
supplementary: false,
v2: false,
saoc_de,
},
0x03 => AacComponentType {
mono: false,
stereo: true,
surround: false,
visually_impaired: false,
hard_of_hearing: false,
supplementary: false,
v2: false,
saoc_de,
},
0x05 => AacComponentType {
mono: false,
stereo: false,
surround: true,
visually_impaired: false,
hard_of_hearing: false,
supplementary: false,
v2: false,
saoc_de,
},
0x40 | 0x47 | 0x48 => AacComponentType {
mono: false,
stereo: false,
surround: false,
visually_impaired: true,
hard_of_hearing: false,
supplementary: matches!(
ct,
AAC_TYPE_RECEIVER_MIX_VISUALLY_IMPAIRED | AAC_TYPE_RECEIVER_MIX_SUPPLEMENTARY
),
v2: false,
saoc_de,
},
0x41 => AacComponentType {
mono: false,
stereo: false,
surround: false,
visually_impaired: false,
hard_of_hearing: true,
supplementary: false,
v2: false,
saoc_de,
},
0x42 => AacComponentType {
mono: false,
stereo: false,
surround: false,
visually_impaired: false,
hard_of_hearing: false,
supplementary: true,
v2: false,
saoc_de,
},
0x43 => AacComponentType {
mono: false,
stereo: true,
surround: false,
visually_impaired: false,
hard_of_hearing: false,
supplementary: false,
v2: true,
saoc_de,
},
0x44 | 0x49 | 0x4A => AacComponentType {
mono: false,
stereo: false,
surround: false,
visually_impaired: true,
hard_of_hearing: false,
supplementary: matches!(
ct,
AAC_TYPE_V2_RECEIVER_MIX_FIRST | AAC_TYPE_V2_RECEIVER_MIX_LAST
),
v2,
saoc_de,
},
0x45 => AacComponentType {
mono: false,
stereo: false,
surround: false,
visually_impaired: false,
hard_of_hearing: true,
supplementary: false,
v2: true,
saoc_de,
},
0x46 => AacComponentType {
mono: false,
stereo: false,
surround: false,
visually_impaired: false,
hard_of_hearing: false,
supplementary: true,
v2: true,
saoc_de,
},
_ => return None,
};
Some(result)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct AacDescriptor<'a> {
pub profile_and_level: u8,
pub extension: Option<AacExtension<'a>>,
}
impl<'a> Parse<'a> for AacDescriptor<'a> {
type Error = crate::error::Error;
fn parse(bytes: &'a [u8]) -> Result<Self> {
need_in(bytes, HEADER_LEN + 1, "AacDescriptor header+profile")?;
let body = descriptor_body(
bytes,
TAG,
"AacDescriptor",
"unexpected tag for AAC_descriptor",
)?;
if body.is_empty() {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "AAC_descriptor body shorter than 1 byte",
});
}
let profile_and_level = body[PROFILE_AND_LEVEL_OFFSET];
let extension = if body.len() > 1 {
let flags = body[FLAGS_OFFSET];
let aac_type_flag = (flags & FLAG_AAC_TYPE) != 0;
let saoc_de_flag = (flags & FLAG_SAOC_DE) != 0;
let mut pos = EXTENSION_OFFSET;
let aac_type = if aac_type_flag {
if pos >= body.len() {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "AAC_type_flag set but AAC_type byte missing",
});
}
let t = body[pos];
pos += 1;
Some(t)
} else {
None
};
let additional_info = &body[pos..];
Some(AacExtension {
saoc_de_flag,
reserved_zero_future_use: ReservedZero::from_bits(u64::from(flags)),
aac_type,
additional_info,
})
} else {
None
};
Ok(Self {
profile_and_level,
extension,
})
}
}
impl Serialize for AacDescriptor<'_> {
type Error = crate::error::Error;
fn serialized_len(&self) -> usize {
let body = 1 + match &self.extension {
None => 0,
Some(ext) => 1 + usize::from(ext.aac_type.is_some()) + ext.additional_info.len(),
};
HEADER_LEN + body
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let body_len = self.serialized_len() - HEADER_LEN;
if body_len > u8::MAX as usize {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "AAC_descriptor body exceeds 255 bytes",
});
}
let len = self.serialized_len();
need_out(buf, len, "AacDescriptor")?;
crate::descriptors::write_descriptor_header(buf, TAG, body_len)?;
buf[HEADER_LEN + PROFILE_AND_LEVEL_OFFSET] = self.profile_and_level;
let mut pos = HEADER_LEN + FLAGS_OFFSET;
if let Some(ext) = &self.extension {
let mut flags = 0u8;
if ext.aac_type.is_some() {
flags |= FLAG_AAC_TYPE;
}
if ext.saoc_de_flag {
flags |= FLAG_SAOC_DE;
}
buf[pos] = flags | ext.reserved_zero_future_use.get() as u8;
pos += 1;
if let Some(t) = ext.aac_type {
buf[pos] = t;
pos += 1;
}
buf[pos..pos + ext.additional_info.len()].copy_from_slice(ext.additional_info);
}
Ok(len)
}
}
impl<'a> crate::traits::DescriptorDef<'a> for AacDescriptor<'a> {
const TAG: u8 = TAG;
const NAME: &'static str = "AAC";
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
#[test]
fn parse_profile_only() {
let bytes = [TAG, 1, 0x50];
let d = AacDescriptor::parse(&bytes).unwrap();
assert_eq!(d.profile_and_level, 0x50);
assert!(d.extension.is_none());
}
#[test]
fn parse_with_flags_no_aac_type() {
let bytes = [TAG, 2, 0x51, FLAG_SAOC_DE];
let d = AacDescriptor::parse(&bytes).unwrap();
let ext = d.extension.unwrap();
assert!(ext.saoc_de_flag);
assert!(ext.aac_type.is_none());
assert!(ext.additional_info.is_empty());
}
#[test]
fn parse_with_aac_type() {
let bytes = [TAG, 3, 0x52, FLAG_AAC_TYPE, 0x03];
let d = AacDescriptor::parse(&bytes).unwrap();
let ext = d.extension.unwrap();
assert!(!ext.saoc_de_flag);
assert_eq!(ext.aac_type, Some(0x03));
assert!(ext.additional_info.is_empty());
}
#[test]
fn parse_with_aac_type_and_additional_info() {
let bytes = [TAG, 5, 0x52, FLAG_AAC_TYPE | FLAG_SAOC_DE, 0x05, 0xAA, 0xBB];
let d = AacDescriptor::parse(&bytes).unwrap();
let ext = d.extension.unwrap();
assert!(ext.saoc_de_flag);
assert_eq!(ext.aac_type, Some(0x05));
assert_eq!(ext.additional_info, &[0xAA, 0xBB]);
}
#[test]
fn decode_aac_component_type_he_aac_stereo() {
let d = AacDescriptor {
profile_and_level: 0x50,
extension: Some(AacExtension::new(false, Some(0x03), &[])),
};
let ct = d.extension.unwrap().decoded_component_type().unwrap();
assert!(!ct.mono);
assert!(ct.stereo);
assert!(!ct.surround);
assert_eq!(ct.name(), "HE-AAC audio, stereo");
}
#[test]
fn decode_aac_component_type_saoc_de() {
let d = AacDescriptor {
profile_and_level: 0x50,
extension: Some(AacExtension::new(true, Some(0xA0), &[])),
};
let ct = d.extension.unwrap().decoded_component_type().unwrap();
assert!(ct.saoc_de);
assert_eq!(ct.name(), "HE-AAC or HE-AAC v2 with SAOC-DE ancillary data");
}
#[test]
fn decode_aac_component_type_unknown() {
let d = AacDescriptor {
profile_and_level: 0x50,
extension: Some(AacExtension::new(false, Some(0xFF), &[])),
};
assert!(d.extension.unwrap().decoded_component_type().is_none());
}
#[test]
fn decode_aac_component_type_every_table_26_code() {
let ct = |mono, stereo, surround, visually_impaired, hard_of_hearing, supplementary, v2| {
AacComponentType {
mono,
stereo,
surround,
visually_impaired,
hard_of_hearing,
supplementary,
v2,
saoc_de: false,
}
};
let cases = [
(0x01, ct(true, false, false, false, false, false, false)),
(0x03, ct(false, true, false, false, false, false, false)),
(0x05, ct(false, false, true, false, false, false, false)),
(0x40, ct(false, false, false, true, false, false, false)),
(0x41, ct(false, false, false, false, true, false, false)),
(0x42, ct(false, false, false, false, false, true, false)),
(0x43, ct(false, true, false, false, false, false, true)),
(0x44, ct(false, false, false, true, false, false, true)),
(0x45, ct(false, false, false, false, true, false, true)),
(0x46, ct(false, false, false, false, false, true, true)),
(0x47, ct(false, false, false, true, false, true, false)),
(0x48, ct(false, false, false, true, false, true, false)),
(0x49, ct(false, false, false, true, false, true, true)),
(0x4A, ct(false, false, false, true, false, true, true)),
];
for (code, want) in cases {
let ext = AacExtension::new(false, Some(code), &[]);
assert_eq!(
ext.decoded_component_type(),
Some(want),
"aac_type = 0x{code:02X}"
);
}
let saoc = AacExtension::new(false, Some(0xA0), &[]);
let want = AacComponentType {
mono: false,
stereo: false,
surround: false,
visually_impaired: false,
hard_of_hearing: false,
supplementary: false,
v2: false,
saoc_de: true,
};
assert_eq!(saoc.decoded_component_type(), Some(want));
}
#[test]
fn parse_rejects_wrong_tag() {
let bytes = [0x7B, 1, 0x50];
assert!(matches!(
AacDescriptor::parse(&bytes).unwrap_err(),
Error::InvalidDescriptor { tag: 0x7B, .. }
));
}
#[test]
fn parse_rejects_aac_type_flag_without_byte() {
let bytes = [TAG, 2, 0x50, FLAG_AAC_TYPE];
assert!(matches!(
AacDescriptor::parse(&bytes).unwrap_err(),
Error::InvalidDescriptor { .. }
));
}
#[test]
fn parse_rejects_length_overrunning_buffer() {
let bytes = [TAG, 4, 0x50];
assert!(matches!(
AacDescriptor::parse(&bytes).unwrap_err(),
Error::BufferTooShort(..)
));
}
#[test]
fn serialize_round_trip_profile_only() {
let d = AacDescriptor {
profile_and_level: 0x58,
extension: None,
};
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf, vec![TAG, 1, 0x58]);
assert_eq!(AacDescriptor::parse(&buf).unwrap(), d);
}
#[test]
fn serialize_round_trip_full() {
let d = AacDescriptor {
profile_and_level: 0x52,
extension: Some(AacExtension::new(true, Some(0x40), &[0xFE, 0xED])),
};
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(AacDescriptor::parse(&buf).unwrap(), d);
}
#[test]
fn aac_reserved_preserved() {
for r in
0u8..=u8::try_from(ReservedZero::<RESERVED_FUTURE_USE_BITS>::MASK).unwrap_or(u8::MAX)
{
for flags in [0u8, FLAG_SAOC_DE] {
let bytes = [TAG, 3, 0x50, flags | r, 0xEE];
let d = AacDescriptor::parse(&bytes).unwrap();
assert_eq!(
d.extension.as_ref().unwrap().reserved_zero_future_use,
ReservedZero::<RESERVED_FUTURE_USE_BITS>::from_bits(u64::from(r))
);
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf, bytes, "r={r:#x} flags={flags:#x}");
}
}
}
#[test]
fn aac_default_is_spec_value() {
let d = AacDescriptor {
profile_and_level: 0x50,
extension: Some(AacExtension::new(true, Some(0x03), &[])),
};
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf, [TAG, 3, 0x50, FLAG_AAC_TYPE | FLAG_SAOC_DE, 0x03]);
}
#[test]
fn serialize_emits_reserved_bits_zero() {
let d = AacDescriptor {
profile_and_level: 0x50,
extension: Some(AacExtension::new(false, None, &[])),
};
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(
buf[3] & ReservedZero::<RESERVED_FUTURE_USE_BITS>::MASK as u8,
0
);
assert_eq!(buf[3], 0x00);
}
#[test]
fn serialize_accepts_max_255_byte_body() {
let info = [0xAAu8; 253];
let d = AacDescriptor {
profile_and_level: 0x50,
extension: Some(AacExtension::new(false, None, &info)),
};
assert_eq!(d.serialized_len(), HEADER_LEN + 255);
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf[1], 0xFF);
}
#[test]
fn serialize_rejects_256_byte_body() {
let info = [0xAAu8; 254];
let d = AacDescriptor {
profile_and_level: 0x50,
extension: Some(AacExtension::new(false, None, &info)),
};
let mut buf = vec![0u8; d.serialized_len()];
assert!(matches!(
d.serialize_into(&mut buf).unwrap_err(),
Error::InvalidDescriptor { tag: TAG, .. }
));
}
}