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