forge
Explore
Log in

Don't you dare go Hollow

Delta-time envelope base mapped across freq-res changes

Browse files at this commit

46f34476696efb2560bcbeb964f8680bfff664a7Ahmet Kaan GümüşParent: e6128af
  • fix
    • delta-time envelope base mapped across freq-res changes
    • locator gains target-vs-reference per-band rows
    • WIP audio readout for the 3 dB books
Show full message
fix(aac-sbr): delta-time envelope base mapped across freq-res changes; locator gains target-vs-reference per-band rows; WIP audio readout for the 3 dB books

- sbr_payload: a DT-coded envelope whose resolution differs from the one it is
  coded against now takes its base band-mapped (high<-containing low band,
  low<-high band at the same edge) instead of index-for-index (the top half of
  such a high-res row read base 0). reeln locator: +0.01 corr/level above
  7 kHz, full-band unchanged.
- sbr_env/noise_fraction_table: 4th column = realised |Y|^2 per QMF band, so
  realised/target is readable (it is 1.00 everywhere: the adjuster hits its
  target; the residual HF tilt is target-side).
- locator: EC_AAC_SBR_LOCATOR_FILE points it at any file; TARGET rows print
  target vs reference PCM per band.
- ROOT CAUSE FOUND, NOT YET FIXED: sbr_tables.rs ENV30_F/ENV30_T/ENVB30_F/
  ENVB30_T carry 0 for every positive delta (32/32/13/13 entries) -- the
  range-check learner cannot see a positive 3 dB delta (6-bit raw field,
  7-bit check ceiling). ENV30_T also holds duplicate codewords. Envelopes can
  only fall across bands -> the measured -5.5 dB/oct vs reference -2.5 dB/oct
  HF tilt on pink noise and the 0.6 HF level on reeln. sbrvalues_audio.py
  is the audio-readout replacement, decoding probe frames to PCM; it does not
  work yet (the probe's SBR payload reads one byte longer than written and the
  decoder drops SBR).
