forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBeb83b6fTahinli3 months ago495 commits

encode.rs1127 lines, 45.1 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..].chunks_exact(3) {
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
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 while self.pcm.len() >= need {
373 let block: Vec<f32> = self.pcm.drain(..need).collect();
374 let packet = self.encode_frame(&block);
375 self.packets.push_back(packet);
376 }
377 }
378
379 /// The next encoded syncframe; [`Error::Eof`] once drained after
380 /// [`Ac3Encoder::finish`], [`Error::NeedMore`] before that.
381 pub fn next_packet(&mut self) -> Result<Vec<u8>> {
382 match self.packets.pop_front() {
383 Some(p) => Ok(p),
384 None if self.finished => Err(Error::Eof),
385 None => Err(Error::NeedMore),
386 }
387 }
388
389 /// One syncframe from `interleaved` (family-order PCM, `coded` channels *
390 /// [`FRAME_SAMPLES`] samples).
391 fn encode_frame(&mut self, interleaved: &[f32]) -> Vec<u8> {
392 // Deinterleave into coded-channel order, pick long or short transform
393 // per block from the transient detector, and run the MDCT.
394 let mut coeffs = vec![vec![[0.0f32; COEFFS]; self.coded]; BLOCKS];
395 let mut blksw = vec![vec![false; self.coded]; BLOCKS];
396 for ch in 0..self.coded {
397 let slot = if ch < self.nfchans {
398 self.order.iter().position(|&s| s == Some(ch)).unwrap()
399 } else {
400 self.order.iter().position(|&s| s.is_none()).unwrap()
401 };
402 for blk in 0..BLOCKS {
403 let mut window_in = [0.0f32; 512];
404 window_in[..256].copy_from_slice(&self.history[ch]);
405 for n in 0..256 {
406 window_in[256 + n] = interleaved[(blk * 256 + n) * self.coded + slot];
407 }
408 // The LFE has no blksw bit in the stream.
409 let short = ch < self.nfchans && is_transient(&window_in);
410 blksw[blk][ch] = short;
411 let mut spectrum = [0.0f32; COEFFS];
412 if short {
413 self.forward_short(&window_in, &mut spectrum);
414 } else {
415 self.mdct
416 .forward_windowed(&window_in, &self.window, &mut spectrum);
417 for v in &mut spectrum {
418 // Measured in `tests::tdac_*`: this makes the forward the
419 // exact adjoint of the decoder's transform.rs IMDCT.
420 *v *= FORWARD_GAIN;
421 }
422 }
423 self.history[ch].copy_from_slice(&window_in[256..]);
424 coeffs[blk][ch] = spectrum;
425 }
426 }
427
428 let endmant: Vec<usize> = (0..self.coded)
429 .map(|ch| if ch < self.nfchans { self.fbw_endmant } else { LFE_ENDMANT })
430 .collect();
431 let budget_bits = self.frame_bytes as u64 * 8 - 2 /* auxdataflag, crcrsv */ - 16 /* crc2 */;
432
433 // Rate loop: the exponent plan fixes the side information, then the
434 // largest csnroffst (and, at that csnroffst, the largest fsnroffst)
435 // whose mantissas still fit is found by binary search — both are
436 // monotone in bits spent. A plan whose side information alone does
437 // not fit (a frame of strategy churn at a low bit rate) is replaced
438 // by the conservative one: a single D45 envelope for the whole frame.
439 let mut chosen: Option<(BitWriter, Plan, u8)> = None;
440 for conservative in [false, true] {
441 let plan = self.plan(&coeffs, &blksw, &endmant, conservative);
442 let fits = |c: u8, f: u8| {
443 let bap = self.allocate(&plan, &endmant, c, f);
444 let w = self.write_frame(&coeffs, &plan, &endmant, &bap, c, f);
445 (w.bit_len() <= budget_bits).then_some(w)
446 };
447 if fits(0, 0).is_none() {
448 continue;
449 }
450 let (mut lo, mut hi) = (0u8, 63u8);
451 while lo < hi {
452 let mid = (lo + hi).div_ceil(2);
453 if fits(mid, 0).is_some() { lo = mid } else { hi = mid - 1 }
454 }
455 let c = lo;
456 let (mut lo, mut hi) = (0u8, 15u8);
457 while lo < hi {
458 let mid = (lo + hi).div_ceil(2);
459 if fits(c, mid).is_some() { lo = mid } else { hi = mid - 1 }
460 }
461 chosen = Some((fits(c, lo).unwrap(), plan, c));
462 break;
463 }
464 let (w, plan, csnroffst) = chosen.unwrap_or_else(|| {
465 // corner-cut: unreachable with the 32 kbps/channel floor `new`
466 // applies (the conservative plan's side info is ~150 bits per
467 // channel per frame); below that the frame would be truncated.
468 // Upgrade path: drop chbwcod until it fits.
469 debug_assert!(false, "side information does not fit the frame");
470 let plan = self.plan(&coeffs, &blksw, &endmant, true);
471 let bap = self.allocate(&plan, &endmant, 0, 0);
472 (self.write_frame(&coeffs, &plan, &endmant, &bap, 0, 0), plan, 0)
473 });
474
475 self.stats.frames += 1;
476 self.stats.csnroffst_sum += u64::from(csnroffst);
477 self.stats.bits_used += w.bit_len();
478 self.stats.bits_budget += budget_bits;
479 for blk in 0..BLOCKS {
480 for ch in 0..self.nfchans {
481 self.stats.blksw_blocks += u64::from(blksw[blk][ch]);
482 match plan.strategy[blk][ch] {
483 Strategy::Reuse => self.stats.reuse += 1,
484 Strategy::D15 => self.stats.d15 += 1,
485 Strategy::D25 => self.stats.d25 += 1,
486 Strategy::D45 => self.stats.d45 += 1,
487 }
488 }
489 }
490 self.finish_frame(w)
491 }
492
493 /// The two 256-point transforms of a block-switched block (§7.9.4.2), as
494 /// the transpose of the decoder's own short inverse (`short_basis`), so
495 /// the pair is TDAC-exact by construction — see `tests::tdac_short_*`.
496 fn forward_short(&self, window_in: &[f32; 512], spectrum: &mut [f32; COEFFS]) {
497 for (k, out) in spectrum.iter_mut().enumerate() {
498 let row = &self.short_basis[k * 512..(k + 1) * 512];
499 *out = SHORT_GAIN * row.iter().zip(window_in).map(|(a, b)| a * b).sum::<f32>();
500 }
501 }
502
503 /// Exponent strategy and exponents for every block and channel.
504 ///
505 /// Block 0 always sends. A later block re-sends when its block switch
506 /// flag changed or its envelope moved ([`envelope_moved`]) since the last
507 /// send; otherwise it reuses. Each run of
508 /// blocks sharing one set codes the run's loudest magnitude per bin, so no
509 /// block's mantissa is asked for more than its exponent's headroom. The
510 /// sending block uses D15 for the LFE channel, D25 when block-switched
511 /// (the short transform's interleaved halves make D15's per-bin cost too
512 /// high — see the D25-vs-D15 note below), D45 for a run of 3+ blocks
513 /// (stationary), D25 otherwise. `conservative` forces one D45 set per
514 /// channel for the whole frame: the cheapest legal side information.
515 fn plan(&self, coeffs: &[Vec<[f32; COEFFS]>], blksw: &[Vec<bool>], endmant: &[usize], conservative: bool) -> Plan {
516 let ideal: Vec<Vec<[u8; COEFFS]>> = coeffs
517 .iter()
518 .map(|blk| (0..self.coded).map(|ch| ideal_exps(&blk[ch], endmant[ch])).collect())
519 .collect();
520 let mut plan = Plan {
521 blksw: blksw.to_vec(),
522 strategy: vec![vec![Strategy::Reuse; self.coded]; BLOCKS],
523 sent: vec![vec![Vec::new(); self.coded]; BLOCKS],
524 exps: vec![vec![[24u8; COEFFS]; self.coded]; BLOCKS],
525 };
526 for ch in 0..self.coded {
527 let mut starts = vec![0usize];
528 if !conservative {
529 for blk in 1..BLOCKS {
530 let last = *starts.last().unwrap();
531 if blksw[blk][ch] != blksw[blk - 1][ch]
532 || envelope_moved(&ideal[blk][ch], &ideal[last][ch], endmant[ch])
533 {
534 starts.push(blk);
535 }
536 }
537 }
538 for (i, &start) in starts.iter().enumerate() {
539 let end = starts.get(i + 1).copied().unwrap_or(BLOCKS);
540 let mut env = ideal[start][ch];
541 for blk in start + 1..end {
542 for bin in 0..endmant[ch] {
543 env[bin] = env[bin].min(ideal[blk][ch][bin]);
544 }
545 }
546 let strategy = if ch >= self.nfchans {
547 Strategy::D15
548 } else if blksw[start][ch] {
549 // The short halves interleave, so pairs (X1[k], X2[k])
550 // share one exponent: the louder half's. D15 would
551 // follow the alternation exactly but at 592 bits per
552 // send — more than a block's whole budget at 96 kbps per
553 // channel — against D25's 298.
554 Strategy::D25
555 } else if conservative || end - start >= 3 {
556 Strategy::D45
557 } else {
558 Strategy::D25
559 };
560 let (sent, exps) = plan_exponents(&env, endmant[ch], strategy);
561 plan.strategy[start][ch] = strategy;
562 plan.sent[start][ch] = sent;
563 for blk in start..end {
564 plan.exps[blk][ch] = exps;
565 }
566 }
567 }
568 plan
569 }
570
571 /// Bit allocation for every block and coded channel at one SNR offset.
572 fn allocate(&self, plan: &Plan, endmant: &[usize], csnroffst: u8, fsnroffst: u8) -> Vec<Vec<[u8; COEFFS]>> {
573 let snroffset = (((i32::from(csnroffst) - 15) << 4) + i32::from(fsnroffst)) << 2;
574 // §7.2.2.1.1: all-zero SNR offsets mean no mantissa bits at all —
575 // the decoder short-circuits there instead of running the model.
576 if csnroffst == 0 && fsnroffst == 0 {
577 return vec![vec![[0u8; COEFFS]; self.coded]; BLOCKS];
578 }
579 let mut out: Vec<Vec<[u8; COEFFS]>> = Vec::with_capacity(BLOCKS);
580 for blk in 0..BLOCKS {
581 let baps = (0..self.coded)
582 .map(|ch| {
583 if blk > 0 && plan.strategy[blk][ch] == Strategy::Reuse {
584 return out[blk - 1][ch];
585 }
586 let kind = if ch < self.nfchans { Channel::Fbw } else { Channel::Lfe };
587 let alloc = Allocation {
588 fscod: self.fscod,
589 params: BA_PARAMS,
590 range: (0, endmant[ch]),
591 fgaincod: FGAINCOD,
592 snroffset,
593 kind,
594 dba: None,
595 high_efficiency: false,
596 };
597 let mut bap = [0u8; COEFFS];
598 bitalloc::compute(&alloc, &plan.exps[blk][ch], &mut bap);
599 bap
600 })
601 .collect();
602 out.push(baps);
603 }
604 out
605 }
606
607 /// Writes syncinfo, bsi and the six audblks; mantissas and their bit cost
608 /// come from `coeffs`, `plan` and `bap` (all already computed for this
609 /// frame). Everything up to the crc/padding tail this function leaves for
610 /// [`Ac3Encoder::finish_frame`], so the rate loop in
611 /// [`Ac3Encoder::encode_frame`] can measure a candidate's length before
612 /// paying for that.
613 fn write_frame(
614 &self,
615 coeffs: &[Vec<[f32; COEFFS]>],
616 plan: &Plan,
617 endmant: &[usize],
618 bap: &[Vec<[u8; COEFFS]>],
619 csnroffst: u8,
620 fsnroffst: u8,
621 ) -> BitWriter {
622 let mut w = BitWriter::with_capacity(self.frame_bytes);
623
624 // syncinfo(): crc1 is patched into the bytes afterwards.
625 w.write_bits(0x0B77, 16);
626 w.write_bits(0, 16);
627 w.write_bits(self.fscod as u32, 2);
628 w.write_bits(u32::from(self.frmsizecod), 6);
629
630 // bsi()
631 w.write_bits(8, 5); // bsid
632 w.write_bits(0, 3); // bsmod
633 w.write_bits(u32::from(self.acmod.code()), 3);
634 if self.acmod.code() & 1 != 0 && self.acmod.code() != 1 {
635 w.write_bits(1, 2); // cmixlev
636 }
637 if self.acmod.code() & 4 != 0 {
638 w.write_bits(1, 2); // surmixlev
639 }
640 if self.acmod == Acmod::Stereo {
641 w.write_bits(0, 2); // dsurmod
642 }
643 w.write_bit(self.lfeon);
644 w.write_bits(31, 5); // dialnorm
645 w.write_bit(false); // compr
646 w.write_bit(false); // langcod
647 w.write_bit(false); // mixlevel/roomtyp
648 w.write_bit(false); // copyrightb
649 w.write_bit(false); // origbs
650 w.write_bit(false); // timecod1
651 w.write_bit(false); // timecod2
652 w.write_bit(false); // addbsi
653
654 for blk in 0..BLOCKS {
655 self.write_block(&mut w, blk, coeffs, plan, endmant, bap, csnroffst, fsnroffst);
656 }
657 w
658 }
659
660 #[allow(clippy::too_many_arguments)]
661 fn write_block(
662 &self,
663 w: &mut BitWriter,
664 blk: usize,
665 coeffs: &[Vec<[f32; COEFFS]>],
666 plan: &Plan,
667 endmant: &[usize],
668 bap: &[Vec<[u8; COEFFS]>],
669 csnroffst: u8,
670 fsnroffst: u8,
671 ) {
672 let first = blk == 0;
673 for ch in 0..self.nfchans {
674 w.write_bit(plan.blksw[blk][ch]);
675 }
676 for _ in 0..self.nfchans {
677 w.write_bit(false); // dithflag
678 }
679 w.write_bit(false); // dynrnge
680 w.write_bit(first); // cplstre: block 0 must declare a strategy
681 if first {
682 w.write_bit(false); // cplinu: no coupling
683 }
684 if self.acmod == Acmod::Stereo {
685 w.write_bit(false); // rematstr (no rematrixing)
686 }
687 for ch in 0..self.nfchans {
688 w.write_bits(strategy_code(plan.strategy[blk][ch]), 2); // chexpstr
689 }
690 if self.lfeon {
691 w.write_bit(plan.strategy[blk][self.nfchans] != Strategy::Reuse); // lfeexpstr
692 }
693 for ch in 0..self.nfchans {
694 if plan.strategy[blk][ch] != Strategy::Reuse {
695 w.write_bits(self.chbwcod, 6);
696 }
697 }
698 for ch in 0..self.nfchans {
699 if plan.strategy[blk][ch] != Strategy::Reuse {
700 write_exp_groups(w, &plan.sent[blk][ch]);
701 w.write_bits(0, 2); // gainrng
702 }
703 }
704 if self.lfeon && plan.strategy[blk][self.nfchans] != Strategy::Reuse {
705 write_exp_groups(w, &plan.sent[blk][self.nfchans]);
706 }
707 // The allocation parameters and SNR offsets are constant across the
708 // frame, so they go once, in block 0 (where they are mandatory); the
709 // decoder carries them forward through blocks 1-5.
710 w.write_bit(first); // baie
711 if first {
712 w.write_bits(u32::from(BA_PARAMS.sdcycod), 2);
713 w.write_bits(u32::from(BA_PARAMS.fdcycod), 2);
714 w.write_bits(u32::from(BA_PARAMS.sgaincod), 2);
715 w.write_bits(u32::from(BA_PARAMS.dbpbcod), 2);
716 w.write_bits(u32::from(BA_PARAMS.floorcod), 3);
717 }
718 w.write_bit(first); // snroffste
719 if first {
720 w.write_bits(u32::from(csnroffst), 6);
721 for _ in 0..self.coded {
722 w.write_bits(u32::from(fsnroffst), 4);
723 w.write_bits(u32::from(FGAINCOD), 3);
724 }
725 }
726 // no coupling leak (cplinu is always false: no bit here at all)
727 w.write_bit(false); // deltbaie
728 w.write_bit(false); // skiple
729
730 let values: Vec<(u8, f32)> = (0..self.coded)
731 .flat_map(|ch| (0..endmant[ch]).map(move |bin| (ch, bin)))
732 .map(|(ch, bin)| (bap[blk][ch][bin], coeffs[blk][ch][bin] * scale(plan.exps[blk][ch][bin])))
733 .collect();
734 write_mantissas(w, &values);
735 }
736
737 /// Patches crc1/crc2 into a written frame and zero-pads it to
738 /// [`Ac3Encoder::frame_bytes`] — the syncframe's own length, so every
739 /// frame is exactly [`crate::tables::FRAME_SIZE_WORDS`].
740 fn finish_frame(&self, mut w: BitWriter) -> Vec<u8> {
741 w.write_bit(false); // auxdataflag
742 w.write_bit(false); // crcrsv
743 while (w.bit_len() as usize) < self.frame_bytes * 8 - 16 {
744 w.write_bit(false);
745 }
746 w.write_bits(0, 16); // crc2 placeholder
747 w.align_to_byte();
748 let mut bytes = w.into_bytes();
749 bytes.resize(self.frame_bytes, 0);
750
751 // §7.10: crc1 covers the first 5/8 of the frame, crc2 the rest.
752 let frame_size_58 = ((self.frame_bytes >> 2) + (self.frame_bytes >> 4)) << 1;
753 let crc1 = crc16(&bytes[4..frame_size_58]);
754 bytes[2..4].copy_from_slice(&crc1.to_be_bytes());
755 let crc2 = crc16(&bytes[2..self.frame_bytes - 2]);
756 bytes[self.frame_bytes - 2..].copy_from_slice(&crc2.to_be_bytes());
757 bytes
758 }
759}
760
761/// Per-frame coding decisions, made before the rate loop runs so every
762/// candidate allocation is measured against the same side information.
763struct Plan {
764 /// Block switch per block per coded channel (always false for the LFE).
765 blksw: Vec<Vec<bool>>,
766 /// Exponent strategy per block per coded channel.
767 strategy: Vec<Vec<Strategy>>,
768 /// The exponent values as sent — the absolute one, then one per
769 /// differential — per block per channel; empty on `Reuse`.
770 sent: Vec<Vec<Vec<u8>>>,
771 /// The exponents the decoder holds during each block, per channel: what
772 /// the bit allocation and the quantisation both run on.
773 exps: Vec<Vec<[u8; COEFFS]>>,
774}
775
776/// What the encoder decided, summed over every frame so far.
777#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
778pub struct EncodeStats {
779 /// Frames coded.
780 pub frames: u64,
781 /// Block-switched (short transform) blocks, over full-bandwidth channels.
782 pub blksw_blocks: u64,
783 /// Block/channel pairs (full-bandwidth) that sent D15 exponents.
784 pub d15: u64,
785 /// ... D25.
786 pub d25: u64,
787 /// ... D45.
788 pub d45: u64,
789 /// ... that reused the previous block's exponents.
790 pub reuse: u64,
791 /// Sum of the `csnroffst` each frame settled on.
792 pub csnroffst_sum: u64,
793 /// Bits the frames' side information and mantissas occupied, before padding.
794 pub bits_used: u64,
795 /// Bits the frames had available for them.
796 pub bits_budget: u64,
797}
798
799/// The 2-bit `chexpstr` code (the inverse of [`Strategy::from_code`]).
800fn strategy_code(strategy: Strategy) -> u32 {
801 match strategy {
802 Strategy::Reuse => 0,
803 Strategy::D15 => 1,
804 Strategy::D25 => 2,
805 Strategy::D45 => 3,
806 }
807}
808
809/// `chbwcod` from the bit rate per full-bandwidth channel: the whole band when
810/// there are bits to fill it, tapering down at low rates so the bits go to the
811/// bands that carry the music. At 48 kHz the rows cut off at about 24, 20, 18,
812/// 16 and 14 kHz.
813fn chbwcod_for(kbps: u32, nfchans: usize) -> u32 {
814 match kbps / nfchans as u32 {
815 80.. => 60,
816 56.. => 48,
817 40.. => 40,
818 28.. => 32,
819 _ => 24,
820 }
821}
822
823/// §7.9.1's spirit in its simplest form: a first-order high-pass, then the
824/// energy of each of the window's eight 64-sample segments; a segment in the
825/// block's own half (the new 256 samples) that is `TRANSIENT_RATIO` above
826/// everything before it, and above the silence floor, is an attack worth a
827/// short transform's time resolution (pre-echo would otherwise smear over
828/// the whole 512-sample window).
829fn is_transient(window_in: &[f32; 512]) -> bool {
830 let mut energy = [0.0f32; 8];
831 for (i, seg) in energy.iter_mut().enumerate() {
832 *seg = (i * 64..(i + 1) * 64)
833 .map(|n| {
834 let d = window_in[n] - window_in[n.saturating_sub(1)];
835 d * d
836 })
837 .sum();
838 }
839 (4..8).any(|j| {
840 let before = energy[..j].iter().copied().fold(0.0f32, f32::max);
841 energy[j] > TRANSIENT_FLOOR && energy[j] > TRANSIENT_RATIO * before
842 })
843}
844
845/// `floor(-log2 |X|)` per bin, clamped to 0..=24 (24 also for zero), up to
846/// `endmant`: the exponent that leaves each coefficient's mantissa in
847/// `[0.5, 1)`.
848fn ideal_exps(coeffs: &[f32; COEFFS], endmant: usize) -> [u8; COEFFS] {
849 let mut e = [24u8; COEFFS];
850 for bin in 0..endmant {
851 let mag = coeffs[bin].abs();
852 e[bin] = if mag <= 0.0 { 24 } else { (-mag.log2()).floor().clamp(0.0, 24.0) as u8 };
853 }
854 e
855}
856
857/// Whether two ideal envelopes differ enough to be worth re-sending: the peak
858/// (minimum exponent) of some 12-bin band within 60 dB of the loudest band
859/// moved by more than [`RESEND_STEPS`]. A re-send costs 150-300 bits per
860/// channel — at 192 kbps stereo that is 30-60 % of a block's whole budget —
861/// so the bands the masking model will starve anyway do not get a vote.
862fn envelope_moved(a: &[u8; COEFFS], b: &[u8; COEFFS], endmant: usize) -> bool {
863 let loudest = a[..endmant].iter().min().unwrap().min(b[..endmant].iter().min().unwrap());
864 a[..endmant].chunks(12).zip(b[..endmant].chunks(12)).any(|(x, y)| {
865 let (px, py) = (*x.iter().min().unwrap(), *y.iter().min().unwrap());
866 px.min(py) <= loudest + 10 && px.abs_diff(py) > RESEND_STEPS
867 })
868}
869
870/// The exponent set a channel sends for a run of blocks: `ideal` is the run's
871/// envelope (min over the run's blocks of each bin's ideal exponent), grouped
872/// by `strategy` (min over each group's bins), fitted to the ±2 differential
873/// coding by [`smooth_exps`], then expanded to what the decoder will hold.
874/// Returns (values as sent, decoded exponents).
875fn plan_exponents(ideal: &[u8; COEFFS], endmant: usize, strategy: Strategy) -> (Vec<u8>, [u8; COEFFS]) {
876 let gs = strategy.group_size();
877 let ngrps = strategy.fbw_groups(endmant);
878 let mut sent = vec![ideal[0].min(15)];
879 for g in 0..ngrps * 3 {
880 let lo = 1 + g * gs;
881 let hi = (lo + gs).min(endmant);
882 sent.push(if lo < hi { *ideal[lo..hi].iter().min().unwrap() } else { 24 });
883 }
884 smooth_exps(&mut sent);
885 let mut exps = [24u8; COEFFS];
886 exps[0] = sent[0];
887 for g in 0..ngrps * 3 {
888 for bin in 1 + g * gs..(1 + (g + 1) * gs).min(COEFFS) {
889 exps[bin] = sent[g + 1];
890 }
891 }
892 (sent, exps)
893}
894
895/// `2^exponent` — the inverse of [`crate::mantissa::scale`], since the
896/// encoder starts from a linear coefficient and has to divide it back out to
897/// the `[-1, 1)` mantissa the quantizers expect.
898fn scale(exponent: u8) -> f32 {
899 f32::from_bits(127u32.wrapping_add(u32::from(exponent)) << 23)
900}
901
902/// Little-endian floats out of a plane.
903fn floats(plane: &Buf, count: usize) -> Vec<f32> {
904 plane
905 .chunks_exact(4)
906 .take(count)
907 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
908 .collect()
909}
910
911impl Encoder for Ac3Encoder {
912 fn codec_parameters(&self) -> &CodecParameters {
913 &self.params
914 }
915
916 fn send_frame(&mut self, frame: &Frame) -> Result<()> {
917 let Frame::Audio(audio) = frame else {
918 return Err(Error::corrupt("video frame pushed into an audio encoder"));
919 };
920 if audio.format != SampleFormat::F32 {
921 return Err(Error::unsupported(
922 format!("{:?} input", audio.format),
923 "this encoder takes 32-bit float samples",
924 ));
925 }
926 let channels = self.coded;
927 let interleaved = if audio.planar {
928 let mut out = vec![0.0f32; audio.samples * channels];
929 for (c, plane) in audio.data.iter().enumerate().take(channels) {
930 for (n, v) in floats(plane, audio.samples).into_iter().enumerate() {
931 out[n * channels + c] = v;
932 }
933 }
934 out
935 } else {
936 floats(&audio.data[0], audio.samples * channels)
937 };
938 self.push_pcm_f32(&interleaved)
939 }
940
941 fn receive_packet(&mut self) -> Result<Packet> {
942 let data = self.next_packet()?;
943 let base = TimeBase::new(1, i64::from(self.config.sample_rate));
944 let mut packet = Packet::new(0, base, data);
945 packet.duration = Some(FRAME_SAMPLES as i64);
946 Ok(packet)
947 }
948
949 fn flush(&mut self) -> Result<()> {
950 self.finish();
951 Ok(())
952 }
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958
959 fn lcg(seed: &mut u64) -> f32 {
960 *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
961 ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
962 }
963
964 /// 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.
965 fn direct_forward(x: &[f32; 512], window: &[f32; 512]) -> [f32; COEFFS] {
966 let mut out = [0.0f32; COEFFS];
967 for (k, o) in out.iter_mut().enumerate() {
968 let mut acc = 0.0f64;
969 for n in 0..512 {
970 let arg = 2.0 * std::f64::consts::PI / 512.0 * (n as f64 + 0.5 + 128.0) * (k as f64 + 0.5);
971 acc += f64::from(x[n] * window[n]) * arg.cos();
972 }
973 *o = acc as f32;
974 }
975 out
976 }
977
978 /// Runs `forward` then the decoder's inverse over 7 overlapping blocks,
979 /// block-switched where `pattern` says so (the short transform must be
980 /// TDAC-exact against both a short and a long neighbour), and returns
981 /// (worst sample error, least-squares gain out/in).
982 fn tdac_pattern(pattern: [bool; 7], forward: impl Fn(&[f32; 512], bool) -> [f32; COEFFS]) -> (f32, f64) {
983 let mut seed = 7u64;
984 let signal: Vec<f32> = (0..256 * 8).map(|_| lcg(&mut seed)).collect();
985 let mut imdct = Imdct::new();
986 let mut delay = [0.0f32; 256];
987 let mut out = [0.0f32; 256];
988 let mut worst = 0.0f32;
989 let (mut dot, mut nrm) = (0.0f64, 0.0f64);
990 for (blk, &short) in pattern.iter().enumerate() {
991 let mut x = [0.0f32; 512];
992 x.copy_from_slice(&signal[blk * 256..blk * 256 + 512]);
993 let spec = forward(&x, short);
994 imdct.block(&spec, short, &mut delay, &mut out);
995 if blk > 0 {
996 // Output of block `blk` reconstructs input samples blk*256..+256.
997 for n in 0..256 {
998 worst = worst.max((out[n] - signal[blk * 256 + n]).abs());
999 dot += f64::from(out[n] * signal[blk * 256 + n]);
1000 nrm += f64::from(signal[blk * 256 + n] * signal[blk * 256 + n]);
1001 }
1002 }
1003 }
1004 (worst, dot / nrm)
1005 }
1006
1007 fn tdac(forward: impl Fn(&[f32; 512]) -> [f32; COEFFS]) -> f32 {
1008 let (worst, gain) = tdac_pattern([false; 7], |x, _| forward(x));
1009 assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}");
1010 worst
1011 }
1012
1013 #[test]
1014 fn tdac_short_forward_reconstructs_against_long_and_short_neighbours() {
1015 let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap();
1016 let window = enc.window;
1017 let basis = enc.short_basis.clone();
1018 let cell = std::cell::RefCell::new(&mut enc.mdct);
1019 let (worst, gain) = tdac_pattern([false, true, true, false, true, false, true], |x, short| {
1020 let mut s = [0.0f32; COEFFS];
1021 if short {
1022 for (k, out) in s.iter_mut().enumerate() {
1023 let row = &basis[k * 512..(k + 1) * 512];
1024 *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::<f32>();
1025 }
1026 } else {
1027 cell.borrow_mut().forward_windowed(x, &window, &mut s);
1028 for v in &mut s {
1029 *v *= FORWARD_GAIN;
1030 }
1031 }
1032 s
1033 });
1034 let (w2, g2) = tdac_pattern([true; 7], |x, _| {
1035 let mut s = [0.0f32; COEFFS];
1036 for (k, out) in s.iter_mut().enumerate() {
1037 let row = &basis[k * 512..(k + 1) * 512];
1038 *out = SHORT_GAIN * row.iter().zip(x).map(|(a, b)| a * b).sum::<f32>();
1039 }
1040 s
1041 });
1042 eprintln!("all-short: worst {w2} gain {g2}; mixed: worst {worst} gain {gain}");
1043 assert!((gain - 1.0).abs() < 1e-4, "least-squares gain out/in = {gain}");
1044 assert!(worst < 1e-4, "short forward + Imdct TDAC error {worst}");
1045 }
1046
1047 fn encode_one(pcm: &[f32]) -> EncodeStats {
1048 let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 96 }).unwrap();
1049 enc.push_pcm_f32(pcm).unwrap();
1050 enc.stats()
1051 }
1052
1053 #[test]
1054 fn stationary_tone_plans_one_d45_set_and_reuses_it() {
1055 let pcm: Vec<f32> = (0..FRAME_SAMPLES * 2)
1056 .map(|n| 0.5 * (2.0 * std::f32::consts::PI * 1000.0 * n as f32 / 48000.0).sin())
1057 .collect();
1058 let stats = encode_one(&pcm);
1059 assert_eq!(stats.frames, 2);
1060 // Frame 0 opens from silence: an onset, so block 0 is legitimately
1061 // short and its first blocks may re-send; frame 1 is steady: one D45
1062 // set, five reuses.
1063 assert!(stats.blksw_blocks <= 1, "{stats:?}");
1064 assert!(stats.d45 >= 1 && stats.d15 == 0 && stats.d25 <= 1, "{stats:?}");
1065 assert!(stats.reuse >= 5, "{stats:?}");
1066 assert!(stats.bits_used * 10 > stats.bits_budget * 9, "rate loop left bits unused: {stats:?}");
1067 }
1068
1069 #[test]
1070 fn a_click_switches_to_short_blocks_and_d25() {
1071 let mut pcm = vec![0.0f32; FRAME_SAMPLES];
1072 for n in 0..FRAME_SAMPLES {
1073 pcm[n] = 0.01 * ((n as f32) * 0.3).sin();
1074 }
1075 pcm[256 * 3 + 100] = 0.9;
1076 pcm[256 * 3 + 101] = -0.9;
1077 let stats = encode_one(&pcm);
1078 assert_eq!(stats.blksw_blocks, 1, "{stats:?}");
1079 assert!(stats.d25 >= 1 && stats.d15 == 0, "{stats:?}");
1080 }
1081
1082 #[test]
1083 fn smoothed_exponents_never_rise_and_always_fit_the_group_coding() {
1084 let mut e = [24u8; COEFFS];
1085 e[100] = 1;
1086 e[0] = 20;
1087 let ideal = e;
1088 smooth_exps(&mut e);
1089 assert!(e.iter().zip(&ideal).all(|(s, i)| s <= i));
1090 assert!(e.windows(2).all(|w| (i32::from(w[0]) - i32::from(w[1])).abs() <= 2));
1091 assert_eq!((e[0], e[99], e[100], e[101]), (15, 3, 1, 3));
1092 let mut again = e;
1093 smooth_exps(&mut again);
1094 assert_eq!(again, e);
1095 }
1096
1097 #[test]
1098 fn tdac_direct_forward_reconstructs() {
1099 let enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap();
1100 let window = enc.window;
1101 // A/52's forward carries -2/N.
1102 let err = tdac(|x| {
1103 let mut s = direct_forward(x, &window);
1104 for v in &mut s {
1105 *v *= -2.0 / 512.0;
1106 }
1107 s
1108 });
1109 assert!(err < 1e-4, "direct forward + Imdct TDAC error {err}");
1110 }
1111
1112 #[test]
1113 fn tdac_ec_dsp_forward_reconstructs() {
1114 let mut enc = Ac3Encoder::new(EncoderConfig { sample_rate: 48000, channels: 1, bitrate_kbps: 192 }).unwrap();
1115 let window = enc.window;
1116 let cell = std::cell::RefCell::new(&mut enc.mdct);
1117 let err = tdac(|x| {
1118 let mut s = [0.0f32; COEFFS];
1119 cell.borrow_mut().forward_windowed(x, &window, &mut s);
1120 for v in &mut s {
1121 *v *= FORWARD_GAIN;
1122 }
1123 s
1124 });
1125 assert!(err < 1e-4, "ec_dsp forward + Imdct TDAC error {err}");
1126 }
1127}