| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | #![forbid(unsafe_code)] |
| 24 | #![warn(missing_docs)] |
| 25 | |
| 26 | mod decode; |
| 27 | |
| 28 | use ec_core::error::{Error, Result}; |
| 29 | use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; |
| 30 | use ec_core::packet::{Buf, Packet}; |
| 31 | use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters}; |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 37 | pub struct MagicCookie { |
| 38 | |
| 39 | |
| 40 | pub frame_length: u32, |
| 41 | |
| 42 | pub compatible_version: u8, |
| 43 | |
| 44 | pub bit_depth: u8, |
| 45 | |
| 46 | pub pb: u8, |
| 47 | |
| 48 | pub mb: u8, |
| 49 | |
| 50 | pub kb: u8, |
| 51 | |
| 52 | pub channels: u8, |
| 53 | |
| 54 | pub max_run: u16, |
| 55 | |
| 56 | pub max_frame_bytes: u32, |
| 57 | |
| 58 | pub avg_bit_rate: u32, |
| 59 | |
| 60 | pub sample_rate: u32, |
| 61 | } |
| 62 | |
| 63 | impl MagicCookie { |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | pub fn parse(data: &[u8]) -> Result<MagicCookie> { |
| 71 | let at = match data { |
| 72 | [_, _, _, _, b'a', b'l', b'a', b'c', ..] if data.len() >= 36 => 12, |
| 73 | _ if data.len() >= 28 && Self::at(data, 0).is_err() => 4, |
| 74 | _ => 0, |
| 75 | }; |
| 76 | Self::at(data, at) |
| 77 | } |
| 78 | |
| 79 | fn at(data: &[u8], at: usize) -> Result<MagicCookie> { |
| 80 | let c = data |
| 81 | .get(at..at + 24) |
| 82 | .ok_or_else(|| Error::corrupt("ALAC: a magic cookie shorter than 24 bytes"))?; |
| 83 | let be32 = |i: usize| u32::from_be_bytes([c[i], c[i + 1], c[i + 2], c[i + 3]]); |
| 84 | let cookie = MagicCookie { |
| 85 | frame_length: be32(0), |
| 86 | compatible_version: c[4], |
| 87 | bit_depth: c[5], |
| 88 | pb: c[6], |
| 89 | mb: c[7], |
| 90 | kb: c[8], |
| 91 | channels: c[9], |
| 92 | max_run: u16::from_be_bytes([c[10], c[11]]), |
| 93 | max_frame_bytes: be32(12), |
| 94 | avg_bit_rate: be32(16), |
| 95 | sample_rate: be32(20), |
| 96 | }; |
| 97 | |
| 98 | |
| 99 | if !(1..=1 << 20).contains(&cookie.frame_length) { |
| 100 | return Err(Error::corrupt(format!( |
| 101 | "ALAC: a {}-sample frame length", |
| 102 | cookie.frame_length |
| 103 | ))); |
| 104 | } |
| 105 | if !(1..=32).contains(&cookie.bit_depth) { |
| 106 | return Err(Error::corrupt(format!( |
| 107 | "ALAC: {}-bit samples", |
| 108 | cookie.bit_depth |
| 109 | ))); |
| 110 | } |
| 111 | if !(1..=8).contains(&cookie.channels) { |
| 112 | return Err(Error::corrupt(format!( |
| 113 | "ALAC: {} channels", |
| 114 | cookie.channels |
| 115 | ))); |
| 116 | } |
| 117 | Ok(cookie) |
| 118 | } |
| 119 | |
| 120 | |
| 121 | |
| 122 | pub fn container_shift(&self) -> u32 { |
| 123 | match u32::from(self.bit_depth) <= 16 { |
| 124 | true => 16 - u32::from(self.bit_depth), |
| 125 | false => 32 - u32::from(self.bit_depth), |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | |
| 130 | pub fn sample_format(&self) -> SampleFormat { |
| 131 | match self.bit_depth <= 16 { |
| 132 | true => SampleFormat::S16, |
| 133 | false => SampleFormat::S32, |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | fn film_order(channels: usize) -> &'static [usize] { |
| 144 | match channels { |
| 145 | 3 => &[1, 2, 0], |
| 146 | 4 => &[1, 2, 0, 3], |
| 147 | 5 => &[1, 2, 0, 3, 4], |
| 148 | 6 => &[1, 2, 0, 5, 3, 4], |
| 149 | 7 => &[1, 2, 0, 6, 5, 3, 4], |
| 150 | 8 => &[3, 4, 0, 7, 5, 6, 1, 2], |
| 151 | |
| 152 | _ => &[0, 1], |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | |
| 157 | #[derive(Debug)] |
| 158 | pub struct AlacDecoder { |
| 159 | cookie: MagicCookie, |
| 160 | params: CodecParameters, |
| 161 | scratch: decode::Scratch, |
| 162 | coded: Vec<i32>, |
| 163 | out: Vec<i32>, |
| 164 | pending: Option<AudioFrame>, |
| 165 | drained: bool, |
| 166 | } |
| 167 | |
| 168 | impl AlacDecoder { |
| 169 | |
| 170 | pub fn new(cookie: MagicCookie) -> AlacDecoder { |
| 171 | AlacDecoder { |
| 172 | params: codec_parameters(&cookie), |
| 173 | cookie, |
| 174 | scratch: decode::Scratch::default(), |
| 175 | coded: Vec::new(), |
| 176 | out: Vec::new(), |
| 177 | pending: None, |
| 178 | drained: false, |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | |
| 183 | |
| 184 | pub fn from_parameters(params: CodecParameters) -> Result<AlacDecoder> { |
| 185 | let cookie = MagicCookie::parse(params.extradata.as_deref().ok_or_else(|| { |
| 186 | Error::corrupt("ALAC: a track with no magic cookie in its extradata") |
| 187 | })?)?; |
| 188 | let mut decoder = AlacDecoder::new(cookie); |
| 189 | decoder.params.extradata = params.extradata; |
| 190 | Ok(decoder) |
| 191 | } |
| 192 | |
| 193 | |
| 194 | pub fn cookie(&self) -> &MagicCookie { |
| 195 | &self.cookie |
| 196 | } |
| 197 | |
| 198 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | pub fn decode(&mut self, data: &[u8]) -> Result<&[i32]> { |
| 203 | let channels = usize::from(self.cookie.channels.max(1)); |
| 204 | let samples = decode::frame(&self.cookie, &mut self.scratch, data, &mut self.coded)?; |
| 205 | let shift = self.cookie.container_shift(); |
| 206 | let map = film_order(channels); |
| 207 | self.out.clear(); |
| 208 | self.out.reserve(samples * channels); |
| 209 | for frame in self.coded.chunks_exact(channels).take(samples) { |
| 210 | for &src in &map[..channels] { |
| 211 | self.out.push(frame[src] << shift); |
| 212 | } |
| 213 | } |
| 214 | Ok(&self.out) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | impl Decoder for AlacDecoder { |
| 219 | fn codec_parameters(&self) -> &CodecParameters { |
| 220 | &self.params |
| 221 | } |
| 222 | |
| 223 | fn send_packet(&mut self, packet: &Packet) -> Result<()> { |
| 224 | self.decode(&packet.data)?; |
| 225 | let channels = usize::from(self.cookie.channels.max(1)); |
| 226 | let format = self.cookie.sample_format(); |
| 227 | let mut bytes = Vec::with_capacity(self.out.len() * format.bytes_per_sample()); |
| 228 | for &s in &self.out { |
| 229 | match format { |
| 230 | SampleFormat::S16 => bytes.extend_from_slice(&(s as i16).to_ne_bytes()), |
| 231 | _ => bytes.extend_from_slice(&s.to_ne_bytes()), |
| 232 | } |
| 233 | } |
| 234 | let mut frame = AudioFrame::try_new( |
| 235 | format, |
| 236 | false, |
| 237 | ChannelLayout::from_count(channels), |
| 238 | self.cookie.sample_rate, |
| 239 | self.out.len() / channels, |
| 240 | vec![Buf::from_vec(bytes)], |
| 241 | )?; |
| 242 | frame.pts = packet |
| 243 | .pts |
| 244 | .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base)); |
| 245 | self.pending = Some(frame); |
| 246 | Ok(()) |
| 247 | } |
| 248 | |
| 249 | fn receive_frame(&mut self) -> Result<Frame> { |
| 250 | match self.pending.take() { |
| 251 | Some(frame) => Ok(Frame::Audio(frame)), |
| 252 | None if self.drained => Err(Error::Eof), |
| 253 | None => Err(Error::NeedMore), |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | fn flush(&mut self) -> Result<()> { |
| 258 | self.drained = true; |
| 259 | Ok(()) |
| 260 | } |
| 261 | |
| 262 | fn reset(&mut self) { |
| 263 | self.pending = None; |
| 264 | self.drained = false; |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | |
| 269 | pub fn codec_parameters(cookie: &MagicCookie) -> CodecParameters { |
| 270 | let mut params = CodecParameters::new(CodecId::Alac); |
| 271 | params.media = MediaParameters::Audio(AudioParameters { |
| 272 | sample_rate: cookie.sample_rate, |
| 273 | layout: ChannelLayout::from_count(usize::from(cookie.channels.max(1))), |
| 274 | format: Some(cookie.sample_format()), |
| 275 | bits_per_sample: Some(u32::from(cookie.bit_depth)), |
| 276 | }); |
| 277 | params |
| 278 | } |
| 279 | |
| 280 | #[cfg(test)] |
| 281 | mod tests { |
| 282 | use super::*; |
| 283 | |
| 284 | |
| 285 | |
| 286 | #[test] |
| 287 | fn a_magic_cookie_is_read_in_every_shape_a_container_states_it() { |
| 288 | let config: [u8; 24] = [ |
| 289 | 0, 0, 0x10, 0, |
| 290 | 0, 16, |
| 291 | 40, 10, 14, |
| 292 | 2, |
| 293 | 0, 255, |
| 294 | 0, 0, 0x10, 0, |
| 295 | 0, 0, 0, 0, |
| 296 | 0, 0, 0xAC, 0x44, |
| 297 | ]; |
| 298 | let bare = MagicCookie::parse(&config).expect("bare config"); |
| 299 | assert_eq!(bare.frame_length, 4096); |
| 300 | assert_eq!(bare.bit_depth, 16); |
| 301 | assert_eq!(bare.channels, 2); |
| 302 | assert_eq!(bare.sample_rate, 44100); |
| 303 | assert_eq!(bare.pb, 40); |
| 304 | assert_eq!(bare.mb, 10); |
| 305 | assert_eq!(bare.kb, 14); |
| 306 | |
| 307 | let mut boxed = vec![0, 0, 0, 36, b'a', b'l', b'a', b'c', 0, 0, 0, 0]; |
| 308 | boxed.extend_from_slice(&config); |
| 309 | assert_eq!(MagicCookie::parse(&boxed).expect("boxed"), bare); |
| 310 | |
| 311 | let mut versioned = vec![0, 0, 0, 0]; |
| 312 | versioned.extend_from_slice(&config); |
| 313 | assert_eq!(MagicCookie::parse(&versioned).expect("versioned"), bare); |
| 314 | |
| 315 | |
| 316 | assert!(MagicCookie::parse(&config[..12]).is_err()); |
| 317 | } |
| 318 | |
| 319 | |
| 320 | |
| 321 | #[test] |
| 322 | fn film_order_is_a_permutation_at_every_width() { |
| 323 | for channels in 1..=8usize { |
| 324 | let map = film_order(channels); |
| 325 | let mut seen: Vec<usize> = map[..channels].to_vec(); |
| 326 | seen.sort_unstable(); |
| 327 | seen.dedup(); |
| 328 | assert_eq!(seen.len(), channels, "{channels} channels"); |
| 329 | assert!(seen.iter().all(|&c| c < channels), "{channels} channels"); |
| 330 | } |
| 331 | |
| 332 | assert_eq!(film_order(6), &[1, 2, 0, 5, 3, 4]); |
| 333 | } |
| 334 | } |