forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB210dfc8Tahinli3 months ago835 commits

encode.rs1108 lines, 38.9 KiBHistoryRawDownload
1//! AAC-LC encoding: psychoacoustics, window decision, quantisation and the
2//! `raw_data_block` writer.
3//!
4//! The psychoacoustic model is the classic three-stage one, and this is exactly
5//! what it does: a 2048-point FFT of the windowed input gives per-band energy;
6//! energy is spread across bands with a two-slope spreading function at
7//! scalefactor-band resolution; tonality is estimated by each band's spectral
8//! flatness (**not** by phase unpredictability, which needs two frames of
9//! history for a fraction of a dB); the signal-to-mask ratio runs from 6 dB on
10//! noise-like bands to 24 dB on tonal ones. Rate control is the two-loop
11//! search of the informative part of ISO/IEC 14496-3: an inner distortion loop
12//! choosing each band's scalefactor against its mask, and an outer rate loop
13//! over a common offset, against a bit reservoir.
14//!
15//! The window decision is shared by every channel of a frame, which is what
16//! lets a channel pair use `common_window` and therefore mid/side coding.
17//!
18//! Band, group and window indices are the domain's own coordinates and address
19//! several parallel arrays at once, so the loops here are written over indices
20//! rather than iterators.
21#![allow(clippy::needless_range_loop)]
22
23use std::sync::LazyLock;
24
25use ec_core::{BitWriter, Error, Result};
26use ec_dsp::{Complex, Mdct, RealFft, Window};
27
28use crate::config::{AdtsHeader, config_for_channels, sf_index_for_rate};
29use crate::decode::{FRAME_LEN, SHORT_LEN, WindowSequence};
30use crate::tables::{CODEBOOKS, Codebook, SCALEFACTOR_CODES, SWB_LONG, SWB_SHORT};
31
32const SF_OFFSET: i32 = 100;
33/// The decoder divides by this; the encoder multiplies by it, so a round trip
34/// is unity gain.
35const INPUT_SCALE: f32 = 65536.0;
36/// Quantiser rounding bias of the informative encoder (§4.6.2).
37const ROUND_BIAS: f32 = 0.4054;
38/// Ceiling on what the reservoir may lend one frame, per channel.
39const RESERVOIR_MAX: i32 = 6144;
40/// Largest magnitude the escape codebook can carry.
41const MAX_QUANT: i32 = 8191;
42/// Masking floor relative to the loudest band of the frame, standing in for the
43/// absolute threshold of hearing (see [`AacEncoder::psychoacoustics`]).
44const ATH_FLOOR: f32 = 1e-7;
45
46/// Which window shape the encoder asks for.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
48pub enum WindowShape {
49 /// Sine window everywhere.
50 #[default]
51 Sine,
52 /// Kaiser-Bessel-derived everywhere: better stop-band rejection, which
53 /// suits tonal material.
54 Kbd,
55}
56
57/// Encoder options.
58#[derive(Debug, Clone, Copy)]
59pub struct AacEncoderConfig {
60 /// Target bitrate in bits per second, over all channels.
61 pub bitrate_bps: u32,
62 /// Window shape policy.
63 pub window_shape: WindowShape,
64 /// Emit ADTS framing around each packet instead of a bare `raw_data_block`.
65 pub adts: bool,
66 /// Allow mid/side coding on channel pairs.
67 pub mid_side: bool,
68 /// Allow the long/short window switch on transients.
69 pub window_switching: bool,
70}
71
72impl Default for AacEncoderConfig {
73 fn default() -> AacEncoderConfig {
74 AacEncoderConfig {
75 bitrate_bps: 128_000,
76 window_shape: WindowShape::Sine,
77 adts: false,
78 mid_side: true,
79 window_switching: true,
80 }
81 }
82}
83
84/// One encoded access unit.
85#[derive(Debug, Clone)]
86pub struct EncodedPacket {
87 pub data: Vec<u8>,
88 /// Presentation time in samples (frame index * 1024).
89 pub pts: i64,
90 /// Duration in samples; always one AAC frame.
91 pub duration: u32,
92}
93
94/// One channel's transform and masking thresholds for a frame.
95#[derive(Clone)]
96struct ChannelFrame {
97 /// MDCT coefficients, window-major for short sequences.
98 coef: Vec<f32>,
99 /// Masking threshold per band.
100 threshold: Vec<f32>,
101}
102
103/// An AAC-LC encoder.
104pub struct AacEncoder {
105 config: AacEncoderConfig,
106 sample_rate: u32,
107 sf_index: u8,
108 channels: usize,
109 /// Input not yet turned into frames, per channel.
110 pcm: Vec<Vec<f32>>,
111 /// The previous frame's samples, the MDCT block's left half.
112 prev: Vec<Vec<f32>>,
113 seq: WindowSequence,
114 energy: f32,
115 mdct_long: Mdct<f32>,
116 mdct_short: Mdct<f32>,
117 fft: RealFft<f32>,
118 sine_long: Vec<f32>,
119 kbd_long: Vec<f32>,
120 sine_short: Vec<f32>,
121 kbd_short: Vec<f32>,
122 queue: std::collections::VecDeque<EncodedPacket>,
123 frames_out: i64,
124 reservoir: i32,
125 flushed: bool,
126 initialised: bool,
127}
128
129impl AacEncoder {
130 /// Samples this encoder emits before the first audible one: one MDCT
131 /// window's worth, always, because the very first frame has no previous
132 /// block to overlap-add against and is pure priming. A muxer writing this
133 /// track's `elst`/`CodecDelay` states it here.
134 pub fn encoder_delay(&self) -> usize {
135 1024
136 }
137
138 pub fn new(config: AacEncoderConfig) -> AacEncoder {
139 AacEncoder {
140 config,
141 sample_rate: 0,
142 sf_index: 3,
143 channels: 0,
144 pcm: Vec::new(),
145 prev: Vec::new(),
146 seq: WindowSequence::OnlyLong,
147 energy: 0.0,
148 mdct_long: Mdct::new(2 * FRAME_LEN),
149 mdct_short: Mdct::new(2 * SHORT_LEN),
150 fft: RealFft::new(2 * FRAME_LEN),
151 sine_long: Window::<f32>::sine(2 * FRAME_LEN).as_slice().to_vec(),
152 kbd_long: Window::<f32>::kbd(2 * FRAME_LEN, 4.0).as_slice().to_vec(),
153 sine_short: Window::<f32>::sine(2 * SHORT_LEN).as_slice().to_vec(),
154 kbd_short: Window::<f32>::kbd(2 * SHORT_LEN, 6.0).as_slice().to_vec(),
155 queue: std::collections::VecDeque::new(),
156 frames_out: 0,
157 reservoir: 0,
158 flushed: false,
159 initialised: false,
160 }
161 }
162
163 /// The stream's sample rate; 0 until the first PCM arrives.
164 pub fn sample_rate(&self) -> u32 {
165 self.sample_rate
166 }
167
168 /// The stream's channel count; 0 until the first PCM arrives.
169 pub fn channels(&self) -> u16 {
170 self.channels as u16
171 }
172
173 /// The AudioSpecificConfig a container needs for this stream.
174 pub fn audio_specific_config(&self) -> Vec<u8> {
175 crate::config::audio_specific_config_bytes(self.sample_rate, self.channels as u16)
176 }
177
178 fn init(&mut self, channels: u16, sample_rate: u32) -> Result<()> {
179 if self.initialised {
180 if self.channels != usize::from(channels) || self.sample_rate != sample_rate {
181 return Err(Error::corrupt("aac: stream parameters changed mid-encode"));
182 }
183 return Ok(());
184 }
185 let sf_index = sf_index_for_rate(sample_rate).ok_or_else(|| {
186 Error::unsupported("aac", format!("{sample_rate} Hz is not an AAC sample rate"))
187 })?;
188 if channels == 0 || channels == 7 || channels > 8 {
189 return Err(Error::unsupported(
190 "aac",
191 format!("{channels} channels has no channelConfiguration"),
192 ));
193 }
194 self.sf_index = sf_index;
195 self.sample_rate = sample_rate;
196 self.channels = usize::from(channels);
197 self.pcm = vec![Vec::new(); self.channels];
198 self.prev = vec![vec![0.0; FRAME_LEN]; self.channels];
199 self.initialised = true;
200 Ok(())
201 }
202
203 /// Appends interleaved PCM.
204 pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> {
205 self.init(channels, sample_rate)?;
206 let n = usize::from(channels);
207 for (i, sample) in interleaved.iter().enumerate() {
208 self.pcm[i % n].push(*sample);
209 }
210 self.drain_frames();
211 Ok(())
212 }
213
214 /// Appends planar PCM, one slice per channel.
215 pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> {
216 self.init(planes.len() as u16, sample_rate)?;
217 for (buf, plane) in self.pcm.iter_mut().zip(planes) {
218 buf.extend_from_slice(plane);
219 }
220 self.drain_frames();
221 Ok(())
222 }
223
224 /// Marks the end of input; the tail is padded to a whole frame.
225 pub fn finish(&mut self) {
226 if !self.initialised || self.flushed {
227 self.flushed = true;
228 return;
229 }
230 self.flushed = true;
231 let left = self.pcm.iter().map(|c| c.len()).max().unwrap_or(0);
232 if left > 0 {
233 // One frame of lookahead is held back for the window decision, and
234 // the filterbank needs another frame of zeroes to flush its tail.
235 let pad = left.div_ceil(FRAME_LEN) * FRAME_LEN + 2 * FRAME_LEN;
236 for c in self.pcm.iter_mut() {
237 c.resize(pad, 0.0);
238 }
239 }
240 self.drain_frames();
241 }
242
243 /// Takes the next encoded packet, or [`Error::Eof`] once drained.
244 pub fn next_packet(&mut self) -> Result<EncodedPacket> {
245 self.queue.pop_front().ok_or(Error::Eof)
246 }
247
248 fn drain_frames(&mut self) {
249 while self.pcm.iter().all(|c| c.len() >= 2 * FRAME_LEN) {
250 self.encode_frame();
251 }
252 }
253
254 fn long_window(&self) -> &[f32] {
255 match self.config.window_shape {
256 WindowShape::Sine => &self.sine_long,
257 WindowShape::Kbd => &self.kbd_long,
258 }
259 }
260
261 fn short_window(&self) -> &[f32] {
262 match self.config.window_shape {
263 WindowShape::Sine => &self.sine_short,
264 WindowShape::Kbd => &self.kbd_short,
265 }
266 }
267
268 fn swb(&self, seq: WindowSequence) -> &'static [u16] {
269 let idx = usize::from(self.sf_index).min(11);
270 if seq == WindowSequence::EightShort {
271 SWB_SHORT[idx]
272 } else {
273 SWB_LONG[idx]
274 }
275 }
276
277 /// Transform, psychoacoustics, quantisation and bitstream for one frame.
278 fn encode_frame(&mut self) {
279 // One window decision for the whole frame: a channel pair can only
280 // share `ics_info` -- and so only use mid/side -- if it shares its
281 // window sequence.
282 let transient = self.config.window_switching && self.frame_transient();
283 self.seq = match self.seq {
284 WindowSequence::LongStart => WindowSequence::EightShort,
285 WindowSequence::EightShort if transient => WindowSequence::EightShort,
286 WindowSequence::EightShort => WindowSequence::LongStop,
287 _ if transient => WindowSequence::LongStart,
288 _ => WindowSequence::OnlyLong,
289 };
290 let seq = self.seq;
291
292 let mut frames = Vec::with_capacity(self.channels);
293 for ch in 0..self.channels {
294 let cur: Vec<f32> = self.pcm[ch][..FRAME_LEN]
295 .iter()
296 .map(|v| v * INPUT_SCALE)
297 .collect();
298 let mut block = Vec::with_capacity(2 * FRAME_LEN);
299 block.extend_from_slice(&self.prev[ch]);
300 block.extend_from_slice(&cur);
301 self.prev[ch] = cur;
302 let coef = self.transform(&block, seq);
303 let threshold = self.psychoacoustics(&block, &coef, seq);
304 frames.push(ChannelFrame { coef, threshold });
305 }
306 for c in self.pcm.iter_mut() {
307 c.drain(..FRAME_LEN);
308 }
309
310 let target = (u64::from(self.config.bitrate_bps) * FRAME_LEN as u64
311 / u64::from(self.sample_rate.max(1))) as i32;
312 let budget = target
313 + self
314 .reservoir
315 .clamp(0, RESERVOIR_MAX * self.channels as i32);
316 let data = self.write_frame(&frames, seq, budget);
317 let used = data.len() as i32 * 8;
318 self.reservoir =
319 (self.reservoir + target - used).clamp(0, RESERVOIR_MAX * self.channels as i32);
320 let data = if self.config.adts {
321 let header = AdtsHeader {
322 object_type: 2,
323 sf_index: self.sf_index,
324 sample_rate: self.sample_rate,
325 channels: self.channels as u16,
326 channel_config: config_for_channels(self.channels as u16),
327 frame_length: data.len() + 7,
328 header_len: 7,
329 raw_blocks: 1,
330 };
331 let mut out = crate::config::write_adts_header(&header);
332 out.extend_from_slice(&data);
333 out
334 } else {
335 data
336 };
337 self.queue.push_back(EncodedPacket {
338 data,
339 pts: self.frames_out * FRAME_LEN as i64,
340 duration: FRAME_LEN as u32,
341 });
342 self.frames_out += 1;
343 }
344
345 /// An eighth-frame energy jump anywhere in the frame ahead is a transient.
346 ///
347 /// The running average is primed by the first frame rather than starting at
348 /// zero: from zero every opening sample looks like an attack, and the frames
349 /// that carry a file's first second would all be coded short.
350 fn frame_transient(&mut self) -> bool {
351 let mut hit = false;
352 let primed = self.energy > 0.0;
353 let mut running = self.energy;
354 for i in 0..8 {
355 let mut e = 0.0f32;
356 for ch in 0..self.channels {
357 let lo = FRAME_LEN + i * SHORT_LEN;
358 for v in &self.pcm[ch][lo..lo + SHORT_LEN] {
359 e += v * v;
360 }
361 }
362 e /= (SHORT_LEN * self.channels) as f32;
363 if primed && e > running * 8.0 && e > 1e-7 {
364 hit = true;
365 }
366 running = if i == 0 && !primed {
367 e
368 } else {
369 running * 0.7 + e * 0.3
370 };
371 }
372 self.energy = running;
373 hit
374 }
375
376 fn transform(&mut self, block: &[f32], seq: WindowSequence) -> Vec<f32> {
377 let mut coef = vec![0.0f32; FRAME_LEN];
378 if seq == WindowSequence::EightShort {
379 let win = self.short_window().to_vec();
380 for w in 0..8 {
381 let base = 448 + w * SHORT_LEN;
382 self.mdct_short.forward_windowed(
383 &block[base..base + 2 * SHORT_LEN],
384 &win,
385 &mut coef[w * SHORT_LEN..(w + 1) * SHORT_LEN],
386 );
387 }
388 return coef;
389 }
390 let long = self.long_window().to_vec();
391 let short = self.short_window().to_vec();
392 let mut win = vec![1.0f32; 2 * FRAME_LEN];
393 match seq {
394 WindowSequence::LongStart => {
395 win[..FRAME_LEN].copy_from_slice(&long[..FRAME_LEN]);
396 win[FRAME_LEN + 448..FRAME_LEN + 576]
397 .copy_from_slice(&short[SHORT_LEN..2 * SHORT_LEN]);
398 win[FRAME_LEN + 576..].fill(0.0);
399 }
400 WindowSequence::LongStop => {
401 win[..448].fill(0.0);
402 win[448..576].copy_from_slice(&short[..SHORT_LEN]);
403 win[FRAME_LEN..].copy_from_slice(&long[FRAME_LEN..]);
404 }
405 _ => win.copy_from_slice(&long),
406 }
407 self.mdct_long.forward_windowed(block, &win, &mut coef);
408 coef
409 }
410
411 /// Per-band masking thresholds; see the module docs for the model.
412 fn psychoacoustics(&mut self, block: &[f32], coef: &[f32], seq: WindowSequence) -> Vec<f32> {
413 let swb = self.swb(seq);
414 let bands = swb.len() - 1;
415 let windowed: Vec<f32> = block
416 .iter()
417 .zip(self.sine_long.iter())
418 .map(|(v, w)| v * w)
419 .collect();
420 let mut spectrum = vec![
421 Complex {
422 re: 0.0f32,
423 im: 0.0f32
424 };
425 FRAME_LEN + 1
426 ];
427 self.fft.forward(&windowed, &mut spectrum);
428 let short = seq == WindowSequence::EightShort;
429 let windows = if short { 8 } else { 1 };
430 let mut energy = vec![0.0f32; bands];
431 let mut flatness = vec![0.0f32; bands];
432 for b in 0..bands {
433 let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
434 // Level comes from the MDCT itself, so the threshold and the
435 // quantisation noise it is compared against are in the same units;
436 // an FFT-scaled threshold would be a constant factor out, and that
437 // constant is the difference between masking a band and coding it.
438 let mut sum = 0.0f64;
439 let mut n = 0usize;
440 for w in 0..windows {
441 let base = if short { w * SHORT_LEN } else { 0 };
442 for k in base + lo..base + hi {
443 sum += f64::from(coef[k]) * f64::from(coef[k]);
444 n += 1;
445 }
446 }
447 energy[b] = (sum / n.max(1) as f64) as f32;
448 // Tonality comes from the FFT, which is what it is good for. A short
449 // block's bands index 128 lines against the FFT's 1024, the same
450 // eightfold ratio the filterbank uses.
451 let (flo, fhi) = if short { (lo * 8, hi * 8) } else { (lo, hi) };
452 let fhi = fhi.min(FRAME_LEN);
453 let fn_ = fhi.saturating_sub(flo).max(1);
454 let mut fsum = 0.0f64;
455 let mut log_sum = 0.0f64;
456 for k in flo..fhi {
457 let p = f64::from(spectrum[k].norm_sqr()) + 1e-9;
458 fsum += p;
459 log_sum += p.ln();
460 }
461 let geometric = (log_sum / fn_ as f64).exp();
462 flatness[b] = (geometric / (fsum / fn_ as f64).max(1e-30)) as f32;
463 }
464 // Two-slope spreading at band resolution: about 10 dB per band upward
465 // in frequency, 25 dB downward.
466 let mut spread = energy.clone();
467 for b in 1..bands {
468 spread[b] = spread[b].max(spread[b - 1] * 0.1);
469 }
470 for b in (0..bands.saturating_sub(1)).rev() {
471 spread[b] = spread[b].max(spread[b + 1] * 0.003);
472 }
473 // Standing in for the absolute threshold of hearing: nothing this far
474 // under the loudest band of the frame is audible, and without a floor
475 // of this kind the spreading function falls away faster than the
476 // filterbank's own leakage does, so an encoder spends its whole budget
477 // coding the skirts of a tone at full precision.
478 let floor = energy.iter().copied().fold(0.0f32, f32::max) * ATH_FLOOR;
479 (0..bands)
480 .map(|b| {
481 // Flat (noise-like) bands mask well, peaky (tonal) ones badly.
482 let tonality = (1.0 - flatness[b]).clamp(0.0, 1.0);
483 let smr = 10f32.powf((6.0 + 18.0 * tonality) / 10.0);
484 (spread[b] / smr).max(floor).max(1e-3)
485 })
486 .collect()
487 }
488
489 /// Quantises every channel against a shared rate loop and writes the block.
490 fn write_frame(
491 &mut self,
492 frames: &[ChannelFrame],
493 seq: WindowSequence,
494 budget: i32,
495 ) -> Vec<u8> {
496 let layout = element_layout(self.channels);
497 let swb = self.swb(seq);
498 let short = seq == WindowSequence::EightShort;
499 let max_sfb = (swb.len() - 1).min(if short { 15 } else { 51 });
500
501 // Mid/side per band, decided once: the pair that codes to the more
502 // lopsided energy split is the one that costs fewer bits.
503 let mut elements: Vec<ElementPlan> = Vec::with_capacity(layout.len());
504 for (element, chans) in &layout {
505 let mut pair: Vec<ChannelFrame> = chans.iter().map(|&c| frames[c].clone()).collect();
506 let mut ms = vec![false; max_sfb];
507 if *element == Element::Cpe && self.config.mid_side {
508 for b in 0..max_sfb {
509 if ms_wins(&pair[0], &pair[1], swb, b, short) {
510 ms[b] = true;
511 }
512 }
513 apply_ms(&mut pair, &ms, swb, max_sfb, short);
514 }
515 elements.push(ElementPlan {
516 element: *element,
517 frames: pair,
518 ms,
519 });
520 }
521
522 // Outer rate loop. Bits fall monotonically as the common offset rises,
523 // so the finest quantisation that fits the budget is a bisection --
524 // which also means the psychoacoustic model only has to get the shape
525 // of the allocation right, not its absolute level.
526 let cost = |enc: &AacEncoder, offset: i32| -> (i32, Vec<Coded>) {
527 let mut coded = Vec::new();
528 let mut bits = 10i32; // END element plus byte-alignment slack
529 for plan in &elements {
530 bits += 3
531 + 4
532 + if plan.element == Element::Cpe {
533 1 + 2 + max_sfb as i32
534 } else {
535 0
536 };
537 for frame in &plan.frames {
538 let c = enc.quantise(frame, seq, swb, max_sfb, offset);
539 bits += c.bits;
540 coded.push(c);
541 }
542 }
543 (bits, coded)
544 };
545 let (mut lo, mut hi) = (-240i32, 240i32);
546 let (mut bits, mut coded) = cost(self, hi);
547 if bits > budget {
548 // Even the coarsest setting overflows: take it and let the
549 // reservoir absorb the overshoot.
550 lo = hi;
551 } else {
552 while lo < hi {
553 let mid = lo + (hi - lo) / 2;
554 let (b, c) = cost(self, mid);
555 if b <= budget {
556 hi = mid;
557 bits = b;
558 coded = c;
559 } else {
560 lo = mid + 1;
561 }
562 }
563 if lo < 240 {
564 let (b, c) = cost(self, lo);
565 if b <= budget {
566 bits = b;
567 coded = c;
568 }
569 }
570 }
571 let _ = (lo, bits);
572
573 let mut w = BitWriter::new();
574 let mut at = 0usize;
575 for plan in &elements {
576 let id = match plan.element {
577 Element::Sce => 0u32,
578 Element::Cpe => 1,
579 Element::Lfe => 3,
580 };
581 w.write_bits(id, 3);
582 w.write_bits(0, 4); // element_instance_tag
583 if plan.element == Element::Cpe {
584 w.write_bit(true); // common_window
585 write_ics_info(&mut w, &coded[at]);
586 w.write_bits(1, 2); // ms_mask_present: per band
587 for b in 0..coded[at].max_sfb {
588 w.write_bit(plan.ms[b]);
589 }
590 write_ics(&mut w, &coded[at], false);
591 write_ics(&mut w, &coded[at + 1], false);
592 at += 2;
593 } else {
594 write_ics(&mut w, &coded[at], true);
595 at += 1;
596 }
597 }
598 w.write_bits(7, 3); // END
599 w.align_to_byte();
600 w.into_bytes()
601 }
602
603 /// Inner distortion loop: the coarsest scalefactor per band whose noise
604 /// still sits under the mask, then codebook choice and an exact bit count.
605 ///
606 /// Only bands that actually code anything carry a scalefactor, and the
607 /// codebook can only code a delta of +/-60 between consecutive ones. Both
608 /// facts are settled here rather than at write time -- a scalefactor the
609 /// bitstream cannot carry would come back at the wrong gain, and chaining
610 /// the constraint through *silent* bands is what drags a fine scalefactor
611 /// into the empty top of the spectrum and spends the frame on leakage.
612 fn quantise(
613 &self,
614 frame: &ChannelFrame,
615 seq: WindowSequence,
616 swb: &'static [u16],
617 max_sfb: usize,
618 offset: i32,
619 ) -> Coded {
620 let short = seq == WindowSequence::EightShort;
621 let windows = if short { 8 } else { 1 };
622 let mut sf = vec![0i32; max_sfb];
623 let mut floor = vec![0i32; max_sfb];
624 let mut zero = vec![true; max_sfb];
625 for b in 0..max_sfb {
626 let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
627 let mut peak = 0.0f32;
628 for w in 0..windows {
629 let base = if short { w * SHORT_LEN } else { 0 };
630 for k in base + lo..base + hi {
631 peak = peak.max(frame.coef[k].abs());
632 }
633 }
634 if peak < 1e-4 {
635 continue;
636 }
637 // The rate loop scales the whole mask rather than shifting the
638 // scalefactors: that keeps the noise following the shape the model
639 // asked for, and lets a band whose signal falls under its own mask
640 // drop out entirely instead of being coded ever more coarsely.
641 let target = frame.threshold[b] * 2f32.powf(offset as f32 * 0.5);
642 let mut energy = 0.0f32;
643 let mut count = 0usize;
644 for w in 0..windows {
645 let base = if short { w * SHORT_LEN } else { 0 };
646 for k in base + lo..base + hi {
647 energy += frame.coef[k] * frame.coef[k];
648 count += 1;
649 }
650 }
651 if energy / count.max(1) as f32 <= target {
652 continue;
653 }
654 floor[b] = sf_floor(peak).max(0);
655 // Noise is non-decreasing in level (coarser step -> more error),
656 // the same assumption the original linear scan relied on to break
657 // on first overage; bisect for the largest level still under
658 // target instead of walking it one step at a time.
659 let mut best = floor[b];
660 if self.band_noise(frame, swb, b, floor[b], windows, short) <= target {
661 let (mut lo, mut hi) = (floor[b], 255);
662 while lo < hi {
663 let mid = lo + (hi - lo + 1) / 2;
664 if self.band_noise(frame, swb, b, mid, windows, short) <= target {
665 lo = mid;
666 } else {
667 hi = mid - 1;
668 }
669 }
670 best = lo;
671 }
672 sf[b] = best.clamp(floor[b], 255);
673 zero[b] = false;
674 }
675
676 let mut quant = vec![0i32; FRAME_LEN];
677 let mut books = vec![0u8; max_sfb];
678 for _ in 0..4 {
679 let mut settled = true;
680 let mut prev: Option<i32> = None;
681 for b in 0..max_sfb {
682 if zero[b] {
683 continue;
684 }
685 let fixed = match prev {
686 None => sf[b],
687 Some(p) => sf[b].clamp(p - 60, p + 60).clamp(0, 255),
688 };
689 if fixed != sf[b] {
690 sf[b] = fixed;
691 settled = false;
692 }
693 prev = Some(sf[b]);
694 }
695 for b in 0..max_sfb {
696 let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
697 if zero[b] {
698 books[b] = 0;
699 for w in 0..windows {
700 let base = if short { w * SHORT_LEN } else { 0 };
701 quant[base + lo..base + hi].fill(0);
702 }
703 continue;
704 }
705 let mut peak = 0i32;
706 for w in 0..windows {
707 let base = if short { w * SHORT_LEN } else { 0 };
708 for k in lo..hi {
709 let q = quantise_one(frame.coef[base + k], sf[b]);
710 quant[base + k] = q;
711 peak = peak.max(q.abs());
712 }
713 }
714 books[b] = codebook_for(peak);
715 if peak == 0 {
716 // Nothing survived: the band leaves the delta chain, which
717 // may free the bands after it to go coarser.
718 zero[b] = true;
719 settled = false;
720 }
721 }
722 if settled {
723 break;
724 }
725 }
726
727 let mut bits = 8 + 3; // global_gain plus the three tool flags
728 let mut prev: Option<i32> = None;
729 for b in 0..max_sfb {
730 if books[b] == 0 {
731 continue;
732 }
733 bits += band_bits(&quant, swb, b, books[b], windows, short);
734 let value = prev.map_or(60, |p| (60 + sf[b] - p).clamp(0, 120));
735 bits += i32::from(SCALEFACTOR_CODES[value as usize].0);
736 prev = Some(sf[b]);
737 }
738 let mut sections = 0;
739 let mut b = 0usize;
740 while b < max_sfb {
741 let book = books[b];
742 while b < max_sfb && books[b] == book {
743 b += 1;
744 }
745 sections += 1;
746 }
747 bits += sections * (4 + if short { 3 } else { 5 });
748 Coded {
749 seq,
750 max_sfb,
751 swb,
752 sf,
753 books,
754 quant,
755 bits,
756 short,
757 }
758 }
759
760 /// Quantisation noise energy of one band at a candidate scalefactor.
761 fn band_noise(
762 &self,
763 frame: &ChannelFrame,
764 swb: &[u16],
765 band: usize,
766 sf: i32,
767 windows: usize,
768 short: bool,
769 ) -> f32 {
770 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
771 let gain = 2f32.powf((sf - SF_OFFSET) as f32 * 0.25);
772 let mut noise = 0.0f32;
773 let mut count = 0usize;
774 for w in 0..windows {
775 let base = if short { w * SHORT_LEN } else { 0 };
776 for k in base + lo..base + hi {
777 let x = frame.coef[k];
778 let q = quantise_one(x, sf);
779 let mut back = pow43(q.unsigned_abs()) * gain;
780 if q < 0 {
781 back = -back;
782 }
783 noise += (x - back) * (x - back);
784 count += 1;
785 }
786 }
787 noise / count.max(1) as f32
788 }
789}
790
791struct ElementPlan {
792 element: Element,
793 frames: Vec<ChannelFrame>,
794 ms: Vec<bool>,
795}
796
797/// A channel's quantised frame, ready to write.
798struct Coded {
799 seq: WindowSequence,
800 max_sfb: usize,
801 swb: &'static [u16],
802 sf: Vec<i32>,
803 books: Vec<u8>,
804 quant: Vec<i32>,
805 bits: i32,
806 short: bool,
807}
808
809/// True when mid/side splits this band's energy more lopsidedly than left/right
810/// does, which is when it costs fewer bits.
811fn ms_wins(l: &ChannelFrame, r: &ChannelFrame, swb: &[u16], band: usize, short: bool) -> bool {
812 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
813 let windows = if short { 8 } else { 1 };
814 let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
815 for w in 0..windows {
816 let base = if short { w * SHORT_LEN } else { 0 };
817 for k in base + lo..base + hi {
818 let (a, b) = (f64::from(l.coef[k]), f64::from(r.coef[k]));
819 el += a * a;
820 er += b * b;
821 em += (a + b) * (a + b) * 0.25;
822 es += (a - b) * (a - b) * 0.25;
823 }
824 }
825 let lr = (el.max(er) + 1e-9) / (el.min(er) + 1e-9);
826 let ms = (em.max(es) + 1e-9) / (em.min(es) + 1e-9);
827 ms > lr * 1.5
828}
829
830fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, short: bool) {
831 let windows = if short { 8 } else { 1 };
832 for b in 0..max_sfb {
833 if !ms[b] {
834 continue;
835 }
836 let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
837 for w in 0..windows {
838 let base = if short { w * SHORT_LEN } else { 0 };
839 for k in base + lo..base + hi {
840 let (a, b2) = (pair[0].coef[k], pair[1].coef[k]);
841 pair[0].coef[k] = (a + b2) * 0.5;
842 pair[1].coef[k] = (a - b2) * 0.5;
843 }
844 }
845 // The side channel inherits the pair's tighter mask.
846 let t = pair[0].threshold[b].min(pair[1].threshold[b]);
847 pair[0].threshold[b] = t;
848 pair[1].threshold[b] = t;
849 }
850}
851
852/// `q^(4/3)` for the (small, bounded-by-`MAX_QUANT`) integer magnitudes the
853/// rate loop's noise search re-tests at every candidate scalefactor: a table
854/// lookup replaces what was otherwise the encoder's hottest `powf` call site.
855static POW43: LazyLock<Vec<f32>> = LazyLock::new(|| {
856 (0..=MAX_QUANT as u32)
857 .map(|q| (q as f32).powf(4.0 / 3.0))
858 .collect()
859});
860
861fn pow43(q: u32) -> f32 {
862 POW43[q.min(MAX_QUANT as u32) as usize]
863}
864
865/// The finest scalefactor at which a peak of this size still fits the escape
866/// codebook: below it the quantiser saturates, which costs bits *and* adds
867/// distortion.
868fn sf_floor(peak: f32) -> i32 {
869 let want = (0.75 * peak.log2() - (MAX_QUANT as f32).log2()) / 0.1875;
870 SF_OFFSET + want.ceil() as i32
871}
872
873fn quantise_one(x: f32, sf: i32) -> i32 {
874 if x == 0.0 {
875 return 0;
876 }
877 let gain = 2f32.powf(-(sf - SF_OFFSET) as f32 * 0.25);
878 // x^0.75 == sqrt(x * sqrt(x)): two sqrtf beat one powf by a wide margin,
879 // and this call site is the rate loop's inner-inner loop.
880 let v = x.abs() * gain;
881 let q = (v.sqrt() * v.sqrt().sqrt() + ROUND_BIAS) as i32;
882 let q = q.min(MAX_QUANT);
883 if x < 0.0 { -q } else { q }
884}
885
886/// The cheapest codebook that can carry a peak magnitude.
887fn codebook_for(peak: i32) -> u8 {
888 match peak {
889 0 => 0,
890 1 => 1,
891 2 => 3,
892 3..=4 => 5,
893 5..=7 => 7,
894 8..=12 => 9,
895 _ => 11,
896 }
897}
898
899fn band_bits(
900 quant: &[i32],
901 swb: &[u16],
902 band: usize,
903 book: u8,
904 windows: usize,
905 short: bool,
906) -> i32 {
907 let cb = &CODEBOOKS[usize::from(book) - 1];
908 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
909 let dim = usize::from(cb.dim);
910 let mut bits = 0i32;
911 for w in 0..windows {
912 let base = if short { w * SHORT_LEN } else { 0 };
913 let mut k = lo;
914 while k < hi {
915 let end = (k + dim).min(hi);
916 bits += tuple_bits(cb, &quant[base + k..base + end]);
917 k += dim;
918 }
919 }
920 bits
921}
922
923/// Bits one Huffman tuple costs, sign and escape included.
924fn tuple_bits(cb: &Codebook, values: &[i32]) -> i32 {
925 let mut bits = i32::from(cb.codes[tuple_index(cb, values)].0);
926 for &v in values {
927 if cb.unsigned && v != 0 {
928 bits += 1;
929 }
930 if cb.esc && v.unsigned_abs() >= 16 {
931 let n = escape_order(v.unsigned_abs());
932 bits += 2 * n + 5;
933 }
934 }
935 bits
936}
937
938/// The escape's unary length: `value` needs `n + 4` payload bits.
939fn escape_order(mag: u32) -> i32 {
940 (32 - mag.leading_zeros()) as i32 - 5
941}
942
943/// Tuple to codebook index, clamped into the codebook's range.
944fn tuple_index(cb: &Codebook, values: &[i32]) -> usize {
945 let span = if cb.unsigned {
946 usize::from(cb.lav) + 1
947 } else {
948 2 * usize::from(cb.lav) + 1
949 };
950 let mut idx = 0usize;
951 for i in 0..usize::from(cb.dim) {
952 let v = values.get(i).copied().unwrap_or(0);
953 let digit = if cb.unsigned {
954 v.unsigned_abs().min(u32::from(cb.lav)) as usize
955 } else {
956 (v.clamp(-i32::from(cb.lav), i32::from(cb.lav)) + i32::from(cb.lav)) as usize
957 };
958 idx = idx * span + digit;
959 }
960 idx
961}
962
963fn write_tuple(w: &mut BitWriter, cb: &Codebook, values: &[i32]) {
964 let (len, code) = cb.codes[tuple_index(cb, values)];
965 w.write_bits(code, u32::from(len));
966 if cb.unsigned {
967 for &v in values.iter().take(usize::from(cb.dim)) {
968 if v != 0 {
969 w.write_bit(v < 0);
970 }
971 }
972 }
973 if cb.esc {
974 for &v in values.iter().take(usize::from(cb.dim)) {
975 let mag = v.unsigned_abs();
976 if mag >= 16 {
977 let n = escape_order(mag) as u32;
978 for _ in 0..n {
979 w.write_bit(true);
980 }
981 w.write_bit(false);
982 w.write_bits(mag & ((1 << (n + 4)) - 1), n + 4);
983 }
984 }
985 }
986}
987
988fn write_ics_info(w: &mut BitWriter, c: &Coded) {
989 w.write_bit(false); // ics_reserved_bit
990 let seq = match c.seq {
991 WindowSequence::OnlyLong => 0,
992 WindowSequence::LongStart => 1,
993 WindowSequence::EightShort => 2,
994 WindowSequence::LongStop => 3,
995 };
996 w.write_bits(seq, 2);
997 w.write_bit(false); // sine window shape
998 if c.short {
999 w.write_bits(c.max_sfb as u32, 4);
1000 w.write_bits(0x7F, 7); // one group of eight windows
1001 } else {
1002 w.write_bits(c.max_sfb as u32, 6);
1003 w.write_bit(false); // predictor_data_present
1004 }
1005}
1006
1007fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
1008 let first = c.books.iter().position(|&b| b != 0);
1009 let global_gain = first.map_or(100, |b| c.sf[b]).clamp(0, 255) as u32;
1010 w.write_bits(global_gain, 8);
1011 if own_info {
1012 write_ics_info(w, c);
1013 }
1014 // section_data
1015 let esc_bits = if c.short { 3 } else { 5 };
1016 let esc = (1u32 << esc_bits) - 1;
1017 let mut b = 0usize;
1018 while b < c.max_sfb {
1019 let book = c.books[b];
1020 let start = b;
1021 while b < c.max_sfb && c.books[b] == book {
1022 b += 1;
1023 }
1024 w.write_bits(u32::from(book), 4);
1025 let mut left = (b - start) as u32;
1026 while left >= esc {
1027 w.write_bits(esc, esc_bits);
1028 left -= esc;
1029 }
1030 w.write_bits(left, esc_bits);
1031 }
1032 // scale_factor_data
1033 let mut prev = global_gain as i32;
1034 for b in 0..c.max_sfb {
1035 if c.books[b] == 0 {
1036 continue;
1037 }
1038 let value = (60 + c.sf[b] - prev).clamp(0, 120) as usize;
1039 let (len, code) = SCALEFACTOR_CODES[value];
1040 w.write_bits(code, u32::from(len));
1041 prev += value as i32 - 60;
1042 }
1043 w.write_bit(false); // pulse_data_present
1044 w.write_bit(false); // tns_data_present
1045 w.write_bit(false); // gain_control_data_present
1046 // spectral_data
1047 let windows = if c.short { 8 } else { 1 };
1048 for b in 0..c.max_sfb {
1049 let book = c.books[b];
1050 if book == 0 {
1051 continue;
1052 }
1053 let cb = &CODEBOOKS[usize::from(book) - 1];
1054 let dim = usize::from(cb.dim);
1055 let (lo, hi) = (usize::from(c.swb[b]), usize::from(c.swb[b + 1]));
1056 for win in 0..windows {
1057 let base = if c.short { win * SHORT_LEN } else { 0 };
1058 let mut k = lo;
1059 while k < hi {
1060 let end = (k + dim).min(hi);
1061 write_tuple(w, cb, &c.quant[base + k..base + end]);
1062 k += dim;
1063 }
1064 }
1065 }
1066}
1067
1068/// Which channel element carries which of the caller's channels. The caller
1069/// speaks film order (`FL, FR, FC, LFE, BL, BR, SL, SR`); the bitstream wants
1070/// centre first and LFE last (ISO/IEC 14496-3 tbl 1.19).
1071#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1072enum Element {
1073 Sce,
1074 Cpe,
1075 Lfe,
1076}
1077
1078fn element_layout(channels: usize) -> Vec<(Element, Vec<usize>)> {
1079 match channels {
1080 1 => vec![(Element::Sce, vec![0])],
1081 2 => vec![(Element::Cpe, vec![0, 1])],
1082 3 => vec![(Element::Sce, vec![2]), (Element::Cpe, vec![0, 1])],
1083 4 => vec![
1084 (Element::Sce, vec![2]),
1085 (Element::Cpe, vec![0, 1]),
1086 (Element::Sce, vec![3]),
1087 ],
1088 5 => vec![
1089 (Element::Sce, vec![2]),
1090 (Element::Cpe, vec![0, 1]),
1091 (Element::Cpe, vec![3, 4]),
1092 ],
1093 6 => vec![
1094 (Element::Sce, vec![2]),
1095 (Element::Cpe, vec![0, 1]),
1096 (Element::Cpe, vec![4, 5]),
1097 (Element::Lfe, vec![3]),
1098 ],
1099 8 => vec![
1100 (Element::Sce, vec![2]),
1101 (Element::Cpe, vec![0, 1]),
1102 (Element::Cpe, vec![6, 7]),
1103 (Element::Cpe, vec![4, 5]),
1104 (Element::Lfe, vec![3]),
1105 ],
1106 n => (0..n).map(|i| (Element::Sce, vec![i])).collect(),
1107 }
1108}