probe(sbr): engagement bisection converges on the harness, not the payload
Browse files at this commit854ea3715e4463dfa01d95cba436644e5b262bdaParent: 9b444423 changed files +194 -5
- crates/ec-aac/examples/adts_to_pcm.rs +13 -4
- scripts/aac-tables/sbrbisect.py +154 -0
- scripts/aac-tables/sbrpatchmap.py +27 -1
crates/ec-aac/examples/adts_to_pcm.rsmodified+13 -4
| @@ -18,17 +18,26 @@ fn main() { | |||
| 18 | .ok() | 18 | .ok() |
| 19 | .and_then(|s| s.parse().ok()) | 19 | .and_then(|s| s.parse().ok()) |
| 20 | .unwrap_or(1); | 20 | .unwrap_or(1); |
| 21 | + // Round-32: built via the SAME write_audio_specific_config + | ||
| 22 | + // with_config_bytes round trip `wrap_sbr` uses (AOT_SBR, core rate | ||
| 23 | + // 22050 = ADTS sf_index 7's SAMPLE_RATES entry, extension 44100) so this | ||
| 24 | + // path and the reference's wrap_sbr-wrapped mp4 read byte-identical ASC | ||
| 25 | + // semantics -- the prior hand-built config (object_type=2/AAC-LC, | ||
| 26 | + // sample_rate=44100 for what is actually the 22050 Hz *core*) diverged | ||
| 27 | + // from wrap_sbr's ASC, which is why the sanity gate (ours vs | ||
| 28 | + // build_patches) was failing independent of any patch-map bug. | ||
| 21 | let mut decoder = if same_rate_sbr { | 29 | let mut decoder = if same_rate_sbr { |
| 22 | - ec_aac::AacDecoder::with_config(ec_aac::AudioSpecificConfig { | 30 | + let asc = ec_aac::write_audio_specific_config(&ec_aac::AudioSpecificConfig { |
| 23 | - object_type: 2, | 31 | + object_type: ec_aac::AOT_SBR, |
| 24 | - sample_rate: 44100, | 32 | + sample_rate: 22050, |
| 25 | sf_index: 7, | 33 | sf_index: 7, |
| 26 | channels, | 34 | channels, |
| 27 | channel_config: channels as u8, | 35 | channel_config: channels as u8, |
| 28 | sbr_present: true, | 36 | sbr_present: true, |
| 29 | ps_present: false, | 37 | ps_present: false, |
| 30 | extension_sample_rate: Some(44100), | 38 | extension_sample_rate: Some(44100), |
| 31 | - }) | 39 | + }); |
| 40 | + ec_aac::AacDecoder::with_config_bytes(&asc).expect("asc parses") | ||
| 32 | } else { | 41 | } else { |
| 33 | ec_aac::AacDecoder::new() | 42 | ec_aac::AacDecoder::new() |
| 34 | }; | 43 | }; |
scripts/aac-tables/sbrbisect.pyadded+154 -0
| @@ -0,0 +1,154 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""Round-32: field-by-field bisection of `sbrchirp.stream()` (proven to | ||
| 3 | +engage the reference's SBR dequant, env sweep moves power 2941x) against | ||
| 4 | +`sbrpatchmap.stream_one_band()` (never engages -- flat env sweep, warning on | ||
| 5 | +every probe), under the wrap_sbr explicit-ASC harness so implicit-signaling | ||
| 6 | +detection (round-30/31's already-closed blocker) cannot confound the result. | ||
| 7 | + | ||
| 8 | +The two writers differ in exactly three respects (read side-by-side against | ||
| 9 | +`sbr_bits_full`, `write_grid` -- FIL type/count/padding, header cadence, and | ||
| 10 | +grid shape fields are IDENTICAL between them, so those charter-listed | ||
| 11 | +candidates are refuted by inspection, not measurement): | ||
| 12 | + (H) the header/table values: `stream()` uses `one_band_header()` (tiny, | ||
| 13 | + n_low=1/n_q=1, so no delta slots are ever needed); `stream_one_band()` | ||
| 14 | + uses a real multi-band header (A: kx=14/k2=43/n_q=3). | ||
| 15 | + (C) the core content: `broadband_core_bits` (proven-clean comb) vs | ||
| 16 | + `tone_core` (round-27/31 flagged, still-live suspicion). | ||
| 17 | + (W) the envelope/noise delta-Huffman words: `[]` (fine for H's n_slots=0) | ||
| 18 | + vs explicit `[zero_delta] * n_slots` (round-29's FILL-desync fix, | ||
| 19 | + needed once H has real bands). | ||
| 20 | +(W) is mechanically forced by (H) -- header A has n_slots > 0, so it MUST | ||
| 21 | +carry real words or decode is bit-desynced regardless of anything else; it | ||
| 22 | +is not an independent flip, it is included with H below. | ||
| 23 | + | ||
| 24 | +Builds each combination via `stream_one_band`'s own frame writer (broadband | ||
| 25 | +core is swapped in unmodified for the (C=broadband) rows), wraps every env0 | ||
| 26 | +value through `wrap_sbr` (explicit-SBR ASC, mp4/esds), decodes with the | ||
| 27 | +reference, and reports whether power in the predicted in-band window moves | ||
| 28 | +across an env0 sweep (engagement) or not. | ||
| 29 | +""" | ||
| 30 | +import os | ||
| 31 | +import subprocess | ||
| 32 | +import sys | ||
| 33 | + | ||
| 34 | +import numpy as np | ||
| 35 | + | ||
| 36 | +HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 37 | +sys.path.insert(0, HERE) | ||
| 38 | + | ||
| 39 | +import sbrchirp as C # noqa: E402 | ||
| 40 | +import sbrpatchmap as PM # noqa: E402 | ||
| 41 | +import sbrpayload_fixtures as F # noqa: E402 | ||
| 42 | +import sbrprobe as P # noqa: E402 | ||
| 43 | + | ||
| 44 | +SF_INDEX = 7 | ||
| 45 | +RATE = 44100 | ||
| 46 | +WRAP = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/wrap_sbr") | ||
| 47 | +NO_QUANT_WARNING = "No quantized data read for sbr_dequant." | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def build(header_tables, use_words, core, active_p, env0_raw, n_frames=24): | ||
| 51 | + """One stream, mirroring `stream_one_band`'s frame writer exactly, but | ||
| 52 | + with (header_tables, use_words, core) as independent flips.""" | ||
| 53 | + cfg, tables = header_tables | ||
| 54 | + swb = P.SWB_LONG[SF_INDEX] | ||
| 55 | + if core == "tone": | ||
| 56 | + k = active_p * 32 + 16 | ||
| 57 | + sfb_idx, group_active = PM.bin_to_sfb_group(k, swb) | ||
| 58 | + grid = dict(frame_class=0, num_env=2, freq_res=0) | ||
| 59 | + zero_delta = [0] | ||
| 60 | + n_slots = 2 * (tables["n_low"] - 1) + 2 * (tables["n_q"] - 1) | ||
| 61 | + frames = [P.silent(SF_INDEX)] | ||
| 62 | + for _ in range(n_frames): | ||
| 63 | + c = dict(cfg, invf=0, header=1, amp_res=1, element="sce", coupling=0, | ||
| 64 | + df_env=[0] * 8, df_noise=[0, 0], env0=[env0_raw] * 8, noise0=[2, 2]) | ||
| 65 | + w = P.BitW() | ||
| 66 | + if core == "tone": | ||
| 67 | + C.tone_core(w, sfb_idx, group_active) | ||
| 68 | + else: | ||
| 69 | + C.broadband_core_bits(w) | ||
| 70 | + words = ([zero_delta] * n_slots) if use_words else [] | ||
| 71 | + body = F.sbr_bits_full(c, tables, grid, words) | ||
| 72 | + w.w(6, 3) | ||
| 73 | + cnt = (len(body.bits) + 4 + 7) // 8 | ||
| 74 | + if cnt >= 15: | ||
| 75 | + w.w(15, 4) | ||
| 76 | + w.w(cnt - 15 + 1, 8) | ||
| 77 | + else: | ||
| 78 | + w.w(cnt, 4) | ||
| 79 | + start = len(w) | ||
| 80 | + w.w(13, 4) | ||
| 81 | + w.wbits(body.bits) | ||
| 82 | + while len(w) - start < cnt * 8: | ||
| 83 | + w.w(0, 1) | ||
| 84 | + w.w(7, 3) | ||
| 85 | + frames.append(P.adts(w.pack(pad=0), SF_INDEX)) | ||
| 86 | + frames.append(P.silent(SF_INDEX)) | ||
| 87 | + return frames | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def wrap_and_decode(frames, tag, kx): | ||
| 91 | + raw = f"/tmp/sbrbisect-{tag}.aac" | ||
| 92 | + mp4 = f"/tmp/sbrbisect-{tag}.mp4" | ||
| 93 | + with open(raw, "wb") as f: | ||
| 94 | + f.write(b"".join(frames)) | ||
| 95 | + r = subprocess.run([WRAP, raw, "22050", "44100", "1", mp4], capture_output=True) | ||
| 96 | + assert r.returncode == 0, f"wrap_sbr failed: {r.stderr.decode()}" | ||
| 97 | + dec = subprocess.run( | ||
| 98 | + ["ffmpeg", "-v", "error", "-i", mp4, "-f", "f32le", "-ac", "1", "-"], | ||
| 99 | + capture_output=True, | ||
| 100 | + ) | ||
| 101 | + pcm = np.frombuffer(dec.stdout, dtype="<f4").astype(np.float64) | ||
| 102 | + err = dec.stderr.decode(errors="replace") | ||
| 103 | + os.remove(raw) | ||
| 104 | + os.remove(mp4) | ||
| 105 | + return pcm, err | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def inband_power(pcm, kx, k2, sr=RATE, n_fft=8192, skip=5): | ||
| 109 | + lo, hi = kx * sr / 128, k2 * sr / 128 | ||
| 110 | + start = skip * 1024 | ||
| 111 | + seg = pcm[start : start + n_fft] | ||
| 112 | + if len(seg) < n_fft: | ||
| 113 | + seg = np.pad(seg, (0, n_fft - len(seg))) | ||
| 114 | + spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg)))) | ||
| 115 | + freqs = np.fft.rfftfreq(n_fft, 1 / sr) | ||
| 116 | + mask = (freqs >= lo) & (freqs < hi) | ||
| 117 | + return float(np.sum(spec[mask] ** 2)) | ||
| 118 | + | ||
| 119 | + | ||
| 120 | +def engagement_sweep(label, header_tables, use_words, core, active_p=0): | ||
| 121 | + cfg, tables = header_tables | ||
| 122 | + kx, k2 = tables["kx"], tables["k2"] | ||
| 123 | + pwrs, warns = [], [] | ||
| 124 | + for env0 in (3, 12, 20, 30, 40, 50, 60): | ||
| 125 | + frames = build(header_tables, use_words, core, active_p, env0) | ||
| 126 | + pcm, err = wrap_and_decode(frames, f"{label}-{env0}", kx) | ||
| 127 | + warns.append(NO_QUANT_WARNING in err) | ||
| 128 | + pwrs.append(inband_power(pcm, kx, k2)) | ||
| 129 | + ratio = (max(pwrs) / min(pwrs)) if min(pwrs) > 0 else float("inf") | ||
| 130 | + engaged = ratio > 10.0 | ||
| 131 | + print(f"{label:40s} kx={kx:3d} k2={k2:3d} pwrs={['%.3e' % p for p in pwrs]} " | ||
| 132 | + f"ratio={ratio:.3e} warn_every_frame={all(warns)} " | ||
| 133 | + f"=> {'ENGAGED' if engaged else 'flat'}") | ||
| 134 | + return engaged | ||
| 135 | + | ||
| 136 | + | ||
| 137 | +if __name__ == "__main__": | ||
| 138 | + assert os.path.exists(WRAP), f"build first: cargo build -p ec-aac --example wrap_sbr ({WRAP})" | ||
| 139 | + | ||
| 140 | + default_ct = F.one_band_header() | ||
| 141 | + header_a_ct = PM.make_tables(start_freq=5, stop_freq=8, freq_scale=2, alter_scale=1, | ||
| 142 | + noise_bands=2, xover_band=0) | ||
| 143 | + | ||
| 144 | + print("== baseline: default header, broadband core (stream()'s own shape) ==") | ||
| 145 | + engagement_sweep("H=default,C=broadband,W=[]", default_ct, False, "broadband") | ||
| 146 | + | ||
| 147 | + print("\n== flip H only: header A, broadband core, real words ==") | ||
| 148 | + engagement_sweep("H=A,C=broadband,W=real", header_a_ct, True, "broadband") | ||
| 149 | + | ||
| 150 | + print("\n== flip C only: default header, tone core, W=[] ==") | ||
| 151 | + engagement_sweep("H=default,C=tone,W=[]", default_ct, False, "tone") | ||
| 152 | + | ||
| 153 | + print("\n== flip both (stream_one_band's actual shape): header A, tone core, real words ==") | ||
| 154 | + engagement_sweep("H=A,C=tone,W=real", header_a_ct, True, "tone") | ||
scripts/aac-tables/sbrpatchmap.pymodified+27 -1
| @@ -107,6 +107,32 @@ import sbrtables as T # noqa: E402 | |||
| 107 | SF_INDEX = 7 | 107 | SF_INDEX = 7 |
| 108 | RATE = 44100 | 108 | RATE = 44100 |
| 109 | OUR_DECODER = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/adts_to_pcm") | 109 | OUR_DECODER = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/adts_to_pcm") |
| 110 | +# Round-32: field-by-field bisection (scripts/aac-tables/sbrbisect.py) proved | ||
| 111 | +# stream_one_band's bit construction ALREADY engages the reference's SBR | ||
| 112 | +# dequant once wrapped in an explicit-SBR ASC (env0 sweep moves in-band power | ||
| 113 | +# ~1e12x, warning fires once at stream head only, PCM length doubles) -- | ||
| 114 | +# every flip tried (header, core content, delta words) engaged identically. | ||
| 115 | +# The round-30/31 "flat" reading was this module still calling `P.decode` | ||
| 116 | +# (bare ADTS, implicit per-frame detection) on the reference side while | ||
| 117 | +# `wrap_sbr` (round-31) sat unused; `ref_decode` below is the fix. | ||
| 118 | +WRAP_SBR = os.path.expanduser("~/.cache/cargo-target-sbr/debug/examples/wrap_sbr") | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def ref_decode(frames, tag): | ||
| 122 | + assert os.path.exists(WRAP_SBR), f"build first: cargo build -p ec-aac --example wrap_sbr ({WRAP_SBR})" | ||
| 123 | + raw = f"/tmp/sbrpatchmap-ref-{tag}.aac" | ||
| 124 | + mp4 = f"/tmp/sbrpatchmap-ref-{tag}.mp4" | ||
| 125 | + with open(raw, "wb") as f: | ||
| 126 | + f.write(b"".join(frames)) | ||
| 127 | + r = subprocess.run([WRAP_SBR, raw, "22050", "44100", "1", mp4], capture_output=True) | ||
| 128 | + assert r.returncode == 0, f"wrap_sbr failed: {r.stderr.decode()}" | ||
| 129 | + dec = subprocess.run( | ||
| 130 | + ["ffmpeg", "-v", "error", "-i", mp4, "-f", "f32le", "-ac", "1", "-"], | ||
| 131 | + capture_output=True, | ||
| 132 | + ) | ||
| 133 | + os.remove(raw) | ||
| 134 | + os.remove(mp4) | ||
| 135 | + return np.frombuffer(dec.stdout, dtype="<f4").astype(np.float64), dec.stderr.decode(errors="replace") | ||
| 110 | BAND_HZ = RATE / 128 # QMF band width, both source and target index units | 136 | BAND_HZ = RATE / 128 # QMF band width, both source and target index units |
| 111 | # Round-30 fix: a source (low) QMF band is 32 core-MDCT bins wide (1024-bin | 137 | # Round-30 fix: a source (low) QMF band is 32 core-MDCT bins wide (1024-bin |
| 112 | # core MDCT / 32 core bands), not 16 -- every prior round's k = p*16 + offset | 138 | # core MDCT / 32 core bands), not 16 -- every prior round's k = p*16 + offset |
| @@ -305,7 +331,7 @@ def run_header(label, start_freq, stop_freq, freq_scale, alter_scale, noise_band | |||
| 305 | our_sane = True | 331 | our_sane = True |
| 306 | for p in range(kx): | 332 | for p in range(kx): |
| 307 | frames = stream_one_band(cfg, tables, p) | 333 | frames = stream_one_band(cfg, tables, p) |
| 308 | - pcm_ref, err_ref = P.decode(frames, SF_INDEX, f"{label}-p{p}") | 334 | + pcm_ref, err_ref = ref_decode(frames, f"{label}-p{p}") |
| 309 | pcm_our, err_our = our_decode(frames, f"{label}-p{p}") | 335 | pcm_our, err_our = our_decode(frames, f"{label}-p{p}") |
| 310 | if NO_QUANT_WARNING in err_ref: | 336 | if NO_QUANT_WARNING in err_ref: |
| 311 | warnings_seen.append(p) | 337 | warnings_seen.append(p) |