use bytes::{Buf, Bytes};
use crate::error::{MediaError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AacPacketType {
SequenceHeader = 0,
Raw = 1,
}
impl AacPacketType {
pub fn from_byte(b: u8) -> Option<Self> {
match b {
0 => Some(AacPacketType::SequenceHeader),
1 => Some(AacPacketType::Raw),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AacProfile {
Main = 1,
Lc = 2,
Ssr = 3,
Ltp = 4,
Sbr = 5,
Scalable = 6,
}
impl AacProfile {
pub fn from_object_type(ot: u8) -> Option<Self> {
match ot {
1 => Some(AacProfile::Main),
2 => Some(AacProfile::Lc),
3 => Some(AacProfile::Ssr),
4 => Some(AacProfile::Ltp),
5 => Some(AacProfile::Sbr),
6 => Some(AacProfile::Scalable),
_ => None,
}
}
pub fn name(&self) -> &'static str {
match self {
AacProfile::Main => "AAC Main",
AacProfile::Lc => "AAC LC",
AacProfile::Ssr => "AAC SSR",
AacProfile::Ltp => "AAC LTP",
AacProfile::Sbr => "HE-AAC",
AacProfile::Scalable => "AAC Scalable",
}
}
}
#[derive(Debug, Clone)]
pub struct AudioSpecificConfig {
pub audio_object_type: u8,
pub sampling_frequency_index: u8,
pub sampling_frequency: u32,
pub channel_configuration: u8,
pub frame_length_flag: bool,
pub depends_on_core_coder: bool,
pub extension_flag: bool,
pub raw: Bytes,
}
impl AudioSpecificConfig {
const SAMPLING_FREQUENCIES: [u32; 16] = [
96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, 0,
0, 0,
];
pub fn parse(data: Bytes) -> Result<Self> {
if data.len() < 2 {
return Err(MediaError::InvalidAacPacket.into());
}
let b0 = data[0];
let b1 = data[1];
let audio_object_type = (b0 >> 3) & 0x1F;
let sampling_frequency_index = ((b0 & 0x07) << 1) | ((b1 >> 7) & 0x01);
let sampling_frequency = if sampling_frequency_index == 0x0F {
if data.len() < 5 {
return Err(MediaError::InvalidAacPacket.into());
}
let f0 = (data[1] & 0x7F) as u32;
let f1 = data[2] as u32;
let f2 = data[3] as u32;
let f3 = (data[4] >> 1) as u32;
(f0 << 17) | (f1 << 9) | (f2 << 1) | f3
} else if (sampling_frequency_index as usize) < Self::SAMPLING_FREQUENCIES.len() {
Self::SAMPLING_FREQUENCIES[sampling_frequency_index as usize]
} else {
return Err(MediaError::InvalidAacPacket.into());
};
let channel_configuration = (b1 >> 3) & 0x0F;
let frame_length_flag = (b1 & 0x04) != 0;
let depends_on_core_coder = (b1 & 0x02) != 0;
let extension_flag = (b1 & 0x01) != 0;
Ok(AudioSpecificConfig {
audio_object_type,
sampling_frequency_index,
sampling_frequency,
channel_configuration,
frame_length_flag,
depends_on_core_coder,
extension_flag,
raw: data,
})
}
pub fn profile(&self) -> Option<AacProfile> {
AacProfile::from_object_type(self.audio_object_type)
}
pub fn channels(&self) -> u8 {
match self.channel_configuration {
0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 8, _ => 0,
}
}
pub fn samples_per_frame(&self) -> u32 {
if self.frame_length_flag {
960
} else {
1024
}
}
}
#[derive(Debug, Clone)]
pub enum AacData {
SequenceHeader(AudioSpecificConfig),
Frame {
data: Bytes,
},
}
impl AacData {
pub fn parse(mut data: Bytes) -> Result<Self> {
if data.is_empty() {
return Err(MediaError::InvalidAacPacket.into());
}
let packet_type = data.get_u8();
match AacPacketType::from_byte(packet_type) {
Some(AacPacketType::SequenceHeader) => {
let config = AudioSpecificConfig::parse(data)?;
Ok(AacData::SequenceHeader(config))
}
Some(AacPacketType::Raw) => Ok(AacData::Frame { data }),
None => Err(MediaError::InvalidAacPacket.into()),
}
}
pub fn is_sequence_header(&self) -> bool {
matches!(self, AacData::SequenceHeader(_))
}
}
pub fn generate_adts_header(config: &AudioSpecificConfig, frame_length: usize) -> [u8; 7] {
let profile = config.audio_object_type.saturating_sub(1); let freq_idx = config.sampling_frequency_index;
let channels = config.channel_configuration;
let frame_len = frame_length + 7;
let mut header = [0u8; 7];
header[0] = 0xFF;
header[1] = 0xF1;
header[2] = ((profile & 0x03) << 6) | ((freq_idx & 0x0F) << 2) | ((channels >> 2) & 0x01);
header[3] = ((channels & 0x03) << 6) | ((frame_len >> 11) & 0x03) as u8;
header[4] = ((frame_len >> 3) & 0xFF) as u8;
header[5] = (((frame_len & 0x07) << 5) | 0x1F) as u8;
header[6] = 0xFC;
header
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_audio_specific_config_parse() {
let data = Bytes::from_static(&[0x12, 0x10]);
let config = AudioSpecificConfig::parse(data).unwrap();
assert_eq!(config.audio_object_type, 2); assert_eq!(config.sampling_frequency_index, 4); assert_eq!(config.sampling_frequency, 44100);
assert_eq!(config.channel_configuration, 2); assert_eq!(config.channels(), 2);
assert_eq!(config.profile(), Some(AacProfile::Lc));
}
#[test]
fn test_adts_header() {
let config = AudioSpecificConfig {
audio_object_type: 2,
sampling_frequency_index: 4,
sampling_frequency: 44100,
channel_configuration: 2,
frame_length_flag: false,
depends_on_core_coder: false,
extension_flag: false,
raw: Bytes::new(),
};
let header = generate_adts_header(&config, 100);
assert_eq!(header[0], 0xFF);
assert_eq!(header[1] & 0xF0, 0xF0);
}
#[test]
fn test_aac_packet_type() {
assert_eq!(
AacPacketType::from_byte(0),
Some(AacPacketType::SequenceHeader)
);
assert_eq!(AacPacketType::from_byte(1), Some(AacPacketType::Raw));
assert_eq!(AacPacketType::from_byte(2), None);
assert_eq!(AacPacketType::from_byte(255), None);
}
#[test]
fn test_aac_profile_from_object_type() {
assert_eq!(AacProfile::from_object_type(1), Some(AacProfile::Main));
assert_eq!(AacProfile::from_object_type(2), Some(AacProfile::Lc));
assert_eq!(AacProfile::from_object_type(3), Some(AacProfile::Ssr));
assert_eq!(AacProfile::from_object_type(4), Some(AacProfile::Ltp));
assert_eq!(AacProfile::from_object_type(5), Some(AacProfile::Sbr));
assert_eq!(AacProfile::from_object_type(6), Some(AacProfile::Scalable));
assert_eq!(AacProfile::from_object_type(0), None);
assert_eq!(AacProfile::from_object_type(7), None);
}
#[test]
fn test_aac_profile_names() {
assert_eq!(AacProfile::Main.name(), "AAC Main");
assert_eq!(AacProfile::Lc.name(), "AAC LC");
assert_eq!(AacProfile::Ssr.name(), "AAC SSR");
assert_eq!(AacProfile::Ltp.name(), "AAC LTP");
assert_eq!(AacProfile::Sbr.name(), "HE-AAC");
assert_eq!(AacProfile::Scalable.name(), "AAC Scalable");
}
#[test]
fn test_audio_specific_config_various_rates() {
let test_cases = [
(&[0x12, 0x10][..], 44100, 2),
(&[0x11, 0x90][..], 48000, 2),
(&[0x11, 0x88][..], 48000, 1),
];
for (data, expected_freq, expected_channels) in test_cases {
let config = AudioSpecificConfig::parse(Bytes::copy_from_slice(data)).unwrap();
assert_eq!(
config.sampling_frequency, expected_freq,
"sampling_frequency mismatch for {:02X?}",
data
);
assert_eq!(
config.channel_configuration, expected_channels,
"channel_configuration mismatch for {:02X?}",
data
);
}
}
#[test]
fn test_audio_specific_config_channels() {
let config = AudioSpecificConfig {
audio_object_type: 2,
sampling_frequency_index: 4,
sampling_frequency: 44100,
channel_configuration: 0, frame_length_flag: false,
depends_on_core_coder: false,
extension_flag: false,
raw: Bytes::new(),
};
assert_eq!(config.channels(), 0);
let channel_tests = [
(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 8), (8, 0), ];
for (config_value, expected_channels) in channel_tests {
let config = AudioSpecificConfig {
audio_object_type: 2,
sampling_frequency_index: 4,
sampling_frequency: 44100,
channel_configuration: config_value,
frame_length_flag: false,
depends_on_core_coder: false,
extension_flag: false,
raw: Bytes::new(),
};
assert_eq!(config.channels(), expected_channels);
}
}
#[test]
fn test_audio_specific_config_samples_per_frame() {
let config_1024 = AudioSpecificConfig {
audio_object_type: 2,
sampling_frequency_index: 4,
sampling_frequency: 44100,
channel_configuration: 2,
frame_length_flag: false, depends_on_core_coder: false,
extension_flag: false,
raw: Bytes::new(),
};
assert_eq!(config_1024.samples_per_frame(), 1024);
let config_960 = AudioSpecificConfig {
audio_object_type: 2,
sampling_frequency_index: 4,
sampling_frequency: 44100,
channel_configuration: 2,
frame_length_flag: true, depends_on_core_coder: false,
extension_flag: false,
raw: Bytes::new(),
};
assert_eq!(config_960.samples_per_frame(), 960);
}
#[test]
fn test_audio_specific_config_profile() {
let config = AudioSpecificConfig {
audio_object_type: 2, sampling_frequency_index: 4,
sampling_frequency: 44100,
channel_configuration: 2,
frame_length_flag: false,
depends_on_core_coder: false,
extension_flag: false,
raw: Bytes::new(),
};
assert_eq!(config.profile(), Some(AacProfile::Lc));
let config_unknown = AudioSpecificConfig {
audio_object_type: 99, sampling_frequency_index: 4,
sampling_frequency: 44100,
channel_configuration: 2,
frame_length_flag: false,
depends_on_core_coder: false,
extension_flag: false,
raw: Bytes::new(),
};
assert!(config_unknown.profile().is_none());
}
#[test]
fn test_aac_data_sequence_header() {
let data = Bytes::from_static(&[
0x00, 0x12, 0x10, ]);
let aac = AacData::parse(data).unwrap();
assert!(aac.is_sequence_header());
if let AacData::SequenceHeader(config) = aac {
assert_eq!(config.audio_object_type, 2);
assert_eq!(config.sampling_frequency, 44100);
assert_eq!(config.channel_configuration, 2);
} else {
panic!("Expected SequenceHeader");
}
}
#[test]
fn test_aac_data_raw_frame() {
let data = Bytes::from_static(&[
0x01, 0x21, 0x00, 0x49, 0x90, 0x02, ]);
let aac = AacData::parse(data).unwrap();
assert!(!aac.is_sequence_header());
if let AacData::Frame { data } = aac {
assert_eq!(data.len(), 5);
} else {
panic!("Expected Frame");
}
}
#[test]
fn test_aac_data_invalid_packet_type() {
let data = Bytes::from_static(&[0x02, 0x00, 0x00]); let result = AacData::parse(data);
assert!(result.is_err());
}
#[test]
fn test_aac_data_empty() {
let data = Bytes::new();
let result = AacData::parse(data);
assert!(result.is_err());
}
#[test]
fn test_audio_specific_config_too_short() {
let data = Bytes::from_static(&[0x12]); let result = AudioSpecificConfig::parse(data);
assert!(result.is_err());
}
#[test]
fn test_adts_header_frame_length() {
let config = AudioSpecificConfig {
audio_object_type: 2,
sampling_frequency_index: 4,
sampling_frequency: 44100,
channel_configuration: 2,
frame_length_flag: false,
depends_on_core_coder: false,
extension_flag: false,
raw: Bytes::new(),
};
let header1 = generate_adts_header(&config, 100);
let header2 = generate_adts_header(&config, 500);
assert_ne!(header1, header2);
assert_eq!(header1[0], 0xFF);
assert_eq!(header2[0], 0xFF);
}
#[test]
fn test_audio_specific_config_all_sampling_frequencies() {
let expected_freqs = [
96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
];
for (index, &expected) in expected_freqs.iter().enumerate() {
if index < 13 {
let freq = AudioSpecificConfig::SAMPLING_FREQUENCIES[index];
assert_eq!(freq, expected);
}
}
}
#[test]
fn test_aac_data_raw_stores_config_bytes() {
let raw_data = Bytes::from_static(&[0x12, 0x10]);
let config = AudioSpecificConfig::parse(raw_data.clone()).unwrap();
assert_eq!(config.raw.len(), 2);
}
}