forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a26b91Tahinli3 months ago348 commits

encode.rs1704 lines, 62.7 KiBHistoryRawDownload
1//! The encoder: PCM in, Vorbis packets out, with a setup header written for the
2//! stream's own channel layout.
3//!
4//! ## What the analysis actually is
5//!
6//! Per block, per channel: an MDCT, a peak magnitude per floor point, a
7//! spreading function over those points, a Bark-domain near-band masker under
8//! it, an absolute threshold of hearing under that, and a headroom the rate
9//! loop moves. The floor
10//! that comes out is the quantiser step: the residue is the spectrum divided by
11//! the floor and rounded, so headroom in dB *is* precision in bits. That is
12//! psychoacoustics-lite and it is stated as such — there is no tonality
13//! estimate beyond a two-mode block switch and no per-band bit allocation
14//! beyond what the floor implies.
15//!
16//! ## Block switching (§1.3.2 / §4.3)
17//!
18//! Two modes: a 256-sample short block and a 2048-sample long block. Steady
19//! content codes long blocks only. A transient — energy in a 128-sample tick
20//! jumping past its predecessor, which is also what an onset after digital
21//! silence looks like — swaps one pair of would-be long blocks for a
22//! long-with-short-right-window (the block that would otherwise carry the
23//! pre-echo), eight short blocks spanning the transient itself, and a
24//! long-with-short-left-window resuming steady state. The granule advance
25//! across that whole run is exactly two long hops, so the switch never moves
26//! the steady-state grid.
27//!
28//! ## Codebooks
29//!
30//! Designed here rather than inherited: a floor book over the folded amplitude
31//! range, a class book over partition-class pairs, and eight residue books whose
32//! ranges (+-1, +-2, +-4 ... +-64, +-127) the partition classifier picks between —
33//! a partition's values sit about a sixth of its class's range on average,
34//! so one book per octave of range keeps every value near the top of its
35//! own book. All of
36//! them are Huffman codes over stated distributions, built at construction and
37//! written into every stream's own setup header — which is why this encoder
38//! needs no embedded profile and has no channel count it cannot serve. Both
39//! block sizes share these books; only the floor's X grid and the residue's
40//! partition size are sized per block.
41
42use ec_core::{
43 AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet,
44 Result, SampleFormat, TimeBase,
45};
46use ec_dsp::Mdct;
47
48use crate::bits::{BitsOut, float32_pack};
49use crate::codebook::{CodebookSpec, ilog, lookup1_values};
50use crate::decode::channel_map;
51use crate::floor::render_floor1;
52use crate::setup::Floor1;
53use crate::window::Windows;
54
55/// Long block size.
56const BLOCK_LONG: usize = 2048;
57/// Short block size.
58const BLOCK_SHORT: usize = 256;
59/// Coefficients in a long block.
60const HALF_LONG: usize = BLOCK_LONG / 2;
61/// Coefficients in a short block.
62const HALF_SHORT: usize = BLOCK_SHORT / 2;
63/// Long-block coefficients per residue partition.
64const PARTITION_LONG: usize = 16;
65/// Short-block coefficients per residue partition.
66const PARTITION_SHORT: usize = 16;
67/// Long floor X points besides the two endpoints. Fewer is better here, on
68/// real music at 128 kbps: 12 beat 16, 20, 32 and 44 in that order, since a
69/// finer floor costs bits of its own and then follows every peak closely
70/// enough to spend residue bits under all of them.
71const FLOOR_POINTS_LONG: usize = 12;
72/// Short floor X points besides the two endpoints.
73const FLOOR_POINTS_SHORT: usize = 8;
74/// Floor values per class.
75const FLOOR_CLASS_DIM: usize = 4;
76/// Residue classes; class 0 codes nothing at all.
77const CLASSES: usize = 9;
78/// Largest quantised residue each class's book can state.
79const CLASS_RANGE: [i32; CLASSES] = [0, 1, 2, 4, 8, 16, 32, 64, 127];
80/// Residue codebook dimensions by class; class 0 codes no residue.
81const RESIDUE_BOOK_DIM: [usize; CLASSES] = [0, 4, 2, 2, 1, 1, 1, 1, 1];
82/// The vector books save packet bits but add setup and make the rate loop spend
83/// harder; this keeps the realised rate at the caller's target.
84const RATE_TARGET_SCALE: f64 = 0.97;
85/// Headroom in dB the widest residue book can actually state: 20 log10 127
86/// is 42, but a coupled angle channel is a difference of two magnitudes, so a
87/// pair's step must leave half that range — 63, 36 dB. Past this the rate loop's extra headroom lowers the absolute-threshold
88/// bound instead, so sparse or quiet content — where most partitions sit under
89/// the threshold and code as class 0 whatever the step — gains bins to spend
90/// bits on rather than a finer step nothing can represent.
91const HEADROOM_RANGE: f64 = 36.0;
92/// A short block's range: the full 42 dB. Its step is what sets the pre-echo
93/// left inside the block that carries an onset, and 6 dB of it is the
94/// difference between a leak twice the reference's and one under it.
95/// Anything the wider range cannot state (a pair's angle, a peak at a floor
96/// region's edge) is caught by the clamp refit in `encode_block`.
97const HEADROOM_RANGE_SHORT: f64 = 42.0;
98/// Nothing more than this many dB under a block's loudest floor point is
99/// coded: a whole-spectrum co-masking cap after local spreading. The Bark
100/// curve keeps nearby bands honest; this cap only stops very quiet distant
101/// bins from spending bits below the noise floor at these rates. Swept on
102/// three tracks at 128 kbps: 50 dB kept the accuracy win without inflating the
103/// files.
104const CO_MASK_RANGE: f64 = 50.0;
105/// Extra dB above the spread threshold. This is the single long-block
106/// rate/quality knob: raising the curve zeroes masked coefficients earlier,
107/// while peaks still ride as residue above it.
108const MASKING_OFFSET_DB: f64 = 9.0;
109/// All-zero partition guard: if the masked band still has a bin within this
110/// fraction of the floor, keep that bin as one sign-only residue sample.
111const NOISE_NORMALISE_MIN_RATIO: f32 = 0.5;
112/// A short block gets no co-masking cap: a bin it drops is an error spread
113/// across its whole window, the half before an onset included, and that is
114/// the pre-echo the short block exists to prevent (44.1k mono, onset on the
115/// grid: peak 0.0085 with the cap, under 0.007 without).
116const CO_MASK_RANGE_SHORT: f64 = f64::INFINITY;
117/// Above this frequency the coupled pair's angle is dropped and only the
118/// magnitude coded (point stereo): the ear does not place HF detail by
119/// inter-channel level difference finely enough to pay for coding it, and at
120/// this rate the bits buy more accuracy in the magnitude. Below it the pair
121/// is coded losslessly. Swept on real music at 128 kbps: 3-6 kHz are equal,
122/// 10 kHz and no cutoff are worse.
123const POINT_STEREO_HZ: f64 = 4_000.0;
124/// Least headroom a short block is quantised with, whatever the rate loop's.
125const HEADROOM_SHORT_MIN: f64 = 42.0;
126/// Samples per transient-detection tick — the short block's own hop, so a
127/// tick lines up with the finest time resolution the encoder has.
128const TICK: usize = BLOCK_SHORT / 4;
129/// Short blocks a detected transient inserts between the two transition long
130/// blocks. Detection looks one long hop ahead of the transition-out
131/// candidate, so the transient can land anywhere in that hop; the run is
132/// sized to three long hops' worth of short-hop resolution (any `8 + 8k`
133/// count keeps the steady-state grid aligned) so it comfortably straddles a
134/// transient found anywhere in the hop being watched, not just at its start.
135const SHORT_RUN: u8 = 16;
136/// Mode index the setup header and every packet agree the short mode is.
137const MODE_SHORT: u32 = 0;
138/// Mode index the setup header and every packet agree the long mode is.
139const MODE_LONG: u32 = 1;
140/// A tick energy jump past this multiple of its predecessor is a transient;
141/// a near-zero predecessor makes this trip on any onset above the floor.
142const TRANSIENT_RATIO: f64 = 14.0;
143/// Below this per-sample mean square (-60 dBFS), a tick is not "content" at
144/// all — the floor that keeps digital silence, dither and fade tails from
145/// tripping the detector.
146const TRANSIENT_FLOOR: f64 = 1e-6;
147/// Ticks before the candidate whose loudest one the jump is measured from.
148const TRANSIENT_HISTORY: usize = 4;
149
150/// Buffer samples of left pre-roll before input sample 0 — one long half, so
151/// even a block starting at the very front of the stream finds zeroes rather
152/// than reading off the front of the buffer.
153const PREROLL: usize = HALF_LONG;
154
155/// How the encoder is set up.
156#[derive(Debug, Clone, Copy, PartialEq)]
157pub struct EncoderConfig {
158 /// Sample rate in Hz.
159 pub sample_rate: u32,
160 /// Channel count, in [`ec_core::ChannelLayout`] order.
161 pub channels: u16,
162 /// Target bitrate. Zero or less runs in pure quality mode.
163 pub bitrate_bps: i32,
164 /// Quality on `[0, 1]`: where the rate loop starts, and the fixed setting
165 /// when `bitrate_bps` is not positive.
166 pub quality: f32,
167}
168
169impl Default for EncoderConfig {
170 fn default() -> EncoderConfig {
171 EncoderConfig {
172 sample_rate: 48_000,
173 channels: 2,
174 bitrate_bps: 128_000,
175 quality: 0.5,
176 }
177 }
178}
179
180/// One encoded packet and where it ends.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct EncodedPacket {
183 /// Packet payload.
184 pub data: Vec<u8>,
185 /// Sample position this packet ends at — the Ogg granule.
186 pub granule: i64,
187 /// Samples this packet finalises.
188 pub samples: i64,
189}
190
191/// One block's shape: its mode and, for a long block, the window flags §4.3
192/// states beside it.
193#[derive(Debug, Clone, Copy)]
194struct BlockPlan {
195 is_long: bool,
196 prev_long: bool,
197 next_long: bool,
198}
199
200/// The block-switch scheduler's state between calls.
201#[derive(Debug, Clone, Copy)]
202enum Sched {
203 /// Long blocks, deciding fresh each time whether the next one is a
204 /// transient's transition-out.
205 Steady,
206 /// Short blocks left to emit, counting this call down to zero.
207 ShortRun(u8),
208 /// The long block that resumes steady state after a short run.
209 TransitionIn,
210}
211
212/// A block size's own floor, codebook-sharing residue geometry and masking data.
213struct BlockConfig {
214 half: usize,
215 partition: usize,
216 floor: Floor1,
217 ath: Vec<f64>,
218 bark: Vec<f64>,
219 /// Headroom the residue range lets this block size state.
220 range: f64,
221 /// dB under the loudest floor point below which nothing is coded.
222 co_mask: f64,
223}
224
225/// Vorbis I encoder.
226pub struct VorbisEncoder {
227 config: EncoderConfig,
228 params: CodecParameters,
229 /// `to_vorbis[ec channel] = vorbis channel`.
230 to_vorbis: Vec<usize>,
231 headers: Vec<Vec<u8>>,
232 long: BlockConfig,
233 short: BlockConfig,
234 floor_book: CodebookSpec,
235 class_book: CodebookSpec,
236 residue_books: Vec<CodebookSpec>,
237 /// Channel pairs coupled by the mapping; empty unless stereo.
238 coupling: Vec<(usize, usize)>,
239 mdct_long: Mdct<f32>,
240 mdct_short: Mdct<f32>,
241 windows: Windows,
242 /// Per Vorbis channel, input samples with [`PREROLL`] zeroes already in
243 /// front.
244 buffer: Vec<Vec<f32>>,
245 /// Input samples taken from the caller.
246 fed: i64,
247 /// Blocks already emitted.
248 blocks_emitted: i64,
249 /// Centre of the block emitted last; the sentinel one long hop before
250 /// sample 0, so the first real centre falls out of the same recurrence
251 /// every later one uses.
252 centre: i64,
253 /// Blocksize of the block emitted last.
254 prev_n: usize,
255 /// Granule of the packet emitted last.
256 granule: i64,
257 scheduler: Sched,
258 /// Headroom under the masking curve, in dB — the rate loop's variable.
259 headroom: f64,
260 finished: bool,
261 packets: std::collections::VecDeque<EncodedPacket>,
262}
263
264impl VorbisEncoder {
265 /// Build an encoder and write its three header packets.
266 pub fn new(config: EncoderConfig) -> Result<VorbisEncoder> {
267 let channels = usize::from(config.channels);
268 if channels == 0 || channels > 255 {
269 return Err(Error::unsupported(
270 format!("{channels} channels"),
271 "Vorbis states a channel count in one byte",
272 ));
273 }
274 if config.sample_rate == 0 {
275 return Err(Error::corrupt("encoder sample rate of zero"));
276 }
277 let (layout, to_ec) = channel_map(channels);
278 let mut to_vorbis = vec![0usize; channels];
279 for (vorbis, &ec) in to_ec.iter().enumerate() {
280 to_vorbis[ec] = vorbis;
281 }
282 // Coupling pays for a stereo pair and nothing else here: the surround
283 // layouts have no two channels that carry the same programme.
284 let coupling = match channels {
285 2 => vec![(0usize, 1usize)],
286 _ => Vec::new(),
287 };
288
289 let floor_book = design_floor_book();
290 let class_book = design_class_book();
291 let residue_books = design_residue_books();
292 let long = build_block_config(
293 HALF_LONG,
294 PARTITION_LONG,
295 FLOOR_POINTS_LONG,
296 HEADROOM_RANGE,
297 CO_MASK_RANGE,
298 &config,
299 );
300 let short = build_block_config(
301 HALF_SHORT,
302 PARTITION_SHORT,
303 FLOOR_POINTS_SHORT,
304 HEADROOM_RANGE_SHORT,
305 CO_MASK_RANGE_SHORT,
306 &config,
307 );
308
309 let headers = write_headers(
310 &config,
311 channels,
312 HeaderSetup {
313 long: &long,
314 short: &short,
315 floor_book: &floor_book,
316 class_book: &class_book,
317 residue_books: &residue_books,
318 coupling: &coupling,
319 },
320 );
321 let params = CodecParameters {
322 codec: CodecId::Vorbis,
323 media: MediaParameters::Audio(AudioParameters {
324 sample_rate: config.sample_rate,
325 layout,
326 format: Some(SampleFormat::F32),
327 bits_per_sample: None,
328 }),
329 extradata: Some(Buf::from_vec(lace(&headers))),
330 };
331
332 let quality = f64::from(config.quality.clamp(0.0, 1.0));
333 Ok(VorbisEncoder {
334 mdct_long: Mdct::new(BLOCK_LONG),
335 mdct_short: Mdct::new(BLOCK_SHORT),
336 windows: Windows::new(BLOCK_SHORT, BLOCK_LONG),
337 buffer: vec![vec![0.0; PREROLL]; channels],
338 fed: 0,
339 blocks_emitted: 0,
340 centre: -(HALF_LONG as i64),
341 prev_n: BLOCK_LONG,
342 granule: 0,
343 scheduler: Sched::Steady,
344 headroom: 4.0 + 26.0 * quality,
345 finished: false,
346 packets: std::collections::VecDeque::new(),
347 config,
348 params,
349 to_vorbis,
350 headers,
351 long,
352 short,
353 floor_book,
354 class_book,
355 residue_books,
356 coupling,
357 })
358 }
359
360 /// The three header packets, in order.
361 pub fn headers(&self) -> Vec<&[u8]> {
362 self.headers.iter().map(|h| &h[..]).collect()
363 }
364
365 /// The three header packets Xiph-laced, the form containers carry.
366 pub fn extradata(&self) -> Vec<u8> {
367 lace(&self.headers)
368 }
369
370 /// Parameters describing the stream, `extradata` included.
371 pub fn parameters(&self) -> &CodecParameters {
372 &self.params
373 }
374
375 /// Push planar samples, one slice per channel in [`ec_core::ChannelLayout`] order.
376 pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> {
377 if channels.len() != usize::from(self.config.channels) {
378 return Err(Error::corrupt(format!(
379 "{} channels pushed into a {}-channel encoder",
380 channels.len(),
381 self.config.channels
382 )));
383 }
384 if self.finished {
385 return Err(Error::corrupt("samples pushed after finish"));
386 }
387 let samples = channels.first().map_or(0, |c| c.len());
388 for (ec, data) in channels.iter().enumerate() {
389 if data.len() != samples {
390 return Err(Error::corrupt("channels of different lengths"));
391 }
392 self.buffer[self.to_vorbis[ec]].extend_from_slice(data);
393 }
394 self.fed += samples as i64;
395 self.encode_ready();
396 Ok(())
397 }
398
399 /// Push interleaved samples in [`ec_core::ChannelLayout`] order.
400 pub fn push_interleaved(&mut self, samples: &[f32]) -> Result<()> {
401 let channels = usize::from(self.config.channels);
402 if !samples.len().is_multiple_of(channels) {
403 return Err(Error::corrupt("interleaved push is not a whole frame"));
404 }
405 if self.finished {
406 return Err(Error::corrupt("samples pushed after finish"));
407 }
408 for (i, &value) in samples.iter().enumerate() {
409 self.buffer[self.to_vorbis[i % channels]].push(value);
410 }
411 self.fed += (samples.len() / channels) as i64;
412 self.encode_ready();
413 Ok(())
414 }
415
416 /// No more input; pad the grid out and encode the tail.
417 pub fn finish(&mut self) {
418 if self.finished {
419 return;
420 }
421 self.finished = true;
422 // Generous padding: a long block's own half plus a whole short-run's
423 // worth of slack, so whatever the scheduler is doing when the input
424 // runs out still finds real (zero) samples rather than the buffer's
425 // edge.
426 let needed = PREROLL + self.fed.max(0) as usize + 2 * BLOCK_LONG;
427 for channel in &mut self.buffer {
428 if channel.len() < needed {
429 channel.resize(needed, 0.0);
430 }
431 }
432 self.encode_ready();
433 }
434
435 /// Take the next packet, or [`Error::Eof`] once the encoder is drained.
436 pub fn next_packet(&mut self) -> Result<EncodedPacket> {
437 match self.packets.pop_front() {
438 Some(packet) => Ok(packet),
439 None if self.finished => Err(Error::Eof),
440 None => Err(Error::NeedMore),
441 }
442 }
443
444 /// Decide the next block's shape without committing the scheduler state;
445 /// used to check whether the data it needs is buffered yet.
446 fn peek_plan(&self) -> BlockPlan {
447 match self.scheduler {
448 Sched::Steady => BlockPlan {
449 is_long: true,
450 prev_long: true,
451 next_long: !self.transient_ahead(),
452 },
453 Sched::ShortRun(_) => BlockPlan {
454 is_long: false,
455 prev_long: true,
456 next_long: true,
457 },
458 Sched::TransitionIn => BlockPlan {
459 is_long: true,
460 prev_long: false,
461 next_long: true,
462 },
463 }
464 }
465
466 /// Advance the scheduler past the plan [`peek_plan`] just returned.
467 fn commit_plan(&mut self, plan: BlockPlan) {
468 self.scheduler = match self.scheduler {
469 Sched::Steady if !plan.next_long => Sched::ShortRun(SHORT_RUN),
470 Sched::Steady => Sched::Steady,
471 Sched::ShortRun(remaining) if remaining > 1 => Sched::ShortRun(remaining - 1),
472 Sched::ShortRun(_) => Sched::TransitionIn,
473 Sched::TransitionIn => Sched::Steady,
474 };
475 }
476
477 /// Whether the *next* steady long block's window carries a transient —
478 /// checked one hop ahead of the block being decided now, so the block
479 /// this call is about to type as transition-out still finishes its own
480 /// carried region (up to a short hop past its centre) safely before the
481 /// transient it is making room for. A tick's energy jumping past its
482 /// predecessor's is exactly what an onset after digital silence looks
483 /// like when the predecessor is zero.
484 fn transient_ahead(&self) -> bool {
485 // The very first block's "predecessor" is the encoder's own silent
486 // pre-roll, not a real signal boundary; nothing to detect there.
487 if self.centre == -(HALF_LONG as i64) {
488 return false;
489 }
490 let candidate_centre = self.centre + (self.prev_n + BLOCK_LONG) as i64 / 4;
491 let lookahead_centre = candidate_centre + BLOCK_LONG as i64 / 2;
492 let window_start = lookahead_centre - HALF_LONG as i64;
493 let buffer_start = window_start + PREROLL as i64;
494 if buffer_start < 0 || self.buffer[0].len() < (buffer_start as usize) + BLOCK_LONG {
495 return false;
496 }
497 let ticks = BLOCK_LONG / TICK;
498 let energy = |t: usize| -> f64 {
499 let start = buffer_start as usize + t * TICK;
500 let mut sum = 0.0f64;
501 for channel in &self.buffer {
502 for &s in &channel[start..start + TICK] {
503 sum += f64::from(s) * f64::from(s);
504 }
505 }
506 sum
507 };
508 // Only the right half is new; its left neighbour was already the
509 // right half the last time this block's window was checked.
510 let floor = TRANSIENT_FLOOR * (TICK * self.buffer.len()) as f64;
511 for t in ticks / 2..ticks {
512 // Against the loudest of the few ticks before it, not just the
513 // one: music rising over a few ticks is not a transient, a drum
514 // hit or an onset after silence is.
515 let previous = (t.saturating_sub(TRANSIENT_HISTORY)..t)
516 .map(energy)
517 .fold(0.0f64, f64::max);
518 let current = energy(t);
519 if current > floor && current > previous * TRANSIENT_RATIO {
520 return true;
521 }
522 }
523 false
524 }
525
526 /// Encode every block the buffer now holds whole.
527 fn encode_ready(&mut self) {
528 let channels = usize::from(self.config.channels);
529 loop {
530 if self.finished && self.blocks_emitted > 0 && self.granule >= self.fed {
531 break;
532 }
533 let plan = self.peek_plan();
534 let n = if plan.is_long {
535 BLOCK_LONG
536 } else {
537 BLOCK_SHORT
538 };
539 let half = if plan.is_long { HALF_LONG } else { HALF_SHORT };
540 let centre = self.centre + (self.prev_n + n) as i64 / 4;
541 let window_start = centre - (n / 2) as i64;
542 let buffer_start = window_start + PREROLL as i64;
543 if buffer_start < 0 || self.buffer[0].len() < buffer_start as usize + n {
544 break;
545 }
546 // A steady long block is typed by the hop *after* it; until that
547 // hop is buffered the plan just peeked was decided blind.
548 if !self.finished
549 && matches!(self.scheduler, Sched::Steady)
550 && self.buffer[0].len() < buffer_start as usize + n + BLOCK_LONG
551 {
552 break;
553 }
554 let granule = match self.finished {
555 true => centre.min(self.fed),
556 false => centre,
557 };
558 let data = self.encode_block(buffer_start as usize, n, half, plan, channels);
559 self.packets.push_back(EncodedPacket {
560 data,
561 granule,
562 samples: (granule - self.granule).max(0),
563 });
564 self.granule = granule;
565 self.centre = centre;
566 self.prev_n = n;
567 self.blocks_emitted += 1;
568 self.commit_plan(plan);
569 }
570 }
571
572 /// One block: analyse, quantise, write.
573 fn encode_block(
574 &mut self,
575 start: usize,
576 n: usize,
577 half: usize,
578 plan: BlockPlan,
579 channels: usize,
580 ) -> Vec<u8> {
581 let bc = if plan.is_long {
582 &self.long
583 } else {
584 &self.short
585 };
586 let partition = bc.partition;
587 let scale = 2.0 / half as f32;
588 let window = self
589 .windows
590 .get(plan.is_long, plan.prev_long, plan.next_long)
591 .to_vec();
592
593 let mut spectra: Vec<Vec<f32>> = Vec::with_capacity(channels);
594 let mut block = vec![0.0f32; n];
595 for channel in 0..channels {
596 block.copy_from_slice(&self.buffer[channel][start..start + n]);
597 let mut coefficients = vec![0.0f32; half];
598 let mdct = if plan.is_long {
599 &mut self.mdct_long
600 } else {
601 &mut self.mdct_short
602 };
603 mdct.forward_windowed(&block, &window, &mut coefficients);
604 for value in coefficients.iter_mut() {
605 *value *= scale;
606 }
607 spectra.push(coefficients);
608 }
609
610 // Floor per channel — one shared floor per coupled pair, so the two
611 // normalised spectra are on the same scale and the angle channel is
612 // small where the pair agrees. The floor is set per X point from the
613 // peak of the region that point owns, then drawn as straight lines
614 // between points: a peak at a region's edge can sit further under the
615 // curve than the range states and clamp. Such a block lifts the two
616 // points either side of every clamping bin by the excess and refits
617 // until nothing clamps, so the curve hugs the peaks the range is
618 // measured from.
619 let limit = CLASS_RANGE[CLASSES - 1];
620 // Blocks next to short windows bound pre-echo too: the transition-out
621 // long block still overlaps the samples just before the onset, so high
622 // bitrate transients get extra minimum precision.
623 let transient_headroom = if self.config.bitrate_bps >= 128_000 {
624 54.0
625 } else {
626 HEADROOM_SHORT_MIN
627 };
628 let headroom = match plan.is_long && plan.prev_long && plan.next_long {
629 true => self.headroom,
630 false => self.headroom.max(transient_headroom),
631 };
632 let mut lift: Vec<Vec<f64>> = vec![vec![1.0; bc.floor.x_list.len()]; channels];
633 // Per X point, the span of bins whose curve it has a hand in.
634 let spans: Vec<(usize, usize)> = bc
635 .floor
636 .x_list
637 .iter()
638 .map(|&x| {
639 let below = bc
640 .floor
641 .x_list
642 .iter()
643 .filter(|&&o| o < x)
644 .max()
645 .map_or(0, |&o| o as usize);
646 let above = bc
647 .floor
648 .x_list
649 .iter()
650 .filter(|&&o| o > x)
651 .min()
652 .map_or(half, |&o| o as usize);
653 (below, above)
654 })
655 .collect();
656 let mut passes = 0;
657 let steady = plan.is_long && plan.prev_long && plan.next_long;
658 let masking_offset = if !steady && self.config.bitrate_bps >= 128_000 {
659 0.0
660 } else {
661 MASKING_OFFSET_DB
662 };
663 let (floor_values, quantised) = loop {
664 let mut curves: Vec<Vec<f32>> = vec![Vec::new(); channels];
665 let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels];
666 let mut fit = |group: &[usize]| {
667 let group_spectra: Vec<&Vec<f32>> = group.iter().map(|&c| &spectra[c]).collect();
668 let mut peaks = peaks_of(&bc.floor, half, &group_spectra);
669 for &c in group {
670 for (peak, &boost) in peaks.iter_mut().zip(&lift[c]) {
671 *peak *= boost;
672 }
673 }
674 let (y, step2) = fit_floor(
675 &bc.floor,
676 &bc.ath,
677 &bc.bark,
678 headroom,
679 bc.range,
680 bc.co_mask,
681 masking_offset,
682 &peaks,
683 );
684 let mut curve = vec![0.0f32; half];
685 render_floor1(&bc.floor, &y, &step2, &mut curve);
686 for &c in group {
687 curves[c] = curve.clone();
688 floor_values[c] = y.clone();
689 }
690 };
691 let mut coded = vec![false; channels];
692 for &(magnitude, angle) in &self.coupling {
693 fit(&[magnitude, angle]);
694 coded[magnitude] = true;
695 coded[angle] = true;
696 }
697 for channel in (0..channels).filter(|&c| !coded[c]) {
698 fit(&[channel]);
699 }
700
701 // Normalise, couple, quantise. The floor is the masking threshold:
702 // bins that do not clear it are inaudible here and code as zero;
703 // bins that do clear it keep their full rounded residue, producing
704 // sparse small classes and larger tonal residues.
705 let mut quantised: Vec<Vec<i32>> = (0..channels)
706 .map(|channel| {
707 spectra[channel]
708 .iter()
709 .zip(curves[channel].iter())
710 .map(|(&value, &floor)| {
711 if floor <= 0.0 || value.abs() <= floor {
712 0
713 } else {
714 (value / floor).round() as i32
715 }
716 })
717 .collect::<Vec<i32>>()
718 })
719 .collect();
720 for channel in 0..channels {
721 for (band, values) in quantised[channel].chunks_mut(partition).enumerate() {
722 if values.iter().any(|&value| value != 0) {
723 continue;
724 }
725 let start = band * partition;
726 let end = (start + values.len()).min(half);
727 let mut peak = (NOISE_NORMALISE_MIN_RATIO, 0usize, 0i32);
728 for bin in start..end {
729 let floor = curves[channel][bin];
730 if floor <= 0.0 {
731 continue;
732 }
733 let value = spectra[channel][bin];
734 let ratio = value.abs() / floor;
735 if ratio > peak.0 {
736 peak = (ratio, bin - start, value.signum() as i32);
737 }
738 }
739 if peak.2 != 0 {
740 values[peak.1] = peak.2;
741 }
742 }
743 }
744 for &(magnitude, angle) in &self.coupling {
745 let mut left = std::mem::take(&mut quantised[magnitude]);
746 let mut right = std::mem::take(&mut quantised[angle]);
747 let cutoff = if self.config.bitrate_bps >= 128_000 {
748 6_000.0
749 } else {
750 POINT_STEREO_HZ
751 };
752 let point = match self.headroom < bc.range {
753 true => (cutoff / (f64::from(self.config.sample_rate) * 0.5) * half as f64)
754 as usize,
755 false => half,
756 };
757 for (bin, (l, r)) in left.iter_mut().zip(right.iter_mut()).enumerate() {
758 let (m, a) = couple(*l, *r);
759 *l = m;
760 *r = if bin < point {
761 a
762 } else {
763 let delta = (spectra[magnitude][bin] - spectra[angle][bin]).abs();
764 if delta > curves[magnitude][bin].max(curves[angle][bin]) {
765 a.signum()
766 } else {
767 0
768 }
769 };
770 }
771 quantised[magnitude] = left;
772 quantised[angle] = right;
773 }
774 let mut clamps = false;
775 for (channel, values) in quantised.iter().enumerate() {
776 for (bin, &value) in values.iter().enumerate() {
777 if value.abs() <= limit {
778 continue;
779 }
780 clamps = true;
781 let excess = f64::from(value.abs()) / f64::from(limit) * 1.05;
782 for (point, &(below, above)) in spans.iter().enumerate() {
783 if bin >= below && bin <= above {
784 lift[channel][point] = lift[channel][point].max(excess);
785 }
786 }
787 }
788 }
789 passes += 1;
790 // Eight lifts is 8 x 6 dB past anything a 42 dB range can leave over.
791 if !clamps || passes == 8 {
792 for channel in quantised.iter_mut() {
793 for value in channel.iter_mut() {
794 *value = (*value).clamp(-limit, limit);
795 }
796 }
797 break (floor_values, quantised);
798 }
799 };
800
801 let mut out = BitsOut::new();
802 out.bit(false);
803 let mode = if plan.is_long { MODE_LONG } else { MODE_SHORT };
804 out.write(mode, 1);
805 if plan.is_long {
806 out.bit(plan.prev_long);
807 out.bit(plan.next_long);
808 }
809 for values in floor_values.iter().take(channels) {
810 write_floor(&mut out, &bc.floor, &self.floor_book, values);
811 }
812 write_residue(
813 &mut out,
814 &quantised,
815 half,
816 partition,
817 &self.class_book,
818 &self.residue_books,
819 );
820 let bits = out.len();
821 let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre;
822 self.update_rate(bits, half, channels, delta);
823 out.finish()
824 }
825
826 /// Move the headroom so the running bitrate meets the target.
827 ///
828 /// One dB of headroom is about one sixth of a bit per coefficient, so the
829 /// step is the bit error divided by that — a proportional loop that settles
830 /// within a few blocks and is clamped either side so a transient cannot
831 /// swing the whole file. The target itself scales with this block's own
832 /// granule advance, so a short block (a small fraction of a long hop) is
833 /// judged against a proportionally small bit budget. The ceiling is well
834 /// past [`HEADROOM_RANGE`]: beyond it headroom buys bins under the
835 /// threshold rather than step, which is what quiet content needs.
836 fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) {
837 if self.config.bitrate_bps <= 0 || delta <= 0 {
838 return;
839 }
840 let target = f64::from(self.config.bitrate_bps) * RATE_TARGET_SCALE * delta as f64
841 / f64::from(self.config.sample_rate);
842 let coefficients = (half * channels) as f64;
843 let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0);
844 // Negative headroom is not a mistake: it puts the floor *above* the
845 // signal, which quantises the coefficients under it to zero and lets a
846 // whole partition become class 0 for two bits. Without that a low target
847 // cannot be reached at all — coding every coefficient with the shortest
848 // codeword there is already costs about a bit each.
849 self.headroom = (self.headroom + step).clamp(-24.0, 84.0);
850 }
851}
852
853/// Peak magnitude around each floor X point, over every channel given.
854///
855/// Each point owns the coefficients halfway to its neighbours either side, so
856/// the whole spectrum is covered exactly once and a peak between two points
857/// still raises the floor that has to carry it.
858fn peaks_of(floor: &Floor1, half: usize, spectra: &[&Vec<f32>]) -> Vec<f64> {
859 let x = &floor.x_list;
860 x.iter()
861 .map(|&centre| {
862 let below = x.iter().filter(|&&o| o < centre).max().copied();
863 let above = x.iter().filter(|&&o| o > centre).min().copied();
864 let lo = below.map_or(0, |b| ((b + centre) / 2) as usize);
865 let hi = above.map_or(half, |a| ((a + centre) / 2) as usize + 1);
866 let lo = lo.min(half - 1);
867 let hi = hi.clamp(lo + 1, half);
868 let mut peak = 0.0f64;
869 for spectrum in spectra {
870 for &value in &spectrum[lo..hi] {
871 peak = peak.max(f64::from(value.abs()));
872 }
873 }
874 peak
875 })
876 .collect()
877}
878
879/// Turn peak magnitudes into coded floor amplitudes.
880///
881/// Spread first (a masker covers its neighbours, with an extra Bark-local
882/// near-band pass), then subtract the rate loop's headroom, then hold the
883/// absolute threshold of hearing as a lower bound: below it the residue
884/// quantises to zero and costs a class-0 partition.
885fn fit_floor(
886 floor: &Floor1,
887 ath: &[f64],
888 bark: &[f64],
889 headroom: f64,
890 range: f64,
891 co_mask: f64,
892 masking_offset: f64,
893 peaks: &[f64],
894) -> (Vec<i32>, Vec<bool>) {
895 let db: Vec<f64> = peaks
896 .iter()
897 .map(|&peak| 20.0 * (peak.max(1e-9)).log10())
898 .collect();
899 let mut spread = db.clone();
900 let order = &floor.sorted;
901 for window in order.windows(2) {
902 let (previous, current) = (window[0], window[1]);
903 spread[current] = spread[current].max(spread[previous] - 12.0);
904 }
905 for window in order.windows(2).rev() {
906 let (current, next) = (window[0], window[1]);
907 spread[current] = spread[current].max(spread[next] - 24.0);
908 }
909 for (source, &level) in db.iter().enumerate() {
910 for (target, masked) in spread.iter_mut().enumerate() {
911 let distance = (bark[target] - bark[source]).abs();
912 if distance > 0.25 {
913 continue;
914 }
915 let slope = if bark[target] >= bark[source] {
916 48.0
917 } else {
918 80.0
919 };
920 *masked = (*masked).max(level - slope * distance);
921 }
922 }
923 let loudest = db.iter().copied().fold(f64::MIN, f64::max);
924 let target: Vec<f64> = spread
925 .iter()
926 .zip(ath.iter())
927 .map(|(&level, &threshold)| {
928 let threshold = threshold.max(loudest - co_mask);
929 let offset = (masking_offset - (headroom - range).max(0.0)).max(0.0);
930 (level - headroom.min(range) + offset)
931 .max(threshold - (headroom - range).max(0.0))
932 })
933 .collect();
934 let y: Vec<i32> = target
935 .iter()
936 .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255))
937 .collect();
938 fold_floor(floor, &y)
939}
940
941/// Run the decoder's own amplitude synthesis forwards, so the curve the
942/// encoder normalises against is the curve the decoder will draw.
943fn fold_floor(floor: &Floor1, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) {
944 let values = wanted.len();
945 let range = 256i32;
946 let mut final_y = vec![0i32; values];
947 let mut step2 = vec![false; values];
948 final_y[0] = wanted[0];
949 final_y[1] = wanted[1];
950 step2[0] = true;
951 step2[1] = true;
952 for i in 2..values {
953 let (low, high) = floor.neighbours[i];
954 let predicted = predict(
955 floor.x_list[low],
956 final_y[low],
957 floor.x_list[high],
958 final_y[high],
959 floor.x_list[i],
960 );
961 let value = fold(predicted, wanted[i], range);
962 if value != 0 {
963 step2[low] = true;
964 step2[high] = true;
965 step2[i] = true;
966 }
967 final_y[i] = wanted[i];
968 }
969 (final_y, step2)
970}
971
972/// Write one channel's floor: the two endpoints raw, the rest folded against
973/// their neighbours and Huffman coded.
974fn write_floor(out: &mut BitsOut, floor: &Floor1, floor_book: &CodebookSpec, y: &[i32]) {
975 out.bit(true);
976 out.write(y[0] as u32, 8);
977 out.write(y[1] as u32, 8);
978 for i in 2..y.len() {
979 let (low, high) = floor.neighbours[i];
980 let predicted = predict(
981 floor.x_list[low],
982 y[low],
983 floor.x_list[high],
984 y[high],
985 floor.x_list[i],
986 );
987 let value = fold(predicted, y[i], 256);
988 floor_book.write(out, value as usize);
989 }
990}
991
992/// Write the residue: one type-2 interleaved vector over every channel,
993/// classified per partition and coded in one pass.
994fn write_residue(
995 out: &mut BitsOut,
996 quantised: &[Vec<i32>],
997 half: usize,
998 partition: usize,
999 class_book: &CodebookSpec,
1000 residue_books: &[CodebookSpec],
1001) {
1002 let channels = quantised.len();
1003 let total = half * channels;
1004 let mut interleaved = vec![0i32; total];
1005 for (i, slot) in interleaved.iter_mut().enumerate() {
1006 *slot = quantised[i % channels][i / channels];
1007 }
1008 let partitions = total / partition;
1009 let classes: Vec<usize> = (0..partitions)
1010 .map(|p| {
1011 let slice = &interleaved[p * partition..(p + 1) * partition];
1012 let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0);
1013 CLASS_RANGE
1014 .iter()
1015 .position(|&range| peak <= range)
1016 .unwrap_or(CLASSES - 1)
1017 })
1018 .collect();
1019 let per_word = class_book.dimensions;
1020 let mut p = 0usize;
1021 while p < partitions {
1022 let mut word = 0usize;
1023 for i in 0..per_word {
1024 word = word * CLASSES + classes.get(p + i).copied().unwrap_or(0);
1025 }
1026 class_book.write(out, word);
1027 for _ in 0..per_word {
1028 if p >= partitions {
1029 break;
1030 }
1031 let class = classes[p];
1032 if class > 0 {
1033 let book = &residue_books[class - 1];
1034 let range = CLASS_RANGE[class];
1035 for chunk in interleaved[p * partition..(p + 1) * partition].chunks(book.dimensions)
1036 {
1037 book.write(out, residue_entry(chunk, range, book.dimensions));
1038 }
1039 }
1040 p += 1;
1041 }
1042 }
1043}
1044
1045/// Entry number for an exact vector value in one residue book.
1046fn residue_entry(values: &[i32], range: i32, dimensions: usize) -> usize {
1047 let base = (2 * range + 1) as usize;
1048 let mut entry = 0usize;
1049 let mut multiplier = 1usize;
1050 for i in 0..dimensions {
1051 let value = values.get(i).copied().unwrap_or(0).clamp(-range, range);
1052 entry += (value + range) as usize * multiplier;
1053 multiplier *= base;
1054 }
1055 entry
1056}
1057
1058/// Forward square-polar coupling (§9.4.2 run backwards).
1059fn couple(left: i32, right: i32) -> (i32, i32) {
1060 match left > 0 {
1061 true => match left > right {
1062 true => (left, left - right),
1063 false => (right, left - right),
1064 },
1065 false => match right > left {
1066 true => (left, right - left),
1067 false => (right, right - left),
1068 },
1069 }
1070}
1071
1072/// §7.2.2 `render_point`, which both sides of the floor coding need.
1073fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 {
1074 let dy = y1 - y0;
1075 let adx = (x1 - x0) as i32;
1076 let ady = dy.abs();
1077 let off = (ady * (x - x0) as i32) / adx;
1078 match dy < 0 {
1079 true => y0 - off,
1080 false => y0 + off,
1081 }
1082}
1083
1084/// The exact inverse of §7.2.3's amplitude synthesis: the value to code so the
1085/// decoder lands on `wanted`.
1086fn fold(predicted: i32, wanted: i32, range: i32) -> i32 {
1087 let high_room = range - predicted;
1088 let low_room = predicted;
1089 let room = high_room.min(low_room) * 2;
1090 let delta = wanted - predicted;
1091 if delta == 0 {
1092 return 0;
1093 }
1094 if delta > 0 && 2 * delta < room {
1095 return 2 * delta;
1096 }
1097 if delta < 0 && -2 * delta - 1 < room {
1098 return -2 * delta - 1;
1099 }
1100 match high_room > low_room {
1101 true => wanted - predicted + low_room,
1102 false => predicted - wanted + high_room - 1,
1103 }
1104}
1105
1106/// The floor-1 configuration for one block size: `half` coefficients, `points`
1107/// non-endpoint X values.
1108fn build_floor(half: usize, points: usize) -> Floor1 {
1109 let mut sorted_x: Vec<u32> = Vec::with_capacity(points);
1110 let mut last = 0u32;
1111 for i in 0..points {
1112 let t = i as f64 / (points - 1) as f64;
1113 // Log spacing over the band, nudged to stay strictly increasing at the
1114 // bottom where the grid is finer than one coefficient.
1115 let value = ((half - 1) as f64).powf(t).round() as u32;
1116 last = value.max(last + 1);
1117 sorted_x.push(last.min(half as u32 - 1));
1118 }
1119 // Coding order: endpoints first, then repeated bisection, so every value is
1120 // predicted from the two coded values that bracket it most closely.
1121 let mut x_list = vec![0u32, half as u32];
1122 let mut ranges = vec![(0usize, sorted_x.len())];
1123 while let Some((lo, hi)) = ranges.pop() {
1124 if lo >= hi {
1125 continue;
1126 }
1127 let mid = (lo + hi) / 2;
1128 x_list.push(sorted_x[mid]);
1129 ranges.insert(0, (lo, mid));
1130 ranges.insert(0, (mid + 1, hi));
1131 }
1132 let values = x_list.len();
1133 let mut sorted: Vec<usize> = (0..values).collect();
1134 sorted.sort_by_key(|&i| x_list[i]);
1135 let neighbours = (0..values)
1136 .map(|i| {
1137 let mut low = 0usize;
1138 let mut high = 0usize;
1139 let mut low_x = None;
1140 let mut high_x = None;
1141 for j in 0..i {
1142 if x_list[j] < x_list[i] && low_x.is_none_or(|b| x_list[j] > b) {
1143 low = j;
1144 low_x = Some(x_list[j]);
1145 }
1146 if x_list[j] > x_list[i] && high_x.is_none_or(|b| x_list[j] < b) {
1147 high = j;
1148 high_x = Some(x_list[j]);
1149 }
1150 }
1151 (low, high)
1152 })
1153 .collect();
1154 let partitions = (values - 2) / FLOOR_CLASS_DIM;
1155 Floor1 {
1156 partition_classes: vec![0; partitions],
1157 class_dimensions: vec![FLOOR_CLASS_DIM],
1158 class_subclasses: vec![0],
1159 class_masterbooks: vec![0],
1160 subclass_books: vec![vec![0]],
1161 multiplier: 1,
1162 x_list,
1163 sorted,
1164 neighbours,
1165 }
1166}
1167
1168/// Build one block size's floor, ATH curve and Bark positions.
1169fn build_block_config(
1170 half: usize,
1171 partition: usize,
1172 points: usize,
1173 range: f64,
1174 co_mask: f64,
1175 config: &EncoderConfig,
1176) -> BlockConfig {
1177 let floor = build_floor(half, points);
1178 let hz: Vec<f64> = floor
1179 .x_list
1180 .iter()
1181 .map(|&x| f64::from(config.sample_rate) * 0.5 * f64::from(x) / half as f64)
1182 .collect();
1183 let ath = hz.iter().map(|&hz| absolute_threshold(hz)).collect();
1184 let bark = hz.iter().map(|&hz| bark(hz)).collect();
1185 BlockConfig {
1186 half,
1187 partition,
1188 floor,
1189 ath,
1190 bark,
1191 range,
1192 co_mask,
1193 }
1194}
1195
1196/// Folded floor amplitudes: mostly small corrections, occasionally an escape
1197/// near the top of the range.
1198fn design_floor_book() -> CodebookSpec {
1199 let weights: Vec<f64> = (0..256)
1200 .map(|v| (-(f64::from(v)) / 7.0).exp() + 0.002)
1201 .collect();
1202 CodebookSpec::huffman(&weights, Vec::new())
1203}
1204
1205/// Class pairs, on the assumption that most partitions are silent.
1206fn design_class_book() -> CodebookSpec {
1207 // Measured on real music at 128 kbps: silent partitions are four in ten,
1208 // the three smallest ranges split most of the rest.
1209 let per_class = [0.40f64, 0.18, 0.19, 0.16, 0.05, 0.011, 0.008, 0.007, 0.001];
1210 let mut weights = Vec::with_capacity(CLASSES * CLASSES);
1211 for &first in &per_class {
1212 for &second in &per_class {
1213 weights.push(first * second);
1214 }
1215 }
1216 let mut spec = CodebookSpec::huffman(&weights, Vec::new());
1217 spec.dimensions = 2;
1218 spec
1219}
1220
1221/// One book per non-silent class. Small ranges use vector entries because
1222/// non-zero partitions still contain many zero coefficients; wider ranges stay
1223/// scalar to keep setup overhead below the bits they can save.
1224fn design_residue_books() -> Vec<CodebookSpec> {
1225 CLASS_RANGE[1..]
1226 .iter()
1227 .enumerate()
1228 .map(|(offset, &range)| {
1229 let class = offset + 1;
1230 let dimensions = RESIDUE_BOOK_DIM[class];
1231 let base = (2 * range + 1) as usize;
1232 let entries = base.pow(dimensions as u32);
1233 let sigma = f64::from(range).max(1.0);
1234 let mut weights = Vec::with_capacity(entries);
1235 let mut values = Vec::with_capacity(entries * dimensions);
1236 for entry in 0..entries {
1237 let mut nonzero = 0usize;
1238 let mut weight = 1.0f64;
1239 for position in 0..dimensions {
1240 let div = base.pow(position as u32);
1241 let value = (entry / div % base) as i32 - range;
1242 values.push(value as f32);
1243 if value == 0 {
1244 weight *= 0.60;
1245 } else {
1246 nonzero += 1;
1247 weight *= 0.40 * (-f64::from(value.abs()) / sigma).exp();
1248 }
1249 }
1250 let sparse = match nonzero {
1251 0 => 4.0,
1252 1 => 2.0,
1253 2 => 0.8,
1254 _ => 0.25,
1255 };
1256 weights.push(weight * sparse + 1e-8);
1257 }
1258 let mut spec = CodebookSpec::huffman(&weights, values);
1259 spec.dimensions = dimensions;
1260 spec
1261 })
1262 .collect()
1263}
1264
1265/// Absolute threshold of hearing in dBFS, full scale taken as 96 dB SPL.
1266///
1267/// Capped at -80 dBFS: the curve's own values at DC and above ~17 kHz
1268/// (-13 / -10 dBFS) are not a quantiser step the rest of a block can live
1269/// with — an onset inside a short block puts real energy in exactly those
1270/// bins, and coding them that coarsely leaked -38 dB of pre-echo across the
1271/// whole 256-sample window.
1272fn absolute_threshold(hz: f64) -> f64 {
1273 let khz = (hz / 1000.0).clamp(0.02, 20.0);
1274 let spl =
1275 3.64 * khz.powf(-0.8) - 6.5 * (-0.6 * (khz - 3.3).powi(2)).exp() + 0.001 * khz.powi(4);
1276 (spl - 96.0).clamp(-120.0, -80.0)
1277}
1278
1279/// Frequency in Barks, using the same compact psychoacoustic scale for every
1280/// sample rate.
1281fn bark(hz: f64) -> f64 {
1282 13.0 * (0.00076 * hz).atan() + 3.5 * ((hz / 7500.0) * (hz / 7500.0)).atan()
1283}
1284
1285struct HeaderSetup<'a> {
1286 long: &'a BlockConfig,
1287 short: &'a BlockConfig,
1288 floor_book: &'a CodebookSpec,
1289 class_book: &'a CodebookSpec,
1290 residue_books: &'a [CodebookSpec],
1291 coupling: &'a [(usize, usize)],
1292}
1293
1294/// The three header packets, in order.
1295fn write_headers(config: &EncoderConfig, channels: usize, setup: HeaderSetup<'_>) -> Vec<Vec<u8>> {
1296 let HeaderSetup {
1297 long,
1298 short,
1299 floor_book,
1300 class_book,
1301 residue_books,
1302 coupling,
1303 } = setup;
1304 let mut ident = vec![1u8];
1305 ident.extend_from_slice(b"vorbis");
1306 ident.extend_from_slice(&0u32.to_le_bytes());
1307 ident.push(channels as u8);
1308 ident.extend_from_slice(&config.sample_rate.to_le_bytes());
1309 ident.extend_from_slice(&0i32.to_le_bytes());
1310 ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes());
1311 ident.extend_from_slice(&0i32.to_le_bytes());
1312 let log2 = |n: usize| n.trailing_zeros() as u8;
1313 ident.push(log2(BLOCK_SHORT) | (log2(BLOCK_LONG) << 4));
1314 ident.push(1);
1315
1316 let mut comment = vec![3u8];
1317 comment.extend_from_slice(b"vorbis");
1318 let vendor = b"ec-vorbis";
1319 comment.extend_from_slice(&(vendor.len() as u32).to_le_bytes());
1320 comment.extend_from_slice(vendor);
1321 comment.extend_from_slice(&0u32.to_le_bytes());
1322 comment.push(1);
1323
1324 let mut out = BitsOut::new();
1325 for byte in [5u8].iter().chain(b"vorbis") {
1326 out.write(u32::from(*byte), 8);
1327 }
1328 let books: Vec<&CodebookSpec> = std::iter::once(floor_book)
1329 .chain(std::iter::once(class_book))
1330 .chain(residue_books.iter())
1331 .collect();
1332 out.write(books.len() as u32 - 1, 8);
1333 for book in &books {
1334 write_codebook(&mut out, book);
1335 }
1336 // One time-domain transform, stated as zero.
1337 out.write(0, 6);
1338 out.write(0, 16);
1339 // Two floors, type 1: long first, then short.
1340 out.write(1, 6);
1341 for bc in [long, short] {
1342 out.write(1, 16);
1343 out.write(bc.floor.partition_classes.len() as u32, 5);
1344 for _ in &bc.floor.partition_classes {
1345 out.write(0, 4);
1346 }
1347 out.write(FLOOR_CLASS_DIM as u32 - 1, 3);
1348 out.write(0, 2);
1349 out.write(1, 8);
1350 out.write(0, 2);
1351 let range_bits = ilog(bc.half as u32) - 1;
1352 out.write(range_bits, 4);
1353 for &x in bc.floor.x_list.iter().skip(2) {
1354 out.write(x, range_bits);
1355 }
1356 }
1357 // Two residues, type 2: long first, then short, each over every channel of
1358 // its own submap and sharing the class/residue books.
1359 out.write(1, 6);
1360 for bc in [long, short] {
1361 out.write(2, 16);
1362 out.write(0, 24);
1363 out.write((bc.half * channels) as u32, 24);
1364 out.write(bc.partition as u32 - 1, 24);
1365 out.write(CLASSES as u32 - 1, 6);
1366 out.write(1, 8);
1367 for class in 0..CLASSES {
1368 out.write(u32::from(class > 0), 3);
1369 out.write(0, 1);
1370 }
1371 for class in 1..CLASSES {
1372 out.write(class as u32 + 1, 8);
1373 }
1374 }
1375 // Two mappings, type 0: mapping 0 is long (floor/residue 0), mapping 1 is
1376 // short (floor/residue 1); both couple the same channels.
1377 out.write(1, 6);
1378 for (floor, residue) in [(0u32, 0u32), (1, 1)] {
1379 out.write(0, 16);
1380 out.write(0, 1);
1381 match coupling.is_empty() {
1382 true => out.write(0, 1),
1383 false => {
1384 out.write(1, 1);
1385 out.write(coupling.len() as u32 - 1, 8);
1386 let field = ilog(channels as u32 - 1);
1387 for &(magnitude, angle) in coupling {
1388 out.write(magnitude as u32, field);
1389 out.write(angle as u32, field);
1390 }
1391 }
1392 }
1393 out.write(0, 2);
1394 out.write(0, 8);
1395 out.write(floor, 8);
1396 out.write(residue, 8);
1397 }
1398 // Two modes: mode `MODE_SHORT` is a short block on mapping 1, mode
1399 // `MODE_LONG` a long block on mapping 0.
1400 out.write(1, 6);
1401 out.bit(false);
1402 out.write(0, 16);
1403 out.write(0, 16);
1404 out.write(1, 8);
1405 out.bit(true);
1406 out.write(0, 16);
1407 out.write(0, 16);
1408 out.write(0, 8);
1409 out.write(1, 1);
1410 let setup = out.finish();
1411
1412 vec![ident, comment, setup]
1413}
1414
1415/// One codebook in setup-header form: flat lengths and, when present, a type-1
1416/// lookup table carrying the scalar alphabet used by entry digits.
1417fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) {
1418 out.write(0x0056_4342, 24);
1419 out.write(book.dimensions as u32, 16);
1420 out.write(book.entries() as u32, 24);
1421 out.write(0, 1);
1422 out.write(0, 1);
1423 for &length in &book.lengths {
1424 out.write(u32::from(length) - 1, 5);
1425 }
1426 if book.values.is_empty() {
1427 out.write(0, 4);
1428 return;
1429 }
1430 out.write(1, 4);
1431 let minimum = book.values.iter().copied().fold(f32::INFINITY, f32::min);
1432 let maximum = book
1433 .values
1434 .iter()
1435 .copied()
1436 .fold(f32::NEG_INFINITY, f32::max);
1437 out.write(float32_pack(minimum), 32);
1438 out.write(float32_pack(1.0), 32);
1439 let lookup_values = lookup1_values(book.entries(), book.dimensions);
1440 let value_bits = ilog((maximum - minimum).round() as u32).max(1);
1441 out.write(value_bits - 1, 4);
1442 out.write(0, 1);
1443 for value in 0..lookup_values {
1444 out.write(value as u32, value_bits);
1445 }
1446}
1447
1448/// Xiph lacing of the three headers, the form containers carry them in.
1449fn lace(headers: &[Vec<u8>]) -> Vec<u8> {
1450 let mut out = vec![2u8];
1451 for header in headers.iter().take(headers.len() - 1) {
1452 let mut length = header.len();
1453 while length >= 255 {
1454 out.push(255);
1455 length -= 255;
1456 }
1457 out.push(length as u8);
1458 }
1459 for header in headers {
1460 out.extend_from_slice(header);
1461 }
1462 out
1463}
1464
1465impl Encoder for VorbisEncoder {
1466 fn codec_parameters(&self) -> &CodecParameters {
1467 &self.params
1468 }
1469
1470 fn send_frame(&mut self, frame: &Frame) -> Result<()> {
1471 let Frame::Audio(audio) = frame else {
1472 return Err(Error::corrupt("video frame pushed into an audio encoder"));
1473 };
1474 if audio.format != SampleFormat::F32 {
1475 return Err(Error::unsupported(
1476 format!("{:?} input", audio.format),
1477 "this encoder takes 32-bit float samples",
1478 ));
1479 }
1480 let channels = usize::from(self.config.channels);
1481 let mut planes: Vec<Vec<f32>> = vec![Vec::with_capacity(audio.samples); channels];
1482 match audio.planar {
1483 true => {
1484 for (channel, plane) in audio.data.iter().enumerate().take(channels) {
1485 planes[channel] = floats(plane, audio.samples);
1486 }
1487 }
1488 false => {
1489 let interleaved = floats(&audio.data[0], audio.samples * channels);
1490 for (i, value) in interleaved.into_iter().enumerate() {
1491 planes[i % channels].push(value);
1492 }
1493 }
1494 }
1495 let borrowed: Vec<&[f32]> = planes.iter().map(|p| &p[..]).collect();
1496 self.push_planar(&borrowed)
1497 }
1498
1499 fn receive_packet(&mut self) -> Result<Packet> {
1500 let encoded = self.next_packet()?;
1501 let base = TimeBase::new(1, i64::from(self.config.sample_rate));
1502 let mut packet = Packet::new(0, base, encoded.data);
1503 packet.pts = Some(encoded.granule - encoded.samples);
1504 packet.duration = Some(encoded.samples);
1505 Ok(packet)
1506 }
1507
1508 fn flush(&mut self) -> Result<()> {
1509 self.finish();
1510 Ok(())
1511 }
1512}
1513
1514/// Little-endian floats out of a plane.
1515fn floats(plane: &Buf, count: usize) -> Vec<f32> {
1516 plane
1517 .chunks_exact(4)
1518 .take(count)
1519 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
1520 .collect()
1521}
1522
1523#[cfg(test)]
1524mod tests {
1525 use super::*;
1526
1527 #[test]
1528 fn folding_is_the_exact_inverse_of_the_decoder() {
1529 // Every predicted/wanted pair in the range must survive the fold, or
1530 // the encoder and the decoder disagree about the floor.
1531 for predicted in [0i32, 1, 40, 128, 200, 255] {
1532 for wanted in 0..256i32 {
1533 let value = fold(predicted, wanted, 256);
1534 assert!((0..256).contains(&value), "{predicted}->{wanted}: {value}");
1535 assert_eq!(
1536 unfold(predicted, value, 256),
1537 wanted,
1538 "predicted {predicted}, wanted {wanted}, coded {value}"
1539 );
1540 }
1541 }
1542 }
1543
1544 /// §7.2.3 as the decoder runs it, for the test above to check against.
1545 fn unfold(predicted: i32, value: i32, range: i32) -> i32 {
1546 let high_room = range - predicted;
1547 let low_room = predicted;
1548 let room = high_room.min(low_room) * 2;
1549 if value == 0 {
1550 return predicted;
1551 }
1552 match value >= room {
1553 true => match high_room > low_room {
1554 true => value - low_room + predicted,
1555 false => predicted - value + high_room - 1,
1556 },
1557 false => match value & 1 == 1 {
1558 true => predicted - (value + 1) / 2,
1559 false => predicted + value / 2,
1560 },
1561 }
1562 }
1563
1564 #[test]
1565 fn vector_residue_books_address_exact_values() {
1566 let books = design_residue_books();
1567 assert_eq!(
1568 books.iter().map(|b| b.dimensions).collect::<Vec<_>>(),
1569 vec![4, 2, 2, 1, 1, 1, 1, 1]
1570 );
1571 for (class, book) in books.iter().enumerate().take(3) {
1572 let range = CLASS_RANGE[class + 1];
1573 let vector: Vec<i32> = (0..book.dimensions)
1574 .map(|i| if i % 2 == 0 { range } else { -range })
1575 .collect();
1576 let entry = residue_entry(&vector, range, book.dimensions);
1577 let start = entry * book.dimensions;
1578 let decoded: Vec<i32> = book.values[start..start + book.dimensions]
1579 .iter()
1580 .map(|&v| v as i32)
1581 .collect();
1582 assert_eq!(decoded, vector);
1583 }
1584 }
1585
1586 #[test]
1587 fn tail_granule_44100_mono() {
1588 let mut enc = VorbisEncoder::new(EncoderConfig {
1589 sample_rate: 44_100,
1590 channels: 2,
1591 bitrate_bps: -1,
1592 quality: 0.85,
1593 })
1594 .unwrap();
1595 let pcm = vec![0.1f32; 44_100 * 2];
1596 enc.push_interleaved(&pcm).unwrap();
1597 enc.finish();
1598 let mut last = 0i64;
1599 let mut n = 0;
1600 loop {
1601 match enc.next_packet() {
1602 Ok(p) => {
1603 last = p.granule;
1604 n += 1;
1605 }
1606 Err(Error::Eof) => break,
1607 Err(e) => panic!("{e}"),
1608 }
1609 }
1610 assert_eq!(n, 45, "packet count");
1611 assert_eq!(last, 44_100, "last granule");
1612 }
1613
1614 #[test]
1615 fn coupling_round_trips_every_sign_case() {
1616 for left in -8..=8i32 {
1617 for right in -8..=8i32 {
1618 let (m, a) = couple(left, right);
1619 let (back_l, back_r) = match (m > 0, a > 0) {
1620 (true, true) => (m, m - a),
1621 (true, false) => (m + a, m),
1622 (false, true) => (m, m + a),
1623 (false, false) => (m - a, m),
1624 };
1625 assert_eq!((back_l, back_r), (left, right), "{left},{right}");
1626 }
1627 }
1628 }
1629
1630 /// A stationary tone never trips the transient detector: every packet
1631 /// decodes to mode `MODE_LONG`.
1632 #[test]
1633 fn a_stationary_signal_uses_only_long_blocks() {
1634 let mut enc = VorbisEncoder::new(EncoderConfig {
1635 sample_rate: 48_000,
1636 channels: 2,
1637 bitrate_bps: -1,
1638 quality: 0.6,
1639 })
1640 .unwrap();
1641 let samples = 48_000usize;
1642 let mut pcm = vec![0.0f32; samples * 2];
1643 for i in 0..samples {
1644 let t = i as f32 / 48_000.0;
1645 let v = (2.0 * std::f32::consts::PI * 1_000.0 * t).sin() * 0.5;
1646 pcm[2 * i] = v;
1647 pcm[2 * i + 1] = v;
1648 }
1649 enc.push_interleaved(&pcm).unwrap();
1650 enc.finish();
1651 let mut modes = std::collections::HashSet::new();
1652 loop {
1653 match enc.next_packet() {
1654 Ok(p) => {
1655 let mut bits = crate::bits::Bits::new(&p.data);
1656 assert!(!bits.bit());
1657 modes.insert(bits.read(1));
1658 }
1659 Err(Error::Eof) => break,
1660 Err(e) => panic!("{e}"),
1661 }
1662 }
1663 assert_eq!(modes, std::collections::HashSet::from([MODE_LONG]));
1664 }
1665
1666 /// An onset after real silence trips the detector: some packet decodes to
1667 /// mode `MODE_SHORT`.
1668 #[test]
1669 fn an_onset_after_silence_uses_short_blocks() {
1670 let mut enc = VorbisEncoder::new(EncoderConfig {
1671 sample_rate: 44_100,
1672 channels: 2,
1673 bitrate_bps: -1,
1674 quality: 0.6,
1675 })
1676 .unwrap();
1677 let silence = 44_100usize;
1678 let tone = 4_410usize;
1679 let mut pcm = vec![0.0f32; (silence + tone) * 2];
1680 for i in 0..tone {
1681 let t = i as f32 / 44_100.0;
1682 let v = (2.0 * std::f32::consts::PI * 1_000.0 * t).sin();
1683 pcm[2 * (silence + i)] = v;
1684 pcm[2 * (silence + i) + 1] = v;
1685 }
1686 enc.push_interleaved(&pcm).unwrap();
1687 enc.finish();
1688 let mut saw_short = false;
1689 loop {
1690 match enc.next_packet() {
1691 Ok(p) => {
1692 let mut bits = crate::bits::Bits::new(&p.data);
1693 assert!(!bits.bit());
1694 if bits.read(1) == MODE_SHORT {
1695 saw_short = true;
1696 }
1697 }
1698 Err(Error::Eof) => break,
1699 Err(e) => panic!("{e}"),
1700 }
1701 }
1702 assert!(saw_short, "no short block coded around the onset");
1703 }
1704}