forge
Explore
Log in

Don't you dare go Hollow

diag(mkv-audio): A/B ec-matroska's AAC and AC-3/E-AC-3 delivery against mp4/ffmpeg -- refuted, not fixed

Browse files at this commit

d6466ca1b5504f529739c98400d0c1438499522dAhmet Kaan GümüşParent: ca94f24
Two mkv-audio-timing tests exercise ec-matroska's own packet stream, decoded
through ec-aac/ec-ac3 exactly as the consumer does, against the sibling mp4
leg of the same OBS recordings and against ffmpeg:

- mkv_vs_mp4_aac_pipeline: 3 real OBS mkv/mp4 pairs. ASC bytes identical,
  packet counts and byte totals identical, mkv pts strictly monotonic with no
  duplicates. Decoded PCM (ours-vs-ours and each vs ffmpeg) correlates at
  1.0000, lag 0, for the two pairs with real signal; the third pair's near-
  silent audio (5180 bytes over 852 packets) reads 0.0 on every leg including
  mp4-vs-ffmpeg, which is a zero-variance correlation floor, not a defect.

- mkv_51_channel_order: the two real-library 5.1 mkv rows the consumer sweep
  flagged (ReelF, E-AC-3; ReelG, AC-3). Our channel 0 matches
  ffmpeg's channel 0 at lag 0, corr 0.9999 and 0.9955 -- no channel-order
  mismatch.

