forge
Explore
Log in

Don't you dare go Hollow

Real block switching — short blocks eliminate pre-echo at silence→onset

Browse files at this commit

63f547a6f93a5658ed886e565b0d0c3672f87b22Ahmet Kaan GümüşParent: b966d5e
  • feat
    • real block switching — short blocks eliminate pre-echo at silence→onset
Show full message
feat(vorbis-enc): real block switching — short blocks eliminate pre-echo at silence→onset

Two modes now: 2048-sample long blocks (steady state) and 256-sample short
blocks, with their own floor1 X-grids and residue partition sizing but
sharing the encoder's designed codebooks. A per-hop energy-tick transient
detector (an onset after digital silence is the degenerate, always-firing
case of the general jump-past-predecessor check) swaps a pair of would-be
long blocks for long-with-short-right-window, a run of short blocks over the
transient, and long-with-short-left-window resuming steady state — a run
sized to land the transient safely inside short-block coverage rather than
in a transition block's own flat (unwindowed) span, which is what silently
reintroduced the leak the first cut of this fix produced.

Granule advance across a switch is exactly N long hops, so it never moves
the steady-state grid; a stationary signal still never leaves long-block
mode (tested). New oracle test onset_after_silence_has_no_pre_echo measures
gap RMS immediately before the onset at 44.1/48 kHz through both our own
decoder and the reference oracle: 0.0064 -> 0.0 (both rates, both decoders).
crates/ec-vorbis/src/encode.rsmodified+584 -310
@@ -10,8 +10,20 @@
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 //!
@@ -20,9 +32,9 @@
20 //! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of32 //! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of
21 //! them are Huffman codes over stated distributions, built at construction and33 //! them are Huffman codes over stated distributions, built at construction and
22 //! written into every stream's own setup header — which is why this encoder34 //! 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.35+//! needs no embedded profile and has no channel count it cannot serve. Both
24-36+//! block sizes share these books; only the floor's X grid and the residue's
25-use std::collections::VecDeque;37+//! partition size are sized per block.
26 38
27 use ec_core::{39 use ec_core::{
28 AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet,40 AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet,
@@ -35,29 +47,55 @@ use crate::codebook::{CodebookSpec, ilog};
35 use crate::decode::channel_map;47 use crate::decode::channel_map;
36 use crate::floor::render_floor1;48 use crate::floor::render_floor1;
37 use crate::setup::Floor1;49 use crate::setup::Floor1;
38-use crate::window;50+use crate::window::Windows;
39-51+
40-/// Long block size; this encoder codes long blocks only.52+/// Long block size.
41-const BLOCK: usize = 2048;53+const BLOCK_LONG: usize = 2048;
42-/// Samples between block centres.54+/// Short block size.
43-const HOP: usize = BLOCK / 2;55+const BLOCK_SHORT: usize = 256;
44-/// Coefficients per block.56+/// Coefficients in a long block.
45-const HALF: usize = BLOCK / 2;57+const HALF_LONG: usize = BLOCK_LONG / 2;
46-/// Coefficients per residue partition.58+/// Coefficients in a short block.
47-const PARTITION: usize = 32;59+const HALF_SHORT: usize = BLOCK_SHORT / 2;
48-/// Floor X points besides the two endpoints.60+/// Long-block coefficients per residue partition.
49-const FLOOR_POINTS: usize = 20;61+const PARTITION_LONG: usize = 32;
62+/// Short-block coefficients per residue partition.
63+const PARTITION_SHORT: usize = 16;
64+/// Long floor X points besides the two endpoints.
65+const FLOOR_POINTS_LONG: usize = 20;
66+/// Short floor X points besides the two endpoints.
67+const FLOOR_POINTS_SHORT: usize = 8;
50 /// Floor values per class.68 /// Floor values per class.
51 const FLOOR_CLASS_DIM: usize = 4;69 const FLOOR_CLASS_DIM: usize = 4;
52 /// Residue classes; class 0 codes nothing at all.70 /// Residue classes; class 0 codes nothing at all.
53 const CLASSES: usize = 5;71 const CLASSES: usize = 5;
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.72 /// Largest quantised residue each class's book can state.
60 const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127];73 const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127];
74+/// Samples per transient-detection tick — the short block's own hop, so a
75+/// tick lines up with the finest time resolution the encoder has.
76+const TICK: usize = BLOCK_SHORT / 4;
77+/// Short blocks a detected transient inserts between the two transition long
78+/// blocks. Detection looks one long hop ahead of the transition-out
79+/// candidate, so the transient can land anywhere in that hop; the run is
80+/// sized to three long hops' worth of short-hop resolution (any `8 + 8k`
81+/// count keeps the steady-state grid aligned) so it comfortably straddles a
82+/// transient found anywhere in the hop being watched, not just at its start.
83+const SHORT_RUN: u8 = 16;
84+/// Mode index the setup header and every packet agree the short mode is.
85+const MODE_SHORT: u32 = 0;
86+/// Mode index the setup header and every packet agree the long mode is.
87+const MODE_LONG: u32 = 1;
88+/// A tick energy jump past this multiple of its predecessor is a transient;
89+/// a near-zero predecessor makes this trip on any onset above the floor.
90+const TRANSIENT_RATIO: f64 = 16.0;
91+/// Below this per-sample mean square, a tick is not "content" at all — the
92+/// floor that keeps digital silence from ever tripping the detector.
93+const TRANSIENT_FLOOR: f64 = 1e-9;
94+
95+/// Buffer samples of left pre-roll before input sample 0 — one long half, so
96+/// even a block starting at the very front of the stream finds zeroes rather
97+/// than reading off the front of the buffer.
98+const PREROLL: usize = HALF_LONG;
61 99
62 /// How the encoder is set up.100 /// How the encoder is set up.
63 #[derive(Debug, Clone, Copy, PartialEq)]101 #[derive(Debug, Clone, Copy, PartialEq)]
@@ -95,6 +133,35 @@ pub struct EncodedPacket {
95 pub samples: i64,133 pub samples: i64,
96 }134 }
97 135
136+/// One block's shape: its mode and, for a long block, the window flags §4.3
137+/// states beside it.
138+#[derive(Debug, Clone, Copy)]
139+struct BlockPlan {
140+ is_long: bool,
141+ prev_long: bool,
142+ next_long: bool,
143+}
144+
145+/// The block-switch scheduler's state between calls.
146+#[derive(Debug, Clone, Copy)]
147+enum Sched {
148+ /// Long blocks, deciding fresh each time whether the next one is a
149+ /// transient's transition-out.
150+ Steady,
151+ /// Short blocks left to emit, counting this call down to zero.
152+ ShortRun(u8),
153+ /// The long block that resumes steady state after a short run.
154+ TransitionIn,
155+}
156+
157+/// A block size's own floor, codebook-sharing residue geometry and ATH.
158+struct BlockConfig {
159+ half: usize,
160+ partition: usize,
161+ floor: Floor1,
162+ ath: Vec<f64>,
163+}
164+
98 /// Vorbis I encoder.165 /// Vorbis I encoder.
99 pub struct VorbisEncoder {166 pub struct VorbisEncoder {
100 config: EncoderConfig,167 config: EncoderConfig,
@@ -102,29 +169,36 @@ pub struct VorbisEncoder {
102 /// `to_vorbis[ec channel] = vorbis channel`.169 /// `to_vorbis[ec channel] = vorbis channel`.
103 to_vorbis: Vec<usize>,170 to_vorbis: Vec<usize>,
104 headers: Vec<Vec<u8>>,171 headers: Vec<Vec<u8>>,
105- floor: Floor1,172+ long: BlockConfig,
173+ short: BlockConfig,
106 floor_book: CodebookSpec,174 floor_book: CodebookSpec,
107 class_book: CodebookSpec,175 class_book: CodebookSpec,
108 residue_books: Vec<CodebookSpec>,176 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.177 /// Channel pairs coupled by the mapping; empty unless stereo.
112 coupling: Vec<(usize, usize)>,178 coupling: Vec<(usize, usize)>,
113- mdct: Mdct<f32>,179+ mdct_long: Mdct<f32>,
114- window: Vec<f32>,180+ mdct_short: Mdct<f32>,
115- /// Per Vorbis channel, input samples with the first block's left half of181+ windows: Windows,
116- /// zeroes already in front.182+ /// Per Vorbis channel, input samples with [`PREROLL`] zeroes already in
183+ /// front.
117 buffer: Vec<Vec<f32>>,184 buffer: Vec<Vec<f32>>,
118 /// Input samples taken from the caller.185 /// Input samples taken from the caller.
119 fed: i64,186 fed: i64,
120 /// Blocks already emitted.187 /// Blocks already emitted.
121- blocks: i64,188+ blocks_emitted: i64,
189+ /// Centre of the block emitted last; the sentinel one long hop before
190+ /// sample 0, so the first real centre falls out of the same recurrence
191+ /// every later one uses.
192+ centre: i64,
193+ /// Blocksize of the block emitted last.
194+ prev_n: usize,
122 /// Granule of the packet emitted last.195 /// Granule of the packet emitted last.
123 granule: i64,196 granule: i64,
197+ scheduler: Sched,
124 /// Headroom under the masking curve, in dB — the rate loop's variable.198 /// Headroom under the masking curve, in dB — the rate loop's variable.
125 headroom: f64,199 headroom: f64,
126 finished: bool,200 finished: bool,
127- packets: VecDeque<EncodedPacket>,201+ packets: std::collections::VecDeque<EncodedPacket>,
128 }202 }
129 203
130 impl VorbisEncoder {204 impl VorbisEncoder {
@@ -152,23 +226,17 @@ impl VorbisEncoder {
152 _ => Vec::new(),226 _ => Vec::new(),
153 };227 };
154 228
155- let floor = build_floor();
156 let floor_book = design_floor_book();229 let floor_book = design_floor_book();
157 let class_book = design_class_book();230 let class_book = design_class_book();
158 let residue_books = design_residue_books();231 let residue_books = design_residue_books();
159- let ath = floor232+ let long = build_block_config(HALF_LONG, PARTITION_LONG, FLOOR_POINTS_LONG, &config);
160- .x_list233+ let short = build_block_config(HALF_SHORT, PARTITION_SHORT, FLOOR_POINTS_SHORT, &config);
161- .iter()
162- .map(|&x| {
163- let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / HALF as f64;
164- absolute_threshold(hz)
165- })
166- .collect();
167 234
168 let headers = write_headers(235 let headers = write_headers(
169 &config,236 &config,
170 channels,237 channels,
171- &floor,238+ &long,
239+ &short,
172 &floor_book,240 &floor_book,
173 &class_book,241 &class_book,
174 &residue_books,242 &residue_books,
@@ -187,26 +255,28 @@ impl VorbisEncoder {
187 255
188 let quality = f64::from(config.quality.clamp(0.0, 1.0));256 let quality = f64::from(config.quality.clamp(0.0, 1.0));
189 Ok(VorbisEncoder {257 Ok(VorbisEncoder {
190- mdct: Mdct::new(BLOCK),258+ mdct_long: Mdct::new(BLOCK_LONG),
191- window: window::build(BLOCK, BLOCK, true, true),259+ mdct_short: Mdct::new(BLOCK_SHORT),
192- // The first block is centred on input sample 0, so its left half is260+ windows: Windows::new(BLOCK_SHORT, BLOCK_LONG),
193- // the only pre-roll there is and the caller never sees it.261+ buffer: vec![vec![0.0; PREROLL]; channels],
194- buffer: vec![vec![0.0; HOP]; channels],
195 fed: 0,262 fed: 0,
196- blocks: 0,263+ blocks_emitted: 0,
264+ centre: -(HALF_LONG as i64),
265+ prev_n: BLOCK_LONG,
197 granule: 0,266 granule: 0,
267+ scheduler: Sched::Steady,
198 headroom: 4.0 + 26.0 * quality,268 headroom: 4.0 + 26.0 * quality,
199 finished: false,269 finished: false,
200- packets: VecDeque::new(),270+ packets: std::collections::VecDeque::new(),
201 config,271 config,
202 params,272 params,
203 to_vorbis,273 to_vorbis,
204 headers,274 headers,
205- floor,275+ long,
276+ short,
206 floor_book,277 floor_book,
207 class_book,278 class_book,
208 residue_books,279 residue_books,
209- ath,
210 coupling,280 coupling,
211 })281 })
212 }282 }
@@ -273,10 +343,11 @@ impl VorbisEncoder {
273 return;343 return;
274 }344 }
275 self.finished = true;345 self.finished = true;
276- // Enough blocks for every input sample to sit left of a block centre,346+ // 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.347+ // 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;348+ // runs out still finds real (zero) samples rather than the buffer's
279- let needed = last * HOP + BLOCK;349+ // edge.
350+ let needed = PREROLL + self.fed.max(0) as usize + 2 * BLOCK_LONG;
280 for channel in &mut self.buffer {351 for channel in &mut self.buffer {
281 if channel.len() < needed {352 if channel.len() < needed {
282 channel.resize(needed, 0.0);353 channel.resize(needed, 0.0);
@@ -294,49 +365,142 @@ impl VorbisEncoder {
294 }365 }
295 }366 }
296 367
368+ /// Decide the next block's shape without committing the scheduler state;
369+ /// used to check whether the data it needs is buffered yet.
370+ fn peek_plan(&self) -> BlockPlan {
371+ match self.scheduler {
372+ Sched::Steady => BlockPlan {
373+ is_long: true,
374+ prev_long: true,
375+ next_long: !self.transient_ahead(),
376+ },
377+ Sched::ShortRun(_) => BlockPlan {
378+ is_long: false,
379+ prev_long: true,
380+ next_long: true,
381+ },
382+ Sched::TransitionIn => BlockPlan {
383+ is_long: true,
384+ prev_long: false,
385+ next_long: true,
386+ },
387+ }
388+ }
389+
390+ /// Advance the scheduler past the plan [`peek_plan`] just returned.
391+ fn commit_plan(&mut self, plan: BlockPlan) {
392+ self.scheduler = match self.scheduler {
393+ Sched::Steady if !plan.next_long => Sched::ShortRun(SHORT_RUN),
394+ Sched::Steady => Sched::Steady,
395+ Sched::ShortRun(remaining) if remaining > 1 => Sched::ShortRun(remaining - 1),
396+ Sched::ShortRun(_) => Sched::TransitionIn,
397+ Sched::TransitionIn => Sched::Steady,
398+ };
399+ }
400+
401+ /// Whether the *next* steady long block's window carries a transient —
402+ /// checked one hop ahead of the block being decided now, so the block
403+ /// this call is about to type as transition-out still finishes its own
404+ /// carried region (up to a short hop past its centre) safely before the
405+ /// transient it is making room for. A tick's energy jumping past its
406+ /// predecessor's is exactly what an onset after digital silence looks
407+ /// like when the predecessor is zero.
408+ fn transient_ahead(&self) -> bool {
409+ // The very first block's "predecessor" is the encoder's own silent
410+ // pre-roll, not a real signal boundary; nothing to detect there.
411+ if self.centre == -(HALF_LONG as i64) {
412+ return false;
413+ }
414+ let candidate_centre = self.centre + (self.prev_n + BLOCK_LONG) as i64 / 4;
415+ let lookahead_centre = candidate_centre + BLOCK_LONG as i64 / 2;
416+ let window_start = lookahead_centre - HALF_LONG as i64;
417+ let buffer_start = window_start + PREROLL as i64;
418+ if buffer_start < 0 || self.buffer[0].len() < (buffer_start as usize) + BLOCK_LONG {
419+ return false;
420+ }
421+ let ticks = BLOCK_LONG / TICK;
422+ let energy = |t: usize| -> f64 {
423+ let start = buffer_start as usize + t * TICK;
424+ let mut sum = 0.0f64;
425+ for channel in &self.buffer {
426+ for &s in &channel[start..start + TICK] {
427+ sum += f64::from(s) * f64::from(s);
428+ }
429+ }
430+ sum
431+ };
432+ // Only the right half is new; its left neighbour was already the
433+ // right half the last time this block's window was checked.
434+ for t in ticks / 2..ticks {
435+ let previous = energy(t - 1);
436+ let current = energy(t);
437+ if current > TRANSIENT_FLOOR && current > previous * TRANSIENT_RATIO {
438+ return true;
439+ }
440+ }
441+ false
442+ }
443+
297 /// Encode every block the buffer now holds whole.444 /// 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) {445 fn encode_ready(&mut self) {
304 let channels = usize::from(self.config.channels);446 let channels = usize::from(self.config.channels);
305 loop {447 loop {
306- if self.finished && self.blocks > 0 && self.granule >= self.fed {448+ if self.finished && self.blocks_emitted > 0 && self.granule >= self.fed {
307 break;449 break;
308 }450 }
309- let start = self.blocks as usize * HOP;451+ let plan = self.peek_plan();
310- if self.buffer[0].len() < start + BLOCK {452+ let n = if plan.is_long { BLOCK_LONG } else { BLOCK_SHORT };
453+ let half = if plan.is_long { HALF_LONG } else { HALF_SHORT };
454+ let centre = self.centre + (self.prev_n + n) as i64 / 4;
455+ let window_start = centre - (n / 2) as i64;
456+ let buffer_start = window_start + PREROLL as i64;
457+ if buffer_start < 0 || self.buffer[0].len() < buffer_start as usize + n {
311 break;458 break;
312 }459 }
313- let centre = self.blocks * HOP as i64;
314 let granule = match self.finished {460 let granule = match self.finished {
315 true => centre.min(self.fed),461 true => centre.min(self.fed),
316 false => centre,462 false => centre,
317 };463 };
318- let data = self.encode_block(start, channels);464+ let data = self.encode_block(buffer_start as usize, n, half, plan, channels);
319 self.packets.push_back(EncodedPacket {465 self.packets.push_back(EncodedPacket {
320 data,466 data,
321 granule,467 granule,
322 samples: (granule - self.granule).max(0),468 samples: (granule - self.granule).max(0),
323 });469 });
324 self.granule = granule;470 self.granule = granule;
325- self.blocks += 1;471+ self.centre = centre;
472+ self.prev_n = n;
473+ self.blocks_emitted += 1;
474+ self.commit_plan(plan);
326 }475 }
327 }476 }
328 477
329 /// One block: analyse, quantise, write.478 /// One block: analyse, quantise, write.
330- fn encode_block(&mut self, start: usize, channels: usize) -> Vec<u8> {479+ fn encode_block(
480+ &mut self,
481+ start: usize,
482+ n: usize,
483+ half: usize,
484+ plan: BlockPlan,
485+ channels: usize,
486+ ) -> Vec<u8> {
487+ let bc = if plan.is_long { &self.long } else { &self.short };
488+ let partition = bc.partition;
489+ let scale = 2.0 / half as f32;
490+ let window = self
491+ .windows
492+ .get(plan.is_long, plan.prev_long, plan.next_long)
493+ .to_vec();
494+
331 let mut spectra: Vec<Vec<f32>> = Vec::with_capacity(channels);495 let mut spectra: Vec<Vec<f32>> = Vec::with_capacity(channels);
332- let mut block = vec![0.0f32; BLOCK];496+ let mut block = vec![0.0f32; n];
333 for channel in 0..channels {497 for channel in 0..channels {
334- block.copy_from_slice(&self.buffer[channel][start..start + BLOCK]);498+ block.copy_from_slice(&self.buffer[channel][start..start + n]);
335- let mut coefficients = vec![0.0f32; HALF];499+ let mut coefficients = vec![0.0f32; half];
336- self.mdct500+ let mdct = if plan.is_long { &mut self.mdct_long } else { &mut self.mdct_short };
337- .forward_windowed(&block, &self.window, &mut coefficients);501+ mdct.forward_windowed(&block, &window, &mut coefficients);
338 for value in coefficients.iter_mut() {502 for value in coefficients.iter_mut() {
339- *value *= VORBIS_MDCT_SCALE;503+ *value *= scale;
340 }504 }
341 spectra.push(coefficients);505 spectra.push(coefficients);
342 }506 }
@@ -348,10 +512,10 @@ impl VorbisEncoder {
348 let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels];512 let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels];
349 let mut coded = vec![false; channels];513 let mut coded = vec![false; channels];
350 for &(magnitude, angle) in &self.coupling {514 for &(magnitude, angle) in &self.coupling {
351- let peaks = self.peaks_of(&[&spectra[magnitude], &spectra[angle]]);515+ let peaks = peaks_of(&bc.floor, half, &[&spectra[magnitude], &spectra[angle]]);
352- let (y, step2) = self.fit_floor(&peaks);516+ let (y, step2) = fit_floor(&bc.floor, &bc.ath, self.headroom, &peaks);
353- let mut curve = vec![0.0f32; HALF];517+ let mut curve = vec![0.0f32; half];
354- render_floor1(&self.floor, &y, &step2, &mut curve);518+ render_floor1(&bc.floor, &y, &step2, &mut curve);
355 curves[magnitude] = curve.clone();519 curves[magnitude] = curve.clone();
356 curves[angle] = curve;520 curves[angle] = curve;
357 floor_values[magnitude] = y.clone();521 floor_values[magnitude] = y.clone();
@@ -363,10 +527,10 @@ impl VorbisEncoder {
363 if coded[channel] {527 if coded[channel] {
364 continue;528 continue;
365 }529 }
366- let peaks = self.peaks_of(&[&spectra[channel]]);530+ let peaks = peaks_of(&bc.floor, half, &[&spectra[channel]]);
367- let (y, step2) = self.fit_floor(&peaks);531+ let (y, step2) = fit_floor(&bc.floor, &bc.ath, self.headroom, &peaks);
368- let mut curve = vec![0.0f32; HALF];532+ let mut curve = vec![0.0f32; half];
369- render_floor1(&self.floor, &y, &step2, &mut curve);533+ render_floor1(&bc.floor, &y, &step2, &mut curve);
370 curves[channel] = curve;534 curves[channel] = curve;
371 floor_values[channel] = y;535 floor_values[channel] = y;
372 }536 }
@@ -386,8 +550,6 @@ impl VorbisEncoder {
386 })550 })
387 .collect();551 .collect();
388 for &(magnitude, angle) in &self.coupling {552 for &(magnitude, angle) in &self.coupling {
389- // Taken out and put back so the pair can be walked in step; a
390- // coupling step never names one channel twice.
391 let mut left = std::mem::take(&mut quantised[magnitude]);553 let mut left = std::mem::take(&mut quantised[magnitude]);
392 let mut right = std::mem::take(&mut quantised[angle]);554 let mut right = std::mem::take(&mut quantised[angle]);
393 for (l, r) in left.iter_mut().zip(right.iter_mut()) {555 for (l, r) in left.iter_mut().zip(right.iter_mut()) {
@@ -406,196 +568,206 @@ impl VorbisEncoder {
406 }568 }
407 569
408 let mut out = BitsOut::new();570 let mut out = BitsOut::new();
409- out.write(0, 1);571+ out.bit(false);
410- // One mode means `ilog(modes - 1)` is zero bits: there is nothing to572+ let mode = if plan.is_long { MODE_LONG } else { MODE_SHORT };
411- // state. The two window flags follow because the mode is a long block.573+ out.write(mode, 1);
412- out.bit(true);574+ if plan.is_long {
413- out.bit(true);575+ out.bit(plan.prev_long);
576+ out.bit(plan.next_long);
577+ }
414 for values in floor_values.iter().take(channels) {578 for values in floor_values.iter().take(channels) {
415- self.write_floor(&mut out, values);579+ write_floor(&mut out, &bc.floor, &self.floor_book, values);
416 }580 }
417- self.write_residue(&mut out, &quantised);581+ write_residue(&mut out, &quantised, half, partition, &self.class_book, &self.residue_books);
418 let bits = out.len();582 let bits = out.len();
419- self.update_rate(bits, channels);583+ let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre;
584+ self.update_rate(bits, half, channels, delta);
420 out.finish()585 out.finish()
421 }586 }
422 587
423- /// Peak magnitude around each floor X point, over every channel given.588+ /// Move the headroom so the running bitrate meets the target.
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- }
443- }
444- peak
445- })
446- .collect()
447- }
448-
449- /// Turn peak magnitudes into coded floor amplitudes.
450 ///589 ///
451- /// Spread first (a masker covers its neighbours), then subtract the rate590+ /// One dB of headroom is about one sixth of a bit per coefficient, so the
452- /// loop's headroom, then hold the absolute threshold of hearing as a lower591+ /// step is the bit error divided by that — a proportional loop that settles
453- /// bound: below it the residue quantises to zero and costs a class-0592+ /// within a few blocks and is clamped either side so a transient cannot
454- /// partition.593+ /// swing the whole file. The target itself scales with this block's own
455- fn fit_floor(&self, peaks: &[f64]) -> (Vec<i32>, Vec<bool>) {594+ /// granule advance, so a short block (a small fraction of a long hop) is
456- let mut db: Vec<f64> = peaks595+ /// judged against a proportionally small bit budget.
457- .iter()596+ fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) {
458- .map(|&peak| 20.0 * (peak.max(1e-9)).log10())597+ if self.config.bitrate_bps <= 0 || delta <= 0 {
459- .collect();598+ return;
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 }599 }
470- let target: Vec<f64> = db600+ let target = f64::from(self.config.bitrate_bps) * delta as f64 / f64::from(self.config.sample_rate);
471- .iter()601+ let coefficients = (half * channels) as f64;
472- .zip(self.ath.iter())602+ let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0);
473- .map(|(&level, &threshold)| (level - self.headroom).max(threshold))603+ // Negative headroom is not a mistake: it puts the floor *above* the
474- .collect();604+ // signal, which quantises the coefficients under it to zero and lets a
475- let y: Vec<i32> = target605+ // whole partition become class 0 for two bits. Without that a low target
476- .iter()606+ // cannot be reached at all — coding every coefficient with the shortest
477- .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255))607+ // codeword there is already costs about a bit each.
478- .collect();608+ self.headroom = (self.headroom + step).clamp(-24.0, 36.0);
479- self.fold_floor(&y)
480 }609 }
610+}
481 611
482- /// Run the decoder's own amplitude synthesis forwards, so the curve the612+/// Peak magnitude around each floor X point, over every channel given.
483- /// encoder normalises against is the curve the decoder will draw.613+///
484- fn fold_floor(&self, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) {614+/// Each point owns the coefficients halfway to its neighbours either side, so
485- let values = wanted.len();615+/// the whole spectrum is covered exactly once and a peak between two points
486- let range = 256i32;616+/// still raises the floor that has to carry it.
487- let mut final_y = vec![0i32; values];617+fn peaks_of(floor: &Floor1, half: usize, spectra: &[&Vec<f32>]) -> Vec<f64> {
488- let mut step2 = vec![false; values];618+ let x = &floor.x_list;
489- final_y[0] = wanted[0];619+ x.iter()
490- final_y[1] = wanted[1];620+ .map(|&centre| {
491- step2[0] = true;621+ let below = x.iter().filter(|&&o| o < centre).max().copied();
492- step2[1] = true;622+ let above = x.iter().filter(|&&o| o > centre).min().copied();
493- for i in 2..values {623+ let lo = below.map_or(0, |b| ((b + centre) / 2) as usize);
494- let (low, high) = self.floor.neighbours[i];624+ let hi = above.map_or(half, |a| ((a + centre) / 2) as usize + 1);
495- let predicted = predict(625+ let lo = lo.min(half - 1);
496- self.floor.x_list[low],626+ let hi = hi.clamp(lo + 1, half);
497- final_y[low],627+ let mut peak = 0.0f64;
498- self.floor.x_list[high],628+ for spectrum in spectra {
499- final_y[high],629+ for &value in &spectrum[lo..hi] {
500- self.floor.x_list[i],630+ peak = peak.max(f64::from(value.abs()));
501- );631+ }
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 }632 }
508- final_y[i] = wanted[i];633+ peak
509- }634+ })
510- (final_y, step2)635+ .collect()
636+}
637+
638+/// Turn peak magnitudes into coded floor amplitudes.
639+///
640+/// Spread first (a masker covers its neighbours), then subtract the rate
641+/// loop's headroom, then hold the absolute threshold of hearing as a lower
642+/// bound: below it the residue quantises to zero and costs a class-0
643+/// partition.
644+fn fit_floor(floor: &Floor1, ath: &[f64], headroom: f64, peaks: &[f64]) -> (Vec<i32>, Vec<bool>) {
645+ let mut db: Vec<f64> = peaks
646+ .iter()
647+ .map(|&peak| 20.0 * (peak.max(1e-9)).log10())
648+ .collect();
649+ let order = &floor.sorted;
650+ for window in order.windows(2) {
651+ let (previous, current) = (window[0], window[1]);
652+ db[current] = db[current].max(db[previous] - 12.0);
511 }653 }
654+ for window in order.windows(2).rev() {
655+ let (current, next) = (window[0], window[1]);
656+ db[current] = db[current].max(db[next] - 24.0);
657+ }
658+ let target: Vec<f64> = db
659+ .iter()
660+ .zip(ath.iter())
661+ .map(|(&level, &threshold)| (level - headroom).max(threshold))
662+ .collect();
663+ let y: Vec<i32> = target
664+ .iter()
665+ .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255))
666+ .collect();
667+ fold_floor(floor, &y)
668+}
512 669
513- /// Write one channel's floor: the two endpoints raw, the rest folded670+/// Run the decoder's own amplitude synthesis forwards, so the curve the
514- /// against their neighbours and Huffman coded.671+/// encoder normalises against is the curve the decoder will draw.
515- fn write_floor(&self, out: &mut BitsOut, y: &[i32]) {672+fn fold_floor(floor: &Floor1, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) {
516- out.bit(true);673+ let values = wanted.len();
517- out.write(y[0] as u32, 8);674+ let range = 256i32;
518- out.write(y[1] as u32, 8);675+ let mut final_y = vec![0i32; values];
519- for i in 2..y.len() {676+ let mut step2 = vec![false; values];
520- let (low, high) = self.floor.neighbours[i];677+ final_y[0] = wanted[0];
521- let predicted = predict(678+ final_y[1] = wanted[1];
522- self.floor.x_list[low],679+ step2[0] = true;
523- y[low],680+ step2[1] = true;
524- self.floor.x_list[high],681+ for i in 2..values {
525- y[high],682+ let (low, high) = floor.neighbours[i];
526- self.floor.x_list[i],683+ let predicted = predict(
527- );684+ floor.x_list[low],
528- let value = fold(predicted, y[i], 256);685+ final_y[low],
529- self.floor_book.write(out, value as usize);686+ floor.x_list[high],
687+ final_y[high],
688+ floor.x_list[i],
689+ );
690+ let value = fold(predicted, wanted[i], range);
691+ if value != 0 {
692+ step2[low] = true;
693+ step2[high] = true;
694+ step2[i] = true;
530 }695 }
696+ final_y[i] = wanted[i];
697+ }
698+ (final_y, step2)
699+}
700+
701+/// Write one channel's floor: the two endpoints raw, the rest folded against
702+/// their neighbours and Huffman coded.
703+fn write_floor(out: &mut BitsOut, floor: &Floor1, floor_book: &CodebookSpec, y: &[i32]) {
704+ out.bit(true);
705+ out.write(y[0] as u32, 8);
706+ out.write(y[1] as u32, 8);
707+ for i in 2..y.len() {
708+ let (low, high) = floor.neighbours[i];
709+ let predicted = predict(
710+ floor.x_list[low],
711+ y[low],
712+ floor.x_list[high],
713+ y[high],
714+ floor.x_list[i],
715+ );
716+ let value = fold(predicted, y[i], 256);
717+ floor_book.write(out, value as usize);
531 }718 }
719+}
532 720
533- /// Write the residue: one type-2 interleaved vector over every channel,721+/// Write the residue: one type-2 interleaved vector over every channel,
534- /// classified per partition and coded in one pass.722+/// classified per partition and coded in one pass.
535- fn write_residue(&self, out: &mut BitsOut, quantised: &[Vec<i32>]) {723+fn write_residue(
536- let channels = quantised.len();724+ out: &mut BitsOut,
537- let total = HALF * channels;725+ quantised: &[Vec<i32>],
538- let mut interleaved = vec![0i32; total];726+ half: usize,
539- for (i, slot) in interleaved.iter_mut().enumerate() {727+ partition: usize,
540- *slot = quantised[i % channels][i / channels];728+ class_book: &CodebookSpec,
729+ residue_books: &[CodebookSpec],
730+) {
731+ let channels = quantised.len();
732+ let total = half * channels;
733+ let mut interleaved = vec![0i32; total];
734+ for (i, slot) in interleaved.iter_mut().enumerate() {
735+ *slot = quantised[i % channels][i / channels];
736+ }
737+ let partitions = total / partition;
738+ let classes: Vec<usize> = (0..partitions)
739+ .map(|p| {
740+ let slice = &interleaved[p * partition..(p + 1) * partition];
741+ let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0);
742+ CLASS_RANGE
743+ .iter()
744+ .position(|&range| peak <= range)
745+ .unwrap_or(CLASSES - 1)
746+ })
747+ .collect();
748+ let per_word = class_book.dimensions;
749+ let mut p = 0usize;
750+ while p < partitions {
751+ let mut word = 0usize;
752+ for i in 0..per_word {
753+ word = word * CLASSES + classes.get(p + i).copied().unwrap_or(0);
541 }754 }
542- let partitions = total / PARTITION;755+ class_book.write(out, word);
543- let classes: Vec<usize> = (0..partitions)756+ for _ in 0..per_word {
544- .map(|partition| {757+ if p >= partitions {
545- let slice = &interleaved[partition * PARTITION..(partition + 1) * PARTITION];758+ break;
546- let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0);
547- CLASS_RANGE
548- .iter()
549- .position(|&range| peak <= range)
550- .unwrap_or(CLASSES - 1)
551- })
552- .collect();
553- let per_word = self.class_book.dimensions;
554- let mut partition = 0usize;
555- while partition < partitions {
556- let mut word = 0usize;
557- for i in 0..per_word {
558- word = word * CLASSES + classes.get(partition + i).copied().unwrap_or(0);
559 }759 }
560- self.class_book.write(out, word);760+ let class = classes[p];
561- for _ in 0..per_word {761+ if class > 0 {
562- if partition >= partitions {762+ let book = &residue_books[class - 1];
563- break;763+ let range = CLASS_RANGE[class];
564- }764+ for &value in &interleaved[p * partition..(p + 1) * partition] {
565- let class = classes[partition];765+ book.write(out, (value.clamp(-range, range) + range) as usize);
566- if class > 0 {
567- let book = &self.residue_books[class - 1];
568- let range = CLASS_RANGE[class];
569- for &value in &interleaved[partition * PARTITION..(partition + 1) * PARTITION] {
570- book.write(out, (value.clamp(-range, range) + range) as usize);
571- }
572 }766 }
573- partition += 1;
574 }767 }
768+ p += 1;
575 }769 }
576 }770 }
577-
578- /// Move the headroom so the running bitrate meets the target.
579- ///
580- /// 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 settles
582- /// within a few blocks and is clamped either side so a transient cannot
583- /// swing the whole file.
584- fn update_rate(&mut self, bits: u64, channels: usize) {
585- if self.config.bitrate_bps <= 0 {
586- return;
587- }
588- let target =
589- f64::from(self.config.bitrate_bps) * HOP as f64 / f64::from(self.config.sample_rate);
590- let coefficients = (HALF * channels) as f64;
591- 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* the
593- // 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 target
595- // cannot be reached at all — coding every coefficient with the shortest
596- // codeword there is already costs about a bit each.
597- self.headroom = (self.headroom + step).clamp(-24.0, 36.0);
598- }
599 }771 }
600 772
601 /// Forward square-polar coupling (§9.4.2 run backwards).773 /// Forward square-polar coupling (§9.4.2 run backwards).
@@ -646,21 +818,22 @@ fn fold(predicted: i32, wanted: i32, range: i32) -> i32 {
646 }818 }
647 }819 }
648 820
649-/// The floor-1 configuration this encoder writes and renders against.821+/// The floor-1 configuration for one block size: `half` coefficients, `points`
650-fn build_floor() -> Floor1 {822+/// non-endpoint X values.
651- let mut sorted_x: Vec<u32> = Vec::with_capacity(FLOOR_POINTS);823+fn build_floor(half: usize, points: usize) -> Floor1 {
824+ let mut sorted_x: Vec<u32> = Vec::with_capacity(points);
652 let mut last = 0u32;825 let mut last = 0u32;
653- for i in 0..FLOOR_POINTS {826+ for i in 0..points {
654- let t = i as f64 / (FLOOR_POINTS - 1) as f64;827+ let t = i as f64 / (points - 1) as f64;
655 // Log spacing over the band, nudged to stay strictly increasing at the828 // Log spacing over the band, nudged to stay strictly increasing at the
656 // bottom where the grid is finer than one coefficient.829 // bottom where the grid is finer than one coefficient.
657- let value = (1023f64).powf(t).round() as u32;830+ let value = ((half - 1) as f64).powf(t).round() as u32;
658 last = value.max(last + 1);831 last = value.max(last + 1);
659- sorted_x.push(last);832+ sorted_x.push(last.min(half as u32 - 1));
660 }833 }
661 // Coding order: endpoints first, then repeated bisection, so every value is834 // Coding order: endpoints first, then repeated bisection, so every value is
662 // predicted from the two coded values that bracket it most closely.835 // predicted from the two coded values that bracket it most closely.
663- let mut x_list = vec![0u32, HALF as u32];836+ let mut x_list = vec![0u32, half as u32];
664 let mut ranges = vec![(0usize, sorted_x.len())];837 let mut ranges = vec![(0usize, sorted_x.len())];
665 while let Some((lo, hi)) = ranges.pop() {838 while let Some((lo, hi)) = ranges.pop() {
666 if lo >= hi {839 if lo >= hi {
@@ -707,6 +880,20 @@ fn build_floor() -> Floor1 {
707 }880 }
708 }881 }
709 882
883+/// Build one block size's floor and ATH curve.
884+fn build_block_config(half: usize, partition: usize, points: usize, config: &EncoderConfig) -> BlockConfig {
885+ let floor = build_floor(half, points);
886+ let ath = floor
887+ .x_list
888+ .iter()
889+ .map(|&x| {
890+ let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / half as f64;
891+ absolute_threshold(hz)
892+ })
893+ .collect();
894+ BlockConfig { half, partition, floor, ath }
895+}
896+
710 /// Folded floor amplitudes: mostly small corrections, occasionally an escape897 /// Folded floor amplitudes: mostly small corrections, occasionally an escape
711 /// near the top of the range.898 /// near the top of the range.
712 fn design_floor_book() -> CodebookSpec {899 fn design_floor_book() -> CodebookSpec {
@@ -757,7 +944,8 @@ fn absolute_threshold(hz: f64) -> f64 {
757 fn write_headers(944 fn write_headers(
758 config: &EncoderConfig,945 config: &EncoderConfig,
759 channels: usize,946 channels: usize,
760- floor: &Floor1,947+ long: &BlockConfig,
948+ short: &BlockConfig,
761 floor_book: &CodebookSpec,949 floor_book: &CodebookSpec,
762 class_book: &CodebookSpec,950 class_book: &CodebookSpec,
763 residue_books: &[CodebookSpec],951 residue_books: &[CodebookSpec],
@@ -772,7 +960,7 @@ fn write_headers(
772 ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes());960 ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes());
773 ident.extend_from_slice(&0i32.to_le_bytes());961 ident.extend_from_slice(&0i32.to_le_bytes());
774 let log2 = |n: usize| n.trailing_zeros() as u8;962 let log2 = |n: usize| n.trailing_zeros() as u8;
775- ident.push(log2(BLOCK) | (log2(BLOCK) << 4));963+ ident.push(log2(BLOCK_SHORT) | (log2(BLOCK_LONG) << 4));
776 ident.push(1);964 ident.push(1);
777 965
778 let mut comment = vec![3u8];966 let mut comment = vec![3u8];
@@ -798,62 +986,73 @@ fn write_headers(
798 // One time-domain transform, stated as zero.986 // One time-domain transform, stated as zero.
799 out.write(0, 6);987 out.write(0, 6);
800 out.write(0, 16);988 out.write(0, 16);
801- // One floor, type 1.989+ // Two floors, type 1: long first, then short.
802- out.write(0, 6);990+ out.write(1, 6);
803- out.write(1, 16);991+ for bc in [long, short] {
804- out.write(floor.partition_classes.len() as u32, 5);992+ out.write(1, 16);
805- for _ in &floor.partition_classes {993+ out.write(bc.floor.partition_classes.len() as u32, 5);
806- out.write(0, 4);994+ for _ in &bc.floor.partition_classes {
995+ out.write(0, 4);
996+ }
997+ out.write(FLOOR_CLASS_DIM as u32 - 1, 3);
998+ out.write(0, 2);
999+ out.write(1, 8);
1000+ out.write(0, 2);
1001+ let range_bits = ilog(bc.half as u32) - 1;
1002+ out.write(range_bits, 4);
1003+ for &x in bc.floor.x_list.iter().skip(2) {
1004+ out.write(x, range_bits);
1005+ }
807 }1006 }
808- out.write(FLOOR_CLASS_DIM as u32 - 1, 3);1007+ // Two residues, type 2: long first, then short, each over every channel of
809- out.write(0, 2);1008+ // its own submap and sharing the class/residue books.
810- // Book number plus one; zero would mean "this subclass codes nothing".1009+ out.write(1, 6);
811- out.write(1, 8);1010+ for bc in [long, short] {
812- out.write(0, 2);1011+ out.write(2, 16);
813- let range_bits = ilog(HALF as u32) - 1;1012+ out.write(0, 24);
814- out.write(range_bits, 4);1013+ out.write((bc.half * channels) as u32, 24);
815- for &x in floor.x_list.iter().skip(2) {1014+ out.write(bc.partition as u32 - 1, 24);
816- out.write(x, range_bits);1015+ out.write(CLASSES as u32 - 1, 6);
1016+ out.write(1, 8);
1017+ for class in 0..CLASSES {
1018+ out.write(u32::from(class > 0), 3);
1019+ out.write(0, 1);
1020+ }
1021+ for class in 1..CLASSES {
1022+ out.write(class as u32 + 1, 8);
1023+ }
817 }1024 }
818- // One residue, type 2, over every channel of the one submap.1025+ // Two mappings, type 0: mapping 0 is long (floor/residue 0), mapping 1 is
819- out.write(0, 6);1026+ // short (floor/residue 1); both couple the same channels.
820- out.write(2, 16);1027+ out.write(1, 6);
821- out.write(0, 24);1028+ for (floor, residue) in [(0u32, 0u32), (1, 1)] {
822- out.write((HALF * channels) as u32, 24);1029+ 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);1030 out.write(0, 1);
830- }1031+ match coupling.is_empty() {
831- for class in 1..CLASSES {1032+ true => out.write(0, 1),
832- out.write(class as u32 + 1, 8);1033+ false => {
833- }1034+ out.write(1, 1);
834- // One mapping, type 0.1035+ out.write(coupling.len() as u32 - 1, 8);
835- out.write(0, 6);1036+ let field = ilog(channels as u32 - 1);
836- out.write(0, 16);1037+ for &(magnitude, angle) in coupling {
837- out.write(0, 1);1038+ out.write(magnitude as u32, field);
838- match coupling.is_empty() {1039+ out.write(angle as u32, field);
839- true => out.write(0, 1),1040+ }
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 }1041 }
848 }1042 }
1043+ out.write(0, 2);
1044+ out.write(0, 8);
1045+ out.write(floor, 8);
1046+ out.write(residue, 8);
849 }1047 }
850- out.write(0, 2);1048+ // Two modes: mode `MODE_SHORT` is a short block on mapping 1, mode
851- out.write(0, 8);1049+ // `MODE_LONG` a long block on mapping 0.
852- out.write(0, 8);1050+ out.write(1, 6);
853- out.write(0, 8);1051+ out.bit(false);
854- // One mode: a long block on mapping 0.1052+ out.write(0, 16);
855- out.write(0, 6);1053+ out.write(0, 16);
856- out.write(1, 1);1054+ out.write(1, 8);
1055+ out.bit(true);
857 out.write(0, 16);1056 out.write(0, 16);
858 out.write(0, 16);1057 out.write(0, 16);
859 out.write(0, 8);1058 out.write(0, 8);
@@ -1048,4 +1247,79 @@ mod tests {
1048 }1247 }
1049 }1248 }
1050 }1249 }
1250+
1251+ /// A stationary tone never trips the transient detector: every packet
1252+ /// decodes to mode `MODE_LONG`.
1253+ #[test]
1254+ fn a_stationary_signal_uses_only_long_blocks() {
1255+ let mut enc = VorbisEncoder::new(EncoderConfig {
1256+ sample_rate: 48_000,
1257+ channels: 2,
1258+ bitrate_bps: -1,
1259+ quality: 0.6,
1260+ })
1261+ .unwrap();
1262+ let samples = 48_000usize;
1263+ let mut pcm = vec![0.0f32; samples * 2];
1264+ for i in 0..samples {
1265+ let t = i as f32 / 48_000.0;
1266+ let v = (2.0 * std::f32::consts::PI * 1_000.0 * t).sin() * 0.5;
1267+ pcm[2 * i] = v;
1268+ pcm[2 * i + 1] = v;
1269+ }
1270+ enc.push_interleaved(&pcm).unwrap();
1271+ enc.finish();
1272+ let mut modes = std::collections::HashSet::new();
1273+ loop {
1274+ match enc.next_packet() {
1275+ Ok(p) => {
1276+ let mut bits = crate::bits::Bits::new(&p.data);
1277+ assert!(!bits.bit());
1278+ modes.insert(bits.read(1));
1279+ }
1280+ Err(Error::Eof) => break,
1281+ Err(e) => panic!("{e}"),
1282+ }
1283+ }
1284+ assert_eq!(modes, std::collections::HashSet::from([MODE_LONG]));
1285+ }
1286+
1287+ /// An onset after real silence trips the detector: some packet decodes to
1288+ /// mode `MODE_SHORT`.
1289+ #[test]
1290+ fn an_onset_after_silence_uses_short_blocks() {
1291+ let mut enc = VorbisEncoder::new(EncoderConfig {
1292+ sample_rate: 44_100,
1293+ channels: 2,
1294+ bitrate_bps: -1,
1295+ quality: 0.6,
1296+ })
1297+ .unwrap();
1298+ let silence = 44_100usize;
1299+ let tone = 4_410usize;
1300+ let mut pcm = vec![0.0f32; (silence + tone) * 2];
1301+ for i in 0..tone {
1302+ let t = i as f32 / 44_100.0;
1303+ let v = (2.0 * std::f32::consts::PI * 1_000.0 * t).sin();
1304+ pcm[2 * (silence + i)] = v;
1305+ pcm[2 * (silence + i) + 1] = v;
1306+ }
1307+ enc.push_interleaved(&pcm).unwrap();
1308+ enc.finish();
1309+ let mut saw_short = false;
1310+ loop {
1311+ match enc.next_packet() {
1312+ Ok(p) => {
1313+ let mut bits = crate::bits::Bits::new(&p.data);
1314+ assert!(!bits.bit());
1315+ if bits.read(1) == MODE_SHORT {
1316+ saw_short = true;
1317+ }
1318+ }
1319+ Err(Error::Eof) => break,
1320+ Err(e) => panic!("{e}"),
1321+ }
1322+ }
1323+ assert!(saw_short, "no short block coded around the onset");
1324+ }
1051 }1325 }
crates/ec-vorbis/tests/oracle.rsmodified+66 -0
@@ -554,6 +554,72 @@ 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+ for rate in [44_100u32, 48_000] {
565+ let silence = rate as usize;
566+ let tone_len = rate as usize;
567+ let mut left = vec![0.0f32; silence + tone_len];
568+ let mut right = vec![0.0f32; silence + tone_len];
569+ for i in 0..tone_len {
570+ let t = i as f64 / f64::from(rate);
571+ let v = (2.0 * std::f64::consts::PI * 1_000.0 * t).sin() as f32;
572+ left[silence + i] = v;
573+ right[silence + i] = v;
574+ }
575+ let source = vec![left, right];
576+ let name = format!("onset-{rate}.ogg");
577+ let path = encode_to_file(&source, rate, -1, &name);
578+
579+ // The reference oracle must decode the short-block stream cleanly:
580+ // no warnings, let alone errors.
581+ let warn = Command::new("ffmpeg")
582+ .args(["-v", "warning", "-i"])
583+ .arg(&path)
584+ .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
585+ .output();
586+ if let Ok(out) = warn {
587+ assert!(
588+ out.stderr.is_empty(),
589+ "{name}: oracle decode warnings: {}",
590+ String::from_utf8_lossy(&out.stderr)
591+ );
592+ }
593+
594+ let window = |plane: &[f32], rate: u32| -> f64 {
595+ let lo = (0.90 * f64::from(rate)) as usize;
596+ let hi = ((0.995 * f64::from(rate)) as usize).min(plane.len());
597+ let lo = lo.min(hi);
598+ rms(&plane[lo..hi])
599+ };
600+ let tone_rms = {
601+ let lo = silence + rate as usize / 20;
602+ let hi = (silence + tone_len).min(silence + tone_len);
603+ rms(&source[0][lo..hi])
604+ };
605+
606+ let (ours, _) = our_decode(&path);
607+ let gap = window(&ours[0], rate);
608+ assert!(
609+ gap <= 0.002 * tone_rms,
610+ "{name}: our decode gap RMS {gap:.6} vs tone RMS {tone_rms:.6}"
611+ );
612+
613+ if let Some((theirs, _)) = ffmpeg_decode(&path) {
614+ let gap = window(&theirs[0], rate);
615+ assert!(
616+ gap <= 0.002 * tone_rms,
617+ "{name}: oracle decode gap RMS {gap:.6} vs tone RMS {tone_rms:.6}"
618+ );
619+ }
620+ }
621+}
622+
557 #[test]623 #[test]
558 fn the_rate_loop_tracks_the_target_bitrate() {624 fn the_rate_loop_tracks_the_target_bitrate() {
559 let rate = 48_000u32;625 let rate = 48_000u32;