forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

oracle.rs1735 lines, 66.5 KiBHistoryRawDownload
1//! Vorbis against the world: the Xiph decoder vectors, this repo's fixtures,
2//! and our own encoder's output decoded by ffmpeg *and* by us.
3//!
4//! ffmpeg is the oracle for decode agreement (labelled as such — this is not an
5//! ISO conformance claim), and the lossless property under test on the encode
6//! side is the timing one: a file must decode to exactly as many samples as
7//! went in, with no pre-roll and no grid overshoot.
8
9use std::fs::File;
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13use ec_core::{Decoder, Demuxer, Frame};
14use ec_ogg::{OggDemuxer, granule_of};
15use ec_vorbis::{BlockLog, EncoderConfig, VorbisDecoder, VorbisEncoder};
16
17fn fixtures() -> PathBuf {
18 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
19}
20
21fn scratch() -> PathBuf {
22 let dir = std::env::temp_dir().join(format!("ec-vorbis-{}", std::process::id()));
23 std::fs::create_dir_all(&dir).expect("scratch dir");
24 dir
25}
26
27/// Decode with ffmpeg into planar f32, one vector per channel.
28///
29/// Answers [`None`] when ffmpeg itself refuses the file — the chained Xiph
30/// vectors change channel count mid-file, which ffmpeg's Ogg demuxer states it
31/// does not implement. Those files are still decoded by us, just without an
32/// oracle to compare against.
33fn ffmpeg_decode(path: &Path) -> Option<(Vec<Vec<f32>>, u32)> {
34 // Key=value rather than csv: ffprobe prints the fields in its own order,
35 // not the order they were asked for, and a positional parse of that reads
36 // the sample rate as a channel count.
37 let channels: usize = probe_field(path, "channels")?.parse().ok()?;
38 let rate: u32 = probe_field(path, "sample_rate")?.parse().ok()?;
39
40 let out = Command::new("ffmpeg")
41 .args(["-v", "error", "-i"])
42 .arg(path)
43 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
44 .output()
45 .expect("ffmpeg runs");
46 if !out.stderr.is_empty() {
47 return None;
48 }
49 let interleaved: Vec<f32> = out
50 .stdout
51 .as_chunks::<4>()
52 .0
53 .iter()
54 .map(|b| f32::from_le_bytes(*b))
55 .collect();
56 let mut planes = vec![Vec::with_capacity(interleaved.len() / channels); channels];
57 for (i, value) in interleaved.into_iter().enumerate() {
58 planes[i % channels].push(value);
59 }
60 Some((planes, rate))
61}
62
63/// One `stream=` field of the first audio stream.
64fn probe_field(path: &Path, field: &str) -> Option<String> {
65 let out = Command::new("ffprobe")
66 .args([
67 "-v",
68 "error",
69 "-select_streams",
70 "a:0",
71 "-show_entries",
72 &format!("stream={field}"),
73 "-of",
74 "default=noprint_wrappers=1:nokey=1",
75 ])
76 .arg(path)
77 .output()
78 .expect("ffprobe runs");
79 let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
80 match text.is_empty() || text == "N/A" {
81 true => None,
82 false => Some(text),
83 }
84}
85
86/// Decode with ours, trimming exactly the way an Ogg player does: the first
87/// page's granule says how much of the first block is before the start of the
88/// stream, and the last page's granule says where it ends.
89fn our_decode(path: &Path) -> (Vec<Vec<f32>>, u32) {
90 let mut demuxer = OggDemuxer::open(File::open(path).expect("open")).expect("ogg");
91 let stream = demuxer
92 .streams()
93 .iter()
94 .find(|s| s.params.codec == ec_core::CodecId::Vorbis)
95 .expect("a Vorbis stream")
96 .clone();
97 let extradata = stream.params.extradata.clone().expect("headers");
98 let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse");
99 let rate = stream
100 .params
101 .audio()
102 .map(|a| a.sample_rate)
103 .expect("audio params");
104
105 let mut planes: Vec<Vec<f32>> = Vec::new();
106 let mut offset: Option<i64> = None;
107 let mut last_granule = 0i64;
108 let mut produced = 0i64;
109 loop {
110 let packet = match demuxer.next_packet() {
111 Ok(packet) => packet,
112 Err(e) if e.is_eof() => break,
113 Err(e) => panic!("demux {}: {e}", path.display()),
114 };
115 if packet.stream != stream.index {
116 continue;
117 }
118 // A packet a decoder cannot use is skipped, not fatal: the Xiph
119 // `unused-mode` vector states a mode number its own setup header never
120 // defined, and ffmpeg skips those packets too.
121 let Ok(decoded) = decoder.decode_audio(&packet.data) else {
122 continue;
123 };
124 if planes.is_empty() {
125 planes = vec![Vec::new(); decoded.len()];
126 }
127 for (channel, samples) in decoded.iter().enumerate() {
128 planes[channel].extend_from_slice(samples);
129 }
130 produced += decoded.first().map_or(0, Vec::len) as i64;
131 if let Some(granule) = granule_of(&packet) {
132 if offset.is_none() {
133 offset = Some(granule - produced);
134 }
135 last_granule = granule;
136 }
137 }
138 let offset = offset.unwrap_or(0);
139 let front = (-offset).max(0) as usize;
140 let end = (last_granule - offset).max(0) as usize;
141 for plane in &mut planes {
142 let end = end.min(plane.len());
143 let front = front.min(end);
144 *plane = plane[front..end].to_vec();
145 }
146 (planes, rate)
147}
148
149/// Normalised cross-correlation of two signals over their common length.
150fn correlation(a: &[f32], b: &[f32]) -> f64 {
151 let n = a.len().min(b.len());
152 if n == 0 {
153 return 0.0;
154 }
155 let mut sum_ab = 0.0f64;
156 let mut sum_aa = 0.0f64;
157 let mut sum_bb = 0.0f64;
158 for i in 0..n {
159 let (x, y) = (f64::from(a[i]), f64::from(b[i]));
160 sum_ab += x * y;
161 sum_aa += x * x;
162 sum_bb += y * y;
163 }
164 match sum_aa > 0.0 && sum_bb > 0.0 {
165 true => sum_ab / (sum_aa.sqrt() * sum_bb.sqrt()),
166 // Two silent signals agree; one silent and one not does not.
167 false => f64::from(u8::from(sum_aa == sum_bb)),
168 }
169}
170
171fn rms(values: &[f32]) -> f64 {
172 match values.is_empty() {
173 true => 0.0,
174 false => (values
175 .iter()
176 .map(|v| f64::from(*v) * f64::from(*v))
177 .sum::<f64>()
178 / values.len() as f64)
179 .sqrt(),
180 }
181}
182
183/// Every `.ogg` in a fixture directory, sorted.
184fn ogg_files(dir: &Path) -> Vec<PathBuf> {
185 let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
186 .unwrap_or_else(|e| panic!("read {}: {e}", dir.display()))
187 .filter_map(|entry| entry.ok().map(|e| e.path()))
188 .filter(|p| p.extension().is_some_and(|e| e == "ogg"))
189 .collect();
190 files.sort();
191 files
192}
193
194#[test]
195fn xiph_vectors_decode_like_ffmpeg() {
196 let dir = fixtures().join("vectors/vorbis-xiph");
197 let files = ogg_files(&dir);
198 assert!(
199 files.len() >= 20,
200 "expected the Xiph vector set, got {}",
201 files.len()
202 );
203 let mut failures = Vec::new();
204 for file in &files {
205 let name = file.file_name().unwrap().to_string_lossy().to_string();
206 let (ours, our_rate) = our_decode(file);
207 let Some((theirs, their_rate)) = ffmpeg_decode(file) else {
208 // No oracle for this one: hold it to what can still be checked,
209 // that it decodes at all and is not silence.
210 let energy: f64 = ours.iter().map(|c| rms(c)).sum();
211 println!(
212 "{name}: ffmpeg refuses this file; ours decodes {} ch, rms sum {energy:.5}",
213 ours.len()
214 );
215 if ours.is_empty() || energy <= 0.0 {
216 failures.push(format!("{name}: decoded to nothing"));
217 }
218 continue;
219 };
220 if our_rate != their_rate || ours.len() != theirs.len() {
221 failures.push(format!(
222 "{name}: {our_rate} Hz x{} vs ffmpeg {their_rate} Hz x{}",
223 ours.len(),
224 theirs.len()
225 ));
226 continue;
227 }
228 for (channel, (mine, theirs)) in ours.iter().zip(theirs.iter()).enumerate() {
229 let corr = correlation(mine, theirs);
230 let length = (mine.len() as i64 - theirs.len() as i64).abs();
231 println!(
232 "{name} ch{channel}: corr {corr:.6} len {} vs {} (delta {length}) rms {:.5}/{:.5}",
233 mine.len(),
234 theirs.len(),
235 rms(mine),
236 rms(theirs)
237 );
238 if corr < 0.999 || length > 0 {
239 failures.push(format!(
240 "{name} ch{channel}: corr {corr:.6}, length delta {length}"
241 ));
242 }
243 }
244 }
245 assert!(
246 failures.is_empty(),
247 "{} failed:\n{}",
248 failures.len(),
249 failures.join("\n")
250 );
251}
252
253#[test]
254fn repo_fixtures_decode_like_ffmpeg_including_surround() {
255 let dir = fixtures().join("audio");
256 let files: Vec<PathBuf> = ogg_files(&dir)
257 .into_iter()
258 .filter(|p| {
259 p.file_name()
260 .unwrap()
261 .to_string_lossy()
262 .starts_with("vorbis-")
263 })
264 .collect();
265 assert!(!files.is_empty(), "no vorbis fixtures in {}", dir.display());
266 let mut failures = Vec::new();
267 for file in &files {
268 let (theirs, _) = ffmpeg_decode(file).expect("ffmpeg decodes the repo fixtures");
269 let (ours, _) = our_decode(file);
270 let name = file.file_name().unwrap().to_string_lossy().to_string();
271 for (channel, (mine, reference)) in ours.iter().zip(theirs.iter()).enumerate() {
272 let corr = correlation(mine, reference);
273 println!(
274 "{name} ch{channel}: corr {corr:.6} len {} vs {}",
275 mine.len(),
276 reference.len()
277 );
278 if corr < 0.999 || mine.len() != reference.len() {
279 failures.push(format!("{name} ch{channel}: corr {corr:.6}"));
280 }
281 }
282 }
283 assert!(failures.is_empty(), "{}", failures.join("\n"));
284}
285
286/// A test signal with a different tone in every channel, so a channel-order
287/// mistake shows up as a correlation of nearly zero rather than a subtlety.
288fn tones(channels: usize, rate: u32, samples: usize) -> Vec<Vec<f32>> {
289 (0..channels)
290 .map(|channel| {
291 let hz = 220.0 * f64::from(channel as u32 + 1);
292 (0..samples)
293 .map(|i| {
294 let t = i as f64 / f64::from(rate);
295 // A slow envelope so the encoder has to track something.
296 let envelope = 0.5 + 0.4 * (2.0 * std::f64::consts::PI * 0.7 * t).sin();
297 (envelope * (2.0 * std::f64::consts::PI * hz * t).sin() * 0.6) as f32
298 })
299 .collect()
300 })
301 .collect()
302}
303
304/// Write our packets into an Ogg file with the ec-ogg muxer.
305fn mux(path: &Path, encoder: &VorbisEncoder, packets: &[(Vec<u8>, i64)], rate: u32, channels: u16) {
306 use ec_core::{
307 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer,
308 Packet, StreamInfo, TimeBase,
309 };
310 let base = TimeBase::new(1, i64::from(rate));
311 let mut params = CodecParameters::new(CodecId::Vorbis);
312 params.media = MediaParameters::Audio(AudioParameters {
313 sample_rate: rate,
314 layout: ChannelLayout::from_count(usize::from(channels)),
315 format: None,
316 bits_per_sample: None,
317 });
318 params.extradata = Some(Buf::from_vec(encoder.extradata()));
319 let file = File::create(path).expect("create");
320 let mut muxer = ec_ogg::OggMuxer::new(file);
321 muxer
322 .add_stream(StreamInfo::new(0, base, params))
323 .expect("add stream");
324 muxer.write_headers().expect("headers");
325 for (data, granule) in packets {
326 let mut packet = Packet::new(0, base, data.clone());
327 packet.side_data.push(ec_ogg::granule_side_data(*granule));
328 muxer.write_packet(&packet).expect("packet");
329 }
330 muxer.finish().expect("finish");
331}
332
333/// Encode `source` and answer the file it was written to.
334fn encode_to_file(source: &[Vec<f32>], rate: u32, bitrate: i32, name: &str) -> PathBuf {
335 let channels = source.len() as u16;
336 let mut encoder = VorbisEncoder::new(EncoderConfig {
337 sample_rate: rate,
338 channels,
339 bitrate_bps: bitrate,
340 quality: 0.6,
341 })
342 .expect("encoder");
343 let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect();
344 encoder.push_planar(&borrowed).expect("push");
345 encoder.finish();
346 let mut packets = Vec::new();
347 loop {
348 match encoder.next_packet() {
349 Ok(packet) => packets.push((packet.data, packet.granule)),
350 Err(e) if e.is_eof() => break,
351 Err(e) => panic!("encode: {e}"),
352 }
353 }
354 let path = scratch().join(name);
355 mux(&path, &encoder, &packets, rate, channels);
356 path
357}
358
359/// Like [`encode_to_file`] but also returns the per-block rate-loop log.
360fn encode_to_file_with_log(
361 source: &[Vec<f32>],
362 rate: u32,
363 bitrate: i32,
364 name: &str,
365) -> (PathBuf, Vec<BlockLog>) {
366 let channels = source.len() as u16;
367 let mut encoder = VorbisEncoder::new(EncoderConfig {
368 sample_rate: rate,
369 channels,
370 bitrate_bps: bitrate,
371 quality: 0.6,
372 })
373 .expect("encoder");
374 encoder.enable_block_log();
375 let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect();
376 encoder.push_planar(&borrowed).expect("push");
377 encoder.finish();
378 let mut packets = Vec::new();
379 loop {
380 match encoder.next_packet() {
381 Ok(packet) => packets.push((packet.data, packet.granule)),
382 Err(e) if e.is_eof() => break,
383 Err(e) => panic!("encode: {e}"),
384 }
385 }
386 let log = encoder.take_block_log();
387 let path = scratch().join(name);
388 mux(&path, &encoder, &packets, rate, channels);
389 (path, log)
390}
391
392/// Duration ffprobe reports, in samples of the stream's own rate.
393fn probed_samples(path: &Path) -> i64 {
394 probe_field(path, "duration_ts")
395 .and_then(|text| text.parse().ok())
396 .unwrap_or(-1)
397}
398
399#[test]
400fn encoded_streams_decode_cleanly_at_the_stated_length() {
401 let rate = 48_000u32;
402 let samples = rate as usize * 2;
403 let mut failures = Vec::new();
404 for channels in [1usize, 2, 6] {
405 let source = tones(channels, rate, samples);
406 for bitrate in [96_000i32, 128_000, 192_000] {
407 let name = format!("enc-{channels}ch-{}k.ogg", bitrate / 1000);
408 let path = encode_to_file(&source, rate, bitrate, &name);
409 let bytes = std::fs::metadata(&path).expect("file").len();
410 let measured = bytes as f64 * 8.0 * f64::from(rate) / samples as f64 / 1000.0;
411
412 // ffmpeg decodes it without a word of complaint...
413 let Some((theirs, _)) = ffmpeg_decode(&path) else {
414 failures.push(format!("{name}: ffmpeg refused the file"));
415 continue;
416 };
417 // ...for exactly as long as the input was.
418 let duration = probed_samples(&path);
419 if duration != samples as i64 {
420 failures.push(format!(
421 "{name}: ffprobe says {duration} samples, source is {samples}"
422 ));
423 }
424 let mut worst = 1.0f64;
425 for (channel, reference) in source.iter().enumerate() {
426 let corr = correlation(&theirs[channel], reference);
427 worst = worst.min(corr);
428 }
429 // ...and our own decoder agrees with ffmpeg about what it says.
430 let (ours, _) = our_decode(&path);
431 let mut agreement = 1.0f64;
432 for (mine, theirs) in ours.iter().zip(theirs.iter()) {
433 agreement = agreement.min(correlation(mine, theirs));
434 }
435 println!(
436 "{name}: {measured:.0} kbps, corr vs source {worst:.4}, ours vs ffmpeg {agreement:.6}, samples {duration}"
437 );
438 let bar = match channels {
439 6 => 0.9,
440 _ => 0.95,
441 };
442 if worst < bar {
443 failures.push(format!("{name}: corr vs source {worst:.4} under {bar}"));
444 }
445 if agreement < 0.999 {
446 failures.push(format!(
447 "{name}: our decode disagrees with ffmpeg ({agreement:.6})"
448 ));
449 }
450 }
451 }
452 assert!(failures.is_empty(), "{}", failures.join("\n"));
453}
454
455/// The `Decoder` trait's own EOS path — `send_packet`/`receive_frame` until
456/// exhausted, then `flush` — has to deliver the terminal block's last hop:
457/// without it, decode is always exactly one hop short of the encoded length.
458#[test]
459fn flush_delivers_the_terminal_hop() {
460 let rate = 48_000u32;
461 let hop = 1024usize;
462 // Not a multiple of the hop, so the tail block's un-overlapped half is
463 // the only place these trailing samples can come from.
464 let samples = rate as usize * 2 + 777;
465 let source = tones(2, rate, samples);
466 let path = encode_to_file(&source, rate, 128_000, "flush-tail.ogg");
467
468 let mut demuxer = OggDemuxer::open(File::open(&path).expect("open")).expect("ogg");
469 let stream = demuxer
470 .streams()
471 .iter()
472 .find(|s| s.params.codec == ec_core::CodecId::Vorbis)
473 .expect("a Vorbis stream")
474 .clone();
475 let extradata = stream.params.extradata.clone().expect("headers");
476 let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse");
477
478 let mut planes: Vec<Vec<f32>> = Vec::new();
479 let mut offset: Option<i64> = None;
480 let mut last_granule = 0i64;
481 let mut produced = 0i64;
482 let push_frame = |frame: ec_core::AudioFrame, planes: &mut Vec<Vec<f32>>| {
483 if planes.is_empty() {
484 *planes = vec![Vec::new(); frame.channels()];
485 }
486 for (channel, plane) in planes.iter_mut().enumerate() {
487 let bytes = &frame.data[channel];
488 for chunk in bytes.as_chunks::<4>().0.iter().take(frame.samples) {
489 plane.push(f32::from_le_bytes(*chunk));
490 }
491 }
492 frame.samples as i64
493 };
494 loop {
495 let packet = match demuxer.next_packet() {
496 Ok(packet) => packet,
497 Err(e) if e.is_eof() => break,
498 Err(e) => panic!("demux: {e}"),
499 };
500 if packet.stream != stream.index {
501 continue;
502 }
503 decoder.send_packet(&packet).expect("send_packet");
504 loop {
505 match decoder.receive_frame() {
506 Ok(Frame::Audio(frame)) => produced += push_frame(frame, &mut planes),
507 Ok(Frame::Video(_)) => unreachable!("Vorbis decodes to audio only"),
508 Err(e) if e.is_need_more() => break,
509 Err(e) => panic!("receive_frame: {e}"),
510 }
511 }
512 if let Some(granule) = granule_of(&packet) {
513 if offset.is_none() {
514 offset = Some(granule - produced);
515 }
516 last_granule = granule;
517 }
518 }
519 decoder.flush().expect("flush");
520 loop {
521 match decoder.receive_frame() {
522 Ok(Frame::Audio(frame)) => {
523 let _ = push_frame(frame, &mut planes);
524 }
525 Ok(Frame::Video(_)) => unreachable!("Vorbis decodes to audio only"),
526 Err(e) if e.is_eof() => break,
527 Err(e) => panic!("receive_frame after flush: {e}"),
528 }
529 }
530 let offset = offset.unwrap_or(0);
531 let front = (-offset).max(0) as usize;
532 let end = (last_granule - offset).max(0) as usize;
533 for plane in &mut planes {
534 let end = end.min(plane.len());
535 let front = front.min(end);
536 *plane = plane[front..end].to_vec();
537 }
538
539 for (channel, plane) in planes.iter().enumerate() {
540 assert_eq!(
541 plane.len(),
542 samples,
543 "ch{channel}: expected exactly {samples} samples out"
544 );
545 let tail_ours = &plane[samples - (hop - 1)..];
546 let tail_source = &source[channel][samples - (hop - 1)..];
547 let corr = correlation(tail_ours, tail_source);
548 assert!(corr > 0.99, "ch{channel}: tail hop corr {corr:.4}");
549 }
550}
551
552#[test]
553fn a_short_input_keeps_its_own_length() {
554 // Shorter than one block: the grid still has to close and the granule
555 // still has to state the input's own count.
556 let rate = 44_100u32;
557 for samples in [1usize, 700, 1024, 1025, 4096] {
558 let source = tones(2, rate, samples);
559 let path = encode_to_file(&source, rate, 128_000, &format!("short-{samples}.ogg"));
560 let duration = probed_samples(&path);
561 assert_eq!(
562 duration, samples as i64,
563 "{samples} samples in, ffprobe says {duration}"
564 );
565 }
566}
567
568/// Noise-plus-tones: a signal with enough going on that the rate loop has
569/// something to spend bits on, which a pure tone does not.
570fn busy(channels: usize, rate: u32, samples: usize) -> Vec<Vec<f32>> {
571 let mut state = 0x2545_f491_4f6c_dd1du64;
572 let mut noise = move || {
573 state ^= state << 13;
574 state ^= state >> 7;
575 state ^= state << 17;
576 (state >> 40) as f32 / 8_388_608.0 - 1.0
577 };
578 (0..channels)
579 .map(|channel| {
580 (0..samples)
581 .map(|i| {
582 let t = i as f64 / f64::from(rate);
583 let hz = 300.0 * f64::from(channel as u32 + 1);
584 let tone = (2.0 * std::f64::consts::PI * hz * t).sin() as f32;
585 0.35 * tone + 0.35 * noise()
586 })
587 .collect()
588 })
589 .collect()
590}
591
592/// A hard silence-to-full-scale onset must not leak into the long block
593/// before it: that block should now be coded with a short right window (or
594/// the onset itself carried by a short block), which windows the leak out
595/// instead of smearing it across ~46 ms the way an all-long-block encoder
596/// does.
597#[test]
598fn onset_after_silence_has_no_pre_echo() {
599 // Onsets swept by phase (fractions of a second, so they land anywhere
600 // relative to the long hop) and by offset from the long-hop grid itself,
601 // since the short run's placement is decided per hop. Stereo carries
602 // distinct content per channel — a different tone on the right, starting
603 // 11 samples later — so coupling cannot hide a per-channel leak. The gap
604 // is measured over the WHOLE silence up to the onset, so a leak in the
605 // last few hundred samples before it cannot hide behind a guard band, and
606 // the peak is barred too.
607 let amp = 0.7f64;
608 for (rate, layouts) in [
609 (44_100u32, &[1usize, 2][..]),
610 (48_000, &[1, 2, 6]),
611 (96_000, &[6]),
612 ] {
613 let grid = 16 * 1024usize;
614 let onsets = [0.3333f64, 0.5, 0.7321, 0.9137, 1.0]
615 .into_iter()
616 .map(|s| (s * f64::from(rate)) as usize)
617 .chain([0usize, 37, 512, 1000, 1023].into_iter().map(|o| grid + o));
618 for onset in onsets {
619 for &channels in layouts {
620 let tone_len = rate as usize;
621 let mut source = vec![vec![0.0f32; onset + tone_len + 11 * channels]; channels];
622 for (c, plane) in source.iter_mut().enumerate() {
623 let hz = 1_000.0 + 370.0 * c as f64;
624 let start = onset + 11 * c;
625 for i in 0..tone_len {
626 let t = i as f64 / f64::from(rate);
627 plane[start + i] =
628 (amp * (2.0 * std::f64::consts::PI * hz * t).sin()) as f32;
629 }
630 }
631 let name = format!("onset-{rate}-{channels}ch-{onset}.ogg");
632 let path = encode_to_file(&source, rate, 128_000, &name);
633
634 // The reference oracle must decode the short-block stream
635 // cleanly: no warnings, let alone errors.
636 let warn = Command::new("ffmpeg")
637 .args(["-v", "warning", "-i"])
638 .arg(&path)
639 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
640 .output();
641 if let Ok(out) = warn {
642 assert!(
643 out.stderr.is_empty(),
644 "{name}: oracle decode warnings: {}",
645 String::from_utf8_lossy(&out.stderr)
646 );
647 }
648
649 let tone_rms = rms(&source[0][onset..]);
650 let check = |label: &str, planes: &[Vec<f32>]| {
651 for (c, plane) in planes.iter().enumerate() {
652 let gap = &plane[..onset.min(plane.len())];
653 let gap_rms = rms(gap);
654 let peak = gap.iter().fold(0.0f32, |m, v| m.max(v.abs()));
655 println!("{name}/{label} ch{c}: gap RMS {gap_rms:.6} peak {peak:.4}");
656 assert!(
657 gap_rms <= 0.002 * tone_rms,
658 "{name}/{label} ch{c}: gap RMS {gap_rms:.6} vs tone RMS {tone_rms:.6}"
659 );
660 assert!(
661 f64::from(peak) <= 0.01 * amp,
662 "{name}/{label} ch{c}: gap peak {peak:.4}"
663 );
664 }
665 };
666 let (ours, _) = our_decode(&path);
667 check("ours", &ours);
668 if let Some((theirs, _)) = ffmpeg_decode(&path) {
669 check("oracle", &theirs);
670 }
671 }
672 }
673 }
674}
675
676#[test]
677fn the_rate_loop_tracks_the_target_bitrate() {
678 let rate = 48_000u32;
679 let samples = rate as usize * 3;
680 let source = busy(2, rate, samples);
681 let mut measured = Vec::new();
682 for target in [96_000i32, 128_000, 192_000] {
683 let path = encode_to_file(
684 &source,
685 rate,
686 target,
687 &format!("abr-{}k.ogg", target / 1000),
688 );
689 let bytes = std::fs::metadata(&path).expect("file").len();
690 let kbps = bytes as f64 * 8.0 * f64::from(rate) / samples as f64 / 1000.0;
691 println!("target {} kbps -> {kbps:.0} kbps", target / 1000);
692 measured.push(kbps);
693 }
694 // Monotone in the target, and within a quarter of it: the loop moves one
695 // quantiser gain, so it tracks rather than hits.
696 assert!(
697 measured[0] < measured[1] && measured[1] < measured[2],
698 "{measured:?}"
699 );
700 for (kbps, target) in measured.iter().zip([96.0, 128.0, 192.0]) {
701 assert!(
702 (kbps - target).abs() / target < 0.25,
703 "{kbps:.0} kbps for a {target:.0} kbps target"
704 );
705 }
706}
707
708/// Quiet and sparse content must reach the target too: with the floor bounded
709/// by the threshold of hearing, most partitions code as class 0 at any step,
710/// so the rate loop's extra headroom has to lower that bound to find bits to
711/// spend. The fixture is a sparse tone at -18 dBFS; the synthetic sources are
712/// the busy and tonal signals at -40 dBFS, the tones over a -90 dBFS noise
713/// floor (what any 16-bit source carries; a pure digital tone has nothing
714/// outside its own bins for any step to find). Noise is incompressible, so the
715/// quiet noise is held to the full-scale noise's own fidelity rather than a
716/// fixed bar.
717///
718/// The rate loop's step search bottoms out at the +-127 step range (36 dB
719/// residue range + 12-point floor): once a quiet source's codable residue is
720/// exhausted, no finer step can spend more bits without a second (cascade)
721/// coding pass, which does not exist yet -- that cascade is the upgrade path.
722/// So the contract is: measured kbps lands within +-25% of target, OR the
723/// encode undershoots because there is nothing left to spend and the result
724/// is transparent (corr >= 0.999 against the source). The monotone-in-target
725/// spend check only applies where the case actually spends against target.
726#[test]
727fn quiet_content_reaches_the_target_or_is_transparent() {
728 let rate = 48_000u32;
729 let samples = rate as usize * 3;
730 let fixture =
731 ffmpeg_decode(&fixtures().join("audio/wav16-stereo-48000.wav")).expect("fixture decodes");
732 assert_eq!(fixture.1, rate);
733 let attenuate = |mut source: Vec<Vec<f32>>| {
734 for channel in source.iter_mut() {
735 for value in channel.iter_mut() {
736 *value *= 0.01;
737 }
738 }
739 source
740 };
741 let corr_at = |path: &Path, source: &[Vec<f32>]| {
742 let (decoded, _) = our_decode(path);
743 decoded
744 .iter()
745 .zip(source.iter())
746 .map(|(channel, original)| {
747 let n = channel.len().min(original.len());
748 correlation(&channel[..n], &original[..n])
749 })
750 .fold(1.0f64, f64::min)
751 };
752 let loud = busy(2, rate, samples);
753 let loud_corr = corr_at(
754 &encode_to_file(&loud, rate, 128_000, "loud-128k.ogg"),
755 &loud,
756 );
757 let quiet_noise = attenuate(loud);
758 let mut quiet_tones = attenuate(tones(2, rate, samples));
759 for (channel, noise) in quiet_tones.iter_mut().zip(busy(2, rate, samples)) {
760 for (value, n) in channel.iter_mut().zip(noise) {
761 *value += n * 0.0001;
762 }
763 }
764 let cases = [
765 ("fixture", &fixture.0, 0.99),
766 ("quiet-tones", &quiet_tones, 0.99),
767 ("quiet-noise", &quiet_noise, loud_corr - 0.02),
768 ];
769 for (name, source, bar) in cases {
770 let mut measured = Vec::new();
771 let mut spent = Vec::new();
772 for target in [96_000i32, 128_000, 192_000] {
773 let path = encode_to_file(
774 source,
775 rate,
776 target,
777 &format!("{name}-{}k.ogg", target / 1000),
778 );
779 let bytes = std::fs::metadata(&path).expect("file").len();
780 let kbps = bytes as f64 * 8.0 * f64::from(rate) / source[0].len() as f64 / 1000.0;
781 let corr = corr_at(&path, source);
782 println!(
783 "{name}: target {} kbps -> {kbps:.0} kbps, corr {corr:.4}",
784 target / 1000
785 );
786 let target_kbps = f64::from(target) / 1000.0;
787 let within_25pct = (kbps - target_kbps).abs() / target_kbps < 0.25;
788 let transparent_undershoot = kbps < target_kbps && corr >= 0.999;
789 assert!(
790 within_25pct || transparent_undershoot,
791 "{name}: {kbps:.0} kbps for {target_kbps:.0} kbps target, corr {corr:.4}"
792 );
793 spent.push(within_25pct);
794 measured.push(kbps);
795 if target == 128_000 {
796 assert!(corr >= bar, "{name}: corr {corr:.4} under {bar:.4}");
797 }
798 }
799 if spent.iter().all(|&s| s) {
800 assert!(
801 measured[0] < measured[1] && measured[1] < measured[2],
802 "{name}: {measured:?}"
803 );
804 }
805 }
806}
807
808/// Per-Bark-band quantised-residue histogram comparison: ours vs libvorbis
809/// reference. We encode the source with our encoder (capturing residue), then
810/// encode the same source with libvorbis and decode that stream with our own
811/// decoder, capturing its decoded residue (after inverse coupling, before
812/// floor multiply — the same domain as the encoder's `quantised`). The
813/// reference is libvorbis's own residue, so per-band divergence names where
814/// our psy spends differently from libvorbis.
815#[test]
816#[ignore = "slow: encodes 7 sources × 128k, needs ffmpeg/libvorbis"]
817fn residue_histogram_vs_reference() {
818 use std::io::Write;
819
820 let sources: &[(&str, &str)] = &[
821 ("nik", "~/Music/reeln.mp4"),
822 ("reelo", "~/Music/reelo.mp3"),
823 ("her", "~/Music/reeli.mp3"),
824 ("reell", "~/Music/reell.mp4"),
825 ("reelm", "~/Music/reelm.wav"),
826 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
827 (
828 "hein",
829 "~/Downloads/reelm.mp3",
830 ),
831 ];
832 let bitrate = 128_000i32;
833 let rate = 48_000u32;
834 let channels = 2u16;
835 // Limit to ~12 s for speed — enough blocks for a stable histogram.
836 let max_samples = rate as usize * 12;
837
838 let out_dir = scratch().join("vorbis7");
839 std::fs::create_dir_all(&out_dir).expect("out dir");
840 let mut report = String::new();
841 report.push_str("# Residue histogram: ours vs libvorbis reference\n\n");
842 report.push_str(&format!(
843 "Bitrate: {} kbps, {} Hz, {}ch, {} s max\n\n",
844 bitrate / 1000,
845 rate,
846 channels,
847 max_samples / rate as usize
848 ));
849 let mut total_ours_bytes = 0u64;
850 let mut total_ref_bytes = 0u64;
851
852 let mut rows = 0usize;
853 for &(name, src_path) in sources {
854 let expanded = shellexpand(src_path);
855 let src = PathBuf::from(&expanded);
856 if !src.exists() {
857 report.push_str(&format!("## {name}: SKIP (file not found: {expanded})\n\n"));
858 continue;
859 }
860 rows += 1;
861 // Decode source with ffmpeg, limit duration.
862 let Some((source_pcm, src_rate)) = ffmpeg_decode_limited(&src, rate, max_samples) else {
863 report.push_str(&format!("## {name}: SKIP (ffmpeg decode failed)\n\n"));
864 continue;
865 };
866 if source_pcm.len() < 2 || source_pcm[0].is_empty() {
867 report.push_str(&format!("## {name}: SKIP (empty decode)\n\n"));
868 continue;
869 }
870 // Resample to 48k if needed — ffmpeg_decode_limited already targets 48k.
871 let _ = src_rate;
872
873 // --- Ours: encode source with our encoder, capture residue, keep the ogg ---
874 let ours_ogg = out_dir.join(format!("ours-{name}-128k.ogg"));
875 let (ours_residue, ours_bytes) =
876 encode_and_capture(&source_pcm, rate, channels, bitrate, &ours_ogg);
877
878 // --- Sanity: decoding our own ogg with capture on must reproduce the
879 // encoder's capture band for band, or the two captures are not in the
880 // same domain and the table below means nothing. ---
881 let (roundtrip, ours_split) = decode_capture_with_bits(&ours_ogg);
882 let (sanity_ok, sanity_detail) = compare_captures(&ours_residue, &roundtrip, rate);
883 let ours_bits = bit_split_summary(&ours_split, &roundtrip);
884
885 // --- Reference: encode with libvorbis, decode with OUR decoder, capture ---
886 let ref_ogg = out_dir.join(format!("ref-{name}-128k.ogg"));
887 let ref_status = Command::new("ffmpeg")
888 // `-vn`: with the video stream still attached (reell, h264+aac mp4)
889 // ffmpeg's libvorbis wrapper ignores -b:a and encodes at ~3.2x the
890 // target; audio-only input encodes at the requested rate.
891 .args(["-y", "-v", "error", "-i"])
892 .arg(&src)
893 .args([
894 "-vn",
895 "-t",
896 &format!("{}", max_samples / rate as usize),
897 "-ac",
898 "2",
899 "-ar",
900 "48000",
901 "-c:a",
902 "libvorbis",
903 "-b:a",
904 "128k",
905 ])
906 .arg(&ref_ogg)
907 .status();
908 let (ref_residue, ref_split) = match ref_status {
909 Ok(s) if s.success() => decode_capture_with_bits(&ref_ogg),
910 _ => {
911 report.push_str(&format!("## {name}: libvorbis encode failed\n\n"));
912 continue;
913 }
914 };
915 let ref_bytes = std::fs::metadata(&ref_ogg).expect("ref ogg").len();
916 total_ours_bytes += ours_bytes;
917 total_ref_bytes += ref_bytes;
918
919 // --- Build per-Bark-band histograms ---
920 let bins = 6; // |q|: 0, 1, 2, 3-4, 5-8, 9+
921 let max_bark = 25;
922 let mut ours_hist = vec![vec![0u64; bins]; max_bark];
923 let mut ref_hist = vec![vec![0u64; bins]; max_bark];
924 for (half, quantised) in &ours_residue {
925 accumulate(quantised, *half, rate, &mut ours_hist, max_bark);
926 }
927 for (half, quantised) in &ref_residue {
928 accumulate(quantised, *half, rate, &mut ref_hist, max_bark);
929 }
930
931 report.push_str(&format!(
932 "## {name} — sanity {}: {} — ours {} B vs ref {} B ({:.2}x)\n\n",
933 if sanity_ok { "PASS" } else { "FAIL" },
934 sanity_detail,
935 ours_bytes,
936 ref_bytes,
937 ours_bytes as f64 / ref_bytes as f64
938 ));
939 let ref_bits = bit_split_summary(&ref_split, &ref_residue);
940 for (who, b) in [("ours", ours_bits), ("ref", ref_bits)] {
941 let (f, r, p, nz) = b;
942 report.push_str(&format!(
943 "bits {who}: floor {f} ({:.1}%), residue {r} ({:.1}%), other {}, packet {p}; non-zero {nz}, residue bits/non-zero {:.2}\n",
944 100.0 * f as f64 / p.max(1) as f64,
945 100.0 * r as f64 / p.max(1) as f64,
946 p.saturating_sub(f + r),
947 r as f64 / nz.max(1) as f64
948 ));
949 }
950 report.push('\n');
951 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");
952 report.push_str("|------|-------------|-----|-----|-------|-------|------|-----------------|-------------|\n");
953 for band in 0..max_bark {
954 let o = &ours_hist[band];
955 let r = &ref_hist[band];
956 let o_total: u64 = o.iter().sum();
957 let r_total: u64 = r.iter().sum();
958 if o_total == 0 && r_total == 0 {
959 continue;
960 }
961 // "Spend" = non-zero entries (bins 1..) — proxy for bits spent.
962 let o_spend: u64 = o[1..].iter().sum();
963 let r_spend: u64 = r[1..].iter().sum();
964 let ratio = if r_spend > 0 {
965 o_spend as f64 / r_spend as f64
966 } else {
967 f64::INFINITY
968 };
969 report.push_str(&format!(
970 "| {} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {:.2} |\n",
971 band,
972 o[0],
973 r[0],
974 o[1],
975 r[1],
976 o[2],
977 r[2],
978 o[3],
979 r[3],
980 o[4],
981 r[4],
982 o[5],
983 r[5],
984 o_total,
985 r_total,
986 ratio,
987 ));
988 }
989
990 // Fraction table: per-band share of entries in each |q| class and the
991 // shape distance = sum |f_ours - f_ref| over the four classes
992 // (0 = identical spend shape; convergence target < 0.15 in Bark 3-22).
993 report.push_str("| Bark | f0 ours | f0 ref | f1 ours | f1 ref | f2 ours | f2 ref | f3+ ours | f3+ ref | dist |\n");
994 report.push_str("|------|---------|--------|---------|--------|---------|--------|----------|---------|------|\n");
995 let frac = |h: &[u64], total: u64| {
996 vec![
997 h[0] as f64 / total as f64,
998 h[1] as f64 / total as f64,
999 h[2] as f64 / total as f64,
1000 (h[3] + h[4] + h[5]) as f64 / total as f64,
1001 ]
1002 };
1003 let mut band_dist: Vec<(usize, f64)> = Vec::new();
1004 for band in 0..max_bark {
1005 let o_total: u64 = ours_hist[band].iter().sum();
1006 let r_total: u64 = ref_hist[band].iter().sum();
1007 if o_total == 0 || r_total == 0 {
1008 continue;
1009 }
1010 let fo = frac(&ours_hist[band], o_total);
1011 let fr = frac(&ref_hist[band], r_total);
1012 let dist: f64 = fo.iter().zip(&fr).map(|(a, b)| (a - b).abs()).sum();
1013 band_dist.push((band, dist));
1014 report.push_str(&format!(
1015 "| {} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} |\n",
1016 band, fo[0], fr[0], fo[1], fr[1], fo[2], fr[2], fo[3], fr[3], dist,
1017 ));
1018 }
1019 let in_scope: Vec<(usize, f64)> = band_dist
1020 .iter()
1021 .filter(|(b, _)| (3..=22).contains(b))
1022 .cloned()
1023 .collect();
1024 if !in_scope.is_empty() {
1025 let max_d = in_scope.iter().map(|(_, d)| *d).fold(f64::MIN, f64::max);
1026 let over = in_scope.iter().filter(|(_, d)| *d >= 0.15).count();
1027 report.push_str(&format!(
1028 "\nshape Bark 3-22: max dist {max_d:.3}, bands >= 0.15: {over}/{} — {}\n",
1029 in_scope.len(),
1030 if over == 0 {
1031 "SHAPE PASS"
1032 } else {
1033 "shape fail"
1034 },
1035 ));
1036 }
1037 report.push('\n');
1038 }
1039
1040 // The seven sources are the user's own library, so each may be absent on a
1041 // given host -- but a run that encoded none of them is a measurement of
1042 // nothing, and the report it writes looks the same as a real one.
1043 assert!(rows > 0, "no library sources were readable");
1044 report.push_str(&format!(
1045 "\nTotal bytes: ours {total_ours_bytes} vs ref {total_ref_bytes} ({:.2}x)\n",
1046 total_ours_bytes as f64 / total_ref_bytes as f64,
1047 ));
1048 let report_path =
1049 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-psy-r1.histogram.txt");
1050 let mut f = File::create(&report_path).expect("create report");
1051 f.write_all(report.as_bytes()).expect("write report");
1052 println!("Histogram report: {}", report_path.display());
1053 // Also print to stdout for immediate viewing.
1054 print!("{report}");
1055}
1056
1057/// Encode PCM with our encoder, capturing per-block quantised residue, and mux
1058/// Per-block residue of one stream: (block size, one residue vector per channel).
1059type ResidueCapture = Vec<(usize, Vec<Vec<i32>>)>;
1060
1061/// the result to `out` so it can be decoded back (sanity check + rate).
1062fn encode_and_capture(
1063 source: &[Vec<f32>],
1064 rate: u32,
1065 channels: u16,
1066 bitrate: i32,
1067 out: &Path,
1068) -> (ResidueCapture, u64) {
1069 let mut encoder = VorbisEncoder::new(EncoderConfig {
1070 sample_rate: rate,
1071 channels,
1072 bitrate_bps: bitrate,
1073 quality: 0.6,
1074 })
1075 .expect("encoder");
1076 encoder.enable_residue_capture();
1077 let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect();
1078 encoder.push_planar(&borrowed).expect("push");
1079 encoder.finish();
1080 let mut packets = Vec::new();
1081 loop {
1082 match encoder.next_packet() {
1083 Ok(packet) => packets.push((packet.data, packet.granule)),
1084 Err(e) if e.is_eof() => break,
1085 Err(e) => panic!("encode: {e}"),
1086 }
1087 }
1088 mux(out, &encoder, &packets, rate, channels);
1089 let bytes = std::fs::metadata(out).expect("muxed file").len();
1090 (encoder.take_residue_capture(), bytes)
1091}
1092
1093/// Bit split summed over the stream: (floor bits, residue bits, packet bits,
1094/// non-zero residue count) — bits per coded value is the coding-efficiency oracle.
1095fn bit_split_summary(
1096 split: &[(u64, u64, u64)],
1097 residue: &[(usize, Vec<Vec<i32>>)],
1098) -> (u64, u64, u64, u64) {
1099 let (mut f, mut r, mut p) = (0u64, 0u64, 0u64);
1100 for &(a, b, c) in split {
1101 f += a;
1102 r += b;
1103 p += c;
1104 }
1105 let nz: u64 = residue
1106 .iter()
1107 .map(|(_, chs)| {
1108 chs.iter()
1109 .map(|c| c.iter().filter(|&&v| v != 0).count() as u64)
1110 .sum::<u64>()
1111 })
1112 .sum();
1113 (f, r, p, nz)
1114}
1115
1116fn decode_capture_with_bits(path: &Path) -> (ResidueCapture, Vec<(u64, u64, u64)>) {
1117 let mut demuxer = OggDemuxer::open(File::open(path).expect("open")).expect("ogg");
1118 let stream = demuxer
1119 .streams()
1120 .iter()
1121 .find(|s| s.params.codec == ec_core::CodecId::Vorbis)
1122 .expect("a Vorbis stream")
1123 .clone();
1124 let extradata = stream.params.extradata.clone().expect("headers");
1125 let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse");
1126 decoder.enable_residue_capture();
1127 loop {
1128 let packet = match demuxer.next_packet() {
1129 Ok(packet) => packet,
1130 Err(e) if e.is_eof() => break,
1131 Err(e) => panic!("demux {}: {e}", path.display()),
1132 };
1133 if packet.stream != stream.index {
1134 continue;
1135 }
1136 // A packet the decoder cannot use is skipped, like in `our_decode`.
1137 if decoder.decode_audio(&packet.data).is_err() {
1138 continue;
1139 }
1140 }
1141 let residue = decoder.take_residue_capture();
1142 let bits = decoder.take_bit_split();
1143 (residue, bits)
1144}
1145
1146/// Bin two captures by Bark and compare every histogram cell.
1147fn compare_captures(
1148 a: &[(usize, Vec<Vec<i32>>)],
1149 b: &[(usize, Vec<Vec<i32>>)],
1150 rate: u32,
1151) -> (bool, String) {
1152 let bins = 6;
1153 let max_bark = 25;
1154 let mut ha = vec![vec![0u64; bins]; max_bark];
1155 let mut hb = vec![vec![0u64; bins]; max_bark];
1156 for (half, q) in a {
1157 accumulate(q, *half, rate, &mut ha, max_bark);
1158 }
1159 for (half, q) in b {
1160 accumulate(q, *half, rate, &mut hb, max_bark);
1161 }
1162 let mut diffs = Vec::new();
1163 for band in 0..max_bark {
1164 for bucket in 0..bins {
1165 if ha[band][bucket] != hb[band][bucket] {
1166 diffs.push(format!(
1167 "bark {band} q{bucket}: {} vs {}",
1168 ha[band][bucket], hb[band][bucket]
1169 ));
1170 }
1171 }
1172 }
1173 if diffs.is_empty() {
1174 (
1175 true,
1176 format!("identical histograms ({} vs {} blocks)", a.len(), b.len()),
1177 )
1178 } else {
1179 (
1180 false,
1181 format!(
1182 "{} vs {} blocks; first diffs: {}",
1183 a.len(),
1184 b.len(),
1185 diffs.iter().take(5).cloned().collect::<Vec<_>>().join("; ")
1186 ),
1187 )
1188 }
1189}
1190
1191/// Decode with ffmpeg into planar f32, resampled to `rate`, limited to `max_samples`.
1192fn ffmpeg_decode_limited(
1193 path: &Path,
1194 rate: u32,
1195 max_samples: usize,
1196) -> Option<(Vec<Vec<f32>>, u32)> {
1197 let out = Command::new("ffmpeg")
1198 .args(["-v", "error", "-i"])
1199 .arg(path)
1200 .args([
1201 "-t",
1202 &format!("{}", max_samples / rate as usize),
1203 "-ac",
1204 "2",
1205 "-ar",
1206 &rate.to_string(),
1207 "-f",
1208 "f32le",
1209 "-acodec",
1210 "pcm_f32le",
1211 "-",
1212 ])
1213 .output()
1214 .expect("ffmpeg runs");
1215 if !out.stderr.is_empty() {
1216 eprintln!("ffmpeg stderr: {}", String::from_utf8_lossy(&out.stderr));
1217 return None;
1218 }
1219 let channels = 2usize;
1220 let interleaved: Vec<f32> = out
1221 .stdout
1222 .as_chunks::<4>()
1223 .0
1224 .iter()
1225 .map(|b| f32::from_le_bytes(*b))
1226 .collect();
1227 let n = interleaved.len() / channels;
1228 let n = n.min(max_samples);
1229 let mut planes: Vec<Vec<f32>> = (0..channels).map(|_| Vec::with_capacity(n)).collect();
1230 for (i, value) in interleaved.into_iter().enumerate().take(n * channels) {
1231 planes[i % channels].push(value);
1232 }
1233 Some((planes, rate))
1234}
1235
1236/// Accumulate per-Bark-band |q| histograms from quantised residue.
1237fn accumulate(
1238 quantised: &[Vec<i32>],
1239 half: usize,
1240 rate: u32,
1241 hist: &mut [Vec<u64>],
1242 max_bark: usize,
1243) {
1244 for channel in quantised {
1245 for (bin, &q) in channel.iter().enumerate() {
1246 if bin >= half {
1247 break;
1248 }
1249 let hz = bin as f64 * f64::from(rate) / (2.0 * half as f64);
1250 let bark = VorbisEncoder::bark_hz(hz) as usize;
1251 let band = bark.min(max_bark - 1);
1252 let bucket = match q.abs() {
1253 0 => 0,
1254 1 => 1,
1255 2 => 2,
1256 3..=4 => 3,
1257 5..=8 => 4,
1258 _ => 5,
1259 };
1260 hist[band][bucket] += 1;
1261 }
1262 }
1263}
1264
1265/// Expand `~` in a path string.
1266fn shellexpand(path: &str) -> String {
1267 if let Some(rest) = path.strip_prefix("~/") {
1268 let home = std::env::var("HOME").unwrap_or_else(|_| "/home".to_string());
1269 format!("{home}/{rest}")
1270 } else {
1271 path.to_string()
1272 }
1273}
1274
1275/// Full-file sweep over the user's library at the two managed rates: ours
1276/// encoded at the size libvorbis actually produced (ffmpeg's -b:a is
1277/// unmanaged VBR, 10-30% under nominal on real music), bytes within ±3% of
1278/// it and correlation-to-source within .005 of it. Both encodes decode
1279/// through our decoder so the gap measures the encoders, not the decoders.
1280/// Writes `lanes/vorbis-psy-r1.sweep.txt`.
1281#[test]
1282#[ignore = "slow: encodes 7 full sources × 2 rates, needs ffmpeg/libvorbis"]
1283fn real_library_sweep_vs_reference() {
1284 let sources: &[(&str, &str)] = &[
1285 ("nik", "~/Music/reeln.mp4"),
1286 ("reelo", "~/Music/reelo.mp3"),
1287 ("her", "~/Music/reeli.mp3"),
1288 ("reell", "~/Music/reell.mp4"),
1289 ("reelm", "~/Music/reelm.wav"),
1290 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
1291 (
1292 "hein",
1293 "~/Downloads/reelm.mp3",
1294 ),
1295 ];
1296 let rate = 48_000u32;
1297 let max_samples = rate as usize * 600;
1298 let out_dir = scratch().join("vorbis7-sweep");
1299 std::fs::create_dir_all(&out_dir).expect("out dir");
1300 let mut table = String::from(
1301 "source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap minsec_o minsec_r drops verdict\n",
1302 );
1303 let mut failures = Vec::new();
1304 let only = std::env::var("SWEEP_ONLY").ok();
1305 let dump_drops = std::env::var("DROPS_DUMP").is_ok();
1306 let mut drops = String::new();
1307 let mut rows = 0usize;
1308 for &(name, src_path) in sources {
1309 if only
1310 .as_deref()
1311 .is_some_and(|o| !o.split(',').any(|n| n == name))
1312 {
1313 continue;
1314 }
1315 let src = PathBuf::from(shellexpand(src_path));
1316 if !src.exists() {
1317 table.push_str(&format!("{name:<7} - SKIP (missing)\n"));
1318 continue;
1319 }
1320 rows += 1;
1321 let Some((source_pcm, _)) = ffmpeg_decode_limited(&src, rate, max_samples) else {
1322 table.push_str(&format!("{name:<7} - SKIP (decode)\n"));
1323 continue;
1324 };
1325 let seconds = source_pcm[0].len() as f64 / f64::from(rate);
1326 for &kbps in &[96i32, 128] {
1327 // libvorbis under ffmpeg's -b:a runs unmanaged VBR and lands
1328 // 10-30% under the nominal rate on real music, so ours is asked
1329 // for the bytes it actually produced: quality at equal size.
1330 let reference = out_dir.join(format!("ref-{name}-{kbps}k.ogg"));
1331 let status = Command::new("ffmpeg")
1332 .args(["-y", "-v", "error", "-i"])
1333 .arg(&src)
1334 .args([
1335 "-vn",
1336 "-t",
1337 "600",
1338 "-ac",
1339 "2",
1340 "-ar",
1341 "48000",
1342 "-c:a",
1343 "libvorbis",
1344 "-b:a",
1345 &format!("{kbps}k"),
1346 ])
1347 .arg(&reference)
1348 .status()
1349 .expect("ffmpeg runs");
1350 assert!(status.success(), "libvorbis encode of {name} at {kbps}k");
1351 let bytes = |p: &Path| std::fs::metadata(p).expect("size").len() as f64;
1352 let ref_kbps = bytes(&reference) * 8.0 / seconds / 1000.0;
1353 let (ours, block_log) = encode_to_file_with_log(
1354 &source_pcm,
1355 rate,
1356 (ref_kbps * 1000.0).round() as i32,
1357 &format!("vorbis7-sweep/ours-{name}-{kbps}k.ogg"),
1358 );
1359 let ours_kbps = bytes(&ours) * 8.0 / seconds / 1000.0;
1360 let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0;
1361 // Whole-file corr plus a per-second trace: a dropout (the
1362 // rate-loop windup class, 200 ms silences after transients) is
1363 // invisible in the mean and bimodal per second, so it is gated
1364 // as "seconds where ours is under 0.9 and the reference is not".
1365 let corr_of = |p: &Path| -> (f64, Vec<f64>) {
1366 let (pcm, _) = our_decode(p);
1367 let n = pcm[0].len().min(source_pcm[0].len());
1368 let mean = (0..2)
1369 .map(|c| correlation(&pcm[c][..n], &source_pcm[c][..n]))
1370 .sum::<f64>()
1371 / 2.0;
1372 let step = rate as usize;
1373 let per_second = (0..n / step)
1374 .map(|s| {
1375 let r = s * step..(s + 1) * step;
1376 (0..2)
1377 .map(|c| correlation(&pcm[c][r.clone()], &source_pcm[c][r.clone()]))
1378 .sum::<f64>()
1379 / 2.0
1380 })
1381 .collect();
1382 (mean, per_second)
1383 };
1384 let (corr_ours, sec_ours) = corr_of(&ours);
1385 let (corr_ref, sec_ref) = corr_of(&reference);
1386 let gap = corr_ref - corr_ours;
1387 let min_of = |v: &[f64]| v.iter().copied().fold(1.0f64, f64::min);
1388 let (min_ours, min_ref) = (min_of(&sec_ours), min_of(&sec_ref));
1389 let dropouts = sec_ours
1390 .iter()
1391 .zip(&sec_ref)
1392 .filter(|(o, r)| **o < 0.9 && **r >= 0.9)
1393 .count();
1394 let dropout_secs: Vec<usize> = sec_ours
1395 .iter()
1396 .zip(&sec_ref)
1397 .enumerate()
1398 .filter(|(_, (o, r))| **o < 0.9 && **r >= 0.9)
1399 .map(|(s, _)| s)
1400 .collect();
1401 let pass = rate_pct.abs() <= 3.0 && gap <= 0.005 && dropouts == 0;
1402 if !pass {
1403 failures.push(format!(
1404 "{name}@{kbps}k rate {rate_pct:+.2}% gap {gap:.4} dropouts {dropouts}"
1405 ));
1406 }
1407 table.push_str(&format!(
1408 "{name:<7} {kbps:<6} {ours_kbps:<9.1} {ref_kbps:<8.1} {rate_pct:+6.2} {corr_ours:<9.4} {corr_ref:<8.4} {gap:<7.4} {min_ours:<8.3} {min_ref:<7.3} {dropouts:<5} {}\n",
1409 if pass { "PASS" } else { "FAIL" }
1410 ));
1411 eprintln!("{}", table.lines().last().unwrap());
1412 if dump_drops {
1413 drops.push_str(&format!(
1414 "\n=== {name}@{kbps}k rate {rate_pct:+.2}% gap {gap:.4} dropouts {dropouts} ===\n"
1415 ));
1416 for &s in &dropout_secs {
1417 let lo = (s.saturating_sub(2)) as i64 * rate as i64;
1418 let hi = (s + 3) as i64 * rate as i64;
1419 drops.push_str(&format!(
1420 " sec {s}: ours {:.3} ref {:.3}\n",
1421 sec_ours[s], sec_ref[s]
1422 ));
1423 drops.push_str(" idx centre_s n kind steady bits headroom rate_hr reservoir target\n");
1424 for (i, b) in block_log.iter().enumerate() {
1425 if b.centre < lo || b.centre >= hi {
1426 continue;
1427 }
1428 drops.push_str(&format!(
1429 " {i:<4} {:>8.2} {:<5} {:<5} {:<6} {:<6} {:>8.1} {:>7.1} {:>9.1} {:>7.1}\n",
1430 b.centre as f64 / rate as f64,
1431 b.n,
1432 if b.is_long { "L" } else { "S" },
1433 b.steady,
1434 b.bits,
1435 b.headroom,
1436 b.rate_headroom,
1437 b.reservoir,
1438 b.target,
1439 ));
1440 }
1441 }
1442 }
1443 }
1444 }
1445 eprintln!("\n{table}");
1446 if dump_drops {
1447 let _ = std::fs::write(
1448 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-hf-r2.drops.txt"),
1449 &drops,
1450 );
1451 }
1452 let _ = std::fs::write(
1453 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-psy-r1.sweep.txt"),
1454 &table,
1455 );
1456 assert!(rows > 0, "no library sources were readable");
1457 assert!(failures.is_empty(), "sweep failures: {failures:?}");
1458}
1459
1460/// In-place radix-2 FFT. Only magnitudes and differences of identically
1461/// transformed spectra are used, so the twiddle sign convention is irrelevant.
1462fn fft(re: &mut [f64], im: &mut [f64]) {
1463 let n = re.len();
1464 assert!(n.is_power_of_two());
1465 let bits = n.trailing_zeros();
1466 for i in 0..n {
1467 let j = ((i as u32).reverse_bits() >> (32 - bits)) as usize;
1468 if j > i {
1469 re.swap(i, j);
1470 im.swap(i, j);
1471 }
1472 }
1473 let mut len = 2;
1474 while len <= n {
1475 let half = len / 2;
1476 let step = std::f64::consts::TAU / len as f64;
1477 for start in (0..n).step_by(len) {
1478 for k in 0..half {
1479 let angle = step * k as f64;
1480 let (wr, wi) = (angle.cos(), angle.sin());
1481 let i = start + k;
1482 let j = i + half;
1483 let tr = re[j] * wr - im[j] * wi;
1484 let ti = re[j] * wi + im[j] * wr;
1485 re[j] = re[i] - tr;
1486 im[j] = im[i] - ti;
1487 re[i] += tr;
1488 im[i] += ti;
1489 }
1490 }
1491 len *= 2;
1492 }
1493}
1494
1495/// Per-Bark-band spectral error, ours vs libvorbis, both decoded through our
1496/// decoder (so the gap measures encoders, not decoders): every 2048-sample
1497/// Hann frame (hop 1024) of the 48 kHz source, band edges in Hz (25 edges →
1498/// 24 bands), energies summed over frames and both channels.
1499/// NSR = 10log10(Σ|X_sig−X_src|²/Σ|X_src|²), E = 10log10(Σ|X_sig|²/Σ|X_src|²).
1500/// The same pass records the bit split of both streams (the decode-side
1501/// capture `decode_capture_with_bits` provides), so the bits table covers the
1502/// same rows without a second encode pass. Writes
1503/// `lanes/vorbis-psy-r1.bands.txt` and `lanes/vorbis-psy-r1.bits.txt`.
1504#[test]
1505#[ignore = "slow: encodes 7 full sources × 2 rates, needs ffmpeg/libvorbis"]
1506fn band_error_vs_reference() {
1507 use std::io::Write;
1508
1509 let sources: &[(&str, &str)] = &[
1510 ("nik", "~/Music/reeln.mp4"),
1511 ("reelo", "~/Music/reelo.mp3"),
1512 ("her", "~/Music/reeli.mp3"),
1513 ("reell", "~/Music/reell.mp4"),
1514 ("reelm", "~/Music/reelm.wav"),
1515 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
1516 (
1517 "hein",
1518 "~/Downloads/reelm.mp3",
1519 ),
1520 ];
1521 let rate = 48_000u32;
1522 let max_samples = rate as usize * 600;
1523 let out_dir = scratch().join("vorbis7-bands");
1524 std::fs::create_dir_all(&out_dir).expect("out dir");
1525
1526 const FRAME: usize = 2048;
1527 const HOP: usize = 1024;
1528 const EDGES: [f64; 25] = [
1529 100.0, 200.0, 300.0, 400.0, 510.0, 630.0, 770.0, 920.0, 1080.0, 1270.0, 1480.0, 1720.0,
1530 2000.0, 2320.0, 2700.0, 3150.0, 3700.0, 4400.0, 5300.0, 6400.0, 7700.0, 9500.0, 12000.0,
1531 15500.0, 24000.0,
1532 ];
1533 let band_of: Vec<Option<usize>> = (0..=FRAME / 2)
1534 .map(|bin| {
1535 let hz = bin as f64 * f64::from(rate) / FRAME as f64;
1536 EDGES.windows(2).position(|w| hz >= w[0] && hz < w[1])
1537 })
1538 .collect();
1539 let window: Vec<f64> = (0..FRAME)
1540 .map(|i| 0.5 - 0.5 * (std::f64::consts::TAU * i as f64 / FRAME as f64).cos())
1541 .collect();
1542
1543 let mut bands = String::from("# Band error: ours vs libvorbis, both via our decoder\n\n");
1544 let mut bits = String::from("# Bit split over full sources, same rows as the band error\n\n");
1545 let only = std::env::var("SWEEP_ONLY").ok();
1546 let mut rows = 0usize;
1547 for &(name, src_path) in sources {
1548 if only
1549 .as_deref()
1550 .is_some_and(|o| !o.split(',').any(|n| n == name))
1551 {
1552 continue;
1553 }
1554 let src = PathBuf::from(shellexpand(src_path));
1555 if !src.exists() {
1556 bands.push_str(&format!("## {name}: SKIP (missing)\n\n"));
1557 continue;
1558 }
1559 rows += 1;
1560 let Some((source_pcm, _)) = ffmpeg_decode_limited(&src, rate, max_samples) else {
1561 bands.push_str(&format!("## {name}: SKIP (decode)\n\n"));
1562 continue;
1563 };
1564 let seconds = source_pcm[0].len() as f64 / f64::from(rate);
1565 let bytes = |p: &Path| std::fs::metadata(p).expect("size").len() as f64;
1566 for &kbps in &[96i32, 128] {
1567 let t0 = std::time::Instant::now();
1568 let reference = out_dir.join(format!("ref-{name}-{kbps}k.ogg"));
1569 let status = Command::new("ffmpeg")
1570 .args(["-y", "-v", "error", "-i"])
1571 .arg(&src)
1572 .args([
1573 "-vn",
1574 "-t",
1575 "600",
1576 "-ac",
1577 "2",
1578 "-ar",
1579 "48000",
1580 "-c:a",
1581 "libvorbis",
1582 "-b:a",
1583 &format!("{kbps}k"),
1584 ])
1585 .arg(&reference)
1586 .status()
1587 .expect("ffmpeg runs");
1588 assert!(status.success(), "libvorbis encode of {name} at {kbps}k");
1589 let ref_kbps = bytes(&reference) * 8.0 / seconds / 1000.0;
1590 // Ours at the size libvorbis actually produced, exactly as the sweep.
1591 let ours = encode_to_file(
1592 &source_pcm,
1593 rate,
1594 (ref_kbps * 1000.0).round() as i32,
1595 &format!("vorbis7-bands/ours-{name}-{kbps}k.ogg"),
1596 );
1597 let ours_kbps = bytes(&ours) * 8.0 / seconds / 1000.0;
1598
1599 // PCM through our decoder for the band error; bit split from the
1600 // same file's residue-domain capture (decode twice — the capture
1601 // path returns no PCM).
1602 let (ours_pcm, ours_split) = {
1603 let (residue, split) = decode_capture_with_bits(&ours);
1604 (our_decode(&ours).0, bit_split_summary(&split, &residue))
1605 };
1606 let (ref_pcm, ref_split) = {
1607 let (residue, split) = decode_capture_with_bits(&reference);
1608 (
1609 our_decode(&reference).0,
1610 bit_split_summary(&split, &residue),
1611 )
1612 };
1613
1614 // Bit-split block: (floor, residue, packet, non-zero) per stream.
1615 let (of, ores, op, onz) = ours_split;
1616 let (rf, rres, rp, rnz) = ref_split;
1617 bits.push_str(&format!(
1618 "## {name} @ {kbps}k (ours {ours_kbps:.1} vs ref {ref_kbps:.1} kbps)\n"
1619 ));
1620 for (who, f, r, p, nz) in [("ours", of, ores, op, onz), ("ref ", rf, rres, rp, rnz)] {
1621 bits.push_str(&format!(
1622 "{who} floor {fb:>10.1}/s ({fpc:5.1}%) residue {rb:>10.1}/s ({rpc:5.1}%) other {ob:>8.1}/s nz {nz:>10} bits/nz {bnz:.2}\n",
1623 fb = f as f64 / seconds,
1624 fpc = 100.0 * f as f64 / p.max(1) as f64,
1625 rb = r as f64 / seconds,
1626 rpc = 100.0 * r as f64 / p.max(1) as f64,
1627 ob = p.saturating_sub(f + r) as f64 / seconds,
1628 bnz = r as f64 / nz.max(1) as f64,
1629 ));
1630 }
1631 bits.push_str(&format!(
1632 "ratio floor {:.3} residue {:.3} bits/nz {:.3}\n\n",
1633 of as f64 / rf.max(1) as f64,
1634 ores as f64 / rres.max(1) as f64,
1635 (ores as f64 / onz.max(1) as f64) / (rres as f64 / rnz.max(1) as f64),
1636 ));
1637
1638 // Band error: align to the source exactly as the sweep does —
1639 // common length from sample 0 (pre-roll trim inside `our_decode`).
1640 let n = source_pcm[0]
1641 .len()
1642 .min(ours_pcm[0].len())
1643 .min(ref_pcm[0].len());
1644 let nb = EDGES.len() - 1;
1645 let (mut e_src, mut e_ours, mut e_ref) =
1646 (vec![0f64; nb], vec![0f64; nb], vec![0f64; nb]);
1647 let (mut err_ours, mut err_ref) = (vec![0f64; nb], vec![0f64; nb]);
1648 let mut spec: Vec<(Vec<f64>, Vec<f64>)> = (0..3)
1649 .map(|_| (vec![0.0; FRAME], vec![0.0; FRAME]))
1650 .collect();
1651 let mut start = 0;
1652 while start + FRAME <= n {
1653 for ch in 0..2 {
1654 for (sig, pcm) in [&source_pcm, &ours_pcm, &ref_pcm].iter().enumerate() {
1655 let s = &mut spec[sig];
1656 for i in 0..FRAME {
1657 s.0[i] = f64::from(pcm[ch][start + i]) * window[i];
1658 s.1[i] = 0.0;
1659 }
1660 fft(&mut s.0, &mut s.1);
1661 }
1662 for (k, band) in band_of.iter().enumerate().take(FRAME / 2 + 1) {
1663 let Some(b) = *band else { continue };
1664 let (sr, si) = (spec[0].0[k], spec[0].1[k]);
1665 e_src[b] += sr * sr + si * si;
1666 let (ur, ui) = (spec[1].0[k], spec[1].1[k]);
1667 e_ours[b] += ur * ur + ui * ui;
1668 let (dr, di) = (ur - sr, ui - si);
1669 err_ours[b] += dr * dr + di * di;
1670 let (vr, vi) = (spec[2].0[k], spec[2].1[k]);
1671 e_ref[b] += vr * vr + vi * vi;
1672 let (er, ei) = (vr - sr, vi - si);
1673 err_ref[b] += er * er + ei * ei;
1674 }
1675 }
1676 start += HOP;
1677 }
1678 let db = |e: f64, s: f64| {
1679 if s > 0.0 {
1680 10.0 * (e / s).log10()
1681 } else {
1682 f64::NAN
1683 }
1684 };
1685 bands.push_str(&format!(
1686 "## {name} @ {kbps}k (ours {ours_kbps:.1} vs ref {ref_kbps:.1} kbps)\n"
1687 ));
1688 bands.push_str("band NSR_ours NSR_ref dNSR E_ours E_ref\n");
1689 for b in 0..nb {
1690 if e_src[b] == 0.0 {
1691 continue; // no source energy: NSR/E undefined
1692 }
1693 let (nsr_o, nsr_r) = (db(err_ours[b], e_src[b]), db(err_ref[b], e_src[b]));
1694 bands.push_str(&format!(
1695 "{:<8} {:7.1} {:7.1} {:6.1} {:7.1} {:7.1}\n",
1696 format!("{}-{}", EDGES[b] as usize, EDGES[b + 1] as usize),
1697 nsr_o,
1698 nsr_r,
1699 nsr_o - nsr_r,
1700 db(e_ours[b], e_src[b]),
1701 db(e_ref[b], e_src[b]),
1702 ));
1703 }
1704 let corr = |pcm: &[Vec<f32>]| {
1705 (0..2)
1706 .map(|c| correlation(&pcm[c][..n], &source_pcm[c][..n]))
1707 .sum::<f64>()
1708 / 2.0
1709 };
1710 bands.push_str(&format!(
1711 "broadband corr: ours {:.4} ref {:.4}\n\n",
1712 corr(&ours_pcm),
1713 corr(&ref_pcm),
1714 ));
1715 eprintln!(
1716 "{name}@{kbps}k: ours {ours_kbps:.1} ref {ref_kbps:.1} kbps, {:.1} s",
1717 t0.elapsed().as_secs_f32()
1718 );
1719 }
1720 }
1721 // Both report files above are written unconditionally, so a run that
1722 // measured no source writes a report indistinguishable from a real one.
1723 assert!(rows > 0, "no library sources were readable");
1724 for (text, file) in [
1725 (&bands, "vorbis-psy-r1.bands.txt"),
1726 (&bits, "vorbis-psy-r1.bits.txt"),
1727 ] {
1728 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1729 .join("../../lanes")
1730 .join(file);
1731 let mut f = File::create(&path).expect("create report");
1732 f.write_all(text.as_bytes()).expect("write report");
1733 println!("{file}: {}", path.display());
1734 }
1735}