forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBabd41b6Tahinli3 months ago75 commits

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