forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

encode.rs1130 lines, 45.2 KiBHistoryRawDownload
1//! An AC-3 encoder: PCM in, spec-valid ATSC A/52 syncframes out.
2//!
3//! The bitstream writer mirrors the parser's normative order (`syncinfo()`,
4//! `bsi()`, six `audblk()`s, `auxdata`/CRC). Per block and channel a transient
5//! detector picks the long or the block-switched short transform, an exponent
6//! planner picks D15/D25/D45/reuse ([`Ac3Encoder::plan`]), and a rate loop
7//! binary-searches the SNR offsets so the frame fills its fixed size
8//! ([`Ac3Encoder::encode_frame`]). The bit allocation parameters themselves
9//! are constants and `crate::bitalloc::compute` is the single source of truth
10//! for what each mantissa gets.
11//!
12//! No coupling, no rematrixing, no delta bit allocation, no AHT: all of that
13//! is legal to leave off (every presence bit for them is simply sent as 0),
14//! and all of it is future work rather than a correctness gap in what is
15//! implemented here.
16
17use ec_core::{
18 AudioParameters, BitWriter, Buf, ChannelLayout, CodecId, CodecParameters, Encoder, Error,
19 Frame, MediaParameters, Packet, Result, SampleFormat, TimeBase,
20};
21use ec_dsp::Mdct;
22
23use crate::bitalloc::{self, Allocation, BitAllocParams, Channel};
24use crate::bsi::Acmod;
25use crate::exps::Strategy;
26use crate::transform::Imdct;
27use crate::tables::{BIT_RATE_KBPS, FRAME_SIZE_WORDS, QNTZTAB, QUANT_LEVELS, SAMPLE_RATE, WINDOW};
28
29/// Samples per channel one syncframe codes.
30const FRAME_SAMPLES: usize = 1536;
31/// Blocks per syncframe.
32const BLOCKS: usize = 6;
33/// Coefficients per channel per block ([`crate::decode::COEFFS`], not public).
34const COEFFS: usize = 256;
35/// Lowest bit rate per coded channel this encoder accepts: below it the
36/// side information of the cheapest legal frame no longer fits (see
37/// [`Ac3Encoder::encode_frame`]); [`Ac3Encoder::new`] raises the request to it.
38const MIN_KBPS_PER_CHANNEL: u32 = 32;
39/// Bit allocation parameters (§7.2.2.3), constant for every frame.
40const BA_PARAMS: BitAllocParams = BitAllocParams { sdcycod: 2, fdcycod: 1, sgaincod: 1, dbpbcod: 2, floorcod: 7 };
41/// Fast gain code, constant for every channel and frame.
42const FGAINCOD: u8 = 4;
43/// [`envelope_moved`]: exponent steps (6 dB each) a band's peak may drift
44/// before the block re-sends exponents.
45const RESEND_STEPS: u8 = 2;
46/// [`is_transient`]: a segment this many times louder than everything before it.
47const TRANSIENT_RATIO: f32 = 8.0;
48/// [`is_transient`]: segment energy (64 high-passed samples) below which
49/// nothing is an attack.
50const TRANSIENT_FLOOR: f32 = 1e-2;
51/// LFE `endmant`, fixed by the standard.
52const LFE_ENDMANT: usize = 7;
53/// Scale from `ec_dsp::Mdct::forward_windowed`'s raw sum (which equals the
54/// plain A/52 §7.9.4 cosine sum) to the coefficients `crate::transform::Imdct`
55/// expects: the standard's `-2/N` (N = 512) forward normalisation, with its
56/// `2.0x` on the way back being the decoder's own half of that pair.
57const FORWARD_GAIN: f32 = -2.0 / 512.0;
58/// Scale from the transpose of the decoder's short inverse to the
59/// coefficients it expects back; measured in `tests::tdac_short_*`.
60const SHORT_GAIN: f32 = 1.0 / 128.0;
61
62/// How the encoder is set up.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct EncoderConfig {
65 /// Sample rate in Hz: 48000, 44100 or 32000.
66 pub sample_rate: u32,
67 /// Channel count, 1 to 6 (6 is 3/2 + LFE).
68 pub channels: u16,
69 /// Target bit rate in kbit/s, snapped to the nearest legal A/52 rate.
70 pub bitrate_kbps: u32,
71}
72
73/// The coded-channel order this encoder writes to the bit stream, alongside
74/// which "family" (public, L/R/C/LFE/Ls/Rs) slot each one reads its PCM from.
75///
76/// Mirrors `decode::Core::channel_order` (decode.rs:737-754) exactly, so a
77/// frame encoded from family-order PCM and decoded back comes out in the same
78/// family order it went in. `None` marks the LFE slot.
79fn channel_order(acmod: Acmod, nfchans: usize, lfeon: bool) -> Vec<Option<usize>> {
80 let mut order: Vec<Option<usize>> = match acmod {
81 Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => {
82 let mut v = vec![Some(0), Some(2), Some(1)];
83 v.extend((3..nfchans).map(Some));
84 v
85 }
86 _ => (0..nfchans).map(Some).collect(),
87 };
88 if lfeon {
89 let fronts = match acmod {
90 Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3,
91 Acmod::Mono => 1,
92 _ => 2,
93 };
94 order.insert(fronts.min(order.len()), None);
95 }
96 order
97}
98
99/// Acmod and LFE presence for a channel count, 1..=6.
100fn acmod_for(channels: u16) -> Result<(Acmod, bool)> {
101 Ok(match channels {
102 1 => (Acmod::Mono, false),
103 2 => (Acmod::Stereo, false),
104 3 => (Acmod::Surround3_0, false),
105 4 => (Acmod::Surround2_2, false),
106 5 => (Acmod::Surround3_2, false),
107 6 => (Acmod::Surround3_2, true),
108 other => {
109 return Err(Error::unsupported(
110 format!("{other} channels"),
111 "this encoder codes 1 to 6 channels (6 is 3/2 + LFE)",
112 ));
113 }
114 })
115}
116
117/// CRC-16, poly `x^16 + x^15 + x^2 + 1` (0x8005), MSB first, as A/52 §7.10
118/// states it: the bit-serial form, not a reflected table.
119fn crc16(data: &[u8]) -> u16 {
120 let mut crc: u16 = 0;
121 for &byte in data {
122 crc ^= (byte as u16) << 8;
123 for _ in 0..8 {
124 crc = if crc & 0x8000 != 0 {
125 (crc << 1) ^ 0x8005
126 } else {
127 crc << 1
128 };
129 }
130 }
131 crc
132}
133
134/// The reconstruction-level index closest to `value` for an `levels`-level
135/// symmetric quantizer — the forward of [`crate::tables::symmetric_level`].
136fn quantize_index(levels: u32, value: f32) -> u32 {
137 let k = ((value * levels as f32 + (levels as f32 - 1.0)) / 2.0).round();
138 k.clamp(0.0, (levels - 1) as f32) as u32
139}
140
141/// Writes a block's mantissas in stream order. The grouped quantizers (bap
142/// 1, 2, 4) are the subtle part: [`crate::mantissa::Mantissas`] reads a whole
143/// group's code word at the *first* of its 3 (or 2) values and the later
144/// members consume nothing, with the group running on across channels
145/// (§7.3.5). So the code word has to be emitted where the first member sits,
146/// which means looking ahead past whatever other-bap mantissas lie in between
147/// for the group's remaining members. A group the block ends partway through
148/// is padded with its midpoint (zero); the decoder never reads the padding.
149fn write_mantissas(w: &mut BitWriter, values: &[(u8, f32)]) {
150 let mut left = [0usize; 16];
151 for (i, &(bap, value)) in values.iter().enumerate() {
152 let (levels, bits, size, radix) = match bap {
153 0 => continue,
154 1 => (QUANT_LEVELS[1], 5, 3, 3),
155 2 => (QUANT_LEVELS[2], 7, 3, 5),
156 4 => (QUANT_LEVELS[4], 7, 2, 11),
157 3 | 5 => {
158 let bits = QNTZTAB[bap as usize];
159 w.write_bits(quantize_index(QUANT_LEVELS[bap as usize], value), bits);
160 continue;
161 }
162 _ => {
163 // 6..=15: asymmetric two's complement (§7.3.2).
164 let bits = QNTZTAB[(bap as usize).min(15)];
165 let scale = (1u32 << (bits - 1)) as f32;
166 let signed = (value * scale).round().clamp(-scale, scale - 1.0) as i32;
167 w.write_signed(signed, bits);
168 continue;
169 }
170 };
171 if left[bap as usize] == 0 {
172 let mut code = 0u32;
173 let mut members = values[i..].iter().filter(|v| v.0 == bap).map(|v| quantize_index(levels, v.1));
174 for _ in 0..size {
175 code = code * radix + members.next().unwrap_or((levels - 1) / 2);
176 }
177 w.write_bits(code, bits);
178 left[bap as usize] = size;
179 }
180 left[bap as usize] -= 1;
181 }
182}
183
184/// Fits an ideal exponent envelope to what the group-diff coding can carry
185/// (each step moves the running exponent by at most 2, and the first bin's
186/// absolute exponent has 4 bits), only ever *lowering* exponents to get
187/// there: a lower exponent than ideal costs mantissa precision, a higher one
188/// clips the mantissa at full scale and loses the coefficient — which is
189/// exactly what a one-directional "walk toward the ideal" does on the rising
190/// edge of a spectral peak. A backward then a forward min-pass make every
191/// neighbouring difference fit, so [`write_exp_groups`]' clamp is then a no-op
192/// and the decoder sees precisely this array.
193fn smooth_exps(exps: &mut [u8]) {
194 exps[0] = exps[0].min(15);
195 for i in (0..exps.len() - 1).rev() {
196 exps[i] = exps[i].min(exps[i + 1] + 2);
197 }
198 for i in 1..exps.len() {
199 exps[i] = exps[i].min(exps[i - 1] + 2);
200 }
201}
202
203/// Writes an exponent set as [`plan_exponents`] produced it: the 4-bit
204/// absolute exponent, then 7-bit groups of three differentials. `sent` has
205/// already been through [`smooth_exps`], so every differential is within ±2
206/// and the decoder reconstructs precisely these values.
207fn write_exp_groups(w: &mut BitWriter, sent: &[u8]) {
208 w.write_bits(u32::from(sent[0]), 4);
209 let mut prev = i32::from(sent[0]);
210 for grp in sent[1..].as_chunks::<3>().0 {
211 let mut code = 0u32;
212 for &v in grp {
213 let diff = i32::from(v) - prev;
214 debug_assert!((-2..=2).contains(&diff));
215 code = code * 5 + (diff + 2) as u32;
216 prev = i32::from(v);
217 }
218 w.write_bits(code, 7);
219 }
220}
221
222/// PCM in, AC-3 syncframes out.
223pub struct Ac3Encoder {
224 config: EncoderConfig,
225 params: CodecParameters,
226 acmod: Acmod,
227 lfeon: bool,
228 nfchans: usize,
229 /// Coded channels, LFE included when present; index `nfchans` is the LFE
230 /// slot whenever `lfeon`.
231 coded: usize,
232 fscod: usize,
233 frmsizecod: u8,
234 frame_bytes: usize,
235 order: Vec<Option<usize>>,
236 mdct: Mdct<f32>,
237 window: [f32; 512],
238 /// The decoder's short (block-switched) inverse as a matrix, 512 samples
239 /// per coefficient, row-major by coefficient — the forward short
240 /// transform is its transpose ([`Ac3Encoder::forward_short`]).
241 short_basis: Vec<f32>,
242 chbwcod: u32,
243 fbw_endmant: usize,
244 stats: EncodeStats,
245 /// Previous block's tail, per coded channel — the MDCT's 50% overlap.
246 history: Vec<[f32; COEFFS]>,
247 pcm: Vec<f32>,
248 packets: std::collections::VecDeque<Vec<u8>>,
249 finished: bool,
250}
251
252impl Ac3Encoder {
253 /// An encoder for this configuration.
254 pub fn new(config: EncoderConfig) -> Result<Ac3Encoder> {
255 let (acmod, lfeon) = acmod_for(config.channels)?;
256 let nfchans = acmod.nfchans();
257 let coded = nfchans + usize::from(lfeon);
258 let fscod = SAMPLE_RATE[..3]
259 .iter()
260 .position(|&r| r == config.sample_rate)
261 .ok_or_else(|| {
262 Error::unsupported(
263 format!("{} Hz", config.sample_rate),
264 "AC-3 codes 48000, 44100 or 32000 Hz",
265 )
266 })?;
267 let kbps = config.bitrate_kbps.max(MIN_KBPS_PER_CHANNEL * coded as u32);
268 let idx = BIT_RATE_KBPS
269 .iter()
270 .enumerate()
271 .min_by_key(|&(_, &k)| k.abs_diff(kbps))
272 .map(|(i, _)| i)
273 .unwrap_or(0);
274 let frmsizecod = (idx * 2) as u8;
275 let frame_bytes = usize::from(FRAME_SIZE_WORDS[frmsizecod as usize][fscod]) * 2;
276
277 let mut window = [0.0f32; 512];
278 for i in 0..256 {
279 window[i] = WINDOW[i];
280 window[511 - i] = WINDOW[i];
281 }
282
283 let mut imdct = Imdct::new();
284 let mut short_basis = vec![0.0f32; COEFFS * 512];
285 for k in 0..COEFFS {
286 let mut spec = [0.0f32; COEFFS];
287 spec[k] = 1.0;
288 let (mut delay, mut out) = ([0.0f32; 256], [0.0f32; 256]);
289 imdct.block(&spec, true, &mut delay, &mut out);
290 let row = &mut short_basis[k * 512..(k + 1) * 512];
291 for n in 0..256 {
292 row[n] = out[n] / 2.0; // `block` doubles its first half
293 row[256 + n] = delay[n];
294 }
295 }
296 let chbwcod = chbwcod_for(BIT_RATE_KBPS[idx], nfchans);
297
298 let mut params = CodecParameters::new(CodecId::Ac3);
299 params.media = MediaParameters::Audio(AudioParameters {
300 sample_rate: config.sample_rate,
301 layout: ChannelLayout::from_count(coded),
302 format: Some(SampleFormat::F32),
303 bits_per_sample: None,
304 });
305
306 Ok(Ac3Encoder {
307 order: channel_order(acmod, nfchans, lfeon),
308 config,
309 params,
310 acmod,
311 lfeon,
312 nfchans,
313 coded,
314 fscod,
315 frmsizecod,
316 frame_bytes,
317 mdct: Mdct::new(512),
318 window,
319 short_basis,
320 chbwcod,
321 fbw_endmant: (chbwcod as usize + 12) * 3 + 37,
322 stats: EncodeStats::default(),
323 history: vec![[0.0; COEFFS]; coded],
324 pcm: Vec::new(),
325 packets: std::collections::VecDeque::new(),
326 finished: false,
327 })
328 }
329
330 /// Codec parameters this encoder declares.
331 pub fn codec_parameters(&self) -> &CodecParameters {
332 &self.params
333 }
334
335 /// Samples this encoder emits before the first audible one: half a
336 /// window (one block), always, because the very first block has no
337 /// previous block to overlap-add against and is pure priming. A muxer
338 /// writing this track's `elst`/`CodecDelay` states it here.
339 pub fn encoder_delay(&self) -> usize {
340 COEFFS
341 }
342
343 /// Coding decisions summed over every frame so far.
344 pub fn stats(&self) -> EncodeStats {
345 self.stats
346 }
347
348 /// Feeds interleaved `f32` PCM, family order (L, R, C, LFE, Ls, Rs — the
349 /// same order [`crate::Ac3Decoder`] hands frames out in).
350 pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> {
351 self.pcm.extend_from_slice(interleaved);
352 self.drain();
353 Ok(())
354 }
355
356 /// Ends the stream: pushes the last block's samples out of the overlap
357 /// (see [`Ac3Encoder::encoder_delay`]), pads the tail to a whole frame
358 /// and flushes it.
359 pub fn finish(&mut self) {
360 let need = FRAME_SAMPLES * self.coded;
361 if !self.pcm.is_empty() || self.stats.frames > 0 {
362 self.pcm.resize(self.pcm.len() + COEFFS * self.coded, 0.0);
363 let padded = self.pcm.len().div_ceil(need) * need;
364 self.pcm.resize(padded, 0.0);
365 }
366 self.drain();
367 self.finished = true;
368 }
369
370 fn drain(&mut self) {
371 let need = FRAME_SAMPLES * self.coded;
372 let rest = self.pcm.split_off(self.pcm.len() / need * need);
373 let full = std::mem::replace(&mut self.pcm, rest);
374 for block in full.chunks_exact(need) {
375 let packet = self.encode_frame(block);
376 self.packets.push_back(packet);
377 }
378 }
379
380 /// The next encoded syncframe; [`Error::Eof`] once drained after
381 /// [`Ac3Encoder::finish`], [`Error::NeedMore`] before that.
382 pub fn next_packet(&mut self) -> Result<Vec<u8>> {
383 match self.packets.pop_front() {
384 Some(p) => Ok(p),
385 None if self.finished => Err(Error::Eof),
386 None => Err(Error::NeedMore),
387 }
388 }
389
390 /// One syncframe from `interleaved` (family-order PCM, `coded` channels *
391 /// [`FRAME_SAMPLES`] samples).
392 fn encode_frame(&mut self, interleaved: &[f32]) -> Vec<u8> {
393 // Deinterleave into coded-channel order, pick long or short transform
394 // per block from the transient detector, and run the MDCT.
395 let mut coeffs = vec![vec![[0.0f32; COEFFS]; self.coded]; BLOCKS];
396 let mut blksw = vec![vec![false; self.coded]; BLOCKS];
397 for ch in 0..self.coded {
398 let slot = if ch < self.nfchans {
399 self.order.iter().position(|&s| s == Some(ch)).unwrap()
400 } else {
401 self.order.iter().position(|&s| s.is_none()).unwrap()
402 };
403 for blk in 0..BLOCKS {
404 let mut window_in = [0.0f32; 512];
405 window_in[..256].copy_from_slice(&self.history[ch]);
406 for n in 0..256 {
407 window_in[256 + n] = interleaved[(blk * 256 + n) * self.coded + slot];
408 }
409 // The LFE has no blksw bit in the stream.
410 let short = ch < self.nfchans && is_transient(&window_in);
411 blksw[blk][ch] = short;
412 let mut spectrum = [0.0f32; COEFFS];
413 if short {
414 self.forward_short(&window_in, &mut spectrum);
415 } else {
416 self.mdct
417 .forward_windowed(&window_in, &self.window, &mut spectrum);
418 for v in &mut spectrum {
419 // Measured in `tests::tdac_*`: this makes the forward the
420 // exact adjoint of the decoder's transform.rs IMDCT.
421 *v *= FORWARD_GAIN;
422 }
423 }
424 self.history[ch].copy_from_slice(&window_in[256..]);
425 coeffs[blk][ch] = spectrum;
426 }
427 }
428
429 let endmant: Vec<usize> = (0..self.coded)
430 .map(|ch| if ch < self.nfchans { self.fbw_endmant } else { LFE_ENDMANT })
431 .collect();
432 let budget_bits = self.frame_bytes as u64 * 8 - 2 /* auxdataflag, crcrsv */ - 16 /* crc2 */;
433
434 // Rate loop: the exponent plan fixes the side information, then the
435 // largest csnroffst (and, at that csnroffst, the largest fsnroffst)
436 // whose mantissas still fit is found by binary search — both are
437 // monotone in bits spent. A plan whose side information alone does
438 // not fit (a frame of strategy churn at a low bit rate) is replaced
439 // by the conservative one: a single D45 envelope for the whole frame.
440 let mut chosen: Option<(BitWriter, Plan, u8)> = None;
441 for conservative in [false, true] {
442 let plan = self.plan(&coeffs, &blksw, &endmant, conservative);
443 let fits = |c: u8, f: u8| {
444 let bap = self.allocate(&plan, &endmant, c, f);
445 let w = self.write_frame(&coeffs, &plan, &endmant, &bap, c, f);
446 (w.bit_len() <= budget_bits).then_some(w)
447 };
448 if fits(0, 0).is_none() {
449 continue;
450 }
451 let (mut lo, mut hi) = (0u8, 63u8);
452 while lo < hi {
453 let mid = (lo + hi).div_ceil(2);
454 if fits(mid, 0).is_some() { lo = mid } else { hi = mid - 1 }
455 }
456 let c = lo;
457 let (mut lo, mut hi) = (0u8, 15u8);
458 while lo < hi {
459 let mid = (lo + hi).div_ceil(2);
460 if fits(c, mid).is_some() { lo = mid } else { hi = mid - 1 }
461 }
462 chosen = Some((fits(c, lo).unwrap(), plan, c));
463 break;
464 }
465 let (w, plan, csnroffst) = chosen.unwrap_or_else(|| {
466 // corner-cut: unreachable with the 32 kbps/channel floor `new`
467 // applies (the conservative plan's side info is ~150 bits per
468 // channel per frame); below that the frame would be truncated.
469 // Upgrade path: drop chbwcod until it fits.
470 debug_assert!(false, "side information does not fit the frame");
471 let plan = self.plan(&coeffs, &blksw, &endmant, true);
472 let bap = self.allocate(&plan, &endmant, 0, 0);
473 (self.write_frame(&coeffs, &plan, &endmant, &bap, 0, 0), plan, 0)
474 });
475
476 self.stats.frames += 1;
477 self.stats.csnroffst_sum += u64::from(csnroffst);
478 self.stats.bits_used += w.bit_len();
479 self.stats.bits_budget += budget_bits;
480 for blk in 0..BLOCKS {
481 for ch in 0..self.nfchans {
482 self.stats.blksw_blocks += u64::from(blksw[blk][ch]);
483 match plan.strategy[blk][ch] {
484 Strategy::Reuse => self.stats.reuse += 1,
485 Strategy::D15 => self.stats.d15 += 1,
486 Strategy::D25 => self.stats.d25 += 1,
487 Strategy::D45 => self.stats.d45 += 1,
488 }
489 }
490 }
491 self.finish_frame(w)
492 }
493
494 /// The two 256-point transforms of a block-switched block (§7.9.4.2), as
495 /// the transpose of the decoder's own short inverse (`short_basis`), so
496 /// the pair is TDAC-exact by construction — see `tests::tdac_short_*`.
497 fn forward_short(&self, window_in: &[f32; 512], spectrum: &mut [f32; COEFFS]) {
498 for (k, out) in spectrum.iter_mut().enumerate() {
499 let row = &self.short_basis[k * 512..(k + 1) * 512];
500 *out = SHORT_GAIN * row.iter().zip(window_in).map(|(a, b)| a * b).sum::<f32>();
501 }
502 }
503
504 /// Exponent strategy and exponents for every block and channel.
505 ///
506 /// Block 0 always sends. A later block re-sends when its block switch
507 /// flag changed or its envelope moved ([`envelope_moved`]) since the last
508 /// send; otherwise it reuses. Each run of
509 /// blocks sharing one set codes the run's loudest magnitude per bin, so no
510 /// block's mantissa is asked for more than its exponent's headroom. The
511 /// sending block uses D15 for the LFE channel, D25 when block-switched
512 /// (the short transform's interleaved halves make D15's per-bin cost too
513 /// high — see the D25-vs-D15 note below), D45 for a run of 3+ blocks
514 /// (stationary), D25 otherwise. `conservative` forces one D45 set per
515 /// channel for the whole frame: the cheapest legal side information.
516 fn plan(&self, coeffs: &[Vec<[f32; COEFFS]>], blksw: &[Vec<bool>], endmant: &[usize], conservative: bool) -> Plan {
517 let ideal: Vec<Vec<[u8; COEFFS]>> = coeffs
518 .iter()
519 .map(|blk| (0..self.coded).map(|ch| ideal_exps(&blk[ch], endmant[ch])).collect())
520 .collect();
521 let mut plan = Plan {
522 blksw: blksw.to_vec(),
523 strategy: vec![vec![Strategy::Reuse; self.coded]; BLOCKS],
524 sent: vec![vec![Vec::new(); self.coded]; BLOCKS],
525 exps: vec![vec![[24u8; COEFFS]; self.coded]; BLOCKS],
526 };
527 for ch in 0..self.coded {
528 let mut starts = vec![0usize];
529 if !conservative {
530 for blk in 1..BLOCKS {
531 let last = *starts.last().unwrap();
532 if blksw[blk][ch] != blksw[blk - 1][ch]
533 || envelope_moved(&ideal[blk][ch], &ideal[last][ch], endmant[ch])
534 {
535 starts.push(blk);
536 }
537 }
538 }
539 for (i, &start) in starts.iter().enumerate() {
540 let end = starts.get(i + 1).copied().unwrap_or(BLOCKS);
541 let mut env = ideal[start][ch];
542 for blk in start + 1..end {
543 for bin in 0..endmant[ch] {
544 env[bin] = env[bin].min(ideal[blk][ch][bin]);
545 }
546 }
547 let strategy = if ch >= self.nfchans {
548 Strategy::D15
549 } else if blksw[start][ch] {
550 // The short halves interleave, so pairs (X1[k], X2[k])
551 // share one exponent: the louder half's. D15 would
552 // follow the alternation exactly but at 592 bits per
553 // send — more than a block's whole budget at 96 kbps per
554 // channel — against D25's 298.
555 Strategy::D25
556 } else if conservative || end - start >= 3 {
557 Strategy::D45
558 } else {
559 Strategy::D25
560 };
561 let (sent, exps) = plan_exponents(&env, endmant[ch], strategy);
562 plan.strategy[start][ch] = strategy;
563 plan.sent[start][ch] = sent;
564 for blk in start..end {
565 plan.exps[blk][ch] = exps;
566 }
567 }
568 }
569 plan
570 }
571
572 /// Bit allocation for every block and coded channel at one SNR offset.
573 fn allocate(&self, plan: &Plan, endmant: &[usize], csnroffst: u8, fsnroffst: u8) -> Vec<Vec<[u8; COEFFS]>> {
574 let snroffset = (((i32::from(csnroffst) - 15) << 4) + i32::from(fsnroffst)) << 2;
575 // §7.2.2.1.1: all-zero SNR offsets mean no mantissa bits at all —
576 // the decoder short-circuits there instead of running the model.
577 if csnroffst == 0 && fsnroffst == 0 {
578 return vec![vec![[0u8; COEFFS]; self.coded]; BLOCKS];
579 }
580 let mut out: Vec<Vec<[u8; COEFFS]>> = Vec::with_capacity(BLOCKS);
581 for blk in 0..BLOCKS {
582 let baps = (0..self.coded)
583 .map(|ch| {
584 if blk > 0 && plan.strategy[blk][ch] == Strategy::Reuse {
585 return out[blk - 1][ch];
586 }
587 let kind = if ch < self.nfchans { Channel::Fbw } else { Channel::Lfe };
588 let alloc = Allocation {
589 fscod: self.fscod,
590 params: BA_PARAMS,
591 range: (0, endmant[ch]),
592 fgaincod: FGAINCOD,
593 snroffset,
594 kind,
595 dba: None,
596 high_efficiency: false,
597 };
598 let mut bap = [0u8; COEFFS];
599 bitalloc::compute(&alloc, &plan.exps[blk][ch], &mut bap);
600 bap
601 })
602 .collect();
603 out.push(baps);
604 }
605 out
606 }
607
608 /// Writes syncinfo, bsi and the six audblks; mantissas and their bit cost
609 /// come from `coeffs`, `plan` and `bap` (all already computed for this
610 /// frame). Everything up to the crc/padding tail this function leaves for
611 /// [`Ac3Encoder::finish_frame`], so the rate loop in
612 /// [`Ac3Encoder::encode_frame`] can measure a candidate's length before
613 /// paying for that.
614 fn write_frame(
615 &self,
616 coeffs: &[Vec<[f32; COEFFS]>],
617 plan: &Plan,
618 endmant: &[usize],
619 bap: &[Vec<[u8; COEFFS]>],
620 csnroffst: u8,
621 fsnroffst: u8,
622 ) -> BitWriter {
623 let mut w = BitWriter::with_capacity(self.frame_bytes);
624
625 // syncinfo(): crc1 is patched into the bytes afterwards.
626 w.write_bits(0x0B77, 16);
627 w.write_bits(0, 16);
628 w.write_bits(self.fscod as u32, 2);
629 w.write_bits(u32::from(self.frmsizecod), 6);
630
631 // bsi()
632 w.write_bits(8, 5); // bsid
633 w.write_bits(0, 3); // bsmod
634 w.write_bits(u32::from(self.acmod.code()), 3);
635 if self.acmod.code() & 1 != 0 && self.acmod.code() != 1 {
636 w.write_bits(1, 2); // cmixlev
637 }
638 if self.acmod.code() & 4 != 0 {
639 w.write_bits(1, 2); // surmixlev
640 }
641 if self.acmod == Acmod::Stereo {
642 w.write_bits(0, 2); // dsurmod
643 }
644 w.write_bit(self.lfeon);
645 w.write_bits(31, 5); // dialnorm
646 w.write_bit(false); // compr
647 w.write_bit(false); // langcod
648 w.write_bit(false); // mixlevel/roomtyp
649 w.write_bit(false); // copyrightb
650 w.write_bit(false); // origbs
651 w.write_bit(false); // timecod1
652 w.write_bit(false); // timecod2
653 w.write_bit(false); // addbsi
654
655 for blk in 0..BLOCKS {
656 self.write_block(&mut w, blk, coeffs, plan, endmant, bap, csnroffst, fsnroffst);
657 }
658 w
659 }
660
661 #[allow(clippy::too_many_arguments)]
662 fn write_block(
663 &self,
664 w: &mut BitWriter,
665 blk: usize,
666 coeffs: &[Vec<[f32; COEFFS]>],
667 plan: &Plan,
668 endmant: &[usize],
669 bap: &[Vec<[u8; COEFFS]>],
670 csnroffst: u8,
671 fsnroffst: u8,
672 ) {
673 let first = blk == 0;
674 for ch in 0..self.nfchans {
675 w.write_bit(plan.blksw[blk][ch]);
676 }
677 for _ in 0..self.nfchans {
678 w.write_bit(false); // dithflag
679 }
680 w.write_bit(false); // dynrnge
681 w.write_bit(first); // cplstre: block 0 must declare a strategy
682 if first {
683 w.write_bit(false); // cplinu: no coupling
684 }
685 if self.acmod == Acmod::Stereo {
686 w.write_bit(false); // rematstr (no rematrixing)
687 }
688 for ch in 0..self.nfchans {
689 w.write_bits(strategy_code(plan.strategy[blk][ch]), 2); // chexpstr
690 }
691 if self.lfeon {
692 w.write_bit(plan.strategy[blk][self.nfchans] != Strategy::Reuse); // lfeexpstr
693 }
694 for ch in 0..self.nfchans {
695 if plan.strategy[blk][ch] != Strategy::Reuse {
696 w.write_bits(self.chbwcod, 6);
697 }
698 }
699 for ch in 0..self.nfchans {
700 if plan.strategy[blk][ch] != Strategy::Reuse {
701 write_exp_groups(w, &plan.sent[blk][ch]);
702 w.write_bits(0, 2); // gainrng
703 }
704 }
705 if self.lfeon && plan.strategy[blk][self.nfchans] != Strategy::Reuse {
706 write_exp_groups(w, &plan.sent[blk][self.nfchans]);
707 }
708 // The allocation parameters and SNR offsets are constant across the
709 // frame, so they go once, in block 0 (where they are mandatory); the
710 // decoder carries them forward through blocks 1-5.
711 w.write_bit(first); // baie
712 if first {
713 w.write_bits(u32::from(BA_PARAMS.sdcycod), 2);
714 w.write_bits(u32::from(BA_PARAMS.fdcycod), 2);
715 w.write_bits(u32::from(BA_PARAMS.sgaincod), 2);
716 w.write_bits(u32::from(BA_PARAMS.dbpbcod), 2);
717 w.write_bits(u32::from(BA_PARAMS.floorcod), 3);
718 }
719 w.write_bit(first); // snroffste
720 if first {
721 w.write_bits(u32::from(csnroffst), 6);
722 for _ in 0..self.coded {
723 w.write_bits(u32::from(fsnroffst), 4);
724 w.write_bits(u32::from(FGAINCOD), 3);
725 }
726 }
727 // no coupling leak (cplinu is always false: no bit here at all)
728 w.write_bit(false); // deltbaie
729 w.write_bit(false); // skiple
730
731 let values: Vec<(u8, f32)> = (0..self.coded)
732 .flat_map(|ch| (0..endmant[ch]).map(move |bin| (ch, bin)))
733 .map(|(ch, bin)| (bap[blk][ch][bin], coeffs[blk][ch][bin] * scale(plan.exps[blk][ch][bin])))
734 .collect();
735 write_mantissas(w, &values);
736 }
737
738 /// Patches crc1/crc2 into a written frame and zero-pads it to
739 /// [`Ac3Encoder::frame_bytes`] — the syncframe's own length, so every
740 /// frame is exactly [`crate::tables::FRAME_SIZE_WORDS`].
741 fn finish_frame(&self, mut w: BitWriter) -> Vec<u8> {
742 w.write_bit(false); // auxdataflag
743 w.write_bit(false); // crcrsv
744 while (w.bit_len() as usize) < self.frame_bytes * 8 - 16 {
745 w.write_bit(false);
746 }
747 w.write_bits(0, 16); // crc2 placeholder
748 w.align_to_byte();
749 let mut bytes = w.into_bytes();
750 bytes.resize(self.frame_bytes, 0);
751
752 // §7.10: crc1 covers the first 5/8 of the frame, crc2 the rest.
753 let frame_size_58 = ((self.frame_bytes >> 2) + (self.frame_bytes >> 4)) << 1;
754 let crc1 = crc16(&bytes[4..frame_size_58]);
755 bytes[2..4].copy_from_slice(&crc1.to_be_bytes());
756 let crc2 = crc16(&bytes[2..self.frame_bytes - 2]);
757 bytes[self.frame_bytes - 2..].copy_from_slice(&crc2.to_be_bytes());
758 bytes
759 }
760}
761
762/// Per-frame coding decisions, made before the rate loop runs so every
763/// candidate allocation is measured against the same side information.
764struct Plan {
765 /// Block switch per block per coded channel (always false for the LFE).
766 blksw: Vec<Vec<bool>>,
767 /// Exponent strategy per block per coded channel.
768 strategy: Vec<Vec<Strategy>>,
769 /// The exponent values as sent — the absolute one, then one per
770 /// differential — per block per channel; empty on `Reuse`.
771 sent: Vec<Vec<Vec<u8>>>,
772 /// The exponents the decoder holds during each block, per channel: what
773 /// the bit allocation and the quantisation both run on.
774 exps: Vec<Vec<[u8; COEFFS]>>,
775}
776
777/// What the encoder decided, summed over every frame so far.
778#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
779pub struct EncodeStats {
780 /// Frames coded.
781 pub frames: u64,
782 /// Block-switched (short transform) blocks, over full-bandwidth channels.
783 pub blksw_blocks: u64,
784 /// Block/channel pairs (full-bandwidth) that sent D15 exponents.
785 pub d15: u64,
786 /// ... D25.
787 pub d25: u64,
788 /// ... D45.
789 pub d45: u64,
790 /// ... that reused the previous block's exponents.
791 pub reuse: u64,
792 /// Sum of the `csnroffst` each frame settled on.
793 pub csnroffst_sum: u64,
794 /// Bits the frames' side information and mantissas occupied, before padding.
795 pub bits_used: u64,
796 /// Bits the frames had available for them.
797 pub bits_budget: u64,
798}
799
800/// The 2-bit `chexpstr` code (the inverse of [`Strategy::from_code`]).
801fn strategy_code(strategy: Strategy) -> u32 {
802 match strategy {
803 Strategy::Reuse => 0,
804 Strategy::D15 => 1,
805 Strategy::D25 => 2,
806 Strategy::D45 => 3,
807 }
808}
809
810/// `chbwcod` from the bit rate per full-bandwidth channel: the whole band when
811/// there are bits to fill it, tapering down at low rates so the bits go to the
812/// bands that carry the music. At 48 kHz the rows cut off at about 24, 20, 18,
813/// 16 and 14 kHz.
814fn chbwcod_for(kbps: u32, nfchans: usize) -> u32 {
815 match kbps / nfchans as u32 {
816 80.. => 60,
817 56.. => 48,
818 40.. => 40,
819 28.. => 32,
820 _ => 24,
821 }
822}
823
824/// §7.9.1's spirit in its simplest form: a first-order high-pass, then the
825/// energy of each of the window's eight 64-sample segments; a segment in the
826/// block's own half (the new 256 samples) that is `TRANSIENT_RATIO` above
827/// everything before it, and above the silence floor, is an attack worth a
828/// short transform's time resolution (pre-echo would otherwise smear over
829/// the whole 512-sample window).
830fn is_transient(window_in: &[f32; 512]) -> bool {
831 let mut energy = [0.0f32; 8];
832 for (i, seg) in energy.iter_mut().enumerate() {
833 *seg = (i * 64..(i + 1) * 64)
834 .map(|n| {
835 let d = window_in[n] - window_in[n.saturating_sub(1)];
836 d * d
837 })
838 .sum();
839 }
840 (4..8).any(|j| {
841 let before = energy[..j].iter().copied().fold(0.0f32, f32::max);
842 energy[j] > TRANSIENT_FLOOR && energy[j] > TRANSIENT_RATIO * before
843 })
844}
845
846/// `floor(-log2 |X|)` per bin, clamped to 0..=24 (24 also for zero), up to
847/// `endmant`: the exponent that leaves each coefficient's mantissa in
848/// `[0.5, 1)`.
849fn ideal_exps(coeffs: &[f32; COEFFS], endmant: usize) -> [u8; COEFFS] {
850 let mut e = [24u8; COEFFS];
851 for bin in 0..endmant {
852 let mag = coeffs[bin].abs();
853 e[bin] = if mag <= 0.0 { 24 } else { (-mag.log2()).floor().clamp(0.0, 24.0) as u8 };
854 }
855 e
856}
857
858/// Whether two ideal envelopes differ enough to be worth re-sending: the peak
859/// (minimum exponent) of some 12-bin band within 60 dB of the loudest band
860/// moved by more than [`RESEND_STEPS`]. A re-send costs 150-300 bits per
861/// channel — at 192 kbps stereo that is 30-60 % of a block's whole budget —
862/// so the bands the masking model will starve anyway do not get a vote.
863fn envelope_moved(a: &[u8; COEFFS], b: &[u8; COEFFS], endmant: usize) -> bool {
864 let loudest = a[..endmant].iter().min().unwrap().min(b[..endmant].iter().min().unwrap());
865 a[..endmant].chunks(12).zip(b[..endmant].chunks(12)).any(|(x, y)| {
866 let (px, py) = (*x.iter().min().unwrap(), *y.iter().min().unwrap());
867 px.min(py) <= loudest + 10 && px.abs_diff(py) > RESEND_STEPS
868 })
869}
870
871/// The exponent set a channel sends for a run of blocks: `ideal` is the run's
872/// envelope (min over the run's blocks of each bin's ideal exponent), grouped
873/// by `strategy` (min over each group's bins), fitted to the ±2 differential
874/// coding by [`smooth_exps`], then expanded to what the decoder will hold.
875/// Returns (values as sent, decoded exponents).
876fn plan_exponents(ideal: &[u8; COEFFS], endmant: usize, strategy: Strategy) -> (Vec<u8>, [u8; COEFFS]) {
877 let gs = strategy.group_size();
878 let ngrps = strategy.fbw_groups(endmant);
879 let mut sent = vec![ideal[0].min(15)];
880 for g in 0..ngrps * 3 {
881 let lo = 1 + g * gs;
882 let hi = (lo + gs).min(endmant);
883 sent.push(if lo < hi { *ideal[lo..hi].iter().min().unwrap() } else { 24 });
884 }
885 smooth_exps(&mut sent);
886 let mut exps = [24u8; COEFFS];
887 exps[0] = sent[0];
888 for g in 0..ngrps * 3 {
889 for bin in 1 + g * gs..(1 + (g + 1) * gs).min(COEFFS) {
890 exps[bin] = sent[g + 1];
891 }
892 }
893 (sent, exps)
894}
895
896/// `2^exponent` — the inverse of [`crate::mantissa::scale`], since the
897/// encoder starts from a linear coefficient and has to divide it back out to
898/// the `[-1, 1)` mantissa the quantizers expect.
899fn scale(exponent: u8) -> f32 {
900 f32::from_bits(127u32.wrapping_add(u32::from(exponent)) << 23)
901}
902
903/// Little-endian floats out of a plane.
904fn floats(plane: &Buf, count: usize) -> Vec<f32> {
905 plane
906 .as_chunks::<4>()
907 .0
908 .iter()
909 .take(count)
910 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
911 .collect()
912}
913
914impl Encoder for Ac3Encoder {
915 fn codec_parameters(&self) -> &CodecParameters {
916 &self.params
917 }
918
919 fn send_frame(&mut self, frame: &Frame) -> Result<()> {
920 let Frame::Audio(audio) = frame else {
921 return Err(Error::corrupt("video frame pushed into an audio encoder"));
922 };
923 if audio.format != SampleFormat::F32 {
924 return Err(Error::unsupported(
925 format!("{:?} input", audio.format),
926 "this encoder takes 32-bit float samples",
927 ));
928 }
929 let channels = self.coded;
930 let interleaved = if audio.planar {
931 let mut out = vec![0.0f32; audio.samples * channels];
932 for (c, plane) in audio.data.iter().enumerate().take(channels) {
933 for (n, v) in floats(plane, audio.samples).into_iter().enumerate() {
934 out[n * channels + c] = v;
935 }
936 }
937 out
938 } else {
939 floats(&audio.data[0], audio.samples * channels)
940 };
941 self.push_pcm_f32(&interleaved)
942 }
943
944 fn receive_packet(&mut self) -> Result<Packet> {
945 let data = self.next_packet()?;
946 let base = TimeBase::new(1, i64::from(self.config.sample_rate));
947 let mut packet = Packet::new(0, base, data);
948 packet.duration = Some(FRAME_SAMPLES as i64);
949 Ok(packet)
950 }
951
952 fn flush(&mut self) -> Result<()> {
953 self.finish();
954 Ok(())
955 }
956}
957
958#[cfg(test)]
959mod tests {
960 use super::*;
961
962 fn lcg(seed: &mut u64) -> f32 {
963 *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
964 ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
965 }
966
967 /// 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.
968 fn direct_forward(x: &[f32; 512], window: &[f32; 512]) -> [f32; COEFFS] {
969 let mut out = [0.0f32; COEFFS];
970 for (k, o) in out.iter_mut().enumerate() {
971 let mut acc = 0.0f64;
972 for n in 0..512 {
973 let arg = 2.0 * std::f64::consts::PI / 512.0 * (n as f64 + 0.5 + 128.0) * (k as f64 + 0.5);
974 acc += f64::from(x[n] * window[n]) * arg.cos();
975 }
976 *o = acc as f32;
977 }
978 out
979 }
980
981 /// Runs `forward` then the decoder's inverse over 7 overlapping blocks,
982 /// block-switched where `pattern` says so (the short transform must be
983 /// TDAC-exact against both a short and a long neighbour), and returns
984 /// (worst sample error, least-squares gain out/in).
985 fn tdac_pattern(pattern: [bool; 7], forward: impl Fn(&[f32; 512], bool) -> [f32; COEFFS]) -> (f32, f64) {
986 let mut seed = 7u64;
987 let signal: Vec<f32> = (0..256 * 8).map(|_| lcg(&mut seed)).collect();
988 let mut imdct = Imdct::new();
989 let mut delay = [0.0f32; 256];
990 let mut out = [0.0f32; 256];
991 let mut worst = 0.0f32;
992 let (mut dot, mut nrm) = (0.0f64, 0.0f64);
993 for (blk, &short) in pattern.iter().enumerate() {
994 let mut x = [0.0f32; 512];
995 x.copy_from_slice(&signal[blk * 256..blk * 256 + 512]);
996 let spec = forward(&x, short);
997 imdct.block(&spec, short, &mut delay, &mut out);
998 if blk > 0 {
999 // Output of block `blk` reconstructs input samples blk*256..+256.
1000 for n in 0..256 {
1001 worst = worst.max((out[n] - signal[blk * 256 + n]).abs());
1002 dot += f64::from(out[n] * signal[blk * 256 + n]);
1003 nrm += f64::from(signal[blk * 256 + n] * signal[blk * 256 + n]);
1004 }
1005 }
1006 }
1007 (worst, dot / nrm)
1008 }
1009
1010 fn tdac(forward: impl Fn(&[f32; 512]) -> [f32; COEFFS]) -> f32 {
1011 let (worst, gain) = tdac_pattern([false; 7], |x, _| forward(x));
1012 assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}");
1013 worst
1014 }
1015
1016 #[test]
1017 fn tdac_short_forward_reconstructs_against_long_and_short_neighbours() {
1018 let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap();
1019 let window = enc.window;
1020 let basis = enc.short_basis.clone();
1021 let cell = std::cell::RefCell::new(&mut enc.mdct);
1022 let (worst, gain) = tdac_pattern([false, true, true, false, true, false, true], |x, short| {
1023 let mut s = [0.0f32; COEFFS];
1024 if short {
1025 for (k, out) in s.iter_mut().enumerate() {
1026 let row = &basis[k * 512..(k + 1) * 512];
1027 *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::<f32>();
1028 }
1029 } else {
1030 cell.borrow_mut().forward_windowed(x, &window, &mut s);
1031 for v in &mut s {
1032 *v *= FORWARD_GAIN;
1033 }
1034 }
1035 s
1036 });
1037 let (w2, g2) = tdac_pattern([true; 7], |x, _| {
1038 let mut s = [0.0f32; COEFFS];
1039 for (k, out) in s.iter_mut().enumerate() {
1040 let row = &basis[k * 512..(k + 1) * 512];
1041 *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::<f32>();
1042 }
1043 s
1044 });
1045 eprintln!("all-short: worst {w2} gain {g2}; mixed: worst {worst} gain {gain}");
1046 assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}");
1047 assert!(worst < 1e-4, "short forward + Imdct TDAC error {worst}");
1048 }
1049
1050 fn encode_one(pcm: &[f32]) -> EncodeStats {
1051 let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 96 }).unwrap();
1052 enc.push_pcm_f32(pcm).unwrap();
1053 enc.stats()
1054 }
1055
1056 #[test]
1057 fn stationary_tone_plans_one_d45_set_and_reuses_it() {
1058 let pcm: Vec<f32> = (0..FRAME_SAMPLES * 2)
1059 .map(|n| 0.5 * (2.0 * std::f32::consts::PI * 1000.0 * n as f32 / 48000.0).sin())
1060 .collect();
1061 let stats = encode_one(&pcm);
1062 assert_eq!(stats.frames, 2);
1063 // Frame 0 opens from silence: an onset, so block 0 is legitimately
1064 // short and its first blocks may re-send; frame 1 is steady: one D45
1065 // set, five reuses.
1066 assert!(stats.blksw_blocks <= 1, "{stats:?}");
1067 assert!(stats.d45 >= 1 && stats.d15 == 0 && stats.d25 <= 1, "{stats:?}");
1068 assert!(stats.reuse >= 5, "{stats:?}");
1069 assert!(stats.bits_used * 10 > stats.bits_budget * 9, "rate loop left bits unused: {stats:?}");
1070 }
1071
1072 #[test]
1073 fn a_click_switches_to_short_blocks_and_d25() {
1074 let mut pcm = vec![0.0f32; FRAME_SAMPLES];
1075 for n in 0..FRAME_SAMPLES {
1076 pcm[n] = 0.01 * ((n as f32) * 0.3).sin();
1077 }
1078 pcm[256 * 3 + 100] = 0.9;
1079 pcm[256 * 3 + 101] = -0.9;
1080 let stats = encode_one(&pcm);
1081 assert_eq!(stats.blksw_blocks, 1, "{stats:?}");
1082 assert!(stats.d25 >= 1 && stats.d15 == 0, "{stats:?}");
1083 }
1084
1085 #[test]
1086 fn smoothed_exponents_never_rise_and_always_fit_the_group_coding() {
1087 let mut e = [24u8; COEFFS];
1088 e[100] = 1;
1089 e[0] = 20;
1090 let ideal = e;
1091 smooth_exps(&mut e);
1092 assert!(e.iter().zip(&ideal).all(|(s, i)| s <= i));
1093 assert!(e.windows(2).all(|w| (i32::from(w[0]) - i32::from(w[1])).abs() <= 2));
1094 assert_eq!((e[0], e[99], e[100], e[101]), (15, 3, 1, 3));
1095 let mut again = e;
1096 smooth_exps(&mut again);
1097 assert_eq!(again, e);
1098 }
1099
1100 #[test]
1101 fn tdac_direct_forward_reconstructs() {
1102 let enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap();
1103 let window = enc.window;
1104 // A/52's forward carries -2/N.
1105 let err = tdac(|x| {
1106 let mut s = direct_forward(x, &window);
1107 for v in &mut s {
1108 *v *= -2.0 / 512.0;
1109 }
1110 s
1111 });
1112 assert!(err < 1e-4, "direct forward + Imdct TDAC error {err}");
1113 }
1114
1115 #[test]
1116 fn tdac_ec_dsp_forward_reconstructs() {
1117 let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap();
1118 let window = enc.window;
1119 let cell = std::cell::RefCell::new(&mut enc.mdct);
1120 let err = tdac(|x| {
1121 let mut s = [0.0f32; COEFFS];
1122 cell.borrow_mut().forward_windowed(x, &window, &mut s);
1123 for v in &mut s {
1124 *v *= FORWARD_GAIN;
1125 }
1126 s
1127 });
1128 assert!(err < 1e-4, "ec_dsp forward + Imdct TDAC error {err}");
1129 }
1130}