Merge branches 'simplify/c-aac' and 'simplify/c-av1rc'
Browse files at this commit11 changed files +276 -136
- crates/ec-aac/src/decode.rs +7 -1
- crates/ec-aac/src/lib.rs +4 -2
- crates/ec-aac/src/sbr_chain.rs +118 -22
- crates/ec-aac/src/sbr_hf.rs +4 -0
- crates/ec-aac/src/sbr_payload.rs +2 -2
- crates/ec-aac/src/sbr_qmf.rs +39 -41
- crates/ec-aac/tests/sbr_real_library/chunk_a.rs +11 -2
- crates/ec-aac/tests/sbr_real_library/helpers.rs +38 -20
- crates/ec-av1/src/encoder/mod.rs +39 -43
- crates/ec-av1/src/encoder/tests.rs +13 -2
- crates/ec-av1/src/stack_budget.rs +1 -1
crates/ec-aac/src/decode.rsmodified+7 -1
| @@ -582,6 +582,12 @@ impl BlockDecoder { | |||
| 582 | self.sbr = rate.map(crate::sbr_chain::SbrChain::new); | 582 | self.sbr = rate.map(crate::sbr_chain::SbrChain::new); |
| 583 | } | 583 | } |
| 584 | 584 | ||
| 585 | + pub fn set_sbr_downsampled(&mut self, on: bool) { | ||
| 586 | + if let Some(sbr) = self.sbr.as_mut() { | ||
| 587 | + sbr.set_downsampled(on); | ||
| 588 | + } | ||
| 589 | + } | ||
| 590 | + | ||
| 585 | /// Marks Parametric Stereo as signalled by the config, for the SBR chain | 591 | /// Marks Parametric Stereo as signalled by the config, for the SBR chain |
| 586 | /// (if one is armed): its elements then decode to two channels. | 592 | /// (if one is armed): its elements then decode to two channels. |
| 587 | pub fn set_sbr_ps(&mut self, on: bool) { | 593 | pub fn set_sbr_ps(&mut self, on: bool) { |
| @@ -986,7 +992,7 @@ impl BlockDecoder { | |||
| 986 | } | 992 | } |
| 987 | } | 993 | } |
| 988 | } | 994 | } |
| 989 | - if !applied { | 995 | + if !applied && !arming { |
| 990 | // No fresh SBR payload this frame (no SBR fill | 996 | // No fresh SBR payload this frame (no SBR fill |
| 991 | // element, or one whose extension_type wasn't | 997 | // element, or one whose extension_type wasn't |
| 992 | // SBR, or a parse failure): §4.6.18 still | 998 | // SBR, or a parse failure): §4.6.18 still |
crates/ec-aac/src/lib.rsmodified+4 -2
| @@ -144,8 +144,10 @@ impl AacDecoder { | |||
| 144 | // SBR (and Parametric Stereo, for HE-AACv2) is reconstructed: the | 144 | // SBR (and Parametric Stereo, for HE-AACv2) is reconstructed: the |
| 145 | // core is decoded first, then the extension-rate chain runs on it. | 145 | // core is decoded first, then the extension-rate chain runs on it. |
| 146 | if cfg.sbr_present { | 146 | if cfg.sbr_present { |
| 147 | - let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2); | 147 | + let sbr_rate = cfg.sample_rate * 2; |
| 148 | - d.block.set_sbr_rate(Some(rate)); | 148 | + let ext_rate = cfg.extension_sample_rate.unwrap_or(sbr_rate); |
| 149 | + d.block.set_sbr_rate(Some(sbr_rate)); | ||
| 150 | + d.block.set_sbr_downsampled(ext_rate < sbr_rate); | ||
| 149 | d.block.set_sbr_ps(cfg.ps_present); | 151 | d.block.set_sbr_ps(cfg.ps_present); |
| 150 | } else if !cfg.ps_present { | 152 | } else if !cfg.ps_present { |
| 151 | // Plain AAC-LC config: an SBR payload may still follow (implicit signalling). | 153 | // Plain AAC-LC config: an SBR payload may still follow (implicit signalling). |
crates/ec-aac/src/sbr_chain.rsmodified+118 -22
| @@ -236,6 +236,19 @@ struct Element { | |||
| 236 | ps_engine: PsEngine, | 236 | ps_engine: PsEngine, |
| 237 | } | 237 | } |
| 238 | 238 | ||
| 239 | +impl Element { | ||
| 240 | + fn ensure_channels(&mut self, need: usize, downsampled: bool) { | ||
| 241 | + while self.channels.len() < need { | ||
| 242 | + let seed = 0x1234_5678u32.wrapping_add(self.channels.len() as u32 * 0x9e37_79b9); | ||
| 243 | + let mut channel = ChannelState::new(1, seed); | ||
| 244 | + if downsampled { | ||
| 245 | + channel.synthesis = Synthesis::downsampled(); | ||
| 246 | + } | ||
| 247 | + self.channels.push(channel); | ||
| 248 | + } | ||
| 249 | + } | ||
| 250 | +} | ||
| 251 | + | ||
| 239 | /// QMF slots per SBR frame: the PS path runs only for the 32-slot frames | 252 | /// QMF slots per SBR frame: the PS path runs only for the 32-slot frames |
| 240 | /// that AAC-LC's 1024-sample frames produce. | 253 | /// that AAC-LC's 1024-sample frames produce. |
| 241 | const PS_SLOTS: usize = 32; | 254 | const PS_SLOTS: usize = 32; |
| @@ -245,6 +258,7 @@ const PS_SLOTS: usize = 32; | |||
| 245 | /// encoder in practice emits it). | 258 | /// encoder in practice emits it). |
| 246 | pub struct SbrChain { | 259 | pub struct SbrChain { |
| 247 | rate: u32, | 260 | rate: u32, |
| 261 | + downsampled: bool, | ||
| 248 | /// PS is signalled by the config (explicit HE-AACv2). | 262 | /// PS is signalled by the config (explicit HE-AACv2). |
| 249 | ps_config: bool, | 263 | ps_config: bool, |
| 250 | // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance | 264 | // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance |
| @@ -263,12 +277,17 @@ impl SbrChain { | |||
| 263 | pub fn new(rate: u32) -> SbrChain { | 277 | pub fn new(rate: u32) -> SbrChain { |
| 264 | SbrChain { | 278 | SbrChain { |
| 265 | rate, | 279 | rate, |
| 280 | + downsampled: false, | ||
| 266 | ps_config: false, | 281 | ps_config: false, |
| 267 | elements: HashMap::new(), | 282 | elements: HashMap::new(), |
| 268 | bypass: HashMap::new(), | 283 | bypass: HashMap::new(), |
| 269 | } | 284 | } |
| 270 | } | 285 | } |
| 271 | 286 | ||
| 287 | + pub fn set_downsampled(&mut self, on: bool) { | ||
| 288 | + self.downsampled = on; | ||
| 289 | + } | ||
| 290 | + | ||
| 272 | /// Marks PS as signalled by the config: the element's output is stereo. | 291 | /// Marks PS as signalled by the config: the element's output is stereo. |
| 273 | pub fn set_ps_config(&mut self, on: bool) { | 292 | pub fn set_ps_config(&mut self, on: bool) { |
| 274 | self.ps_config = on; | 293 | self.ps_config = on; |
| @@ -280,8 +299,24 @@ impl SbrChain { | |||
| 280 | /// Parses one FIL element's `sbr_extension_data` (the reader | 299 | /// Parses one FIL element's `sbr_extension_data` (the reader |
| 281 | /// positioned right past `bs_extension_type`) for element `tag`. | 300 | /// positioned right past `bs_extension_type`) for element `tag`. |
| 282 | pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> { | 301 | pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> { |
| 302 | + let (ps_config, downsampled) = (self.ps_config, self.downsampled); | ||
| 303 | + let elem = self.element(tag, is_cpe); | ||
| 304 | + let data = elem.parser.parse(r, is_cpe).ok()?; | ||
| 305 | + let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); | ||
| 306 | + let ps_out = data.ps.is_some() || (ps_config && !is_cpe); | ||
| 307 | + let need = data.channels.len().max(if ps_out { 2 } else { 1 }); | ||
| 308 | + elem.ensure_channels(need, downsampled); | ||
| 309 | + for ch in &mut elem.channels { | ||
| 310 | + if ch.chirp.bands() != n_q { | ||
| 311 | + ch.chirp = ChirpState::new(n_q); | ||
| 312 | + } | ||
| 313 | + } | ||
| 314 | + Some(data) | ||
| 315 | + } | ||
| 316 | + | ||
| 317 | + fn element(&mut self, tag: u8, is_cpe: bool) -> &mut Element { | ||
| 283 | let (rate, ps_config) = (self.rate, self.ps_config); | 318 | let (rate, ps_config) = (self.rate, self.ps_config); |
| 284 | - let elem = self.elements.entry((tag, is_cpe)).or_insert_with(|| { | 319 | + self.elements.entry((tag, is_cpe)).or_insert_with(|| { |
| 285 | let mut parser = SbrParser::new(rate); | 320 | let mut parser = SbrParser::new(rate); |
| 286 | parser.set_ps_config(ps_config); | 321 | parser.set_ps_config(ps_config); |
| 287 | Element { | 322 | Element { |
| @@ -291,16 +326,57 @@ impl SbrChain { | |||
| 291 | last_header: None, | 326 | last_header: None, |
| 292 | ps_engine: PsEngine::new(), | 327 | ps_engine: PsEngine::new(), |
| 293 | } | 328 | } |
| 294 | - }); | 329 | + }) |
| 295 | - let data = elem.parser.parse(r, is_cpe).ok()?; | 330 | + } |
| 296 | - let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); | 331 | + |
| 297 | - // PS needs a second synthesis state: the right output channel. | 332 | + fn apply_low_only(&mut self, tag: u8, is_cpe: bool, planes: &mut [Vec<f32>]) { |
| 298 | - let need = data.channels.len().max(if data.ps.is_some() { 2 } else { 1 }); | 333 | + let dup = !is_cpe && planes.len() == 2; |
| 299 | - while elem.channels.len() < need { | 334 | + let downsampled = self.downsampled; |
| 300 | - let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9); | 335 | + let elem = self.element(tag, is_cpe); |
| 301 | - elem.channels.push(ChannelState::new(n_q, seed)); | 336 | + elem.ensure_channels(planes.len(), downsampled); |
| 337 | + let mut right_synth = if dup { | ||
| 338 | + Some(std::mem::take(&mut elem.channels[1].synthesis)) | ||
| 339 | + } else { | ||
| 340 | + None | ||
| 341 | + }; | ||
| 342 | + let mut right_plane = None; | ||
| 343 | + for (plane, state) in planes.iter_mut().zip(elem.channels.iter_mut()) { | ||
| 344 | + if right_plane.is_some() { | ||
| 345 | + break; | ||
| 346 | + } | ||
| 347 | + let num_slots = plane.len() / ANALYSIS_BANDS; | ||
| 348 | + let mut raw = Vec::with_capacity(num_slots); | ||
| 349 | + for slot in 0..num_slots { | ||
| 350 | + let mut chunk = [0f32; ANALYSIS_BANDS]; | ||
| 351 | + chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); | ||
| 352 | + for s in &mut chunk { | ||
| 353 | + *s /= crate::decode::OUTPUT_SCALE; | ||
| 354 | + } | ||
| 355 | + raw.push(state.analysis.process_slot(&chunk)); | ||
| 356 | + } | ||
| 357 | + let mut delayed = state.low_tail.clone(); | ||
| 358 | + delayed.extend_from_slice(&raw); | ||
| 359 | + state.low_tail = delayed[delayed.len() - HF_ADJ..].to_vec(); | ||
| 360 | + delayed.truncate(num_slots); | ||
| 361 | + let vs: Vec<[Complex<f64>; SYNTHESIS_BANDS]> = delayed | ||
| 362 | + .iter() | ||
| 363 | + .map(|sub| { | ||
| 364 | + let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; | ||
| 365 | + v[..ANALYSIS_BANDS].copy_from_slice(sub); | ||
| 366 | + v | ||
| 367 | + }) | ||
| 368 | + .collect(); | ||
| 369 | + *plane = synth_slots(&mut state.synthesis, &vs); | ||
| 370 | + if let Some(rs) = right_synth.as_mut() { | ||
| 371 | + right_plane = Some(synth_slots(rs, &vs)); | ||
| 372 | + } | ||
| 373 | + } | ||
| 374 | + if let Some(rs) = right_synth { | ||
| 375 | + elem.channels[1].synthesis = rs; | ||
| 376 | + } | ||
| 377 | + if let Some(right) = right_plane { | ||
| 378 | + planes[1] = right; | ||
| 302 | } | 379 | } |
| 303 | - Some(data) | ||
| 304 | } | 380 | } |
| 305 | 381 | ||
| 306 | /// Doubles the rate of an LFE plane. The standard gives the LFE no SBR | 382 | /// Doubles the rate of an LFE plane. The standard gives the LFE no SBR |
| @@ -310,13 +386,19 @@ impl SbrChain { | |||
| 310 | /// planes, with the high bands left empty, which is what ffmpeg's output | 386 | /// planes, with the high bands left empty, which is what ffmpeg's output |
| 311 | /// does for the LFE channel. | 387 | /// does for the LFE channel. |
| 312 | pub fn bypass_plane(&mut self, tag: u8, plane: &mut Vec<f32>) { | 388 | pub fn bypass_plane(&mut self, tag: u8, plane: &mut Vec<f32>) { |
| 313 | - let (state, delay) = self | 389 | + let downsampled = self.downsampled; |
| 314 | - .bypass | 390 | + let (state, delay) = self.bypass.entry(tag).or_insert_with(|| { |
| 315 | - .entry(tag) | 391 | + let mut state = ChannelState::new(1, 0); |
| 316 | - .or_insert_with(|| (ChannelState::new(1, 0), vec![0.0; BYPASS_DELAY])); | 392 | + let mut delay = BYPASS_DELAY; |
| 393 | + if downsampled { | ||
| 394 | + state.synthesis = Synthesis::downsampled(); | ||
| 395 | + delay /= 2; | ||
| 396 | + } | ||
| 397 | + (state, vec![0.0; delay]) | ||
| 398 | + }); | ||
| 317 | let num_slots = plane.len() / ANALYSIS_BANDS; | 399 | let num_slots = plane.len() / ANALYSIS_BANDS; |
| 318 | let mut out = std::mem::take(delay); | 400 | let mut out = std::mem::take(delay); |
| 319 | - out.reserve(num_slots * SYNTHESIS_BANDS); | 401 | + out.reserve(num_slots * state.synthesis.bands()); |
| 320 | for slot in 0..num_slots { | 402 | for slot in 0..num_slots { |
| 321 | let mut chunk = [0f32; ANALYSIS_BANDS]; | 403 | let mut chunk = [0f32; ANALYSIS_BANDS]; |
| 322 | chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); | 404 | chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); |
| @@ -332,7 +414,7 @@ impl SbrChain { | |||
| 332 | } | 414 | } |
| 333 | // The reconstructed planes lag their raw analysis by `HF_ADJ` slots; | 415 | // The reconstructed planes lag their raw analysis by `HF_ADJ` slots; |
| 334 | // hold the bypass output back by the same amount so they line up. | 416 | // hold the bypass output back by the same amount so they line up. |
| 335 | - let produced = num_slots * SYNTHESIS_BANDS; | 417 | + let produced = num_slots * state.synthesis.bands(); |
| 336 | *plane = out[..produced].to_vec(); | 418 | *plane = out[..produced].to_vec(); |
| 337 | *delay = out[produced..].to_vec(); | 419 | *delay = out[produced..].to_vec(); |
| 338 | } | 420 | } |
| @@ -350,7 +432,7 @@ impl SbrChain { | |||
| 350 | start: usize, | 432 | start: usize, |
| 351 | n: usize, | 433 | n: usize, |
| 352 | ) -> crate::Result<()> { | 434 | ) -> crate::Result<()> { |
| 353 | - let n = expand_for_ps(out, start, n, is_cpe, data.ps.is_some()); | 435 | + let n = expand_for_ps(out, start, n, is_cpe, data.ps.is_some() || self.ps_config); |
| 354 | self.apply(tag, is_cpe, data, &mut out[start..start + n]) | 436 | self.apply(tag, is_cpe, data, &mut out[start..start + n]) |
| 355 | } | 437 | } |
| 356 | 438 | ||
| @@ -367,7 +449,8 @@ impl SbrChain { | |||
| 367 | .elements | 449 | .elements |
| 368 | .get(&(tag, is_cpe)) | 450 | .get(&(tag, is_cpe)) |
| 369 | .and_then(|e| e.last_data.as_ref()) | 451 | .and_then(|e| e.last_data.as_ref()) |
| 370 | - .is_some_and(|d| d.ps.is_some()); | 452 | + .is_some_and(|d| d.ps.is_some()) |
| 453 | + || self.ps_config; | ||
| 371 | let n = expand_for_ps(out, start, n, is_cpe, has_ps); | 454 | let n = expand_for_ps(out, start, n, is_cpe, has_ps); |
| 372 | self.apply_last(tag, is_cpe, &mut out[start..start + n]) | 455 | self.apply_last(tag, is_cpe, &mut out[start..start + n]) |
| 373 | } | 456 | } |
| @@ -405,6 +488,7 @@ impl SbrChain { | |||
| 405 | .get(&(tag, is_cpe)) | 488 | .get(&(tag, is_cpe)) |
| 406 | .and_then(|e| e.last_data.clone()) | 489 | .and_then(|e| e.last_data.clone()) |
| 407 | else { | 490 | else { |
| 491 | + self.apply_low_only(tag, is_cpe, planes); | ||
| 408 | return Ok(()); | 492 | return Ok(()); |
| 409 | }; | 493 | }; |
| 410 | self.apply_data(tag, is_cpe, &data, planes, "hold") | 494 | self.apply_data(tag, is_cpe, &data, planes, "hold") |
| @@ -421,6 +505,7 @@ impl SbrChain { | |||
| 421 | if source == "hold" { | 505 | if source == "hold" { |
| 422 | HOLD_CALLS.fetch_add(1, Ordering::Relaxed); | 506 | HOLD_CALLS.fetch_add(1, Ordering::Relaxed); |
| 423 | } | 507 | } |
| 508 | + let band_limit = if self.downsampled { ANALYSIS_BANDS } else { SYNTHESIS_BANDS }; | ||
| 424 | let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { | 509 | let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { |
| 425 | return Ok(()); | 510 | return Ok(()); |
| 426 | }; | 511 | }; |
| @@ -443,7 +528,8 @@ impl SbrChain { | |||
| 443 | // through channel 1's (the right output), so both stay in step. | 528 | // through channel 1's (the right output), so both stay in step. |
| 444 | let ps_mode = !is_cpe && planes.len() >= 2 && data.ps.is_some(); | 529 | let ps_mode = !is_cpe && planes.len() >= 2 && data.ps.is_some(); |
| 445 | let mut ps_planes: Option<(Vec<f32>, Vec<f32>)> = None; | 530 | let mut ps_planes: Option<(Vec<f32>, Vec<f32>)> = None; |
| 446 | - let mut r_synth = if ps_mode && elem.channels.len() >= 2 { | 531 | + let dup_mode = !is_cpe && planes.len() >= 2 && data.ps.is_none(); |
| 532 | + let mut r_synth = if (ps_mode || dup_mode) && elem.channels.len() >= 2 { | ||
| 447 | Some(std::mem::take(&mut elem.channels[1].synthesis)) | 533 | Some(std::mem::take(&mut elem.channels[1].synthesis)) |
| 448 | } else { | 534 | } else { |
| 449 | None | 535 | None |
| @@ -637,7 +723,7 @@ impl SbrChain { | |||
| 637 | } | 723 | } |
| 638 | 724 | ||
| 639 | let kx = (tables.kx as usize).min(ANALYSIS_BANDS); | 725 | let kx = (tables.kx as usize).min(ANALYSIS_BANDS); |
| 640 | - let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS); | 726 | + let k2 = (tables.k2 as usize).min(band_limit); |
| 641 | let mut vs: Vec<[Complex<f64>; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots); | 727 | let mut vs: Vec<[Complex<f64>; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots); |
| 642 | for slot in 0..num_slots { | 728 | for slot in 0..num_slots { |
| 643 | let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; | 729 | let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; |
| @@ -663,6 +749,15 @@ impl SbrChain { | |||
| 663 | ps_planes = Some((left_pcm, right_pcm)); | 749 | ps_planes = Some((left_pcm, right_pcm)); |
| 664 | Vec::new() | 750 | Vec::new() |
| 665 | } | 751 | } |
| 752 | + _ if dup_mode => { | ||
| 753 | + let left_pcm = synth_slots(&mut state.synthesis, &vs); | ||
| 754 | + let right_pcm = match r_synth.as_mut() { | ||
| 755 | + Some(rs) => synth_slots(rs, &vs), | ||
| 756 | + None => left_pcm.clone(), | ||
| 757 | + }; | ||
| 758 | + ps_planes = Some((left_pcm, right_pcm)); | ||
| 759 | + Vec::new() | ||
| 760 | + } | ||
| 666 | _ => synth_slots(&mut state.synthesis, &vs), | 761 | _ => synth_slots(&mut state.synthesis, &vs), |
| 667 | }; | 762 | }; |
| 668 | if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() { | 763 | if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() { |
| @@ -766,7 +861,8 @@ fn render_ps( | |||
| 766 | 861 | ||
| 767 | /// Runs `slots` through a synthesis bank, at the SBR output scale. | 862 | /// Runs `slots` through a synthesis bank, at the SBR output scale. |
| 768 | fn synth_slots(synth: &mut Synthesis, slots: &[[Complex<f64>; SYNTHESIS_BANDS]]) -> Vec<f32> { | 863 | fn synth_slots(synth: &mut Synthesis, slots: &[[Complex<f64>; SYNTHESIS_BANDS]]) -> Vec<f32> { |
| 769 | - let mut out = Vec::with_capacity(slots.len() * SYNTHESIS_BANDS); | 864 | + let bands = synth.bands(); |
| 865 | + let mut out = Vec::with_capacity(slots.len() * bands); | ||
| 770 | for v in slots { | 866 | for v in slots { |
| 771 | let mut pcm = synth.process_slot(v); | 867 | let mut pcm = synth.process_slot(v); |
| 772 | for s in &mut pcm { | 868 | for s in &mut pcm { |
| @@ -775,7 +871,7 @@ fn synth_slots(synth: &mut Synthesis, slots: &[[Complex<f64>; SYNTHESIS_BANDS]]) | |||
| 775 | // core's amplitude; the 2x is the upsampler's gain. | 871 | // core's amplitude; the 2x is the upsampler's gain. |
| 776 | *s *= 2.0 * crate::decode::OUTPUT_SCALE; | 872 | *s *= 2.0 * crate::decode::OUTPUT_SCALE; |
| 777 | } | 873 | } |
| 778 | - out.extend_from_slice(&pcm); | 874 | + out.extend_from_slice(&pcm[..bands]); |
| 779 | } | 875 | } |
| 780 | out | 876 | out |
| 781 | } | 877 | } |
crates/ec-aac/src/sbr_hf.rsmodified+4 -0
| @@ -277,6 +277,10 @@ impl ChirpState { | |||
| 277 | } | 277 | } |
| 278 | } | 278 | } |
| 279 | 279 | ||
| 280 | + pub fn bands(&self) -> usize { | ||
| 281 | + self.bw.len() | ||
| 282 | + } | ||
| 283 | + | ||
| 280 | /// Advances the state one frame given this frame's `bs_invf_mode` per | 284 | /// Advances the state one frame given this frame's `bs_invf_mode` per |
| 281 | /// noise band, returning the smoothed bw to use for HF generation. | 285 | /// noise band, returning the smoothed bw to use for HF generation. |
| 282 | /// | 286 | /// |
crates/ec-aac/src/sbr_payload.rsmodified+2 -2
| @@ -350,7 +350,7 @@ impl SbrParser { | |||
| 350 | t[num_env] = trail; | 350 | t[num_env] = trail; |
| 351 | let mut acc = trail; | 351 | let mut acc = trail; |
| 352 | for i in (1..num_env).rev() { | 352 | for i in (1..num_env).rev() { |
| 353 | - acc -= rel[i - 1]; | 353 | + acc -= rel[num_env - 1 - i]; |
| 354 | t[i] = acc; | 354 | t[i] = acc; |
| 355 | } | 355 | } |
| 356 | } else { | 356 | } else { |
| @@ -394,7 +394,7 @@ impl SbrParser { | |||
| 394 | t[num_env] = trail; | 394 | t[num_env] = trail; |
| 395 | let mut acc = trail; | 395 | let mut acc = trail; |
| 396 | for i in (num_rel0 + 1..num_env).rev() { | 396 | for i in (num_rel0 + 1..num_env).rev() { |
| 397 | - acc -= rel1[i - num_rel0 - 1]; | 397 | + acc -= rel1[num_env - 1 - i]; |
| 398 | t[i] = acc; | 398 | t[i] = acc; |
| 399 | } | 399 | } |
| 400 | if t.windows(2).any(|w| w[0] >= w[1]) { | 400 | if t.windows(2).any(|w| w[0] >= w[1]) { |
crates/ec-aac/src/sbr_qmf.rsmodified+39 -41
| @@ -218,70 +218,68 @@ impl Default for HfAnalysis { | |||
| 218 | } | 218 | } |
| 219 | } | 219 | } |
| 220 | 220 | ||
| 221 | -/// The ISO/IEC 14496-3 4.6.18.8.2 64-band complex synthesis QMF bank: | ||
| 222 | -/// complex subband slots in, doubled-rate PCM out, [`SYNTHESIS_BANDS`] | ||
| 223 | -/// output samples per slot. Verified against the literal spec equations at | ||
| 224 | -/// `corr=0.999999` self-consistency (see the module doc). | ||
| 225 | pub struct Synthesis { | 221 | pub struct Synthesis { |
| 226 | - /// History buffer `v`, `10 * PROTO_LEN / SYNTHESIS_BANDS * SYNTHESIS_BANDS` | 222 | + bands: usize, |
| 227 | - /// = `1280` samples (`4.6.18.8.2`'s own length, not `PROTO_LEN`). | 223 | + v: Vec<f64>, |
| 228 | - v: [f64; 1280], | ||
| 229 | cos_tab: Vec<f64>, | 224 | cos_tab: Vec<f64>, |
| 230 | sin_tab: Vec<f64>, | 225 | sin_tab: Vec<f64>, |
| 231 | } | 226 | } |
| 232 | 227 | ||
| 233 | impl Synthesis { | 228 | impl Synthesis { |
| 234 | - /// A fresh bank with a silent history buffer. | ||
| 235 | pub fn new() -> Synthesis { | 229 | pub fn new() -> Synthesis { |
| 236 | - let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; | 230 | + Synthesis::with_bands(SYNTHESIS_BANDS, 0.0) |
| 237 | - let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; | 231 | + } |
| 238 | - for k in 0..SYNTHESIS_BANDS { | 232 | + |
| 239 | - for n in 0..128 { | 233 | + pub fn downsampled() -> Synthesis { |
| 240 | - // phi = pi/128*(k+0.5)*(2n-255) | 234 | + Synthesis::with_bands(SYNTHESIS_BANDS / 2, -0.5) |
| 241 | - let phi = std::f64::consts::PI / 128.0 | 235 | + } |
| 236 | + | ||
| 237 | + fn with_bands(bands: usize, shift: f64) -> Synthesis { | ||
| 238 | + let len = 2 * bands; | ||
| 239 | + let mut cos_tab = vec![0.0f64; bands * len]; | ||
| 240 | + let mut sin_tab = vec![0.0f64; bands * len]; | ||
| 241 | + for k in 0..bands { | ||
| 242 | + for n in 0..len { | ||
| 243 | + let phi = std::f64::consts::PI / len as f64 | ||
| 242 | * (k as f64 + 0.5) | 244 | * (k as f64 + 0.5) |
| 243 | - * (2.0 * n as f64 - 255.0); | 245 | + * (2.0 * n as f64 - (2 * len - 1) as f64 + shift); |
| 244 | - cos_tab[k * 128 + n] = phi.cos(); | 246 | + cos_tab[k * len + n] = phi.cos(); |
| 245 | - sin_tab[k * 128 + n] = phi.sin(); | 247 | + sin_tab[k * len + n] = phi.sin(); |
| 246 | } | 248 | } |
| 247 | } | 249 | } |
| 248 | Synthesis { | 250 | Synthesis { |
| 249 | - v: [0.0; 1280], | 251 | + bands, |
| 252 | + v: vec![0.0; 10 * len], | ||
| 250 | cos_tab, | 253 | cos_tab, |
| 251 | sin_tab, | 254 | sin_tab, |
| 252 | } | 255 | } |
| 253 | } | 256 | } |
| 254 | 257 | ||
| 255 | - /// Feeds one slot of [`SYNTHESIS_BANDS`] complex subband samples and | 258 | + pub fn bands(&self) -> usize { |
| 256 | - /// returns [`SYNTHESIS_BANDS`] output PCM samples. | 259 | + self.bands |
| 260 | + } | ||
| 261 | + | ||
| 257 | pub fn process_slot(&mut self, x: &[Complex<f64>; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] { | 262 | pub fn process_slot(&mut self, x: &[Complex<f64>; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] { |
| 258 | - // v[n] = v[n-128] for n=1279..128 (shift), then v[0..128] filled with | 263 | + let bands = self.bands; |
| 259 | - // v[n] = Re{ (1/64) sum_k X[k]*exp(j*phi) }, n=0..127. | 264 | + let len = 2 * bands; |
| 260 | - self.v.copy_within(0..1152, 128); | 265 | + self.v.copy_within(0..9 * len, len); |
| 261 | - for n in 0..128 { | 266 | + for n in 0..len { |
| 262 | let mut re = 0.0f64; | 267 | let mut re = 0.0f64; |
| 263 | - for (k, xk) in x.iter().enumerate() { | 268 | + for (k, xk) in x.iter().take(bands).enumerate() { |
| 264 | - let row = k * 128; | 269 | + let at = k * len + n; |
| 265 | - // Re{X[k]*exp(j*phi)} = Xre*cos(phi) - Xim*sin(phi) | 270 | + re += xk.re * self.cos_tab[at] - xk.im * self.sin_tab[at]; |
| 266 | - re += xk.re * self.cos_tab[row + n] - xk.im * self.sin_tab[row + n]; | ||
| 267 | } | 271 | } |
| 268 | self.v[n] = re / SYNTHESIS_BANDS as f64; | 272 | self.v[n] = re / SYNTHESIS_BANDS as f64; |
| 269 | } | 273 | } |
| 270 | - // g[128i+n] = v[256i+n], g[128i+64+n] = v[256i+192+n], i=0..4, n=0..63 | 274 | + let step = SYNTHESIS_BANDS / bands; |
| 271 | - let mut g = [0.0f64; PROTO_LEN]; | ||
| 272 | - for i in 0..5 { | ||
| 273 | - for n in 0..64 { | ||
| 274 | - g[128 * i + n] = self.v[256 * i + n]; | ||
| 275 | - g[128 * i + 64 + n] = self.v[256 * i + 192 + n]; | ||
| 276 | - } | ||
| 277 | - } | ||
| 278 | - // w[n] = g[n]*c[n], n=0..639; y[n] = sum_{k=0}^{9} w[64k+n], n=0..63 | ||
| 279 | let mut out = [0.0f32; SYNTHESIS_BANDS]; | 275 | let mut out = [0.0f32; SYNTHESIS_BANDS]; |
| 280 | - for (n, o) in out.iter_mut().enumerate() { | 276 | + for (n, o) in out.iter_mut().take(bands).enumerate() { |
| 281 | let mut acc = 0.0f64; | 277 | let mut acc = 0.0f64; |
| 282 | - for k in 0..10 { | 278 | + for i in 0..5 { |
| 283 | - let idx = 64 * k + n; | 279 | + let near = self.v[2 * len * i + n]; |
| 284 | - acc += g[idx] * QMF_WINDOW[idx]; | 280 | + let far = self.v[2 * len * i + 3 * bands + n]; |
| 281 | + acc += near * QMF_WINDOW[step * (len * i + n)]; | ||
| 282 | + acc += far * QMF_WINDOW[step * (len * i + bands + n)]; | ||
| 285 | } | 283 | } |
| 286 | *o = acc as f32; | 284 | *o = acc as f32; |
| 287 | } | 285 | } |
crates/ec-aac/tests/sbr_real_library/chunk_a.rsmodified+11 -2
| @@ -164,9 +164,18 @@ pub(super) fn full_chain_low_band_matches_own_core() { | |||
| 164 | // sample-for-sample with the full-chain output's rate -- | 164 | // sample-for-sample with the full-chain output's rate -- |
| 165 | // crude, but a low-pass well below the core Nyquist erases the | 165 | // crude, but a low-pass well below the core Nyquist erases the |
| 166 | // stairstep artifacts this introduces. | 166 | // stairstep artifacts this introduces. |
| 167 | - let up: Vec<f32> = core[ch].iter().flat_map(|&s| [s, s]).collect(); | 167 | + let up = if full_rate == core_rate { |
| 168 | + core[ch].clone() | ||
| 169 | + } else { | ||
| 170 | + upsample_2x(&core[ch]) | ||
| 171 | + }; | ||
| 168 | let cutoff = f64::from(core_rate) * 0.4; | 172 | let cutoff = f64::from(core_rate) * 0.4; |
| 169 | - let ol = lowpass(&full[ch], full_rate, cutoff); | 173 | + let keep = if full.len() > core.len() { |
| 174 | + mono_prefix(&full) | ||
| 175 | + } else { | ||
| 176 | + full[ch].len() | ||
| 177 | + }; | ||
| 178 | + let ol = lowpass(&full[ch][..keep], full_rate, cutoff); | ||
| 170 | let ul = lowpass(&up, full_rate, cutoff); | 179 | let ul = lowpass(&up, full_rate, cutoff); |
| 171 | // Escalating search: narrow (`WIDE_LAG_MAX`=20_000, the file's | 180 | // Escalating search: narrow (`WIDE_LAG_MAX`=20_000, the file's |
| 172 | // original bound) first, widen to `SEARCH_LAG_MAX` only if that | 181 | // original bound) first, widen to `SEARCH_LAG_MAX` only if that |
crates/ec-aac/tests/sbr_real_library/helpers.rsmodified+38 -20
| @@ -231,11 +231,7 @@ pub(super) fn correlation(a: &[f32], b: &[f32]) -> f64 { | |||
| 231 | /// case the coarse slice picked a noisy lag) gives the reported number. | 231 | /// case the coarse slice picked a noisy lag) gives the reported number. |
| 232 | pub(super) fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) { | 232 | pub(super) fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) { |
| 233 | const COARSE: usize = 4_096; | 233 | const COARSE: usize = 4_096; |
| 234 | - let start = ours | 234 | + let start = window_start(ours, theirs); |
| 235 | - .len() | ||
| 236 | - .min(theirs.len()) | ||
| 237 | - .saturating_sub(WINDOW) | ||
| 238 | - .min(ours.len() / 4); | ||
| 239 | let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { | 235 | let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { |
| 240 | let (oa, ob) = if lag >= 0 { | 236 | let (oa, ob) = if lag >= 0 { |
| 241 | (start, start + lag as usize) | 237 | (start, start + lag as usize) |
| @@ -365,11 +361,7 @@ pub(super) fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i | |||
| 365 | /// refinement it replaces, so the resolution is simply not worth trading. | 361 | /// refinement it replaces, so the resolution is simply not worth trading. |
| 366 | pub(super) fn exhaustive_lag_correlation(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) { | 362 | pub(super) fn exhaustive_lag_correlation(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) { |
| 367 | const COARSE: usize = 4_096; | 363 | const COARSE: usize = 4_096; |
| 368 | - let start = ours | 364 | + let start = window_start(ours, theirs); |
| 369 | - .len() | ||
| 370 | - .min(theirs.len()) | ||
| 371 | - .saturating_sub(WINDOW) | ||
| 372 | - .min(ours.len() / 4); | ||
| 373 | let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { | 365 | let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { |
| 374 | let (oa, ob) = if lag >= 0 { | 366 | let (oa, ob) = if lag >= 0 { |
| 375 | (start, start + lag as usize) | 367 | (start, start + lag as usize) |
| @@ -421,11 +413,7 @@ pub(super) fn robust_lag_topk( | |||
| 421 | k: usize, | 413 | k: usize, |
| 422 | ) -> (i64, f64, bool) { | 414 | ) -> (i64, f64, bool) { |
| 423 | const COARSE: usize = 4_096; | 415 | const COARSE: usize = 4_096; |
| 424 | - let start = ours | 416 | + let start = window_start(ours, theirs); |
| 425 | - .len() | ||
| 426 | - .min(theirs.len()) | ||
| 427 | - .saturating_sub(WINDOW) | ||
| 428 | - .min(ours.len() / 4); | ||
| 429 | let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { | 417 | let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { |
| 430 | let (oa, ob) = if lag >= 0 { | 418 | let (oa, ob) = if lag >= 0 { |
| 431 | (start, start + lag as usize) | 419 | (start, start + lag as usize) |
| @@ -477,6 +465,40 @@ pub(super) fn robust_lag_topk( | |||
| 477 | best | 465 | best |
| 478 | } | 466 | } |
| 479 | 467 | ||
| 468 | +pub(super) fn window_start(ours: &[f32], theirs: &[f32]) -> usize { | ||
| 469 | + const CHUNK: usize = 1_024; | ||
| 470 | + const CHUNKS: usize = 4; | ||
| 471 | + let end = ours.len().min(theirs.len()); | ||
| 472 | + let base = end.saturating_sub(WINDOW).min(ours.len() / 4); | ||
| 473 | + let power = |s: &[f32]| { | ||
| 474 | + s.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() / s.len().max(1) as f64 | ||
| 475 | + }; | ||
| 476 | + let floor = 1e-4 * power(&ours[base..end]).min(power(&theirs[base..end])); | ||
| 477 | + let loud = |p: usize| { | ||
| 478 | + p + CHUNK * CHUNKS <= end | ||
| 479 | + && (p..p + CHUNK * CHUNKS) | ||
| 480 | + .step_by(CHUNK) | ||
| 481 | + .all(|a| power(&ours[a..a + CHUNK]) > floor && power(&theirs[a..a + CHUNK]) > floor) | ||
| 482 | + }; | ||
| 483 | + (base..end).step_by(CHUNK).find(|&p| loud(p)).unwrap_or(base) | ||
| 484 | +} | ||
| 485 | + | ||
| 486 | +pub(super) fn upsample_2x(core: &[f32]) -> Vec<f32> { | ||
| 487 | + let mut out = Vec::with_capacity(core.len() * 2); | ||
| 488 | + for (i, &s) in core.iter().enumerate() { | ||
| 489 | + out.push(s); | ||
| 490 | + out.push((s + core.get(i + 1).copied().unwrap_or(s)) * 0.5); | ||
| 491 | + } | ||
| 492 | + out | ||
| 493 | +} | ||
| 494 | + | ||
| 495 | +pub(super) fn mono_prefix(planes: &[Vec<f32>]) -> usize { | ||
| 496 | + let first = &planes[0]; | ||
| 497 | + planes.get(1).map_or(first.len(), |second| { | ||
| 498 | + first.iter().zip(second).position(|(a, b)| a != b).unwrap_or(first.len()) | ||
| 499 | + }) | ||
| 500 | +} | ||
| 501 | + | ||
| 480 | /// Signed correlation of `ours` against `theirs` at one fixed `lag`, full | 502 | /// Signed correlation of `ours` against `theirs` at one fixed `lag`, full |
| 481 | /// `WINDOW`-sized, anchored at the SAME `start` offset `best_lag_correlation` | 503 | /// `WINDOW`-sized, anchored at the SAME `start` offset `best_lag_correlation` |
| 482 | /// uses internally -- used to test a hypothesized sign inversion by reusing | 504 | /// uses internally -- used to test a hypothesized sign inversion by reusing |
| @@ -486,11 +508,7 @@ pub(super) fn robust_lag_topk( | |||
| 486 | /// match `best_lag_correlation`'s `start`, not sample 0 -- the two windows | 508 | /// match `best_lag_correlation`'s `start`, not sample 0 -- the two windows |
| 487 | /// otherwise cover different seconds of audio and are not comparable. | 509 | /// otherwise cover different seconds of audio and are not comparable. |
| 488 | pub(super) fn correlation_at_lag(ours: &[f32], theirs: &[f32], lag: i64) -> f64 { | 510 | pub(super) fn correlation_at_lag(ours: &[f32], theirs: &[f32], lag: i64) -> f64 { |
| 489 | - let start = ours | 511 | + let start = window_start(ours, theirs); |
| 490 | - .len() | ||
| 491 | - .min(theirs.len()) | ||
| 492 | - .saturating_sub(WINDOW) | ||
| 493 | - .min(ours.len() / 4); | ||
| 494 | let (oa, ob) = if lag >= 0 { | 512 | let (oa, ob) = if lag >= 0 { |
| 495 | (start, start + lag as usize) | 513 | (start, start + lag as usize) |
| 496 | } else { | 514 | } else { |
crates/ec-av1/src/encoder/mod.rsmodified+39 -43
| @@ -125,6 +125,7 @@ impl RateTarget { | |||
| 125 | /// (`None` for the two open-loop variants). `mini_gop` is `Some` in | 125 | /// (`None` for the two open-loop variants). `mini_gop` is `Some` in |
| 126 | /// pyramid mode, which is what makes the loop keep a quantizer per level. | 126 | /// pyramid mode, which is what makes the loop keep a quantizer per level. |
| 127 | fn into_loop(self, config: &mut EncoderConfig, pyramid: Option<Pyramid>) -> Option<RateLoop> { | 127 | fn into_loop(self, config: &mut EncoderConfig, pyramid: Option<Pyramid>) -> Option<RateLoop> { |
| 128 | + let repay = matches!(self, RateTarget::Bitrate { .. }); | ||
| 128 | let target_bytes = match self { | 129 | let target_bytes = match self { |
| 129 | RateTarget::QIndex(q) => { | 130 | RateTarget::QIndex(q) => { |
| 130 | config.base_q_idx = q; | 131 | config.base_q_idx = q; |
| @@ -140,12 +141,14 @@ impl RateTarget { | |||
| 140 | frames_per_second, | 141 | frames_per_second, |
| 141 | } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0), | 142 | } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0), |
| 142 | }; | 143 | }; |
| 143 | - Some(RateLoop::new( | 144 | + let mut rate_loop = RateLoop::new( |
| 144 | target_bytes, | 145 | target_bytes, |
| 145 | f64::from(config.base_q_idx), | 146 | f64::from(config.base_q_idx), |
| 146 | pyramid, | 147 | pyramid, |
| 147 | config.gop, | 148 | config.gop, |
| 148 | - )) | 149 | + ); |
| 150 | + rate_loop.repay = repay; | ||
| 151 | + Some(rate_loop) | ||
| 149 | } | 152 | } |
| 150 | } | 153 | } |
| 151 | 154 | ||
| @@ -236,14 +239,11 @@ struct RateLoop { | |||
| 236 | target: [f64; 3], | 239 | target: [f64; 3], |
| 237 | /// Quantizer per level, same index. | 240 | /// Quantizer per level, same index. |
| 238 | q: [f64; 3], | 241 | q: [f64; 3], |
| 239 | - /// Whether the three slots are actually distinct (pyramid mode) or all | ||
| 240 | - /// one shared controller (the flat path, unchanged from before levels | ||
| 241 | - /// existed). | ||
| 242 | - per_level: bool, | ||
| 243 | /// Whether each slot has already steered off a real coded frame. The | 242 | /// Whether each slot has already steered off a real coded frame. The |
| 244 | /// FIRST update of a slot is the seeding one and takes the model's whole | 243 | /// FIRST update of a slot is the seeding one and takes the model's whole |
| 245 | /// step ([`RateLoop::update`]); every later one is clamped. | 244 | /// step ([`RateLoop::update`]); every later one is clamped. |
| 246 | seeded: [bool; 3], | 245 | seeded: [bool; 3], |
| 246 | + prev_ratio: [f64; 3], | ||
| 247 | /// The leaf's own q offset: the zero of the level weight | 247 | /// The leaf's own q offset: the zero of the level weight |
| 248 | /// ([`WEIGHT_LEVEL_GAIN`]), so slot 1's target can be read in | 248 | /// ([`WEIGHT_LEVEL_GAIN`]), so slot 1's target can be read in |
| 249 | /// LEAF-EQUIVALENT bytes and scaled per frame by that frame's offset. | 249 | /// LEAF-EQUIVALENT bytes and scaled per frame by that frame's offset. |
| @@ -272,6 +272,7 @@ struct RateLoop { | |||
| 272 | /// a level held at its bound hands its unspent bytes to the others, but | 272 | /// a level held at its bound hands its unspent bytes to the others, but |
| 273 | /// no level's target may exceed this many times its own opening share. | 273 | /// no level's target may exceed this many times its own opening share. |
| 274 | scale0: f64, | 274 | scale0: f64, |
| 275 | + repay: bool, | ||
| 275 | /// `EC_AV1_RL_CENSUS=1`: one line per coded frame on stderr. | 276 | /// `EC_AV1_RL_CENSUS=1`: one line per coded frame on stderr. |
| 276 | census: bool, | 277 | census: bool, |
| 277 | coded: usize, | 278 | coded: usize, |
| @@ -285,7 +286,7 @@ impl RateLoop { | |||
| 285 | const STEP_CLAMP: f64 = 12.0; | 286 | const STEP_CLAMP: f64 = 12.0; |
| 286 | /// The calibration sweep's own slope (see the struct doc), inverted to | 287 | /// The calibration sweep's own slope (see the struct doc), inverted to |
| 287 | /// convert a bytes ratio into a `q_idx` step. | 288 | /// convert a bytes ratio into a `q_idx` step. |
| 288 | - const GAIN: f64 = 1.0 / 0.0154; | 289 | + const GAIN: f64 = 1.0 / WEIGHT_LEVEL_GAIN; |
| 289 | /// The windup bound on [`RateLoop::replan`]: however much a bound level | 290 | /// The windup bound on [`RateLoop::replan`]: however much a bound level |
| 290 | /// fails to spend, no other level's target may grow past this multiple of | 291 | /// fails to spend, no other level's target may grow past this multiple of |
| 291 | /// its opening share. Without it a run whose hidden levels are all at the | 292 | /// its opening share. Without it a run whose hidden levels are all at the |
| @@ -297,26 +298,9 @@ impl RateLoop { | |||
| 297 | /// target), which is how the first cut of this fix froze every level of a | 298 | /// target), which is how the first cut of this fix froze every level of a |
| 298 | /// run at whatever quantizer it had reached. | 299 | /// run at whatever quantizer it had reached. |
| 299 | const REPLAN_FLOOR: f64 = 0.25; | 300 | const REPLAN_FLOOR: f64 = 0.25; |
| 301 | + const TINY_FRAME_DIVISOR: f64 = 4.0; | ||
| 300 | 302 | ||
| 301 | fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self { | 303 | fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self { |
| 302 | - let Some(p) = pyramid else { | ||
| 303 | - return Self { | ||
| 304 | - target: [target_bytes; 3], | ||
| 305 | - q: [start_q; 3], | ||
| 306 | - per_level: false, | ||
| 307 | - seeded: [false; 3], | ||
| 308 | - leaf_q_offset: 0, | ||
| 309 | - key_weight: 1.0, | ||
| 310 | - run_weight: 0.0, | ||
| 311 | - run_bytes: 0.0, | ||
| 312 | - left_weight: 0.0, | ||
| 313 | - left_bytes: 0.0, | ||
| 314 | - plans: [None; 5], | ||
| 315 | - scale0: target_bytes, | ||
| 316 | - census: census_on(), | ||
| 317 | - coded: 0, | ||
| 318 | - }; | ||
| 319 | - }; | ||
| 320 | // THE LEVEL MODEL. Every coded frame of the run is priced by its own | 304 | // THE LEVEL MODEL. Every coded frame of the run is priced by its own |
| 321 | // q offset through `WEIGHT_LEVEL_GAIN`, in units of one leaf, and the | 305 | // q offset through `WEIGHT_LEVEL_GAIN`, in units of one leaf, and the |
| 322 | // run's `gop` frame targets are shared out in those units. The old | 306 | // run's `gop` frame targets are shared out in those units. The old |
| @@ -327,11 +311,17 @@ impl RateLoop { | |||
| 327 | // [`Pyramid::quarter_q_offset`]), and a hidden frame is worth far | 311 | // [`Pyramid::quarter_q_offset`]), and a hidden frame is worth far |
| 328 | // more than two leaves -- the census reads the top ARF at 24x a leaf | 312 | // more than two leaves -- the census reads the top ARF at 24x a leaf |
| 329 | // and the mid at 5x. Both are fixed here, in one diff. | 313 | // and the mid at 5x. Both are fixed here, in one diff. |
| 314 | + let (key_q_offset, leaf_q_offset, hidden, leaves) = match pyramid { | ||
| 315 | + Some(p) => { | ||
| 316 | + let (hidden, leaves) = gop_shape(p, gop); | ||
| 317 | + (p.key_q_offset, p.leaf_q_offset, hidden, leaves) | ||
| 318 | + } | ||
| 319 | + None => (0, 0, Vec::new(), gop.saturating_sub(1)), | ||
| 320 | + }; | ||
| 330 | let w = |offset: i16| { | 321 | let w = |offset: i16| { |
| 331 | - ((f64::from(p.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp() | 322 | + ((f64::from(leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp() |
| 332 | }; | 323 | }; |
| 333 | - let (hidden, leaves) = gop_shape(p, gop); | 324 | + let key = KEY_WEIGHT * w(key_q_offset); |
| 334 | - let key = KEY_WEIGHT * w(p.key_q_offset); | ||
| 335 | let total: f64 = | 325 | let total: f64 = |
| 336 | key + leaves as f64 + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>(); | 326 | key + leaves as f64 + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>(); |
| 337 | // One leaf's byte target: the run is worth `gop` frame targets and | 327 | // One leaf's byte target: the run is worth `gop` frame targets and |
| @@ -347,19 +337,18 @@ impl RateLoop { | |||
| 347 | // One plan per level, in coding order: key, hidden levels (at most | 337 | // One plan per level, in coding order: key, hidden levels (at most |
| 348 | // three distinct offsets -- top, mid, quarters), leaves. | 338 | // three distinct offsets -- top, mid, quarters), leaves. |
| 349 | let mut plans = [None; 5]; | 339 | let mut plans = [None; 5]; |
| 350 | - plans[0] = Some(LevelPlan::new(0, p.key_q_offset, key)); | 340 | + plans[0] = Some(LevelPlan::new(0, key_q_offset, key)); |
| 351 | let mut i = 1; | 341 | let mut i = 1; |
| 352 | for &(o, n) in hidden.iter().take(3) { | 342 | for &(o, n) in hidden.iter().take(3) { |
| 353 | plans[i] = Some(LevelPlan::new(1, o, n as f64 * w(o))); | 343 | plans[i] = Some(LevelPlan::new(1, o, n as f64 * w(o))); |
| 354 | i += 1; | 344 | i += 1; |
| 355 | } | 345 | } |
| 356 | - plans[i] = Some(LevelPlan::new(2, p.leaf_q_offset, leaves as f64)); | 346 | + plans[i] = Some(LevelPlan::new(2, leaf_q_offset, leaves as f64)); |
| 357 | Self { | 347 | Self { |
| 358 | target: [scale * key, scale, scale], | 348 | target: [scale * key, scale, scale], |
| 359 | q: [start_q; 3], | 349 | q: [start_q; 3], |
| 360 | - per_level: true, | ||
| 361 | seeded: [false; 3], | 350 | seeded: [false; 3], |
| 362 | - leaf_q_offset: p.leaf_q_offset, | 351 | + leaf_q_offset, |
| 363 | key_weight: key, | 352 | key_weight: key, |
| 364 | run_weight: total, | 353 | run_weight: total, |
| 365 | run_bytes: target_bytes * gop.max(1) as f64, | 354 | run_bytes: target_bytes * gop.max(1) as f64, |
| @@ -367,6 +356,8 @@ impl RateLoop { | |||
| 367 | left_bytes: target_bytes * gop.max(1) as f64, | 356 | left_bytes: target_bytes * gop.max(1) as f64, |
| 368 | plans, | 357 | plans, |
| 369 | scale0: scale, | 358 | scale0: scale, |
| 359 | + repay: true, | ||
| 360 | + prev_ratio: [1.0; 3], | ||
| 370 | census: census_on(), | 361 | census: census_on(), |
| 371 | coded: 0, | 362 | coded: 0, |
| 372 | } | 363 | } |
| @@ -386,12 +377,7 @@ impl RateLoop { | |||
| 386 | .position(|p| p.is_some_and(|p| p.slot == slot && (slot != 1 || p.offset == offset))) | 377 | .position(|p| p.is_some_and(|p| p.slot == slot && (slot != 1 || p.offset == offset))) |
| 387 | } | 378 | } |
| 388 | 379 | ||
| 389 | - /// Which controller a level uses: one shared slot on the flat path, three | ||
| 390 | - /// separate ones under a pyramid. | ||
| 391 | fn slot(&self, level: Level) -> usize { | 380 | fn slot(&self, level: Level) -> usize { |
| 392 | - if !self.per_level { | ||
| 393 | - return 0; | ||
| 394 | - } | ||
| 395 | match level { | 381 | match level { |
| 396 | Level::Key => 0, | 382 | Level::Key => 0, |
| 397 | Level::Arf => 1, | 383 | Level::Arf => 1, |
| @@ -423,7 +409,7 @@ impl RateLoop { | |||
| 423 | 1 => self.weight(offset), | 409 | 1 => self.weight(offset), |
| 424 | _ => 1.0, | 410 | _ => 1.0, |
| 425 | }; | 411 | }; |
| 426 | - let target = match self.per_level && slot == 1 { | 412 | + let target = match slot == 1 { |
| 427 | true => self.target[slot] * frame_weight, | 413 | true => self.target[slot] * frame_weight, |
| 428 | false => self.target[slot], | 414 | false => self.target[slot], |
| 429 | }; | 415 | }; |
| @@ -439,12 +425,23 @@ impl RateLoop { | |||
| 439 | // step and seeds `q` where the log-linear slope says it belongs; from | 425 | // step and seeds `q` where the log-linear slope says it belongs; from |
| 440 | // the second frame on the clamp is back, and nothing is accumulated | 426 | // the second frame on the clamp is back, and nothing is accumulated |
| 441 | // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds. | 427 | // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds. |
| 442 | - let raw = ratio.ln() * Self::GAIN; | 428 | + let seeded = std::mem::replace(&mut self.seeded[slot], true); |
| 443 | - let step = if std::mem::replace(&mut self.seeded[slot], true) { | 429 | + let smoothed = if seeded && !self.repay { |
| 430 | + (ratio * self.prev_ratio[slot]).sqrt() | ||
| 431 | + } else { | ||
| 432 | + ratio | ||
| 433 | + }; | ||
| 434 | + self.prev_ratio[slot] = ratio; | ||
| 435 | + let raw = smoothed.ln() * Self::GAIN; | ||
| 436 | + let step = if seeded { | ||
| 444 | raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP) | 437 | raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP) |
| 445 | } else { | 438 | } else { |
| 446 | raw | 439 | raw |
| 447 | }; | 440 | }; |
| 441 | + let step = match ratio < 1.0 / Self::TINY_FRAME_DIVISOR && step < 0.0 { | ||
| 442 | + true => 0.0, | ||
| 443 | + false => step, | ||
| 444 | + }; | ||
| 448 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); | 445 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); |
| 449 | let bound = !(1..=255).contains(&raw_q); | 446 | let bound = !(1..=255).contains(&raw_q); |
| 450 | if let Some(plan) = self | 447 | if let Some(plan) = self |
| @@ -467,8 +464,10 @@ impl RateLoop { | |||
| 467 | ); | 464 | ); |
| 468 | self.coded += 1; | 465 | self.coded += 1; |
| 469 | } | 466 | } |
| 467 | + if self.repay { | ||
| 470 | self.replan(level, slot, offset, frame_weight, actual_bytes as f64); | 468 | self.replan(level, slot, offset, frame_weight, actual_bytes as f64); |
| 471 | } | 469 | } |
| 470 | + } | ||
| 472 | 471 | ||
| 473 | /// Re-plans the REST OF THE RUN from what it has actually spent: the | 472 | /// Re-plans the REST OF THE RUN from what it has actually spent: the |
| 474 | /// level model says how the budget SPLITS, and nothing but a measurement | 473 | /// level model says how the budget SPLITS, and nothing but a measurement |
| @@ -495,9 +494,6 @@ impl RateLoop { | |||
| 495 | frame_weight: f64, | 494 | frame_weight: f64, |
| 496 | actual_bytes: f64, | 495 | actual_bytes: f64, |
| 497 | ) { | 496 | ) { |
| 498 | - if !self.per_level { | ||
| 499 | - return; | ||
| 500 | - } | ||
| 501 | if level == Level::Key { | 497 | if level == Level::Key { |
| 502 | self.left_weight = self.run_weight; | 498 | self.left_weight = self.run_weight; |
| 503 | self.left_bytes = self.run_bytes; | 499 | self.left_bytes = self.run_bytes; |
crates/ec-av1/src/encoder/tests.rsmodified+13 -2
| @@ -672,6 +672,15 @@ | |||
| 672 | width: usize, | 672 | width: usize, |
| 673 | height: usize, | 673 | height: usize, |
| 674 | frames: usize, | 674 | frames: usize, |
| 675 | + ) -> Option<Vec<Picture>> { | ||
| 676 | + h264_clip_frames_at(20, width, height, frames) | ||
| 677 | + } | ||
| 678 | + | ||
| 679 | + fn h264_clip_frames_at( | ||
| 680 | + start: u32, | ||
| 681 | + width: usize, | ||
| 682 | + height: usize, | ||
| 683 | + frames: usize, | ||
| 675 | ) -> Option<Vec<Picture>> { | 684 | ) -> Option<Vec<Picture>> { |
| 676 | // lane-av1speed3: the wall tables below are read on REAL film as | 685 | // lane-av1speed3: the wall tables below are read on REAL film as |
| 677 | // well as on the colour-bar fixture (`bars` vs `film` in the BD | 686 | // well as on the colour-bar fixture (`bars` vs `film` in the BD |
| @@ -694,7 +703,7 @@ | |||
| 694 | // therefore `return` on `None` WITHOUT printing a second one -- the | 703 | // therefore `return` on `None` WITHOUT printing a second one -- the |
| 695 | // second "no fixture" line per gate was the noise that hid this defect. | 704 | // second "no fixture" line per gate was the noise that hid this defect. |
| 696 | let out = ec_testkit::ffmpeg() | 705 | let out = ec_testkit::ffmpeg() |
| 697 | - .args(["-v", "error", "-ss", "20", "-i", clip.to_str().unwrap()]) | 706 | + .args(["-v", "error", "-ss", &start.to_string(), "-i", clip.to_str().unwrap()]) |
| 698 | .args(["-frames:v", &frames.to_string()]) | 707 | .args(["-frames:v", &frames.to_string()]) |
| 699 | .args(["-vf", &format!("scale={width}:{height}")]) | 708 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 700 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() | 709 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() |
| @@ -915,11 +924,13 @@ | |||
| 915 | ); | 924 | ); |
| 916 | } | 925 | } |
| 917 | 926 | ||
| 927 | + const CLEAN_START: u32 = 23; | ||
| 928 | + | ||
| 918 | #[test] | 929 | #[test] |
| 919 | fn bitrate_target_lands_within_5_percent_over_48_frames() { | 930 | fn bitrate_target_lands_within_5_percent_over_48_frames() { |
| 920 | let _knobs = crate::speed::knob_read(); | 931 | let _knobs = crate::speed::knob_read(); |
| 921 | let (width, height, frames) = (640usize, 384usize, 48usize); | 932 | let (width, height, frames) = (640usize, 384usize, 48usize); |
| 922 | - let Some(pictures) = h264_clip_frames(width, | 933 | + let Some(pictures) = h264_clip_frames_at(CLEAN_START, width, |
| 923 | height, | 934 | height, |
| 924 | frames, | 935 | frames, |
| 925 | ) else { | 936 | ) else { |
crates/ec-av1/src/stack_budget.rsmodified+1 -1
| @@ -192,7 +192,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option<usize>, bool, &str)] = &[ | |||
| 192 | // -- encoder.rs ------------------------------------------------------- | 192 | // -- encoder.rs ------------------------------------------------------- |
| 193 | ( | 193 | ( |
| 194 | "Av1Encoder", | 194 | "Av1Encoder", |
| 195 | - Some(2704), | 195 | + Some(2728), |
| 196 | true, | 196 | true, |
| 197 | "Av1Encoder::new / with_speed / with_pyramid / with_rate_target / \ | 197 | "Av1Encoder::new / with_speed / with_pyramid / with_rate_target / \ |
| 198 | with_pyramid_and_rate_target, all `Result<Self>`, nesting three deep", | 198 | with_pyramid_and_rate_target, all `Result<Self>`, nesting three deep", |