forge
Explore
Log in

Don't you dare go Hollow

Quality per bit on real music — finer residue classes, co-mask cap, point stereo, drum-only transient detector

Browse files at this commit

9203ba6c8a7dde5a80a74ff4681fae6b1e676968Ahmet Kaan GümüşParent: a554dfa
  • perf
    • quality per bit on real music — finer residue classes, co-mask cap, point stereo, drum-only transient detector
Show full message
perf(vorbis-enc): quality per bit on real music — finer residue classes, co-mask cap, point stereo, drum-only transient detector

Three 30 s tracks at 128 kbps, correlation with the source: 0.9812/0.9745/0.9911
(9ac19d6) -> 0.9711/0.9663/0.9984 (f1fa335, block switching firing ~1/s on music
with 16 short blocks each) -> 0.9955/0.9936/1.0000 now, at 131/131/109 kbps.
At the reference encoder's own size (109/116/92 kbps): 0.9906/0.9901/0.9999
vs its 0.9970/0.9960/0.9986.

- residue: nine classes one octave of range apart (+-1 ... +-64, +-127), 16
  coefficients per long partition, books from measured per-class statistics
  (mean |v| ~ range/6): 0.977 -> 0.988 on the two rock tracks alone
- floor: 12 long points instead of 20 (16/20/32/44 each worse on music)
- co-mask cap: nothing under loudest-50 dB in a long block is coded;
  corner-cut named in the code, upgrade is a Bark-domain spread
- point stereo above 4 kHz while the rate loop is starving (headroom under
  the range); lossless pair coding otherwise
- transient detector: jump measured against the loudest of the four ticks
  before, -60 dBFS absolute floor; music now fires 16-32 short blocks per 30 s
- short blocks quantised with at least 42 dB headroom whatever the loop's
  state, and no co-mask cap: fixes the 6 ch / 96 kHz onset leak (peak 0.0106
  -> 0.0062 at 36 dB, under 0.005 at 42) that the sweep now covers
  (onset sweep: 44.1k 1/2 ch, 48k 1/2/6 ch, 96k 6 ch)

