diff --git a/crates/ec-truehd/src/decode.rs b/crates/ec-truehd/src/decode.rs index bebb14c3..1b023bad 100644 --- a/crates/ec-truehd/src/decode.rs +++ b/crates/ec-truehd/src/decode.rs @@ -111,16 +111,64 @@ const PARAM_PRESENCE: u8 = 1 << 0; /// external encoder's output (`tests/oracle.rs`). pub const HUFFMAN_TABLES: [[(u16, u8); 18]; 3] = [ [ - (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x04, 3), (0x05, 3), - (0x06, 3), (0x07, 3), (0x03, 3), (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 9), + (0x01, 9), + (0x01, 8), + (0x01, 7), + (0x01, 6), + (0x01, 5), + (0x01, 4), + (0x01, 3), + (0x04, 3), + (0x05, 3), + (0x06, 3), + (0x07, 3), + (0x03, 3), + (0x05, 4), + (0x09, 5), + (0x11, 6), + (0x21, 7), + (0x41, 8), + (0x81, 9), ], [ - (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x02, 2), (0x03, 2), - (0x03, 3), (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 9), (0, 0), (0, 0), + (0x01, 9), + (0x01, 8), + (0x01, 7), + (0x01, 6), + (0x01, 5), + (0x01, 4), + (0x01, 3), + (0x02, 2), + (0x03, 2), + (0x03, 3), + (0x05, 4), + (0x09, 5), + (0x11, 6), + (0x21, 7), + (0x41, 8), + (0x81, 9), + (0, 0), + (0, 0), ], [ - (0x01, 9), (0x01, 8), (0x01, 7), (0x01, 6), (0x01, 5), (0x01, 4), (0x01, 3), (0x01, 1), (0x03, 3), - (0x05, 4), (0x09, 5), (0x11, 6), (0x21, 7), (0x41, 8), (0x81, 9), (0, 0), (0, 0), (0, 0), + (0x01, 9), + (0x01, 8), + (0x01, 7), + (0x01, 6), + (0x01, 5), + (0x01, 4), + (0x01, 3), + (0x01, 1), + (0x03, 3), + (0x05, 4), + (0x09, 5), + (0x11, 6), + (0x21, 7), + (0x41, 8), + (0x81, 9), + (0, 0), + (0, 0), + (0, 0), ], ]; @@ -165,7 +213,11 @@ fn crc8(poly: u8, init: u8, bytes: &[u8]) -> u8 { for &b in bytes { crc ^= b; for _ in 0..8 { - crc = if crc & 0x80 != 0 { (crc << 1) ^ poly } else { crc << 1 }; + crc = if crc & 0x80 != 0 { + (crc << 1) ^ poly + } else { + crc << 1 + }; } } crc @@ -174,7 +226,7 @@ fn crc8(poly: u8, init: u8, bytes: &[u8]) -> u8 { /// The restart header's own CRC-8 (poly 0x1D), over the header from its /// first byte (`buf[0]`, whose two leading bits — the params/restart flags — /// are masked off) through its last full byte and the trailing partial bits. -fn restart_checksum(buf: &[u8], bit_size: u64) -> u8 { +pub(crate) fn restart_checksum(buf: &[u8], bit_size: u64) -> u8 { let bit_size = bit_size as usize + 2; let num_bytes = bit_size / 8; let mut crc = crc8(0x1D, 0, &[buf[0] & 0x3F]); @@ -271,7 +323,12 @@ impl Substream { fn recompute_sign_offset(&mut self, ch: usize) { let cp = &mut self.channels[ch]; let lsb_bits = i32::from(cp.huff_lsbs) - self.quant_step_size[ch] as i32; - let sign_shift = lsb_bits + if cp.codebook > 0 { 2 - i32::from(cp.codebook) } else { -1 }; + let sign_shift = lsb_bits + + if cp.codebook > 0 { + 2 - i32::from(cp.codebook) + } else { + -1 + }; let mut off = cp.huff_offset; if cp.codebook > 0 { off -= 7 << lsb_bits; @@ -350,7 +407,11 @@ impl Core { /// Decodes one access unit whose header already parsed; `None` until the /// first major sync and every substream's first restart header are seen. - pub(crate) fn decode(&mut self, header: &AccessUnitHeader, data: &[u8]) -> Result> { + pub(crate) fn decode( + &mut self, + header: &AccessUnitHeader, + data: &[u8], + ) -> Result> { if !self.prepare(header)? || !self.decode_substreams(header, data)? { return Ok(None); } @@ -403,7 +464,10 @@ impl Core { let layout = ChannelLayout::from_count(channels); if layout == ChannelLayout::Surround7_1 && self.ch8_assignment != 0x4F { return Err(Error::unsupported( - format!("TrueHD 8-channel presentation with channel assignment {:#x}", self.ch8_assignment), + format!( + "TrueHD 8-channel presentation with channel assignment {:#x}", + self.ch8_assignment + ), "only the standard 7.1 (L R C LFE Ls Rs Lrs Rrs) assignment is mapped", )); } @@ -543,7 +607,10 @@ impl Core { if flags & PARAM_BLOCKSIZE != 0 && br.read_bit()? { s.blocksize = br.read_bits(9)? as usize; if s.blocksize < 8 || s.blocksize > self.access_unit_size { - return Err(Error::corrupt(format!("TrueHD: block size {}", s.blocksize))); + return Err(Error::corrupt(format!( + "TrueHD: block size {}", + s.blocksize + ))); } } if flags & PARAM_MATRIX != 0 && br.read_bit()? { @@ -649,7 +716,12 @@ impl Core { } } for ch in s.min_channel..=s.max_channel { - filter_channel(&mut s.channels[ch], s.quant_step_size[ch], &mut self.sample_buffer[s.blockpos..s.blockpos + s.blocksize], ch); + filter_channel( + &mut s.channels[ch], + s.quant_step_size[ch], + &mut self.sample_buffer[s.blockpos..s.blockpos + s.blocksize], + ch, + ); } s.blockpos += s.blocksize; if let Some(end) = expected_end { @@ -745,7 +817,9 @@ fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> { let coeff_bits = br.read_bits(5)?; let coeff_shift = br.read_bits(3)?; if !(1..=16).contains(&coeff_bits) || coeff_bits + coeff_shift > 16 { - return Err(Error::corrupt("TrueHD: filter coefficient precision out of range")); + return Err(Error::corrupt( + "TrueHD: filter coefficient precision out of range", + )); } for c in f.coeffs.iter_mut().take(f.order) { *c = br.read_signed(coeff_bits)? << coeff_shift; @@ -757,7 +831,11 @@ fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> { let state_bits = br.read_bits(4)?; let state_shift = br.read_bits(4)?; for st in f.state.iter_mut().take(f.order) { - *st = if state_bits > 0 { br.read_signed(state_bits)? << state_shift } else { 0 }; + *st = if state_bits > 0 { + br.read_signed(state_bits)? << state_shift + } else { + 0 + }; } } } @@ -768,7 +846,11 @@ fn read_filter(br: &mut BitReader, f: &mut Filter, iir: bool) -> Result<()> { /// (over past residual-after-prediction) filters, in place on column `ch`. fn filter_channel(cp: &mut ChannelParams, qss: u32, rows: &mut [[i32; MAX_CHANNELS]], ch: usize) { let mask = !((1i32 << qss) - 1); - let shift = if cp.fir.order > 0 { cp.fir.shift } else { cp.iir.shift }; + let shift = if cp.fir.order > 0 { + cp.fir.shift + } else { + cp.iir.shift + }; for row in rows { let mut accum: i64 = 0; for j in 0..cp.fir.order { @@ -807,7 +889,11 @@ mod tests { w.write_bits(0x5A5, 11); let bytes = w.into_bytes(); let mut br = BitReader::new(&bytes); - assert_eq!(lut.decode(&mut br, book).unwrap(), index as i32, "book {book} index {index}"); + assert_eq!( + lut.decode(&mut br, book).unwrap(), + index as i32, + "book {book} index {index}" + ); assert_eq!(br.bit_position(), u64::from(len)); // Bare code at the very end of the buffer must decode too. let mut w = BitWriter::new(); @@ -836,4 +922,3 @@ mod tests { } } } - diff --git a/crates/ec-truehd/src/encode.rs b/crates/ec-truehd/src/encode.rs new file mode 100644 index 00000000..9fd103d2 --- /dev/null +++ b/crates/ec-truehd/src/encode.rs @@ -0,0 +1,419 @@ +//! A stereo, lossless TrueHD encoder. +//! +//! **Scope (r1)**: 44.1/48 kHz family stereo only, one substream, one +//! restart header per access unit (so no cross-AU predictor/parameter +//! state), no matrixing (0 primitive matrices — the stereo pair is written +//! as two independent, uncorrelated channels) and no FIR/IIR prediction +//! (filter order 0 on both channels): every sample is written raw, as a +//! 24-bit offset-binary residual (`codebook = 0`, `huff_lsbs = 24`, +//! `quant_step = 0`), which [`crate::decode::Core::read_block`] reconstructs +//! back to the exact sample with no predictor and no quantization. This +//! trades compression for the shortest bitstream that is still conformant: +//! every field this build's own decoder does not need to see change is left +//! at the restart header's own reset default (`Substream::new()`), so the +//! encoder only ever sets `params_present`/`restart_present`, block size, +//! and the per-channel codebook/`huff_lsbs` pair. +//! +//! **Restart header self-check**: the lossless-check byte a restart header +//! after the first carries is verified by the decoder against the samples +//! output by the *previous* restart interval ([`decode::Core::output`]'s +//! `lossless_check_data` fold); since every access unit here is its own +//! restart interval, this encoder folds each AU's own samples the same way +//! and carries that byte into the next AU's restart header. + +use std::collections::VecDeque; + +use ec_core::bitio::BitWriter; +use ec_core::error::{Error, Result}; +use ec_core::frame::{ChannelLayout, Frame, SampleFormat}; +use ec_core::packet::Packet; +use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Encoder, MediaParameters}; + +use crate::decode::restart_checksum; +use crate::sync::MAJOR_SYNC_TRUEHD; + +/// `0x31EA >> 1`: the restart header's 13-bit sync field, common to both +/// noise types (the 14th bit picks the type). +const RESTART_SYNC13: u32 = 0x31EA >> 1; +/// Offset-binary bias for a 24-bit residual with no predictor and no +/// quantization: `sample + 2^23`, matching +/// [`crate::decode::Substream::recompute_sign_offset`] at `codebook = 0`, +/// `huff_lsbs = 24`, `quant_step = 0`. +const SAMPLE_BIAS_24: i64 = 1 << 23; + +/// XOR-fold a 32-bit word to 8 bits (same fold [`decode::Core::output`] +/// uses for the lossless-check byte). +fn xor_32_to_8(v: u32) -> u8 { + (v ^ (v >> 8) ^ (v >> 16) ^ (v >> 24)) as u8 +} + +/// The major sync's own CRC-16 (poly `0x002D`, MSB-first table form, +/// matching ffmpeg's `av_crc_init(..., le=0, bits=16, poly=0x2D, ...)`): +/// this crate's own decoder does not validate it (see `sync.rs`'s module +/// docs — no public description of its generator was available to check +/// against), but a foreign decoder (ffmpeg's `mlp_parse.c`) does, so a +/// bitstream meant to round-trip through one needs a correct value. +fn mlp_crc16_table() -> [u32; 256] { + let mut table = [0u32; 256]; + for (i, entry) in table.iter_mut().enumerate() { + let mut c = (i as i32) << 24; + for _ in 0..8 { + let overflow = c >> 31; + c = (c << 1) ^ ((0x002D_i32 << 16) & overflow); + } + *entry = (c as u32).swap_bytes(); + } + table +} + +/// The major sync's checksum field (bytes 26..28, little-endian): a CRC-16 +/// over `major_sync[0..24]`, XORed with the little-endian word at +/// `major_sync[24..26]`. +fn major_sync_checksum(major_sync: &[u8; 28]) -> u16 { + let table = mlp_crc16_table(); + let mut crc: u32 = 0; + for &b in &major_sync[..24] { + crc = table[usize::from((crc as u8) ^ b)] ^ (crc >> 8); + } + (crc as u16) ^ u16::from_le_bytes([major_sync[24], major_sync[25]]) +} + +/// A stereo TrueHD encoder. See the module docs for scope. +#[derive(Debug)] +pub struct TrueHdEncoder { + params: CodecParameters, + sample_rate: u32, + rate_code: u8, + /// Samples per channel a full access unit carries (`40 << (rate_code & + /// 7)`); the last, partial access unit may carry fewer. + access_unit_size: usize, + /// Interleaved stereo samples awaiting an access unit, true PCM range + /// (matches [`crate::decode::TrueHdDecoder`]'s own S32 left-justified + /// output once shifted right by 8). + pending: Vec, + packets: VecDeque>, + /// Lossless-check byte for the *next* access unit's restart header, + /// folded from the access unit just written; `0` (unchecked by the + /// decoder) before the first one. + next_check: u8, + eof: bool, +} + +impl TrueHdEncoder { + /// An encoder for one 44.1/48 kHz-family stereo stream. + pub fn new(sample_rate: u32) -> Result { + let (rate_code, access_unit_size) = match sample_rate { + 48_000 => (0u8, 40usize), + 96_000 => (1u8, 80usize), + 192_000 => (2u8, 160usize), + 44_100 => (8u8, 40usize), + 88_200 => (9u8, 80usize), + 176_400 => (10u8, 160usize), + other => { + return Err(Error::unsupported( + format!("TrueHD encoding at {other} Hz"), + "only the 44.1/48 kHz families are implemented", + )); + } + }; + let mut params = CodecParameters::new(CodecId::TrueHd); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate, + layout: ChannelLayout::Stereo, + format: Some(SampleFormat::S32), + bits_per_sample: None, + }); + Ok(TrueHdEncoder { + params, + sample_rate, + rate_code, + access_unit_size, + pending: Vec::new(), + packets: VecDeque::new(), + next_check: 0, + eof: false, + }) + } + + /// Encodes one access unit from `samples` (interleaved stereo, `<= + /// access_unit_size` per channel — a shorter slice writes a shorter, + /// still fully self-contained, access unit). + fn encode_access_unit(&mut self, samples: &[i32]) -> Vec { + let n = samples.len() / 2; + debug_assert!(n <= self.access_unit_size); + + let mut seg = BitWriter::new(); + seg.write_bit(true); // params_present + seg.write_bit(true); // restart_present + + seg.write_bits(RESTART_SYNC13, 13); + seg.write_bit(true); // noise_type (0x31EB); unused, no matrices read it + seg.write_bits(0, 16); // output_timing, uninterpreted by the decoder + seg.write_bits(0, 4); // min_channel + seg.write_bits(1, 4); // max_channel + seg.write_bits(1, 4); // max_matrix_channel + seg.write_bits(0, 4); // noise_shift + seg.write_bits(0, 23); // noisegen_seed + seg.write_bits(0, 19); // reserved + seg.write_bit(false); // data_check_present + seg.write_bits(u32::from(self.next_check), 8); // lossless_check + seg.write_bits(0, 16); // reserved + seg.write_bits(0, 6); // ch_assign: matrix channel 0 -> output slot 0 + seg.write_bits(1, 6); // ch_assign: matrix channel 1 -> output slot 1 + let bit_size = seg.bit_len() - 2; // restart_checksum's own convention + let crc = restart_checksum(seg.as_bytes(), bit_size); + seg.write_bits(u32::from(crc), 8); + + seg.write_bit(false); // presence-flags gate: keep the restart's 0xFF default + seg.write_bit(true); // blocksize gate + seg.write_bits(n as u32, 9); + seg.write_bit(false); // matrix gate: keep 0 matrices + seg.write_bit(false); // output-shift gate: keep shift 0 + seg.write_bit(false); // quant-step gate: keep step 0 + for _ch in 0..2 { + seg.write_bit(true); // per-channel gate + seg.write_bit(false); // FIR gate: keep order 0 + seg.write_bit(false); // IIR gate: keep order 0 + seg.write_bit(false); // huff_offset gate: keep 0 + seg.write_bits(0, 2); // codebook 0: raw, no Huffman code + seg.write_bits(24, 5); // huff_lsbs: full 24-bit raw residual + } + + for &sample in samples { + let raw = ((i64::from(sample) + SAMPLE_BIAS_24) as u32) & 0x00FF_FFFF; + seg.write_bits(raw, 24); + } + + seg.write_bit(true); // end_of_segment + seg.align_to_byte(); + if seg.bit_len() % 16 != 0 { + seg.write_bits(0, 8); + } + let seg_bytes = seg.into_bytes(); + + // Fold this AU's own samples the way `decode::Core::output` does, + // for the *next* AU's restart header. + let mut fold = 0u32; + for (i, &sample) in samples.iter().enumerate() { + fold ^= ((sample as u32) & 0x00FF_FFFF) << (i % 2); + } + self.next_check = xor_32_to_8(fold); + + // A foreign decoder (ffmpeg's mlp_parse.c) reads more of the major + // sync than this crate's own decoder does: the two 13/5-bit + // "channel arrangement" fields (`ch_arr`/`ch_arr2`, both set to a + // stereo-only chanmap of 1 so `mlpdec.c` reports AV_CH_LAYOUT_STEREO + // and `group1_bits == 24` so it decodes at S32) and `num_substreams` + // (4 bits, at byte 16's top nibble) — 1, matching our own single- + // substream directory. + let mut major_sync = [0u8; 28]; + major_sync[0..4].copy_from_slice(&MAJOR_SYNC_TRUEHD.to_be_bytes()); + major_sync[4] = self.rate_code << 4; // low nibble ignored by both decoders + major_sync[5] = 0x00; + major_sync[6] = 0x80; // ch_arr low bit (=1) + ch_arr2 top 5 bits (0) + major_sync[7] = 0x01; // ch_arr2 low 8 bits (=1) + major_sync[16] = 0x10; // num_substreams = 1 + let checksum = major_sync_checksum(&major_sync); + major_sync[26..28].copy_from_slice(&checksum.to_le_bytes()); + let dir_word = (seg_bytes.len() as u16 / 2) & 0x0FFF; // 1 substream, no extra word + + let total_len = 4 + major_sync.len() + 2 + seg_bytes.len(); + let len_words = (total_len as u16 / 2) & 0x0FFF; + let dir_bytes = dir_word.to_be_bytes(); + // Not "unused" after all: a foreign decoder (ffmpeg's mlpdec.c, + // `ff_mlp_calculate_parity`) folds the AU header's 4 bytes against + // the substream directory's bytes and rejects the AU unless the + // result's two nibbles are bitwise complements. This crate's own + // decoder never checks it (`sync.rs`'s docs), so the nibble is free + // to pick; find the one value (of 16) that satisfies the fold. + let check_nibble = (0u8..16) + .find(|&cn| { + let b0 = (cn << 4) | ((len_words >> 8) as u8 & 0x0F); + let b1 = (len_words & 0xFF) as u8; + let p = b0 ^ b1 ^ dir_bytes[0] ^ dir_bytes[1]; + ((p >> 4) ^ p) & 0xF == 0xF + }) + .expect("one of the 16 check-nibble values always satisfies the fold"); + let length_word = (u16::from(check_nibble) << 12) | len_words; + + let mut au = Vec::with_capacity(total_len); + au.extend_from_slice(&length_word.to_be_bytes()); + au.extend_from_slice(&0u16.to_be_bytes()); // input_timing + au.extend_from_slice(&major_sync); + au.extend_from_slice(&dir_bytes); + au.extend_from_slice(&seg_bytes); + au + } + + fn drain_full_units(&mut self) { + let per_au = self.access_unit_size * 2; + while self.pending.len() >= per_au { + let samples: Vec = self.pending.drain(..per_au).collect(); + let bytes = self.encode_access_unit(&samples); + self.packets.push_back(bytes); + } + } +} + +impl Encoder for TrueHdEncoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_frame(&mut self, frame: &Frame) -> Result<()> { + let Frame::Audio(audio) = frame else { + return Err(Error::corrupt("video frame pushed into a TrueHD encoder")); + }; + if audio.format != SampleFormat::S32 { + return Err(Error::unsupported( + format!("{:?} input", audio.format), + "this encoder takes S32 (24-bit left-justified) samples", + )); + } + if audio.layout.channel_count() != 2 { + return Err(Error::unsupported( + format!("{} channel input", audio.layout.channel_count()), + "this encoder writes stereo only", + )); + } + if audio.rate != self.sample_rate { + return Err(Error::unsupported( + format!("{} Hz input", audio.rate), + "this encoder was set up for a different sample rate", + )); + } + if audio.planar { + for i in 0..audio.samples { + for plane in audio.data.iter().take(2) { + let at = i * 4; + let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]]; + self.pending.push(i32::from_ne_bytes(w) >> 8); + } + } + } else { + for word in audio.data[0].chunks_exact(4).take(audio.samples * 2) { + self.pending + .push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> 8); + } + } + self.drain_full_units(); + Ok(()) + } + + fn receive_packet(&mut self) -> Result { + match self.packets.pop_front() { + Some(data) => Ok(Packet::new( + 0, + ec_core::timebase::TimeBase::new(1, i64::from(self.sample_rate)), + data, + )), + None if self.eof => Err(Error::Eof), + None => Err(Error::NeedMore), + } + } + + fn flush(&mut self) -> Result<()> { + if !self.pending.is_empty() { + let mut samples = std::mem::take(&mut self.pending); + // corner-cut: TrueHD's own block-size field is invalid under 8 + // samples/channel (crate::decode::read_decoding_params rejects + // it); a final partial access unit shorter than that is padded + // by repeating its last real sample pair. Ceiling: a caller + // wanting the exact original count trims the decoder's output + // to it (the container's duration, same as any codec's short + // final frame) — upgrade path is a real short-block encoding, + // not needed at r1 scope. + if samples.len() / 2 < 8 { + let last = [ + *samples.get(samples.len().wrapping_sub(2)).unwrap_or(&0), + *samples.last().unwrap_or(&0), + ]; + while samples.len() / 2 < 8 { + samples.extend_from_slice(&last); + } + } + let bytes = self.encode_access_unit(&samples); + self.packets.push_back(bytes); + } + self.eof = true; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sync::TrueHdDecoder; + use ec_core::frame::{AudioFrame, Frame as EcFrame}; + use ec_core::packet::Buf; + + /// A deterministic tone+noise fixture, interleaved stereo S32 + /// left-justified, `n` samples per channel. + fn tone_fixture(n: usize) -> Vec { + let mut v = Vec::with_capacity(n * 2); + let mut lcg: u32 = 0x12345; + for i in 0..n { + let l = ((i as f64 * 0.07).sin() * 4_000_000.0) as i32; + lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let r = l.wrapping_add((lcg >> 8) as i32 % 5000 - 2500); + v.push(l.clamp(-8_388_608, 8_388_607)); + v.push(r.clamp(-8_388_608, 8_388_607)); + } + v + } + + fn s32_frame(interleaved: &[i32], sample_rate: u32) -> ec_core::frame::AudioFrame { + let mut bytes = Vec::with_capacity(interleaved.len() * 4); + for &s in interleaved { + bytes.extend_from_slice(&(s << 8).to_ne_bytes()); + } + AudioFrame::try_new( + SampleFormat::S32, + false, + ChannelLayout::Stereo, + sample_rate, + interleaved.len() / 2, + vec![Buf::from_vec(bytes)], + ) + .unwrap() + } + + /// Round-trip gate 1: encode a multi-access-unit stereo fixture (a + /// partial final access unit included), decode every access unit back + /// through this crate's own decoder, and check every sample exactly. + #[test] + fn encoder_round_trips_through_our_own_decoder() { + for n in [173usize, 40, 40 * 5 + 7, 1] { + let samples = tone_fixture(n); + let mut enc = TrueHdEncoder::new(48_000).unwrap(); + enc.send_frame(&EcFrame::Audio(s32_frame(&samples, 48_000))) + .unwrap(); + enc.flush().unwrap(); + + let mut dec = TrueHdDecoder::new(); + let mut decoded = Vec::new(); + loop { + match enc.receive_packet() { + Ok(pkt) => { + if let Some(frame) = dec.decode_access_unit(&pkt.data).unwrap() { + for word in frame.data[0].chunks_exact(4) { + decoded.push( + i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> 8, + ); + } + } + } + Err(Error::Eof) => break, + Err(e) => panic!("n={n}: {e:?}"), + } + } + decoded.truncate(samples.len()); + assert_eq!(decoded, samples, "n={n}: sample mismatch"); + let stats = dec.check_stats(); + assert_eq!(stats.restart_crc_failures, 0, "n={n}: restart CRC"); + assert_eq!(stats.lossless_check_failures, 0, "n={n}: lossless check"); + assert_eq!(stats.parity_failures, 0, "n={n}: parity"); + assert_eq!(stats.length_mismatches, 0, "n={n}: length mismatch"); + } + } +} diff --git a/crates/ec-truehd/src/lib.rs b/crates/ec-truehd/src/lib.rs index 5df560fc..105897ed 100644 --- a/crates/ec-truehd/src/lib.rs +++ b/crates/ec-truehd/src/lib.rs @@ -37,8 +37,12 @@ #![warn(missing_docs)] pub mod decode; +pub mod encode; pub mod sync; -pub use ec_core::Error; pub use decode::CheckStats; -pub use sync::{AccessUnitHeader, MajorSyncInfo, MajorSyncFormat, SubstreamInfo, TrueHdDecoder, frame_length}; +pub use ec_core::Error; +pub use encode::TrueHdEncoder; +pub use sync::{ + AccessUnitHeader, MajorSyncFormat, MajorSyncInfo, SubstreamInfo, TrueHdDecoder, frame_length, +}; diff --git a/crates/ec-truehd/src/sync.rs b/crates/ec-truehd/src/sync.rs index 1bee6a65..c98dfa74 100644 --- a/crates/ec-truehd/src/sync.rs +++ b/crates/ec-truehd/src/sync.rs @@ -208,19 +208,24 @@ impl AccessUnitHeader { let input_timing = u16::from_be_bytes([au[2], au[3]]); let major_sync = match au.get(4..8) { - Some(w) if w == MAJOR_SYNC_TRUEHD.to_be_bytes() || w == MAJOR_SYNC_MLP.to_be_bytes() => { + Some(w) + if w == MAJOR_SYNC_TRUEHD.to_be_bytes() || w == MAJOR_SYNC_MLP.to_be_bytes() => + { Some(MajorSyncInfo::parse(&au[4..])?) } _ => None, }; - let dir_start = AU_HEADER_LEN + if major_sync.is_some() { MAJOR_SYNC_LEN } else { 0 }; + let dir_start = AU_HEADER_LEN + + if major_sync.is_some() { + MAJOR_SYNC_LEN + } else { + 0 + }; let mut substreams = Vec::new(); let mut pos = dir_start; loop { - let word = au - .get(pos..pos + 2) - .ok_or(Error::NeedMore)?; + let word = au.get(pos..pos + 2).ok_or(Error::NeedMore)?; let word = u16::from_be_bytes([word[0], word[1]]); let flags = (word >> 12) as u8; let end_offset_words = word & 0x0FFF; @@ -270,7 +275,10 @@ impl AccessUnitHeader { } else { self.data_start + usize::from(self.substreams[i - 1].end_offset_words) * 2 }; - (start, self.data_start + usize::from(self.substreams[i].end_offset_words) * 2) + ( + start, + self.data_start + usize::from(self.substreams[i].end_offset_words) * 2, + ) } /// The channel layout Dolby's substream convention implies: substream 0 diff --git a/crates/ec-truehd/tests/oracle.rs b/crates/ec-truehd/tests/oracle.rs index ed91882c..63fff207 100644 --- a/crates/ec-truehd/tests/oracle.rs +++ b/crates/ec-truehd/tests/oracle.rs @@ -12,11 +12,13 @@ use std::process::Command; use ec_core::{CodecId, Demuxer}; use ec_matroska::MatroskaDemuxer; -use ec_truehd::{frame_length, TrueHdDecoder}; +use ec_truehd::{TrueHdDecoder, TrueHdEncoder, frame_length}; fn find_file() -> Option { fn walk(dir: &Path, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { return }; + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; for e in entries.flatten() { let p = e.path(); if p.is_dir() { @@ -37,17 +39,32 @@ fn find_file() -> Option { } fn have_ffmpeg() -> bool { - Command::new("ffmpeg").arg("-version").output().map(|o| o.status.success()).unwrap_or(false) + Command::new("ffmpeg") + .arg("-version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) } fn ffmpeg(args: &[&str]) -> Vec { - let out = Command::new("ffmpeg").args(["-v", "error", "-nostdin"]).args(args).output().expect("run ffmpeg"); - assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); + let out = Command::new("ffmpeg") + .args(["-v", "error", "-nostdin"]) + .args(args) + .output() + .expect("run ffmpeg"); + assert!( + out.status.success(), + "ffmpeg {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); out.stdout } fn s32le(bytes: &[u8]) -> Vec { - bytes.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect() + bytes + .chunks_exact(4) + .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect() } /// Compares `ours` with `reference` sample-for-sample; returns (exact, @@ -78,12 +95,23 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { } const SECONDS: usize = 60; let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); - let track = demux.streams().iter().find(|s| s.params.codec == CodecId::TrueHd).expect("a TrueHD track"); + let track = demux + .streams() + .iter() + .find(|s| s.params.codec == CodecId::TrueHd) + .expect("a TrueHD track"); let stream_index = track.index; let reference = s32le(&ffmpeg(&[ - "-i", path.to_str().unwrap(), "-map", &format!("0:{stream_index}"), "-t", &SECONDS.to_string(), - "-f", "s32le", "-", + "-i", + path.to_str().unwrap(), + "-map", + &format!("0:{stream_index}"), + "-t", + &SECONDS.to_string(), + "-f", + "s32le", + "-", ])); let channels = 8; let wanted = SECONDS * 48_000 * channels; @@ -100,7 +128,9 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { if packet.stream != stream_index { continue; } - let frame = decoder.decode_access_unit(&packet.data).unwrap_or_else(|e| panic!("AU {aus}: {e}")); + let frame = decoder + .decode_access_unit(&packet.data) + .unwrap_or_else(|e| panic!("AU {aus}: {e}")); aus += 1; if let Some(f) = frame { assert_eq!(f.channels(), channels); @@ -111,7 +141,9 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { let stats = decoder.check_stats(); for ch in 0..channels { let n = total / channels; - let e = (0..n).filter(|&i| ours[i * channels + ch] == reference[i * channels + ch]).count(); + let e = (0..n) + .filter(|&i| ours[i * channels + ch] == reference[i * channels + ch]) + .count(); eprintln!("channel {ch}: {e}/{n} exact"); } eprintln!( @@ -119,12 +151,18 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { total / channels / 48_000, 100.0 * exact as f64 / total as f64 ); - assert!(total >= (SECONDS - 1) * 48_000 * channels, "only {total} samples"); + assert!( + total >= (SECONDS - 1) * 48_000 * channels, + "only {total} samples" + ); assert_eq!(stats.lossless_check_failures, 0, "{stats:?}"); assert_eq!(stats.parity_failures, 0, "{stats:?}"); assert_eq!(stats.restart_crc_failures, 0, "{stats:?}"); assert_eq!(stats.length_mismatches, 0, "{stats:?}"); - assert!(exact as f64 >= 0.9999 * total as f64, "{exact}/{total} exact, first mismatch {first:?}"); + assert!( + exact as f64 >= 0.9999 * total as f64, + "{exact}/{total} exact, first mismatch {first:?}" + ); } /// An externally encoded MLP stream (raw access units) decoded by us must @@ -140,15 +178,33 @@ fn externally_encoded_mlp_round_trips_bit_exact() { std::fs::create_dir_all(&dir).unwrap(); let mut failures = Vec::new(); for (codec, layout, channels) in [ - ("mlp", "mono", 1usize), ("mlp", "stereo", 2), ("mlp", "5.1", 6), - ("truehd", "mono", 1), ("truehd", "stereo", 2), ("truehd", "5.1", 6), + ("mlp", "mono", 1usize), + ("mlp", "stereo", 2), + ("mlp", "5.1", 6), + ("truehd", "mono", 1), + ("truehd", "stereo", 2), + ("truehd", "5.1", 6), ] { let name = format!("{codec}-{layout}"); - let mlp = dir.join(format!("{name}.{}", if codec == "mlp" { "mlp" } else { "thd" })); + let mlp = dir.join(format!( + "{name}.{}", + if codec == "mlp" { "mlp" } else { "thd" } + )); let src = format!( "anoisesrc=color=pink:amplitude=0.3:seed=7:sample_rate=48000:duration=3,aformat=sample_fmts=s32:channel_layouts={layout}" ); - ffmpeg(&["-y", "-f", "lavfi", "-i", &src, "-c:a", codec, "-strict", "-2", mlp.to_str().unwrap()]); + ffmpeg(&[ + "-y", + "-f", + "lavfi", + "-i", + &src, + "-c:a", + codec, + "-strict", + "-2", + mlp.to_str().unwrap(), + ]); let reference = s32le(&ffmpeg(&["-i", mlp.to_str().unwrap(), "-f", "s32le", "-"])); let data = std::fs::read(&mlp).unwrap(); @@ -165,14 +221,92 @@ fn externally_encoded_mlp_round_trips_bit_exact() { } let (exact, total, first) = compare(&ours, &reference); let stats = decoder.check_stats(); - eprintln!("{name}: {exact}/{total} exact (ours {}, reference {}), first mismatch {first:?}, {stats:?}", ours.len(), reference.len()); + eprintln!( + "{name}: {exact}/{total} exact (ours {}, reference {}), first mismatch {first:?}, {stats:?}", + ours.len(), + reference.len() + ); if stats.lossless_check_failures + stats.parity_failures + stats.restart_crc_failures != 0 || exact != total || total < 2 * 48_000 * channels { - failures.push(format!("{name}: {exact}/{total}, first mismatch {first:?}, {stats:?}")); + failures.push(format!( + "{name}: {exact}/{total}, first mismatch {first:?}, {stats:?}" + )); } } let _ = std::fs::remove_dir_all(&dir); assert!(failures.is_empty(), "{failures:#?}"); } + +/// GATE 2: a foreign decoder (ffmpeg's own `truehd`/MLP decoder, not this +/// crate's) decodes bytes from [`TrueHdEncoder`] sample-exact against the +/// PCM that went in — the decisive oracle per the shared-oracle-blindness +/// class (see the project ledger): our own decoder alone, as an encoder +/// gate, would only prove the two halves of this crate agree with each +/// other. +#[test] +fn ffmpeg_decodes_our_encoder_bit_exact() { + if !have_ffmpeg() { + eprintln!("ffmpeg not found, skipping"); + return; + } + use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; + use ec_core::packet::Buf; + use ec_core::registry::Encoder; + + let n = 48_000usize; + let mut samples = Vec::with_capacity(n * 2); + let mut lcg: u32 = 0xC0FF_EE00; + for i in 0..n { + let l = ((i as f64 * 440.0 * std::f64::consts::TAU / 48_000.0).sin() * 3_000_000.0) as i32; + lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let r = l.wrapping_add((lcg >> 8) as i32 % 20_000 - 10_000); + samples.push(l.clamp(-8_388_608, 8_388_607)); + samples.push(r.clamp(-8_388_608, 8_388_607)); + } + let mut bytes = Vec::with_capacity(samples.len() * 4); + for &s in &samples { + bytes.extend_from_slice(&(s << 8).to_le_bytes()); + } + let reference = s32le(&bytes); + let frame = AudioFrame::try_new( + SampleFormat::S32, + false, + ChannelLayout::Stereo, + 48_000, + n, + vec![Buf::from_vec(bytes)], + ) + .unwrap(); + + let mut enc = TrueHdEncoder::new(48_000).unwrap(); + enc.send_frame(&Frame::Audio(frame)).unwrap(); + enc.flush().unwrap(); + let mut thd = Vec::new(); + while let Ok(pkt) = enc.receive_packet() { + thd.extend_from_slice(&pkt.data); + } + + let dir = std::env::temp_dir().join(format!("ec-truehd-enc-oracle-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ours.thd"); + std::fs::write(&path, &thd).unwrap(); + let out = ffmpeg(&[ + "-f", + "truehd", + "-i", + path.to_str().unwrap(), + "-f", + "s32le", + "-", + ]); + let _ = std::fs::remove_dir_all(&dir); + + let decoded = s32le(&out); + let (exact, total, first) = compare(&decoded, &reference); + assert_eq!( + exact, total, + "ffmpeg vs our own PCM: first mismatch {first:?} of {total}" + ); +}