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 +650 -310
- crates/ec-vorbis/src/encode.rs +584 -310
- crates/ec-vorbis/tests/oracle.rs +66 -0
crates/ec-vorbis/src/encode.rsmodified+584 -310
| @@ -10,8 +10,20 @@ | ||
| 10 | 10 | //! that comes out is the quantiser step: the residue is the spectrum divided by |
| 11 | 11 | //! the floor and rounded, so headroom in dB *is* precision in bits. That is |
| 12 | 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 | |
| 14 | -//! what the floor implies. | |
| 13 | +//! estimate beyond a two-mode block switch and no per-band bit allocation | |
| 14 | +//! beyond what the floor implies. | |
| 15 | +//! | |
| 16 | +//! ## Block switching (§1.3.2 / §4.3) | |
| 17 | +//! | |
| 18 | +//! Two modes: a 256-sample short block and a 2048-sample long block. Steady | |
| 19 | +//! content codes long blocks only. A transient — energy in a 128-sample tick | |
| 20 | +//! jumping past its predecessor, which is also what an onset after digital | |
| 21 | +//! silence looks like — swaps one pair of would-be long blocks for a | |
| 22 | +//! long-with-short-right-window (the block that would otherwise carry the | |
| 23 | +//! pre-echo), eight short blocks spanning the transient itself, and a | |
| 24 | +//! long-with-short-left-window resuming steady state. The granule advance | |
| 25 | +//! across that whole run is exactly two long hops, so the switch never moves | |
| 26 | +//! the steady-state grid. | |
| 15 | 27 | //! |
| 16 | 28 | //! ## Codebooks |
| 17 | 29 | //! |
| @@ -20,9 +32,9 @@ | ||
| 20 | 32 | //! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of |
| 21 | 33 | //! them are Huffman codes over stated distributions, built at construction and |
| 22 | 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. | |
| 24 | - | |
| 25 | -use std::collections::VecDeque; | |
| 35 | +//! needs no embedded profile and has no channel count it cannot serve. Both | |
| 36 | +//! block sizes share these books; only the floor's X grid and the residue's | |
| 37 | +//! partition size are sized per block. | |
| 26 | 38 | |
| 27 | 39 | use ec_core::{ |
| 28 | 40 | AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet, |
| @@ -35,29 +47,55 @@ use crate::codebook::{CodebookSpec, ilog}; | ||
| 35 | 47 | use crate::decode::channel_map; |
| 36 | 48 | use crate::floor::render_floor1; |
| 37 | 49 | use crate::setup::Floor1; |
| 38 | -use crate::window; | |
| 39 | - | |
| 40 | -/// Long block size; this encoder codes long blocks only. | |
| 41 | -const BLOCK: usize = 2048; | |
| 42 | -/// Samples between block centres. | |
| 43 | -const HOP: usize = BLOCK / 2; | |
| 44 | -/// Coefficients per block. | |
| 45 | -const HALF: usize = BLOCK / 2; | |
| 46 | -/// Coefficients per residue partition. | |
| 47 | -const PARTITION: usize = 32; | |
| 48 | -/// Floor X points besides the two endpoints. | |
| 49 | -const FLOOR_POINTS: usize = 20; | |
| 50 | +use crate::window::Windows; | |
| 51 | + | |
| 52 | +/// Long block size. | |
| 53 | +const BLOCK_LONG: usize = 2048; | |
| 54 | +/// Short block size. | |
| 55 | +const BLOCK_SHORT: usize = 256; | |
| 56 | +/// Coefficients in a long block. | |
| 57 | +const HALF_LONG: usize = BLOCK_LONG / 2; | |
| 58 | +/// Coefficients in a short block. | |
| 59 | +const HALF_SHORT: usize = BLOCK_SHORT / 2; | |
| 60 | +/// Long-block coefficients per residue partition. | |
| 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 | 68 | /// Floor values per class. |
| 51 | 69 | const FLOOR_CLASS_DIM: usize = 4; |
| 52 | 70 | /// Residue classes; class 0 codes nothing at all. |
| 53 | 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 | 72 | /// Largest quantised residue each class's book can state. |
| 60 | 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 | 100 | /// How the encoder is set up. |
| 63 | 101 | #[derive(Debug, Clone, Copy, PartialEq)] |
| @@ -95,6 +133,35 @@ pub struct EncodedPacket { | ||
| 95 | 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 | 165 | /// Vorbis I encoder. |
| 99 | 166 | pub struct VorbisEncoder { |
| 100 | 167 | config: EncoderConfig, |
| @@ -102,29 +169,36 @@ pub struct VorbisEncoder { | ||
| 102 | 169 | /// `to_vorbis[ec channel] = vorbis channel`. |
| 103 | 170 | to_vorbis: Vec<usize>, |
| 104 | 171 | headers: Vec<Vec<u8>>, |
| 105 | - floor: Floor1, | |
| 172 | + long: BlockConfig, | |
| 173 | + short: BlockConfig, | |
| 106 | 174 | floor_book: CodebookSpec, |
| 107 | 175 | class_book: CodebookSpec, |
| 108 | 176 | residue_books: Vec<CodebookSpec>, |
| 109 | - /// Absolute threshold of hearing per floor point, in dBFS. | |
| 110 | - ath: Vec<f64>, | |
| 111 | 177 | /// Channel pairs coupled by the mapping; empty unless stereo. |
| 112 | 178 | coupling: Vec<(usize, usize)>, |
| 113 | - mdct: Mdct<f32>, | |
| 114 | - window: Vec<f32>, | |
| 115 | - /// Per Vorbis channel, input samples with the first block's left half of | |
| 116 | - /// zeroes already in front. | |
| 179 | + mdct_long: Mdct<f32>, | |
| 180 | + mdct_short: Mdct<f32>, | |
| 181 | + windows: Windows, | |
| 182 | + /// Per Vorbis channel, input samples with [`PREROLL`] zeroes already in | |
| 183 | + /// front. | |
| 117 | 184 | buffer: Vec<Vec<f32>>, |
| 118 | 185 | /// Input samples taken from the caller. |
| 119 | 186 | fed: i64, |
| 120 | 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 | 195 | /// Granule of the packet emitted last. |
| 123 | 196 | granule: i64, |
| 197 | + scheduler: Sched, | |
| 124 | 198 | /// Headroom under the masking curve, in dB — the rate loop's variable. |
| 125 | 199 | headroom: f64, |
| 126 | 200 | finished: bool, |
| 127 | - packets: VecDeque<EncodedPacket>, | |
| 201 | + packets: std::collections::VecDeque<EncodedPacket>, | |
| 128 | 202 | } |
| 129 | 203 | |
| 130 | 204 | impl VorbisEncoder { |
| @@ -152,23 +226,17 @@ impl VorbisEncoder { | ||
| 152 | 226 | _ => Vec::new(), |
| 153 | 227 | }; |
| 154 | 228 | |
| 155 | - let floor = build_floor(); | |
| 156 | 229 | let floor_book = design_floor_book(); |
| 157 | 230 | let class_book = design_class_book(); |
| 158 | 231 | let residue_books = design_residue_books(); |
| 159 | - let ath = floor | |
| 160 | - .x_list | |
| 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(); | |
| 232 | + let long = build_block_config(HALF_LONG, PARTITION_LONG, FLOOR_POINTS_LONG, &config); | |
| 233 | + let short = build_block_config(HALF_SHORT, PARTITION_SHORT, FLOOR_POINTS_SHORT, &config); | |
| 167 | 234 | |
| 168 | 235 | let headers = write_headers( |
| 169 | 236 | &config, |
| 170 | 237 | channels, |
| 171 | - &floor, | |
| 238 | + &long, | |
| 239 | + &short, | |
| 172 | 240 | &floor_book, |
| 173 | 241 | &class_book, |
| 174 | 242 | &residue_books, |
| @@ -187,26 +255,28 @@ impl VorbisEncoder { | ||
| 187 | 255 | |
| 188 | 256 | let quality = f64::from(config.quality.clamp(0.0, 1.0)); |
| 189 | 257 | Ok(VorbisEncoder { |
| 190 | - mdct: Mdct::new(BLOCK), | |
| 191 | - window: window::build(BLOCK, BLOCK, true, true), | |
| 192 | - // The first block is centred on input sample 0, so its left half is | |
| 193 | - // the only pre-roll there is and the caller never sees it. | |
| 194 | - buffer: vec![vec![0.0; HOP]; channels], | |
| 258 | + mdct_long: Mdct::new(BLOCK_LONG), | |
| 259 | + mdct_short: Mdct::new(BLOCK_SHORT), | |
| 260 | + windows: Windows::new(BLOCK_SHORT, BLOCK_LONG), | |
| 261 | + buffer: vec![vec![0.0; PREROLL]; channels], | |
| 195 | 262 | fed: 0, |
| 196 | - blocks: 0, | |
| 263 | + blocks_emitted: 0, | |
| 264 | + centre: -(HALF_LONG as i64), | |
| 265 | + prev_n: BLOCK_LONG, | |
| 197 | 266 | granule: 0, |
| 267 | + scheduler: Sched::Steady, | |
| 198 | 268 | headroom: 4.0 + 26.0 * quality, |
| 199 | 269 | finished: false, |
| 200 | - packets: VecDeque::new(), | |
| 270 | + packets: std::collections::VecDeque::new(), | |
| 201 | 271 | config, |
| 202 | 272 | params, |
| 203 | 273 | to_vorbis, |
| 204 | 274 | headers, |
| 205 | - floor, | |
| 275 | + long, | |
| 276 | + short, | |
| 206 | 277 | floor_book, |
| 207 | 278 | class_book, |
| 208 | 279 | residue_books, |
| 209 | - ath, | |
| 210 | 280 | coupling, |
| 211 | 281 | }) |
| 212 | 282 | } |
| @@ -273,10 +343,11 @@ impl VorbisEncoder { | ||
| 273 | 343 | return; |
| 274 | 344 | } |
| 275 | 345 | self.finished = true; |
| 276 | - // Enough blocks for every input sample to sit left of a block centre, | |
| 277 | - // and enough padding for that last block to be whole. | |
| 278 | - let last = ((self.fed + HOP as i64 - 1) / HOP as i64).max(1) as usize; | |
| 279 | - let needed = last * HOP + BLOCK; | |
| 346 | + // Generous padding: a long block's own half plus a whole short-run's | |
| 347 | + // worth of slack, so whatever the scheduler is doing when the input | |
| 348 | + // runs out still finds real (zero) samples rather than the buffer's | |
| 349 | + // edge. | |
| 350 | + let needed = PREROLL + self.fed.max(0) as usize + 2 * BLOCK_LONG; | |
| 280 | 351 | for channel in &mut self.buffer { |
| 281 | 352 | if channel.len() < needed { |
| 282 | 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 | 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 | 445 | fn encode_ready(&mut self) { |
| 304 | 446 | let channels = usize::from(self.config.channels); |
| 305 | 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 | 449 | break; |
| 308 | 450 | } |
| 309 | - let start = self.blocks as usize * HOP; | |
| 310 | - if self.buffer[0].len() < start + BLOCK { | |
| 451 | + let plan = self.peek_plan(); | |
| 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 | 458 | break; |
| 312 | 459 | } |
| 313 | - let centre = self.blocks * HOP as i64; | |
| 314 | 460 | let granule = match self.finished { |
| 315 | 461 | true => centre.min(self.fed), |
| 316 | 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 | 465 | self.packets.push_back(EncodedPacket { |
| 320 | 466 | data, |
| 321 | 467 | granule, |
| 322 | 468 | samples: (granule - self.granule).max(0), |
| 323 | 469 | }); |
| 324 | 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 | 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 | 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 | 497 | for channel in 0..channels { |
| 334 | - block.copy_from_slice(&self.buffer[channel][start..start + BLOCK]); | |
| 335 | - let mut coefficients = vec![0.0f32; HALF]; | |
| 336 | - self.mdct | |
| 337 | - .forward_windowed(&block, &self.window, &mut coefficients); | |
| 498 | + block.copy_from_slice(&self.buffer[channel][start..start + n]); | |
| 499 | + let mut coefficients = vec![0.0f32; half]; | |
| 500 | + let mdct = if plan.is_long { &mut self.mdct_long } else { &mut self.mdct_short }; | |
| 501 | + mdct.forward_windowed(&block, &window, &mut coefficients); | |
| 338 | 502 | for value in coefficients.iter_mut() { |
| 339 | - *value *= VORBIS_MDCT_SCALE; | |
| 503 | + *value *= scale; | |
| 340 | 504 | } |
| 341 | 505 | spectra.push(coefficients); |
| 342 | 506 | } |
| @@ -348,10 +512,10 @@ impl VorbisEncoder { | ||
| 348 | 512 | let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels]; |
| 349 | 513 | let mut coded = vec![false; channels]; |
| 350 | 514 | for &(magnitude, angle) in &self.coupling { |
| 351 | - let peaks = self.peaks_of(&[&spectra[magnitude], &spectra[angle]]); | |
| 352 | - let (y, step2) = self.fit_floor(&peaks); | |
| 353 | - let mut curve = vec![0.0f32; HALF]; | |
| 354 | - render_floor1(&self.floor, &y, &step2, &mut curve); | |
| 515 | + let peaks = peaks_of(&bc.floor, half, &[&spectra[magnitude], &spectra[angle]]); | |
| 516 | + let (y, step2) = fit_floor(&bc.floor, &bc.ath, self.headroom, &peaks); | |
| 517 | + let mut curve = vec![0.0f32; half]; | |
| 518 | + render_floor1(&bc.floor, &y, &step2, &mut curve); | |
| 355 | 519 | curves[magnitude] = curve.clone(); |
| 356 | 520 | curves[angle] = curve; |
| 357 | 521 | floor_values[magnitude] = y.clone(); |
| @@ -363,10 +527,10 @@ impl VorbisEncoder { | ||
| 363 | 527 | if coded[channel] { |
| 364 | 528 | continue; |
| 365 | 529 | } |
| 366 | - let peaks = self.peaks_of(&[&spectra[channel]]); | |
| 367 | - let (y, step2) = self.fit_floor(&peaks); | |
| 368 | - let mut curve = vec![0.0f32; HALF]; | |
| 369 | - render_floor1(&self.floor, &y, &step2, &mut curve); | |
| 530 | + let peaks = peaks_of(&bc.floor, half, &[&spectra[channel]]); | |
| 531 | + let (y, step2) = fit_floor(&bc.floor, &bc.ath, self.headroom, &peaks); | |
| 532 | + let mut curve = vec![0.0f32; half]; | |
| 533 | + render_floor1(&bc.floor, &y, &step2, &mut curve); | |
| 370 | 534 | curves[channel] = curve; |
| 371 | 535 | floor_values[channel] = y; |
| 372 | 536 | } |
| @@ -386,8 +550,6 @@ impl VorbisEncoder { | ||
| 386 | 550 | }) |
| 387 | 551 | .collect(); |
| 388 | 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 | 553 | let mut left = std::mem::take(&mut quantised[magnitude]); |
| 392 | 554 | let mut right = std::mem::take(&mut quantised[angle]); |
| 393 | 555 | for (l, r) in left.iter_mut().zip(right.iter_mut()) { |
| @@ -406,196 +568,206 @@ impl VorbisEncoder { | ||
| 406 | 568 | } |
| 407 | 569 | |
| 408 | 570 | let mut out = BitsOut::new(); |
| 409 | - out.write(0, 1); | |
| 410 | - // One mode means `ilog(modes - 1)` is zero bits: there is nothing to | |
| 411 | - // state. The two window flags follow because the mode is a long block. | |
| 412 | - out.bit(true); | |
| 413 | - out.bit(true); | |
| 571 | + out.bit(false); | |
| 572 | + let mode = if plan.is_long { MODE_LONG } else { MODE_SHORT }; | |
| 573 | + out.write(mode, 1); | |
| 574 | + if plan.is_long { | |
| 575 | + out.bit(plan.prev_long); | |
| 576 | + out.bit(plan.next_long); | |
| 577 | + } | |
| 414 | 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 | 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 | 585 | out.finish() |
| 421 | 586 | } |
| 422 | 587 | |
| 423 | - /// Peak magnitude around each floor X point, over every channel given. | |
| 424 | - /// | |
| 425 | - /// Each point owns the coefficients halfway to its neighbours either side, | |
| 426 | - /// so the whole spectrum is covered exactly once and a peak between two | |
| 427 | - /// points still raises the floor that has to carry it. | |
| 428 | - fn peaks_of(&self, spectra: &[&Vec<f32>]) -> Vec<f64> { | |
| 429 | - let x = &self.floor.x_list; | |
| 430 | - x.iter() | |
| 431 | - .map(|¢re| { | |
| 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. | |
| 588 | + /// Move the headroom so the running bitrate meets the target. | |
| 450 | 589 | /// |
| 451 | - /// Spread first (a masker covers its neighbours), then subtract the rate | |
| 452 | - /// 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 | |
| 454 | - /// partition. | |
| 455 | - fn fit_floor(&self, peaks: &[f64]) -> (Vec<i32>, Vec<bool>) { | |
| 456 | - let mut db: Vec<f64> = peaks | |
| 457 | - .iter() | |
| 458 | - .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) | |
| 459 | - .collect(); | |
| 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); | |
| 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; | |
| 469 | 599 | } |
| 470 | - let target: Vec<f64> = db | |
| 471 | - .iter() | |
| 472 | - .zip(self.ath.iter()) | |
| 473 | - .map(|(&level, &threshold)| (level - self.headroom).max(threshold)) | |
| 474 | - .collect(); | |
| 475 | - let y: Vec<i32> = target | |
| 476 | - .iter() | |
| 477 | - .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255)) | |
| 478 | - .collect(); | |
| 479 | - self.fold_floor(&y) | |
| 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); | |
| 480 | 609 | } |
| 610 | +} | |
| 481 | 611 | |
| 482 | - /// Run the decoder's own amplitude synthesis forwards, so the curve the | |
| 483 | - /// encoder normalises against is the curve the decoder will draw. | |
| 484 | - fn fold_floor(&self, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) { | |
| 485 | - let values = wanted.len(); | |
| 486 | - let range = 256i32; | |
| 487 | - let mut final_y = vec![0i32; values]; | |
| 488 | - let mut step2 = vec![false; values]; | |
| 489 | - final_y[0] = wanted[0]; | |
| 490 | - final_y[1] = wanted[1]; | |
| 491 | - step2[0] = true; | |
| 492 | - step2[1] = true; | |
| 493 | - for i in 2..values { | |
| 494 | - let (low, high) = self.floor.neighbours[i]; | |
| 495 | - let predicted = predict( | |
| 496 | - self.floor.x_list[low], | |
| 497 | - final_y[low], | |
| 498 | - self.floor.x_list[high], | |
| 499 | - final_y[high], | |
| 500 | - self.floor.x_list[i], | |
| 501 | - ); | |
| 502 | - let value = fold(predicted, wanted[i], range); | |
| 503 | - if value != 0 { | |
| 504 | - step2[low] = true; | |
| 505 | - step2[high] = true; | |
| 506 | - step2[i] = true; | |
| 612 | +/// Peak magnitude around each floor X point, over every channel given. | |
| 613 | +/// | |
| 614 | +/// Each point owns the coefficients halfway to its neighbours either side, so | |
| 615 | +/// the whole spectrum is covered exactly once and a peak between two points | |
| 616 | +/// still raises the floor that has to carry it. | |
| 617 | +fn peaks_of(floor: &Floor1, half: usize, spectra: &[&Vec<f32>]) -> Vec<f64> { | |
| 618 | + let x = &floor.x_list; | |
| 619 | + x.iter() | |
| 620 | + .map(|¢re| { | |
| 621 | + let below = x.iter().filter(|&&o| o < centre).max().copied(); | |
| 622 | + let above = x.iter().filter(|&&o| o > centre).min().copied(); | |
| 623 | + let lo = below.map_or(0, |b| ((b + centre) / 2) as usize); | |
| 624 | + let hi = above.map_or(half, |a| ((a + centre) / 2) as usize + 1); | |
| 625 | + let lo = lo.min(half - 1); | |
| 626 | + let hi = hi.clamp(lo + 1, half); | |
| 627 | + let mut peak = 0.0f64; | |
| 628 | + for spectrum in spectra { | |
| 629 | + for &value in &spectrum[lo..hi] { | |
| 630 | + peak = peak.max(f64::from(value.abs())); | |
| 631 | + } | |
| 507 | 632 | } |
| 508 | - final_y[i] = wanted[i]; | |
| 509 | - } | |
| 510 | - (final_y, step2) | |
| 633 | + peak | |
| 634 | + }) | |
| 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 folded | |
| 514 | - /// against their neighbours and Huffman coded. | |
| 515 | - fn write_floor(&self, out: &mut BitsOut, y: &[i32]) { | |
| 516 | - out.bit(true); | |
| 517 | - out.write(y[0] as u32, 8); | |
| 518 | - out.write(y[1] as u32, 8); | |
| 519 | - for i in 2..y.len() { | |
| 520 | - let (low, high) = self.floor.neighbours[i]; | |
| 521 | - let predicted = predict( | |
| 522 | - self.floor.x_list[low], | |
| 523 | - y[low], | |
| 524 | - self.floor.x_list[high], | |
| 525 | - y[high], | |
| 526 | - self.floor.x_list[i], | |
| 527 | - ); | |
| 528 | - let value = fold(predicted, y[i], 256); | |
| 529 | - self.floor_book.write(out, value as usize); | |
| 670 | +/// Run the decoder's own amplitude synthesis forwards, so the curve the | |
| 671 | +/// encoder normalises against is the curve the decoder will draw. | |
| 672 | +fn fold_floor(floor: &Floor1, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) { | |
| 673 | + let values = wanted.len(); | |
| 674 | + let range = 256i32; | |
| 675 | + let mut final_y = vec![0i32; values]; | |
| 676 | + let mut step2 = vec![false; values]; | |
| 677 | + final_y[0] = wanted[0]; | |
| 678 | + final_y[1] = wanted[1]; | |
| 679 | + step2[0] = true; | |
| 680 | + step2[1] = true; | |
| 681 | + for i in 2..values { | |
| 682 | + let (low, high) = floor.neighbours[i]; | |
| 683 | + let predicted = predict( | |
| 684 | + floor.x_list[low], | |
| 685 | + final_y[low], | |
| 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, | |
| 534 | - /// classified per partition and coded in one pass. | |
| 535 | - fn write_residue(&self, out: &mut BitsOut, quantised: &[Vec<i32>]) { | |
| 536 | - let channels = quantised.len(); | |
| 537 | - let total = HALF * channels; | |
| 538 | - let mut interleaved = vec![0i32; total]; | |
| 539 | - for (i, slot) in interleaved.iter_mut().enumerate() { | |
| 540 | - *slot = quantised[i % channels][i / channels]; | |
| 721 | +/// Write the residue: one type-2 interleaved vector over every channel, | |
| 722 | +/// classified per partition and coded in one pass. | |
| 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 | +) { | |
| 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; | |
| 543 | - let classes: Vec<usize> = (0..partitions) | |
| 544 | - .map(|partition| { | |
| 545 | - let slice = &interleaved[partition * PARTITION..(partition + 1) * PARTITION]; | |
| 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); | |
| 755 | + class_book.write(out, word); | |
| 756 | + for _ in 0..per_word { | |
| 757 | + if p >= partitions { | |
| 758 | + break; | |
| 559 | 759 | } |
| 560 | - self.class_book.write(out, word); | |
| 561 | - for _ in 0..per_word { | |
| 562 | - if partition >= partitions { | |
| 563 | - break; | |
| 564 | - } | |
| 565 | - let class = classes[partition]; | |
| 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 | - } | |
| 760 | + let class = classes[p]; | |
| 761 | + if class > 0 { | |
| 762 | + let book = &residue_books[class - 1]; | |
| 763 | + let range = CLASS_RANGE[class]; | |
| 764 | + for &value in &interleaved[p * partition..(p + 1) * partition] { | |
| 765 | + book.write(out, (value.clamp(-range, range) + range) as usize); | |
| 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 | 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. | |
| 650 | -fn build_floor() -> Floor1 { | |
| 651 | - let mut sorted_x: Vec<u32> = Vec::with_capacity(FLOOR_POINTS); | |
| 821 | +/// The floor-1 configuration for one block size: `half` coefficients, `points` | |
| 822 | +/// non-endpoint X values. | |
| 823 | +fn build_floor(half: usize, points: usize) -> Floor1 { | |
| 824 | + let mut sorted_x: Vec<u32> = Vec::with_capacity(points); | |
| 652 | 825 | let mut last = 0u32; |
| 653 | - for i in 0..FLOOR_POINTS { | |
| 654 | - let t = i as f64 / (FLOOR_POINTS - 1) as f64; | |
| 826 | + for i in 0..points { | |
| 827 | + let t = i as f64 / (points - 1) as f64; | |
| 655 | 828 | // Log spacing over the band, nudged to stay strictly increasing at the |
| 656 | 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 | 831 | last = value.max(last + 1); |
| 659 | - sorted_x.push(last); | |
| 832 | + sorted_x.push(last.min(half as u32 - 1)); | |
| 660 | 833 | } |
| 661 | 834 | // Coding order: endpoints first, then repeated bisection, so every value is |
| 662 | 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 | 837 | let mut ranges = vec![(0usize, sorted_x.len())]; |
| 665 | 838 | while let Some((lo, hi)) = ranges.pop() { |
| 666 | 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 | 897 | /// Folded floor amplitudes: mostly small corrections, occasionally an escape |
| 711 | 898 | /// near the top of the range. |
| 712 | 899 | fn design_floor_book() -> CodebookSpec { |
| @@ -757,7 +944,8 @@ fn absolute_threshold(hz: f64) -> f64 { | ||
| 757 | 944 | fn write_headers( |
| 758 | 945 | config: &EncoderConfig, |
| 759 | 946 | channels: usize, |
| 760 | - floor: &Floor1, | |
| 947 | + long: &BlockConfig, | |
| 948 | + short: &BlockConfig, | |
| 761 | 949 | floor_book: &CodebookSpec, |
| 762 | 950 | class_book: &CodebookSpec, |
| 763 | 951 | residue_books: &[CodebookSpec], |
| @@ -772,7 +960,7 @@ fn write_headers( | ||
| 772 | 960 | ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes()); |
| 773 | 961 | ident.extend_from_slice(&0i32.to_le_bytes()); |
| 774 | 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 | 964 | ident.push(1); |
| 777 | 965 | |
| 778 | 966 | let mut comment = vec![3u8]; |
| @@ -798,62 +986,73 @@ fn write_headers( | ||
| 798 | 986 | // One time-domain transform, stated as zero. |
| 799 | 987 | out.write(0, 6); |
| 800 | 988 | out.write(0, 16); |
| 801 | - // One floor, type 1. | |
| 802 | - out.write(0, 6); | |
| 803 | - out.write(1, 16); | |
| 804 | - out.write(floor.partition_classes.len() as u32, 5); | |
| 805 | - for _ in &floor.partition_classes { | |
| 806 | - out.write(0, 4); | |
| 989 | + // Two floors, type 1: long first, then short. | |
| 990 | + out.write(1, 6); | |
| 991 | + for bc in [long, short] { | |
| 992 | + out.write(1, 16); | |
| 993 | + out.write(bc.floor.partition_classes.len() as u32, 5); | |
| 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); | |
| 809 | - out.write(0, 2); | |
| 810 | - // Book number plus one; zero would mean "this subclass codes nothing". | |
| 811 | - out.write(1, 8); | |
| 812 | - out.write(0, 2); | |
| 813 | - let range_bits = ilog(HALF as u32) - 1; | |
| 814 | - out.write(range_bits, 4); | |
| 815 | - for &x in floor.x_list.iter().skip(2) { | |
| 816 | - out.write(x, range_bits); | |
| 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] { | |
| 1011 | + out.write(2, 16); | |
| 1012 | + out.write(0, 24); | |
| 1013 | + out.write((bc.half * channels) as u32, 24); | |
| 1014 | + out.write(bc.partition as u32 - 1, 24); | |
| 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. | |
| 819 | - out.write(0, 6); | |
| 820 | - out.write(2, 16); | |
| 821 | - out.write(0, 24); | |
| 822 | - out.write((HALF * channels) as u32, 24); | |
| 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); | |
| 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)] { | |
| 1029 | + out.write(0, 16); | |
| 829 | 1030 | out.write(0, 1); |
| 830 | - } | |
| 831 | - for class in 1..CLASSES { | |
| 832 | - out.write(class as u32 + 1, 8); | |
| 833 | - } | |
| 834 | - // One mapping, type 0. | |
| 835 | - out.write(0, 6); | |
| 836 | - out.write(0, 16); | |
| 837 | - out.write(0, 1); | |
| 838 | - match coupling.is_empty() { | |
| 839 | - true => out.write(0, 1), | |
| 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); | |
| 1031 | + match coupling.is_empty() { | |
| 1032 | + true => out.write(0, 1), | |
| 1033 | + false => { | |
| 1034 | + out.write(1, 1); | |
| 1035 | + out.write(coupling.len() as u32 - 1, 8); | |
| 1036 | + let field = ilog(channels as u32 - 1); | |
| 1037 | + for &(magnitude, angle) in coupling { | |
| 1038 | + out.write(magnitude as u32, field); | |
| 1039 | + out.write(angle as u32, field); | |
| 1040 | + } | |
| 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); | |
| 851 | - out.write(0, 8); | |
| 852 | - out.write(0, 8); | |
| 853 | - out.write(0, 8); | |
| 854 | - // One mode: a long block on mapping 0. | |
| 855 | - out.write(0, 6); | |
| 856 | - out.write(1, 1); | |
| 1048 | + // Two modes: mode `MODE_SHORT` is a short block on mapping 1, mode | |
| 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 | 1056 | out.write(0, 16); |
| 858 | 1057 | out.write(0, 16); |
| 859 | 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 | 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 | 623 | #[test] |
| 558 | 624 | fn the_rate_loop_tracks_the_target_bitrate() { |
| 559 | 625 | let rate = 48_000u32; |