forge
Explore
Log in

Don't you dare go Hollow

Key SbrChain per-element state by (tag, is_cpe), not tag alone

Browse files at this commit

2a9df8d740e36dab1cddbb8ceb53f5afb5cba53aAhmet Kaan GümüşParent: 2b4d691
  • fix
    • key SbrChain per-element state by (tag, is_cpe), not tag alone
Show full message
fix(aac-sbr): key SbrChain per-element state by (tag, is_cpe), not tag alone

ISO/IEC 14496-3 §4.4: element_instance_tag is a namespace per syntactic
element type, so an encoder may legally give an SCE and a CPE in the same
access unit the same tag value (routine in a 5.1 SCE+CPE+CPE+LFE stream).
SbrChain::elements was a HashMap<u8, Element> keyed by the bare tag, so a
same-tagged SCE and CPE silently aliased one Analysis/Synthesis/HF/noise
state -- the CPE's parse/apply would read and mutate the SCE's element
state and vice versa. Rekeyed to (tag, is_cpe); decode.rs's three
sbr.apply/apply_last call sites now pass is_cpe through from `pending`.

Also stopped LFE (raw_data_block id 3) from ever becoming a pending SBR
target: §4.6.18.1 never applies SBR to the LFE channel (no FIL follows
it), so treating it like an SCE for `pending` could let a stray fallback
branch stretch the LFE plane to double rate using a held SBR payload that
belongs to a different, same-tagged element.

New regression test `an_sce_and_a_same_tagged_cpe_do_not_share_state`
proves an SCE at tag 0 is untouched by a same-tagged CPE's apply() call
in between two of the SCE's own calls; it fails without this fix.

Diagnostic finding: the assumption that motivated this investigation --
that the failing real-file test candidate (a BluRay-rip HEVC/mkv with a
real 6-channel HE-AAC track, tests/sbr_real_library.rs candidates(),
aac_stream=1) actually exercises that 6ch stream -- is WRONG. That
candidate's AudioSpecificConfig (asc=[13,10,56,e5,98]) decodes to
audioObjectType=2 (AAC LC), channelConfiguration=2 (stereo), sf_index=6
(24000 Hz core, SBR to 48000). ffprobe confirms the container's global
stream 1 is the real 6ch AAC track and global stream 3 is a separate 2ch
AAC track, but extract_aac_track's stream_index=1 (this test's
aac_stream) resolves to the 2ch track, not the 6ch one -- our_decode's
own debug output ("2 ch, 48000 Hz") already showed this before any
digging. This real-file failure is therefore NOT a multichannel/SBR-state
bug: this fix does not move sbr_real_library_matches_reference's
correlation for that file (unchanged at -0.025253/0.010226) or
full_chain_low_band_matches_own_core (unchanged at 0.217393). The other
real fixture (a stereo HE-AAC file, same-shape stream) stays at its prior
0.987006/0.986222 -- no regression.

GATE numbers (this commit):
  sbr_real_library_matches_reference: stereo fixture 0.987006/0.986222;
    the mislabelled candidate's SBR full-band bar 0.999 still fails,
    unchanged from baseline -0.025253/0.010226
  full_chain_low_band_matches_own_core: stereo fixture 0.996713/0.996842
    (pass); mislabelled candidate 0.217393 (fail, unchanged from baseline
    0.22)
  ec-aac --lib: 45 passed (44 prior + 1 new regression test)
