diff --git a/crates/ec-aac/src/sbr_tables.rs b/crates/ec-aac/src/sbr_tables.rs index c3ccaa21..aeb40ef1 100644 --- a/crates/ec-aac/src/sbr_tables.rs +++ b/crates/ec-aac/src/sbr_tables.rs @@ -7,6 +7,13 @@ //! `env_facs_q`/`noise_facs_q` range check reads the delta value each //! codeword carries off the same payload. Every table here closed with //! a Kraft sum of exactly 1 (asserted below). +//! +//! GENERATED: books by `sbrtables.py --stage values`, then the four 3.0 dB +//! books (`ENV30_F`, `ENV30_T`, `ENVB30_F`, `ENVB30_T`) re-valued in place by +//! `scripts/aac-tables/sbrvalues.py`, which walks each codeword's delta out +//! of range by delta-time ACCUMULATION (a single +d on the 6-bit 3 dB raw +//! field never reaches the 7-bit ceiling, so the one-shot stage read every +//! positive 3 dB delta as 0). Do not hand-edit the books. #![allow(dead_code)] /// SBR Huffman book `ENV15_F`: (length, code, delta) by codeword. @@ -263,31 +270,31 @@ pub(crate) static ENV15_T: [(u8, u32, i32); 121] = [ pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [ (1, 0, 0), (2, 2, -1), - (3, 6, 0), + (3, 6, 1), (4, 14, -2), - (5, 30, 0), + (5, 30, 2), (6, 62, -3), - (7, 126, 0), + (7, 126, 3), (8, 254, -4), - (9, 510, 0), + (9, 510, 4), (11, 2044, -5), - (11, 2045, 0), + (11, 2045, 5), (12, 4092, -6), (13, 8186, -7), - (13, 8187, 0), + (13, 8187, 6), (14, 16376, -8), - (14, 16377, 0), + (14, 16377, 7), (14, 16378, -9), (14, 16379, -10), - (14, 16380, 0), - (15, 32762, 0), - (16, 65526, 0), + (14, 16380, 8), + (15, 32762, 9), + (16, 65526, 10), (16, 65527, -13), (16, 65528, -11), (16, 65529, -12), (17, 131060, -14), - (17, 131061, 0), - (18, 262124, 0), + (17, 131061, 11), + (18, 262124, 12), (18, 262125, -31), (18, 262126, -30), (19, 524254, -29), @@ -305,76 +312,76 @@ pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [ (19, 524266, -17), (19, 524267, -16), (19, 524268, -15), - (19, 524269, 0), - (19, 524270, 0), - (19, 524271, 0), - (19, 524272, 0), - (19, 524273, 0), - (19, 524274, 0), - (19, 524275, 0), - (19, 524276, 0), - (19, 524277, 0), - (19, 524278, 0), - (19, 524279, 0), - (19, 524280, 0), - (19, 524281, 0), - (19, 524282, 0), - (19, 524283, 0), - (19, 524284, 0), - (19, 524285, 0), - (19, 524286, 0), - (19, 524287, 0), + (19, 524269, 13), + (19, 524270, 14), + (19, 524271, 15), + (19, 524272, 16), + (19, 524273, 17), + (19, 524274, 18), + (19, 524275, 19), + (19, 524276, 20), + (19, 524277, 21), + (19, 524278, 22), + (19, 524279, 23), + (19, 524280, 24), + (19, 524281, 25), + (19, 524282, 26), + (19, 524283, 27), + (19, 524284, 28), + (19, 524285, 29), + (19, 524286, 30), + (19, 524287, 31), ]; /// SBR Huffman book `ENV30_F`: (length, code, delta) by codeword. pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [ (1, 0, 0), (2, 2, -1), - (3, 6, 0), + (3, 6, 1), (4, 14, -2), - (5, 30, 0), + (5, 30, 2), (6, 62, -3), - (8, 252, 0), + (8, 252, 3), (8, 253, -4), - (9, 508, 0), + (9, 508, 4), (9, 509, -5), - (10, 1020, 0), + (10, 1020, 5), (10, 1021, -6), - (11, 2044, 0), + (11, 2044, 6), (11, 2045, -7), - (12, 4092, 0), + (12, 4092, 7), (12, 4093, -8), - (13, 8188, 0), - (14, 16378, 0), + (13, 8188, 8), + (14, 16378, 9), (14, 16379, -9), (15, 32760, -10), - (15, 32761, 0), - (15, 32762, 0), + (15, 32761, 10), + (15, 32762, 11), (16, 65526, -11), (16, 65527, -12), - (16, 65528, 0), - (16, 65529, 0), + (16, 65528, 12), + (16, 65529, 13), (17, 131060, -13), (17, 131061, -15), - (17, 131062, 0), - (17, 131063, 0), + (17, 131062, 14), + (17, 131063, 15), (18, 262128, -14), - (18, 262129, 0), + (18, 262129, 18), (18, 262130, -18), (18, 262131, -24), (18, 262132, -19), - (18, 262133, 0), - (18, 262134, 0), + (18, 262133, 16), + (18, 262134, 17), (19, 524270, -22), (19, 524271, -21), (19, 524272, -16), - (19, 524273, 0), - (19, 524274, 0), - (19, 524275, 0), - (19, 524276, 0), + (19, 524273, 20), + (19, 524274, 21), + (19, 524275, 22), + (19, 524276, 25), (19, 524277, -23), (19, 524278, -20), - (19, 524279, 0), + (19, 524279, 24), (20, 1048560, -31), (20, 1048561, -30), (20, 1048562, -29), @@ -383,14 +390,14 @@ pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [ (20, 1048565, -26), (20, 1048566, -25), (20, 1048567, -17), - (20, 1048568, 0), - (20, 1048569, 0), - (20, 1048570, 0), - (20, 1048571, 0), - (20, 1048572, 0), - (20, 1048573, 0), - (20, 1048574, 0), - (20, 1048575, 0), + (20, 1048568, 19), + (20, 1048569, 23), + (20, 1048570, 26), + (20, 1048571, 27), + (20, 1048572, 28), + (20, 1048573, 29), + (20, 1048574, 30), + (20, 1048575, 31), ]; /// SBR Huffman book `NOISE_T`: (length, code, delta) by codeword. @@ -636,14 +643,14 @@ pub(crate) static ENVB15_T: [(u8, u32, i32); 49] = [ /// SBR Huffman book `ENVB30_T`: (length, code, delta) by codeword. pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [ (1, 0, 0), - (2, 2, 0), + (2, 2, 1), (3, 6, -1), (4, 14, -2), - (5, 30, 0), - (6, 62, 0), + (5, 30, 2), + (6, 62, 3), (7, 126, -3), (8, 254, -4), - (9, 510, 0), + (9, 510, 4), (12, 4088, -5), (13, 8178, -12), (13, 8179, -11), @@ -652,30 +659,30 @@ pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [ (13, 8182, -8), (13, 8183, -7), (13, 8184, -6), - (13, 8185, 0), - (13, 8186, 0), - (13, 8187, 0), - (13, 8188, 0), - (13, 8189, 0), - (13, 8190, 0), - (14, 16382, 0), - (14, 16383, 0), + (13, 8185, 5), + (13, 8186, 6), + (13, 8187, 7), + (13, 8188, 8), + (13, 8189, 9), + (13, 8190, 10), + (14, 16382, 11), + (14, 16383, 12), ]; /// SBR Huffman book `ENVB30_F`: (length, code, delta) by codeword. pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [ (1, 0, 0), (2, 2, -1), - (3, 6, 0), + (3, 6, 1), (4, 14, -2), - (5, 30, 0), - (6, 62, 0), + (5, 30, 2), + (6, 62, 3), (7, 126, -3), (8, 254, -4), - (9, 510, 0), + (9, 510, 4), (11, 2044, -5), - (12, 4090, 0), - (13, 8182, 0), + (12, 4090, 5), + (13, 8182, 6), (13, 8183, -12), (13, 8184, -11), (13, 8185, -10), @@ -683,12 +690,12 @@ pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [ (13, 8187, -8), (14, 16376, -7), (14, 16377, -6), - (14, 16378, 0), - (14, 16379, 0), - (14, 16380, 0), - (14, 16381, 0), - (14, 16382, 0), - (14, 16383, 0), + (14, 16378, 7), + (14, 16379, 8), + (14, 16380, 9), + (14, 16381, 10), + (14, 16382, 11), + (14, 16383, 12), ]; /// SBR Huffman book `NOISEB_T`: (length, code, delta) by codeword. diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index e8128722..da9eeae4 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -305,6 +305,19 @@ fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, if !found { best = coarse_best; } + // A winning lag at the search bound is not a measurement (the true + // alignment may lie outside it): widen once to `SEARCH_LAG_MAX`, and if + // it still sits at the edge fail here rather than hand any caller a + // noise-driven number (instrument-at-bound class). + if at_edge && lag_max < SEARCH_LAG_MAX { + return best_lag_correlation_ex(ours, theirs, SEARCH_LAG_MAX); + } + assert!( + !at_edge, + "winning lag {} sits at the +/-{lag_max} search bound -- the true \ + alignment is outside the search, corr {:.6} is noise, not a measurement", + best.0, best.2 + ); (best.0, best.2, at_edge) } @@ -2249,20 +2262,10 @@ fn full_chain_low_band_matches_own_core() { // without exposing the well-behaved one to the wider bound's // noise floor. const WIDE_LAG_MAX: i64 = 20_000; - let (mut lag, mut corr, mut at_edge) = best_lag_correlation_ex(&ol, &ul, WIDE_LAG_MAX); - let mut bound = WIDE_LAG_MAX; - if at_edge { - bound = SEARCH_LAG_MAX; - (lag, corr, at_edge) = best_lag_correlation_ex(&ol, &ul, SEARCH_LAG_MAX); - } + // `_ex` itself widens to `SEARCH_LAG_MAX` and asserts when the + // winner sits at the bound. + let (lag, corr, _) = best_lag_correlation_ex(&ol, &ul, WIDE_LAG_MAX); println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}"); - assert!( - !at_edge, - "{} ch{ch}: winning lag {lag} sits at the +/-{bound} \ - search bound -- the true alignment is outside the search, \ - corr {corr:.6} is noise, not a measurement", - c.path.display() - ); assert!( corr >= 0.99, "{} ch{ch}: full-chain low band vs our own core-only decode \ @@ -3380,12 +3383,12 @@ fn sbr_actual_noise_fraction() { // invoke this test by name, not as part of a parallel `cargo test` run. unsafe { std::env::remove_var("EC_AAC_SBR_NOISE_ZERO"); - std::env::set_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG", "1"); + std::env::set_var("EC_AAC_SBR_NOISE_FRACTION", "1"); } let (ours_on, _, rate) = our_decode(&path, 0).expect("our_decode works (noise on)"); let bookkept = ec_aac::noise_fraction_table(); unsafe { - std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG"); + std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION"); std::env::set_var("EC_AAC_SBR_NOISE_ZERO", "1"); } let (ours_off, _, _) = our_decode(&path, 0).expect("our_decode works (noise zeroed)"); diff --git a/scripts/aac-tables/sbrvalues.py b/scripts/aac-tables/sbrvalues.py new file mode 100644 index 00000000..e653c935 --- /dev/null +++ b/scripts/aac-tables/sbrvalues.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Reads the delta every 3.0 dB envelope codeword carries off the reference +decoder's `env_facs_q V is invalid` range check, by ACCUMULATION. + +`sbrtables.py --stage values` applies a codeword once to a raw start value and +reads the delta from the out-of-range complaint. The 3.0 dB books ride a 6-bit +(5-bit balance) raw field but are checked against a 7-bit ceiling, so a single +positive 3.0 dB delta never trips it and every one was emitted as 0 +(ENV30_F/ENV30_T/ENVB30_F/ENVB30_T: 32/32/13/13 zeros). + +The check sees the ACCUMULATED value, and delta-time coding accumulates across +envelopes and frames: a `_T` codeword repeated for enough envelopes walks any +non-zero delta out of range, and a `_F` codeword is walked out by trusted +negative `_T` steps riding after it. The complaint reports the first value out +of range (mod 256); a tiny simulator predicts that value for every candidate +delta and the one candidate that reproduces every probe is the answer. Trusted +negative entries go through the same readout and must come back unchanged. + +Writes the values in place into crates/ec-aac/src/sbr_tables.rs. + + python3 scripts/aac-tables/sbrvalues.py +""" + +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import sbrtables as T # noqa: E402 +from sbrprobe import silent # noqa: E402 + +RS = os.path.join(T.ROOT, "crates", "ec-aac", "src", "sbr_tables.rs") +KINDS = ["ENV30_T", "ENVB30_T", "ENV30_F", "ENVB30_F"] +INVALID = re.compile(r"env_facs_q (-?\d+) is invalid") +RUNS = 40 + + +def load_books(): + src = open(RS).read() + books = {} + for m in re.finditer(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", src, re.S): + books[m.group(1)] = { + (int(a), int(b)): int(c) + for a, b, c in re.findall(r"\((\d+), (\d+), (-?\d+)\)", m.group(2)) + } + return books + + +def by_value(book, v): + return T.as_bits(*next(lc for lc, d in book.items() if d == v)) + + +def first_invalid(err): + m = INVALID.search(err) + return int(m.group(1)) if m else None + + +def simulate(steps, scale, raw): + """First out-of-range `scale * value` (mod 256) along `raw + cumsum(steps)`.""" + acc = raw + for s in steps: + acc += s + v = scale * acc + if v < 0 or v > 127: + return v % 256 + return None + + +def probe_t(kind, book, cfg, tables, word, raw, balance): + """env0 F-coded from `raw` (no F slots: one band), env1 T-coded with `word`, + then RUNS frames with both envelopes T-coded with `word`. ch0 of a coupled + pair rides trusted zero words.""" + key = "env0b" if balance else "env0" + start = dict(cfg, **{key: [raw] * 8}) + run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8}) + z = by_value(T_BOOK, 0) + ch0 = [z] if balance else [] + frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word])] + frames += [T.frame(run, tables, ch0 * 2 + [word, word])] * RUNS + return b"".join(frames), [None] + [None] * (2 * RUNS) # steps = word each + + +def probe_f(kind, book, cfg, tables, word, raw, balance, step_book, step): + """env0 F-coded from `raw` with `word` in band 1, env1 T-coded with band 0 + zero and band 1 `step`, then RUNS frames of the same T pair.""" + key = "env0b" if balance else "env0" + start = dict(cfg, df_env=[0, 1] + [0] * 6, **{key: [raw] * 8}) + run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8}) + zf, zt = by_value(F_BOOK, 0), by_value(T_BOOK, 0) + s = by_value(step_book, step) + zs = by_value(T_BOOK if balance else step_book, 0) + ch0 = [zf, zt, zt] if balance else [] + ch0r = [zt, zt, zt, zt] if balance else [] + frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word, zs, s])] + frames += [T.frame(run, tables, ch0r + [zs, s, zs, s])] * 6 + return b"".join(frames), [None] + [step] * 13 + + +def read_book(oracle, kind, books): + book = books[kind] + balance = kind.startswith("ENVB") + scale = 2 if balance else 1 + span = 12 if balance else 31 + cands = range(-span, span + 1) + cfg, tables = T.recipe_config(kind) + raw_max = 31 if balance else 63 + out = {} + for lc in sorted(book): + word = T.as_bits(*lc) + obs = [] # (steps template, raw, observed) + alive = set(cands) + # Probe until exactly one candidate reproduces every observation. + if kind.endswith("_T"): + plan = [("t", raw, None) for raw in range(raw_max, -1, -1)] + else: + sb = books["ENVB30_T" if balance else "ENV30_T"] + neg = sorted({d for d in sb.values() if d < 0}) + plan = [("f", raw_max, s) for s in neg[:4]] + [("f", 0, s) for s in neg[:4]] + for mode, raw, s in plan: + if mode == "t": + data, steps = probe_t(kind, book, cfg, tables, word, raw, balance) + else: + data, steps = probe_f(kind, book, cfg, tables, word, raw, balance, sb, s) + err = oracle.one(f"acc:{kind}:{lc}:{mode}:{raw}:{s}", data) + got = first_invalid(err) + alive = { + d for d in alive + if simulate([d if x is None else x for x in steps], scale, raw) == got + } + if len(alive) <= 1: + break + if len(alive) != 1: + print(f" {kind} {lc}: UNRESOLVED, candidates {sorted(alive)}") + continue + d = next(iter(alive)) + old = book[lc] + flag = "" if old == d else (" (was 0)" if old == 0 else f" <-- DISAGREES with {old}") + print(f" {kind} {lc}: {d:>4}{flag}") + out[lc] = d + vals = sorted(out.values()) + complete = vals == list(cands) and len(out) == len(book) + print(f"{kind}: {len(out)}/{len(book)} read, values {'complete -%d..%d once each' % (span, span) if complete else 'NOT a permutation: ' + str(vals)}") + return out, complete + + +def main(): + books = load_books() + global F_BOOK, T_BOOK + F_BOOK, T_BOOK = books["ENV30_F"], books["ENV30_T"] + oracle = T.Oracle(12) + out = {} + try: + for kind in KINDS: + vals, complete = read_book(oracle, kind, books) + if complete: + out[kind] = vals + books[kind] = vals # later books ride on these + if kind == "ENV30_T": + T_BOOK = vals + finally: + oracle.save() + src = open(RS).read() + + def patch_block(m): + name, body = m.group(1), m.group(2) + if name not in out: + return m.group(0) + new = re.sub( + r"\((\d+), (\d+), (-?\d+)\)", + lambda t: f"({t.group(1)}, {t.group(2)}, {out[name][(int(t.group(1)), int(t.group(2)))]})", + body, + ) + return m.group(0).replace(body, new) + + src = re.sub(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", patch_block, src, flags=re.S) + open(RS, "w").write(src) + print(f"wrote {RS}: {sorted(out)}") + + +if __name__ == "__main__": + main() diff --git a/scripts/aac-tables/sbrvalues_audio.py b/scripts/aac-tables/sbrvalues_audio.py deleted file mode 100644 index 3376c742..00000000 --- a/scripts/aac-tables/sbrvalues_audio.py +++ /dev/null @@ -1,202 +0,0 @@ -#!/usr/bin/env python3 -"""Reads the delta each 3.0 dB envelope codeword carries off the reference -decoder's AUDIO, not its range check. - -`sbrtables.py --stage values` learns a codeword's delta from the decoder's -scalefactor range complaint, bisecting the raw start value. That only sees a -delta that pushes the accumulated value OUT of range: the 3.0 dB books ride a -6-bit (5-bit balance) raw field but are range-checked against the 1.5 dB -books' 7-bit ceiling, so no positive 3.0 dB delta can ever trip it and every -one was emitted as 0 (ENV30_F/ENV30_T/ENVB30_F/ENVB30_T: 32/32/13/13 zeros). - -Here the same single-codeword probe frames are decoded to PCM instead and the -delta is the log2 energy ratio between the two bands (`_F` books) or the two -envelopes (`_T` books) it separates -- a 3 dB step per unit, trivially -resolvable. Negative deltas the range check DID see are re-read the same way -as a cross-check. Writes the corrected values back into sbr_tables.rs. -""" - -import math -import os -import re -import subprocess -import sys - -import numpy as np - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import sbrtables as T # noqa: E402 - -RS = os.path.join(T.ROOT, "crates", "ec-aac", "src", "sbr_tables.rs") -KINDS = ["ENV30_F", "ENV30_T", "ENVB30_F", "ENVB30_T"] - - -def load_books(): - src = open(RS).read() - books = {} - for m in re.finditer(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", src, re.S): - books[m.group(1)] = { - (int(a), int(b)): int(c) - for a, b, c in re.findall(r"\((\d+), (\d+), (-?\d+)\)", m.group(2)) - } - return books - - -def decode(data, channels): - src = f"/tmp/sbrvalues-{os.getpid()}.aac" - with open(src, "wb") as f: - f.write(data) - r = subprocess.run( - ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", str(channels), "-"], - capture_output=True, - ) - os.remove(src) - pcm = np.frombuffer(r.stdout, dtype=np.float32).reshape(-1, channels) - return pcm - - -def band_energy(x, rate, k0, k1): - """Energy of 64-band QMF bands k0..k1 (at the doubled output rate).""" - spec = np.abs(np.fft.rfft(x)) ** 2 - hz = rate / len(x) - band_hz = rate / 128.0 - lo, hi = int(k0 * band_hz / hz), int(k1 * band_hz / hz) - return float(spec[lo:hi].sum()) - - -def frame(cfg, tables, words): - """`sbrtables.frame` with the FIL payload padded out to its byte count - and that count written exactly: the length probes deliberately under- - declare it to provoke the parser's byte-count complaint, but a decoder - that is to produce AUDIO must find END right where the count says.""" - from sbrprobe import BitW, adts - - cpe = cfg.get("element") == "cpe" - w = BitW() - T.core_element(w, cfg["sf_index"], 4, 2 if cpe else 1) - body = T.sbr_bits(cfg, tables, words) - bits = 4 + len(body.bits) - cnt = (bits + 7) // 8 - w.w(6, 3) # FIL - if cnt >= 15: - w.w(15, 4) - w.w(cnt - 15 + 1, 8) - else: - w.w(cnt, 4) - w.w(13, 4) # EXT_SBR_DATA - w.wbits(body.bits) - w.w(0, cnt * 8 - bits) - w.w(7, 3) # END - return adts(w.pack(pad=0), cfg["sf_index"], 2 if cpe else 1) - - -def probe(kind, cfg, tables, key, word, books, raw): - words = T.fill_words(cfg, tables, kind, word, books, extra=0) - v = dict(cfg) - arr = list(v[key]) - arr[0] = raw - v[key] = arr - v["limiter_gains"] = 3 - data = frame(v, tables, words) * 8 - ch = 2 if cfg.get("element") == "cpe" else 1 - pcm = decode(data, ch) - return pcm - - -def main(): - books = load_books() - out = {} - for kind in KINDS: - made = T.values_config(kind) - if made is None: - print(f"{kind}: no config") - continue - cfg, tables, key, width, scale = made - balance = kind.startswith("ENVB") - if not balance: - # A mono SBR stream is re-laid-out as implicit stereo by the - # reference decoder and then dropped; ride a CPE instead (both - # channels use the same books, the word lands in ch1). - cfg = dict(cfg, element="cpe", coupling=0) - rate = T.SBR_RATE_FOR_SF[cfg["sf_index"]] - raw = 12 if balance else 30 - f_high = tables["f_high"] - frame = 2048 - codes = sorted(books[kind]) - # Alignment for _T books: the trusted -1 codeword (second envelope - # 3 dB below the first) picks the frame phase. - offset = None - if kind.endswith("_T"): - cal = next(lc for lc in codes if books[kind][lc] == -1) - pcm = probe(kind, cfg, tables, key, T.as_bits(*cal), books, raw) - x = pcm[:, 1] - best = None - for o in range(0, frame, 64): - a = b = 0.0 - for s in range(3 * frame + o, len(x) - frame, frame): - a += float((x[s : s + 1024] ** 2).sum()) - b += float((x[s + 1024 : s + 2048] ** 2).sum()) - c = math.log2(b / a) if a > 0 and b > 0 else 0.0 - if best is None or c < best[0]: - best = (c, o) - offset = best[1] - print(f"{kind}: alignment offset {offset}, calibration log2 ratio {best[0]:.3f} (expect -1)") - got = {} - for lc in codes: - pcm = probe(kind, cfg, tables, key, T.as_bits(*lc), books, raw) - if kind.endswith("_F"): - x = pcm[3 * frame :] - e = [ - [band_energy(x[:, c], rate, f_high[b], f_high[b + 1]) for b in (0, 1)] - for c in range(x.shape[1]) - ] - # Both envelopes of the `_F` probe carry the same row (the - # second is T-coded with the trusted 0 codeword), so the - # whole-signal band ratio is the delta itself. - if balance: - rho = (e[0][1] / e[1][1]) / (e[0][0] / e[1][0]) - d = math.log2(rho) / 2 - else: - d = math.log2(e[1][1] / e[1][0]) - else: - x = pcm - a = b = 0.0 - al = bl = 0.0 - for s in range(3 * frame + offset, len(x) - frame, frame): - a += float((x[s : s + 1024, 1] ** 2).sum()) - b += float((x[s + 1024 : s + 2048, 1] ** 2).sum()) - al += float((x[s : s + 1024, 0] ** 2).sum()) - bl += float((x[s + 1024 : s + 2048, 0] ** 2).sum()) - if balance: - # ch1 carries the balance word: its L/R swing against ch0. - rho = (bl / b) / (al / a) - d = math.log2(rho) / 2 - else: - d = math.log2(b / a) - got[lc] = d - old = books[kind][lc] - flag = "" if (old != 0 and abs(d - old) < 0.3) or (old == 0) else " <-- DISAGREES with range-check value" - print(f" {kind} {lc}: old {old:>4} read {d:7.3f}{flag}") - out[kind] = got - # Rewrite: every codeword takes the rounded readout. - src = open(RS).read() - # Targeted replacement per book block. - def patch_block(m): - name, body = m.group(1), m.group(2) - if name not in out: - return m.group(0) - def sub(t): - l, c, v = int(t.group(1)), int(t.group(2)), int(t.group(3)) - d = out[name].get((l, c)) - if d is None or math.isnan(d): - return t.group(0) - return f"({l}, {c}, {round(d)})" - return m.group(0).replace(body, re.sub(r"\((\d+), (\d+), (-?\d+)\)", sub, body)) - src = re.sub(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", patch_block, src, flags=re.S) - open(RS, "w").write(src) - print(f"wrote {RS}") - - -if __name__ == "__main__": - main()