Decoder-side residue reference — valid histogram oracle (cherry-pick 5ede0ed)
Browse files at this commit454cb750ced2ca0c14f0ee072b102e8507aa5710Parent: 2461109- test
- decoder-side residue reference — valid histogram oracle (cherry-pick 5ede0ed)
3 changed files +360 -1
- crates/ec-vorbis/src/decode.rs +26 -0
- crates/ec-vorbis/src/encode.rs +66 -0
- crates/ec-vorbis/tests/oracle.rs +268 -1
crates/ec-vorbis/src/decode.rsmodified+26 -0
| @@ -47,6 +47,12 @@ pub struct VorbisDecoder { | |||
| 47 | next_pts: Option<i64>, | 47 | next_pts: Option<i64>, |
| 48 | frames: VecDeque<Frame>, | 48 | frames: VecDeque<Frame>, |
| 49 | drained: bool, | 49 | drained: bool, |
| 50 | + /// Per-block captured decoded residue: (half, per-channel integer residue). | ||
| 51 | + /// Populated only when `enable_residue_capture` is set. | ||
| 52 | + residue_capture: Vec<(usize, Vec<Vec<i32>>)>, | ||
| 53 | + /// When true, `decode_audio` copies each block's residue (after inverse | ||
| 54 | + /// coupling, before floor multiply) into `residue_capture`. | ||
| 55 | + enable_residue_capture: bool, | ||
| 50 | } | 56 | } |
| 51 | 57 | ||
| 52 | impl VorbisDecoder { | 58 | impl VorbisDecoder { |
| @@ -85,6 +91,8 @@ impl VorbisDecoder { | |||
| 85 | next_pts: None, | 91 | next_pts: None, |
| 86 | frames: VecDeque::new(), | 92 | frames: VecDeque::new(), |
| 87 | drained: false, | 93 | drained: false, |
| 94 | + residue_capture: Vec::new(), | ||
| 95 | + enable_residue_capture: false, | ||
| 88 | ident, | 96 | ident, |
| 89 | comments, | 97 | comments, |
| 90 | setup, | 98 | setup, |
| @@ -224,6 +232,14 @@ impl VorbisDecoder { | |||
| 224 | spectra[angle] = angles; | 232 | spectra[angle] = angles; |
| 225 | } | 233 | } |
| 226 | 234 | ||
| 235 | + if self.enable_residue_capture { | ||
| 236 | + let captured: Vec<Vec<i32>> = spectra | ||
| 237 | + .iter() | ||
| 238 | + .map(|ch| ch.iter().map(|&v| v.round() as i32).collect()) | ||
| 239 | + .collect(); | ||
| 240 | + self.residue_capture.push((half, captured)); | ||
| 241 | + } | ||
| 242 | + | ||
| 227 | // Floor times residue, then out of the frequency domain. | 243 | // Floor times residue, then out of the frequency domain. |
| 228 | let window = self.windows.get(mode.block_flag, previous_long, next_long); | 244 | let window = self.windows.get(mode.block_flag, previous_long, next_long); |
| 229 | let mdct = match mode.block_flag { | 245 | let mdct = match mode.block_flag { |
| @@ -320,8 +336,18 @@ impl VorbisDecoder { | |||
| 320 | self.frames.clear(); | 336 | self.frames.clear(); |
| 321 | self.drained = false; | 337 | self.drained = false; |
| 322 | } | 338 | } |
| 339 | + | ||
| 340 | + /// Enable per-block residue capture for offline histogram analysis. | ||
| 341 | + pub fn enable_residue_capture(&mut self) { | ||
| 342 | + self.enable_residue_capture = true; | ||
| 323 | } | 343 | } |
| 324 | 344 | ||
| 345 | + /// Take the captured per-block residue: each entry is `(half, per-channel integer residue)`. | ||
| 346 | + pub fn take_residue_capture(&mut self) -> Vec<(usize, Vec<Vec<i32>>)> { | ||
| 347 | + std::mem::take(&mut self.residue_capture) | ||
| 348 | + } | ||
| 349 | + | ||
| 350 | +} | ||
| 325 | /// Vorbis channel order (§4.3.9) mapped onto [`ChannelLayout`]'s order. | 351 | /// Vorbis channel order (§4.3.9) mapped onto [`ChannelLayout`]'s order. |
| 326 | /// | 352 | /// |
| 327 | /// Vorbis orders a 5.1 stream FL, FC, FR, BL, BR, LFE and a 7.1 stream FL, FC, | 353 | /// Vorbis orders a 5.1 stream FL, FC, FR, BL, BR, LFE and a 7.1 stream FL, FC, |
crates/ec-vorbis/src/encode.rsmodified+66 -0
| @@ -262,6 +262,12 @@ pub struct VorbisEncoder { | |||
| 262 | reservoir_debt: f64, | 262 | reservoir_debt: f64, |
| 263 | finished: bool, | 263 | finished: bool, |
| 264 | packets: std::collections::VecDeque<EncodedPacket>, | 264 | packets: std::collections::VecDeque<EncodedPacket>, |
| 265 | + /// Per-block captured quantised residue: (half, per-channel quantised). | ||
| 266 | + /// Populated only when `enable_residue_capture` is set. | ||
| 267 | + residue_capture: Vec<(usize, Vec<Vec<i32>>)>, | ||
| 268 | + /// When true, `encode_block` copies each block's quantised residue into | ||
| 269 | + /// `residue_capture` for offline histogram analysis. | ||
| 270 | + enable_residue_capture: bool, | ||
| 265 | } | 271 | } |
| 266 | 272 | ||
| 267 | impl VorbisEncoder { | 273 | impl VorbisEncoder { |
| @@ -358,6 +364,8 @@ impl VorbisEncoder { | |||
| 358 | class_book, | 364 | class_book, |
| 359 | residue_books, | 365 | residue_books, |
| 360 | coupling, | 366 | coupling, |
| 367 | + residue_capture: Vec::new(), | ||
| 368 | + enable_residue_capture: false, | ||
| 361 | }) | 369 | }) |
| 362 | } | 370 | } |
| 363 | 371 | ||
| @@ -376,6 +384,21 @@ impl VorbisEncoder { | |||
| 376 | &self.params | 384 | &self.params |
| 377 | } | 385 | } |
| 378 | 386 | ||
| 387 | + /// Enable per-block quantised-residue capture for offline histogram analysis. | ||
| 388 | + pub fn enable_residue_capture(&mut self) { | ||
| 389 | + self.enable_residue_capture = true; | ||
| 390 | + } | ||
| 391 | + | ||
| 392 | + /// Take the captured per-block quantised residue: each entry is `(half, per-channel quantised)`. | ||
| 393 | + pub fn take_residue_capture(&mut self) -> Vec<(usize, Vec<Vec<i32>>)> { | ||
| 394 | + std::mem::take(&mut self.residue_capture) | ||
| 395 | + } | ||
| 396 | + | ||
| 397 | + /// Frequency in Barks for a given Hz — public so tests can bin by band. | ||
| 398 | + pub fn bark_hz(hz: f64) -> f64 { | ||
| 399 | + bark(hz) | ||
| 400 | + } | ||
| 401 | + | ||
| 379 | /// Push planar samples, one slice per channel in [`ec_core::ChannelLayout`] order. | 402 | /// Push planar samples, one slice per channel in [`ec_core::ChannelLayout`] order. |
| 380 | pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> { | 403 | pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> { |
| 381 | if channels.len() != usize::from(self.config.channels) { | 404 | if channels.len() != usize::from(self.config.channels) { |
| @@ -801,6 +824,37 @@ impl VorbisEncoder { | |||
| 801 | break (floor_values, quantised); | 824 | break (floor_values, quantised); |
| 802 | } | 825 | } |
| 803 | }; | 826 | }; |
| 827 | + if self.enable_residue_capture { | ||
| 828 | + // The bitstream stores the coupled magnitude/angle form; the | ||
| 829 | + // decoder inverse-couples before floor multiply. Capture in that | ||
| 830 | + // same per-channel domain so the histogram matches the decoder- | ||
| 831 | + // side reference capture exactly (sanity: decoding our own .ogg | ||
| 832 | + // reproduces these vectors). | ||
| 833 | + // Main codes the full `half * channels` interleaved region (no | ||
| 834 | + // HF truncation), so every bin below `half` is coded and the | ||
| 835 | + // capture keeps the whole per-channel vector. | ||
| 836 | + let coded = half; | ||
| 837 | + let mut per_channel: Vec<Vec<i32>> = quantised | ||
| 838 | + .iter() | ||
| 839 | + .map(|ch| { | ||
| 840 | + let mut v = ch[..coded].to_vec(); | ||
| 841 | + v.resize(half, 0); | ||
| 842 | + v | ||
| 843 | + }) | ||
| 844 | + .collect(); | ||
| 845 | + for &(magnitude, angle) in &self.coupling { | ||
| 846 | + let mut mags = std::mem::take(&mut per_channel[magnitude]); | ||
| 847 | + let mut angs = std::mem::take(&mut per_channel[angle]); | ||
| 848 | + for (m, a) in mags.iter_mut().zip(angs.iter_mut()) { | ||
| 849 | + let (l, r) = decouple(*m, *a); | ||
| 850 | + *m = l; | ||
| 851 | + *a = r; | ||
| 852 | + } | ||
| 853 | + per_channel[magnitude] = mags; | ||
| 854 | + per_channel[angle] = angs; | ||
| 855 | + } | ||
| 856 | + self.residue_capture.push((half, per_channel)); | ||
| 857 | + } | ||
| 804 | 858 | ||
| 805 | let mut out = BitsOut::new(); | 859 | let mut out = BitsOut::new(); |
| 806 | out.bit(false); | 860 | out.bit(false); |
| @@ -1088,6 +1142,18 @@ fn couple(left: i32, right: i32) -> (i32, i32) { | |||
| 1088 | }, | 1142 | }, |
| 1089 | } | 1143 | } |
| 1090 | } | 1144 | } |
| 1145 | +/// Inverse square-polar coupling on integer residue — the exact inverse of | ||
| 1146 | +/// [`couple`] and the integer form of the decoder's §9.4.2 step. Used only to | ||
| 1147 | +/// bring the residue capture back to per-channel (magnitude/angle undone) so it | ||
| 1148 | +/// matches the decoder-side capture domain. | ||
| 1149 | +fn decouple(m: i32, a: i32) -> (i32, i32) { | ||
| 1150 | + match (m > 0, a > 0) { | ||
| 1151 | + (true, true) => (m, m - a), | ||
| 1152 | + (true, false) => (m + a, m), | ||
| 1153 | + (false, true) => (m, m + a), | ||
| 1154 | + (false, false) => (m - a, m), | ||
| 1155 | + } | ||
| 1156 | +} | ||
| 1091 | 1157 | ||
| 1092 | /// §7.2.2 `render_point`, which both sides of the floor coding need. | 1158 | /// §7.2.2 `render_point`, which both sides of the floor coding need. |
| 1093 | fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { | 1159 | fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { |
crates/ec-vorbis/tests/oracle.rsmodified+268 -1
| @@ -748,7 +748,246 @@ fn quiet_content_reaches_the_target_or_is_transparent() { | |||
| 748 | } | 748 | } |
| 749 | } | 749 | } |
| 750 | 750 | ||
| 751 | +/// Per-Bark-band quantised-residue histogram comparison: ours vs libvorbis | ||
| 752 | +/// reference. We encode the source with our encoder (capturing residue), then | ||
| 753 | +/// encode the same source with libvorbis and decode that stream with our own | ||
| 754 | +/// decoder, capturing its decoded residue (after inverse coupling, before | ||
| 755 | +/// floor multiply — the same domain as the encoder's `quantised`). The | ||
| 756 | +/// reference is libvorbis's own residue, so per-band divergence names where | ||
| 757 | +/// our psy spends differently from libvorbis. | ||
| 758 | +#[test] | ||
| 759 | +#[ignore = "slow: encodes 7 sources × 128k, needs ffmpeg/libvorbis"] | ||
| 760 | +fn residue_histogram_vs_reference() { | ||
| 761 | + use std::io::Write; | ||
| 762 | + | ||
| 763 | + let sources: &[(&str, &str)] = &[ | ||
| 764 | + ("nik", "~/Music/reeln.mp4"), | ||
| 765 | + ("reelo", "~/Music/reelo.mp3"), | ||
| 766 | + ("her", "~/Music/reeli.mp3"), | ||
| 767 | + ("reell", "~/Music/reell.mp4"), | ||
| 768 | + ("reelm", "~/Music/reelm.wav"), | ||
| 769 | + ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), | ||
| 770 | + ("hein", "~/Downloads/reelm.mp3"), | ||
| 771 | + ]; | ||
| 772 | + let bitrate = 128_000i32; | ||
| 773 | + let rate = 48_000u32; | ||
| 774 | + let channels = 2u16; | ||
| 775 | + // Limit to ~12 s for speed — enough blocks for a stable histogram. | ||
| 776 | + let max_samples = rate as usize * 12; | ||
| 777 | + | ||
| 778 | + let out_dir = scratch().join("vorbis7"); | ||
| 779 | + std::fs::create_dir_all(&out_dir).expect("out dir"); | ||
| 780 | + let mut report = String::new(); | ||
| 781 | + report.push_str("# Residue histogram: ours vs libvorbis reference\n\n"); | ||
| 782 | + report.push_str(&format!("Bitrate: {} kbps, {} Hz, {}ch, {} s max\n\n", | ||
| 783 | + bitrate / 1000, rate, channels, max_samples / rate as usize)); | ||
| 784 | + | ||
| 785 | + for &(name, src_path) in sources { | ||
| 786 | + let expanded = shellexpand(src_path); | ||
| 787 | + let src = PathBuf::from(&expanded); | ||
| 788 | + if !src.exists() { | ||
| 789 | + report.push_str(&format!("## {name}: SKIP (file not found: {expanded})\n\n")); | ||
| 790 | + continue; | ||
| 791 | + } | ||
| 792 | + // Decode source with ffmpeg, limit duration. | ||
| 793 | + let Some((source_pcm, src_rate)) = ffmpeg_decode_limited(&src, rate, max_samples) else { | ||
| 794 | + report.push_str(&format!("## {name}: SKIP (ffmpeg decode failed)\n\n")); | ||
| 795 | + continue; | ||
| 796 | + }; | ||
| 797 | + if source_pcm.len() < 2 || source_pcm[0].is_empty() { | ||
| 798 | + report.push_str(&format!("## {name}: SKIP (empty decode)\n\n")); | ||
| 799 | + continue; | ||
| 800 | + } | ||
| 801 | + // Resample to 48k if needed — ffmpeg_decode_limited already targets 48k. | ||
| 802 | + let _ = src_rate; | ||
| 803 | + | ||
| 804 | + // --- Ours: encode source with our encoder, capture residue, keep the ogg --- | ||
| 805 | + let ours_ogg = out_dir.join(format!("ours-{name}-128k.ogg")); | ||
| 806 | + let (ours_residue, ours_bytes) = | ||
| 807 | + encode_and_capture(&source_pcm, rate, channels, bitrate, &ours_ogg); | ||
| 808 | + | ||
| 809 | + // --- Sanity: decoding our own ogg with capture on must reproduce the | ||
| 810 | + // encoder's capture band for band, or the two captures are not in the | ||
| 811 | + // same domain and the table below means nothing. --- | ||
| 812 | + let roundtrip = decode_capture(&ours_ogg); | ||
| 813 | + let (sanity_ok, sanity_detail) = compare_captures(&ours_residue, &roundtrip, rate); | ||
| 814 | + | ||
| 815 | + // --- Reference: encode with libvorbis, decode with OUR decoder, capture --- | ||
| 816 | + let ref_ogg = out_dir.join(format!("ref-{name}-128k.ogg")); | ||
| 817 | + let ref_status = Command::new("ffmpeg") | ||
| 818 | + .args(["-y", "-v", "error", "-i"]) | ||
| 819 | + .arg(&src) | ||
| 820 | + .args(["-t", &format!("{}", max_samples / rate as usize), | ||
| 821 | + "-ac", "2", "-ar", "48000", | ||
| 822 | + "-c:a", "libvorbis", "-b:a", "128k"]) | ||
| 823 | + .arg(&ref_ogg) | ||
| 824 | + .status(); | ||
| 825 | + let ref_residue = match ref_status { | ||
| 826 | + Ok(s) if s.success() => decode_capture(&ref_ogg), | ||
| 827 | + _ => { | ||
| 828 | + report.push_str(&format!("## {name}: libvorbis encode failed\n\n")); | ||
| 829 | + continue; | ||
| 830 | + } | ||
| 831 | + }; | ||
| 832 | + let ref_bytes = std::fs::metadata(&ref_ogg).expect("ref ogg").len(); | ||
| 833 | + | ||
| 834 | + // --- Build per-Bark-band histograms --- | ||
| 835 | + let bins = 6; // |q|: 0, 1, 2, 3-4, 5-8, 9+ | ||
| 836 | + let max_bark = 25; | ||
| 837 | + let mut ours_hist = vec![vec![0u64; bins]; max_bark]; | ||
| 838 | + let mut ref_hist = vec![vec![0u64; bins]; max_bark]; | ||
| 839 | + for (half, quantised) in &ours_residue { | ||
| 840 | + accumulate(quantised, *half, rate, &mut ours_hist, max_bark); | ||
| 841 | + } | ||
| 842 | + for (half, quantised) in &ref_residue { | ||
| 843 | + accumulate(quantised, *half, rate, &mut ref_hist, max_bark); | ||
| 844 | + } | ||
| 845 | + | ||
| 846 | + report.push_str(&format!( | ||
| 847 | + "## {name} — sanity {}: {} — ours {} B vs ref {} B ({:.2}x)\n\n", | ||
| 848 | + if sanity_ok { "PASS" } else { "FAIL" }, | ||
| 849 | + sanity_detail, | ||
| 850 | + ours_bytes, | ||
| 851 | + ref_bytes, | ||
| 852 | + ours_bytes as f64 / ref_bytes as f64 | ||
| 853 | + )); | ||
| 854 | + report.push_str("| Bark | q=0 ours/ref | q=1 | q=2 | q=3-4 | q=5-8 | q=9+ | total ours/ref | spend ratio |\n"); | ||
| 855 | + report.push_str("|------|-------------|-----|-----|-------|-------|------|-----------------|-------------|\n"); | ||
| 856 | + for band in 0..max_bark { | ||
| 857 | + let o = &ours_hist[band]; | ||
| 858 | + let r = &ref_hist[band]; | ||
| 859 | + let o_total: u64 = o.iter().sum(); | ||
| 860 | + let r_total: u64 = r.iter().sum(); | ||
| 861 | + if o_total == 0 && r_total == 0 { | ||
| 862 | + continue; | ||
| 863 | + } | ||
| 864 | + // "Spend" = non-zero entries (bins 1..) — proxy for bits spent. | ||
| 865 | + let o_spend: u64 = o[1..].iter().sum(); | ||
| 866 | + let r_spend: u64 = r[1..].iter().sum(); | ||
| 867 | + let ratio = if r_spend > 0 { | ||
| 868 | + o_spend as f64 / r_spend as f64 | ||
| 869 | + } else { f64::INFINITY }; | ||
| 870 | + report.push_str(&format!( | ||
| 871 | + "| {} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {:.2} |\n", | ||
| 872 | + band, o[0], r[0], o[1], r[1], o[2], r[2], o[3], r[3], o[4], r[4], o[5], r[5], | ||
| 873 | + o_total, r_total, ratio, | ||
| 874 | + )); | ||
| 875 | + } | ||
| 876 | + report.push_str("\n"); | ||
| 877 | + } | ||
| 878 | + | ||
| 879 | + let report_path = out_dir.join("histogram.txt"); | ||
| 880 | + let mut f = File::create(&report_path).expect("create report"); | ||
| 881 | + f.write_all(report.as_bytes()).expect("write report"); | ||
| 882 | + println!("Histogram report: {}", report_path.display()); | ||
| 883 | + // Also print to stdout for immediate viewing. | ||
| 884 | + print!("{report}"); | ||
| 885 | +} | ||
| 886 | + | ||
| 887 | +/// Encode PCM with our encoder, capturing per-block quantised residue, and mux | ||
| 888 | +/// the result to `out` so it can be decoded back (sanity check + rate). | ||
| 889 | +fn encode_and_capture( | ||
| 890 | + source: &[Vec<f32>], | ||
| 891 | + rate: u32, | ||
| 892 | + channels: u16, | ||
| 893 | + bitrate: i32, | ||
| 894 | + out: &Path, | ||
| 895 | +) -> (Vec<(usize, Vec<Vec<i32>>)>, u64) { | ||
| 896 | + let mut encoder = VorbisEncoder::new(EncoderConfig { | ||
| 897 | + sample_rate: rate, | ||
| 898 | + channels, | ||
| 899 | + bitrate_bps: bitrate, | ||
| 900 | + quality: 0.6, | ||
| 901 | + }) | ||
| 902 | + .expect("encoder"); | ||
| 903 | + encoder.enable_residue_capture(); | ||
| 904 | + let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect(); | ||
| 905 | + encoder.push_planar(&borrowed).expect("push"); | ||
| 906 | + encoder.finish(); | ||
| 907 | + let mut packets = Vec::new(); | ||
| 908 | + loop { | ||
| 909 | + match encoder.next_packet() { | ||
| 910 | + Ok(packet) => packets.push((packet.data, packet.granule)), | ||
| 911 | + Err(e) if e.is_eof() => break, | ||
| 912 | + Err(e) => panic!("encode: {e}"), | ||
| 913 | + } | ||
| 914 | + } | ||
| 915 | + mux(out, &encoder, &packets, rate, channels); | ||
| 916 | + let bytes = std::fs::metadata(out).expect("muxed file").len(); | ||
| 917 | + (encoder.take_residue_capture(), bytes) | ||
| 918 | +} | ||
| 919 | + | ||
| 920 | +/// Decode with ours, capturing per-block residue (after inverse coupling, | ||
| 921 | +/// before floor multiply) — the decoder-side view of the same domain the | ||
| 922 | +/// encoder captures. | ||
| 923 | +fn decode_capture(path: &Path) -> Vec<(usize, Vec<Vec<i32>>)> { | ||
| 924 | + let mut demuxer = OggDemuxer::open(File::open(path).expect("open")).expect("ogg"); | ||
| 925 | + let stream = demuxer | ||
| 926 | + .streams() | ||
| 927 | + .iter() | ||
| 928 | + .find(|s| s.params.codec == ec_core::CodecId::Vorbis) | ||
| 929 | + .expect("a Vorbis stream") | ||
| 930 | + .clone(); | ||
| 931 | + let extradata = stream.params.extradata.clone().expect("headers"); | ||
| 932 | + let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse"); | ||
| 933 | + decoder.enable_residue_capture(); | ||
| 934 | + loop { | ||
| 935 | + let packet = match demuxer.next_packet() { | ||
| 936 | + Ok(packet) => packet, | ||
| 937 | + Err(e) if e.is_eof() => break, | ||
| 938 | + Err(e) => panic!("demux {}: {e}", path.display()), | ||
| 939 | + }; | ||
| 940 | + if packet.stream != stream.index { | ||
| 941 | + continue; | ||
| 942 | + } | ||
| 943 | + // A packet the decoder cannot use is skipped, like in `our_decode`. | ||
| 944 | + if decoder.decode_audio(&packet.data).is_err() { | ||
| 945 | + continue; | ||
| 946 | + } | ||
| 947 | + } | ||
| 948 | + decoder.take_residue_capture() | ||
| 949 | +} | ||
| 751 | 950 | ||
| 951 | +/// Bin two captures by Bark and compare every histogram cell. | ||
| 952 | +fn compare_captures( | ||
| 953 | + a: &[(usize, Vec<Vec<i32>>)], | ||
| 954 | + b: &[(usize, Vec<Vec<i32>>)], | ||
| 955 | + rate: u32, | ||
| 956 | +) -> (bool, String) { | ||
| 957 | + let bins = 6; | ||
| 958 | + let max_bark = 25; | ||
| 959 | + let mut ha = vec![vec![0u64; bins]; max_bark]; | ||
| 960 | + let mut hb = vec![vec![0u64; bins]; max_bark]; | ||
| 961 | + for (half, q) in a { | ||
| 962 | + accumulate(q, *half, rate, &mut ha, max_bark); | ||
| 963 | + } | ||
| 964 | + for (half, q) in b { | ||
| 965 | + accumulate(q, *half, rate, &mut hb, max_bark); | ||
| 966 | + } | ||
| 967 | + let mut diffs = Vec::new(); | ||
| 968 | + for band in 0..max_bark { | ||
| 969 | + for bucket in 0..bins { | ||
| 970 | + if ha[band][bucket] != hb[band][bucket] { | ||
| 971 | + diffs.push(format!( | ||
| 972 | + "bark {band} q{bucket}: {} vs {}", | ||
| 973 | + ha[band][bucket], hb[band][bucket] | ||
| 974 | + )); | ||
| 975 | + } | ||
| 976 | + } | ||
| 977 | + } | ||
| 978 | + if diffs.is_empty() { | ||
| 979 | + (true, format!("identical histograms ({} vs {} blocks)", a.len(), b.len())) | ||
| 980 | + } else { | ||
| 981 | + (false, format!( | ||
| 982 | + "{} vs {} blocks; first diffs: {}", | ||
| 983 | + a.len(), | ||
| 984 | + b.len(), | ||
| 985 | + diffs.iter().take(5).cloned().collect::<Vec<_>>().join("; ") | ||
| 986 | + )) | ||
| 987 | + } | ||
| 988 | +} | ||
| 989 | + | ||
| 990 | +/// Decode with ffmpeg into planar f32, resampled to `rate`, limited to `max_samples`. | ||
| 752 | fn ffmpeg_decode_limited(path: &Path, rate: u32, max_samples: usize) -> Option<(Vec<Vec<f32>>, u32)> { | 991 | fn ffmpeg_decode_limited(path: &Path, rate: u32, max_samples: usize) -> Option<(Vec<Vec<f32>>, u32)> { |
| 753 | let out = Command::new("ffmpeg") | 992 | let out = Command::new("ffmpeg") |
| 754 | .args(["-v", "error", "-i"]) | 993 | .args(["-v", "error", "-i"]) |
| @@ -777,8 +1016,36 @@ fn ffmpeg_decode_limited(path: &Path, rate: u32, max_samples: usize) -> Option<( | |||
| 777 | Some((planes, rate)) | 1016 | Some((planes, rate)) |
| 778 | } | 1017 | } |
| 779 | 1018 | ||
| 1019 | +/// Accumulate per-Bark-band |q| histograms from quantised residue. | ||
| 1020 | +fn accumulate( | ||
| 1021 | + quantised: &[Vec<i32>], | ||
| 1022 | + half: usize, | ||
| 1023 | + rate: u32, | ||
| 1024 | + hist: &mut [Vec<u64>], | ||
| 1025 | + max_bark: usize, | ||
| 1026 | +) { | ||
| 1027 | + for channel in quantised { | ||
| 1028 | + for (bin, &q) in channel.iter().enumerate() { | ||
| 1029 | + if bin >= half { | ||
| 1030 | + break; | ||
| 1031 | + } | ||
| 1032 | + let hz = bin as f64 * f64::from(rate) / (2.0 * half as f64); | ||
| 1033 | + let bark = VorbisEncoder::bark_hz(hz) as usize; | ||
| 1034 | + let band = bark.min(max_bark - 1); | ||
| 1035 | + let bucket = match q.abs() { | ||
| 1036 | + 0 => 0, | ||
| 1037 | + 1 => 1, | ||
| 1038 | + 2 => 2, | ||
| 1039 | + 3..=4 => 3, | ||
| 1040 | + 5..=8 => 4, | ||
| 1041 | + _ => 5, | ||
| 1042 | + }; | ||
| 1043 | + hist[band][bucket] += 1; | ||
| 1044 | + } | ||
| 1045 | + } | ||
| 1046 | +} | ||
| 780 | 1047 | ||
| 781 | - | 1048 | +/// Expand `~` in a path string. |
| 782 | fn shellexpand(path: &str) -> String { | 1049 | fn shellexpand(path: &str) -> String { |
| 783 | if let Some(rest) = path.strip_prefix("~/") { | 1050 | if let Some(rest) = path.strip_prefix("~/") { |
| 784 | let home = std::env::var("HOME").unwrap_or_else(|_| "/home".to_string()); | 1051 | let home = std::env::var("HOME").unwrap_or_else(|_| "/home".to_string()); |