forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBea55462Tahinli3 months ago753 commits

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