Root cause: neither of the charter's two ec-matroska-side hypotheses (lace/
pts damage to AAC packet delivery, 5.1 channel order) holds against real
files -- this crate's demux and the shared ec-aac/ec-ac3 decode of it are
byte- and sample-correct here. No code fix lands in ec-matroska because there
is nothing wrong to fix in it for these files. The 0.06-0.34 mkv-leg
correlation the consumer sweep saw, if still real, has to come from
edith_replica's own consumption of these same packets (SymTrack's pts ->
samples_at conversion, priming, or channel folding in
crates/engine/src/audio.rs) rather than from container demux or codec decode
-- reported, not fixed, since that file is out of this repo.
Cargo.lockmodified+3 -0
@@ -347,8 +347,11 @@ dependencies = [
347 name = "ec-matroska"347 name = "ec-matroska"
348 version = "0.1.0"348 version = "0.1.0"
349 dependencies = [349 dependencies = [
350+ "ec-aac",
351+ "ec-ac3",
350 "ec-core",352 "ec-core",
351 "ec-inflate",353 "ec-inflate",
354+ "ec-mp4",
352 ]355 ]
353 356
354 [[package]]357 [[package]]
crates/ec-matroska/Cargo.tomlmodified+5 -0
@@ -9,3 +9,8 @@ authors.workspace = true
9 [dependencies]9 [dependencies]
10 ec-core.workspace = true10 ec-core.workspace = true
11 ec-inflate.workspace = true11 ec-inflate.workspace = true
12+
13+[dev-dependencies]
14+ec-mp4.workspace = true
15+ec-aac.workspace = true
16+ec-ac3.workspace = true
crates/ec-matroska/tests/matroska.rsmodified+314 -0
@@ -975,3 +975,317 @@ fn real_hdr_film_container_states_no_light_metadata() {
975 }975 }
976 assert!(checked, "no video stream found");976 assert!(checked, "no video stream found");
977 }977 }
978+
979+// ===== mkv-vs-mp4 audio A/B (mkv-audio-timing) =====
980+//
981+// The consumer sweep found: same OBS recording's `.mkv` leg scores far below
982+// its sibling `.mp4` leg on channel-0 correlation from t=0, and 5.1 AC-3/E-AC-3
983+// tracks that are only ever carried in Matroska score near zero. These tests
984+// isolate whether that is packet delivery out of `ec-matroska` (order,
985+// duplication, pts) or the shared decoder crate, and which physical channel
986+// our 5.1 decode calls "channel 0".
987+
988+use ec_ac3::Ac3Decoder;
989+use ec_aac::AacDecoder;
990+use ec_core::CodecId;
991+
992+/// Opens whichever container `path` actually is — both crates implement the
993+/// same `Demuxer` trait, so the rest of the harness never has to know which.
994+fn open_any(path: &Path) -> Box<dyn Demuxer> {
995+ use std::io::Read;
996+ let mut head = [0u8; 12];
997+ File::open(path)
998+ .expect("open")
999+ .read_exact(&mut head)
1000+ .expect("read head");
1001+ if ec_mp4::is_mp4(&head) {
1002+ Box::new(ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4 opens"))
1003+ } else {
1004+ Box::new(MatroskaDemuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mkv opens"))
1005+ }
1006+}
1007+
1008+/// The first stream of `codec`'s extradata plus its packets, `(pts, data)`,
1009+/// in the order the container's own demuxer hands them back — capped so a
1010+/// multi-gigabyte recording does not have to be decoded whole.
1011+fn audio_track(path: &Path, codec: CodecId) -> Option<(Option<Vec<u8>>, u32, Vec<(i64, Vec<u8>)>)> {
1012+ let mut d = open_any(path);
1013+ let s = d.streams().iter().find(|s| s.params.codec == codec)?;
1014+ let idx = s.index;
1015+ let extradata = s.params.extradata.as_ref().map(|b| b.to_vec());
1016+ let rate = s.params.audio()?.sample_rate;
1017+ let mut pkts = Vec::new();
1018+ loop {
1019+ match d.next_packet() {
1020+ Ok(p) if p.stream == idx => {
1021+ pkts.push((p.pts.unwrap_or(0), p.data.to_vec()));
1022+ if pkts.len() >= 2_000 {
1023+ break;
1024+ }
1025+ }
1026+ Ok(_) => continue,
1027+ Err(_) => break,
1028+ }
1029+ }
1030+ Some((extradata, rate, pkts))
1031+}
1032+
1033+/// Our AAC decode of a container's access units, interleaved-to-planar.
1034+fn decode_aac(extradata: &[u8], pkts: &[(i64, Vec<u8>)]) -> Vec<Vec<f32>> {
1035+ let mut decoder = AacDecoder::with_config_bytes(extradata).expect("AudioSpecificConfig parses");
1036+ let mut planes: Vec<Vec<f32>> = Vec::new();
1037+ for (_, au) in pkts {
1038+ let Ok(frame) = decoder.decode(au, None) else {
1039+ continue;
1040+ };
1041+ let ch = usize::from(frame.channels);
1042+ if ch == 0 {
1043+ continue;
1044+ }
1045+ if planes.is_empty() {
1046+ planes = vec![Vec::new(); ch];
1047+ }
1048+ for (i, v) in frame.samples.iter().enumerate() {
1049+ planes[i % ch].push(*v);
1050+ }
1051+ }
1052+ planes
1053+}
1054+
1055+/// Our AC-3/E-AC-3 decode of a container's frames, interleaved-to-planar.
1056+fn decode_ac3(pkts: &[(i64, Vec<u8>)]) -> Vec<Vec<f32>> {
1057+ let mut decoder = Ac3Decoder::new();
1058+ let mut planes: Vec<Vec<f32>> = Vec::new();
1059+ for (_, data) in pkts {
1060+ let Ok(frame) = decoder.decode_frame(data) else {
1061+ continue;
1062+ };
1063+ let ch = frame.channels();
1064+ if ch == 0 {
1065+ continue;
1066+ }
1067+ if planes.is_empty() {
1068+ planes = vec![Vec::new(); ch];
1069+ }
1070+ let samples: Vec<f32> = frame.data[0]
1071+ .chunks_exact(4)
1072+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1073+ .collect();
1074+ for (i, v) in samples.iter().enumerate() {
1075+ planes[i % ch].push(*v);
1076+ }
1077+ }
1078+ planes
1079+}
1080+
1081+fn have_ffmpeg() -> bool {
1082+ Command::new("ffmpeg")
1083+ .arg("-version")
1084+ .output()
1085+ .is_ok_and(|o| o.status.success())
1086+}
1087+
1088+/// ffmpeg's decode of a file's first audio stream, planar by channel.
1089+fn ffmpeg_decode_planar(path: &Path, channels: usize) -> Vec<Vec<f32>> {
1090+ let out = Command::new("ffmpeg")
1091+ .args(["-v", "error", "-i"])
1092+ .arg(path)
1093+ .args([
1094+ "-map", "0:a:0", "-t", "20", "-f", "f32le", "-acodec", "pcm_f32le", "-",
1095+ ])
1096+ .output()
1097+ .expect("ffmpeg runs");
1098+ assert!(
1099+ out.status.success(),
1100+ "ffmpeg decode failed: {}",
1101+ String::from_utf8_lossy(&out.stderr)
1102+ );
1103+ let samples: Vec<f32> = out
1104+ .stdout
1105+ .chunks_exact(4)
1106+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
1107+ .collect();
1108+ let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
1109+ for (i, v) in samples.iter().enumerate() {
1110+ planes[i % channels].push(*v);
1111+ }
1112+ planes
1113+}
1114+
1115+fn correlation(a: &[f32], b: &[f32]) -> f64 {
1116+ let n = a.len().min(b.len());
1117+ if n < 1024 {
1118+ return 0.0;
1119+ }
1120+ let (a, b) = (&a[..n], &b[..n]);
1121+ let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1122+ let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1123+ let (mut num, mut da, mut db) = (0.0f64, 0.0f64, 0.0f64);
1124+ for i in 0..n {
1125+ let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
1126+ num += x * y;
1127+ da += x * x;
1128+ db += y * y;
1129+ }
1130+ let den = (da * db).sqrt();
1131+ if den == 0.0 { 0.0 } else { num / den }
1132+}
1133+
1134+/// Best correlation over a bounded lag search from the start of both
1135+/// streams — the whole point here is t=0 alignment, so no whole-file window
1136+/// slide is needed, just enough lag to absorb container/codec delay.
1137+const LAG_MAX: i64 = 4_000;
1138+const WINDOW: usize = 100_000;
1139+
1140+fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
1141+ let mut best_abs = -1.0f64;
1142+ let mut best = (0i64, 0.0f64);
1143+ for lag in -LAG_MAX..=LAG_MAX {
1144+ let (oa, ob) = if lag >= 0 { (0usize, lag as usize) } else { ((-lag) as usize, 0usize) };
1145+ let len = WINDOW.min(ours.len().saturating_sub(oa)).min(theirs.len().saturating_sub(ob));
1146+ if len < 1024 {
1147+ continue;
1148+ }
1149+ let c = correlation(&ours[oa..oa + len], &theirs[ob..ob + len]);
1150+ if c.abs() > best_abs {
1151+ best_abs = c.abs();
1152+ best = (lag, c);
1153+ }
1154+ }
1155+ best
1156+}
1157+
1158+/// mkv vs mp4: the same recording's AAC stream, decoded through each
1159+/// container's own demux path, ours-vs-ours and each vs ffmpeg. Isolates the
1160+/// consumer sweep's "same channel 0, same track, `.mkv` corr 0.06-0.34 but
1161+/// sibling `.mp4` 0.76-0.92" finding to this crate's packet delivery or to
1162+/// the shared AAC decoder.
1163+///
1164+/// Run with `cargo test -p ec-matroska --test matroska mkv_vs_mp4_aac_pipeline -- --ignored --nocapture`.
1165+#[test]
1166+#[ignore = "reads the real library, mkv-audio-timing A/B"]
1167+fn mkv_vs_mp4_aac_pipeline() {
1168+ if !have_ffmpeg() {
1169+ eprintln!("skipped: no ffmpeg");
1170+ return;
1171+ }
1172+ let obs = Path::new("/home/user/Videos/OBS");
1173+ let stems = [
1174+ "2026-07-25 02-09-04",
1175+ "2026-08-17 01-57-17",
1176+ "2026-08-17 11-01-56",
1177+ ];
1178+ let mut any = false;
1179+ for stem in stems {
1180+ let mkv = obs.join(format!("{stem}.mkv"));
1181+ let mp4 = obs.join(format!("{stem}.mp4"));
1182+ if !mkv.exists() || !mp4.exists() {
1183+ continue;
1184+ }
1185+ any = true;
1186+ println!("=== {stem} ===");
1187+ let (mkv_asc, mkv_rate, mkv_pkts) = audio_track(&mkv, CodecId::Aac).expect("mkv aac track");
1188+ let (mp4_asc, mp4_rate, mp4_pkts) = audio_track(&mp4, CodecId::Aac).expect("mp4 aac track");
1189+ println!(
1190+ "mkv asc={:02x?} rate={mkv_rate} packets={} bytes={}",
1191+ mkv_asc,
1192+ mkv_pkts.len(),
1193+ mkv_pkts.iter().map(|(_, d)| d.len()).sum::<usize>()
1194+ );
1195+ println!(
1196+ "mp4 asc={:02x?} rate={mp4_rate} packets={} bytes={}",
1197+ mp4_asc,
1198+ mp4_pkts.len(),
1199+ mp4_pkts.iter().map(|(_, d)| d.len()).sum::<usize>()
1200+ );
1201+ println!(
1202+ "mkv first5 pts = {:?}",
1203+ mkv_pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1204+ );
1205+ println!(
1206+ "mp4 first5 pts = {:?}",
1207+ mp4_pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1208+ );
1209+ let (mut out_of_order, mut dup) = (0, 0);
1210+ for w in mkv_pkts.windows(2) {
1211+ if w[1].0 < w[0].0 {
1212+ out_of_order += 1;
1213+ }
1214+ if w[1].0 == w[0].0 {
1215+ dup += 1;
1216+ }
1217+ }
1218+ println!("mkv out_of_order={out_of_order} dup_pts={dup}");
1219+
1220+ let mkv_planes = decode_aac(mkv_asc.as_deref().unwrap_or(&[]), &mkv_pkts);
1221+ let mp4_planes = decode_aac(mp4_asc.as_deref().unwrap_or(&[]), &mp4_pkts);
1222+ assert!(
1223+ !mkv_planes.is_empty() && !mp4_planes.is_empty(),
1224+ "{stem}: decode produced no channels (mkv {} ch, mp4 {} ch)",
1225+ mkv_planes.len(),
1226+ mp4_planes.len()
1227+ );
1228+
1229+ let (lag, c_mm) = best_lag_correlation(&mkv_planes[0], &mp4_planes[0]);
1230+ let mkv_ff = ffmpeg_decode_planar(&mkv, mkv_planes.len());
1231+ let mp4_ff = ffmpeg_decode_planar(&mp4, mp4_planes.len());
1232+ let (_, c_mkv_ff) = best_lag_correlation(&mkv_planes[0], &mkv_ff[0]);
1233+ let (_, c_mp4_ff) = best_lag_correlation(&mp4_planes[0], &mp4_ff[0]);
1234+ println!(
1235+ "{stem}: mkv-vs-mp4(ours) corr={c_mm:.4} lag={lag}; mkv-vs-ffmpeg corr={c_mkv_ff:.4}; mp4-vs-ffmpeg corr={c_mp4_ff:.4}"
1236+ );
1237+ }
1238+ assert!(any, "no OBS mkv/mp4 pairs present");
1239+}
1240+
1241+/// The two mkv-only 5.1 real-library rows the consumer sweep flagged
1242+/// (E-AC-3 and AC-3): our decode of every channel against ffmpeg's channel
1243+/// 0, so a channel-order mismatch (mkv hands a different physical channel
1244+/// first than ffmpeg calls "channel 0") shows up as a non-zero-index best
1245+/// match instead of a flat near-zero across all of them.
1246+///
1247+/// Run with `cargo test -p ec-matroska --test matroska mkv_51_channel_order -- --ignored --nocapture`.
1248+#[test]
1249+#[ignore = "reads the real library, mkv-audio-timing A/B"]
1250+fn mkv_51_channel_order() {
1251+ if !have_ffmpeg() {
1252+ eprintln!("skipped: no ffmpeg");
1253+ return;
1254+ }
1255+ let files: [(&str, CodecId); 2] = [
1256+ (
1257+ "/home/user/Downloads/reelf/reelf.mkv",
1258+ CodecId::EAc3,
1259+ ),
1260+ (
1261+ "/home/user/Downloads/reelg/reelg.mkv",
1262+ CodecId::Ac3,
1263+ ),
1264+ ];
1265+ let mut any = false;
1266+ for (path, codec) in files {
1267+ let path = Path::new(path);
1268+ if !path.exists() {
1269+ eprintln!("skipped: {} absent", path.display());
1270+ continue;
1271+ }
1272+ any = true;
1273+ let (_, _rate, pkts) = audio_track(path, codec).expect("audio track");
1274+ println!(
1275+ "{}: first5 pts = {:?}",
1276+ path.file_name().unwrap().to_string_lossy(),
1277+ pkts.iter().take(5).map(|(p, _)| *p).collect::<Vec<_>>()
1278+ );
1279+ let planes = decode_ac3(&pkts);
1280+ assert!(!planes.is_empty(), "{}: no channels decoded", path.display());
1281+ let ffref = ffmpeg_decode_planar(path, planes.len());
1282+ for (i, ch) in planes.iter().enumerate() {
1283+ let (lag, c) = best_lag_correlation(ch, &ffref[0]);
1284+ println!(
1285+ "{}: our ch{i} vs ffmpeg ch0 corr={c:.4} lag={lag}",
1286+ path.file_name().unwrap().to_string_lossy()
1287+ );
1288+ }
1289+ }
1290+ assert!(any, "no 5.1 mkv fixtures present");
1291+}