Merge branch 'simplify/u9' into simplify/w1b
Browse files at this commit7 changed files +29 -879
- crates/ec-alac/src/encode.rs +5 -18
- crates/ec-alac/tests/encode.rs +22 -126
- crates/ec-flac/tests/level_depth_parity.rs +0 -330
- crates/ec-vorbis/src/decode.rs +0 -43
- crates/ec-vorbis/src/encode.rs +1 -122
- crates/ec-vorbis/src/lib.rs +1 -1
- crates/ec-vorbis/tests/oracle.rs +0 -239
crates/ec-alac/src/encode.rsmodified+5 -18
| @@ -269,12 +269,11 @@ fn analyze(y: &[i32], order: usize, den_shift: u32, chan_bits: u32) -> Vec<i32> | ||
| 269 | 269 | res |
| 270 | 270 | } |
| 271 | 271 | |
| 272 | -/// One channel's chosen filter: the mode and order fields to write, the | |
| 272 | +/// One channel's chosen filter: the order field to write, the | |
| 273 | 273 | /// residuals it produces, and its total cost in bits (16-bit plan header + |
| 274 | 274 | /// coefficients + the Rice-coded residuals), for comparing against every |
| 275 | 275 | /// other choice. |
| 276 | 276 | struct Candidate { |
| 277 | - mode: u32, | |
| 278 | 277 | order: u32, |
| 279 | 278 | res: Vec<i32>, |
| 280 | 279 | bits: u64, |
| @@ -296,7 +295,6 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) | ||
| 296 | 295 | |
| 297 | 296 | if best.as_ref().is_none_or(|b| bits < b.bits) { |
| 298 | 297 | best = Some(Candidate { |
| 299 | - mode: 0, | |
| 300 | 298 | order: order as u32, |
| 301 | 299 | res, |
| 302 | 300 | bits, |
| @@ -304,7 +302,6 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) | ||
| 304 | 302 | } |
| 305 | 303 | } |
| 306 | 304 | best.unwrap_or(Candidate { |
| 307 | - mode: 0, | |
| 308 | 305 | order: 0, |
| 309 | 306 | res: y.to_vec(), |
| 310 | 307 | bits: u64::MAX, |
| @@ -336,7 +333,7 @@ fn write_plan<S: BitSink>(sink: &mut S, plan: &ChannelPlan) { | ||
| 336 | 333 | /// One SCE (mono) or CPE (stereo) element, choosing per-element between raw |
| 337 | 334 | /// (escape) and compressed, and for a pair, between direct L/R and a |
| 338 | 335 | /// mid/side mix, whichever is smaller. |
| 339 | -fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize, allow_shift: bool) { | |
| 336 | +fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize) { | |
| 340 | 337 | w.put(0, 16); // element instance tag + 12 reserved bits. |
| 341 | 338 | let pair = planes.len() == 2; |
| 342 | 339 | let channels = planes.len() as u32; |
| @@ -350,7 +347,7 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp | ||
| 350 | 347 | // compressing the sample whole. Only 0 and 1 are ever tried: 3 is the |
| 351 | 348 | // format's escape sentinel (decode.rs:439), and a stream never carries |
| 352 | 349 | // more than one low byte's worth of headroom worth shifting off. |
| 353 | - let shift_candidates: &[u32] = if bit_depth == 24 && allow_shift { &[0, 1] } else { &[0] }; | |
| 350 | + let shift_candidates: &[u32] = if bit_depth == 24 { &[0, 1] } else { &[0] }; | |
| 354 | 351 | |
| 355 | 352 | let compressed = (samples >= 2).then(|| { |
| 356 | 353 | shift_candidates |
| @@ -446,7 +443,7 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp | ||
| 446 | 443 | |
| 447 | 444 | fn plan_of(c: Candidate) -> ChannelPlan { |
| 448 | 445 | ChannelPlan { |
| 449 | - mode: c.mode, | |
| 446 | + mode: 0, | |
| 450 | 447 | order: c.order, |
| 451 | 448 | pb_factor: PB_FACTOR, |
| 452 | 449 | res: c.res, |
| @@ -478,7 +475,6 @@ pub struct AlacEncoder { | ||
| 478 | 475 | pending: Vec<i32>, |
| 479 | 476 | packets: std::collections::VecDeque<Vec<u8>>, |
| 480 | 477 | eof: bool, |
| 481 | - allow_shift: bool, | |
| 482 | 478 | } |
| 483 | 479 | |
| 484 | 480 | impl AlacEncoder { |
| @@ -529,18 +525,9 @@ impl AlacEncoder { | ||
| 529 | 525 | pending: Vec::new(), |
| 530 | 526 | packets: std::collections::VecDeque::new(), |
| 531 | 527 | eof: false, |
| 532 | - allow_shift: true, | |
| 533 | 528 | }) |
| 534 | 529 | } |
| 535 | 530 | |
| 536 | - /// Test-only: force bytes_shifted 0 even at 24 bits, so a test can | |
| 537 | - /// measure both paths against the same source. Both outputs decode the | |
| 538 | - /// same; this only trades size. | |
| 539 | - #[doc(hidden)] | |
| 540 | - pub fn set_byte_shift(&mut self, allow: bool) { | |
| 541 | - self.allow_shift = allow; | |
| 542 | - } | |
| 543 | - | |
| 544 | 531 | /// What this encoder states about the stream it writes. |
| 545 | 532 | pub fn cookie(&self) -> &MagicCookie { |
| 546 | 533 | &self.cookie |
| @@ -567,7 +554,7 @@ impl AlacEncoder { | ||
| 567 | 554 | } |
| 568 | 555 | let mut w = BitWriter::default(); |
| 569 | 556 | w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3); |
| 570 | - write_element(&self.cookie, &mut w, &planes, n, self.allow_shift); | |
| 557 | + write_element(&self.cookie, &mut w, &planes, n); | |
| 571 | 558 | w.put(ID_END, 3); |
| 572 | 559 | Ok(w.finish()) |
| 573 | 560 | } |
crates/ec-alac/tests/encode.rsmodified+22 -126
| @@ -1,11 +1,10 @@ | ||
| 1 | 1 | //! Round-trip the encoder through the decoder it was written to feed, then |
| 2 | 2 | |
| 3 | -use std::fs::File; | |
| 4 | -use std::io::{BufReader, Cursor}; | |
| 3 | +use std::io::Cursor; | |
| 5 | 4 | use std::path::{Path, PathBuf}; |
| 6 | 5 | |
| 7 | 6 | use ec_alac::{AlacDecoder, AlacEncoder}; |
| 8 | -use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo}; | |
| 7 | +use ec_core::registry::{Encoder, Muxer, StreamInfo}; | |
| 9 | 8 | use ec_core::timebase::TimeBase; |
| 10 | 9 | use ec_core::Packet; |
| 11 | 10 | |
| @@ -85,41 +84,6 @@ fn ffmpeg_decode(path: &Path, fmt: &str) -> Vec<u8> { | ||
| 85 | 84 | decode.stdout |
| 86 | 85 | } |
| 87 | 86 | |
| 88 | -#[test] | |
| 89 | -fn twenty_four_bit_uses_byte_shift_when_cheaper() { | |
| 90 | - // Real 16-bit audio widened to 24 bits with random dither in the low | |
| 91 | - // byte: exactly the shape a 24-bit master of 16-bit source material has, | |
| 92 | - // and exactly what bytes_shifted exists for — the high bits alone | |
| 93 | - // predict well, but folded together with the dither's noise they do not. | |
| 94 | - let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); | |
| 95 | - let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); | |
| 96 | - let spec = reader.spec(); | |
| 97 | - let mut rng = Rng(0xdead_beef); | |
| 98 | - let samples: Vec<i32> = reader | |
| 99 | - .read_all_i32() | |
| 100 | - .expect("pcm") | |
| 101 | - .into_iter() | |
| 102 | - .map(|s| (s << 8) | (rng.next() & 0xff) as i32) | |
| 103 | - .collect(); | |
| 104 | - let channels = spec.channels as u8; | |
| 105 | - | |
| 106 | - round_trip(spec.sample_rate, channels, 24, 4096, &samples); | |
| 107 | - | |
| 108 | - let per_frame = 4096 * channels as usize; | |
| 109 | - let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); | |
| 110 | - let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).expect("frame").len()).sum(); | |
| 111 | - | |
| 112 | - let mut without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); | |
| 113 | - without_shift.set_byte_shift(false); | |
| 114 | - let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).expect("frame").len()).sum(); | |
| 115 | - | |
| 116 | - eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes"); | |
| 117 | - assert!( | |
| 118 | - with_bytes < without_bytes, | |
| 119 | - "bytes_shifted split ({with_bytes}) should beat forcing bytes_shifted=0 ({without_bytes})" | |
| 120 | - ); | |
| 121 | -} | |
| 122 | - | |
| 123 | 87 | #[test] |
| 124 | 88 | fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { |
| 125 | 89 | // A smooth tone's first residuals are far bigger than the coder's |
| @@ -134,24 +98,21 @@ fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { | ||
| 134 | 98 | .collect(); |
| 135 | 99 | let wide: Vec<i32> = tone.iter().map(|&s| (s << 8) | (rng.next() & 0xff) as i32).collect(); |
| 136 | 100 | for samples in [&tone, &wide] { |
| 137 | - for allow_shift in [true, false] { | |
| 138 | - let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); | |
| 139 | - enc.set_byte_shift(allow_shift); | |
| 140 | - let mut dec = AlacDecoder::new(*enc.cookie()); | |
| 141 | - let shift = enc.cookie().container_shift(); | |
| 142 | - let mut decoded = Vec::new(); | |
| 143 | - for chunk in samples.chunks(4096 * channels as usize) { | |
| 144 | - decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift)); | |
| 145 | - } | |
| 146 | - assert_eq!(&decoded, samples, "{channels}ch 24-bit tone, shift={allow_shift}"); | |
| 147 | - | |
| 148 | - // And the reference decoder agrees with what we wrote. | |
| 149 | - let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); | |
| 150 | - let got = ffmpeg_decode(&out_path, "s32le"); | |
| 151 | - std::fs::remove_dir_all(&dir).ok(); | |
| 152 | - let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); | |
| 153 | - assert!(got == want, "{channels}ch 24-bit tone, shift={allow_shift}: reference decode differs"); | |
| 101 | + let enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); | |
| 102 | + let mut dec = AlacDecoder::new(*enc.cookie()); | |
| 103 | + let shift = enc.cookie().container_shift(); | |
| 104 | + let mut decoded = Vec::new(); | |
| 105 | + for chunk in samples.chunks(4096 * channels as usize) { | |
| 106 | + decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift)); | |
| 154 | 107 | } |
| 108 | + assert_eq!(&decoded, samples, "{channels}ch 24-bit tone"); | |
| 109 | + | |
| 110 | + // And the reference decoder agrees with what we wrote. | |
| 111 | + let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); | |
| 112 | + let got = ffmpeg_decode(&out_path, "s32le"); | |
| 113 | + std::fs::remove_dir_all(&dir).ok(); | |
| 114 | + let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); | |
| 115 | + assert!(got == want, "{channels}ch 24-bit tone: reference decode differs"); | |
| 155 | 116 | } |
| 156 | 117 | } |
| 157 | 118 | } |
| @@ -188,84 +149,21 @@ fn real_audio_round_trips_and_compresses() { | ||
| 188 | 149 | assert!(ratio <= 0.75, "compression ratio {ratio:.4} > 0.75"); |
| 189 | 150 | } |
| 190 | 151 | |
| 191 | -#[test] | |
| 192 | -fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { | |
| 193 | - let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); | |
| 194 | - let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); | |
| 195 | - let spec = reader.spec(); | |
| 196 | - let samples = reader.read_all_i32().expect("pcm"); | |
| 197 | - let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) | |
| 198 | - .expect("encoder"); | |
| 199 | - | |
| 200 | - let (dir, out_path) = mux_to_m4a(&enc, spec.channels as usize, spec.sample_rate, &samples); | |
| 201 | - | |
| 202 | - // Sanity without an oracle: our own demuxer/decoder reads it back | |
| 203 | - // bit-exact against the source PCM. | |
| 204 | - let mut demuxer = | |
| 205 | - ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&out_path).expect("open"))).expect("mp4"); | |
| 206 | - let track = demuxer | |
| 207 | - .streams() | |
| 208 | - .iter() | |
| 209 | - .find(|s| s.params.codec == CodecId::Alac) | |
| 210 | - .expect("alac track") | |
| 211 | - .clone(); | |
| 212 | - let mut dec = AlacDecoder::from_parameters(track.params).expect("cookie"); | |
| 213 | - let shift = dec.cookie().container_shift(); | |
| 214 | - let mut decoded = Vec::new(); | |
| 215 | - loop { | |
| 216 | - match demuxer.next_packet() { | |
| 217 | - Ok(p) if p.stream != track.index => continue, | |
| 218 | - Ok(p) => decoded.extend(dec.decode(&p.data).expect("decode").iter().map(|&s| s >> shift)), | |
| 219 | - Err(e) if e.is_eof() => break, | |
| 220 | - Err(e) => panic!("{e}"), | |
| 221 | - } | |
| 222 | - } | |
| 223 | - assert_eq!(decoded, samples, "mux -> demux -> decode round trip"); | |
| 224 | - | |
| 225 | - // The oracle: ffprobe reads the track back as alac at the right rate and | |
| 226 | - // channel count, and ffmpeg's own decode matches the source exactly. | |
| 227 | - let probe = ec_testkit::ffprobe() | |
| 228 | - .args([ | |
| 229 | - "-v", "error", "-select_streams", "a:0", "-show_entries", | |
| 230 | - "stream=codec_name,sample_rate,channels", | |
| 231 | - "-of", "default=noprint_wrappers=1", | |
| 232 | - ]) | |
| 233 | - .arg(&out_path) | |
| 234 | - .output() | |
| 235 | - .expect("ffprobe"); | |
| 236 | - let info = String::from_utf8_lossy(&probe.stdout); | |
| 237 | - assert!(info.contains("codec_name=alac"), "{info}"); | |
| 238 | - assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}"); | |
| 239 | - assert!(info.contains(&format!("channels={}", spec.channels)), "{info}"); | |
| 240 | - | |
| 241 | - let stdout = ffmpeg_decode(&out_path, "s16le"); | |
| 242 | - let want: Vec<i16> = samples.iter().map(|&s| s as i16).collect(); | |
| 243 | - let got: Vec<i16> = stdout | |
| 244 | - .as_chunks::<2>().0.iter() | |
| 245 | - .map(|c| i16::from_le_bytes([c[0], c[1]])) | |
| 246 | - .collect(); | |
| 247 | - assert_eq!(got, want, "ffmpeg decode of the muxed file vs source PCM"); | |
| 248 | - | |
| 249 | - let _ = std::fs::remove_dir_all(&dir); | |
| 250 | -} | |
| 251 | - | |
| 252 | - | |
| 253 | -fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, what: &str) { | |
| 254 | - let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); | |
| 255 | - enc.set_byte_shift(allow_shift); | |
| 152 | +fn round_trip_both_decoders(channels: u8, samples: &[i32], what: &str) { | |
| 153 | + let enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); | |
| 256 | 154 | let mut dec = AlacDecoder::new(*enc.cookie()); |
| 257 | 155 | let shift = enc.cookie().container_shift(); |
| 258 | 156 | let mut decoded = Vec::new(); |
| 259 | 157 | for chunk in samples.chunks(4096 * channels as usize) { |
| 260 | 158 | decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift)); |
| 261 | 159 | } |
| 262 | - assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}"); | |
| 160 | + assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit"); | |
| 263 | 161 | |
| 264 | 162 | let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); |
| 265 | 163 | let got = ffmpeg_decode(&out_path, "s32le"); |
| 266 | 164 | std::fs::remove_dir_all(&dir).ok(); |
| 267 | 165 | let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); |
| 268 | - assert!(got == want, "{what}: {channels}ch 24-bit, shift={allow_shift}: reference decode differs"); | |
| 166 | + assert!(got == want, "{what}: {channels}ch 24-bit: reference decode differs"); | |
| 269 | 167 | } |
| 270 | 168 | |
| 271 | 169 | #[test] |
| @@ -275,9 +173,7 @@ fn mono_24_bit_ramp_round_trips_bit_exactly() { | ||
| 275 | 173 | // carries, so the encoder must wrap it the way the decoder does. |
| 276 | 174 | for n in [1015usize, 1016, 1024, 2048, 4096] { |
| 277 | 175 | let samples: Vec<i32> = (0..n).map(|i| ((i as i64 * 7919) % 8_000_000 - 4_000_000) as i32).collect(); |
| 278 | - for allow_shift in [true, false] { | |
| 279 | - round_trip_both_decoders(1, &samples, allow_shift, &format!("ramp n={n}")); | |
| 280 | - } | |
| 176 | + round_trip_both_decoders(1, &samples, &format!("ramp n={n}")); | |
| 281 | 177 | } |
| 282 | 178 | } |
| 283 | 179 | |
| @@ -285,7 +181,7 @@ fn mono_24_bit_ramp_round_trips_bit_exactly() { | ||
| 285 | 181 | fn mono_24_bit_full_scale_alternating_round_trips() { |
| 286 | 182 | for n in [512usize, 4096] { |
| 287 | 183 | let samples: Vec<i32> = (0..n).map(|i| if i % 2 == 0 { 8_388_607 } else { -8_388_607 }).collect(); |
| 288 | - round_trip_both_decoders(1, &samples, true, &format!("alternating n={n}")); | |
| 184 | + round_trip_both_decoders(1, &samples, &format!("alternating n={n}")); | |
| 289 | 185 | } |
| 290 | 186 | } |
| 291 | 187 |
crates/ec-flac/tests/level_depth_parity.rsdeleted+0 -330
| @@ -1,330 +0,0 @@ | ||
| 1 | -//! Parity with the flacenc export that ec-flac replaced. | |
| 2 | -//! | |
| 3 | -//! edith's old writer ran `flacenc::config::Encoder::default()` (4096-sample | |
| 4 | -//! fixed blocks, LPC to order 12, Rice partitions to order 6) on 16-bit input, | |
| 5 | -//! and `engine::flac_write` still asks for 16 bits. The 24-bit path is reachable | |
| 6 | -//! through the writer, so it is covered too. | |
| 7 | -//! | |
| 8 | -//! For every ec-flac level in [`levels`] and every case in [`CASES`], a | |
| 9 | -//! sine-plus-noise signal generated by ffmpeg (2.0 and 5.1) goes through | |
| 10 | -//! `ec_flac::encode` and is checked three ways: | |
| 11 | -//! | |
| 12 | -//! (a) ffmpeg decodes our stream back to the input PCM byte for byte; | |
| 13 | -//! (b) STREAMINFO carries the right rate, channels, bit depth and length, and | |
| 14 | -//! the MD5 of the input PCM (the MD5 is computed by `md5sum`, not by us); | |
| 15 | -//! (c) our size is at most [`MARGIN`] times the size ffmpeg's own FLAC encoder | |
| 16 | -//! produces at the matching `-compression_level`. | |
| 17 | -//! | |
| 18 | -//! ec-flac has no compression-level enum. Its levels are [`EncoderConfig`] | |
| 19 | -//! presets, paired with the ffmpeg level they sit nearest to (see [`levels`]). | |
| 20 | -//! | |
| 21 | -//! Run the table: | |
| 22 | -//! cargo test -p ec-flac --release --test level_depth_parity -- --nocapture | |
| 23 | - | |
| 24 | -use std::fs; | |
| 25 | -use std::path::{Path, PathBuf}; | |
| 26 | -use std::process::Command; | |
| 27 | - | |
| 28 | -use ec_flac::decode::FlacReader; | |
| 29 | -use ec_flac::encode::{EncoderConfig, encode}; | |
| 30 | - | |
| 31 | -/// Largest accepted ratio of our size to ffmpeg's size at the matching level. | |
| 32 | -const MARGIN: f64 = 1.05; | |
| 33 | - | |
| 34 | -/// Seconds of signal per case. | |
| 35 | -const SECONDS: u32 = 5; | |
| 36 | - | |
| 37 | -/// (label, ec-flac settings, matching ffmpeg `-compression_level`). | |
| 38 | -fn levels() -> Vec<(&'static str, EncoderConfig, u8)> { | |
| 39 | - vec![ | |
| 40 | - ( | |
| 41 | - "ec L0 fixed", | |
| 42 | - EncoderConfig { | |
| 43 | - max_lpc_order: 0, | |
| 44 | - max_partition_order: 3, | |
| 45 | - ..EncoderConfig::default() | |
| 46 | - }, | |
| 47 | - 0, | |
| 48 | - ), | |
| 49 | - ("ec default (edith)", EncoderConfig::default(), 5), | |
| 50 | - ( | |
| 51 | - "ec L8 max", | |
| 52 | - EncoderConfig { | |
| 53 | - max_lpc_order: 32, | |
| 54 | - max_partition_order: 6, | |
| 55 | - ..EncoderConfig::default() | |
| 56 | - }, | |
| 57 | - 8, | |
| 58 | - ), | |
| 59 | - ] | |
| 60 | -} | |
| 61 | - | |
| 62 | -struct Case { | |
| 63 | - name: &'static str, | |
| 64 | - layout: &'static str, | |
| 65 | - channels: usize, | |
| 66 | - rate: u32, | |
| 67 | - bits: u32, | |
| 68 | -} | |
| 69 | - | |
| 70 | -const CASES: [Case; 4] = [ | |
| 71 | - Case { | |
| 72 | - name: "16-bit 2.0 44.1k", | |
| 73 | - layout: "stereo", | |
| 74 | - channels: 2, | |
| 75 | - rate: 44100, | |
| 76 | - bits: 16, | |
| 77 | - }, | |
| 78 | - Case { | |
| 79 | - name: "16-bit 5.1 48k", | |
| 80 | - layout: "5.1", | |
| 81 | - channels: 6, | |
| 82 | - rate: 48000, | |
| 83 | - bits: 16, | |
| 84 | - }, | |
| 85 | - Case { | |
| 86 | - name: "24-bit 2.0 48k", | |
| 87 | - layout: "stereo", | |
| 88 | - channels: 2, | |
| 89 | - rate: 48000, | |
| 90 | - bits: 24, | |
| 91 | - }, | |
| 92 | - Case { | |
| 93 | - name: "24-bit 5.1 48k", | |
| 94 | - layout: "5.1", | |
| 95 | - channels: 6, | |
| 96 | - rate: 48000, | |
| 97 | - bits: 24, | |
| 98 | - }, | |
| 99 | -]; | |
| 100 | - | |
| 101 | -fn ffmpeg(args: &[&str]) { | |
| 102 | - let status = ec_testkit::ffmpeg() | |
| 103 | - .args(["-hide_banner", "-loglevel", "error", "-y"]) | |
| 104 | - .args(args) | |
| 105 | - .status() | |
| 106 | - .expect("run ffmpeg (is it installed?)"); | |
| 107 | - assert!(status.success(), "ffmpeg {args:?} failed"); | |
| 108 | -} | |
| 109 | - | |
| 110 | -fn ffprobe_stream(path: &Path) -> (u32, u32, u32) { | |
| 111 | - let out = ec_testkit::ffprobe() | |
| 112 | - .args([ | |
| 113 | - "-v", | |
| 114 | - "error", | |
| 115 | - "-select_streams", | |
| 116 | - "a:0", | |
| 117 | - "-show_entries", | |
| 118 | - "stream=sample_rate,channels,bits_per_raw_sample", | |
| 119 | - "-of", | |
| 120 | - "csv=p=0", | |
| 121 | - ]) | |
| 122 | - .arg(path) | |
| 123 | - .output() | |
| 124 | - .expect("run ffprobe"); | |
| 125 | - assert!(out.status.success(), "ffprobe failed on {}", path.display()); | |
| 126 | - let text = String::from_utf8(out.stdout).expect("ffprobe utf8"); | |
| 127 | - let fields: Vec<u32> = text | |
| 128 | - .trim() | |
| 129 | - .split(',') | |
| 130 | - .map(|f| f.parse().expect("ffprobe numeric field")) | |
| 131 | - .collect(); | |
| 132 | - // csv order: sample_rate, channels, bits_per_raw_sample | |
| 133 | - (fields[0], fields[1], fields[2]) | |
| 134 | -} | |
| 135 | - | |
| 136 | -fn md5_hex(path: &Path) -> String { | |
| 137 | - let out = Command::new("md5sum") | |
| 138 | - .arg(path) | |
| 139 | - .output() | |
| 140 | - .expect("run md5sum"); | |
| 141 | - assert!(out.status.success(), "md5sum failed"); | |
| 142 | - String::from_utf8_lossy(&out.stdout) | |
| 143 | - .split_whitespace() | |
| 144 | - .next() | |
| 145 | - .expect("md5sum digest") | |
| 146 | - .to_string() | |
| 147 | -} | |
| 148 | - | |
| 149 | -fn fmt_for(bits: u32) -> &'static str { | |
| 150 | - match bits { | |
| 151 | - 16 => "s16le", | |
| 152 | - 24 => "s24le", | |
| 153 | - _ => panic!("unsupported bit depth {bits}"), | |
| 154 | - } | |
| 155 | -} | |
| 156 | - | |
| 157 | -/// Sine plus noise, one sine per channel, generated by ffmpeg as raw PCM. | |
| 158 | -fn generate(dir: &Path, c: &Case) -> PathBuf { | |
| 159 | - let exprs: Vec<String> = (0..c.channels) | |
| 160 | - .map(|i| { | |
| 161 | - let f = 220.0 * (i as f64 + 1.0); | |
| 162 | - format!("0.4*sin(2*PI*{f}*t)+0.08*(random({i})*2-1)") | |
| 163 | - }) | |
| 164 | - .collect(); | |
| 165 | - let src = format!( | |
| 166 | - "aevalsrc=exprs={}:s={}:d={}:c={}", | |
| 167 | - exprs.join("|"), | |
| 168 | - c.rate, | |
| 169 | - SECONDS, | |
| 170 | - c.layout | |
| 171 | - ); | |
| 172 | - let path = dir.join(format!("in-{}-{}-{}.raw", c.channels, c.bits, c.rate)); | |
| 173 | - ffmpeg(&[ | |
| 174 | - "-f", | |
| 175 | - "lavfi", | |
| 176 | - "-i", | |
| 177 | - &src, | |
| 178 | - "-f", | |
| 179 | - fmt_for(c.bits), | |
| 180 | - path.to_str().unwrap(), | |
| 181 | - ]); | |
| 182 | - path | |
| 183 | -} | |
| 184 | - | |
| 185 | -/// Little-endian signed PCM bytes to sign-extended samples. | |
| 186 | -fn to_samples(pcm: &[u8], bits: u32) -> Vec<i32> { | |
| 187 | - match bits { | |
| 188 | - 16 => pcm | |
| 189 | - .as_chunks::<2>() | |
| 190 | - .0 | |
| 191 | - .iter() | |
| 192 | - .map(|b| i16::from_le_bytes(*b) as i32) | |
| 193 | - .collect(), | |
| 194 | - 24 => pcm | |
| 195 | - .as_chunks::<3>() | |
| 196 | - .0 | |
| 197 | - .iter() | |
| 198 | - .map(|b| (((b[0] as i32) | ((b[1] as i32) << 8) | ((b[2] as i32) << 16)) << 8) >> 8) | |
| 199 | - .collect(), | |
| 200 | - _ => panic!("unsupported bit depth {bits}"), | |
| 201 | - } | |
| 202 | -} | |
| 203 | - | |
| 204 | -fn ffmpeg_reference_size(raw: &Path, c: &Case, level: u8, out: &Path) -> u64 { | |
| 205 | - ffmpeg(&[ | |
| 206 | - "-f", | |
| 207 | - fmt_for(c.bits), | |
| 208 | - "-ar", | |
| 209 | - &c.rate.to_string(), | |
| 210 | - "-ac", | |
| 211 | - &c.channels.to_string(), | |
| 212 | - "-i", | |
| 213 | - raw.to_str().unwrap(), | |
| 214 | - "-c:a", | |
| 215 | - "flac", | |
| 216 | - "-compression_level", | |
| 217 | - &level.to_string(), | |
| 218 | - out.to_str().unwrap(), | |
| 219 | - ]); | |
| 220 | - fs::metadata(out).expect("reference size").len() | |
| 221 | -} | |
| 222 | - | |
| 223 | -#[test] | |
| 224 | -fn level_and_depth_parity_with_ffmpeg_flac() { | |
| 225 | - let dir = std::env::temp_dir().join(format!("ec-flac-parity-{}", std::process::id())); | |
| 226 | - fs::create_dir_all(&dir).expect("create work dir"); | |
| 227 | - | |
| 228 | - println!(); | |
| 229 | - println!( | |
| 230 | - "| case | ec-flac level | ec-flac bytes | ffmpeg -compression_level | ffmpeg bytes | ratio | verdict |" | |
| 231 | - ); | |
| 232 | - println!("|---|---|---|---|---|---|---|"); | |
| 233 | - | |
| 234 | - let mut failures: Vec<String> = Vec::new(); | |
| 235 | - | |
| 236 | - for c in &CASES { | |
| 237 | - let raw = generate(&dir, c); | |
| 238 | - let pcm = fs::read(&raw).expect("read generated pcm"); | |
| 239 | - let samples = to_samples(&pcm, c.bits); | |
| 240 | - let frames = (samples.len() / c.channels) as u64; | |
| 241 | - let md5_expected = md5_hex(&raw); | |
| 242 | - | |
| 243 | - for (label, config, ff_level) in levels() { | |
| 244 | - let tag = format!("{}-{}", c.bits, c.channels); | |
| 245 | - let flac_path = dir.join(format!("ours-{tag}-{ff_level}.flac")); | |
| 246 | - let back_path = dir.join(format!("back-{tag}-{ff_level}.raw")); | |
| 247 | - let ref_path = dir.join(format!("ref-{tag}-{ff_level}.flac")); | |
| 248 | - | |
| 249 | - // Encode. | |
| 250 | - let stream = encode(&config, &samples, c.channels, c.bits, c.rate) | |
| 251 | - .unwrap_or_else(|e| panic!("encode {} {label}: {e:?}", c.name)); | |
| 252 | - fs::write(&flac_path, &stream).expect("write our flac"); | |
| 253 | - let our_size = stream.len() as u64; | |
| 254 | - | |
| 255 | - // (b) STREAMINFO, read by our own parser. | |
| 256 | - let reader = FlacReader::new(&stream).expect("open our stream"); | |
| 257 | - let info = reader.stream_info().expect("streaminfo").clone(); | |
| 258 | - let mut bad = Vec::new(); | |
| 259 | - if info.sample_rate != c.rate { | |
| 260 | - bad.push(format!("rate {} != {}", info.sample_rate, c.rate)); | |
| 261 | - } | |
| 262 | - if usize::from(info.channels) != c.channels { | |
| 263 | - bad.push(format!("channels {} != {}", info.channels, c.channels)); | |
| 264 | - } | |
| 265 | - if u32::from(info.bits_per_sample) != c.bits { | |
| 266 | - bad.push(format!("bits {} != {}", info.bits_per_sample, c.bits)); | |
| 267 | - } | |
| 268 | - if info.total_samples != frames { | |
| 269 | - bad.push(format!("total_samples {} != {frames}", info.total_samples)); | |
| 270 | - } | |
| 271 | - if info.md5.iter().all(|&b| b == 0) { | |
| 272 | - bad.push("md5 is zero".to_string()); | |
| 273 | - } | |
| 274 | - let md5_stream: String = info.md5.iter().map(|b| format!("{b:02x}")).collect(); | |
| 275 | - if md5_stream != md5_expected { | |
| 276 | - bad.push(format!("md5 {md5_stream} != input {md5_expected}")); | |
| 277 | - } | |
| 278 | - | |
| 279 | - // (b) cross-checked by ffprobe on the file itself. | |
| 280 | - let (p_rate, p_ch, p_bits) = ffprobe_stream(&flac_path); | |
| 281 | - if (p_rate, p_ch as usize, p_bits) != (c.rate, c.channels, c.bits) { | |
| 282 | - bad.push(format!( | |
| 283 | - "ffprobe rate/ch/bits {p_rate}/{p_ch}/{p_bits} != {}/{}/{}", | |
| 284 | - c.rate, c.channels, c.bits | |
| 285 | - )); | |
| 286 | - } | |
| 287 | - | |
| 288 | - // (a) ffmpeg decodes our stream back to the input, byte for byte. | |
| 289 | - ffmpeg(&[ | |
| 290 | - "-i", | |
| 291 | - flac_path.to_str().unwrap(), | |
| 292 | - "-f", | |
| 293 | - fmt_for(c.bits), | |
| 294 | - back_path.to_str().unwrap(), | |
| 295 | - ]); | |
| 296 | - let back = fs::read(&back_path).expect("read decoded pcm"); | |
| 297 | - if back != pcm { | |
| 298 | - let first = back.iter().zip(&pcm).position(|(a, b)| a != b); | |
| 299 | - bad.push(format!( | |
| 300 | - "not bit-exact: lengths {} vs {}, first diff at byte {first:?}", | |
| 301 | - back.len(), | |
| 302 | - pcm.len() | |
| 303 | - )); | |
| 304 | - } | |
| 305 | - | |
| 306 | - // (c) size against ffmpeg's FLAC encoder at the matching level. | |
| 307 | - let ref_size = ffmpeg_reference_size(&raw, c, ff_level, &ref_path); | |
| 308 | - let ratio = our_size as f64 / ref_size as f64; | |
| 309 | - if ratio > MARGIN { | |
| 310 | - bad.push(format!("size ratio {ratio:.4} > {MARGIN}")); | |
| 311 | - } | |
| 312 | - | |
| 313 | - let verdict = if bad.is_empty() { "PASS" } else { "FAIL" }; | |
| 314 | - println!( | |
| 315 | - "| {} | {} | {} | {} | {} | {:.4} | {} |", | |
| 316 | - c.name, label, our_size, ff_level, ref_size, ratio, verdict | |
| 317 | - ); | |
| 318 | - for b in bad { | |
| 319 | - failures.push(format!("{} / {label}: {b}", c.name)); | |
| 320 | - } | |
| 321 | - } | |
| 322 | - } | |
| 323 | - | |
| 324 | - let _ = fs::remove_dir_all(&dir); | |
| 325 | - assert!( | |
| 326 | - failures.is_empty(), | |
| 327 | - "parity failures:\n{}", | |
| 328 | - failures.join("\n") | |
| 329 | - ); | |
| 330 | -} |
crates/ec-vorbis/src/decode.rsmodified+0 -43
| @@ -50,14 +50,6 @@ pub struct VorbisDecoder { | ||
| 50 | 50 | drained: bool, |
| 51 | 51 | /// Holds decoded samples until the page granules say which are the stream's. |
| 52 | 52 | trim: GranuleTrim, |
| 53 | - /// Per-block captured decoded residue: (half, per-channel integer residue). | |
| 54 | - /// Populated only when `enable_residue_capture` is set. | |
| 55 | - residue_capture: Vec<(usize, Vec<Vec<i32>>)>, | |
| 56 | - /// Per-block bit split captured alongside: (floor bits, residue bits, packet bits). | |
| 57 | - bit_split: Vec<(u64, u64, u64)>, | |
| 58 | - /// When true, `decode_audio` copies each block's residue (after inverse | |
| 59 | - /// coupling, before floor multiply) into `residue_capture`. | |
| 60 | - enable_residue_capture: bool, | |
| 61 | 53 | } |
| 62 | 54 | |
| 63 | 55 | impl VorbisDecoder { |
| @@ -97,9 +89,6 @@ impl VorbisDecoder { | ||
| 97 | 89 | frames: VecDeque::new(), |
| 98 | 90 | drained: false, |
| 99 | 91 | trim: GranuleTrim::new(channels), |
| 100 | - residue_capture: Vec::new(), | |
| 101 | - bit_split: Vec::new(), | |
| 102 | - enable_residue_capture: false, | |
| 103 | 92 | ident, |
| 104 | 93 | comments, |
| 105 | 94 | setup, |
| @@ -185,8 +174,6 @@ impl VorbisDecoder { | ||
| 185 | 174 | } |
| 186 | 175 | |
| 187 | 176 | let mapping = &self.setup.mappings[mode.mapping]; |
| 188 | - let packet_bits = data.len() as u64 * 8; | |
| 189 | - let before_floors = bits.remaining(); | |
| 190 | 177 | let mut floors = Vec::with_capacity(channels); |
| 191 | 178 | let mut no_residue = Vec::with_capacity(channels); |
| 192 | 179 | for &submap in mapping.mux.iter().take(channels) { |
| @@ -201,7 +188,6 @@ impl VorbisDecoder { | ||
| 201 | 188 | no_residue.push(state.is_unused()); |
| 202 | 189 | floors.push(state); |
| 203 | 190 | } |
| 204 | - let after_floors = bits.remaining(); | |
| 205 | 191 | // A coupled pair shares its residue, so one live channel keeps both. |
| 206 | 192 | for &(magnitude, angle) in &mapping.coupling { |
| 207 | 193 | if !no_residue[magnitude] || !no_residue[angle] { |
| @@ -266,20 +252,6 @@ impl VorbisDecoder { | ||
| 266 | 252 | spectra[angle] = angles; |
| 267 | 253 | } |
| 268 | 254 | |
| 269 | - if self.enable_residue_capture { | |
| 270 | - let after_residues = bits.remaining(); | |
| 271 | - self.bit_split.push(( | |
| 272 | - before_floors - after_floors, | |
| 273 | - after_floors - after_residues, | |
| 274 | - packet_bits, | |
| 275 | - )); | |
| 276 | - let captured: Vec<Vec<i32>> = spectra | |
| 277 | - .iter() | |
| 278 | - .map(|ch| ch.iter().map(|&v| v.round() as i32).collect()) | |
| 279 | - .collect(); | |
| 280 | - self.residue_capture.push((half, captured)); | |
| 281 | - } | |
| 282 | - | |
| 283 | 255 | // Floor times residue, then out of the frequency domain. |
| 284 | 256 | let window = self.windows.get(mode.block_flag, previous_long, next_long); |
| 285 | 257 | let mdct = match mode.block_flag { |
| @@ -378,21 +350,6 @@ impl VorbisDecoder { | ||
| 378 | 350 | self.trim.reset(); |
| 379 | 351 | } |
| 380 | 352 | |
| 381 | - /// Enable per-block residue capture for offline histogram analysis. | |
| 382 | - pub fn enable_residue_capture(&mut self) { | |
| 383 | - self.enable_residue_capture = true; | |
| 384 | - } | |
| 385 | - | |
| 386 | - /// Take the captured per-block residue: each entry is `(half, per-channel integer residue)`. | |
| 387 | - pub fn take_residue_capture(&mut self) -> Vec<(usize, Vec<Vec<i32>>)> { | |
| 388 | - std::mem::take(&mut self.residue_capture) | |
| 389 | - } | |
| 390 | - | |
| 391 | - /// Take the per-block (floor bits, residue bits, packet bits) captured with the residue. | |
| 392 | - pub fn take_bit_split(&mut self) -> Vec<(u64, u64, u64)> { | |
| 393 | - std::mem::take(&mut self.bit_split) | |
| 394 | - } | |
| 395 | - | |
| 396 | 353 | } |
| 397 | 354 | /// Vorbis channel order (§4.3.9) mapped onto [`ChannelLayout`]'s order. |
| 398 | 355 | /// |
crates/ec-vorbis/src/encode.rsmodified+1 -122
| @@ -246,30 +246,6 @@ struct BlockPlan { | ||
| 246 | 246 | next_long: bool, |
| 247 | 247 | } |
| 248 | 248 | |
| 249 | -/// Per-block rate-loop snapshot, captured when `enable_block_log` is set. | |
| 250 | -/// Used by the sweep to localise dropout seconds to their reservoir state. | |
| 251 | -#[derive(Debug, Clone, Copy)] | |
| 252 | -pub struct BlockLog { | |
| 253 | - /// Centre sample of the block (maps to seconds via `centre / sample_rate`). | |
| 254 | - pub centre: i64, | |
| 255 | - /// Block size in samples (2048 long, 256 short). | |
| 256 | - pub n: usize, | |
| 257 | - /// Whether this is a long (2048) block. | |
| 258 | - pub is_long: bool, | |
| 259 | - /// Whether this block is steady (long, surrounded by long blocks). | |
| 260 | - pub steady: bool, | |
| 261 | - /// Coded size of this block's packet in bits. | |
| 262 | - pub bits: u64, | |
| 263 | - /// Headroom (dB) actually applied to this block's floor fit. | |
| 264 | - pub headroom: f64, | |
| 265 | - /// `self.headroom` after `update_rate` adjusted it. | |
| 266 | - pub rate_headroom: f64, | |
| 267 | - /// `reservoir_debt` after `update_rate`. | |
| 268 | - pub reservoir: f64, | |
| 269 | - /// Bit target this block was judged against. | |
| 270 | - pub target: f64, | |
| 271 | -} | |
| 272 | - | |
| 273 | 249 | /// The block-switch scheduler's state between calls. |
| 274 | 250 | #[derive(Debug, Clone, Copy)] |
| 275 | 251 | enum Sched { |
| @@ -335,16 +311,6 @@ pub struct VorbisEncoder { | ||
| 335 | 311 | reservoir_debt: f64, |
| 336 | 312 | finished: bool, |
| 337 | 313 | packets: std::collections::VecDeque<EncodedPacket>, |
| 338 | - /// Per-block captured quantised residue: (half, per-channel quantised). | |
| 339 | - /// Populated only when `enable_residue_capture` is set. | |
| 340 | - residue_capture: Vec<(usize, Vec<Vec<i32>>)>, | |
| 341 | - /// Per-block rate-loop snapshots; populated only when `enable_block_log`. | |
| 342 | - block_log: Vec<BlockLog>, | |
| 343 | - /// When true, `encode_block` records a [`BlockLog`] entry per block. | |
| 344 | - enable_block_log: bool, | |
| 345 | - /// When true, `encode_block` copies each block's quantised residue into | |
| 346 | - /// `residue_capture` for offline histogram analysis. | |
| 347 | - enable_residue_capture: bool, | |
| 348 | 314 | } |
| 349 | 315 | |
| 350 | 316 | impl VorbisEncoder { |
| @@ -444,10 +410,6 @@ impl VorbisEncoder { | ||
| 444 | 410 | class_book, |
| 445 | 411 | residue_books, |
| 446 | 412 | coupling, |
| 447 | - residue_capture: Vec::new(), | |
| 448 | - enable_residue_capture: false, | |
| 449 | - block_log: Vec::new(), | |
| 450 | - enable_block_log: false, | |
| 451 | 413 | }) |
| 452 | 414 | } |
| 453 | 415 | |
| @@ -466,31 +428,6 @@ impl VorbisEncoder { | ||
| 466 | 428 | &self.params |
| 467 | 429 | } |
| 468 | 430 | |
| 469 | - /// Enable per-block quantised-residue capture for offline histogram analysis. | |
| 470 | - pub fn enable_residue_capture(&mut self) { | |
| 471 | - self.enable_residue_capture = true; | |
| 472 | - } | |
| 473 | - | |
| 474 | - /// Take the captured per-block quantised residue: each entry is `(half, per-channel quantised)`. | |
| 475 | - pub fn take_residue_capture(&mut self) -> Vec<(usize, Vec<Vec<i32>>)> { | |
| 476 | - std::mem::take(&mut self.residue_capture) | |
| 477 | - } | |
| 478 | - | |
| 479 | - /// Enable per-block rate-loop capture for dropout diagnosis. | |
| 480 | - pub fn enable_block_log(&mut self) { | |
| 481 | - self.enable_block_log = true; | |
| 482 | - } | |
| 483 | - | |
| 484 | - /// Take the captured per-block rate-loop snapshots. | |
| 485 | - pub fn take_block_log(&mut self) -> Vec<BlockLog> { | |
| 486 | - std::mem::take(&mut self.block_log) | |
| 487 | - } | |
| 488 | - | |
| 489 | - /// Frequency in Barks for a given Hz — public so tests can bin by band. | |
| 490 | - pub fn bark_hz(hz: f64) -> f64 { | |
| 491 | - bark(hz) | |
| 492 | - } | |
| 493 | - | |
| 494 | 431 | /// Push planar samples, one slice per channel in [`ec_core::ChannelLayout`] order. |
| 495 | 432 | pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> { |
| 496 | 433 | if channels.len() != usize::from(self.config.channels) { |
| @@ -944,38 +881,6 @@ impl VorbisEncoder { | ||
| 944 | 881 | break (floor_values, quantised); |
| 945 | 882 | } |
| 946 | 883 | }; |
| 947 | - if self.enable_residue_capture { | |
| 948 | - // The bitstream stores the coupled magnitude/angle form; the | |
| 949 | - // decoder inverse-couples before floor multiply. Capture in that | |
| 950 | - // same per-channel domain so the histogram matches the decoder- | |
| 951 | - // side reference capture exactly (sanity: decoding our own .ogg | |
| 952 | - // reproduces these vectors). | |
| 953 | - // Main codes the full `half * channels` interleaved region (no | |
| 954 | - // HF truncation), so every bin below `half` is coded and the | |
| 955 | - // capture keeps the whole per-channel vector. | |
| 956 | - let coded = half; | |
| 957 | - let mut per_channel: Vec<Vec<i32>> = quantised | |
| 958 | - .iter() | |
| 959 | - .map(|ch| { | |
| 960 | - let mut v = ch[..coded].to_vec(); | |
| 961 | - v.resize(half, 0); | |
| 962 | - v | |
| 963 | - }) | |
| 964 | - .collect(); | |
| 965 | - for &(magnitude, angle) in &self.coupling { | |
| 966 | - let mut mags = std::mem::take(&mut per_channel[magnitude]); | |
| 967 | - let mut angs = std::mem::take(&mut per_channel[angle]); | |
| 968 | - for (m, a) in mags.iter_mut().zip(angs.iter_mut()) { | |
| 969 | - let (l, r) = decouple(*m, *a); | |
| 970 | - *m = l; | |
| 971 | - *a = r; | |
| 972 | - } | |
| 973 | - per_channel[magnitude] = mags; | |
| 974 | - per_channel[angle] = angs; | |
| 975 | - } | |
| 976 | - self.residue_capture.push((half, per_channel)); | |
| 977 | - } | |
| 978 | - | |
| 979 | 884 | let mut out = BitsOut::new(); |
| 980 | 885 | out.bit(false); |
| 981 | 886 | let mode = if plan.is_long { MODE_LONG } else { MODE_SHORT }; |
| @@ -998,21 +903,7 @@ impl VorbisEncoder { | ||
| 998 | 903 | let bits = out.len(); |
| 999 | 904 | let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre; |
| 1000 | 905 | let steady = plan.is_long && plan.prev_long && plan.next_long; |
| 1001 | - let target = self.update_rate(bits, half, channels, delta, steady); | |
| 1002 | - if self.enable_block_log { | |
| 1003 | - let centre = self.centre + (self.prev_n + n) as i64 / 4; | |
| 1004 | - self.block_log.push(BlockLog { | |
| 1005 | - centre, | |
| 1006 | - n, | |
| 1007 | - is_long: plan.is_long, | |
| 1008 | - steady, | |
| 1009 | - bits, | |
| 1010 | - headroom, | |
| 1011 | - rate_headroom: self.headroom, | |
| 1012 | - reservoir: self.reservoir_debt, | |
| 1013 | - target, | |
| 1014 | - }); | |
| 1015 | - } | |
| 906 | + self.update_rate(bits, half, channels, delta, steady); | |
| 1016 | 907 | out.finish() |
| 1017 | 908 | } |
| 1018 | 909 | |
| @@ -1305,18 +1196,6 @@ fn couple(left: i32, right: i32) -> (i32, i32) { | ||
| 1305 | 1196 | }, |
| 1306 | 1197 | } |
| 1307 | 1198 | } |
| 1308 | -/// Inverse square-polar coupling on integer residue — the exact inverse of | |
| 1309 | -/// [`couple`] and the integer form of the decoder's §9.4.2 step. Used only to | |
| 1310 | -/// bring the residue capture back to per-channel (magnitude/angle undone) so it | |
| 1311 | -/// matches the decoder-side capture domain. | |
| 1312 | -fn decouple(m: i32, a: i32) -> (i32, i32) { | |
| 1313 | - match (m > 0, a > 0) { | |
| 1314 | - (true, true) => (m, m - a), | |
| 1315 | - (true, false) => (m + a, m), | |
| 1316 | - (false, true) => (m, m + a), | |
| 1317 | - (false, false) => (m - a, m), | |
| 1318 | - } | |
| 1319 | -} | |
| 1320 | 1199 | |
| 1321 | 1200 | /// §7.2.2 `render_point`, which both sides of the floor coding need. |
| 1322 | 1201 | fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { |
crates/ec-vorbis/src/lib.rsmodified+1 -1
| @@ -42,5 +42,5 @@ mod trim; | ||
| 42 | 42 | mod window; |
| 43 | 43 | |
| 44 | 44 | pub use decode::{VorbisDecoder, channel_map}; |
| 45 | -pub use encode::{BlockLog, EncoderConfig, VorbisEncoder}; | |
| 45 | +pub use encode::{EncoderConfig, VorbisEncoder}; | |
| 46 | 46 | pub use setup::{Comments, Identification}; |
crates/ec-vorbis/tests/oracle.rsmodified+0 -239
| @@ -530,242 +530,3 @@ fn a_short_input_keeps_its_own_length() { | ||
| 530 | 530 | ); |
| 531 | 531 | } |
| 532 | 532 | } |
| 533 | - | |
| 534 | -/// Noise-plus-tones: a signal with enough going on that the rate loop has | |
| 535 | -/// something to spend bits on, which a pure tone does not. | |
| 536 | -fn busy(channels: usize, rate: u32, samples: usize) -> Vec<Vec<f32>> { | |
| 537 | - let mut state = 0x2545_f491_4f6c_dd1du64; | |
| 538 | - let mut noise = move || { | |
| 539 | - state ^= state << 13; | |
| 540 | - state ^= state >> 7; | |
| 541 | - state ^= state << 17; | |
| 542 | - (state >> 40) as f32 / 8_388_608.0 - 1.0 | |
| 543 | - }; | |
| 544 | - (0..channels) | |
| 545 | - .map(|channel| { | |
| 546 | - (0..samples) | |
| 547 | - .map(|i| { | |
| 548 | - let t = i as f64 / f64::from(rate); | |
| 549 | - let hz = 300.0 * f64::from(channel as u32 + 1); | |
| 550 | - let tone = (2.0 * std::f64::consts::PI * hz * t).sin() as f32; | |
| 551 | - 0.35 * tone + 0.35 * noise() | |
| 552 | - }) | |
| 553 | - .collect() | |
| 554 | - }) | |
| 555 | - .collect() | |
| 556 | -} | |
| 557 | - | |
| 558 | -/// A hard silence-to-full-scale onset must not leak into the long block | |
| 559 | -/// before it: that block should now be coded with a short right window (or | |
| 560 | -/// the onset itself carried by a short block), which windows the leak out | |
| 561 | -/// instead of smearing it across ~46 ms the way an all-long-block encoder | |
| 562 | -/// does. | |
| 563 | -#[test] | |
| 564 | -fn onset_after_silence_has_no_pre_echo() { | |
| 565 | - // Onsets swept by phase (fractions of a second, so they land anywhere | |
| 566 | - // relative to the long hop) and by offset from the long-hop grid itself, | |
| 567 | - // since the short run's placement is decided per hop. Stereo carries | |
| 568 | - // distinct content per channel — a different tone on the right, starting | |
| 569 | - // 11 samples later — so coupling cannot hide a per-channel leak. The gap | |
| 570 | - // is measured over the WHOLE silence up to the onset, so a leak in the | |
| 571 | - // last few hundred samples before it cannot hide behind a guard band, and | |
| 572 | - // the peak is barred too. | |
| 573 | - let amp = 0.7f64; | |
| 574 | - for (rate, layouts) in [ | |
| 575 | - (44_100u32, &[1usize, 2][..]), | |
| 576 | - (48_000, &[1, 2, 6]), | |
| 577 | - (96_000, &[6]), | |
| 578 | - ] { | |
| 579 | - let grid = 16 * 1024usize; | |
| 580 | - let onsets = [0.3333f64, 0.5, 0.7321, 0.9137, 1.0] | |
| 581 | - .into_iter() | |
| 582 | - .map(|s| (s * f64::from(rate)) as usize) | |
| 583 | - .chain([0usize, 37, 512, 1000, 1023].into_iter().map(|o| grid + o)); | |
| 584 | - for onset in onsets { | |
| 585 | - for &channels in layouts { | |
| 586 | - let tone_len = rate as usize; | |
| 587 | - let mut source = vec![vec![0.0f32; onset + tone_len + 11 * channels]; channels]; | |
| 588 | - for (c, plane) in source.iter_mut().enumerate() { | |
| 589 | - let hz = 1_000.0 + 370.0 * c as f64; | |
| 590 | - let start = onset + 11 * c; | |
| 591 | - for i in 0..tone_len { | |
| 592 | - let t = i as f64 / f64::from(rate); | |
| 593 | - plane[start + i] = | |
| 594 | - (amp * (2.0 * std::f64::consts::PI * hz * t).sin()) as f32; | |
| 595 | - } | |
| 596 | - } | |
| 597 | - let name = format!("onset-{rate}-{channels}ch-{onset}.ogg"); | |
| 598 | - let path = encode_to_file(&source, rate, 128_000, &name); | |
| 599 | - | |
| 600 | - // The reference oracle must decode the short-block stream | |
| 601 | - // cleanly: no warnings, let alone errors. | |
| 602 | - let out = ec_testkit::ffmpeg() | |
| 603 | - .args(["-v", "warning", "-i"]) | |
| 604 | - .arg(&path) | |
| 605 | - .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) | |
| 606 | - .output() | |
| 607 | - .expect("ffmpeg runs"); | |
| 608 | - assert!( | |
| 609 | - out.stderr.is_empty(), | |
| 610 | - "{name}: oracle decode warnings: {}", | |
| 611 | - String::from_utf8_lossy(&out.stderr) | |
| 612 | - ); | |
| 613 | - | |
| 614 | - let tone_rms = rms(&source[0][onset..]); | |
| 615 | - let check = |label: &str, planes: &[Vec<f32>]| { | |
| 616 | - for (c, plane) in planes.iter().enumerate() { | |
| 617 | - let gap = &plane[..onset.min(plane.len())]; | |
| 618 | - let gap_rms = rms(gap); | |
| 619 | - let peak = gap.iter().fold(0.0f32, |m, v| m.max(v.abs())); | |
| 620 | - println!("{name}/{label} ch{c}: gap RMS {gap_rms:.6} peak {peak:.4}"); | |
| 621 | - assert!( | |
| 622 | - gap_rms <= 0.002 * tone_rms, | |
| 623 | - "{name}/{label} ch{c}: gap RMS {gap_rms:.6} vs tone RMS {tone_rms:.6}" | |
| 624 | - ); | |
| 625 | - assert!( | |
| 626 | - f64::from(peak) <= 0.01 * amp, | |
| 627 | - "{name}/{label} ch{c}: gap peak {peak:.4}" | |
| 628 | - ); | |
| 629 | - } | |
| 630 | - }; | |
| 631 | - let (ours, _) = our_decode(&path); | |
| 632 | - check("ours", &ours); | |
| 633 | - if let Some((theirs, _)) = ffmpeg_decode(&path) { | |
| 634 | - check("oracle", &theirs); | |
| 635 | - } | |
| 636 | - } | |
| 637 | - } | |
| 638 | - } | |
| 639 | -} | |
| 640 | - | |
| 641 | -#[test] | |
| 642 | -fn the_rate_loop_tracks_the_target_bitrate() { | |
| 643 | - let rate = 48_000u32; | |
| 644 | - let samples = rate as usize * 3; | |
| 645 | - let source = busy(2, rate, samples); | |
| 646 | - let mut measured = Vec::new(); | |
| 647 | - for target in [96_000i32, 128_000, 192_000] { | |
| 648 | - let path = encode_to_file( | |
| 649 | - &source, | |
| 650 | - rate, | |
| 651 | - target, | |
| 652 | - &format!("abr-{}k.ogg", target / 1000), | |
| 653 | - ); | |
| 654 | - let bytes = std::fs::metadata(&path).expect("file").len(); | |
| 655 | - let kbps = bytes as f64 * 8.0 * f64::from(rate) / samples as f64 / 1000.0; | |
| 656 | - println!("target {} kbps -> {kbps:.0} kbps", target / 1000); | |
| 657 | - measured.push(kbps); | |
| 658 | - } | |
| 659 | - // Monotone in the target, and within a quarter of it: the loop moves one | |
| 660 | - // quantiser gain, so it tracks rather than hits. | |
| 661 | - assert!( | |
| 662 | - measured[0] < measured[1] && measured[1] < measured[2], | |
| 663 | - "{measured:?}" | |
| 664 | - ); | |
| 665 | - for (kbps, target) in measured.iter().zip([96.0, 128.0, 192.0]) { | |
| 666 | - assert!( | |
| 667 | - (kbps - target).abs() / target < 0.25, | |
| 668 | - "{kbps:.0} kbps for a {target:.0} kbps target" | |
| 669 | - ); | |
| 670 | - } | |
| 671 | -} | |
| 672 | - | |
| 673 | -/// Quiet and sparse content must reach the target too: with the floor bounded | |
| 674 | -/// by the threshold of hearing, most partitions code as class 0 at any step, | |
| 675 | -/// so the rate loop's extra headroom has to lower that bound to find bits to | |
| 676 | -/// spend. The fixture is a sparse tone at -18 dBFS; the synthetic sources are | |
| 677 | -/// the busy and tonal signals at -40 dBFS, the tones over a -90 dBFS noise | |
| 678 | -/// floor (what any 16-bit source carries; a pure digital tone has nothing | |
| 679 | -/// outside its own bins for any step to find). Noise is incompressible, so the | |
| 680 | -/// quiet noise is held to the full-scale noise's own fidelity rather than a | |
| 681 | -/// fixed bar. | |
| 682 | -/// | |
| 683 | -/// The rate loop's step search bottoms out at the +-127 step range (36 dB | |
| 684 | -/// residue range + 12-point floor): once a quiet source's codable residue is | |
| 685 | -/// exhausted, no finer step can spend more bits without a second (cascade) | |
| 686 | -/// coding pass, which does not exist yet -- that cascade is the upgrade path. | |
| 687 | -/// So the contract is: measured kbps lands within +-25% of target, OR the | |
| 688 | -/// encode undershoots because there is nothing left to spend and the result | |
| 689 | -/// is transparent (corr >= 0.999 against the source). The monotone-in-target | |
| 690 | -/// spend check only applies where the case actually spends against target. | |
| 691 | -#[test] | |
| 692 | -fn quiet_content_reaches_the_target_or_is_transparent() { | |
| 693 | - let rate = 48_000u32; | |
| 694 | - let samples = rate as usize * 3; | |
| 695 | - let fixture = | |
| 696 | - ffmpeg_decode(&fixtures().join("audio/wav16-stereo-48000.wav")).expect("fixture decodes"); | |
| 697 | - assert_eq!(fixture.1, rate); | |
| 698 | - let attenuate = |mut source: Vec<Vec<f32>>| { | |
| 699 | - for channel in source.iter_mut() { | |
| 700 | - for value in channel.iter_mut() { | |
| 701 | - *value *= 0.01; | |
| 702 | - } | |
| 703 | - } | |
| 704 | - source | |
| 705 | - }; | |
| 706 | - let corr_at = |path: &Path, source: &[Vec<f32>]| { | |
| 707 | - let (decoded, _) = our_decode(path); | |
| 708 | - decoded | |
| 709 | - .iter() | |
| 710 | - .zip(source.iter()) | |
| 711 | - .map(|(channel, original)| { | |
| 712 | - let n = channel.len().min(original.len()); | |
| 713 | - correlation(&channel[..n], &original[..n]) | |
| 714 | - }) | |
| 715 | - .fold(1.0f64, f64::min) | |
| 716 | - }; | |
| 717 | - let loud = busy(2, rate, samples); | |
| 718 | - let loud_corr = corr_at( | |
| 719 | - &encode_to_file(&loud, rate, 128_000, "loud-128k.ogg"), | |
| 720 | - &loud, | |
| 721 | - ); | |
| 722 | - let quiet_noise = attenuate(loud); | |
| 723 | - let mut quiet_tones = attenuate(tones(2, rate, samples)); | |
| 724 | - for (channel, noise) in quiet_tones.iter_mut().zip(busy(2, rate, samples)) { | |
| 725 | - for (value, n) in channel.iter_mut().zip(noise) { | |
| 726 | - *value += n * 0.0001; | |
| 727 | - } | |
| 728 | - } | |
| 729 | - let cases = [ | |
| 730 | - ("fixture", &fixture.0, 0.99), | |
| 731 | - ("quiet-tones", &quiet_tones, 0.99), | |
| 732 | - ("quiet-noise", &quiet_noise, loud_corr - 0.02), | |
| 733 | - ]; | |
| 734 | - for (name, source, bar) in cases { | |
| 735 | - let mut measured = Vec::new(); | |
| 736 | - let mut spent = Vec::new(); | |
| 737 | - for target in [96_000i32, 128_000, 192_000] { | |
| 738 | - let path = encode_to_file( | |
| 739 | - source, | |
| 740 | - rate, | |
| 741 | - target, | |
| 742 | - &format!("{name}-{}k.ogg", target / 1000), | |
| 743 | - ); | |
| 744 | - let bytes = std::fs::metadata(&path).expect("file").len(); | |
| 745 | - let kbps = bytes as f64 * 8.0 * f64::from(rate) / source[0].len() as f64 / 1000.0; | |
| 746 | - let corr = corr_at(&path, source); | |
| 747 | - println!( | |
| 748 | - "{name}: target {} kbps -> {kbps:.0} kbps, corr {corr:.4}", | |
| 749 | - target / 1000 | |
| 750 | - ); | |
| 751 | - let target_kbps = f64::from(target) / 1000.0; | |
| 752 | - let within_25pct = (kbps - target_kbps).abs() / target_kbps < 0.25; | |
| 753 | - let transparent_undershoot = kbps < target_kbps && corr >= 0.999; | |
| 754 | - assert!( | |
| 755 | - within_25pct || transparent_undershoot, | |
| 756 | - "{name}: {kbps:.0} kbps for {target_kbps:.0} kbps target, corr {corr:.4}" | |
| 757 | - ); | |
| 758 | - spent.push(within_25pct); | |
| 759 | - measured.push(kbps); | |
| 760 | - if target == 128_000 { | |
| 761 | - assert!(corr >= bar, "{name}: corr {corr:.4} under {bar:.4}"); | |
| 762 | - } | |
| 763 | - } | |
| 764 | - if spent.iter().all(|&s| s) { | |
| 765 | - assert!( | |
| 766 | - measured[0] < measured[1] && measured[1] < measured[2], | |
| 767 | - "{name}: {measured:?}" | |
| 768 | - ); | |
| 769 | - } | |
| 770 | - } | |
| 771 | -} |