forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ps_mp4.rs109 lines, 3.9 KiBHistoryRawDownload
1//! HE-AACv2 (Parametric Stereo) through the mp4 container path.
2//!
3//! The PS fixture is remuxed to mp4 with ffmpeg (stream copy), then its access
4//! units are read back through `ec_mp4::Mp4Demuxer` and decoded with the
5//! AudioSpecificConfig the `esds` box carries, as `AacDecoder::with_config_bytes`
6//! does for any container. Nothing on this path may refuse PS: the decode must
7//! produce two channels at the extension rate, matching FFmpeg's own decode of
8//! the same mp4.
9
10use crate::shared::have_ffmpeg;
11use crate::common::fixture;
12use std::fs::File;
13use std::io::BufReader;
14use std::path::{Path, PathBuf};
15use std::process::Command;
16
17use ec_aac::AacDecoder;
18use ec_core::{CodecId, Demuxer, Packet};
19use ec_mp4::Mp4Demuxer;
20
21const FIXTURE: &str = "ps_48000_music.aac";
22const RATE: u32 = 48_000;
23
24/// FFmpeg's decode of `path` as interleaved f32, two channels at `RATE`.
25fn ffmpeg_stereo(path: &Path) -> Vec<f32> {
26 let out = Command::new("ffmpeg")
27 .args(["-v", "error", "-i"])
28 .arg(path)
29 .args(["-f", "f32le", "-ac", "2", "-ar", "48000", "-"])
30 .output()
31 .expect("ffmpeg runs");
32 assert!(out.status.success(), "ffmpeg decode failed");
33 out.stdout
34 .chunks(4)
35 .map(|b| f32::from_le_bytes(b.try_into().expect("whole f32 samples")))
36 .collect()
37}
38
39fn correlation(a: &[f32], b: &[f32]) -> f64 {
40 let n = a.len().min(b.len());
41 let (mut num, mut da, mut db) = (0f64, 0f64, 0f64);
42 for i in 0..n {
43 let (x, y) = (f64::from(a[i]), f64::from(b[i]));
44 num += x * y;
45 da += x * x;
46 db += y * y;
47 }
48 num / (da.sqrt() * db.sqrt()).max(1e-30)
49}
50
51#[test]
52fn ps_in_mp4_decodes_to_stereo_like_ffmpeg() {
53 if !have_ffmpeg() {
54 eprintln!("SKIP: ffmpeg not installed");
55 return;
56 }
57 let src = fixture(FIXTURE);
58 assert!(src.exists(), "fixture {} is absent", src.display());
59 let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"));
60 std::fs::create_dir_all(&dir).expect("temp dir");
61 let mp4 = dir.join("ps_48000_music.m4a");
62 let status = Command::new("ffmpeg")
63 .args(["-v", "error", "-y", "-i"])
64 .arg(&src)
65 .args(["-c", "copy", "-f", "mp4"])
66 .arg(&mp4)
67 .status()
68 .expect("ffmpeg runs");
69 assert!(status.success(), "ffmpeg could not remux the PS fixture to mp4");
70
71 let mut demux = Mp4Demuxer::new(BufReader::new(File::open(&mp4).expect("mp4 opens")))
72 .expect("mp4 parses");
73 let (idx, asc) = {
74 let aac = demux
75 .streams()
76 .iter()
77 .find(|s| s.params.codec == CodecId::Aac)
78 .expect("mp4 has an AAC track");
79 let asc = aac.params.extradata.as_ref().expect("esds carries the ASC").to_vec();
80 (aac.index, asc)
81 };
82 let mut decoder = AacDecoder::with_config_bytes(&asc).expect("ASC parses");
83 // The config is implicit HE-AACv2 (an LC config at the core rate), so the rate
84 // is only known once the first frame has revealed the SBR/PS extension.
85
86 let mut ours: Vec<f32> = Vec::new();
87 let mut channels = 0u16;
88 let mut rate = 0u32;
89 while let Ok(Packet { stream, data, .. }) = demux.next_packet() {
90 if stream != idx {
91 continue;
92 }
93 let frame = decoder
94 .decode(&data, None)
95 .unwrap_or_else(|e| panic!("access unit failed to decode: {e:?}"));
96 channels = frame.channels;
97 rate = frame.sample_rate;
98 ours.extend_from_slice(&frame.samples);
99 }
100 assert_eq!(channels, 2, "PS must decode to two channels");
101 assert_eq!(rate, RATE, "PS must decode at the extension rate");
102
103 let theirs = ffmpeg_stereo(&mp4);
104 let n = ours.len().min(theirs.len());
105 assert!(n > RATE as usize, "too few samples decoded: {n}");
106 let corr = correlation(&ours[..n], &theirs[..n]);
107 println!("ps mp4: ours {} samples, ffmpeg {} samples, corr {corr:.6}", ours.len(), theirs.len());
108 assert!(corr >= 0.999, "PS in mp4 correlates {corr:.6} with ffmpeg, below 0.999");
109}