wip(opus-64): r3 handoff — tf_analysis port, code ready to paste
Browse files at this commit74c150acae72713d2c09ce92feb7d3ecf2340b34Parent: 4adf26d1 changed file +299 -0
- lanes/opus-64-r3.handoff.md +299 -0
lanes/opus-64-r3.handoff.mdadded+299 -0
| @@ -0,0 +1,299 @@ | |||
| 1 | +## HANDOFF | ||
| 2 | + | ||
| 3 | +### Status | ||
| 4 | +All research complete. Zero code written. Tool cap hit before first edit. Every formula, line number, borrow structure, and C reference verified. The code below is ready to paste — only the `MULT16_16` and `QCONST32` float-mode defs were not explicitly confirmed (all other MULT/QCONST macros confirmed as identity in float mode at `arch.h:219-268`; these follow the same pattern). | ||
| 5 | + | ||
| 6 | +### Files | ||
| 7 | +- `crates/ec-opus/src/celt_enc.rs` — all edits go here | ||
| 8 | +- C reference: `~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/audiopus_sys-0.2.2/opus/celt/celt_encoder.c` lines 228-410 (transient), 571-583 (l1_metric), 584-745 (tf_analysis) | ||
| 9 | +- `arch.h` lines 210-268: float-mode macros (all identity/no-ops) | ||
| 10 | + | ||
| 11 | +### Exact edits to make | ||
| 12 | + | ||
| 13 | +**Edit 1: INV_TABLE constant** — after line 42 (`const CACHE_BITS: &[u8] = &crate::celt::CACHE_BITS;`), insert: | ||
| 14 | +```rust | ||
| 15 | +const INV_TABLE: [u8; 128] = [ | ||
| 16 | + 255,255,156,110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25, | ||
| 17 | + 23, 22, 21, 20, 19, 18, 17, 16, 16, 15, 15, 14, 13, 13, 12, 12, | ||
| 18 | + 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 9, 9, 8, 8, | ||
| 19 | + 8, 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, | ||
| 20 | + 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, | ||
| 21 | + 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, | ||
| 22 | + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, | ||
| 23 | + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, | ||
| 24 | +]; | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +**Edit 2: l1_metric standalone fn** — insert before the `impl CeltEncoder` block (after the free functions, ~line 253 area, near `stereo_itheta`): | ||
| 28 | +```rust | ||
| 29 | +/// `l1_metric()` from the reference: L1 norm scaled by `(1 + LM*bias)`. | ||
| 30 | +/// In float mode `MAC16_32_Q15(c, a*b) = c + a*b`, so this is `L1*(1 + LM*bias)`. | ||
| 31 | +fn l1_metric(tmp: &[f32], n: usize, lm: usize, bias: f32) -> f32 { | ||
| 32 | + let mut l1 = 0.0f32; | ||
| 33 | + for i in 0..n { | ||
| 34 | + l1 += tmp[i].abs(); | ||
| 35 | + } | ||
| 36 | + l1 * (1.0 + lm as f32 * bias) | ||
| 37 | +} | ||
| 38 | +``` | ||
| 39 | + | ||
| 40 | +**Edit 3: Replace transient_analysis** (lines 1016-1082) with: | ||
| 41 | +```rust | ||
| 42 | + /// `transient_analysis()` — libopus float-mode algorithm. | ||
| 43 | + /// Returns `(is_transient, tf_estimate, tf_chan)`. | ||
| 44 | + fn transient_analysis(&mut self, len: usize, c: usize, stride: usize) -> (bool, f32, usize) { | ||
| 45 | + let tmp = &mut self.transient_tmp[..len]; | ||
| 46 | + let len2 = len / 2; | ||
| 47 | + let mut mask_metric: i32 = 0; | ||
| 48 | + let mut tf_chan: usize = 0; | ||
| 49 | + | ||
| 50 | + for ch in 0..c { | ||
| 51 | + // Copy this channel's samples (C layout: in[i + c*len] = in_buf[ch*stride + i]) | ||
| 52 | + tmp.copy_from_slice(&self.in_buf[ch * stride..ch * stride + len]); | ||
| 53 | + | ||
| 54 | + // High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) | ||
| 55 | + let mut mem0 = 0.0f32; | ||
| 56 | + let mut mem1 = 0.0f32; | ||
| 57 | + for v in tmp.iter_mut() { | ||
| 58 | + let x = *v; | ||
| 59 | + let y = mem0 + x; | ||
| 60 | + mem0 = mem1 + y - 2.0 * x; | ||
| 61 | + mem1 = x - 0.5 * y; | ||
| 62 | + *v = y; | ||
| 63 | + } | ||
| 64 | + // First few samples are bad because we don't propagate the memory | ||
| 65 | + for v in tmp.iter_mut().take(12) { | ||
| 66 | + *v = 0.0; | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + // Forward pass: post-echo threshold (forward_decay = 0.0625) | ||
| 70 | + let mut mean = 0.0f32; | ||
| 71 | + let mut fm0 = 0.0f32; | ||
| 72 | + for i in 0..len2 { | ||
| 73 | + let x2 = tmp[2 * i] * tmp[2 * i] + tmp[2 * i + 1] * tmp[2 * i + 1]; | ||
| 74 | + mean += x2; | ||
| 75 | + tmp[i] = fm0 + 0.0625 * (x2 - fm0); | ||
| 76 | + fm0 = tmp[i]; | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + // Backward pass: pre-echo threshold (backward_decay = 0.125) | ||
| 80 | + let mut bm0 = 0.0f32; | ||
| 81 | + let mut max_e = 0.0f32; | ||
| 82 | + for i in (0..len2).rev() { | ||
| 83 | + tmp[i] = bm0 + 0.125 * (tmp[i] - bm0); | ||
| 84 | + bm0 = tmp[i]; | ||
| 85 | + max_e = max_e.max(bm0); | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + // Geometric mean of frame energy and half the max | ||
| 89 | + mean = (mean * max_e * 0.5 * len2 as f32).sqrt(); | ||
| 90 | + | ||
| 91 | + // Inverse of the mean energy (float mode: SHL32/SHR32 are no-ops) | ||
| 92 | + let norm = len2 as f32 / (1e-15 + mean); | ||
| 93 | + | ||
| 94 | + // Harmonic mean discarding unreliable boundaries (1/4th of samples) | ||
| 95 | + let mut unmask: i32 = 0; | ||
| 96 | + let mut i = 12; | ||
| 97 | + while i < len2 - 5 { | ||
| 98 | + let id = ((64.0 * norm * (tmp[i] + 1e-15)).floor() as i32).clamp(0, 127) as usize; | ||
| 99 | + unmask += INV_TABLE[id] as i32; | ||
| 100 | + i += 4; | ||
| 101 | + } | ||
| 102 | + // Normalize: 1/4th sampling, factor of 6 in inv_table | ||
| 103 | + unmask = 64 * unmask * 4 / (6 * (len2 as i32 - 17)); | ||
| 104 | + if unmask > mask_metric { | ||
| 105 | + tf_chan = ch; | ||
| 106 | + mask_metric = unmask; | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + let is_transient = mask_metric > 200; | ||
| 111 | + // tf_max and tf_estimate (float mode: all Q-shifts are no-ops) | ||
| 112 | + let tf_max = ((27.0 * mask_metric as f32).sqrt() - 42.0).max(0.0); | ||
| 113 | + let tf_estimate = (0.0069 * tf_max.min(163.0) - 0.139).max(0.0).sqrt(); | ||
| 114 | + | ||
| 115 | + (is_transient, tf_estimate, tf_chan) | ||
| 116 | + } | ||
| 117 | +``` | ||
| 118 | + | ||
| 119 | +**Edit 4: Add tf_analysis method** — insert after `tf_encode` method ends (~line 1295, after the closing `}` of tf_encode, before `// -- Band shapes --`): | ||
| 120 | +```rust | ||
| 121 | + /// `tf_analysis()` — libopus Viterbi time/frequency search. | ||
| 122 | + /// Writes `self.tf_res[0..len]` and returns `tf_select`. | ||
| 123 | + #[allow(clippy::too_many_arguments)] | ||
| 124 | + fn tf_analysis( | ||
| 125 | + &mut self, | ||
| 126 | + len: usize, | ||
| 127 | + is_transient: bool, | ||
| 128 | + lambda: i32, | ||
| 129 | + n: usize, | ||
| 130 | + lm: usize, | ||
| 131 | + tf_estimate: f32, | ||
| 132 | + tf_chan: usize, | ||
| 133 | + importance: &[i32; NB_BANDS], | ||
| 134 | + ) -> usize { | ||
| 135 | + // bias = 0.04 * max(-0.25, 0.5 - tf_estimate) | ||
| 136 | + let bias = 0.04 * (0.5 - tf_estimate).max(-0.25); | ||
| 137 | + let t = usize::from(is_transient); | ||
| 138 | + | ||
| 139 | + let mut metric = [0i32; NB_BANDS]; | ||
| 140 | + let mut path0 = [0i32; NB_BANDS]; | ||
| 141 | + let mut path1 = [0i32; NB_BANDS]; | ||
| 142 | + let mut tf_res = [0i32; NB_BANDS]; | ||
| 143 | + | ||
| 144 | + // Max band width for tmp/tmp_1 scratch | ||
| 145 | + let max_band_w = ((E_BANDS[len] - E_BANDS[len - 1]) << lm).max(1); | ||
| 146 | + let (tmp_s, tmp_1_s) = self.hadamard_tmp.split_at_mut(max_band_w); | ||
| 147 | + let x = &self.x; | ||
| 148 | + | ||
| 149 | + for i in 0..len { | ||
| 150 | + let band_w = (E_BANDS[i + 1] - E_BANDS[i]) << lm; | ||
| 151 | + let narrow = E_BANDS[i + 1] - E_BANDS[i] == 1; | ||
| 152 | + let tmp = &mut tmp_s[..band_w]; | ||
| 153 | + let tmp_1 = &mut tmp_1_s[..band_w]; | ||
| 154 | + | ||
| 155 | + // Copy band coefficients: X[tf_chan*N0 + (eBands[i]<<LM)] | ||
| 156 | + let offset = tf_chan * n + (E_BANDS[i] << lm); | ||
| 157 | + tmp.copy_from_slice(&x[offset..offset + band_w]); | ||
| 158 | + | ||
| 159 | + let mut best_level = 0i32; | ||
| 160 | + let mut best_l1 = l1_metric(tmp, band_w, if is_transient { lm } else { 0 }, bias); | ||
| 161 | + | ||
| 162 | + // Check the -1 case for transients | ||
| 163 | + if is_transient && !narrow { | ||
| 164 | + tmp_1.copy_from_slice(tmp); | ||
| 165 | + haar1(tmp_1, band_w >> lm, 1 << lm); | ||
| 166 | + let l1 = l1_metric(tmp_1, band_w, lm + 1, bias); | ||
| 167 | + if l1 < best_l1 { | ||
| 168 | + best_l1 = l1; | ||
| 169 | + best_level = -1; | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + for k in 0..(lm + usize::from(!(is_transient || narrow))) { | ||
| 174 | + let b = if is_transient { lm - k - 1 } else { k + 1 }; | ||
| 175 | + haar1(tmp, band_w >> k, 1 << k); | ||
| 176 | + let l1 = l1_metric(tmp, band_w, b, bias); | ||
| 177 | + if l1 < best_l1 { | ||
| 178 | + best_l1 = l1; | ||
| 179 | + best_level = (k as i32) + 1; | ||
| 180 | + } | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + metric[i] = if is_transient { 2 * best_level } else { -2 * best_level }; | ||
| 184 | + if narrow && (metric[i] == 0 || metric[i] == -2 * lm as i32) { | ||
| 185 | + metric[i] -= 1; | ||
| 186 | + } | ||
| 187 | + } | ||
| 188 | + | ||
| 189 | + // Search for optimal tf resolution (tf_select) | ||
| 190 | + let mut tf_select = 0usize; | ||
| 191 | + let mut selcost = [0i32; 2]; | ||
| 192 | + for sel in 0..2 { | ||
| 193 | + let mut cost0 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * sel]).abs(); | ||
| 194 | + let mut cost1 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * sel + 1]).abs() | ||
| 195 | + + if is_transient { 0 } else { lambda }; | ||
| 196 | + for i in 1..len { | ||
| 197 | + let curr0 = cost0.min(cost1 + lambda); | ||
| 198 | + let curr1 = (cost0 + lambda).min(cost1); | ||
| 199 | + cost0 = curr0 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * sel]).abs(); | ||
| 200 | + cost1 = curr1 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * sel + 1]).abs(); | ||
| 201 | + } | ||
| 202 | + selcost[sel] = cost0.min(cost1); | ||
| 203 | + } | ||
| 204 | + if selcost[1] < selcost[0] && is_transient { | ||
| 205 | + tf_select = 1; | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + // Final Viterbi forward pass | ||
| 209 | + let mut cost0 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select]).abs(); | ||
| 210 | + let mut cost1 = importance[0] * (metric[0] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select + 1]).abs() | ||
| 211 | + + if is_transient { 0 } else { lambda }; | ||
| 212 | + for i in 1..len { | ||
| 213 | + // curr0: best path to state 0 | ||
| 214 | + let from0 = cost0; | ||
| 215 | + let from1 = cost1 + lambda; | ||
| 216 | + let (curr0, p0) = if from0 < from1 { (from0, 0) } else { (from1, 1) }; | ||
| 217 | + path0[i] = p0; | ||
| 218 | + // curr1: best path to state 1 (uses OLD cost0) | ||
| 219 | + let from0 = cost0 + lambda; | ||
| 220 | + let from1 = cost1; | ||
| 221 | + let (curr1, p1) = if from0 < from1 { (from0, 0) } else { (from1, 1) }; | ||
| 222 | + path1[i] = p1; | ||
| 223 | + | ||
| 224 | + cost0 = curr0 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select]).abs(); | ||
| 225 | + cost1 = curr1 + importance[i] * (metric[i] - 2 * TF_SELECT[lm][4 * t + 2 * tf_select + 1]).abs(); | ||
| 226 | + } | ||
| 227 | + | ||
| 228 | + // Backward pass | ||
| 229 | + tf_res[len - 1] = if cost0 < cost1 { 0 } else { 1 }; | ||
| 230 | + for i in (0..len - 1).rev() { | ||
| 231 | + tf_res[i] = if tf_res[i + 1] == 1 { path1[i + 1] } else { path0[i + 1] }; | ||
| 232 | + } | ||
| 233 | + | ||
| 234 | + self.tf_res = tf_res; | ||
| 235 | + tf_select | ||
| 236 | + } | ||
| 237 | +``` | ||
| 238 | + | ||
| 239 | +**Edit 5: Update transient call site** (lines 579-583). Replace: | ||
| 240 | +```rust | ||
| 241 | + let mut is_transient = false; | ||
| 242 | + let mut short_blocks = 0usize; | ||
| 243 | + if lm > 0 && enc.tell() as i32 + 3 <= total_bits { | ||
| 244 | + is_transient = self.transient_analysis(n + OVERLAP, c, stride); | ||
| 245 | +``` | ||
| 246 | +with: | ||
| 247 | +```rust | ||
| 248 | + let mut is_transient = false; | ||
| 249 | + let mut short_blocks = 0usize; | ||
| 250 | + let mut tf_estimate = 0.0f32; | ||
| 251 | + let mut tf_chan = 0usize; | ||
| 252 | + if lm > 0 && enc.tell() as i32 + 3 <= total_bits { | ||
| 253 | + let (ta, te, tc) = self.transient_analysis(n + OVERLAP, c, stride); | ||
| 254 | + is_transient = ta; | ||
| 255 | + tf_estimate = te; | ||
| 256 | + tf_chan = tc; | ||
| 257 | +``` | ||
| 258 | + | ||
| 259 | +**Edit 6: Replace tf_res wiring** (lines 611-612). Replace: | ||
| 260 | +```rust | ||
| 261 | + self.tf_res = [0; NB_BANDS]; | ||
| 262 | + let tf_select = 0usize; | ||
| 263 | +``` | ||
| 264 | +with: | ||
| 265 | +```rust | ||
| 266 | + let tf_select = if effective_bytes >= 15 * c as i32 { | ||
| 267 | + let lambda = (80i32).max(20480 / effective_bytes + 2); | ||
| 268 | + let mut importance = [0i32; NB_BANDS]; | ||
| 269 | + for i in start..end { | ||
| 270 | + importance[i] = 13; | ||
| 271 | + } | ||
| 272 | + self.tf_analysis(end, is_transient, lambda, n, lm, tf_estimate, tf_chan, &importance) | ||
| 273 | + } else { | ||
| 274 | + self.tf_res = [0; NB_BANDS]; | ||
| 275 | + 0usize | ||
| 276 | + }; | ||
| 277 | +``` | ||
| 278 | + | ||
| 279 | +### After edits | ||
| 280 | +1. `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-opus-drop` | ||
| 281 | +2. `cargo check -p ec-opus` — fix any borrow/type errors | ||
| 282 | +3. Gate test: `SWEEP_ONLY=reelm,hein cargo test -p ec-opus --release --test conformance encoder_library_gate_vs_libopus -- --ignored --nocapture` | ||
| 283 | +4. Compare to baselines: reelm@64 gap +.0043 minsec .9148; hein@64 +.0020 minsec .9210 — keep only if BOTH gaps shrink and minsec holds | ||
| 284 | +5. If gate passes: full 14-row sweep vs `lanes/opus-drop-r2.sweep.txt` (no row corr −.001, no dropouts, rate ±5%) | ||
| 285 | +6. `git checkout -- lanes/opus-gate-r1.sweep.txt` before committing | ||
| 286 | +7. If gate fails: wrap wiring in `const TF_ANALYSIS: bool = false;` gate, commit behind flag | ||
| 287 | +8. Write `lanes/opus-64-r3.handoff.md` | ||
| 288 | + | ||
| 289 | +### Key verified facts | ||
| 290 | +- Float-mode macros (`arch.h:210-268`): `SHR32/SHL32/PSHR32` = identity, `MULT16_16_Q14(a,b)=a*b`, `MULT16_16_P15(a,b)=a*b`, `SROUND16=identity`, `QCONST16(x,b)=x`, `EPSILON=1e-15`, `EXTEND32=identity`, `ADD32=a+b`, `celt_sqrt=(float)sqrt(x)` | ||
| 291 | +- `haar1(x: &mut [f32], n0: usize, stride: usize)` at `celt.rs:2580` | ||
| 292 | +- Input layout: C uses `in[i+c*len]`, Rust uses `in_buf[ch*stride+i]` where `stride=len=n+OVERLAP` — same layout | ||
| 293 | +- `effEnd = end` for CELT-only 48kHz (C line 1612), so `len=end` is correct | ||
| 294 | +- `effective_bytes` is `i32`, declared line 497, never reassigned before line 611 | ||
| 295 | +- `tf_encode` (lines 1256-1295) already correct — no changes needed | ||
| 296 | +- Borrow strategy: split `self.hadamard_tmp` once, borrow `self.x` as `&`, use local `tf_res` array, write `self.tf_res` at end | ||
| 297 | +- `importance[i]=13` for `start..end`, 0 elsewhere — matches C's `else` branch in `dynalloc_analysis` (line 1157) | ||
| 298 | +- `allow_weak_transients=false` — skip weak transient path entirely | ||
| 299 | +- `len2-17` in unmask normalization: for 960-sample frames, `len2=480`, `len2-17=463` — safe (no div-by-zero) | ||