forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1f91eddTahinli2 months ago3507 commits

encode.rs1298 lines, 46.1 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 /// The rate loop's working point from the previous frame, where the next
126 /// frame's search starts looking for its own edge.
127 warm_offset: i32,
128 flushed: bool,
129 initialised: bool,
130}
131
132impl AacEncoder {
133 /// Samples this encoder emits before the first audible one: one MDCT
134 /// window's worth, always, because the very first frame has no previous
135 /// block to overlap-add against and is pure priming. A muxer writing this
136 /// track's `elst`/`CodecDelay` states it here.
137 pub fn encoder_delay(&self) -> usize {
138 1024
139 }
140
141 pub fn new(config: AacEncoderConfig) -> AacEncoder {
142 AacEncoder {
143 config,
144 sample_rate: 0,
145 sf_index: 3,
146 channels: 0,
147 pcm: Vec::new(),
148 prev: Vec::new(),
149 seq: WindowSequence::OnlyLong,
150 energy: 0.0,
151 mdct_long: Mdct::new(2 * FRAME_LEN),
152 mdct_short: Mdct::new(2 * SHORT_LEN),
153 fft: RealFft::new(2 * FRAME_LEN),
154 sine_long: Window::<f32>::sine(2 * FRAME_LEN).as_slice().to_vec(),
155 kbd_long: Window::<f32>::kbd(2 * FRAME_LEN, 4.0).as_slice().to_vec(),
156 sine_short: Window::<f32>::sine(2 * SHORT_LEN).as_slice().to_vec(),
157 kbd_short: Window::<f32>::kbd(2 * SHORT_LEN, 6.0).as_slice().to_vec(),
158 queue: std::collections::VecDeque::new(),
159 frames_out: 0,
160 reservoir: 0,
161 warm_offset: 0,
162 flushed: false,
163 initialised: false,
164 }
165 }
166
167 /// The stream's sample rate; 0 until the first PCM arrives.
168 pub fn sample_rate(&self) -> u32 {
169 self.sample_rate
170 }
171
172 /// The stream's channel count; 0 until the first PCM arrives.
173 pub fn channels(&self) -> u16 {
174 self.channels as u16
175 }
176
177 /// The AudioSpecificConfig a container needs for this stream.
178 pub fn audio_specific_config(&self) -> Vec<u8> {
179 crate::config::audio_specific_config_bytes(self.sample_rate, self.channels as u16)
180 }
181
182 fn init(&mut self, channels: u16, sample_rate: u32) -> Result<()> {
183 if self.initialised {
184 if self.channels != usize::from(channels) || self.sample_rate != sample_rate {
185 return Err(Error::corrupt("aac: stream parameters changed mid-encode"));
186 }
187 return Ok(());
188 }
189 let sf_index = sf_index_for_rate(sample_rate).ok_or_else(|| {
190 Error::unsupported("aac", format!("{sample_rate} Hz is not an AAC sample rate"))
191 })?;
192 if channels == 0 || channels == 7 || channels > 8 {
193 return Err(Error::unsupported(
194 "aac",
195 format!("{channels} channels has no channelConfiguration"),
196 ));
197 }
198 self.sf_index = sf_index;
199 self.sample_rate = sample_rate;
200 self.channels = usize::from(channels);
201 self.pcm = vec![Vec::new(); self.channels];
202 self.prev = vec![vec![0.0; FRAME_LEN]; self.channels];
203 self.initialised = true;
204 Ok(())
205 }
206
207 /// Appends interleaved PCM.
208 pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> {
209 self.init(channels, sample_rate)?;
210 let n = usize::from(channels);
211 for (i, sample) in interleaved.iter().enumerate() {
212 self.pcm[i % n].push(*sample);
213 }
214 self.drain_frames();
215 Ok(())
216 }
217
218 /// Appends planar PCM, one slice per channel.
219 pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> {
220 self.init(planes.len() as u16, sample_rate)?;
221 for (buf, plane) in self.pcm.iter_mut().zip(planes) {
222 buf.extend_from_slice(plane);
223 }
224 self.drain_frames();
225 Ok(())
226 }
227
228 /// Marks the end of input; the tail is padded to a whole frame.
229 pub fn finish(&mut self) {
230 if !self.initialised || self.flushed {
231 self.flushed = true;
232 return;
233 }
234 self.flushed = true;
235 let left = self.pcm.iter().map(|c| c.len()).max().unwrap_or(0);
236 if left > 0 {
237 // One frame of lookahead is held back for the window decision, and
238 // the filterbank needs another frame of zeroes to flush its tail.
239 let pad = left.div_ceil(FRAME_LEN) * FRAME_LEN + 2 * FRAME_LEN;
240 for c in self.pcm.iter_mut() {
241 c.resize(pad, 0.0);
242 }
243 }
244 self.drain_frames();
245 }
246
247 /// Takes the next encoded packet, or [`Error::Eof`] once drained.
248 pub fn next_packet(&mut self) -> Result<EncodedPacket> {
249 self.queue.pop_front().ok_or(Error::Eof)
250 }
251
252 fn drain_frames(&mut self) {
253 while self.pcm.iter().all(|c| c.len() >= 2 * FRAME_LEN) {
254 self.encode_frame();
255 }
256 }
257
258 fn long_window(&self) -> &[f32] {
259 match self.config.window_shape {
260 WindowShape::Sine => &self.sine_long,
261 WindowShape::Kbd => &self.kbd_long,
262 }
263 }
264
265 fn short_window(&self) -> &[f32] {
266 match self.config.window_shape {
267 WindowShape::Sine => &self.sine_short,
268 WindowShape::Kbd => &self.kbd_short,
269 }
270 }
271
272 fn swb(&self, seq: WindowSequence) -> &'static [u16] {
273 let idx = usize::from(self.sf_index).min(11);
274 if seq == WindowSequence::EightShort {
275 SWB_SHORT[idx]
276 } else {
277 SWB_LONG[idx]
278 }
279 }
280
281 /// Transform, psychoacoustics, quantisation and bitstream for one frame.
282 fn encode_frame(&mut self) {
283 // One window decision for the whole frame: a channel pair can only
284 // share `ics_info` -- and so only use mid/side -- if it shares its
285 // window sequence.
286 let transient = self.config.window_switching && self.frame_transient();
287 self.seq = match self.seq {
288 WindowSequence::LongStart => WindowSequence::EightShort,
289 WindowSequence::EightShort if transient => WindowSequence::EightShort,
290 WindowSequence::EightShort => WindowSequence::LongStop,
291 _ if transient => WindowSequence::LongStart,
292 _ => WindowSequence::OnlyLong,
293 };
294 let seq = self.seq;
295
296 let mut frames = Vec::with_capacity(self.channels);
297 for ch in 0..self.channels {
298 let cur: Vec<f32> = self.pcm[ch][..FRAME_LEN]
299 .iter()
300 .map(|v| v * INPUT_SCALE)
301 .collect();
302 let mut block = Vec::with_capacity(2 * FRAME_LEN);
303 block.extend_from_slice(&self.prev[ch]);
304 block.extend_from_slice(&cur);
305 self.prev[ch] = cur;
306 let coef = self.transform(&block, seq);
307 let threshold = self.psychoacoustics(&block, &coef, seq);
308 frames.push(ChannelFrame { coef, threshold });
309 }
310 for c in self.pcm.iter_mut() {
311 c.drain(..FRAME_LEN);
312 }
313
314 let target = (u64::from(self.config.bitrate_bps) * FRAME_LEN as u64
315 / u64::from(self.sample_rate.max(1))) as i32;
316 let budget = target
317 + self
318 .reservoir
319 .clamp(0, RESERVOIR_MAX * self.channels as i32);
320 let data = self.write_frame(&frames, seq, budget);
321 let used = data.len() as i32 * 8;
322 self.reservoir =
323 (self.reservoir + target - used).clamp(0, RESERVOIR_MAX * self.channels as i32);
324 let data = if self.config.adts {
325 let header = AdtsHeader {
326 object_type: 2,
327 sf_index: self.sf_index,
328 sample_rate: self.sample_rate,
329 channels: self.channels as u16,
330 channel_config: config_for_channels(self.channels as u16),
331 frame_length: data.len() + 7,
332 header_len: 7,
333 raw_blocks: 1,
334 };
335 let mut out = crate::config::write_adts_header(&header);
336 out.extend_from_slice(&data);
337 out
338 } else {
339 data
340 };
341 self.queue.push_back(EncodedPacket {
342 data,
343 pts: self.frames_out * FRAME_LEN as i64,
344 duration: FRAME_LEN as u32,
345 });
346 self.frames_out += 1;
347 }
348
349 /// An eighth-frame energy jump anywhere in the frame ahead is a transient.
350 ///
351 /// The running average is primed by the first frame rather than starting at
352 /// zero: from zero every opening sample looks like an attack, and the frames
353 /// that carry a file's first second would all be coded short.
354 fn frame_transient(&mut self) -> bool {
355 let mut hit = false;
356 let primed = self.energy > 0.0;
357 let mut running = self.energy;
358 for i in 0..8 {
359 let mut e = 0.0f32;
360 for ch in 0..self.channels {
361 let lo = FRAME_LEN + i * SHORT_LEN;
362 for v in &self.pcm[ch][lo..lo + SHORT_LEN] {
363 e += v * v;
364 }
365 }
366 e /= (SHORT_LEN * self.channels) as f32;
367 if primed && e > running * 8.0 && e > 1e-7 {
368 hit = true;
369 }
370 running = if i == 0 && !primed {
371 e
372 } else {
373 running * 0.7 + e * 0.3
374 };
375 }
376 self.energy = running;
377 hit
378 }
379
380 fn transform(&mut self, block: &[f32], seq: WindowSequence) -> Vec<f32> {
381 let mut coef = vec![0.0f32; FRAME_LEN];
382 if seq == WindowSequence::EightShort {
383 let win = self.short_window().to_vec();
384 for w in 0..8 {
385 let base = 448 + w * SHORT_LEN;
386 self.mdct_short.forward_windowed(
387 &block[base..base + 2 * SHORT_LEN],
388 &win,
389 &mut coef[w * SHORT_LEN..(w + 1) * SHORT_LEN],
390 );
391 }
392 return coef;
393 }
394 let long = self.long_window().to_vec();
395 let short = self.short_window().to_vec();
396 let mut win = vec![1.0f32; 2 * FRAME_LEN];
397 match seq {
398 WindowSequence::LongStart => {
399 win[..FRAME_LEN].copy_from_slice(&long[..FRAME_LEN]);
400 win[FRAME_LEN + 448..FRAME_LEN + 576]
401 .copy_from_slice(&short[SHORT_LEN..2 * SHORT_LEN]);
402 win[FRAME_LEN + 576..].fill(0.0);
403 }
404 WindowSequence::LongStop => {
405 win[..448].fill(0.0);
406 win[448..576].copy_from_slice(&short[..SHORT_LEN]);
407 win[FRAME_LEN..].copy_from_slice(&long[FRAME_LEN..]);
408 }
409 _ => win.copy_from_slice(&long),
410 }
411 self.mdct_long.forward_windowed(block, &win, &mut coef);
412 coef
413 }
414
415 /// Per-band masking thresholds; see the module docs for the model.
416 fn psychoacoustics(&mut self, block: &[f32], coef: &[f32], seq: WindowSequence) -> Vec<f32> {
417 let swb = self.swb(seq);
418 let bands = swb.len() - 1;
419 let windowed: Vec<f32> = block
420 .iter()
421 .zip(self.sine_long.iter())
422 .map(|(v, w)| v * w)
423 .collect();
424 let mut spectrum = vec![
425 Complex {
426 re: 0.0f32,
427 im: 0.0f32
428 };
429 FRAME_LEN + 1
430 ];
431 self.fft.forward(&windowed, &mut spectrum);
432 let short = seq == WindowSequence::EightShort;
433 let windows = if short { 8 } else { 1 };
434 let mut energy = vec![0.0f32; bands];
435 let mut flatness = vec![0.0f32; bands];
436 for b in 0..bands {
437 let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
438 // Level comes from the MDCT itself, so the threshold and the
439 // quantisation noise it is compared against are in the same units;
440 // an FFT-scaled threshold would be a constant factor out, and that
441 // constant is the difference between masking a band and coding it.
442 let mut sum = 0.0f64;
443 let mut n = 0usize;
444 for w in 0..windows {
445 let base = if short { w * SHORT_LEN } else { 0 };
446 for k in base + lo..base + hi {
447 sum += f64::from(coef[k]) * f64::from(coef[k]);
448 n += 1;
449 }
450 }
451 energy[b] = (sum / n.max(1) as f64) as f32;
452 // Tonality comes from the FFT, which is what it is good for. A short
453 // block's bands index 128 lines against the FFT's 1024, the same
454 // eightfold ratio the filterbank uses.
455 let (flo, fhi) = if short { (lo * 8, hi * 8) } else { (lo, hi) };
456 let fhi = fhi.min(FRAME_LEN);
457 let fn_ = fhi.saturating_sub(flo).max(1);
458 let mut fsum = 0.0f64;
459 let mut log_sum = 0.0f64;
460 for k in flo..fhi {
461 let p = f64::from(spectrum[k].norm_sqr()) + 1e-9;
462 fsum += p;
463 log_sum += p.ln();
464 }
465 let geometric = (log_sum / fn_ as f64).exp();
466 flatness[b] = (geometric / (fsum / fn_ as f64).max(1e-30)) as f32;
467 }
468 // Two-slope spreading at band resolution: about 10 dB per band upward
469 // in frequency, 25 dB downward.
470 let mut spread = energy.clone();
471 for b in 1..bands {
472 spread[b] = spread[b].max(spread[b - 1] * 0.1);
473 }
474 for b in (0..bands.saturating_sub(1)).rev() {
475 spread[b] = spread[b].max(spread[b + 1] * 0.003);
476 }
477 // Standing in for the absolute threshold of hearing: nothing this far
478 // under the loudest band of the frame is audible, and without a floor
479 // of this kind the spreading function falls away faster than the
480 // filterbank's own leakage does, so an encoder spends its whole budget
481 // coding the skirts of a tone at full precision.
482 let floor = energy.iter().copied().fold(0.0f32, f32::max) * ATH_FLOOR;
483 (0..bands)
484 .map(|b| {
485 // Flat (noise-like) bands mask well, peaky (tonal) ones badly.
486 let tonality = (1.0 - flatness[b]).clamp(0.0, 1.0);
487 let smr = 10f32.powf((6.0 + 18.0 * tonality) / 10.0);
488 (spread[b] / smr).max(floor).max(1e-3)
489 })
490 .collect()
491 }
492
493 /// Quantises every channel against a shared rate loop and writes the block.
494 fn write_frame(
495 &mut self,
496 frames: &[ChannelFrame],
497 seq: WindowSequence,
498 budget: i32,
499 ) -> Vec<u8> {
500 let layout = element_layout(self.channels);
501 let swb = self.swb(seq);
502 let short = seq == WindowSequence::EightShort;
503 let max_sfb = (swb.len() - 1).min(if short { 15 } else { 51 });
504
505 // Mid/side per band, decided once: the pair that codes to the more
506 // lopsided energy split is the one that costs fewer bits.
507 let mut elements: Vec<ElementPlan> = Vec::with_capacity(layout.len());
508 for (element, chans) in &layout {
509 let mut pair: Vec<ChannelFrame> = chans.iter().map(|&c| frames[c].clone()).collect();
510 let mut ms = vec![false; max_sfb];
511 if *element == Element::Cpe && self.config.mid_side {
512 for b in 0..max_sfb {
513 if ms_wins(&pair[0], &pair[1], swb, b, short) {
514 ms[b] = true;
515 }
516 }
517 apply_ms(&mut pair, &ms, swb, max_sfb, short);
518 }
519 elements.push(ElementPlan {
520 element: *element,
521 frames: pair,
522 ms,
523 });
524 }
525
526 // Outer rate loop. Bits fall monotonically as the common offset rises,
527 // so the finest quantisation that fits the budget is a bisection --
528 // which also means the psychoacoustic model only has to get the shape
529 // of the allocation right, not its absolute level.
530 // Per-band peak, energy and scalefactor floor on the post-M/S
531 // coefficients: none of them depend on the rate loop's offset, so
532 // they are computed once per channel and read by every cost probe.
533 let profiles: Vec<Vec<BandProfile>> = elements
534 .iter()
535 .map(|plan| {
536 plan.frames
537 .iter()
538 .map(|frame| band_profile(frame, swb, max_sfb, short))
539 .collect()
540 })
541 .collect();
542 // Every noise query a probe makes is memoised for the frame: the
543 // bisection probes revisit the same (band, scalefactor) pairs across
544 // the outer loop, and band_noise is pure per frame.
545 let mut memo = NoiseMemo::new(self.channels * max_sfb * 256);
546 let mut cost = |enc: &AacEncoder, offset: i32| -> (i32, Vec<Coded>) {
547 let mut coded = Vec::new();
548 let mut bits = 10i32; // END element plus byte-alignment slack
549 let mut ch_slot = 0usize;
550 for (plan, profiles) in elements.iter().zip(&profiles) {
551 bits += 3
552 + 4
553 + if plan.element == Element::Cpe {
554 1 + 2 + max_sfb as i32
555 } else {
556 0
557 };
558 for (frame, profile) in plan.frames.iter().zip(profiles) {
559 let c =
560 enc.quantise(frame, profile, &mut memo, ch_slot, seq, swb, max_sfb, offset);
561 bits += c.bits;
562 coded.push(c);
563 ch_slot += 1;
564 }
565 }
566 (bits, coded)
567 };
568 let (probe_bits, mut coded) = cost(self, 240);
569 let mut answer = 240i32;
570 if probe_bits > budget {
571 // Even the coarsest setting overflows: take it and let the
572 // reservoir absorb the overshoot.
573 } else {
574 // Bits fall monotonically as the offset rises, so "fits the
575 // budget" is true on an upper interval and the finest fitting
576 // setting is its left edge. Last frame's working point sits next
577 // to that edge, so probe it first and gallop outward until one
578 // side is known to fail, then bisect the short bracket -- the
579 // same edge a full-range bisection would find, in a few probes.
580 let start = self.warm_offset.clamp(-240, 240);
581 let (start_bits, start_coded) = cost(self, start);
582 if start_bits <= budget {
583 // Known to fit: the edge is at or below `start`. Walk down.
584 let mut hi = start;
585 coded = start_coded;
586 let mut fail = None;
587 let mut step = 1i32;
588 loop {
589 let probe = (start - step).max(-240);
590 let (b, c) = cost(self, probe);
591 if b <= budget {
592 hi = probe;
593 coded = c;
594 } else {
595 fail = Some(probe);
596 }
597 let done = probe == -240 || fail.is_some();
598 if done {
599 break;
600 }
601 step *= 2;
602 }
603 if let Some(mut lo) = fail {
604 while hi - lo > 1 {
605 let mid = lo + (hi - lo + 1) / 2;
606 let (b, c) = cost(self, mid);
607 if b <= budget {
608 hi = mid;
609 coded = c;
610 } else {
611 lo = mid;
612 }
613 }
614 }
615 answer = hi;
616 } else {
617 // `start` sits past the edge: the answer is above it. Walk up.
618 let mut lo = start;
619 let mut hi = 240i32; // known to fit from the first probe
620 let mut step = 1i32;
621 loop {
622 let probe = (start + step).min(240);
623 if probe == 240 {
624 // Already probed and known to fit; `hi` keeps 240.
625 break;
626 }
627 let (b, c) = cost(self, probe);
628 if b <= budget {
629 hi = probe;
630 coded = c;
631 break;
632 }
633 lo = probe;
634 step *= 2;
635 }
636 while hi - lo > 1 {
637 let mid = lo + (hi - lo + 1) / 2;
638 let (b, c) = cost(self, mid);
639 if b <= budget {
640 hi = mid;
641 coded = c;
642 } else {
643 lo = mid;
644 }
645 }
646 answer = hi;
647 }
648 }
649 self.warm_offset = answer;
650
651 let mut w = BitWriter::new();
652 let mut at = 0usize;
653 for plan in &elements {
654 let id = match plan.element {
655 Element::Sce => 0u32,
656 Element::Cpe => 1,
657 Element::Lfe => 3,
658 };
659 w.write_bits(id, 3);
660 w.write_bits(0, 4); // element_instance_tag
661 if plan.element == Element::Cpe {
662 w.write_bit(true); // common_window
663 write_ics_info(&mut w, &coded[at]);
664 w.write_bits(1, 2); // ms_mask_present: per band
665 for b in 0..coded[at].max_sfb {
666 w.write_bit(plan.ms[b]);
667 }
668 write_ics(&mut w, &coded[at], false);
669 write_ics(&mut w, &coded[at + 1], false);
670 at += 2;
671 } else {
672 write_ics(&mut w, &coded[at], true);
673 at += 1;
674 }
675 }
676 w.write_bits(7, 3); // END
677 w.align_to_byte();
678 w.into_bytes()
679 }
680
681 /// Inner distortion loop: the coarsest scalefactor per band whose noise
682 /// still sits under the mask, then codebook choice and an exact bit count.
683 ///
684 /// Only bands that actually code anything carry a scalefactor, and the
685 /// codebook can only code a delta of +/-60 between consecutive ones. Both
686 /// facts are settled here rather than at write time -- a scalefactor the
687 /// bitstream cannot carry would come back at the wrong gain, and chaining
688 /// the constraint through *silent* bands is what drags a fine scalefactor
689 /// into the empty top of the spectrum and spends the frame on leakage.
690 fn quantise(
691 &self,
692 frame: &ChannelFrame,
693 profile: &BandProfile,
694 memo: &mut NoiseMemo,
695 ch_slot: usize,
696 seq: WindowSequence,
697 swb: &'static [u16],
698 max_sfb: usize,
699 offset: i32,
700 ) -> Coded {
701 let short = seq == WindowSequence::EightShort;
702 let windows = if short { 8 } else { 1 };
703 let mut sf = vec![0i32; max_sfb];
704 let mut floor = vec![0i32; max_sfb];
705 let mut zero = vec![true; max_sfb];
706 for b in 0..max_sfb {
707 if profile.peak[b] < 1e-4 {
708 continue;
709 }
710 // The rate loop scales the whole mask rather than shifting the
711 // scalefactors: that keeps the noise following the shape the model
712 // asked for, and lets a band whose signal falls under its own mask
713 // drop out entirely instead of being coded ever more coarsely.
714 let target = frame.threshold[b] * POW_HALF[(offset + 240) as usize];
715 if profile.energy[b] / profile.count[b].max(1) as f32 <= target {
716 continue;
717 }
718 floor[b] = profile.floor[b];
719 // Noise is non-decreasing in level (coarser step -> more error),
720 // the same assumption the original linear scan relied on to break
721 // on first overage; bisect for the largest level still under
722 // target instead of walking it one step at a time.
723 let mut best = floor[b];
724 if memo.noise(
725 ch_slot,
726 max_sfb,
727 b,
728 floor[b],
729 || self.band_noise(frame, swb, b, floor[b], windows, short),
730 ) <= target
731 {
732 let (mut lo, mut hi) = (floor[b], 255);
733 while lo < hi {
734 let mid = lo + (hi - lo + 1) / 2;
735 if memo.noise(ch_slot, max_sfb, b, mid, || {
736 self.band_noise(frame, swb, b, mid, windows, short)
737 }) <= target {
738 lo = mid;
739 } else {
740 hi = mid - 1;
741 }
742 }
743 best = lo;
744 }
745 sf[b] = best.clamp(floor[b], 255);
746 zero[b] = false;
747 }
748
749 let mut quant = vec![0i32; FRAME_LEN];
750 let mut books = vec![0u8; max_sfb];
751 // Bands whose scalefactor the delta chain moved since they were last
752 // quantised; every band is dirty on the first pass.
753 let mut dirty = vec![true; max_sfb];
754 for _ in 0..4 {
755 let mut settled = true;
756 let mut prev: Option<i32> = None;
757 for b in 0..max_sfb {
758 if zero[b] {
759 continue;
760 }
761 let fixed = match prev {
762 None => sf[b],
763 Some(p) => sf[b].clamp(p - 60, p + 60).clamp(0, 255),
764 };
765 if fixed != sf[b] {
766 sf[b] = fixed;
767 dirty[b] = true;
768 settled = false;
769 }
770 prev = Some(sf[b]);
771 }
772 for b in 0..max_sfb {
773 let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
774 if zero[b] {
775 books[b] = 0;
776 for w in 0..windows {
777 let base = if short { w * SHORT_LEN } else { 0 };
778 quant[base + lo..base + hi].fill(0);
779 }
780 dirty[b] = false;
781 continue;
782 }
783 // A band the delta chain left alone keeps its quantised
784 // values, its peak and its codebook from the previous pass.
785 if !dirty[b] {
786 continue;
787 }
788 let gain = pow_quarter(SF_OFFSET - sf[b]);
789 let mut peak = 0i32;
790 for w in 0..windows {
791 let base = if short { w * SHORT_LEN } else { 0 };
792 for k in lo..hi {
793 let q = quantise_one(frame.coef[base + k], gain);
794 quant[base + k] = q;
795 peak = peak.max(q.abs());
796 }
797 }
798 books[b] = codebook_for(peak);
799 dirty[b] = false;
800 if peak == 0 {
801 // Nothing survived: the band leaves the delta chain, which
802 // may free the bands after it to go coarser.
803 zero[b] = true;
804 settled = false;
805 }
806 }
807 if settled {
808 break;
809 }
810 }
811
812 let mut bits = 8 + 3; // global_gain plus the three tool flags
813 let mut prev: Option<i32> = None;
814 for b in 0..max_sfb {
815 if books[b] == 0 {
816 continue;
817 }
818 bits += band_bits(&quant, swb, b, books[b], windows, short);
819 let value = prev.map_or(60, |p| (60 + sf[b] - p).clamp(0, 120));
820 bits += i32::from(SCALEFACTOR_CODES[value as usize].0);
821 prev = Some(sf[b]);
822 }
823 let mut sections = 0;
824 let mut b = 0usize;
825 while b < max_sfb {
826 let book = books[b];
827 while b < max_sfb && books[b] == book {
828 b += 1;
829 }
830 sections += 1;
831 }
832 bits += sections * (4 + if short { 3 } else { 5 });
833 Coded {
834 seq,
835 max_sfb,
836 swb,
837 sf,
838 books,
839 quant,
840 bits,
841 short,
842 }
843 }
844
845 /// Quantisation noise energy of one band at a candidate scalefactor.
846 fn band_noise(
847 &self,
848 frame: &ChannelFrame,
849 swb: &[u16],
850 band: usize,
851 sf: i32,
852 windows: usize,
853 short: bool,
854 ) -> f32 {
855 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
856 let gain = pow_quarter(sf - SF_OFFSET);
857 let gain_inv = pow_quarter(SF_OFFSET - sf);
858 let mut noise = 0.0f32;
859 let mut count = 0usize;
860 for w in 0..windows {
861 let base = if short { w * SHORT_LEN } else { 0 };
862 for k in base + lo..base + hi {
863 let x = frame.coef[k];
864 let q = quantise_one(x, gain_inv);
865 let mut back = pow43(q.unsigned_abs()) * gain;
866 if q < 0 {
867 back = -back;
868 }
869 noise += (x - back) * (x - back);
870 count += 1;
871 }
872 }
873 noise / count.max(1) as f32
874 }
875}
876
877struct ElementPlan {
878 element: Element,
879 frames: Vec<ChannelFrame>,
880 ms: Vec<bool>,
881}
882
883/// A channel's quantised frame, ready to write.
884struct Coded {
885 seq: WindowSequence,
886 max_sfb: usize,
887 swb: &'static [u16],
888 sf: Vec<i32>,
889 books: Vec<u8>,
890 quant: Vec<i32>,
891 bits: i32,
892 short: bool,
893}
894
895/// True when mid/side splits this band's energy more lopsidedly than left/right
896/// does, which is when it costs fewer bits.
897fn ms_wins(l: &ChannelFrame, r: &ChannelFrame, swb: &[u16], band: usize, short: bool) -> bool {
898 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
899 let windows = if short { 8 } else { 1 };
900 let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
901 for w in 0..windows {
902 let base = if short { w * SHORT_LEN } else { 0 };
903 for k in base + lo..base + hi {
904 let (a, b) = (f64::from(l.coef[k]), f64::from(r.coef[k]));
905 el += a * a;
906 er += b * b;
907 em += (a + b) * (a + b) * 0.25;
908 es += (a - b) * (a - b) * 0.25;
909 }
910 }
911 let lr = (el.max(er) + 1e-9) / (el.min(er) + 1e-9);
912 let ms = (em.max(es) + 1e-9) / (em.min(es) + 1e-9);
913 ms > lr * 1.5
914}
915
916/// Per-band constants of one channel's quantised frame: the peak magnitude,
917/// the coefficient energy and the escape-codebook scalefactor floor. All
918/// three are independent of the rate loop's offset, so `write_frame` computes
919/// them once and every cost probe reads them back.
920struct BandProfile {
921 peak: Vec<f32>,
922 energy: Vec<f32>,
923 /// Coefficient count per band, the energy's divisor.
924 count: Vec<usize>,
925 floor: Vec<i32>,
926}
927
928fn band_profile(frame: &ChannelFrame, swb: &[u16], max_sfb: usize, short: bool) -> BandProfile {
929 let windows = if short { 8 } else { 1 };
930 let mut peak = vec![0.0f32; max_sfb];
931 let mut energy = vec![0.0f32; max_sfb];
932 let mut count = vec![0usize; max_sfb];
933 let mut floor = vec![0i32; max_sfb];
934 for b in 0..max_sfb {
935 let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
936 for w in 0..windows {
937 let base = if short { w * SHORT_LEN } else { 0 };
938 for k in base + lo..base + hi {
939 let c = frame.coef[k];
940 peak[b] = peak[b].max(c.abs());
941 energy[b] += c * c;
942 count[b] += 1;
943 }
944 }
945 floor[b] = sf_floor(peak[b]).max(0);
946 }
947 BandProfile {
948 peak,
949 energy,
950 count,
951 floor,
952 }
953}
954
955/// Per-frame cache for the noise search: `band_noise(band, sf)` is pure for
956/// one frame's coefficients, and the outer rate loop's probes re-ask the same
957/// (band, scalefactor) pairs, so each pair is computed at most once per frame
958/// clearing pass.
959struct NoiseMemo {
960 stamp: Vec<u32>,
961 val: Vec<f32>,
962 cur: u32,
963}
964
965impl NoiseMemo {
966 fn new(capacity: usize) -> NoiseMemo {
967 NoiseMemo {
968 stamp: vec![0; capacity],
969 val: vec![0.0; capacity],
970 cur: 1,
971 }
972 }
973
974 /// The memoised noise at `(band, sf)`, computing through `f` on a miss.
975 fn noise(
976 &mut self,
977 ch_slot: usize,
978 max_sfb: usize,
979 band: usize,
980 sf: i32,
981 f: impl FnOnce() -> f32,
982 ) -> f32 {
983 let idx = (ch_slot * max_sfb + band) * 256 + sf as usize;
984 if self.stamp[idx] == self.cur {
985 return self.val[idx];
986 }
987 let noise = f();
988 self.stamp[idx] = self.cur;
989 self.val[idx] = noise;
990 noise
991 }
992}
993
994fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, short: bool) {
995 let windows = if short { 8 } else { 1 };
996 for b in 0..max_sfb {
997 if !ms[b] {
998 continue;
999 }
1000 let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1]));
1001 for w in 0..windows {
1002 let base = if short { w * SHORT_LEN } else { 0 };
1003 for k in base + lo..base + hi {
1004 let (a, b2) = (pair[0].coef[k], pair[1].coef[k]);
1005 pair[0].coef[k] = (a + b2) * 0.5;
1006 pair[1].coef[k] = (a - b2) * 0.5;
1007 }
1008 }
1009 // The side channel inherits the pair's tighter mask.
1010 let t = pair[0].threshold[b].min(pair[1].threshold[b]);
1011 pair[0].threshold[b] = t;
1012 pair[1].threshold[b] = t;
1013 }
1014}
1015
1016/// `q^(4/3)` for the (small, bounded-by-`MAX_QUANT`) integer magnitudes the
1017/// rate loop's noise search re-tests at every candidate scalefactor: a table
1018/// lookup replaces what was otherwise the encoder's hottest `powf` call site.
1019static POW43: LazyLock<Vec<f32>> = LazyLock::new(|| {
1020 (0..=MAX_QUANT as u32)
1021 .map(|q| (q as f32).powf(4.0 / 3.0))
1022 .collect()
1023});
1024
1025/// `2^(v/4)` for every integer v the rate loop asks for: a band's quantiser
1026/// step is `2^((sf-100)/4)` in `band_noise` and its reciprocal inside
1027/// [`quantise_one`], and the exponent's integer range over sf in 0..=255 is
1028/// -100..=155 either way. Every entry is produced by the very `powf` call it
1029/// replaces, so lookups return the bit-identical value.
1030static POW_QUARTER: LazyLock<Vec<f32>> = LazyLock::new(|| {
1031 (-155i32..=155)
1032 .map(|v| 2f32.powf(v as f32 * 0.25))
1033 .collect()
1034});
1035
1036fn pow_quarter(v: i32) -> f32 {
1037 POW_QUARTER[(v + 155) as usize]
1038}
1039
1040/// `2^(offset/2)`, the rate loop's mask scale, same table trick at the
1041/// half-octave stride; the bisection bounds keep offset in -240..=240.
1042static POW_HALF: LazyLock<Vec<f32>> = LazyLock::new(|| {
1043 (-240i32..=240)
1044 .map(|o| 2f32.powf(o as f32 * 0.5))
1045 .collect()
1046});
1047
1048fn pow43(q: u32) -> f32 {
1049 POW43[q.min(MAX_QUANT as u32) as usize]
1050}
1051
1052/// The finest scalefactor at which a peak of this size still fits the escape
1053/// codebook: below it the quantiser saturates, which costs bits *and* adds
1054/// distortion.
1055fn sf_floor(peak: f32) -> i32 {
1056 let want = (0.75 * peak.log2() - (MAX_QUANT as f32).log2()) / 0.1875;
1057 SF_OFFSET + want.ceil() as i32
1058}
1059
1060/// The gain is the band's `2^((sf-100)/4)` reciprocal -- `pow_quarter`'s
1061/// job -- hoisted to the call sites so the inner-inner loop is sqrts only.
1062/// The value is the same f32 the old per-coefficient `powf` produced, so the
1063/// quantised integers do not move.
1064fn quantise_one(x: f32, gain: f32) -> i32 {
1065 if x == 0.0 {
1066 return 0;
1067 }
1068 // x^0.75 == sqrt(x * sqrt(x)): two sqrtf beat one powf by a wide margin,
1069 // and this call site is the rate loop's inner-inner loop.
1070 let v = x.abs() * gain;
1071 let q = (v.sqrt() * v.sqrt().sqrt() + ROUND_BIAS) as i32;
1072 let q = q.min(MAX_QUANT);
1073 if x < 0.0 { -q } else { q }
1074}
1075
1076/// The cheapest codebook that can carry a peak magnitude.
1077fn codebook_for(peak: i32) -> u8 {
1078 match peak {
1079 0 => 0,
1080 1 => 1,
1081 2 => 3,
1082 3..=4 => 5,
1083 5..=7 => 7,
1084 8..=12 => 9,
1085 _ => 11,
1086 }
1087}
1088
1089fn band_bits(
1090 quant: &[i32],
1091 swb: &[u16],
1092 band: usize,
1093 book: u8,
1094 windows: usize,
1095 short: bool,
1096) -> i32 {
1097 let cb = &CODEBOOKS[usize::from(book) - 1];
1098 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
1099 let dim = usize::from(cb.dim);
1100 let mut bits = 0i32;
1101 for w in 0..windows {
1102 let base = if short { w * SHORT_LEN } else { 0 };
1103 let mut k = lo;
1104 while k < hi {
1105 let end = (k + dim).min(hi);
1106 bits += tuple_bits(cb, &quant[base + k..base + end]);
1107 k += dim;
1108 }
1109 }
1110 bits
1111}
1112
1113/// Bits one Huffman tuple costs, sign and escape included.
1114fn tuple_bits(cb: &Codebook, values: &[i32]) -> i32 {
1115 let mut bits = i32::from(cb.codes[tuple_index(cb, values)].0);
1116 for &v in values {
1117 if cb.unsigned && v != 0 {
1118 bits += 1;
1119 }
1120 if cb.esc && v.unsigned_abs() >= 16 {
1121 let n = escape_order(v.unsigned_abs());
1122 bits += 2 * n + 5;
1123 }
1124 }
1125 bits
1126}
1127
1128/// The escape's unary length: `value` needs `n + 4` payload bits.
1129fn escape_order(mag: u32) -> i32 {
1130 (32 - mag.leading_zeros()) as i32 - 5
1131}
1132
1133/// Tuple to codebook index, clamped into the codebook's range.
1134fn tuple_index(cb: &Codebook, values: &[i32]) -> usize {
1135 let span = if cb.unsigned {
1136 usize::from(cb.lav) + 1
1137 } else {
1138 2 * usize::from(cb.lav) + 1
1139 };
1140 let mut idx = 0usize;
1141 for i in 0..usize::from(cb.dim) {
1142 let v = values.get(i).copied().unwrap_or(0);
1143 let digit = if cb.unsigned {
1144 v.unsigned_abs().min(u32::from(cb.lav)) as usize
1145 } else {
1146 (v.clamp(-i32::from(cb.lav), i32::from(cb.lav)) + i32::from(cb.lav)) as usize
1147 };
1148 idx = idx * span + digit;
1149 }
1150 idx
1151}
1152
1153fn write_tuple(w: &mut BitWriter, cb: &Codebook, values: &[i32]) {
1154 let (len, code) = cb.codes[tuple_index(cb, values)];
1155 w.write_bits(code, u32::from(len));
1156 if cb.unsigned {
1157 for &v in values.iter().take(usize::from(cb.dim)) {
1158 if v != 0 {
1159 w.write_bit(v < 0);
1160 }
1161 }
1162 }
1163 if cb.esc {
1164 for &v in values.iter().take(usize::from(cb.dim)) {
1165 let mag = v.unsigned_abs();
1166 if mag >= 16 {
1167 let n = escape_order(mag) as u32;
1168 for _ in 0..n {
1169 w.write_bit(true);
1170 }
1171 w.write_bit(false);
1172 w.write_bits(mag & ((1 << (n + 4)) - 1), n + 4);
1173 }
1174 }
1175 }
1176}
1177
1178fn write_ics_info(w: &mut BitWriter, c: &Coded) {
1179 w.write_bit(false); // ics_reserved_bit
1180 let seq = match c.seq {
1181 WindowSequence::OnlyLong => 0,
1182 WindowSequence::LongStart => 1,
1183 WindowSequence::EightShort => 2,
1184 WindowSequence::LongStop => 3,
1185 };
1186 w.write_bits(seq, 2);
1187 w.write_bit(false); // sine window shape
1188 if c.short {
1189 w.write_bits(c.max_sfb as u32, 4);
1190 w.write_bits(0x7F, 7); // one group of eight windows
1191 } else {
1192 w.write_bits(c.max_sfb as u32, 6);
1193 w.write_bit(false); // predictor_data_present
1194 }
1195}
1196
1197fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
1198 let first = c.books.iter().position(|&b| b != 0);
1199 let global_gain = first.map_or(100, |b| c.sf[b]).clamp(0, 255) as u32;
1200 w.write_bits(global_gain, 8);
1201 if own_info {
1202 write_ics_info(w, c);
1203 }
1204 // section_data
1205 let esc_bits = if c.short { 3 } else { 5 };
1206 let esc = (1u32 << esc_bits) - 1;
1207 let mut b = 0usize;
1208 while b < c.max_sfb {
1209 let book = c.books[b];
1210 let start = b;
1211 while b < c.max_sfb && c.books[b] == book {
1212 b += 1;
1213 }
1214 w.write_bits(u32::from(book), 4);
1215 let mut left = (b - start) as u32;
1216 while left >= esc {
1217 w.write_bits(esc, esc_bits);
1218 left -= esc;
1219 }
1220 w.write_bits(left, esc_bits);
1221 }
1222 // scale_factor_data
1223 let mut prev = global_gain as i32;
1224 for b in 0..c.max_sfb {
1225 if c.books[b] == 0 {
1226 continue;
1227 }
1228 let value = (60 + c.sf[b] - prev).clamp(0, 120) as usize;
1229 let (len, code) = SCALEFACTOR_CODES[value];
1230 w.write_bits(code, u32::from(len));
1231 prev += value as i32 - 60;
1232 }
1233 w.write_bit(false); // pulse_data_present
1234 w.write_bit(false); // tns_data_present
1235 w.write_bit(false); // gain_control_data_present
1236 // spectral_data
1237 let windows = if c.short { 8 } else { 1 };
1238 for b in 0..c.max_sfb {
1239 let book = c.books[b];
1240 if book == 0 {
1241 continue;
1242 }
1243 let cb = &CODEBOOKS[usize::from(book) - 1];
1244 let dim = usize::from(cb.dim);
1245 let (lo, hi) = (usize::from(c.swb[b]), usize::from(c.swb[b + 1]));
1246 for win in 0..windows {
1247 let base = if c.short { win * SHORT_LEN } else { 0 };
1248 let mut k = lo;
1249 while k < hi {
1250 let end = (k + dim).min(hi);
1251 write_tuple(w, cb, &c.quant[base + k..base + end]);
1252 k += dim;
1253 }
1254 }
1255 }
1256}
1257
1258/// Which channel element carries which of the caller's channels. The caller
1259/// speaks film order (`FL, FR, FC, LFE, BL, BR, SL, SR`); the bitstream wants
1260/// centre first and LFE last (ISO/IEC 14496-3 tbl 1.19).
1261#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1262enum Element {
1263 Sce,
1264 Cpe,
1265 Lfe,
1266}
1267
1268fn element_layout(channels: usize) -> Vec<(Element, Vec<usize>)> {
1269 match channels {
1270 1 => vec![(Element::Sce, vec![0])],
1271 2 => vec![(Element::Cpe, vec![0, 1])],
1272 3 => vec![(Element::Sce, vec![2]), (Element::Cpe, vec![0, 1])],
1273 4 => vec![
1274 (Element::Sce, vec![2]),
1275 (Element::Cpe, vec![0, 1]),
1276 (Element::Sce, vec![3]),
1277 ],
1278 5 => vec![
1279 (Element::Sce, vec![2]),
1280 (Element::Cpe, vec![0, 1]),
1281 (Element::Cpe, vec![3, 4]),
1282 ],
1283 6 => vec![
1284 (Element::Sce, vec![2]),
1285 (Element::Cpe, vec![0, 1]),
1286 (Element::Cpe, vec![4, 5]),
1287 (Element::Lfe, vec![3]),
1288 ],
1289 8 => vec![
1290 (Element::Sce, vec![2]),
1291 (Element::Cpe, vec![0, 1]),
1292 (Element::Cpe, vec![6, 7]),
1293 (Element::Cpe, vec![4, 5]),
1294 (Element::Lfe, vec![3]),
1295 ],
1296 n => (0..n).map(|i| (Element::Sce, vec![i])).collect(),
1297 }
1298}