Skip to main content

hang/catalog/audio/
aac.rs

1use crate::Error;
2
3use serde::{Deserialize, Serialize};
4
5/// AAC codec mimetype.
6///
7/// This struct contains the profile information for AAC audio streams.
8/// AAC supports multiple profiles with different complexity and quality levels.
9#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
10pub struct AAC {
11	/// AAC profile (e.g., 2 for LC, 5 for HE-AAC, 29 for HE-AACv2)
12	pub profile: u8,
13	// TODO:
14	// freq_index
15	// chan_conf
16}
17
18impl std::fmt::Display for AAC {
19	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20		write!(f, "mp4a.40.{}", self.profile)
21	}
22}
23
24impl std::str::FromStr for AAC {
25	type Err = Error;
26
27	fn from_str(s: &str) -> Result<Self, Self::Err> {
28		let remain = s.strip_prefix("mp4a.40.").ok_or(Error::InvalidCodec)?;
29		Ok(Self {
30			profile: crate::catalog::codec_number(remain, 10)?,
31		})
32	}
33}
34
35#[cfg(test)]
36mod test {
37	use std::str::FromStr;
38
39	use super::*;
40
41	#[test]
42	fn test_aac() {
43		let encoded = "mp4a.40.2";
44		let decoded = AAC { profile: 2 };
45
46		let output = AAC::from_str(encoded).expect("failed to parse AAC string");
47		assert_eq!(output, decoded);
48
49		let output = decoded.to_string();
50		assert_eq!(output, encoded);
51
52		// The WebCodecs AAC registration spells each object type with and without a leading zero.
53		assert_eq!(AAC::from_str("mp4a.40.05").unwrap(), AAC { profile: 5 });
54		assert_eq!(AAC::from_str("mp4a.40.02").unwrap(), AAC { profile: 2 });
55	}
56}