forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5a2f5efTahinli3 months ago1409 commits

sbrnoise.py111 lines, 4.1 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Black-box measurement of the reference decoder's SBR noise-floor
3dequantization law (round-21 Task 1).
4
5Method: reuse `sbrchirp.py`'s repaired probe shape (SCE, FIXFIX num_env=2,
6amp_res=1, broadband comb core so the HF-signal envelope target is fixed
7and non-zero), fix the envelope raw value, and sweep only the noise-floor
8raw value `q_q` (`noise0`) across its 5-bit range. Noise is spec-additive
9on top of the gain-adjusted HF signal (module doc in sbr_env.rs), so the
10total power measured in the target band at each `q_q` is
11`signal_energy(fixed) + noise_energy(q_q)`; subtracting the high-`q_q`
12(minimal-noise) baseline isolates `noise_energy(q_q)` and its shape can be
13fit against `q_q` directly, independent of our own decoder.
14"""
15import os
16import sys
17
18import numpy as np
19
20HERE = os.path.dirname(os.path.abspath(__file__))
21sys.path.insert(0, HERE)
22
23import sbrchirp as C
24import sbrpayload_fixtures as F
25
26RATE = C.RATE
27
28
29def noise_stream(cfg, tables, n_frames, q, env=40):
30 """Like `sbrchirp.stream()` but `bs_invf_mode` held at NONE (0, so the
31 injected noise is not reshaped by the inverse filter) and `noise0`
32 swept to `[q, q]` instead of `bs_invf_mode`; `env` is the fixed
33 envelope raw value."""
34 grid = dict(frame_class=0, num_env=2, freq_res=0)
35 frames = [C.P.silent(C.SF_INDEX)]
36 for _ in range(n_frames):
37 c = dict(cfg, invf=0, header=1, amp_res=1, element="sce", coupling=0,
38 df_env=[0] * 8, df_noise=[0, 0], env0=[env] * 8, noise0=[q, q])
39 w = C.P.BitW()
40 C.broadband_core_bits(w)
41 body = F.sbr_bits_full(c, tables, grid, [])
42 w.w(6, 3)
43 cnt = (len(body.bits) + 4 + 7) // 8
44 if cnt >= 15:
45 w.w(15, 4)
46 w.w(cnt - 15 + 1, 8)
47 else:
48 w.w(cnt, 4)
49 start = len(w)
50 w.w(13, 4)
51 w.wbits(body.bits)
52 while len(w) - start < cnt * 8:
53 w.w(0, 1)
54 w.w(7, 3)
55 frames.append(C.P.adts(w.pack(pad=0), C.SF_INDEX))
56 frames.append(C.P.silent(C.SF_INDEX))
57 return frames
58
59
60def band_power(pcm, lo_hz, hi_hz, skip=6, n_fft=8192):
61 start = skip * 1024
62 seg = pcm[start : start + n_fft]
63 if len(seg) < n_fft:
64 seg = np.pad(seg, (0, n_fft - len(seg)))
65 spec = np.abs(np.fft.rfft(seg * np.hanning(len(seg)))) ** 2
66 freqs = np.fft.rfftfreq(n_fft, 1 / RATE)
67 mask = (freqs >= lo_hz) & (freqs < hi_hz)
68 return float(np.sum(spec[mask]))
69
70
71if __name__ == "__main__":
72 cfg0, tables0 = F.one_band_header()
73 lo, hi = 19 * RATE / 128, 23 * RATE / 128
74 print(f"target region {lo:.1f}-{hi:.1f} Hz, RAW_NOISE bits={C.T.RAW_NOISE} (q range 0..{2**C.T.RAW_NOISE - 1})")
75
76 print("\n== value-engagement check: envelope raw sweep (fixed q_q) must move power by orders ==")
77 for e in (10, 40, 60):
78 cfg = dict(cfg0)
79 frames = noise_stream(cfg, tables0, 20, 30, env=e)
80 pcm, err = C.decode(frames, f"env_check{e}")
81 pwr = band_power(pcm, lo, hi)
82 print(f" env0={e} (q_q=30, minimal noise) pwr={pwr:.4e} err={err.strip()[:60]!r}")
83
84 print("\n== Task 1: noise-floor raw (q_q) sweep, fixed envelope ==")
85 qs = list(range(0, 31, 3))
86 pwrs = {}
87 for q in qs:
88 cfg = dict(cfg0)
89 frames = noise_stream(cfg, tables0, 20, q)
90 pcm, err = C.decode(frames, f"q{q}")
91 pwr = band_power(pcm, lo, hi)
92 pwrs[q] = pwr
93 print(f" q_q={q:2d} pwr={pwr:.6e} err={err.strip()[:80]!r}")
94
95 baseline = pwrs[qs[-1]]
96 print(f"\nbaseline (q_q={qs[-1]}, minimal noise) pwr={baseline:.6e}")
97 print("q_q, noise_energy=pwr-baseline, log2(noise_energy)")
98 fit_x, fit_y = [], []
99 for q in qs[:-1]:
100 n = pwrs[q] - baseline
101 if n > 0:
102 l2 = np.log2(n)
103 print(f" {q:2d} {n:.6e} {l2:.4f}")
104 fit_x.append(q)
105 fit_y.append(l2)
106 else:
107 print(f" {q:2d} {n:.6e} (non-positive, skipped)")
108 if len(fit_x) >= 2:
109 slope, intercept = np.polyfit(fit_x, fit_y, 1)
110 print(f"\nfit: log2(noise_energy) = {slope:.4f} * q_q + {intercept:.4f}")
111 print(f"(spec/ours form: log2(noise_energy) = -1*q_q + 6 => slope~-1, intercept~6 expected if law matches)")