Add residue vector books
Browse files at this commit42f34264a344c36ad7b7021747c88ec8e54163b1Parent: e44f0f4- feat
- add residue vector books
2 changed files +188 -59
crates/ec-vorbis/src/codebook.rsmodified+2 -2
| @@ -323,13 +323,13 @@ fn free_depth(slot: i32, nodes: &[Node]) -> u8 { | |||
| 323 | /// and the packet writer both need: lengths to state, codewords to emit. | 323 | /// and the packet writer both need: lengths to state, codewords to emit. |
| 324 | #[derive(Debug, Clone)] | 324 | #[derive(Debug, Clone)] |
| 325 | pub struct CodebookSpec { | 325 | pub struct CodebookSpec { |
| 326 | - /// Values per entry; 1 for every book this encoder writes. | 326 | + /// Values per entry. |
| 327 | pub dimensions: usize, | 327 | pub dimensions: usize, |
| 328 | /// Codeword length per entry, all non-zero (no sparse books written). | 328 | /// Codeword length per entry, all non-zero (no sparse books written). |
| 329 | pub lengths: Vec<u8>, | 329 | pub lengths: Vec<u8>, |
| 330 | /// Codeword per entry, MSB-first in `lengths[i]` bits. | 330 | /// Codeword per entry, MSB-first in `lengths[i]` bits. |
| 331 | pub codes: Vec<u32>, | 331 | 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 |
| 333 | /// pure symbol book. | 333 | /// pure symbol book. |
| 334 | pub values: Vec<f32>, | 334 | pub values: Vec<f32>, |
| 335 | } | 335 | } |
crates/ec-vorbis/src/encode.rsmodified+186 -57
| @@ -4,9 +4,9 @@ | |||
| 4 | //! ## What the analysis actually is | 4 | //! ## What the analysis actually is |
| 5 | //! | 5 | //! |
| 6 | //! Per block, per channel: an MDCT, a peak magnitude per floor point, a | 6 | //! 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 | 7 | +//! spreading function over those points, a Bark-domain near-band masker under |
| 8 | -//! spectrum, which is the cheap stand-in for a masking curve), an absolute | 8 | +//! it, an absolute threshold of hearing under that, and a headroom the rate |
| 9 | -//! threshold of hearing under it, and a headroom the rate loop moves. The floor | 9 | +//! loop moves. The floor |
| 10 | //! that comes out is the quantiser step: the residue is the spectrum divided by | 10 | //! that comes out is the quantiser step: the residue is the spectrum divided by |
| 11 | //! the floor and rounded, so headroom in dB *is* precision in bits. That is | 11 | //! the floor and rounded, so headroom in dB *is* precision in bits. That is |
| 12 | //! psychoacoustics-lite and it is stated as such — there is no tonality | 12 | //! psychoacoustics-lite and it is stated as such — there is no tonality |
| @@ -46,7 +46,7 @@ use ec_core::{ | |||
| 46 | use ec_dsp::Mdct; | 46 | use ec_dsp::Mdct; |
| 47 | 47 | ||
| 48 | use crate::bits::{BitsOut, float32_pack}; | 48 | use crate::bits::{BitsOut, float32_pack}; |
| 49 | -use crate::codebook::{CodebookSpec, ilog}; | 49 | +use crate::codebook::{CodebookSpec, ilog, lookup1_values}; |
| 50 | use crate::decode::channel_map; | 50 | use crate::decode::channel_map; |
| 51 | use crate::floor::render_floor1; | 51 | use crate::floor::render_floor1; |
| 52 | use crate::setup::Floor1; | 52 | use crate::setup::Floor1; |
| @@ -77,6 +77,11 @@ const FLOOR_CLASS_DIM: usize = 4; | |||
| 77 | const CLASSES: usize = 9; | 77 | const CLASSES: usize = 9; |
| 78 | /// Largest quantised residue each class's book can state. | 78 | /// Largest quantised residue each class's book can state. |
| 79 | const CLASS_RANGE: [i32; CLASSES] = [0, 1, 2, 4, 8, 16, 32, 64, 127]; | 79 | 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; | ||
| 80 | /// Headroom in dB the widest residue book can actually state: 20 log10 127 | 85 | /// 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 | 86 | /// 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 | 87 | /// 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; | |||
| 91 | /// region's edge) is caught by the clamp refit in `encode_block`. | 96 | /// region's edge) is caught by the clamp refit in `encode_block`. |
| 92 | const HEADROOM_RANGE_SHORT: f64 = 42.0; | 97 | const HEADROOM_RANGE_SHORT: f64 = 42.0; |
| 93 | /// Nothing more than this many dB under a block's loudest floor point is | 98 | /// 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 | 99 | +/// coded: a whole-spectrum co-masking cap after local spreading. The Bark |
| 95 | -/// spreading function — real masking falls off with distance in Barks, so | 100 | +/// curve keeps nearby bands honest; this cap only stops very quiet distant |
| 96 | -/// this drops a quiet treble part under a loud bass note that the ear would | 101 | +/// bins from spending bits below the noise floor at these rates. Swept on |
| 97 | -/// still pick out. It is what buys real music its accuracy at this rate (on | 102 | +/// three tracks at 128 kbps: 50 dB kept the accuracy win without inflating the |
| 98 | -/// three tracks at 128 kbps, 0.989 -> 0.995 correlation with the source); | 103 | +/// files. |
| 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; | 104 | const CO_MASK_RANGE: f64 = 50.0; |
| 103 | /// A short block gets no co-masking cap: a bin it drops is an error spread | 105 | /// 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 | 106 | /// across its whole window, the half before an onset included, and that is |
| @@ -200,12 +202,13 @@ enum Sched { | |||
| 200 | TransitionIn, | 202 | TransitionIn, |
| 201 | } | 203 | } |
| 202 | 204 | ||
| 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. |
| 204 | struct BlockConfig { | 206 | struct BlockConfig { |
| 205 | half: usize, | 207 | half: usize, |
| 206 | partition: usize, | 208 | partition: usize, |
| 207 | floor: Floor1, | 209 | floor: Floor1, |
| 208 | ath: Vec<f64>, | 210 | ath: Vec<f64>, |
| 211 | + bark: Vec<f64>, | ||
| 209 | /// Headroom the residue range lets this block size state. | 212 | /// Headroom the residue range lets this block size state. |
| 210 | range: f64, | 213 | range: f64, |
| 211 | /// dB under the loudest floor point below which nothing is coded. | 214 | /// dB under the loudest floor point below which nothing is coded. |
| @@ -502,7 +505,9 @@ impl VorbisEncoder { | |||
| 502 | // Against the loudest of the few ticks before it, not just the | 505 | // Against the loudest of the few ticks before it, not just the |
| 503 | // one: music rising over a few ticks is not a transient, a drum | 506 | // one: music rising over a few ticks is not a transient, a drum |
| 504 | // hit or an onset after silence is. | 507 | // 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); | ||
| 506 | let current = energy(t); | 511 | let current = energy(t); |
| 507 | if current > floor && current > previous * TRANSIENT_RATIO { | 512 | if current > floor && current > previous * TRANSIENT_RATIO { |
| 508 | return true; | 513 | return true; |
| @@ -519,7 +524,11 @@ impl VorbisEncoder { | |||
| 519 | break; | 524 | break; |
| 520 | } | 525 | } |
| 521 | let plan = self.peek_plan(); | 526 | 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 | + }; | ||
| 523 | let half = if plan.is_long { HALF_LONG } else { HALF_SHORT }; | 532 | let half = if plan.is_long { HALF_LONG } else { HALF_SHORT }; |
| 524 | let centre = self.centre + (self.prev_n + n) as i64 / 4; | 533 | let centre = self.centre + (self.prev_n + n) as i64 / 4; |
| 525 | let window_start = centre - (n / 2) as i64; | 534 | let window_start = centre - (n / 2) as i64; |
| @@ -562,7 +571,11 @@ impl VorbisEncoder { | |||
| 562 | plan: BlockPlan, | 571 | plan: BlockPlan, |
| 563 | channels: usize, | 572 | channels: usize, |
| 564 | ) -> Vec<u8> { | 573 | ) -> 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 | + }; | ||
| 566 | let partition = bc.partition; | 579 | let partition = bc.partition; |
| 567 | let scale = 2.0 / half as f32; | 580 | let scale = 2.0 / half as f32; |
| 568 | let window = self | 581 | let window = self |
| @@ -575,7 +588,11 @@ impl VorbisEncoder { | |||
| 575 | for channel in 0..channels { | 588 | for channel in 0..channels { |
| 576 | block.copy_from_slice(&self.buffer[channel][start..start + n]); | 589 | block.copy_from_slice(&self.buffer[channel][start..start + n]); |
| 577 | let mut coefficients = vec![0.0f32; half]; | 590 | 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 | + }; | ||
| 579 | mdct.forward_windowed(&block, &window, &mut coefficients); | 596 | mdct.forward_windowed(&block, &window, &mut coefficients); |
| 580 | for value in coefficients.iter_mut() { | 597 | for value in coefficients.iter_mut() { |
| 581 | *value *= scale; | 598 | *value *= scale; |
| @@ -639,7 +656,9 @@ impl VorbisEncoder { | |||
| 639 | *peak *= boost; | 656 | *peak *= boost; |
| 640 | } | 657 | } |
| 641 | } | 658 | } |
| 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 | + ); | ||
| 643 | let mut curve = vec![0.0f32; half]; | 662 | let mut curve = vec![0.0f32; half]; |
| 644 | render_floor1(&bc.floor, &y, &step2, &mut curve); | 663 | render_floor1(&bc.floor, &y, &step2, &mut curve); |
| 645 | for &c in group { | 664 | for &c in group { |
| @@ -678,7 +697,10 @@ impl VorbisEncoder { | |||
| 678 | // rate loop saying the step cannot get finer, so the budget | 697 | // rate loop saying the step cannot get finer, so the budget |
| 679 | // is better spent stating the angle than left unspent. | 698 | // is better spent stating the angle than left unspent. |
| 680 | let point = match self.headroom < bc.range { | 699 | 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 | + } | ||
| 682 | false => half, | 704 | false => half, |
| 683 | }; | 705 | }; |
| 684 | for (bin, (l, r)) in left.iter_mut().zip(right.iter_mut()).enumerate() { | 706 | for (bin, (l, r)) in left.iter_mut().zip(right.iter_mut()).enumerate() { |
| @@ -727,7 +749,14 @@ impl VorbisEncoder { | |||
| 727 | for values in floor_values.iter().take(channels) { | 749 | for values in floor_values.iter().take(channels) { |
| 728 | write_floor(&mut out, &bc.floor, &self.floor_book, values); | 750 | write_floor(&mut out, &bc.floor, &self.floor_book, values); |
| 729 | } | 751 | } |
| 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 | + ); | ||
| 731 | let bits = out.len(); | 760 | let bits = out.len(); |
| 732 | let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre; | 761 | let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre; |
| 733 | self.update_rate(bits, half, channels, delta); | 762 | self.update_rate(bits, half, channels, delta); |
| @@ -748,7 +777,8 @@ impl VorbisEncoder { | |||
| 748 | if self.config.bitrate_bps <= 0 || delta <= 0 { | 777 | if self.config.bitrate_bps <= 0 || delta <= 0 { |
| 749 | return; | 778 | return; |
| 750 | } | 779 | } |
| 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); | ||
| 752 | let coefficients = (half * channels) as f64; | 782 | let coefficients = (half * channels) as f64; |
| 753 | let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0); | 783 | let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0); |
| 754 | // Negative headroom is not a mistake: it puts the floor *above* the | 784 | // 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> { | |||
| 788 | 818 | ||
| 789 | /// Turn peak magnitudes into coded floor amplitudes. | 819 | /// Turn peak magnitudes into coded floor amplitudes. |
| 790 | /// | 820 | /// |
| 791 | -/// Spread first (a masker covers its neighbours), then subtract the rate | 821 | +/// Spread first (a masker covers its neighbours, with an extra Bark-local |
| 792 | -/// loop's headroom, then hold the absolute threshold of hearing as a lower | 822 | +/// near-band pass), then subtract the rate loop's headroom, then hold the |
| 793 | -/// bound: below it the residue quantises to zero and costs a class-0 | 823 | +/// absolute threshold of hearing as a lower bound: below it the residue |
| 794 | -/// partition. | 824 | +/// quantises to zero and costs a class-0 partition. |
| 795 | fn fit_floor( | 825 | fn fit_floor( |
| 796 | floor: &Floor1, | 826 | floor: &Floor1, |
| 797 | ath: &[f64], | 827 | ath: &[f64], |
| 828 | + bark: &[f64], | ||
| 798 | headroom: f64, | 829 | headroom: f64, |
| 799 | range: f64, | 830 | range: f64, |
| 800 | co_mask: f64, | 831 | co_mask: f64, |
| 801 | peaks: &[f64], | 832 | peaks: &[f64], |
| 802 | ) -> (Vec<i32>, Vec<bool>) { | 833 | ) -> (Vec<i32>, Vec<bool>) { |
| 803 | - let mut db: Vec<f64> = peaks | 834 | + let db: Vec<f64> = peaks |
| 804 | .iter() | 835 | .iter() |
| 805 | .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) | 836 | .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) |
| 806 | .collect(); | 837 | .collect(); |
| 838 | + let mut spread = db.clone(); | ||
| 807 | let order = &floor.sorted; | 839 | let order = &floor.sorted; |
| 808 | for window in order.windows(2) { | 840 | for window in order.windows(2) { |
| 809 | let (previous, current) = (window[0], window[1]); | 841 | 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); |
| 811 | } | 843 | } |
| 812 | for window in order.windows(2).rev() { | 844 | for window in order.windows(2).rev() { |
| 813 | let (current, next) = (window[0], window[1]); | 845 | 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 | + } | ||
| 815 | } | 861 | } |
| 816 | let loudest = db.iter().copied().fold(f64::MIN, f64::max); | 862 | let loudest = db.iter().copied().fold(f64::MIN, f64::max); |
| 817 | - let target: Vec<f64> = db | 863 | + let target: Vec<f64> = spread |
| 818 | .iter() | 864 | .iter() |
| 819 | .zip(ath.iter()) | 865 | .zip(ath.iter()) |
| 820 | .map(|(&level, &threshold)| { | 866 | .map(|(&level, &threshold)| { |
| @@ -923,8 +969,9 @@ fn write_residue( | |||
| 923 | if class > 0 { | 969 | if class > 0 { |
| 924 | let book = &residue_books[class - 1]; | 970 | let book = &residue_books[class - 1]; |
| 925 | let range = CLASS_RANGE[class]; | 971 | let range = CLASS_RANGE[class]; |
| 926 | - for &value in &interleaved[p * partition..(p + 1) * partition] { | 972 | + for chunk in interleaved[p * partition..(p + 1) * partition].chunks(book.dimensions) |
| 927 | - book.write(out, (value.clamp(-range, range) + range) as usize); | 973 | + { |
| 974 | + book.write(out, residue_entry(chunk, range, book.dimensions)); | ||
| 928 | } | 975 | } |
| 929 | } | 976 | } |
| 930 | p += 1; | 977 | p += 1; |
| @@ -932,6 +979,19 @@ fn write_residue( | |||
| 932 | } | 979 | } |
| 933 | } | 980 | } |
| 934 | 981 | ||
| 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 | + | ||
| 935 | /// Forward square-polar coupling (§9.4.2 run backwards). | 995 | /// Forward square-polar coupling (§9.4.2 run backwards). |
| 936 | fn couple(left: i32, right: i32) -> (i32, i32) { | 996 | fn couple(left: i32, right: i32) -> (i32, i32) { |
| 937 | match left > 0 { | 997 | match left > 0 { |
| @@ -1042,7 +1102,7 @@ fn build_floor(half: usize, points: usize) -> Floor1 { | |||
| 1042 | } | 1102 | } |
| 1043 | } | 1103 | } |
| 1044 | 1104 | ||
| 1045 | -/// Build one block size's floor and ATH curve. | 1105 | +/// Build one block size's floor, ATH curve and Bark positions. |
| 1046 | fn build_block_config( | 1106 | fn build_block_config( |
| 1047 | half: usize, | 1107 | half: usize, |
| 1048 | partition: usize, | 1108 | partition: usize, |
| @@ -1052,15 +1112,22 @@ fn build_block_config( | |||
| 1052 | config: &EncoderConfig, | 1112 | config: &EncoderConfig, |
| 1053 | ) -> BlockConfig { | 1113 | ) -> BlockConfig { |
| 1054 | let floor = build_floor(half, points); | 1114 | let floor = build_floor(half, points); |
| 1055 | - let ath = floor | 1115 | + let hz: Vec<f64> = floor |
| 1056 | .x_list | 1116 | .x_list |
| 1057 | .iter() | 1117 | .iter() |
| 1058 | - .map(|&x| { | 1118 | + .map(|&x| f64::from(config.sample_rate) * 0.5 * f64::from(x) / half as f64) |
| 1059 | - let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / half as f64; | ||
| 1060 | - absolute_threshold(hz) | ||
| 1061 | - }) | ||
| 1062 | .collect(); | 1119 | .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 | + } | ||
| 1064 | } | 1131 | } |
| 1065 | 1132 | ||
| 1066 | /// Folded floor amplitudes: mostly small corrections, occasionally an escape | 1133 | /// Folded floor amplitudes: mostly small corrections, occasionally an escape |
| @@ -1088,19 +1155,46 @@ fn design_class_book() -> CodebookSpec { | |||
| 1088 | spec | 1155 | spec |
| 1089 | } | 1156 | } |
| 1090 | 1157 | ||
| 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. | ||
| 1092 | fn design_residue_books() -> Vec<CodebookSpec> { | 1161 | fn design_residue_books() -> Vec<CodebookSpec> { |
| 1093 | CLASS_RANGE[1..] | 1162 | CLASS_RANGE[1..] |
| 1094 | .iter() | 1163 | .iter() |
| 1095 | - .map(|&range| { | 1164 | + .enumerate() |
| 1096 | - // Measured mean |value| inside a partition of each class is about | 1165 | + .map(|(offset, &range)| { |
| 1097 | - // a sixth of the class's range, whatever the range. | 1166 | + let class = offset + 1; |
| 1098 | - let sigma = f64::from(range).max(1.0) / 6.0; | 1167 | + let dimensions = RESIDUE_BOOK_DIM[class]; |
| 1099 | - let weights: Vec<f64> = (-range..=range) | 1168 | + let base = (2 * range + 1) as usize; |
| 1100 | - .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4) | 1169 | + let entries = base.pow(dimensions as u32); |
| 1101 | - .collect(); | 1170 | + let sigma = f64::from(range).max(1.0); |
| 1102 | - let values: Vec<f32> = (-range..=range).map(|v| v as f32).collect(); | 1171 | + let mut weights = Vec::with_capacity(entries); |
| 1103 | - CodebookSpec::huffman(&weights, values) | 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 | ||
| 1104 | }) | 1198 | }) |
| 1105 | .collect() | 1199 | .collect() |
| 1106 | } | 1200 | } |
| @@ -1119,6 +1213,12 @@ fn absolute_threshold(hz: f64) -> f64 { | |||
| 1119 | (spl - 96.0).clamp(-120.0, -80.0) | 1213 | (spl - 96.0).clamp(-120.0, -80.0) |
| 1120 | } | 1214 | } |
| 1121 | 1215 | ||
| 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 | + | ||
| 1122 | struct HeaderSetup<'a> { | 1222 | struct HeaderSetup<'a> { |
| 1123 | long: &'a BlockConfig, | 1223 | long: &'a BlockConfig, |
| 1124 | short: &'a BlockConfig, | 1224 | short: &'a BlockConfig, |
| @@ -1249,8 +1349,8 @@ fn write_headers(config: &EncoderConfig, channels: usize, setup: HeaderSetup<'_> | |||
| 1249 | vec![ident, comment, setup] | 1349 | vec![ident, comment, setup] |
| 1250 | } | 1350 | } |
| 1251 | 1351 | ||
| 1252 | -/// One codebook in setup-header form: flat lengths, and a scalar lookup when | 1352 | +/// One codebook in setup-header form: flat lengths and, when present, a type-1 |
| 1253 | -/// the book carries values. | 1353 | +/// lookup table carrying the scalar alphabet used by entry digits. |
| 1254 | fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) { | 1354 | fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) { |
| 1255 | out.write(0x0056_4342, 24); | 1355 | out.write(0x0056_4342, 24); |
| 1256 | out.write(book.dimensions as u32, 16); | 1356 | out.write(book.dimensions as u32, 16); |
| @@ -1264,17 +1364,21 @@ fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) { | |||
| 1264 | out.write(0, 4); | 1364 | out.write(0, 4); |
| 1265 | return; | 1365 | return; |
| 1266 | } | 1366 | } |
| 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. | ||
| 1269 | out.write(1, 4); | 1367 | 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); | ||
| 1271 | out.write(float32_pack(minimum), 32); | 1374 | out.write(float32_pack(minimum), 32); |
| 1272 | out.write(float32_pack(1.0), 32); | 1375 | 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); | ||
| 1274 | out.write(value_bits - 1, 4); | 1378 | out.write(value_bits - 1, 4); |
| 1275 | out.write(0, 1); | 1379 | out.write(0, 1); |
| 1276 | - for i in 0..book.entries() { | 1380 | + for value in 0..lookup_values { |
| 1277 | - out.write(i as u32, value_bits); | 1381 | + out.write(value as u32, value_bits); |
| 1278 | } | 1382 | } |
| 1279 | } | 1383 | } |
| 1280 | 1384 | ||
| @@ -1394,6 +1498,28 @@ mod tests { | |||
| 1394 | } | 1498 | } |
| 1395 | } | 1499 | } |
| 1396 | 1500 | ||
| 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 | + | ||
| 1397 | #[test] | 1523 | #[test] |
| 1398 | fn tail_granule_44100_mono() { | 1524 | fn tail_granule_44100_mono() { |
| 1399 | let mut enc = VorbisEncoder::new(EncoderConfig { | 1525 | let mut enc = VorbisEncoder::new(EncoderConfig { |
| @@ -1410,7 +1536,10 @@ mod tests { | |||
| 1410 | let mut n = 0; | 1536 | let mut n = 0; |
| 1411 | loop { | 1537 | loop { |
| 1412 | match enc.next_packet() { | 1538 | match enc.next_packet() { |
| 1413 | - Ok(p) => { last = p.granule; n += 1; } | 1539 | + Ok(p) => { |
| 1540 | + last = p.granule; | ||
| 1541 | + n += 1; | ||
| 1542 | + } | ||
| 1414 | Err(Error::Eof) => break, | 1543 | Err(Error::Eof) => break, |
| 1415 | Err(e) => panic!("{e}"), | 1544 | Err(e) => panic!("{e}"), |
| 1416 | } | 1545 | } |