forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-vorbisvq': dim-2/dim-4 residue vector books and Bark-local masking in the Vorbis encoder

Browse files at this commit

eca8b3ddd40b614c59d3af0797935498e7b27399Ahmet Kaan GümüşParent: 20680e842f3426
crates/ec-vorbis/src/codebook.rsmodified+2 -2
@@ -323,13 +323,13 @@ fn free_depth(slot: i32, nodes: &[Node]) -> u8 {
323323 /// and the packet writer both need: lengths to state, codewords to emit.
324324 #[derive(Debug, Clone)]
325325 pub struct CodebookSpec {
326- /// Values per entry; 1 for every book this encoder writes.
326+ /// Values per entry.
327327 pub dimensions: usize,
328328 /// Codeword length per entry, all non-zero (no sparse books written).
329329 pub lengths: Vec<u8>,
330330 /// Codeword per entry, MSB-first in `lengths[i]` bits.
331331 pub codes: Vec<u32>,
332- /// Quantised value per entry when the book carries a lookup, empty for a
332+ /// Quantised values per entry when the book carries a lookup, empty for a
333333 /// pure symbol book.
334334 pub values: Vec<f32>,
335335 }
crates/ec-vorbis/src/encode.rsmodified+186 -57
@@ -4,9 +4,9 @@
44 //! ## What the analysis actually is
55 //!
66 //! Per block, per channel: an MDCT, a peak magnitude per floor point, a
7-//! spreading function over those points (a one-pole decay up and down the
8-//! spectrum, which is the cheap stand-in for a masking curve), an absolute
9-//! threshold of hearing under it, and a headroom the rate loop moves. The floor
7+//! spreading function over those points, a Bark-domain near-band masker under
8+//! it, an absolute threshold of hearing under that, and a headroom the rate
9+//! loop moves. The floor
1010 //! that comes out is the quantiser step: the residue is the spectrum divided by
1111 //! the floor and rounded, so headroom in dB *is* precision in bits. That is
1212 //! psychoacoustics-lite and it is stated as such — there is no tonality
@@ -46,7 +46,7 @@ use ec_core::{
4646 use ec_dsp::Mdct;
4747
4848 use crate::bits::{BitsOut, float32_pack};
49-use crate::codebook::{CodebookSpec, ilog};
49+use crate::codebook::{CodebookSpec, ilog, lookup1_values};
5050 use crate::decode::channel_map;
5151 use crate::floor::render_floor1;
5252 use crate::setup::Floor1;
@@ -77,6 +77,11 @@ const FLOOR_CLASS_DIM: usize = 4;
7777 const CLASSES: usize = 9;
7878 /// Largest quantised residue each class's book can state.
7979 const CLASS_RANGE: [i32; CLASSES] = [0, 1, 2, 4, 8, 16, 32, 64, 127];
80+/// Residue codebook dimensions by class; class 0 codes no residue.
81+const RESIDUE_BOOK_DIM: [usize; CLASSES] = [0, 4, 2, 2, 1, 1, 1, 1, 1];
82+/// The vector books save packet bits but add setup and make the rate loop spend
83+/// harder; this keeps the realised rate at the caller's target.
84+const RATE_TARGET_SCALE: f64 = 0.99;
8085 /// Headroom in dB the widest residue book can actually state: 20 log10 127
8186 /// is 42, but a coupled angle channel is a difference of two magnitudes, so a
8287 /// pair's step must leave half that range — 63, 36 dB. Past this the rate loop's extra headroom lowers the absolute-threshold
@@ -91,14 +96,11 @@ const HEADROOM_RANGE: f64 = 36.0;
9196 /// region's edge) is caught by the clamp refit in `encode_block`.
9297 const HEADROOM_RANGE_SHORT: f64 = 42.0;
9398 /// 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.
99+/// coded: a whole-spectrum co-masking cap after local spreading. The Bark
100+/// curve keeps nearby bands honest; this cap only stops very quiet distant
101+/// bins from spending bits below the noise floor at these rates. Swept on
102+/// three tracks at 128 kbps: 50 dB kept the accuracy win without inflating the
103+/// files.
102104 const CO_MASK_RANGE: f64 = 50.0;
103105 /// A short block gets no co-masking cap: a bin it drops is an error spread
104106 /// across its whole window, the half before an onset included, and that is
@@ -200,12 +202,13 @@ enum Sched {
200202 TransitionIn,
201203 }
202204
203-/// A block size's own floor, codebook-sharing residue geometry and ATH.
205+/// A block size's own floor, codebook-sharing residue geometry and masking data.
204206 struct BlockConfig {
205207 half: usize,
206208 partition: usize,
207209 floor: Floor1,
208210 ath: Vec<f64>,
211+ bark: Vec<f64>,
209212 /// Headroom the residue range lets this block size state.
210213 range: f64,
211214 /// dB under the loudest floor point below which nothing is coded.
@@ -502,7 +505,9 @@ impl VorbisEncoder {
502505 // Against the loudest of the few ticks before it, not just the
503506 // one: music rising over a few ticks is not a transient, a drum
504507 // hit or an onset after silence is.
505- let previous = (t.saturating_sub(TRANSIENT_HISTORY)..t).map(energy).fold(0.0f64, f64::max);
508+ let previous = (t.saturating_sub(TRANSIENT_HISTORY)..t)
509+ .map(energy)
510+ .fold(0.0f64, f64::max);
506511 let current = energy(t);
507512 if current > floor && current > previous * TRANSIENT_RATIO {
508513 return true;
@@ -519,7 +524,11 @@ impl VorbisEncoder {
519524 break;
520525 }
521526 let plan = self.peek_plan();
522- let n = if plan.is_long { BLOCK_LONG } else { BLOCK_SHORT };
527+ let n = if plan.is_long {
528+ BLOCK_LONG
529+ } else {
530+ BLOCK_SHORT
531+ };
523532 let half = if plan.is_long { HALF_LONG } else { HALF_SHORT };
524533 let centre = self.centre + (self.prev_n + n) as i64 / 4;
525534 let window_start = centre - (n / 2) as i64;
@@ -562,7 +571,11 @@ impl VorbisEncoder {
562571 plan: BlockPlan,
563572 channels: usize,
564573 ) -> Vec<u8> {
565- let bc = if plan.is_long { &self.long } else { &self.short };
574+ let bc = if plan.is_long {
575+ &self.long
576+ } else {
577+ &self.short
578+ };
566579 let partition = bc.partition;
567580 let scale = 2.0 / half as f32;
568581 let window = self
@@ -575,7 +588,11 @@ impl VorbisEncoder {
575588 for channel in 0..channels {
576589 block.copy_from_slice(&self.buffer[channel][start..start + n]);
577590 let mut coefficients = vec![0.0f32; half];
578- let mdct = if plan.is_long { &mut self.mdct_long } else { &mut self.mdct_short };
591+ let mdct = if plan.is_long {
592+ &mut self.mdct_long
593+ } else {
594+ &mut self.mdct_short
595+ };
579596 mdct.forward_windowed(&block, &window, &mut coefficients);
580597 for value in coefficients.iter_mut() {
581598 *value *= scale;
@@ -639,7 +656,9 @@ impl VorbisEncoder {
639656 *peak *= boost;
640657 }
641658 }
642- let (y, step2) = fit_floor(&bc.floor, &bc.ath, headroom, bc.range, bc.co_mask, &peaks);
659+ let (y, step2) = fit_floor(
660+ &bc.floor, &bc.ath, &bc.bark, headroom, bc.range, bc.co_mask, &peaks,
661+ );
643662 let mut curve = vec![0.0f32; half];
644663 render_floor1(&bc.floor, &y, &step2, &mut curve);
645664 for &c in group {
@@ -678,7 +697,10 @@ impl VorbisEncoder {
678697 // rate loop saying the step cannot get finer, so the budget
679698 // is better spent stating the angle than left unspent.
680699 let point = match self.headroom < bc.range {
681- true => (POINT_STEREO_HZ / (f64::from(self.config.sample_rate) * 0.5) * half as f64) as usize,
700+ true => {
701+ (POINT_STEREO_HZ / (f64::from(self.config.sample_rate) * 0.5) * half as f64)
702+ as usize
703+ }
682704 false => half,
683705 };
684706 for (bin, (l, r)) in left.iter_mut().zip(right.iter_mut()).enumerate() {
@@ -727,7 +749,14 @@ impl VorbisEncoder {
727749 for values in floor_values.iter().take(channels) {
728750 write_floor(&mut out, &bc.floor, &self.floor_book, values);
729751 }
730- write_residue(&mut out, &quantised, half, partition, &self.class_book, &self.residue_books);
752+ write_residue(
753+ &mut out,
754+ &quantised,
755+ half,
756+ partition,
757+ &self.class_book,
758+ &self.residue_books,
759+ );
731760 let bits = out.len();
732761 let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre;
733762 self.update_rate(bits, half, channels, delta);
@@ -748,7 +777,8 @@ impl VorbisEncoder {
748777 if self.config.bitrate_bps <= 0 || delta <= 0 {
749778 return;
750779 }
751- let target = f64::from(self.config.bitrate_bps) * delta as f64 / f64::from(self.config.sample_rate);
780+ let target = f64::from(self.config.bitrate_bps) * RATE_TARGET_SCALE * delta as f64
781+ / f64::from(self.config.sample_rate);
752782 let coefficients = (half * channels) as f64;
753783 let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0);
754784 // Negative headroom is not a mistake: it puts the floor *above* the
@@ -788,33 +818,49 @@ fn peaks_of(floor: &Floor1, half: usize, spectra: &[&Vec<f32>]) -> Vec<f64> {
788818
789819 /// Turn peak magnitudes into coded floor amplitudes.
790820 ///
791-/// Spread first (a masker covers its neighbours), then subtract the rate
792-/// loop's headroom, then hold the absolute threshold of hearing as a lower
793-/// bound: below it the residue quantises to zero and costs a class-0
794-/// partition.
821+/// Spread first (a masker covers its neighbours, with an extra Bark-local
822+/// near-band pass), then subtract the rate loop's headroom, then hold the
823+/// absolute threshold of hearing as a lower bound: below it the residue
824+/// quantises to zero and costs a class-0 partition.
795825 fn fit_floor(
796826 floor: &Floor1,
797827 ath: &[f64],
828+ bark: &[f64],
798829 headroom: f64,
799830 range: f64,
800831 co_mask: f64,
801832 peaks: &[f64],
802833 ) -> (Vec<i32>, Vec<bool>) {
803- let mut db: Vec<f64> = peaks
834+ let db: Vec<f64> = peaks
804835 .iter()
805836 .map(|&peak| 20.0 * (peak.max(1e-9)).log10())
806837 .collect();
838+ let mut spread = db.clone();
807839 let order = &floor.sorted;
808840 for window in order.windows(2) {
809841 let (previous, current) = (window[0], window[1]);
810- db[current] = db[current].max(db[previous] - 12.0);
842+ spread[current] = spread[current].max(spread[previous] - 12.0);
811843 }
812844 for window in order.windows(2).rev() {
813845 let (current, next) = (window[0], window[1]);
814- db[current] = db[current].max(db[next] - 24.0);
846+ spread[current] = spread[current].max(spread[next] - 24.0);
847+ }
848+ for (source, &level) in db.iter().enumerate() {
849+ for (target, masked) in spread.iter_mut().enumerate() {
850+ let distance = (bark[target] - bark[source]).abs();
851+ if distance > 0.25 {
852+ continue;
853+ }
854+ let slope = if bark[target] >= bark[source] {
855+ 48.0
856+ } else {
857+ 80.0
858+ };
859+ *masked = (*masked).max(level - slope * distance);
860+ }
815861 }
816862 let loudest = db.iter().copied().fold(f64::MIN, f64::max);
817- let target: Vec<f64> = db
863+ let target: Vec<f64> = spread
818864 .iter()
819865 .zip(ath.iter())
820866 .map(|(&level, &threshold)| {
@@ -923,8 +969,9 @@ fn write_residue(
923969 if class > 0 {
924970 let book = &residue_books[class - 1];
925971 let range = CLASS_RANGE[class];
926- for &value in &interleaved[p * partition..(p + 1) * partition] {
927- book.write(out, (value.clamp(-range, range) + range) as usize);
972+ for chunk in interleaved[p * partition..(p + 1) * partition].chunks(book.dimensions)
973+ {
974+ book.write(out, residue_entry(chunk, range, book.dimensions));
928975 }
929976 }
930977 p += 1;
@@ -932,6 +979,19 @@ fn write_residue(
932979 }
933980 }
934981
982+/// Entry number for an exact vector value in one residue book.
983+fn residue_entry(values: &[i32], range: i32, dimensions: usize) -> usize {
984+ let base = (2 * range + 1) as usize;
985+ let mut entry = 0usize;
986+ let mut multiplier = 1usize;
987+ for i in 0..dimensions {
988+ let value = values.get(i).copied().unwrap_or(0).clamp(-range, range);
989+ entry += (value + range) as usize * multiplier;
990+ multiplier *= base;
991+ }
992+ entry
993+}
994+
935995 /// Forward square-polar coupling (§9.4.2 run backwards).
936996 fn couple(left: i32, right: i32) -> (i32, i32) {
937997 match left > 0 {
@@ -1042,7 +1102,7 @@ fn build_floor(half: usize, points: usize) -> Floor1 {
10421102 }
10431103 }
10441104
1045-/// Build one block size's floor and ATH curve.
1105+/// Build one block size's floor, ATH curve and Bark positions.
10461106 fn build_block_config(
10471107 half: usize,
10481108 partition: usize,
@@ -1052,15 +1112,22 @@ fn build_block_config(
10521112 config: &EncoderConfig,
10531113 ) -> BlockConfig {
10541114 let floor = build_floor(half, points);
1055- let ath = floor
1115+ let hz: Vec<f64> = floor
10561116 .x_list
10571117 .iter()
1058- .map(|&x| {
1059- let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / half as f64;
1060- absolute_threshold(hz)
1061- })
1118+ .map(|&x| f64::from(config.sample_rate) * 0.5 * f64::from(x) / half as f64)
10621119 .collect();
1063- BlockConfig { half, partition, floor, ath, range, co_mask }
1120+ let ath = hz.iter().map(|&hz| absolute_threshold(hz)).collect();
1121+ let bark = hz.iter().map(|&hz| bark(hz)).collect();
1122+ BlockConfig {
1123+ half,
1124+ partition,
1125+ floor,
1126+ ath,
1127+ bark,
1128+ range,
1129+ co_mask,
1130+ }
10641131 }
10651132
10661133 /// Folded floor amplitudes: mostly small corrections, occasionally an escape
@@ -1088,19 +1155,46 @@ fn design_class_book() -> CodebookSpec {
10881155 spec
10891156 }
10901157
1091-/// One book per non-silent class, Laplacian over its own range.
1158+/// One book per non-silent class. Small ranges use vector entries because
1159+/// non-zero partitions still contain many zero coefficients; wider ranges stay
1160+/// scalar to keep setup overhead below the bits they can save.
10921161 fn design_residue_books() -> Vec<CodebookSpec> {
10931162 CLASS_RANGE[1..]
10941163 .iter()
1095- .map(|&range| {
1096- // Measured mean |value| inside a partition of each class is about
1097- // a sixth of the class's range, whatever the range.
1098- let sigma = f64::from(range).max(1.0) / 6.0;
1099- let weights: Vec<f64> = (-range..=range)
1100- .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4)
1101- .collect();
1102- let values: Vec<f32> = (-range..=range).map(|v| v as f32).collect();
1103- CodebookSpec::huffman(&weights, values)
1164+ .enumerate()
1165+ .map(|(offset, &range)| {
1166+ let class = offset + 1;
1167+ let dimensions = RESIDUE_BOOK_DIM[class];
1168+ let base = (2 * range + 1) as usize;
1169+ let entries = base.pow(dimensions as u32);
1170+ let sigma = f64::from(range).max(1.0);
1171+ let mut weights = Vec::with_capacity(entries);
1172+ let mut values = Vec::with_capacity(entries * dimensions);
1173+ for entry in 0..entries {
1174+ let mut nonzero = 0usize;
1175+ let mut weight = 1.0f64;
1176+ for position in 0..dimensions {
1177+ let div = base.pow(position as u32);
1178+ let value = (entry / div % base) as i32 - range;
1179+ values.push(value as f32);
1180+ if value == 0 {
1181+ weight *= 0.60;
1182+ } else {
1183+ nonzero += 1;
1184+ weight *= 0.40 * (-f64::from(value.abs()) / sigma).exp();
1185+ }
1186+ }
1187+ let sparse = match nonzero {
1188+ 0 => 4.0,
1189+ 1 => 2.0,
1190+ 2 => 0.8,
1191+ _ => 0.25,
1192+ };
1193+ weights.push(weight * sparse + 1e-8);
1194+ }
1195+ let mut spec = CodebookSpec::huffman(&weights, values);
1196+ spec.dimensions = dimensions;
1197+ spec
11041198 })
11051199 .collect()
11061200 }
@@ -1119,6 +1213,12 @@ fn absolute_threshold(hz: f64) -> f64 {
11191213 (spl - 96.0).clamp(-120.0, -80.0)
11201214 }
11211215
1216+/// Frequency in Barks, using the same compact psychoacoustic scale for every
1217+/// sample rate.
1218+fn bark(hz: f64) -> f64 {
1219+ 13.0 * (0.00076 * hz).atan() + 3.5 * ((hz / 7500.0) * (hz / 7500.0)).atan()
1220+}
1221+
11221222 struct HeaderSetup<'a> {
11231223 long: &'a BlockConfig,
11241224 short: &'a BlockConfig,
@@ -1249,8 +1349,8 @@ fn write_headers(config: &EncoderConfig, channels: usize, setup: HeaderSetup<'_>
12491349 vec![ident, comment, setup]
12501350 }
12511351
1252-/// One codebook in setup-header form: flat lengths, and a scalar lookup when
1253-/// the book carries values.
1352+/// One codebook in setup-header form: flat lengths and, when present, a type-1
1353+/// lookup table carrying the scalar alphabet used by entry digits.
12541354 fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) {
12551355 out.write(0x0056_4342, 24);
12561356 out.write(book.dimensions as u32, 16);
@@ -1264,17 +1364,21 @@ fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) {
12641364 out.write(0, 4);
12651365 return;
12661366 }
1267- // Lookup type 1 with one dimension: the entry number *is* the index, so
1268- // `minimum + i * delta` states every value in `ilog(entries)` bits each.
12691367 out.write(1, 4);
1270- let minimum = book.values[0];
1368+ let minimum = book.values.iter().copied().fold(f32::INFINITY, f32::min);
1369+ let maximum = book
1370+ .values
1371+ .iter()
1372+ .copied()
1373+ .fold(f32::NEG_INFINITY, f32::max);
12711374 out.write(float32_pack(minimum), 32);
12721375 out.write(float32_pack(1.0), 32);
1273- let value_bits = ilog(book.entries() as u32 - 1).max(1);
1376+ let lookup_values = lookup1_values(book.entries(), book.dimensions);
1377+ let value_bits = ilog((maximum - minimum).round() as u32).max(1);
12741378 out.write(value_bits - 1, 4);
12751379 out.write(0, 1);
1276- for i in 0..book.entries() {
1277- out.write(i as u32, value_bits);
1380+ for value in 0..lookup_values {
1381+ out.write(value as u32, value_bits);
12781382 }
12791383 }
12801384
@@ -1394,6 +1498,28 @@ mod tests {
13941498 }
13951499 }
13961500
1501+ #[test]
1502+ fn vector_residue_books_address_exact_values() {
1503+ let books = design_residue_books();
1504+ assert_eq!(
1505+ books.iter().map(|b| b.dimensions).collect::<Vec<_>>(),
1506+ vec![4, 2, 2, 1, 1, 1, 1, 1]
1507+ );
1508+ for (class, book) in books.iter().enumerate().take(3) {
1509+ let range = CLASS_RANGE[class + 1];
1510+ let vector: Vec<i32> = (0..book.dimensions)
1511+ .map(|i| if i % 2 == 0 { range } else { -range })
1512+ .collect();
1513+ let entry = residue_entry(&vector, range, book.dimensions);
1514+ let start = entry * book.dimensions;
1515+ let decoded: Vec<i32> = book.values[start..start + book.dimensions]
1516+ .iter()
1517+ .map(|&v| v as i32)
1518+ .collect();
1519+ assert_eq!(decoded, vector);
1520+ }
1521+ }
1522+
13971523 #[test]
13981524 fn tail_granule_44100_mono() {
13991525 let mut enc = VorbisEncoder::new(EncoderConfig {
@@ -1410,7 +1536,10 @@ mod tests {
14101536 let mut n = 0;
14111537 loop {
14121538 match enc.next_packet() {
1413- Ok(p) => { last = p.granule; n += 1; }
1539+ Ok(p) => {
1540+ last = p.granule;
1541+ n += 1;
1542+ }
14141543 Err(Error::Eof) => break,
14151544 Err(e) => panic!("{e}"),
14161545 }