diag(aac-sbr): 44.1k-family "sample drift" is a narrow-search artifact, not clock drift
Browse files at this commit9f92c74b0608bcd3f6c6f9dad48e73fc8fb615f7Parent: 340601e3 changed files +243 -1
- crates/ec-aac/src/lib.rs +1 -1
- crates/ec-aac/src/sbr_chain.rs +17 -0
- crates/ec-aac/tests/sbr_real_library.rs +225 -0
crates/ec-aac/src/lib.rsmodified+1 -1
| @@ -51,7 +51,7 @@ pub use ec_core::{Error, Result}; | |||
| 51 | pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; | 51 | pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; |
| 52 | /// Diagnostic only (round-20): per-(access-unit, channel) side-info rows | 52 | /// Diagnostic only (round-20): per-(access-unit, channel) side-info rows |
| 53 | /// logged during decode when `EC_AAC_SBR_SIDEINFO_DEBUG` is set. | 53 | /// logged during decode when `EC_AAC_SBR_SIDEINFO_DEBUG` is set. |
| 54 | -pub use sbr_chain::{SbrSideInfoRow, sbr_sideinfo_log}; | 54 | +pub use sbr_chain::{SbrSideInfoRow, hold_call_count, sbr_sideinfo_log}; |
| 55 | /// Diagnostic only (round-17 Task 1 conviction check): reads back the | 55 | /// Diagnostic only (round-17 Task 1 conviction check): reads back the |
| 56 | /// per-absolute-QMF-band transmitted signal/noise energy sums | 56 | /// per-absolute-QMF-band transmitted signal/noise energy sums |
| 57 | /// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode. | 57 | /// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` accumulates during decode. |
crates/ec-aac/src/sbr_chain.rsmodified+17 -0
| @@ -117,6 +117,20 @@ static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> | |||
| 117 | std::sync::OnceLock::new(); | 117 | std::sync::OnceLock::new(); |
| 118 | static SIDEINFO_FRAME: AtomicUsize = AtomicUsize::new(0); | 118 | static SIDEINFO_FRAME: AtomicUsize = AtomicUsize::new(0); |
| 119 | 119 | ||
| 120 | +/// Diagnostic-only counter: how many `apply_data` calls process-wide ran | ||
| 121 | +/// with `source == "hold"` (an AU whose FIL carried no fresh SBR payload, | ||
| 122 | +/// falling back to `apply_last`'s reuse of the last parsed frame). Read via | ||
| 123 | +/// [`hold_call_count`]; not gated by an env var since incrementing an atomic | ||
| 124 | +/// is unconditionally cheap, unlike the `EC_AAC_SBR_*_DEBUG` prints nearby. | ||
| 125 | +static HOLD_CALLS: AtomicUsize = AtomicUsize::new(0); | ||
| 126 | + | ||
| 127 | +/// Total `apply_data` calls process-wide where the SBR payload was reused | ||
| 128 | +/// from a prior frame (`apply_last`) rather than freshly parsed this AU -- | ||
| 129 | +/// diagnostic instrument for `sbr441_family_sample_drift_probe`. | ||
| 130 | +pub fn hold_call_count() -> usize { | ||
| 131 | + HOLD_CALLS.load(Ordering::Relaxed) | ||
| 132 | +} | ||
| 133 | + | ||
| 120 | fn sideinfo_enabled() -> bool { | 134 | fn sideinfo_enabled() -> bool { |
| 121 | std::env::var("EC_AAC_SBR_SIDEINFO_DEBUG").is_ok() | 135 | std::env::var("EC_AAC_SBR_SIDEINFO_DEBUG").is_ok() |
| 122 | } | 136 | } |
| @@ -271,6 +285,9 @@ impl SbrChain { | |||
| 271 | planes: &mut [Vec<f32>], | 285 | planes: &mut [Vec<f32>], |
| 272 | source: &'static str, | 286 | source: &'static str, |
| 273 | ) { | 287 | ) { |
| 288 | + if source == "hold" { | ||
| 289 | + HOLD_CALLS.fetch_add(1, Ordering::Relaxed); | ||
| 290 | + } | ||
| 274 | let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { | 291 | let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { |
| 275 | return; | 292 | return; |
| 276 | }; | 293 | }; |
crates/ec-aac/tests/sbr_real_library.rsmodified+225 -0
| @@ -4141,3 +4141,228 @@ fn coupled_cpe_channel_swap_probe() { | |||
| 4141 | } | 4141 | } |
| 4142 | } | 4142 | } |
| 4143 | } | 4143 | } |
| 4144 | + | ||
| 4145 | +/// Full decode of one container-native AAC stream, WITHOUT `our_decode`'s | ||
| 4146 | +/// `MAX_SAMPLES` (~22.7s @44100) cap -- this probe needs the ~30s the | ||
| 4147 | +/// per-1s lag-drift table walks, and the sample-count comparison below | ||
| 4148 | +/// needs the true total the decoder produced, not a cap-truncated one. | ||
| 4149 | +/// Bounded only by `extract_from`'s existing 1_500-AU read cap. | ||
| 4150 | +fn our_decode_uncapped(path: &Path, stream_index: usize) -> Option<(Vec<Vec<f32>>, u32, usize)> { | ||
| 4151 | + let (asc, aus) = extract_aac_track(path, stream_index)?; | ||
| 4152 | + let mut decoder = AacDecoder::with_config_bytes(&asc).ok()?; | ||
| 4153 | + let rate = decoder.output_sample_rate().unwrap_or(0); | ||
| 4154 | + let mut planes: Vec<Vec<f32>> = Vec::new(); | ||
| 4155 | + for au in &aus { | ||
| 4156 | + if let Ok(f) = decoder.decode(au, None) { | ||
| 4157 | + let ch = usize::from(f.channels); | ||
| 4158 | + if ch == 0 { | ||
| 4159 | + continue; | ||
| 4160 | + } | ||
| 4161 | + if planes.is_empty() { | ||
| 4162 | + planes = vec![Vec::new(); ch]; | ||
| 4163 | + } | ||
| 4164 | + for (i, v) in f.samples.iter().enumerate() { | ||
| 4165 | + planes[i % ch].push(*v); | ||
| 4166 | + } | ||
| 4167 | + } | ||
| 4168 | + } | ||
| 4169 | + if planes.is_empty() { | ||
| 4170 | + return None; | ||
| 4171 | + } | ||
| 4172 | + Some((planes, rate, aus.len())) | ||
| 4173 | +} | ||
| 4174 | + | ||
| 4175 | +/// Total sample count of an unbounded ffmpeg decode of one container-native | ||
| 4176 | +/// AAC stream, interleaved-`f32` byte count / 4 -- i.e. `channels * | ||
| 4177 | +/// per_channel_samples`, not capped at 30s the way `ffmpeg_decode` is. | ||
| 4178 | +fn ffmpeg_total_interleaved_samples(path: &Path, absolute_stream: usize) -> u64 { | ||
| 4179 | + let out = Command::new("ffmpeg") | ||
| 4180 | + .args(["-v", "error", "-i"]) | ||
| 4181 | + .arg(path) | ||
| 4182 | + .args([ | ||
| 4183 | + "-map", | ||
| 4184 | + &format!("0:{absolute_stream}"), | ||
| 4185 | + "-f", | ||
| 4186 | + "f32le", | ||
| 4187 | + "-acodec", | ||
| 4188 | + "pcm_f32le", | ||
| 4189 | + "-", | ||
| 4190 | + ]) | ||
| 4191 | + .output() | ||
| 4192 | + .expect("ffmpeg runs"); | ||
| 4193 | + assert!( | ||
| 4194 | + out.status.success(), | ||
| 4195 | + "ffmpeg full decode failed: {}", | ||
| 4196 | + String::from_utf8_lossy(&out.stderr) | ||
| 4197 | + ); | ||
| 4198 | + out.stdout.len() as u64 / 4 | ||
| 4199 | +} | ||
| 4200 | + | ||
| 4201 | +/// `ffprobe -show_entries stream=<entry>` on the file's first audio stream, | ||
| 4202 | +/// trimmed. Used to cross-check the container's declared `sample_rate` and | ||
| 4203 | +/// `duration` against what our decoder derives and what ffmpeg actually | ||
| 4204 | +/// produces. | ||
| 4205 | +fn ffprobe_field(path: &Path, entry: &str) -> String { | ||
| 4206 | + let out = Command::new("ffprobe") | ||
| 4207 | + .args([ | ||
| 4208 | + "-v", | ||
| 4209 | + "error", | ||
| 4210 | + "-select_streams", | ||
| 4211 | + "a:0", | ||
| 4212 | + "-show_entries", | ||
| 4213 | + &format!("stream={entry}"), | ||
| 4214 | + "-of", | ||
| 4215 | + "default=nw=1:nk=1", | ||
| 4216 | + ]) | ||
| 4217 | + .arg(path) | ||
| 4218 | + .output() | ||
| 4219 | + .expect("ffprobe runs"); | ||
| 4220 | + String::from_utf8_lossy(&out.stdout).trim().to_string() | ||
| 4221 | +} | ||
| 4222 | + | ||
| 4223 | +/// Narrow (`center +/- half`) fixed-window lag search anchored at ours-index | ||
| 4224 | +/// `oa0`, `len` samples long -- immune to the periodic-content aliasing that | ||
| 4225 | +/// makes `best_lag_correlation_ex`'s free ~100_000-wide coarse search | ||
| 4226 | +/// unreliable on this file (see the ledger dead-end on ref-L-vs-ref-R | ||
| 4227 | +/// itself mis-landing at lag=-24). `theirs`-index is `ours_index + lag`, | ||
| 4228 | +/// the same convention `best_lag_correlation_ex::slice_at` uses. | ||
| 4229 | +fn narrow_lag_at( | ||
| 4230 | + ours: &[f32], | ||
| 4231 | + theirs: &[f32], | ||
| 4232 | + oa0: usize, | ||
| 4233 | + len: usize, | ||
| 4234 | + center: i64, | ||
| 4235 | + half: i64, | ||
| 4236 | +) -> (i64, f64) { | ||
| 4237 | + let mut best = (center, -2.0f64); | ||
| 4238 | + for lag in (center - half)..=(center + half) { | ||
| 4239 | + let ob_i = oa0 as i64 + lag; | ||
| 4240 | + if ob_i < 0 { | ||
| 4241 | + continue; | ||
| 4242 | + } | ||
| 4243 | + let (oa, ob) = (oa0, ob_i as usize); | ||
| 4244 | + if oa + len > ours.len() || ob + len > theirs.len() { | ||
| 4245 | + continue; | ||
| 4246 | + } | ||
| 4247 | + let c = correlation(&ours[oa..oa + len], &theirs[ob..ob + len]); | ||
| 4248 | + if c > best.1 { | ||
| 4249 | + best = (lag, c); | ||
| 4250 | + } | ||
| 4251 | + } | ||
| 4252 | + best | ||
| 4253 | +} | ||
| 4254 | + | ||
| 4255 | +/// Round-55 charter probe: is the `heaac_44100_48k.m4a` (44.1k-family HE-AAC) | ||
| 4256 | +/// lag-vs-time drift a sample-count mismatch between our decode and | ||
| 4257 | +/// ffmpeg's reference (dropped/duplicated AU somewhere in the chain), or a | ||
| 4258 | +/// rate-label bug (we call it 44100 but produce samples at another rate), | ||
| 4259 | +/// or per-AU apply_last/hold fallbacks accumulating skew? Runs the same | ||
| 4260 | +/// three measurements on one 48k-family HE-AAC fixture and on reeln | ||
| 4261 | +/// (real 44.1k HE-AAC) as controls that are known NOT to show the drift. | ||
| 4262 | +#[test] | ||
| 4263 | +fn sbr441_family_sample_drift_probe() { | ||
| 4264 | + if !have_ffmpeg() { | ||
| 4265 | + eprintln!("SKIP: ffmpeg not on PATH"); | ||
| 4266 | + return; | ||
| 4267 | + } | ||
| 4268 | + let dir = std::env::var("EC_AAC_HEAAC_FIXTURES").unwrap_or_else(|_| { | ||
| 4269 | + format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")) | ||
| 4270 | + }); | ||
| 4271 | + let home = std::env::var("HOME").unwrap_or_default(); | ||
| 4272 | + let cases: [(&str, PathBuf, i64); 3] = [ | ||
| 4273 | + ( | ||
| 4274 | + "heaac_44100_48k (FAIL family)", | ||
| 4275 | + PathBuf::from(&dir).join("heaac_44100_48k.m4a"), | ||
| 4276 | + -4674, | ||
| 4277 | + ), | ||
| 4278 | + ( | ||
| 4279 | + "heaac_48000_48k (48k control)", | ||
| 4280 | + PathBuf::from(&dir).join("heaac_48000_48k.m4a"), | ||
| 4281 | + // corrected via this test's own wide free-search cross-check | ||
| 4282 | + // (below) -- 0 was a bad guess, true fixed lag is -4673, same | ||
| 4283 | + // as the failing family's. | ||
| 4284 | + -4673, | ||
| 4285 | + ), | ||
| 4286 | + ( | ||
| 4287 | + "reeln (44.1k control)", | ||
| 4288 | + PathBuf::from(format!("{home}/Music/reeln.mp4")), | ||
| 4289 | + // corrected via this test's own wide free-search cross-check | ||
| 4290 | + // (below) -- -576 was this file's CORE-vs-FULL-chain delay | ||
| 4291 | + // from an earlier probe, not its full-chain-vs-ffmpeg-reference | ||
| 4292 | + // lag, which is +385. | ||
| 4293 | + 385, | ||
| 4294 | + ), | ||
| 4295 | + ]; | ||
| 4296 | + for (label, path, seed_lag) in cases { | ||
| 4297 | + println!("\n=== {label}: {} ===", path.display()); | ||
| 4298 | + if !path.exists() { | ||
| 4299 | + eprintln!("SKIP {label}: {} absent", path.display()); | ||
| 4300 | + continue; | ||
| 4301 | + } | ||
| 4302 | + let holds_before = ec_aac::hold_call_count(); | ||
| 4303 | + let Some((ours, out_rate, au_count)) = our_decode_uncapped(&path, 0) else { | ||
| 4304 | + eprintln!("SKIP {label}: our_decode_uncapped failed"); | ||
| 4305 | + continue; | ||
| 4306 | + }; | ||
| 4307 | + // `ffmpeg_decode_pan_channel` caps at 10s (per its own charter, | ||
| 4308 | + // shared with `reelq_multichannel_lc_matches_reference`); | ||
| 4309 | + // this probe walks out to t=29s, so it needs `ffmpeg_decode`'s 30s | ||
| 4310 | + // cap instead -- planar channel 0 is L for every stereo case here. | ||
| 4311 | + let ref_l = ffmpeg_decode(&path, 0, 2).swap_remove(0); | ||
| 4312 | + let ch0 = &ours[0]; | ||
| 4313 | + // Cross-check the hardcoded `seed_lag` guess with a free wide | ||
| 4314 | + // search before trusting the narrow window around it -- a wrong | ||
| 4315 | + // seed on a control file reads as near-zero correlation | ||
| 4316 | + // everywhere, indistinguishable from "no signal", not "no drift". | ||
| 4317 | + { | ||
| 4318 | + let (wlag, wcorr) = best_lag_correlation_wide(ch0, &ref_l, SEARCH_LAG_MAX); | ||
| 4319 | + println!(" (wide free-search cross-check: lag={wlag} corr={wcorr:.6})"); | ||
| 4320 | + } | ||
| 4321 | + | ||
| 4322 | + // (1) per-1s narrow lag search, +/-128 around the file's known | ||
| 4323 | + // (or, for the controls, assumed-near-zero) fixed lag. | ||
| 4324 | + println!("-- lag(t), narrow +/-128 window around seed lag {seed_lag} --"); | ||
| 4325 | + let mut lag_points: Vec<(f64, f64)> = Vec::new(); | ||
| 4326 | + let step = out_rate.max(1) as usize; | ||
| 4327 | + for t in 0..30usize { | ||
| 4328 | + let oa0 = t * step; | ||
| 4329 | + if oa0 + step > ch0.len() { | ||
| 4330 | + break; | ||
| 4331 | + } | ||
| 4332 | + let (lag, corr) = narrow_lag_at(ch0, &ref_l, oa0, step, seed_lag, 128); | ||
| 4333 | + println!(" t={t:>2}s lag={lag:>7} corr={corr:.6}"); | ||
| 4334 | + lag_points.push((t as f64, lag as f64)); | ||
| 4335 | + } | ||
| 4336 | + if lag_points.len() >= 2 { | ||
| 4337 | + let n = lag_points.len() as f64; | ||
| 4338 | + let sx: f64 = lag_points.iter().map(|(x, _)| x).sum(); | ||
| 4339 | + let sy: f64 = lag_points.iter().map(|(_, y)| y).sum(); | ||
| 4340 | + let sxy: f64 = lag_points.iter().map(|(x, y)| x * y).sum(); | ||
| 4341 | + let sxx: f64 = lag_points.iter().map(|(x, _)| x * x).sum(); | ||
| 4342 | + let slope = (n * sxy - sx * sy) / (n * sxx - sx * sx); | ||
| 4343 | + println!(" fitted slope = {slope:.4} samples/second"); | ||
| 4344 | + } | ||
| 4345 | + | ||
| 4346 | + // (2) total sample count per channel: ours vs ffmpeg vs ffprobe | ||
| 4347 | + // duration*rate vs AU-count*2048. | ||
| 4348 | + let our_total = ch0.len() as u64; | ||
| 4349 | + let ffmpeg_total = ffmpeg_total_interleaved_samples(&path, 0) / 2; // stereo | ||
| 4350 | + let ffprobe_duration: f64 = ffprobe_field(&path, "duration").parse().unwrap_or(0.0); | ||
| 4351 | + let ffprobe_rate: f64 = ffprobe_field(&path, "sample_rate").parse().unwrap_or(0.0); | ||
| 4352 | + let ffprobe_total = (ffprobe_duration * ffprobe_rate).round() as u64; | ||
| 4353 | + let au_implied_total = au_count as u64 * 2048; | ||
| 4354 | + println!( | ||
| 4355 | + "-- sample counts (per channel): ours={our_total} ffmpeg={ffmpeg_total} \ | ||
| 4356 | + ffprobe(duration*rate)={ffprobe_total} au_count*2048={au_implied_total} \ | ||
| 4357 | + (au_count={au_count}) our_decode_rate={out_rate} ffprobe_rate={ffprobe_rate} \ | ||
| 4358 | + ratio(ours/ffmpeg)={:.6}", | ||
| 4359 | + our_total as f64 / ffmpeg_total.max(1) as f64 | ||
| 4360 | + ); | ||
| 4361 | + | ||
| 4362 | + // (4) apply_last/hold fallback count for this file's own decode | ||
| 4363 | + // (process-wide counter, delta'd against this file's own before/ | ||
| 4364 | + // after since the test loop shares one process). | ||
| 4365 | + let holds = ec_aac::hold_call_count() - holds_before; | ||
| 4366 | + println!("-- apply_last (hold) calls during this file's decode: {holds} of {au_count} AUs"); | ||
| 4367 | + } | ||
| 4368 | +} | ||