| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use crate::sbr_env::{self, AdjustState}; |
| 8 | use crate::sbr_hf::{self, ChirpState, HfHistory}; |
| 9 | use crate::sbr_payload::{SbrChannel, SbrData, SbrParser}; |
| 10 | use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis}; |
| 11 | use ec_core::BitReader; |
| 12 | use ec_dsp::Complex; |
| 13 | use std::collections::HashMap; |
| 14 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 15 | |
| 16 | |
| 17 | |
| 18 | fn debug_dump( |
| 19 | header: &crate::sbr_payload::SbrHeader, |
| 20 | tables: &crate::sbr_bands::BandTables, |
| 21 | ch: &SbrChannel, |
| 22 | ch_idx: usize, |
| 23 | ) { |
| 24 | static COUNT: AtomicUsize = AtomicUsize::new(0); |
| 25 | let n = COUNT.fetch_add(1, Ordering::Relaxed); |
| 26 | if n >= 20 { |
| 27 | return; |
| 28 | } |
| 29 | eprintln!( |
| 30 | "SBRDBG frame {n} ch{ch_idx}: amp_res={} kx={} k2={} n_low={} n_high={} n_q={} t_env={:?} freq_res={:?} t_noise={:?} f_high={:?} patches={:?}", |
| 31 | header.amp_res, |
| 32 | tables.kx, |
| 33 | tables.k2, |
| 34 | tables.n_low, |
| 35 | tables.n_high, |
| 36 | tables.n_q, |
| 37 | ch.t_env, |
| 38 | ch.freq_res, |
| 39 | ch.t_noise, |
| 40 | tables.f_high, |
| 41 | crate::sbr_hf::build_patches(tables), |
| 42 | ); |
| 43 | for (i, row) in ch.e_q.iter().enumerate() { |
| 44 | let (mn, mx) = row |
| 45 | .iter() |
| 46 | .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v))); |
| 47 | eprintln!(" e_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len()); |
| 48 | } |
| 49 | for (i, row) in ch.q_q.iter().enumerate() { |
| 50 | let (mn, mx) = row |
| 51 | .iter() |
| 52 | .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v))); |
| 53 | eprintln!(" q_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len()); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | const RATE: i64 = 2; |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | #[derive(Clone, Debug)] |
| 70 | pub struct SbrSideInfoRow { |
| 71 | pub frame: usize, |
| 72 | pub tag: u8, |
| 73 | pub ch: usize, |
| 74 | |
| 75 | |
| 76 | |
| 77 | pub source: &'static str, |
| 78 | pub coupling: bool, |
| 79 | pub amp_res: u8, |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | pub kx: i64, |
| 85 | pub k2: i64, |
| 86 | pub f_high: Vec<i64>, |
| 87 | pub f_noise: Vec<i64>, |
| 88 | pub t_env: Vec<i64>, |
| 89 | pub freq_res: Vec<u8>, |
| 90 | pub invf_mode: Vec<u8>, |
| 91 | pub add_harmonic: Option<Vec<u8>>, |
| 92 | pub e_q_means: Vec<f64>, |
| 93 | pub q_q_means: Vec<f64>, |
| 94 | |
| 95 | |
| 96 | |
| 97 | pub freq_scale: u8, |
| 98 | pub alter_scale: u8, |
| 99 | pub noise_bands: u8, |
| 100 | pub limiter_bands: u8, |
| 101 | pub limiter_gains: u8, |
| 102 | pub interpol_freq: u8, |
| 103 | pub smoothing_mode: u8, |
| 104 | pub start_freq: u8, |
| 105 | pub stop_freq: u8, |
| 106 | pub xover_band: u8, |
| 107 | |
| 108 | pub num_noise: usize, |
| 109 | |
| 110 | |
| 111 | pub patch_lengths: Vec<usize>, |
| 112 | pub df_env: Vec<u8>, |
| 113 | pub df_noise: Vec<u8>, |
| 114 | } |
| 115 | |
| 116 | static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> = |
| 117 | std::sync::OnceLock::new(); |
| 118 | static SIDEINFO_FRAME: AtomicUsize = AtomicUsize::new(0); |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | static HOLD_CALLS: AtomicUsize = AtomicUsize::new(0); |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | pub fn hold_call_count() -> usize { |
| 131 | HOLD_CALLS.load(Ordering::Relaxed) |
| 132 | } |
| 133 | |
| 134 | fn sideinfo_enabled() -> bool { |
| 135 | std::env::var("EC_AAC_SBR_SIDEINFO_DEBUG").is_ok() |
| 136 | } |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | fn qmfdump_enabled() -> bool { |
| 145 | std::env::var("EC_AAC_SBR_QMFDUMP").is_ok() |
| 146 | } |
| 147 | |
| 148 | fn qmfdump_energies(stage: &str, start_band: usize, rows: &[Vec<Complex<f64>>]) { |
| 149 | let means: Vec<f64> = rows |
| 150 | .iter() |
| 151 | .map(|series| { |
| 152 | if series.is_empty() { |
| 153 | 0.0 |
| 154 | } else { |
| 155 | series |
| 156 | .iter() |
| 157 | .map(|c| c.re * c.re + c.im * c.im) |
| 158 | .sum::<f64>() |
| 159 | / series.len() as f64 |
| 160 | } |
| 161 | }) |
| 162 | .collect(); |
| 163 | eprintln!("QMFDUMP stage={stage} start_band={start_band} means={means:?}"); |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | pub fn sbr_sideinfo_log() -> Vec<SbrSideInfoRow> { |
| 170 | let Some(log) = SIDEINFO_LOG.get() else { |
| 171 | return Vec::new(); |
| 172 | }; |
| 173 | log.lock().map(|l| l.clone()).unwrap_or_default() |
| 174 | } |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | struct ChannelState { |
| 180 | analysis: Analysis, |
| 181 | synthesis: Synthesis, |
| 182 | hf_hist: HfHistory, |
| 183 | chirp: ChirpState, |
| 184 | adj: AdjustState, |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | low_tail: Vec<[Complex<f64>; ANALYSIS_BANDS]>, |
| 191 | hf_tail: Vec<Vec<Complex<f64>>>, |
| 192 | y_carry: Vec<Vec<Complex<f64>>>, |
| 193 | } |
| 194 | |
| 195 | |
| 196 | |
| 197 | const HF_ADJ: usize = 6; |
| 198 | |
| 199 | impl ChannelState { |
| 200 | fn new(n_q: usize, _seed: u32) -> ChannelState { |
| 201 | ChannelState { |
| 202 | analysis: Analysis::new(), |
| 203 | synthesis: Synthesis::new(), |
| 204 | hf_hist: HfHistory::new(ANALYSIS_BANDS), |
| 205 | chirp: ChirpState::new(n_q.max(1)), |
| 206 | adj: AdjustState::new(), |
| 207 | low_tail: vec![[Complex::ZERO; ANALYSIS_BANDS]; HF_ADJ], |
| 208 | hf_tail: Vec::new(), |
| 209 | y_carry: Vec::new(), |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | |
| 215 | struct Element { |
| 216 | parser: SbrParser, |
| 217 | channels: Vec<ChannelState>, |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | last_data: Option<SbrData>, |
| 227 | |
| 228 | last_header: Option<crate::sbr_payload::SbrHeader>, |
| 229 | } |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | pub struct SbrChain { |
| 235 | rate: u32, |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | elements: HashMap<(u8, bool), Element>, |
| 243 | } |
| 244 | |
| 245 | impl SbrChain { |
| 246 | pub fn new(rate: u32) -> SbrChain { |
| 247 | SbrChain { |
| 248 | rate, |
| 249 | elements: HashMap::new(), |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | |
| 254 | |
| 255 | pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> { |
| 256 | let elem = self.elements.entry((tag, is_cpe)).or_insert_with(|| Element { |
| 257 | parser: SbrParser::new(self.rate), |
| 258 | channels: Vec::new(), |
| 259 | last_data: None, |
| 260 | last_header: None, |
| 261 | }); |
| 262 | let data = elem.parser.parse(r, is_cpe).ok()?; |
| 263 | let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); |
| 264 | while elem.channels.len() < data.channels.len() { |
| 265 | let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9); |
| 266 | elem.channels.push(ChannelState::new(n_q, seed)); |
| 267 | } |
| 268 | Some(data) |
| 269 | } |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | pub fn apply(&mut self, tag: u8, is_cpe: bool, data: &SbrData, planes: &mut [Vec<f32>]) { |
| 276 | if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) { |
| 277 | elem.last_data = Some(data.clone()); |
| 278 | } |
| 279 | self.apply_data(tag, is_cpe, data, planes, "fresh"); |
| 280 | } |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | pub fn apply_last(&mut self, tag: u8, is_cpe: bool, planes: &mut [Vec<f32>]) { |
| 288 | let Some(data) = self |
| 289 | .elements |
| 290 | .get(&(tag, is_cpe)) |
| 291 | .and_then(|e| e.last_data.clone()) |
| 292 | else { |
| 293 | return; |
| 294 | }; |
| 295 | self.apply_data(tag, is_cpe, &data, planes, "hold"); |
| 296 | } |
| 297 | |
| 298 | fn apply_data( |
| 299 | &mut self, |
| 300 | tag: u8, |
| 301 | is_cpe: bool, |
| 302 | data: &SbrData, |
| 303 | planes: &mut [Vec<f32>], |
| 304 | source: &'static str, |
| 305 | ) { |
| 306 | if source == "hold" { |
| 307 | HOLD_CALLS.fetch_add(1, Ordering::Relaxed); |
| 308 | } |
| 309 | let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { |
| 310 | return; |
| 311 | }; |
| 312 | let Some(tables) = elem.parser.tables().cloned() else { |
| 313 | return; |
| 314 | }; |
| 315 | let reset = elem.last_header.as_ref() != elem.parser.header(); |
| 316 | elem.last_header = elem.parser.header().cloned(); |
| 317 | let Some(header) = elem.parser.header().cloned() else { |
| 318 | return; |
| 319 | }; |
| 320 | let coupling = data.coupling; |
| 321 | let sideinfo_on = sideinfo_enabled(); |
| 322 | let au_frame = if sideinfo_on { |
| 323 | SIDEINFO_FRAME.fetch_add(1, Ordering::Relaxed) |
| 324 | } else { |
| 325 | 0 |
| 326 | }; |
| 327 | for (ch, plane) in planes.iter_mut().enumerate() { |
| 328 | if ch >= data.channels.len() || ch >= elem.channels.len() { |
| 329 | continue; |
| 330 | } |
| 331 | let num_slots = plane.len() / ANALYSIS_BANDS; |
| 332 | if num_slots == 0 { |
| 333 | continue; |
| 334 | } |
| 335 | if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() { |
| 336 | static N: AtomicUsize = AtomicUsize::new(0); |
| 337 | let n = N.fetch_add(1, Ordering::Relaxed); |
| 338 | if n < 40 { |
| 339 | let rms = (plane.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() |
| 340 | / plane.len().max(1) as f64) |
| 341 | .sqrt(); |
| 342 | eprintln!( |
| 343 | "PREQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}", |
| 344 | plane.len(), |
| 345 | &plane[..8.min(plane.len())] |
| 346 | ); |
| 347 | } |
| 348 | } |
| 349 | let state = &mut elem.channels[ch]; |
| 350 | let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS]; |
| 351 | let mut raw = Vec::with_capacity(num_slots); |
| 352 | for slot in 0..num_slots { |
| 353 | let mut chunk = [0f32; ANALYSIS_BANDS]; |
| 354 | chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); |
| 355 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | for s in &mut chunk { |
| 367 | *s /= crate::decode::OUTPUT_SCALE; |
| 368 | } |
| 369 | let sub = state.analysis.process_slot(&chunk); |
| 370 | for b in 0..ANALYSIS_BANDS { |
| 371 | low_cur[b][slot] = sub[b]; |
| 372 | } |
| 373 | raw.push(sub); |
| 374 | } |
| 375 | |
| 376 | let sbr_ch = &data.channels[ch]; |
| 377 | if std::env::var("EC_AAC_SBR_DEBUG").is_ok() { |
| 378 | eprintln!("SBRDBG coupling={}", data.coupling); |
| 379 | debug_dump(&header, &tables, sbr_ch, ch); |
| 380 | } |
| 381 | if sideinfo_on { |
| 382 | let mean = |rows: &[Vec<i32>]| -> Vec<f64> { |
| 383 | rows.iter() |
| 384 | .map(|r| { |
| 385 | if r.is_empty() { |
| 386 | 0.0 |
| 387 | } else { |
| 388 | r.iter().map(|&v| f64::from(v)).sum::<f64>() / r.len() as f64 |
| 389 | } |
| 390 | }) |
| 391 | .collect() |
| 392 | }; |
| 393 | let row = SbrSideInfoRow { |
| 394 | frame: au_frame, |
| 395 | tag, |
| 396 | ch, |
| 397 | source, |
| 398 | coupling, |
| 399 | amp_res: header.amp_res, |
| 400 | kx: tables.kx, |
| 401 | k2: tables.k2, |
| 402 | f_high: tables.f_high.clone(), |
| 403 | f_noise: tables.f_noise.clone(), |
| 404 | t_env: sbr_ch.t_env.clone(), |
| 405 | freq_res: sbr_ch.freq_res.clone(), |
| 406 | invf_mode: sbr_ch.invf_mode.clone(), |
| 407 | add_harmonic: sbr_ch.add_harmonic.clone(), |
| 408 | e_q_means: mean(&sbr_ch.e_q), |
| 409 | q_q_means: mean(&sbr_ch.q_q), |
| 410 | freq_scale: header.freq_scale, |
| 411 | alter_scale: header.alter_scale, |
| 412 | noise_bands: header.noise_bands, |
| 413 | limiter_bands: header.limiter_bands, |
| 414 | limiter_gains: header.limiter_gains, |
| 415 | interpol_freq: header.interpol_freq, |
| 416 | smoothing_mode: header.smoothing_mode, |
| 417 | start_freq: header.start_freq, |
| 418 | stop_freq: header.stop_freq, |
| 419 | xover_band: header.xover_band, |
| 420 | num_noise: sbr_ch.t_noise.len().saturating_sub(1), |
| 421 | patch_lengths: sbr_hf::build_patches(&tables).iter().map(|p| p.width).collect(), |
| 422 | df_env: sbr_ch.df_env.clone(), |
| 423 | df_noise: sbr_ch.df_noise.clone(), |
| 424 | }; |
| 425 | let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new())); |
| 426 | if let Ok(mut l) = log.lock() { |
| 427 | l.push(row); |
| 428 | } |
| 429 | } |
| 430 | let qmfdump_on = qmfdump_enabled(); |
| 431 | if qmfdump_on { |
| 432 | qmfdump_energies("analysis", 0, &low_cur); |
| 433 | } |
| 434 | let hf = sbr_hf::generate( |
| 435 | &low_cur, |
| 436 | &tables, |
| 437 | &sbr_ch.invf_mode, |
| 438 | &mut state.chirp, |
| 439 | &mut state.hf_hist, |
| 440 | ); |
| 441 | if qmfdump_on { |
| 442 | qmfdump_energies("post_patch", tables.kx as usize, &hf); |
| 443 | } |
| 444 | let (env_energy, noise_energy) = |
| 445 | sbr_env::dequantize_frame(&data.channels, ch, coupling); |
| 446 | |
| 447 | |
| 448 | let scaled = SbrChannel { |
| 449 | t_env: sbr_ch.t_env.iter().map(|&t| t * RATE).collect(), |
| 450 | t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(), |
| 451 | ..sbr_ch.clone() |
| 452 | }; |
| 453 | let limiter_table = sbr_hf::limiter_band_table( |
| 454 | &tables, |
| 455 | &sbr_hf::build_patches(&tables), |
| 456 | header.limiter_bands, |
| 457 | ); |
| 458 | |
| 459 | |
| 460 | |
| 461 | let m_max = hf.len(); |
| 462 | if state.hf_tail.len() != m_max || reset { |
| 463 | state.hf_tail = vec![vec![Complex::ZERO; HF_ADJ]; m_max]; |
| 464 | state.y_carry.clear(); |
| 465 | } |
| 466 | let mut xh: Vec<Vec<Complex<f64>>> = (0..m_max) |
| 467 | .map(|m| { |
| 468 | let mut v = state.hf_tail[m].clone(); |
| 469 | v.extend_from_slice(&hf[m]); |
| 470 | v |
| 471 | }) |
| 472 | .collect(); |
| 473 | for (m, band) in hf.iter().enumerate().take(m_max) { |
| 474 | state.hf_tail[m] = band[num_slots.saturating_sub(HF_ADJ)..].to_vec(); |
| 475 | } |
| 476 | sbr_env::adjust( |
| 477 | &mut xh, |
| 478 | &tables, |
| 479 | &header, |
| 480 | &scaled, |
| 481 | &env_energy, |
| 482 | &noise_energy, |
| 483 | &limiter_table, |
| 484 | &mut state.adj, |
| 485 | reset, |
| 486 | ); |
| 487 | |
| 488 | |
| 489 | |
| 490 | let i_temp = state.y_carry.first().map(Vec::len).unwrap_or(0).min(num_slots); |
| 491 | let t_end = (scaled.t_env.last().copied().unwrap_or(0).max(0) as usize).min(xh[0].len()); |
| 492 | let mut hf: Vec<Vec<Complex<f64>>> = vec![vec![Complex::ZERO; num_slots]; m_max]; |
| 493 | for (m, band) in hf.iter_mut().enumerate().take(m_max) { |
| 494 | for (i, slot) in band.iter_mut().enumerate().take(i_temp) { |
| 495 | *slot = state.y_carry[m][i]; |
| 496 | } |
| 497 | for (i, slot) in band.iter_mut().enumerate().take(num_slots).skip(i_temp) { |
| 498 | *slot = xh[m][i]; |
| 499 | } |
| 500 | } |
| 501 | state.y_carry = (0..m_max) |
| 502 | .map(|m| xh[m][num_slots.min(t_end)..t_end].to_vec()) |
| 503 | .collect(); |
| 504 | let raw: Vec<[Complex<f64>; ANALYSIS_BANDS]> = { |
| 505 | let mut d = state.low_tail.clone(); |
| 506 | d.extend_from_slice(&raw); |
| 507 | state.low_tail = d[d.len() - HF_ADJ..].to_vec(); |
| 508 | d.truncate(num_slots); |
| 509 | d |
| 510 | }; |
| 511 | if qmfdump_on { |
| 512 | qmfdump_energies("post_adjust", tables.kx as usize, &hf); |
| 513 | } |
| 514 | |
| 515 | let kx = (tables.kx as usize).min(ANALYSIS_BANDS); |
| 516 | let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS); |
| 517 | let mut out = Vec::with_capacity(num_slots * SYNTHESIS_BANDS); |
| 518 | for slot in 0..num_slots { |
| 519 | let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; |
| 520 | v[0..kx].copy_from_slice(&raw[slot][0..kx]); |
| 521 | if std::env::var("EC_AAC_SBR_HF_BYPASS").is_err() { |
| 522 | for b in kx..k2 { |
| 523 | if b - kx < hf.len() { |
| 524 | v[b] = hf[b - kx][slot]; |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | let mut pcm = state.synthesis.process_slot(&v); |
| 529 | for s in &mut pcm { |
| 530 | |
| 531 | |
| 532 | |
| 533 | *s *= 2.0 * crate::decode::OUTPUT_SCALE; |
| 534 | } |
| 535 | out.extend_from_slice(&pcm); |
| 536 | } |
| 537 | if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() { |
| 538 | static N: AtomicUsize = AtomicUsize::new(0); |
| 539 | let n = N.fetch_add(1, Ordering::Relaxed); |
| 540 | if n < 40 { |
| 541 | let rms = (out.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() |
| 542 | / out.len().max(1) as f64) |
| 543 | .sqrt(); |
| 544 | eprintln!( |
| 545 | "POSTQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}", |
| 546 | out.len(), |
| 547 | &out[..8.min(out.len())] |
| 548 | ); |
| 549 | } |
| 550 | } |
| 551 | *plane = out; |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | #[cfg(test)] |
| 557 | mod tests { |
| 558 | use super::*; |
| 559 | use crate::sbr_bands::freq_tables; |
| 560 | use crate::sbr_payload::{SbrHeader, SbrParser}; |
| 561 | |
| 562 | fn tables() -> crate::sbr_bands::BandTables { |
| 563 | freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap() |
| 564 | } |
| 565 | |
| 566 | fn header() -> SbrHeader { |
| 567 | SbrHeader { |
| 568 | amp_res: 1, |
| 569 | start_freq: 5, |
| 570 | stop_freq: 3, |
| 571 | xover_band: 2, |
| 572 | freq_scale: 2, |
| 573 | alter_scale: 1, |
| 574 | noise_bands: 2, |
| 575 | limiter_bands: 2, |
| 576 | limiter_gains: 3, |
| 577 | interpol_freq: 1, |
| 578 | smoothing_mode: 1, |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | fn one_channel(n_q: usize, n_low: usize) -> SbrChannel { |
| 583 | SbrChannel { |
| 584 | t_env: vec![0, 16], |
| 585 | freq_res: vec![0], |
| 586 | t_noise: vec![0, 16], |
| 587 | e_q: vec![vec![10i32; n_low]], |
| 588 | q_q: vec![vec![2i32; n_q]], |
| 589 | invf_mode: vec![0; n_q], |
| 590 | add_harmonic: None, |
| 591 | df_env: vec![], |
| 592 | df_noise: vec![], |
| 593 | l_a: -1, |
| 594 | amp_res: 1, |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | |
| 599 | |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 604 | |
| 605 | #[test] |
| 606 | fn two_adjacent_access_units_double_rate_with_no_junction_discontinuity() { |
| 607 | let t = tables(); |
| 608 | let n_low = t.n_low; |
| 609 | let n_q = t.n_q; |
| 610 | let mut chain = SbrChain::new(44100); |
| 611 | let tag = 0u8; |
| 612 | chain.elements.insert( |
| 613 | (tag, true), |
| 614 | Element { |
| 615 | parser: SbrParser::new(44100), |
| 616 | channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)], |
| 617 | last_data: None, |
| 618 | last_header: None, |
| 619 | }, |
| 620 | ); |
| 621 | chain |
| 622 | .elements |
| 623 | .get_mut(&(tag, true)) |
| 624 | .unwrap() |
| 625 | .parser |
| 626 | .set_for_test(header(), t.clone()); |
| 627 | |
| 628 | let data = SbrData { |
| 629 | coupling: false, |
| 630 | channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)], |
| 631 | }; |
| 632 | |
| 633 | |
| 634 | |
| 635 | |
| 636 | let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() }; |
| 637 | let mut planes = vec![core_au(), core_au()]; |
| 638 | chain.apply(tag, true, &data, &mut planes); |
| 639 | |
| 640 | let expected_len = 32 * SYNTHESIS_BANDS; |
| 641 | for (ch, plane) in planes.iter().enumerate() { |
| 642 | assert_eq!( |
| 643 | plane.len(), |
| 644 | expected_len, |
| 645 | "ch{ch} AU1 didn't double to {expected_len} samples" |
| 646 | ); |
| 647 | } |
| 648 | |
| 649 | |
| 650 | |
| 651 | |
| 652 | |
| 653 | let mut planes2 = vec![core_au(), core_au()]; |
| 654 | chain.apply(tag, true, &data, &mut planes2); |
| 655 | for (ch, plane) in planes2.iter().enumerate() { |
| 656 | assert_eq!( |
| 657 | plane.len(), |
| 658 | expected_len, |
| 659 | "ch{ch} AU2 didn't double to {expected_len} samples" |
| 660 | ); |
| 661 | } |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | for ch in 0..2 { |
| 671 | let mut joined = planes[ch].clone(); |
| 672 | joined.extend_from_slice(&planes2[ch]); |
| 673 | assert_eq!(joined.len(), 2 * expected_len); |
| 674 | |
| 675 | let steady_delta = |s: &[f32]| -> f32 { |
| 676 | s.windows(2) |
| 677 | .skip(expected_len / 2) |
| 678 | .take(expected_len / 4) |
| 679 | .map(|w| (w[1] - w[0]).abs()) |
| 680 | .fold(0.0f32, f32::max) |
| 681 | }; |
| 682 | let typical = steady_delta(&joined); |
| 683 | let junction_delta = (joined[expected_len] - joined[expected_len - 1]).abs(); |
| 684 | assert!( |
| 685 | junction_delta <= typical * 4.0 + 1e-6, |
| 686 | "ch{ch} junction delta {junction_delta} far exceeds steady-state delta {typical} -- AU-boundary discontinuity" |
| 687 | ); |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | |
| 692 | |
| 693 | |
| 694 | |
| 695 | |
| 696 | |
| 697 | |
| 698 | |
| 699 | |
| 700 | #[test] |
| 701 | fn an_sce_and_a_same_tagged_cpe_do_not_share_state() { |
| 702 | let t = tables(); |
| 703 | let n_low = t.n_low; |
| 704 | let n_q = t.n_q; |
| 705 | let mut chain = SbrChain::new(44100); |
| 706 | let tag = 0u8; |
| 707 | |
| 708 | for is_cpe in [false, true] { |
| 709 | let n_ch = if is_cpe { 2 } else { 1 }; |
| 710 | chain.elements.insert( |
| 711 | (tag, is_cpe), |
| 712 | Element { |
| 713 | parser: SbrParser::new(44100), |
| 714 | channels: (0..n_ch) |
| 715 | .map(|i| ChannelState::new(n_q, 10 + i as u32)) |
| 716 | .collect(), |
| 717 | last_data: None, |
| 718 | last_header: None, |
| 719 | }, |
| 720 | ); |
| 721 | chain |
| 722 | .elements |
| 723 | .get_mut(&(tag, is_cpe)) |
| 724 | .unwrap() |
| 725 | .parser |
| 726 | .set_for_test(header(), t.clone()); |
| 727 | } |
| 728 | |
| 729 | let sce_data = SbrData { |
| 730 | coupling: false, |
| 731 | channels: vec![one_channel(n_q, n_low)], |
| 732 | }; |
| 733 | let cpe_data = SbrData { |
| 734 | coupling: false, |
| 735 | channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)], |
| 736 | }; |
| 737 | |
| 738 | let sce_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.05).sin() * 0.2).collect() }; |
| 739 | let cpe_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.37).sin() * 0.2).collect() }; |
| 740 | |
| 741 | let mut sce_planes = vec![sce_tone()]; |
| 742 | chain.apply(tag, false, &sce_data, &mut sce_planes); |
| 743 | let mut cpe_planes = vec![cpe_tone(), cpe_tone()]; |
| 744 | chain.apply(tag, true, &cpe_data, &mut cpe_planes); |
| 745 | |
| 746 | |
| 747 | |
| 748 | |
| 749 | |
| 750 | |
| 751 | let mut sce_planes2 = vec![sce_tone()]; |
| 752 | chain.apply(tag, false, &sce_data, &mut sce_planes2); |
| 753 | |
| 754 | |
| 755 | |
| 756 | let mut reference = SbrChain::new(44100); |
| 757 | reference.elements.insert( |
| 758 | (tag, false), |
| 759 | Element { |
| 760 | parser: SbrParser::new(44100), |
| 761 | channels: vec![ChannelState::new(n_q, 10)], |
| 762 | last_data: None, |
| 763 | last_header: None, |
| 764 | }, |
| 765 | ); |
| 766 | reference |
| 767 | .elements |
| 768 | .get_mut(&(tag, false)) |
| 769 | .unwrap() |
| 770 | .parser |
| 771 | .set_for_test(header(), t.clone()); |
| 772 | let mut sce_ref1 = vec![sce_tone()]; |
| 773 | reference.apply(tag, false, &sce_data, &mut sce_ref1); |
| 774 | let mut sce_ref2 = vec![sce_tone()]; |
| 775 | reference.apply(tag, false, &sce_data, &mut sce_ref2); |
| 776 | |
| 777 | assert_eq!( |
| 778 | sce_planes[0], sce_ref1[0], |
| 779 | "SCE tag 0's first call already diverges from an isolated reference" |
| 780 | ); |
| 781 | assert_eq!( |
| 782 | sce_planes2[0], sce_ref2[0], |
| 783 | "SCE tag 0's state was mutated by the same-tagged CPE's apply() call in between" |
| 784 | ); |
| 785 | } |
| 786 | |
| 787 | |
| 788 | |
| 789 | |
| 790 | |
| 791 | |
| 792 | |
| 793 | |
| 794 | |
| 795 | |
| 796 | |
| 797 | |
| 798 | |
| 799 | |
| 800 | |
| 801 | |
| 802 | |
| 803 | |
| 804 | |
| 805 | |
| 806 | #[test] |
| 807 | fn ten_aus_worth_of_qmf_slots_chained_per_au_are_bit_identical_to_one_continuous_pass() { |
| 808 | let mut rng = 0x02f6_e2b1_u64; |
| 809 | let mut next = || { |
| 810 | rng ^= rng << 13; |
| 811 | rng ^= rng >> 7; |
| 812 | rng ^= rng << 17; |
| 813 | (rng >> 11) as f64 / (1u64 << 53) as f64 - 0.5 |
| 814 | }; |
| 815 | let all_samples: Vec<f32> = (0..10 * 1024).map(|_| next() as f32 * 0.3).collect(); |
| 816 | |
| 817 | |
| 818 | |
| 819 | |
| 820 | let mut analysis_a = Analysis::new(); |
| 821 | let mut synthesis_a = Synthesis::new(); |
| 822 | let mut per_au_out: Vec<f32> = Vec::new(); |
| 823 | for au in all_samples.chunks(1024) { |
| 824 | for slot in au.chunks_exact(ANALYSIS_BANDS) { |
| 825 | let mut chunk = [0f32; ANALYSIS_BANDS]; |
| 826 | chunk.copy_from_slice(slot); |
| 827 | let sub = analysis_a.process_slot(&chunk); |
| 828 | let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; |
| 829 | v[0..ANALYSIS_BANDS].copy_from_slice(&sub); |
| 830 | per_au_out.extend(synthesis_a.process_slot(&v)); |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | |
| 835 | |
| 836 | let mut analysis_b = Analysis::new(); |
| 837 | let mut synthesis_b = Synthesis::new(); |
| 838 | let mut continuous_out: Vec<f32> = Vec::new(); |
| 839 | for slot in all_samples.chunks_exact(ANALYSIS_BANDS) { |
| 840 | let mut chunk = [0f32; ANALYSIS_BANDS]; |
| 841 | chunk.copy_from_slice(slot); |
| 842 | let sub = analysis_b.process_slot(&chunk); |
| 843 | let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; |
| 844 | v[0..ANALYSIS_BANDS].copy_from_slice(&sub); |
| 845 | continuous_out.extend(synthesis_b.process_slot(&v)); |
| 846 | } |
| 847 | |
| 848 | assert_eq!(per_au_out.len(), continuous_out.len()); |
| 849 | let mut max_diff = 0.0f32; |
| 850 | let mut diverging = 0usize; |
| 851 | for (a, b) in per_au_out.iter().zip(&continuous_out) { |
| 852 | let d = (a - b).abs(); |
| 853 | if d != 0.0 { |
| 854 | diverging += 1; |
| 855 | } |
| 856 | max_diff = max_diff.max(d); |
| 857 | } |
| 858 | let total = per_au_out.len(); |
| 859 | println!("stitching check: {diverging}/{total} samples differ, max abs diff {max_diff:e}"); |
| 860 | assert!( |
| 861 | max_diff < 1e-5, |
| 862 | "per-AU chaining and one continuous pass diverge by {max_diff:e} -- a real QMF stitching bug" |
| 863 | ); |
| 864 | } |
| 865 | } |