crates/ec-aac/src/decode.rsmodified+17 -5
@@ -707,7 +707,17 @@ impl BlockDecoder {
707 let start = out.len();707 let start = out.len();
708 let mut ch = [self.channel_stream(r, None)?];708 let mut ch = [self.channel_stream(r, None)?];
709 self.finish(&mut ch, None, &mut out);709 self.finish(&mut ch, None, &mut out);
710- pending = Some((tag, start, 1, false));710+ // §4.6.18.1: SBR is never applied to the LFE channel (no
711+ // FIL/SBR payload follows it), so it must not become a
712+ // pending SBR target -- otherwise a later fallback
713+ // (`apply_last`/no-FIL branch) could mistakenly stretch
714+ // the LFE plane to double rate using a *different*
715+ // element's held SBR data, corrupting it.
716+ pending = if id == 0 {
717+ Some((tag, start, 1, false))
718+ } else {
719+ None
720+ };
711 }721 }
712 1 => {722 1 => {
713 let tag = r.read_bits(4)? as u8;723 let tag = r.read_bits(4)? as u8;
@@ -780,7 +790,7 @@ impl BlockDecoder {
780 r.skip_bits(10)?; // bs_sbr_crc_bits790 r.skip_bits(10)?; // bs_sbr_crc_bits
781 }791 }
782 if let Some(data) = sbr.parse(r, tag, is_cpe) {792 if let Some(data) = sbr.parse(r, tag, is_cpe) {
783- sbr.apply(tag, &data, &mut out[start..start + n]);793+ sbr.apply(tag, is_cpe, &data, &mut out[start..start + n]);
784 applied = true;794 applied = true;
785 }795 }
786 }796 }
@@ -791,7 +801,7 @@ impl BlockDecoder {
791 // SBR, or a parse failure): §4.6.18 still801 // SBR, or a parse failure): §4.6.18 still
792 // requires doubled-rate reconstruction, using802 // requires doubled-rate reconstruction, using
793 // the last successfully parsed frame's data.803 // the last successfully parsed frame's data.
794- sbr.apply_last(tag, &mut out[start..start + n]);804+ sbr.apply_last(tag, is_cpe, &mut out[start..start + n]);
795 }805 }
796 }806 }
797 // Resync to the FIL's declared byte boundary regardless807 // Resync to the FIL's declared byte boundary regardless
@@ -810,8 +820,10 @@ impl BlockDecoder {
810 // a non-SBR one) -- same "unavailable frame" case as the820 // a non-SBR one) -- same "unavailable frame" case as the
811 // no-fresh-payload branch in id 6 above, so fall back to821 // no-fresh-payload branch in id 6 above, so fall back to
812 // the last known SBR data the same way.822 // the last known SBR data the same way.
813- if let (Some(sbr), Some((tag, start, n, _))) = (self.sbr.as_mut(), pending) {823+ if let (Some(sbr), Some((tag, start, n, is_cpe))) =
814- sbr.apply_last(tag, &mut out[start..start + n]);824+ (self.sbr.as_mut(), pending)
825+ {
826+ sbr.apply_last(tag, is_cpe, &mut out[start..start + n]);
815 }827 }
816 break;828 break;
817 }829 }
crates/ec-aac/src/sbr_chain.rsmodified+118 -13
@@ -202,7 +202,13 @@ struct Element {
202 /// encoder in practice emits it).202 /// encoder in practice emits it).
203 pub struct SbrChain {203 pub struct SbrChain {
204 rate: u32,204 rate: u32,
205- elements: HashMap<u8, Element>,205+ // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance
206+ // tags are independent namespaces per §4.4 (an encoder may legally
207+ // reuse tag 0 for both an SCE and a CPE in the same access unit), so
208+ // a bare `u8` key aliased two distinct elements' QMF/HF/noise state
209+ // together whenever that happened -- exactly the case in a 5.1
210+ // stream (SCE + two CPEs).
211+ elements: HashMap<(u8, bool), Element>,
206 }212 }
207 213
208 impl SbrChain {214 impl SbrChain {
@@ -216,7 +222,7 @@ impl SbrChain {
216 /// Parses one FIL element's `sbr_extension_data` (the reader222 /// Parses one FIL element's `sbr_extension_data` (the reader
217 /// positioned right past `bs_extension_type`) for element `tag`.223 /// positioned right past `bs_extension_type`) for element `tag`.
218 pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> {224 pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> {
219- let elem = self.elements.entry(tag).or_insert_with(|| Element {225+ let elem = self.elements.entry((tag, is_cpe)).or_insert_with(|| Element {
220 parser: SbrParser::new(self.rate),226 parser: SbrParser::new(self.rate),
221 channels: Vec::new(),227 channels: Vec::new(),
222 last_data: None,228 last_data: None,
@@ -234,11 +240,11 @@ impl SbrChain {
234 /// PCM, one plane per channel), replacing each in place with its240 /// PCM, one plane per channel), replacing each in place with its
235 /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a241 /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a
236 /// silent no-op: `planes` is left at its core content.242 /// silent no-op: `planes` is left at its core content.
237- pub fn apply(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec<f32>]) {243+ pub fn apply(&mut self, tag: u8, is_cpe: bool, data: &SbrData, planes: &mut [Vec<f32>]) {
238- if let Some(elem) = self.elements.get_mut(&tag) {244+ if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) {
239 elem.last_data = Some(data.clone());245 elem.last_data = Some(data.clone());
240 }246 }
241- self.apply_data(tag, data, planes, "fresh");247+ self.apply_data(tag, is_cpe, data, planes, "fresh");
242 }248 }
243 249
244 /// Re-runs the chain for `tag` using the last successfully parsed250 /// Re-runs the chain for `tag` using the last successfully parsed
@@ -246,21 +252,26 @@ impl SbrChain {
246 /// fresh payload this frame. A no-op (planes left at core content, same252 /// fresh payload this frame. A no-op (planes left at core content, same
247 /// as [`apply`]'s existing malformed/missing-state fallback) if no prior253 /// as [`apply`]'s existing malformed/missing-state fallback) if no prior
248 /// frame ever parsed successfully for this element.254 /// frame ever parsed successfully for this element.
249- pub fn apply_last(&mut self, tag: u8, planes: &mut [Vec<f32>]) {255+ pub fn apply_last(&mut self, tag: u8, is_cpe: bool, planes: &mut [Vec<f32>]) {
250- let Some(data) = self.elements.get(&tag).and_then(|e| e.last_data.clone()) else {256+ let Some(data) = self
257+ .elements
258+ .get(&(tag, is_cpe))
259+ .and_then(|e| e.last_data.clone())
260+ else {
251 return;261 return;
252 };262 };
253- self.apply_data(tag, &data, planes, "hold");263+ self.apply_data(tag, is_cpe, &data, planes, "hold");
254 }264 }
255 265
256 fn apply_data(266 fn apply_data(
257 &mut self,267 &mut self,
258 tag: u8,268 tag: u8,
269+ is_cpe: bool,
259 data: &SbrData,270 data: &SbrData,
260 planes: &mut [Vec<f32>],271 planes: &mut [Vec<f32>],
261 source: &'static str,272 source: &'static str,
262 ) {273 ) {
263- let Some(elem) = self.elements.get_mut(&tag) else {274+ let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else {
264 return;275 return;
265 };276 };
266 let Some(tables) = elem.parser.tables().cloned() else {277 let Some(tables) = elem.parser.tables().cloned() else {
@@ -490,7 +501,7 @@ mod tests {
490 let mut chain = SbrChain::new(44100);501 let mut chain = SbrChain::new(44100);
491 let tag = 0u8;502 let tag = 0u8;
492 chain.elements.insert(503 chain.elements.insert(
493- tag,504+ (tag, true),
494 Element {505 Element {
495 parser: SbrParser::new(44100),506 parser: SbrParser::new(44100),
496 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],507 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],
@@ -499,7 +510,7 @@ mod tests {
499 );510 );
500 chain511 chain
501 .elements512 .elements
502- .get_mut(&tag)513+ .get_mut(&(tag, true))
503 .unwrap()514 .unwrap()
504 .parser515 .parser
505 .set_for_test(header(), t.clone());516 .set_for_test(header(), t.clone());
@@ -514,7 +525,7 @@ mod tests {
514 // discontinuity this test exists to catch.525 // discontinuity this test exists to catch.
515 let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() };526 let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() };
516 let mut planes = vec![core_au(), core_au()];527 let mut planes = vec![core_au(), core_au()];
517- chain.apply(tag, &data, &mut planes);528+ chain.apply(tag, true, &data, &mut planes);
518 529
519 let expected_len = 32 * SYNTHESIS_BANDS;530 let expected_len = 32 * SYNTHESIS_BANDS;
520 for (ch, plane) in planes.iter().enumerate() {531 for (ch, plane) in planes.iter().enumerate() {
@@ -530,7 +541,7 @@ mod tests {
530 // generator continuity across the junction, not just each AU in541 // generator continuity across the junction, not just each AU in
531 // isolation.542 // isolation.
532 let mut planes2 = vec![core_au(), core_au()];543 let mut planes2 = vec![core_au(), core_au()];
533- chain.apply(tag, &data, &mut planes2);544+ chain.apply(tag, true, &data, &mut planes2);
534 for (ch, plane) in planes2.iter().enumerate() {545 for (ch, plane) in planes2.iter().enumerate() {
535 assert_eq!(546 assert_eq!(
536 plane.len(),547 plane.len(),
@@ -567,6 +578,100 @@ mod tests {
567 }578 }
568 }579 }
569 580
581+ /// §4.4: `element_instance_tag` is a namespace per element *type* --
582+ /// an encoder may legally give an SCE and a CPE in the same access
583+ /// unit the same tag value (this is exactly what a 5.1 stream with
584+ /// SCE+CPE+CPE+LFE does). `SbrChain` used to key its per-element state
585+ /// by the bare tag, so the CPE's `parse`/`apply` would silently reuse
586+ /// (and corrupt) the SCE's parser/channel state. Keying by `(tag,
587+ /// is_cpe)` must keep them fully independent: driving distinct tones
588+ /// through an SCE and a same-tagged CPE must not bleed into each
589+ /// other's output.
590+ #[test]
591+ fn an_sce_and_a_same_tagged_cpe_do_not_share_state() {
592+ let t = tables();
593+ let n_low = t.n_low;
594+ let n_q = t.n_q;
595+ let mut chain = SbrChain::new(44100);
596+ let tag = 0u8;
597+
598+ for is_cpe in [false, true] {
599+ let n_ch = if is_cpe { 2 } else { 1 };
600+ chain.elements.insert(
601+ (tag, is_cpe),
602+ Element {
603+ parser: SbrParser::new(44100),
604+ channels: (0..n_ch)
605+ .map(|i| ChannelState::new(n_q, 10 + i as u32))
606+ .collect(),
607+ last_data: None,
608+ },
609+ );
610+ chain
611+ .elements
612+ .get_mut(&(tag, is_cpe))
613+ .unwrap()
614+ .parser
615+ .set_for_test(header(), t.clone());
616+ }
617+
618+ let sce_data = SbrData {
619+ coupling: false,
620+ channels: vec![one_channel(n_q, n_low)],
621+ };
622+ let cpe_data = SbrData {
623+ coupling: false,
624+ channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],
625+ };
626+
627+ let sce_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.05).sin() * 0.2).collect() };
628+ let cpe_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.37).sin() * 0.2).collect() };
629+
630+ let mut sce_planes = vec![sce_tone()];
631+ chain.apply(tag, false, &sce_data, &mut sce_planes);
632+ let mut cpe_planes = vec![cpe_tone(), cpe_tone()];
633+ chain.apply(tag, true, &cpe_data, &mut cpe_planes);
634+
635+ // If state aliased, the CPE call above would have run through (and
636+ // mutated) the SCE's Analysis/Synthesis/chirp/noise state instead
637+ // of its own -- re-running the SCE with the same input must give
638+ // the SAME output as the first call, proving its state was never
639+ // touched by the CPE call in between.
640+ let mut sce_planes2 = vec![sce_tone()];
641+ chain.apply(tag, false, &sce_data, &mut sce_planes2);
642+
643+ // A fresh, never-driven SCE-only chain gives the reference: one AU
644+ // through tag/is_cpe=(0,false), nothing else touching its state.
645+ let mut reference = SbrChain::new(44100);
646+ reference.elements.insert(
647+ (tag, false),
648+ Element {
649+ parser: SbrParser::new(44100),
650+ channels: vec![ChannelState::new(n_q, 10)],
651+ last_data: None,
652+ },
653+ );
654+ reference
655+ .elements
656+ .get_mut(&(tag, false))
657+ .unwrap()
658+ .parser
659+ .set_for_test(header(), t.clone());
660+ let mut sce_ref1 = vec![sce_tone()];
661+ reference.apply(tag, false, &sce_data, &mut sce_ref1);
662+ let mut sce_ref2 = vec![sce_tone()];
663+ reference.apply(tag, false, &sce_data, &mut sce_ref2);
664+
665+ assert_eq!(
666+ sce_planes[0], sce_ref1[0],
667+ "SCE tag 0's first call already diverges from an isolated reference"
668+ );
669+ assert_eq!(
670+ sce_planes2[0], sce_ref2[0],
671+ "SCE tag 0's state was mutated by the same-tagged CPE's apply() call in between"
672+ );
673+ }
674+
570 /// Round-13 stitching verdict (queue item 1): the QMF filterbank pair675 /// Round-13 stitching verdict (queue item 1): the QMF filterbank pair
571 /// underneath the low band (`0..kx`, `apply_data` copies676 /// underneath the low band (`0..kx`, `apply_data` copies
572 /// `raw[slot][0..kx]` straight from `Analysis` into `Synthesis`, no677 /// `raw[slot][0..kx]` straight from `Analysis` into `Synthesis`, no