forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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