edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·8fd360c·Tahinli·2 months ago·2655 commits
| 1 | //! Round-trip the encoder through the decoder it was written to feed, then |
| 2 | //! through a real mp4 mux and (when the oracle is present) ffmpeg/ffprobe. |
| 3 | |
| 4 | use std::fs::File; |
| 5 | use std::io::{BufReader, Cursor}; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::process::Command; |
| 8 | |
| 9 | use ec_alac::{AlacDecoder, AlacEncoder}; |
| 10 | use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo}; |
| 11 | use ec_core::timebase::TimeBase; |
| 12 | use ec_core::Packet; |
| 13 | |
| 14 | fn fixtures() -> PathBuf { |
| 15 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") |
| 16 | } |
| 17 | |
| 18 | /// A small deterministic PRNG so a "random data" test does not depend on an |
| 19 | /// external crate: xorshift32. |
| 20 | struct Rng(u32); |
| 21 | impl Rng { |
| 22 | fn next(&mut self) -> u32 { |
| 23 | self.0 ^= self.0 << 13; |
| 24 | self.0 ^= self.0 >> 17; |
| 25 | self.0 ^= self.0 << 5; |
| 26 | self.0 |
| 27 | } |
| 28 | fn range(&mut self, bit_depth: u8) -> i32 { |
| 29 | let max = 1i64 << (bit_depth - 1); |
| 30 | ((self.next() as i64 % (2 * max)) - max) as i32 |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | /// Encode `samples` (interleaved, `channels` wide) in `frame_length`-sample |
| 35 | /// chunks (the last one short) and decode every packet straight back, |
| 36 | /// asserting bit-exact recovery. |
| 37 | fn round_trip(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32, samples: &[i32]) { |
| 38 | let enc = AlacEncoder::new(sample_rate, channels, bit_depth, frame_length).expect("encoder"); |
| 39 | let mut dec = AlacDecoder::new(*enc.cookie()); |
| 40 | let per_frame = frame_length as usize * channels as usize; |
| 41 | let mut decoded = Vec::with_capacity(samples.len()); |
| 42 | for chunk in samples.chunks(per_frame) { |
| 43 | let packet = enc.encode_frame(chunk); |
| 44 | let out = dec.decode(&packet).expect("decode"); |
| 45 | // decode() shifts into the PCM container; undo that to compare |
| 46 | // against the true-range input encode_frame took. |
| 47 | let shift = enc.cookie().container_shift(); |
| 48 | decoded.extend(out.iter().map(|&s| s >> shift)); |
| 49 | } |
| 50 | assert_eq!(decoded, samples, "{channels}ch {bit_depth}bit round trip"); |
| 51 | } |
| 52 | |
| 53 | /// Encode `samples` frame by frame through a real mp4 mux into a fresh temp |
| 54 | /// file, returned with its directory (delete it when done). |
| 55 | fn mux_to_m4a(enc: &AlacEncoder, channels: usize, sample_rate: u32, samples: &[i32]) -> (PathBuf, PathBuf) { |
| 56 | let mut mp4 = ec_mp4::Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); |
| 57 | let time_base = TimeBase::new(1, i64::from(sample_rate)); |
| 58 | let stream = mp4 |
| 59 | .add_stream(StreamInfo::new(0, time_base, enc.codec_parameters().clone())) |
| 60 | .expect("add_stream"); |
| 61 | let mut pts = 0i64; |
| 62 | for chunk in samples.chunks(4096 * channels) { |
| 63 | let n = chunk.len() / channels; |
| 64 | let data = enc.encode_frame(chunk); |
| 65 | let mut packet = Packet::new(stream, time_base, data).with_pts(pts); |
| 66 | packet.duration = Some(n as i64); |
| 67 | mp4.write_packet(&packet).expect("write_packet"); |
| 68 | pts += n as i64; |
| 69 | } |
| 70 | mp4.finish().expect("finish"); |
| 71 | let bytes = mp4.into_inner().into_inner(); |
| 72 | // Tests run in parallel in one process: a per-call serial keeps them out |
| 73 | // of each other's directories. |
| 74 | static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 75 | let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 76 | let dir = std::env::temp_dir().join(format!("ec-alac-mux-test-{}-{serial}", std::process::id())); |
| 77 | std::fs::create_dir_all(&dir).unwrap(); |
| 78 | let out_path = dir.join("out.m4a"); |
| 79 | std::fs::write(&out_path, &bytes).expect("write m4a"); |
| 80 | (dir, out_path) |
| 81 | } |
| 82 | |
| 83 | /// ffmpeg's decode of `path` in raw format `fmt`, or None when no oracle is |
| 84 | /// installed. |
| 85 | fn ffmpeg_decode(path: &Path, fmt: &str) -> Option<Vec<u8>> { |
| 86 | let decode = Command::new("ffmpeg") |
| 87 | .args(["-nostdin", "-v", "error", "-i"]) |
| 88 | .arg(path) |
| 89 | .args(["-f", fmt, "-"]) |
| 90 | .output() |
| 91 | .ok()?; |
| 92 | assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr)); |
| 93 | Some(decode.stdout) |
| 94 | } |
| 95 | |
| 96 | #[test] |
| 97 | fn twenty_four_bit_uses_byte_shift_when_cheaper() { |
| 98 | // Real 16-bit audio widened to 24 bits with random dither in the low |
| 99 | // byte: exactly the shape a 24-bit master of 16-bit source material has, |
| 100 | // and exactly what bytes_shifted exists for — the high bits alone |
| 101 | // predict well, but folded together with the dither's noise they do not. |
| 102 | let path = fixtures().join("wav16-stereo-48000.wav"); |
| 103 | if !path.exists() { |
| 104 | eprintln!("fixtures/audio absent (gitignored) — skipping"); |
| 105 | return; |
| 106 | } |
| 107 | let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); |
| 108 | let spec = reader.spec(); |
| 109 | let mut rng = Rng(0xdead_beef); |
| 110 | let samples: Vec<i32> = reader |
| 111 | .read_all_i32() |
| 112 | .expect("pcm") |
| 113 | .into_iter() |
| 114 | .map(|s| (s << 8) | (rng.next() & 0xff) as i32) |
| 115 | .collect(); |
| 116 | let channels = spec.channels as u8; |
| 117 | |
| 118 | round_trip(spec.sample_rate, channels, 24, 4096, &samples); |
| 119 | |
| 120 | let per_frame = 4096 * channels as usize; |
| 121 | let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); |
| 122 | let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).len()).sum(); |
| 123 | |
| 124 | let mut without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); |
| 125 | without_shift.set_byte_shift(false); |
| 126 | let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).len()).sum(); |
| 127 | |
| 128 | eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes"); |
| 129 | assert!( |
| 130 | with_bytes < without_bytes, |
| 131 | "bytes_shifted split ({with_bytes}) should beat forcing bytes_shifted=0 ({without_bytes})" |
| 132 | ); |
| 133 | } |
| 134 | |
| 135 | #[test] |
| 136 | fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { |
| 137 | // A smooth tone's first residuals are far bigger than the coder's |
| 138 | // starting mean allows, so they go out as 24-bit raw escapes — the one |
| 139 | // Golomb shape random data (whole-frame escape) and 16-bit-derived 24-bit |
| 140 | // audio (bytes_shifted 1, 16 coded bits) never produce. |
| 141 | let mut rng = Rng(0x0bad_cafe); |
| 142 | let n = 4096 * 2 + 777; |
| 143 | for channels in [1u8, 2] { |
| 144 | let tone: Vec<i32> = (0..n * channels as usize) |
| 145 | .map(|i| (2000.0 * (i as f64 / 64.0).sin()) as i32) |
| 146 | .collect(); |
| 147 | let wide: Vec<i32> = tone.iter().map(|&s| (s << 8) | (rng.next() & 0xff) as i32).collect(); |
| 148 | for samples in [&tone, &wide] { |
| 149 | for allow_shift in [true, false] { |
| 150 | let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); |
| 151 | enc.set_byte_shift(allow_shift); |
| 152 | let mut dec = AlacDecoder::new(*enc.cookie()); |
| 153 | let shift = enc.cookie().container_shift(); |
| 154 | let mut decoded = Vec::new(); |
| 155 | for chunk in samples.chunks(4096 * channels as usize) { |
| 156 | decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift)); |
| 157 | } |
| 158 | assert_eq!(&decoded, samples, "{channels}ch 24-bit tone, shift={allow_shift}"); |
| 159 | |
| 160 | // And the reference decoder agrees with what we wrote. |
| 161 | let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); |
| 162 | let got = ffmpeg_decode(&out_path, "s32le"); |
| 163 | std::fs::remove_dir_all(&dir).ok(); |
| 164 | let Some(got) = got else { continue }; |
| 165 | let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); |
| 166 | assert!(got == want, "{channels}ch 24-bit tone, shift={allow_shift}: reference decode differs"); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | #[test] |
| 173 | fn escape_frames_round_trip_random_data() { |
| 174 | let mut rng = Rng(0x1234_5678); |
| 175 | for &(channels, bit_depth) in &[(1u8, 16u8), (2, 16), (1, 24), (2, 24)] { |
| 176 | // 4096 + a short tail, so the last frame is partial. |
| 177 | let n = 4096 * 2 + 777; |
| 178 | let samples: Vec<i32> = (0..n * channels as usize).map(|_| rng.range(bit_depth)).collect(); |
| 179 | round_trip(48_000, channels, bit_depth, 4096, &samples); |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | #[test] |
| 184 | fn real_audio_round_trips_and_compresses() { |
| 185 | let path = fixtures().join("wav16-stereo-48000.wav"); |
| 186 | if !path.exists() { |
| 187 | eprintln!("fixtures/audio absent (gitignored) — skipping"); |
| 188 | return; |
| 189 | } |
| 190 | let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); |
| 191 | let spec = reader.spec(); |
| 192 | let samples = reader.read_all_i32().expect("pcm"); |
| 193 | round_trip(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096, &samples); |
| 194 | |
| 195 | let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) |
| 196 | .expect("encoder"); |
| 197 | let per_frame = 4096 * spec.channels as usize; |
| 198 | let mut coded_bytes = 0usize; |
| 199 | for chunk in samples.chunks(per_frame) { |
| 200 | coded_bytes += enc.encode_frame(chunk).len(); |
| 201 | } |
| 202 | let raw_bytes = samples.len() * 2; |
| 203 | let ratio = coded_bytes as f64 / raw_bytes as f64; |
| 204 | eprintln!("wav16-stereo-48000: {coded_bytes}/{raw_bytes} bytes, ratio {ratio:.4}"); |
| 205 | assert!(ratio <= 0.75, "compression ratio {ratio:.4} > 0.75"); |
| 206 | } |
| 207 | |
| 208 | #[test] |
| 209 | fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { |
| 210 | let path = fixtures().join("wav16-stereo-48000.wav"); |
| 211 | if !path.exists() { |
| 212 | eprintln!("fixtures/audio absent (gitignored) — skipping"); |
| 213 | return; |
| 214 | } |
| 215 | let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); |
| 216 | let spec = reader.spec(); |
| 217 | let samples = reader.read_all_i32().expect("pcm"); |
| 218 | let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) |
| 219 | .expect("encoder"); |
| 220 | |
| 221 | let (dir, out_path) = mux_to_m4a(&enc, spec.channels as usize, spec.sample_rate, &samples); |
| 222 | |
| 223 | // Sanity without an oracle: our own demuxer/decoder reads it back |
| 224 | // bit-exact against the source PCM. |
| 225 | let mut demuxer = |
| 226 | ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&out_path).expect("open"))).expect("mp4"); |
| 227 | let track = demuxer |
| 228 | .streams() |
| 229 | .iter() |
| 230 | .find(|s| s.params.codec == CodecId::Alac) |
| 231 | .expect("alac track") |
| 232 | .clone(); |
| 233 | let mut dec = AlacDecoder::from_parameters(track.params).expect("cookie"); |
| 234 | let shift = dec.cookie().container_shift(); |
| 235 | let mut decoded = Vec::new(); |
| 236 | loop { |
| 237 | match demuxer.next_packet() { |
| 238 | Ok(p) if p.stream != track.index => continue, |
| 239 | Ok(p) => decoded.extend(dec.decode(&p.data).expect("decode").iter().map(|&s| s >> shift)), |
| 240 | Err(e) if e.is_eof() => break, |
| 241 | Err(e) => panic!("{e}"), |
| 242 | } |
| 243 | } |
| 244 | assert_eq!(decoded, samples, "mux -> demux -> decode round trip"); |
| 245 | |
| 246 | // The oracle: ffprobe reads the track back as alac at the right rate and |
| 247 | // channel count, and ffmpeg's own decode matches the source exactly. |
| 248 | if Command::new("ffprobe").arg("-version").output().is_err() { |
| 249 | eprintln!("ffprobe absent — skipping oracle checks"); |
| 250 | return; |
| 251 | } |
| 252 | let probe = Command::new("ffprobe") |
| 253 | .args([ |
| 254 | "-v", "error", "-select_streams", "a:0", "-show_entries", |
| 255 | "stream=codec_name,sample_rate,channels", |
| 256 | "-of", "default=noprint_wrappers=1", |
| 257 | ]) |
| 258 | .arg(&out_path) |
| 259 | .output() |
| 260 | .expect("ffprobe"); |
| 261 | let info = String::from_utf8_lossy(&probe.stdout); |
| 262 | assert!(info.contains("codec_name=alac"), "{info}"); |
| 263 | assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}"); |
| 264 | assert!(info.contains(&format!("channels={}", spec.channels)), "{info}"); |
| 265 | |
| 266 | let Some(stdout) = ffmpeg_decode(&out_path, "s16le") else { return }; |
| 267 | let want: Vec<i16> = samples.iter().map(|&s| s as i16).collect(); |
| 268 | let got: Vec<i16> = stdout |
| 269 | .chunks_exact(2) |
| 270 | .map(|c| i16::from_le_bytes([c[0], c[1]])) |
| 271 | .collect(); |
| 272 | assert_eq!(got, want, "ffmpeg decode of the muxed file vs source PCM"); |
| 273 | |
| 274 | let _ = std::fs::remove_dir_all(&dir); |
| 275 | } |
| 276 | |
| 277 | |
| 278 | /// Encode through our encoder, decode through ours and (when installed) the |
| 279 | /// reference decoder via a real m4a; both must hand back `samples` exactly. |
| 280 | fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, what: &str) { |
| 281 | let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); |
| 282 | enc.set_byte_shift(allow_shift); |
| 283 | let mut dec = AlacDecoder::new(*enc.cookie()); |
| 284 | let shift = enc.cookie().container_shift(); |
| 285 | let mut decoded = Vec::new(); |
| 286 | for chunk in samples.chunks(4096 * channels as usize) { |
| 287 | decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift)); |
| 288 | } |
| 289 | assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}"); |
| 290 | |
| 291 | let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); |
| 292 | let got = ffmpeg_decode(&out_path, "s32le"); |
| 293 | std::fs::remove_dir_all(&dir).ok(); |
| 294 | let Some(got) = got else { return }; |
| 295 | let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); |
| 296 | assert!(got == want, "{what}: {channels}ch 24-bit, shift={allow_shift}: reference decode differs"); |
| 297 | } |
| 298 | |
| 299 | #[test] |
| 300 | fn mono_24_bit_ramp_round_trips_bit_exactly() { |
| 301 | // A modular ramp whose wrap-around steps are wider than 2^23: the |
| 302 | // residual of that step needs 25 bits, one more than the 24-bit escape |
| 303 | // carries, so the encoder must wrap it the way the decoder does. |
| 304 | for n in [1015usize, 1016, 1024, 2048, 4096] { |
| 305 | let samples: Vec<i32> = (0..n).map(|i| ((i as i64 * 7919) % 8_000_000 - 4_000_000) as i32).collect(); |
| 306 | for allow_shift in [true, false] { |
| 307 | round_trip_both_decoders(1, &samples, allow_shift, &format!("ramp n={n}")); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | #[test] |
| 313 | fn mono_24_bit_full_scale_alternating_round_trips() { |
| 314 | for n in [512usize, 4096] { |
| 315 | let samples: Vec<i32> = (0..n).map(|i| if i % 2 == 0 { 8_388_607 } else { -8_388_607 }).collect(); |
| 316 | round_trip_both_decoders(1, &samples, true, &format!("alternating n={n}")); |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | #[test] |
| 321 | fn fuzz_round_trips_bit_exactly() { |
| 322 | let mut rng = Rng(0x5eed_f00d); |
| 323 | for case in 0..200 { |
| 324 | let bit_depth = [16u8, 24][rng.next() as usize % 2]; |
| 325 | let channels = [1u8, 2][rng.next() as usize % 2]; |
| 326 | let n = 1 + rng.next() as usize % 4097; |
| 327 | let content = rng.next() % 4; |
| 328 | let full = (1i64 << (bit_depth - 1)) - 1; |
| 329 | let samples: Vec<i32> = (0..n * channels as usize) |
| 330 | .map(|i| match content { |
| 331 | 0 => rng.range(bit_depth), |
| 332 | 1 => ((i as i64 * 7919) % (2 * full) - full) as i32, |
| 333 | 2 => if i % 2 == 0 { full as i32 } else { -full as i32 }, |
| 334 | _ => (full as f64 * 0.9 * (i as f64 / 37.0).sin()) as i32, |
| 335 | }) |
| 336 | .collect(); |
| 337 | round_trip(48_000, channels, bit_depth, 4096, &samples); |
| 338 | eprintln!("case {case}: {bit_depth}bit {channels}ch n={n} content={content} ok"); |
| 339 | } |
| 340 | } |