From 9b44442f6adc7de3211dd0af1b4a7e2cf23bb8d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 04:22:53 +0300 Subject: [PATCH] aac(sbr): explicit-SBR AudioSpecificConfig writer, plus a wrap-to-mp4 probe instrument MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit write_audio_specific_config never emitted the extension sf_index/ extensionAudioObjectType an AOT_SBR/AOT_PS config needs (§1.6.2.1) -- it wrote plain GASpecificConfig fields regardless of object type, so every config it built for an SBR-signalling caller was spec-invalid. Extended it minimally (parse_audio_specific_config already read the extension fields correctly, so only the writer was missing them) and added a round-trip unit test. Also adds crates/ec-aac/examples/wrap_sbr, the round-30/31 instrument blocker's fix: wraps bare ADTS probe streams (the SBR patch-map scripts' output) in an mp4 carrying this explicit-SBR ASC as their esds, so the reference decoder has an out-of-band AudioSpecificConfig to arm HE-AAC output from instead of only its (never-engaging) implicit per-frame detection on bare ADTS. --- crates/ec-aac/examples/wrap_sbr.rs | 108 +++++++++++++++++++++++++++++ crates/ec-aac/src/config.rs | 44 ++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 crates/ec-aac/examples/wrap_sbr.rs diff --git a/crates/ec-aac/examples/wrap_sbr.rs b/crates/ec-aac/examples/wrap_sbr.rs new file mode 100644 index 00000000..5984fcc8 --- /dev/null +++ b/crates/ec-aac/examples/wrap_sbr.rs @@ -0,0 +1,108 @@ +//! Wraps a bare ADTS stream (the SBR patch-map probes' +//! `scripts/aac-tables/sbrpatchmap.py` output) in an mp4 container carrying +//! an EXPLICIT-SBR AudioSpecificConfig as its `esds` -- the instrument +//! round-30's blocker needed: a bare `.aac` file carries no out-of-band +//! AudioSpecificConfig at all, so a decoder that trusts one (rather than +//! only its bare-ADTS implicit per-frame SBR detection) has nothing to arm +//! HE-AAC output from and locks to core-rate. +//! +//! Matroska was tried first (`MatroskaMuxer`, dev-dep already proven to +//! round-trip `CodecPrivate` byte-for-byte in +//! `crates/ec-aac/tests/sbr_real_library.rs`) but the reference decoder's +//! Matroska demuxer reads the *codec ID string* ("A_AAC" vs. +//! "A_AAC/MPEG4/SBR") for its reported profile, not just the `CodecPrivate` +//! bytes our `MatroskaMuxer` writes generically -- it still upgraded the +//! reported sample rate to the extension rate (proving it DOES parse +//! `CodecPrivate` for that), but kept reporting profile "LC". mp4's `esds` +//! carries the same explicit-SBR AudioSpecificConfig and needs no such +//! sibling string, matching the real `~/Music/reeln.mp4` fixture's +//! own container exactly. +//! +//! `stream()`/`stream_one_band()`'s probe frames are full ADTS (7-byte +//! header + raw_data_block); this strips the header off each frame and +//! remuxes the raw access units into an mp4 track whose `esds` is +//! `write_audio_specific_config` with `object_type = AOT_SBR` and an +//! explicit `extension_sample_rate`. +//! +//! usage: wrap_sbr_mkv +use std::fs::File; + +use ec_aac::{AOT_SBR, AudioSpecificConfig, sf_index_for_rate, write_audio_specific_config}; +use ec_core::{ + AudioParameters, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer, Packet, + StreamInfo, TimeBase, +}; +use ec_mp4::Mp4Muxer; + +fn main() { + let args: Vec = std::env::args().collect(); + assert_eq!( + args.len(), + 6, + "usage: wrap_sbr_mkv " + ); + let data = std::fs::read(&args[1]).expect("input readable"); + let core_rate: u32 = args[2].parse().expect("core_rate is a number"); + let ext_rate: u32 = args[3].parse().expect("ext_rate is a number"); + let channels: u16 = args[4].parse().expect("channels is a number"); + + // Strip each ADTS frame down to its raw access unit (no header, no CRC). + let mut aus = Vec::new(); + let mut at = 0usize; + while at + 7 <= data.len() { + let Ok(header) = ec_aac::parse_adts(&data[at..]) else { + break; + }; + let end = (at + header.frame_length).min(data.len()); + aus.push(data[at + header.header_len..end].to_vec()); + at = end; + } + assert!(!aus.is_empty(), "no ADTS frames found in {}", args[1]); + + let sf_index = sf_index_for_rate(core_rate).expect("core_rate is a valid AAC rate"); + let channel_config = channels as u8; + let asc = write_audio_specific_config(&AudioSpecificConfig { + object_type: AOT_SBR, + sample_rate: core_rate, + sf_index, + channels, + channel_config, + sbr_present: true, + ps_present: false, + extension_sample_rate: Some(ext_rate), + }); + + let time_base = TimeBase::from_rate(core_rate); + let layout = if channels == 1 { + ChannelLayout::Mono + } else { + ChannelLayout::Stereo + }; + let mut params = CodecParameters::new(CodecId::Aac); + params.extradata = Some(asc.into()); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate: core_rate, + layout, + format: None, + bits_per_sample: None, + }); + let mut info = StreamInfo::new(0, time_base, params); + info.default = true; + + let out = File::create(&args[5]).expect("output creatable"); + let mut muxer = Mp4Muxer::new(out).expect("mp4 muxer opens"); + muxer.add_stream(info).expect("stream declared"); + for (i, au) in aus.iter().enumerate() { + let pts = i as i64 * 1024; + let packet = Packet::new(0, time_base, au.as_slice()) + .with_pts(pts) + .with_duration(1024); + muxer.write_packet(&packet).expect("packet written"); + } + muxer.finish().expect("finished"); + eprintln!( + "wrote {} ({} frames, core={core_rate}Hz ext={ext_rate}Hz ch={channels})", + args[5], + aus.len() + ); +} diff --git a/crates/ec-aac/src/config.rs b/crates/ec-aac/src/config.rs index 4b906f19..f02f0169 100644 --- a/crates/ec-aac/src/config.rs +++ b/crates/ec-aac/src/config.rs @@ -136,11 +136,25 @@ pub fn parse_audio_specific_config(data: &[u8]) -> Result { } /// Serialises the two-byte (plus SBR extension) AudioSpecificConfig. +/// +/// `AOT_SBR`/`AOT_PS` are the *explicit* signalling form (§1.6.2.1's "SBR +/// config"): a core `sf_index`/`channel_config`, then the extension +/// (`SBR`-output) `sf_index` and an `extensionAudioObjectType` of AAC-LC +/// before the GASpecificConfig that form always carries -- without those +/// fields a decoder that trusts the object type (rather than only its +/// bare-ADTS implicit per-frame detection) has no extension rate to read and +/// never reports itself as HE-AAC. pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec { let mut w = BitWriter::new(); w.write_bits(u32::from(cfg.object_type), 5); w.write_bits(u32::from(cfg.sf_index), 4); w.write_bits(u32::from(cfg.channel_config), 4); + if cfg.object_type == AOT_SBR || cfg.object_type == AOT_PS { + let ext_rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2); + let ext_sf_index = sf_index_for_rate(ext_rate).unwrap_or(3); + w.write_bits(u32::from(ext_sf_index), 4); + w.write_bits(u32::from(AOT_AAC_LC), 5); // extensionAudioObjectType + } w.write_bit(false); // frameLengthFlag: 1024 samples w.write_bit(false); // dependsOnCoreCoder w.write_bit(false); // extensionFlag @@ -308,3 +322,33 @@ pub fn write_adts_header(header: &AdtsHeader) -> Vec { w.write_bits(u32::from(header.raw_blocks.saturating_sub(1)), 2); w.into_bytes() } + +#[cfg(test)] +mod tests { + use super::*; + + /// An explicit-SBR AudioSpecificConfig (object type 5) round-trips its + /// core AND extension sample rate through `write`/`parse` -- the write + /// side that a bare-ADTS ASC needs so a decoder trusting the object type + /// (rather than implicit per-frame detection) reports HE-AAC at the + /// doubled rate. + #[test] + fn explicit_sbr_config_round_trips() { + let cfg = AudioSpecificConfig { + object_type: AOT_SBR, + sample_rate: 22050, + sf_index: sf_index_for_rate(22050).unwrap(), + channels: 1, + channel_config: 1, + sbr_present: true, + ps_present: false, + extension_sample_rate: Some(44100), + }; + let bytes = write_audio_specific_config(&cfg); + let parsed = parse_audio_specific_config(&bytes).expect("parses"); + assert!(parsed.sbr_present, "explicit SBR must round-trip as SBR"); + assert_eq!(parsed.sample_rate, 22050); + assert_eq!(parsed.extension_sample_rate, Some(44100)); + assert_eq!(parsed.channels, 1); + } +}