probe(sbr-patchmap): infra for measuring the reference's real HF patch map
Browse files at this commite3a8adf8679af9d034937f97ddef81563d025fc0Parent: bf135ff2 changed files +259 -0
crates/ec-aac/examples/adts_to_pcm.rsadded+49 -0
| @@ -0,0 +1,49 @@ | ||
| 1 | +//! Decodes an ADTS file (argv[1]) to raw interleaved f32le PCM on stdout, for | |
| 2 | +//! the patch-map probe scripts (`scripts/aac-tables/sbrpatchmap.py`) to read | |
| 3 | +//! our own decoder's output through the exact same FFT/comb-reading code as | |
| 4 | +//! the reference decoder's, with no format translation in between. | |
| 5 | +use std::io::Write; | |
| 6 | + | |
| 7 | +fn main() { | |
| 8 | + let path = std::env::args().nth(1).expect("usage: adts_to_pcm <file.aac>"); | |
| 9 | + let data = std::fs::read(&path).expect("file readable"); | |
| 10 | + // Plain `AacDecoder::new()` never enables SBR (it only turns on from an | |
| 11 | + // explicit AudioSpecificConfig's `sbr_present`, per `with_config`) -- | |
| 12 | + // the probe streams here are raw same-rate-SBR ADTS with no ASC, so | |
| 13 | + // build one directly rather than parsing bytes we don't have. | |
| 14 | + let same_rate_sbr = std::env::var("EC_AAC_SBR_SAME_RATE").is_ok(); | |
| 15 | + let channels: u16 = std::env::var("EC_AAC_SBR_CHANNELS") | |
| 16 | + .ok() | |
| 17 | + .and_then(|s| s.parse().ok()) | |
| 18 | + .unwrap_or(1); | |
| 19 | + let mut decoder = if same_rate_sbr { | |
| 20 | + ec_aac::AacDecoder::with_config(ec_aac::AudioSpecificConfig { | |
| 21 | + object_type: 2, | |
| 22 | + sample_rate: 44100, | |
| 23 | + sf_index: 7, | |
| 24 | + channels, | |
| 25 | + channel_config: channels as u8, | |
| 26 | + sbr_present: true, | |
| 27 | + ps_present: false, | |
| 28 | + extension_sample_rate: Some(44100), | |
| 29 | + }) | |
| 30 | + } else { | |
| 31 | + ec_aac::AacDecoder::new() | |
| 32 | + }; | |
| 33 | + let mut at = 0usize; | |
| 34 | + let stdout = std::io::stdout(); | |
| 35 | + let mut out = stdout.lock(); | |
| 36 | + while at + 7 <= data.len() { | |
| 37 | + let header = match ec_aac::parse_adts(&data[at..]) { | |
| 38 | + Ok(h) => h, | |
| 39 | + Err(_) => break, | |
| 40 | + }; | |
| 41 | + let end = (at + header.frame_length).min(data.len()); | |
| 42 | + if let Ok(frame) = decoder.decode(&data[at..end], None) { | |
| 43 | + for v in &frame.samples { | |
| 44 | + out.write_all(&v.to_le_bytes()).expect("stdout writable"); | |
| 45 | + } | |
| 46 | + } | |
| 47 | + at = end; | |
| 48 | + } | |
| 49 | +} |
scripts/aac-tables/sbrpatchmap.pyadded+210 -0
| @@ -0,0 +1,210 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Round-27: measures the reference decoder's ACTUAL SBR HF patch map (which | |
| 3 | +low QMF source band feeds which high target band), by isolating one source | |
| 4 | +band at a time and reading off which target bands carry power in the output. | |
| 5 | + | |
| 6 | +Method (one-band-at-a-time, simpler than a multi-line comb and avoids any | |
| 7 | +ambiguity from overlapping lines): the core spectrum for a probe frame is a | |
| 8 | +single isolated MDCT bin -- `tone_core()` in `sbrchirp.py`, already proven to | |
| 9 | +place value 2 in one 4-bin group and ZERO_HCB everywhere else -- at the first | |
| 10 | +bin of low QMF band `p` (`k = p*16`, always a group boundary since a QMF band | |
| 11 | +is 16 MDCT bins wide and a group is 4). Patching copies that source band's | |
| 12 | +complex QMF series verbatim (mixed by LPC/chirp, which round-19 already | |
| 13 | +measured as a <0.1% power effect regardless of `bs_invf_mode`) into every | |
| 14 | +target band any patch maps it to, so an FFT of the decoded output that finds | |
| 15 | +elevated power in target band `q` means "patch measured: source `p` -> target | |
| 16 | +`q`" directly, no fractional-offset bookkeeping needed. | |
| 17 | + | |
| 18 | +Runs the same probes through our own decoder via the `adts_to_pcm` example | |
| 19 | +(`cargo build -p ec-aac --example adts_to_pcm`) for the sanity cross-check the | |
| 20 | +charter requires: our measured map must equal `build_patches`' prediction, or | |
| 21 | +the fingerprint method itself is the thing that's broken. | |
| 22 | +""" | |
| 23 | +import os | |
| 24 | +import subprocess | |
| 25 | +import sys | |
| 26 | + | |
| 27 | +import numpy as np | |
| 28 | + | |
| 29 | +HERE = os.path.dirname(os.path.abspath(__file__)) | |
| 30 | +sys.path.insert(0, HERE) | |
| 31 | + | |
| 32 | +import sbrchirp as C # noqa: E402 | |
| 33 | +import sbrpayload_fixtures as F # noqa: E402 | |
| 34 | +import sbrprobe as P # noqa: E402 | |
| 35 | +import sbrtables as T # noqa: E402 | |
| 36 | + | |
| 37 | +SF_INDEX = 7 | |
| 38 | +RATE = 44100 | |
| 39 | +OUR_DECODER = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/adts_to_pcm") | |
| 40 | + | |
| 41 | + | |
| 42 | +def build_patches_predicted(kx, k2, f_high): | |
| 43 | + """Python port of `build_patches` (crates/ec-aac/src/sbr_hf.rs), for | |
| 44 | + comparing the reference's measured map against our own prediction.""" | |
| 45 | + patches = [] | |
| 46 | + if kx == 0 or k2 <= kx: | |
| 47 | + return patches | |
| 48 | + msb, sb = kx, kx | |
| 49 | + while sb < k2: | |
| 50 | + width, probe = 0, sb | |
| 51 | + while True: | |
| 52 | + border = next((b for b in f_high if b > probe), None) | |
| 53 | + if border is None: | |
| 54 | + break | |
| 55 | + iv = border - probe | |
| 56 | + if width + iv > msb or border > k2: | |
| 57 | + break | |
| 58 | + width += iv | |
| 59 | + probe = border | |
| 60 | + if width == 0: | |
| 61 | + width = min(k2 - sb, max(msb, 1)) | |
| 62 | + source_start = msb - min(width, msb) | |
| 63 | + patches.append((source_start, sb, width)) | |
| 64 | + sb += width | |
| 65 | + msb = kx if source_start == 0 else source_start | |
| 66 | + return patches | |
| 67 | + | |
| 68 | + | |
| 69 | +def predicted_targets(patches, p): | |
| 70 | + out = [] | |
| 71 | + for source_start, target_start, width in patches: | |
| 72 | + if source_start <= p < source_start + width: | |
| 73 | + out.append(target_start + (p - source_start)) | |
| 74 | + return out | |
| 75 | + | |
| 76 | + | |
| 77 | +def bin_to_sfb_group(k, swb): | |
| 78 | + for i in range(len(swb) - 1): | |
| 79 | + if swb[i] <= k < swb[i + 1]: | |
| 80 | + return i, (k - swb[i]) // 4 | |
| 81 | + return None | |
| 82 | + | |
| 83 | + | |
| 84 | +def make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band): | |
| 85 | + cfg = dict(T.DEFAULT, sf_index=SF_INDEX, start_freq=start_freq, stop_freq=stop_freq, | |
| 86 | + freq_scale=freq_scale, alter_scale=alter_scale, noise_bands=noise_bands, | |
| 87 | + xover_band=xover_band) | |
| 88 | + t = T.freq_tables(RATE, cfg) | |
| 89 | + return cfg, t | |
| 90 | + | |
| 91 | + | |
| 92 | +def stream_one_band(cfg, tables, active_p, n_frames=16, invf_mode=0): | |
| 93 | + """`n_frames` FIXFIX/2-env amp_res=1 frames (round-19's engaging shape), | |
| 94 | + core = one isolated tone at low QMF band `active_p`'s first bin, held | |
| 95 | + fixed; envelope flat/loud, noise floor minimal, invf NONE, no harmonics.""" | |
| 96 | + swb = P.SWB_LONG[SF_INDEX] | |
| 97 | + k = active_p * 16 | |
| 98 | + found = bin_to_sfb_group(k, swb) | |
| 99 | + assert found is not None, f"band {active_p} bin {k} not in SWB_LONG[{SF_INDEX}]" | |
| 100 | + sfb_idx, group_active = found | |
| 101 | + grid = dict(frame_class=0, num_env=2, freq_res=0) | |
| 102 | + frames = [P.silent(SF_INDEX)] | |
| 103 | + for _ in range(n_frames): | |
| 104 | + c = dict(cfg, invf=invf_mode, header=1, amp_res=1, element="sce", coupling=0, | |
| 105 | + df_env=[0] * 8, df_noise=[0, 0], env0=[40] * 8, noise0=[2, 2]) | |
| 106 | + w = P.BitW() | |
| 107 | + C.tone_core(w, sfb_idx, group_active) | |
| 108 | + body = F.sbr_bits_full(c, tables, grid, []) | |
| 109 | + w.w(6, 3) | |
| 110 | + cnt = (len(body.bits) + 4 + 7) // 8 | |
| 111 | + if cnt >= 15: | |
| 112 | + w.w(15, 4) | |
| 113 | + w.w(cnt - 15 + 1, 8) | |
| 114 | + else: | |
| 115 | + w.w(cnt, 4) | |
| 116 | + start = len(w) | |
| 117 | + w.w(13, 4) | |
| 118 | + w.wbits(body.bits) | |
| 119 | + while len(w) - start < cnt * 8: | |
| 120 | + w.w(0, 1) | |
| 121 | + w.w(7, 3) | |
| 122 | + frames.append(P.adts(w.pack(pad=0), SF_INDEX)) | |
| 123 | + frames.append(P.silent(SF_INDEX)) | |
| 124 | + return frames | |
| 125 | + | |
| 126 | + | |
| 127 | +def our_decode(frames, tag): | |
| 128 | + src = f"/tmp/sbrpatchmap-our-{tag}.aac" | |
| 129 | + with open(src, "wb") as f: | |
| 130 | + f.write(b"".join(frames)) | |
| 131 | + env = dict(os.environ, EC_AAC_SBR_SAME_RATE="1", EC_AAC_SBR_CHANNELS="1") | |
| 132 | + r = subprocess.run([OUR_DECODER, src], capture_output=True, env=env) | |
| 133 | + os.remove(src) | |
| 134 | + return np.frombuffer(r.stdout, dtype="<f4").astype(np.float64), r.stderr.decode(errors="replace") | |
| 135 | + | |
| 136 | + | |
| 137 | +def band_powers(pcm, kx, k2, n_fft=8192, skip_samples=5120): | |
| 138 | + """Power in each target band `q in [kx, k2)`, from a steady-state FFT | |
| 139 | + window (RATE/128 Hz per band, `n_fft=8192` gives ~5.4 Hz/bin -- fine | |
| 140 | + enough that a single active source band's line falls cleanly in one | |
| 141 | + band's bin range even without knowing its exact intra-band position).""" | |
| 142 | + seg = pcm[skip_samples : skip_samples + n_fft] | |
| 143 | + if len(seg) < n_fft: | |
| 144 | + seg = np.pad(seg, (0, n_fft - len(seg))) | |
| 145 | + spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg)))) ** 2 | |
| 146 | + freqs = np.fft.rfftfreq(n_fft, 1 / RATE) | |
| 147 | + powers = {} | |
| 148 | + for q in range(kx, k2): | |
| 149 | + lo, hi = q * RATE / 128, (q + 1) * RATE / 128 | |
| 150 | + mask = (freqs >= lo) & (freqs < hi) | |
| 151 | + powers[q] = float(spec[mask].sum()) | |
| 152 | + return powers | |
| 153 | + | |
| 154 | + | |
| 155 | +def measured_targets(powers, rel_threshold=0.05): | |
| 156 | + """Bands whose power is at least `rel_threshold` of the loudest band's -- | |
| 157 | + the loudest is always the patch that actually fired, background/leakage | |
| 158 | + bands sit orders of magnitude lower.""" | |
| 159 | + if not powers: | |
| 160 | + return [] | |
| 161 | + top = max(powers.values()) | |
| 162 | + if top <= 0: | |
| 163 | + return [] | |
| 164 | + return sorted(q for q, p in powers.items() if p >= rel_threshold * top) | |
| 165 | + | |
| 166 | + | |
| 167 | +def run_header(label, start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band): | |
| 168 | + cfg, tables = make_tables(start_freq, stop_freq, freq_scale, alter_scale, noise_bands, xover_band) | |
| 169 | + assert tables is not None, f"{label}: header does not produce valid tables" | |
| 170 | + kx, k2 = tables["kx"], tables["k2"] | |
| 171 | + print(f"\n== {label}: start={start_freq} stop={stop_freq} scale={freq_scale} alter={alter_scale}" | |
| 172 | + f" noise={noise_bands} xover={xover_band} -> kx={kx} k2={k2} n_q={tables['n_q']} ==") | |
| 173 | + patches = build_patches_predicted(kx, k2, tables["f_high"]) | |
| 174 | + print(f" predicted patches (src_start, tgt_start, width): {patches}") | |
| 175 | + | |
| 176 | + ref_map, our_map = {}, {} | |
| 177 | + for p in range(kx): | |
| 178 | + frames = stream_one_band(cfg, tables, p, n_frames=16) | |
| 179 | + pcm_ref, err_ref = P.decode(frames, SF_INDEX, f"{label}-p{p}") | |
| 180 | + pcm_our, err_our = our_decode(frames, f"{label}-p{p}") | |
| 181 | + pw_ref = band_powers(pcm_ref, kx, k2) | |
| 182 | + pw_our = band_powers(pcm_our, kx, k2) | |
| 183 | + tgt_ref = measured_targets(pw_ref) | |
| 184 | + tgt_our = measured_targets(pw_our) | |
| 185 | + pred = predicted_targets(patches, p) | |
| 186 | + ref_map[p] = tgt_ref | |
| 187 | + our_map[p] = tgt_our | |
| 188 | + flag = "" if tgt_ref == pred else " <<< DIFFERS FROM PREDICTION" | |
| 189 | + our_flag = "" if tgt_our == pred else " <<< OUR DECODER DIFFERS FROM build_patches" | |
| 190 | + print(f" p={p:2d} predicted={pred} measured(ref)={tgt_ref}{flag} measured(ours)={tgt_our}{our_flag}" | |
| 191 | + f" [ref_err={err_ref.strip()[:60]!r} our_err={err_our.strip()[:40]!r}]") | |
| 192 | + return kx, k2, patches, ref_map, our_map | |
| 193 | + | |
| 194 | + | |
| 195 | +if __name__ == "__main__": | |
| 196 | + assert os.path.exists(OUR_DECODER), f"build first: cargo build -p ec-aac --example adts_to_pcm ({OUR_DECODER})" | |
| 197 | + # Header A: the real file's ACTUAL SBR header, read straight off | |
| 198 | + # reeln's own bitstream via `EC_AAC_SBR_DEBUG=1` on our own decoder | |
| 199 | + # (start_freq=5 stop_freq=8 xover_band=0 freq_scale=2 alter_scale=1 | |
| 200 | + # noise_bands=2 -> kx=14 k2=43 n_q=3) -- NOT the `sbr_hf.rs` unit test's | |
| 201 | + # `real_file_tables()`, whose stop_freq/xover_band guess (3/2) was wrong | |
| 202 | + # and gives a different, smaller kx=16 k2=29 header. | |
| 203 | + run_header("A-reeln", start_freq=5, stop_freq=8, freq_scale=2, alter_scale=1, | |
| 204 | + noise_bands=2, xover_band=0) | |
| 205 | + # Headers B and C: different start/stop/xover -> differently-shaped | |
| 206 | + # kx/k2, to pin the algorithm's shape rather than one lucky header. | |
| 207 | + run_header("B-alt", start_freq=8, stop_freq=10, freq_scale=2, alter_scale=1, | |
| 208 | + noise_bands=2, xover_band=1) | |
| 209 | + run_header("C-alt", start_freq=3, stop_freq=5, freq_scale=2, alter_scale=1, | |
| 210 | + noise_bands=2, xover_band=0) |