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