FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
codecs: HE-AAC plays at its output rate; AAC export caps the bitrate (#108)
carlitosteso3463a59c1b4b0
diff --git a/crates/aac/src/decoder.rs b/crates/aac/src/decoder.rsindex b112eb379..14dbbf4e2 100644--- a/crates/aac/src/decoder.rs+++ b/crates/aac/src/decoder.rs@@ -19,6 +19,10 @@ const ID_PCE: u32 = 5;const ID_FIL: u32 = 6;const ID_END: u32 = 7;+/// `extension_type` of a fill element carrying SBR data (ISO/IEC 14496-3 §4.5.2.8.2, Table 4.121).+const EXT_SBR_DATA: u32 = 13;+const EXT_SBR_DATA_CRC: u32 = 14;+/// One decoded `individual_channel_stream` before stereo processing and synthesis.struct Ics {info: IcsInfo,@@ -45,6 +49,8 @@ pub struct Decoder {offsets: Vec<usize>,channels: Vec<ChannelState>,noise_state: u32,+ /// A fill element carried SBR data (implicitly signalled HE-AAC).+ sbr_seen: bool,}impl Decoder {@@ -67,7 +73,7 @@ impl Decoder {if layout.is_empty() && asc.channel_config != 0 {return Err(Error::InvalidConfig("unsupported channel configuration"));}- let mut d = Decoder { asc, layout: Vec::new(), offsets: Vec::new(), channels: Vec::new(), noise_state: 0x2545_F491 };+ let mut d = Decoder { asc, layout: Vec::new(), offsets: Vec::new(), channels: Vec::new(), noise_state: 0x2545_F491, sbr_seen: false };d.set_layout(layout);Ok(d)}@@ -90,6 +96,12 @@ impl Decoder {pub fn sample_rate(&self) -> u32 {self.asc.sample_rate}+ /// Whether the stream is HE-AAC: SBR signalled in the `AudioSpecificConfig` (explicit) or SBR+ /// data seen in a fill element of a decoded access unit (implicit). Only the AAC-LC core is+ /// decoded, at [`Self::sample_rate`]; the SBR high band is not reconstructed.+ pub fn sbr(&self) -> bool {+ self.asc.sbr || self.sbr_seen+ }pub fn channels(&self) -> usize {self.channels.len()}@@ -174,7 +186,11 @@ impl Decoder {count += br.read_bits(8)? as usize;count -= 1;}- br.skip(count * 8)?;+ if count > 0 {+ let ext = br.read_bits(4)?;+ self.sbr_seen |= matches!(ext, EXT_SBR_DATA | EXT_SBR_DATA_CRC);+ br.skip(count * 8 - 4)?;+ }}_ => break, // ID_END}@@ -542,3 +558,27 @@ fn synth(state: &mut ChannelState, info: &IcsInfo, spec: &[f32]) -> Vec<f32> {state.prev_shape = cur;out}++#[cfg(test)]+mod tests {+ use super::*;++ /// Implicitly signalled HE-AAC (an AAC-LC config) is recognised from the SBR fill element.+ #[test]+ fn sbr_fill_element_marks_implicit_he_aac() {+ // AAC-LC, 22.05 kHz, stereo+ let mut dec = Decoder::new(&[0x13, 0x90]).unwrap();+ assert!(!dec.sbr());+ // ID_FIL, count 1, extension_type EXT_SBR_DATA (+ 4 bits of payload), ID_END+ let _ = dec.decode(&[0b1100_0011, 0b1010_0001, 0b1100_0000]);+ assert!(dec.sbr());+ // other fill payloads (EXT_FILL) don't+ let mut dec = Decoder::new(&[0x13, 0x90]).unwrap();+ let _ = dec.decode(&[0b1100_0010, 0b0000_0001, 0b1100_0000]);+ assert!(!dec.sbr());+ // explicit signalling: AOT 5, core 22.05 kHz, stereo, extension 44.1 kHz, core AOT 2+ let dec = Decoder::new(&[0x2B, 0x92, 0x08, 0x00]).unwrap();+ assert!(dec.sbr());+ assert_eq!(dec.sample_rate(), 22_050);+ }+}diff --git a/crates/codecs/src/audio.rs b/crates/codecs/src/audio.rsindex 7954473d1..4942f6a6c 100644--- a/crates/codecs/src/audio.rs+++ b/crates/codecs/src/audio.rs@@ -15,8 +15,8 @@ use symphonia::core::probe::Hint;use crate::{CodecError, Result};enum Inner {- /// Our own AAC-LC decoder.- Aac { dec: Box<filmcraft_aac::Decoder>, asc: Vec<u8> },+ /// Our own AAC-LC decoder. `up` interpolates HE-AAC's core to the output rate (see [`Upsample2x`]).+ Aac { dec: Box<filmcraft_aac::Decoder>, asc: Vec<u8>, up: Option<Box<Upsample2x>> },/// AAC whose configuration arrives with the first frame (ADTS / LATM).AacPending,/// Our own Opus decoder (always 48 kHz output; pre-skip is left to container timestamps).@@ -82,11 +82,13 @@ impl PacketDecoder {let dec = symphonia::default::get_codecs().make(&p, &DecoderOptions::default()).map_err(|e| CodecError::Unsupported(e.to_string()))?;Ok(Self { inner: Inner::Symphonia(dec), channels: 0 })}- /// AAC: our decoder for AAC-LC; symphonia for other object types (HE-AAC…).+ /// AAC: our decoder for AAC-LC and the AAC-LC core of HE-AAC (v1/v2); symphonia for other+ /// object types. `sample_rate` is the stream's output rate: when it is twice the core rate+ /// (HE-AAC, see [`aac_output_rate`]) the decoded core is upsampled to it.pub fn aac(asc: &[u8], sample_rate: u32) -> Result<Self> {- let lc = asc.first().map(|b| b >> 3) == Some(2);- if lc && let Ok(dec) = filmcraft_aac::Decoder::new(asc) {- return Ok(Self { inner: Inner::Aac { dec: Box::new(dec), asc: asc.to_vec() }, channels: 0 });+ if let Ok(dec) = filmcraft_aac::Decoder::new(asc) {+ let up = (dec.sample_rate().checked_mul(2) == Some(sample_rate)).then(|| Box::new(Upsample2x::new(dec.channels())));+ return Ok(Self { inner: Inner::Aac { dec: Box::new(dec), asc: asc.to_vec(), up }, channels: 0 });}Self::new(CODEC_TYPE_AAC, sample_rate, Some(asc.to_vec()))}@@ -119,7 +121,7 @@ impl PacketDecoder {return Ok(());}let dec = filmcraft_aac::Decoder::new(asc).map_err(|e| CodecError::Unsupported(format!("AAC: {e}")))?;- self.inner = Inner::Aac { dec: Box::new(dec), asc: asc.to_vec() };+ self.inner = Inner::Aac { dec: Box::new(dec), asc: asc.to_vec(), up: None };Ok(())}/// AC-3 (ATSC A/52).@@ -133,7 +135,7 @@ impl PacketDecoder {pub fn for_isobmff(c: &filmcraft_isobmff::CodecConfig, rate: u32) -> Result<Self> {use filmcraft_isobmff::CodecConfig as C;match c {- C::Aac(a) => Self::aac(&a.asc, if a.sample_rate > 0 { a.sample_rate } else { rate }),+ C::Aac(a) => Self::aac(&a.asc, if rate > 0 { rate } else { a.sample_rate }),C::Mp3 => Self::new(CODEC_TYPE_MP3, rate, None),C::Ac3 { .. } => Self::ac3(),C::Alac { cookie } => Self::new(CODEC_TYPE_ALAC, rate, Some(cookie.clone())),@@ -145,8 +147,11 @@ impl PacketDecoder {/// Decode one packet into planar channels.pub fn decode(&mut self, data: &[u8], ts: u64) -> Result<Vec<Vec<f32>>> {let dec = match &mut self.inner {- Inner::Aac { dec, .. } => {- let out = dec.decode(data).map_err(|e| CodecError::Decode(e.to_string()))?;+ Inner::Aac { dec, up, .. } => {+ let mut out = dec.decode(data).map_err(|e| CodecError::Decode(e.to_string()))?;+ if let Some(up) = up {+ out = up.process(out);+ }self.channels = out.len();return Ok(out);}@@ -202,10 +207,13 @@ impl PacketDecoder {}pub fn reset(&mut self) {match &mut self.inner {- Inner::Aac { dec, asc } => {+ Inner::Aac { dec, asc, up } => {if let Ok(d) = filmcraft_aac::Decoder::new(asc) {**dec = d;}+ if let Some(up) = up {+ up.reset();+ }}Inner::Opus { dec, .. } => dec.reset(),Inner::Symphonia(d) => d.reset(),@@ -215,6 +223,94 @@ impl PacketDecoder {}}+/// The output rate of an AAC stream: twice the core rate for HE-AAC (ISO/IEC 14496-3 §1.6.5).+/// Explicit signalling names the rate in the `AudioSpecificConfig`; with implicit signalling (an+/// AAC-LC config at 24 kHz or less) SBR is only visible as fill-element data in the access units,+/// so the first ones are decoded to look for it. `None` if `asc` is not one our decoder reads.+pub fn aac_output_rate<'a>(asc: &[u8], first_units: impl IntoIterator<Item = &'a [u8]>) -> Option<u32> {+ let mut dec = filmcraft_aac::Decoder::new(asc).ok()?;+ let core = dec.sample_rate();+ if let Some(ext) = dec.config().extension_sample_rate {+ return Some(ext);+ }+ if core <= 24_000 {+ for au in first_units {+ let _ = dec.decode(au);+ if dec.sbr() {+ return Some(core * 2);+ }+ }+ }+ Some(core)+}++/// Taps on each side of the interpolation point in [`Upsample2x`].+const UPSAMPLE_HALF: usize = 12;++/// 2× upsampler for HE-AAC. Our decoder reconstructs the AAC-LC core at half the output rate and+/// not yet the SBR high band, so the core is interpolated to the output rate: timing and pitch are+/// right and the band above the core's Nyquist stays empty. Even outputs are the input samples,+/// odd ones a Blackman-windowed sinc half-band interpolation over 2 × [`UPSAMPLE_HALF`] inputs.+/// The look-ahead delays the output by `UPSAMPLE_HALF` input samples (0.5 ms at 24 kHz); the+/// state carries across packets, so a seek primed with the preceding packet gives the same+/// samples as continuous decoding.+#[derive(Clone)]+pub struct Upsample2x {+ taps: [f32; 2 * UPSAMPLE_HALF],+ /// The last `2 × UPSAMPLE_HALF` input samples per channel.+ hist: Vec<Vec<f32>>,+}++impl Upsample2x {+ pub fn new(channels: usize) -> Self {+ let m = UPSAMPLE_HALF as f64;+ let mut taps = [0f32; 2 * UPSAMPLE_HALF];+ let mut sum = 0.0;+ for (k, t) in taps.iter_mut().enumerate() {+ // distance from the interpolation point (halfway between two inputs)+ let x = k as f64 - m + 0.5;+ let sinc = (std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x);+ let w = 0.42 + 0.5 * (std::f64::consts::PI * x / m).cos() + 0.08 * (2.0 * std::f64::consts::PI * x / m).cos();+ *t = (sinc * w) as f32;+ sum += sinc * w;+ }+ for t in &mut taps {+ *t = (*t as f64 / sum) as f32;+ }+ Self { taps, hist: vec![vec![0.0; 2 * UPSAMPLE_HALF]; channels] }+ }++ pub fn reset(&mut self) {+ for h in &mut self.hist {+ h.fill(0.0);+ }+ }++ pub fn process(&mut self, input: Vec<Vec<f32>>) -> Vec<Vec<f32>> {+ if self.hist.len() < input.len() {+ self.hist.resize(input.len(), vec![0.0; 2 * UPSAMPLE_HALF]);+ }+ let m = UPSAMPLE_HALF;+ input+ .into_iter()+ .zip(&mut self.hist)+ .map(|(x, hist)| {+ let mut buf = std::mem::take(hist);+ buf.extend_from_slice(&x);+ let mut out = Vec::with_capacity(x.len() * 2);+ // output pair i is centred on buf[i + m]: the sample itself, then the point halfway+ // to the next one from buf[i + 1 ..= i + 2m]+ for w in buf.windows(2 * m + 1).take(x.len()) {+ out.push(w[m]);+ out.push(w[1..].iter().zip(&self.taps).map(|(a, b)| a * b).sum());+ }+ *hist = buf.split_off(buf.len() - 2 * m);+ out+ })+ .collect()+ }+}+/// Whether AC-3 audio decodes (our ATSC A/52 decoder).pub const AC3_DECODER: bool = true;@@ -603,3 +699,43 @@ pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<std::result::Result<Shared}Some(AudioFileSource::decode(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))}++#[cfg(test)]+mod he_aac_tests {+ use super::*;++ /// AAC-LC config, 22.05 kHz stereo.+ const LC_22K: [u8; 2] = [0x13, 0x90];+ /// An access unit holding only a fill element with SBR data (ID_FIL, EXT_SBR_DATA, ID_END).+ const SBR_FILL: [u8; 3] = [0b1100_0011, 0b1010_0001, 0b1100_0000];++ #[test]+ fn output_rate_doubles_for_he_aac() {+ // explicit: the extension rate from the config+ assert_eq!(aac_output_rate(&[0x2B, 0x92, 0x08, 0x00], []), Some(44_100));+ // implicit: SBR data in the first access units of a ≤ 24 kHz AAC-LC stream+ assert_eq!(aac_output_rate(&LC_22K, [&SBR_FILL[..]]), Some(44_100));+ assert_eq!(aac_output_rate(&LC_22K, []), Some(22_050));+ // AAC-LC at 44.1 kHz stays as it is, even with SBR-looking fill data+ assert_eq!(aac_output_rate(&[0x12, 0x10], [&SBR_FILL[..]]), Some(44_100));+ }++ #[test]+ fn upsampler_interpolates_continuously_across_packets() {+ let f = 1000.0 / 22_050.0;+ let x: Vec<f32> = (0..4096).map(|i| (2.0 * std::f32::consts::PI * f * i as f32).sin()).collect();+ let mut up = Upsample2x::new(1);+ let mut y = Vec::new();+ for chunk in x.chunks(1024) {+ y.extend(up.process(vec![chunk.to_vec()]).remove(0));+ }+ assert_eq!(y.len(), 8192);+ // output 2k + 1 is input k − UPSAMPLE_HALF + ½ (the look-ahead delay), within 0.1 %+ let d = UPSAMPLE_HALF as f32;+ for k in 100..4000 {+ let want = (2.0 * std::f32::consts::PI * f * (k as f32 - d + 0.5)).sin();+ assert!((y[2 * k + 1] - want).abs() < 1e-3, "{k}: {} vs {want}", y[2 * k + 1]);+ assert_eq!(y[2 * k], x[k - UPSAMPLE_HALF]);+ }+ }+}diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rsindex 9820fbc87..7afe35227 100644--- a/crates/codecs/src/mp4.rs+++ b/crates/codecs/src/mp4.rs@@ -178,7 +178,16 @@ impl Mp4Source {let ap = entry.audio.clone().unwrap_or_default();let (rate, ch, bits) = match &entry.codec {CodecConfig::Aac(a) => (- if a.sample_rate > 0 { a.sample_rate } else { ap.sample_rate as u32 },+ {+ // HE-AAC plays at twice the core rate the AudioSpecificConfig starts with+ let units = t.samples.iter().take(8).filter_map(|x| filmcraft_media::reader::read_range(&*bytes.0, x.offset, x.size as usize).ok());+ let units: Vec<Vec<u8>> = units.collect();+ match crate::audio::aac_output_rate(&a.asc, units.iter().map(Vec::as_slice)) {+ Some(r) => r,+ None if a.sample_rate > 0 => a.sample_rate,+ None => ap.sample_rate as u32,+ }+ },if a.channel_config > 0 { a.channel_config as u32 } else { ap.channels },None,),@@ -604,3 +613,40 @@ mod tests {assert_eq!(s.info().video.as_ref().map(|v| (v.width, v.height)), Some((32, 64)));}}++#[cfg(test)]+mod he_aac_tests {+ use filmcraft_isobmff::{Brand, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};+ use filmcraft_media::MediaSource;++ /// #108: an HE-AAC MP4 (explicit SBR signalling, core 22.05 kHz, output 44.1 kHz, timescale+ /// 44.1 kHz) built here from our AAC-LC encoder: the stream has no SBR data, which only the+ /// high band would need. It was reported at the 22.05 kHz core rate, so sequences made from+ /// such a clip were created at 22.05 kHz.+ #[test]+ fn he_aac_plays_at_the_output_rate() {+ let core = 22_050u32;+ let n = core as usize * 2;+ let tone: Vec<f32> = (0..n).map(|i| 0.25 * (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / core as f32).sin()).collect();+ let mut enc = filmcraft_aac::Encoder::new(filmcraft_aac::EncoderConfig::cbr(core, 2, 64_000)).unwrap();+ let mut aus = enc.encode(&[&tone, &tone]);+ aus.extend(enc.flush());+ // AOT 5, core 22.05 kHz, stereo, extension 44.1 kHz, core AOT 2+ let asc = vec![0x2B, 0x92, 0x08, 0x00];+ let mut mux = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();+ let t = mux.add_track(TrackConfig::new(SampleEntry::aac(asc, 2, 44_100), 44_100)).unwrap();+ for au in &aus {+ mux.write_sample(t, WriteSample { data: au, duration: 2048, composition_offset: 0, is_sync: true }).unwrap();+ }+ let b = mux.finish().unwrap().into_inner();+ let src = super::Mp4Source::open("he.mp4", b.into()).unwrap();+ assert_eq!(src.info().audio.as_ref().unwrap().sample_rate, 44_100);+ // one second from 0.5 s at 44.1 kHz: the 1 kHz tone at its level (not silence, not shifted)+ let buf = src.audio(22_050, 44_100, 44_100).unwrap();+ let x = &buf.channels[0];+ let peak = x.iter().fold(0f32, |m, v| m.max(v.abs()));+ assert!((0.2..0.3).contains(&peak), "peak {peak}");+ let crossings = x.windows(2).filter(|w| w[0] < 0.0 && w[1] >= 0.0).count();+ assert!((995..=1005).contains(&crossings), "{crossings} Hz");+ }+}diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex 30a6d02cf..a46771fc4 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -616,7 +616,10 @@ impl AudioEncoder for AacEncoder {}fn aac_factory(_format: Format, sample_rate: u32, channels: u32, s: &ExportSettings) -> Option<Result<Box<dyn AudioEncoder>>> {- let bps = s.audio.bitrate_kbps.clamp(32, 512) * 1000;+ // AAC caps a frame at 6144 bits per channel (ISO/IEC 14496-3 §4.5.3.2): 6 bits per sample, so+ // 264.6 kbps for stereo at 22.05 kHz; a higher setting is capped instead of refused+ let max = (6 * sample_rate as u64 * channels.max(1) as u64).min(u32::MAX as u64) as u32;+ let bps = (s.audio.bitrate_kbps.clamp(32, 512) * 1000).min(max);Some(filmcraft_aac::Encoder::new(filmcraft_aac::EncoderConfig::cbr(sample_rate, channels as usize, bps)).map(|enc| Box::new(AacEncoder { enc, rate: sample_rate, channels }) as Box<dyn AudioEncoder>)diff --git a/crates/export/src/settings_tests.rs b/crates/export/src/settings_tests.rsindex 9904d3c3b..4a7562fee 100644--- a/crates/export/src/settings_tests.rs+++ b/crates/export/src/settings_tests.rs@@ -398,3 +398,15 @@ fn builtin_presets_are_valid_and_unique() {let back: ExportPreset = serde_json::from_value(json).unwrap();assert_eq!(back.settings.adaptive_bitrate, Some(0.2));}++/// #108: the default 320 kbps is more than AAC can carry in stereo at 22.05 kHz (6 bits per sample+/// and channel). The export failed with "bitrate out of range"; it is now capped to the limit.+#[test]+fn aac_bitrate_is_capped_for_low_sample_rates() {+ let mut s = ExportSettings::default();+ s.audio.bitrate_kbps = 320;+ for (rate, ch) in [(22_050, 2), (16_000, 2), (8_000, 6), (48_000, 2)] {+ let enc = aac_factory(Format::H264, rate, ch, &s).expect("AAC is always available");+ assert!(enc.is_ok(), "{rate} Hz × {ch}: {:?}", enc.err());+ }+}