forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.2 MiBe18142dTahinli5 hours ago4543 commits

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