forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB070e7ebTahinli3 months ago374 commits

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