Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

#922: eight-channel AAC reports and returns eight channels

JordyUSAd348dccd21a2
diff --git a/crates/aac/README.md b/crates/aac/README.md
index d2b7e63d3..ffd5bf571 100644
--- a/crates/aac/README.md
+++ b/crates/aac/README.md
@@ -48,6 +48,9 @@ from bitrate/quality), `tns`, `ms_stereo`, `window_shape` (sine/KBD), `adts` (pr
| 7 | 0 + PCE | C L R Ls Rs Cs LFE (PCE in the ASC; repeated in every AU when ADTS-framed) |
| 8 | 7 | C Lc Rc L R Ls Rs LFE |
+The decoder also reads configurations 11 (6.1: C L R Ls Rs Cs LFE) and 12 (7.1: C L R Ls Rs Lsr Rsr
+LFE) from ISO/IEC 14496-3 Amd 4; ffmpeg 9 writes 7.1 AAC as configuration 12.
+
`Decoder::layout()` reports the element layout (it follows a PCE for configuration 0).
## Encoder
diff --git a/crates/aac/src/config.rs b/crates/aac/src/config.rs
index d0da2f350..f0b326d0a 100644
--- a/crates/aac/src/config.rs
+++ b/crates/aac/src/config.rs
@@ -136,7 +136,8 @@ impl ProgramConfig {
}
}
-/// Element layout of `channelConfiguration` 1..=7 (tags as conventionally assigned).
+/// Element layout of `channelConfiguration` 1..=7, 11 and 12 (tags as conventionally assigned; 11 and
+/// 12 from ISO/IEC 14496-3 Amd 4: 6.1 with a back centre, 7.1 with back surrounds).
pub fn config_layout(channel_config: u8) -> Option<Vec<(ElementType, u8)>> {
use ElementType::*;
Some(match channel_config {
@@ -146,7 +147,8 @@ pub fn config_layout(channel_config: u8) -> Option<Vec<(ElementType, u8)>> {
4 => vec![(Sce, 0), (Cpe, 0), (Sce, 1)],
5 => vec![(Sce, 0), (Cpe, 0), (Cpe, 1)],
6 => vec![(Sce, 0), (Cpe, 0), (Cpe, 1), (Lfe, 0)],
- 7 => vec![(Sce, 0), (Cpe, 0), (Cpe, 1), (Cpe, 2), (Lfe, 0)],
+ 7 | 12 => vec![(Sce, 0), (Cpe, 0), (Cpe, 1), (Cpe, 2), (Lfe, 0)],
+ 11 => vec![(Sce, 0), (Cpe, 0), (Cpe, 1), (Sce, 1), (Lfe, 0)],
_ => return None,
})
}
@@ -388,6 +390,14 @@ mod tests {
assert_eq!(AudioSpecificConfig::parse(&a.to_bytes()).unwrap().channels(), 6);
}
+ #[test]
+ fn amd4_channel_configurations() {
+ // 6.1 and 7.1 back (#922); 22.2 and 7.1 with heights stay unsupported
+ let channels = |c| AudioSpecificConfig::parse(&AudioSpecificConfig::lc(3, c).to_bytes()).map(|a| a.channels()).ok();
+ assert_eq!([7, 11, 12].map(channels), [Some(8), Some(7), Some(8)]);
+ assert_eq!([13, 14].map(config_layout), [None, None]);
+ }
+
#[test]
fn asc_with_pce() {
let pce = ProgramConfig {
diff --git a/crates/codecs/src/audio.rs b/crates/codecs/src/audio.rs
index daba8f4cd..e0bc3f139 100644
--- a/crates/codecs/src/audio.rs
+++ b/crates/codecs/src/audio.rs
@@ -59,13 +59,16 @@ fn vorbis_to_wav_order(channels: usize) -> Option<&'static [usize]> {
/// Channel order for AAC surround (ISO/IEC 14496-3 Table 1.19, our decoder's element order: C, L R,
/// surrounds, LFE): output channel → decoded channel, giving the WAV/SMPTE order (L R C LFE Ls Rs)
/// used elsewhere, as the AC-3 decoder does and the AAC encoder's caller undoes on export. Only the
-/// unambiguous channel configurations 3–6; 1, 2, 7 and PCE layouts keep the decoded order.
+/// unambiguous channel configurations 3–6, 11 (6.1: … LFE, back centre, sides) and 12 (7.1: … LFE,
+/// backs, sides); 1, 2, 7 and PCE layouts keep the decoded order.
fn aac_to_wav_order(channel_config: u8) -> Option<&'static [usize]> {
Some(match channel_config {
3 => &[1, 2, 0],
4 => &[1, 2, 0, 3],
5 => &[1, 2, 0, 3, 4],
6 => &[1, 2, 0, 5, 3, 4],
+ 11 => &[1, 2, 0, 6, 5, 3, 4],
+ 12 => &[1, 2, 0, 7, 5, 6, 3, 4],
_ => return None,
})
}
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index c7ea9d069..2f43bce00 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -540,7 +540,8 @@ fn audio_stream_info(t: &filmcraft_isobmff::Track, bytes: &crate::Src) -> Option
None => ap.sample_rate as u32,
}
},
- if a.channel_config > 0 { a.channel_config as u32 } else { ap.channels },
+ // the configuration is an index (7 and 12 are both eight channels), not a count
+ if a.channels() > 0 { a.channels() } else { ap.channels },
None,
),
CodecConfig::Pcm(p) => (p.sample_rate as u32, p.channels, Some(p.bits as u32)),
diff --git a/crates/codecs/tests/aac_channels_oracle.rs b/crates/codecs/tests/aac_channels_oracle.rs
new file mode 100644
index 000000000..5f850ac3e
--- /dev/null
+++ b/crates/codecs/tests/aac_channels_oracle.rs
@@ -0,0 +1,108 @@
+//! Multichannel AAC in MP4 against ffmpeg (#922). The AudioSpecificConfig's channel configuration
+//! is an index into ISO/IEC 14496-3 Table 1.19 (with Amd 4), not a channel count: 7 and 12 are
+//! both 7.1 (eight channels) and 11 is 6.1 (seven). Each channel carries its own tone, so a
+//! dropped or swapped channel shows up against ffmpeg's decode.
+
+mod common;
+
+use std::io::Cursor;
+
+use common::*;
+use filmcraft_isobmff::{Brand, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
+
+const RATE: u32 = 48_000;
+
+/// A one-second AAC MP4 of `layout` (`n` channels), channel `i` a tone of 200 + 100·i Hz, except
+/// the LFE (fourth in all these layouts) at 60 Hz: AAC band-limits it.
+fn tones(ff: &std::path::Path, name: &str, layout: &str, n: usize) -> Option<std::path::PathBuf> {
+ let mut graph: String =
+ (0..n).map(|i| format!("sine=frequency={}:sample_rate={RATE}:duration=1[a{i}];", if i == 3 { 60 } else { 200 + 100 * i })).collect();
+ graph.extend((0..n).map(|i| format!("[a{i}]")));
+ graph.push_str(&format!("join=inputs={n}:channel_layout={layout}[out]"));
+ fixture(ff, name, &["-filter_complex", &graph, "-map", "[out]", "-c:a", "aac", "-b:a", "512k"])
+}
+
+/// The AAC access units of `path`'s audio track, rewrapped in a new MP4 whose AudioSpecificConfig
+/// says `channel_config` (AAC LC, 48 kHz), keeping each sample's duration and the priming edit.
+fn rewrap(path: &std::path::Path, name: &str, channel_config: u8, channels: u32) -> std::path::PathBuf {
+ let data = bytes(path);
+ let file = filmcraft_isobmff::open(&data).unwrap();
+ let track = file.tracks.iter().find(|t| t.kind == filmcraft_isobmff::TrackKind::Audio).unwrap();
+ // object type 2, rate index 3 (48 kHz), then the configuration
+ let asc = (((2u16 << 11) | (3 << 7) | ((channel_config as u16) << 3)).to_be_bytes()).to_vec();
+ let mut mux = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
+ let id = mux.add_track(TrackConfig::new(SampleEntry::aac(asc, channels, RATE), RATE)).unwrap();
+ for s in &track.samples {
+ let au = &data[s.offset as usize..s.offset as usize + s.size as usize];
+ mux.write_sample(id, WriteSample { data: au, duration: s.duration, composition_offset: 0, is_sync: true }).unwrap();
+ }
+ let out = dir().join(name);
+ std::fs::write(&out, mux.finish().unwrap().into_inner()).unwrap();
+ out
+}
+
+/// Our decode of the whole file, channel by channel.
+fn ours(path: &std::path::Path, name: &str) -> (u32, Vec<Vec<f32>>) {
+ let src = filmcraft_codecs::open_bytes(name, bytes(path)).unwrap();
+ let ch = src.info().audio().map(|a| a.channels).unwrap();
+ (ch, src.audio(0, RATE as usize * 9 / 10, RATE).unwrap().channels)
+}
+
+/// ffmpeg's decode, deinterleaved into `n` channels.
+fn theirs(ff: &std::path::Path, path: &std::path::Path, n: usize) -> Vec<Vec<f32>> {
+ let all = ffmpeg_audio_f32(ff, path, &[]);
+ (0..n).map(|c| all.iter().skip(c).step_by(n).copied().collect()).collect()
+}
+
+/// Largest sample difference over the first `len` samples, best over a small lag either way (the
+/// two decoders may place the priming differently by a few samples).
+fn diff(a: &[f32], b: &[f32]) -> f32 {
+ let len = a.len().min(b.len()).saturating_sub(64);
+ (0..=32).flat_map(|l| [(l, 0), (0, l)]).map(|(x, y)| (32..len).map(|i| (a[i + x] - b[i + y]).abs()).fold(0.0, f32::max)).fold(f32::MAX, f32::min)
+}
+
+fn peak(x: &[f32]) -> f32 {
+ x.iter().fold(0.0, |m, v| m.max(v.abs()))
+}
+
+#[test]
+fn aac_channel_configurations_report_and_decode_every_channel() {
+ let ff = filmcraft_testkit::require_ffmpeg!();
+ // ffmpeg 8 writes 7.1 as configuration 7 and ffmpeg 9 as 12: the same five elements
+ let Some(seven) = tones(&ff, "aac_71.mp4", "7.1", 8) else {
+ eprintln!("SKIPPED: this ffmpeg can't encode 7.1 AAC");
+ return;
+ };
+ let asc = filmcraft_isobmff::open(bytes(&seven)).unwrap().tracks.iter().find_map(|t| match &t.entries.first()?.codec {
+ filmcraft_isobmff::CodecConfig::Aac(a) => Some(a.channel_config),
+ _ => None,
+ });
+ let twelve = match asc {
+ Some(7) => rewrap(&seven, "aac_71_cfg12.mp4", 12, 8),
+ Some(12) => seven.clone(),
+ other => panic!("ffmpeg wrote 7.1 AAC as configuration {other:?}"),
+ };
+ let seven = if asc == Some(7) { seven } else { rewrap(&seven, "aac_71_cfg7.mp4", 7, 8) };
+
+ // configuration 7: eight channels reported and returned, the last one too
+ let (ch, got) = ours(&seven, "aac_71_cfg7.mp4");
+ assert_eq!((ch, got.len()), (8, 8), "configuration 7");
+ assert!(got.iter().all(|c| peak(c) > 0.05), "configuration 7: a silent channel");
+
+ // configuration 12 (7.1 back): decoded, in ffmpeg's (and WAV's) L R C LFE Lb Rb Ls Rs order
+ let (ch, got) = ours(&twelve, "aac_71_cfg12.mp4");
+ assert_eq!((ch, got.len()), (8, 8), "configuration 12");
+ let want = theirs(&ff, &twelve, 8);
+ for (c, (a, b)) in got.iter().zip(&want).enumerate() {
+ let d = diff(a, b);
+ println!("configuration 12, channel {c}: peak {:.3}, max |ours - ffmpeg| {d:.5}", peak(a));
+ assert!(peak(a) > 0.05 && d < 0.01, "configuration 12, channel {c}: off ffmpeg's decode by {d}");
+ }
+
+ // controls: 5.1 (configuration 6) and 6.1 (ffmpeg writes a PCE)
+ for (layout, n, name) in [("5.1", 6, "aac_51.mp4"), ("6.1", 7, "aac_61.mp4")] {
+ let path = tones(&ff, name, layout, n).unwrap();
+ let (ch, got) = ours(&path, name);
+ assert_eq!((ch as usize, got.len()), (n, n), "{layout}");
+ }
+}
diff --git a/crates/isobmff/src/codec.rs b/crates/isobmff/src/codec.rs
index 6d2ff79b2..7050f74c8 100644
--- a/crates/isobmff/src/codec.rs
+++ b/crates/isobmff/src/codec.rs
@@ -569,11 +569,15 @@ impl AacConfig {
let (object_type, sample_rate, channel_config) = parse_asc(&asc).unwrap_or((0, 0, 0));
AacConfig { asc, object_type, sample_rate, channel_config, max_bitrate: 0, avg_bitrate: 0, buffer_size: 0 }
}
- /// Channel count implied by the channel configuration (0 if unspecified).
+ /// Channel count implied by the channel configuration (ISO/IEC 14496-3 Table 1.19 with Amd 4:
+ /// 7 and 12 are 7.1 front / back, 11 is 6.1, 13 is 22.2, 14 is 7.1 with front heights), 0 if
+ /// unspecified (a PCE) or reserved.
pub fn channels(&self) -> u32 {
match self.channel_config {
1..=6 => self.channel_config as u32,
- 7 => 8,
+ 11 => 7,
+ 7 | 12 | 14 => 8,
+ 13 => 24,
_ => 0,
}
}
@@ -1632,6 +1636,13 @@ mod tests {
assert_eq!(OpusConfig::parse(&o.to_bytes()).unwrap(), o);
}
+ #[test]
+ fn aac_channel_configuration_is_an_index() {
+ // 48 kHz AAC LC: configuration → channels (Table 1.19 with Amd 4; #922)
+ let channels = |c: u16| AacConfig::from_asc(((2 << 11) | (3 << 7) | (c << 3)).to_be_bytes().to_vec()).channels();
+ assert_eq!([0, 1, 6, 7, 8, 11, 12, 13, 14, 15].map(channels), [0, 1, 6, 8, 0, 7, 8, 24, 8, 0]);
+ }
+
#[test]
fn aac_esds_roundtrip() {
let e = SampleEntry::aac(vec![0x12, 0x10], 2, 44100);