forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiBd08a7f7Tahinli3 months ago776 commits

encode.rs419 lines, 17.4 KiBHistoryRawDownload
1//! A stereo, lossless TrueHD encoder.
2//!
3//! **Scope (r1)**: 44.1/48 kHz family stereo only, one substream, one
4//! restart header per access unit (so no cross-AU predictor/parameter
5//! state), no matrixing (0 primitive matrices — the stereo pair is written
6//! as two independent, uncorrelated channels) and no FIR/IIR prediction
7//! (filter order 0 on both channels): every sample is written raw, as a
8//! 24-bit offset-binary residual (`codebook = 0`, `huff_lsbs = 24`,
9//! `quant_step = 0`), which [`crate::decode::Core::read_block`] reconstructs
10//! back to the exact sample with no predictor and no quantization. This
11//! trades compression for the shortest bitstream that is still conformant:
12//! every field this build's own decoder does not need to see change is left
13//! at the restart header's own reset default (`Substream::new()`), so the
14//! encoder only ever sets `params_present`/`restart_present`, block size,
15//! and the per-channel codebook/`huff_lsbs` pair.
16//!
17//! **Restart header self-check**: the lossless-check byte a restart header
18//! after the first carries is verified by the decoder against the samples
19//! output by the *previous* restart interval ([`decode::Core::output`]'s
20//! `lossless_check_data` fold); since every access unit here is its own
21//! restart interval, this encoder folds each AU's own samples the same way
22//! and carries that byte into the next AU's restart header.
23
24use std::collections::VecDeque;
25
26use ec_core::bitio::BitWriter;
27use ec_core::error::{Error, Result};
28use ec_core::frame::{ChannelLayout, Frame, SampleFormat};
29use ec_core::packet::Packet;
30use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Encoder, MediaParameters};
31
32use crate::decode::restart_checksum;
33use crate::sync::MAJOR_SYNC_TRUEHD;
34
35/// `0x31EA >> 1`: the restart header's 13-bit sync field, common to both
36/// noise types (the 14th bit picks the type).
37const RESTART_SYNC13: u32 = 0x31EA >> 1;
38/// Offset-binary bias for a 24-bit residual with no predictor and no
39/// quantization: `sample + 2^23`, matching
40/// [`crate::decode::Substream::recompute_sign_offset`] at `codebook = 0`,
41/// `huff_lsbs = 24`, `quant_step = 0`.
42const SAMPLE_BIAS_24: i64 = 1 << 23;
43
44/// XOR-fold a 32-bit word to 8 bits (same fold [`decode::Core::output`]
45/// uses for the lossless-check byte).
46fn xor_32_to_8(v: u32) -> u8 {
47 (v ^ (v >> 8) ^ (v >> 16) ^ (v >> 24)) as u8
48}
49
50/// The major sync's own CRC-16 (poly `0x002D`, MSB-first table form,
51/// matching ffmpeg's `av_crc_init(..., le=0, bits=16, poly=0x2D, ...)`):
52/// this crate's own decoder does not validate it (see `sync.rs`'s module
53/// docs — no public description of its generator was available to check
54/// against), but a foreign decoder (ffmpeg's `mlp_parse.c`) does, so a
55/// bitstream meant to round-trip through one needs a correct value.
56fn mlp_crc16_table() -> [u32; 256] {
57 let mut table = [0u32; 256];
58 for (i, entry) in table.iter_mut().enumerate() {
59 let mut c = (i as i32) << 24;
60 for _ in 0..8 {
61 let overflow = c >> 31;
62 c = (c << 1) ^ ((0x002D_i32 << 16) & overflow);
63 }
64 *entry = (c as u32).swap_bytes();
65 }
66 table
67}
68
69/// The major sync's checksum field (bytes 26..28, little-endian): a CRC-16
70/// over `major_sync[0..24]`, XORed with the little-endian word at
71/// `major_sync[24..26]`.
72fn major_sync_checksum(major_sync: &[u8; 28]) -> u16 {
73 let table = mlp_crc16_table();
74 let mut crc: u32 = 0;
75 for &b in &major_sync[..24] {
76 crc = table[usize::from((crc as u8) ^ b)] ^ (crc >> 8);
77 }
78 (crc as u16) ^ u16::from_le_bytes([major_sync[24], major_sync[25]])
79}
80
81/// A stereo TrueHD encoder. See the module docs for scope.
82#[derive(Debug)]
83pub struct TrueHdEncoder {
84 params: CodecParameters,
85 sample_rate: u32,
86 rate_code: u8,
87 /// Samples per channel a full access unit carries (`40 << (rate_code &
88 /// 7)`); the last, partial access unit may carry fewer.
89 access_unit_size: usize,
90 /// Interleaved stereo samples awaiting an access unit, true PCM range
91 /// (matches [`crate::decode::TrueHdDecoder`]'s own S32 left-justified
92 /// output once shifted right by 8).
93 pending: Vec<i32>,
94 packets: VecDeque<Vec<u8>>,
95 /// Lossless-check byte for the *next* access unit's restart header,
96 /// folded from the access unit just written; `0` (unchecked by the
97 /// decoder) before the first one.
98 next_check: u8,
99 eof: bool,
100}
101
102impl TrueHdEncoder {
103 /// An encoder for one 44.1/48 kHz-family stereo stream.
104 pub fn new(sample_rate: u32) -> Result<TrueHdEncoder> {
105 let (rate_code, access_unit_size) = match sample_rate {
106 48_000 => (0u8, 40usize),
107 96_000 => (1u8, 80usize),
108 192_000 => (2u8, 160usize),
109 44_100 => (8u8, 40usize),
110 88_200 => (9u8, 80usize),
111 176_400 => (10u8, 160usize),
112 other => {
113 return Err(Error::unsupported(
114 format!("TrueHD encoding at {other} Hz"),
115 "only the 44.1/48 kHz families are implemented",
116 ));
117 }
118 };
119 let mut params = CodecParameters::new(CodecId::TrueHd);
120 params.media = MediaParameters::Audio(AudioParameters {
121 sample_rate,
122 layout: ChannelLayout::Stereo,
123 format: Some(SampleFormat::S32),
124 bits_per_sample: None,
125 });
126 Ok(TrueHdEncoder {
127 params,
128 sample_rate,
129 rate_code,
130 access_unit_size,
131 pending: Vec::new(),
132 packets: VecDeque::new(),
133 next_check: 0,
134 eof: false,
135 })
136 }
137
138 /// Encodes one access unit from `samples` (interleaved stereo, `<=
139 /// access_unit_size` per channel — a shorter slice writes a shorter,
140 /// still fully self-contained, access unit).
141 fn encode_access_unit(&mut self, samples: &[i32]) -> Vec<u8> {
142 let n = samples.len() / 2;
143 debug_assert!(n <= self.access_unit_size);
144
145 let mut seg = BitWriter::new();
146 seg.write_bit(true); // params_present
147 seg.write_bit(true); // restart_present
148
149 seg.write_bits(RESTART_SYNC13, 13);
150 seg.write_bit(true); // noise_type (0x31EB); unused, no matrices read it
151 seg.write_bits(0, 16); // output_timing, uninterpreted by the decoder
152 seg.write_bits(0, 4); // min_channel
153 seg.write_bits(1, 4); // max_channel
154 seg.write_bits(1, 4); // max_matrix_channel
155 seg.write_bits(0, 4); // noise_shift
156 seg.write_bits(0, 23); // noisegen_seed
157 seg.write_bits(0, 19); // reserved
158 seg.write_bit(false); // data_check_present
159 seg.write_bits(u32::from(self.next_check), 8); // lossless_check
160 seg.write_bits(0, 16); // reserved
161 seg.write_bits(0, 6); // ch_assign: matrix channel 0 -> output slot 0
162 seg.write_bits(1, 6); // ch_assign: matrix channel 1 -> output slot 1
163 let bit_size = seg.bit_len() - 2; // restart_checksum's own convention
164 let crc = restart_checksum(seg.as_bytes(), bit_size);
165 seg.write_bits(u32::from(crc), 8);
166
167 seg.write_bit(false); // presence-flags gate: keep the restart's 0xFF default
168 seg.write_bit(true); // blocksize gate
169 seg.write_bits(n as u32, 9);
170 seg.write_bit(false); // matrix gate: keep 0 matrices
171 seg.write_bit(false); // output-shift gate: keep shift 0
172 seg.write_bit(false); // quant-step gate: keep step 0
173 for _ch in 0..2 {
174 seg.write_bit(true); // per-channel gate
175 seg.write_bit(false); // FIR gate: keep order 0
176 seg.write_bit(false); // IIR gate: keep order 0
177 seg.write_bit(false); // huff_offset gate: keep 0
178 seg.write_bits(0, 2); // codebook 0: raw, no Huffman code
179 seg.write_bits(24, 5); // huff_lsbs: full 24-bit raw residual
180 }
181
182 for &sample in samples {
183 let raw = ((i64::from(sample) + SAMPLE_BIAS_24) as u32) & 0x00FF_FFFF;
184 seg.write_bits(raw, 24);
185 }
186
187 seg.write_bit(true); // end_of_segment
188 seg.align_to_byte();
189 if seg.bit_len() % 16 != 0 {
190 seg.write_bits(0, 8);
191 }
192 let seg_bytes = seg.into_bytes();
193
194 // Fold this AU's own samples the way `decode::Core::output` does,
195 // for the *next* AU's restart header.
196 let mut fold = 0u32;
197 for (i, &sample) in samples.iter().enumerate() {
198 fold ^= ((sample as u32) & 0x00FF_FFFF) << (i % 2);
199 }
200 self.next_check = xor_32_to_8(fold);
201
202 // A foreign decoder (ffmpeg's mlp_parse.c) reads more of the major
203 // sync than this crate's own decoder does: the two 13/5-bit
204 // "channel arrangement" fields (`ch_arr`/`ch_arr2`, both set to a
205 // stereo-only chanmap of 1 so `mlpdec.c` reports AV_CH_LAYOUT_STEREO
206 // and `group1_bits == 24` so it decodes at S32) and `num_substreams`
207 // (4 bits, at byte 16's top nibble) — 1, matching our own single-
208 // substream directory.
209 let mut major_sync = [0u8; 28];
210 major_sync[0..4].copy_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes());
211 major_sync[4] = self.rate_code << 4; // low nibble ignored by both decoders
212 major_sync[5] = 0x00;
213 major_sync[6] = 0x80; // ch_arr low bit (=1) + ch_arr2 top 5 bits (0)
214 major_sync[7] = 0x01; // ch_arr2 low 8 bits (=1)
215 major_sync[16] = 0x10; // num_substreams = 1
216 let checksum = major_sync_checksum(&major_sync);
217 major_sync[26..28].copy_from_slice(&checksum.to_le_bytes());
218 let dir_word = (seg_bytes.len() as u16 / 2) & 0x0FFF; // 1 substream, no extra word
219
220 let total_len = 4 + major_sync.len() + 2 + seg_bytes.len();
221 let len_words = (total_len as u16 / 2) & 0x0FFF;
222 let dir_bytes = dir_word.to_be_bytes();
223 // Not "unused" after all: a foreign decoder (ffmpeg's mlpdec.c,
224 // `ff_mlp_calculate_parity`) folds the AU header's 4 bytes against
225 // the substream directory's bytes and rejects the AU unless the
226 // result's two nibbles are bitwise complements. This crate's own
227 // decoder never checks it (`sync.rs`'s docs), so the nibble is free
228 // to pick; find the one value (of 16) that satisfies the fold.
229 let check_nibble = (0u8..16)
230 .find(|&cn| {
231 let b0 = (cn << 4) | ((len_words >> 8) as u8 & 0x0F);
232 let b1 = (len_words & 0xFF) as u8;
233 let p = b0 ^ b1 ^ dir_bytes[0] ^ dir_bytes[1];
234 ((p >> 4) ^ p) & 0xF == 0xF
235 })
236 .expect("one of the 16 check-nibble values always satisfies the fold");
237 let length_word = (u16::from(check_nibble) << 12) | len_words;
238
239 let mut au = Vec::with_capacity(total_len);
240 au.extend_from_slice(&length_word.to_be_bytes());
241 au.extend_from_slice(&0u16.to_be_bytes()); // input_timing
242 au.extend_from_slice(&major_sync);
243 au.extend_from_slice(&dir_bytes);
244 au.extend_from_slice(&seg_bytes);
245 au
246 }
247
248 fn drain_full_units(&mut self) {
249 let per_au = self.access_unit_size * 2;
250 while self.pending.len() >= per_au {
251 let samples: Vec<i32> = self.pending.drain(..per_au).collect();
252 let bytes = self.encode_access_unit(&samples);
253 self.packets.push_back(bytes);
254 }
255 }
256}
257
258impl Encoder for TrueHdEncoder {
259 fn codec_parameters(&self) -> &CodecParameters {
260 &self.params
261 }
262
263 fn send_frame(&mut self, frame: &Frame) -> Result<()> {
264 let Frame::Audio(audio) = frame else {
265 return Err(Error::corrupt("video frame pushed into a TrueHD encoder"));
266 };
267 if audio.format != SampleFormat::S32 {
268 return Err(Error::unsupported(
269 format!("{:?} input", audio.format),
270 "this encoder takes S32 (24-bit left-justified) samples",
271 ));
272 }
273 if audio.layout.channel_count() != 2 {
274 return Err(Error::unsupported(
275 format!("{} channel input", audio.layout.channel_count()),
276 "this encoder writes stereo only",
277 ));
278 }
279 if audio.rate != self.sample_rate {
280 return Err(Error::unsupported(
281 format!("{} Hz input", audio.rate),
282 "this encoder was set up for a different sample rate",
283 ));
284 }
285 if audio.planar {
286 for i in 0..audio.samples {
287 for plane in audio.data.iter().take(2) {
288 let at = i * 4;
289 let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]];
290 self.pending.push(i32::from_ne_bytes(w) >> 8);
291 }
292 }
293 } else {
294 for word in audio.data[0].chunks_exact(4).take(audio.samples * 2) {
295 self.pending
296 .push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> 8);
297 }
298 }
299 self.drain_full_units();
300 Ok(())
301 }
302
303 fn receive_packet(&mut self) -> Result<Packet> {
304 match self.packets.pop_front() {
305 Some(data) => Ok(Packet::new(
306 0,
307 ec_core::timebase::TimeBase::new(1, i64::from(self.sample_rate)),
308 data,
309 )),
310 None if self.eof => Err(Error::Eof),
311 None => Err(Error::NeedMore),
312 }
313 }
314
315 fn flush(&mut self) -> Result<()> {
316 if !self.pending.is_empty() {
317 let mut samples = std::mem::take(&mut self.pending);
318 // corner-cut: TrueHD's own block-size field is invalid under 8
319 // samples/channel (crate::decode::read_decoding_params rejects
320 // it); a final partial access unit shorter than that is padded
321 // by repeating its last real sample pair. Ceiling: a caller
322 // wanting the exact original count trims the decoder's output
323 // to it (the container's duration, same as any codec's short
324 // final frame) — upgrade path is a real short-block encoding,
325 // not needed at r1 scope.
326 if samples.len() / 2 < 8 {
327 let last = [
328 *samples.get(samples.len().wrapping_sub(2)).unwrap_or(&0),
329 *samples.last().unwrap_or(&0),
330 ];
331 while samples.len() / 2 < 8 {
332 samples.extend_from_slice(&last);
333 }
334 }
335 let bytes = self.encode_access_unit(&samples);
336 self.packets.push_back(bytes);
337 }
338 self.eof = true;
339 Ok(())
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use crate::sync::TrueHdDecoder;
347 use ec_core::frame::{AudioFrame, Frame as EcFrame};
348 use ec_core::packet::Buf;
349
350 /// A deterministic tone+noise fixture, interleaved stereo S32
351 /// left-justified, `n` samples per channel.
352 fn tone_fixture(n: usize) -> Vec<i32> {
353 let mut v = Vec::with_capacity(n * 2);
354 let mut lcg: u32 = 0x12345;
355 for i in 0..n {
356 let l = ((i as f64 * 0.07).sin() * 4_000_000.0) as i32;
357 lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
358 let r = l.wrapping_add((lcg >> 8) as i32 % 5000 - 2500);
359 v.push(l.clamp(-8_388_608, 8_388_607));
360 v.push(r.clamp(-8_388_608, 8_388_607));
361 }
362 v
363 }
364
365 fn s32_frame(interleaved: &[i32], sample_rate: u32) -> ec_core::frame::AudioFrame {
366 let mut bytes = Vec::with_capacity(interleaved.len() * 4);
367 for &s in interleaved {
368 bytes.extend_from_slice(&(s << 8).to_ne_bytes());
369 }
370 AudioFrame::try_new(
371 SampleFormat::S32,
372 false,
373 ChannelLayout::Stereo,
374 sample_rate,
375 interleaved.len() / 2,
376 vec![Buf::from_vec(bytes)],
377 )
378 .unwrap()
379 }
380
381 /// Round-trip gate 1: encode a multi-access-unit stereo fixture (a
382 /// partial final access unit included), decode every access unit back
383 /// through this crate's own decoder, and check every sample exactly.
384 #[test]
385 fn encoder_round_trips_through_our_own_decoder() {
386 for n in [173usize, 40, 40 * 5 + 7, 1] {
387 let samples = tone_fixture(n);
388 let mut enc = TrueHdEncoder::new(48_000).unwrap();
389 enc.send_frame(&EcFrame::Audio(s32_frame(&samples, 48_000)))
390 .unwrap();
391 enc.flush().unwrap();
392
393 let mut dec = TrueHdDecoder::new();
394 let mut decoded = Vec::new();
395 loop {
396 match enc.receive_packet() {
397 Ok(pkt) => {
398 if let Some(frame) = dec.decode_access_unit(&pkt.data).unwrap() {
399 for word in frame.data[0].chunks_exact(4) {
400 decoded.push(
401 i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> 8,
402 );
403 }
404 }
405 }
406 Err(Error::Eof) => break,
407 Err(e) => panic!("n={n}: {e:?}"),
408 }
409 }
410 decoded.truncate(samples.len());
411 assert_eq!(decoded, samples, "n={n}: sample mismatch");
412 let stats = dec.check_stats();
413 assert_eq!(stats.restart_crc_failures, 0, "n={n}: restart CRC");
414 assert_eq!(stats.lossless_check_failures, 0, "n={n}: lossless check");
415 assert_eq!(stats.parity_failures, 0, "n={n}: parity");
416 assert_eq!(stats.length_mismatches, 0, "n={n}: length mismatch");
417 }
418 }
419}