Derive four SBR noise Huffman codebooks, black box
Browse files at this commitc53ad6b993a15d6a88ef52f9d9138bded94e7f71Parent: 0eae21c- feat
- derive four SBR noise Huffman codebooks, black box
3 changed files +499 -2
- crates/ec-aac/src/lib.rs +1 -0
- crates/ec-aac/src/sbr_tables.rs +248 -0
- scripts/aac-tables/sbrtables.py +250 -2
crates/ec-aac/src/lib.rsmodified+1 -0
| @@ -28,6 +28,7 @@ mod config; | |||
| 28 | mod decode; | 28 | mod decode; |
| 29 | mod encode; | 29 | mod encode; |
| 30 | mod huffman; | 30 | mod huffman; |
| 31 | +mod sbr_tables; | ||
| 31 | pub mod tables; | 32 | pub mod tables; |
| 32 | 33 | ||
| 33 | pub use config::{ | 34 | pub use config::{ |
crates/ec-aac/src/sbr_tables.rsadded+248 -0
| @@ -0,0 +1,248 @@ | |||
| 1 | +//! SBR (HE-AAC v1) Huffman codebooks (ISO/IEC 14496-3 §4.6.18.3.6). | ||
| 2 | +//! | ||
| 3 | +//! Derived black box from a reference decoder's own bit accounting by | ||
| 4 | +//! `scripts/aac-tables/sbrtables.py`: no source was consulted. The | ||
| 5 | +//! decoder's "Expected to read N SBR bytes actually read M" complaint | ||
| 6 | +//! reads codeword lengths off a controlled FIL payload, and its | ||
| 7 | +//! `env_facs_q`/`noise_facs_q` range check reads the delta value each | ||
| 8 | +//! codeword carries off the same payload. Every table here closed with | ||
| 9 | +//! a Kraft sum of exactly 1 (asserted below). | ||
| 10 | +#![allow(dead_code)] | ||
| 11 | + | ||
| 12 | +// Not emitted (values incomplete or book did not close): ['ENV15_F', 'ENV15_T', 'ENV30_T', 'ENV30_F', 'ENVB15_F', 'ENVB15_T', 'ENVB30_T', 'ENVB30_F'] | ||
| 13 | + | ||
| 14 | +/// SBR Huffman book `NOISE_T`: (length, code, delta) by codeword. | ||
| 15 | +pub(crate) static NOISE_T: [(u8, u32, i32); 63] = [ | ||
| 16 | + (1, 0, 0), | ||
| 17 | + (2, 2, 1), | ||
| 18 | + (3, 6, -1), | ||
| 19 | + (4, 14, -2), | ||
| 20 | + (5, 30, 2), | ||
| 21 | + (6, 62, -3), | ||
| 22 | + (8, 252, 3), | ||
| 23 | + (8, 253, -4), | ||
| 24 | + (10, 1016, 4), | ||
| 25 | + (11, 2034, -5), | ||
| 26 | + (13, 8140, 5), | ||
| 27 | + (13, 8141, 11), | ||
| 28 | + (13, 8142, -31), | ||
| 29 | + (13, 8143, -30), | ||
| 30 | + (13, 8144, -29), | ||
| 31 | + (13, 8145, -28), | ||
| 32 | + (13, 8146, -27), | ||
| 33 | + (13, 8147, -26), | ||
| 34 | + (13, 8148, -25), | ||
| 35 | + (13, 8149, -24), | ||
| 36 | + (13, 8150, -23), | ||
| 37 | + (13, 8151, -22), | ||
| 38 | + (13, 8152, -21), | ||
| 39 | + (13, 8153, -20), | ||
| 40 | + (13, 8154, -19), | ||
| 41 | + (13, 8155, -18), | ||
| 42 | + (13, 8156, -17), | ||
| 43 | + (13, 8157, -16), | ||
| 44 | + (13, 8158, -15), | ||
| 45 | + (13, 8159, -14), | ||
| 46 | + (13, 8160, -13), | ||
| 47 | + (13, 8161, -12), | ||
| 48 | + (13, 8162, -11), | ||
| 49 | + (13, 8163, -10), | ||
| 50 | + (13, 8164, -9), | ||
| 51 | + (13, 8165, -8), | ||
| 52 | + (13, 8166, -7), | ||
| 53 | + (13, 8167, -6), | ||
| 54 | + (13, 8168, 6), | ||
| 55 | + (13, 8169, 7), | ||
| 56 | + (13, 8170, 8), | ||
| 57 | + (13, 8171, 9), | ||
| 58 | + (13, 8172, 10), | ||
| 59 | + (13, 8173, 12), | ||
| 60 | + (13, 8174, 13), | ||
| 61 | + (13, 8175, 14), | ||
| 62 | + (13, 8176, 15), | ||
| 63 | + (13, 8177, 16), | ||
| 64 | + (13, 8178, 17), | ||
| 65 | + (13, 8179, 18), | ||
| 66 | + (13, 8180, 19), | ||
| 67 | + (13, 8181, 20), | ||
| 68 | + (13, 8182, 21), | ||
| 69 | + (13, 8183, 22), | ||
| 70 | + (13, 8184, 23), | ||
| 71 | + (13, 8185, 24), | ||
| 72 | + (13, 8186, 25), | ||
| 73 | + (13, 8187, 26), | ||
| 74 | + (13, 8188, 27), | ||
| 75 | + (13, 8189, 28), | ||
| 76 | + (13, 8190, 29), | ||
| 77 | + (14, 16382, 30), | ||
| 78 | + (14, 16383, 31), | ||
| 79 | +]; | ||
| 80 | + | ||
| 81 | +/// SBR Huffman book `NOISE_F`: (length, code, delta) by codeword. | ||
| 82 | +pub(crate) static NOISE_F: [(u8, u32, i32); 63] = [ | ||
| 83 | + (1, 0, 0), | ||
| 84 | + (2, 2, -1), | ||
| 85 | + (3, 6, 1), | ||
| 86 | + (4, 14, -2), | ||
| 87 | + (5, 30, 2), | ||
| 88 | + (6, 62, -3), | ||
| 89 | + (8, 252, 3), | ||
| 90 | + (8, 253, -4), | ||
| 91 | + (9, 508, 4), | ||
| 92 | + (9, 509, -5), | ||
| 93 | + (10, 1020, 5), | ||
| 94 | + (10, 1021, -6), | ||
| 95 | + (11, 2044, 6), | ||
| 96 | + (11, 2045, -7), | ||
| 97 | + (12, 4092, 7), | ||
| 98 | + (12, 4093, -8), | ||
| 99 | + (13, 8188, 8), | ||
| 100 | + (14, 16378, 9), | ||
| 101 | + (14, 16379, -9), | ||
| 102 | + (15, 32760, -10), | ||
| 103 | + (15, 32761, 10), | ||
| 104 | + (15, 32762, 11), | ||
| 105 | + (16, 65526, -11), | ||
| 106 | + (16, 65527, -12), | ||
| 107 | + (16, 65528, 12), | ||
| 108 | + (16, 65529, 13), | ||
| 109 | + (17, 131060, -13), | ||
| 110 | + (17, 131061, -15), | ||
| 111 | + (17, 131062, 14), | ||
| 112 | + (17, 131063, 15), | ||
| 113 | + (18, 262128, -14), | ||
| 114 | + (18, 262129, 18), | ||
| 115 | + (18, 262130, -18), | ||
| 116 | + (18, 262131, -24), | ||
| 117 | + (18, 262132, -19), | ||
| 118 | + (18, 262133, 16), | ||
| 119 | + (18, 262134, 17), | ||
| 120 | + (19, 524270, -22), | ||
| 121 | + (19, 524271, -21), | ||
| 122 | + (19, 524272, -16), | ||
| 123 | + (19, 524273, 20), | ||
| 124 | + (19, 524274, 21), | ||
| 125 | + (19, 524275, 22), | ||
| 126 | + (19, 524276, 25), | ||
| 127 | + (19, 524277, -23), | ||
| 128 | + (19, 524278, -20), | ||
| 129 | + (19, 524279, 24), | ||
| 130 | + (20, 1048560, -31), | ||
| 131 | + (20, 1048561, -30), | ||
| 132 | + (20, 1048562, -29), | ||
| 133 | + (20, 1048563, -28), | ||
| 134 | + (20, 1048564, -27), | ||
| 135 | + (20, 1048565, -26), | ||
| 136 | + (20, 1048566, -25), | ||
| 137 | + (20, 1048567, -17), | ||
| 138 | + (20, 1048568, 19), | ||
| 139 | + (20, 1048569, 23), | ||
| 140 | + (20, 1048570, 26), | ||
| 141 | + (20, 1048571, 27), | ||
| 142 | + (20, 1048572, 28), | ||
| 143 | + (20, 1048573, 29), | ||
| 144 | + (20, 1048574, 30), | ||
| 145 | + (20, 1048575, 31), | ||
| 146 | +]; | ||
| 147 | + | ||
| 148 | +/// SBR Huffman book `NOISEB_T`: (length, code, delta) by codeword. | ||
| 149 | +pub(crate) static NOISEB_T: [(u8, u32, i32); 25] = [ | ||
| 150 | + (1, 0, 0), | ||
| 151 | + (2, 2, -1), | ||
| 152 | + (3, 6, 1), | ||
| 153 | + (5, 28, -2), | ||
| 154 | + (6, 58, 2), | ||
| 155 | + (8, 236, -12), | ||
| 156 | + (8, 237, -11), | ||
| 157 | + (8, 238, -10), | ||
| 158 | + (8, 239, -9), | ||
| 159 | + (8, 240, -8), | ||
| 160 | + (8, 241, -7), | ||
| 161 | + (8, 242, -6), | ||
| 162 | + (8, 243, -5), | ||
| 163 | + (8, 244, -4), | ||
| 164 | + (8, 245, -3), | ||
| 165 | + (8, 246, 3), | ||
| 166 | + (8, 247, 4), | ||
| 167 | + (8, 248, 5), | ||
| 168 | + (8, 249, 6), | ||
| 169 | + (8, 250, 7), | ||
| 170 | + (8, 251, 8), | ||
| 171 | + (8, 252, 9), | ||
| 172 | + (8, 253, 10), | ||
| 173 | + (8, 254, 11), | ||
| 174 | + (8, 255, 12), | ||
| 175 | +]; | ||
| 176 | + | ||
| 177 | +/// SBR Huffman book `NOISEB_F`: (length, code, delta) by codeword. | ||
| 178 | +pub(crate) static NOISEB_F: [(u8, u32, i32); 25] = [ | ||
| 179 | + (1, 0, 0), | ||
| 180 | + (2, 2, -1), | ||
| 181 | + (3, 6, 1), | ||
| 182 | + (4, 14, -2), | ||
| 183 | + (5, 30, 2), | ||
| 184 | + (6, 62, 3), | ||
| 185 | + (7, 126, -3), | ||
| 186 | + (8, 254, -4), | ||
| 187 | + (9, 510, 4), | ||
| 188 | + (11, 2044, -5), | ||
| 189 | + (12, 4090, 5), | ||
| 190 | + (13, 8182, 6), | ||
| 191 | + (13, 8183, -12), | ||
| 192 | + (13, 8184, -11), | ||
| 193 | + (13, 8185, -10), | ||
| 194 | + (13, 8186, -9), | ||
| 195 | + (13, 8187, -8), | ||
| 196 | + (14, 16376, -7), | ||
| 197 | + (14, 16377, -6), | ||
| 198 | + (14, 16378, 7), | ||
| 199 | + (14, 16379, 8), | ||
| 200 | + (14, 16380, 9), | ||
| 201 | + (14, 16381, 10), | ||
| 202 | + (14, 16382, 11), | ||
| 203 | + (14, 16383, 12), | ||
| 204 | +]; | ||
| 205 | + | ||
| 206 | +#[cfg(test)] | ||
| 207 | +mod tests { | ||
| 208 | + use super::*; | ||
| 209 | + | ||
| 210 | + fn kraft_is_one(codes: &[(u8, u32, i32)]) { | ||
| 211 | + let sum: f64 = codes.iter().map(|&(l, _, _)| 2f64.powi(-(l as i32))).sum(); | ||
| 212 | + assert!((sum - 1.0).abs() < 1e-9, "Kraft sum {sum}"); | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + fn is_prefix_free(codes: &[(u8, u32, i32)]) { | ||
| 216 | + for (i, &(li, ci, _)) in codes.iter().enumerate() { | ||
| 217 | + for &(lj, cj, _) in codes.iter().skip(i + 1) { | ||
| 218 | + let (short, long) = if li <= lj { (li, lj) } else { (lj, li) }; | ||
| 219 | + let (sc, lc) = if li <= lj { (ci, cj) } else { (cj, ci) }; | ||
| 220 | + assert_ne!(sc, lc >> (long - short), "{ci:?} prefixes {cj:?}"); | ||
| 221 | + } | ||
| 222 | + } | ||
| 223 | + } | ||
| 224 | + | ||
| 225 | + #[test] | ||
| 226 | + fn noise_t_is_a_complete_prefix_code() { | ||
| 227 | + kraft_is_one(&NOISE_T); | ||
| 228 | + is_prefix_free(&NOISE_T); | ||
| 229 | + } | ||
| 230 | + | ||
| 231 | + #[test] | ||
| 232 | + fn noise_f_is_a_complete_prefix_code() { | ||
| 233 | + kraft_is_one(&NOISE_F); | ||
| 234 | + is_prefix_free(&NOISE_F); | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + #[test] | ||
| 238 | + fn noiseb_t_is_a_complete_prefix_code() { | ||
| 239 | + kraft_is_one(&NOISEB_T); | ||
| 240 | + is_prefix_free(&NOISEB_T); | ||
| 241 | + } | ||
| 242 | + | ||
| 243 | + #[test] | ||
| 244 | + fn noiseb_f_is_a_complete_prefix_code() { | ||
| 245 | + kraft_is_one(&NOISEB_F); | ||
| 246 | + is_prefix_free(&NOISEB_F); | ||
| 247 | + } | ||
| 248 | +} | ||
scripts/aac-tables/sbrtables.pymodified+250 -2
| @@ -663,7 +663,13 @@ BAD_VALUE = re.compile(r"is invalid|out of range|overflow|SBR reset failed") | |||
| 663 | # survives both ends of its table (0 and 30 are the limits the tool enforces), | 663 | # survives both ends of its table (0 and 30 are the limits the tool enforces), |
| 664 | # so both ends are tried and the probe it does not refuse is the one that | 664 | # so both ends are tried and the probe it does not refuse is the one that |
| 665 | # measured something. | 665 | # measured something. |
| 666 | -RAW_TRIES = [(0, 16), (30, 16), (0, 0), (30, 30)] | 666 | +# A balance value is checked doubled (a coupled channel's noise floor is the |
| 667 | +# base channel's combined with the ratio the balance value codes), so 16 -- the | ||
| 668 | +# middle of the raw field -- can already read as 32 and refuse on its own, | ||
| 669 | +# before the codeword under test ever contributes: the extra, smaller-magnitude | ||
| 670 | +# pairs are the fallback once that is observed (`exact_bits` requires a sane | ||
| 671 | +# 1..32 answer, not just an unrefused one). | ||
| 672 | +RAW_TRIES = [(0, 16), (30, 16), (0, 0), (30, 30), (8, 8), (0, 8), (8, 0)] | ||
| 667 | 673 | ||
| 668 | 674 | ||
| 669 | def as_bits(length, code): | 675 | def as_bits(length, code): |
| @@ -756,7 +762,7 @@ def exact_bits(oracle, cfg, tables, kind, word, books): | |||
| 756 | break | 762 | break |
| 757 | top = 8 * n - 4 - base + (trailing if BAD_VALUE.search(err) else 0) | 763 | top = 8 * n - 4 - base + (trailing if BAD_VALUE.search(err) else 0) |
| 758 | lo, hi = max(lo, top - 7), min(hi, top) | 764 | lo, hi = max(lo, top - 7), min(hi, top) |
| 759 | - if not bad and lo == hi: | 765 | + if not bad and lo == hi and 1 <= lo <= 32: |
| 760 | return lo | 766 | return lo |
| 761 | return None | 767 | return None |
| 762 | 768 | ||
| @@ -853,6 +859,223 @@ def stage_books(oracle, sf_index=7, only=None, books=None): | |||
| 853 | return out | 859 | return out |
| 854 | 860 | ||
| 855 | 861 | ||
| 862 | +# -------------------------------------------------------------- values stage | ||
| 863 | + | ||
| 864 | +# `env_facs_q`/`noise_facs_q` are the reference decoder's own accumulated | ||
| 865 | +# scalefactor: it prints the value it computed the instant that value leaves | ||
| 866 | +# the valid range, which is `raw + delta` for a plain codebook or, measured | ||
| 867 | +# below, `2 * (raw + delta)` for a balance one (the coupled channel's value is | ||
| 868 | +# reconstructed from double the coded ratio). Placing the codeword under test | ||
| 869 | +# at `raw = 0` and at the field's own maximum brackets every delta the ten | ||
| 870 | +# tables carry: a delta that overflows high is read straight off the | ||
| 871 | +# maximum-raw probe, a delta that overflows low wraps through the decoder's | ||
| 872 | +# own byte-sized accumulator and is read off the zero-raw probe once | ||
| 873 | +# unwrapped -- the write-up above is what pins the wrap width at 256 and the | ||
| 874 | +# scale at 1 or 2, not an assumption. | ||
| 875 | +VALUE_RE_CACHE = {} | ||
| 876 | + | ||
| 877 | + | ||
| 878 | +def value_re(field): | ||
| 879 | + if field not in VALUE_RE_CACHE: | ||
| 880 | + VALUE_RE_CACHE[field] = re.compile(rf"{field} (-?\d+) is invalid") | ||
| 881 | + return VALUE_RE_CACHE[field] | ||
| 882 | + | ||
| 883 | + | ||
| 884 | +def values_config(kind, sf_index=7): | ||
| 885 | + """A config in which `kind` carries exactly one codeword, plus the raw | ||
| 886 | + field/width/scale that codeword's delta is read against.""" | ||
| 887 | + balance = kind.startswith("ENVB") or kind.startswith("NOISEB") | ||
| 888 | + is_env = kind.startswith("ENV") | ||
| 889 | + amp_res = 1 if "30" in kind else 0 | ||
| 890 | + scale = 2 if balance else 1 | ||
| 891 | + element = "cpe" if balance else "sce" | ||
| 892 | + if kind.endswith("_F"): | ||
| 893 | + if is_env: | ||
| 894 | + over = dict(element=element, coupling=1, num_env=1, amp_res=amp_res, | ||
| 895 | + df_env=[0] * 8, df_noise=[0, 0], freq_res=1) | ||
| 896 | + found = find_config(sf_index, over, n_high=2, n_q=1) | ||
| 897 | + key, width = ("env0b" if balance else "env0"), RAW_ENV[(1 if balance else 0, amp_res)] | ||
| 898 | + else: | ||
| 899 | + over = dict(element=element, coupling=1, num_env=1, amp_res=0, | ||
| 900 | + df_env=[0] * 8, df_noise=[0, 0], freq_res=0) | ||
| 901 | + found = find_config(sf_index, over, n_q=2) | ||
| 902 | + key, width = ("noise0b" if balance else "noise0"), RAW_NOISE | ||
| 903 | + if found is None: | ||
| 904 | + return None | ||
| 905 | + cfg, tables = found | ||
| 906 | + else: | ||
| 907 | + found = recipe_config(kind, sf_index) | ||
| 908 | + if found is None: | ||
| 909 | + return None | ||
| 910 | + cfg, tables = found | ||
| 911 | + if is_env: | ||
| 912 | + key, width = ("env0b" if balance else "env0"), RAW_ENV[(1 if balance else 0, amp_res_of(cfg))] | ||
| 913 | + else: | ||
| 914 | + key, width = ("noise0b" if balance else "noise0"), RAW_NOISE | ||
| 915 | + kinds, _ = plan(cfg, tables) | ||
| 916 | + if kinds.count(kind) != 1: | ||
| 917 | + return None | ||
| 918 | + return cfg, tables, key, width, scale | ||
| 919 | + | ||
| 920 | + | ||
| 921 | +def book_values(oracle, kind, cfg, tables, key, width, scale, books): | ||
| 922 | + """`{(length, code): delta}` for every codeword `stage_books` found.""" | ||
| 923 | + codes = sorted(books[kind]) | ||
| 924 | + raw_max = (1 << width) - 1 | ||
| 925 | + field = "env_facs_q" if kind.startswith("ENV") else "noise_facs_q" | ||
| 926 | + pat = value_re(field) | ||
| 927 | + cases, meta = [], [] | ||
| 928 | + for length, code in codes: | ||
| 929 | + # The exact codeword, no trailing pad: `stage_books` already closed the | ||
| 930 | + # length for every codeword here, so (unlike the length-search bisection, | ||
| 931 | + # which pads because the length is what it is looking for) padding would | ||
| 932 | + # only shift every field after this slot and desync the frame. | ||
| 933 | + word = as_bits(length, code) | ||
| 934 | + words = fill_words(cfg, tables, kind, word, books, extra=0) | ||
| 935 | + if words is None: | ||
| 936 | + continue | ||
| 937 | + for raw in (0, raw_max): | ||
| 938 | + v = dict(cfg) | ||
| 939 | + arr = list(v[key]) | ||
| 940 | + arr[0] = raw | ||
| 941 | + v[key] = arr | ||
| 942 | + cases.append((v, tables, words)) | ||
| 943 | + meta.append((length, code, raw)) | ||
| 944 | + got = measure(oracle, cases) | ||
| 945 | + seen = {} | ||
| 946 | + crashed = set() | ||
| 947 | + clean = set() | ||
| 948 | + for (length, code, raw), (_n, err) in zip(meta, got): | ||
| 949 | + m = pat.search(err) | ||
| 950 | + if not m: | ||
| 951 | + # Not a range-check complaint: either a clean decode (only the | ||
| 952 | + # routine byte-count line) or the parser aborting the element for | ||
| 953 | + # an unrelated reason -- only the former licenses the "both ends | ||
| 954 | + # valid" inference below, so the two are told apart here. | ||
| 955 | + if "is not allocated" in err or "Invalid data found" in err: | ||
| 956 | + crashed.add((length, code)) | ||
| 957 | + else: | ||
| 958 | + clean.add((length, code)) | ||
| 959 | + continue | ||
| 960 | + val = int(m.group(1)) | ||
| 961 | + if raw == 0: | ||
| 962 | + v = val % 256 | ||
| 963 | + if v > 128: | ||
| 964 | + v -= 256 | ||
| 965 | + if v % scale: | ||
| 966 | + continue | ||
| 967 | + delta = v // scale | ||
| 968 | + else: | ||
| 969 | + if val % scale: | ||
| 970 | + continue | ||
| 971 | + delta = val // scale - raw | ||
| 972 | + seen.setdefault((length, code), set()).add(delta) | ||
| 973 | + values, gaps = {}, [] | ||
| 974 | + for length, code in codes: | ||
| 975 | + vs = seen.get((length, code)) | ||
| 976 | + if not vs: | ||
| 977 | + if (length, code) in clean and (length, code) not in crashed: | ||
| 978 | + # Neither end complained and neither crashed either: the | ||
| 979 | + # codeword's delta and the raw value it rides with both | ||
| 980 | + # stayed inside `[0, raw_max]`, which only `delta = 0` can do | ||
| 981 | + # at *both* ends of the field at once. | ||
| 982 | + values[(length, code)] = 0 | ||
| 983 | + else: | ||
| 984 | + gaps.append((length, code, "crashed" if (length, code) in crashed else "no signal")) | ||
| 985 | + continue | ||
| 986 | + if len(vs) > 1: | ||
| 987 | + gaps.append((length, code, vs)) | ||
| 988 | + continue | ||
| 989 | + values[(length, code)] = next(iter(vs)) | ||
| 990 | + return values, gaps | ||
| 991 | + | ||
| 992 | + | ||
| 993 | +def stage_values(oracle, books, sf_index=7): | ||
| 994 | + """Assigns the delta value every codeword of every closed book carries.""" | ||
| 995 | + values = {} | ||
| 996 | + for kind in KINDS: | ||
| 997 | + if kind not in books: | ||
| 998 | + print(f" {kind}: no lengths, skipped") | ||
| 999 | + continue | ||
| 1000 | + made = values_config(kind, sf_index) | ||
| 1001 | + if made is None: | ||
| 1002 | + print(f" {kind}: no single-codeword configuration for values") | ||
| 1003 | + continue | ||
| 1004 | + cfg, tables, key, width, scale = made | ||
| 1005 | + vals, gaps = book_values(oracle, kind, cfg, tables, key, width, scale, books) | ||
| 1006 | + if gaps: | ||
| 1007 | + print(f" {kind}: {len(gaps)}/{len(books[kind])} codewords unresolved: {gaps[:5]}") | ||
| 1008 | + if len(vals) == len(books[kind]): | ||
| 1009 | + values[kind] = vals | ||
| 1010 | + lo, hi = min(vals.values()), max(vals.values()) | ||
| 1011 | + print(f" {kind}: {len(vals)} values, range {lo}..{hi}") | ||
| 1012 | + else: | ||
| 1013 | + print(f" {kind}: incomplete ({len(vals)}/{len(books[kind])}), not emitted") | ||
| 1014 | + return values | ||
| 1015 | + | ||
| 1016 | + | ||
| 1017 | +def write_rust(books, values, path=None): | ||
| 1018 | + """Emits the closed, fully-valued books as `crates/ec-aac/src/sbr_tables.rs`.""" | ||
| 1019 | + path = path or os.path.join(ROOT, "crates", "ec-aac", "src", "sbr_tables.rs") | ||
| 1020 | + ready = [k for k in KINDS if k in books and k in values and len(values[k]) == len(books[k])] | ||
| 1021 | + skipped = [k for k in KINDS if k not in ready] | ||
| 1022 | + lines = [ | ||
| 1023 | + "//! SBR (HE-AAC v1) Huffman codebooks (ISO/IEC 14496-3 §4.6.18.3.6).", | ||
| 1024 | + "//!", | ||
| 1025 | + "//! Derived black box from a reference decoder's own bit accounting by", | ||
| 1026 | + "//! `scripts/aac-tables/sbrtables.py`: no source was consulted. The", | ||
| 1027 | + "//! decoder's \"Expected to read N SBR bytes actually read M\" complaint", | ||
| 1028 | + "//! reads codeword lengths off a controlled FIL payload, and its", | ||
| 1029 | + "//! `env_facs_q`/`noise_facs_q` range check reads the delta value each", | ||
| 1030 | + "//! codeword carries off the same payload. Every table here closed with", | ||
| 1031 | + "//! a Kraft sum of exactly 1 (asserted below).", | ||
| 1032 | + "#![allow(dead_code)]", | ||
| 1033 | + "", | ||
| 1034 | + ] | ||
| 1035 | + if skipped: | ||
| 1036 | + lines.append(f"// Not emitted (values incomplete or book did not close): {skipped}") | ||
| 1037 | + lines.append("") | ||
| 1038 | + for kind in ready: | ||
| 1039 | + codes = sorted(books[kind]) | ||
| 1040 | + vals = values[kind] | ||
| 1041 | + lines.append(f"/// SBR Huffman book `{kind}`: (length, code, delta) by codeword.") | ||
| 1042 | + lines.append(f"pub(crate) static {kind}: [(u8, u32, i32); {len(codes)}] = [") | ||
| 1043 | + for length, code in codes: | ||
| 1044 | + lines.append(f" ({length}, {code}, {vals[(length, code)]}),") | ||
| 1045 | + lines.append("];") | ||
| 1046 | + lines.append("") | ||
| 1047 | + lines.append("#[cfg(test)]") | ||
| 1048 | + lines.append("mod tests {") | ||
| 1049 | + lines.append(" use super::*;") | ||
| 1050 | + lines.append("") | ||
| 1051 | + lines.append(" fn kraft_is_one(codes: &[(u8, u32, i32)]) {") | ||
| 1052 | + lines.append(" let sum: f64 = codes.iter().map(|&(l, _, _)| 2f64.powi(-(l as i32))).sum();") | ||
| 1053 | + lines.append(" assert!((sum - 1.0).abs() < 1e-9, \"Kraft sum {sum}\");") | ||
| 1054 | + lines.append(" }") | ||
| 1055 | + lines.append("") | ||
| 1056 | + lines.append(" fn is_prefix_free(codes: &[(u8, u32, i32)]) {") | ||
| 1057 | + lines.append(" for (i, &(li, ci, _)) in codes.iter().enumerate() {") | ||
| 1058 | + lines.append(" for &(lj, cj, _) in codes.iter().skip(i + 1) {") | ||
| 1059 | + lines.append(" let (short, long) = if li <= lj { (li, lj) } else { (lj, li) };") | ||
| 1060 | + lines.append(" let (sc, lc) = if li <= lj { (ci, cj) } else { (cj, ci) };") | ||
| 1061 | + lines.append(" assert_ne!(sc, lc >> (long - short), \"{ci:?} prefixes {cj:?}\");") | ||
| 1062 | + lines.append(" }") | ||
| 1063 | + lines.append(" }") | ||
| 1064 | + lines.append(" }") | ||
| 1065 | + lines.append("") | ||
| 1066 | + for kind in ready: | ||
| 1067 | + lines.append(" #[test]") | ||
| 1068 | + lines.append(f" fn {kind.lower()}_is_a_complete_prefix_code() {{") | ||
| 1069 | + lines.append(f" kraft_is_one(&{kind});") | ||
| 1070 | + lines.append(f" is_prefix_free(&{kind});") | ||
| 1071 | + lines.append(" }") | ||
| 1072 | + lines.append("") | ||
| 1073 | + lines.append("}") | ||
| 1074 | + with open(path, "w") as f: | ||
| 1075 | + f.write("\n".join(lines) + "\n") | ||
| 1076 | + print(f"wrote {path}: {len(ready)} books, {len(skipped)} skipped") | ||
| 1077 | + return ready, skipped | ||
| 1078 | + | ||
| 856 | 1079 | ||
| 857 | # ---------------------------------------------------------------- raw widths | 1080 | # ---------------------------------------------------------------- raw widths |
| 858 | 1081 | ||
| @@ -1120,6 +1343,21 @@ def stage_diag(oracle): | |||
| 1120 | print(f"diag: {total - disagree}/{total} headers agree on n_master") | 1343 | print(f"diag: {total - disagree}/{total} headers agree on n_master") |
| 1121 | 1344 | ||
| 1122 | 1345 | ||
| 1346 | +def run_books_to_fixpoint(oracle, sf_index=7): | ||
| 1347 | + """Repeats `stage_books` until no further kind closes, honoring the | ||
| 1348 | + dependency order `stage_books` itself discovers via its `missing` check.""" | ||
| 1349 | + books = {} | ||
| 1350 | + remaining = set(KINDS) | ||
| 1351 | + while remaining: | ||
| 1352 | + made = stage_books(oracle, sf_index, only=remaining, books=books) | ||
| 1353 | + if not made: | ||
| 1354 | + break | ||
| 1355 | + remaining -= set(made) | ||
| 1356 | + if remaining: | ||
| 1357 | + print(f"books: did not close: {sorted(remaining)}") | ||
| 1358 | + return books | ||
| 1359 | + | ||
| 1360 | + | ||
| 1123 | if __name__ == "__main__": | 1361 | if __name__ == "__main__": |
| 1124 | ap = argparse.ArgumentParser() | 1362 | ap = argparse.ArgumentParser() |
| 1125 | ap.add_argument("--stage", default="sweep") | 1363 | ap.add_argument("--stage", default="sweep") |
| @@ -1131,6 +1369,16 @@ if __name__ == "__main__": | |||
| 1131 | stage_sweep(oracle) | 1369 | stage_sweep(oracle) |
| 1132 | if args.stage == "diag": | 1370 | if args.stage == "diag": |
| 1133 | stage_diag(oracle) | 1371 | stage_diag(oracle) |
| 1372 | + if args.stage == "k0": | ||
| 1373 | + stage_k0(oracle) | ||
| 1374 | + if args.stage in ("widths", "all"): | ||
| 1375 | + stage_widths(oracle) | ||
| 1376 | + books = None | ||
| 1377 | + if args.stage in ("books", "values", "all"): | ||
| 1378 | + books = run_books_to_fixpoint(oracle) | ||
| 1379 | + if args.stage in ("values", "all"): | ||
| 1380 | + values = stage_values(oracle, books) | ||
| 1381 | + write_rust(books, values) | ||
| 1134 | finally: | 1382 | finally: |
| 1135 | oracle.save() | 1383 | oracle.save() |
| 1136 | print(f"oracle: {oracle.runs} decoder runs, {oracle.hits} cache hits") | 1384 | print(f"oracle: {oracle.runs} decoder runs, {oracle.hits} cache hits") |