Fixed-allocation AC-3 encoder skeleton that round-trips at corr 0.998
Browse files at this commitf663ba5d6006da1a545f82b5b951be7c4389c713Parent: b966d5e- feat
- fixed-allocation AC-3 encoder skeleton that round-trips at corr 0.998
3 changed files +959 -2
- crates/ec-ac3/src/encode.rs +762 -0
- crates/ec-ac3/src/lib.rs +7 -2
- crates/ec-ac3/tests/encode_matrix.rs +190 -0
crates/ec-ac3/src/encode.rsadded+762 -0
| @@ -0,0 +1,762 @@ | ||
| 1 | +//! An AC-3 encoder: PCM in, spec-valid ATSC A/52 syncframes out. | |
| 2 | +//! | |
| 3 | +//! This is the skeleton subtask: the bitstream writer mirrors the parser's | |
| 4 | +//! normative order (`syncinfo()`, `bsi()`, six `audblk()`s, `auxdata`/CRC) but | |
| 5 | +//! runs a *fixed* allocation rather than a real psychoacoustic search — | |
| 6 | +//! exponent strategy is D15 on block 0 and reused for the rest of the frame, | |
| 7 | +//! the bit allocation parameters are constants, and the only thing that | |
| 8 | +//! adapts per frame is `csnroffst`, stepped down until the fixed allocation's | |
| 9 | +//! mantissas fit the frame's byte budget. A2 replaces the fixed exponent | |
| 10 | +//! strategy and per-frame envelope with a real one; A3 replaces the | |
| 11 | +//! `csnroffst` step-down with a proper rate-controlled search | |
| 12 | +//! ([`Ac3Encoder::try_csnroffst`], [`Ac3Encoder::build_frame`]). | |
| 13 | +//! | |
| 14 | +//! No coupling, no rematrixing, no delta bit allocation, no AHT: all of that | |
| 15 | +//! is legal to leave off (every presence bit for them is simply sent as 0), | |
| 16 | +//! and all of it is future work rather than a correctness gap in what is | |
| 17 | +//! implemented here. | |
| 18 | + | |
| 19 | +use ec_core::{ | |
| 20 | + AudioParameters, BitWriter, Buf, ChannelLayout, CodecId, CodecParameters, Encoder, Error, | |
| 21 | + Frame, MediaParameters, Packet, Result, SampleFormat, TimeBase, | |
| 22 | +}; | |
| 23 | +use ec_dsp::Mdct; | |
| 24 | + | |
| 25 | +use crate::bitalloc::{self, Allocation, BitAllocParams, Channel}; | |
| 26 | +use crate::bsi::Acmod; | |
| 27 | +use crate::exps::Strategy; | |
| 28 | +use crate::tables::{BIT_RATE_KBPS, FRAME_SIZE_WORDS, QNTZTAB, QUANT_LEVELS, SAMPLE_RATE, WINDOW}; | |
| 29 | + | |
| 30 | +/// Samples per channel one syncframe codes. | |
| 31 | +const FRAME_SAMPLES: usize = 1536; | |
| 32 | +/// Blocks per syncframe. | |
| 33 | +const BLOCKS: usize = 6; | |
| 34 | +/// Coefficients per channel per block ([`crate::decode::COEFFS`], not public). | |
| 35 | +const COEFFS: usize = 256; | |
| 36 | +/// `chbwcod` this encoder always sends: maximum bandwidth. | |
| 37 | +const CHBWCOD: u32 = 60; | |
| 38 | +/// Full-bandwidth `endmant` at [`CHBWCOD`]: `(chbwcod + 12) * 3 + 37`. | |
| 39 | +const FBW_ENDMANT: usize = (CHBWCOD as usize + 12) * 3 + 37; | |
| 40 | +/// LFE `endmant`, fixed by the standard. | |
| 41 | +const LFE_ENDMANT: usize = 7; | |
| 42 | +/// Scale from `ec_dsp::Mdct::forward_windowed`'s raw sum (which equals the | |
| 43 | +/// plain A/52 §7.9.4 cosine sum) to the coefficients `crate::transform::Imdct` | |
| 44 | +/// expects: the standard's `-2/N` (N = 512) forward normalisation, with its | |
| 45 | +/// `2.0x` on the way back being the decoder's own half of that pair. | |
| 46 | +const FORWARD_GAIN: f32 = -2.0 / 512.0; | |
| 47 | + | |
| 48 | +/// How the encoder is set up. | |
| 49 | +#[derive(Debug, Clone, Copy, PartialEq)] | |
| 50 | +pub struct EncoderConfig { | |
| 51 | + /// Sample rate in Hz: 48000, 44100 or 32000. | |
| 52 | + pub sample_rate: u32, | |
| 53 | + /// Channel count, 1 to 6 (6 is 3/2 + LFE). | |
| 54 | + pub channels: u16, | |
| 55 | + /// Target bit rate in kbit/s, snapped to the nearest legal A/52 rate. | |
| 56 | + pub bitrate_kbps: u32, | |
| 57 | +} | |
| 58 | + | |
| 59 | +/// The coded-channel order this encoder writes to the bit stream, alongside | |
| 60 | +/// which "family" (public, L/R/C/LFE/Ls/Rs) slot each one reads its PCM from. | |
| 61 | +/// | |
| 62 | +/// Mirrors `decode::Core::channel_order` (decode.rs:737-754) exactly, so a | |
| 63 | +/// frame encoded from family-order PCM and decoded back comes out in the same | |
| 64 | +/// family order it went in. `None` marks the LFE slot. | |
| 65 | +fn channel_order(acmod: Acmod, nfchans: usize, lfeon: bool) -> Vec<Option<usize>> { | |
| 66 | + let mut order: Vec<Option<usize>> = match acmod { | |
| 67 | + Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => { | |
| 68 | + let mut v = vec![Some(0), Some(2), Some(1)]; | |
| 69 | + v.extend((3..nfchans).map(Some)); | |
| 70 | + v | |
| 71 | + } | |
| 72 | + _ => (0..nfchans).map(Some).collect(), | |
| 73 | + }; | |
| 74 | + if lfeon { | |
| 75 | + let fronts = match acmod { | |
| 76 | + Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3, | |
| 77 | + Acmod::Mono => 1, | |
| 78 | + _ => 2, | |
| 79 | + }; | |
| 80 | + order.insert(fronts.min(order.len()), None); | |
| 81 | + } | |
| 82 | + order | |
| 83 | +} | |
| 84 | + | |
| 85 | +/// Acmod and LFE presence for a channel count, 1..=6. | |
| 86 | +fn acmod_for(channels: u16) -> Result<(Acmod, bool)> { | |
| 87 | + Ok(match channels { | |
| 88 | + 1 => (Acmod::Mono, false), | |
| 89 | + 2 => (Acmod::Stereo, false), | |
| 90 | + 3 => (Acmod::Surround3_0, false), | |
| 91 | + 4 => (Acmod::Surround2_2, false), | |
| 92 | + 5 => (Acmod::Surround3_2, false), | |
| 93 | + 6 => (Acmod::Surround3_2, true), | |
| 94 | + other => { | |
| 95 | + return Err(Error::unsupported( | |
| 96 | + format!("{other} channels"), | |
| 97 | + "this encoder codes 1 to 6 channels (6 is 3/2 + LFE)", | |
| 98 | + )); | |
| 99 | + } | |
| 100 | + }) | |
| 101 | +} | |
| 102 | + | |
| 103 | +/// CRC-16, poly `x^16 + x^15 + x^2 + 1` (0x8005), MSB first, as A/52 §7.10 | |
| 104 | +/// states it: the bit-serial form, not a reflected table. | |
| 105 | +fn crc16(data: &[u8]) -> u16 { | |
| 106 | + let mut crc: u16 = 0; | |
| 107 | + for &byte in data { | |
| 108 | + crc ^= (byte as u16) << 8; | |
| 109 | + for _ in 0..8 { | |
| 110 | + crc = if crc & 0x8000 != 0 { | |
| 111 | + (crc << 1) ^ 0x8005 | |
| 112 | + } else { | |
| 113 | + crc << 1 | |
| 114 | + }; | |
| 115 | + } | |
| 116 | + } | |
| 117 | + crc | |
| 118 | +} | |
| 119 | + | |
| 120 | +/// The reconstruction-level index closest to `value` for an `levels`-level | |
| 121 | +/// symmetric quantizer — the forward of [`crate::tables::symmetric_level`]. | |
| 122 | +fn quantize_index(levels: u32, value: f32) -> u32 { | |
| 123 | + let k = ((value * levels as f32 + (levels as f32 - 1.0)) / 2.0).round(); | |
| 124 | + k.clamp(0.0, (levels - 1) as f32) as u32 | |
| 125 | +} | |
| 126 | + | |
| 127 | +/// Writes a block's mantissas in stream order. The grouped quantizers (bap | |
| 128 | +/// 1, 2, 4) are the subtle part: [`crate::mantissa::Mantissas`] reads a whole | |
| 129 | +/// group's code word at the *first* of its 3 (or 2) values and the later | |
| 130 | +/// members consume nothing, with the group running on across channels | |
| 131 | +/// (§7.3.5). So the code word has to be emitted where the first member sits, | |
| 132 | +/// which means looking ahead past whatever other-bap mantissas lie in between | |
| 133 | +/// for the group's remaining members. A group the block ends partway through | |
| 134 | +/// is padded with its midpoint (zero); the decoder never reads the padding. | |
| 135 | +fn write_mantissas(w: &mut BitWriter, values: &[(u8, f32)]) { | |
| 136 | + let mut left = [0usize; 16]; | |
| 137 | + for (i, &(bap, value)) in values.iter().enumerate() { | |
| 138 | + let (levels, bits, size, radix) = match bap { | |
| 139 | + 0 => continue, | |
| 140 | + 1 => (QUANT_LEVELS[1], 5, 3, 3), | |
| 141 | + 2 => (QUANT_LEVELS[2], 7, 3, 5), | |
| 142 | + 4 => (QUANT_LEVELS[4], 7, 2, 11), | |
| 143 | + 3 | 5 => { | |
| 144 | + let bits = QNTZTAB[bap as usize]; | |
| 145 | + w.write_bits(quantize_index(QUANT_LEVELS[bap as usize], value), bits); | |
| 146 | + continue; | |
| 147 | + } | |
| 148 | + _ => { | |
| 149 | + // 6..=15: asymmetric two's complement (§7.3.2). | |
| 150 | + let bits = QNTZTAB[(bap as usize).min(15)]; | |
| 151 | + let scale = (1u32 << (bits - 1)) as f32; | |
| 152 | + let signed = (value * scale).round().clamp(-scale, scale - 1.0) as i32; | |
| 153 | + w.write_signed(signed, bits); | |
| 154 | + continue; | |
| 155 | + } | |
| 156 | + }; | |
| 157 | + if left[bap as usize] == 0 { | |
| 158 | + let mut code = 0u32; | |
| 159 | + let mut members = values[i..].iter().filter(|v| v.0 == bap).map(|v| quantize_index(levels, v.1)); | |
| 160 | + for _ in 0..size { | |
| 161 | + code = code * radix + members.next().unwrap_or((levels - 1) / 2); | |
| 162 | + } | |
| 163 | + w.write_bits(code, bits); | |
| 164 | + left[bap as usize] = size; | |
| 165 | + } | |
| 166 | + left[bap as usize] -= 1; | |
| 167 | + } | |
| 168 | +} | |
| 169 | + | |
| 170 | +/// Fits an ideal exponent envelope to what the group-diff coding can carry | |
| 171 | +/// (each step moves the running exponent by at most 2, and the first bin's | |
| 172 | +/// absolute exponent has 4 bits), only ever *lowering* exponents to get | |
| 173 | +/// there: a lower exponent than ideal costs mantissa precision, a higher one | |
| 174 | +/// clips the mantissa at full scale and loses the coefficient — which is | |
| 175 | +/// exactly what a one-directional "walk toward the ideal" does on the rising | |
| 176 | +/// edge of a spectral peak. A backward then a forward min-pass make every | |
| 177 | +/// neighbouring difference fit, so [`write_exp_groups`]' clamp is then a no-op | |
| 178 | +/// and the decoder sees precisely this array. | |
| 179 | +fn smooth_exps(exps: &mut [u8]) { | |
| 180 | + exps[0] = exps[0].min(15); | |
| 181 | + for i in (0..exps.len() - 1).rev() { | |
| 182 | + exps[i] = exps[i].min(exps[i + 1] + 2); | |
| 183 | + } | |
| 184 | + for i in 1..exps.len() { | |
| 185 | + exps[i] = exps[i].min(exps[i - 1] + 2); | |
| 186 | + } | |
| 187 | +} | |
| 188 | + | |
| 189 | +/// Writes `ngrps` 7-bit exponent groups covering 3 bins each. `realized` must | |
| 190 | +/// already have been through [`smooth_exps`], so the values the decoder | |
| 191 | +/// reconstructs are exactly the ones [`crate::bitalloc::compute`] was run | |
| 192 | +/// against. | |
| 193 | +fn write_exp_groups(w: &mut BitWriter, realized: &[u8; COEFFS], mut prev: i32, first_bin: usize, ngrps: usize) { | |
| 194 | + let mut bin = first_bin; | |
| 195 | + for _ in 0..ngrps { | |
| 196 | + let mut mapped = [0i32; 3]; | |
| 197 | + for slot in &mut mapped { | |
| 198 | + let target = if bin < COEFFS { i32::from(realized[bin]) } else { prev }; | |
| 199 | + let diff = (target - prev).clamp(-2, 2); | |
| 200 | + prev = (prev + diff).clamp(0, 24); | |
| 201 | + *slot = diff + 2; | |
| 202 | + bin += 1; | |
| 203 | + } | |
| 204 | + let code = (mapped[0] * 25 + mapped[1] * 5 + mapped[2]) as u32; | |
| 205 | + w.write_bits(code, 7); | |
| 206 | + } | |
| 207 | +} | |
| 208 | + | |
| 209 | +/// PCM in, AC-3 syncframes out. | |
| 210 | +pub struct Ac3Encoder { | |
| 211 | + config: EncoderConfig, | |
| 212 | + params: CodecParameters, | |
| 213 | + acmod: Acmod, | |
| 214 | + lfeon: bool, | |
| 215 | + nfchans: usize, | |
| 216 | + /// Coded channels, LFE included when present; index `nfchans` is the LFE | |
| 217 | + /// slot whenever `lfeon`. | |
| 218 | + coded: usize, | |
| 219 | + fscod: usize, | |
| 220 | + frmsizecod: u8, | |
| 221 | + frame_bytes: usize, | |
| 222 | + order: Vec<Option<usize>>, | |
| 223 | + mdct: Mdct<f32>, | |
| 224 | + window: [f32; 512], | |
| 225 | + /// Previous block's tail, per coded channel — the MDCT's 50% overlap. | |
| 226 | + history: Vec<[f32; COEFFS]>, | |
| 227 | + pcm: Vec<f32>, | |
| 228 | + packets: std::collections::VecDeque<Vec<u8>>, | |
| 229 | + finished: bool, | |
| 230 | +} | |
| 231 | + | |
| 232 | +impl Ac3Encoder { | |
| 233 | + /// An encoder for this configuration. | |
| 234 | + pub fn new(config: EncoderConfig) -> Result<Ac3Encoder> { | |
| 235 | + let (acmod, lfeon) = acmod_for(config.channels)?; | |
| 236 | + let nfchans = acmod.nfchans(); | |
| 237 | + let coded = nfchans + usize::from(lfeon); | |
| 238 | + let fscod = SAMPLE_RATE | |
| 239 | + .iter() | |
| 240 | + .position(|&r| r == config.sample_rate) | |
| 241 | + .ok_or_else(|| { | |
| 242 | + Error::unsupported( | |
| 243 | + format!("{} Hz", config.sample_rate), | |
| 244 | + "AC-3 codes 48000, 44100 or 32000 Hz", | |
| 245 | + ) | |
| 246 | + })?; | |
| 247 | + let idx = BIT_RATE_KBPS | |
| 248 | + .iter() | |
| 249 | + .enumerate() | |
| 250 | + .min_by_key(|&(_, &k)| k.abs_diff(config.bitrate_kbps)) | |
| 251 | + .map(|(i, _)| i) | |
| 252 | + .unwrap_or(0); | |
| 253 | + let frmsizecod = (idx * 2) as u8; | |
| 254 | + let frame_bytes = usize::from(FRAME_SIZE_WORDS[frmsizecod as usize][fscod]) * 2; | |
| 255 | + | |
| 256 | + let mut window = [0.0f32; 512]; | |
| 257 | + for i in 0..256 { | |
| 258 | + window[i] = WINDOW[i]; | |
| 259 | + window[511 - i] = WINDOW[i]; | |
| 260 | + } | |
| 261 | + | |
| 262 | + let mut params = CodecParameters::new(CodecId::Ac3); | |
| 263 | + params.media = MediaParameters::Audio(AudioParameters { | |
| 264 | + sample_rate: config.sample_rate, | |
| 265 | + layout: ChannelLayout::from_count(coded), | |
| 266 | + format: Some(SampleFormat::F32), | |
| 267 | + bits_per_sample: None, | |
| 268 | + }); | |
| 269 | + | |
| 270 | + Ok(Ac3Encoder { | |
| 271 | + order: channel_order(acmod, nfchans, lfeon), | |
| 272 | + config, | |
| 273 | + params, | |
| 274 | + acmod, | |
| 275 | + lfeon, | |
| 276 | + nfchans, | |
| 277 | + coded, | |
| 278 | + fscod, | |
| 279 | + frmsizecod, | |
| 280 | + frame_bytes, | |
| 281 | + mdct: Mdct::new(512), | |
| 282 | + window, | |
| 283 | + history: vec![[0.0; COEFFS]; coded], | |
| 284 | + pcm: Vec::new(), | |
| 285 | + packets: std::collections::VecDeque::new(), | |
| 286 | + finished: false, | |
| 287 | + }) | |
| 288 | + } | |
| 289 | + | |
| 290 | + /// Codec parameters this encoder declares. | |
| 291 | + pub fn codec_parameters(&self) -> &CodecParameters { | |
| 292 | + &self.params | |
| 293 | + } | |
| 294 | + | |
| 295 | + /// Feeds interleaved `f32` PCM, family order (L, R, C, LFE, Ls, Rs — the | |
| 296 | + /// same order [`crate::Ac3Decoder`] hands frames out in). | |
| 297 | + pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> { | |
| 298 | + self.pcm.extend_from_slice(interleaved); | |
| 299 | + self.drain(); | |
| 300 | + Ok(()) | |
| 301 | + } | |
| 302 | + | |
| 303 | + /// Ends the stream: pads the tail to a whole frame and flushes it. | |
| 304 | + pub fn finish(&mut self) { | |
| 305 | + let need = FRAME_SAMPLES * self.coded; | |
| 306 | + if !self.pcm.is_empty() { | |
| 307 | + let padded = self.pcm.len().div_ceil(need) * need; | |
| 308 | + self.pcm.resize(padded, 0.0); | |
| 309 | + } | |
| 310 | + self.drain(); | |
| 311 | + self.finished = true; | |
| 312 | + } | |
| 313 | + | |
| 314 | + fn drain(&mut self) { | |
| 315 | + let need = FRAME_SAMPLES * self.coded; | |
| 316 | + while self.pcm.len() >= need { | |
| 317 | + let block: Vec<f32> = self.pcm.drain(..need).collect(); | |
| 318 | + let packet = self.encode_frame(&block); | |
| 319 | + self.packets.push_back(packet); | |
| 320 | + } | |
| 321 | + } | |
| 322 | + | |
| 323 | + /// The next encoded syncframe; [`Error::Eof`] once drained after | |
| 324 | + /// [`Ac3Encoder::finish`], [`Error::NeedMore`] before that. | |
| 325 | + pub fn next_packet(&mut self) -> Result<Vec<u8>> { | |
| 326 | + match self.packets.pop_front() { | |
| 327 | + Some(p) => Ok(p), | |
| 328 | + None if self.finished => Err(Error::Eof), | |
| 329 | + None => Err(Error::NeedMore), | |
| 330 | + } | |
| 331 | + } | |
| 332 | + | |
| 333 | + /// One syncframe from `interleaved` (family-order PCM, `coded` channels * | |
| 334 | + /// [`FRAME_SAMPLES`] samples). | |
| 335 | + fn encode_frame(&mut self, interleaved: &[f32]) -> Vec<u8> { | |
| 336 | + // Deinterleave into coded-channel order and run the MDCT per block. | |
| 337 | + let mut coeffs = vec![vec![[0.0f32; COEFFS]; self.coded]; BLOCKS]; | |
| 338 | + for ch in 0..self.coded { | |
| 339 | + let slot = if ch < self.nfchans { | |
| 340 | + self.order.iter().position(|&s| s == Some(ch)).unwrap() | |
| 341 | + } else { | |
| 342 | + self.order.iter().position(|&s| s.is_none()).unwrap() | |
| 343 | + }; | |
| 344 | + for blk in 0..BLOCKS { | |
| 345 | + let mut window_in = [0.0f32; 512]; | |
| 346 | + window_in[..256].copy_from_slice(&self.history[ch]); | |
| 347 | + for n in 0..256 { | |
| 348 | + window_in[256 + n] = interleaved[(blk * 256 + n) * self.coded + slot]; | |
| 349 | + } | |
| 350 | + let mut spectrum = [0.0f32; COEFFS]; | |
| 351 | + self.mdct | |
| 352 | + .forward_windowed(&window_in, &self.window, &mut spectrum); | |
| 353 | + for v in &mut spectrum { | |
| 354 | + // Measured in `tests::tdac_*`: this makes the forward the | |
| 355 | + // exact adjoint of the decoder's transform.rs IMDCT. | |
| 356 | + *v *= FORWARD_GAIN; | |
| 357 | + } | |
| 358 | + self.history[ch].copy_from_slice(&window_in[256..]); | |
| 359 | + coeffs[blk][ch] = spectrum; | |
| 360 | + } | |
| 361 | + } | |
| 362 | + | |
| 363 | + // Exponents: one D15 envelope per coded channel, tracking the loudest | |
| 364 | + // magnitude any of the frame's 6 blocks reaches at each bin, so no | |
| 365 | + // block's mantissa is asked to represent more than the exponent's | |
| 366 | + // headroom allows. | |
| 367 | + let endmant: Vec<usize> = (0..self.coded) | |
| 368 | + .map(|ch| if ch < self.nfchans { FBW_ENDMANT } else { LFE_ENDMANT }) | |
| 369 | + .collect(); | |
| 370 | + let exps: Vec<[u8; COEFFS]> = (0..self.coded) | |
| 371 | + .map(|ch| { | |
| 372 | + let mut e = [24u8; COEFFS]; | |
| 373 | + for bin in 0..endmant[ch] { | |
| 374 | + let mag = coeffs | |
| 375 | + .iter() | |
| 376 | + .map(|b| b[ch][bin].abs()) | |
| 377 | + .fold(0.0f32, f32::max); | |
| 378 | + e[bin] = if mag <= 0.0 { | |
| 379 | + 24 | |
| 380 | + } else { | |
| 381 | + (-mag.log2()).floor().clamp(0.0, 24.0) as u8 | |
| 382 | + }; | |
| 383 | + } | |
| 384 | + e | |
| 385 | + }) | |
| 386 | + .collect(); | |
| 387 | + // Fit the envelope to what the group-diff coding can carry, never | |
| 388 | + // raising an exponent (that would clip its mantissas); the bit | |
| 389 | + // allocation below then runs on exactly what the decoder will decode. | |
| 390 | + let exps: Vec<[u8; COEFFS]> = exps | |
| 391 | + .into_iter() | |
| 392 | + .enumerate() | |
| 393 | + .map(|(ch, mut e)| { | |
| 394 | + smooth_exps(&mut e[..endmant[ch]]); | |
| 395 | + e | |
| 396 | + }) | |
| 397 | + .collect(); | |
| 398 | + | |
| 399 | + // Fixed allocation: step csnroffst down from a generous default until | |
| 400 | + // the mantissas it buys fit the frame. A3 replaces this with a rate | |
| 401 | + // loop that also varies floorcod/gaincod; see `Ac3Encoder::try_csnroffst`. | |
| 402 | + let mut csnroffst: i32 = 40; | |
| 403 | + let budget_bits = self.frame_bytes as u64 * 8 - 2 /* auxdataflag, crcrsv */ - 16 /* crc2 */; | |
| 404 | + let mut w; | |
| 405 | + loop { | |
| 406 | + let bap = self.allocate(&exps, &endmant, csnroffst as u8); | |
| 407 | + w = self.write_frame(&coeffs, &exps, &endmant, &bap, csnroffst as u8); | |
| 408 | + if w.bit_len() <= budget_bits || csnroffst == 0 { | |
| 409 | + break; | |
| 410 | + } | |
| 411 | + csnroffst -= 1; | |
| 412 | + } | |
| 413 | + | |
| 414 | + self.finish_frame(w) | |
| 415 | + } | |
| 416 | + | |
| 417 | + /// Bit allocation for every coded channel at one `csnroffst`. | |
| 418 | + fn allocate(&self, exps: &[[u8; COEFFS]], endmant: &[usize], csnroffst: u8) -> Vec<[u8; COEFFS]> { | |
| 419 | + let snroffset = ((i32::from(csnroffst) - 15) << 4) << 2; // fsnroffst = 0 | |
| 420 | + let params = BitAllocParams { | |
| 421 | + sdcycod: 2, | |
| 422 | + fdcycod: 1, | |
| 423 | + sgaincod: 1, | |
| 424 | + dbpbcod: 2, | |
| 425 | + floorcod: 7, | |
| 426 | + }; | |
| 427 | + (0..self.coded) | |
| 428 | + .map(|ch| { | |
| 429 | + let kind = if ch < self.nfchans { Channel::Fbw } else { Channel::Lfe }; | |
| 430 | + let alloc = Allocation { | |
| 431 | + fscod: self.fscod, | |
| 432 | + params, | |
| 433 | + range: (0, endmant[ch]), | |
| 434 | + fgaincod: 4, | |
| 435 | + snroffset, | |
| 436 | + kind, | |
| 437 | + dba: None, | |
| 438 | + high_efficiency: false, | |
| 439 | + }; | |
| 440 | + let mut bap = [0u8; COEFFS]; | |
| 441 | + bitalloc::compute(&alloc, &exps[ch], &mut bap); | |
| 442 | + bap | |
| 443 | + }) | |
| 444 | + .collect() | |
| 445 | + } | |
| 446 | + | |
| 447 | + /// Writes syncinfo, bsi and the six audblks; mantissas and their bit cost | |
| 448 | + /// come from `coeffs`, `exps` and `bap` (all already computed for this | |
| 449 | + /// frame). Everything up to the crc/padding tail this function leaves for | |
| 450 | + /// [`Ac3Encoder::finish_frame`], so the retry loop in | |
| 451 | + /// [`Ac3Encoder::encode_frame`] can measure a candidate's length before | |
| 452 | + /// paying for that. | |
| 453 | + fn write_frame( | |
| 454 | + &self, | |
| 455 | + coeffs: &[Vec<[f32; COEFFS]>], | |
| 456 | + exps: &[[u8; COEFFS]], | |
| 457 | + endmant: &[usize], | |
| 458 | + bap: &[[u8; COEFFS]], | |
| 459 | + csnroffst: u8, | |
| 460 | + ) -> BitWriter { | |
| 461 | + let mut w = BitWriter::with_capacity(self.frame_bytes); | |
| 462 | + | |
| 463 | + // syncinfo(): crc1 is patched into the bytes afterwards. | |
| 464 | + w.write_bits(0x0B77, 16); | |
| 465 | + w.write_bits(0, 16); | |
| 466 | + w.write_bits(self.fscod as u32, 2); | |
| 467 | + w.write_bits(u32::from(self.frmsizecod), 6); | |
| 468 | + | |
| 469 | + // bsi() | |
| 470 | + w.write_bits(8, 5); // bsid | |
| 471 | + w.write_bits(0, 3); // bsmod | |
| 472 | + w.write_bits(u32::from(self.acmod.code()), 3); | |
| 473 | + if self.acmod.code() & 1 != 0 && self.acmod.code() != 1 { | |
| 474 | + w.write_bits(1, 2); // cmixlev | |
| 475 | + } | |
| 476 | + if self.acmod.code() & 4 != 0 { | |
| 477 | + w.write_bits(1, 2); // surmixlev | |
| 478 | + } | |
| 479 | + if self.acmod == Acmod::Stereo { | |
| 480 | + w.write_bits(0, 2); // dsurmod | |
| 481 | + } | |
| 482 | + w.write_bit(self.lfeon); | |
| 483 | + w.write_bits(31, 5); // dialnorm | |
| 484 | + w.write_bit(false); // compr | |
| 485 | + w.write_bit(false); // langcod | |
| 486 | + w.write_bit(false); // mixlevel/roomtyp | |
| 487 | + w.write_bit(false); // copyrightb | |
| 488 | + w.write_bit(false); // origbs | |
| 489 | + w.write_bit(false); // timecod1 | |
| 490 | + w.write_bit(false); // timecod2 | |
| 491 | + w.write_bit(false); // addbsi | |
| 492 | + | |
| 493 | + for blk in 0..BLOCKS { | |
| 494 | + self.write_block(&mut w, blk, coeffs, exps, endmant, bap, csnroffst); | |
| 495 | + } | |
| 496 | + w | |
| 497 | + } | |
| 498 | + | |
| 499 | + #[allow(clippy::too_many_arguments)] | |
| 500 | + fn write_block( | |
| 501 | + &self, | |
| 502 | + w: &mut BitWriter, | |
| 503 | + blk: usize, | |
| 504 | + coeffs: &[Vec<[f32; COEFFS]>], | |
| 505 | + exps: &[[u8; COEFFS]], | |
| 506 | + endmant: &[usize], | |
| 507 | + bap: &[[u8; COEFFS]], | |
| 508 | + csnroffst: u8, | |
| 509 | + ) { | |
| 510 | + let first = blk == 0; | |
| 511 | + for _ in 0..self.nfchans { | |
| 512 | + w.write_bit(false); // blksw | |
| 513 | + } | |
| 514 | + for _ in 0..self.nfchans { | |
| 515 | + w.write_bit(false); // dithflag | |
| 516 | + } | |
| 517 | + w.write_bit(false); // dynrnge | |
| 518 | + w.write_bit(first); // cplstre: block 0 must declare a strategy | |
| 519 | + if first { | |
| 520 | + w.write_bit(false); // cplinu: no coupling | |
| 521 | + } | |
| 522 | + if self.acmod == Acmod::Stereo { | |
| 523 | + w.write_bit(false); // rematstr (no rematrixing) | |
| 524 | + } | |
| 525 | + for _ in 0..self.nfchans { | |
| 526 | + w.write_bits(if first { 1 } else { 0 }, 2); // chexpstr: D15 / reuse | |
| 527 | + } | |
| 528 | + if self.lfeon { | |
| 529 | + w.write_bit(first); // lfeexpstr: D15 / reuse | |
| 530 | + } | |
| 531 | + if first { | |
| 532 | + for _ in 0..self.nfchans { | |
| 533 | + w.write_bits(CHBWCOD, 6); // chbwcod | |
| 534 | + } | |
| 535 | + } | |
| 536 | + if first { | |
| 537 | + for ch in 0..self.nfchans { | |
| 538 | + let absexp = exps[ch][0].min(15); | |
| 539 | + w.write_bits(u32::from(absexp), 4); | |
| 540 | + let ngrps = Strategy::D15.fbw_groups(endmant[ch]); | |
| 541 | + write_exp_groups(w, &exps[ch], i32::from(absexp), 1, ngrps); | |
| 542 | + w.write_bits(0, 2); // gainrng | |
| 543 | + } | |
| 544 | + if self.lfeon { | |
| 545 | + let ch = self.nfchans; | |
| 546 | + let absexp = exps[ch][0].min(15); | |
| 547 | + w.write_bits(u32::from(absexp), 4); | |
| 548 | + write_exp_groups(w, &exps[ch], i32::from(absexp), 1, 2); | |
| 549 | + } | |
| 550 | + } | |
| 551 | + w.write_bit(first); // baie | |
| 552 | + if first { | |
| 553 | + w.write_bits(2, 2); // sdcycod | |
| 554 | + w.write_bits(1, 2); // fdcycod | |
| 555 | + w.write_bits(1, 2); // sgaincod | |
| 556 | + w.write_bits(2, 2); // dbpbcod | |
| 557 | + w.write_bits(7, 3); // floorcod | |
| 558 | + } | |
| 559 | + w.write_bit(first); // snroffste | |
| 560 | + if first { | |
| 561 | + w.write_bits(u32::from(csnroffst), 6); | |
| 562 | + for _ in 0..self.nfchans { | |
| 563 | + w.write_bits(0, 4); // fsnroffst | |
| 564 | + w.write_bits(4, 3); // fgaincod | |
| 565 | + } | |
| 566 | + if self.lfeon { | |
| 567 | + w.write_bits(0, 4); | |
| 568 | + w.write_bits(4, 3); | |
| 569 | + } | |
| 570 | + } | |
| 571 | + // no coupling leak (cplinu is always false: no bit here at all) | |
| 572 | + w.write_bit(false); // deltbaie | |
| 573 | + w.write_bit(false); // skiple | |
| 574 | + | |
| 575 | + let values: Vec<(u8, f32)> = (0..self.coded) | |
| 576 | + .flat_map(|ch| (0..endmant[ch]).map(move |bin| (ch, bin))) | |
| 577 | + .map(|(ch, bin)| (bap[ch][bin], coeffs[blk][ch][bin] * scale(exps[ch][bin]))) | |
| 578 | + .collect(); | |
| 579 | + write_mantissas(w, &values); | |
| 580 | + } | |
| 581 | + | |
| 582 | + /// Patches crc1/crc2 into a written frame and zero-pads it to | |
| 583 | + /// [`Ac3Encoder::frame_bytes`] — the syncframe's own length, so every | |
| 584 | + /// frame is exactly [`crate::tables::FRAME_SIZE_WORDS`] regardless of how | |
| 585 | + /// far under it this frame's fixed allocation landed. | |
| 586 | + fn finish_frame(&self, mut w: BitWriter) -> Vec<u8> { | |
| 587 | + w.write_bit(false); // auxdataflag | |
| 588 | + w.write_bit(false); // crcrsv | |
| 589 | + while (w.bit_len() as usize) < self.frame_bytes * 8 - 16 { | |
| 590 | + w.write_bit(false); | |
| 591 | + } | |
| 592 | + w.write_bits(0, 16); // crc2 placeholder | |
| 593 | + w.align_to_byte(); | |
| 594 | + let mut bytes = w.into_bytes(); | |
| 595 | + bytes.resize(self.frame_bytes, 0); | |
| 596 | + | |
| 597 | + // §7.10: crc1 covers the first 5/8 of the frame, crc2 the rest. | |
| 598 | + let frame_size_58 = ((self.frame_bytes >> 2) + (self.frame_bytes >> 4)) << 1; | |
| 599 | + let crc1 = crc16(&bytes[4..frame_size_58]); | |
| 600 | + bytes[2..4].copy_from_slice(&crc1.to_be_bytes()); | |
| 601 | + let crc2 = crc16(&bytes[2..self.frame_bytes - 2]); | |
| 602 | + bytes[self.frame_bytes - 2..].copy_from_slice(&crc2.to_be_bytes()); | |
| 603 | + bytes | |
| 604 | + } | |
| 605 | +} | |
| 606 | + | |
| 607 | +/// `2^exponent` — the inverse of [`crate::mantissa::scale`], since the | |
| 608 | +/// encoder starts from a linear coefficient and has to divide it back out to | |
| 609 | +/// the `[-1, 1)` mantissa the quantizers expect. | |
| 610 | +fn scale(exponent: u8) -> f32 { | |
| 611 | + f32::from_bits(127u32.wrapping_add(u32::from(exponent)) << 23) | |
| 612 | +} | |
| 613 | + | |
| 614 | +/// Little-endian floats out of a plane. | |
| 615 | +fn floats(plane: &Buf, count: usize) -> Vec<f32> { | |
| 616 | + plane | |
| 617 | + .chunks_exact(4) | |
| 618 | + .take(count) | |
| 619 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | |
| 620 | + .collect() | |
| 621 | +} | |
| 622 | + | |
| 623 | +impl Encoder for Ac3Encoder { | |
| 624 | + fn codec_parameters(&self) -> &CodecParameters { | |
| 625 | + &self.params | |
| 626 | + } | |
| 627 | + | |
| 628 | + fn send_frame(&mut self, frame: &Frame) -> Result<()> { | |
| 629 | + let Frame::Audio(audio) = frame else { | |
| 630 | + return Err(Error::corrupt("video frame pushed into an audio encoder")); | |
| 631 | + }; | |
| 632 | + if audio.format != SampleFormat::F32 { | |
| 633 | + return Err(Error::unsupported( | |
| 634 | + format!("{:?} input", audio.format), | |
| 635 | + "this encoder takes 32-bit float samples", | |
| 636 | + )); | |
| 637 | + } | |
| 638 | + let channels = self.coded; | |
| 639 | + let interleaved = if audio.planar { | |
| 640 | + let mut out = vec![0.0f32; audio.samples * channels]; | |
| 641 | + for (c, plane) in audio.data.iter().enumerate().take(channels) { | |
| 642 | + for (n, v) in floats(plane, audio.samples).into_iter().enumerate() { | |
| 643 | + out[n * channels + c] = v; | |
| 644 | + } | |
| 645 | + } | |
| 646 | + out | |
| 647 | + } else { | |
| 648 | + floats(&audio.data[0], audio.samples * channels) | |
| 649 | + }; | |
| 650 | + self.push_pcm_f32(&interleaved) | |
| 651 | + } | |
| 652 | + | |
| 653 | + fn receive_packet(&mut self) -> Result<Packet> { | |
| 654 | + let data = self.next_packet()?; | |
| 655 | + let base = TimeBase::new(1, i64::from(self.config.sample_rate)); | |
| 656 | + let mut packet = Packet::new(0, base, data); | |
| 657 | + packet.duration = Some(FRAME_SAMPLES as i64); | |
| 658 | + Ok(packet) | |
| 659 | + } | |
| 660 | + | |
| 661 | + fn flush(&mut self) -> Result<()> { | |
| 662 | + self.finish(); | |
| 663 | + Ok(()) | |
| 664 | + } | |
| 665 | +} | |
| 666 | + | |
| 667 | +#[cfg(test)] | |
| 668 | +mod tests { | |
| 669 | + use super::*; | |
| 670 | + use crate::transform::Imdct; | |
| 671 | + | |
| 672 | + fn lcg(seed: &mut u64) -> f32 { | |
| 673 | + *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); | |
| 674 | + ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 | |
| 675 | + } | |
| 676 | + | |
| 677 | + /// A/52 §7.9.4 forward: X[k] = Σ x[n] w[n] cos(2π/N (n + 1/2 + N/4)(k + 1/2)), N = 512. | |
| 678 | + fn direct_forward(x: &[f32; 512], window: &[f32; 512]) -> [f32; COEFFS] { | |
| 679 | + let mut out = [0.0f32; COEFFS]; | |
| 680 | + for (k, o) in out.iter_mut().enumerate() { | |
| 681 | + let mut acc = 0.0f64; | |
| 682 | + for n in 0..512 { | |
| 683 | + let arg = 2.0 * std::f64::consts::PI / 512.0 * (n as f64 + 0.5 + 128.0) * (k as f64 + 0.5); | |
| 684 | + acc += f64::from(x[n] * window[n]) * arg.cos(); | |
| 685 | + } | |
| 686 | + *o = acc as f32; | |
| 687 | + } | |
| 688 | + out | |
| 689 | + } | |
| 690 | + | |
| 691 | + fn tdac(forward: impl Fn(&[f32; 512]) -> [f32; COEFFS]) -> f32 { | |
| 692 | + let mut seed = 7u64; | |
| 693 | + let signal: Vec<f32> = (0..256 * 6).map(|_| lcg(&mut seed)).collect(); | |
| 694 | + let mut imdct = Imdct::new(); | |
| 695 | + let mut delay = [0.0f32; 256]; | |
| 696 | + let mut out = [0.0f32; 256]; | |
| 697 | + let mut worst = 0.0f32; | |
| 698 | + let (mut dot, mut nrm) = (0.0f64, 0.0f64); | |
| 699 | + for blk in 0..5 { | |
| 700 | + let mut x = [0.0f32; 512]; | |
| 701 | + x.copy_from_slice(&signal[blk * 256..blk * 256 + 512]); | |
| 702 | + let spec = forward(&x); | |
| 703 | + imdct.block(&spec, false, &mut delay, &mut out); | |
| 704 | + if blk > 0 { | |
| 705 | + // Output of block `blk` reconstructs input samples blk*256..+256. | |
| 706 | + for n in 0..256 { | |
| 707 | + worst = worst.max((out[n] - signal[blk * 256 + n]).abs()); | |
| 708 | + dot += f64::from(out[n] * signal[blk * 256 + n]); | |
| 709 | + nrm += f64::from(signal[blk * 256 + n] * signal[blk * 256 + n]); | |
| 710 | + } | |
| 711 | + } | |
| 712 | + } | |
| 713 | + assert!((dot / nrm - 1.0).abs() < 1e-4, "least-squares gain out/in = {}", dot / nrm); | |
| 714 | + worst | |
| 715 | + } | |
| 716 | + | |
| 717 | + #[test] | |
| 718 | + fn smoothed_exponents_never_rise_and_always_fit_the_group_coding() { | |
| 719 | + let mut e = [24u8; COEFFS]; | |
| 720 | + e[100] = 1; | |
| 721 | + e[0] = 20; | |
| 722 | + let ideal = e; | |
| 723 | + smooth_exps(&mut e); | |
| 724 | + assert!(e.iter().zip(&ideal).all(|(s, i)| s <= i)); | |
| 725 | + assert!(e.windows(2).all(|w| (i32::from(w[0]) - i32::from(w[1])).abs() <= 2)); | |
| 726 | + assert_eq!((e[0], e[99], e[100], e[101]), (15, 3, 1, 3)); | |
| 727 | + let mut again = e; | |
| 728 | + smooth_exps(&mut again); | |
| 729 | + assert_eq!(again, e); | |
| 730 | + } | |
| 731 | + | |
| 732 | + #[test] | |
| 733 | + fn tdac_direct_forward_reconstructs() { | |
| 734 | + let enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap(); | |
| 735 | + let window = enc.window; | |
| 736 | + // A/52's forward carries -2/N. | |
| 737 | + let err = tdac(|x| { | |
| 738 | + let mut s = direct_forward(x, &window); | |
| 739 | + for v in &mut s { | |
| 740 | + *v *= -2.0 / 512.0; | |
| 741 | + } | |
| 742 | + s | |
| 743 | + }); | |
| 744 | + assert!(err < 1e-4, "direct forward + Imdct TDAC error {err}"); | |
| 745 | + } | |
| 746 | + | |
| 747 | + #[test] | |
| 748 | + fn tdac_ec_dsp_forward_reconstructs() { | |
| 749 | + let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap(); | |
| 750 | + let window = enc.window; | |
| 751 | + let cell = std::cell::RefCell::new(&mut enc.mdct); | |
| 752 | + let err = tdac(|x| { | |
| 753 | + let mut s = [0.0f32; COEFFS]; | |
| 754 | + cell.borrow_mut().forward_windowed(x, &window, &mut s); | |
| 755 | + for v in &mut s { | |
| 756 | + *v *= FORWARD_GAIN; | |
| 757 | + } | |
| 758 | + s | |
| 759 | + }); | |
| 760 | + assert!(err < 1e-4, "ec_dsp forward + Imdct TDAC error {err}"); | |
| 761 | + } | |
| 762 | +} |
crates/ec-ac3/src/lib.rsmodified+7 -2
| @@ -10,8 +10,11 @@ | ||
| 10 | 10 | //! |
| 11 | 11 | //! Contracts worth knowing before implementing against this crate: |
| 12 | 12 | //! |
| 13 | -//! - **Decode only.** Nothing here encodes AC-3; the format is a decode-side | |
| 14 | -//! concern for this family. | |
| 13 | +//! - **Encoding is a fixed-allocation skeleton so far.** [`Ac3Encoder`] writes | |
| 14 | +//! spec-valid syncframes — real MDCT, real bit allocation, real CRCs — but | |
| 15 | +//! with a constant exponent strategy and bit allocation curve rather than a | |
| 16 | +//! psychoacoustic search; see [`encode`] for exactly what is and is not | |
| 17 | +//! adaptive yet. | |
| 15 | 18 | //! - **Truncated input is [`Error::NeedMore`]**, a broken bit stream is |
| 16 | 19 | //! [`Error::Corrupt`], and a construct this build does not implement is |
| 17 | 20 | //! [`Error::Unsupported`] naming *what* and *why*. No input panics — the bit |
| @@ -62,9 +65,11 @@ pub mod transform; | ||
| 62 | 65 | |
| 63 | 66 | mod decode; |
| 64 | 67 | mod decoder; |
| 68 | +pub mod encode; | |
| 65 | 69 | |
| 66 | 70 | pub use decode::Syntax; |
| 67 | 71 | pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options}; |
| 72 | +pub use encode::{Ac3Encoder, EncoderConfig}; | |
| 68 | 73 | pub use ec_core::Error; |
| 69 | 74 | |
| 70 | 75 | /// Samples per channel one audio block produces. |
crates/ec-ac3/tests/encode_matrix.rsadded+190 -0
| @@ -0,0 +1,190 @@ | ||
| 1 | +//! A1 skeleton coverage: the fixed-allocation encoder writes frames our own | |
| 2 | +//! decoder round-trips, and ffmpeg accepts as valid AC-3 when it is present. | |
| 3 | + | |
| 4 | +use std::path::Path; | |
| 5 | +use std::process::Command; | |
| 6 | + | |
| 7 | +use ec_ac3::{Ac3Decoder, Ac3Encoder, EncoderConfig}; | |
| 8 | + | |
| 9 | +fn have_ffmpeg() -> bool { | |
| 10 | + Command::new("ffmpeg") | |
| 11 | + .arg("-version") | |
| 12 | + .output() | |
| 13 | + .is_ok_and(|o| o.status.success()) | |
| 14 | +} | |
| 15 | + | |
| 16 | +/// 440 Hz tone for 1 s, then 0.5 s of silence, interleaved across `channels`. | |
| 17 | +fn tone_then_silence(sample_rate: u32, channels: usize) -> Vec<f32> { | |
| 18 | + let tone_samples = sample_rate as usize; | |
| 19 | + let silence_samples = sample_rate as usize / 2; | |
| 20 | + let mut out = Vec::with_capacity((tone_samples + silence_samples) * channels); | |
| 21 | + for n in 0..tone_samples { | |
| 22 | + let t = n as f32 / sample_rate as f32; | |
| 23 | + let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin(); | |
| 24 | + for _ in 0..channels { | |
| 25 | + out.push(v); | |
| 26 | + } | |
| 27 | + } | |
| 28 | + out.extend(std::iter::repeat_n(0.0f32, silence_samples * channels)); | |
| 29 | + out | |
| 30 | +} | |
| 31 | + | |
| 32 | +fn correlation(a: &[f32], b: &[f32]) -> f64 { | |
| 33 | + let n = a.len().min(b.len()); | |
| 34 | + if n == 0 { | |
| 35 | + return 0.0; | |
| 36 | + } | |
| 37 | + let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0); | |
| 38 | + for i in 0..n { | |
| 39 | + let (x, y) = (f64::from(a[i]), f64::from(b[i])); | |
| 40 | + sa += x; | |
| 41 | + sb += y; | |
| 42 | + saa += x * x; | |
| 43 | + sbb += y * y; | |
| 44 | + sab += x * y; | |
| 45 | + } | |
| 46 | + let n = n as f64; | |
| 47 | + let cov = sab / n - (sa / n) * (sb / n); | |
| 48 | + let va = (saa / n - (sa / n).powi(2)).max(0.0); | |
| 49 | + let vb = (sbb / n - (sb / n).powi(2)).max(0.0); | |
| 50 | + if va <= 0.0 || vb <= 0.0 { | |
| 51 | + return 1.0; // both flat (silence): trivially aligned | |
| 52 | + } | |
| 53 | + cov / (va.sqrt() * vb.sqrt()) | |
| 54 | +} | |
| 55 | + | |
| 56 | +/// Lag-searched correlation on one channel, +/- 64 samples: the encoder's | |
| 57 | +/// analysis window and the decoder's overlap-add each carry their own group | |
| 58 | +/// delay. | |
| 59 | +fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 { | |
| 60 | + let mut best = -1.0f64; | |
| 61 | + for lag in -64i32..=64 { | |
| 62 | + let (sa, sb): (&[f32], &[f32]) = if lag >= 0 { | |
| 63 | + (&a[lag as usize..], b) | |
| 64 | + } else { | |
| 65 | + (a, &b[(-lag) as usize..]) | |
| 66 | + }; | |
| 67 | + best = best.max(correlation(sa, sb)); | |
| 68 | + } | |
| 69 | + best | |
| 70 | +} | |
| 71 | + | |
| 72 | +/// Deinterleave channel `ch` of `channels`. | |
| 73 | +fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec<f32> { | |
| 74 | + interleaved | |
| 75 | + .iter() | |
| 76 | + .skip(ch) | |
| 77 | + .step_by(channels) | |
| 78 | + .copied() | |
| 79 | + .collect() | |
| 80 | +} | |
| 81 | + | |
| 82 | +fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec<u8> { | |
| 83 | + let mut enc = Ac3Encoder::new(config).unwrap(); | |
| 84 | + enc.push_pcm_f32(pcm).unwrap(); | |
| 85 | + enc.finish(); | |
| 86 | + let mut out = Vec::new(); | |
| 87 | + loop { | |
| 88 | + match enc.next_packet() { | |
| 89 | + Ok(frame) => out.extend_from_slice(&frame), | |
| 90 | + Err(e) if e.is_eof() => break, | |
| 91 | + Err(e) => panic!("{e}"), | |
| 92 | + } | |
| 93 | + } | |
| 94 | + out | |
| 95 | +} | |
| 96 | + | |
| 97 | +fn decode_all(data: &[u8], channels: usize) -> Vec<f32> { | |
| 98 | + let mut decoder = Ac3Decoder::new(); | |
| 99 | + let mut out = Vec::new(); | |
| 100 | + let mut pos = 0; | |
| 101 | + while pos + 6 <= data.len() { | |
| 102 | + let size = ec_ac3::frame_size(&data[pos..]).unwrap(); | |
| 103 | + assert!(pos + size <= data.len(), "frame overruns the stream"); | |
| 104 | + let frame = decoder | |
| 105 | + .decode_frame(&data[pos..pos + size]) | |
| 106 | + .unwrap_or_else(|e| panic!("frame at byte {pos}: {e}")); | |
| 107 | + assert_eq!(frame.samples, 1536); | |
| 108 | + assert_eq!(frame.channels(), channels); | |
| 109 | + out.extend( | |
| 110 | + frame.data[0] | |
| 111 | + .chunks_exact(4) | |
| 112 | + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), | |
| 113 | + ); | |
| 114 | + pos += size; | |
| 115 | + } | |
| 116 | + out | |
| 117 | +} | |
| 118 | + | |
| 119 | +#[test] | |
| 120 | +fn silence_and_tone_frames_decode_in_our_decoder() { | |
| 121 | + for &(sample_rate, channels) in &[(48_000u32, 1u16), (48_000, 2), (48_000, 6), (44_100, 2)] { | |
| 122 | + let config = EncoderConfig { | |
| 123 | + sample_rate, | |
| 124 | + channels, | |
| 125 | + bitrate_kbps: if channels >= 5 { 384 } else { 192 }, | |
| 126 | + }; | |
| 127 | + let pcm = tone_then_silence(sample_rate, channels as usize); | |
| 128 | + let data = encode(config, &pcm); | |
| 129 | + assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames"); | |
| 130 | + let decoded = decode_all(&data, channels as usize); | |
| 131 | + assert!(!decoded.is_empty()); | |
| 132 | + for ch in 0..channels as usize { | |
| 133 | + let want = take_channel(&pcm, channels as usize, ch); | |
| 134 | + let got = take_channel(&decoded, channels as usize, ch); | |
| 135 | + let corr = best_lag_correlation(&want, &got); | |
| 136 | + assert!( | |
| 137 | + corr >= 0.95, | |
| 138 | + "{sample_rate} Hz {channels}ch channel {ch}: corr {corr}" | |
| 139 | + ); | |
| 140 | + } | |
| 141 | + } | |
| 142 | +} | |
| 143 | + | |
| 144 | +#[test] | |
| 145 | +fn oracle_accepts_our_frames() { | |
| 146 | + if !have_ffmpeg() { | |
| 147 | + eprintln!("skipping: ffmpeg not found"); | |
| 148 | + return; | |
| 149 | + } | |
| 150 | + let config = EncoderConfig { | |
| 151 | + sample_rate: 48_000, | |
| 152 | + channels: 2, | |
| 153 | + bitrate_kbps: 192, | |
| 154 | + }; | |
| 155 | + let pcm = tone_then_silence(48_000, 2); | |
| 156 | + let data = encode(config, &pcm); | |
| 157 | + let dir = std::env::temp_dir(); | |
| 158 | + let path = dir.join("ec_ac3_encode_matrix_oracle.ac3"); | |
| 159 | + std::fs::write(&path, &data).unwrap(); | |
| 160 | + | |
| 161 | + let out = Command::new("ffmpeg") | |
| 162 | + .args(["-v", "warning", "-i"]) | |
| 163 | + .arg(&path) | |
| 164 | + .args(["-f", "f32le", "-"]) | |
| 165 | + .output() | |
| 166 | + .expect("ffmpeg"); | |
| 167 | + let stderr = String::from_utf8_lossy(&out.stderr); | |
| 168 | + let complaint = stderr | |
| 169 | + .lines() | |
| 170 | + .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k))); | |
| 171 | + assert!( | |
| 172 | + !complaint, | |
| 173 | + "ffmpeg complained about our frames:\n{stderr}" | |
| 174 | + ); | |
| 175 | + | |
| 176 | + let decoded: Vec<f32> = out | |
| 177 | + .stdout | |
| 178 | + .chunks_exact(4) | |
| 179 | + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| 180 | + .collect(); | |
| 181 | + for ch in 0..2 { | |
| 182 | + let want = take_channel(&pcm, 2, ch); | |
| 183 | + let got = take_channel(&decoded, 2, ch); | |
| 184 | + let corr = best_lag_correlation(&want, &got); | |
| 185 | + assert!(corr >= 0.95, "oracle channel {ch} corr {corr}"); | |
| 186 | + } | |
| 187 | + | |
| 188 | + let _ = std::fs::remove_file(Path::new(&path)); | |
| 189 | +} | |
| 190 | + |