edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·381.4 MiB·cdccbc2·Tahinli·10 hours ago·4263 commits
| 1 | //! Round-trip the encoder through the decoder it was written to feed, then |
| 2 | |
| 3 | use std::fs::File; |
| 4 | use std::io::{BufReader, Cursor}; |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | |
| 7 | use ec_alac::{AlacDecoder, AlacEncoder}; |
| 8 | use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo}; |
| 9 | use ec_core::timebase::TimeBase; |
| 10 | use ec_core::Packet; |
| 11 | |
| 12 | /// A small deterministic PRNG so a "random data" test does not depend on an |
| 13 | /// external crate: xorshift32. |
| 14 | struct Rng(u32); |
| 15 | impl Rng { |
| 16 | fn next(&mut self) -> u32 { |
| 17 | self.0 ^= self.0 << 13; |
| 18 | self.0 ^= self.0 >> 17; |
| 19 | self.0 ^= self.0 << 5; |
| 20 | self.0 |
| 21 | } |
| 22 | fn range(&mut self, bit_depth: u8) -> i32 { |
| 23 | let max = 1i64 << (bit_depth - 1); |
| 24 | ((self.next() as i64 % (2 * max)) - max) as i32 |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | /// Encode `samples` (interleaved, `channels` wide) in `frame_length`-sample |
| 29 | /// chunks (the last one short) and decode every packet straight back, |
| 30 | /// asserting bit-exact recovery. |
| 31 | fn round_trip(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32, samples: &[i32]) { |
| 32 | let enc = AlacEncoder::new(sample_rate, channels, bit_depth, frame_length).expect("encoder"); |
| 33 | let mut dec = AlacDecoder::new(*enc.cookie()); |
| 34 | let per_frame = frame_length as usize * channels as usize; |
| 35 | let mut decoded = Vec::with_capacity(samples.len()); |
| 36 | for chunk in samples.chunks(per_frame) { |
| 37 | let packet = enc.encode_frame(chunk).expect("frame"); |
| 38 | let out = dec.decode(&packet).expect("decode"); |
| 39 | // decode() shifts into the PCM container; undo that to compare |
| 40 | // against the true-range input encode_frame took. |
| 41 | let shift = enc.cookie().container_shift(); |
| 42 | decoded.extend(out.iter().map(|&s| s >> shift)); |
| 43 | } |
| 44 | assert_eq!(decoded, samples, "{channels}ch {bit_depth}bit round trip"); |
| 45 | } |
| 46 | |
| 47 | /// Encode `samples` frame by frame through a real mp4 mux into a fresh temp |
| 48 | /// file, returned with its directory (delete it when done). |
| 49 | fn mux_to_m4a(enc: &AlacEncoder, channels: usize, sample_rate: u32, samples: &[i32]) -> (PathBuf, PathBuf) { |
| 50 | let mut mp4 = ec_mp4::Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); |
| 51 | let time_base = TimeBase::new(1, i64::from(sample_rate)); |
| 52 | let stream = mp4 |
| 53 | .add_stream(StreamInfo::new(0, time_base, enc.codec_parameters().clone())) |
| 54 | .expect("add_stream"); |
| 55 | let mut pts = 0i64; |
| 56 | for chunk in samples.chunks(4096 * channels) { |
| 57 | let n = chunk.len() / channels; |
| 58 | let data = enc.encode_frame(chunk).expect("frame"); |
| 59 | let mut packet = Packet::new(stream, time_base, data).with_pts(pts); |
| 60 | packet.duration = Some(n as i64); |
| 61 | mp4.write_packet(&packet).expect("write_packet"); |
| 62 | pts += n as i64; |
| 63 | } |
| 64 | mp4.finish().expect("finish"); |
| 65 | let bytes = mp4.into_inner().into_inner(); |
| 66 | // Tests run in parallel in one process: a per-call serial keeps them out |
| 67 | // of each other's directories. |
| 68 | static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 69 | let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 70 | let dir = std::env::temp_dir().join(format!("ec-alac-mux-test-{}-{serial}", std::process::id())); |
| 71 | std::fs::create_dir_all(&dir).unwrap(); |
| 72 | let out_path = dir.join("out.m4a"); |
| 73 | std::fs::write(&out_path, &bytes).expect("write m4a"); |
| 74 | (dir, out_path) |
| 75 | } |
| 76 | |
| 77 | fn ffmpeg_decode(path: &Path, fmt: &str) -> Vec<u8> { |
| 78 | let decode = ec_testkit::ffmpeg() |
| 79 | .args(["-nostdin", "-v", "error", "-i"]) |
| 80 | .arg(path) |
| 81 | .args(["-f", fmt, "-"]) |
| 82 | .output() |
| 83 | .expect("ffmpeg"); |
| 84 | assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr)); |
| 85 | decode.stdout |
| 86 | } |
| 87 | |
| 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 | #[test] |
| 124 | fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { |
| 125 | // A smooth tone's first residuals are far bigger than the coder's |
| 126 | // starting mean allows, so they go out as 24-bit raw escapes — the one |
| 127 | // Golomb shape random data (whole-frame escape) and 16-bit-derived 24-bit |
| 128 | // audio (bytes_shifted 1, 16 coded bits) never produce. |
| 129 | let mut rng = Rng(0x0bad_cafe); |
| 130 | let n = 4096 * 2 + 777; |
| 131 | for channels in [1u8, 2] { |
| 132 | let tone: Vec<i32> = (0..n * channels as usize) |
| 133 | .map(|i| (2000.0 * (i as f64 / 64.0).sin()) as i32) |
| 134 | .collect(); |
| 135 | let wide: Vec<i32> = tone.iter().map(|&s| (s << 8) | (rng.next() & 0xff) as i32).collect(); |
| 136 | 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"); |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | #[test] |
| 160 | fn escape_frames_round_trip_random_data() { |
| 161 | let mut rng = Rng(0x1234_5678); |
| 162 | for &(channels, bit_depth) in &[(1u8, 16u8), (2, 16), (1, 24), (2, 24)] { |
| 163 | // 4096 + a short tail, so the last frame is partial. |
| 164 | let n = 4096 * 2 + 777; |
| 165 | let samples: Vec<i32> = (0..n * channels as usize).map(|_| rng.range(bit_depth)).collect(); |
| 166 | round_trip(48_000, channels, bit_depth, 4096, &samples); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | #[test] |
| 171 | fn real_audio_round_trips_and_compresses() { |
| 172 | let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); |
| 173 | let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); |
| 174 | let spec = reader.spec(); |
| 175 | let samples = reader.read_all_i32().expect("pcm"); |
| 176 | round_trip(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096, &samples); |
| 177 | |
| 178 | let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) |
| 179 | .expect("encoder"); |
| 180 | let per_frame = 4096 * spec.channels as usize; |
| 181 | let mut coded_bytes = 0usize; |
| 182 | for chunk in samples.chunks(per_frame) { |
| 183 | coded_bytes += enc.encode_frame(chunk).expect("frame").len(); |
| 184 | } |
| 185 | let raw_bytes = samples.len() * 2; |
| 186 | let ratio = coded_bytes as f64 / raw_bytes as f64; |
| 187 | eprintln!("wav16-stereo-48000: {coded_bytes}/{raw_bytes} bytes, ratio {ratio:.4}"); |
| 188 | assert!(ratio <= 0.75, "compression ratio {ratio:.4} > 0.75"); |
| 189 | } |
| 190 | |
| 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); |
| 256 | let mut dec = AlacDecoder::new(*enc.cookie()); |
| 257 | let shift = enc.cookie().container_shift(); |
| 258 | let mut decoded = Vec::new(); |
| 259 | for chunk in samples.chunks(4096 * channels as usize) { |
| 260 | decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift)); |
| 261 | } |
| 262 | assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}"); |
| 263 | |
| 264 | let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); |
| 265 | let got = ffmpeg_decode(&out_path, "s32le"); |
| 266 | std::fs::remove_dir_all(&dir).ok(); |
| 267 | 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"); |
| 269 | } |
| 270 | |
| 271 | #[test] |
| 272 | fn mono_24_bit_ramp_round_trips_bit_exactly() { |
| 273 | // A modular ramp whose wrap-around steps are wider than 2^23: the |
| 274 | // residual of that step needs 25 bits, one more than the 24-bit escape |
| 275 | // carries, so the encoder must wrap it the way the decoder does. |
| 276 | for n in [1015usize, 1016, 1024, 2048, 4096] { |
| 277 | 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 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn mono_24_bit_full_scale_alternating_round_trips() { |
| 286 | for n in [512usize, 4096] { |
| 287 | 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}")); |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn fuzz_round_trips_bit_exactly() { |
| 294 | let mut rng = Rng(0x5eed_f00d); |
| 295 | for case in 0..200 { |
| 296 | let bit_depth = [16u8, 24][rng.next() as usize % 2]; |
| 297 | let channels = [1u8, 2][rng.next() as usize % 2]; |
| 298 | let n = 1 + rng.next() as usize % 4097; |
| 299 | let content = rng.next() % 4; |
| 300 | let full = (1i64 << (bit_depth - 1)) - 1; |
| 301 | let samples: Vec<i32> = (0..n * channels as usize) |
| 302 | .map(|i| match content { |
| 303 | 0 => rng.range(bit_depth), |
| 304 | 1 => ((i as i64 * 7919) % (2 * full) - full) as i32, |
| 305 | 2 => if i % 2 == 0 { full as i32 } else { -full as i32 }, |
| 306 | _ => (full as f64 * 0.9 * (i as f64 / 37.0).sin()) as i32, |
| 307 | }) |
| 308 | .collect(); |
| 309 | round_trip(48_000, channels, bit_depth, 4096, &samples); |
| 310 | eprintln!("case {case}: {bit_depth}bit {channels}ch n={n} content={content} ok"); |
| 311 | } |
| 312 | } |