forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

edith_surface.rs105 lines, 4.6 KiBHistoryRawDownload
1//! The AC-3 path exactly as the replica drives it: read the rate and the
2//! layout out of the first syncframe's headers, ask the registry for a decoder
3//! folded to that layout, decode, and read the frame back as S16 little-endian
4//! (`engine/src/audio.rs:1954-2170`).
5//!
6//! Missing fixtures skip rather than fail, as the `ec-ac3` matrix does;
7//! `scripts/gen-fixtures.sh` writes them.
8
9use std::path::{Path, PathBuf};
10
11use oxideav_ac3::{bsi, eac3, register_codecs, syncinfo};
12use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Error, Frame, Packet, TimeBase};
13
14fn fixture(name: &str) -> Option<Vec<u8>> {
15 let path: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR"))
16 .join("../../fixtures/audio")
17 .join(name);
18 std::fs::read(path).ok()
19}
20
21/// `engine/src/audio.rs:2130` — a fresh decoder out of a fresh registry.
22fn ac3_decoder(codec: &str, channels: Option<u16>) -> Box<dyn Decoder> {
23 let mut registry = CodecRegistry::new();
24 register_codecs(&mut registry);
25 let mut params = CodecParameters::audio(CodecId::new(codec));
26 params.channels = channels;
27 registry.first_decoder(&params).expect("no AC-3 decoder")
28}
29
30/// `engine/src/audio.rs:2150` — one syncframe in, interleaved `f32` and the
31/// frames per channel out; `None` when the decoder wants more input.
32fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> Option<(Vec<f32>, u64)> {
33 let packet = Packet::new(0, TimeBase::new(1, 48_000), bytes.to_vec());
34 decoder.send_packet(&packet).expect("AC-3 decode failed");
35 match decoder.receive_frame() {
36 Ok(Frame::Audio(audio)) => Some((
37 audio.data[0]
38 .chunks_exact(2)
39 .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0)
40 .collect(),
41 u64::from(audio.samples),
42 )),
43 Ok(other) => panic!("AC-3 decoder handed back {other:?}"),
44 Err(Error::NeedMore) => None,
45 Err(e) => panic!("AC-3 decode failed: {e:?}"),
46 }
47}
48
49/// `engine/src/audio.rs:2061` — rate and `nfchans` out of the bit stream,
50/// whichever syntax it is.
51fn header(codec: &str, frame: &[u8]) -> (u32, usize) {
52 if codec == "eac3" {
53 let bsi = eac3::bsi::parse(frame.get(2..).unwrap_or_default()).expect("E-AC-3 bsi");
54 (bsi.sample_rate, bsi.nfchans)
55 } else {
56 let sync = syncinfo::parse(frame).expect("AC-3 syncinfo");
57 let bsi = bsi::parse(frame.get(5..).unwrap_or_default()).expect("AC-3 bsi");
58 (sync.sample_rate, bsi.nfchans)
59 }
60}
61
62fn rms(pcm: &[f32]) -> f64 {
63 (pcm.iter().map(|&v| f64::from(v) * f64::from(v)).sum::<f64>() / pcm.len().max(1) as f64).sqrt()
64}
65
66/// Every generated layout, opened the way a timeline source is opened: wider
67/// than mono folds to stereo, mono stays mono, and neither decodes to silence
68/// (the replica's mono `corner-cut` exists because the incumbent did).
69#[test]
70fn the_replicas_open_path_lands_on_audible_pcm() {
71 let cases = [
72 ("ac3-5.1-48000.ac3", "ac3", 48_000, 5, 2),
73 ("ac3-stereo-48000.ac3", "ac3", 48_000, 2, 2),
74 ("ac3-mono-44100.ac3", "ac3", 44_100, 1, 1),
75 ("eac3-5.1-48000.eac3", "eac3", 48_000, 5, 2),
76 ("eac3-mono-48000.eac3", "eac3", 48_000, 1, 1),
77 ];
78 let mut ran = 0;
79 for (name, codec, rate, nfchans_want, channels_want) in cases {
80 let Some(data) = fixture(name) else { continue };
81 ran += 1;
82
83 let (sample_rate, nfchans) = header(codec, &data);
84 assert_eq!(sample_rate, rate, "{name}: sample rate");
85 assert_eq!(nfchans, nfchans_want, "{name}: nfchans");
86
87 let requested = (nfchans > 1).then_some(2);
88 let mut decoder = ac3_decoder(codec, requested);
89 let (pcm, samples) = decode_ac3(&mut decoder, &data).expect("the first syncframe decoded");
90 let channels = (pcm.len() as u64 / samples.max(1)) as u16;
91 assert_eq!(channels, channels_want, "{name}: decoded channels");
92 assert!(samples > 0, "{name}: no samples");
93 assert!(rms(&pcm) > 1e-3, "{name}: decoded to silence, rms {}", rms(&pcm));
94
95 // The replica then feeds the rest of the stream frame by frame; a
96 // second frame proves the packet walk does not desync on the shim's
97 // conversion.
98 let size = ec_ac3::frame_size(&data).expect("frame size");
99 if let Some(next) = data.get(size..).filter(|rest| rest.len() > size) {
100 let (pcm, samples) = decode_ac3(&mut decoder, next).expect("the second syncframe");
101 assert_eq!((pcm.len() as u64 / samples.max(1)) as u16, channels_want);
102 }
103 }
104 assert!(ran > 0, "no AC-3 fixtures: run scripts/gen-fixtures.sh");
105}