forge
Explore
Log in

Don't you dare go Hollow

3 dB envelope/balance books carry their positive deltas (accumulation readout)

Browse files at this commit

060a762c5314afe6249d5fd4002ce31cd2fbf825Ahmet Kaan GümüşParent: 46f3447
  • fix
    • 3 dB envelope/balance books carry their positive deltas (accumulation readout)
    • lag search asserts off-bound
    • noise-fraction env name
Show full message
fix(aac-sbr): 3 dB envelope/balance books carry their positive deltas (accumulation readout); lag search asserts off-bound; noise-fraction env name

ENV30_F/ENV30_T/ENVB30_F/ENVB30_T had 0 for every positive delta: the
one-shot range-check readout cannot see a +d on the 6-bit 3 dB raw field
against the 7-bit ceiling. scripts/aac-tables/sbrvalues.py walks each
codeword out of range by delta-time accumulation instead (repeated T
frames; F words followed by trusted negative T steps) and picks the one
delta a simulator of the decoder's complaint reproduces on every probe.
All four books read back as exact permutations of -31..31 / -12..12 and
every trusted negative entry reproduced unchanged. reeln HF level per
band 0.58-0.93 -> 0.99-1.02 up to 22 kHz.

best_lag_correlation_ex widens to SEARCH_LAG_MAX on an at-edge winner and
asserts !at_edge for every caller; the noise-fraction probe now sets the
env name sbr_env actually reads.
crates/ec-aac/src/sbr_tables.rsmodified+93 -86
@@ -7,6 +7,13 @@
7 //! `env_facs_q`/`noise_facs_q` range check reads the delta value each7 //! `env_facs_q`/`noise_facs_q` range check reads the delta value each
8 //! codeword carries off the same payload. Every table here closed with8 //! codeword carries off the same payload. Every table here closed with
9 //! a Kraft sum of exactly 1 (asserted below).9 //! a Kraft sum of exactly 1 (asserted below).
10+//!
11+//! GENERATED: books by `sbrtables.py --stage values`, then the four 3.0 dB
12+//! books (`ENV30_F`, `ENV30_T`, `ENVB30_F`, `ENVB30_T`) re-valued in place by
13+//! `scripts/aac-tables/sbrvalues.py`, which walks each codeword's delta out
14+//! of range by delta-time ACCUMULATION (a single +d on the 6-bit 3 dB raw
15+//! field never reaches the 7-bit ceiling, so the one-shot stage read every
16+//! positive 3 dB delta as 0). Do not hand-edit the books.
10 #![allow(dead_code)]17 #![allow(dead_code)]
11 18
12 /// SBR Huffman book `ENV15_F`: (length, code, delta) by codeword.19 /// SBR Huffman book `ENV15_F`: (length, code, delta) by codeword.
@@ -263,31 +270,31 @@ pub(crate) static ENV15_T: [(u8, u32, i32); 121] = [
263 pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [270 pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [
264 (1, 0, 0),271 (1, 0, 0),
265 (2, 2, -1),272 (2, 2, -1),
266- (3, 6, 0),273+ (3, 6, 1),
267 (4, 14, -2),274 (4, 14, -2),
268- (5, 30, 0),275+ (5, 30, 2),
269 (6, 62, -3),276 (6, 62, -3),
270- (7, 126, 0),277+ (7, 126, 3),
271 (8, 254, -4),278 (8, 254, -4),
272- (9, 510, 0),279+ (9, 510, 4),
273 (11, 2044, -5),280 (11, 2044, -5),
274- (11, 2045, 0),281+ (11, 2045, 5),
275 (12, 4092, -6),282 (12, 4092, -6),
276 (13, 8186, -7),283 (13, 8186, -7),
277- (13, 8187, 0),284+ (13, 8187, 6),
278 (14, 16376, -8),285 (14, 16376, -8),
279- (14, 16377, 0),286+ (14, 16377, 7),
280 (14, 16378, -9),287 (14, 16378, -9),
281 (14, 16379, -10),288 (14, 16379, -10),
282- (14, 16380, 0),289+ (14, 16380, 8),
283- (15, 32762, 0),290+ (15, 32762, 9),
284- (16, 65526, 0),291+ (16, 65526, 10),
285 (16, 65527, -13),292 (16, 65527, -13),
286 (16, 65528, -11),293 (16, 65528, -11),
287 (16, 65529, -12),294 (16, 65529, -12),
288 (17, 131060, -14),295 (17, 131060, -14),
289- (17, 131061, 0),296+ (17, 131061, 11),
290- (18, 262124, 0),297+ (18, 262124, 12),
291 (18, 262125, -31),298 (18, 262125, -31),
292 (18, 262126, -30),299 (18, 262126, -30),
293 (19, 524254, -29),300 (19, 524254, -29),
@@ -305,76 +312,76 @@ pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [
305 (19, 524266, -17),312 (19, 524266, -17),
306 (19, 524267, -16),313 (19, 524267, -16),
307 (19, 524268, -15),314 (19, 524268, -15),
308- (19, 524269, 0),315+ (19, 524269, 13),
309- (19, 524270, 0),316+ (19, 524270, 14),
310- (19, 524271, 0),317+ (19, 524271, 15),
311- (19, 524272, 0),318+ (19, 524272, 16),
312- (19, 524273, 0),319+ (19, 524273, 17),
313- (19, 524274, 0),320+ (19, 524274, 18),
314- (19, 524275, 0),321+ (19, 524275, 19),
315- (19, 524276, 0),322+ (19, 524276, 20),
316- (19, 524277, 0),323+ (19, 524277, 21),
317- (19, 524278, 0),324+ (19, 524278, 22),
318- (19, 524279, 0),325+ (19, 524279, 23),
319- (19, 524280, 0),326+ (19, 524280, 24),
320- (19, 524281, 0),327+ (19, 524281, 25),
321- (19, 524282, 0),328+ (19, 524282, 26),
322- (19, 524283, 0),329+ (19, 524283, 27),
323- (19, 524284, 0),330+ (19, 524284, 28),
324- (19, 524285, 0),331+ (19, 524285, 29),
325- (19, 524286, 0),332+ (19, 524286, 30),
326- (19, 524287, 0),333+ (19, 524287, 31),
327 ];334 ];
328 335
329 /// SBR Huffman book `ENV30_F`: (length, code, delta) by codeword.336 /// SBR Huffman book `ENV30_F`: (length, code, delta) by codeword.
330 pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [337 pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [
331 (1, 0, 0),338 (1, 0, 0),
332 (2, 2, -1),339 (2, 2, -1),
333- (3, 6, 0),340+ (3, 6, 1),
334 (4, 14, -2),341 (4, 14, -2),
335- (5, 30, 0),342+ (5, 30, 2),
336 (6, 62, -3),343 (6, 62, -3),
337- (8, 252, 0),344+ (8, 252, 3),
338 (8, 253, -4),345 (8, 253, -4),
339- (9, 508, 0),346+ (9, 508, 4),
340 (9, 509, -5),347 (9, 509, -5),
341- (10, 1020, 0),348+ (10, 1020, 5),
342 (10, 1021, -6),349 (10, 1021, -6),
343- (11, 2044, 0),350+ (11, 2044, 6),
344 (11, 2045, -7),351 (11, 2045, -7),
345- (12, 4092, 0),352+ (12, 4092, 7),
346 (12, 4093, -8),353 (12, 4093, -8),
347- (13, 8188, 0),354+ (13, 8188, 8),
348- (14, 16378, 0),355+ (14, 16378, 9),
349 (14, 16379, -9),356 (14, 16379, -9),
350 (15, 32760, -10),357 (15, 32760, -10),
351- (15, 32761, 0),358+ (15, 32761, 10),
352- (15, 32762, 0),359+ (15, 32762, 11),
353 (16, 65526, -11),360 (16, 65526, -11),
354 (16, 65527, -12),361 (16, 65527, -12),
355- (16, 65528, 0),362+ (16, 65528, 12),
356- (16, 65529, 0),363+ (16, 65529, 13),
357 (17, 131060, -13),364 (17, 131060, -13),
358 (17, 131061, -15),365 (17, 131061, -15),
359- (17, 131062, 0),366+ (17, 131062, 14),
360- (17, 131063, 0),367+ (17, 131063, 15),
361 (18, 262128, -14),368 (18, 262128, -14),
362- (18, 262129, 0),369+ (18, 262129, 18),
363 (18, 262130, -18),370 (18, 262130, -18),
364 (18, 262131, -24),371 (18, 262131, -24),
365 (18, 262132, -19),372 (18, 262132, -19),
366- (18, 262133, 0),373+ (18, 262133, 16),
367- (18, 262134, 0),374+ (18, 262134, 17),
368 (19, 524270, -22),375 (19, 524270, -22),
369 (19, 524271, -21),376 (19, 524271, -21),
370 (19, 524272, -16),377 (19, 524272, -16),
371- (19, 524273, 0),378+ (19, 524273, 20),
372- (19, 524274, 0),379+ (19, 524274, 21),
373- (19, 524275, 0),380+ (19, 524275, 22),
374- (19, 524276, 0),381+ (19, 524276, 25),
375 (19, 524277, -23),382 (19, 524277, -23),
376 (19, 524278, -20),383 (19, 524278, -20),
377- (19, 524279, 0),384+ (19, 524279, 24),
378 (20, 1048560, -31),385 (20, 1048560, -31),
379 (20, 1048561, -30),386 (20, 1048561, -30),
380 (20, 1048562, -29),387 (20, 1048562, -29),
@@ -383,14 +390,14 @@ pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [
383 (20, 1048565, -26),390 (20, 1048565, -26),
384 (20, 1048566, -25),391 (20, 1048566, -25),
385 (20, 1048567, -17),392 (20, 1048567, -17),
386- (20, 1048568, 0),393+ (20, 1048568, 19),
387- (20, 1048569, 0),394+ (20, 1048569, 23),
388- (20, 1048570, 0),395+ (20, 1048570, 26),
389- (20, 1048571, 0),396+ (20, 1048571, 27),
390- (20, 1048572, 0),397+ (20, 1048572, 28),
391- (20, 1048573, 0),398+ (20, 1048573, 29),
392- (20, 1048574, 0),399+ (20, 1048574, 30),
393- (20, 1048575, 0),400+ (20, 1048575, 31),
394 ];401 ];
395 402
396 /// SBR Huffman book `NOISE_T`: (length, code, delta) by codeword.403 /// SBR Huffman book `NOISE_T`: (length, code, delta) by codeword.
@@ -636,14 +643,14 @@ pub(crate) static ENVB15_T: [(u8, u32, i32); 49] = [
636 /// SBR Huffman book `ENVB30_T`: (length, code, delta) by codeword.643 /// SBR Huffman book `ENVB30_T`: (length, code, delta) by codeword.
637 pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [644 pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [
638 (1, 0, 0),645 (1, 0, 0),
639- (2, 2, 0),646+ (2, 2, 1),
640 (3, 6, -1),647 (3, 6, -1),
641 (4, 14, -2),648 (4, 14, -2),
642- (5, 30, 0),649+ (5, 30, 2),
643- (6, 62, 0),650+ (6, 62, 3),
644 (7, 126, -3),651 (7, 126, -3),
645 (8, 254, -4),652 (8, 254, -4),
646- (9, 510, 0),653+ (9, 510, 4),
647 (12, 4088, -5),654 (12, 4088, -5),
648 (13, 8178, -12),655 (13, 8178, -12),
649 (13, 8179, -11),656 (13, 8179, -11),
@@ -652,30 +659,30 @@ pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [
652 (13, 8182, -8),659 (13, 8182, -8),
653 (13, 8183, -7),660 (13, 8183, -7),
654 (13, 8184, -6),661 (13, 8184, -6),
655- (13, 8185, 0),662+ (13, 8185, 5),
656- (13, 8186, 0),663+ (13, 8186, 6),
657- (13, 8187, 0),664+ (13, 8187, 7),
658- (13, 8188, 0),665+ (13, 8188, 8),
659- (13, 8189, 0),666+ (13, 8189, 9),
660- (13, 8190, 0),667+ (13, 8190, 10),
661- (14, 16382, 0),668+ (14, 16382, 11),
662- (14, 16383, 0),669+ (14, 16383, 12),
663 ];670 ];
664 671
665 /// SBR Huffman book `ENVB30_F`: (length, code, delta) by codeword.672 /// SBR Huffman book `ENVB30_F`: (length, code, delta) by codeword.
666 pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [673 pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [
667 (1, 0, 0),674 (1, 0, 0),
668 (2, 2, -1),675 (2, 2, -1),
669- (3, 6, 0),676+ (3, 6, 1),
670 (4, 14, -2),677 (4, 14, -2),
671- (5, 30, 0),678+ (5, 30, 2),
672- (6, 62, 0),679+ (6, 62, 3),
673 (7, 126, -3),680 (7, 126, -3),
674 (8, 254, -4),681 (8, 254, -4),
675- (9, 510, 0),682+ (9, 510, 4),
676 (11, 2044, -5),683 (11, 2044, -5),
677- (12, 4090, 0),684+ (12, 4090, 5),
678- (13, 8182, 0),685+ (13, 8182, 6),
679 (13, 8183, -12),686 (13, 8183, -12),
680 (13, 8184, -11),687 (13, 8184, -11),
681 (13, 8185, -10),688 (13, 8185, -10),
@@ -683,12 +690,12 @@ pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [
683 (13, 8187, -8),690 (13, 8187, -8),
684 (14, 16376, -7),691 (14, 16376, -7),
685 (14, 16377, -6),692 (14, 16377, -6),
686- (14, 16378, 0),693+ (14, 16378, 7),
687- (14, 16379, 0),694+ (14, 16379, 8),
688- (14, 16380, 0),695+ (14, 16380, 9),
689- (14, 16381, 0),696+ (14, 16381, 10),
690- (14, 16382, 0),697+ (14, 16382, 11),
691- (14, 16383, 0),698+ (14, 16383, 12),
692 ];699 ];
693 700
694 /// SBR Huffman book `NOISEB_T`: (length, code, delta) by codeword.701 /// SBR Huffman book `NOISEB_T`: (length, code, delta) by codeword.
crates/ec-aac/tests/sbr_real_library.rsmodified+18 -15
@@ -305,6 +305,19 @@ fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64,
305 if !found {305 if !found {
306 best = coarse_best;306 best = coarse_best;
307 }307 }
308+ // A winning lag at the search bound is not a measurement (the true
309+ // alignment may lie outside it): widen once to `SEARCH_LAG_MAX`, and if
310+ // it still sits at the edge fail here rather than hand any caller a
311+ // noise-driven number (instrument-at-bound class).
312+ if at_edge && lag_max < SEARCH_LAG_MAX {
313+ return best_lag_correlation_ex(ours, theirs, SEARCH_LAG_MAX);
314+ }
315+ assert!(
316+ !at_edge,
317+ "winning lag {} sits at the +/-{lag_max} search bound -- the true \
318+ alignment is outside the search, corr {:.6} is noise, not a measurement",
319+ best.0, best.2
320+ );
308 (best.0, best.2, at_edge)321 (best.0, best.2, at_edge)
309 }322 }
310 323
@@ -2249,20 +2262,10 @@ fn full_chain_low_band_matches_own_core() {
2249 // without exposing the well-behaved one to the wider bound's2262 // without exposing the well-behaved one to the wider bound's
2250 // noise floor.2263 // noise floor.
2251 const WIDE_LAG_MAX: i64 = 20_000;2264 const WIDE_LAG_MAX: i64 = 20_000;
2252- let (mut lag, mut corr, mut at_edge) = best_lag_correlation_ex(&ol, &ul, WIDE_LAG_MAX);2265+ // `_ex` itself widens to `SEARCH_LAG_MAX` and asserts when the
2253- let mut bound = WIDE_LAG_MAX;2266+ // winner sits at the bound.
2254- if at_edge {2267+ let (lag, corr, _) = best_lag_correlation_ex(&ol, &ul, WIDE_LAG_MAX);
2255- bound = SEARCH_LAG_MAX;
2256- (lag, corr, at_edge) = best_lag_correlation_ex(&ol, &ul, SEARCH_LAG_MAX);
2257- }
2258 println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}");2268 println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}");
2259- assert!(
2260- !at_edge,
2261- "{} ch{ch}: winning lag {lag} sits at the +/-{bound} \
2262- search bound -- the true alignment is outside the search, \
2263- corr {corr:.6} is noise, not a measurement",
2264- c.path.display()
2265- );
2266 assert!(2269 assert!(
2267 corr >= 0.99,2270 corr >= 0.99,
2268 "{} ch{ch}: full-chain low band vs our own core-only decode \2271 "{} ch{ch}: full-chain low band vs our own core-only decode \
@@ -3380,12 +3383,12 @@ fn sbr_actual_noise_fraction() {
3380 // invoke this test by name, not as part of a parallel `cargo test` run.3383 // invoke this test by name, not as part of a parallel `cargo test` run.
3381 unsafe {3384 unsafe {
3382 std::env::remove_var("EC_AAC_SBR_NOISE_ZERO");3385 std::env::remove_var("EC_AAC_SBR_NOISE_ZERO");
3383- std::env::set_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG", "1");3386+ std::env::set_var("EC_AAC_SBR_NOISE_FRACTION", "1");
3384 }3387 }
3385 let (ours_on, _, rate) = our_decode(&path, 0).expect("our_decode works (noise on)");3388 let (ours_on, _, rate) = our_decode(&path, 0).expect("our_decode works (noise on)");
3386 let bookkept = ec_aac::noise_fraction_table();3389 let bookkept = ec_aac::noise_fraction_table();
3387 unsafe {3390 unsafe {
3388- std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG");3391+ std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION");
3389 std::env::set_var("EC_AAC_SBR_NOISE_ZERO", "1");3392 std::env::set_var("EC_AAC_SBR_NOISE_ZERO", "1");
3390 }3393 }
3391 let (ours_off, _, _) = our_decode(&path, 0).expect("our_decode works (noise zeroed)");3394 let (ours_off, _, _) = our_decode(&path, 0).expect("our_decode works (noise zeroed)");
scripts/aac-tables/sbrvalues.pyadded+182 -0
@@ -0,0 +1,182 @@
1+#!/usr/bin/env python3
2+"""Reads the delta every 3.0 dB envelope codeword carries off the reference
3+decoder's `env_facs_q V is invalid` range check, by ACCUMULATION.
4+
5+`sbrtables.py --stage values` applies a codeword once to a raw start value and
6+reads the delta from the out-of-range complaint. The 3.0 dB books ride a 6-bit
7+(5-bit balance) raw field but are checked against a 7-bit ceiling, so a single
8+positive 3.0 dB delta never trips it and every one was emitted as 0
9+(ENV30_F/ENV30_T/ENVB30_F/ENVB30_T: 32/32/13/13 zeros).
10+
11+The check sees the ACCUMULATED value, and delta-time coding accumulates across
12+envelopes and frames: a `_T` codeword repeated for enough envelopes walks any
13+non-zero delta out of range, and a `_F` codeword is walked out by trusted
14+negative `_T` steps riding after it. The complaint reports the first value out
15+of range (mod 256); a tiny simulator predicts that value for every candidate
16+delta and the one candidate that reproduces every probe is the answer. Trusted
17+negative entries go through the same readout and must come back unchanged.
18+
19+Writes the values in place into crates/ec-aac/src/sbr_tables.rs.
20+
21+ python3 scripts/aac-tables/sbrvalues.py
22+"""
23+
24+import os
25+import re
26+import sys
27+
28+HERE = os.path.dirname(os.path.abspath(__file__))
29+sys.path.insert(0, HERE)
30+import sbrtables as T # noqa: E402
31+from sbrprobe import silent # noqa: E402
32+
33+RS = os.path.join(T.ROOT, "crates", "ec-aac", "src", "sbr_tables.rs")
34+KINDS = ["ENV30_T", "ENVB30_T", "ENV30_F", "ENVB30_F"]
35+INVALID = re.compile(r"env_facs_q (-?\d+) is invalid")
36+RUNS = 40
37+
38+
39+def load_books():
40+ src = open(RS).read()
41+ books = {}
42+ for m in re.finditer(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", src, re.S):
43+ books[m.group(1)] = {
44+ (int(a), int(b)): int(c)
45+ for a, b, c in re.findall(r"\((\d+), (\d+), (-?\d+)\)", m.group(2))
46+ }
47+ return books
48+
49+
50+def by_value(book, v):
51+ return T.as_bits(*next(lc for lc, d in book.items() if d == v))
52+
53+
54+def first_invalid(err):
55+ m = INVALID.search(err)
56+ return int(m.group(1)) if m else None
57+
58+
59+def simulate(steps, scale, raw):
60+ """First out-of-range `scale * value` (mod 256) along `raw + cumsum(steps)`."""
61+ acc = raw
62+ for s in steps:
63+ acc += s
64+ v = scale * acc
65+ if v < 0 or v > 127:
66+ return v % 256
67+ return None
68+
69+
70+def probe_t(kind, book, cfg, tables, word, raw, balance):
71+ """env0 F-coded from `raw` (no F slots: one band), env1 T-coded with `word`,
72+ then RUNS frames with both envelopes T-coded with `word`. ch0 of a coupled
73+ pair rides trusted zero words."""
74+ key = "env0b" if balance else "env0"
75+ start = dict(cfg, **{key: [raw] * 8})
76+ run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8})
77+ z = by_value(T_BOOK, 0)
78+ ch0 = [z] if balance else []
79+ frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word])]
80+ frames += [T.frame(run, tables, ch0 * 2 + [word, word])] * RUNS
81+ return b"".join(frames), [None] + [None] * (2 * RUNS) # steps = word each
82+
83+
84+def probe_f(kind, book, cfg, tables, word, raw, balance, step_book, step):
85+ """env0 F-coded from `raw` with `word` in band 1, env1 T-coded with band 0
86+ zero and band 1 `step`, then RUNS frames of the same T pair."""
87+ key = "env0b" if balance else "env0"
88+ start = dict(cfg, df_env=[0, 1] + [0] * 6, **{key: [raw] * 8})
89+ run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8})
90+ zf, zt = by_value(F_BOOK, 0), by_value(T_BOOK, 0)
91+ s = by_value(step_book, step)
92+ zs = by_value(T_BOOK if balance else step_book, 0)
93+ ch0 = [zf, zt, zt] if balance else []
94+ ch0r = [zt, zt, zt, zt] if balance else []
95+ frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word, zs, s])]
96+ frames += [T.frame(run, tables, ch0r + [zs, s, zs, s])] * 6
97+ return b"".join(frames), [None] + [step] * 13
98+
99+
100+def read_book(oracle, kind, books):
101+ book = books[kind]
102+ balance = kind.startswith("ENVB")
103+ scale = 2 if balance else 1
104+ span = 12 if balance else 31
105+ cands = range(-span, span + 1)
106+ cfg, tables = T.recipe_config(kind)
107+ raw_max = 31 if balance else 63
108+ out = {}
109+ for lc in sorted(book):
110+ word = T.as_bits(*lc)
111+ obs = [] # (steps template, raw, observed)
112+ alive = set(cands)
113+ # Probe until exactly one candidate reproduces every observation.
114+ if kind.endswith("_T"):
115+ plan = [("t", raw, None) for raw in range(raw_max, -1, -1)]
116+ else:
117+ sb = books["ENVB30_T" if balance else "ENV30_T"]
118+ neg = sorted({d for d in sb.values() if d < 0})
119+ plan = [("f", raw_max, s) for s in neg[:4]] + [("f", 0, s) for s in neg[:4]]
120+ for mode, raw, s in plan:
121+ if mode == "t":
122+ data, steps = probe_t(kind, book, cfg, tables, word, raw, balance)
123+ else:
124+ data, steps = probe_f(kind, book, cfg, tables, word, raw, balance, sb, s)
125+ err = oracle.one(f"acc:{kind}:{lc}:{mode}:{raw}:{s}", data)
126+ got = first_invalid(err)
127+ alive = {
128+ d for d in alive
129+ if simulate([d if x is None else x for x in steps], scale, raw) == got
130+ }
131+ if len(alive) <= 1:
132+ break
133+ if len(alive) != 1:
134+ print(f" {kind} {lc}: UNRESOLVED, candidates {sorted(alive)}")
135+ continue
136+ d = next(iter(alive))
137+ old = book[lc]
138+ flag = "" if old == d else (" (was 0)" if old == 0 else f" <-- DISAGREES with {old}")
139+ print(f" {kind} {lc}: {d:>4}{flag}")
140+ out[lc] = d
141+ vals = sorted(out.values())
142+ complete = vals == list(cands) and len(out) == len(book)
143+ print(f"{kind}: {len(out)}/{len(book)} read, values {'complete -%d..%d once each' % (span, span) if complete else 'NOT a permutation: ' + str(vals)}")
144+ return out, complete
145+
146+
147+def main():
148+ books = load_books()
149+ global F_BOOK, T_BOOK
150+ F_BOOK, T_BOOK = books["ENV30_F"], books["ENV30_T"]
151+ oracle = T.Oracle(12)
152+ out = {}
153+ try:
154+ for kind in KINDS:
155+ vals, complete = read_book(oracle, kind, books)
156+ if complete:
157+ out[kind] = vals
158+ books[kind] = vals # later books ride on these
159+ if kind == "ENV30_T":
160+ T_BOOK = vals
161+ finally:
162+ oracle.save()
163+ src = open(RS).read()
164+
165+ def patch_block(m):
166+ name, body = m.group(1), m.group(2)
167+ if name not in out:
168+ return m.group(0)
169+ new = re.sub(
170+ r"\((\d+), (\d+), (-?\d+)\)",
171+ lambda t: f"({t.group(1)}, {t.group(2)}, {out[name][(int(t.group(1)), int(t.group(2)))]})",
172+ body,
173+ )
174+ return m.group(0).replace(body, new)
175+
176+ src = re.sub(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", patch_block, src, flags=re.S)
177+ open(RS, "w").write(src)
178+ print(f"wrote {RS}: {sorted(out)}")
179+
180+
181+if __name__ == "__main__":
182+ main()
scripts/aac-tables/sbrvalues_audio.pydeleted+0 -202
@@ -1,202 +0,0 @@
1-#!/usr/bin/env python3
2-"""Reads the delta each 3.0 dB envelope codeword carries off the reference
3-decoder's AUDIO, not its range check.
4-
5-`sbrtables.py --stage values` learns a codeword's delta from the decoder's
6-scalefactor range complaint, bisecting the raw start value. That only sees a
7-delta that pushes the accumulated value OUT of range: the 3.0 dB books ride a
8-6-bit (5-bit balance) raw field but are range-checked against the 1.5 dB
9-books' 7-bit ceiling, so no positive 3.0 dB delta can ever trip it and every
10-one was emitted as 0 (ENV30_F/ENV30_T/ENVB30_F/ENVB30_T: 32/32/13/13 zeros).
11-
12-Here the same single-codeword probe frames are decoded to PCM instead and the
13-delta is the log2 energy ratio between the two bands (`_F` books) or the two
14-envelopes (`_T` books) it separates -- a 3 dB step per unit, trivially
15-resolvable. Negative deltas the range check DID see are re-read the same way
16-as a cross-check. Writes the corrected values back into sbr_tables.rs.
17-"""
18-
19-import math
20-import os
21-import re
22-import subprocess
23-import sys
24-
25-import numpy as np
26-
27-HERE = os.path.dirname(os.path.abspath(__file__))
28-sys.path.insert(0, HERE)
29-import sbrtables as T # noqa: E402
30-
31-RS = os.path.join(T.ROOT, "crates", "ec-aac", "src", "sbr_tables.rs")
32-KINDS = ["ENV30_F", "ENV30_T", "ENVB30_F", "ENVB30_T"]
33-
34-
35-def load_books():
36- src = open(RS).read()
37- books = {}
38- for m in re.finditer(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", src, re.S):
39- books[m.group(1)] = {
40- (int(a), int(b)): int(c)
41- for a, b, c in re.findall(r"\((\d+), (\d+), (-?\d+)\)", m.group(2))
42- }
43- return books
44-
45-
46-def decode(data, channels):
47- src = f"/tmp/sbrvalues-{os.getpid()}.aac"
48- with open(src, "wb") as f:
49- f.write(data)
50- r = subprocess.run(
51- ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", str(channels), "-"],
52- capture_output=True,
53- )
54- os.remove(src)
55- pcm = np.frombuffer(r.stdout, dtype=np.float32).reshape(-1, channels)
56- return pcm
57-
58-
59-def band_energy(x, rate, k0, k1):
60- """Energy of 64-band QMF bands k0..k1 (at the doubled output rate)."""
61- spec = np.abs(np.fft.rfft(x)) ** 2
62- hz = rate / len(x)
63- band_hz = rate / 128.0
64- lo, hi = int(k0 * band_hz / hz), int(k1 * band_hz / hz)
65- return float(spec[lo:hi].sum())
66-
67-
68-def frame(cfg, tables, words):
69- """`sbrtables.frame` with the FIL payload padded out to its byte count
70- and that count written exactly: the length probes deliberately under-
71- declare it to provoke the parser's byte-count complaint, but a decoder
72- that is to produce AUDIO must find END right where the count says."""
73- from sbrprobe import BitW, adts
74-
75- cpe = cfg.get("element") == "cpe"
76- w = BitW()
77- T.core_element(w, cfg["sf_index"], 4, 2 if cpe else 1)
78- body = T.sbr_bits(cfg, tables, words)
79- bits = 4 + len(body.bits)
80- cnt = (bits + 7) // 8
81- w.w(6, 3) # FIL
82- if cnt >= 15:
83- w.w(15, 4)
84- w.w(cnt - 15 + 1, 8)
85- else:
86- w.w(cnt, 4)
87- w.w(13, 4) # EXT_SBR_DATA
88- w.wbits(body.bits)
89- w.w(0, cnt * 8 - bits)
90- w.w(7, 3) # END
91- return adts(w.pack(pad=0), cfg["sf_index"], 2 if cpe else 1)
92-
93-
94-def probe(kind, cfg, tables, key, word, books, raw):
95- words = T.fill_words(cfg, tables, kind, word, books, extra=0)
96- v = dict(cfg)
97- arr = list(v[key])
98- arr[0] = raw
99- v[key] = arr
100- v["limiter_gains"] = 3
101- data = frame(v, tables, words) * 8
102- ch = 2 if cfg.get("element") == "cpe" else 1
103- pcm = decode(data, ch)
104- return pcm
105-
106-
107-def main():
108- books = load_books()
109- out = {}
110- for kind in KINDS:
111- made = T.values_config(kind)
112- if made is None:
113- print(f"{kind}: no config")
114- continue
115- cfg, tables, key, width, scale = made
116- balance = kind.startswith("ENVB")
117- if not balance:
118- # A mono SBR stream is re-laid-out as implicit stereo by the
119- # reference decoder and then dropped; ride a CPE instead (both
120- # channels use the same books, the word lands in ch1).
121- cfg = dict(cfg, element="cpe", coupling=0)
122- rate = T.SBR_RATE_FOR_SF[cfg["sf_index"]]
123- raw = 12 if balance else 30
124- f_high = tables["f_high"]
125- frame = 2048
126- codes = sorted(books[kind])
127- # Alignment for _T books: the trusted -1 codeword (second envelope
128- # 3 dB below the first) picks the frame phase.
129- offset = None
130- if kind.endswith("_T"):
131- cal = next(lc for lc in codes if books[kind][lc] == -1)
132- pcm = probe(kind, cfg, tables, key, T.as_bits(*cal), books, raw)
133- x = pcm[:, 1]
134- best = None
135- for o in range(0, frame, 64):
136- a = b = 0.0
137- for s in range(3 * frame + o, len(x) - frame, frame):
138- a += float((x[s : s + 1024] ** 2).sum())
139- b += float((x[s + 1024 : s + 2048] ** 2).sum())
140- c = math.log2(b / a) if a > 0 and b > 0 else 0.0
141- if best is None or c < best[0]:
142- best = (c, o)
143- offset = best[1]
144- print(f"{kind}: alignment offset {offset}, calibration log2 ratio {best[0]:.3f} (expect -1)")
145- got = {}
146- for lc in codes:
147- pcm = probe(kind, cfg, tables, key, T.as_bits(*lc), books, raw)
148- if kind.endswith("_F"):
149- x = pcm[3 * frame :]
150- e = [
151- [band_energy(x[:, c], rate, f_high[b], f_high[b + 1]) for b in (0, 1)]
152- for c in range(x.shape[1])
153- ]
154- # Both envelopes of the `_F` probe carry the same row (the
155- # second is T-coded with the trusted 0 codeword), so the
156- # whole-signal band ratio is the delta itself.
157- if balance:
158- rho = (e[0][1] / e[1][1]) / (e[0][0] / e[1][0])
159- d = math.log2(rho) / 2
160- else:
161- d = math.log2(e[1][1] / e[1][0])
162- else:
163- x = pcm
164- a = b = 0.0
165- al = bl = 0.0
166- for s in range(3 * frame + offset, len(x) - frame, frame):
167- a += float((x[s : s + 1024, 1] ** 2).sum())
168- b += float((x[s + 1024 : s + 2048, 1] ** 2).sum())
169- al += float((x[s : s + 1024, 0] ** 2).sum())
170- bl += float((x[s + 1024 : s + 2048, 0] ** 2).sum())
171- if balance:
172- # ch1 carries the balance word: its L/R swing against ch0.
173- rho = (bl / b) / (al / a)
174- d = math.log2(rho) / 2
175- else:
176- d = math.log2(b / a)
177- got[lc] = d
178- old = books[kind][lc]
179- flag = "" if (old != 0 and abs(d - old) < 0.3) or (old == 0) else " <-- DISAGREES with range-check value"
180- print(f" {kind} {lc}: old {old:>4} read {d:7.3f}{flag}")
181- out[kind] = got
182- # Rewrite: every codeword takes the rounded readout.
183- src = open(RS).read()
184- # Targeted replacement per book block.
185- def patch_block(m):
186- name, body = m.group(1), m.group(2)
187- if name not in out:
188- return m.group(0)
189- def sub(t):
190- l, c, v = int(t.group(1)), int(t.group(2)), int(t.group(3))
191- d = out[name].get((l, c))
192- if d is None or math.isnan(d):
193- return t.group(0)
194- return f"({l}, {c}, {round(d)})"
195- return m.group(0).replace(body, re.sub(r"\((\d+), (\d+), (-?\d+)\)", sub, body))
196- src = re.sub(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", patch_block, src, flags=re.S)
197- open(RS, "w").write(src)
198- print(f"wrote {RS}")
199-
200-
201-if __name__ == "__main__":
202- main()