forge
Explore
Log in

Don't you dare go Hollow

AC3 tracks decode with a built-in stereo downmix

Browse files at this commit

8c7bf808ae19e1655737ac07a94de22b5002565fAhmet Kaan GümüşParent: 951c3fc
  • feat
    • AC3 tracks decode with a built-in stereo downmix
Show full message
✨ feat(audio): AC3 tracks decode with a built-in stereo downmix
Cargo.lockmodified+22 -0
@@ -1634,6 +1634,8 @@ dependencies = [
1634 "hound",1634 "hound",
1635 "libloading",1635 "libloading",
1636 "mp4",1636 "mp4",
1637+ "oxideav-ac3",
1638+ "oxideav-core",
1637 "rusty_h264",1639 "rusty_h264",
1638 "symphonia",1640 "symphonia",
1639 "symphonia-codec-aac",1641 "symphonia-codec-aac",
@@ -3924,6 +3926,26 @@ dependencies = [
3924 "pin-project-lite",3926 "pin-project-lite",
3925 ]3927 ]
3926 3928
3929+[[package]]
3930+name = "oxideav-ac3"
3931+version = "0.0.10"
3932+source = "registry+https://github.com/rust-lang/crates.io-index"
3933+checksum = "4c60744c9688507efb6849b1bff197fb17e742b56f8a7f914129464bc86197ad"
3934+dependencies = [
3935+ "oxideav-core",
3936+]
3937+
3938+[[package]]
3939+name = "oxideav-core"
3940+version = "0.1.34"
3941+source = "registry+https://github.com/rust-lang/crates.io-index"
3942+checksum = "5a68d9a74d6d0a7373589eca0c0bb8ab380c46fd1d7fc807e696d716cdad078c"
3943+dependencies = [
3944+ "bytemuck",
3945+ "serde_json",
3946+ "thiserror 2.0.20",
3947+]
3948+
3927 [[package]]3949 [[package]]
3928 name = "parking"3950 name = "parking"
3929 version = "2.2.1"3951 version = "2.2.1"
crates/app/src/main.rsmodified+3 -3
@@ -3826,9 +3826,9 @@ fn layout(channels: u16) -> Option<String> {
3826 /// picker that hides them is a picker that lies.3826 /// picker that hides them is a picker that lies.
3827 fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<String> {3827 fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<String> {
3828 if !info.decodable {3828 if !info.decodable {
3829- // ponytail: mp4 0.14 keeps no fourcc for a sample entry it does not3829+ // AAC and AC-3 name themselves (`StreamInfo::codec`, which reads the
3830- // parse (`StreamInfo::codec`), so an AC-3 track can only be named as3830+ // stsd fourcc by hand); anything else mp4 0.14 does not parse has no
3831- // unsupported, not as AC-3. Upgrade path is reading the stsd ourselves.3831+ // name to give, and a row with no name still says why it is greyed.
3832 return Some(match info.codec.as_str() {3832 return Some(match info.codec.as_str() {
3833 "unknown" => "unsupported codec".to_string(),3833 "unknown" => "unsupported codec".to_string(),
3834 codec => format!("{codec} is not supported"),3834 codec => format!("{codec} is not supported"),
crates/engine/Cargo.tomlmodified+2 -0
@@ -35,3 +35,5 @@ symphonia = { version = "0.6", default-features = false, features = [
35 "vorbis",35 "vorbis",
36 "wav",36 "wav",
37 ] }37 ] }
38+oxideav-ac3 = "=0.0.10"
39+oxideav-core = "0.1.34"
crates/engine/src/audio.rsmodified+294 -11
@@ -2,11 +2,14 @@
2 //! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own2 //! interleaved f32 over a bounded channel, same shape as `decode`. Uses its own
3 //! reader so the video demuxer stays single-owner.3 //! reader so the video demuxer stays single-owner.
4 //!4 //!
5-//! Two readers, one output. An mp4 goes through `mp4`+`symphonia-codec-aac` as5+//! Three readers, one output. An mp4 goes through `mp4`+`symphonia-codec-aac` as
6 //! it always has -- that path also yields the raw access units the export6 //! it always has -- that path also yields the raw access units the export
7 //! copies, which is the only reason it is kept separate -- and a standalone7 //! copies, which is the only reason it is kept separate -- and a standalone
8 //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through8 //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through
9-//! symphonia's own format probe. Everything downstream of [`Track`] sees the9+//! symphonia's own format probe. An mp4's **AC-3** track is the third: the same
10+//! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the
11+//! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo
12+//! timeline. Everything downstream of [`Track`] sees the
10 //! same samples either way; only the packet copy asks which reader it came from,13 //! same samples either way; only the packet copy asks which reader it came from,
11 //! because there is nothing to copy out of an mp3 that an mp4 can hold.14 //! because there is nothing to copy out of an mp3 that an mp4 can hold.
12 //!15 //!
@@ -27,6 +30,7 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
27 use std::thread;30 use std::thread;
28 31
29 use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType};32 use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType};
33+use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet};
30 use symphonia_codec_aac::AacDecoder;34 use symphonia_codec_aac::AacDecoder;
31 use symphonia_core::codecs::audio::{35 use symphonia_core::codecs::audio::{
32 AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC,36 AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC,
@@ -59,6 +63,14 @@ const PRE_ROLL: u32 = 2;
59 /// Frames per channel one AAC-LC packet carries. Fixed by the codec.63 /// Frames per channel one AAC-LC packet carries. Fixed by the codec.
60 const SAMPLES_PER_PACKET: u32 = 1024;64 const SAMPLES_PER_PACKET: u32 = 1024;
61 65
66+/// Frames per channel one AC-3 syncframe carries. Fixed by the codec (6 blocks
67+/// of 256), the way 1024 is fixed for AAC-LC.
68+const AC3_SAMPLES_PER_FRAME: u32 = 1536;
69+
70+/// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the
71+/// 256-sample overlap-add the target frame is reconstructed with.
72+const AC3_PRE_ROLL: u32 = 1;
73+
62 /// Frames per channel a seek into a standalone audio file lands ahead of the74 /// Frames per channel a seek into a standalone audio file lands ahead of the
63 /// window, decoded and thrown away: enough to refill an mp3's bit reservoir75 /// window, decoded and thrown away: enough to refill an mp3's bit reservoir
64 /// (a frame is 1152 samples and the reservoir reaches back two of them) at any76 /// (a frame is 1152 samples and the reservoir reaches back two of them) at any
@@ -493,14 +505,35 @@ impl AudioSession {
493 .map(|(index, id)| {505 .map(|(index, id)| {
494 let track = &reader.tracks()[&id];506 let track = &reader.tracks()[&id];
495 let aac = matches!(track.media_type(), Ok(MediaType::AAC));507 let aac = matches!(track.media_type(), Ok(MediaType::AAC));
508+ // An AC-3 track describes itself through its own reader: mp4
509+ // 0.14 parses no sample entry for it, so `channel_config` and
510+ // `sample_freq_index` have nothing to say. What is listed is
511+ // the *decoded* shape -- stereo, because that is what the §7.8
512+ // downmix hands the timeline (see [`Ac3Track`]).
513+ let ac3 = (!aac)
514+ .then(|| Ac3Track::open(path, index).ok().flatten())
515+ .flatten();
496 let lang = track.language();516 let lang = track.language();
497 StreamInfo {517 StreamInfo {
498 index,518 index,
499- codec: if aac { "aac" } else { "unknown" }.into(),519+ codec: match (aac, &ac3) {
500- channels: track.channel_config().map_or(0, channel_count),520+ (true, _) => "aac",
501- sample_rate: track.sample_freq_index().map_or(0, |f| f.freq()),521+ (_, Some(_)) => "ac-3",
522+ _ => "unknown",
523+ }
524+ .into(),
525+ channels: ac3
526+ .as_ref()
527+ .map_or_else(|| track.channel_config().map_or(0, channel_count), |t| {
528+ t.channels
529+ }),
530+ sample_rate: ac3.as_ref().map_or_else(
531+ || track.sample_freq_index().map_or(0, |f| f.freq()),
532+ |t| t.sample_rate,
533+ ),
502 lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()),534 lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()),
503- decodable: aac535+ decodable: ac3.as_ref().is_some_and(|t| matches!(t.channels, 1 | 2))
536+ || aac
504 && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity))537 && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity))
505 && matches!(538 && matches!(
506 track.channel_config(),539 track.channel_config(),
@@ -732,15 +765,24 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
732 match Track::open(path, stream)? {765 match Track::open(path, stream)? {
733 None => Ok(None),766 None => Ok(None),
734 Some(Track::Aac(track)) => Ok(Some(track)),767 Some(Track::Aac(track)) => Ok(Some(track)),
735- Some(Track::Sym(track)) => Err(format!(768+ Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)),
736- "export needs AAC audio today; {} is {}",769+ // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
770+ // sample table can hold, and there is no AAC encoder here to turn it
771+ // into one. A WAV/FLAC export of the same timeline decodes fine.
772+ Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")),
773+ }
774+}
775+
776+/// The one wording for "this source's audio cannot be copied into an mp4",
777+/// shared by every format that cannot be: a front-end shows it verbatim.
778+fn uncopyable(path: &Path, codec: &str) -> crate::Error {
779+ format!(
780+ "export needs AAC audio today; {} is {codec}",
737 path.file_name()781 path.file_name()
738 .unwrap_or(path.as_os_str())782 .unwrap_or(path.as_os_str())
739 .to_string_lossy(),783 .to_string_lossy(),
740- track.codec
741 )784 )
742- .into()),785+ .into()
743- }
744 }786 }
745 787
746 /// One source's audio, however it is stored: the mp4 AAC track the export can788 /// One source's audio, however it is stored: the mp4 AAC track the export can
@@ -748,6 +790,7 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
748 /// the worker speak to this, never to either reader directly.790 /// the worker speak to this, never to either reader directly.
749 enum Track {791 enum Track {
750 Aac(AacTrack),792 Aac(AacTrack),
793+ Ac3(Ac3Track),
751 Sym(SymTrack),794 Sym(SymTrack),
752 }795 }
753 796
@@ -773,6 +816,15 @@ impl Track {
773 return Ok(None);816 return Ok(None);
774 }817 }
775 let audio_file = crate::is_audio(path);818 let audio_file = crate::is_audio(path);
819+ // Ahead of the AAC reader, because that one answers "not AAC" for a
820+ // *named* stream with an `Err` and an AC-3 track is not an error any
821+ // more. `Ok(None)` here means "not an AC-3 track", so every other file
822+ // falls through to exactly the reader it always used.
823+ if !audio_file
824+ && let Some(track) = Ac3Track::open(path, stream)?
825+ {
826+ return Ok(Some(Self::Ac3(track)));
827+ }
776 match AacTrack::open(path, stream) {828 match AacTrack::open(path, stream) {
777 Ok(Some(track)) => return Ok(Some(Self::Aac(track))),829 Ok(Some(track)) => return Ok(Some(Self::Aac(track))),
778 Ok(None) if !audio_file => return Ok(None),830 Ok(None) if !audio_file => return Ok(None),
@@ -788,6 +840,7 @@ impl Track {
788 fn sample_rate(&self) -> u32 {840 fn sample_rate(&self) -> u32 {
789 match self {841 match self {
790 Self::Aac(t) => t.sample_rate,842 Self::Aac(t) => t.sample_rate,
843+ Self::Ac3(t) => t.sample_rate,
791 Self::Sym(t) => t.sample_rate,844 Self::Sym(t) => t.sample_rate,
792 }845 }
793 }846 }
@@ -797,6 +850,12 @@ impl Track {
797 fn channels(&self) -> crate::Result<u16> {850 fn channels(&self) -> crate::Result<u16> {
798 match self {851 match self {
799 Self::Aac(t) => t.channels(),852 Self::Aac(t) => t.channels(),
853+ // Already downmixed: `channels` is what comes *out* of the decoder,
854+ // which is 2 for everything from mono to 5.1 (see [`Ac3Track`]).
855+ Self::Ac3(t) => match t.channels {
856+ 1 | 2 => Ok(t.channels),
857+ n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
858+ },
800 Self::Sym(t) => match t.channels {859 Self::Sym(t) => match t.channels {
801 1 | 2 => Ok(t.channels),860 1 | 2 => Ok(t.channels),
802 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),861 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
@@ -808,6 +867,7 @@ impl Track {
808 fn total_samples(&self) -> Option<u64> {867 fn total_samples(&self) -> Option<u64> {
809 match self {868 match self {
810 Self::Aac(t) => t.total_samples,869 Self::Aac(t) => t.total_samples,
870+ Self::Ac3(t) => t.total_samples,
811 Self::Sym(t) => t.total_samples,871 Self::Sym(t) => t.total_samples,
812 }872 }
813 }873 }
@@ -816,6 +876,7 @@ impl Track {
816 fn priming(&self) -> u64 {876 fn priming(&self) -> u64 {
817 match self {877 match self {
818 Self::Aac(t) => t.priming,878 Self::Aac(t) => t.priming,
879+ Self::Ac3(t) => t.priming,
819 Self::Sym(t) => t.priming,880 Self::Sym(t) => t.priming,
820 }881 }
821 }882 }
@@ -825,6 +886,7 @@ impl Track {
825 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {886 fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
826 match self {887 match self {
827 Self::Aac(t) => t.segment(source, start_secs, end_secs),888 Self::Aac(t) => t.segment(source, start_secs, end_secs),
889+ Self::Ac3(t) => t.segment(source, start_secs, end_secs),
828 Self::Sym(t) => {890 Self::Sym(t) => {
829 let media_target = t.media(start_secs);891 let media_target = t.media(start_secs);
830 Segment {892 Segment {
@@ -845,6 +907,9 @@ impl Track {
845 Self::Aac(t) => {907 Self::Aac(t) => {
846 AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;908 AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;
847 }909 }
910+ Self::Ac3(t) => {
911+ ac3_decoder(t.requested)?;
912+ }
848 Self::Sym(t) => {913 Self::Sym(t) => {
849 t.decoder()?;914 t.decoder()?;
850 }915 }
@@ -945,6 +1010,159 @@ impl SymTrack {
945 }1010 }
946 }1011 }
947 1012
1013+/// One source's AC-3 track: the same mp4 sample tables the AAC track is read
1014+/// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder
1015+/// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and
1016+/// one timeline layout is all there is. A 5.1 BluRay track therefore arrives
1017+/// here as an ordinary stereo source, and its rows in the picker say so.
1018+///
1019+/// `channels` is what the decoder actually emitted for the first frame rather
1020+/// than an assumed 2: everything from mono to 5.1 downmixes to stereo, but a 2.1
1021+/// stream is a passthrough the library leaves at 3, and that is refused by name
1022+/// in [`Track::channels`] instead of being mislabelled.
1023+struct Ac3Track {
1024+ reader: Mp4Reader<BufReader<File>>,
1025+ track_id: u32,
1026+ sample_count: u32,
1027+ sample_rate: u32,
1028+ channels: u16,
1029+ timescale: u32,
1030+ priming: u64,
1031+ total_samples: Option<u64>,
1032+ stts: Vec<(u32, u32)>,
1033+ /// What the decoder is asked to hand out, from this track's own layout:
1034+ /// `Some(2)` for anything with more than one front channel, `None` — the
1035+ /// library's passthrough — for a mono track. See [`ac3_decoder`].
1036+ requested: Option<u16>,
1037+}
1038+
1039+impl Ac3Track {
1040+ /// The `stream`-th audio track of `path` when it is AC-3, `Ok(None)` when it
1041+ /// is anything else (including out of range) — the caller then goes on to
1042+ /// the AAC reader, which owns those verdicts and their wording.
1043+ ///
1044+ /// mp4 0.14 parses `mp4a` sample entries and drops every other kind without
1045+ /// keeping the fourcc, so what the track *is* comes out of the `stsd` by
1046+ /// hand ([`crate::demux::sample_entry`]); the rate and the channel count
1047+ /// come out of the first syncframe, which is where AC-3 states them.
1048+ fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
1049+ let file = File::open(path)?;
1050+ let size = file.metadata()?.len();
1051+ let mut reader = Mp4Reader::read_header(BufReader::new(file), size)?;
1052+ let ids = audio_track_ids(&reader);
1053+ let Some(&track_id) = ids.get(stream) else {
1054+ return Ok(None);
1055+ };
1056+ if !matches!(crate::demux::sample_entry(path, track_id), Ok((kind, _)) if &kind == b"ac-3")
1057+ {
1058+ return Ok(None);
1059+ }
1060+ let track = &reader.tracks()[&track_id];
1061+ let timescale = track.timescale();
1062+ let duration = track.trak.mdia.mdhd.duration;
1063+ let edit = edit_media_time(track);
1064+ let stts: Vec<(u32, u32)> = stts_pairs(track).collect();
1065+ let sample_count = reader.sample_count(track_id)?;
1066+
1067+ let first = reader
1068+ .read_sample(track_id, 1)?
1069+ .ok_or("the AC-3 track has no samples")?;
1070+ let sample_rate = oxideav_ac3::syncinfo::parse(&first.bytes)
1071+ .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?
1072+ .sample_rate;
1073+ let nfchans = oxideav_ac3::bsi::parse(first.bytes.get(5..).unwrap_or_default())
1074+ .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?
1075+ .nfchans;
1076+ let requested = (nfchans > 1).then_some(2);
1077+ let mut decoder = ac3_decoder(requested)?;
1078+ let channels = decode_ac3(&mut decoder, &first.bytes)?
1079+ .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16)
1080+ .filter(|&c| c > 0)
1081+ .ok_or("the first AC-3 syncframe decoded to nothing")?;
1082+
1083+ // No encoder delay in AC-3; a remux that writes an edit list is still
1084+ // honoured, exactly as the AAC track honours it.
1085+ let priming = edit
1086+ .and_then(|t| scale(t, sample_rate, timescale))
1087+ .unwrap_or(0);
1088+ Ok(Some(Self {
1089+ track_id,
1090+ sample_count,
1091+ sample_rate,
1092+ channels,
1093+ timescale,
1094+ priming,
1095+ total_samples: scale(duration, sample_rate, timescale)
1096+ .map(|d| d.saturating_sub(priming)),
1097+ stts,
1098+ requested,
1099+ reader,
1100+ }))
1101+ }
1102+
1103+ /// `secs` on this source's audible timeline into media samples.
1104+ fn media(&self, secs: f64) -> u64 {
1105+ ((secs * f64::from(self.sample_rate)) as u64).saturating_add(self.priming)
1106+ }
1107+
1108+ /// One `[start, end)` window, resolved to syncframes and media samples —
1109+ /// [`AacTrack::segment`] with AC-3's own frame length and pre-roll.
1110+ fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1111+ let media_target = self.media(start_secs);
1112+ let target_ts = unscale(media_target, self.sample_rate, self.timescale);
1113+ let (start_id, start_ts) = packet_at(self.stts.iter().copied(), target_ts, AC3_PRE_ROLL);
1114+ Segment {
1115+ source: Some(source),
1116+ start_id,
1117+ start_pos: scale(start_ts, self.sample_rate, self.timescale).unwrap_or(0),
1118+ media_target,
1119+ media_end: self.media(end_secs).max(media_target),
1120+ }
1121+ }
1122+}
1123+
1124+/// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own
1125+/// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a
1126+/// 5.1 track at all. Fresh per segment for the same reason every other decoder
1127+/// here is: a seek leaves overlap-add state belonging to the frames we skipped.
1128+///
1129+/// ponytail: `Some(2)` on a **mono** (`acmod` 1/0) source decodes to digital
1130+/// silence in oxideav-ac3 0.0.10 — measured, 5.1 and stereo are correct — so a
1131+/// mono track asks for no downmix at all and stays the mono source it is. The
1132+/// upgrade path is `Some(2)` unconditionally once the library duplicates the
1133+/// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change.
1134+fn ac3_decoder(channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> {
1135+ let mut registry = CodecRegistry::new();
1136+ oxideav_ac3::register_codecs(&mut registry);
1137+ let mut params = CodecParameters::audio(CodecId::new("ac3"));
1138+ params.channels = channels;
1139+ registry
1140+ .first_decoder(&params)
1141+ .map_err(|e| format!("no AC-3 decoder: {e:?}").into())
1142+}
1143+
1144+/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the
1145+/// decoder wants more input before it can hand a frame back, which is not an
1146+/// error. The library speaks S16 little-endian; `/32768` is the whole
1147+/// conversion, and it lands in the `[-1, 1)` every other reader here emits.
1148+fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> crate::Result<Option<Vec<f32>>> {
1149+ let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec());
1150+ decoder
1151+ .send_packet(&packet)
1152+ .map_err(|e| format!("AC-3 decode failed: {e:?}"))?;
1153+ match decoder.receive_frame() {
1154+ Ok(Frame::Audio(audio)) => Ok(Some(
1155+ audio.data[0]
1156+ .chunks_exact(2)
1157+ .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0)
1158+ .collect(),
1159+ )),
1160+ Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()),
1161+ Err(oxideav_core::Error::NeedMore) => Ok(None),
1162+ Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()),
1163+ }
1164+}
1165+
948 /// One source's AAC track, resolved once: the reader plus everything the header1166 /// One source's AAC track, resolved once: the reader plus everything the header
949 /// has to say about it. `stts` is copied out because every other field would1167 /// has to say about it. `stts` is copied out because every other field would
950 /// otherwise keep a borrow alive on the reader the worker needs mutably — a real1168 /// otherwise keep a borrow alive on the reader the worker needs mutably — a real
@@ -1416,6 +1634,12 @@ fn run(mut w: Worker) {
1416 }1634 }
1417 continue;1635 continue;
1418 }1636 }
1637+ Track::Ac3(track) => {
1638+ if !run_ac3(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) {
1639+ return; // consumer went away
1640+ }
1641+ continue;
1642+ }
1419 Track::Aac(track) => track,1643 Track::Aac(track) => track,
1420 };1644 };
1421 let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())1645 let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())
@@ -1523,6 +1747,65 @@ fn emit(
1523 tx.send(chunk).is_ok()1747 tx.send(chunk).is_ok()
1524 }1748 }
1525 1749
1750+/// One segment of an AC-3 track: the AAC loop with AC-3's decoder. Sample ids
1751+/// come out of the same mp4 tables, the window rules are [`emit`]'s as always,
1752+/// and what reaches the mixer is already the stereo downmix. `false` means the
1753+/// consumer went away.
1754+fn run_ac3(
1755+ track: &mut Ac3Track,
1756+ seg: &Segment,
1757+ mut eq: Option<&mut EqState>,
1758+ channels: usize,
1759+ timeline: &mut u64,
1760+ tx: &SyncSender<AudioChunk>,
1761+) -> bool {
1762+ let mut decoder = match ac3_decoder(track.requested) {
1763+ Ok(decoder) => decoder,
1764+ Err(e) => {
1765+ eprintln!("audio decoder init failed: {e}");
1766+ return true;
1767+ }
1768+ };
1769+ let mut pos = seg.start_pos;
1770+ for id in seg.start_id..=track.sample_count {
1771+ let mut interleaved;
1772+ if pos >= seg.media_end {
1773+ return true; // segment done, on to the next one
1774+ }
1775+ let sample = match track.reader.read_sample(track.track_id, id) {
1776+ Ok(Some(sample)) => sample,
1777+ Ok(None) => return true,
1778+ Err(e) => {
1779+ eprintln!("audio demux error at sample {id}: {e}");
1780+ return true;
1781+ }
1782+ };
1783+ match decode_ac3(&mut decoder, &sample.bytes) {
1784+ Ok(Some(pcm)) => interleaved = pcm,
1785+ Ok(None) => continue, // the decoder wants another frame first
1786+ Err(e) => {
1787+ eprintln!("audio decode error at sample {id}: {e}");
1788+ return true;
1789+ }
1790+ }
1791+ let next = pos + (interleaved.len() / channels) as u64;
1792+ if !emit(
1793+ &mut interleaved,
1794+ channels,
1795+ seg,
1796+ eq.as_deref_mut(),
1797+ pos,
1798+ next,
1799+ timeline,
1800+ tx,
1801+ ) {
1802+ return false;
1803+ }
1804+ pos = next;
1805+ }
1806+ true
1807+}
1808+
1526 /// One segment of a standalone audio file: seek the reader to just before the1809 /// One segment of a standalone audio file: seek the reader to just before the
1527 /// window, then decode forward until the window is filled.1810 /// window, then decode forward until the window is filled.
1528 ///1811 ///
crates/engine/src/demux.rsmodified+3 -2
@@ -876,8 +876,9 @@ fn hvcc_record(path: &Path, track_id: u32) -> crate::Result<Vec<u8>> {
876 /// entry's payload. Read by hand for the same reason the record above is: the876 /// entry's payload. Read by hand for the same reason the record above is: the
877 /// crate keeps no fourcc for a sample entry it does not recognise, so this is877 /// crate keeps no fourcc for a sample entry it does not recognise, so this is
878 /// the only thing that can tell an `hvc1` track from a track in a codec nothing878 /// the only thing that can tell an `hvc1` track from a track in a codec nothing
879-/// here reads.879+/// here reads. Shared with `audio`, which asks it the same question of a `soun`
880-fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec<u8>)> {880+/// track: `mp4a` or the `ac-3` the crate drops on the floor.
881+pub(crate) fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4], Vec<u8>)> {
881 let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?;882 let moov = read_top_level(path, b"moov")?.ok_or("no moov box in file")?;
882 let trak = boxes(&moov)883 let trak = boxes(&moov)
883 .filter(|(kind, _)| *kind == b"trak")884 .filter(|(kind, _)| *kind == b"trak")
crates/engine/src/waveform.rsmodified+4 -2
@@ -165,7 +165,9 @@ mod tests {
165 // that is what this refuses.165 // that is what this refuses.
166 assert_ne!(zero, one, "both streams drew the same envelope");166 assert_ne!(zero, one, "both streams drew the same envelope");
167 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");167 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");
168- // A stream that does not decode is refused, not drawn as silence.168+ // Stream 2 is AC-3, and it decodes now: it draws its own envelope like
169- assert!(peaks(&multi, 2, BPS).is_err(), "AC-3 has no envelope");169+ // any other stream rather than being refused.
170+ let two = peaks(&multi, 2, BPS).expect("AC-3 opens").expect("stream 2");
171+ assert!(!two.is_empty(), "the AC-3 stream drew nothing");
170 }172 }
171 }173 }
crates/engine/tests/audio_decode.rsmodified+48 -13
@@ -117,24 +117,59 @@ fn video_only_file_has_no_audio() {
117 );117 );
118 }118 }
119 119
120-/// Sound we cannot decode must not be silence we say nothing about: the AC-3120+/// Both ends of the AC-3 path decode: the 44.1 kHz **mono** fixture stays the
121-/// fixture opens as picture-only and the session carries the reason a121+/// mono source it is, and the 48 kHz **5.1** one — the shape a BluRay remux has
122-/// front-end shows (`Player::open_media`).122+/// — arrives as stereo, downmixed by the decoder itself (A/52 §7.8). Both play
123+/// their two seconds, at a level that is neither silence nor clipping, and
124+/// neither owes the session an excuse.
123 #[test]125 #[test]
124-fn an_undecodable_audio_track_is_named() {126+fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
125- let path = asset("test_ac3.mp4");127+ for (name, rate, channels) in [("test_ac3.mp4", 44100, 1), ("test_ac3_51.mp4", 48000, 2)] {
128+ let path = asset(name);
129+ let (meta, rx) = AudioSession::open(&path)
130+ .expect("open")
131+ .expect("AC-3 decodes now");
132+ assert_eq!((meta.sample_rate, meta.channels), (rate, channels), "{name}");
133+ let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
134+ let secs = (samples.len() / channels as usize) as f64 / f64::from(rate);
126 assert!(135 assert!(
127- AudioSession::open(&path).expect("open").is_none(),136+ (1.9..2.1).contains(&secs),
128- "AC-3 is not decodable here"137+ "{name} is two seconds, decoded {secs:.3}s"
138+ );
139+ // The 440 Hz sine survives at a sane level. The vetting caveat was an
140+ // LFE passthrough running hot, which the built-in downmix is what
141+ // avoids; this is that level check, and it is also what catches a
142+ // downmix that comes out silent.
143+ let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
144+ / samples.len() as f64)
145+ .sqrt();
146+ assert!(
147+ (0.005..0.75).contains(&rms),
148+ "{name}: RMS {rms:.6} is not a sine at a sane level"
149+ );
150+ assert!(
151+ samples.iter().all(|s| s.abs() <= 1.0),
152+ "{name}: the decode must not leave the device's range"
129 );153 );
130- let reason = AudioSession::unsupported(&path)
131- .expect("probe")
132- .expect("the file has an audio track, so it owes a reason");
133- assert!(reason.contains("decode"), "unhelpful reason: {reason}");
134 let session = engine::PlaybackSession::open(&path).expect("open for playback");154 let session = engine::PlaybackSession::open(&path).expect("open for playback");
135 assert_eq!(155 assert_eq!(
136 session.audio_disabled_reason(),156 session.audio_disabled_reason(),
137- Some(reason.as_str()),157+ None,
138- "the session must carry it to the front-end"158+ "{name}: a track that decodes owes no excuse"
159+ );
160+ }
161+}
162+
163+/// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC
164+/// encoder here -- and that refusal is named, never a silent silent export.
165+#[test]
166+fn an_ac3_source_refuses_an_mp4_audio_copy() {
167+ let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else {
168+ panic!("AC-3 cannot become an mp4a track");
169+ };
170+ let err = err.to_string();
171+ assert!(
172+ err.contains("needs AAC audio") && err.contains("AC-3"),
173+ "unhelpful refusal: {err}"
139 );174 );
140 }175 }
crates/engine/tests/audio_export.rsmodified+54 -0
@@ -305,3 +305,57 @@ fn a_silent_timeline_refuses_an_audio_export() {
305 "nothing written"305 "nothing written"
306 );306 );
307 }307 }
308+
309+/// An AC-3 source leaves through this door and no other: the mp4 export cannot
310+/// copy a syncframe into an `mp4a` track (no AAC encoder here), but a WAV of the
311+/// same timeline decodes, downmixes and reopens through the engine's own reader.
312+#[test]
313+fn a_51_ac3_source_round_trips_through_a_wav() {
314+ let source = asset("test_ac3_51.mp4");
315+ let project = Project::from_parts(
316+ vec![Source::new(source.clone(), 0)],
317+ vec![(
318+ LaneKind::Audio,
319+ vec![Clip {
320+ start: 0,
321+ in_frame: 0,
322+ out_frame: 30,
323+ source: 0,
324+ link: None,
325+ eq: None,
326+ color: None,
327+ fit: FitPolicy::default(),
328+ }],
329+ )],
330+ Vec::new(),
331+ Vec::new(),
332+ )
333+ .expect("a one-source AC-3 project");
334+ let video = engine::demux::Demuxer::open(&source).expect("open the fixture").0;
335+
336+ let out = out_path("ac3", "wav");
337+ let handle = engine::export::start(
338+ project,
339+ video,
340+ &out,
341+ &ExportSettings {
342+ format: Format::Wav,
343+ ..Default::default()
344+ },
345+ );
346+ wait(&handle, Duration::from_secs(60)).expect("wav export of an AC-3 source");
347+
348+ let (meta, samples) = decode(&out);
349+ assert_eq!(
350+ (meta.sample_rate, meta.channels),
351+ (48_000, 2),
352+ "the §7.8 downmix is what reaches the file"
353+ );
354+ let secs = (samples.len() / 2) as f64 / 48_000.;
355+ assert!((0.9..1.1).contains(&secs), "one second of clip, got {secs:.3}s");
356+ let energy = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
357+ / samples.len() as f64)
358+ .sqrt();
359+ assert!(energy > 0.005, "the exported AC-3 is silence: RMS {energy:.6}");
360+ std::fs::remove_file(&out).unwrap();
361+}
crates/engine/tests/audio_streams.rsmodified+15 -16
@@ -68,17 +68,17 @@ fn probe_streams_lists_every_audio_track_in_file_order() {
68 lang: Some("fra".into()),68 lang: Some("fra".into()),
69 decodable: true,69 decodable: true,
70 },70 },
71- // The one we cannot play is listed all the same, so a picker can71+ // mp4 0.14 parses no sample entry for AC-3 and keeps no fourcc, so
72- // grey it rather than pretend the file has two streams. mp4 0.1472+ // this row is described by the AC-3 reader itself: the codec by the
73- // keeps no fourcc for a sample entry it does not parse, hence the73+ // stsd fourcc read by hand, the rate and the layout by the first
74- // blanks — the row exists, which is the point.74+ // syncframe. Stereo, because that is what the downmix hands out.
75 StreamInfo {75 StreamInfo {
76 index: 2,76 index: 2,
77- codec: "unknown".into(),77+ codec: "ac-3".into(),
78- channels: 0,78+ channels: 2,
79- sample_rate: 0,79+ sample_rate: 44100,
80 lang: None,80 lang: None,
81- decodable: false,81+ decodable: true,
82 },82 },
83 ]83 ]
84 );84 );
@@ -152,15 +152,14 @@ fn an_impossible_stream_is_refused_not_guessed() {
152 err.to_string().contains("audio stream 3 of 3"),152 err.to_string().contains("audio stream 3 of 3"),
153 "unhelpful refusal: {err}"153 "unhelpful refusal: {err}"
154 );154 );
155- // Stream 2 exists but is AC-3: refused with its own message, not decoded155+ // Stream 2 is AC-3, and a *named* stream is opened by its own reader: it
156- // into noise and not silently swapped for a stream that does decode.156+ // decodes to the same 44.1 kHz stereo the AAC stream 0 does, which is what
157+ // lets it share this timeline at all.
157 let ac3 = [(asset(MULTI), 2)];158 let ac3 = [(asset(MULTI), 2)];
158- let err = AudioSession::open_multi_streams(&ac3, &[(Some(0), 0.0, 1.0)])159+ let (meta, _rx) = AudioSession::open_multi_streams(&ac3, &[(Some(0), 0.0, 1.0)])
159- .expect_err("AC-3 does not decode here");160+ .expect("AC-3 decodes now")
160- assert!(161+ .expect("the stream is there");
161- err.to_string().contains("audio stream 2 is not AAC"),162+ assert_eq!((meta.sample_rate, meta.channels), (44100, 2));
162- "unhelpful refusal: {err}"
163- );
164 // A source a *segment* names, opened lazily, refuses just the same.163 // A source a *segment* names, opened lazily, refuses just the same.
165 let sources = [(asset(MULTI), 0), (asset(MULTI), 9)];164 let sources = [(asset(MULTI), 0), (asset(MULTI), 9)];
166 assert!(165 assert!(
scripts/gen_fixtures.shmodified+7 -0
@@ -48,6 +48,13 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
48 -f lavfi -i "sine=frequency=440:duration=2" \48 -f lavfi -i "sine=frequency=440:duration=2" \
49 -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \49 -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
50 -c:a ac3 -b:a 192k assets/test_ac3.mp450 -c:a ac3 -b:a 192k assets/test_ac3.mp4
51+# The shape a BluRay remux has: 48 kHz 5.1 AC-3, which the decoder downmixes to
52+# stereo for the timeline. The mono fixture above is the other end of the same
53+# path — no downmix at all — and both have to work.
54+ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
55+ -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \
56+ -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
57+ -ac 6 -c:a ac3 -b:a 448k assets/test_ac3_51.mp4
51 # Multi-language fixture: the shape real media has — one video and two AAC58 # Multi-language fixture: the shape real media has — one video and two AAC
52 # streams that *agree* on rate and layout (44.1k stereo) and differ only in59 # streams that *agree* on rate and layout (44.1k stereo) and differ only in
53 # language and content, 440/880 Hz undefined and 220/330 Hz French. One60 # language and content, 440/880 Hz undefined and 220/330 Hz French. One