🔀 merge(A1): Matroska speaks AC-3 and E-AC-3 — blocks straight to the decoder that was already aboard
Browse files at this commit4 changed files +510 -62
- crates/engine/src/audio.rs +270 -39
- crates/engine/src/demux.rs +122 -21
- crates/engine/tests/audio_decode.rs +97 -0
- scripts/gen_fixtures.sh +21 -2
crates/engine/src/audio.rsmodified+270 -39
| @@ -66,10 +66,6 @@ const PRE_ROLL: u32 = 2; | ||
| 66 | 66 | /// Frames per channel one AAC-LC packet carries. Fixed by the codec. |
| 67 | 67 | const SAMPLES_PER_PACKET: u32 = 1024; |
| 68 | 68 | |
| 69 | -/// Frames per channel one AC-3 syncframe carries. Fixed by the codec (6 blocks | |
| 70 | -/// of 256), the way 1024 is fixed for AAC-LC. | |
| 71 | -const AC3_SAMPLES_PER_FRAME: u32 = 1536; | |
| 72 | - | |
| 73 | 69 | /// Syncframes decoded and thrown away ahead of an AC-3 seek target: one, for the |
| 74 | 70 | /// 256-sample overlap-add the target frame is reconstructed with. |
| 75 | 71 | const AC3_PRE_ROLL: u32 = 1; |
| @@ -541,17 +537,26 @@ impl AudioSession { | ||
| 541 | 537 | /// -- nothing to tell the user there. Header only, and only worth calling |
| 542 | 538 | /// once the open has already returned no audio. |
| 543 | 539 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { |
| 544 | - // Matroska: AAC is read out of one ([`Track::open`]) and everything | |
| 545 | - // else -- Opus, AC-3, DTS, none of which symphonia decodes at any | |
| 546 | - // version -- is named rather than left playing silent with no reason | |
| 547 | - // given. A Matroska file with no audio track at all returns `None` here | |
| 548 | - // like any other silent file. | |
| 540 | + // Matroska: what symphonia reads out of one ([`Track::open`]) plus the | |
| 541 | + // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder | |
| 542 | + // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here | |
| 543 | + // has at any version -- is named rather than left playing silent with no | |
| 544 | + // reason given. A Matroska file with no audio track at all returns | |
| 545 | + // `None` here like any other silent file. | |
| 549 | 546 | if crate::demux::is_matroska(path.as_ref()) { |
| 550 | - return Ok( | |
| 551 | - crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| { | |
| 552 | - format!("the {codec} track of this Matroska file cannot be decoded (AAC only)") | |
| 553 | - }), | |
| 554 | - ); | |
| 547 | + let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { | |
| 548 | + return Ok(None); | |
| 549 | + }; | |
| 550 | + // An AC-3 track that came up silent all the same is one that could | |
| 551 | + // not be read -- a laced block, an unreadable syncframe -- and the | |
| 552 | + // reader's own words are the ones worth showing. | |
| 553 | + return Ok(Some(match MkvAc3Track::open(path.as_ref()) { | |
| 554 | + Ok(Some(_)) => return Ok(None), | |
| 555 | + Ok(None) => format!( | |
| 556 | + "the {codec} track of this Matroska file cannot be decoded (AAC and AC-3 only)" | |
| 557 | + ), | |
| 558 | + Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), | |
| 559 | + })); | |
| 555 | 560 | } |
| 556 | 561 | let file = File::open(path.as_ref())?; |
| 557 | 562 | let size = file.metadata()?.len(); |
| @@ -599,10 +604,24 @@ impl AudioSession { | ||
| 599 | 604 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { |
| 600 | 605 | let path = path.as_ref(); |
| 601 | 606 | // A Matroska file has exactly one readable audio stream here -- the |
| 602 | - // reader's default track ([`SymTrack::open`]) -- so it lists like a | |
| 607 | + // reader's default track ([`SymTrack::open`]), or the AC-3 / E-AC-3 one | |
| 608 | + // symphonia has no decoder for ([`MkvAc3Track`]) -- so it lists like a | |
| 603 | 609 | // standalone audio file rather than like an mp4, and one with no |
| 604 | 610 | // readable track at all lists as the silent source it is. |
| 605 | 611 | if crate::demux::is_matroska(path) { |
| 612 | + // The AC-3 row describes what the decoder *emits*, which is the | |
| 613 | + // stereo the §7.8 downmix hands the timeline, not the 5.1 the file | |
| 614 | + // carries -- exactly as the mp4 AC-3 rows do. | |
| 615 | + if let Ok(Some(track)) = MkvAc3Track::open(path) { | |
| 616 | + return Ok(vec![StreamInfo { | |
| 617 | + index: 0, | |
| 618 | + codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(), | |
| 619 | + channels: track.channels, | |
| 620 | + sample_rate: track.sample_rate, | |
| 621 | + lang: None, | |
| 622 | + decodable: matches!(track.channels, 1 | 2), | |
| 623 | + }]); | |
| 624 | + } | |
| 606 | 625 | let Ok(track) = SymTrack::open(path) else { |
| 607 | 626 | return Ok(Vec::new()); |
| 608 | 627 | }; |
| @@ -924,7 +943,7 @@ fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> { | ||
| 924 | 943 | // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` |
| 925 | 944 | // sample table can hold. The export decodes it and encodes AAC, exactly |
| 926 | 945 | // as it does for every other source no copy reaches. |
| 927 | - Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), | |
| 946 | + Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")), | |
| 928 | 947 | } |
| 929 | 948 | } |
| 930 | 949 | |
| @@ -947,6 +966,9 @@ fn uncopyable(path: &Path, codec: &str) -> crate::Error { | ||
| 947 | 966 | enum Track { |
| 948 | 967 | Aac(AacTrack), |
| 949 | 968 | Ac3(Ac3Track), |
| 969 | + /// The same AC-3 decoder, fed out of a Matroska file's blocks instead of an | |
| 970 | + /// mp4's sample table. | |
| 971 | + Mkv(MkvAc3Track), | |
| 950 | 972 | Sym(SymTrack), |
| 951 | 973 | } |
| 952 | 974 | |
| @@ -965,16 +987,27 @@ impl Track { | ||
| 965 | 987 | /// has exactly one, so any `stream` above 0 there is a promise the file |
| 966 | 988 | /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. |
| 967 | 989 | fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { |
| 968 | - // A Matroska file goes straight to symphonia, whose `mkv` reader is the | |
| 969 | - // one thing here that reads its packets -- neither mp4 reader can open | |
| 970 | - // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia | |
| 971 | - // has no such decoder at any version) leaves the source the silent one | |
| 972 | - // it always was, which `AudioSession::unsupported` puts into words, | |
| 973 | - // rather than failing the import of a file whose picture is fine. | |
| 990 | + // A Matroska file goes to symphonia, whose `mkv` reader is the one thing | |
| 991 | + // here that reads its packets -- neither mp4 reader can open the file at | |
| 992 | + // all -- except for the two codecs symphonia has no decoder for at any | |
| 993 | + // version and this project does: AC-3 and E-AC-3 are handed to the Dolby | |
| 994 | + // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither | |
| 995 | + // one can decode (Opus, DTS) leaves the source the silent one it always | |
| 996 | + // was, which `AudioSession::unsupported` puts into words, rather than | |
| 997 | + // failing the import of a file whose picture is fine -- and so does an | |
| 998 | + // AC-3 track that will not open, a laced block say. | |
| 974 | 999 | if crate::demux::is_matroska(path) { |
| 975 | 1000 | if stream > 0 { |
| 976 | 1001 | return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); |
| 977 | 1002 | } |
| 1003 | + match MkvAc3Track::open(path) { | |
| 1004 | + Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), | |
| 1005 | + Ok(None) => {} | |
| 1006 | + // Named on the way past for the same reason symphonia's failure | |
| 1007 | + // is, below: an AC-3 track that broke is a bug, not a codec we | |
| 1008 | + // never had. | |
| 1009 | + Err(e) => eprintln!("matroska audio: {}: {e}", path.display()), | |
| 1010 | + } | |
| 978 | 1011 | // Logged on the way past: "silent" here covers both a codec nothing |
| 979 | 1012 | // decodes and a track that genuinely broke, and only the second is a |
| 980 | 1013 | // bug -- with no trace at all it reaches the user as a lane that |
| @@ -1015,6 +1048,7 @@ impl Track { | ||
| 1015 | 1048 | match self { |
| 1016 | 1049 | Self::Aac(t) => t.sample_rate, |
| 1017 | 1050 | Self::Ac3(t) => t.sample_rate, |
| 1051 | + Self::Mkv(t) => t.sample_rate, | |
| 1018 | 1052 | Self::Sym(t) => t.sample_rate, |
| 1019 | 1053 | } |
| 1020 | 1054 | } |
| @@ -1030,6 +1064,11 @@ impl Track { | ||
| 1030 | 1064 | 1 | 2 => Ok(t.channels), |
| 1031 | 1065 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), |
| 1032 | 1066 | }, |
| 1067 | + // Downmixed by the very same decoder, out of a Matroska file. | |
| 1068 | + Self::Mkv(t) => match t.channels { | |
| 1069 | + 1 | 2 => Ok(t.channels), | |
| 1070 | + n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), | |
| 1071 | + }, | |
| 1033 | 1072 | Self::Sym(t) => match t.channels { |
| 1034 | 1073 | 1 | 2 => Ok(t.channels), |
| 1035 | 1074 | n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), |
| @@ -1042,6 +1081,7 @@ impl Track { | ||
| 1042 | 1081 | match self { |
| 1043 | 1082 | Self::Aac(t) => t.total_samples, |
| 1044 | 1083 | Self::Ac3(t) => t.total_samples, |
| 1084 | + Self::Mkv(t) => t.total_samples, | |
| 1045 | 1085 | Self::Sym(t) => t.total_samples, |
| 1046 | 1086 | } |
| 1047 | 1087 | } |
| @@ -1051,6 +1091,9 @@ impl Track { | ||
| 1051 | 1091 | match self { |
| 1052 | 1092 | Self::Aac(t) => t.priming, |
| 1053 | 1093 | Self::Ac3(t) => t.priming, |
| 1094 | + // Matroska writes no edit list and AC-3 has no encoder delay: | |
| 1095 | + // block 0 is sample 0. | |
| 1096 | + Self::Mkv(_) => 0, | |
| 1054 | 1097 | Self::Sym(t) => t.priming, |
| 1055 | 1098 | } |
| 1056 | 1099 | } |
| @@ -1061,6 +1104,7 @@ impl Track { | ||
| 1061 | 1104 | match self { |
| 1062 | 1105 | Self::Aac(t) => t.segment(source, start_secs, end_secs), |
| 1063 | 1106 | Self::Ac3(t) => t.segment(source, start_secs, end_secs), |
| 1107 | + Self::Mkv(t) => t.segment(source, start_secs, end_secs), | |
| 1064 | 1108 | Self::Sym(t) => { |
| 1065 | 1109 | let media_target = t.media(start_secs); |
| 1066 | 1110 | Segment { |
| @@ -1082,7 +1126,10 @@ impl Track { | ||
| 1082 | 1126 | AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; |
| 1083 | 1127 | } |
| 1084 | 1128 | Self::Ac3(t) => { |
| 1085 | - ac3_decoder(t.requested)?; | |
| 1129 | + ac3_decoder("ac3", t.requested)?; | |
| 1130 | + } | |
| 1131 | + Self::Mkv(t) => { | |
| 1132 | + ac3_decoder(t.mkv.codec, t.requested)?; | |
| 1086 | 1133 | } |
| 1087 | 1134 | Self::Sym(t) => { |
| 1088 | 1135 | t.decoder()?; |
| @@ -1335,9 +1382,9 @@ impl Ac3Track { | ||
| 1335 | 1382 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? |
| 1336 | 1383 | .nfchans; |
| 1337 | 1384 | let requested = (nfchans > 1).then_some(2); |
| 1338 | - let mut decoder = ac3_decoder(requested)?; | |
| 1385 | + let mut decoder = ac3_decoder("ac3", requested)?; | |
| 1339 | 1386 | let channels = decode_ac3(&mut decoder, &first.bytes)? |
| 1340 | - .map(|pcm| (pcm.len() / AC3_SAMPLES_PER_FRAME as usize) as u16) | |
| 1387 | + .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16) | |
| 1341 | 1388 | .filter(|&c| c > 0) |
| 1342 | 1389 | .ok_or("the first AC-3 syncframe decoded to nothing")?; |
| 1343 | 1390 | |
| @@ -1382,6 +1429,101 @@ impl Ac3Track { | ||
| 1382 | 1429 | } |
| 1383 | 1430 | } |
| 1384 | 1431 | |
| 1432 | +/// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same | |
| 1433 | +/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of | |
| 1434 | +/// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux | |
| 1435 | +/// therefore arrives on the timeline as an ordinary stereo source, exactly as | |
| 1436 | +/// the mp4 path's does, and the mono passthrough quirk is the same one. | |
| 1437 | +/// | |
| 1438 | +/// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side | |
| 1439 | +/// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]): | |
| 1440 | +/// one block is one packet, one packet is one syncframe, and a seek lands on | |
| 1441 | +/// the block at or before the target with [`AC3_PRE_ROLL`] blocks of warm-up in | |
| 1442 | +/// front of it. | |
| 1443 | +struct MkvAc3Track { | |
| 1444 | + mkv: crate::demux::MkvAudio, | |
| 1445 | + sample_rate: u32, | |
| 1446 | + /// What comes *out* of the decoder, measured on the first frame — 2 for | |
| 1447 | + /// anything from stereo to 5.1, 1 for a mono track (see `requested`). | |
| 1448 | + channels: u16, | |
| 1449 | + total_samples: Option<u64>, | |
| 1450 | + /// What the decoder is asked to hand out, from this track's own layout: | |
| 1451 | + /// `Some(2)` for anything with more than one front channel, `None` for a | |
| 1452 | + /// mono track. The reason is [`ac3_decoder`]'s `ponytail`, not this file's. | |
| 1453 | + requested: Option<u16>, | |
| 1454 | +} | |
| 1455 | + | |
| 1456 | +impl MkvAc3Track { | |
| 1457 | + /// `Ok(None)` when the file's first audio track is not AC-3 or E-AC-3 — | |
| 1458 | + /// that mkv is the silent source it has always been. An `Err` is a track | |
| 1459 | + /// that is one and could not be read, which | |
| 1460 | + /// [`AudioSession::unsupported`] quotes back to the user. | |
| 1461 | + fn open(path: &Path) -> crate::Result<Option<Self>> { | |
| 1462 | + let Some(mut mkv) = crate::demux::MkvAudio::open(path)? else { | |
| 1463 | + return Ok(None); | |
| 1464 | + }; | |
| 1465 | + let first = mkv | |
| 1466 | + .frame(0)? | |
| 1467 | + .ok_or("the AC-3 track of this Matroska file has no blocks")?; | |
| 1468 | + // Rate and layout come out of the bit stream, which is where AC-3 | |
| 1469 | + // states them: Matroska's `Audio` element repeats them and muxers get | |
| 1470 | + // that wrong often enough that the frame is the better source. | |
| 1471 | + // `nfchans` excludes the LFE in both syntaxes, which is what the | |
| 1472 | + // downmix decision wants. | |
| 1473 | + let (sample_rate, nfchans) = if mkv.codec == "eac3" { | |
| 1474 | + // Annex E's BSI starts right after the 16-bit syncword. | |
| 1475 | + let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default()) | |
| 1476 | + .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?; | |
| 1477 | + (bsi.sample_rate, bsi.nfchans) | |
| 1478 | + } else { | |
| 1479 | + let sync = oxideav_ac3::syncinfo::parse(&first) | |
| 1480 | + .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?; | |
| 1481 | + let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default()) | |
| 1482 | + .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?; | |
| 1483 | + (sync.sample_rate, bsi.nfchans) | |
| 1484 | + }; | |
| 1485 | + let requested = (nfchans > 1).then_some(2); | |
| 1486 | + let mut decoder = ac3_decoder(mkv.codec, requested)?; | |
| 1487 | + let (pcm, samples) = | |
| 1488 | + decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?; | |
| 1489 | + let channels = (pcm.len() as u64 / samples.max(1)) as u16; | |
| 1490 | + if channels == 0 { | |
| 1491 | + return Err("the first AC-3 syncframe decoded to nothing".into()); | |
| 1492 | + } | |
| 1493 | + // The track runs to the last block's timestamp plus that block's own | |
| 1494 | + // frame -- a container that indexes nothing states no duration either, | |
| 1495 | + // and every frame of a syncframe stream is the same length. | |
| 1496 | + let last = mkv.secs(mkv.blocks().saturating_sub(1)); | |
| 1497 | + Ok(Some(Self { | |
| 1498 | + total_samples: Some((last * f64::from(sample_rate)) as u64 + samples), | |
| 1499 | + sample_rate, | |
| 1500 | + channels, | |
| 1501 | + requested, | |
| 1502 | + mkv, | |
| 1503 | + })) | |
| 1504 | + } | |
| 1505 | + | |
| 1506 | + /// `secs` on this source's timeline into media samples. No priming: the | |
| 1507 | + /// container carries no edit list and AC-3 no encoder delay. | |
| 1508 | + fn media(&self, secs: f64) -> u64 { | |
| 1509 | + (secs.max(0.0) * f64::from(self.sample_rate)) as u64 | |
| 1510 | + } | |
| 1511 | + | |
| 1512 | + /// One `[start, end)` window, resolved to blocks and media samples — | |
| 1513 | + /// [`Ac3Track::segment`] against block timestamps instead of an `stts`. | |
| 1514 | + fn segment(&self, source: usize, start_secs: f64, end_secs: f64) -> Segment { | |
| 1515 | + let media_target = self.media(start_secs); | |
| 1516 | + let start_id = self.mkv.block_at(start_secs, AC3_PRE_ROLL as usize); | |
| 1517 | + Segment { | |
| 1518 | + source: Some(source), | |
| 1519 | + start_id: start_id as u32, | |
| 1520 | + start_pos: self.media(self.mkv.secs(start_id)), | |
| 1521 | + media_target, | |
| 1522 | + media_end: self.media(end_secs).max(media_target), | |
| 1523 | + } | |
| 1524 | + } | |
| 1525 | +} | |
| 1526 | + | |
| 1385 | 1527 | /// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own |
| 1386 | 1528 | /// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a |
| 1387 | 1529 | /// 5.1 track at all. Fresh per segment for the same reason every other decoder |
| @@ -1392,32 +1534,47 @@ impl Ac3Track { | ||
| 1392 | 1534 | /// mono track asks for no downmix at all and stays the mono source it is. The |
| 1393 | 1535 | /// upgrade path is `Some(2)` unconditionally once the library duplicates the |
| 1394 | 1536 | /// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. |
| 1395 | -fn ac3_decoder(channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> { | |
| 1537 | +/// | |
| 1538 | +/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers | |
| 1539 | +/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct | |
| 1540 | +/// behind both dispatches per packet on `bsid` in any case, so what this picks | |
| 1541 | +/// is the capability set, not the syntax. | |
| 1542 | +fn ac3_decoder(codec: &str, channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> { | |
| 1396 | 1543 | let mut registry = CodecRegistry::new(); |
| 1397 | 1544 | oxideav_ac3::register_codecs(&mut registry); |
| 1398 | - let mut params = CodecParameters::audio(CodecId::new("ac3")); | |
| 1545 | + let mut params = CodecParameters::audio(CodecId::new(codec)); | |
| 1399 | 1546 | params.channels = channels; |
| 1400 | 1547 | registry |
| 1401 | 1548 | .first_decoder(¶ms) |
| 1402 | 1549 | .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) |
| 1403 | 1550 | } |
| 1404 | 1551 | |
| 1405 | -/// One syncframe in, one buffer of interleaved f32 out. `Ok(None)` when the | |
| 1406 | -/// decoder wants more input before it can hand a frame back, which is not an | |
| 1407 | -/// error. The library speaks S16 little-endian; `/32768` is the whole | |
| 1408 | -/// conversion, and it lands in the `[-1, 1)` every other reader here emits. | |
| 1409 | -fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> crate::Result<Option<Vec<f32>>> { | |
| 1552 | +/// One syncframe in, one buffer of interleaved f32 out and the frames per | |
| 1553 | +/// channel it holds. `Ok(None)` when the decoder wants more input before it can | |
| 1554 | +/// hand a frame back, which is not an error. The library speaks S16 | |
| 1555 | +/// little-endian; `/32768` is the whole conversion, and it lands in the | |
| 1556 | +/// `[-1, 1)` every other reader here emits. | |
| 1557 | +/// | |
| 1558 | +/// The frame count comes back beside the samples because an E-AC-3 frame is not | |
| 1559 | +/// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2 | |
| 1560 | +/// or 3 blocks instead of 6 -- and dividing by an assumed length would put the | |
| 1561 | +/// channel count and every media position after it out. | |
| 1562 | +fn decode_ac3( | |
| 1563 | + decoder: &mut Box<dyn Decoder>, | |
| 1564 | + bytes: &[u8], | |
| 1565 | +) -> crate::Result<Option<(Vec<f32>, u64)>> { | |
| 1410 | 1566 | let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); |
| 1411 | 1567 | decoder |
| 1412 | 1568 | .send_packet(&packet) |
| 1413 | 1569 | .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; |
| 1414 | 1570 | match decoder.receive_frame() { |
| 1415 | - Ok(Frame::Audio(audio)) => Ok(Some( | |
| 1571 | + Ok(Frame::Audio(audio)) => Ok(Some(( | |
| 1416 | 1572 | audio.data[0] |
| 1417 | 1573 | .chunks_exact(2) |
| 1418 | 1574 | .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) |
| 1419 | 1575 | .collect(), |
| 1420 | - )), | |
| 1576 | + u64::from(audio.samples), | |
| 1577 | + ))), | |
| 1421 | 1578 | Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), |
| 1422 | 1579 | Err(oxideav_core::Error::NeedMore) => Ok(None), |
| 1423 | 1580 | Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), |
| @@ -2035,6 +2192,21 @@ fn run(mut w: Worker) { | ||
| 2035 | 2192 | } |
| 2036 | 2193 | continue; |
| 2037 | 2194 | } |
| 2195 | + Track::Mkv(track) => { | |
| 2196 | + if !run_mkv_ac3( | |
| 2197 | + track, | |
| 2198 | + seg, | |
| 2199 | + eq.as_mut(), | |
| 2200 | + speed, | |
| 2201 | + channels, | |
| 2202 | + &mut timeline, | |
| 2203 | + &w.tx, | |
| 2204 | + ) || !settle(speed, channels, &mut timeline, &w.tx) | |
| 2205 | + { | |
| 2206 | + return; // consumer went away | |
| 2207 | + } | |
| 2208 | + continue; | |
| 2209 | + } | |
| 2038 | 2210 | Track::Ac3(track) => { |
| 2039 | 2211 | if !run_ac3( |
| 2040 | 2212 | track, |
| @@ -2200,7 +2372,7 @@ fn run_ac3( | ||
| 2200 | 2372 | timeline: &mut u64, |
| 2201 | 2373 | tx: &SyncSender<AudioChunk>, |
| 2202 | 2374 | ) -> bool { |
| 2203 | - let mut decoder = match ac3_decoder(track.requested) { | |
| 2375 | + let mut decoder = match ac3_decoder("ac3", track.requested) { | |
| 2204 | 2376 | Ok(decoder) => decoder, |
| 2205 | 2377 | Err(e) => { |
| 2206 | 2378 | eprintln!("audio decoder init failed: {e}"); |
| @@ -2209,7 +2381,6 @@ fn run_ac3( | ||
| 2209 | 2381 | }; |
| 2210 | 2382 | let mut pos = seg.start_pos; |
| 2211 | 2383 | for id in seg.start_id..=track.sample_count { |
| 2212 | - let mut interleaved; | |
| 2213 | 2384 | if pos >= seg.media_end { |
| 2214 | 2385 | return true; // segment done, on to the next one |
| 2215 | 2386 | } |
| @@ -2221,15 +2392,75 @@ fn run_ac3( | ||
| 2221 | 2392 | return true; |
| 2222 | 2393 | } |
| 2223 | 2394 | }; |
| 2224 | - match decode_ac3(&mut decoder, &sample.bytes) { | |
| 2225 | - Ok(Some(pcm)) => interleaved = pcm, | |
| 2395 | + let (mut interleaved, samples) = match decode_ac3(&mut decoder, &sample.bytes) { | |
| 2396 | + Ok(Some(decoded)) => decoded, | |
| 2226 | 2397 | Ok(None) => continue, // the decoder wants another frame first |
| 2227 | 2398 | Err(e) => { |
| 2228 | 2399 | eprintln!("audio decode error at sample {id}: {e}"); |
| 2229 | 2400 | return true; |
| 2230 | 2401 | } |
| 2402 | + }; | |
| 2403 | + let next = pos + samples; | |
| 2404 | + if !emit( | |
| 2405 | + &mut interleaved, | |
| 2406 | + channels, | |
| 2407 | + seg, | |
| 2408 | + eq.as_deref_mut(), | |
| 2409 | + speed.as_mut(), | |
| 2410 | + pos, | |
| 2411 | + next, | |
| 2412 | + timeline, | |
| 2413 | + tx, | |
| 2414 | + ) { | |
| 2415 | + return false; | |
| 2231 | 2416 | } |
| 2232 | - let next = pos + (interleaved.len() / channels) as u64; | |
| 2417 | + pos = next; | |
| 2418 | + } | |
| 2419 | + true | |
| 2420 | +} | |
| 2421 | + | |
| 2422 | +/// One segment of a Matroska AC-3 / E-AC-3 track: [`run_ac3`] reading blocks | |
| 2423 | +/// instead of mp4 samples. The decoder, the window rules ([`emit`]) and the | |
| 2424 | +/// stereo downmix are the same ones; only where a packet comes from differs. | |
| 2425 | +/// `false` means the consumer went away. | |
| 2426 | +fn run_mkv_ac3( | |
| 2427 | + track: &mut MkvAc3Track, | |
| 2428 | + seg: &Segment, | |
| 2429 | + mut eq: Option<&mut EqState>, | |
| 2430 | + speed: &mut Option<Resample>, | |
| 2431 | + channels: usize, | |
| 2432 | + timeline: &mut u64, | |
| 2433 | + tx: &SyncSender<AudioChunk>, | |
| 2434 | +) -> bool { | |
| 2435 | + let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) { | |
| 2436 | + Ok(decoder) => decoder, | |
| 2437 | + Err(e) => { | |
| 2438 | + eprintln!("audio decoder init failed: {e}"); | |
| 2439 | + return true; | |
| 2440 | + } | |
| 2441 | + }; | |
| 2442 | + let mut pos = seg.start_pos; | |
| 2443 | + for id in seg.start_id as usize.. { | |
| 2444 | + if pos >= seg.media_end { | |
| 2445 | + return true; // segment done, on to the next one | |
| 2446 | + } | |
| 2447 | + let block = match track.mkv.frame(id) { | |
| 2448 | + Ok(Some(bytes)) => bytes, | |
| 2449 | + Ok(None) => return true, // end of the track | |
| 2450 | + Err(e) => { | |
| 2451 | + eprintln!("audio demux error at block {id}: {e}"); | |
| 2452 | + return true; | |
| 2453 | + } | |
| 2454 | + }; | |
| 2455 | + let (mut interleaved, samples) = match decode_ac3(&mut decoder, &block) { | |
| 2456 | + Ok(Some(decoded)) => decoded, | |
| 2457 | + Ok(None) => continue, // the decoder wants another frame first | |
| 2458 | + Err(e) => { | |
| 2459 | + eprintln!("audio decode error at block {id}: {e}"); | |
| 2460 | + return true; | |
| 2461 | + } | |
| 2462 | + }; | |
| 2463 | + let next = pos + samples; | |
| 2233 | 2464 | if !emit( |
| 2234 | 2465 | &mut interleaved, |
| 2235 | 2466 | channels, |
crates/engine/src/demux.rsmodified+122 -21
| @@ -329,15 +329,18 @@ impl Mp4Demuxer { | ||
| 329 | 329 | } |
| 330 | 330 | } |
| 331 | 331 | |
| 332 | -/// One Matroska block of the video track: where its bytes are and whether a | |
| 333 | -/// decoder may start on it. 16 bytes an entry, so an hour of 30 fps costs ~1.7 | |
| 334 | -/// MB of index -- the price of knowing the frame count and the sync points of a | |
| 332 | +/// One Matroska block of an indexed track: where its bytes are, whether a | |
| 333 | +/// decoder may start on it, and when it is presented (in `TimestampScale` | |
| 334 | +/// ticks, which is what a sound track seeks against -- Matroska indexes no | |
| 335 | +/// samples either). 24 bytes an entry, so an hour of 30 fps costs ~2.6 MB of | |
| 336 | +/// index -- the price of knowing the frame count and the sync points of a | |
| 335 | 337 | /// container that indexes neither. |
| 336 | 338 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 337 | 339 | struct Block { |
| 338 | 340 | at: u64, |
| 339 | 341 | len: usize, |
| 340 | 342 | key: bool, |
| 343 | + ts: i64, | |
| 341 | 344 | } |
| 342 | 345 | |
| 343 | 346 | /// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`). |
| @@ -378,7 +381,7 @@ impl MkvDemuxer { | ||
| 378 | 381 | let mut file = File::open(path)?; |
| 379 | 382 | let end = file.metadata()?.len(); |
| 380 | 383 | let segment = mkv_segment(&mut file, end)?; |
| 381 | - let (video, _, other) = mkv_tracks(&mut file, segment)?; | |
| 384 | + let (video, _, other, _) = mkv_tracks(&mut file, segment)?; | |
| 382 | 385 | let video = match video { |
| 383 | 386 | Some(video) => video, |
| 384 | 387 | // Named, because "no video track" is a lie about a file that has one |
| @@ -487,13 +490,99 @@ impl MkvDemuxer { | ||
| 487 | 490 | |
| 488 | 491 | /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or |
| 489 | 492 | /// `None` for a Matroska file with no sound at all. Header only, and only worth |
| 490 | -/// calling once a session has come up silent: no audio track of a Matroska file | |
| 491 | -/// is decoded yet, so this exists to say which one is being left out. | |
| 493 | +/// calling once a session has come up silent: a Matroska file's sound is read | |
| 494 | +/// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and | |
| 495 | +/// this exists to say which codec neither of them took. | |
| 492 | 496 | pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> { |
| 493 | 497 | let mut file = File::open(path)?; |
| 494 | 498 | let end = file.metadata()?.len(); |
| 495 | 499 | let segment = mkv_segment(&mut file, end)?; |
| 496 | - Ok(mkv_tracks(&mut file, segment)?.1) | |
| 500 | + Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec)| codec)) | |
| 501 | +} | |
| 502 | + | |
| 503 | +/// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio | |
| 504 | +/// track, in storage order, with the timestamp a seek resolves against. The | |
| 505 | +/// same walk the picture costs ([`MkvDemuxer`]), on the other track number, and | |
| 506 | +/// the two keep their own file handle and their own index -- the sound is | |
| 507 | +/// opened by the audio worker and the picture by the decoder, never together. | |
| 508 | +/// | |
| 509 | +/// Matroska carries no sample table, so a block's own timestamp is the only | |
| 510 | +/// thing a window can be resolved against; [`Self::block_at`] is what an `stts` | |
| 511 | +/// lookup is on the mp4 side. | |
| 512 | +pub struct MkvAudio { | |
| 513 | + file: File, | |
| 514 | + blocks: Vec<Block>, | |
| 515 | + /// The `oxideav-ac3` codec id these blocks are packets of: `ac3` or `eac3`. | |
| 516 | + pub codec: &'static str, | |
| 517 | + /// Seconds one `TimestampScale` tick is worth, resolved once at open. | |
| 518 | + secs_per_tick: f64, | |
| 519 | +} | |
| 520 | + | |
| 521 | +impl MkvAudio { | |
| 522 | + /// `Ok(None)` when `path` has no audio track at all, or when its first one | |
| 523 | + /// is in a codec nothing here decodes -- that file is the silent source it | |
| 524 | + /// has always been, and [`crate::audio::AudioSession::unsupported`] names | |
| 525 | + /// the codec. An `Err` is a track that *is* AC-3 and could not be read. | |
| 526 | + pub fn open(path: &Path) -> crate::Result<Option<Self>> { | |
| 527 | + let mut file = File::open(path)?; | |
| 528 | + let end = file.metadata()?.len(); | |
| 529 | + let segment = mkv_segment(&mut file, end)?; | |
| 530 | + let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?; | |
| 531 | + let Some((number, codec)) = audio else { | |
| 532 | + return Ok(None); | |
| 533 | + }; | |
| 534 | + let codec = match codec.as_str() { | |
| 535 | + "A_AC3" => "ac3", | |
| 536 | + "A_EAC3" => "eac3", | |
| 537 | + _ => return Ok(None), | |
| 538 | + }; | |
| 539 | + let (blocks, _) = mkv_blocks(&mut file, segment, number)?; | |
| 540 | + if blocks.is_empty() { | |
| 541 | + return Err("the AC-3 track in this Matroska file has no blocks".into()); | |
| 542 | + } | |
| 543 | + Ok(Some(Self { | |
| 544 | + file, | |
| 545 | + blocks, | |
| 546 | + codec, | |
| 547 | + secs_per_tick: timestamp_scale as f64 / 1e9, | |
| 548 | + })) | |
| 549 | + } | |
| 550 | + | |
| 551 | + /// How many blocks the track has; one syncframe each, lacing being refused | |
| 552 | + /// in [`mkv_blocks`]. | |
| 553 | + pub fn blocks(&self) -> usize { | |
| 554 | + self.blocks.len() | |
| 555 | + } | |
| 556 | + | |
| 557 | + /// The bytes of block `index` -- one whole packet for the decoder, an | |
| 558 | + /// E-AC-3 frame's dependent substreams included. `None` past the last one. | |
| 559 | + pub fn frame(&mut self, index: usize) -> crate::Result<Option<Vec<u8>>> { | |
| 560 | + let Some(&block) = self.blocks.get(index) else { | |
| 561 | + return Ok(None); | |
| 562 | + }; | |
| 563 | + let mut bytes = vec![0u8; block.len]; | |
| 564 | + read_exact_at(&mut self.file, block.at, &mut bytes)?; | |
| 565 | + Ok(Some(bytes)) | |
| 566 | + } | |
| 567 | + | |
| 568 | + /// When block `index` is presented, in seconds on the file's own clock. The | |
| 569 | + /// last block's time for anything past the end, which is what a duration | |
| 570 | + /// wants. | |
| 571 | + pub fn secs(&self, index: usize) -> f64 { | |
| 572 | + let index = index.min(self.blocks.len().saturating_sub(1)); | |
| 573 | + self.blocks.get(index).map_or(0.0, |b| b.ts as f64) * self.secs_per_tick | |
| 574 | + } | |
| 575 | + | |
| 576 | + /// The block a decoder is started from to hear `secs`: the last one at or | |
| 577 | + /// before it, `pre_roll` blocks earlier so the decoder has something to warm | |
| 578 | + /// up on before the audible part. Blocks are in storage order, which for a | |
| 579 | + /// sound track is presentation order (no reordering exists in AC-3). | |
| 580 | + pub fn block_at(&self, secs: f64, pre_roll: usize) -> usize { | |
| 581 | + let ticks = (secs / self.secs_per_tick) as i64; | |
| 582 | + self.blocks | |
| 583 | + .partition_point(|b| b.ts <= ticks) | |
| 584 | + .saturating_sub(1 + pre_roll) | |
| 585 | + } | |
| 497 | 586 | } |
| 498 | 587 | |
| 499 | 588 | /// What the `Tracks` element says about the video track. |
| @@ -543,17 +632,19 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { | ||
| 543 | 632 | Err("no Segment element: not a Matroska file".into()) |
| 544 | 633 | } |
| 545 | 634 | |
| 546 | -/// The video track of `segment`, the codec id of its first audio track, and the | |
| 547 | -/// codec id of a video track this cannot read -- the last two are what tell a | |
| 548 | -/// user why a file plays silent ([`crate::audio::AudioSession::unsupported`]) | |
| 549 | -/// or refuses to open at all. | |
| 635 | +/// The video track of `segment`, the number and codec id of its first audio | |
| 636 | +/// track, the codec id of a video track this cannot read, and the segment's | |
| 637 | +/// `TimestampScale` in nanoseconds. The audio pair is what [`MkvAudio`] reads a | |
| 638 | +/// sound track from; it and the other codec id are what tell a user why a file | |
| 639 | +/// plays silent ([`crate::audio::AudioSession::unsupported`]) or refuses to | |
| 640 | +/// open at all. | |
| 550 | 641 | /// |
| 551 | 642 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful |
| 552 | 643 | /// of seeks whatever the file weighs. |
| 553 | 644 | fn mkv_tracks( |
| 554 | 645 | file: &mut File, |
| 555 | 646 | segment: (u64, u64), |
| 556 | -) -> crate::Result<(Option<MkvVideo>, Option<String>, Option<String>)> { | |
| 647 | +) -> crate::Result<(Option<MkvVideo>, Option<(u64, String)>, Option<String>, u64)> { | |
| 557 | 648 | let (mut video, mut audio, mut other) = (None, None, None); |
| 558 | 649 | let mut timestamp_scale = 1_000_000; |
| 559 | 650 | let mut at = segment.0; |
| @@ -576,7 +667,9 @@ fn mkv_tracks( | ||
| 576 | 667 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { |
| 577 | 668 | MkvEntry::Video(track) if video.is_none() => video = Some(track), |
| 578 | 669 | MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), |
| 579 | - MkvEntry::Audio(codec) if audio.is_none() => audio = Some(codec), | |
| 670 | + MkvEntry::Audio(number, codec) if audio.is_none() => { | |
| 671 | + audio = Some((number, codec)) | |
| 672 | + } | |
| 580 | 673 | _ => {} |
| 581 | 674 | } |
| 582 | 675 | } |
| @@ -587,7 +680,7 @@ fn mkv_tracks( | ||
| 587 | 680 | } |
| 588 | 681 | at = stop; |
| 589 | 682 | } |
| 590 | - Ok((video, audio, other)) | |
| 683 | + Ok((video, audio, other, timestamp_scale)) | |
| 591 | 684 | } |
| 592 | 685 | |
| 593 | 686 | /// What one `TrackEntry` turned out to be. |
| @@ -595,8 +688,9 @@ enum MkvEntry { | ||
| 595 | 688 | Video(MkvVideo), |
| 596 | 689 | /// A video track in a codec this does not read, by the name it gives itself. |
| 597 | 690 | OtherVideo(String), |
| 598 | - /// An audio track, likewise by its codec id (`A_AAC`, `A_OPUS`, ...). | |
| 599 | - Audio(String), | |
| 691 | + /// An audio track: its track number, which is what [`MkvAudio`] indexes the | |
| 692 | + /// blocks of, and its codec id (`A_AAC`, `A_EAC3`, ...). | |
| 693 | + Audio(u64, String), | |
| 600 | 694 | /// Subtitles, buttons: nobody's here. |
| 601 | 695 | Other, |
| 602 | 696 | } |
| @@ -658,7 +752,7 @@ fn mkv_track_entry( | ||
| 658 | 752 | (Codec::H264, nal_length, sets, 8) |
| 659 | 753 | } |
| 660 | 754 | (1, _) => return Ok(MkvEntry::OtherVideo(codec)), |
| 661 | - (2, _) => return Ok(MkvEntry::Audio(codec)), | |
| 755 | + (2, _) => return Ok(MkvEntry::Audio(number, codec)), | |
| 662 | 756 | _ => return Ok(MkvEntry::Other), |
| 663 | 757 | }; |
| 664 | 758 | Ok(MkvEntry::Video(MkvVideo { |
| @@ -807,11 +901,17 @@ fn mkv_blocks( | ||
| 807 | 901 | if block.number != number { |
| 808 | 902 | continue; |
| 809 | 903 | } |
| 810 | - // Lacing packs several frames into one block. Audio muxers use it, | |
| 811 | - // video ones do not, and guessing at frame boundaries inside a laced | |
| 812 | - // block is not something to do silently. | |
| 904 | + // Lacing packs several frames into one block, behind a header of | |
| 905 | + // frame sizes this does not read. Video muxers write none; an audio | |
| 906 | + // muxer may, and guessing at frame boundaries inside a laced block | |
| 907 | + // is not something to do silently. | |
| 908 | + // | |
| 909 | + // ponytail: a laced audio track is refused by name rather than | |
| 910 | + // played. The upgrade path is the three lace headers of the spec | |
| 911 | + // (Xiph, fixed, EBML) read here into one `Block` per frame; ffmpeg, | |
| 912 | + // which writes the fixtures and most remuxes, laces nothing. | |
| 813 | 913 | if block.flags & 0x06 != 0 { |
| 814 | - return Err("laced video blocks are not supported".into()); | |
| 914 | + return Err("laced Matroska blocks are not supported".into()); | |
| 815 | 915 | } |
| 816 | 916 | let ts = cluster_ts + i64::from(block.rel); |
| 817 | 917 | span = Some(match span { |
| @@ -822,6 +922,7 @@ fn mkv_blocks( | ||
| 822 | 922 | at: block.at, |
| 823 | 923 | len: block.len, |
| 824 | 924 | key, |
| 925 | + ts, | |
| 825 | 926 | }); |
| 826 | 927 | } |
| 827 | 928 | } |
crates/engine/tests/audio_decode.rsmodified+97 -0
| @@ -160,6 +160,103 @@ 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: the AAC track of a Matroska file is | |
| 212 | + // still symphonia's, listed and decoded exactly as it was. | |
| 213 | + let streams = AudioSession::probe_streams(asset("test_av1.mkv")).expect("streams"); | |
| 214 | + assert_eq!(streams.len(), 1); | |
| 215 | + assert_eq!(streams[0].codec, "aac", "AAC in an mkv is untouched by this"); | |
| 216 | + assert!( | |
| 217 | + AudioSession::open(asset("test_av1.mkv")) | |
| 218 | + .expect("open") | |
| 219 | + .is_some(), | |
| 220 | + "AAC in an mkv still decodes" | |
| 221 | + ); | |
| 222 | +} | |
| 223 | + | |
| 224 | +/// A seek into a Matroska AC-3 track: Matroska indexes no samples, so the block | |
| 225 | +/// a decode starts on is found by the blocks' own timestamps -- and getting that | |
| 226 | +/// wrong is a tail that is the wrong length or lands in the wrong place. It is | |
| 227 | +/// the same check `audio_seek` makes of the mp4 path, on the container that has | |
| 228 | +/// no sample table. | |
| 229 | +#[test] | |
| 230 | +fn a_seek_into_a_matroska_ac3_track_is_the_tail_of_a_full_run() { | |
| 231 | + let path = asset("test_eac3.mkv"); | |
| 232 | + let full: Vec<f32> = AudioSession::open(&path) | |
| 233 | + .expect("open") | |
| 234 | + .expect("audio") | |
| 235 | + .1 | |
| 236 | + .into_iter() | |
| 237 | + .flat_map(|c| c.samples) | |
| 238 | + .collect(); | |
| 239 | + let start = 48_000u64; // one second in, in frames per channel | |
| 240 | + let mut next = start; | |
| 241 | + let mut tail = Vec::new(); | |
| 242 | + for chunk in AudioSession::open_at(&path, 1.0).expect("open").expect("audio").1 { | |
| 243 | + assert_eq!(chunk.start_sample, next, "a seeked run numbers from the seek"); | |
| 244 | + next += (chunk.samples.len() / 2) as u64; | |
| 245 | + tail.extend(chunk.samples); | |
| 246 | + } | |
| 247 | + let want = &full[start as usize * 2..]; | |
| 248 | + assert_eq!(tail.len(), want.len(), "the seeked run is a different length"); | |
| 249 | + let diff = tail | |
| 250 | + .iter() | |
| 251 | + .zip(want) | |
| 252 | + .map(|(a, b)| (a - b).abs()) | |
| 253 | + .fold(0.0f32, f32::max); | |
| 254 | + // One syncframe of pre-roll is what the 256-sample overlap-add needs, so | |
| 255 | + // this is exact in practice; the tolerance is for a decoder that carries | |
| 256 | + // more state than the frame before, not for a wrong block. | |
| 257 | + assert!(diff < 1e-3, "max abs diff {diff} after the seek"); | |
| 258 | +} | |
| 259 | + | |
| 163 | 260 | /// An AC-3 syncframe is not something an `mp4a` sample table holds, so the |
| 164 | 261 | /// *copy* path names it and hands the export on to the re-encode (which decodes |
| 165 | 262 | /// this very source: the downmix above is what it encodes). Named either way -- |
scripts/gen_fixtures.shmodified+21 -2
| @@ -104,8 +104,9 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 104 | 104 | # the others so the tests measure the codec and nothing else -- but `-g 30` is |
| 105 | 105 | # not a preference: it puts a second keyframe at frame 30, which is what the |
| 106 | 106 | # sync index and the seek test are checked against. 8-bit Main profile here; the |
| 107 | -# 10-bit twin is below. Its AAC track is deliberate too: Matroska audio is not | |
| 108 | -# wired to the decoder yet, and the notice that says so needs a track to name. | |
| 107 | +# 10-bit twin is below. Its AAC track is deliberate too: it is the AAC a Matroska | |
| 108 | +# file's sound is read out of through symphonia, beside the AC-3 fixtures further | |
| 109 | +# down that no symphonia version decodes. | |
| 109 | 110 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ |
| 110 | 111 | -f lavfi -i "sine=frequency=440:duration=2" \ |
| 111 | 112 | -f lavfi -i "sine=frequency=880:duration=2" \ |
| @@ -176,6 +177,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 176 | 177 | -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \ |
| 177 | 178 | -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \ |
| 178 | 179 | -c:a aac -b:a 384k assets/test_hevc10.mkv |
| 180 | +# Matroska sound: the two Dolby codecs that arrive in one and are read straight | |
| 181 | +# out of its blocks (`demux::MkvAudio`). Stereo AC-3 for the plain syntax and | |
| 182 | +# **5.1 E-AC-3** for Annex E -- the shape a remux has, and the one that must | |
| 183 | +# come down to stereo through the same A/52 7.8 downmix the mp4 path uses. | |
| 184 | +# 48 kHz both, which is the only rate E-AC-3 is written at in practice. Small | |
| 185 | +# H.264 picture on purpose: these two are about the sound, and the software | |
| 186 | +# decoder reads that one, so an audio test needs no VA-API plugin to open a | |
| 187 | +# session on them. | |
| 188 | +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | |
| 189 | + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | |
| 190 | + -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \ | |
| 191 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a]" \ | |
| 192 | + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | |
| 193 | + -c:a ac3 -b:a 192k assets/test_ac3.mkv | |
| 194 | +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | |
| 195 | + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | |
| 196 | + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | |
| 197 | + -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv | |
| 179 | 198 | # Sync fixture: one flash and one beep, at the same instant. Black picture with |
| 180 | 199 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that |
| 181 | 200 | # stretch — so a test can find each of them and say how far apart they came out. |