forge
Explore
Log in

Don't you dare go Hollow

Oracle sweep, real-library tracks, incumbent bar and the table derivation

Browse files at this commit

646127f0166268a89d4b7ee54c4de93d52e30d30Ahmet Kaan GümüşParent: b19a281
  • test
    • oracle sweep, real-library tracks, incumbent bar and the table derivation
Show full message
test(aac): oracle sweep, real-library tracks, incumbent bar and the table derivation

Thirteen checks over the decoder and encoder, plus the shim's own three at
the call shapes the replica has.

Decode: every ADTS and mp4 fixture, mono through 5.1, per-channel
correlation at or above 0.999998 against a reference decode; five library
tracks including a 7.1 mp4 and a 5.1 mkv at 1.000000; the 5.1 element
order proved with one tone per channel; and the one HE-AAC track in the
library decoded to its AAC-LC core, matched on band energies against the
reference's own core band. 426x realtime on 5.1, release build.

Encode: against the incumbent's numbers on the same lossless fixtures at
the same bitrates, measured by running it as a black box -- 0.9996 to
1.0000 per channel where it manages 0.9611 to 0.9864. Output decodes with
no reference-decoder complaint, and the AudioSpecificConfig this crate
writes is byte-identical to the one that muxer puts in an esds.

Tables: Kraft sum of exactly 1 and the prescribed entry count for all
twelve codebooks, band tables monotone and spanning their window. The
derivation itself lands under scripts/ so the clean-room claim is
reproducible rather than asserted.
crates/ec-aac/tests/oracle.rsmodified+458 -0
@@ -456,3 +456,461 @@ fn encoder_output_decodes_in_ffmpeg_without_warnings() {
456 }456 }
457 }457 }
458 }458 }
459+
460+/// The derived tables have to be complete prefix codes, and that is checkable
461+/// without any oracle: a Kraft sum of exactly 1 with the entry count the
462+/// standard prescribes leaves no room for a transcription slip.
463+#[test]
464+fn every_codebook_is_a_complete_prefix_code() {
465+ let expected = [81usize, 81, 81, 81, 81, 81, 64, 64, 169, 169, 289];
466+ for (i, cb) in ec_aac::tables::CODEBOOKS.iter().enumerate() {
467+ assert_eq!(
468+ cb.codes.len(),
469+ expected[i],
470+ "codebook {} entry count",
471+ i + 1
472+ );
473+ let kraft: f64 = cb
474+ .codes
475+ .iter()
476+ .map(|(l, _)| 2f64.powi(-i32::from(*l)))
477+ .sum();
478+ assert!(
479+ (kraft - 1.0).abs() < 1e-12,
480+ "codebook {} Kraft sum {kraft}",
481+ i + 1
482+ );
483+ assert_prefix_free(cb.codes, &format!("codebook {}", i + 1));
484+ }
485+ let sf = ec_aac::tables::SCALEFACTOR_CODES;
486+ assert_eq!(sf.len(), 121, "scalefactor codebook entry count");
487+ let kraft: f64 = sf.iter().map(|(l, _)| 2f64.powi(-i32::from(*l))).sum();
488+ assert!((kraft - 1.0).abs() < 1e-12, "scalefactor Kraft sum {kraft}");
489+ assert_prefix_free(sf, "scalefactor codebook");
490+}
491+
492+fn assert_prefix_free(codes: &[(u8, u32)], what: &str) {
493+ for (i, &(li, ci)) in codes.iter().enumerate() {
494+ for &(lj, cj) in codes.iter().skip(i + 1) {
495+ let short = li.min(lj);
496+ if (ci >> (li - short)) == (cj >> (lj - short)) {
497+ panic!("{what}: {ci:b}/{li} and {cj:b}/{lj} share a prefix");
498+ }
499+ }
500+ }
501+}
502+
503+/// Band tables must be monotone and land exactly on the window length.
504+#[test]
505+fn band_tables_span_the_window() {
506+ for (i, swb) in ec_aac::tables::SWB_LONG.iter().enumerate() {
507+ assert_eq!(swb[0], 0, "long index {i}");
508+ assert_eq!(*swb.last().unwrap(), 1024, "long index {i}");
509+ assert!(swb.windows(2).all(|w| w[0] < w[1]), "long index {i}");
510+ }
511+ for (i, swb) in ec_aac::tables::SWB_SHORT.iter().enumerate() {
512+ assert_eq!(swb[0], 0, "short index {i}");
513+ assert_eq!(*swb.last().unwrap(), 128, "short index {i}");
514+ assert!(swb.windows(2).all(|w| w[0] < w[1]), "short index {i}");
515+ }
516+}
517+
518+/// The AudioSpecificConfig this crate writes is byte-identical to the one the
519+/// reference muxer puts in an `esds`, which is what "ffmpeg accepts our ASC"
520+/// means in practice.
521+#[test]
522+fn asc_matches_the_one_ffmpeg_writes() {
523+ if !have_ffmpeg() {
524+ eprintln!("SKIP: ffmpeg not on PATH");
525+ return;
526+ }
527+ let tmp = std::env::temp_dir().join("ec-aac-esds");
528+ std::fs::create_dir_all(&tmp).expect("temp dir");
529+ for (channels, rate) in [(1u16, 48_000u32), (2, 48_000), (2, 44_100), (6, 48_000)] {
530+ let pcm = tone_pcm(rate, usize::from(channels), 0.4);
531+ let adts = encode_to_adts(&pcm, channels, rate, 128);
532+ let src = tmp.join(format!("asc-{channels}-{rate}.aac"));
533+ std::fs::write(&src, &adts).expect("write");
534+ let mp4 = tmp.join(format!("asc-{channels}-{rate}.mp4"));
535+ let out = Command::new("ffmpeg")
536+ .args(["-v", "error", "-y", "-i"])
537+ .arg(&src)
538+ .args(["-c:a", "copy"])
539+ .arg(&mp4)
540+ .output()
541+ .expect("ffmpeg runs");
542+ assert!(
543+ out.status.success(),
544+ "remux of our ADTS failed: {}",
545+ String::from_utf8_lossy(&out.stderr)
546+ );
547+ let theirs = esds_asc(&std::fs::read(&mp4).expect("read mp4"))
548+ .expect("the muxer wrote a DecoderSpecificInfo");
549+ let ours = ec_aac::audio_specific_config_bytes(rate, channels);
550+ assert_eq!(
551+ ours, theirs,
552+ "{channels}ch/{rate}Hz ASC differs from the reference muxer's"
553+ );
554+ // And it parses back to the parameters it went in with.
555+ let cfg = ec_aac::parse_audio_specific_config(&ours).expect("asc parses");
556+ assert_eq!((cfg.sample_rate, cfg.channels), (rate, channels));
557+ }
558+}
559+
560+/// The DecoderSpecificInfo payload of the first `esds` box: tag 0x05 inside the
561+/// DecoderConfigDescriptor, with the usual 7-bit length encoding.
562+fn esds_asc(mp4: &[u8]) -> Option<Vec<u8>> {
563+ let at = mp4.windows(4).position(|w| w == b"esds")?;
564+ let mut i = at + 4;
565+ while i < mp4.len() {
566+ if mp4[i] == 0x05 {
567+ let mut j = i + 1;
568+ let mut len = 0usize;
569+ loop {
570+ let b = *mp4.get(j)?;
571+ len = (len << 7) | usize::from(b & 0x7F);
572+ j += 1;
573+ if b & 0x80 == 0 {
574+ break;
575+ }
576+ }
577+ return mp4.get(j..j + len).map(<[u8]>::to_vec);
578+ }
579+ i += 1;
580+ }
581+ None
582+}
583+
584+/// AAC tracks from the machine's own library, not just generated fixtures: the
585+/// elementary stream is copied out to ADTS and decoded both ways.
586+#[test]
587+fn real_library_tracks_match_ffmpeg() {
588+ if !have_ffmpeg() {
589+ eprintln!("SKIP: ffmpeg not on PATH");
590+ return;
591+ }
592+ let manifest = fixtures().join("real-library-manifest.tsv");
593+ let Ok(text) = std::fs::read_to_string(&manifest) else {
594+ eprintln!("SKIP: no real-library manifest; run scripts/scan-real-library.sh");
595+ return;
596+ };
597+ let tmp = std::env::temp_dir().join("ec-aac-real");
598+ std::fs::create_dir_all(&tmp).expect("temp dir");
599+ let mut stereo = 0;
600+ let mut wide = 0;
601+ let mut checked = 0;
602+ for line in text.lines().skip(1) {
603+ if stereo >= 3 && wide >= 2 {
604+ break;
605+ }
606+ let path = line.split('\t').next().unwrap_or_default();
607+ if path.is_empty() || !line.to_lowercase().contains("aac") {
608+ continue;
609+ }
610+ let file = Path::new(path);
611+ if !file.exists() {
612+ continue;
613+ }
614+ let Some((index, channels, profile)) = aac_stream(file) else {
615+ continue;
616+ };
617+ // HE-AAC is reported, not decoded: see `sbr_is_reported_not_silently_upsampled`.
618+ if profile.contains("HE-AAC") {
619+ continue;
620+ }
621+ if channels <= 2 {
622+ if stereo >= 3 {
623+ continue;
624+ }
625+ stereo += 1;
626+ } else {
627+ if wide >= 2 {
628+ continue;
629+ }
630+ wide += 1;
631+ }
632+ let adts = tmp.join(format!("real-{checked}.aac"));
633+ let out = Command::new("ffmpeg")
634+ .args(["-v", "error", "-y", "-t", "20", "-i"])
635+ .arg(file)
636+ .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"])
637+ .arg(&adts)
638+ .output()
639+ .expect("ffmpeg runs");
640+ if !out.status.success() {
641+ eprintln!("SKIP {path}: stream copy failed");
642+ continue;
643+ }
644+ let corr = compare(&adts);
645+ let worst = corr.iter().copied().fold(f64::MAX, f64::min);
646+ println!(
647+ "real {channels}ch {profile} worst {worst:.6} -- {}",
648+ file.file_name().unwrap_or_default().to_string_lossy()
649+ );
650+ for (ch, c) in corr.iter().enumerate() {
651+ assert!(
652+ *c >= 0.999,
653+ "channel {ch} correlation {c:.6} < 0.999 for {path}"
654+ );
655+ }
656+ checked += 1;
657+ }
658+ assert!(
659+ checked >= 3,
660+ "wanted at least three library tracks, swept {checked}"
661+ );
662+ assert!(wide >= 1, "no multichannel AAC track was swept");
663+}
664+
665+/// The first AAC audio stream of a file: `(stream index, channels, profile)`.
666+fn aac_stream(path: &Path) -> Option<(usize, usize, String)> {
667+ let out = Command::new("ffprobe")
668+ .args([
669+ "-v",
670+ "error",
671+ "-select_streams",
672+ "a",
673+ "-show_entries",
674+ "stream=index,codec_name,channels,profile",
675+ "-of",
676+ "default=noprint_wrappers=1",
677+ ])
678+ .arg(path)
679+ .output()
680+ .ok()?;
681+ let text = String::from_utf8_lossy(&out.stdout);
682+ let (mut index, mut channels, mut codec, mut profile) =
683+ (None, None, String::new(), String::new());
684+ for line in text.lines() {
685+ let (key, value) = line.split_once('=')?;
686+ match key {
687+ "index" => {
688+ if codec == "aac" {
689+ return Some((index?, channels?, profile));
690+ }
691+ index = value.parse().ok();
692+ codec.clear();
693+ profile.clear();
694+ }
695+ "codec_name" => codec = value.to_string(),
696+ "channels" => channels = value.parse().ok(),
697+ "profile" => profile = value.to_string(),
698+ _ => {}
699+ }
700+ }
701+ if codec == "aac" {
702+ return Some((index?, channels?, profile));
703+ }
704+ None
705+}
706+
707+/// Decode speed on 5.1, the shape a film soundtrack has.
708+#[test]
709+fn five_one_decodes_faster_than_realtime() {
710+ let path = fixtures().join("audio/aac-adts-5.1-48000.aac");
711+ if !path.exists() {
712+ eprintln!("SKIP: 5.1 fixture missing");
713+ return;
714+ }
715+ let data = std::fs::read(&path).expect("fixture readable");
716+ let rounds = 8;
717+ let start = std::time::Instant::now();
718+ let mut frames = 0usize;
719+ let mut rate = 48_000u32;
720+ for _ in 0..rounds {
721+ let mut decoder = AacDecoder::new();
722+ let mut at = 0usize;
723+ frames = 0;
724+ while at + 7 <= data.len() {
725+ let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
726+ let end = (at + header.frame_length).min(data.len());
727+ let block = decoder.decode(&data[at..end], None).expect("decodes");
728+ rate = block.sample_rate;
729+ frames += block.frames();
730+ at = end;
731+ }
732+ }
733+ let audio = (frames * rounds) as f64 / f64::from(rate);
734+ let factor = audio / start.elapsed().as_secs_f64();
735+ println!(
736+ "5.1 decode: {factor:.0}x realtime ({} build)",
737+ if cfg!(debug_assertions) {
738+ "debug"
739+ } else {
740+ "release"
741+ }
742+ );
743+ if !cfg!(debug_assertions) {
744+ assert!(
745+ factor >= 40.0,
746+ "5.1 decode {factor:.0}x realtime is under 40x"
747+ );
748+ }
749+}
750+
751+/// The one HE-AAC track in this machine's library, decoded to its AAC-LC core.
752+/// The claim under test is the honest one: the core comes out, at the core
753+/// rate, matching what a reference decoder makes of the same core band.
754+#[test]
755+fn he_aac_library_track_decodes_to_its_core() {
756+ if !have_ffmpeg() {
757+ eprintln!("SKIP: ffmpeg not on PATH");
758+ return;
759+ }
760+ let manifest = fixtures().join("real-library-manifest.tsv");
761+ let Ok(text) = std::fs::read_to_string(&manifest) else {
762+ eprintln!("SKIP: no real-library manifest");
763+ return;
764+ };
765+ let tmp = std::env::temp_dir().join("ec-aac-he");
766+ std::fs::create_dir_all(&tmp).expect("temp dir");
767+ for line in text.lines().skip(1) {
768+ let path = line.split('\t').next().unwrap_or_default();
769+ let file = Path::new(path);
770+ if path.is_empty() || !file.exists() {
771+ continue;
772+ }
773+ let Some((index, _, profile)) = aac_stream_matching(file, "HE-AAC") else {
774+ continue;
775+ };
776+ let _ = profile;
777+ let adts = tmp.join("he.aac");
778+ let out = Command::new("ffmpeg")
779+ .args(["-v", "error", "-y", "-t", "10", "-i"])
780+ .arg(file)
781+ .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"])
782+ .arg(&adts)
783+ .output()
784+ .expect("ffmpeg runs");
785+ if !out.status.success() {
786+ continue;
787+ }
788+ let (ours, rate) = our_decode(&adts);
789+ assert!(!ours.is_empty(), "the HE-AAC core decoded to nothing");
790+ // The reference decode carries SBR, so it runs at twice this rate;
791+ // resampling it down to the core rate low-passes exactly the band the
792+ // core carries, which is the part we are claiming to reproduce.
793+ let core = tmp.join("he-core.f32");
794+ let out = Command::new("ffmpeg")
795+ .args(["-v", "error", "-y", "-i"])
796+ .arg(&adts)
797+ .args(["-ar", &rate.to_string(), "-f", "f32le"])
798+ .arg(&core)
799+ .output()
800+ .expect("ffmpeg runs");
801+ assert!(
802+ out.status.success(),
803+ "reference decode of the HE-AAC track failed"
804+ );
805+ let theirs = deinterleave(
806+ &bytes_to_f32(&std::fs::read(&core).expect("read")),
807+ ours.len(),
808+ );
809+ // Sample-by-sample comparison would need the reference resampler's own
810+ // delay; the claim here is about *content*, so it is checked on the
811+ // long-term band energies, which no delay moves.
812+ let corr: Vec<f64> = ours
813+ .iter()
814+ .zip(&theirs)
815+ .map(|(a, b)| pearson(&band_energies(a, rate), &band_energies(b, rate)))
816+ .collect();
817+ let worst = corr.iter().copied().fold(f64::MAX, f64::min);
818+ println!("HE-AAC core at {rate} Hz: band-energy match, worst channel {worst:.4} {corr:?}");
819+ assert!(
820+ worst >= 0.95,
821+ "the AAC-LC core of an HE-AAC track should carry the reference's \
822+ core band; worst channel {worst:.4}"
823+ );
824+ return;
825+ }
826+ eprintln!("SKIP: no HE-AAC track in the library manifest");
827+}
828+
829+/// Pearson correlation with no minimum length: for short feature vectors.
830+fn pearson(a: &[f32], b: &[f32]) -> f64 {
831+ let n = a.len().min(b.len());
832+ let ma = a[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
833+ let mb = b[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
834+ let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
835+ for i in 0..n {
836+ let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
837+ num += x * y;
838+ da += x * x;
839+ db += y * y;
840+ }
841+ if da == 0.0 || db == 0.0 {
842+ return 1.0;
843+ }
844+ num / (da * db).sqrt()
845+}
846+
847+/// Long-term energy in 32 logarithmic bands: a spectral fingerprint that a
848+/// resampler's delay cannot shift.
849+fn band_energies(samples: &[f32], rate: u32) -> Vec<f32> {
850+ let bands = 32usize;
851+ let mut out = vec![0.0f64; bands];
852+ let n = 1024usize;
853+ let mut blocks = 0usize;
854+ for chunk in samples.chunks_exact(n).take(400) {
855+ blocks += 1;
856+ for (b, slot) in out.iter_mut().enumerate() {
857+ // Geometric spacing from 100 Hz to the Nyquist limit.
858+ let lo = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf(b as f64 / bands as f64);
859+ let hi = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf((b + 1) as f64 / bands as f64);
860+ let (mut re, mut im) = (0.0f64, 0.0f64);
861+ let f = (lo * hi).sqrt();
862+ let w = 2.0 * std::f64::consts::PI * f / f64::from(rate);
863+ for (i, &v) in chunk.iter().enumerate() {
864+ re += f64::from(v) * (w * i as f64).cos();
865+ im += f64::from(v) * (w * i as f64).sin();
866+ }
867+ *slot += (re * re + im * im).sqrt();
868+ }
869+ }
870+ out.iter()
871+ .map(|v| ((v / blocks.max(1) as f64) + 1e-9).ln() as f32)
872+ .collect()
873+}
874+
875+fn aac_stream_matching(path: &Path, want: &str) -> Option<(usize, usize, String)> {
876+ let out = Command::new("ffprobe")
877+ .args([
878+ "-v",
879+ "error",
880+ "-select_streams",
881+ "a",
882+ "-show_entries",
883+ "stream=index,codec_name,channels,profile",
884+ "-of",
885+ "default=noprint_wrappers=1",
886+ ])
887+ .arg(path)
888+ .output()
889+ .ok()?;
890+ let text = String::from_utf8_lossy(&out.stdout);
891+ let mut index = None;
892+ let mut channels = None;
893+ let mut codec = String::new();
894+ let mut profile = String::new();
895+ for line in text.lines() {
896+ let (key, value) = line.split_once('=')?;
897+ match key {
898+ "index" => {
899+ if codec == "aac" && profile.contains(want) {
900+ return Some((index?, channels?, profile));
901+ }
902+ index = value.parse().ok();
903+ codec.clear();
904+ profile.clear();
905+ }
906+ "codec_name" => codec = value.to_string(),
907+ "channels" => channels = value.parse().ok(),
908+ "profile" => profile = value.to_string(),
909+ _ => {}
910+ }
911+ }
912+ if codec == "aac" && profile.contains(want) {
913+ return Some((index?, channels?, profile));
914+ }
915+ None
916+}
scripts/aac-tables/aacprobe.pyadded+132 -0
@@ -0,0 +1,132 @@
1+#!/usr/bin/env python3
2+"""Black-box derivation of the ISO/IEC 14496-3 AAC-LC Huffman codebooks.
3+
4+Clean-room: no AAC implementation source is read. The only oracle is ffmpeg's
5+`aac` decoder driven as a black box. We synthesise ADTS frames whose spectral
6+payload is a bit string we choose, decode them, invert the (windowed) MDCT to
7+recover the quantised spectrum, and learn the prefix code from bits -> tuple.
8+
9+Frame shape (mono, 48 kHz, ONLY_LONG, sine window):
10+ SCE(3)=0 tag(4)=0 global_gain(8) ics_info section_data sf_data flags spectral
11+max_sfb=2 gives one section of 8 coefficients, so the spectral field always
12+outlives the probe prefix and the trailing all-ones run lands on an END element
13+(id 7 = 0b111). The ones run is bounded -- a long 0xFF tail makes ffmpeg's ADTS
14+parser resync on a false 0xFFF sync word.
15+"""
16+
17+import numpy as np
18+import subprocess
19+import os
20+
21+SR = 48000
22+N = 1024
23+ONES_RUN = 96 # bits of `1` filler after the probe, then zero padding
24+
25+
26+class BitW:
27+ def __init__(self):
28+ self.bits = []
29+
30+ def w(self, val, n):
31+ for i in range(n - 1, -1, -1):
32+ self.bits.append((val >> i) & 1)
33+ return self
34+
35+ def wbits(self, seq):
36+ self.bits.extend(seq)
37+ return self
38+
39+ def __len__(self):
40+ return len(self.bits)
41+
42+ def pack(self, total_bytes=None, pad=0):
43+ if total_bytes is None:
44+ total_bytes = (len(self.bits) + 7) // 8
45+ b = (self.bits + [pad] * (total_bytes * 8))[: total_bytes * 8]
46+ out = bytearray()
47+ for i in range(0, len(b), 8):
48+ v = 0
49+ for bit in b[i : i + 8]:
50+ v = (v << 1) | bit
51+ out.append(v)
52+ return bytes(out)
53+
54+
55+def adts(payload: bytes, sf_index=3, chan_cfg=1) -> bytes:
56+ h = BitW()
57+ h.w(0xFFF, 12).w(0, 1).w(0, 2).w(1, 1) # sync, MPEG-4, layer, no CRC
58+ h.w(1, 2).w(sf_index, 4).w(0, 1).w(chan_cfg, 3) # AAC-LC
59+ h.w(0, 1).w(0, 1).w(0, 1).w(0, 1) # original, home, copyright id/start
60+ h.w(len(payload) + 7, 13).w(0x7FF, 11).w(0, 2)
61+ return h.pack(7) + payload
62+
63+
64+def probe_frame(cb, sf_bits, probe_bits, gg=200, max_sfb=2):
65+ w = BitW()
66+ w.w(0, 3).w(0, 4) # SCE, instance tag
67+ w.w(gg, 8)
68+ w.w(0, 1).w(0, 2).w(0, 1).w(max_sfb, 6).w(0, 1) # ONLY_LONG, sine window
69+ w.w(cb, 4).w(max_sfb, 5) # one section covering every band
70+ w.wbits(sf_bits)
71+ w.w(0, 3) # pulse / tns / gain-control absent
72+ w.wbits(probe_bits).wbits([1] * ONES_RUN)
73+ return adts(w.pack(pad=0))
74+
75+
76+def silent_frame():
77+ w = BitW()
78+ w.w(0, 3).w(0, 4).w(128, 8)
79+ w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1) # max_sfb = 0: nothing coded
80+ w.w(0, 3).w(7, 3) # flags, END
81+ return adts(w.pack(4))
82+
83+
84+# --- MDCT read-back ---------------------------------------------------------
85+
86+_PINV = None
87+
88+
89+def recover(block, ncoef=12):
90+ """Quantised-spectrum-proportional coefficients from 2048 output samples."""
91+ global _PINV
92+ if _PINV is None:
93+ cache = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pinv.npy")
94+ if os.path.exists(cache):
95+ _PINV = np.load(cache)
96+ else:
97+ n = np.arange(2 * N)
98+ k = np.arange(N)
99+ m = np.cos(2 * np.pi / N * np.outer(n + 0.5 + N / 2, k + 0.5))
100+ win = np.sin(np.pi / (2 * N) * (n + 0.5))
101+ _PINV = np.linalg.pinv(m * win[:, None])[:32].astype(np.float64)
102+ np.save(cache, _PINV)
103+ return _PINV[:ncoef] @ block
104+
105+
106+def decode_probes(frames, tag="p"):
107+ """One 2048-sample block per probe frame, or None when ffmpeg refused it."""
108+ d = os.path.dirname(os.path.abspath(__file__))
109+ src = os.path.join(d, f"probe-{tag}.aac")
110+ sil = silent_frame()
111+ with open(src, "wb") as f:
112+ f.write(sil + b"".join(fr + sil + sil for fr in frames))
113+ raw = subprocess.run(
114+ ["ffmpeg", "-v", "error", "-i", src, "-f", "f32le", "-ac", "1", "-"],
115+ capture_output=True,
116+ )
117+ pcm = np.frombuffer(raw.stdout, dtype="<f4")
118+ nblk = len(pcm) // N
119+ pcm = pcm[: nblk * N].reshape(nblk, N).astype(np.float64)
120+ os.remove(src)
121+ if nblk != 3 * len(frames) + 1:
122+ return None, raw.stderr.decode()
123+ return [np.concatenate([pcm[3 * i + 1], pcm[3 * i + 2]]) for i in range(len(frames))], ""
124+
125+
126+if __name__ == "__main__":
127+ frs = [probe_frame(3, [0] * 2, [1] * 40)]
128+ blocks, err = decode_probes(frs, "smoke")
129+ if blocks is None:
130+ print("MISALIGNED", err[:400])
131+ else:
132+ print("coefs", np.round(recover(blocks[0], 12), 6))
scripts/aac-tables/gen_tables.pyadded+121 -0
@@ -0,0 +1,121 @@
1+#!/usr/bin/env python3
2+"""Emit crates/ec-aac/src/tables.rs from the probed tables."""
3+
4+import json
5+import sys
6+
7+SPEC = { # cb: (dim, lav, unsigned, esc)
8+ 1: (4, 1, False, False),
9+ 2: (4, 1, False, False),
10+ 3: (4, 2, True, False),
11+ 4: (4, 2, True, False),
12+ 5: (2, 4, False, False),
13+ 6: (2, 4, False, False),
14+ 7: (2, 7, True, False),
15+ 8: (2, 7, True, False),
16+ 9: (2, 12, True, False),
17+ 10: (2, 12, True, False),
18+ 11: (2, 16, True, True),
19+}
20+
21+
22+def index_of(t, dim, lav, unsigned):
23+ span = lav + 1 if unsigned else 2 * lav + 1
24+ off = 0 if unsigned else lav
25+ idx = 0
26+ for v in t:
27+ idx = idx * span + (v + off)
28+ return idx
29+
30+
31+def emit_codebook(cb):
32+ dim, lav, unsigned, esc = SPEC[cb]
33+ d = json.load(open(f"cb{cb}.json"))
34+ span = lav + 1 if unsigned else 2 * lav + 1
35+ n = span ** dim
36+ table = [None] * n
37+ for bits, tup in d.items():
38+ i = index_of(tuple(tup), dim, lav, unsigned)
39+ assert table[i] is None, (cb, tup)
40+ table[i] = (len(bits), int(bits, 2))
41+ missing = [i for i, v in enumerate(table) if v is None]
42+ assert not missing, (cb, missing[:5])
43+ body = ", ".join(f"({l},{c})" for l, c in table)
44+ return f"/// Codebook {cb}: dim {dim}, lav {lav}, " \
45+ f"{'unsigned' if unsigned else 'signed'}{', escape' if esc else ''}.\n" \
46+ f"static HCB{cb}: [(u8, u32); {n}] = [{body}];\n"
47+
48+
49+def main():
50+ out = []
51+ out.append('''//! Normative AAC tables (ISO/IEC 14496-3 §4.6.2, §4.6.9, tbl 4.140).
52+//!
53+//! Every number here was derived by black-box probing of a reference decoder,
54+//! not copied from an implementation: `scripts/derive-aac-tables.py` synthesises
55+//! access units whose spectral payload is a chosen bit string, decodes them, and
56+//! reads the quantised spectrum back through the inverse MDCT. Each codebook
57+//! came out with a Kraft sum of exactly 1 and the entry count the standard
58+//! prescribes, which is what makes the derivation self-checking.
59+''')
60+ for cb in range(1, 12):
61+ out.append(emit_codebook(cb))
62+
63+ sf = json.load(open("sfb.json"))
64+ tab = [None] * 121
65+ for bits, v in sf.items():
66+ tab[v] = (len(bits), int(bits, 2))
67+ assert all(t is not None for t in tab)
68+ out.append("/// Scalefactor codebook: index is the coded value, delta = index - 60.\n"
69+ "static HCB_SF: [(u8, u32); 121] = ["
70+ + ", ".join(f"({l},{c})" for l, c in tab) + "];\n")
71+
72+ lng = json.load(open("swb.json"))
73+ sht = json.load(open("swb_short.json"))
74+ for name, src, cap in (("LONG", lng, "long"), ("SHORT", sht, None)):
75+ rows = []
76+ for i in range(12):
77+ e = src[str(i)]["long"] if cap else src[str(i)]
78+ rows.append("&[0, " + ", ".join(str(v) for v in e) + "]")
79+ out.append(f"/// Scalefactor-band offsets for {'1024' if cap else '128'}-line "
80+ f"windows, by samplingFrequencyIndex.\n"
81+ f"pub static SWB_{name}: [&[u16]; 12] = [\n "
82+ + ",\n ".join(rows) + ",\n];\n")
83+
84+ out.append('''
85+/// One spectral codebook's shape.
86+#[derive(Clone, Copy, Debug)]
87+pub struct Codebook {
88+ /// Coefficients per Huffman codeword (2 or 4).
89+ pub dim: u8,
90+ /// Largest absolute value the codebook can carry.
91+ pub lav: u8,
92+ /// True when magnitudes are coded and each non-zero one takes a sign bit.
93+ pub unsigned: bool,
94+ /// True for codebook 11, whose magnitude 16 opens an escape sequence.
95+ pub esc: bool,
96+ /// `(length, code)` by tuple index, most-significant bit first.
97+ pub codes: &'static [(u8, u32)],
98+}
99+
100+/// The eleven spectral codebooks, indexed by `sect_cb - 1`.
101+pub static CODEBOOKS: [Codebook; 11] = [
102+''')
103+ for cb in range(1, 12):
104+ dim, lav, unsigned, esc = SPEC[cb]
105+ out.append(f" Codebook {{ dim: {dim}, lav: {lav}, unsigned: {str(unsigned).lower()}, "
106+ f"esc: {str(esc).lower()}, codes: &HCB{cb} }},\n")
107+ out.append("];\n\n")
108+ out.append('''/// The scalefactor codebook, as a `Codebook`-shaped table of `(length, code)`.
109+pub static SCALEFACTOR_CODES: &[(u8, u32)] = &HCB_SF;
110+
111+/// Sampling frequencies by `samplingFrequencyIndex` (ISO 14496-3 tbl 1.18).
112+pub static SAMPLE_RATES: [u32; 13] = [
113+ 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
114+];
115+''')
116+ src = "".join(out)
117+ open(sys.argv[1], "w").write(src)
118+ print(f"wrote {sys.argv[1]}, {len(src)} bytes")
119+
120+
121+main()
scripts/aac-tables/learn.pyadded+151 -0
@@ -0,0 +1,151 @@
1+#!/usr/bin/env python3
2+"""Learn one AAC spectral Huffman codebook by black-box probing of ffmpeg.
3+
4+A bit string b is a complete codeword iff the first decoded tuple does not
5+change when a 0 is appended (prefix codes are injective, and the filler after
6+the codeword is identical in both probes). BFS over the binary tree therefore
7+enumerates the whole codebook in ~2M probes for M codewords.
8+"""
9+
10+import numpy as np
11+import subprocess
12+import os
13+import sys
14+import json
15+
16+import aacprobe as A
17+
18+N = 1024
19+_M = None
20+
21+
22+def basis():
23+ global _M
24+ if _M is None:
25+ n = np.arange(2 * N)
26+ _M = np.cos(np.pi / N * np.outer(n + 512.5, np.arange(16) + 0.5))
27+ return _M
28+
29+
30+WIN = np.sin(np.pi / (2 * N) * (np.arange(2 * N) + 0.5))
31+
32+
33+def spectrum(block):
34+ return (basis().T @ (block / WIN)) / N
35+
36+
37+def quant(x):
38+ """Dequantised coefficient -> signed quantised integer."""
39+ a = abs(x)
40+ if a < 1e-3:
41+ return 0
42+ v = int(round(a ** 0.75))
43+ return -v if x < 0 else v
44+
45+
46+def _decode(frames, tag=None):
47+ d = os.path.dirname(os.path.abspath(__file__))
48+ src = os.path.join(d, f"probe-{tag or os.getpid()}.aac")
49+ sil = A.silent_frame()
50+ with open(src, "wb") as f:
51+ f.write(sil + b"".join(fr + sil + sil for fr in frames))
52+ raw = subprocess.run(
53+ ["ffmpeg", "-v", "quiet", "-i", src, "-f", "f32le", "-ac", "1", "-"],
54+ capture_output=True,
55+ )
56+ pcm = np.frombuffer(raw.stdout, dtype="<f4").astype(np.float64)
57+ nblk = len(pcm) // N
58+ os.remove(src)
59+ if nblk != 3 * len(frames) + 1:
60+ return None
61+ pcm = pcm[: nblk * N].reshape(nblk, N)
62+ out = []
63+ for i in range(len(frames)):
64+ # the third packet of every triple decodes to silence; if it does not,
65+ # the stream lost a packet and every later index is off by one
66+ if float(np.abs(pcm[3 * i + 3]).max()) > 1e-9:
67+ return None
68+ out.append(np.concatenate([pcm[3 * i + 1], pcm[3 * i + 2]]))
69+ return out
70+
71+
72+def _blocks(frames):
73+ """One 2048-sample block per frame; None for frames ffmpeg refused.
74+
75+ A refused frame costs the whole batch its packet alignment, so a failed
76+ batch is bisected until the offenders are isolated.
77+ """
78+ got = _decode(frames)
79+ if got is not None:
80+ return got
81+ if len(frames) == 1:
82+ return [None]
83+ h = len(frames) // 2
84+ return _blocks(frames[:h]) + _blocks(frames[h:])
85+
86+
87+def run_batch(cb, probes, filler, gg=200, tag=None):
88+ """Decode one frame per probe; returns a list of 8 quantised values or None."""
89+ frames = [A.probe_frame(cb, [0, 0], list(p) + filler, gg=gg) for p in probes]
90+ return [
91+ None if b is None else tuple(quant(v) for v in spectrum(b)[:8])
92+ for b in _blocks(frames)
93+ ]
94+
95+
96+def learn(cb, dim, signed, esc=False, filler=None):
97+ filler = filler if filler is not None else [1] * 96
98+ cache = {}
99+
100+ def evaluate(nodes):
101+ todo = [b for b in nodes if b not in cache]
102+ for i in range(0, len(todo), 400):
103+ chunk = todo[i : i + 400]
104+ res = run_batch(cb, chunk, filler)
105+ for b, r in zip(chunk, res):
106+ if r is None:
107+ cache[b] = None
108+ else:
109+ t = r[:dim]
110+ if not signed:
111+ t = tuple(abs(v) for v in t)
112+ if esc:
113+ t = tuple(min(v, 16) if v >= 0 else max(v, -16) for v in t)
114+ cache[b] = t
115+
116+ codewords = {}
117+ frontier = [()]
118+ depth = 0
119+ while frontier and depth < 22:
120+ evaluate(frontier + [b + (0,) for b in frontier])
121+ nxt = []
122+ for b in frontier:
123+ g, g0 = cache[b], cache[b + (0,)]
124+ if g is None:
125+ continue # frame refused: subtree unreachable, retried below
126+ if g == g0:
127+ codewords[b] = g
128+ else:
129+ nxt += [b + (0,), b + (1,)]
130+ frontier = nxt
131+ depth += 1
132+ print(f" cb{cb} depth {depth}: {len(codewords)} codewords, {len(frontier)} open",
133+ file=sys.stderr)
134+ return codewords
135+
136+
137+def kraft(codewords):
138+ return sum(2.0 ** -len(b) for b in codewords)
139+
140+
141+if __name__ == "__main__":
142+ cb = int(sys.argv[1])
143+ dim = int(sys.argv[2])
144+ signed = sys.argv[3] == "s"
145+ esc = len(sys.argv) > 4 and sys.argv[4] == "esc"
146+ cw = learn(cb, dim, signed, esc)
147+ tuples = set(cw.values())
148+ print(f"cb{cb}: {len(cw)} codewords, {len(tuples)} distinct tuples, kraft={kraft(cw):.6f}")
149+ out = {"".join(map(str, b)): list(t) for b, t in cw.items()}
150+ with open(f"cb{cb}.json", "w") as f:
151+ json.dump(out, f)
scripts/aac-tables/learn11.pyadded+137 -0
@@ -0,0 +1,137 @@
1+#!/usr/bin/env python3
2+"""Codebook 11 (escape) and the scalefactor codebook.
3+
4+cb11: an all-ones filler makes the escape's unary length run away, so the
5+filler is `1^6 0` repeated -- bounded escapes -- and probes that land their
6+END element on one of those zeros are retried at another phase.
7+
8+sfb: the probe sits in the scale_factor_data field of a one-band frame whose
9+spectral field is the all-ones filler; the band's scalefactor is read back from
10+the dequantised magnitudes (|X| = x^(4/3) * 2^((sf-100)/4), x integral).
11+"""
12+
13+import json
14+import os
15+import subprocess
16+import sys
17+
18+import numpy as np
19+
20+import aacprobe as A
21+import learn as L
22+
23+FILLERS = [([1] * k + [0]) * (140 // (k + 1)) for k in (12, 20, 9, 6, 16, 24, 7, 30)]
24+
25+
26+def eval_cb11(nodes, cache):
27+ todo = [b for b in nodes if b not in cache]
28+ pending = list(todo)
29+ for filler in FILLERS:
30+ if not pending:
31+ break
32+ nxt = []
33+ for i in range(0, len(pending), 400):
34+ chunk = pending[i : i + 400]
35+ res = L.run_batch(11, chunk, filler)
36+ for b, r in zip(chunk, res):
37+ if r is None:
38+ nxt.append(b)
39+ else:
40+ cache[b] = tuple(min(abs(v), 16) for v in r[:2])
41+ pending = nxt
42+ for b in pending:
43+ cache[b] = None
44+
45+
46+def learn_cb11():
47+ cache = {}
48+ codewords = {}
49+ frontier = [()]
50+ depth = 0
51+ while frontier and depth < 32:
52+ eval_cb11(frontier + [b + (0,) for b in frontier], cache)
53+ nxt = []
54+ for b in frontier:
55+ g, g0 = cache[b], cache[b + (0,)]
56+ if g is None or g0 is None:
57+ print(" UNRESOLVED", b, file=sys.stderr)
58+ continue
59+ if g == g0:
60+ codewords[b] = g
61+ else:
62+ nxt += [b + (0,), b + (1,)]
63+ frontier = nxt
64+ depth += 1
65+ print(f" cb11 depth {depth}: {len(codewords)} codewords, {len(frontier)} open",
66+ file=sys.stderr)
67+ return codewords
68+
69+
70+# --- scalefactor codebook ---------------------------------------------------
71+
72+
73+def sf_batch(probes, tag=None):
74+ """Scalefactor of the second coded band, one frame per probe."""
75+ frames = [A.probe_frame(3, [0] + list(p), [1] * 96, gg=160, max_sfb=2) for p in probes]
76+ out = []
77+ for blk in L._blocks(frames):
78+ if blk is None:
79+ out.append(None)
80+ continue
81+ peak = float(np.abs(L.spectrum(blk)[4:8]).max())
82+ if peak < 1e-9:
83+ out.append(None)
84+ continue
85+ # |X| = x^(4/3) * 2^((sf-100)/4) with x in {1, 2} (codebook 3, lav 2);
86+ # only one of the two makes sf integral.
87+ best = None
88+ for x in (1, 2):
89+ sf = 100 + 4 * np.log2(peak / x ** (4 / 3))
90+ if abs(sf - round(sf)) < 0.02:
91+ best = int(round(sf))
92+ out.append(best)
93+ return out
94+
95+
96+def learn_sf():
97+ cache = {}
98+
99+ def evaluate(nodes):
100+ todo = [b for b in nodes if b not in cache]
101+ for i in range(0, len(todo), 400):
102+ chunk = todo[i : i + 400]
103+ for b, r in zip(chunk, sf_batch(chunk)):
104+ cache[b] = r
105+
106+ codewords = {}
107+ frontier = [()]
108+ depth = 0
109+ while frontier and depth < 32:
110+ evaluate(frontier + [b + (0,) for b in frontier])
111+ nxt = []
112+ for b in frontier:
113+ g, g0 = cache[b], cache[b + (0,)]
114+ if g is not None and g == g0:
115+ codewords[b] = g
116+ else:
117+ nxt += [b + (0,), b + (1,)]
118+ frontier = nxt
119+ depth += 1
120+ print(f" sfb depth {depth}: {len(codewords)} codewords, {len(frontier)} open",
121+ file=sys.stderr)
122+ return codewords
123+
124+
125+if __name__ == "__main__":
126+ if sys.argv[1] == "11":
127+ cw = learn_cb11()
128+ print(f"cb11: {len(cw)} codewords, {len(set(cw.values()))} tuples, "
129+ f"kraft={L.kraft(cw):.6f}")
130+ json.dump({"".join(map(str, b)): list(t) for b, t in cw.items()},
131+ open("cb11.json", "w"))
132+ else:
133+ cw = learn_sf()
134+ print(f"sfb: {len(cw)} codewords, {len(set(cw.values()))} values, "
135+ f"kraft={L.kraft(cw):.6f}, range={min(cw.values())}..{max(cw.values())}")
136+ json.dump({"".join(map(str, b)): v for b, v in cw.items()},
137+ open("sfb.json", "w"))
scripts/aac-tables/swb.pyadded+119 -0
@@ -0,0 +1,119 @@
1+#!/usr/bin/env python3
2+"""Derive the scalefactor-band offset tables (ISO 14496-3 tbl 4.140) by probing.
3+
4+For a frame coded with max_sfb = k, the highest non-zero spectral coefficient is
5+swb_offset[k] - 1. Long windows are read back through the exact MDCT inverse;
6+short windows through the FFT of the 2048-sample frame, whose bin spacing
7+(fs/2048) is eight times finer than one short-block coefficient (fs/256).
8+"""
9+
10+import json
11+import os
12+import subprocess
13+import sys
14+
15+import numpy as np
16+
17+import aacprobe as A
18+import learn as L
19+
20+BASIS = np.cos(np.pi / 1024 * np.outer(np.arange(2048) + 512.5, np.arange(1024) + 0.5))
21+
22+
23+def sect_len(w, k, bits):
24+ esc = (1 << bits) - 1
25+ left = k
26+ while left >= esc:
27+ w.w(esc, bits)
28+ left -= esc
29+ w.w(left, bits)
30+
31+
32+def frame_long(k, sf_index):
33+ w = A.BitW()
34+ w.w(0, 3).w(0, 4).w(200, 8)
35+ w.w(0, 1).w(0, 2).w(0, 1).w(k, 6).w(0, 1)
36+ w.w(3, 4)
37+ sect_len(w, k, 5)
38+ w.wbits([0] * k) # the one-bit delta-zero scalefactor codeword per band
39+ w.w(0, 3)
40+ w.wbits([1] * 6000)
41+ return A.adts(w.pack(pad=0), sf_index=sf_index)
42+
43+
44+def frame_short(k, sf_index):
45+ w = A.BitW()
46+ w.w(0, 3).w(0, 4).w(200, 8)
47+ w.w(0, 1).w(2, 2).w(0, 1).w(k, 4).w(0x7F, 7) # EIGHT_SHORT, one group of 8
48+ w.w(3, 4)
49+ sect_len(w, k, 3)
50+ w.wbits([0] * k)
51+ w.w(0, 3)
52+ w.wbits([1] * 6000)
53+ return A.adts(w.pack(pad=0), sf_index=sf_index)
54+
55+
56+def silent(sf_index):
57+ w = A.BitW()
58+ w.w(0, 3).w(0, 4).w(128, 8)
59+ w.w(0, 1).w(0, 2).w(0, 1).w(0, 6).w(0, 1)
60+ w.w(0, 3).w(7, 3)
61+ return A.adts(w.pack(4), sf_index=sf_index)
62+
63+
64+def blocks(frames, sf_index):
65+ src = f"swb-{os.getpid()}.aac"
66+ sil = silent(sf_index)
67+ with open(src, "wb") as f:
68+ f.write(sil + b"".join(fr + sil + sil for fr in frames))
69+ raw = subprocess.run(
70+ ["ffmpeg", "-v", "quiet", "-i", src, "-f", "f32le", "-ac", "1", "-"],
71+ capture_output=True,
72+ )
73+ pcm = np.frombuffer(raw.stdout, dtype="<f4").astype(np.float64)
74+ os.remove(src)
75+ nb = len(pcm) // 1024
76+ if nb != 3 * len(frames) + 1:
77+ if len(frames) == 1:
78+ return [None]
79+ h = len(frames) // 2
80+ return blocks(frames[:h], sf_index) + blocks(frames[h:], sf_index)
81+ pcm = pcm[: nb * 1024].reshape(nb, 1024)
82+ return [np.concatenate([pcm[3 * i + 1], pcm[3 * i + 2]]) for i in range(len(frames))]
83+
84+
85+def long_offsets(sf_index):
86+ out = []
87+ got = blocks([frame_long(k, sf_index) for k in range(1, 52)], sf_index)
88+ for blk in got:
89+ if blk is None:
90+ break
91+ spec = (BASIS.T @ (blk / L.WIN)) / 1024
92+ nz = np.where(np.abs(spec) > 1e-3)[0]
93+ if len(nz) == 0:
94+ break
95+ out.append(int(nz.max()) + 1)
96+ return out
97+
98+
99+def short_offsets(sf_index):
100+ out = []
101+ got = blocks([frame_short(k, sf_index) for k in range(1, 17)], sf_index)
102+ for blk in got:
103+ if blk is None:
104+ break
105+ mag = np.abs(np.fft.rfft(blk * np.hanning(2048)))
106+ top = np.where(mag > mag.max() * 3e-4)[0].max()
107+ out.append(top / 8.0)
108+ return out
109+
110+
111+if __name__ == "__main__":
112+ out = {}
113+ for idx in range(0, 12):
114+ lo = long_offsets(idx)
115+ sh = short_offsets(idx)
116+ out[idx] = {"long": lo, "short": sh}
117+ print(idx, "long", len(lo), lo, file=sys.stderr)
118+ print(idx, "short", [round(v, 1) for v in sh], file=sys.stderr)
119+ json.dump(out, open("swb.json", "w"))
scripts/aac-tables/swblong.pyadded+12 -0
@@ -0,0 +1,12 @@
1+"""Long-window scalefactor-band offsets, one sweep per samplingFrequencyIndex."""
2+
3+import json
4+
5+import swb
6+
7+res = {}
8+for idx in range(12):
9+ edges = swb.long_offsets(idx)
10+ res[idx] = {"long": edges}
11+ print(idx, len(edges), edges, flush=True)
12+json.dump(res, open("swb.json", "w"))
scripts/aac-tables/swbshort.pyadded+20 -0
@@ -0,0 +1,20 @@
1+import numpy as np, json, swb
2+n=np.arange(256); ws=np.sin(np.pi/256*(n+0.5))
3+Ms=np.cos(np.pi/128*np.outer(n+64.5, np.arange(128)+0.5))*ws[:,None]
4+A=np.zeros((2048,8*128))
5+for i in range(8):
6+ A[448+128*i:448+128*i+256, i*128:(i+1)*128]=Ms
7+P=np.linalg.solve(A.T@A + 1e-8*np.eye(1024), A.T)
8+res={}
9+for idx in range(12):
10+ got=swb.blocks([swb.frame_short(k,idx) for k in range(1,17)], idx)
11+ edges=[]
12+ for blk in got:
13+ if blk is None: break
14+ X=(P@blk).reshape(8,128)
15+ if np.abs(X).max()<1e-9: break
16+ nz=np.where(np.abs(X)>1e-4*np.abs(X).max())
17+ edges.append(int(nz[1].max())+1)
18+ res[idx]=edges
19+ print(idx, len(edges), edges, flush=True)
20+json.dump(res, open('swb_short.json','w'))
scripts/aac-tables/tns.pyadded+34 -0
@@ -0,0 +1,34 @@
1+import swb, aacprobe as A, sys
2+def frame_tns(max_sfb, n_filt, coef_res, length, order, direction, compress, coefs, sf_index=3):
3+ w=A.BitW()
4+ w.w(0,3).w(0,4).w(200,8)
5+ w.w(0,1).w(0,2).w(0,1).w(max_sfb,6).w(0,1)
6+ w.w(3,4); swb.sect_len(w,max_sfb,5)
7+ w.wbits([0]*max_sfb)
8+ w.w(0,1) # pulse_data_present
9+ w.w(1,1) # tns_data_present
10+ w.w(n_filt,2)
11+ if n_filt:
12+ w.w(coef_res,1)
13+ for f in range(n_filt):
14+ w.w(length,6); w.w(order,5)
15+ if order:
16+ w.w(direction,1); w.w(compress,1)
17+ bits = coef_res + 3 - compress
18+ for c in coefs[:order]:
19+ w.w(c & ((1<<bits)-1), bits)
20+ w.w(0,1) # gain_control
21+ w.wbits([1]*6000)
22+ return A.adts(w.pack(pad=0), sf_index=sf_index)
23+sil=swb.silent(3)
24+cases=[
25+ (20,1,0,8,4,0,0,[1,2,-1,0]),
26+ (20,1,0,8,4,1,0,[1,2,-1,0]),
27+ (20,1,1,10,6,0,0,[3,-2,1,0,2,-1]),
28+ (20,1,1,10,6,0,1,[1,-1,1,0,1,-1]),
29+ (30,1,0,40,3,0,0,[2,-2,1]),
30+ (20,2,0,6,3,0,0,[1,1,-1]),
31+]
32+frames=[frame_tns(*c) for c in cases]
33+open('/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/6410b1a2-7cdb-42c3-ac18-2bbfd6cd1284/scratchpad/short/tns.aac','wb').write(sil+b''.join(f+sil+sil for f in frames))
34+print('cases', len(cases))
scripts/derive-aac-tables.pyadded+64 -0
@@ -0,0 +1,64 @@
1+#!/usr/bin/env python3
2+"""Derive the normative AAC-LC tables by black-box probing of a reference decoder.
3+
4+Clean room: no AAC implementation source is read. The only oracle is ffmpeg's
5+`aac` decoder, driven as a black box. Synthetic access units carry a spectral
6+payload we choose; decoding them and inverting the MDCT recovers the quantised
7+values, and a binary-tree walk over bit prefixes enumerates each codebook.
8+
9+A bit string `b` is a complete codeword exactly when the first decoded tuple does
10+not change if a `0` is appended -- prefix codes are injective, and the filler
11+after the codeword is identical in both probes. That makes the walk about `2M`
12+probes for `M` codewords, and every codebook it produces is checked against a
13+Kraft sum of exactly 1 and the entry count ISO/IEC 14496-3 prescribes, which is
14+what makes the derivation self-checking.
15+
16+The band tables come out the same way: with `max_sfb = k` the highest non-zero
17+coefficient is `swb_offset[k] - 1`, and the TNS band limits show up as the
18+`max_sfb` at which a filter stops being applied.
19+
20+Usage: python3 scripts/derive-aac-tables.py [work-dir]
21+Writes cb1..cb11.json, sfb.json, swb.json and swb_short.json into the work
22+directory, then regenerates crates/ec-aac/src/tables.rs. Needs numpy and ffmpeg.
23+"""
24+
25+import json
26+import os
27+import subprocess
28+import sys
29+
30+HERE = os.path.dirname(os.path.abspath(__file__))
31+MODULES = os.path.join(HERE, "aac-tables")
32+CODEBOOKS = [
33+ (1, 4, "s"), (2, 4, "s"), (3, 4, "u"), (4, 4, "u"), (5, 2, "s"), (6, 2, "s"),
34+ (7, 2, "u"), (8, 2, "u"), (9, 2, "u"), (10, 2, "u"),
35+]
36+
37+
38+def run(args, cwd):
39+ print("+", " ".join(args), flush=True)
40+ subprocess.run([sys.executable, *args], cwd=cwd, check=True)
41+
42+
43+def main():
44+ work = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "aac-tables-work")
45+ os.makedirs(work, exist_ok=True)
46+ for name in os.listdir(MODULES):
47+ if name.endswith(".py"):
48+ with open(os.path.join(MODULES, name)) as src, \
49+ open(os.path.join(work, name), "w") as dst:
50+ dst.write(src.read())
51+ for cb, dim, signed in CODEBOOKS:
52+ run(["learn.py", str(cb), str(dim), signed], work)
53+ run(["learn11.py", "11"], work)
54+ run(["learn11.py", "sf"], work)
55+ run(["swblong.py"], work) if os.path.exists(os.path.join(work, "swblong.py")) else None
56+ run(["swbshort.py"], work)
57+ out = os.path.join(HERE, "..", "crates", "ec-aac", "src", "tables.rs")
58+ run(["gen_tables.py", os.path.abspath(out)], work)
59+ with open(os.path.join(work, "cb11.json")) as f:
60+ print("cb11 entries:", len(json.load(f)))
61+
62+
63+if __name__ == "__main__":
64+ main()
shims/rusty_aac/tests/edith_surface.rsadded+73 -0
@@ -0,0 +1,73 @@
1+//! The call sites edith actually has, compiled and run against the shim.
2+//!
3+//! Each one mirrors a line in the replica: `audio.rs:1731` builds the decoder
4+//! for a multichannel track from its AudioSpecificConfig, `export.rs:1678`
5+//! turns a sample rate into a `samplingFrequencyIndex`, and `export.rs:1756`
6+//! plus `mux.rs:2116` drive the encoder over a mix.
7+
8+#[test]
9+fn sf_index_for_rate_covers_the_rates_the_exporter_offers() {
10+ assert_eq!(rusty_aac::sf_index_for_rate(48_000), Some(3));
11+ assert_eq!(rusty_aac::sf_index_for_rate(44_100), Some(4));
12+ assert_eq!(rusty_aac::sf_index_for_rate(96_000), Some(0));
13+ assert_eq!(rusty_aac::sf_index_for_rate(8_000), Some(11));
14+ // The exporter's own error path: a rate AAC cannot carry.
15+ assert_eq!(rusty_aac::sf_index_for_rate(37_000), None);
16+}
17+
18+#[test]
19+fn a_multichannel_track_builds_from_its_audio_specific_config() {
20+ // 5.1 at 48 kHz, which is what a film's mkv hands over as CodecPrivate.
21+ let asc = rusty_aac::audio_specific_config_bytes(48_000, 6);
22+ let decoder = rusty_aac::AacDecoder::with_config_bytes(&asc).expect("decoder builds");
23+ assert_eq!(decoder.output_sample_rate(), Some(48_000));
24+ assert_eq!(decoder.sbr_support(), rusty_aac::SbrSupport::NotSignalled);
25+}
26+
27+/// `export.rs:1756`: the caller's bitrate over the config's defaults, PCM in,
28+/// packets out until `Eof`.
29+#[test]
30+fn the_export_encoder_loop_runs_to_eof() {
31+ let rate = 48_000u32;
32+ let channels = 2u16;
33+ let frames = rate as usize;
34+ let mut pcm = Vec::with_capacity(frames * usize::from(channels));
35+ for i in 0..frames {
36+ let s = (i as f32 * 440.0 * std::f32::consts::TAU / rate as f32).sin() * 0.5;
37+ for _ in 0..channels {
38+ pcm.push(s);
39+ }
40+ }
41+ let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig {
42+ bitrate_bps: 256 * 1_000,
43+ ..Default::default()
44+ });
45+ encoder
46+ .push_pcm(&pcm, channels, rate)
47+ .expect("pcm accepted");
48+ encoder.finish();
49+ let mut packets = Vec::new();
50+ while let Ok(packet) = encoder.next_packet() {
51+ assert_eq!(packet.duration, 1024, "one AAC frame per packet");
52+ assert!(!packet.data.is_empty(), "a packet with no payload");
53+ packets.push(packet);
54+ }
55+ assert!(
56+ packets.len() > 10,
57+ "a second of audio is many packets, got {}",
58+ packets.len()
59+ );
60+ assert_eq!(encoder.sample_rate(), rate);
61+ assert_eq!(encoder.channels(), channels);
62+
63+ // And the packets are a stream this family's own decoder reads back.
64+ let asc = rusty_aac::audio_specific_config_bytes(rate, channels);
65+ let mut decoder = rusty_aac::AacDecoder::with_config_bytes(&asc).expect("decoder builds");
66+ let mut decoded = 0usize;
67+ for packet in &packets {
68+ let audio = decoder.decode(&packet.data, None).expect("packet decodes");
69+ assert_eq!(audio.channels, channels);
70+ decoded += audio.frames();
71+ }
72+ assert_eq!(decoded, packets.len() * 1024);
73+}