crates/ec-aac/src/sbr_env.rsmodified+19 -5
@@ -173,13 +173,15 @@ fn noise_fraction_debug() -> bool {
173 std::env::var("EC_AAC_SBR_NOISE_FRACTION").is_ok()173 std::env::var("EC_AAC_SBR_NOISE_FRACTION").is_ok()
174 }174 }
175 175
176-static NOISE_FRACTION: std::sync::OnceLock<std::sync::Mutex<Vec<(usize, f64, f64)>>> =176+static NOISE_FRACTION: std::sync::OnceLock<std::sync::Mutex<Vec<(usize, f64, f64, f64)>>> =
177 std::sync::OnceLock::new();177 std::sync::OnceLock::new();
178 178
179 /// Diagnostic (`EC_AAC_SBR_NOISE_FRACTION`): per absolute QMF band,179 /// Diagnostic (`EC_AAC_SBR_NOISE_FRACTION`): per absolute QMF band,
180-/// bookkept `(band, Σ signal energy·slots, Σ noise energy·slots)`.180+/// bookkept `(band, Σ signal energy·slots, Σ noise energy·slots, Σ |Y|²
181-pub fn noise_fraction_table() -> Vec<(usize, f64, f64)> {181+/// post-adjust)` -- the last column against the first two's sum is the
182- let mut out: Vec<(usize, f64, f64)> = NOISE_FRACTION182+/// per-subband realised/target energy ratio.
183+pub fn noise_fraction_table() -> Vec<(usize, f64, f64, f64)> {
184+ let mut out: Vec<(usize, f64, f64, f64)> = NOISE_FRACTION
183 .get()185 .get()
184 .and_then(|m| m.lock().ok())186 .and_then(|m| m.lock().ok())
185 .map(|g| g.clone())187 .map(|g| g.clone())
@@ -381,7 +383,7 @@ pub fn adjust(
381 row.1 += sig;383 row.1 += sig;
382 row.2 += noi;384 row.2 += noi;
383 } else {385 } else {
384- t.push((m + kx, sig, noi));386+ t.push((m + kx, sig, noi, 0.0));
385 }387 }
386 }388 }
387 }389 }
@@ -455,6 +457,18 @@ pub fn adjust(
455 row[i] = y;457 row[i] = y;
456 p_im = -p_im;458 p_im = -p_im;
457 }459 }
460+ if track_fraction {
461+ let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new()));
462+ if let Ok(mut t) = tab.lock() {
463+ for m in 0..m_max {
464+ if let (Some(row), Some(y)) =
465+ (t.iter_mut().find(|r| r.0 == m + kx), hf[m].get(i))
466+ {
467+ row.3 += y.norm_sqr();
468+ }
469+ }
470+ }
471+ }
458 state.index_noise = (state.index_noise + m_max) & 0x1ff;472 state.index_noise = (state.index_noise + m_max) & 0x1ff;
459 state.index_sine = (state.index_sine + 1) & 3;473 state.index_sine = (state.index_sine + 1) & 3;
460 }474 }
crates/ec-aac/src/sbr_payload.rsmodified+39 -1
@@ -191,6 +191,39 @@ fn amp_res_of(header_amp_res: u8, grid: &Grid) -> u8 {
191 if grid.fixfix && grid.num_env == 1 { 0 } else { header_amp_res }191 if grid.fixfix && grid.num_env == 1 { 0 } else { header_amp_res }
192 }192 }
193 193
194+/// Delta-time base for an envelope whose frequency resolution differs from
195+/// the envelope it is coded against (§4.6.18.3.3): a high-res band takes the
196+/// low-res band containing it, a low-res band the high-res band starting at
197+/// the same edge. Same resolution (or a degenerate table) passes through.
198+/// Without this the top half of a high-res row coded against a low-res row
199+/// read an out-of-range base of 0 -- a near-silent envelope -- and every
200+/// low-res band read the high-res band of half its frequency.
201+fn map_prev_env(prev: &[i32], tables: &BandTables, cur_high: bool) -> Vec<i32> {
202+ let (n_low, n_high) = (tables.n_low, tables.n_high);
203+ if n_low == n_high || prev.len() == if cur_high { n_high } else { n_low } {
204+ return prev.to_vec();
205+ }
206+ let (f_low, f_high) = (&tables.f_low, &tables.f_high);
207+ if cur_high {
208+ (0..n_high)
209+ .map(|j| {
210+ let k = (0..n_low)
211+ .rev()
212+ .find(|&k| f_low[k] <= f_high[j])
213+ .unwrap_or(0);
214+ prev.get(k).copied().unwrap_or(0)
215+ })
216+ .collect()
217+ } else {
218+ (0..n_low)
219+ .map(|j| {
220+ let k = (0..n_high).find(|&k| f_high[k] == f_low[j]).unwrap_or(0);
221+ prev.get(k).copied().unwrap_or(0)
222+ })
223+ .collect()
224+ }
225+}
226+
194 /// Reads one Huffman codeword by walking bit-by-bit until it matches a table227 /// Reads one Huffman codeword by walking bit-by-bit until it matches a table
195 /// entry. Every book here is a complete prefix code (Kraft sum 1, checked in228 /// entry. Every book here is a complete prefix code (Kraft sum 1, checked in
196 /// `sbr_tables`), so a well-formed stream always terminates; a codeword229 /// `sbr_tables`), so a well-formed stream always terminates; a codeword
@@ -569,7 +602,12 @@ impl SbrParser {
569 } else {602 } else {
570 &this.state[ch].last_env603 &this.state[ch].last_env
571 };604 };
572- let row = this.decode_envelope(r, bands, dt, balance, amp_res, prev)?;605+ let prev = if dt {
606+ map_prev_env(prev, &tables, grids[ch].freq_res[i] != 0)
607+ } else {
608+ Vec::new()
609+ };
610+ let row = this.decode_envelope(r, bands, dt, balance, amp_res, &prev)?;
573 e_q.push(row);611 e_q.push(row);
574 }612 }
575 e_q_all[ch] = e_q;613 e_q_all[ch] = e_q;
crates/ec-aac/tests/sbr_real_library.rsmodified+34 -5
@@ -2774,15 +2774,16 @@ fn sbr_real_library_matches_reference() {
2774 println!(2774 println!(
2775 " NOISE-FRACTION ceiling prediction (band_hz, f_noise, predicted_ceiling):"2775 " NOISE-FRACTION ceiling prediction (band_hz, f_noise, predicted_ceiling):"
2776 );2776 );
2777- for (band, signal, noise) in ec_aac::noise_fraction_table() {2777+ for (band, signal, noise, out) in ec_aac::noise_fraction_table() {
2778 if signal + noise <= 0.0 {2778 if signal + noise <= 0.0 {
2779 continue;2779 continue;
2780 }2780 }
2781 let f = noise / (signal + noise);2781 let f = noise / (signal + noise);
2782 println!(2782 println!(
2783- " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4}",2783+ " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4} realised/target {:.4}",
2784 band as f64 * band_hz,2784 band as f64 * band_hz,
2785- (1.0 - f).max(0.0).sqrt()2785+ (1.0 - f).max(0.0).sqrt(),
2786+ out / (signal + noise)
2786 );2787 );
2787 }2788 }
2788 }2789 }
@@ -3436,7 +3437,7 @@ fn sbr_actual_noise_fraction() {
3436 let book = bookkept3437 let book = bookkept
3437 .iter()3438 .iter()
3438 .find(|(b, ..)| *b == band)3439 .find(|(b, ..)| *b == band)
3439- .map(|(_, s, n)| if s + n > 0.0 { n / (s + n) } else { 0.0 })3440+ .map(|(_, s, n, _)| if s + n > 0.0 { n / (s + n) } else { 0.0 })
3440 .unwrap_or(0.0);3441 .unwrap_or(0.0);
3441 println!(3442 println!(
3442 " {hz:>6.0}Hz: on {e_on:.3e} off {e_off:.3e} actual {actual:.4} bookkept {book:.4}"3443 " {hz:>6.0}Hz: on {e_on:.3e} off {e_off:.3e} actual {actual:.4} bookkept {book:.4}"
@@ -4630,7 +4631,11 @@ fn sbr_residual_locator() {
4630 return;4631 return;
4631 }4632 }
4632 let home = std::env::var("HOME").unwrap();4633 let home = std::env::var("HOME").unwrap();
4633- let path = PathBuf::from(format!("{home}/Music/reeln.mp4"));4634+ // `EC_AAC_SBR_LOCATOR_FILE` points the same instrument at any other
4635+ // HE-AAC file (e.g. a mono, uncoupled, noise-only probe encode).
4636+ let path = std::env::var("EC_AAC_SBR_LOCATOR_FILE")
4637+ .map(PathBuf::from)
4638+ .unwrap_or_else(|_| PathBuf::from(format!("{home}/Music/reeln.mp4")));
4634 if !path.exists() {4639 if !path.exists() {
4635 return;4640 return;
4636 }4641 }
@@ -4671,6 +4676,30 @@ fn sbr_residual_locator() {
4671 }4676 }
4672 let hz = f64::from(rate) / FFT_LEN as f64;4677 let hz = f64::from(rate) / FFT_LEN as f64;
4673 let tot: f64 = acc.iter().map(|a| a[1] + a[2]).sum();4678 let tot: f64 = acc.iter().map(|a| a[1] + a[2]).sum();
4679+ // With `EC_AAC_SBR_NOISE_FRACTION` set the decoder bookkeeps the
4680+ // dequantized target per QMF band; print it next to the reference's
4681+ // measured energy in the same band so a target-side (bitstream ->
4682+ // E_orig) tilt separates from an adjust/synthesis-side one.
4683+ if ch == 0 {
4684+ let band_hz = f64::from(rate) / 128.0;
4685+ for (band, sig, noi, out) in ec_aac::noise_fraction_table() {
4686+ let (lo, hi) = (
4687+ (band as f64 * band_hz / hz) as usize,
4688+ ((band + 1) as f64 * band_hz / hz) as usize,
4689+ );
4690+ let pt: f64 = (lo..hi.min(bins)).map(|k| acc[k][2]).sum();
4691+ let po: f64 = (lo..hi.min(bins)).map(|k| acc[k][1]).sum();
4692+ println!(
4693+ "TARGET band {band:>2} {:>6.0}Hz target {:.3e} realised/target {:.4} ref_pcm {:.3e} ours_pcm {:.3e} target/ref_pcm {:.3e}",
4694+ band as f64 * band_hz,
4695+ sig + noi,
4696+ out / (sig + noi),
4697+ pt,
4698+ po,
4699+ (sig + noi) / pt
4700+ );
4701+ }
4702+ }
4674 // group into 250 Hz bands up to 8 kHz, then 1 kHz4703 // group into 250 Hz bands up to 8 kHz, then 1 kHz
4675 let mut edges: Vec<usize> = (0..=32).map(|i| ((i as f64 * 250.0) / hz) as usize).collect();4704 let mut edges: Vec<usize> = (0..=32).map(|i| ((i as f64 * 250.0) / hz) as usize).collect();
4676 edges.extend((9..=22).map(|i| ((i as f64 * 1000.0) / hz) as usize));4705 edges.extend((9..=22).map(|i| ((i as f64 * 1000.0) / hz) as usize));
scripts/aac-tables/sbrvalues_audio.pyadded+202 -0
@@ -0,0 +1,202 @@
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()