Xiph vectors, fixture sweep and encode oracle
Browse files at this commitc547ecb435655288028f4b3554497ebad7b1d674Parent: c0023ff- test
- Xiph vectors, fixture sweep and encode oracle
1 changed file +490 -0
- crates/ec-vorbis/tests/oracle.rs +490 -0
crates/ec-vorbis/tests/oracle.rsadded+490 -0
| @@ -0,0 +1,490 @@ | ||
| 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 | + | |
| 9 | +use std::fs::File; | |
| 10 | +use std::path::{Path, PathBuf}; | |
| 11 | +use std::process::Command; | |
| 12 | + | |
| 13 | +use ec_core::Demuxer; | |
| 14 | +use ec_ogg::{OggDemuxer, granule_of}; | |
| 15 | +use ec_vorbis::{EncoderConfig, VorbisDecoder, VorbisEncoder}; | |
| 16 | + | |
| 17 | +fn fixtures() -> PathBuf { | |
| 18 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") | |
| 19 | +} | |
| 20 | + | |
| 21 | +fn 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. | |
| 33 | +fn 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 | + .chunks_exact(4) | |
| 52 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | |
| 53 | + .collect(); | |
| 54 | + let mut planes = vec![Vec::with_capacity(interleaved.len() / channels); channels]; | |
| 55 | + for (i, value) in interleaved.into_iter().enumerate() { | |
| 56 | + planes[i % channels].push(value); | |
| 57 | + } | |
| 58 | + Some((planes, rate)) | |
| 59 | +} | |
| 60 | + | |
| 61 | +/// One `stream=` field of the first audio stream. | |
| 62 | +fn probe_field(path: &Path, field: &str) -> Option<String> { | |
| 63 | + let out = Command::new("ffprobe") | |
| 64 | + .args([ | |
| 65 | + "-v", | |
| 66 | + "error", | |
| 67 | + "-select_streams", | |
| 68 | + "a:0", | |
| 69 | + "-show_entries", | |
| 70 | + &format!("stream={field}"), | |
| 71 | + "-of", | |
| 72 | + "default=noprint_wrappers=1:nokey=1", | |
| 73 | + ]) | |
| 74 | + .arg(path) | |
| 75 | + .output() | |
| 76 | + .expect("ffprobe runs"); | |
| 77 | + let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); | |
| 78 | + match text.is_empty() || text == "N/A" { | |
| 79 | + true => None, | |
| 80 | + false => Some(text), | |
| 81 | + } | |
| 82 | +} | |
| 83 | + | |
| 84 | +/// Decode with ours, trimming exactly the way an Ogg player does: the first | |
| 85 | +/// page's granule says how much of the first block is before the start of the | |
| 86 | +/// stream, and the last page's granule says where it ends. | |
| 87 | +fn our_decode(path: &Path) -> (Vec<Vec<f32>>, u32) { | |
| 88 | + let mut demuxer = OggDemuxer::open(File::open(path).expect("open")).expect("ogg"); | |
| 89 | + let stream = demuxer | |
| 90 | + .streams() | |
| 91 | + .iter() | |
| 92 | + .find(|s| s.params.codec == ec_core::CodecId::Vorbis) | |
| 93 | + .expect("a Vorbis stream") | |
| 94 | + .clone(); | |
| 95 | + let extradata = stream.params.extradata.clone().expect("headers"); | |
| 96 | + let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse"); | |
| 97 | + let rate = stream | |
| 98 | + .params | |
| 99 | + .audio() | |
| 100 | + .map(|a| a.sample_rate) | |
| 101 | + .expect("audio params"); | |
| 102 | + | |
| 103 | + let mut planes: Vec<Vec<f32>> = Vec::new(); | |
| 104 | + let mut offset: Option<i64> = None; | |
| 105 | + let mut last_granule = 0i64; | |
| 106 | + let mut produced = 0i64; | |
| 107 | + loop { | |
| 108 | + let packet = match demuxer.next_packet() { | |
| 109 | + Ok(packet) => packet, | |
| 110 | + Err(e) if e.is_eof() => break, | |
| 111 | + Err(e) => panic!("demux {}: {e}", path.display()), | |
| 112 | + }; | |
| 113 | + if packet.stream != stream.index { | |
| 114 | + continue; | |
| 115 | + } | |
| 116 | + // A packet a decoder cannot use is skipped, not fatal: the Xiph | |
| 117 | + // `unused-mode` vector states a mode number its own setup header never | |
| 118 | + // defined, and ffmpeg skips those packets too. | |
| 119 | + let Ok(decoded) = decoder.decode_audio(&packet.data) else { | |
| 120 | + continue; | |
| 121 | + }; | |
| 122 | + if planes.is_empty() { | |
| 123 | + planes = vec![Vec::new(); decoded.len()]; | |
| 124 | + } | |
| 125 | + for (channel, samples) in decoded.iter().enumerate() { | |
| 126 | + planes[channel].extend_from_slice(samples); | |
| 127 | + } | |
| 128 | + produced += decoded.first().map_or(0, Vec::len) as i64; | |
| 129 | + if let Some(granule) = granule_of(&packet) { | |
| 130 | + if offset.is_none() { | |
| 131 | + offset = Some(granule - produced); | |
| 132 | + } | |
| 133 | + last_granule = granule; | |
| 134 | + } | |
| 135 | + } | |
| 136 | + let offset = offset.unwrap_or(0); | |
| 137 | + let front = (-offset).max(0) as usize; | |
| 138 | + let end = (last_granule - offset).max(0) as usize; | |
| 139 | + for plane in &mut planes { | |
| 140 | + let end = end.min(plane.len()); | |
| 141 | + let front = front.min(end); | |
| 142 | + *plane = plane[front..end].to_vec(); | |
| 143 | + } | |
| 144 | + (planes, rate) | |
| 145 | +} | |
| 146 | + | |
| 147 | +/// Normalised cross-correlation of two signals over their common length. | |
| 148 | +fn correlation(a: &[f32], b: &[f32]) -> f64 { | |
| 149 | + let n = a.len().min(b.len()); | |
| 150 | + if n == 0 { | |
| 151 | + return 0.0; | |
| 152 | + } | |
| 153 | + let mut sum_ab = 0.0f64; | |
| 154 | + let mut sum_aa = 0.0f64; | |
| 155 | + let mut sum_bb = 0.0f64; | |
| 156 | + for i in 0..n { | |
| 157 | + let (x, y) = (f64::from(a[i]), f64::from(b[i])); | |
| 158 | + sum_ab += x * y; | |
| 159 | + sum_aa += x * x; | |
| 160 | + sum_bb += y * y; | |
| 161 | + } | |
| 162 | + match sum_aa > 0.0 && sum_bb > 0.0 { | |
| 163 | + true => sum_ab / (sum_aa.sqrt() * sum_bb.sqrt()), | |
| 164 | + // Two silent signals agree; one silent and one not does not. | |
| 165 | + false => f64::from(u8::from(sum_aa == sum_bb)), | |
| 166 | + } | |
| 167 | +} | |
| 168 | + | |
| 169 | +fn rms(values: &[f32]) -> f64 { | |
| 170 | + match values.is_empty() { | |
| 171 | + true => 0.0, | |
| 172 | + false => (values | |
| 173 | + .iter() | |
| 174 | + .map(|v| f64::from(*v) * f64::from(*v)) | |
| 175 | + .sum::<f64>() | |
| 176 | + / values.len() as f64) | |
| 177 | + .sqrt(), | |
| 178 | + } | |
| 179 | +} | |
| 180 | + | |
| 181 | +/// Every `.ogg` in a fixture directory, sorted. | |
| 182 | +fn ogg_files(dir: &Path) -> Vec<PathBuf> { | |
| 183 | + let mut files: Vec<PathBuf> = std::fs::read_dir(dir) | |
| 184 | + .unwrap_or_else(|e| panic!("read {}: {e}", dir.display())) | |
| 185 | + .filter_map(|entry| entry.ok().map(|e| e.path())) | |
| 186 | + .filter(|p| p.extension().is_some_and(|e| e == "ogg")) | |
| 187 | + .collect(); | |
| 188 | + files.sort(); | |
| 189 | + files | |
| 190 | +} | |
| 191 | + | |
| 192 | +#[test] | |
| 193 | +fn xiph_vectors_decode_like_ffmpeg() { | |
| 194 | + let dir = fixtures().join("vectors/vorbis-xiph"); | |
| 195 | + let files = ogg_files(&dir); | |
| 196 | + assert!( | |
| 197 | + files.len() >= 20, | |
| 198 | + "expected the Xiph vector set, got {}", | |
| 199 | + files.len() | |
| 200 | + ); | |
| 201 | + let mut failures = Vec::new(); | |
| 202 | + for file in &files { | |
| 203 | + let name = file.file_name().unwrap().to_string_lossy().to_string(); | |
| 204 | + let (ours, our_rate) = our_decode(file); | |
| 205 | + let Some((theirs, their_rate)) = ffmpeg_decode(file) else { | |
| 206 | + // No oracle for this one: hold it to what can still be checked, | |
| 207 | + // that it decodes at all and is not silence. | |
| 208 | + let energy: f64 = ours.iter().map(|c| rms(c)).sum(); | |
| 209 | + println!( | |
| 210 | + "{name}: ffmpeg refuses this file; ours decodes {} ch, rms sum {energy:.5}", | |
| 211 | + ours.len() | |
| 212 | + ); | |
| 213 | + if ours.is_empty() || energy <= 0.0 { | |
| 214 | + failures.push(format!("{name}: decoded to nothing")); | |
| 215 | + } | |
| 216 | + continue; | |
| 217 | + }; | |
| 218 | + if our_rate != their_rate || ours.len() != theirs.len() { | |
| 219 | + failures.push(format!( | |
| 220 | + "{name}: {our_rate} Hz x{} vs ffmpeg {their_rate} Hz x{}", | |
| 221 | + ours.len(), | |
| 222 | + theirs.len() | |
| 223 | + )); | |
| 224 | + continue; | |
| 225 | + } | |
| 226 | + for (channel, (mine, theirs)) in ours.iter().zip(theirs.iter()).enumerate() { | |
| 227 | + let corr = correlation(mine, theirs); | |
| 228 | + let length = (mine.len() as i64 - theirs.len() as i64).abs(); | |
| 229 | + println!( | |
| 230 | + "{name} ch{channel}: corr {corr:.6} len {} vs {} (delta {length}) rms {:.5}/{:.5}", | |
| 231 | + mine.len(), | |
| 232 | + theirs.len(), | |
| 233 | + rms(mine), | |
| 234 | + rms(theirs) | |
| 235 | + ); | |
| 236 | + if corr < 0.999 || length > 0 { | |
| 237 | + failures.push(format!( | |
| 238 | + "{name} ch{channel}: corr {corr:.6}, length delta {length}" | |
| 239 | + )); | |
| 240 | + } | |
| 241 | + } | |
| 242 | + } | |
| 243 | + assert!( | |
| 244 | + failures.is_empty(), | |
| 245 | + "{} failed:\n{}", | |
| 246 | + failures.len(), | |
| 247 | + failures.join("\n") | |
| 248 | + ); | |
| 249 | +} | |
| 250 | + | |
| 251 | +#[test] | |
| 252 | +fn repo_fixtures_decode_like_ffmpeg_including_surround() { | |
| 253 | + let dir = fixtures().join("audio"); | |
| 254 | + let files: Vec<PathBuf> = ogg_files(&dir) | |
| 255 | + .into_iter() | |
| 256 | + .filter(|p| { | |
| 257 | + p.file_name() | |
| 258 | + .unwrap() | |
| 259 | + .to_string_lossy() | |
| 260 | + .starts_with("vorbis-") | |
| 261 | + }) | |
| 262 | + .collect(); | |
| 263 | + assert!(!files.is_empty(), "no vorbis fixtures in {}", dir.display()); | |
| 264 | + let mut failures = Vec::new(); | |
| 265 | + for file in &files { | |
| 266 | + let (theirs, _) = ffmpeg_decode(file).expect("ffmpeg decodes the repo fixtures"); | |
| 267 | + let (ours, _) = our_decode(file); | |
| 268 | + let name = file.file_name().unwrap().to_string_lossy().to_string(); | |
| 269 | + for (channel, (mine, reference)) in ours.iter().zip(theirs.iter()).enumerate() { | |
| 270 | + let corr = correlation(mine, reference); | |
| 271 | + println!( | |
| 272 | + "{name} ch{channel}: corr {corr:.6} len {} vs {}", | |
| 273 | + mine.len(), | |
| 274 | + reference.len() | |
| 275 | + ); | |
| 276 | + if corr < 0.999 || mine.len() != reference.len() { | |
| 277 | + failures.push(format!("{name} ch{channel}: corr {corr:.6}")); | |
| 278 | + } | |
| 279 | + } | |
| 280 | + } | |
| 281 | + assert!(failures.is_empty(), "{}", failures.join("\n")); | |
| 282 | +} | |
| 283 | + | |
| 284 | +/// A test signal with a different tone in every channel, so a channel-order | |
| 285 | +/// mistake shows up as a correlation of nearly zero rather than a subtlety. | |
| 286 | +fn tones(channels: usize, rate: u32, samples: usize) -> Vec<Vec<f32>> { | |
| 287 | + (0..channels) | |
| 288 | + .map(|channel| { | |
| 289 | + let hz = 220.0 * f64::from(channel as u32 + 1); | |
| 290 | + (0..samples) | |
| 291 | + .map(|i| { | |
| 292 | + let t = i as f64 / f64::from(rate); | |
| 293 | + // A slow envelope so the encoder has to track something. | |
| 294 | + let envelope = 0.5 + 0.4 * (2.0 * std::f64::consts::PI * 0.7 * t).sin(); | |
| 295 | + (envelope * (2.0 * std::f64::consts::PI * hz * t).sin() * 0.6) as f32 | |
| 296 | + }) | |
| 297 | + .collect() | |
| 298 | + }) | |
| 299 | + .collect() | |
| 300 | +} | |
| 301 | + | |
| 302 | +/// Write our packets into an Ogg file with the ec-ogg muxer. | |
| 303 | +fn mux(path: &Path, encoder: &VorbisEncoder, packets: &[(Vec<u8>, i64)], rate: u32, channels: u16) { | |
| 304 | + use ec_core::{ | |
| 305 | + AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer, | |
| 306 | + Packet, StreamInfo, TimeBase, | |
| 307 | + }; | |
| 308 | + let base = TimeBase::new(1, i64::from(rate)); | |
| 309 | + let mut params = CodecParameters::new(CodecId::Vorbis); | |
| 310 | + params.media = MediaParameters::Audio(AudioParameters { | |
| 311 | + sample_rate: rate, | |
| 312 | + layout: ChannelLayout::from_count(usize::from(channels)), | |
| 313 | + format: None, | |
| 314 | + bits_per_sample: None, | |
| 315 | + }); | |
| 316 | + params.extradata = Some(Buf::from_vec(encoder.extradata())); | |
| 317 | + let file = File::create(path).expect("create"); | |
| 318 | + let mut muxer = ec_ogg::OggMuxer::new(file); | |
| 319 | + muxer | |
| 320 | + .add_stream(StreamInfo::new(0, base, params)) | |
| 321 | + .expect("add stream"); | |
| 322 | + muxer.write_headers().expect("headers"); | |
| 323 | + for (data, granule) in packets { | |
| 324 | + let mut packet = Packet::new(0, base, data.clone()); | |
| 325 | + packet.side_data.push(ec_ogg::granule_side_data(*granule)); | |
| 326 | + muxer.write_packet(&packet).expect("packet"); | |
| 327 | + } | |
| 328 | + muxer.finish().expect("finish"); | |
| 329 | +} | |
| 330 | + | |
| 331 | +/// Encode `source` and answer the file it was written to. | |
| 332 | +fn encode_to_file(source: &[Vec<f32>], rate: u32, bitrate: i32, name: &str) -> PathBuf { | |
| 333 | + let channels = source.len() as u16; | |
| 334 | + let mut encoder = VorbisEncoder::new(EncoderConfig { | |
| 335 | + sample_rate: rate, | |
| 336 | + channels, | |
| 337 | + bitrate_bps: bitrate, | |
| 338 | + quality: 0.6, | |
| 339 | + }) | |
| 340 | + .expect("encoder"); | |
| 341 | + let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect(); | |
| 342 | + encoder.push_planar(&borrowed).expect("push"); | |
| 343 | + encoder.finish(); | |
| 344 | + let mut packets = Vec::new(); | |
| 345 | + loop { | |
| 346 | + match encoder.next_packet() { | |
| 347 | + Ok(packet) => packets.push((packet.data, packet.granule)), | |
| 348 | + Err(e) if e.is_eof() => break, | |
| 349 | + Err(e) => panic!("encode: {e}"), | |
| 350 | + } | |
| 351 | + } | |
| 352 | + let path = scratch().join(name); | |
| 353 | + mux(&path, &encoder, &packets, rate, channels); | |
| 354 | + path | |
| 355 | +} | |
| 356 | + | |
| 357 | +/// Duration ffprobe reports, in samples of the stream's own rate. | |
| 358 | +fn probed_samples(path: &Path) -> i64 { | |
| 359 | + probe_field(path, "duration_ts") | |
| 360 | + .and_then(|text| text.parse().ok()) | |
| 361 | + .unwrap_or(-1) | |
| 362 | +} | |
| 363 | + | |
| 364 | +#[test] | |
| 365 | +fn encoded_streams_decode_cleanly_at_the_stated_length() { | |
| 366 | + let rate = 48_000u32; | |
| 367 | + let samples = rate as usize * 2; | |
| 368 | + let mut failures = Vec::new(); | |
| 369 | + for channels in [1usize, 2, 6] { | |
| 370 | + let source = tones(channels, rate, samples); | |
| 371 | + for bitrate in [96_000i32, 128_000, 192_000] { | |
| 372 | + let name = format!("enc-{channels}ch-{}k.ogg", bitrate / 1000); | |
| 373 | + let path = encode_to_file(&source, rate, bitrate, &name); | |
| 374 | + let bytes = std::fs::metadata(&path).expect("file").len(); | |
| 375 | + let measured = bytes as f64 * 8.0 * f64::from(rate) / samples as f64 / 1000.0; | |
| 376 | + | |
| 377 | + // ffmpeg decodes it without a word of complaint... | |
| 378 | + let Some((theirs, _)) = ffmpeg_decode(&path) else { | |
| 379 | + failures.push(format!("{name}: ffmpeg refused the file")); | |
| 380 | + continue; | |
| 381 | + }; | |
| 382 | + // ...for exactly as long as the input was. | |
| 383 | + let duration = probed_samples(&path); | |
| 384 | + if duration != samples as i64 { | |
| 385 | + failures.push(format!( | |
| 386 | + "{name}: ffprobe says {duration} samples, source is {samples}" | |
| 387 | + )); | |
| 388 | + } | |
| 389 | + let mut worst = 1.0f64; | |
| 390 | + for (channel, reference) in source.iter().enumerate() { | |
| 391 | + let corr = correlation(&theirs[channel], reference); | |
| 392 | + worst = worst.min(corr); | |
| 393 | + } | |
| 394 | + // ...and our own decoder agrees with ffmpeg about what it says. | |
| 395 | + let (ours, _) = our_decode(&path); | |
| 396 | + let mut agreement = 1.0f64; | |
| 397 | + for (mine, theirs) in ours.iter().zip(theirs.iter()) { | |
| 398 | + agreement = agreement.min(correlation(mine, theirs)); | |
| 399 | + } | |
| 400 | + println!( | |
| 401 | + "{name}: {measured:.0} kbps, corr vs source {worst:.4}, ours vs ffmpeg {agreement:.6}, samples {duration}" | |
| 402 | + ); | |
| 403 | + let bar = match channels { | |
| 404 | + 6 => 0.9, | |
| 405 | + _ => 0.95, | |
| 406 | + }; | |
| 407 | + if worst < bar { | |
| 408 | + failures.push(format!("{name}: corr vs source {worst:.4} under {bar}")); | |
| 409 | + } | |
| 410 | + if agreement < 0.999 { | |
| 411 | + failures.push(format!( | |
| 412 | + "{name}: our decode disagrees with ffmpeg ({agreement:.6})" | |
| 413 | + )); | |
| 414 | + } | |
| 415 | + } | |
| 416 | + } | |
| 417 | + assert!(failures.is_empty(), "{}", failures.join("\n")); | |
| 418 | +} | |
| 419 | + | |
| 420 | +#[test] | |
| 421 | +fn a_short_input_keeps_its_own_length() { | |
| 422 | + // Shorter than one block: the grid still has to close and the granule | |
| 423 | + // still has to state the input's own count. | |
| 424 | + let rate = 44_100u32; | |
| 425 | + for samples in [1usize, 700, 1024, 1025, 4096] { | |
| 426 | + let source = tones(2, rate, samples); | |
| 427 | + let path = encode_to_file(&source, rate, 128_000, &format!("short-{samples}.ogg")); | |
| 428 | + let duration = probed_samples(&path); | |
| 429 | + assert_eq!( | |
| 430 | + duration, samples as i64, | |
| 431 | + "{samples} samples in, ffprobe says {duration}" | |
| 432 | + ); | |
| 433 | + } | |
| 434 | +} | |
| 435 | + | |
| 436 | +/// Noise-plus-tones: a signal with enough going on that the rate loop has | |
| 437 | +/// something to spend bits on, which a pure tone does not. | |
| 438 | +fn busy(channels: usize, rate: u32, samples: usize) -> Vec<Vec<f32>> { | |
| 439 | + let mut state = 0x2545_f491_4f6c_dd1du64; | |
| 440 | + let mut noise = move || { | |
| 441 | + state ^= state << 13; | |
| 442 | + state ^= state >> 7; | |
| 443 | + state ^= state << 17; | |
| 444 | + (state >> 40) as f32 / 8_388_608.0 - 1.0 | |
| 445 | + }; | |
| 446 | + (0..channels) | |
| 447 | + .map(|channel| { | |
| 448 | + (0..samples) | |
| 449 | + .map(|i| { | |
| 450 | + let t = i as f64 / f64::from(rate); | |
| 451 | + let hz = 300.0 * f64::from(channel as u32 + 1); | |
| 452 | + let tone = (2.0 * std::f64::consts::PI * hz * t).sin() as f32; | |
| 453 | + 0.35 * tone + 0.35 * noise() | |
| 454 | + }) | |
| 455 | + .collect() | |
| 456 | + }) | |
| 457 | + .collect() | |
| 458 | +} | |
| 459 | + | |
| 460 | +#[test] | |
| 461 | +fn the_rate_loop_tracks_the_target_bitrate() { | |
| 462 | + let rate = 48_000u32; | |
| 463 | + let samples = rate as usize * 3; | |
| 464 | + let source = busy(2, rate, samples); | |
| 465 | + let mut measured = Vec::new(); | |
| 466 | + for target in [96_000i32, 128_000, 192_000] { | |
| 467 | + let path = encode_to_file( | |
| 468 | + &source, | |
| 469 | + rate, | |
| 470 | + target, | |
| 471 | + &format!("abr-{}k.ogg", target / 1000), | |
| 472 | + ); | |
| 473 | + let bytes = std::fs::metadata(&path).expect("file").len(); | |
| 474 | + let kbps = bytes as f64 * 8.0 * f64::from(rate) / samples as f64 / 1000.0; | |
| 475 | + println!("target {} kbps -> {kbps:.0} kbps", target / 1000); | |
| 476 | + measured.push(kbps); | |
| 477 | + } | |
| 478 | + // Monotone in the target, and within a quarter of it: the loop moves one | |
| 479 | + // quantiser gain, so it tracks rather than hits. | |
| 480 | + assert!( | |
| 481 | + measured[0] < measured[1] && measured[1] < measured[2], | |
| 482 | + "{measured:?}" | |
| 483 | + ); | |
| 484 | + for (kbps, target) in measured.iter().zip([96.0, 128.0, 192.0]) { | |
| 485 | + assert!( | |
| 486 | + (kbps - target).abs() / target < 0.25, | |
| 487 | + "{kbps:.0} kbps for a {target:.0} kbps target" | |
| 488 | + ); | |
| 489 | + } | |
| 490 | +} |