forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB34789daTahinli3 months ago1757 commits

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