forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7947774Tahinli1 month ago3899 commits

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