forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'vorbis-short-blocks': Vorbis encoder block switching, pre-echo fix, rate tracking, residue/floor efficiency

Browse files at this commit

011ae0f4bfec0f0608ce6eda8288809c9ce0c674Ahmet Kaan GümüşParent: 3557679cc68682
crates/ec-vorbis/src/encode.rsmodified+816 -365
@@ -10,19 +10,34 @@
10 //! that comes out is the quantiser step: the residue is the spectrum divided by10 //! 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 is11 //! 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 tonality12 //! psychoacoustics-lite and it is stated as such — there is no tonality
13-//! estimate, no temporal pre-echo control and no per-band bit allocation beyond13+//! estimate beyond a two-mode block switch and no per-band bit allocation
14-//! what the floor implies.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.
15 //!27 //!
16 //! ## Codebooks28 //! ## Codebooks
17 //!29 //!
18 //! Designed here rather than inherited: a floor book over the folded amplitude30 //! Designed here rather than inherited: a floor book over the folded amplitude
19-//! range, a class book over partition-class pairs, and four residue books whose31+//! range, a class book over partition-class pairs, and eight residue books whose
20-//! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of32+//! 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
21 //! them are Huffman codes over stated distributions, built at construction and36 //! them are Huffman codes over stated distributions, built at construction and
22 //! written into every stream's own setup header — which is why this encoder37 //! written into every stream's own setup header — which is why this encoder
23-//! needs no embedded profile and has no channel count it cannot serve.38+//! needs no embedded profile and has no channel count it cannot serve. Both
24-39+//! block sizes share these books; only the floor's X grid and the residue's
25-use std::collections::VecDeque;40+//! partition size are sized per block.
26 41
27 use ec_core::{42 use ec_core::{
28 AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet,43 AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet,
@@ -35,29 +50,98 @@ use crate::codebook::{CodebookSpec, ilog};
35 use crate::decode::channel_map;50 use crate::decode::channel_map;
36 use crate::floor::render_floor1;51 use crate::floor::render_floor1;
37 use crate::setup::Floor1;52 use crate::setup::Floor1;
38-use crate::window;53+use crate::window::Windows;
39-54+
40-/// Long block size; this encoder codes long blocks only.55+/// Long block size.
41-const BLOCK: usize = 2048;56+const BLOCK_LONG: usize = 2048;
42-/// Samples between block centres.57+/// Short block size.
43-const HOP: usize = BLOCK / 2;58+const BLOCK_SHORT: usize = 256;
44-/// Coefficients per block.59+/// Coefficients in a long block.
45-const HALF: usize = BLOCK / 2;60+const HALF_LONG: usize = BLOCK_LONG / 2;
46-/// Coefficients per residue partition.61+/// Coefficients in a short block.
47-const PARTITION: usize = 32;62+const HALF_SHORT: usize = BLOCK_SHORT / 2;
48-/// Floor X points besides the two endpoints.63+/// Long-block coefficients per residue partition.
49-const FLOOR_POINTS: usize = 20;64+const PARTITION_LONG: usize = 16;
65+/// Short-block coefficients per residue partition.
66+const 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.
71+const FLOOR_POINTS_LONG: usize = 12;
72+/// Short floor X points besides the two endpoints.
73+const FLOOR_POINTS_SHORT: usize = 8;
50 /// Floor values per class.74 /// Floor values per class.
51 const FLOOR_CLASS_DIM: usize = 4;75 const FLOOR_CLASS_DIM: usize = 4;
52 /// Residue classes; class 0 codes nothing at all.76 /// Residue classes; class 0 codes nothing at all.
53-const CLASSES: usize = 5;77+const CLASSES: usize = 9;
54-/// Vorbis states spectral coefficients on the scale where a full-scale tone is
55-/// a coefficient of about one, which is what lets the floor table (whose top is
56-/// exactly 1.0) carry them. That is `2/N` times the unnormalised transform
57-/// ec-dsp computes, `N` being the coefficient count.
58-const VORBIS_MDCT_SCALE: f32 = 2.0 / HALF as f32;
59 /// Largest quantised residue each class's book can state.78 /// Largest quantised residue each class's book can state.
60-const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127];79+const CLASS_RANGE: [i32; CLASSES] = [0, 1, 2, 4, 8, 16, 32, 64, 127];
80+/// Headroom in dB the widest residue book can actually state: 20 log10 127
81+/// is 42, but a coupled angle channel is a difference of two magnitudes, so a
82+/// pair's step must leave half that range — 63, 36 dB. Past this the rate loop's extra headroom lowers the absolute-threshold
83+/// bound instead, so sparse or quiet content — where most partitions sit under
84+/// the threshold and code as class 0 whatever the step — gains bins to spend
85+/// bits on rather than a finer step nothing can represent.
86+const HEADROOM_RANGE: f64 = 36.0;
87+/// A short block's range: the full 42 dB. Its step is what sets the pre-echo
88+/// left inside the block that carries an onset, and 6 dB of it is the
89+/// difference between a leak twice the reference's and one under it.
90+/// Anything the wider range cannot state (a pair's angle, a peak at a floor
91+/// region's edge) is caught by the clamp refit in `encode_block`.
92+const HEADROOM_RANGE_SHORT: f64 = 42.0;
93+/// Nothing more than this many dB under a block's loudest floor point is
94+/// coded: a whole-spectrum co-masking cap. corner-cut: a flat cap is not a
95+/// spreading function — real masking falls off with distance in Barks, so
96+/// this drops a quiet treble part under a loud bass note that the ear would
97+/// still pick out. It is what buys real music its accuracy at this rate (on
98+/// three tracks at 128 kbps, 0.989 -> 0.995 correlation with the source);
99+/// the upgrade is a Bark-domain spread in `fit_floor` in place of the
100+/// per-point decay plus this cap. Swept 40 / 50 / 60 dB: 40 is better still
101+/// on the metric but too deaf to be honest.
102+const CO_MASK_RANGE: f64 = 50.0;
103+/// A short block gets no co-masking cap: a bin it drops is an error spread
104+/// across its whole window, the half before an onset included, and that is
105+/// the pre-echo the short block exists to prevent (44.1k mono, onset on the
106+/// grid: peak 0.0085 with the cap, under 0.007 without).
107+const CO_MASK_RANGE_SHORT: f64 = f64::INFINITY;
108+/// Above this frequency the coupled pair's angle is dropped and only the
109+/// magnitude coded (point stereo): the ear does not place HF detail by
110+/// inter-channel level difference finely enough to pay for coding it, and at
111+/// this rate the bits buy more accuracy in the magnitude. Below it the pair
112+/// is coded losslessly. Swept on real music at 128 kbps: 3-6 kHz are equal,
113+/// 10 kHz and no cutoff are worse.
114+const POINT_STEREO_HZ: f64 = 4_000.0;
115+/// Least headroom a short block is quantised with, whatever the rate loop's.
116+const HEADROOM_SHORT_MIN: f64 = 42.0;
117+/// Samples per transient-detection tick — the short block's own hop, so a
118+/// tick lines up with the finest time resolution the encoder has.
119+const TICK: usize = BLOCK_SHORT / 4;
120+/// Short blocks a detected transient inserts between the two transition long
121+/// blocks. Detection looks one long hop ahead of the transition-out
122+/// candidate, so the transient can land anywhere in that hop; the run is
123+/// sized to three long hops' worth of short-hop resolution (any `8 + 8k`
124+/// count keeps the steady-state grid aligned) so it comfortably straddles a
125+/// transient found anywhere in the hop being watched, not just at its start.
126+const SHORT_RUN: u8 = 16;
127+/// Mode index the setup header and every packet agree the short mode is.
128+const MODE_SHORT: u32 = 0;
129+/// Mode index the setup header and every packet agree the long mode is.
130+const MODE_LONG: u32 = 1;
131+/// A tick energy jump past this multiple of its predecessor is a transient;
132+/// a near-zero predecessor makes this trip on any onset above the floor.
133+const TRANSIENT_RATIO: f64 = 16.0;
134+/// Below this per-sample mean square (-60 dBFS), a tick is not "content" at
135+/// all — the floor that keeps digital silence, dither and fade tails from
136+/// tripping the detector.
137+const TRANSIENT_FLOOR: f64 = 1e-6;
138+/// Ticks before the candidate whose loudest one the jump is measured from.
139+const TRANSIENT_HISTORY: usize = 4;
140+
141+/// Buffer samples of left pre-roll before input sample 0 — one long half, so
142+/// even a block starting at the very front of the stream finds zeroes rather
143+/// than reading off the front of the buffer.
144+const PREROLL: usize = HALF_LONG;
61 145
62 /// How the encoder is set up.146 /// How the encoder is set up.
63 #[derive(Debug, Clone, Copy, PartialEq)]147 #[derive(Debug, Clone, Copy, PartialEq)]
@@ -95,6 +179,39 @@ pub struct EncodedPacket {
95 pub samples: i64,179 pub samples: i64,
96 }180 }
97 181
182+/// One block's shape: its mode and, for a long block, the window flags §4.3
183+/// states beside it.
184+#[derive(Debug, Clone, Copy)]
185+struct BlockPlan {
186+ is_long: bool,
187+ prev_long: bool,
188+ next_long: bool,
189+}
190+
191+/// The block-switch scheduler's state between calls.
192+#[derive(Debug, Clone, Copy)]
193+enum Sched {
194+ /// Long blocks, deciding fresh each time whether the next one is a
195+ /// transient's transition-out.
196+ Steady,
197+ /// Short blocks left to emit, counting this call down to zero.
198+ ShortRun(u8),
199+ /// The long block that resumes steady state after a short run.
200+ TransitionIn,
201+}
202+
203+/// A block size's own floor, codebook-sharing residue geometry and ATH.
204+struct BlockConfig {
205+ half: usize,
206+ partition: usize,
207+ floor: Floor1,
208+ ath: Vec<f64>,
209+ /// Headroom the residue range lets this block size state.
210+ range: f64,
211+ /// dB under the loudest floor point below which nothing is coded.
212+ co_mask: f64,
213+}
214+
98 /// Vorbis I encoder.215 /// Vorbis I encoder.
99 pub struct VorbisEncoder {216 pub struct VorbisEncoder {
100 config: EncoderConfig,217 config: EncoderConfig,
@@ -102,29 +219,36 @@ pub struct VorbisEncoder {
102 /// `to_vorbis[ec channel] = vorbis channel`.219 /// `to_vorbis[ec channel] = vorbis channel`.
103 to_vorbis: Vec<usize>,220 to_vorbis: Vec<usize>,
104 headers: Vec<Vec<u8>>,221 headers: Vec<Vec<u8>>,
105- floor: Floor1,222+ long: BlockConfig,
223+ short: BlockConfig,
106 floor_book: CodebookSpec,224 floor_book: CodebookSpec,
107 class_book: CodebookSpec,225 class_book: CodebookSpec,
108 residue_books: Vec<CodebookSpec>,226 residue_books: Vec<CodebookSpec>,
109- /// Absolute threshold of hearing per floor point, in dBFS.
110- ath: Vec<f64>,
111 /// Channel pairs coupled by the mapping; empty unless stereo.227 /// Channel pairs coupled by the mapping; empty unless stereo.
112 coupling: Vec<(usize, usize)>,228 coupling: Vec<(usize, usize)>,
113- mdct: Mdct<f32>,229+ mdct_long: Mdct<f32>,
114- window: Vec<f32>,230+ mdct_short: Mdct<f32>,
115- /// Per Vorbis channel, input samples with the first block's left half of231+ windows: Windows,
116- /// zeroes already in front.232+ /// Per Vorbis channel, input samples with [`PREROLL`] zeroes already in
233+ /// front.
117 buffer: Vec<Vec<f32>>,234 buffer: Vec<Vec<f32>>,
118 /// Input samples taken from the caller.235 /// Input samples taken from the caller.
119 fed: i64,236 fed: i64,
120 /// Blocks already emitted.237 /// Blocks already emitted.
121- blocks: i64,238+ blocks_emitted: i64,
239+ /// Centre of the block emitted last; the sentinel one long hop before
240+ /// sample 0, so the first real centre falls out of the same recurrence
241+ /// every later one uses.
242+ centre: i64,
243+ /// Blocksize of the block emitted last.
244+ prev_n: usize,
122 /// Granule of the packet emitted last.245 /// Granule of the packet emitted last.
123 granule: i64,246 granule: i64,
247+ scheduler: Sched,
124 /// Headroom under the masking curve, in dB — the rate loop's variable.248 /// Headroom under the masking curve, in dB — the rate loop's variable.
125 headroom: f64,249 headroom: f64,
126 finished: bool,250 finished: bool,
127- packets: VecDeque<EncodedPacket>,251+ packets: std::collections::VecDeque<EncodedPacket>,
128 }252 }
129 253
130 impl VorbisEncoder {254 impl VorbisEncoder {
@@ -152,23 +276,31 @@ impl VorbisEncoder {
152 _ => Vec::new(),276 _ => Vec::new(),
153 };277 };
154 278
155- let floor = build_floor();
156 let floor_book = design_floor_book();279 let floor_book = design_floor_book();
157 let class_book = design_class_book();280 let class_book = design_class_book();
158 let residue_books = design_residue_books();281 let residue_books = design_residue_books();
159- let ath = floor282+ let long = build_block_config(
160- .x_list283+ HALF_LONG,
161- .iter()284+ PARTITION_LONG,
162- .map(|&x| {285+ FLOOR_POINTS_LONG,
163- let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / HALF as f64;286+ HEADROOM_RANGE,
164- absolute_threshold(hz)287+ CO_MASK_RANGE,
165- })288+ &config,
166- .collect();289+ );
290+ let short = build_block_config(
291+ HALF_SHORT,
292+ PARTITION_SHORT,
293+ FLOOR_POINTS_SHORT,
294+ HEADROOM_RANGE_SHORT,
295+ CO_MASK_RANGE_SHORT,
296+ &config,
297+ );
167 298
168 let headers = write_headers(299 let headers = write_headers(
169 &config,300 &config,
170 channels,301 channels,
171- &floor,302+ &long,
303+ &short,
172 &floor_book,304 &floor_book,
173 &class_book,305 &class_book,
174 &residue_books,306 &residue_books,
@@ -187,26 +319,28 @@ impl VorbisEncoder {
187 319
188 let quality = f64::from(config.quality.clamp(0.0, 1.0));320 let quality = f64::from(config.quality.clamp(0.0, 1.0));
189 Ok(VorbisEncoder {321 Ok(VorbisEncoder {
190- mdct: Mdct::new(BLOCK),322+ mdct_long: Mdct::new(BLOCK_LONG),
191- window: window::build(BLOCK, BLOCK, true, true),323+ mdct_short: Mdct::new(BLOCK_SHORT),
192- // The first block is centred on input sample 0, so its left half is324+ windows: Windows::new(BLOCK_SHORT, BLOCK_LONG),
193- // the only pre-roll there is and the caller never sees it.325+ buffer: vec![vec![0.0; PREROLL]; channels],
194- buffer: vec![vec![0.0; HOP]; channels],
195 fed: 0,326 fed: 0,
196- blocks: 0,327+ blocks_emitted: 0,
328+ centre: -(HALF_LONG as i64),
329+ prev_n: BLOCK_LONG,
197 granule: 0,330 granule: 0,
331+ scheduler: Sched::Steady,
198 headroom: 4.0 + 26.0 * quality,332 headroom: 4.0 + 26.0 * quality,
199 finished: false,333 finished: false,
200- packets: VecDeque::new(),334+ packets: std::collections::VecDeque::new(),
201 config,335 config,
202 params,336 params,
203 to_vorbis,337 to_vorbis,
204 headers,338 headers,
205- floor,339+ long,
340+ short,
206 floor_book,341 floor_book,
207 class_book,342 class_book,
208 residue_books,343 residue_books,
209- ath,
210 coupling,344 coupling,
211 })345 })
212 }346 }
@@ -273,10 +407,11 @@ impl VorbisEncoder {
273 return;407 return;
274 }408 }
275 self.finished = true;409 self.finished = true;
276- // Enough blocks for every input sample to sit left of a block centre,410+ // Generous padding: a long block's own half plus a whole short-run's
277- // and enough padding for that last block to be whole.411+ // worth of slack, so whatever the scheduler is doing when the input
278- let last = ((self.fed + HOP as i64 - 1) / HOP as i64).max(1) as usize;412+ // runs out still finds real (zero) samples rather than the buffer's
279- let needed = last * HOP + BLOCK;413+ // edge.
414+ let needed = PREROLL + self.fed.max(0) as usize + 2 * BLOCK_LONG;
280 for channel in &mut self.buffer {415 for channel in &mut self.buffer {
281 if channel.len() < needed {416 if channel.len() < needed {
282 channel.resize(needed, 0.0);417 channel.resize(needed, 0.0);
@@ -294,285 +429,307 @@ impl VorbisEncoder {
294 }429 }
295 }430 }
296 431
432+ /// Decide the next block's shape without committing the scheduler state;
433+ /// used to check whether the data it needs is buffered yet.
434+ fn peek_plan(&self) -> BlockPlan {
435+ match self.scheduler {
436+ Sched::Steady => BlockPlan {
437+ is_long: true,
438+ prev_long: true,
439+ next_long: !self.transient_ahead(),
440+ },
441+ Sched::ShortRun(_) => BlockPlan {
442+ is_long: false,
443+ prev_long: true,
444+ next_long: true,
445+ },
446+ Sched::TransitionIn => BlockPlan {
447+ is_long: true,
448+ prev_long: false,
449+ next_long: true,
450+ },
451+ }
452+ }
453+
454+ /// Advance the scheduler past the plan [`peek_plan`] just returned.
455+ fn commit_plan(&mut self, plan: BlockPlan) {
456+ self.scheduler = match self.scheduler {
457+ Sched::Steady if !plan.next_long => Sched::ShortRun(SHORT_RUN),
458+ Sched::Steady => Sched::Steady,
459+ Sched::ShortRun(remaining) if remaining > 1 => Sched::ShortRun(remaining - 1),
460+ Sched::ShortRun(_) => Sched::TransitionIn,
461+ Sched::TransitionIn => Sched::Steady,
462+ };
463+ }
464+
465+ /// Whether the *next* steady long block's window carries a transient —
466+ /// checked one hop ahead of the block being decided now, so the block
467+ /// this call is about to type as transition-out still finishes its own
468+ /// carried region (up to a short hop past its centre) safely before the
469+ /// transient it is making room for. A tick's energy jumping past its
470+ /// predecessor's is exactly what an onset after digital silence looks
471+ /// like when the predecessor is zero.
472+ fn transient_ahead(&self) -> bool {
473+ // The very first block's "predecessor" is the encoder's own silent
474+ // pre-roll, not a real signal boundary; nothing to detect there.
475+ if self.centre == -(HALF_LONG as i64) {
476+ return false;
477+ }
478+ let candidate_centre = self.centre + (self.prev_n + BLOCK_LONG) as i64 / 4;
479+ let lookahead_centre = candidate_centre + BLOCK_LONG as i64 / 2;
480+ let window_start = lookahead_centre - HALF_LONG as i64;
481+ let buffer_start = window_start + PREROLL as i64;
482+ if buffer_start < 0 || self.buffer[0].len() < (buffer_start as usize) + BLOCK_LONG {
483+ return false;
484+ }
485+ let ticks = BLOCK_LONG / TICK;
486+ let energy = |t: usize| -> f64 {
487+ let start = buffer_start as usize + t * TICK;
488+ let mut sum = 0.0f64;
489+ for channel in &self.buffer {
490+ for &s in &channel[start..start + TICK] {
491+ sum += f64::from(s) * f64::from(s);
492+ }
493+ }
494+ sum
495+ };
496+ // Only the right half is new; its left neighbour was already the
497+ // right half the last time this block's window was checked.
498+ let floor = TRANSIENT_FLOOR * (TICK * self.buffer.len()) as f64;
499+ for t in ticks / 2..ticks {
500+ // Against the loudest of the few ticks before it, not just the
501+ // one: music rising over a few ticks is not a transient, a drum
502+ // hit or an onset after silence is.
503+ let previous = (t.saturating_sub(TRANSIENT_HISTORY)..t).map(energy).fold(0.0f64, f64::max);
504+ let current = energy(t);
505+ if current > floor && current > previous * TRANSIENT_RATIO {
506+ return true;
507+ }
508+ }
509+ false
510+ }
511+
297 /// Encode every block the buffer now holds whole.512 /// Encode every block the buffer now holds whole.
298- ///
299- /// Block `k` is centred on input sample `k * HOP`, and that centre is the
300- /// granule: the decoder's output reaches exactly there when the block's
301- /// window closes. The last block's granule is the input's own sample count
302- /// instead, which is what trims the grid's overshoot off the file.
303 fn encode_ready(&mut self) {513 fn encode_ready(&mut self) {
304 let channels = usize::from(self.config.channels);514 let channels = usize::from(self.config.channels);
305 loop {515 loop {
306- if self.finished && self.blocks > 0 && self.granule >= self.fed {516+ if self.finished && self.blocks_emitted > 0 && self.granule >= self.fed {
517+ break;
518+ }
519+ let plan = self.peek_plan();
520+ let n = if plan.is_long { BLOCK_LONG } else { BLOCK_SHORT };
521+ let half = if plan.is_long { HALF_LONG } else { HALF_SHORT };
522+ let centre = self.centre + (self.prev_n + n) as i64 / 4;
523+ let window_start = centre - (n / 2) as i64;
524+ let buffer_start = window_start + PREROLL as i64;
525+ if buffer_start < 0 || self.buffer[0].len() < buffer_start as usize + n {
307 break;526 break;
308 }527 }
309- let start = self.blocks as usize * HOP;528+ // A steady long block is typed by the hop *after* it; until that
310- if self.buffer[0].len() < start + BLOCK {529+ // hop is buffered the plan just peeked was decided blind.
530+ if !self.finished
531+ && matches!(self.scheduler, Sched::Steady)
532+ && self.buffer[0].len() < buffer_start as usize + n + BLOCK_LONG
533+ {
311 break;534 break;
312 }535 }
313- let centre = self.blocks * HOP as i64;
314 let granule = match self.finished {536 let granule = match self.finished {
315 true => centre.min(self.fed),537 true => centre.min(self.fed),
316 false => centre,538 false => centre,
317 };539 };
318- let data = self.encode_block(start, channels);540+ let data = self.encode_block(buffer_start as usize, n, half, plan, channels);
319 self.packets.push_back(EncodedPacket {541 self.packets.push_back(EncodedPacket {
320 data,542 data,
321 granule,543 granule,
322 samples: (granule - self.granule).max(0),544 samples: (granule - self.granule).max(0),
323 });545 });
324 self.granule = granule;546 self.granule = granule;
325- self.blocks += 1;547+ self.centre = centre;
548+ self.prev_n = n;
549+ self.blocks_emitted += 1;
550+ self.commit_plan(plan);
326 }551 }
327 }552 }
328 553
329 /// One block: analyse, quantise, write.554 /// One block: analyse, quantise, write.
330- fn encode_block(&mut self, start: usize, channels: usize) -> Vec<u8> {555+ fn encode_block(
556+ &mut self,
557+ start: usize,
558+ n: usize,
559+ half: usize,
560+ plan: BlockPlan,
561+ channels: usize,
562+ ) -> Vec<u8> {
563+ let bc = if plan.is_long { &self.long } else { &self.short };
564+ let partition = bc.partition;
565+ let scale = 2.0 / half as f32;
566+ let window = self
567+ .windows
568+ .get(plan.is_long, plan.prev_long, plan.next_long)
569+ .to_vec();
570+
331 let mut spectra: Vec<Vec<f32>> = Vec::with_capacity(channels);571 let mut spectra: Vec<Vec<f32>> = Vec::with_capacity(channels);
332- let mut block = vec![0.0f32; BLOCK];572+ let mut block = vec![0.0f32; n];
333 for channel in 0..channels {573 for channel in 0..channels {
334- block.copy_from_slice(&self.buffer[channel][start..start + BLOCK]);574+ block.copy_from_slice(&self.buffer[channel][start..start + n]);
335- let mut coefficients = vec![0.0f32; HALF];575+ let mut coefficients = vec![0.0f32; half];
336- self.mdct576+ let mdct = if plan.is_long { &mut self.mdct_long } else { &mut self.mdct_short };
337- .forward_windowed(&block, &self.window, &mut coefficients);577+ mdct.forward_windowed(&block, &window, &mut coefficients);
338 for value in coefficients.iter_mut() {578 for value in coefficients.iter_mut() {
339- *value *= VORBIS_MDCT_SCALE;579+ *value *= scale;
340 }580 }
341 spectra.push(coefficients);581 spectra.push(coefficients);
342 }582 }
343 583
344 // Floor per channel — one shared floor per coupled pair, so the two584 // Floor per channel — one shared floor per coupled pair, so the two
345 // normalised spectra are on the same scale and the angle channel is585 // normalised spectra are on the same scale and the angle channel is
346- // small where the pair agrees.586+ // small where the pair agrees. The floor is set per X point from the
347- let mut curves: Vec<Vec<f32>> = vec![Vec::new(); channels];587+ // peak of the region that point owns, then drawn as straight lines
348- let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels];588+ // between points: a peak at a region's edge can sit further under the
349- let mut coded = vec![false; channels];589+ // curve than the range states and clamp. Such a block lifts the two
350- for &(magnitude, angle) in &self.coupling {590+ // points either side of every clamping bin by the excess and refits
351- let peaks = self.peaks_of(&[&spectra[magnitude], &spectra[angle]]);591+ // until nothing clamps, so the curve hugs the peaks the range is
352- let (y, step2) = self.fit_floor(&peaks);592+ // measured from.
353- let mut curve = vec![0.0f32; HALF];593+ let limit = CLASS_RANGE[CLASSES - 1];
354- render_floor1(&self.floor, &y, &step2, &mut curve);594+ // A short block's precision is what bounds the pre-echo inside the
355- curves[magnitude] = curve.clone();595+ // window that carries an onset, so it does not inherit whatever
356- curves[angle] = curve;596+ // headroom the music before it left the rate loop at: at 6 ch / 96 kHz
357- floor_values[magnitude] = y.clone();597+ // the loop sat at 22 dB when the onset came and leaked -36 dB across
358- floor_values[angle] = y;598+ // the half-window before it. A short run is 16 blocks once a second
359- coded[magnitude] = true;599+ // or so on music, so the extra bits are noise to the loop.
360- coded[angle] = true;600+ let headroom = match plan.is_long {
361- }601+ true => self.headroom,
362- for channel in 0..channels {602+ false => self.headroom.max(HEADROOM_SHORT_MIN),
363- if coded[channel] {603+ };
364- continue;604+ let mut lift: Vec<Vec<f64>> = vec![vec![1.0; bc.floor.x_list.len()]; channels];
365- }605+ // Per X point, the span of bins whose curve it has a hand in.
366- let peaks = self.peaks_of(&[&spectra[channel]]);606+ let spans: Vec<(usize, usize)> = bc
367- let (y, step2) = self.fit_floor(&peaks);607+ .floor
368- let mut curve = vec![0.0f32; HALF];608+ .x_list
369- render_floor1(&self.floor, &y, &step2, &mut curve);609+ .iter()
370- curves[channel] = curve;610+ .map(|&x| {
371- floor_values[channel] = y;611+ let below = bc
372- }612+ .floor
373-613+ .x_list
374- // Normalise, couple, quantise.
375- let mut quantised: Vec<Vec<i32>> = (0..channels)
376- .map(|channel| {
377- spectra[channel]
378 .iter()614 .iter()
379- .zip(curves[channel].iter())615+ .filter(|&&o| o < x)
380- .map(|(&value, &floor)| match floor > 0.0 {616+ .max()
381- true => value / floor,617+ .map_or(0, |&o| o as usize);
382- false => 0.0,618+ let above = bc
383- })619+ .floor
384- .map(|normalised| normalised.round() as i32)620+ .x_list
385- .collect::<Vec<i32>>()621+ .iter()
622+ .filter(|&&o| o > x)
623+ .min()
624+ .map_or(half, |&o| o as usize);
625+ (below, above)
386 })626 })
387 .collect();627 .collect();
388- for &(magnitude, angle) in &self.coupling {628+ let mut passes = 0;
389- // Taken out and put back so the pair can be walked in step; a629+ let (floor_values, quantised) = loop {
390- // coupling step never names one channel twice.630+ let mut curves: Vec<Vec<f32>> = vec![Vec::new(); channels];
391- let mut left = std::mem::take(&mut quantised[magnitude]);631+ let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels];
392- let mut right = std::mem::take(&mut quantised[angle]);632+ let mut fit = |group: &[usize]| {
393- for (l, r) in left.iter_mut().zip(right.iter_mut()) {633+ let group_spectra: Vec<&Vec<f32>> = group.iter().map(|&c| &spectra[c]).collect();
394- let (m, a) = couple(*l, *r);634+ let mut peaks = peaks_of(&bc.floor, half, &group_spectra);
395- *l = m;635+ for &c in group {
396- *r = a;636+ for (peak, &boost) in peaks.iter_mut().zip(&lift[c]) {
397- }637+ *peak *= boost;
398- quantised[magnitude] = left;
399- quantised[angle] = right;
400- }
401- let limit = CLASS_RANGE[CLASSES - 1];
402- for channel in quantised.iter_mut() {
403- for value in channel.iter_mut() {
404- *value = (*value).clamp(-limit, limit);
405- }
406- }
407-
408- let mut out = BitsOut::new();
409- out.write(0, 1);
410- // One mode means `ilog(modes - 1)` is zero bits: there is nothing to
411- // state. The two window flags follow because the mode is a long block.
412- out.bit(true);
413- out.bit(true);
414- for values in floor_values.iter().take(channels) {
415- self.write_floor(&mut out, values);
416- }
417- self.write_residue(&mut out, &quantised);
418- let bits = out.len();
419- self.update_rate(bits, channels);
420- out.finish()
421- }
422-
423- /// Peak magnitude around each floor X point, over every channel given.
424- ///
425- /// Each point owns the coefficients halfway to its neighbours either side,
426- /// so the whole spectrum is covered exactly once and a peak between two
427- /// points still raises the floor that has to carry it.
428- fn peaks_of(&self, spectra: &[&Vec<f32>]) -> Vec<f64> {
429- let x = &self.floor.x_list;
430- x.iter()
431- .map(|&centre| {
432- let below = x.iter().filter(|&&o| o < centre).max().copied();
433- let above = x.iter().filter(|&&o| o > centre).min().copied();
434- let lo = below.map_or(0, |b| ((b + centre) / 2) as usize);
435- let hi = above.map_or(HALF, |a| ((a + centre) / 2) as usize + 1);
436- let lo = lo.min(HALF - 1);
437- let hi = hi.clamp(lo + 1, HALF);
438- let mut peak = 0.0f64;
439- for spectrum in spectra {
440- for &value in &spectrum[lo..hi] {
441- peak = peak.max(f64::from(value.abs()));
442 }638 }
443 }639 }
444- peak640+ let (y, step2) = fit_floor(&bc.floor, &bc.ath, headroom, bc.range, bc.co_mask, &peaks);
445- })641+ let mut curve = vec![0.0f32; half];
446- .collect()642+ render_floor1(&bc.floor, &y, &step2, &mut curve);
447- }643+ for &c in group {
448-644+ curves[c] = curve.clone();
449- /// Turn peak magnitudes into coded floor amplitudes.645+ floor_values[c] = y.clone();
450- ///646+ }
451- /// Spread first (a masker covers its neighbours), then subtract the rate647+ };
452- /// loop's headroom, then hold the absolute threshold of hearing as a lower648+ let mut coded = vec![false; channels];
453- /// bound: below it the residue quantises to zero and costs a class-0649+ for &(magnitude, angle) in &self.coupling {
454- /// partition.650+ fit(&[magnitude, angle]);
455- fn fit_floor(&self, peaks: &[f64]) -> (Vec<i32>, Vec<bool>) {651+ coded[magnitude] = true;
456- let mut db: Vec<f64> = peaks652+ coded[angle] = true;
457- .iter()653+ }
458- .map(|&peak| 20.0 * (peak.max(1e-9)).log10())654+ for channel in (0..channels).filter(|&c| !coded[c]) {
459- .collect();655+ fit(&[channel]);
460- // Frequency order, not coding order: spreading is a fact about the ear.
461- let order = &self.floor.sorted;
462- for window in order.windows(2) {
463- let (previous, current) = (window[0], window[1]);
464- db[current] = db[current].max(db[previous] - 12.0);
465- }
466- for window in order.windows(2).rev() {
467- let (current, next) = (window[0], window[1]);
468- db[current] = db[current].max(db[next] - 24.0);
469- }
470- let target: Vec<f64> = db
471- .iter()
472- .zip(self.ath.iter())
473- .map(|(&level, &threshold)| (level - self.headroom).max(threshold))
474- .collect();
475- let y: Vec<i32> = target
476- .iter()
477- .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255))
478- .collect();
479- self.fold_floor(&y)
480- }
481-
482- /// Run the decoder's own amplitude synthesis forwards, so the curve the
483- /// encoder normalises against is the curve the decoder will draw.
484- fn fold_floor(&self, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) {
485- let values = wanted.len();
486- let range = 256i32;
487- let mut final_y = vec![0i32; values];
488- let mut step2 = vec![false; values];
489- final_y[0] = wanted[0];
490- final_y[1] = wanted[1];
491- step2[0] = true;
492- step2[1] = true;
493- for i in 2..values {
494- let (low, high) = self.floor.neighbours[i];
495- let predicted = predict(
496- self.floor.x_list[low],
497- final_y[low],
498- self.floor.x_list[high],
499- final_y[high],
500- self.floor.x_list[i],
501- );
502- let value = fold(predicted, wanted[i], range);
503- if value != 0 {
504- step2[low] = true;
505- step2[high] = true;
506- step2[i] = true;
507 }656 }
508- final_y[i] = wanted[i];
509- }
510- (final_y, step2)
511- }
512-
513- /// Write one channel's floor: the two endpoints raw, the rest folded
514- /// against their neighbours and Huffman coded.
515- fn write_floor(&self, out: &mut BitsOut, y: &[i32]) {
516- out.bit(true);
517- out.write(y[0] as u32, 8);
518- out.write(y[1] as u32, 8);
519- for i in 2..y.len() {
520- let (low, high) = self.floor.neighbours[i];
521- let predicted = predict(
522- self.floor.x_list[low],
523- y[low],
524- self.floor.x_list[high],
525- y[high],
526- self.floor.x_list[i],
527- );
528- let value = fold(predicted, y[i], 256);
529- self.floor_book.write(out, value as usize);
530- }
531- }
532 657
533- /// Write the residue: one type-2 interleaved vector over every channel,658+ // Normalise, couple, quantise.
534- /// classified per partition and coded in one pass.659+ let mut quantised: Vec<Vec<i32>> = (0..channels)
535- fn write_residue(&self, out: &mut BitsOut, quantised: &[Vec<i32>]) {660+ .map(|channel| {
536- let channels = quantised.len();661+ spectra[channel]
537- let total = HALF * channels;662+ .iter()
538- let mut interleaved = vec![0i32; total];663+ .zip(curves[channel].iter())
539- for (i, slot) in interleaved.iter_mut().enumerate() {664+ .map(|(&value, &floor)| match floor > 0.0 {
540- *slot = quantised[i % channels][i / channels];665+ true => value / floor,
541- }666+ false => 0.0,
542- let partitions = total / PARTITION;667+ })
543- let classes: Vec<usize> = (0..partitions)668+ .map(|normalised| normalised.round() as i32)
544- .map(|partition| {669+ .collect::<Vec<i32>>()
545- let slice = &interleaved[partition * PARTITION..(partition + 1) * PARTITION];670+ })
546- let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0);671+ .collect();
547- CLASS_RANGE672+ for &(magnitude, angle) in &self.coupling {
548- .iter()673+ let mut left = std::mem::take(&mut quantised[magnitude]);
549- .position(|&range| peak <= range)674+ let mut right = std::mem::take(&mut quantised[angle]);
550- .unwrap_or(CLASSES - 1)675+ // Only while bits are scarce: headroom at the range is the
551- })676+ // rate loop saying the step cannot get finer, so the budget
552- .collect();677+ // is better spent stating the angle than left unspent.
553- let per_word = self.class_book.dimensions;678+ let point = match self.headroom < bc.range {
554- let mut partition = 0usize;679+ true => (POINT_STEREO_HZ / (f64::from(self.config.sample_rate) * 0.5) * half as f64) as usize,
555- while partition < partitions {680+ false => half,
556- let mut word = 0usize;681+ };
557- for i in 0..per_word {682+ for (bin, (l, r)) in left.iter_mut().zip(right.iter_mut()).enumerate() {
558- word = word * CLASSES + classes.get(partition + i).copied().unwrap_or(0);683+ let (m, a) = couple(*l, *r);
684+ *l = m;
685+ *r = if bin >= point { 0 } else { a };
686+ }
687+ quantised[magnitude] = left;
688+ quantised[angle] = right;
559 }689 }
560- self.class_book.write(out, word);690+ let mut clamps = false;
561- for _ in 0..per_word {691+ for (channel, values) in quantised.iter().enumerate() {
562- if partition >= partitions {692+ for (bin, &value) in values.iter().enumerate() {
563- break;693+ if value.abs() <= limit {
694+ continue;
695+ }
696+ clamps = true;
697+ let excess = f64::from(value.abs()) / f64::from(limit) * 1.05;
698+ for (point, &(below, above)) in spans.iter().enumerate() {
699+ if bin >= below && bin <= above {
700+ lift[channel][point] = lift[channel][point].max(excess);
701+ }
702+ }
564 }703 }
565- let class = classes[partition];704+ }
566- if class > 0 {705+ passes += 1;
567- let book = &self.residue_books[class - 1];706+ // Eight lifts is 8 x 6 dB past anything a 42 dB range can leave over.
568- let range = CLASS_RANGE[class];707+ if !clamps || passes == 8 {
569- for &value in &interleaved[partition * PARTITION..(partition + 1) * PARTITION] {708+ for channel in quantised.iter_mut() {
570- book.write(out, (value.clamp(-range, range) + range) as usize);709+ for value in channel.iter_mut() {
710+ *value = (*value).clamp(-limit, limit);
571 }711 }
572 }712 }
573- partition += 1;713+ break (floor_values, quantised);
574 }714 }
715+ };
716+
717+ let mut out = BitsOut::new();
718+ out.bit(false);
719+ let mode = if plan.is_long { MODE_LONG } else { MODE_SHORT };
720+ out.write(mode, 1);
721+ if plan.is_long {
722+ out.bit(plan.prev_long);
723+ out.bit(plan.next_long);
724+ }
725+ for values in floor_values.iter().take(channels) {
726+ write_floor(&mut out, &bc.floor, &self.floor_book, values);
575 }727 }
728+ write_residue(&mut out, &quantised, half, partition, &self.class_book, &self.residue_books);
729+ let bits = out.len();
730+ let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre;
731+ self.update_rate(bits, half, channels, delta);
732+ out.finish()
576 }733 }
577 734
578 /// Move the headroom so the running bitrate meets the target.735 /// Move the headroom so the running bitrate meets the target.
@@ -580,21 +737,196 @@ impl VorbisEncoder {
580 /// One dB of headroom is about one sixth of a bit per coefficient, so the737 /// One dB of headroom is about one sixth of a bit per coefficient, so the
581 /// step is the bit error divided by that — a proportional loop that settles738 /// step is the bit error divided by that — a proportional loop that settles
582 /// within a few blocks and is clamped either side so a transient cannot739 /// within a few blocks and is clamped either side so a transient cannot
583- /// swing the whole file.740+ /// swing the whole file. The target itself scales with this block's own
584- fn update_rate(&mut self, bits: u64, channels: usize) {741+ /// granule advance, so a short block (a small fraction of a long hop) is
585- if self.config.bitrate_bps <= 0 {742+ /// judged against a proportionally small bit budget. The ceiling is well
743+ /// past [`HEADROOM_RANGE`]: beyond it headroom buys bins under the
744+ /// threshold rather than step, which is what quiet content needs.
745+ fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) {
746+ if self.config.bitrate_bps <= 0 || delta <= 0 {
586 return;747 return;
587 }748 }
588- let target =749+ let target = f64::from(self.config.bitrate_bps) * delta as f64 / f64::from(self.config.sample_rate);
589- f64::from(self.config.bitrate_bps) * HOP as f64 / f64::from(self.config.sample_rate);750+ let coefficients = (half * channels) as f64;
590- let coefficients = (HALF * channels) as f64;
591 let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0);751 let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0);
592 // Negative headroom is not a mistake: it puts the floor *above* the752 // Negative headroom is not a mistake: it puts the floor *above* the
593 // signal, which quantises the coefficients under it to zero and lets a753 // signal, which quantises the coefficients under it to zero and lets a
594 // whole partition become class 0 for two bits. Without that a low target754 // whole partition become class 0 for two bits. Without that a low target
595 // cannot be reached at all — coding every coefficient with the shortest755 // cannot be reached at all — coding every coefficient with the shortest
596 // codeword there is already costs about a bit each.756 // codeword there is already costs about a bit each.
597- self.headroom = (self.headroom + step).clamp(-24.0, 36.0);757+ self.headroom = (self.headroom + step).clamp(-24.0, 84.0);
758+ }
759+}
760+
761+/// Peak magnitude around each floor X point, over every channel given.
762+///
763+/// Each point owns the coefficients halfway to its neighbours either side, so
764+/// the whole spectrum is covered exactly once and a peak between two points
765+/// still raises the floor that has to carry it.
766+fn peaks_of(floor: &Floor1, half: usize, spectra: &[&Vec<f32>]) -> Vec<f64> {
767+ let x = &floor.x_list;
768+ x.iter()
769+ .map(|&centre| {
770+ let below = x.iter().filter(|&&o| o < centre).max().copied();
771+ let above = x.iter().filter(|&&o| o > centre).min().copied();
772+ let lo = below.map_or(0, |b| ((b + centre) / 2) as usize);
773+ let hi = above.map_or(half, |a| ((a + centre) / 2) as usize + 1);
774+ let lo = lo.min(half - 1);
775+ let hi = hi.clamp(lo + 1, half);
776+ let mut peak = 0.0f64;
777+ for spectrum in spectra {
778+ for &value in &spectrum[lo..hi] {
779+ peak = peak.max(f64::from(value.abs()));
780+ }
781+ }
782+ peak
783+ })
784+ .collect()
785+}
786+
787+/// Turn peak magnitudes into coded floor amplitudes.
788+///
789+/// Spread first (a masker covers its neighbours), then subtract the rate
790+/// loop's headroom, then hold the absolute threshold of hearing as a lower
791+/// bound: below it the residue quantises to zero and costs a class-0
792+/// partition.
793+fn fit_floor(
794+ floor: &Floor1,
795+ ath: &[f64],
796+ headroom: f64,
797+ range: f64,
798+ co_mask: f64,
799+ peaks: &[f64],
800+) -> (Vec<i32>, Vec<bool>) {
801+ let mut db: Vec<f64> = peaks
802+ .iter()
803+ .map(|&peak| 20.0 * (peak.max(1e-9)).log10())
804+ .collect();
805+ let order = &floor.sorted;
806+ for window in order.windows(2) {
807+ let (previous, current) = (window[0], window[1]);
808+ db[current] = db[current].max(db[previous] - 12.0);
809+ }
810+ for window in order.windows(2).rev() {
811+ let (current, next) = (window[0], window[1]);
812+ db[current] = db[current].max(db[next] - 24.0);
813+ }
814+ let loudest = db.iter().copied().fold(f64::MIN, f64::max);
815+ let target: Vec<f64> = db
816+ .iter()
817+ .zip(ath.iter())
818+ .map(|(&level, &threshold)| {
819+ let threshold = threshold.max(loudest - co_mask);
820+ (level - headroom.min(range)).max(threshold - (headroom - range).max(0.0))
821+ })
822+ .collect();
823+ let y: Vec<i32> = target
824+ .iter()
825+ .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255))
826+ .collect();
827+ fold_floor(floor, &y)
828+}
829+
830+/// Run the decoder's own amplitude synthesis forwards, so the curve the
831+/// encoder normalises against is the curve the decoder will draw.
832+fn fold_floor(floor: &Floor1, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) {
833+ let values = wanted.len();
834+ let range = 256i32;
835+ let mut final_y = vec![0i32; values];
836+ let mut step2 = vec![false; values];
837+ final_y[0] = wanted[0];
838+ final_y[1] = wanted[1];
839+ step2[0] = true;
840+ step2[1] = true;
841+ for i in 2..values {
842+ let (low, high) = floor.neighbours[i];
843+ let predicted = predict(
844+ floor.x_list[low],
845+ final_y[low],
846+ floor.x_list[high],
847+ final_y[high],
848+ floor.x_list[i],
849+ );
850+ let value = fold(predicted, wanted[i], range);
851+ if value != 0 {
852+ step2[low] = true;
853+ step2[high] = true;
854+ step2[i] = true;
855+ }
856+ final_y[i] = wanted[i];
857+ }
858+ (final_y, step2)
859+}
860+
861+/// Write one channel's floor: the two endpoints raw, the rest folded against
862+/// their neighbours and Huffman coded.
863+fn write_floor(out: &mut BitsOut, floor: &Floor1, floor_book: &CodebookSpec, y: &[i32]) {
864+ out.bit(true);
865+ out.write(y[0] as u32, 8);
866+ out.write(y[1] as u32, 8);
867+ for i in 2..y.len() {
868+ let (low, high) = floor.neighbours[i];
869+ let predicted = predict(
870+ floor.x_list[low],
871+ y[low],
872+ floor.x_list[high],
873+ y[high],
874+ floor.x_list[i],
875+ );
876+ let value = fold(predicted, y[i], 256);
877+ floor_book.write(out, value as usize);
878+ }
879+}
880+
881+/// Write the residue: one type-2 interleaved vector over every channel,
882+/// classified per partition and coded in one pass.
883+fn write_residue(
884+ out: &mut BitsOut,
885+ quantised: &[Vec<i32>],
886+ half: usize,
887+ partition: usize,
888+ class_book: &CodebookSpec,
889+ residue_books: &[CodebookSpec],
890+) {
891+ let channels = quantised.len();
892+ let total = half * channels;
893+ let mut interleaved = vec![0i32; total];
894+ for (i, slot) in interleaved.iter_mut().enumerate() {
895+ *slot = quantised[i % channels][i / channels];
896+ }
897+ let partitions = total / partition;
898+ let classes: Vec<usize> = (0..partitions)
899+ .map(|p| {
900+ let slice = &interleaved[p * partition..(p + 1) * partition];
901+ let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0);
902+ CLASS_RANGE
903+ .iter()
904+ .position(|&range| peak <= range)
905+ .unwrap_or(CLASSES - 1)
906+ })
907+ .collect();
908+ let per_word = class_book.dimensions;
909+ let mut p = 0usize;
910+ while p < partitions {
911+ let mut word = 0usize;
912+ for i in 0..per_word {
913+ word = word * CLASSES + classes.get(p + i).copied().unwrap_or(0);
914+ }
915+ class_book.write(out, word);
916+ for _ in 0..per_word {
917+ if p >= partitions {
918+ break;
919+ }
920+ let class = classes[p];
921+ if class > 0 {
922+ let book = &residue_books[class - 1];
923+ let range = CLASS_RANGE[class];
924+ for &value in &interleaved[p * partition..(p + 1) * partition] {
925+ book.write(out, (value.clamp(-range, range) + range) as usize);
926+ }
927+ }
928+ p += 1;
929+ }
598 }930 }
599 }931 }
600 932
@@ -646,21 +978,22 @@ fn fold(predicted: i32, wanted: i32, range: i32) -> i32 {
646 }978 }
647 }979 }
648 980
649-/// The floor-1 configuration this encoder writes and renders against.981+/// The floor-1 configuration for one block size: `half` coefficients, `points`
650-fn build_floor() -> Floor1 {982+/// non-endpoint X values.
651- let mut sorted_x: Vec<u32> = Vec::with_capacity(FLOOR_POINTS);983+fn build_floor(half: usize, points: usize) -> Floor1 {
984+ let mut sorted_x: Vec<u32> = Vec::with_capacity(points);
652 let mut last = 0u32;985 let mut last = 0u32;
653- for i in 0..FLOOR_POINTS {986+ for i in 0..points {
654- let t = i as f64 / (FLOOR_POINTS - 1) as f64;987+ let t = i as f64 / (points - 1) as f64;
655 // Log spacing over the band, nudged to stay strictly increasing at the988 // Log spacing over the band, nudged to stay strictly increasing at the
656 // bottom where the grid is finer than one coefficient.989 // bottom where the grid is finer than one coefficient.
657- let value = (1023f64).powf(t).round() as u32;990+ let value = ((half - 1) as f64).powf(t).round() as u32;
658 last = value.max(last + 1);991 last = value.max(last + 1);
659- sorted_x.push(last);992+ sorted_x.push(last.min(half as u32 - 1));
660 }993 }
661 // Coding order: endpoints first, then repeated bisection, so every value is994 // Coding order: endpoints first, then repeated bisection, so every value is
662 // predicted from the two coded values that bracket it most closely.995 // predicted from the two coded values that bracket it most closely.
663- let mut x_list = vec![0u32, HALF as u32];996+ let mut x_list = vec![0u32, half as u32];
664 let mut ranges = vec![(0usize, sorted_x.len())];997 let mut ranges = vec![(0usize, sorted_x.len())];
665 while let Some((lo, hi)) = ranges.pop() {998 while let Some((lo, hi)) = ranges.pop() {
666 if lo >= hi {999 if lo >= hi {
@@ -707,6 +1040,27 @@ fn build_floor() -> Floor1 {
707 }1040 }
708 }1041 }
709 1042
1043+/// Build one block size's floor and ATH curve.
1044+fn build_block_config(
1045+ half: usize,
1046+ partition: usize,
1047+ points: usize,
1048+ range: f64,
1049+ co_mask: f64,
1050+ config: &EncoderConfig,
1051+) -> BlockConfig {
1052+ let floor = build_floor(half, points);
1053+ let ath = floor
1054+ .x_list
1055+ .iter()
1056+ .map(|&x| {
1057+ let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / half as f64;
1058+ absolute_threshold(hz)
1059+ })
1060+ .collect();
1061+ BlockConfig { half, partition, floor, ath, range, co_mask }
1062+}
1063+
710 /// Folded floor amplitudes: mostly small corrections, occasionally an escape1064 /// Folded floor amplitudes: mostly small corrections, occasionally an escape
711 /// near the top of the range.1065 /// near the top of the range.
712 fn design_floor_book() -> CodebookSpec {1066 fn design_floor_book() -> CodebookSpec {
@@ -718,10 +1072,12 @@ fn design_floor_book() -> CodebookSpec {
718 1072
719 /// Class pairs, on the assumption that most partitions are silent.1073 /// Class pairs, on the assumption that most partitions are silent.
720 fn design_class_book() -> CodebookSpec {1074 fn design_class_book() -> CodebookSpec {
721- let per_class = [0.55f64, 0.20, 0.15, 0.08, 0.02];1075+ // Measured on real music at 128 kbps: silent partitions are four in ten,
1076+ // the three smallest ranges split most of the rest.
1077+ let per_class = [0.40f64, 0.18, 0.19, 0.16, 0.05, 0.011, 0.008, 0.007, 0.001];
722 let mut weights = Vec::with_capacity(CLASSES * CLASSES);1078 let mut weights = Vec::with_capacity(CLASSES * CLASSES);
723- for first in per_class {1079+ for &first in &per_class {
724- for second in per_class {1080+ for &second in &per_class {
725 weights.push(first * second);1081 weights.push(first * second);
726 }1082 }
727 }1083 }
@@ -735,7 +1091,9 @@ fn design_residue_books() -> Vec<CodebookSpec> {
735 CLASS_RANGE[1..]1091 CLASS_RANGE[1..]
736 .iter()1092 .iter()
737 .map(|&range| {1093 .map(|&range| {
738- let sigma = f64::from(range).max(1.0) / 2.5;1094+ // Measured mean |value| inside a partition of each class is about
1095+ // a sixth of the class's range, whatever the range.
1096+ let sigma = f64::from(range).max(1.0) / 6.0;
739 let weights: Vec<f64> = (-range..=range)1097 let weights: Vec<f64> = (-range..=range)
740 .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4)1098 .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4)
741 .collect();1099 .collect();
@@ -746,18 +1104,25 @@ fn design_residue_books() -> Vec<CodebookSpec> {
746 }1104 }
747 1105
748 /// Absolute threshold of hearing in dBFS, full scale taken as 96 dB SPL.1106 /// Absolute threshold of hearing in dBFS, full scale taken as 96 dB SPL.
1107+///
1108+/// Capped at -80 dBFS: the curve's own values at DC and above ~17 kHz
1109+/// (-13 / -10 dBFS) are not a quantiser step the rest of a block can live
1110+/// with — an onset inside a short block puts real energy in exactly those
1111+/// bins, and coding them that coarsely leaked -38 dB of pre-echo across the
1112+/// whole 256-sample window.
749 fn absolute_threshold(hz: f64) -> f64 {1113 fn absolute_threshold(hz: f64) -> f64 {
750 let khz = (hz / 1000.0).clamp(0.02, 20.0);1114 let khz = (hz / 1000.0).clamp(0.02, 20.0);
751 let spl =1115 let spl =
752 3.64 * khz.powf(-0.8) - 6.5 * (-0.6 * (khz - 3.3).powi(2)).exp() + 0.001 * khz.powi(4);1116 3.64 * khz.powf(-0.8) - 6.5 * (-0.6 * (khz - 3.3).powi(2)).exp() + 0.001 * khz.powi(4);
753- (spl - 96.0).clamp(-120.0, -10.0)1117+ (spl - 96.0).clamp(-120.0, -80.0)
754 }1118 }
755 1119
756 /// The three header packets, in order.1120 /// The three header packets, in order.
757 fn write_headers(1121 fn write_headers(
758 config: &EncoderConfig,1122 config: &EncoderConfig,
759 channels: usize,1123 channels: usize,
760- floor: &Floor1,1124+ long: &BlockConfig,
1125+ short: &BlockConfig,
761 floor_book: &CodebookSpec,1126 floor_book: &CodebookSpec,
762 class_book: &CodebookSpec,1127 class_book: &CodebookSpec,
763 residue_books: &[CodebookSpec],1128 residue_books: &[CodebookSpec],
@@ -772,7 +1137,7 @@ fn write_headers(
772 ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes());1137 ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes());
773 ident.extend_from_slice(&0i32.to_le_bytes());1138 ident.extend_from_slice(&0i32.to_le_bytes());
774 let log2 = |n: usize| n.trailing_zeros() as u8;1139 let log2 = |n: usize| n.trailing_zeros() as u8;
775- ident.push(log2(BLOCK) | (log2(BLOCK) << 4));1140+ ident.push(log2(BLOCK_SHORT) | (log2(BLOCK_LONG) << 4));
776 ident.push(1);1141 ident.push(1);
777 1142
778 let mut comment = vec![3u8];1143 let mut comment = vec![3u8];
@@ -798,62 +1163,73 @@ fn write_headers(
798 // One time-domain transform, stated as zero.1163 // One time-domain transform, stated as zero.
799 out.write(0, 6);1164 out.write(0, 6);
800 out.write(0, 16);1165 out.write(0, 16);
801- // One floor, type 1.1166+ // Two floors, type 1: long first, then short.
802- out.write(0, 6);1167+ out.write(1, 6);
803- out.write(1, 16);1168+ for bc in [long, short] {
804- out.write(floor.partition_classes.len() as u32, 5);1169+ out.write(1, 16);
805- for _ in &floor.partition_classes {1170+ out.write(bc.floor.partition_classes.len() as u32, 5);
806- out.write(0, 4);1171+ for _ in &bc.floor.partition_classes {
1172+ out.write(0, 4);
1173+ }
1174+ out.write(FLOOR_CLASS_DIM as u32 - 1, 3);
1175+ out.write(0, 2);
1176+ out.write(1, 8);
1177+ out.write(0, 2);
1178+ let range_bits = ilog(bc.half as u32) - 1;
1179+ out.write(range_bits, 4);
1180+ for &x in bc.floor.x_list.iter().skip(2) {
1181+ out.write(x, range_bits);
1182+ }
807 }1183 }
808- out.write(FLOOR_CLASS_DIM as u32 - 1, 3);1184+ // Two residues, type 2: long first, then short, each over every channel of
809- out.write(0, 2);1185+ // its own submap and sharing the class/residue books.
810- // Book number plus one; zero would mean "this subclass codes nothing".1186+ out.write(1, 6);
811- out.write(1, 8);1187+ for bc in [long, short] {
812- out.write(0, 2);1188+ out.write(2, 16);
813- let range_bits = ilog(HALF as u32) - 1;1189+ out.write(0, 24);
814- out.write(range_bits, 4);1190+ out.write((bc.half * channels) as u32, 24);
815- for &x in floor.x_list.iter().skip(2) {1191+ out.write(bc.partition as u32 - 1, 24);
816- out.write(x, range_bits);1192+ out.write(CLASSES as u32 - 1, 6);
1193+ out.write(1, 8);
1194+ for class in 0..CLASSES {
1195+ out.write(u32::from(class > 0), 3);
1196+ out.write(0, 1);
1197+ }
1198+ for class in 1..CLASSES {
1199+ out.write(class as u32 + 1, 8);
1200+ }
817 }1201 }
818- // One residue, type 2, over every channel of the one submap.1202+ // Two mappings, type 0: mapping 0 is long (floor/residue 0), mapping 1 is
819- out.write(0, 6);1203+ // short (floor/residue 1); both couple the same channels.
820- out.write(2, 16);1204+ out.write(1, 6);
821- out.write(0, 24);1205+ for (floor, residue) in [(0u32, 0u32), (1, 1)] {
822- out.write((HALF * channels) as u32, 24);1206+ out.write(0, 16);
823- out.write(PARTITION as u32 - 1, 24);
824- out.write(CLASSES as u32 - 1, 6);
825- out.write(1, 8);
826- for class in 0..CLASSES {
827- // Class 0 codes nothing at all; the rest have one book in pass 0.
828- out.write(u32::from(class > 0), 3);
829 out.write(0, 1);1207 out.write(0, 1);
830- }1208+ match coupling.is_empty() {
831- for class in 1..CLASSES {1209+ true => out.write(0, 1),
832- out.write(class as u32 + 1, 8);1210+ false => {
833- }1211+ out.write(1, 1);
834- // One mapping, type 0.1212+ out.write(coupling.len() as u32 - 1, 8);
835- out.write(0, 6);1213+ let field = ilog(channels as u32 - 1);
836- out.write(0, 16);1214+ for &(magnitude, angle) in coupling {
837- out.write(0, 1);1215+ out.write(magnitude as u32, field);
838- match coupling.is_empty() {1216+ out.write(angle as u32, field);
839- true => out.write(0, 1),1217+ }
840- false => {
841- out.write(1, 1);
842- out.write(coupling.len() as u32 - 1, 8);
843- let field = ilog(channels as u32 - 1);
844- for &(magnitude, angle) in coupling {
845- out.write(magnitude as u32, field);
846- out.write(angle as u32, field);
847 }1218 }
848 }1219 }
1220+ out.write(0, 2);
1221+ out.write(0, 8);
1222+ out.write(floor, 8);
1223+ out.write(residue, 8);
849 }1224 }
850- out.write(0, 2);1225+ // Two modes: mode `MODE_SHORT` is a short block on mapping 1, mode
851- out.write(0, 8);1226+ // `MODE_LONG` a long block on mapping 0.
852- out.write(0, 8);1227+ out.write(1, 6);
853- out.write(0, 8);1228+ out.bit(false);
854- // One mode: a long block on mapping 0.1229+ out.write(0, 16);
855- out.write(0, 6);1230+ out.write(0, 16);
856- out.write(1, 1);1231+ out.write(1, 8);
1232+ out.bit(true);
857 out.write(0, 16);1233 out.write(0, 16);
858 out.write(0, 16);1234 out.write(0, 16);
859 out.write(0, 8);1235 out.write(0, 8);
@@ -1048,4 +1424,79 @@ mod tests {
1048 }1424 }
1049 }1425 }
1050 }1426 }
1427+
1428+ /// A stationary tone never trips the transient detector: every packet
1429+ /// decodes to mode `MODE_LONG`.
1430+ #[test]
1431+ fn a_stationary_signal_uses_only_long_blocks() {
1432+ let mut enc = VorbisEncoder::new(EncoderConfig {
1433+ sample_rate: 48_000,
1434+ channels: 2,
1435+ bitrate_bps: -1,
1436+ quality: 0.6,
1437+ })
1438+ .unwrap();
1439+ let samples = 48_000usize;
1440+ let mut pcm = vec![0.0f32; samples * 2];
1441+ for i in 0..samples {
1442+ let t = i as f32 / 48_000.0;
1443+ let v = (2.0 * std::f32::consts::PI * 1_000.0 * t).sin() * 0.5;
1444+ pcm[2 * i] = v;
1445+ pcm[2 * i + 1] = v;
1446+ }
1447+ enc.push_interleaved(&pcm).unwrap();
1448+ enc.finish();
1449+ let mut modes = std::collections::HashSet::new();
1450+ loop {
1451+ match enc.next_packet() {
1452+ Ok(p) => {
1453+ let mut bits = crate::bits::Bits::new(&p.data);
1454+ assert!(!bits.bit());
1455+ modes.insert(bits.read(1));
1456+ }
1457+ Err(Error::Eof) => break,
1458+ Err(e) => panic!("{e}"),
1459+ }
1460+ }
1461+ assert_eq!(modes, std::collections::HashSet::from([MODE_LONG]));
1462+ }
1463+
1464+ /// An onset after real silence trips the detector: some packet decodes to
1465+ /// mode `MODE_SHORT`.
1466+ #[test]
1467+ fn an_onset_after_silence_uses_short_blocks() {
1468+ let mut enc = VorbisEncoder::new(EncoderConfig {
1469+ sample_rate: 44_100,
1470+ channels: 2,
1471+ bitrate_bps: -1,
1472+ quality: 0.6,
1473+ })
1474+ .unwrap();
1475+ let silence = 44_100usize;
1476+ let tone = 4_410usize;
1477+ let mut pcm = vec![0.0f32; (silence + tone) * 2];
1478+ for i in 0..tone {
1479+ let t = i as f32 / 44_100.0;
1480+ let v = (2.0 * std::f32::consts::PI * 1_000.0 * t).sin();
1481+ pcm[2 * (silence + i)] = v;
1482+ pcm[2 * (silence + i) + 1] = v;
1483+ }
1484+ enc.push_interleaved(&pcm).unwrap();
1485+ enc.finish();
1486+ let mut saw_short = false;
1487+ loop {
1488+ match enc.next_packet() {
1489+ Ok(p) => {
1490+ let mut bits = crate::bits::Bits::new(&p.data);
1491+ assert!(!bits.bit());
1492+ if bits.read(1) == MODE_SHORT {
1493+ saw_short = true;
1494+ }
1495+ }
1496+ Err(Error::Eof) => break,
1497+ Err(e) => panic!("{e}"),
1498+ }
1499+ }
1500+ assert!(saw_short, "no short block coded around the onset");
1501+ }
1051 }1502 }
crates/ec-vorbis/tests/oracle.rsmodified+162 -0
@@ -554,6 +554,82 @@ fn busy(channels: usize, rate: u32, samples: usize) -> Vec<Vec<f32>> {
554 .collect()554 .collect()
555 }555 }
556 556
557+/// A hard silence-to-full-scale onset must not leak into the long block
558+/// before it: that block should now be coded with a short right window (or
559+/// the onset itself carried by a short block), which windows the leak out
560+/// instead of smearing it across ~46 ms the way an all-long-block encoder
561+/// does.
562+#[test]
563+fn onset_after_silence_has_no_pre_echo() {
564+ // Onsets swept by phase (fractions of a second, so they land anywhere
565+ // relative to the long hop) and by offset from the long-hop grid itself,
566+ // since the short run's placement is decided per hop. Stereo carries
567+ // distinct content per channel — a different tone on the right, starting
568+ // 11 samples later — so coupling cannot hide a per-channel leak. The gap
569+ // is measured over the WHOLE silence up to the onset, so a leak in the
570+ // last few hundred samples before it cannot hide behind a guard band, and
571+ // the peak is barred too.
572+ let amp = 0.7f64;
573+ for (rate, layouts) in [(44_100u32, &[1usize, 2][..]), (48_000, &[1, 2, 6]), (96_000, &[6])] {
574+ let grid = 16 * 1024usize;
575+ let onsets = [0.3333f64, 0.5, 0.7321, 0.9137, 1.0]
576+ .into_iter()
577+ .map(|s| (s * f64::from(rate)) as usize)
578+ .chain([0usize, 37, 512, 1000, 1023].into_iter().map(|o| grid + o));
579+ for onset in onsets {
580+ for &channels in layouts {
581+ let tone_len = rate as usize;
582+ let mut source = vec![vec![0.0f32; onset + tone_len + 11 * channels]; channels];
583+ for (c, plane) in source.iter_mut().enumerate() {
584+ let hz = 1_000.0 + 370.0 * c as f64;
585+ let start = onset + 11 * c;
586+ for i in 0..tone_len {
587+ let t = i as f64 / f64::from(rate);
588+ plane[start + i] = (amp * (2.0 * std::f64::consts::PI * hz * t).sin()) as f32;
589+ }
590+ }
591+ let name = format!("onset-{rate}-{channels}ch-{onset}.ogg");
592+ let path = encode_to_file(&source, rate, 128_000, &name);
593+
594+ // The reference oracle must decode the short-block stream
595+ // cleanly: no warnings, let alone errors.
596+ let warn = Command::new("ffmpeg")
597+ .args(["-v", "warning", "-i"])
598+ .arg(&path)
599+ .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
600+ .output();
601+ if let Ok(out) = warn {
602+ assert!(
603+ out.stderr.is_empty(),
604+ "{name}: oracle decode warnings: {}",
605+ String::from_utf8_lossy(&out.stderr)
606+ );
607+ }
608+
609+ let tone_rms = rms(&source[0][onset..]);
610+ let check = |label: &str, planes: &[Vec<f32>]| {
611+ for (c, plane) in planes.iter().enumerate() {
612+ let gap = &plane[..onset.min(plane.len())];
613+ let gap_rms = rms(gap);
614+ let peak = gap.iter().fold(0.0f32, |m, v| m.max(v.abs()));
615+ println!("{name}/{label} ch{c}: gap RMS {gap_rms:.6} peak {peak:.4}");
616+ assert!(
617+ gap_rms <= 0.002 * tone_rms,
618+ "{name}/{label} ch{c}: gap RMS {gap_rms:.6} vs tone RMS {tone_rms:.6}"
619+ );
620+ assert!(f64::from(peak) <= 0.01 * amp, "{name}/{label} ch{c}: gap peak {peak:.4}");
621+ }
622+ };
623+ let (ours, _) = our_decode(&path);
624+ check("ours", &ours);
625+ if let Some((theirs, _)) = ffmpeg_decode(&path) {
626+ check("oracle", &theirs);
627+ }
628+ }
629+ }
630+ }
631+}
632+
557 #[test]633 #[test]
558 fn the_rate_loop_tracks_the_target_bitrate() {634 fn the_rate_loop_tracks_the_target_bitrate() {
559 let rate = 48_000u32;635 let rate = 48_000u32;
@@ -585,3 +661,89 @@ fn the_rate_loop_tracks_the_target_bitrate() {
585 );661 );
586 }662 }
587 }663 }
664+
665+/// Quiet and sparse content must reach the target too: with the floor bounded
666+/// by the threshold of hearing, most partitions code as class 0 at any step,
667+/// so the rate loop's extra headroom has to lower that bound to find bits to
668+/// spend. The fixture is a sparse tone at -18 dBFS; the synthetic sources are
669+/// the busy and tonal signals at -40 dBFS, the tones over a -90 dBFS noise
670+/// floor (what any 16-bit source carries; a pure digital tone has nothing
671+/// outside its own bins for any step to find). Noise is incompressible, so the
672+/// quiet noise is held to the full-scale noise's own fidelity rather than a
673+/// fixed bar.
674+///
675+/// The rate loop's step search bottoms out at the +-127 step range (36 dB
676+/// residue range + 12-point floor): once a quiet source's codable residue is
677+/// exhausted, no finer step can spend more bits without a second (cascade)
678+/// coding pass, which does not exist yet -- that cascade is the upgrade path.
679+/// So the contract is: measured kbps lands within +-25% of target, OR the
680+/// encode undershoots because there is nothing left to spend and the result
681+/// is transparent (corr >= 0.999 against the source). The monotone-in-target
682+/// spend check only applies where the case actually spends against target.
683+#[test]
684+fn quiet_content_reaches_the_target_or_is_transparent() {
685+ let rate = 48_000u32;
686+ let samples = rate as usize * 3;
687+ let fixture = ffmpeg_decode(&fixtures().join("audio/wav16-stereo-48000.wav"))
688+ .expect("fixture decodes");
689+ assert_eq!(fixture.1, rate);
690+ let attenuate = |mut source: Vec<Vec<f32>>| {
691+ for channel in source.iter_mut() {
692+ for value in channel.iter_mut() {
693+ *value *= 0.01;
694+ }
695+ }
696+ source
697+ };
698+ let corr_at = |path: &Path, source: &[Vec<f32>]| {
699+ let (decoded, _) = our_decode(path);
700+ decoded
701+ .iter()
702+ .zip(source.iter())
703+ .map(|(channel, original)| {
704+ let n = channel.len().min(original.len());
705+ correlation(&channel[..n], &original[..n])
706+ })
707+ .fold(1.0f64, f64::min)
708+ };
709+ let loud = busy(2, rate, samples);
710+ let loud_corr = corr_at(&encode_to_file(&loud, rate, 128_000, "loud-128k.ogg"), &loud);
711+ let quiet_noise = attenuate(loud);
712+ let mut quiet_tones = attenuate(tones(2, rate, samples));
713+ for (channel, noise) in quiet_tones.iter_mut().zip(busy(2, rate, samples)) {
714+ for (value, n) in channel.iter_mut().zip(noise) {
715+ *value += n * 0.0001;
716+ }
717+ }
718+ let cases = [
719+ ("fixture", &fixture.0, 0.99),
720+ ("quiet-tones", &quiet_tones, 0.99),
721+ ("quiet-noise", &quiet_noise, loud_corr - 0.02),
722+ ];
723+ for (name, source, bar) in cases {
724+ let mut measured = Vec::new();
725+ let mut spent = Vec::new();
726+ for target in [96_000i32, 128_000, 192_000] {
727+ let path = encode_to_file(source, rate, target, &format!("{name}-{}k.ogg", target / 1000));
728+ let bytes = std::fs::metadata(&path).expect("file").len();
729+ let kbps = bytes as f64 * 8.0 * f64::from(rate) / source[0].len() as f64 / 1000.0;
730+ let corr = corr_at(&path, source);
731+ println!("{name}: target {} kbps -> {kbps:.0} kbps, corr {corr:.4}", target / 1000);
732+ let target_kbps = f64::from(target) / 1000.0;
733+ let within_25pct = (kbps - target_kbps).abs() / target_kbps < 0.25;
734+ let transparent_undershoot = kbps < target_kbps && corr >= 0.999;
735+ assert!(
736+ within_25pct || transparent_undershoot,
737+ "{name}: {kbps:.0} kbps for {target_kbps:.0} kbps target, corr {corr:.4}"
738+ );
739+ spent.push(within_25pct);
740+ measured.push(kbps);
741+ if target == 128_000 {
742+ assert!(corr >= bar, "{name}: corr {corr:.4} under {bar:.4}");
743+ }
744+ }
745+ if spent.iter().all(|&s| s) {
746+ assert!(measured[0] < measured[1] && measured[1] < measured[2], "{name}: {measured:?}");
747+ }
748+ }
749+}