forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a5feaaTahinli2 months ago3162 commits

lib.rs367 lines, 13.2 KiBHistoryRawDownload
1//! ALAC (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//! - [`AlacEncoder`], the mirror image: frames in, coded packets out, for a
16//! container that wants to write ALAC instead of read it.
17//!
18//! **Clean room.** Written from the published ALAC format description; the reference
19//! decoder sources were not read. Samples are returned shifted into their PCM
20//! container the way the oracle'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;
27mod encode;
28
29pub use encode::AlacEncoder;
30
31use ec_core::error::{Error, Result};
32use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
33use ec_core::packet::{Buf, Packet};
34use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters};
35
36/// The `ALACSpecificConfig` every ALAC stream is introduced by: 24 bytes,
37/// big-endian, carried as the body of an `alac` box in mp4 and as `CodecPrivate`
38/// in Matroska.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct MagicCookie {
41 /// Samples per channel in a full frame (4096 from the reference encoder). A
42 /// stream's last frame states its own shorter length.
43 pub frame_length: u32,
44 /// Bitstream version the file is compatible with; 0 is the only one.
45 pub compatible_version: u8,
46 /// Bits per sample: 16, 20, 24 or 32.
47 pub bit_depth: u8,
48 /// Golomb mean update rate.
49 pub pb: u8,
50 /// Initial Golomb mean.
51 pub mb: u8,
52 /// Ceiling on the Rice parameter.
53 pub kb: u8,
54 /// Channels the stream carries.
55 pub channels: u8,
56 /// Longest zero run the encoder emits.
57 pub max_run: u16,
58 /// Largest coded frame in bytes, `0` when the encoder did not say.
59 pub max_frame_bytes: u32,
60 /// Nominal bit rate, `0` when the encoder did not say.
61 pub avg_bit_rate: u32,
62 /// Sample rate in Hz.
63 pub sample_rate: u32,
64}
65
66impl MagicCookie {
67 /// Parse a cookie from the bytes a container carries.
68 ///
69 /// Accepts the three shapes those bytes arrive in: the bare 24-byte config,
70 /// the config behind a four-byte version/flags word, and the whole `alac`
71 /// box with its size and type in front (which is what the oracle and this
72 /// family's own mp4 demuxer hand over).
73 pub fn parse(data: &[u8]) -> Result<MagicCookie> {
74 let at = match data {
75 [_, _, _, _, b'a', b'l', b'a', b'c', ..] if data.len() >= 36 => 12,
76 _ if data.len() >= 28 && Self::at(data, 0).is_err() => 4,
77 _ => 0,
78 };
79 Self::at(data, at)
80 }
81
82 fn at(data: &[u8], at: usize) -> Result<MagicCookie> {
83 let c = data
84 .get(at..at + 24)
85 .ok_or_else(|| Error::corrupt("ALAC: a magic cookie shorter than 24 bytes"))?;
86 let be32 = |i: usize| u32::from_be_bytes([c[i], c[i + 1], c[i + 2], c[i + 3]]);
87 let cookie = MagicCookie {
88 frame_length: be32(0),
89 compatible_version: c[4],
90 bit_depth: c[5],
91 pb: c[6],
92 mb: c[7],
93 kb: c[8],
94 channels: c[9],
95 max_run: u16::from_be_bytes([c[10], c[11]]),
96 max_frame_bytes: be32(12),
97 avg_bit_rate: be32(16),
98 sample_rate: be32(20),
99 };
100 // The three fields a decoder cannot proceed on, checked here so a
101 // mis-sliced cookie is caught at open rather than as garbled audio.
102 if !(1..=1 << 20).contains(&cookie.frame_length) {
103 return Err(Error::corrupt(format!(
104 "ALAC: a {}-sample frame length",
105 cookie.frame_length
106 )));
107 }
108 if !(1..=32).contains(&cookie.bit_depth) {
109 return Err(Error::corrupt(format!(
110 "ALAC: {}-bit samples",
111 cookie.bit_depth
112 )));
113 }
114 if !(1..=8).contains(&cookie.channels) {
115 return Err(Error::corrupt(format!(
116 "ALAC: {} channels",
117 cookie.channels
118 )));
119 }
120 Ok(cookie)
121 }
122
123 /// Bits the decoded samples are shifted left by to fill their PCM
124 /// container, matching [`MagicCookie::sample_format`].
125 pub fn container_shift(&self) -> u32 {
126 match u32::from(self.bit_depth) <= 16 {
127 true => 16 - u32::from(self.bit_depth),
128 false => 32 - u32::from(self.bit_depth),
129 }
130 }
131
132 /// The sample format decoded audio is delivered in.
133 pub fn sample_format(&self) -> SampleFormat {
134 match self.bit_depth <= 16 {
135 true => SampleFormat::S16,
136 false => SampleFormat::S32,
137 }
138 }
139
140 /// The bare 24-byte `ALACSpecificConfig`, big-endian.
141 pub fn to_bytes(&self) -> [u8; 24] {
142 let mut b = [0u8; 24];
143 b[0..4].copy_from_slice(&self.frame_length.to_be_bytes());
144 b[4] = self.compatible_version;
145 b[5] = self.bit_depth;
146 b[6] = self.pb;
147 b[7] = self.mb;
148 b[8] = self.kb;
149 b[9] = self.channels;
150 b[10..12].copy_from_slice(&self.max_run.to_be_bytes());
151 b[12..16].copy_from_slice(&self.max_frame_bytes.to_be_bytes());
152 b[16..20].copy_from_slice(&self.avg_bit_rate.to_be_bytes());
153 b[20..24].copy_from_slice(&self.sample_rate.to_be_bytes());
154 b
155 }
156
157 /// The whole `alac` box a container's sample entry carries: a 12-byte
158 /// full-box header (size, `alac`, version/flags) in front of
159 /// [`MagicCookie::to_bytes`], which is the shape `ec_mp4`'s muxer expects
160 /// as a track's `extradata`.
161 pub fn extradata_box(&self) -> Vec<u8> {
162 let mut out = Vec::with_capacity(36);
163 out.extend_from_slice(&36u32.to_be_bytes());
164 out.extend_from_slice(b"alac");
165 out.extend_from_slice(&0u32.to_be_bytes());
166 out.extend_from_slice(&self.to_bytes());
167 out
168 }
169}
170
171/// Where each output channel sits in the stream's own coded order.
172///
173/// ALAC codes centre first (C, L, R, Ls, Rs, LFE for 5.1) because its elements
174/// are AAC's; every consumer in this family wants film order (FL, FR, FC, LFE,
175/// BL, BR), so the map is applied once, on the way out.
176fn film_order(channels: usize) -> &'static [usize] {
177 match channels {
178 3 => &[1, 2, 0],
179 4 => &[1, 2, 0, 3],
180 5 => &[1, 2, 0, 3, 4],
181 6 => &[1, 2, 0, 5, 3, 4],
182 7 => &[1, 2, 0, 6, 5, 3, 4],
183 8 => &[3, 4, 0, 7, 5, 6, 1, 2],
184 // Mono and stereo are already in it.
185 _ => &[0, 1],
186 }
187}
188
189/// An ALAC decoder for one stream.
190#[derive(Debug)]
191pub struct AlacDecoder {
192 cookie: MagicCookie,
193 params: CodecParameters,
194 scratch: decode::Scratch,
195 coded: Vec<i32>,
196 out: Vec<i32>,
197 pending: Option<AudioFrame>,
198 drained: bool,
199}
200
201impl AlacDecoder {
202 /// A decoder for a stream described by `cookie`.
203 pub fn new(cookie: MagicCookie) -> AlacDecoder {
204 AlacDecoder {
205 params: codec_parameters(&cookie),
206 cookie,
207 scratch: decode::Scratch::default(),
208 coded: Vec::new(),
209 out: Vec::new(),
210 pending: None,
211 drained: false,
212 }
213 }
214
215 /// A decoder for a stream whose `extradata` is its magic cookie, which is
216 /// how every container states one.
217 pub fn from_parameters(params: CodecParameters) -> Result<AlacDecoder> {
218 let cookie = MagicCookie::parse(params.extradata.as_deref().ok_or_else(|| {
219 Error::corrupt("ALAC: a track with no magic cookie in its extradata")
220 })?)?;
221 let mut decoder = AlacDecoder::new(cookie);
222 decoder.params.extradata = params.extradata;
223 Ok(decoder)
224 }
225
226 /// What the stream said about itself.
227 pub fn cookie(&self) -> &MagicCookie {
228 &self.cookie
229 }
230
231 /// One coded frame in, interleaved samples out in film order, already
232 /// shifted into their PCM container.
233 ///
234 /// The slice is valid until the next call; a caller that keeps it copies.
235 pub fn decode(&mut self, data: &[u8]) -> Result<&[i32]> {
236 let channels = usize::from(self.cookie.channels.max(1));
237 let samples = decode::frame(&self.cookie, &mut self.scratch, data, &mut self.coded)?;
238 let shift = self.cookie.container_shift();
239 let map = film_order(channels);
240 self.out.clear();
241 self.out.reserve(samples * channels);
242 for frame in self.coded.chunks_exact(channels).take(samples) {
243 for &src in &map[..channels] {
244 self.out.push(frame[src] << shift);
245 }
246 }
247 Ok(&self.out)
248 }
249}
250
251impl Decoder for AlacDecoder {
252 fn codec_parameters(&self) -> &CodecParameters {
253 &self.params
254 }
255
256 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
257 self.decode(&packet.data)?;
258 let channels = usize::from(self.cookie.channels.max(1));
259 let format = self.cookie.sample_format();
260 let mut bytes = Vec::with_capacity(self.out.len() * format.bytes_per_sample());
261 for &s in &self.out {
262 match format {
263 SampleFormat::S16 => bytes.extend_from_slice(&(s as i16).to_ne_bytes()),
264 _ => bytes.extend_from_slice(&s.to_ne_bytes()),
265 }
266 }
267 let mut frame = AudioFrame::try_new(
268 format,
269 false,
270 ChannelLayout::from_count(channels),
271 self.cookie.sample_rate,
272 self.out.len() / channels,
273 vec![Buf::from_vec(bytes)],
274 )?;
275 frame.pts = packet
276 .pts
277 .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base));
278 self.pending = Some(frame);
279 Ok(())
280 }
281
282 fn receive_frame(&mut self) -> Result<Frame> {
283 match self.pending.take() {
284 Some(frame) => Ok(Frame::Audio(frame)),
285 None if self.drained => Err(Error::Eof),
286 None => Err(Error::NeedMore),
287 }
288 }
289
290 fn flush(&mut self) -> Result<()> {
291 self.drained = true;
292 Ok(())
293 }
294
295 fn reset(&mut self) {
296 self.pending = None;
297 self.drained = false;
298 }
299}
300
301/// Codec parameters for the stream a cookie describes.
302pub fn codec_parameters(cookie: &MagicCookie) -> CodecParameters {
303 let mut params = CodecParameters::new(CodecId::Alac);
304 params.media = MediaParameters::Audio(AudioParameters {
305 sample_rate: cookie.sample_rate,
306 layout: ChannelLayout::from_count(usize::from(cookie.channels.max(1))),
307 format: Some(cookie.sample_format()),
308 bits_per_sample: Some(u32::from(cookie.bit_depth)),
309 });
310 params
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316
317 /// the oracle's 36-byte `alac` box, a bare 24-byte config and the 28-byte form
318 /// in between all describe the same stream.
319 #[test]
320 fn a_magic_cookie_is_read_in_every_shape_a_container_states_it() {
321 let config: [u8; 24] = [
322 0, 0, 0x10, 0, // frameLength 4096
323 0, 16, // version 0, 16-bit
324 40, 10, 14, // pb, mb, kb
325 2, // channels
326 0, 255, // maxRun
327 0, 0, 0x10, 0, // maxFrameBytes
328 0, 0, 0, 0, // avgBitRate
329 0, 0, 0xAC, 0x44, // 44100
330 ];
331 let bare = MagicCookie::parse(&config).expect("bare config");
332 assert_eq!(bare.frame_length, 4096);
333 assert_eq!(bare.bit_depth, 16);
334 assert_eq!(bare.channels, 2);
335 assert_eq!(bare.sample_rate, 44100);
336 assert_eq!(bare.pb, 40);
337 assert_eq!(bare.mb, 10);
338 assert_eq!(bare.kb, 14);
339
340 let mut boxed = vec![0, 0, 0, 36, b'a', b'l', b'a', b'c', 0, 0, 0, 0];
341 boxed.extend_from_slice(&config);
342 assert_eq!(MagicCookie::parse(&boxed).expect("boxed"), bare);
343
344 let mut versioned = vec![0, 0, 0, 0];
345 versioned.extend_from_slice(&config);
346 assert_eq!(MagicCookie::parse(&versioned).expect("versioned"), bare);
347
348 // A refusal that names what it refused, rather than decoding noise.
349 assert!(MagicCookie::parse(&config[..12]).is_err());
350 }
351
352 /// The layout map is a permutation for every width, which is the property
353 /// that keeps a channel from being dropped or doubled on the way out.
354 #[test]
355 fn film_order_is_a_permutation_at_every_width() {
356 for channels in 1..=8usize {
357 let map = film_order(channels);
358 let mut seen: Vec<usize> = map[..channels].to_vec();
359 seen.sort_unstable();
360 seen.dedup();
361 assert_eq!(seen.len(), channels, "{channels} channels");
362 assert!(seen.iter().all(|&c| c < channels), "{channels} channels");
363 }
364 // 5.1: the stream's centre channel is coded first and lands third.
365 assert_eq!(film_order(6), &[1, 2, 0, 5, 3, 4]);
366 }
367}