forge
Explore
Log in

Don't you dare go Hollow

AC-3 and E-AC-3 sound out of a Matroska file

Browse files at this commit

a71f015dcab11e1fcd7c684d1b7ceb9b40d60f61Ahmet Kaan GümüşParent: 88fbed0
  • feat
    • AC-3 and E-AC-3 sound out of a Matroska file
Show full message
✨ feat(audio): AC-3 and E-AC-3 sound out of a Matroska file

The "(AAC only)" refusal fired on every A_AC3/A_EAC3 track in an mkv
because a Matroska file's sound reached no reader at all. The blocks of
its first audio track are now indexed beside the picture's and handed to
the oxideav-ac3 decoder the mp4 path already uses, downmix and all.
crates/engine/src/audio.rsmodified+267 -38
@@ -63,10 +63,6 @@ const PRE_ROLL: u32 = 2;
63 /// 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.
64 const SAMPLES_PER_PACKET: u32 = 1024;64 const SAMPLES_PER_PACKET: u32 = 1024;
65 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 the66 /// 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.67 /// 256-sample overlap-add the target frame is reconstructed with.
72 const AC3_PRE_ROLL: u32 = 1;68 const AC3_PRE_ROLL: u32 = 1;
@@ -490,16 +486,26 @@ impl AudioSession {
490 /// -- nothing to tell the user there. Header only, and only worth calling486 /// -- nothing to tell the user there. Header only, and only worth calling
491 /// once the open has already returned no audio.487 /// once the open has already returned no audio.
492 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {488 pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> {
493- // Matroska: the demuxer reads its picture and nothing else yet, so a489+ // Matroska: the demuxer reads its picture and its AC-3 sound, so a file
494- // file that has sound is told so by name rather than playing silent490+ // whose audio is in any other codec is told so by name rather than
495- // with no reason given. A Matroska file with no audio track at all491+ // playing silent with no reason given. A Matroska file with no audio
496- // returns `None` here like any other silent file.492+ // track at all returns `None` here like any other silent file.
497 if crate::demux::is_matroska(path.as_ref()) {493 if crate::demux::is_matroska(path.as_ref()) {
498- return Ok(494+ let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else {
499- crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| {495+ return Ok(None);
496+ };
497+ // ...except AC-3 and E-AC-3, which are read out of the blocks
498+ // themselves now ([`MkvAc3Track`]). If one of those still came up
499+ // silent it is the track that could not be read, and the reader's
500+ // own words -- a laced block, an unreadable syncframe -- are the
501+ // ones worth showing.
502+ return Ok(Some(match MkvAc3Track::open(path.as_ref()) {
503+ Ok(Some(_)) => return Ok(None),
504+ Ok(None) => {
500 format!("{codec} audio in a Matroska file is not wired to the decoder yet")505 format!("{codec} audio in a Matroska file is not wired to the decoder yet")
501- }),506+ }
502- );507+ Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"),
508+ }));
503 }509 }
504 let file = File::open(path.as_ref())?;510 let file = File::open(path.as_ref())?;
505 let size = file.metadata()?.len();511 let size = file.metadata()?.len();
@@ -546,11 +552,26 @@ impl AudioSession {
546 /// and an ALAC `.m4a` only half is.552 /// and an ALAC `.m4a` only half is.
547 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {553 pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> {
548 let path = path.as_ref();554 let path = path.as_ref();
549- // A Matroska file's audio tracks are not readable here yet ([`Track`]),555+ // A Matroska file offers the one AC-3 / E-AC-3 track [`MkvAc3Track`]
550- // and a stream nothing can open is not one to offer: an mkv lists as556+ // reads, in the shape it decodes to (stereo, per the §7.8 downmix), and
551- // the silent source it currently is.557+ // nothing else: a stream nothing can open is not one to offer, so an
558+ // mkv whose sound is in any other codec still lists as the silent
559+ // source it currently is.
552 if crate::demux::is_matroska(path) {560 if crate::demux::is_matroska(path) {
553- return Ok(Vec::new());561+ return Ok(MkvAc3Track::open(path)
562+ .ok()
563+ .flatten()
564+ .map(|track| {
565+ vec![StreamInfo {
566+ index: 0,
567+ codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(),
568+ channels: track.channels,
569+ sample_rate: track.sample_rate,
570+ lang: None,
571+ decodable: matches!(track.channels, 1 | 2),
572+ }]
573+ })
574+ .unwrap_or_default());
554 }575 }
555 if crate::is_audio(path) {576 if crate::is_audio(path) {
556 let track = SymTrack::open(path)?;577 let track = SymTrack::open(path)?;
@@ -838,7 +859,7 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> {
838 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`859 // Decoded, never copied: an AC-3 syncframe is not something an `mp4a`
839 // sample table can hold, and there is no AAC encoder here to turn it860 // sample table can hold, and there is no AAC encoder here to turn it
840 // into one. A WAV/FLAC export of the same timeline decodes fine.861 // into one. A WAV/FLAC export of the same timeline decodes fine.
841- Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")),862+ Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")),
842 }863 }
843 }864 }
844 865
@@ -860,6 +881,9 @@ fn uncopyable(path: &Path, codec: &str) -> crate::Error {
860 enum Track {881 enum Track {
861 Aac(AacTrack),882 Aac(AacTrack),
862 Ac3(Ac3Track),883 Ac3(Ac3Track),
884+ /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an
885+ /// mp4's sample table.
886+ Mkv(MkvAc3Track),
863 Sym(SymTrack),887 Sym(SymTrack),
864 }888 }
865 889
@@ -878,11 +902,18 @@ impl Track {
878 /// has exactly one, so any `stream` above 0 there is a promise the file902 /// has exactly one, so any `stream` above 0 there is a promise the file
879 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.903 /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have.
880 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {904 fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> {
881- // A Matroska file's sound is not wired to either reader yet: its picture905+ // A Matroska file's sound reaches neither mp4 reader: its AC-3 and
882- // is what this slice delivers, and the source counts as a silent one --906+ // E-AC-3 tracks come out of the blocks themselves and everything else
883- // which `AudioSession::unsupported` puts into words for the user.907+ // in one is still a silent source -- which `AudioSession::unsupported`
908+ // puts into words for the user. A track that *is* AC-3 and will not
909+ // open (a laced block, an unreadable syncframe) stays a silent source
910+ // too rather than failing the import: an mkv has never been refused
911+ // over its sound, and `unsupported` says what went wrong.
884 if crate::demux::is_matroska(path) {912 if crate::demux::is_matroska(path) {
885- return Ok(None);913+ return Ok((stream == 0)
914+ .then(|| MkvAc3Track::open(path).ok().flatten())
915+ .flatten()
916+ .map(Self::Mkv));
886 }917 }
887 let audio_file = crate::is_audio(path);918 let audio_file = crate::is_audio(path);
888 // Ahead of the AAC reader, because that one answers "not AAC" for a919 // Ahead of the AAC reader, because that one answers "not AAC" for a
@@ -910,6 +941,7 @@ impl Track {
910 match self {941 match self {
911 Self::Aac(t) => t.sample_rate,942 Self::Aac(t) => t.sample_rate,
912 Self::Ac3(t) => t.sample_rate,943 Self::Ac3(t) => t.sample_rate,
944+ Self::Mkv(t) => t.sample_rate,
913 Self::Sym(t) => t.sample_rate,945 Self::Sym(t) => t.sample_rate,
914 }946 }
915 }947 }
@@ -925,6 +957,11 @@ impl Track {
925 1 | 2 => Ok(t.channels),957 1 | 2 => Ok(t.channels),
926 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),958 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
927 },959 },
960+ // Downmixed by the very same decoder, out of a Matroska file.
961+ Self::Mkv(t) => match t.channels {
962+ 1 | 2 => Ok(t.channels),
963+ n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
964+ },
928 Self::Sym(t) => match t.channels {965 Self::Sym(t) => match t.channels {
929 1 | 2 => Ok(t.channels),966 1 | 2 => Ok(t.channels),
930 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),967 n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
@@ -937,6 +974,7 @@ impl Track {
937 match self {974 match self {
938 Self::Aac(t) => t.total_samples,975 Self::Aac(t) => t.total_samples,
939 Self::Ac3(t) => t.total_samples,976 Self::Ac3(t) => t.total_samples,
977+ Self::Mkv(t) => t.total_samples,
940 Self::Sym(t) => t.total_samples,978 Self::Sym(t) => t.total_samples,
941 }979 }
942 }980 }
@@ -946,6 +984,9 @@ impl Track {
946 match self {984 match self {
947 Self::Aac(t) => t.priming,985 Self::Aac(t) => t.priming,
948 Self::Ac3(t) => t.priming,986 Self::Ac3(t) => t.priming,
987+ // Matroska writes no edit list and AC-3 has no encoder delay:
988+ // block 0 is sample 0.
989+ Self::Mkv(_) => 0,
949 Self::Sym(t) => t.priming,990 Self::Sym(t) => t.priming,
950 }991 }
951 }992 }
@@ -956,6 +997,7 @@ impl Track {
956 match self {997 match self {
957 Self::Aac(t) => t.segment(source, start_secs, end_secs),998 Self::Aac(t) => t.segment(source, start_secs, end_secs),
958 Self::Ac3(t) => t.segment(source, start_secs, end_secs),999 Self::Ac3(t) => t.segment(source, start_secs, end_secs),
1000+ Self::Mkv(t) => t.segment(source, start_secs, end_secs),
959 Self::Sym(t) => {1001 Self::Sym(t) => {
960 let media_target = t.media(start_secs);1002 let media_target = t.media(start_secs);
961 Segment {1003 Segment {
@@ -977,7 +1019,10 @@ impl Track {
977 AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;1019 AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;
978 }1020 }
979 Self::Ac3(t) => {1021 Self::Ac3(t) => {
980- ac3_decoder(t.requested)?;1022+ ac3_decoder("ac3", t.requested)?;
1023+ }
1024+ Self::Mkv(t) => {
1025+ ac3_decoder(t.mkv.codec, t.requested)?;
981 }1026 }
982 Self::Sym(t) => {1027 Self::Sym(t) => {
983 t.decoder()?;1028 t.decoder()?;
@@ -1143,9 +1188,9 @@ impl Ac3Track {
1143 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?1188 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?
1144 .nfchans;1189 .nfchans;
1145 let requested = (nfchans > 1).then_some(2);1190 let requested = (nfchans > 1).then_some(2);
1146- let mut decoder = ac3_decoder(requested)?;1191+ let mut decoder = ac3_decoder("ac3", requested)?;
1147 let channels = decode_ac3(&mut decoder, &first.bytes)?1192 let channels = decode_ac3(&mut decoder, &first.bytes)?
1148- .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16)1193+ .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16)
1149 .filter(|&c| c > 0)1194 .filter(|&c| c > 0)
1150 .ok_or("the first AC-3 syncframe decoded to nothing")?;1195 .ok_or("the first AC-3 syncframe decoded to nothing")?;
1151 1196
@@ -1190,6 +1235,101 @@ impl Ac3Track {
1190 }1235 }
1191 }1236 }
1192 1237
1238+/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same
1239+/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of
1240+/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux
1241+/// therefore arrives on the timeline as an ordinary stereo source, exactly as
1242+/// the mp4 path's does, and the mono passthrough quirk is the same one.
1243+///
1244+/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side
1245+/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]):
1246+/// one block is one packet, one packet is one syncframe, and a seek lands on
1247+/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in
1248+/// front of it.
1249+struct MkvAc3Track {
1250+ mkv: crate::demux::MkvAudio,
1251+ sample_rate: u32,
1252+ /// What comes *out* of the decoder, measured on the first frame — 2 for
1253+ /// anything from stereo to 5.1, 1 for a mono track (see `requested`).
1254+ channels: u16,
1255+ total_samples: Option<u64>,
1256+ /// What the decoder is asked to hand out, from this track's own layout:
1257+ /// `Some(2)` for anything with more than one front channel, `None` for a
1258+ /// mono track. The reason is [`ac3_decoder`]'s `ponytail`, not this file's.
1259+ requested: Option<u16>,
1260+}
1261+
1262+impl MkvAc3Track {
1263+ /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 —
1264+ /// that mkv is the silent source it has always been. An `Err` is a track
1265+ /// that is one and could not be read, which
1266+ /// [`AudioSession::unsupported`] quotes back to the user.
1267+ fn open(path: &Path) -> crate::Result<Option<Self>> {
1268+ let Some(mut mkv) = crate::demux::MkvAudio::open(path)? else {
1269+ return Ok(None);
1270+ };
1271+ let first = mkv
1272+ .frame(0)?
1273+ .ok_or("the AC-3 track of this Matroska file has no blocks")?;
1274+ // Rate and layout come out of the bit stream, which is where AC-3
1275+ // states them: Matroska's `Audio` element repeats them and muxers get
1276+ // that wrong often enough that the frame is the better source.
1277+ // `nfchans` excludes the LFE in both syntaxes, which is what the
1278+ // downmix decision wants.
1279+ let (sample_rate, nfchans) = if mkv.codec == "eac3" {
1280+ // Annex E's BSI starts right after the 16-bit syncword.
1281+ let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default())
1282+ .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?;
1283+ (bsi.sample_rate, bsi.nfchans)
1284+ } else {
1285+ let sync = oxideav_ac3::syncinfo::parse(&first)
1286+ .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?;
1287+ let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default())
1288+ .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?;
1289+ (sync.sample_rate, bsi.nfchans)
1290+ };
1291+ let requested = (nfchans > 1).then_some(2);
1292+ let mut decoder = ac3_decoder(mkv.codec, requested)?;
1293+ let (pcm, samples) =
1294+ decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?;
1295+ let channels = (pcm.len() as u64 / samples.max(1)) as u16;
1296+ if channels == 0 {
1297+ return Err("the first AC-3 syncframe decoded to nothing".into());
1298+ }
1299+ // The track runs to the last block's timestamp plus that block's own
1300+ // frame -- a container that indexes nothing states no duration either,
1301+ // and every frame of a syncframe stream is the same length.
1302+ let last = mkv.secs(mkv.blocks().saturating_sub(1));
1303+ Ok(Some(Self {
1304+ total_samples: Some((last * f64::from(sample_rate)) as u64 + samples),
1305+ sample_rate,
1306+ channels,
1307+ requested,
1308+ mkv,
1309+ }))
1310+ }
1311+
1312+ /// `secs` on this source's timeline into media samples. No priming: the
1313+ /// container carries no edit list and AC-3 no encoder delay.
1314+ fn media(&self, secs: f64) -> u64 {
1315+ (secs.max(0.0) * f64::from(self.sample_rate)) as u64
1316+ }
1317+
1318+ /// One `[start, end)` window, resolved to blocks and media samples —
1319+ /// [`Ac3Track::segment`] against block timestamps instead of an `stts`.
1320+ fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment {
1321+ let media_target = self.media(start_secs);
1322+ let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize);
1323+ Segment {
1324+ source: Some(source),
1325+ start_id: start_id as u32,
1326+ start_pos: self.media(self.mkv.secs(start_id)),
1327+ media_target,
1328+ media_end: self.media(end_secs).max(media_target),
1329+ }
1330+ }
1331+}
1332+
1193 /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own1333 /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own
1194 /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a1334 /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a
1195 /// 5.1 track at all. Fresh per segment for the same reason every other decoder1335 /// 5.1 track at all. Fresh per segment for the same reason every other decoder
@@ -1200,32 +1340,47 @@ impl Ac3Track {
1200 /// mono track asks for no downmix at all and stays the mono source it is. The1340 /// mono track asks for no downmix at all and stays the mono source it is. The
1201 /// upgrade path is `Some(2)` unconditionally once the library duplicates the1341 /// upgrade path is `Some(2)` unconditionally once the library duplicates the
1202 /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change.1342 /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change.
1203-fn ac3_decoder(channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> {1343+///
1344+/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers
1345+/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct
1346+/// behind both dispatches per packet on `bsid` in any case, so what this picks
1347+/// is the capability set, not the syntax.
1348+fn ac3_decoder(codec: &str, channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> {
1204 let mut registry = CodecRegistry::new();1349 let mut registry = CodecRegistry::new();
1205 oxideav_ac3::register_codecs(&mut registry);1350 oxideav_ac3::register_codecs(&mut registry);
1206- let mut params = CodecParameters::audio(CodecId::new("ac3"));1351+ let mut params = CodecParameters::audio(CodecId::new(codec));
1207 params.channels = channels;1352 params.channels = channels;
1208 registry1353 registry
1209 .first_decoder(&params)1354 .first_decoder(&params)
1210 .map_err(|e| format!("no AC-3 decoder: {e:?}").into())1355 .map_err(|e| format!("no AC-3 decoder: {e:?}").into())
1211 }1356 }
1212 1357
1213-/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the1358+/// One syncframe in, one buffer of interleaved f32 out and the frames per
1214-/// decoder wants more input before it can hand a frame back, which is not an1359+/// channel it holds. `Ok(None)` when the decoder wants more input before it can
1215-/// error. The library speaks S16 little-endian; `/32768` is the whole1360+/// hand a frame back, which is not an error. The library speaks S16
1216-/// conversion, and it lands in the `[-1, 1)` every other reader here emits.1361+/// little-endian; `/32768` is the whole conversion, and it lands in the
1217-fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> crate::Result<Option<Vec<f32>>> {1362+/// `[-1, 1)` every other reader here emits.
1363+///
1364+/// The frame count comes back beside the samples because an E-AC-3 frame is not
1365+/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2
1366+/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the
1367+/// channel count and every media position after it out.
1368+fn decode_ac3(
1369+ decoder: &mut Box<dyn Decoder>,
1370+ bytes: &[u8],
1371+) -> crate::Result<Option<(Vec<f32>, u64)>> {
1218 let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec());1372 let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec());
1219 decoder1373 decoder
1220 .send_packet(&packet)1374 .send_packet(&packet)
1221 .map_err(|e| format!("AC-3 decode failed: {e:?}"))?;1375 .map_err(|e| format!("AC-3 decode failed: {e:?}"))?;
1222 match decoder.receive_frame() {1376 match decoder.receive_frame() {
1223- Ok(Frame::Audio(audio)) => Ok(Some(1377+ Ok(Frame::Audio(audio)) => Ok(Some((
1224 audio.data[0]1378 audio.data[0]
1225 .chunks_exact(2)1379 .chunks_exact(2)
1226 .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0)1380 .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0)
1227 .collect(),1381 .collect(),
1228- )),1382+ u64::from(audio.samples),
1383+ ))),
1229 Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()),1384 Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()),
1230 Err(oxideav_core::Error::NeedMore) => Ok(None),1385 Err(oxideav_core::Error::NeedMore) => Ok(None),
1231 Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()),1386 Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()),
@@ -1817,6 +1972,21 @@ fn run(mut w: Worker) {
1817 }1972 }
1818 continue;1973 continue;
1819 }1974 }
1975+ Track::Mkv(track) => {
1976+ if !run_mkv_ac3(
1977+ track,
1978+ seg,
1979+ eq.as_mut(),
1980+ speed,
1981+ channels,
1982+ &mut timeline,
1983+ &w.tx,
1984+ ) || !settle(speed, channels, &mut timeline, &w.tx)
1985+ {
1986+ return; // consumer went away
1987+ }
1988+ continue;
1989+ }
1820 Track::Ac3(track) => {1990 Track::Ac3(track) => {
1821 if !run_ac3(1991 if !run_ac3(
1822 track,1992 track,
@@ -1982,7 +2152,7 @@ fn run_ac3(
1982 timeline: &mut u64,2152 timeline: &mut u64,
1983 tx: &SyncSender<AudioChunk>,2153 tx: &SyncSender<AudioChunk>,
1984 ) -> bool {2154 ) -> bool {
1985- let mut decoder = match ac3_decoder(track.requested) {2155+ let mut decoder = match ac3_decoder("ac3", track.requested) {
1986 Ok(decoder) => decoder,2156 Ok(decoder) => decoder,
1987 Err(e) => {2157 Err(e) => {
1988 eprintln!("audio decoder init failed: {e}");2158 eprintln!("audio decoder init failed: {e}");
@@ -1991,7 +2161,6 @@ fn run_ac3(
1991 };2161 };
1992 let mut pos = seg.start_pos;2162 let mut pos = seg.start_pos;
1993 for id in seg.start_id..=track.sample_count {2163 for id in seg.start_id..=track.sample_count {
1994- let mut interleaved;
1995 if pos >= seg.media_end {2164 if pos >= seg.media_end {
1996 return true; // segment done, on to the next one2165 return true; // segment done, on to the next one
1997 }2166 }
@@ -2003,15 +2172,75 @@ fn run_ac3(
2003 return true;2172 return true;
2004 }2173 }
2005 };2174 };
2006- match decode_ac3(&mut decoder, &sample.bytes) {2175+ let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) {
2007- Ok(Some(pcm)) => interleaved = pcm,2176+ Ok(Some(decoded)) => decoded,
2008 Ok(None) => continue, // the decoder wants another frame first2177 Ok(None) => continue, // the decoder wants another frame first
2009 Err(e) => {2178 Err(e) => {
2010 eprintln!("audio decode error at sample {id}: {e}");2179 eprintln!("audio decode error at sample {id}: {e}");
2011 return true;2180 return true;
2012 }2181 }
2182+ };
2183+ let next = pos + samples;
2184+ if !emit(
2185+ &mut interleaved,
2186+ channels,
2187+ seg,
2188+ eq.as_deref_mut(),
2189+ speed.as_mut(),
2190+ pos,
2191+ next,
2192+ timeline,
2193+ tx,
2194+ ) {
2195+ return false;
2196+ }
2197+ pos = next;
2013 }2198 }
2014- let next = pos + (interleaved.len() / channels) as u64;2199+ true
2200+}
2201+
2202+/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks
2203+/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the
2204+/// stereo downmix are the same ones; only where a packet comes from differs.
2205+/// `false` means the consumer went away.
2206+fn run_mkv_ac3(
2207+ track: &mut MkvAc3Track,
2208+ seg: &Segment,
2209+ mut eq: Option<&mut EqState>,
2210+ speed: &mut Option<Resample>,
2211+ channels: usize,
2212+ timeline: &mut u64,
2213+ tx: &SyncSender<AudioChunk>,
2214+) -> bool {
2215+ let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) {
2216+ Ok(decoder) => decoder,
2217+ Err(e) => {
2218+ eprintln!("audio decoder init failed: {e}");
2219+ return true;
2220+ }
2221+ };
2222+ let mut pos = seg.start_pos;
2223+ for id in seg.start_id as usize.. {
2224+ if pos >= seg.media_end {
2225+ return true; // segment done, on to the next one
2226+ }
2227+ let block = match track.mkv.frame(id) {
2228+ Ok(Some(bytes)) => bytes,
2229+ Ok(None) => return true, // end of the track
2230+ Err(e) => {
2231+ eprintln!("audio demux error at block {id}: {e}");
2232+ return true;
2233+ }
2234+ };
2235+ let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) {
2236+ Ok(Some(decoded)) => decoded,
2237+ Ok(None) => continue, // the decoder wants another frame first
2238+ Err(e) => {
2239+ eprintln!("audio decode error at block {id}: {e}");
2240+ return true;
2241+ }
2242+ };
2243+ let next = pos + samples;
2015 if !emit(2244 if !emit(
2016 &mut interleaved,2245 &mut interleaved,
2017 channels,2246 channels,
crates/engine/src/demux.rsmodified+115 -19
@@ -280,15 +280,18 @@ impl Mp4Demuxer {
280 }280 }
281 }281 }
282 282
283-/// One Matroska block of the video track: where its bytes are and whether a283+/// One Matroska block of an indexed track: where its bytes are, whether a
284-/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7284+/// decoder may start on it, and when it is presented (in `TimestampScale`
285-/// MB of index -- the price of knowing the frame count and the sync points of a285+/// ticks, which is what a sound track seeks against -- Matroska indexes no
286+/// samples either). 24 bytes an entry, so an hour of 30 fps costs ~2.6 MB of
287+/// index -- the price of knowing the frame count and the sync points of a
286 /// container that indexes neither.288 /// container that indexes neither.
287 #[derive(Debug, Clone, Copy, PartialEq, Eq)]289 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
288 struct Block {290 struct Block {
289 at: u64,291 at: u64,
290 len: usize,292 len: usize,
291 key: bool,293 key: bool,
294+ ts: i64,
292 }295 }
293 296
294 /// AV1 out of a Matroska file (`.mkv`/`.webm`).297 /// AV1 out of a Matroska file (`.mkv`/`.webm`).
@@ -314,7 +317,7 @@ impl MkvDemuxer {
314 let mut file = File::open(path)?;317 let mut file = File::open(path)?;
315 let end = file.metadata()?.len();318 let end = file.metadata()?.len();
316 let segment = mkv_segment(&mut file, end)?;319 let segment = mkv_segment(&mut file, end)?;
317- let (video, _) = mkv_tracks(&mut file, segment)?;320+ let (video, _, _) = mkv_tracks(&mut file, segment)?;
318 let video = video.ok_or(321 let video = video.ok_or(
319 "no AV1 video track in this Matroska file — AV1 is the only codec read from one",322 "no AV1 video track in this Matroska file — AV1 is the only codec read from one",
320 )?;323 )?;
@@ -398,7 +401,92 @@ pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
398 let mut file = File::open(path)?;401 let mut file = File::open(path)?;
399 let end = file.metadata()?.len();402 let end = file.metadata()?.len();
400 let segment = mkv_segment(&mut file, end)?;403 let segment = mkv_segment(&mut file, end)?;
401- Ok(mkv_tracks(&mut file, segment)?.1)404+ Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec)| codec))
405+}
406+
407+/// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio
408+/// track, in storage order, with the timestamp a seek resolves against. The
409+/// same walk the picture costs ([`MkvDemuxer`]), on the other track number, and
410+/// the two keep their own file handle and their own index -- the sound is
411+/// opened by the audio worker and the picture by the decoder, never together.
412+///
413+/// Matroska carries no sample table, so a block's own timestamp is the only
414+/// thing a window can be resolved against; [`Self::block_at`] is what an `stts`
415+/// lookup is on the mp4 side.
416+pub struct MkvAudio {
417+ file: File,
418+ blocks: Vec<Block>,
419+ /// The `oxideav-ac3` codec id these blocks are packets of: `ac3` or `eac3`.
420+ pub codec: &'static str,
421+ /// Seconds one `TimestampScale` tick is worth, resolved once at open.
422+ secs_per_tick: f64,
423+}
424+
425+impl MkvAudio {
426+ /// `Ok(None)` when `path` has no audio track at all, or when its first one
427+ /// is in a codec nothing here decodes -- that file is the silent source it
428+ /// has always been, and [`crate::audio::AudioSession::unsupported`] names
429+ /// the codec. An `Err` is a track that *is* AC-3 and could not be read.
430+ pub fn open(path: &Path) -> crate::Result<Option<Self>> {
431+ let mut file = File::open(path)?;
432+ let end = file.metadata()?.len();
433+ let segment = mkv_segment(&mut file, end)?;
434+ let (_, audio, timestamp_scale) = mkv_tracks(&mut file, segment)?;
435+ let Some((number, codec)) = audio else {
436+ return Ok(None);
437+ };
438+ let codec = match codec.as_str() {
439+ "A_AC3" => "ac3",
440+ "A_EAC3" => "eac3",
441+ _ => return Ok(None),
442+ };
443+ let (blocks, _) = mkv_blocks(&mut file, segment, number)?;
444+ if blocks.is_empty() {
445+ return Err("the AC-3 track in this Matroska file has no blocks".into());
446+ }
447+ Ok(Some(Self {
448+ file,
449+ blocks,
450+ codec,
451+ secs_per_tick: timestamp_scale as f64 / 1e9,
452+ }))
453+ }
454+
455+ /// How many blocks the track has; one syncframe each, lacing being refused
456+ /// in [`mkv_blocks`].
457+ pub fn blocks(&self) -> usize {
458+ self.blocks.len()
459+ }
460+
461+ /// The bytes of block `index` -- one whole packet for the decoder, an
462+ /// E-AC-3 frame's dependent substreams included. `None` past the last one.
463+ pub fn frame(&mut self, index: usize) -> crate::Result<Option<Vec<u8>>> {
464+ let Some(&block) = self.blocks.get(index) else {
465+ return Ok(None);
466+ };
467+ let mut bytes = vec![0u8; block.len];
468+ read_exact_at(&mut self.file, block.at, &mut bytes)?;
469+ Ok(Some(bytes))
470+ }
471+
472+ /// When block `index` is presented, in seconds on the file's own clock. The
473+ /// last block's time for anything past the end, which is what a duration
474+ /// wants.
475+ pub fn secs(&self, index: usize) -> f64 {
476+ let index = index.min(self.blocks.len().saturating_sub(1));
477+ self.blocks.get(index).map_or(0.0, |b| b.ts as f64) * self.secs_per_tick
478+ }
479+
480+ /// The block a decoder is started from to hear `secs`: the last one at or
481+ /// before it, `pre_roll` blocks earlier so the decoder has something to warm
482+ /// up on before the audible part. Blocks are in storage order, which for a
483+ /// sound track is presentation order (no reordering exists in AC-3).
484+ pub fn block_at(&self, secs: f64, pre_roll: usize) -> usize {
485+ let ticks = (secs / self.secs_per_tick) as i64;
486+ self.blocks
487+ .partition_point(|b| b.ts <= ticks)
488+ .saturating_sub(1 + pre_roll)
489+ }
402 }490 }
403 491
404 /// What the `Tracks` element says about the AV1 track.492 /// What the `Tracks` element says about the AV1 track.
@@ -445,16 +533,17 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
445 Err("no Segment element: not a Matroska file".into())533 Err("no Segment element: not a Matroska file".into())
446 }534 }
447 535
448-/// The AV1 video track of `segment`, and how a *non*-AV1 audio track would be536+/// The AV1 video track of `segment`, the number and codec id of its first audio
449-/// named -- the second is what tells a user why a file with sound plays silent537+/// track, and the segment's `TimestampScale` in nanoseconds. The audio pair is
450-/// ([`crate::audio::AudioSession::unsupported`]).538+/// what [`MkvAudio`] reads a sound track from and what tells a user why a file
539+/// with sound plays silent ([`crate::audio::AudioSession::unsupported`]).
451 ///540 ///
452 /// Header only: the walk stops at the first `Cluster`, so this costs a handful541 /// Header only: the walk stops at the first `Cluster`, so this costs a handful
453 /// of seeks whatever the file weighs.542 /// of seeks whatever the file weighs.
454 fn mkv_tracks(543 fn mkv_tracks(
455 file: &mut File,544 file: &mut File,
456 segment: (u64, u64),545 segment: (u64, u64),
457-) -> crate::Result<(Option<MkvVideo>, Option<String>)> {546+) -> crate::Result<(Option<MkvVideo>, Option<(u64, String)>, u64)> {
458 let (mut video, mut audio) = (None, None);547 let (mut video, mut audio) = (None, None);
459 let mut timestamp_scale = 1_000_000;548 let mut timestamp_scale = 1_000_000;
460 let mut at = segment.0;549 let mut at = segment.0;
@@ -476,7 +565,7 @@ fn mkv_tracks(
476 if e.0 == TRACK_ENTRY {565 if e.0 == TRACK_ENTRY {
477 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {566 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
478 (Some(track), _) if video.is_none() => video = Some(track),567 (Some(track), _) if video.is_none() => video = Some(track),
479- (_, Some(codec)) if audio.is_none() => audio = Some(codec),568+ (_, Some(track)) if audio.is_none() => audio = Some(track),
480 _ => {}569 _ => {}
481 }570 }
482 }571 }
@@ -487,17 +576,17 @@ fn mkv_tracks(
487 }576 }
488 at = stop;577 at = stop;
489 }578 }
490- Ok((video, audio))579+ Ok((video, audio, timestamp_scale))
491 }580 }
492 581
493-/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the codec id582+/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the number
494-/// of an audio track otherwise.583+/// and codec id of an audio track otherwise.
495 fn mkv_track_entry(584 fn mkv_track_entry(
496 file: &mut File,585 file: &mut File,
497 body: u64,586 body: u64,
498 end: u64,587 end: u64,
499 timestamp_scale: u64,588 timestamp_scale: u64,
500-) -> crate::Result<(Option<MkvVideo>, Option<String>)> {589+) -> crate::Result<(Option<MkvVideo>, Option<(u64, String)>)> {
501 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);590 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
502 let (mut width, mut height, mut config) = (0, 0, Vec::new());591 let (mut width, mut height, mut config) = (0, 0, Vec::new());
503 let mut at = body;592 let mut at = body;
@@ -540,7 +629,7 @@ fn mkv_track_entry(
540 }),629 }),
541 None,630 None,
542 )),631 )),
543- (2, _) => Ok((None, Some(codec))),632+ (2, _) => Ok((None, Some((number, codec)))),
544 _ => Ok((None, None)),633 _ => Ok((None, None)),
545 }634 }
546 }635 }
@@ -628,11 +717,17 @@ fn mkv_blocks(
628 if block.number != number {717 if block.number != number {
629 continue;718 continue;
630 }719 }
631- // Lacing packs several frames into one block. Audio muxers use it,720+ // Lacing packs several frames into one block, behind a header of
632- // video ones do not, and guessing at frame boundaries inside a laced721+ // frame sizes this does not read. Video muxers write none; an audio
633- // block is not something to do silently.722+ // muxer may, and guessing at frame boundaries inside a laced block
723+ // is not something to do silently.
724+ //
725+ // ponytail: a laced audio track is refused by name rather than
726+ // played. The upgrade path is the three lace headers of the spec
727+ // (Xiph, fixed, EBML) read here into one `Block` per frame; ffmpeg,
728+ // which writes the fixtures and most remuxes, laces nothing.
634 if block.flags & 0x06 != 0 {729 if block.flags & 0x06 != 0 {
635- return Err("laced video blocks are not supported".into());730+ return Err("laced Matroska blocks are not supported".into());
636 }731 }
637 let ts = cluster_ts + i64::from(block.rel);732 let ts = cluster_ts + i64::from(block.rel);
638 span = Some(match span {733 span = Some(match span {
@@ -643,6 +738,7 @@ fn mkv_blocks(
643 at: block.at,738 at: block.at,
644 len: block.len,739 len: block.len,
645 key,740 key,
741+ ts,
646 });742 });
647 }743 }
648 }744 }
crates/engine/tests/audio_decode.rsmodified+92 -0
@@ -160,6 +160,98 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
160 }160 }
161 }161 }
162 162
163+/// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and
164+/// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)"
165+/// refusal used to fire on -- both come out of the blocks, both arrive as the
166+/// stereo the §7.8 downmix hands the timeline, and neither owes the session an
167+/// excuse any more.
168+#[test]
169+fn matroska_ac3_and_eac3_decode_out_of_the_blocks() {
170+ for (name, codec) in [("test_ac3.mkv", "ac-3"), ("test_eac3.mkv", "e-ac-3")] {
171+ let path = asset(name);
172+ let (meta, rx) = AudioSession::open(&path)
173+ .expect("open")
174+ .expect("Matroska AC-3 decodes now");
175+ assert_eq!((meta.sample_rate, meta.channels), (48000, 2), "{name}");
176+ let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
177+ let secs = (samples.len() / 2) as f64 / 48000.0;
178+ assert!(
179+ (1.9..2.1).contains(&secs),
180+ "{name} is two seconds, decoded {secs:.3}s"
181+ );
182+ let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
183+ / samples.len() as f64)
184+ .sqrt();
185+ assert!(
186+ (0.005..0.75).contains(&rms),
187+ "{name}: RMS {rms:.6} is not a sine at a sane level"
188+ );
189+ assert!(
190+ samples.iter().all(|s| s.abs() <= 1.0),
191+ "{name}: the decode must not leave the device's range"
192+ );
193+ // The user-facing half: the session comes up with sound and no notice,
194+ // and the file's one audio stream is offered by the name it is in.
195+ let session = engine::PlaybackSession::open(&path).expect("open for playback");
196+ assert_eq!(
197+ session.audio_disabled_reason(),
198+ None,
199+ "{name}: a track that decodes owes no excuse"
200+ );
201+ let streams = AudioSession::probe_streams(&path).expect("streams");
202+ assert_eq!(streams.len(), 1, "{name}: one audio track, one row");
203+ assert_eq!(streams[0].codec, codec, "{name}");
204+ assert!(streams[0].decodable, "{name}");
205+ assert_eq!(
206+ AudioSession::unsupported(&path).expect("unsupported"),
207+ None,
208+ "{name}: nothing to excuse when it plays"
209+ );
210+ }
211+ // The invariant, stated as an assert: a Matroska file whose sound is in a
212+ // codec this still cannot read is named, not silently silent.
213+ let reason = AudioSession::unsupported(asset("test_av1.mkv"))
214+ .expect("unsupported")
215+ .expect("the AAC track of an mkv is still named");
216+ assert!(reason.contains("A_AAC") && reason.contains("not wired"), "{reason}");
217+}
218+
219+/// A seek into a Matroska AC-3 track: Matroska indexes no samples, so the block
220+/// a decode starts on is found by the blocks' own timestamps -- and getting that
221+/// wrong is a tail that is the wrong length or lands in the wrong place. It is
222+/// the same check `audio_seek` makes of the mp4 path, on the container that has
223+/// no sample table.
224+#[test]
225+fn a_seek_into_a_matroska_ac3_track_is_the_tail_of_a_full_run() {
226+ let path = asset("test_eac3.mkv");
227+ let full: Vec<f32> = AudioSession::open(&path)
228+ .expect("open")
229+ .expect("audio")
230+ .1
231+ .into_iter()
232+ .flat_map(|c| c.samples)
233+ .collect();
234+ let start = 48_000u64; // one second in, in frames per channel
235+ let mut next = start;
236+ let mut tail = Vec::new();
237+ for chunk in AudioSession::open_at(&path, 1.0).expect("open").expect("audio").1 {
238+ assert_eq!(chunk.start_sample, next, "a seeked run numbers from the seek");
239+ next += (chunk.samples.len() / 2) as u64;
240+ tail.extend(chunk.samples);
241+ }
242+ let want = &full[start as usize * 2..];
243+ assert_eq!(tail.len(), want.len(), "the seeked run is a different length");
244+ let diff = tail
245+ .iter()
246+ .zip(want)
247+ .map(|(a, b)| (a - b).abs())
248+ .fold(0.0f32, f32::max);
249+ // One syncframe of pre-roll is what the 256-sample overlap-add needs, so
250+ // this is exact in practice; the tolerance is for a decoder that carries
251+ // more state than the frame before, not for a wrong block.
252+ assert!(diff < 1e-3, "max abs diff {diff} after the seek");
253+}
254+
163 /// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC255 /// 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.256 /// encoder here -- and that refusal is named, never a silent silent export.
165 #[test]257 #[test]
scripts/gen_fixtures.shmodified+16 -0
@@ -113,6 +113,22 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \113 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \114 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
115 -c:a aac -b:a 128k assets/test_av1.mkv115 -c:a aac -b:a 128k assets/test_av1.mkv
116+# Matroska sound: the two Dolby codecs that arrive in one and are read straight
117+# out of its blocks (`demux::MkvAudio`). Stereo AC-3 for the plain syntax and
118+# **5.1 E-AC-3** for Annex E -- the shape a remux has, and the one that must
119+# come down to stereo through the same A/52 7.8 downmix the mp4 path uses.
120+# 48 kHz both, which is the only rate E-AC-3 is written at in practice. Small
121+# picture on purpose: these two are about the sound.
122+ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
123+ -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \
124+ -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \
125+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a]" \
126+ -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
127+ -c:a ac3 -b:a 192k assets/test_ac3.mkv
128+ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
129+ -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \
130+ -map 0:v -map 1:a -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
131+ -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv
116 # Sync fixture: one flash and one beep, at the same instant. Black picture with132 # Sync fixture: one flash and one beep, at the same instant. Black picture with
117 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that133 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
118 # stretch — so a test can find each of them and say how far apart they came out.134 # stretch — so a test can find each of them and say how far apart they came out.