forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'sbr-multichannel'

Browse files at this commit

fb8eddb66477ff31ab139cacbcf579395ecd821aAhmet Kaan GümüşParent: ca94f242a9df8d
crates/ec-aac/src/decode.rsmodified+17 -5
@@ -707,7 +707,17 @@ impl BlockDecoder {
707707 let start = out.len();
708708 let mut ch = [self.channel_stream(r, None)?];
709709 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+ };
711721 }
712722 1 => {
713723 let tag = r.read_bits(4)? as u8;
@@ -780,7 +790,7 @@ impl BlockDecoder {
780790 r.skip_bits(10)?; // bs_sbr_crc_bits
781791 }
782792 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]);
784794 applied = true;
785795 }
786796 }
@@ -791,7 +801,7 @@ impl BlockDecoder {
791801 // SBR, or a parse failure): §4.6.18 still
792802 // requires doubled-rate reconstruction, using
793803 // 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]);
795805 }
796806 }
797807 // Resync to the FIL's declared byte boundary regardless
@@ -810,8 +820,10 @@ impl BlockDecoder {
810820 // a non-SBR one) -- same "unavailable frame" case as the
811821 // no-fresh-payload branch in id 6 above, so fall back to
812822 // the last known SBR data the same way.
813- if let (Some(sbr), Some((tag, start, n, _))) = (self.sbr.as_mut(), pending) {
814- sbr.apply_last(tag, &mut out[start..start + n]);
823+ if let (Some(sbr), Some((tag, start, n, is_cpe))) =
824+ (self.sbr.as_mut(), pending)
825+ {
826+ sbr.apply_last(tag, is_cpe, &mut out[start..start + n]);
815827 }
816828 break;
817829 }
crates/ec-aac/src/sbr_chain.rsmodified+118 -13
@@ -202,7 +202,13 @@ struct Element {
202202 /// encoder in practice emits it).
203203 pub struct SbrChain {
204204 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>,
206212 }
207213
208214 impl SbrChain {
@@ -216,7 +222,7 @@ impl SbrChain {
216222 /// Parses one FIL element's `sbr_extension_data` (the reader
217223 /// positioned right past `bs_extension_type`) for element `tag`.
218224 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 {
220226 parser: SbrParser::new(self.rate),
221227 channels: Vec::new(),
222228 last_data: None,
@@ -234,11 +240,11 @@ impl SbrChain {
234240 /// PCM, one plane per channel), replacing each in place with its
235241 /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a
236242 /// silent no-op: `planes` is left at its core content.
237- pub fn apply(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec<f32>]) {
238- if let Some(elem) = self.elements.get_mut(&tag) {
243+ pub fn apply(&mut self, tag: u8, is_cpe: bool, data: &SbrData, planes: &mut [Vec<f32>]) {
244+ if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) {
239245 elem.last_data = Some(data.clone());
240246 }
241- self.apply_data(tag, data, planes, "fresh");
247+ self.apply_data(tag, is_cpe, data, planes, "fresh");
242248 }
243249
244250 /// Re-runs the chain for `tag` using the last successfully parsed
@@ -246,21 +252,26 @@ impl SbrChain {
246252 /// fresh payload this frame. A no-op (planes left at core content, same
247253 /// as [`apply`]'s existing malformed/missing-state fallback) if no prior
248254 /// frame ever parsed successfully for this element.
249- pub fn apply_last(&mut self, tag: u8, planes: &mut [Vec<f32>]) {
250- let Some(data) = self.elements.get(&tag).and_then(|e| e.last_data.clone()) else {
255+ pub fn apply_last(&mut self, tag: u8, is_cpe: bool, planes: &mut [Vec<f32>]) {
256+ let Some(data) = self
257+ .elements
258+ .get(&(tag, is_cpe))
259+ .and_then(|e| e.last_data.clone())
260+ else {
251261 return;
252262 };
253- self.apply_data(tag, &data, planes, "hold");
263+ self.apply_data(tag, is_cpe, &data, planes, "hold");
254264 }
255265
256266 fn apply_data(
257267 &mut self,
258268 tag: u8,
269+ is_cpe: bool,
259270 data: &SbrData,
260271 planes: &mut [Vec<f32>],
261272 source: &'static str,
262273 ) {
263- let Some(elem) = self.elements.get_mut(&tag) else {
274+ let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else {
264275 return;
265276 };
266277 let Some(tables) = elem.parser.tables().cloned() else {
@@ -490,7 +501,7 @@ mod tests {
490501 let mut chain = SbrChain::new(44100);
491502 let tag = 0u8;
492503 chain.elements.insert(
493- tag,
504+ (tag, true),
494505 Element {
495506 parser: SbrParser::new(44100),
496507 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],
@@ -499,7 +510,7 @@ mod tests {
499510 );
500511 chain
501512 .elements
502- .get_mut(&tag)
513+ .get_mut(&(tag, true))
503514 .unwrap()
504515 .parser
505516 .set_for_test(header(), t.clone());
@@ -514,7 +525,7 @@ mod tests {
514525 // discontinuity this test exists to catch.
515526 let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() };
516527 let mut planes = vec![core_au(), core_au()];
517- chain.apply(tag, &data, &mut planes);
528+ chain.apply(tag, true, &data, &mut planes);
518529
519530 let expected_len = 32 * SYNTHESIS_BANDS;
520531 for (ch, plane) in planes.iter().enumerate() {
@@ -530,7 +541,7 @@ mod tests {
530541 // generator continuity across the junction, not just each AU in
531542 // isolation.
532543 let mut planes2 = vec![core_au(), core_au()];
533- chain.apply(tag, &data, &mut planes2);
544+ chain.apply(tag, true, &data, &mut planes2);
534545 for (ch, plane) in planes2.iter().enumerate() {
535546 assert_eq!(
536547 plane.len(),
@@ -567,6 +578,100 @@ mod tests {
567578 }
568579 }
569580
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+
570675 /// Round-13 stitching verdict (queue item 1): the QMF filterbank pair
571676 /// underneath the low band (`0..kx`, `apply_data` copies
572677 /// `raw[slot][0..kx]` straight from `Analysis` into `Synthesis`, no