Known failing: quiet_content_reaches_the_target_within_25pct — the quiet
fixture codes at corr 0.9999 and 74 kbps at every target; with the cheaper
residue and 12-point floor nothing codable is left inside the 36 dB range,
so the loop cannot spend up to 128/192 kbps on it.
crates/ec-vorbis/src/encode.rsmodified+86 -20
@@ -28,8 +28,11 @@
28 //! ## Codebooks28 //! ## Codebooks
29 //!29 //!
30 //! Designed here rather than inherited: a floor book over the folded amplitude30 //! Designed here rather than inherited: a floor book over the folded amplitude
31-//! range, a class book over partition-class pairs, and four residue books whose31+//! range, a class book over partition-class pairs, and eight residue books whose
32-//! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of32+//! ranges (+-1, +-2, +-4 ... +-64, +-127) the partition classifier picks between —
33+//! a partition's values sit about a sixth of its class's range on average,
34+//! so one book per octave of range keeps every value near the top of its
35+//! own book. All of
33 //! them are Huffman codes over stated distributions, built at construction and36 //! them are Huffman codes over stated distributions, built at construction and
34 //! written into every stream's own setup header — which is why this encoder37 //! written into every stream's own setup header — which is why this encoder
35 //! needs no embedded profile and has no channel count it cannot serve. Both38 //! needs no embedded profile and has no channel count it cannot serve. Both
@@ -58,19 +61,22 @@ const HALF_LONG: usize = BLOCK_LONG / 2;
58 /// Coefficients in a short block.61 /// Coefficients in a short block.
59 const HALF_SHORT: usize = BLOCK_SHORT / 2;62 const HALF_SHORT: usize = BLOCK_SHORT / 2;
60 /// Long-block coefficients per residue partition.63 /// Long-block coefficients per residue partition.
61-const PARTITION_LONG: usize = 32;64+const PARTITION_LONG: usize = 16;
62 /// Short-block coefficients per residue partition.65 /// Short-block coefficients per residue partition.
63 const PARTITION_SHORT: usize = 16;66 const PARTITION_SHORT: usize = 16;
64-/// Long floor X points besides the two endpoints.67+/// Long floor X points besides the two endpoints. Fewer is better here, on
65-const FLOOR_POINTS_LONG: usize = 20;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;
66 /// Short floor X points besides the two endpoints.72 /// Short floor X points besides the two endpoints.
67 const FLOOR_POINTS_SHORT: usize = 8;73 const FLOOR_POINTS_SHORT: usize = 8;
68 /// Floor values per class.74 /// Floor values per class.
69 const FLOOR_CLASS_DIM: usize = 4;75 const FLOOR_CLASS_DIM: usize = 4;
70 /// Residue classes; class 0 codes nothing at all.76 /// Residue classes; class 0 codes nothing at all.
71-const CLASSES: usize = 5;77+const CLASSES: usize = 9;
72 /// Largest quantised residue each class's book can state.78 /// Largest quantised residue each class's book can state.
73-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];
74 /// Headroom in dB the widest residue book can actually state: 20 log10 12780 /// Headroom in dB the widest residue book can actually state: 20 log10 127
75 /// is 42, but a coupled angle channel is a difference of two magnitudes, so a81 /// is 42, but a coupled angle channel is a difference of two magnitudes, so a
76 /// pair's step must leave half that range — 63, 36 dB. Past this the rate loop's extra headroom lowers the absolute-threshold82 /// pair's step must leave half that range — 63, 36 dB. Past this the rate loop's extra headroom lowers the absolute-threshold
@@ -84,6 +90,30 @@ const HEADROOM_RANGE: f64 = 36.0;
84 /// Anything the wider range cannot state (a pair's angle, a peak at a floor90 /// Anything the wider range cannot state (a pair's angle, a peak at a floor
85 /// region's edge) is caught by the clamp refit in `encode_block`.91 /// region's edge) is caught by the clamp refit in `encode_block`.
86 const HEADROOM_RANGE_SHORT: f64 = 42.0;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;
87 /// Samples per transient-detection tick — the short block's own hop, so a117 /// Samples per transient-detection tick — the short block's own hop, so a
88 /// tick lines up with the finest time resolution the encoder has.118 /// tick lines up with the finest time resolution the encoder has.
89 const TICK: usize = BLOCK_SHORT / 4;119 const TICK: usize = BLOCK_SHORT / 4;
@@ -101,9 +131,12 @@ const MODE_LONG: u32 = 1;
101 /// A tick energy jump past this multiple of its predecessor is a transient;131 /// A tick energy jump past this multiple of its predecessor is a transient;
102 /// a near-zero predecessor makes this trip on any onset above the floor.132 /// a near-zero predecessor makes this trip on any onset above the floor.
103 const TRANSIENT_RATIO: f64 = 16.0;133 const TRANSIENT_RATIO: f64 = 16.0;
104-/// Below this per-sample mean square, a tick is not "content" at all — the134+/// Below this per-sample mean square (-60 dBFS), a tick is not "content" at
105-/// floor that keeps digital silence from ever tripping the detector.135+/// all — the floor that keeps digital silence, dither and fade tails from
106-const TRANSIENT_FLOOR: f64 = 1e-9;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;
107 140
108 /// Buffer samples of left pre-roll before input sample 0 — one long half, so141 /// Buffer samples of left pre-roll before input sample 0 — one long half, so
109 /// even a block starting at the very front of the stream finds zeroes rather142 /// even a block starting at the very front of the stream finds zeroes rather
@@ -175,6 +208,8 @@ struct BlockConfig {
175 ath: Vec<f64>,208 ath: Vec<f64>,
176 /// Headroom the residue range lets this block size state.209 /// Headroom the residue range lets this block size state.
177 range: f64,210 range: f64,
211+ /// dB under the loudest floor point below which nothing is coded.
212+ co_mask: f64,
178 }213 }
179 214
180 /// Vorbis I encoder.215 /// Vorbis I encoder.
@@ -249,6 +284,7 @@ impl VorbisEncoder {
249 PARTITION_LONG,284 PARTITION_LONG,
250 FLOOR_POINTS_LONG,285 FLOOR_POINTS_LONG,
251 HEADROOM_RANGE,286 HEADROOM_RANGE,
287+ CO_MASK_RANGE,
252 &config,288 &config,
253 );289 );
254 let short = build_block_config(290 let short = build_block_config(
@@ -256,6 +292,7 @@ impl VorbisEncoder {
256 PARTITION_SHORT,292 PARTITION_SHORT,
257 FLOOR_POINTS_SHORT,293 FLOOR_POINTS_SHORT,
258 HEADROOM_RANGE_SHORT,294 HEADROOM_RANGE_SHORT,
295+ CO_MASK_RANGE_SHORT,
259 &config,296 &config,
260 );297 );
261 298
@@ -458,10 +495,14 @@ impl VorbisEncoder {
458 };495 };
459 // Only the right half is new; its left neighbour was already the496 // Only the right half is new; its left neighbour was already the
460 // right half the last time this block's window was checked.497 // right half the last time this block's window was checked.
498+ let floor = TRANSIENT_FLOOR * (TICK * self.buffer.len()) as f64;
461 for t in ticks / 2..ticks {499 for t in ticks / 2..ticks {
462- let previous = energy(t - 1);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);
463 let current = energy(t);504 let current = energy(t);
464- if current > TRANSIENT_FLOOR && current > previous * TRANSIENT_RATIO {505+ if current > floor && current > previous * TRANSIENT_RATIO {
465 return true;506 return true;
466 }507 }
467 }508 }
@@ -550,6 +591,16 @@ impl VorbisEncoder {
550 // until nothing clamps, so the curve hugs the peaks the range is591 // until nothing clamps, so the curve hugs the peaks the range is
551 // measured from.592 // measured from.
552 let limit = CLASS_RANGE[CLASSES - 1];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+ };
553 let mut lift: Vec<Vec<f64>> = vec![vec![1.0; bc.floor.x_list.len()]; channels];604 let mut lift: Vec<Vec<f64>> = vec![vec![1.0; bc.floor.x_list.len()]; channels];
554 // Per X point, the span of bins whose curve it has a hand in.605 // Per X point, the span of bins whose curve it has a hand in.
555 let spans: Vec<(usize, usize)> = bc606 let spans: Vec<(usize, usize)> = bc
@@ -586,7 +637,7 @@ impl VorbisEncoder {
586 *peak *= boost;637 *peak *= boost;
587 }638 }
588 }639 }
589- let (y, step2) = fit_floor(&bc.floor, &bc.ath, self.headroom, bc.range, &peaks);640+ let (y, step2) = fit_floor(&bc.floor, &bc.ath, headroom, bc.range, bc.co_mask, &peaks);
590 let mut curve = vec![0.0f32; half];641 let mut curve = vec![0.0f32; half];
591 render_floor1(&bc.floor, &y, &step2, &mut curve);642 render_floor1(&bc.floor, &y, &step2, &mut curve);
592 for &c in group {643 for &c in group {
@@ -621,10 +672,17 @@ impl VorbisEncoder {
621 for &(magnitude, angle) in &self.coupling {672 for &(magnitude, angle) in &self.coupling {
622 let mut left = std::mem::take(&mut quantised[magnitude]);673 let mut left = std::mem::take(&mut quantised[magnitude]);
623 let mut right = std::mem::take(&mut quantised[angle]);674 let mut right = std::mem::take(&mut quantised[angle]);
624- for (l, r) in left.iter_mut().zip(right.iter_mut()) {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() {
625 let (m, a) = couple(*l, *r);683 let (m, a) = couple(*l, *r);
626 *l = m;684 *l = m;
627- *r = a;685+ *r = if bin >= point { 0 } else { a };
628 }686 }
629 quantised[magnitude] = left;687 quantised[magnitude] = left;
630 quantised[angle] = right;688 quantised[angle] = right;
@@ -737,6 +795,7 @@ fn fit_floor(
737 ath: &[f64],795 ath: &[f64],
738 headroom: f64,796 headroom: f64,
739 range: f64,797 range: f64,
798+ co_mask: f64,
740 peaks: &[f64],799 peaks: &[f64],
741 ) -> (Vec<i32>, Vec<bool>) {800 ) -> (Vec<i32>, Vec<bool>) {
742 let mut db: Vec<f64> = peaks801 let mut db: Vec<f64> = peaks
@@ -752,10 +811,12 @@ fn fit_floor(
752 let (current, next) = (window[0], window[1]);811 let (current, next) = (window[0], window[1]);
753 db[current] = db[current].max(db[next] - 24.0);812 db[current] = db[current].max(db[next] - 24.0);
754 }813 }
814+ let loudest = db.iter().copied().fold(f64::MIN, f64::max);
755 let target: Vec<f64> = db815 let target: Vec<f64> = db
756 .iter()816 .iter()
757 .zip(ath.iter())817 .zip(ath.iter())
758 .map(|(&level, &threshold)| {818 .map(|(&level, &threshold)| {
819+ let threshold = threshold.max(loudest - co_mask);
759 (level - headroom.min(range)).max(threshold - (headroom - range).max(0.0))820 (level - headroom.min(range)).max(threshold - (headroom - range).max(0.0))
760 })821 })
761 .collect();822 .collect();
@@ -985,6 +1046,7 @@ fn build_block_config(
985 partition: usize,1046 partition: usize,
986 points: usize,1047 points: usize,
987 range: f64,1048 range: f64,
1049+ co_mask: f64,
988 config: &EncoderConfig,1050 config: &EncoderConfig,
989 ) -> BlockConfig {1051 ) -> BlockConfig {
990 let floor = build_floor(half, points);1052 let floor = build_floor(half, points);
@@ -996,7 +1058,7 @@ fn build_block_config(
996 absolute_threshold(hz)1058 absolute_threshold(hz)
997 })1059 })
998 .collect();1060 .collect();
999- BlockConfig { half, partition, floor, ath, range }1061+ BlockConfig { half, partition, floor, ath, range, co_mask }
1000 }1062 }
1001 1063
1002 /// Folded floor amplitudes: mostly small corrections, occasionally an escape1064 /// Folded floor amplitudes: mostly small corrections, occasionally an escape
@@ -1010,10 +1072,12 @@ fn design_floor_book() -> CodebookSpec {
1010 1072
1011 /// Class pairs, on the assumption that most partitions are silent.1073 /// Class pairs, on the assumption that most partitions are silent.
1012 fn design_class_book() -> CodebookSpec {1074 fn design_class_book() -> CodebookSpec {
1013- 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];
1014 let mut weights = Vec::with_capacity(CLASSES * CLASSES);1078 let mut weights = Vec::with_capacity(CLASSES * CLASSES);
1015- for first in per_class {1079+ for &first in &per_class {
1016- for second in per_class {1080+ for &second in &per_class {
1017 weights.push(first * second);1081 weights.push(first * second);
1018 }1082 }
1019 }1083 }
@@ -1027,7 +1091,9 @@ fn design_residue_books() -> Vec<CodebookSpec> {
1027 CLASS_RANGE[1..]1091 CLASS_RANGE[1..]
1028 .iter()1092 .iter()
1029 .map(|&range| {1093 .map(|&range| {
1030- 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;
1031 let weights: Vec<f64> = (-range..=range)1097 let weights: Vec<f64> = (-range..=range)
1032 .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4)1098 .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4)
1033 .collect();1099 .collect();
crates/ec-vorbis/tests/oracle.rsmodified+3 -3
@@ -570,16 +570,16 @@ fn onset_after_silence_has_no_pre_echo() {
570 // last few hundred samples before it cannot hide behind a guard band, and570 // last few hundred samples before it cannot hide behind a guard band, and
571 // the peak is barred too.571 // the peak is barred too.
572 let amp = 0.7f64;572 let amp = 0.7f64;
573- for rate in [44_100u32, 48_000] {573+ for (rate, layouts) in [(44_100u32, &[1usize, 2][..]), (48_000, &[1, 2, 6]), (96_000, &[6])] {
574 let grid = 16 * 1024usize;574 let grid = 16 * 1024usize;
575 let onsets = [0.3333f64, 0.5, 0.7321, 0.9137, 1.0]575 let onsets = [0.3333f64, 0.5, 0.7321, 0.9137, 1.0]
576 .into_iter()576 .into_iter()
577 .map(|s| (s * f64::from(rate)) as usize)577 .map(|s| (s * f64::from(rate)) as usize)
578 .chain([0usize, 37, 512, 1000, 1023].into_iter().map(|o| grid + o));578 .chain([0usize, 37, 512, 1000, 1023].into_iter().map(|o| grid + o));
579 for onset in onsets {579 for onset in onsets {
580- for channels in [1usize, 2] {580+ for &channels in layouts {
581 let tone_len = rate as usize;581 let tone_len = rate as usize;
582- let mut source = vec![vec![0.0f32; onset + tone_len + 11]; channels];582+ let mut source = vec![vec![0.0f32; onset + tone_len + 11 * channels]; channels];
583 for (c, plane) in source.iter_mut().enumerate() {583 for (c, plane) in source.iter_mut().enumerate() {
584 let hz = 1_000.0 + 370.0 * c as f64;584 let hz = 1_000.0 + 370.0 * c as f64;
585 let start = onset + 11 * c;585 let start = onset + 11 * c;