SBR HF generation and envelope adjustment, unwired
Browse files at this commit49f840b412b570e34063b048b3c46d6f2ee823c0Parent: 2ebc6c0- feat
- SBR HF generation and envelope adjustment, unwired
3 changed files +683 -2
- crates/ec-aac/src/lib.rs +2 -2
- crates/ec-aac/src/sbr_env.rs +340 -0
- crates/ec-aac/src/sbr_hf.rs +341 -0
crates/ec-aac/src/lib.rsmodified+2 -2
| @@ -29,9 +29,9 @@ mod decode; | |||
| 29 | mod encode; | 29 | mod encode; |
| 30 | mod huffman; | 30 | mod huffman; |
| 31 | mod sbr_bands; | 31 | mod sbr_bands; |
| 32 | +mod sbr_env; | ||
| 33 | +mod sbr_hf; | ||
| 32 | mod sbr_payload; | 34 | mod sbr_payload; |
| 33 | -// Consumed once the SBR decode chain lands; until then only its tests call it. | ||
| 34 | -#[allow(dead_code)] | ||
| 35 | mod sbr_qmf; | 35 | mod sbr_qmf; |
| 36 | mod sbr_tables; | 36 | mod sbr_tables; |
| 37 | pub mod tables; | 37 | pub mod tables; |
crates/ec-aac/src/sbr_env.rsadded+340 -0
| @@ -0,0 +1,340 @@ | |||
| 1 | +//! SBR envelope adjustment (ISO/IEC 14496-3 §4.6.18.7): scales the raw HF | ||
| 2 | +//! QMF estimate [`crate::sbr_hf::generate`] produced so each transmitted | ||
| 3 | +//! (envelope, band) cell carries the energy the encoder actually measured, | ||
| 4 | +//! injects the transmitted noise floor, and adds sinusoids at the bands | ||
| 5 | +//! `bs_add_harmonic` flags. | ||
| 6 | +//! | ||
| 7 | +//! # Dequantization | ||
| 8 | +//! | ||
| 9 | +//! A plain (non-coupled) envelope's linear energy is `2^(alpha * e_q)` | ||
| 10 | +//! with `alpha = 1.0` at `bs_amp_res = 1` (3 dB steps) and `0.5` at | ||
| 11 | +//! `bs_amp_res = 0` (1.5 dB steps); the noise floor is `2^(6 - q_q)` | ||
| 12 | +//! (`NOISE_FLOOR_OFFSET = 6`). A coupled CPE's balance channel (`e_q`'s | ||
| 13 | +//! second channel) carries a log-ratio rather than an absolute | ||
| 14 | +//! scalefactor; `dequant_pair` de-mixes it against channel 0's raw value | ||
| 15 | +//! into left/right energies that are equal (and sum to `2 * channel 0's | ||
| 16 | +//! energy`) when the ratio is centred, which is the symmetric convention | ||
| 17 | +//! this module uses in the absence of an exercised real-file fixture for | ||
| 18 | +//! it (corner-cut: exact reference offset unverified, ceiling = a | ||
| 19 | +//! panning-accuracy-only artifact on files whose SBR CPE actually | ||
| 20 | +//! couples, upgrade path = pin against a captured coupled real-file | ||
| 21 | +//! trace). | ||
| 22 | +//! | ||
| 23 | +//! # Gain, limiter, noise, sinusoids | ||
| 24 | +//! | ||
| 25 | +//! For every `(envelope, band)` cell this measures the HF estimate's own | ||
| 26 | +//! average energy over that time/frequency window and scales it toward | ||
| 27 | +//! the transmitted target; the limiter then caps how far above the | ||
| 28 | +//! band's own transmitted noise floor that gain is allowed to reach | ||
| 29 | +//! (`bs_limiter_gains`), noise is mixed in at the transmitted floor, and | ||
| 30 | +//! flagged bands get an added tone. | ||
| 31 | + | ||
| 32 | +use crate::sbr_bands::BandTables; | ||
| 33 | +use crate::sbr_payload::{SbrChannel, SbrHeader}; | ||
| 34 | +use ec_dsp::Complex; | ||
| 35 | + | ||
| 36 | +const NOISE_FLOOR_OFFSET: f64 = 6.0; | ||
| 37 | + | ||
| 38 | +/// Envelope amp-resolution exponent: `2.0` (`bs_amp_res=1`, 3 dB) or `1.0` | ||
| 39 | +/// (`bs_amp_res=0`, 1.5 dB) -- expressed as the multiplier on `e_q/2` so | ||
| 40 | +/// callers can write `2f64.powf(alpha * e_q as f64 / 2.0)` uniformly, or | ||
| 41 | +/// just use [`dequant_env`] directly. | ||
| 42 | +fn alpha(amp_res: u8) -> f64 { | ||
| 43 | + if amp_res != 0 { 1.0 } else { 0.5 } | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// Plain (non-coupled) envelope dequantization. | ||
| 47 | +pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 { | ||
| 48 | + 2f64.powf(alpha(amp_res) * f64::from(e_q)) | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// Plain noise-floor dequantization. | ||
| 52 | +pub fn dequant_noise(q_q: i32) -> f64 { | ||
| 53 | + 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q_q)) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into | ||
| 57 | +/// `(left, right)` linear energies. See the module doc for the convention. | ||
| 58 | +pub fn dequant_pair(e0_raw: i32, e1_raw: i32, amp_res: u8) -> (f64, f64) { | ||
| 59 | + let e0 = dequant_env(e0_raw, amp_res); | ||
| 60 | + let ratio = 2f64.powf(alpha(amp_res) * f64::from(e1_raw)); | ||
| 61 | + let left = 2.0 * e0 * ratio / (1.0 + ratio); | ||
| 62 | + let right = 2.0 * e0 / (1.0 + ratio); | ||
| 63 | + (left, right) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// A small deterministic PRNG for the injected noise floor -- the same | ||
| 67 | +/// generator shape `decode::Noise` uses, kept local so this module has no | ||
| 68 | +/// dependency on the core decoder's internals. | ||
| 69 | +pub struct NoiseGen(u32); | ||
| 70 | + | ||
| 71 | +impl NoiseGen { | ||
| 72 | + pub fn new(seed: u32) -> NoiseGen { | ||
| 73 | + NoiseGen(seed | 1) | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + fn next(&mut self) -> f64 { | ||
| 77 | + self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 78 | + f64::from(self.0 >> 8) / f64::from(1u32 << 23) - 0.5 | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + fn complex_unit(&mut self) -> Complex<f64> { | ||
| 82 | + Complex::new(self.next(), self.next()) | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +const LIMITER_FACTOR: [f64; 4] = [1.4125, 2.0, 4.0, 1.0e6]; // 1.5/3/6 dB, "no limit" | ||
| 87 | + | ||
| 88 | +/// Applies envelope adjustment in place to `hf` (`[target band 0-based | ||
| 89 | +/// from kx][slot]`, as [`crate::sbr_hf::generate`] returns it): gain | ||
| 90 | +/// toward `env_energy`, the transmitted noise floor from `noise_energy`, | ||
| 91 | +/// and sinusoids at `ch.add_harmonic`'s flagged high-resolution bands. | ||
| 92 | +#[allow(clippy::too_many_arguments)] | ||
| 93 | +pub fn adjust( | ||
| 94 | + hf: &mut [Vec<Complex<f64>>], | ||
| 95 | + tables: &BandTables, | ||
| 96 | + header: &SbrHeader, | ||
| 97 | + ch: &SbrChannel, | ||
| 98 | + env_energy: &[Vec<f64>], | ||
| 99 | + noise_energy: &[Vec<f64>], | ||
| 100 | + rng: &mut NoiseGen, | ||
| 101 | +) { | ||
| 102 | + let kx = tables.kx as usize; | ||
| 103 | + let limiter_max = LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]; | ||
| 104 | + | ||
| 105 | + // Noise floor first: every target bin gets the transmitted floor for | ||
| 106 | + // its noise-time-segment and noise-frequency-band, independent of the | ||
| 107 | + // envelope grid (they are different, coarser grids over the same axes). | ||
| 108 | + for (ni, (t0, t1)) in ch.t_noise.windows(2).map(|w| (w[0], w[1])).enumerate() { | ||
| 109 | + if ni >= noise_energy.len() { | ||
| 110 | + break; | ||
| 111 | + } | ||
| 112 | + for q in 0..tables.n_q { | ||
| 113 | + let lo = tables.f_noise[q] as usize; | ||
| 114 | + let hi = tables.f_noise[q + 1] as usize; | ||
| 115 | + let energy = noise_energy[ni].get(q).copied().unwrap_or(0.0); | ||
| 116 | + let amp = (energy / (hi - lo).max(1) as f64).sqrt(); | ||
| 117 | + for band in lo..hi { | ||
| 118 | + if band < kx || band - kx >= hf.len() { | ||
| 119 | + continue; | ||
| 120 | + } | ||
| 121 | + let row = &mut hf[band - kx]; | ||
| 122 | + for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) { | ||
| 123 | + row[slot] = row[slot] + rng.complex_unit().scale(amp); | ||
| 124 | + } | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + | ||
| 129 | + // Gain toward the transmitted envelope, per (envelope, band) cell, | ||
| 130 | + // limited relative to that cell's own noise floor. | ||
| 131 | + for (ei, (t0, t1)) in ch.t_env.windows(2).map(|w| (w[0], w[1])).enumerate() { | ||
| 132 | + if ei >= env_energy.len() { | ||
| 133 | + break; | ||
| 134 | + } | ||
| 135 | + let high_res = ch.freq_res.get(ei).copied().unwrap_or(0) != 0; | ||
| 136 | + let table = if high_res { &tables.f_high } else { &tables.f_low }; | ||
| 137 | + // The noise segment covering this envelope's time range (noise | ||
| 138 | + // borders are a coarser subset of the envelope borders sharing the | ||
| 139 | + // same start/end points). | ||
| 140 | + let noise_row: Option<&Vec<f64>> = ch | ||
| 141 | + .t_noise | ||
| 142 | + .windows(2) | ||
| 143 | + .position(|w| t0 >= w[0] && t0 < w[1]) | ||
| 144 | + .and_then(|ni| noise_energy.get(ni)); | ||
| 145 | + for b in 0..table.len().saturating_sub(1) { | ||
| 146 | + let lo = table[b] as usize; | ||
| 147 | + let hi = table[b + 1] as usize; | ||
| 148 | + let target = env_energy[ei].get(b).copied().unwrap_or(0.0); | ||
| 149 | + let (mut sum, mut count) = (0.0f64, 0usize); | ||
| 150 | + for band in lo..hi { | ||
| 151 | + if band < kx || band - kx >= hf.len() { | ||
| 152 | + continue; | ||
| 153 | + } | ||
| 154 | + let row = &hf[band - kx]; | ||
| 155 | + for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) { | ||
| 156 | + sum += row[slot].norm_sqr(); | ||
| 157 | + count += 1; | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | + let current = if count > 0 { sum / count as f64 } else { 0.0 }; | ||
| 161 | + let mut gain = (target / current.max(1e-12)).sqrt(); | ||
| 162 | + let q = noise_band_for(tables, lo); | ||
| 163 | + let noise_here = noise_row | ||
| 164 | + .and_then(|r| r.get(q).copied()) | ||
| 165 | + .unwrap_or(0.0) | ||
| 166 | + .max(1e-12); | ||
| 167 | + gain = gain.min((noise_here * limiter_max / current.max(1e-12)).sqrt().max(gain.min(limiter_max))); | ||
| 168 | + gain = gain.min(limiter_max * 64.0); // absolute ceiling: never amplify a silent cell to infinity | ||
| 169 | + for band in lo..hi { | ||
| 170 | + if band < kx || band - kx >= hf.len() { | ||
| 171 | + continue; | ||
| 172 | + } | ||
| 173 | + let row = &mut hf[band - kx]; | ||
| 174 | + for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) { | ||
| 175 | + row[slot] = row[slot].scale(gain); | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + | ||
| 180 | + // Sinusoids: one extra tone per flagged high-resolution band, | ||
| 181 | + // added after gain so its amplitude is exact regardless of the | ||
| 182 | + // cell's measured HF energy. | ||
| 183 | + if let Some(flags) = &ch.add_harmonic { | ||
| 184 | + for (b, &on) in flags.iter().enumerate() { | ||
| 185 | + if on == 0 || b + 1 >= tables.f_high.len() { | ||
| 186 | + continue; | ||
| 187 | + } | ||
| 188 | + let lo = tables.f_high[b] as usize; | ||
| 189 | + let hi = tables.f_high[b + 1] as usize; | ||
| 190 | + let e = if high_res { | ||
| 191 | + env_energy[ei].get(b).copied().unwrap_or(0.0) | ||
| 192 | + } else { | ||
| 193 | + // The envelope grid was low-res this frame; approximate | ||
| 194 | + // the harmonic band's share of its low-res parent cell. | ||
| 195 | + let lb = table | ||
| 196 | + .iter() | ||
| 197 | + .position(|&x| x as usize > lo) | ||
| 198 | + .map(|i| i.saturating_sub(1)) | ||
| 199 | + .unwrap_or(0); | ||
| 200 | + env_energy[ei].get(lb).copied().unwrap_or(0.0) | ||
| 201 | + }; | ||
| 202 | + let amp = (2.0 * e).sqrt(); | ||
| 203 | + for band in lo..hi { | ||
| 204 | + if band < kx || band - kx >= hf.len() { | ||
| 205 | + continue; | ||
| 206 | + } | ||
| 207 | + let row = &mut hf[band - kx]; | ||
| 208 | + for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) { | ||
| 209 | + row[slot] = row[slot] + Complex::new(amp, 0.0); | ||
| 210 | + } | ||
| 211 | + } | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +fn noise_band_for(tables: &BandTables, low_band: usize) -> usize { | ||
| 218 | + let mut q = 0usize; | ||
| 219 | + for i in 0..tables.n_q { | ||
| 220 | + if (low_band as i64) >= tables.f_noise[i] { | ||
| 221 | + q = i; | ||
| 222 | + } | ||
| 223 | + } | ||
| 224 | + q | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +#[cfg(test)] | ||
| 228 | +mod tests { | ||
| 229 | + use super::*; | ||
| 230 | + use crate::sbr_bands::freq_tables; | ||
| 231 | + use crate::sbr_payload::SbrChannel; | ||
| 232 | + | ||
| 233 | + fn flat_tables() -> BandTables { | ||
| 234 | + freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap() | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + fn header(amp_res: u8, limiter_gains: u8) -> SbrHeader { | ||
| 238 | + SbrHeader { | ||
| 239 | + amp_res, | ||
| 240 | + start_freq: 5, | ||
| 241 | + stop_freq: 3, | ||
| 242 | + xover_band: 2, | ||
| 243 | + freq_scale: 2, | ||
| 244 | + alter_scale: 1, | ||
| 245 | + noise_bands: 2, | ||
| 246 | + limiter_bands: 2, | ||
| 247 | + limiter_gains, | ||
| 248 | + interpol_freq: 1, | ||
| 249 | + smoothing_mode: 1, | ||
| 250 | + } | ||
| 251 | + } | ||
| 252 | + | ||
| 253 | + #[test] | ||
| 254 | + fn flat_hf_region_reaches_the_stated_envelope_energy() { | ||
| 255 | + let tables = flat_tables(); | ||
| 256 | + let kx = tables.kx as usize; | ||
| 257 | + let k2 = tables.k2 as usize; | ||
| 258 | + let slots = 16usize; | ||
| 259 | + let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx]; | ||
| 260 | + let ch = SbrChannel { | ||
| 261 | + t_env: vec![0, 16], | ||
| 262 | + freq_res: vec![0], | ||
| 263 | + t_noise: vec![0, 16], | ||
| 264 | + e_q: vec![vec![]], | ||
| 265 | + q_q: vec![vec![]], | ||
| 266 | + invf_mode: vec![], | ||
| 267 | + add_harmonic: None, | ||
| 268 | + }; | ||
| 269 | + let target = 4.0f64; | ||
| 270 | + let env_energy = vec![vec![target; tables.n_low]]; | ||
| 271 | + let noise_energy = vec![vec![0.0f64; tables.n_q]]; | ||
| 272 | + let mut rng = NoiseGen::new(1); | ||
| 273 | + adjust(&mut hf, &tables, &header(1, 3), &ch, &env_energy, &noise_energy, &mut rng); | ||
| 274 | + | ||
| 275 | + // Every low-res band's average energy should land close to target. | ||
| 276 | + for b in 0..tables.n_low { | ||
| 277 | + let lo = tables.f_low[b] as usize; | ||
| 278 | + let hi = tables.f_low[b + 1] as usize; | ||
| 279 | + let mut sum = 0.0; | ||
| 280 | + let mut n = 0usize; | ||
| 281 | + for band in lo..hi { | ||
| 282 | + if band < kx { | ||
| 283 | + continue; | ||
| 284 | + } | ||
| 285 | + for slot in 0..slots { | ||
| 286 | + sum += hf[band - kx][slot].norm_sqr(); | ||
| 287 | + n += 1; | ||
| 288 | + } | ||
| 289 | + } | ||
| 290 | + if n == 0 { | ||
| 291 | + continue; | ||
| 292 | + } | ||
| 293 | + let avg = sum / n as f64; | ||
| 294 | + assert!( | ||
| 295 | + (avg - target).abs() / target < 0.05, | ||
| 296 | + "band {b}: avg {avg} vs target {target}" | ||
| 297 | + ); | ||
| 298 | + } | ||
| 299 | + } | ||
| 300 | + | ||
| 301 | + #[test] | ||
| 302 | + fn limiter_caps_a_pathological_gain() { | ||
| 303 | + let tables = flat_tables(); | ||
| 304 | + let kx = tables.kx as usize; | ||
| 305 | + let k2 = tables.k2 as usize; | ||
| 306 | + let slots = 16usize; | ||
| 307 | + // Near-silent HF estimate against a huge target energy: an | ||
| 308 | + // unlimited gain would blow this up by many orders of magnitude. | ||
| 309 | + let mut hf = vec![vec![Complex::new(1e-9, 0.0); slots]; k2 - kx]; | ||
| 310 | + let ch = SbrChannel { | ||
| 311 | + t_env: vec![0, 16], | ||
| 312 | + freq_res: vec![0], | ||
| 313 | + t_noise: vec![0, 16], | ||
| 314 | + e_q: vec![vec![]], | ||
| 315 | + q_q: vec![vec![]], | ||
| 316 | + invf_mode: vec![], | ||
| 317 | + add_harmonic: None, | ||
| 318 | + }; | ||
| 319 | + let env_energy = vec![vec![1.0e6f64; tables.n_low]]; | ||
| 320 | + let noise_energy = vec![vec![1e-3f64; tables.n_q]]; | ||
| 321 | + let mut rng = NoiseGen::new(1); | ||
| 322 | + adjust(&mut hf, &tables, &header(1, 0), &ch, &env_energy, &noise_energy, &mut rng); | ||
| 323 | + for band in 0..hf.len() { | ||
| 324 | + for slot in 0..slots { | ||
| 325 | + assert!( | ||
| 326 | + hf[band][slot].norm_sqr().sqrt() < 1.0, | ||
| 327 | + "limiter failed to cap band {band} slot {slot}: {:?}", | ||
| 328 | + hf[band][slot] | ||
| 329 | + ); | ||
| 330 | + } | ||
| 331 | + } | ||
| 332 | + } | ||
| 333 | + | ||
| 334 | + #[test] | ||
| 335 | + fn coupled_balance_round_trips_at_a_centred_ratio() { | ||
| 336 | + let (l, r) = dequant_pair(10, 0, 1); | ||
| 337 | + let e0 = dequant_env(10, 1); | ||
| 338 | + assert!((l - e0).abs() < 1e-9 && (r - e0).abs() < 1e-9, "{l} {r} vs {e0}"); | ||
| 339 | + } | ||
| 340 | +} | ||
crates/ec-aac/src/sbr_hf.rsadded+341 -0
| @@ -0,0 +1,341 @@ | |||
| 1 | +//! SBR high-frequency generation (ISO/IEC 14496-3 §4.6.18.6): patch | ||
| 2 | +//! construction that copies low-band QMF content up into the region the | ||
| 3 | +//! core codec never carried, plus per-subband second-order linear | ||
| 4 | +//! prediction (LPC) whose bandwidth-expanded ("chirped") coefficients | ||
| 5 | +//! whiten the copied content so it can be re-tonalised by the envelope | ||
| 6 | +//! adjustment stage rather than sounding like a raw comb of copies. | ||
| 7 | +//! | ||
| 8 | +//! # Patch construction | ||
| 9 | +//! | ||
| 10 | +//! Each patch copies a contiguous run of QMF bands from just below the | ||
| 11 | +//! crossover (`kx`) up into the target HF region `[kx, k2)`. The walk keeps | ||
| 12 | +//! two pointers: `msb`, the source read pointer, starts at `kx` and moves | ||
| 13 | +//! *down* toward band 0 as patches are consumed; `sb`, the target write | ||
| 14 | +//! pointer, starts at `kx` and moves *up* toward `k2`. A patch's width is | ||
| 15 | +//! chosen to land on a boundary of the target-side high-resolution band | ||
| 16 | +//! table (`tables.f_high`) so envelope adjustment never has to split a | ||
| 17 | +//! patch mid-band, and is capped by how many source bands remain below the | ||
| 18 | +//! current `msb`. When the source is exhausted the read pointer wraps back | ||
| 19 | +//! to `kx` (the band closest to the crossover, so the next patch borrows | ||
| 20 | +//! the most plausible content again rather than running off the bottom of | ||
| 21 | +//! the spectrum). | ||
| 22 | +//! | ||
| 23 | +//! # Linear prediction and chirp | ||
| 24 | +//! | ||
| 25 | +//! For each *source* subband, a covariance-method order-2 LPC is fit to | ||
| 26 | +//! that subband's own QMF time series (two slots of carried-over history | ||
| 27 | +//! plus the current frame's slots). The residual against those raw | ||
| 28 | +//! coefficients is then re-synthesised through a *bandwidth-expanded* | ||
| 29 | +//! all-pole filter -- coefficients scaled by `bw` and `bw^2` -- which is | ||
| 30 | +//! the standard SBR "inverse filtering" trick: `bw` near 1 leaves the | ||
| 31 | +//! subband's own resonance intact (a strongly tonal patch), `bw` near 0 | ||
| 32 | +//! flattens it toward its whitened residual (a noise-like patch). `bw` | ||
| 33 | +//! itself comes from `bs_invf_mode` and is smoothed frame to frame with a | ||
| 34 | +//! fast-attack/slow-release curve so inverse-filter mode changes don't pop. | ||
| 35 | + | ||
| 36 | +use crate::sbr_bands::BandTables; | ||
| 37 | +use ec_dsp::Complex; | ||
| 38 | + | ||
| 39 | +/// One copy-up patch: `width` consecutive QMF bands starting at | ||
| 40 | +/// `source_start` are written to `target_start..target_start+width`. | ||
| 41 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 42 | +pub struct Patch { | ||
| 43 | + pub source_start: usize, | ||
| 44 | + pub target_start: usize, | ||
| 45 | + pub width: usize, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// Builds the patch list filling `[tables.kx, tables.k2)` from bands below | ||
| 49 | +/// `kx`, walking the source pointer down and wrapping it back to `kx` when | ||
| 50 | +/// exhausted. Deterministic: the same tables always produce the same patches. | ||
| 51 | +pub fn build_patches(tables: &BandTables) -> Vec<Patch> { | ||
| 52 | + let kx = tables.kx as usize; | ||
| 53 | + let k2 = tables.k2 as usize; | ||
| 54 | + let f_high: Vec<usize> = tables.f_high.iter().map(|&b| b as usize).collect(); | ||
| 55 | + let mut patches = Vec::new(); | ||
| 56 | + if kx == 0 || k2 <= kx { | ||
| 57 | + return patches; | ||
| 58 | + } | ||
| 59 | + let mut msb = kx; // source read pointer, decreasing | ||
| 60 | + let mut sb = kx; // target write pointer, increasing | ||
| 61 | + while sb < k2 { | ||
| 62 | + // Widest run of consecutive f_high intervals starting at `sb` whose | ||
| 63 | + // total width still fits below the current source pointer. | ||
| 64 | + let mut width = 0usize; | ||
| 65 | + let mut probe = sb; | ||
| 66 | + loop { | ||
| 67 | + let next_border = f_high.iter().find(|&&b| b > probe).copied(); | ||
| 68 | + let Some(border) = next_border else { break }; | ||
| 69 | + let iv = border - probe; | ||
| 70 | + if width + iv > msb || border > k2 { | ||
| 71 | + break; | ||
| 72 | + } | ||
| 73 | + width += iv; | ||
| 74 | + probe = border; | ||
| 75 | + } | ||
| 76 | + if width == 0 { | ||
| 77 | + width = (k2 - sb).min(msb.max(1)); | ||
| 78 | + } | ||
| 79 | + let source_start = msb - width.min(msb); | ||
| 80 | + patches.push(Patch { | ||
| 81 | + source_start, | ||
| 82 | + target_start: sb, | ||
| 83 | + width, | ||
| 84 | + }); | ||
| 85 | + sb += width; | ||
| 86 | + msb = if source_start == 0 { kx } else { source_start }; | ||
| 87 | + } | ||
| 88 | + patches | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// `bs_invf_mode` bandwidth-expansion targets (OFF, LOW, MID, HIGH), the | ||
| 92 | +/// four inverse-filtering strengths §4.6.18.6.2 defines. | ||
| 93 | +const BW_TABLE: [f64; 4] = [0.0, 0.6, 0.9, 0.98]; | ||
| 94 | + | ||
| 95 | +/// Per-noise-band chirp factor state, smoothed frame to frame with a | ||
| 96 | +/// fast-attack (toward a *lower* bw, i.e. more whitening) / slow-release | ||
| 97 | +/// curve, as the spec's own smoothing does. | ||
| 98 | +#[derive(Clone, Debug)] | ||
| 99 | +pub struct ChirpState { | ||
| 100 | + bw: Vec<f64>, | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +impl ChirpState { | ||
| 104 | + pub fn new(n_q: usize) -> ChirpState { | ||
| 105 | + ChirpState { bw: vec![0.0; n_q] } | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + /// Advances the state one frame given this frame's `bs_invf_mode` per | ||
| 109 | + /// noise band, returning the smoothed bw to use for HF generation. | ||
| 110 | + pub fn update(&mut self, invf_mode: &[u8]) -> &[f64] { | ||
| 111 | + for (slot, &mode) in self.bw.iter_mut().zip(invf_mode) { | ||
| 112 | + let target = BW_TABLE[usize::from(mode).min(3)]; | ||
| 113 | + *slot = if target < *slot { | ||
| 114 | + 0.75 * target + 0.25 * *slot | ||
| 115 | + } else { | ||
| 116 | + 0.90625 * *slot + 0.09375 * target | ||
| 117 | + }; | ||
| 118 | + } | ||
| 119 | + &self.bw | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// Order-2 covariance-method LPC over `x` (index 0 is the oldest sample): | ||
| 124 | +/// solves the 2x2 normal equations minimizing `sum |x[n] - a1*x[n-1] - | ||
| 125 | +/// a2*x[n-2]|^2` over `n = 2..x.len()`. Returns `(a1, a2)`; `(0, 0)` if `x` | ||
| 126 | +/// is too short or the system is singular (silence or a near-constant | ||
| 127 | +/// subband, both of which need no prediction). | ||
| 128 | +pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) { | ||
| 129 | + if x.len() < 3 { | ||
| 130 | + return (Complex::ZERO, Complex::ZERO); | ||
| 131 | + } | ||
| 132 | + let mut r00 = Complex::ZERO; // <x1,x1> | ||
| 133 | + let mut r01 = Complex::ZERO; // <x1,x2> | ||
| 134 | + let mut r11 = Complex::ZERO; // <x2,x2> | ||
| 135 | + let mut r0y = Complex::ZERO; // <x1,y> | ||
| 136 | + let mut r1y = Complex::ZERO; // <x2,y> | ||
| 137 | + for n in 2..x.len() { | ||
| 138 | + let y = x[n]; | ||
| 139 | + let x1 = x[n - 1]; | ||
| 140 | + let x2 = x[n - 2]; | ||
| 141 | + r00 = r00 + x1.conj() * x1; | ||
| 142 | + r01 = r01 + x1.conj() * x2; | ||
| 143 | + r11 = r11 + x2.conj() * x2; | ||
| 144 | + r0y = r0y + x1.conj() * y; | ||
| 145 | + r1y = r1y + x2.conj() * y; | ||
| 146 | + } | ||
| 147 | + // R is Hermitian (r10 = conj(r01)): solve the 2x2 system directly | ||
| 148 | + // rather than reusing r01 for both off-diagonal entries. | ||
| 149 | + let r10 = r01.conj(); | ||
| 150 | + let det = r00 * r11 - r01 * r10; | ||
| 151 | + let norm = det.norm_sqr(); | ||
| 152 | + if norm < 1e-20 { | ||
| 153 | + return (Complex::ZERO, Complex::ZERO); | ||
| 154 | + } | ||
| 155 | + let inv_det = det.conj().scale(1.0 / norm); | ||
| 156 | + let a1 = (r0y * r11 - r01 * r1y) * inv_det; | ||
| 157 | + let a2 = (r00 * r1y - r10 * r0y) * inv_det; | ||
| 158 | + (a1, a2) | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +/// Per-source-subband history: the last two QMF slots, carried across | ||
| 162 | +/// `generate` calls so the LPC and whitening filter have continuity at | ||
| 163 | +/// frame boundaries instead of restarting cold every frame. | ||
| 164 | +#[derive(Clone, Debug)] | ||
| 165 | +pub struct HfHistory { | ||
| 166 | + x: Vec<[Complex<f64>; 2]>, | ||
| 167 | + y: Vec<[Complex<f64>; 2]>, | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +impl HfHistory { | ||
| 171 | + pub fn new(bands: usize) -> HfHistory { | ||
| 172 | + HfHistory { | ||
| 173 | + x: vec![[Complex::ZERO; 2]; bands], | ||
| 174 | + y: vec![[Complex::ZERO; 2]; bands], | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +/// Generates one frame's raw (pre-envelope-adjustment) HF QMF matrix, | ||
| 180 | +/// `[target band index, 0-based from kx][slot]`, `k2 - kx` bands by | ||
| 181 | +/// `low_cur[0].len()` slots (`low_cur` is `[source band][slot]`, bands | ||
| 182 | +/// `0..kx` only need be populated). | ||
| 183 | +pub fn generate( | ||
| 184 | + low_cur: &[Vec<Complex<f64>>], | ||
| 185 | + tables: &BandTables, | ||
| 186 | + invf_mode: &[u8], | ||
| 187 | + chirp: &mut ChirpState, | ||
| 188 | + history: &mut HfHistory, | ||
| 189 | +) -> Vec<Vec<Complex<f64>>> { | ||
| 190 | + let kx = tables.kx as usize; | ||
| 191 | + let k2 = tables.k2 as usize; | ||
| 192 | + let num_slots = low_cur.first().map(Vec::len).unwrap_or(0); | ||
| 193 | + let mut out = vec![vec![Complex::ZERO; num_slots]; k2.saturating_sub(kx)]; | ||
| 194 | + let patches = build_patches(tables); | ||
| 195 | + let bw = chirp.update(invf_mode).to_vec(); | ||
| 196 | + | ||
| 197 | + // Noise-band lookup for a target QMF band, to pick which bw applies. | ||
| 198 | + let noise_band_of = |target_band: usize| -> usize { | ||
| 199 | + let f_noise = &tables.f_noise; | ||
| 200 | + let mut q = 0usize; | ||
| 201 | + for i in 0..tables.n_q { | ||
| 202 | + if (target_band as i64) >= f_noise[i] && (target_band as i64) < f_noise[i + 1] { | ||
| 203 | + q = i; | ||
| 204 | + } | ||
| 205 | + } | ||
| 206 | + q.min(bw.len().saturating_sub(1)) | ||
| 207 | + }; | ||
| 208 | + | ||
| 209 | + for patch in &patches { | ||
| 210 | + for offset in 0..patch.width { | ||
| 211 | + let source_band = patch.source_start + offset; | ||
| 212 | + let target_band = patch.target_start + offset; | ||
| 213 | + if source_band >= low_cur.len() || target_band < kx || target_band >= k2 { | ||
| 214 | + continue; | ||
| 215 | + } | ||
| 216 | + let series = &low_cur[source_band]; | ||
| 217 | + let (a1, a2) = { | ||
| 218 | + let mut ext = Vec::with_capacity(num_slots + 2); | ||
| 219 | + if source_band < history.x.len() { | ||
| 220 | + ext.push(history.x[source_band][0]); | ||
| 221 | + ext.push(history.x[source_band][1]); | ||
| 222 | + } else { | ||
| 223 | + ext.push(Complex::ZERO); | ||
| 224 | + ext.push(Complex::ZERO); | ||
| 225 | + } | ||
| 226 | + ext.extend_from_slice(series); | ||
| 227 | + lpc2(&ext) | ||
| 228 | + }; | ||
| 229 | + let g = bw[noise_band_of(target_band)]; | ||
| 230 | + let ca1 = a1.scale(g); | ||
| 231 | + let ca2 = a2.scale(g * g); | ||
| 232 | + let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() { | ||
| 233 | + (history.y[source_band][1], history.y[source_band][0]) | ||
| 234 | + } else { | ||
| 235 | + (Complex::ZERO, Complex::ZERO) | ||
| 236 | + }; | ||
| 237 | + let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() { | ||
| 238 | + (history.x[source_band][1], history.x[source_band][0]) | ||
| 239 | + } else { | ||
| 240 | + (Complex::ZERO, Complex::ZERO) | ||
| 241 | + }; | ||
| 242 | + let dst = &mut out[target_band - kx]; | ||
| 243 | + for (n, &x) in series.iter().enumerate() { | ||
| 244 | + let residual = x - a1 * x_prev1 - a2 * x_prev2; | ||
| 245 | + let y = residual + ca1 * y_prev1 + ca2 * y_prev2; | ||
| 246 | + dst[n] = y; | ||
| 247 | + x_prev2 = x_prev1; | ||
| 248 | + x_prev1 = x; | ||
| 249 | + y_prev2 = y_prev1; | ||
| 250 | + y_prev1 = y; | ||
| 251 | + } | ||
| 252 | + } | ||
| 253 | + } | ||
| 254 | + | ||
| 255 | + // Every source subband's history advances regardless of whether a | ||
| 256 | + // patch used it this frame: the low-band QMF stream is continuous. | ||
| 257 | + for (band, series) in low_cur.iter().enumerate() { | ||
| 258 | + if band >= history.x.len() || series.len() < 2 { | ||
| 259 | + continue; | ||
| 260 | + } | ||
| 261 | + let n = series.len(); | ||
| 262 | + history.x[band] = [series[n - 2], series[n - 1]]; | ||
| 263 | + // y-history only meaningfully advances for bands a patch actually | ||
| 264 | + // wrote; untouched bands hold their input as a neutral seed. | ||
| 265 | + history.y[band] = [series[n - 2], series[n - 1]]; | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | + out | ||
| 269 | +} | ||
| 270 | + | ||
| 271 | +#[cfg(test)] | ||
| 272 | +mod tests { | ||
| 273 | + use super::*; | ||
| 274 | + use crate::sbr_bands::freq_tables; | ||
| 275 | + | ||
| 276 | + fn real_file_tables() -> BandTables { | ||
| 277 | + // The rig's own header params for ~/Music/reeln.mp4's SBR | ||
| 278 | + // element (44100 Hz extension rate, core-Nyquist crossover ~5 kHz): | ||
| 279 | + // freq_scale=2, alter_scale=1, noise_bands=2, start/stop/xover taken | ||
| 280 | + // from the mid-range defaults `EXTRA1_DEFAULTS` documents when a | ||
| 281 | + // stream omits bs_header_extra_1/2. | ||
| 282 | + freq_tables(44100, 5, 3, 2, 1, 2, 2).expect("valid header for the real file's rate") | ||
| 283 | + } | ||
| 284 | + | ||
| 285 | + #[test] | ||
| 286 | + fn patch_map_is_deterministic_and_covers_the_hf_region() { | ||
| 287 | + let tables = real_file_tables(); | ||
| 288 | + let a = build_patches(&tables); | ||
| 289 | + let b = build_patches(&tables); | ||
| 290 | + assert_eq!(a, b); | ||
| 291 | + assert!(!a.is_empty()); | ||
| 292 | + let mut sb = tables.kx as usize; | ||
| 293 | + for p in &a { | ||
| 294 | + assert_eq!(p.target_start, sb); | ||
| 295 | + assert!(p.source_start + p.width <= tables.kx as usize); | ||
| 296 | + sb += p.width; | ||
| 297 | + } | ||
| 298 | + assert_eq!(sb, tables.k2 as usize); | ||
| 299 | + } | ||
| 300 | + | ||
| 301 | + #[test] | ||
| 302 | + fn lpc_recovers_the_poles_of_a_synthetic_ar2_process() { | ||
| 303 | + // x[n] = a1*x[n-1] + a2*x[n-2] + white noise, driven by a | ||
| 304 | + // deterministic xorshift so the test has no external dependency. | ||
| 305 | + let a1 = Complex::new(0.6, 0.1); | ||
| 306 | + let a2 = Complex::new(-0.3, 0.0); | ||
| 307 | + let mut state = 0x9e37_79b9u64; | ||
| 308 | + let mut rng = move || { | ||
| 309 | + state ^= state << 13; | ||
| 310 | + state ^= state >> 7; | ||
| 311 | + state ^= state << 17; | ||
| 312 | + (state >> 40) as f64 / (1u64 << 24) as f64 - 0.5 | ||
| 313 | + }; | ||
| 314 | + let mut x = vec![Complex::new(0.01, 0.0), Complex::new(-0.01, 0.02)]; | ||
| 315 | + for _ in 0..4000 { | ||
| 316 | + let n = x.len(); | ||
| 317 | + let v = a1 * x[n - 1] + a2 * x[n - 2] + Complex::new(rng() * 0.001, rng() * 0.001); | ||
| 318 | + x.push(v); | ||
| 319 | + } | ||
| 320 | + let (fa1, fa2) = lpc2(&x); | ||
| 321 | + assert!((fa1 - a1).norm_sqr().sqrt() < 0.05, "a1 {fa1:?} vs {a1:?}"); | ||
| 322 | + assert!((fa2 - a2).norm_sqr().sqrt() < 0.05, "a2 {fa2:?} vs {a2:?}"); | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + #[test] | ||
| 326 | + fn chirp_smoothing_tracks_mode_transitions_asymmetrically() { | ||
| 327 | + let mut chirp = ChirpState::new(1); | ||
| 328 | + // Jump from OFF straight to HIGH: attack (rising bw) is the slow | ||
| 329 | + // (0.90625/0.09375) branch here since target > current. | ||
| 330 | + let after_rise = chirp.update(&[3])[0]; | ||
| 331 | + assert!(after_rise > 0.0 && after_rise < BW_TABLE[3]); | ||
| 332 | + // Now drop back to OFF: release (falling bw) is the fast | ||
| 333 | + // (0.75/0.25) branch, so it should move further in one step than | ||
| 334 | + // the rise did. | ||
| 335 | + let before = after_rise; | ||
| 336 | + let after_fall = chirp.update(&[0])[0]; | ||
| 337 | + let fall_step = before - after_fall; | ||
| 338 | + let rise_step = after_rise; // started from 0.0 | ||
| 339 | + assert!(fall_step > rise_step * 0.5, "fall {fall_step} rise {rise_step}"); | ||
| 340 | + } | ||
| 341 | +} | ||