forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

lib.rs334 lines, 11.9 KiBHistoryRawDownload
1//! Apple Lossless (ALAC) decoding for the edith_codecs family.
2//!
3//! Two ways in:
4//!
5//! - [`AlacDecoder::decode`], one coded frame in, interleaved samples out, in
6//! the layout order the rest of the family uses (FL, FR, FC, LFE, BL, BR for
7//! 5.1 — the stream's own order is centre-first).
8//! - [`AlacDecoder`] as an [`ec_core::Decoder`], for a container that hands out
9//! one ALAC frame per packet, which is how mp4 and Matroska deliver them.
10//!
11//! The stream describes itself in a *magic cookie* ([`MagicCookie`]) that every
12//! container carries as extradata: the frame length, the bit depth and the
13//! three Golomb constants the residual coder adapts from.
14//!
15//! Decode only — edith never writes ALAC, so there is no encoder here and no
16//! pretending otherwise.
17//!
18//! **Clean room.** Written from the published ALAC format description; Apple's
19//! decoder sources were not read. Samples are returned shifted into their PCM
20//! container the way ffmpeg's decoder returns them (16-bit as `s16`, 24-bit as
21//! `s32` with the low 8 bits zero), so raw output compares byte for byte.
22
23#![forbid(unsafe_code)]
24#![warn(missing_docs)]
25
26mod decode;
27
28use ec_core::error::{Error, Result};
29use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
30use ec_core::packet::{Buf, Packet};
31use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters};
32
33/// The `ALACSpecificConfig` every ALAC stream is introduced by: 24 bytes,
34/// big-endian, carried as the body of an `alac` box in mp4 and as `CodecPrivate`
35/// in Matroska.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct MagicCookie {
38 /// Samples per channel in a full frame (4096 from Apple's encoder). A
39 /// stream's last frame states its own shorter length.
40 pub frame_length: u32,
41 /// Bitstream version the file is compatible with; 0 is the only one.
42 pub compatible_version: u8,
43 /// Bits per sample: 16, 20, 24 or 32.
44 pub bit_depth: u8,
45 /// Golomb mean update rate.
46 pub pb: u8,
47 /// Initial Golomb mean.
48 pub mb: u8,
49 /// Ceiling on the Rice parameter.
50 pub kb: u8,
51 /// Channels the stream carries.
52 pub channels: u8,
53 /// Longest zero run the encoder emits.
54 pub max_run: u16,
55 /// Largest coded frame in bytes, `0` when the encoder did not say.
56 pub max_frame_bytes: u32,
57 /// Nominal bit rate, `0` when the encoder did not say.
58 pub avg_bit_rate: u32,
59 /// Sample rate in Hz.
60 pub sample_rate: u32,
61}
62
63impl MagicCookie {
64 /// Parse a cookie from the bytes a container carries.
65 ///
66 /// Accepts the three shapes those bytes arrive in: the bare 24-byte config,
67 /// the config behind a four-byte version/flags word, and the whole `alac`
68 /// box with its size and type in front (which is what ffmpeg and this
69 /// family's own mp4 demuxer hand over).
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 // The three fields a decoder cannot proceed on, checked here so a
98 // mis-sliced cookie is caught at open rather than as garbled audio.
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 /// Bits the decoded samples are shifted left by to fill their PCM
121 /// container, matching [`MagicCookie::sample_format`].
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 /// The sample format decoded audio is delivered in.
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/// Where each output channel sits in the stream's own coded order.
139///
140/// ALAC codes centre first (C, L, R, Ls, Rs, LFE for 5.1) because its elements
141/// are AAC's; every consumer in this family wants film order (FL, FR, FC, LFE,
142/// BL, BR), so the map is applied once, on the way out.
143fn 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 // Mono and stereo are already in it.
152 _ => &[0, 1],
153 }
154}
155
156/// An ALAC decoder for one stream.
157#[derive(Debug)]
158pub 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
168impl AlacDecoder {
169 /// A decoder for a stream described by `cookie`.
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 /// A decoder for a stream whose `extradata` is its magic cookie, which is
183 /// how every container states one.
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 /// What the stream said about itself.
194 pub fn cookie(&self) -> &MagicCookie {
195 &self.cookie
196 }
197
198 /// One coded frame in, interleaved samples out in film order, already
199 /// shifted into their PCM container.
200 ///
201 /// The slice is valid until the next call; a caller that keeps it copies.
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
218impl 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/// Codec parameters for the stream a cookie describes.
269pub 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)]
281mod tests {
282 use super::*;
283
284 /// ffmpeg's 36-byte `alac` box, a bare 24-byte config and the 28-byte form
285 /// in between all describe the same stream.
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, // frameLength 4096
290 0, 16, // version 0, 16-bit
291 40, 10, 14, // pb, mb, kb
292 2, // channels
293 0, 255, // maxRun
294 0, 0, 0x10, 0, // maxFrameBytes
295 0, 0, 0, 0, // avgBitRate
296 0, 0, 0xAC, 0x44, // 44100
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 // A refusal that names what it refused, rather than decoding noise.
316 assert!(MagicCookie::parse(&config[..12]).is_err());
317 }
318
319 /// The layout map is a permutation for every width, which is the property
320 /// that keeps a channel from being dropped or doubled on the way out.
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 // 5.1: the stream's centre channel is coded first and lands third.
332 assert_eq!(film_order(6), &[1, 2, 0, 5, 3, 4]);
333 }
334}