forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe12d32fTahinli6 days ago3982 commits

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