diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index 89681d85..6160d5c9 100644 --- a/crates/ec-aac/src/decode.rs +++ b/crates/ec-aac/src/decode.rs @@ -582,6 +582,12 @@ impl BlockDecoder { self.sbr = rate.map(crate::sbr_chain::SbrChain::new); } + pub fn set_sbr_downsampled(&mut self, on: bool) { + if let Some(sbr) = self.sbr.as_mut() { + sbr.set_downsampled(on); + } + } + /// Marks Parametric Stereo as signalled by the config, for the SBR chain /// (if one is armed): its elements then decode to two channels. pub fn set_sbr_ps(&mut self, on: bool) { @@ -986,7 +992,7 @@ impl BlockDecoder { } } } - if !applied { + if !applied && !arming { // No fresh SBR payload this frame (no SBR fill // element, or one whose extension_type wasn't // SBR, or a parse failure): ยง4.6.18 still diff --git a/crates/ec-aac/src/lib.rs b/crates/ec-aac/src/lib.rs index 106b7426..2a96f88e 100644 --- a/crates/ec-aac/src/lib.rs +++ b/crates/ec-aac/src/lib.rs @@ -144,8 +144,10 @@ impl AacDecoder { // SBR (and Parametric Stereo, for HE-AACv2) is reconstructed: the // core is decoded first, then the extension-rate chain runs on it. if cfg.sbr_present { - let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2); - d.block.set_sbr_rate(Some(rate)); + let sbr_rate = cfg.sample_rate * 2; + let ext_rate = cfg.extension_sample_rate.unwrap_or(sbr_rate); + d.block.set_sbr_rate(Some(sbr_rate)); + d.block.set_sbr_downsampled(ext_rate < sbr_rate); d.block.set_sbr_ps(cfg.ps_present); } else if !cfg.ps_present { // Plain AAC-LC config: an SBR payload may still follow (implicit signalling). diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index a6032a87..0ba1c501 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -236,6 +236,19 @@ struct Element { ps_engine: PsEngine, } +impl Element { + fn ensure_channels(&mut self, need: usize, downsampled: bool) { + while self.channels.len() < need { + let seed = 0x1234_5678u32.wrapping_add(self.channels.len() as u32 * 0x9e37_79b9); + let mut channel = ChannelState::new(1, seed); + if downsampled { + channel.synthesis = Synthesis::downsampled(); + } + self.channels.push(channel); + } + } +} + /// QMF slots per SBR frame: the PS path runs only for the 32-slot frames /// that AAC-LC's 1024-sample frames produce. const PS_SLOTS: usize = 32; @@ -245,6 +258,7 @@ const PS_SLOTS: usize = 32; /// encoder in practice emits it). pub struct SbrChain { rate: u32, + downsampled: bool, /// PS is signalled by the config (explicit HE-AACv2). ps_config: bool, // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance @@ -263,12 +277,17 @@ impl SbrChain { pub fn new(rate: u32) -> SbrChain { SbrChain { rate, + downsampled: false, ps_config: false, elements: HashMap::new(), bypass: HashMap::new(), } } + pub fn set_downsampled(&mut self, on: bool) { + self.downsampled = on; + } + /// Marks PS as signalled by the config: the element's output is stereo. pub fn set_ps_config(&mut self, on: bool) { self.ps_config = on; @@ -280,8 +299,24 @@ impl SbrChain { /// Parses one FIL element's `sbr_extension_data` (the reader /// positioned right past `bs_extension_type`) for element `tag`. pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option { + let (ps_config, downsampled) = (self.ps_config, self.downsampled); + let elem = self.element(tag, is_cpe); + let data = elem.parser.parse(r, is_cpe).ok()?; + let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); + let ps_out = data.ps.is_some() || (ps_config && !is_cpe); + let need = data.channels.len().max(if ps_out { 2 } else { 1 }); + elem.ensure_channels(need, downsampled); + for ch in &mut elem.channels { + if ch.chirp.bands() != n_q { + ch.chirp = ChirpState::new(n_q); + } + } + Some(data) + } + + fn element(&mut self, tag: u8, is_cpe: bool) -> &mut Element { let (rate, ps_config) = (self.rate, self.ps_config); - let elem = self.elements.entry((tag, is_cpe)).or_insert_with(|| { + self.elements.entry((tag, is_cpe)).or_insert_with(|| { let mut parser = SbrParser::new(rate); parser.set_ps_config(ps_config); Element { @@ -291,16 +326,57 @@ impl SbrChain { last_header: None, ps_engine: PsEngine::new(), } - }); - let data = elem.parser.parse(r, is_cpe).ok()?; - let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); - // PS needs a second synthesis state: the right output channel. - let need = data.channels.len().max(if data.ps.is_some() { 2 } else { 1 }); - while elem.channels.len() < need { - let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9); - elem.channels.push(ChannelState::new(n_q, seed)); + }) + } + + fn apply_low_only(&mut self, tag: u8, is_cpe: bool, planes: &mut [Vec]) { + let dup = !is_cpe && planes.len() == 2; + let downsampled = self.downsampled; + let elem = self.element(tag, is_cpe); + elem.ensure_channels(planes.len(), downsampled); + let mut right_synth = if dup { + Some(std::mem::take(&mut elem.channels[1].synthesis)) + } else { + None + }; + let mut right_plane = None; + for (plane, state) in planes.iter_mut().zip(elem.channels.iter_mut()) { + if right_plane.is_some() { + break; + } + let num_slots = plane.len() / ANALYSIS_BANDS; + let mut raw = Vec::with_capacity(num_slots); + for slot in 0..num_slots { + let mut chunk = [0f32; ANALYSIS_BANDS]; + chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); + for s in &mut chunk { + *s /= crate::decode::OUTPUT_SCALE; + } + raw.push(state.analysis.process_slot(&chunk)); + } + let mut delayed = state.low_tail.clone(); + delayed.extend_from_slice(&raw); + state.low_tail = delayed[delayed.len() - HF_ADJ..].to_vec(); + delayed.truncate(num_slots); + let vs: Vec<[Complex; SYNTHESIS_BANDS]> = delayed + .iter() + .map(|sub| { + let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; + v[..ANALYSIS_BANDS].copy_from_slice(sub); + v + }) + .collect(); + *plane = synth_slots(&mut state.synthesis, &vs); + if let Some(rs) = right_synth.as_mut() { + right_plane = Some(synth_slots(rs, &vs)); + } + } + if let Some(rs) = right_synth { + elem.channels[1].synthesis = rs; + } + if let Some(right) = right_plane { + planes[1] = right; } - Some(data) } /// Doubles the rate of an LFE plane. The standard gives the LFE no SBR @@ -310,13 +386,19 @@ impl SbrChain { /// planes, with the high bands left empty, which is what ffmpeg's output /// does for the LFE channel. pub fn bypass_plane(&mut self, tag: u8, plane: &mut Vec) { - let (state, delay) = self - .bypass - .entry(tag) - .or_insert_with(|| (ChannelState::new(1, 0), vec![0.0; BYPASS_DELAY])); + let downsampled = self.downsampled; + let (state, delay) = self.bypass.entry(tag).or_insert_with(|| { + let mut state = ChannelState::new(1, 0); + let mut delay = BYPASS_DELAY; + if downsampled { + state.synthesis = Synthesis::downsampled(); + delay /= 2; + } + (state, vec![0.0; delay]) + }); let num_slots = plane.len() / ANALYSIS_BANDS; let mut out = std::mem::take(delay); - out.reserve(num_slots * SYNTHESIS_BANDS); + out.reserve(num_slots * state.synthesis.bands()); for slot in 0..num_slots { let mut chunk = [0f32; ANALYSIS_BANDS]; chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); @@ -332,7 +414,7 @@ impl SbrChain { } // The reconstructed planes lag their raw analysis by `HF_ADJ` slots; // hold the bypass output back by the same amount so they line up. - let produced = num_slots * SYNTHESIS_BANDS; + let produced = num_slots * state.synthesis.bands(); *plane = out[..produced].to_vec(); *delay = out[produced..].to_vec(); } @@ -350,7 +432,7 @@ impl SbrChain { start: usize, n: usize, ) -> crate::Result<()> { - let n = expand_for_ps(out, start, n, is_cpe, data.ps.is_some()); + let n = expand_for_ps(out, start, n, is_cpe, data.ps.is_some() || self.ps_config); self.apply(tag, is_cpe, data, &mut out[start..start + n]) } @@ -367,7 +449,8 @@ impl SbrChain { .elements .get(&(tag, is_cpe)) .and_then(|e| e.last_data.as_ref()) - .is_some_and(|d| d.ps.is_some()); + .is_some_and(|d| d.ps.is_some()) + || self.ps_config; let n = expand_for_ps(out, start, n, is_cpe, has_ps); self.apply_last(tag, is_cpe, &mut out[start..start + n]) } @@ -405,6 +488,7 @@ impl SbrChain { .get(&(tag, is_cpe)) .and_then(|e| e.last_data.clone()) else { + self.apply_low_only(tag, is_cpe, planes); return Ok(()); }; self.apply_data(tag, is_cpe, &data, planes, "hold") @@ -421,6 +505,7 @@ impl SbrChain { if source == "hold" { HOLD_CALLS.fetch_add(1, Ordering::Relaxed); } + let band_limit = if self.downsampled { ANALYSIS_BANDS } else { SYNTHESIS_BANDS }; let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { return Ok(()); }; @@ -443,7 +528,8 @@ impl SbrChain { // through channel 1's (the right output), so both stay in step. let ps_mode = !is_cpe && planes.len() >= 2 && data.ps.is_some(); let mut ps_planes: Option<(Vec, Vec)> = None; - let mut r_synth = if ps_mode && elem.channels.len() >= 2 { + let dup_mode = !is_cpe && planes.len() >= 2 && data.ps.is_none(); + let mut r_synth = if (ps_mode || dup_mode) && elem.channels.len() >= 2 { Some(std::mem::take(&mut elem.channels[1].synthesis)) } else { None @@ -637,7 +723,7 @@ impl SbrChain { } let kx = (tables.kx as usize).min(ANALYSIS_BANDS); - let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS); + let k2 = (tables.k2 as usize).min(band_limit); let mut vs: Vec<[Complex; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots); for slot in 0..num_slots { let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; @@ -663,6 +749,15 @@ impl SbrChain { ps_planes = Some((left_pcm, right_pcm)); Vec::new() } + _ if dup_mode => { + let left_pcm = synth_slots(&mut state.synthesis, &vs); + let right_pcm = match r_synth.as_mut() { + Some(rs) => synth_slots(rs, &vs), + None => left_pcm.clone(), + }; + ps_planes = Some((left_pcm, right_pcm)); + Vec::new() + } _ => synth_slots(&mut state.synthesis, &vs), }; if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() { @@ -766,7 +861,8 @@ fn render_ps( /// Runs `slots` through a synthesis bank, at the SBR output scale. fn synth_slots(synth: &mut Synthesis, slots: &[[Complex; SYNTHESIS_BANDS]]) -> Vec { - let mut out = Vec::with_capacity(slots.len() * SYNTHESIS_BANDS); + let bands = synth.bands(); + let mut out = Vec::with_capacity(slots.len() * bands); for v in slots { let mut pcm = synth.process_slot(v); for s in &mut pcm { @@ -775,7 +871,7 @@ fn synth_slots(synth: &mut Synthesis, slots: &[[Complex; SYNTHESIS_BANDS]]) // core's amplitude; the 2x is the upsampler's gain. *s *= 2.0 * crate::decode::OUTPUT_SCALE; } - out.extend_from_slice(&pcm); + out.extend_from_slice(&pcm[..bands]); } out } diff --git a/crates/ec-aac/src/sbr_hf.rs b/crates/ec-aac/src/sbr_hf.rs index 7d605cf4..7420658f 100644 --- a/crates/ec-aac/src/sbr_hf.rs +++ b/crates/ec-aac/src/sbr_hf.rs @@ -277,6 +277,10 @@ impl ChirpState { } } + pub fn bands(&self) -> usize { + self.bw.len() + } + /// Advances the state one frame given this frame's `bs_invf_mode` per /// noise band, returning the smoothed bw to use for HF generation. /// diff --git a/crates/ec-aac/src/sbr_payload.rs b/crates/ec-aac/src/sbr_payload.rs index 7aadfd5f..fa58f27f 100644 --- a/crates/ec-aac/src/sbr_payload.rs +++ b/crates/ec-aac/src/sbr_payload.rs @@ -350,7 +350,7 @@ impl SbrParser { t[num_env] = trail; let mut acc = trail; for i in (1..num_env).rev() { - acc -= rel[i - 1]; + acc -= rel[num_env - 1 - i]; t[i] = acc; } } else { @@ -394,7 +394,7 @@ impl SbrParser { t[num_env] = trail; let mut acc = trail; for i in (num_rel0 + 1..num_env).rev() { - acc -= rel1[i - num_rel0 - 1]; + acc -= rel1[num_env - 1 - i]; t[i] = acc; } if t.windows(2).any(|w| w[0] >= w[1]) { diff --git a/crates/ec-aac/src/sbr_qmf.rs b/crates/ec-aac/src/sbr_qmf.rs index f3c39e4a..a1c06315 100644 --- a/crates/ec-aac/src/sbr_qmf.rs +++ b/crates/ec-aac/src/sbr_qmf.rs @@ -218,70 +218,68 @@ impl Default for HfAnalysis { } } -/// The ISO/IEC 14496-3 4.6.18.8.2 64-band complex synthesis QMF bank: -/// complex subband slots in, doubled-rate PCM out, [`SYNTHESIS_BANDS`] -/// output samples per slot. Verified against the literal spec equations at -/// `corr=0.999999` self-consistency (see the module doc). pub struct Synthesis { - /// History buffer `v`, `10 * PROTO_LEN / SYNTHESIS_BANDS * SYNTHESIS_BANDS` - /// = `1280` samples (`4.6.18.8.2`'s own length, not `PROTO_LEN`). - v: [f64; 1280], + bands: usize, + v: Vec, cos_tab: Vec, sin_tab: Vec, } impl Synthesis { - /// A fresh bank with a silent history buffer. pub fn new() -> Synthesis { - let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; - let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; - for k in 0..SYNTHESIS_BANDS { - for n in 0..128 { - // phi = pi/128*(k+0.5)*(2n-255) - let phi = std::f64::consts::PI / 128.0 + Synthesis::with_bands(SYNTHESIS_BANDS, 0.0) + } + + pub fn downsampled() -> Synthesis { + Synthesis::with_bands(SYNTHESIS_BANDS / 2, -0.5) + } + + fn with_bands(bands: usize, shift: f64) -> Synthesis { + let len = 2 * bands; + let mut cos_tab = vec![0.0f64; bands * len]; + let mut sin_tab = vec![0.0f64; bands * len]; + for k in 0..bands { + for n in 0..len { + let phi = std::f64::consts::PI / len as f64 * (k as f64 + 0.5) - * (2.0 * n as f64 - 255.0); - cos_tab[k * 128 + n] = phi.cos(); - sin_tab[k * 128 + n] = phi.sin(); + * (2.0 * n as f64 - (2 * len - 1) as f64 + shift); + cos_tab[k * len + n] = phi.cos(); + sin_tab[k * len + n] = phi.sin(); } } Synthesis { - v: [0.0; 1280], + bands, + v: vec![0.0; 10 * len], cos_tab, sin_tab, } } - /// Feeds one slot of [`SYNTHESIS_BANDS`] complex subband samples and - /// returns [`SYNTHESIS_BANDS`] output PCM samples. + pub fn bands(&self) -> usize { + self.bands + } + pub fn process_slot(&mut self, x: &[Complex; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] { - // v[n] = v[n-128] for n=1279..128 (shift), then v[0..128] filled with - // v[n] = Re{ (1/64) sum_k X[k]*exp(j*phi) }, n=0..127. - self.v.copy_within(0..1152, 128); - for n in 0..128 { + let bands = self.bands; + let len = 2 * bands; + self.v.copy_within(0..9 * len, len); + for n in 0..len { let mut re = 0.0f64; - for (k, xk) in x.iter().enumerate() { - let row = k * 128; - // Re{X[k]*exp(j*phi)} = Xre*cos(phi) - Xim*sin(phi) - re += xk.re * self.cos_tab[row + n] - xk.im * self.sin_tab[row + n]; + for (k, xk) in x.iter().take(bands).enumerate() { + let at = k * len + n; + re += xk.re * self.cos_tab[at] - xk.im * self.sin_tab[at]; } self.v[n] = re / SYNTHESIS_BANDS as f64; } - // g[128i+n] = v[256i+n], g[128i+64+n] = v[256i+192+n], i=0..4, n=0..63 - let mut g = [0.0f64; PROTO_LEN]; - for i in 0..5 { - for n in 0..64 { - g[128 * i + n] = self.v[256 * i + n]; - g[128 * i + 64 + n] = self.v[256 * i + 192 + n]; - } - } - // w[n] = g[n]*c[n], n=0..639; y[n] = sum_{k=0}^{9} w[64k+n], n=0..63 + let step = SYNTHESIS_BANDS / bands; let mut out = [0.0f32; SYNTHESIS_BANDS]; - for (n, o) in out.iter_mut().enumerate() { + for (n, o) in out.iter_mut().take(bands).enumerate() { let mut acc = 0.0f64; - for k in 0..10 { - let idx = 64 * k + n; - acc += g[idx] * QMF_WINDOW[idx]; + for i in 0..5 { + let near = self.v[2 * len * i + n]; + let far = self.v[2 * len * i + 3 * bands + n]; + acc += near * QMF_WINDOW[step * (len * i + n)]; + acc += far * QMF_WINDOW[step * (len * i + bands + n)]; } *o = acc as f32; } diff --git a/crates/ec-aac/tests/sbr_real_library/chunk_a.rs b/crates/ec-aac/tests/sbr_real_library/chunk_a.rs index 48bad545..578dcaed 100644 --- a/crates/ec-aac/tests/sbr_real_library/chunk_a.rs +++ b/crates/ec-aac/tests/sbr_real_library/chunk_a.rs @@ -164,9 +164,18 @@ pub(super) fn full_chain_low_band_matches_own_core() { // sample-for-sample with the full-chain output's rate -- // crude, but a low-pass well below the core Nyquist erases the // stairstep artifacts this introduces. - let up: Vec = core[ch].iter().flat_map(|&s| [s, s]).collect(); + let up = if full_rate == core_rate { + core[ch].clone() + } else { + upsample_2x(&core[ch]) + }; let cutoff = f64::from(core_rate) * 0.4; - let ol = lowpass(&full[ch], full_rate, cutoff); + let keep = if full.len() > core.len() { + mono_prefix(&full) + } else { + full[ch].len() + }; + let ol = lowpass(&full[ch][..keep], full_rate, cutoff); let ul = lowpass(&up, full_rate, cutoff); // Escalating search: narrow (`WIDE_LAG_MAX`=20_000, the file's // original bound) first, widen to `SEARCH_LAG_MAX` only if that diff --git a/crates/ec-aac/tests/sbr_real_library/helpers.rs b/crates/ec-aac/tests/sbr_real_library/helpers.rs index e8b0f15d..4c50a910 100644 --- a/crates/ec-aac/tests/sbr_real_library/helpers.rs +++ b/crates/ec-aac/tests/sbr_real_library/helpers.rs @@ -231,11 +231,7 @@ pub(super) fn correlation(a: &[f32], b: &[f32]) -> f64 { /// case the coarse slice picked a noisy lag) gives the reported number. pub(super) fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) { const COARSE: usize = 4_096; - let start = ours - .len() - .min(theirs.len()) - .saturating_sub(WINDOW) - .min(ours.len() / 4); + let start = window_start(ours, theirs); let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { let (oa, ob) = if lag >= 0 { (start, start + lag as usize) @@ -365,11 +361,7 @@ pub(super) fn best_lag_correlation_wide(ours: &[f32], theirs: &[f32], lag_max: i /// refinement it replaces, so the resolution is simply not worth trading. pub(super) fn exhaustive_lag_correlation(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64, f64, bool) { const COARSE: usize = 4_096; - let start = ours - .len() - .min(theirs.len()) - .saturating_sub(WINDOW) - .min(ours.len() / 4); + let start = window_start(ours, theirs); let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { let (oa, ob) = if lag >= 0 { (start, start + lag as usize) @@ -421,11 +413,7 @@ pub(super) fn robust_lag_topk( k: usize, ) -> (i64, f64, bool) { const COARSE: usize = 4_096; - let start = ours - .len() - .min(theirs.len()) - .saturating_sub(WINDOW) - .min(ours.len() / 4); + let start = window_start(ours, theirs); let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { let (oa, ob) = if lag >= 0 { (start, start + lag as usize) @@ -477,6 +465,40 @@ pub(super) fn robust_lag_topk( best } +pub(super) fn window_start(ours: &[f32], theirs: &[f32]) -> usize { + const CHUNK: usize = 1_024; + const CHUNKS: usize = 4; + let end = ours.len().min(theirs.len()); + let base = end.saturating_sub(WINDOW).min(ours.len() / 4); + let power = |s: &[f32]| { + s.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::() / s.len().max(1) as f64 + }; + let floor = 1e-4 * power(&ours[base..end]).min(power(&theirs[base..end])); + let loud = |p: usize| { + p + CHUNK * CHUNKS <= end + && (p..p + CHUNK * CHUNKS) + .step_by(CHUNK) + .all(|a| power(&ours[a..a + CHUNK]) > floor && power(&theirs[a..a + CHUNK]) > floor) + }; + (base..end).step_by(CHUNK).find(|&p| loud(p)).unwrap_or(base) +} + +pub(super) fn upsample_2x(core: &[f32]) -> Vec { + let mut out = Vec::with_capacity(core.len() * 2); + for (i, &s) in core.iter().enumerate() { + out.push(s); + out.push((s + core.get(i + 1).copied().unwrap_or(s)) * 0.5); + } + out +} + +pub(super) fn mono_prefix(planes: &[Vec]) -> usize { + let first = &planes[0]; + planes.get(1).map_or(first.len(), |second| { + first.iter().zip(second).position(|(a, b)| a != b).unwrap_or(first.len()) + }) +} + /// Signed correlation of `ours` against `theirs` at one fixed `lag`, full /// `WINDOW`-sized, anchored at the SAME `start` offset `best_lag_correlation` /// uses internally -- used to test a hypothesized sign inversion by reusing @@ -486,11 +508,7 @@ pub(super) fn robust_lag_topk( /// match `best_lag_correlation`'s `start`, not sample 0 -- the two windows /// otherwise cover different seconds of audio and are not comparable. pub(super) fn correlation_at_lag(ours: &[f32], theirs: &[f32], lag: i64) -> f64 { - let start = ours - .len() - .min(theirs.len()) - .saturating_sub(WINDOW) - .min(ours.len() / 4); + let start = window_start(ours, theirs); let (oa, ob) = if lag >= 0 { (start, start + lag as usize) } else { diff --git a/crates/ec-av1/src/encoder/mod.rs b/crates/ec-av1/src/encoder/mod.rs index 8823dee8..eb3b9068 100644 --- a/crates/ec-av1/src/encoder/mod.rs +++ b/crates/ec-av1/src/encoder/mod.rs @@ -125,6 +125,7 @@ impl RateTarget { /// (`None` for the two open-loop variants). `mini_gop` is `Some` in /// pyramid mode, which is what makes the loop keep a quantizer per level. fn into_loop(self, config: &mut EncoderConfig, pyramid: Option) -> Option { + let repay = matches!(self, RateTarget::Bitrate { .. }); let target_bytes = match self { RateTarget::QIndex(q) => { config.base_q_idx = q; @@ -140,12 +141,14 @@ impl RateTarget { frames_per_second, } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0), }; - Some(RateLoop::new( + let mut rate_loop = RateLoop::new( target_bytes, f64::from(config.base_q_idx), pyramid, config.gop, - )) + ); + rate_loop.repay = repay; + Some(rate_loop) } } @@ -236,14 +239,11 @@ struct RateLoop { target: [f64; 3], /// Quantizer per level, same index. q: [f64; 3], - /// Whether the three slots are actually distinct (pyramid mode) or all - /// one shared controller (the flat path, unchanged from before levels - /// existed). - per_level: bool, /// Whether each slot has already steered off a real coded frame. The /// FIRST update of a slot is the seeding one and takes the model's whole /// step ([`RateLoop::update`]); every later one is clamped. seeded: [bool; 3], + prev_ratio: [f64; 3], /// The leaf's own q offset: the zero of the level weight /// ([`WEIGHT_LEVEL_GAIN`]), so slot 1's target can be read in /// LEAF-EQUIVALENT bytes and scaled per frame by that frame's offset. @@ -272,6 +272,7 @@ struct RateLoop { /// a level held at its bound hands its unspent bytes to the others, but /// no level's target may exceed this many times its own opening share. scale0: f64, + repay: bool, /// `EC_AV1_RL_CENSUS=1`: one line per coded frame on stderr. census: bool, coded: usize, @@ -285,7 +286,7 @@ impl RateLoop { const STEP_CLAMP: f64 = 12.0; /// The calibration sweep's own slope (see the struct doc), inverted to /// convert a bytes ratio into a `q_idx` step. - const GAIN: f64 = 1.0 / 0.0154; + const GAIN: f64 = 1.0 / WEIGHT_LEVEL_GAIN; /// The windup bound on [`RateLoop::replan`]: however much a bound level /// fails to spend, no other level's target may grow past this multiple of /// its opening share. Without it a run whose hidden levels are all at the @@ -297,26 +298,9 @@ impl RateLoop { /// target), which is how the first cut of this fix froze every level of a /// run at whatever quantizer it had reached. const REPLAN_FLOOR: f64 = 0.25; + const TINY_FRAME_DIVISOR: f64 = 4.0; fn new(target_bytes: f64, start_q: f64, pyramid: Option, gop: usize) -> Self { - let Some(p) = pyramid else { - return Self { - target: [target_bytes; 3], - q: [start_q; 3], - per_level: false, - seeded: [false; 3], - leaf_q_offset: 0, - key_weight: 1.0, - run_weight: 0.0, - run_bytes: 0.0, - left_weight: 0.0, - left_bytes: 0.0, - plans: [None; 5], - scale0: target_bytes, - census: census_on(), - coded: 0, - }; - }; // THE LEVEL MODEL. Every coded frame of the run is priced by its own // q offset through `WEIGHT_LEVEL_GAIN`, in units of one leaf, and the // run's `gop` frame targets are shared out in those units. The old @@ -327,11 +311,17 @@ impl RateLoop { // [`Pyramid::quarter_q_offset`]), and a hidden frame is worth far // more than two leaves -- the census reads the top ARF at 24x a leaf // and the mid at 5x. Both are fixed here, in one diff. + let (key_q_offset, leaf_q_offset, hidden, leaves) = match pyramid { + Some(p) => { + let (hidden, leaves) = gop_shape(p, gop); + (p.key_q_offset, p.leaf_q_offset, hidden, leaves) + } + None => (0, 0, Vec::new(), gop.saturating_sub(1)), + }; let w = |offset: i16| { - ((f64::from(p.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp() + ((f64::from(leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp() }; - let (hidden, leaves) = gop_shape(p, gop); - let key = KEY_WEIGHT * w(p.key_q_offset); + let key = KEY_WEIGHT * w(key_q_offset); let total: f64 = key + leaves as f64 + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::(); // One leaf's byte target: the run is worth `gop` frame targets and @@ -347,19 +337,18 @@ impl RateLoop { // One plan per level, in coding order: key, hidden levels (at most // three distinct offsets -- top, mid, quarters), leaves. let mut plans = [None; 5]; - plans[0] = Some(LevelPlan::new(0, p.key_q_offset, key)); + plans[0] = Some(LevelPlan::new(0, key_q_offset, key)); let mut i = 1; for &(o, n) in hidden.iter().take(3) { plans[i] = Some(LevelPlan::new(1, o, n as f64 * w(o))); i += 1; } - plans[i] = Some(LevelPlan::new(2, p.leaf_q_offset, leaves as f64)); + plans[i] = Some(LevelPlan::new(2, leaf_q_offset, leaves as f64)); Self { target: [scale * key, scale, scale], q: [start_q; 3], - per_level: true, seeded: [false; 3], - leaf_q_offset: p.leaf_q_offset, + leaf_q_offset, key_weight: key, run_weight: total, run_bytes: target_bytes * gop.max(1) as f64, @@ -367,6 +356,8 @@ impl RateLoop { left_bytes: target_bytes * gop.max(1) as f64, plans, scale0: scale, + repay: true, + prev_ratio: [1.0; 3], census: census_on(), coded: 0, } @@ -386,12 +377,7 @@ impl RateLoop { .position(|p| p.is_some_and(|p| p.slot == slot && (slot != 1 || p.offset == offset))) } - /// Which controller a level uses: one shared slot on the flat path, three - /// separate ones under a pyramid. fn slot(&self, level: Level) -> usize { - if !self.per_level { - return 0; - } match level { Level::Key => 0, Level::Arf => 1, @@ -423,7 +409,7 @@ impl RateLoop { 1 => self.weight(offset), _ => 1.0, }; - let target = match self.per_level && slot == 1 { + let target = match slot == 1 { true => self.target[slot] * frame_weight, false => self.target[slot], }; @@ -439,12 +425,23 @@ impl RateLoop { // step and seeds `q` where the log-linear slope says it belongs; from // the second frame on the clamp is back, and nothing is accumulated // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds. - let raw = ratio.ln() * Self::GAIN; - let step = if std::mem::replace(&mut self.seeded[slot], true) { + let seeded = std::mem::replace(&mut self.seeded[slot], true); + let smoothed = if seeded && !self.repay { + (ratio * self.prev_ratio[slot]).sqrt() + } else { + ratio + }; + self.prev_ratio[slot] = ratio; + let raw = smoothed.ln() * Self::GAIN; + let step = if seeded { raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP) } else { raw }; + let step = match ratio < 1.0 / Self::TINY_FRAME_DIVISOR && step < 0.0 { + true => 0.0, + false => step, + }; self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); let bound = !(1..=255).contains(&raw_q); if let Some(plan) = self @@ -467,7 +464,9 @@ impl RateLoop { ); self.coded += 1; } - self.replan(level, slot, offset, frame_weight, actual_bytes as f64); + if self.repay { + self.replan(level, slot, offset, frame_weight, actual_bytes as f64); + } } /// Re-plans the REST OF THE RUN from what it has actually spent: the @@ -495,9 +494,6 @@ impl RateLoop { frame_weight: f64, actual_bytes: f64, ) { - if !self.per_level { - return; - } if level == Level::Key { self.left_weight = self.run_weight; self.left_bytes = self.run_bytes; diff --git a/crates/ec-av1/src/encoder/tests.rs b/crates/ec-av1/src/encoder/tests.rs index c8ce5eab..a21cf532 100644 --- a/crates/ec-av1/src/encoder/tests.rs +++ b/crates/ec-av1/src/encoder/tests.rs @@ -672,6 +672,15 @@ width: usize, height: usize, frames: usize, + ) -> Option> { + h264_clip_frames_at(20, width, height, frames) + } + + fn h264_clip_frames_at( + start: u32, + width: usize, + height: usize, + frames: usize, ) -> Option> { // lane-av1speed3: the wall tables below are read on REAL film as // well as on the colour-bar fixture (`bars` vs `film` in the BD @@ -694,7 +703,7 @@ // therefore `return` on `None` WITHOUT printing a second one -- the // second "no fixture" line per gate was the noise that hid this defect. let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-ss", "20", "-i", clip.to_str().unwrap()]) + .args(["-v", "error", "-ss", &start.to_string(), "-i", clip.to_str().unwrap()]) .args(["-frames:v", &frames.to_string()]) .args(["-vf", &format!("scale={width}:{height}")]) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]).output() @@ -915,11 +924,13 @@ ); } + const CLEAN_START: u32 = 23; + #[test] fn bitrate_target_lands_within_5_percent_over_48_frames() { let _knobs = crate::speed::knob_read(); let (width, height, frames) = (640usize, 384usize, 48usize); - let Some(pictures) = h264_clip_frames(width, + let Some(pictures) = h264_clip_frames_at(CLEAN_START, width, height, frames, ) else { diff --git a/crates/ec-av1/src/stack_budget.rs b/crates/ec-av1/src/stack_budget.rs index b98ebc6a..d57e2d3a 100644 --- a/crates/ec-av1/src/stack_budget.rs +++ b/crates/ec-av1/src/stack_budget.rs @@ -192,7 +192,7 @@ pub(crate) const BY_VALUE_TYPES: &[(&str, Option, bool, &str)] = &[ // -- encoder.rs ------------------------------------------------------- ( "Av1Encoder", - Some(2704), + Some(2728), true, "Av1Encoder::new / with_speed / with_pyramid / with_rate_target / \ with_pyramid_and_rate_target, all `Result`, nesting three deep",