Real block switching — short blocks eliminate pre-echo at silence→onset
Browse files at this commit63f547a6f93a5658ed886e565b0d0c3672f87b22Parent: b966d5e- feat
- real block switching — short blocks eliminate pre-echo at silence→onset
2 changed files +524 -184
- crates/ec-vorbis/src/encode.rs +458 -184
- crates/ec-vorbis/tests/oracle.rs +66 -0
crates/ec-vorbis/src/encode.rsmodified+458 -184
| @@ -10,8 +10,20 @@ | |||
| 10 | //! that comes out is the quantiser step: the residue is the spectrum divided by | 10 | //! that comes out is the quantiser step: the residue is the spectrum divided by |
| 11 | //! the floor and rounded, so headroom in dB *is* precision in bits. That is | 11 | //! the floor and rounded, so headroom in dB *is* precision in bits. That is |
| 12 | //! psychoacoustics-lite and it is stated as such — there is no tonality | 12 | //! 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 beyond | 13 | +//! 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 | //! ## Codebooks | 28 | //! ## Codebooks |
| 17 | //! | 29 | //! |
| @@ -20,9 +32,9 @@ | |||
| 20 | //! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of | 32 | //! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of |
| 21 | //! them are Huffman codes over stated distributions, built at construction and | 33 | //! them are Huffman codes over stated distributions, built at construction and |
| 22 | //! written into every stream's own setup header — which is why this encoder | 34 | //! 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 of | 181 | + 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 = floor | 232 | + let long = build_block_config(HALF_LONG, PARTITION_LONG, FLOOR_POINTS_LONG, &config); |
| 160 | - .x_list | 233 | + 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 is | 260 | + 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.mdct | 500 | + 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,35 +568,62 @@ 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 to | 572 | + 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 | ||
| 588 | + /// Move the headroom so the running bitrate meets the target. | ||
| 589 | + /// | ||
| 590 | + /// One dB of headroom is about one sixth of a bit per coefficient, so the | ||
| 591 | + /// step is the bit error divided by that — a proportional loop that settles | ||
| 592 | + /// within a few blocks and is clamped either side so a transient cannot | ||
| 593 | + /// swing the whole file. The target itself scales with this block's own | ||
| 594 | + /// granule advance, so a short block (a small fraction of a long hop) is | ||
| 595 | + /// judged against a proportionally small bit budget. | ||
| 596 | + fn update_rate(&mut self, bits: u64, half: usize, channels: usize, delta: i64) { | ||
| 597 | + if self.config.bitrate_bps <= 0 || delta <= 0 { | ||
| 598 | + return; | ||
| 599 | + } | ||
| 600 | + let target = f64::from(self.config.bitrate_bps) * delta as f64 / f64::from(self.config.sample_rate); | ||
| 601 | + let coefficients = (half * channels) as f64; | ||
| 602 | + let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0); | ||
| 603 | + // Negative headroom is not a mistake: it puts the floor *above* the | ||
| 604 | + // signal, which quantises the coefficients under it to zero and lets a | ||
| 605 | + // whole partition become class 0 for two bits. Without that a low target | ||
| 606 | + // cannot be reached at all — coding every coefficient with the shortest | ||
| 607 | + // codeword there is already costs about a bit each. | ||
| 608 | + self.headroom = (self.headroom + step).clamp(-24.0, 36.0); | ||
| 609 | + } | ||
| 610 | +} | ||
| 611 | + | ||
| 423 | /// Peak magnitude around each floor X point, over every channel given. | 612 | /// Peak magnitude around each floor X point, over every channel given. |
| 424 | /// | 613 | /// |
| 425 | - /// Each point owns the coefficients halfway to its neighbours either side, | 614 | +/// Each point owns the coefficients halfway to its neighbours either side, so |
| 426 | - /// so the whole spectrum is covered exactly once and a peak between two | 615 | +/// the whole spectrum is covered exactly once and a peak between two points |
| 427 | - /// points still raises the floor that has to carry it. | 616 | +/// still raises the floor that has to carry it. |
| 428 | - fn peaks_of(&self, spectra: &[&Vec<f32>]) -> Vec<f64> { | 617 | +fn peaks_of(floor: &Floor1, half: usize, spectra: &[&Vec<f32>]) -> Vec<f64> { |
| 429 | - let x = &self.floor.x_list; | 618 | + let x = &floor.x_list; |
| 430 | x.iter() | 619 | x.iter() |
| 431 | .map(|¢re| { | 620 | .map(|¢re| { |
| 432 | let below = x.iter().filter(|&&o| o < centre).max().copied(); | 621 | let below = x.iter().filter(|&&o| o < centre).max().copied(); |
| 433 | let above = x.iter().filter(|&&o| o > centre).min().copied(); | 622 | let above = x.iter().filter(|&&o| o > centre).min().copied(); |
| 434 | let lo = below.map_or(0, |b| ((b + centre) / 2) as usize); | 623 | 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); | 624 | + let hi = above.map_or(half, |a| ((a + centre) / 2) as usize + 1); |
| 436 | - let lo = lo.min(HALF - 1); | 625 | + let lo = lo.min(half - 1); |
| 437 | - let hi = hi.clamp(lo + 1, HALF); | 626 | + let hi = hi.clamp(lo + 1, half); |
| 438 | let mut peak = 0.0f64; | 627 | let mut peak = 0.0f64; |
| 439 | for spectrum in spectra { | 628 | for spectrum in spectra { |
| 440 | for &value in &spectrum[lo..hi] { | 629 | for &value in &spectrum[lo..hi] { |
| @@ -452,13 +641,12 @@ impl VorbisEncoder { | |||
| 452 | /// loop's headroom, then hold the absolute threshold of hearing as a lower | 641 | /// loop's headroom, then hold the absolute threshold of hearing as a lower |
| 453 | /// bound: below it the residue quantises to zero and costs a class-0 | 642 | /// bound: below it the residue quantises to zero and costs a class-0 |
| 454 | /// partition. | 643 | /// partition. |
| 455 | - fn fit_floor(&self, peaks: &[f64]) -> (Vec<i32>, Vec<bool>) { | 644 | +fn fit_floor(floor: &Floor1, ath: &[f64], headroom: f64, peaks: &[f64]) -> (Vec<i32>, Vec<bool>) { |
| 456 | let mut db: Vec<f64> = peaks | 645 | let mut db: Vec<f64> = peaks |
| 457 | .iter() | 646 | .iter() |
| 458 | .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) | 647 | .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) |
| 459 | .collect(); | 648 | .collect(); |
| 460 | - // Frequency order, not coding order: spreading is a fact about the ear. | 649 | + let order = &floor.sorted; |
| 461 | - let order = &self.floor.sorted; | ||
| 462 | for window in order.windows(2) { | 650 | for window in order.windows(2) { |
| 463 | let (previous, current) = (window[0], window[1]); | 651 | let (previous, current) = (window[0], window[1]); |
| 464 | db[current] = db[current].max(db[previous] - 12.0); | 652 | db[current] = db[current].max(db[previous] - 12.0); |
| @@ -469,19 +657,19 @@ impl VorbisEncoder { | |||
| 469 | } | 657 | } |
| 470 | let target: Vec<f64> = db | 658 | let target: Vec<f64> = db |
| 471 | .iter() | 659 | .iter() |
| 472 | - .zip(self.ath.iter()) | 660 | + .zip(ath.iter()) |
| 473 | - .map(|(&level, &threshold)| (level - self.headroom).max(threshold)) | 661 | + .map(|(&level, &threshold)| (level - headroom).max(threshold)) |
| 474 | .collect(); | 662 | .collect(); |
| 475 | let y: Vec<i32> = target | 663 | let y: Vec<i32> = target |
| 476 | .iter() | 664 | .iter() |
| 477 | .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255)) | 665 | .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255)) |
| 478 | .collect(); | 666 | .collect(); |
| 479 | - self.fold_floor(&y) | 667 | + fold_floor(floor, &y) |
| 480 | } | 668 | } |
| 481 | 669 | ||
| 482 | /// Run the decoder's own amplitude synthesis forwards, so the curve the | 670 | /// Run the decoder's own amplitude synthesis forwards, so the curve the |
| 483 | /// encoder normalises against is the curve the decoder will draw. | 671 | /// encoder normalises against is the curve the decoder will draw. |
| 484 | - fn fold_floor(&self, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) { | 672 | +fn fold_floor(floor: &Floor1, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) { |
| 485 | let values = wanted.len(); | 673 | let values = wanted.len(); |
| 486 | let range = 256i32; | 674 | let range = 256i32; |
| 487 | let mut final_y = vec![0i32; values]; | 675 | let mut final_y = vec![0i32; values]; |
| @@ -491,13 +679,13 @@ impl VorbisEncoder { | |||
| 491 | step2[0] = true; | 679 | step2[0] = true; |
| 492 | step2[1] = true; | 680 | step2[1] = true; |
| 493 | for i in 2..values { | 681 | for i in 2..values { |
| 494 | - let (low, high) = self.floor.neighbours[i]; | 682 | + let (low, high) = floor.neighbours[i]; |
| 495 | let predicted = predict( | 683 | let predicted = predict( |
| 496 | - self.floor.x_list[low], | 684 | + floor.x_list[low], |
| 497 | final_y[low], | 685 | final_y[low], |
| 498 | - self.floor.x_list[high], | 686 | + floor.x_list[high], |
| 499 | final_y[high], | 687 | final_y[high], |
| 500 | - self.floor.x_list[i], | 688 | + floor.x_list[i], |
| 501 | ); | 689 | ); |
| 502 | let value = fold(predicted, wanted[i], range); | 690 | let value = fold(predicted, wanted[i], range); |
| 503 | if value != 0 { | 691 | if value != 0 { |
| @@ -510,39 +698,46 @@ impl VorbisEncoder { | |||
| 510 | (final_y, step2) | 698 | (final_y, step2) |
| 511 | } | 699 | } |
| 512 | 700 | ||
| 513 | - /// Write one channel's floor: the two endpoints raw, the rest folded | 701 | +/// Write one channel's floor: the two endpoints raw, the rest folded against |
| 514 | - /// against their neighbours and Huffman coded. | 702 | +/// their neighbours and Huffman coded. |
| 515 | - fn write_floor(&self, out: &mut BitsOut, y: &[i32]) { | 703 | +fn write_floor(out: &mut BitsOut, floor: &Floor1, floor_book: &CodebookSpec, y: &[i32]) { |
| 516 | out.bit(true); | 704 | out.bit(true); |
| 517 | out.write(y[0] as u32, 8); | 705 | out.write(y[0] as u32, 8); |
| 518 | out.write(y[1] as u32, 8); | 706 | out.write(y[1] as u32, 8); |
| 519 | for i in 2..y.len() { | 707 | for i in 2..y.len() { |
| 520 | - let (low, high) = self.floor.neighbours[i]; | 708 | + let (low, high) = floor.neighbours[i]; |
| 521 | let predicted = predict( | 709 | let predicted = predict( |
| 522 | - self.floor.x_list[low], | 710 | + floor.x_list[low], |
| 523 | y[low], | 711 | y[low], |
| 524 | - self.floor.x_list[high], | 712 | + floor.x_list[high], |
| 525 | y[high], | 713 | y[high], |
| 526 | - self.floor.x_list[i], | 714 | + floor.x_list[i], |
| 527 | ); | 715 | ); |
| 528 | let value = fold(predicted, y[i], 256); | 716 | let value = fold(predicted, y[i], 256); |
| 529 | - self.floor_book.write(out, value as usize); | 717 | + floor_book.write(out, value as usize); |
| 530 | } | 718 | } |
| 531 | } | 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( |
| 724 | + out: &mut BitsOut, | ||
| 725 | + quantised: &[Vec<i32>], | ||
| 726 | + half: usize, | ||
| 727 | + partition: usize, | ||
| 728 | + class_book: &CodebookSpec, | ||
| 729 | + residue_books: &[CodebookSpec], | ||
| 730 | +) { | ||
| 536 | let channels = quantised.len(); | 731 | let channels = quantised.len(); |
| 537 | - let total = HALF * channels; | 732 | + let total = half * channels; |
| 538 | let mut interleaved = vec![0i32; total]; | 733 | let mut interleaved = vec![0i32; total]; |
| 539 | for (i, slot) in interleaved.iter_mut().enumerate() { | 734 | for (i, slot) in interleaved.iter_mut().enumerate() { |
| 540 | *slot = quantised[i % channels][i / channels]; | 735 | *slot = quantised[i % channels][i / channels]; |
| 541 | } | 736 | } |
| 542 | - let partitions = total / PARTITION; | 737 | + let partitions = total / partition; |
| 543 | let classes: Vec<usize> = (0..partitions) | 738 | let classes: Vec<usize> = (0..partitions) |
| 544 | - .map(|partition| { | 739 | + .map(|p| { |
| 545 | - let slice = &interleaved[partition * PARTITION..(partition + 1) * PARTITION]; | 740 | + let slice = &interleaved[p * partition..(p + 1) * partition]; |
| 546 | let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0); | 741 | let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0); |
| 547 | CLASS_RANGE | 742 | CLASS_RANGE |
| 548 | .iter() | 743 | .iter() |
| @@ -550,54 +745,31 @@ impl VorbisEncoder { | |||
| 550 | .unwrap_or(CLASSES - 1) | 745 | .unwrap_or(CLASSES - 1) |
| 551 | }) | 746 | }) |
| 552 | .collect(); | 747 | .collect(); |
| 553 | - let per_word = self.class_book.dimensions; | 748 | + let per_word = class_book.dimensions; |
| 554 | - let mut partition = 0usize; | 749 | + let mut p = 0usize; |
| 555 | - while partition < partitions { | 750 | + while p < partitions { |
| 556 | let mut word = 0usize; | 751 | let mut word = 0usize; |
| 557 | for i in 0..per_word { | 752 | for i in 0..per_word { |
| 558 | - word = word * CLASSES + classes.get(partition + i).copied().unwrap_or(0); | 753 | + word = word * CLASSES + classes.get(p + i).copied().unwrap_or(0); |
| 559 | } | 754 | } |
| 560 | - self.class_book.write(out, word); | 755 | + class_book.write(out, word); |
| 561 | for _ in 0..per_word { | 756 | for _ in 0..per_word { |
| 562 | - if partition >= partitions { | 757 | + if p >= partitions { |
| 563 | break; | 758 | break; |
| 564 | } | 759 | } |
| 565 | - let class = classes[partition]; | 760 | + let class = classes[p]; |
| 566 | if class > 0 { | 761 | if class > 0 { |
| 567 | - let book = &self.residue_books[class - 1]; | 762 | + let book = &residue_books[class - 1]; |
| 568 | let range = CLASS_RANGE[class]; | 763 | let range = CLASS_RANGE[class]; |
| 569 | - for &value in &interleaved[partition * PARTITION..(partition + 1) * PARTITION] { | 764 | + for &value in &interleaved[p * partition..(p + 1) * partition] { |
| 570 | book.write(out, (value.clamp(-range, range) + range) as usize); | 765 | book.write(out, (value.clamp(-range, range) + range) as usize); |
| 571 | } | 766 | } |
| 572 | } | 767 | } |
| 573 | - partition += 1; | 768 | + p += 1; |
| 574 | } | 769 | } |
| 575 | } | 770 | } |
| 576 | } | 771 | } |
| 577 | 772 | ||
| 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 | -} | ||
| 600 | - | ||
| 601 | /// Forward square-polar coupling (§9.4.2 run backwards). | 773 | /// Forward square-polar coupling (§9.4.2 run backwards). |
| 602 | fn couple(left: i32, right: i32) -> (i32, i32) { | 774 | fn couple(left: i32, right: i32) -> (i32, i32) { |
| 603 | match left > 0 { | 775 | match left > 0 { |
| @@ -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 the | 828 | // 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 is | 834 | // 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 escape | 897 | /// 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,41 +986,46 @@ 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); |
| 991 | + for bc in [long, short] { | ||
| 803 | out.write(1, 16); | 992 | out.write(1, 16); |
| 804 | - out.write(floor.partition_classes.len() as u32, 5); | 993 | + out.write(bc.floor.partition_classes.len() as u32, 5); |
| 805 | - for _ in &floor.partition_classes { | 994 | + for _ in &bc.floor.partition_classes { |
| 806 | out.write(0, 4); | 995 | out.write(0, 4); |
| 807 | } | 996 | } |
| 808 | out.write(FLOOR_CLASS_DIM as u32 - 1, 3); | 997 | out.write(FLOOR_CLASS_DIM as u32 - 1, 3); |
| 809 | out.write(0, 2); | 998 | out.write(0, 2); |
| 810 | - // Book number plus one; zero would mean "this subclass codes nothing". | ||
| 811 | out.write(1, 8); | 999 | out.write(1, 8); |
| 812 | out.write(0, 2); | 1000 | out.write(0, 2); |
| 813 | - let range_bits = ilog(HALF as u32) - 1; | 1001 | + let range_bits = ilog(bc.half as u32) - 1; |
| 814 | out.write(range_bits, 4); | 1002 | out.write(range_bits, 4); |
| 815 | - for &x in floor.x_list.iter().skip(2) { | 1003 | + for &x in bc.floor.x_list.iter().skip(2) { |
| 816 | out.write(x, range_bits); | 1004 | out.write(x, range_bits); |
| 817 | } | 1005 | } |
| 818 | - // One residue, type 2, over every channel of the one submap. | 1006 | + } |
| 819 | - out.write(0, 6); | 1007 | + // Two residues, type 2: long first, then short, each over every channel of |
| 1008 | + // its own submap and sharing the class/residue books. | ||
| 1009 | + out.write(1, 6); | ||
| 1010 | + for bc in [long, short] { | ||
| 820 | out.write(2, 16); | 1011 | out.write(2, 16); |
| 821 | out.write(0, 24); | 1012 | out.write(0, 24); |
| 822 | - out.write((HALF * channels) as u32, 24); | 1013 | + out.write((bc.half * channels) as u32, 24); |
| 823 | - out.write(PARTITION as u32 - 1, 24); | 1014 | + out.write(bc.partition as u32 - 1, 24); |
| 824 | out.write(CLASSES as u32 - 1, 6); | 1015 | out.write(CLASSES as u32 - 1, 6); |
| 825 | out.write(1, 8); | 1016 | out.write(1, 8); |
| 826 | for class in 0..CLASSES { | 1017 | 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); | 1018 | out.write(u32::from(class > 0), 3); |
| 829 | out.write(0, 1); | 1019 | out.write(0, 1); |
| 830 | } | 1020 | } |
| 831 | for class in 1..CLASSES { | 1021 | for class in 1..CLASSES { |
| 832 | out.write(class as u32 + 1, 8); | 1022 | out.write(class as u32 + 1, 8); |
| 833 | } | 1023 | } |
| 834 | - // One mapping, type 0. | 1024 | + } |
| 835 | - out.write(0, 6); | 1025 | + // Two mappings, type 0: mapping 0 is long (floor/residue 0), mapping 1 is |
| 1026 | + // short (floor/residue 1); both couple the same channels. | ||
| 1027 | + out.write(1, 6); | ||
| 1028 | + for (floor, residue) in [(0u32, 0u32), (1, 1)] { | ||
| 836 | out.write(0, 16); | 1029 | out.write(0, 16); |
| 837 | out.write(0, 1); | 1030 | out.write(0, 1); |
| 838 | match coupling.is_empty() { | 1031 | match coupling.is_empty() { |
| @@ -849,11 +1042,17 @@ fn write_headers( | |||
| 849 | } | 1042 | } |
| 850 | out.write(0, 2); | 1043 | out.write(0, 2); |
| 851 | out.write(0, 8); | 1044 | out.write(0, 8); |
| 852 | - out.write(0, 8); | 1045 | + out.write(floor, 8); |
| 853 | - out.write(0, 8); | 1046 | + out.write(residue, 8); |
| 854 | - // One mode: a long block on mapping 0. | 1047 | + } |
| 855 | - out.write(0, 6); | 1048 | + // Two modes: mode `MODE_SHORT` is a short block on mapping 1, mode |
| 856 | - out.write(1, 1); | 1049 | + // `MODE_LONG` a long block on mapping 0. |
| 1050 | + out.write(1, 6); | ||
| 1051 | + out.bit(false); | ||
| 1052 | + out.write(0, 16); | ||
| 1053 | + out.write(0, 16); | ||
| 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; |