forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'ac3-enc': AC-3 encoder (block switching, exponent planner, rate loop) + shim

Browse files at this commit

dc51bffe48da7d8f50097eb88a44870673c59654Ahmet Kaan GümüşParent: b7c132ef8b6839
crates/ec-ac3/src/encode.rsadded+1127 -0
@@ -0,0 +1,1127 @@
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+
17+use ec_core::{
18+ AudioParameters, BitWriter, Buf, ChannelLayout, CodecId, CodecParameters, Encoder, Error,
19+ Frame, MediaParameters, Packet, Result, SampleFormat, TimeBase,
20+};
21+use ec_dsp::Mdct;
22+
23+use crate::bitalloc::{self, Allocation, BitAllocParams, Channel};
24+use crate::bsi::Acmod;
25+use crate::exps::Strategy;
26+use crate::transform::Imdct;
27+use crate::tables::{BIT_RATE_KBPS, FRAME_SIZE_WORDS, QNTZTAB, QUANT_LEVELS, SAMPLE_RATE, WINDOW};
28+
29+/// Samples per channel one syncframe codes.
30+const FRAME_SAMPLES: usize = 1536;
31+/// Blocks per syncframe.
32+const BLOCKS: usize = 6;
33+/// Coefficients per channel per block ([`crate::decode::COEFFS`], not public).
34+const 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.
38+const MIN_KBPS_PER_CHANNEL: u32 = 32;
39+/// Bit allocation parameters (§7.2.2.3), constant for every frame.
40+const BA_PARAMS: BitAllocParams = BitAllocParams { sdcycod: 2, fdcycod: 1, sgaincod: 1, dbpbcod: 2, floorcod: 7 };
41+/// Fast gain code, constant for every channel and frame.
42+const FGAINCOD: u8 = 4;
43+/// [`envelope_moved`]: exponent steps (6 dB each) a band's peak may drift
44+/// before the block re-sends exponents.
45+const RESEND_STEPS: u8 = 2;
46+/// [`is_transient`]: a segment this many times louder than everything before it.
47+const TRANSIENT_RATIO: f32 = 8.0;
48+/// [`is_transient`]: segment energy (64 high-passed samples) below which
49+/// nothing is an attack.
50+const TRANSIENT_FLOOR: f32 = 1e-2;
51+/// LFE `endmant`, fixed by the standard.
52+const 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.
57+const 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_*`.
60+const SHORT_GAIN: f32 = 1.0 / 128.0;
61+
62+/// How the encoder is set up.
63+#[derive(Debug, Clone, Copy, PartialEq)]
64+pub 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.
79+fn 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.
100+fn 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.
119+fn 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`].
136+fn 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.
149+fn 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.
193+fn 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.
207+fn 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.
223+pub 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+
252+impl 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.
763+struct 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)]
778+pub 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`]).
800+fn 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.
813+fn 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).
829+fn 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)`.
848+fn 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.
862+fn 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).
875+fn 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.
898+fn 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.
903+fn 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+
911+impl 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)]
956+mod 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+}
crates/ec-ac3/src/lib.rsmodified+10 -2
@@ -10,8 +10,14 @@
1010 //!
1111 //! Contracts worth knowing before implementing against this crate:
1212 //!
13-//! - **Decode only.** Nothing here encodes AC-3; the format is a decode-side
14-//! concern for this family.
13+//! - **Encoding has no psychoacoustic model yet.** [`Ac3Encoder`] writes
14+//! spec-valid syncframes — real MDCT, per-block/channel transient-driven
15+//! block switching, an exponent planner (D15/D25/D45/reuse) and a
16+//! binary-searched SNR-offset rate loop that fills a frame to roughly
17+//! 93-99.6% of its budget depending on content and bit rate — but the bit
18+//! allocation curve itself is the standard's masking model rather than a
19+//! perceptual search; see [`encode`] for exactly what is and is not
20+//! adaptive yet.
1521 //! - **Truncated input is [`Error::NeedMore`]**, a broken bit stream is
1622 //! [`Error::Corrupt`], and a construct this build does not implement is
1723 //! [`Error::Unsupported`] naming *what* and *why*. No input panics — the bit
@@ -62,9 +68,11 @@ pub mod transform;
6268
6369 mod decode;
6470 mod decoder;
71+pub mod encode;
6572
6673 pub use decode::Syntax;
6774 pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options};
75+pub use encode::{Ac3Encoder, EncodeStats, EncoderConfig};
6876 pub use ec_core::Error;
6977
7078 /// Samples per channel one audio block produces.
crates/ec-ac3/tests/encode_matrix.rsadded+422 -0
@@ -0,0 +1,422 @@
1+//! Encoder coverage: frames our own decoder round-trips, and that ffmpeg
2+//! (when present) accepts as valid AC-3 and decodes to the same audio — on
3+//! synthetic signals and on the real 16-bit fixtures, at every rate and
4+//! layout the encoder offers.
5+
6+use std::path::Path;
7+use std::process::Command;
8+
9+use ec_ac3::{Ac3Decoder, Ac3Encoder, EncoderConfig};
10+
11+fn have_ffmpeg() -> bool {
12+ Command::new("ffmpeg")
13+ .arg("-version")
14+ .output()
15+ .is_ok_and(|o| o.status.success())
16+}
17+
18+/// 440 Hz tone for 1 s, then 0.5 s of silence, interleaved across `channels`.
19+fn tone_then_silence(sample_rate: u32, channels: usize) -> Vec<f32> {
20+ let tone_samples = sample_rate as usize;
21+ let silence_samples = sample_rate as usize / 2;
22+ let mut out = Vec::with_capacity((tone_samples + silence_samples) * channels);
23+ for n in 0..tone_samples {
24+ let t = n as f32 / sample_rate as f32;
25+ let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
26+ for _ in 0..channels {
27+ out.push(v);
28+ }
29+ }
30+ out.extend(std::iter::repeat_n(0.0f32, silence_samples * channels));
31+ out
32+}
33+
34+fn correlation(a: &[f32], b: &[f32]) -> f64 {
35+ let n = a.len().min(b.len());
36+ if n == 0 {
37+ return 0.0;
38+ }
39+ let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0);
40+ for i in 0..n {
41+ let (x, y) = (f64::from(a[i]), f64::from(b[i]));
42+ sa += x;
43+ sb += y;
44+ saa += x * x;
45+ sbb += y * y;
46+ sab += x * y;
47+ }
48+ let n = n as f64;
49+ let cov = sab / n - (sa / n) * (sb / n);
50+ let va = (saa / n - (sa / n).powi(2)).max(0.0);
51+ let vb = (sbb / n - (sb / n).powi(2)).max(0.0);
52+ if va <= 0.0 || vb <= 0.0 {
53+ return 1.0; // both flat (silence): trivially aligned
54+ }
55+ cov / (va.sqrt() * vb.sqrt())
56+}
57+
58+/// Encoder priming, `Ac3Encoder::encoder_delay`: the decoded stream starts
59+/// with this many samples of silence per channel.
60+const DELAY: usize = 256;
61+
62+/// Lag-searched correlation on one channel after the priming is dropped,
63+/// +/- 64 samples of slack: a bug that shifts the audio by a block shows up
64+/// as ~0 here, where an unbounded search on a periodic signal would hide it.
65+fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 {
66+ let b = &b[DELAY.min(b.len())..];
67+ let mut best = -1.0f64;
68+ for lag in -64i32..=64 {
69+ let (sa, sb): (&[f32], &[f32]) = if lag >= 0 {
70+ (&a[lag as usize..], b)
71+ } else {
72+ (a, &b[(-lag) as usize..])
73+ };
74+ best = best.max(correlation(sa, sb));
75+ }
76+ best
77+}
78+
79+/// Deinterleave channel `ch` of `channels`.
80+fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec<f32> {
81+ interleaved
82+ .iter()
83+ .skip(ch)
84+ .step_by(channels)
85+ .copied()
86+ .collect()
87+}
88+
89+/// The fixture's PCM decoded by ffmpeg, with its rate and channel count; None
90+/// without ffmpeg.
91+fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
92+ let out = Command::new("ffmpeg")
93+ .args(["-v", "error", "-i"])
94+ .arg(path)
95+ .args(["-f", "f32le", "-"])
96+ .output()
97+ .ok()?;
98+ if !out.status.success() {
99+ return None;
100+ }
101+ let samples = out
102+ .stdout
103+ .chunks_exact(4)
104+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
105+ .collect();
106+ let probe = ffprobe(path, "channels,sample_rate");
107+ let field = |key: &str| probe_field(&probe, key).and_then(|v| v.parse::<u32>().ok());
108+ Some((samples, field("sample_rate")?, field("channels")? as usize))
109+}
110+
111+fn ffprobe(path: &Path, entries: &str) -> String {
112+ let out = Command::new("ffprobe")
113+ .args(["-v", "error", "-select_streams", "a:0", "-show_entries"])
114+ .arg(format!("stream={entries}"))
115+ .args(["-of", "default=noprint_wrappers=1"])
116+ .arg(path)
117+ .output()
118+ .expect("ffprobe");
119+ String::from_utf8_lossy(&out.stdout).into_owned()
120+}
121+
122+fn probe_field(text: &str, key: &str) -> Option<String> {
123+ text.lines()
124+ .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
125+ .map(|v| v.trim().to_owned())
126+}
127+
128+/// ffmpeg's decode of an AC-3 file, asserting it voiced no complaint.
129+fn oracle_decode(path: &Path) -> Vec<f32> {
130+ let out = Command::new("ffmpeg")
131+ .args(["-v", "warning", "-i"])
132+ .arg(path)
133+ .args(["-f", "f32le", "-"])
134+ .output()
135+ .expect("ffmpeg");
136+ let stderr = String::from_utf8_lossy(&out.stderr);
137+ let complaint = stderr
138+ .lines()
139+ .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k)));
140+ assert!(!complaint, "ffmpeg complained about {}:\n{stderr}", path.display());
141+ out.stdout
142+ .chunks_exact(4)
143+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
144+ .collect()
145+}
146+
147+fn encode_with_stats(config: EncoderConfig, pcm: &[f32]) -> (Vec<u8>, ec_ac3::EncodeStats) {
148+ let mut enc = Ac3Encoder::new(config).unwrap();
149+ enc.push_pcm_f32(pcm).unwrap();
150+ enc.finish();
151+ let mut out = Vec::new();
152+ loop {
153+ match enc.next_packet() {
154+ Ok(frame) => out.extend_from_slice(&frame),
155+ Err(e) if e.is_eof() => break,
156+ Err(e) => panic!("{e}"),
157+ }
158+ }
159+ (out, enc.stats())
160+}
161+
162+fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec<u8> {
163+ encode_with_stats(config, pcm).0
164+}
165+
166+/// Worst per-channel lag-searched correlation between `want` and `got`.
167+fn worst_corr(want: &[f32], got: &[f32], channels: usize) -> f64 {
168+ (0..channels)
169+ .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch)))
170+ .fold(1.0, f64::min)
171+}
172+
173+/// [`worst_corr`] over the full-bandwidth channels only: the LFE (family slot
174+/// 3 of six) is band-limited to 7 bins (~660 Hz at 48 kHz) by the standard,
175+/// so a fixture whose LFE carries full-band content can never correlate with
176+/// it; that channel is gated on our decoder agreeing with the oracle instead.
177+fn worst_fbw_corr(want: &[f32], got: &[f32], channels: usize) -> f64 {
178+ (0..channels)
179+ .filter(|&ch| !(channels == 6 && ch == 3))
180+ .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch)))
181+ .fold(1.0, f64::min)
182+}
183+
184+/// Deterministic white noise, `len` interleaved samples.
185+fn noise(len: usize, seed: &mut u64) -> Vec<f32> {
186+ (0..len)
187+ .map(|_| {
188+ *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
189+ ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
190+ })
191+ .collect()
192+}
193+
194+fn decode_all(data: &[u8], channels: usize) -> Vec<f32> {
195+ let mut decoder = Ac3Decoder::new();
196+ let mut out = Vec::new();
197+ let mut pos = 0;
198+ while pos + 6 <= data.len() {
199+ let size = ec_ac3::frame_size(&data[pos..]).unwrap();
200+ assert!(pos + size <= data.len(), "frame overruns the stream");
201+ let frame = decoder
202+ .decode_frame(&data[pos..pos + size])
203+ .unwrap_or_else(|e| panic!("frame at byte {pos}: {e}"));
204+ assert_eq!(frame.samples, 1536);
205+ assert_eq!(frame.channels(), channels);
206+ out.extend(
207+ frame.data[0]
208+ .chunks_exact(4)
209+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
210+ );
211+ pos += size;
212+ }
213+ out
214+}
215+
216+#[test]
217+fn silence_and_tone_frames_decode_in_our_decoder() {
218+ for &(sample_rate, channels) in &[(48_000u32, 1u16), (48_000, 2), (48_000, 6), (44_100, 2)] {
219+ let config = EncoderConfig {
220+ sample_rate,
221+ channels,
222+ bitrate_kbps: if channels >= 5 { 384 } else { 192 },
223+ };
224+ let pcm = tone_then_silence(sample_rate, channels as usize);
225+ let data = encode(config, &pcm);
226+ assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames");
227+ let decoded = decode_all(&data, channels as usize);
228+ assert!(!decoded.is_empty());
229+ let corr = worst_corr(&pcm, &decoded, channels as usize);
230+ assert!(corr >= 0.95, "{sample_rate} Hz {channels}ch: corr {corr}");
231+ }
232+}
233+
234+#[test]
235+fn oracle_accepts_our_frames() {
236+ if !have_ffmpeg() {
237+ eprintln!("skipping: ffmpeg not found");
238+ return;
239+ }
240+ let config = EncoderConfig {
241+ sample_rate: 48_000,
242+ channels: 2,
243+ bitrate_kbps: 192,
244+ };
245+ let pcm = tone_then_silence(48_000, 2);
246+ let data = encode(config, &pcm);
247+ let dir = std::env::temp_dir();
248+ let path = dir.join("ec_ac3_encode_matrix_oracle.ac3");
249+ std::fs::write(&path, &data).unwrap();
250+
251+ let out = Command::new("ffmpeg")
252+ .args(["-v", "warning", "-i"])
253+ .arg(&path)
254+ .args(["-f", "f32le", "-"])
255+ .output()
256+ .expect("ffmpeg");
257+ let stderr = String::from_utf8_lossy(&out.stderr);
258+ let complaint = stderr
259+ .lines()
260+ .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k)));
261+ assert!(
262+ !complaint,
263+ "ffmpeg complained about our frames:\n{stderr}"
264+ );
265+
266+ let decoded: Vec<f32> = out
267+ .stdout
268+ .chunks_exact(4)
269+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
270+ .collect();
271+ for ch in 0..2 {
272+ let want = take_channel(&pcm, 2, ch);
273+ let got = take_channel(&decoded, 2, ch);
274+ let corr = best_lag_correlation(&want, &got);
275+ assert!(corr >= 0.95, "oracle channel {ch} corr {corr}");
276+ }
277+
278+ let _ = std::fs::remove_file(Path::new(&path));
279+}
280+
281+
282+/// The full fixture matrix: every wav16 fixture at its layout's bit rate,
283+/// through our decoder and the oracle, with ffprobe agreeing on what was
284+/// asked for. Prints the per-file numbers and the stereo strategy shares.
285+#[test]
286+fn real_fixtures_round_trip_through_our_decoder_and_the_oracle() {
287+ if !have_ffmpeg() {
288+ eprintln!("skipping: ffmpeg not found");
289+ return;
290+ }
291+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio");
292+ let mut failures = Vec::new();
293+ for layout in ["mono", "stereo", "5.1"] {
294+ for rate in [48_000u32, 44_100] {
295+ let path = root.join(format!("wav16-{layout}-{rate}.wav"));
296+ let (pcm, sample_rate, channels) = read_wav(&path).unwrap_or_else(|| panic!("{}", path.display()));
297+ assert_eq!(sample_rate, rate);
298+ let bitrate_kbps = match channels { 1 => 96, 2 => 192, _ => 448 };
299+ let config = EncoderConfig { sample_rate, channels: channels as u16, bitrate_kbps };
300+ let (data, stats) = encode_with_stats(config, &pcm);
301+ let frame = ec_ac3::frame_size(&data).unwrap();
302+ assert_eq!(data.len() % frame, 0, "{layout} {rate}: frames are not all {frame} bytes");
303+
304+ let decoded = decode_all(&data, channels);
305+ let ours = worst_fbw_corr(&pcm, &decoded, channels);
306+ let out = std::env::temp_dir().join(format!("ec_ac3_encode_matrix_{layout}_{rate}.ac3"));
307+ std::fs::write(&out, &data).unwrap();
308+ let oracle_pcm = oracle_decode(&out);
309+ let oracle = worst_fbw_corr(&pcm, &oracle_pcm, channels);
310+ if channels == 6 {
311+ let lfe = correlation(&take_channel(&decoded, 6, 3), &take_channel(&oracle_pcm, 6, 3));
312+ assert!(lfe >= 0.99, "{layout} {rate}: LFE ours vs oracle corr {lfe}");
313+ }
314+ let probe = ffprobe(&out, "channels,channel_layout,sample_rate,bit_rate");
315+ let _ = std::fs::remove_file(&out);
316+
317+ let total = (stats.d15 + stats.d25 + stats.d45 + stats.reuse) as f64;
318+ let share = |n: u64| n as f64 / total * 100.0;
319+ eprintln!(
320+ "{layout} {rate}: {} frames, ours {ours:.4} oracle {oracle:.4}, csnroffst mean {:.1}, fill {:.1}%, blksw {}, D15 {:.1}% D25 {:.1}% D45 {:.1}% REUSE {:.1}%",
321+ stats.frames,
322+ stats.csnroffst_sum as f64 / stats.frames as f64,
323+ stats.bits_used as f64 / stats.bits_budget as f64 * 100.0,
324+ stats.blksw_blocks,
325+ share(stats.d15), share(stats.d25), share(stats.d45), share(stats.reuse),
326+ );
327+ if ours < 0.99 || oracle < 0.99 {
328+ failures.push(format!("{layout} {rate}: ours {ours:.4} oracle {oracle:.4}"));
329+ }
330+ assert!(stats.bits_used * 10 > stats.bits_budget * 9, "{layout} {rate}: rate loop left bits unused: {stats:?}");
331+ let expect_layout = match channels { 1 => "mono", 2 => "stereo", _ => "5.1" };
332+ assert_eq!(probe_field(&probe, "channels").as_deref(), Some(channels.to_string().as_str()), "{probe}");
333+ assert!(probe_field(&probe, "channel_layout").is_some_and(|l| l.starts_with(expect_layout)), "{probe}");
334+ assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some(rate.to_string().as_str()), "{probe}");
335+ assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some((bitrate_kbps * 1000).to_string().as_str()), "{probe}");
336+ }
337+ }
338+ assert!(failures.is_empty(), "corr < 0.99:\n{}", failures.join("\n"));
339+}
340+
341+/// A train of sharp attacks (decaying 2 kHz bursts, 25 per second) over a
342+/// quiet noise floor: every attack is a block switch, and the stream still
343+/// round-trips through both decoders.
344+#[test]
345+fn click_train_switches_blocks_and_still_round_trips() {
346+ let channels = 2;
347+ let mut pcm = noise(48_000 * channels, &mut 11u64);
348+ for v in &mut pcm {
349+ *v *= 0.01;
350+ }
351+ for n in (500..48_000).step_by(1900) {
352+ for i in 0..200 {
353+ let v = 0.8 * (-(i as f32) / 40.0).exp() * (i as f32 * 2.0 * std::f32::consts::PI * 2000.0 / 48_000.0).sin();
354+ for ch in 0..channels {
355+ pcm[(n + i) * channels + ch] += v;
356+ }
357+ }
358+ }
359+ let config = EncoderConfig { sample_rate: 48_000, channels: 2, bitrate_kbps: 192 };
360+ let (data, stats) = encode_with_stats(config, &pcm);
361+ assert!(stats.blksw_blocks >= 20, "{stats:?}");
362+ let corr = worst_corr(&pcm, &decode_all(&data, channels), channels);
363+ eprintln!("click train: ours {corr:.4}, {stats:?}");
364+ assert!(corr >= 0.95, "click train corr {corr}");
365+ if have_ffmpeg() {
366+ let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3");
367+ std::fs::write(&out, &data).unwrap();
368+ let corr = worst_corr(&pcm, &oracle_decode(&out), channels);
369+ let _ = std::fs::remove_file(&out);
370+ eprintln!("click train: oracle {corr:.4}");
371+ assert!(corr >= 0.95, "click train oracle corr {corr}");
372+ }
373+}
374+
375+#[test]
376+fn tone_at_32khz_round_trips() {
377+ let rate = 32_000;
378+ let pcm: Vec<f32> = (0..rate as usize * 2)
379+ .flat_map(|n| {
380+ let t = n as f32 / rate as f32;
381+ let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
382+ [v, 0.5 * v]
383+ })
384+ .collect();
385+ let config = EncoderConfig { sample_rate: rate, channels: 2, bitrate_kbps: 96 };
386+ let data = encode(config, &pcm);
387+ let corr = worst_corr(&pcm, &decode_all(&data, 2), 2);
388+ assert!(corr >= 0.99, "32 kHz ours corr {corr}");
389+ if have_ffmpeg() {
390+ let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3");
391+ std::fs::write(&out, &data).unwrap();
392+ let corr = worst_corr(&pcm, &oracle_decode(&out), 2);
393+ let probe = ffprobe(&out, "sample_rate,bit_rate");
394+ let _ = std::fs::remove_file(&out);
395+ assert!(corr >= 0.99, "32 kHz oracle corr {corr}");
396+ assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}");
397+ assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}");
398+ }
399+}
400+
401+/// 200 random (rate, channels, bit rate) configurations, two frames of
402+/// noise each: nothing panics and our decoder takes every frame.
403+#[test]
404+fn random_configs_never_panic_and_always_decode() {
405+ let (mut seed, mut noise_seed) = (99u64, 7u64);
406+ let mut next = |n: u64| {
407+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
408+ (seed >> 33) % n
409+ };
410+ for _ in 0..200 {
411+ let sample_rate = ec_ac3::tables::SAMPLE_RATE[next(3) as usize];
412+ let channels = next(6) as u16 + 1;
413+ let bitrate_kbps = ec_ac3::tables::BIT_RATE_KBPS[next(ec_ac3::tables::BIT_RATE_KBPS.len() as u64) as usize];
414+ let config = EncoderConfig { sample_rate, channels, bitrate_kbps };
415+ let pcm = noise(1536 * 2 * channels as usize, &mut noise_seed);
416+ let data = encode(config, &pcm);
417+ let decoded = decode_all(&data, channels as usize);
418+ assert!(decoded.len() >= pcm.len() + 256, "{config:?}: {} of {} samples", decoded.len(), pcm.len());
419+ }
420+}
421+
422+
fixturesadded+1 -0
@@ -0,0 +1 @@
1+/home/user/Documents/Code/Rust/edith_codecs/fixtures
\ No newline at end of file
shims/oxideav-ac3/src/lib.rsmodified+122 -0
@@ -23,6 +23,12 @@
2323 //! [`CodecParameters::channels`] and `ec_ac3` takes a [`Downmix`] mode; the
2424 //! factory translates. `Some(2)` is the A/52 §7.8 stereo fold the replica
2525 //! asks for on anything wider than mono, `None` the stream's own layout.
26+//!
27+//! Encoding is not on the incumbent's own surface, so [`Ac3Encoder`] is
28+//! shaped after this family's other software encoder shim instead —
29+//! `rusty_aac::AacEncoder`'s `new`/`push_pcm_f32`/`next_packet`/
30+//! `encoder_delay` — so an export path already wired to one SW audio
31+//! encoder here can add this one the same way.
2632
2733 #![forbid(unsafe_code)]
2834
@@ -101,6 +107,49 @@ fn s16le(samples: &[u8]) -> Vec<u8> {
101107 out
102108 }
103109
110+/// How [`Ac3Encoder::new`] is configured.
111+pub struct EncoderConfig {
112+ pub sample_rate: u32,
113+ pub channels: u16,
114+ pub bitrate_kbps: u32,
115+}
116+
117+/// An AC-3 encoder: PCM in, syncframes out.
118+pub struct Ac3Encoder(ec_ac3::Ac3Encoder);
119+
120+impl Ac3Encoder {
121+ pub fn new(sample_rate: u32, channels: u16, bitrate_kbps: u32) -> Result<Ac3Encoder> {
122+ Ok(Ac3Encoder(ec_ac3::Ac3Encoder::new(ec_ac3::EncoderConfig {
123+ sample_rate,
124+ channels,
125+ bitrate_kbps,
126+ })?))
127+ }
128+
129+ /// Samples of priming delay before the first audible one; a muxer states
130+ /// this on the track's edit list / codec delay.
131+ pub fn encoder_delay(&self) -> usize {
132+ self.0.encoder_delay()
133+ }
134+
135+ /// Feeds interleaved `f32` PCM, family order (L, R, C, LFE, Ls, Rs).
136+ pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> {
137+ Ok(self.0.push_pcm_f32(interleaved)?)
138+ }
139+
140+ /// Ends the stream, padding and flushing the last frame.
141+ pub fn finish(&mut self) {
142+ self.0.finish();
143+ }
144+
145+ /// The next encoded syncframe; [`oxideav_core::Error`] with the
146+ /// underlying `Eof`/`NeedMore` distinction once drained after
147+ /// [`Ac3Encoder::finish`] or before enough PCM has arrived.
148+ pub fn next_packet(&mut self) -> Result<Vec<u8>> {
149+ Ok(self.0.next_packet()?)
150+ }
151+}
152+
104153 #[cfg(test)]
105154 mod tests {
106155 use super::*;
@@ -126,4 +175,77 @@ mod tests {
126175 assert!(registry.has_decoder(&CodecId::new("eac3")));
127176 assert!(!registry.has_decoder(&CodecId::new("truehd")));
128177 }
178+
179+ /// One second of stereo through [`Ac3Encoder`], then back through this
180+ /// shim's own decoder: after dropping the encoder's priming delay, the
181+ /// two channels should still correlate almost perfectly with the source.
182+ #[test]
183+ fn encode_then_decode_round_trips() {
184+ let sample_rate = 48000u32;
185+ let seconds = 1.0f32;
186+ let n = (sample_rate as f32 * seconds) as usize;
187+ let mut pcm = vec![0.0f32; n * 2];
188+ for i in 0..n {
189+ let t = i as f32 / sample_rate as f32;
190+ pcm[2 * i] = 0.4 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
191+ pcm[2 * i + 1] = 0.4 * (2.0 * std::f32::consts::PI * 660.0 * t).sin();
192+ }
193+
194+ let mut enc = Ac3Encoder::new(sample_rate, 2, 192).unwrap();
195+ enc.push_pcm_f32(&pcm).unwrap();
196+ enc.finish();
197+ let mut bitstream = Vec::new();
198+ loop {
199+ match enc.next_packet() {
200+ Ok(packet) => bitstream.extend_from_slice(&packet),
201+ Err(_) => break,
202+ }
203+ }
204+
205+ let mut registry = CodecRegistry::new();
206+ register_codecs(&mut registry);
207+ let params = CodecParameters {
208+ channels: Some(2),
209+ ..CodecParameters::audio(CodecId::new("ac3"))
210+ };
211+ let mut dec = registry.first_decoder(&params).unwrap();
212+
213+ let mut decoded_s16: Vec<i16> = Vec::new();
214+ let mut offset = 0;
215+ while offset < bitstream.len() {
216+ let len = ec_ac3::frame_size(&bitstream[offset..]).unwrap();
217+ let packet = oxideav_core::Packet::new(
218+ 0,
219+ oxideav_core::TimeBase::new(1, sample_rate.into()),
220+ bitstream[offset..offset + len].to_vec(),
221+ );
222+ dec.send_packet(&packet).unwrap();
223+ offset += len;
224+ while let Ok(Frame::Audio(frame)) = dec.receive_frame() {
225+ for plane in &frame.data {
226+ decoded_s16.extend(plane.chunks_exact(2).map(|b| i16::from_le_bytes([b[0], b[1]])));
227+ }
228+ }
229+ }
230+ let decoded: Vec<f32> = decoded_s16.iter().map(|&s| s as f32 / 32768.0).collect();
231+
232+ // Drop the encoder's priming delay (one block, both channels).
233+ let delay = enc.encoder_delay() * 2;
234+ let decoded = &decoded[delay.min(decoded.len())..];
235+ let source = &pcm[..decoded.len().min(pcm.len())];
236+ let decoded = &decoded[..source.len()];
237+
238+ let mean_s = source.iter().sum::<f32>() / source.len() as f32;
239+ let mean_d = decoded.iter().sum::<f32>() / decoded.len() as f32;
240+ let mut num = 0.0f64;
241+ let (mut den_s, mut den_d) = (0.0f64, 0.0f64);
242+ for (&s, &d) in source.iter().zip(decoded.iter()) {
243+ let (s, d) = ((s - mean_s) as f64, (d - mean_d) as f64);
244+ num += s * d;
245+ den_s += s * s;
246+ den_d += d * d;
247+ }
248+ let corr = num / (den_s.sqrt() * den_d.sqrt());
249+ assert!(corr >= 0.99, "round-trip correlation too low: {corr}");
250+ }
129251 }