Every audio track of an mkv is a row, and the second one plays
Browse files at this commit264c10cb1283bef8c9fc4abec02360e65520f933Parent: 0a39fae- feat
- every audio track of an mkv is a row, and the second one plays
4 changed files +350 -63
- crates/engine/src/audio.rs +120 -38
- crates/engine/src/demux.rs +86 -25
- crates/engine/tests/audio_streams.rs +126 -0
- scripts/gen_fixtures.sh +18 -0
crates/engine/src/audio.rsmodified+120 -38
| @@ -712,40 +712,55 @@ impl AudioSession { | |||
| 712 | /// and an ALAC `.m4a` only half is. | 712 | /// and an ALAC `.m4a` only half is. |
| 713 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { | 713 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { |
| 714 | let path = path.as_ref(); | 714 | let path = path.as_ref(); |
| 715 | - // A Matroska file has exactly one readable audio stream here -- the | 715 | + // A Matroska file lists one row per `TrackEntry` of audio, in the order |
| 716 | - // reader's default track ([`SymTrack::open`]), or the AC-3 / E-AC-3 one | 716 | + // its `Tracks` element gives them -- a dual-audio remux has two, and the |
| 717 | - // symphonia has no decoder for ([`MkvAc3Track`]) -- so it lists like a | 717 | + // second one used to be invisible. A file whose header will not walk at |
| 718 | - // standalone audio file rather than like an mp4, and one with no | 718 | + // all is an `Err` here, as it is in [`Track::open`]: a listing that |
| 719 | - // readable track at all lists as the silent source it is. | 719 | + // quietly came back empty for a broken file is how a lane ends up silent |
| 720 | + // with nothing to go on. No audio track at all is an empty list, which | ||
| 721 | + // is the silent source it says it is. | ||
| 720 | if crate::demux::is_matroska(path) { | 722 | if crate::demux::is_matroska(path) { |
| 721 | - // The AC-3 row describes what the decoder *emits*, which is the | 723 | + let mut streams = Vec::new(); |
| 722 | - // stereo the §7.8 downmix hands the timeline, not the 5.1 the file | 724 | + for (index, entry) in crate::demux::matroska_audio_tracks(path)? |
| 723 | - // carries -- exactly as the mp4 AC-3 rows do. | 725 | + .iter() |
| 724 | - if let Ok(Some(track)) = MkvAc3Track::open(path) { | 726 | + .enumerate() |
| 725 | - return Ok(vec![StreamInfo { | 727 | + { |
| 726 | - index: 0, | 728 | + // The routing [`Track::open`] does, one row at a time, so a row |
| 727 | - codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(), | 729 | + // describes the track that would really open: AC-3 and E-AC-3 |
| 728 | - channels: track.channels, | 730 | + // through the Dolby decoder's own reader, everything else |
| 729 | - sample_rate: track.sample_rate, | 731 | + // through symphonia. The AC-3 row describes what the decoder |
| 730 | - lang: None, | 732 | + // *emits*, which is the stereo the §7.8 downmix hands the |
| 731 | - decodable: matches!(track.channels, 1 | 2), | 733 | + // timeline, not the 5.1 the file carries -- exactly as the mp4 |
| 732 | - }]); | 734 | + // AC-3 rows do. |
| 735 | + let ac3 = matches!(entry.codec.as_str(), "A_AC3" | "A_EAC3") | ||
| 736 | + .then(|| MkvAc3Track::open_track(path, entry.number).ok().flatten()) | ||
| 737 | + .flatten(); | ||
| 738 | + // A track symphonia cannot even describe is listed undecodable | ||
| 739 | + // by the name the container gives it, rather than taking the | ||
| 740 | + // whole listing down with it: the other language still plays. | ||
| 741 | + let sym = match &ac3 { | ||
| 742 | + Some(_) => None, | ||
| 743 | + None => SymTrack::open_track(path, entry.number).ok().flatten(), | ||
| 744 | + }; | ||
| 745 | + let channels = ac3.as_ref().map_or_else( | ||
| 746 | + || sym.as_ref().map_or(0, |t| t.channels), | ||
| 747 | + |t| t.channels, | ||
| 748 | + ); | ||
| 749 | + streams.push(StreamInfo { | ||
| 750 | + index, | ||
| 751 | + codec: mkv_codec_name(&entry.codec), | ||
| 752 | + channels, | ||
| 753 | + sample_rate: ac3.as_ref().map_or_else( | ||
| 754 | + || sym.as_ref().map_or(0, |t| t.sample_rate), | ||
| 755 | + |t| t.sample_rate, | ||
| 756 | + ), | ||
| 757 | + lang: (entry.language != "und" && !entry.language.is_empty()) | ||
| 758 | + .then(|| entry.language.clone()), | ||
| 759 | + decodable: matches!(channels, 1 | 2) | ||
| 760 | + && (ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok())), | ||
| 761 | + }); | ||
| 733 | } | 762 | } |
| 734 | - // No audio track lists as the silent source it is; a track that | 763 | + return Ok(streams); |
| 735 | - // will not open at all is an `Err` here, as it is in | ||
| 736 | - // [`Track::open`] -- a listing that quietly came back empty for a | ||
| 737 | - // broken file is how a lane ends up silent with nothing to go on. | ||
| 738 | - let Some(track) = SymTrack::open(path)? else { | ||
| 739 | - return Ok(Vec::new()); | ||
| 740 | - }; | ||
| 741 | - return Ok(vec![StreamInfo { | ||
| 742 | - index: 0, | ||
| 743 | - codec: track.codec.into(), | ||
| 744 | - channels: track.channels, | ||
| 745 | - sample_rate: track.sample_rate, | ||
| 746 | - lang: None, | ||
| 747 | - decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(), | ||
| 748 | - }]); | ||
| 749 | } | 764 | } |
| 750 | if crate::is_audio(path) { | 765 | if crate::is_audio(path) { |
| 751 | let track = SymTrack::open_required(path)?; | 766 | let track = SymTrack::open_required(path)?; |
| @@ -1123,10 +1138,26 @@ impl Track { | |||
| 1123 | // failing the import of a file whose picture is fine. A track that will | 1138 | // failing the import of a file whose picture is fine. A track that will |
| 1124 | // not open at all is *not* in that group: see below. | 1139 | // not open at all is *not* in that group: see below. |
| 1125 | if crate::demux::is_matroska(path) { | 1140 | if crate::demux::is_matroska(path) { |
| 1126 | - if stream > 0 { | 1141 | + // File order, the one `probe_streams` lists and a project saves: |
| 1127 | - return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); | 1142 | + // the stream index picks a `TrackEntry`, that entry's *track |
| 1143 | + // number* is what both readers are then pointed at. Positions are | ||
| 1144 | + // never handed to a reader -- symphonia's own order is its business | ||
| 1145 | + // -- because a mapping that drifts plays the wrong language and | ||
| 1146 | + // saves it into the project. | ||
| 1147 | + let tracks = crate::demux::matroska_audio_tracks(path)?; | ||
| 1148 | + if tracks.is_empty() { | ||
| 1149 | + return Ok(None); | ||
| 1128 | } | 1150 | } |
| 1129 | - match MkvAc3Track::open(path) { | 1151 | + let Some(entry) = tracks.get(stream) else { |
| 1152 | + return Err(format!( | ||
| 1153 | + "{}: audio stream {stream} of {} stream{}", | ||
| 1154 | + path.display(), | ||
| 1155 | + tracks.len(), | ||
| 1156 | + if tracks.len() == 1 { "" } else { "s" } | ||
| 1157 | + ) | ||
| 1158 | + .into()); | ||
| 1159 | + }; | ||
| 1160 | + match MkvAc3Track::open_track(path, entry.number) { | ||
| 1130 | Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), | 1161 | Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), |
| 1131 | Ok(None) => {} | 1162 | Ok(None) => {} |
| 1132 | // Named on the way past rather than returned: symphonia gets the | 1163 | // Named on the way past rather than returned: symphonia gets the |
| @@ -1142,7 +1173,7 @@ impl Track { | |||
| 1142 | // same answer the mp4 arm gives: turned into silence it would play | 1173 | // same answer the mp4 arm gives: turned into silence it would play |
| 1143 | // and export as a hole with only an eprintln to say why, which is a | 1174 | // and export as a hole with only an eprintln to say why, which is a |
| 1144 | // bug wearing a feature's clothes. | 1175 | // bug wearing a feature's clothes. |
| 1145 | - let Some(track) = SymTrack::open(path)? else { | 1176 | + let Some(track) = SymTrack::open_track(path, entry.number)? else { |
| 1146 | return Ok(None); | 1177 | return Ok(None); |
| 1147 | }; | 1178 | }; |
| 1148 | if let Err(e) = track.decoder() { | 1179 | if let Err(e) = track.decoder() { |
| @@ -1311,6 +1342,22 @@ impl SymTrack { | |||
| 1311 | /// difference matters because silence is played and exported without a word | 1342 | /// difference matters because silence is played and exported without a word |
| 1312 | /// while an `Err` is shown ([`Track::open`]). | 1343 | /// while an `Err` is shown ([`Track::open`]). |
| 1313 | fn open(path: &Path) -> crate::Result<Option<Self>> { | 1344 | fn open(path: &Path) -> crate::Result<Option<Self>> { |
| 1345 | + Self::open_inner(path, None) | ||
| 1346 | + } | ||
| 1347 | + | ||
| 1348 | + /// [`open`](Self::open) pointed at one **named** track: a Matroska | ||
| 1349 | + /// `TrackNumber`, which symphonia keeps as the track's id | ||
| 1350 | + /// (`symphonia-format-mkv` `demuxer.rs:301`). That is what makes the second | ||
| 1351 | + /// language of a dual-audio file reachable, and it is matched by number | ||
| 1352 | + /// rather than by position so this reader and | ||
| 1353 | + /// [`crate::demux::matroska_audio_tracks`] cannot disagree about which | ||
| 1354 | + /// track a stream index meant. `Ok(None)` for a number the reader does not | ||
| 1355 | + /// carry. | ||
| 1356 | + fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> { | ||
| 1357 | + Self::open_inner(path, Some(number)) | ||
| 1358 | + } | ||
| 1359 | + | ||
| 1360 | + fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> { | ||
| 1314 | let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); | 1361 | let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); |
| 1315 | // The extension is a hint, not a decision: the probe reads the magic and | 1362 | // The extension is a hint, not a decision: the probe reads the magic and |
| 1316 | // is free to disagree, which is what makes a mislabelled file work. | 1363 | // is free to disagree, which is what makes a mislabelled file work. |
| @@ -1324,7 +1371,14 @@ impl SymTrack { | |||
| 1324 | FormatOptions::default(), | 1371 | FormatOptions::default(), |
| 1325 | MetadataOptions::default(), | 1372 | MetadataOptions::default(), |
| 1326 | )?; | 1373 | )?; |
| 1327 | - let Some(track) = reader.default_track(SymKind::Audio) else { | 1374 | + let track = match number { |
| 1375 | + Some(number) => reader | ||
| 1376 | + .tracks() | ||
| 1377 | + .iter() | ||
| 1378 | + .find(|t| u64::from(t.id) == number), | ||
| 1379 | + None => reader.default_track(SymKind::Audio), | ||
| 1380 | + }; | ||
| 1381 | + let Some(track) = track else { | ||
| 1328 | return Ok(None); | 1382 | return Ok(None); |
| 1329 | }; | 1383 | }; |
| 1330 | // `track.delay` is deliberately not read: see the `priming` field. | 1384 | // `track.delay` is deliberately not read: see the `priming` field. |
| @@ -1611,7 +1665,19 @@ impl MkvAc3Track { | |||
| 1611 | /// that is one and could not be read, which | 1665 | /// that is one and could not be read, which |
| 1612 | /// [`AudioSession::unsupported`] quotes back to the user. | 1666 | /// [`AudioSession::unsupported`] quotes back to the user. |
| 1613 | fn open(path: &Path) -> crate::Result<Option<Self>> { | 1667 | fn open(path: &Path) -> crate::Result<Option<Self>> { |
| 1614 | - let Some(mut mkv) = crate::demux::MkvAudio::open(path)? else { | 1668 | + Self::from_blocks(crate::demux::MkvAudio::open(path)?) |
| 1669 | + } | ||
| 1670 | + | ||
| 1671 | + /// [`open`](Self::open) on one **named** track ([`MkvAudioTrack::number`]), | ||
| 1672 | + /// which is how the AC-3 half of a dual-audio file is reached. | ||
| 1673 | + /// | ||
| 1674 | + /// [`MkvAudioTrack::number`]: crate::demux::MkvAudioTrack::number | ||
| 1675 | + fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> { | ||
| 1676 | + Self::from_blocks(crate::demux::MkvAudio::open_track(path, number)?) | ||
| 1677 | + } | ||
| 1678 | + | ||
| 1679 | + fn from_blocks(mkv: Option<crate::demux::MkvAudio>) -> crate::Result<Option<Self>> { | ||
| 1680 | + let Some(mut mkv) = mkv else { | ||
| 1615 | return Ok(None); | 1681 | return Ok(None); |
| 1616 | }; | 1682 | }; |
| 1617 | let first = mkv | 1683 | let first = mkv |
| @@ -1889,6 +1955,22 @@ fn packet_run(err: &mut i64, ideal: i64, available: u32) -> u32 { | |||
| 1889 | n | 1955 | n |
| 1890 | } | 1956 | } |
| 1891 | 1957 | ||
| 1958 | +/// The name a Matroska audio row wears: the container's own codec id, cut down | ||
| 1959 | +/// to what a picker shows — `A_AAC` is `aac`, `A_EAC3` is `e-ac-3`. | ||
| 1960 | +/// | ||
| 1961 | +/// The codec id rather than symphonia's short name, because the rows that most | ||
| 1962 | +/// need naming are exactly the ones it has no decoder for: an Opus or DTS track | ||
| 1963 | +/// is greyed out with the codec in the reason (`unusable` in the app reads this | ||
| 1964 | +/// very string), where symphonia would call it "an unsupported format". | ||
| 1965 | +fn mkv_codec_name(id: &str) -> String { | ||
| 1966 | + match id { | ||
| 1967 | + "A_AC3" => "ac-3".into(), | ||
| 1968 | + "A_EAC3" => "e-ac-3".into(), | ||
| 1969 | + "A_MPEG/L3" => "mp3".into(), | ||
| 1970 | + _ => id.strip_prefix("A_").unwrap_or(id).to_ascii_lowercase(), | ||
| 1971 | + } | ||
| 1972 | +} | ||
| 1973 | + | ||
| 1892 | /// This file's audio tracks in file order — the order a stream index counts in. | 1974 | /// This file's audio tracks in file order — the order a stream index counts in. |
| 1893 | /// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a | 1975 | /// It comes out of `moov.traks` and not `Mp4Reader::tracks`, which is a |
| 1894 | /// `HashMap`: iterating that would make "stream 0" a different track from one | 1976 | /// `HashMap`: iterating that would make "stream 0" a different track from one |
crates/engine/src/demux.rsmodified+86 -25
| @@ -512,10 +512,35 @@ impl MkvDemuxer { | |||
| 512 | /// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and | 512 | /// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and |
| 513 | /// this exists to say which codec neither of them took. | 513 | /// this exists to say which codec neither of them took. |
| 514 | pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> { | 514 | pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> { |
| 515 | + Ok(matroska_audio_tracks(path)?.into_iter().next().map(|t| t.codec)) | ||
| 516 | +} | ||
| 517 | + | ||
| 518 | +/// One audio `TrackEntry` of a Matroska file, as the header describes it. | ||
| 519 | +pub struct MkvAudioTrack { | ||
| 520 | + /// `TrackNumber`: what this track's blocks are stamped with ([`MkvAudio`]), | ||
| 521 | + /// and the id symphonia keeps for the same track. *Not* a position -- a | ||
| 522 | + /// file's first audio track is number 2 as often as not. | ||
| 523 | + pub number: u64, | ||
| 524 | + /// The Matroska codec id: `A_AAC`, `A_EAC3`, `A_DTS`, ... | ||
| 525 | + pub codec: String, | ||
| 526 | + /// `TrackLanguage`, `"und"` for an entry that declares none (the spec's own | ||
| 527 | + /// default), which is what a muxer writes when nobody said. | ||
| 528 | + pub language: String, | ||
| 529 | + /// `TrackName` -- "Japanese 5.1", "Commentary" -- empty when there is none. | ||
| 530 | + pub name: String, | ||
| 531 | + /// What this track's blocks have to be put back through. | ||
| 532 | + unpack: Unpack, | ||
| 533 | +} | ||
| 534 | + | ||
| 535 | +/// Every audio track of a Matroska file, in file order: the numbering | ||
| 536 | +/// [`crate::AudioSession::probe_streams`] hands out, and the one a dual-audio | ||
| 537 | +/// remux is picked from. Header only, like [`matroska_audio_codec`], and an | ||
| 538 | +/// empty list is a file with no sound at all rather than an error. | ||
| 539 | +pub fn matroska_audio_tracks(path: &Path) -> crate::Result<Vec<MkvAudioTrack>> { | ||
| 515 | let mut file = File::open(path)?; | 540 | let mut file = File::open(path)?; |
| 516 | let end = file.metadata()?.len(); | 541 | let end = file.metadata()?.len(); |
| 517 | let segment = mkv_segment(&mut file, end)?; | 542 | let segment = mkv_segment(&mut file, end)?; |
| 518 | - Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec, _)| codec)) | 543 | + Ok(mkv_tracks(&mut file, segment)?.1) |
| 519 | } | 544 | } |
| 520 | 545 | ||
| 521 | /// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio | 546 | /// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio |
| @@ -543,12 +568,36 @@ impl MkvAudio { | |||
| 543 | /// is in a codec nothing here decodes -- that file is the silent source it | 568 | /// is in a codec nothing here decodes -- that file is the silent source it |
| 544 | /// has always been, and [`crate::audio::AudioSession::unsupported`] names | 569 | /// has always been, and [`crate::audio::AudioSession::unsupported`] names |
| 545 | /// the codec. An `Err` is a track that *is* AC-3 and could not be read. | 570 | /// the codec. An `Err` is a track that *is* AC-3 and could not be read. |
| 571 | + /// | ||
| 572 | + /// The file's *first* audio track, which is the one this has always read. | ||
| 546 | pub fn open(path: &Path) -> crate::Result<Option<Self>> { | 573 | pub fn open(path: &Path) -> crate::Result<Option<Self>> { |
| 574 | + Self::open_inner(path, None) | ||
| 575 | + } | ||
| 576 | + | ||
| 577 | + /// The audio track stamped `number` ([`MkvAudioTrack::number`], not a | ||
| 578 | + /// position), for a file carrying more than one -- a dual-audio remux, where | ||
| 579 | + /// which track is heard is the user's pick and not the muxer's order. | ||
| 580 | + /// `Ok(None)` for a number this file does not have, or one whose codec is | ||
| 581 | + /// not AC-3, exactly as [`open`](Self::open) answers for the first track. | ||
| 582 | + pub fn open_track(path: &Path, number: u64) -> crate::Result<Option<Self>> { | ||
| 583 | + Self::open_inner(path, Some(number)) | ||
| 584 | + } | ||
| 585 | + | ||
| 586 | + fn open_inner(path: &Path, number: Option<u64>) -> crate::Result<Option<Self>> { | ||
| 547 | let mut file = File::open(path)?; | 587 | let mut file = File::open(path)?; |
| 548 | let end = file.metadata()?.len(); | 588 | let end = file.metadata()?.len(); |
| 549 | let segment = mkv_segment(&mut file, end)?; | 589 | let segment = mkv_segment(&mut file, end)?; |
| 550 | let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?; | 590 | let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?; |
| 551 | - let Some((number, codec, unpack)) = audio else { | 591 | + let Some(MkvAudioTrack { |
| 592 | + number, | ||
| 593 | + codec, | ||
| 594 | + unpack, | ||
| 595 | + .. | ||
| 596 | + }) = (match number { | ||
| 597 | + Some(number) => audio.into_iter().find(|t| t.number == number), | ||
| 598 | + None => audio.into_iter().next(), | ||
| 599 | + }) | ||
| 600 | + else { | ||
| 552 | return Ok(None); | 601 | return Ok(None); |
| 553 | }; | 602 | }; |
| 554 | let codec = match codec.as_str() { | 603 | let codec = match codec.as_str() { |
| @@ -752,6 +801,8 @@ const DEFAULT_DURATION: u32 = 0x23E383; | |||
| 752 | const VIDEO: u32 = 0xE0; | 801 | const VIDEO: u32 = 0xE0; |
| 753 | const PIXEL_WIDTH: u32 = 0xB0; | 802 | const PIXEL_WIDTH: u32 = 0xB0; |
| 754 | const PIXEL_HEIGHT: u32 = 0xBA; | 803 | const PIXEL_HEIGHT: u32 = 0xBA; |
| 804 | +const TRACK_LANGUAGE: u32 = 0x22B59C; | ||
| 805 | +const TRACK_NAME: u32 = 0x536E; | ||
| 755 | const CONTENT_ENCODINGS: u32 = 0x6D80; | 806 | const CONTENT_ENCODINGS: u32 = 0x6D80; |
| 756 | const CONTENT_ENCODING: u32 = 0x6240; | 807 | const CONTENT_ENCODING: u32 = 0x6240; |
| 757 | const CONTENT_ENCODING_SCOPE: u32 = 0x5032; | 808 | const CONTENT_ENCODING_SCOPE: u32 = 0x5032; |
| @@ -778,25 +829,21 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { | |||
| 778 | Err("no Segment element: not a Matroska file".into()) | 829 | Err("no Segment element: not a Matroska file".into()) |
| 779 | } | 830 | } |
| 780 | 831 | ||
| 781 | -/// The video track of `segment`, the number and codec id of its first audio | 832 | +/// The video track of `segment`, **every** audio track in file order, the codec |
| 782 | -/// track, the codec id of a video track this cannot read, and the segment's | 833 | +/// id of a video track this cannot read, and the segment's `TimestampScale` in |
| 783 | -/// `TimestampScale` in nanoseconds. The audio pair is what [`MkvAudio`] reads a | 834 | +/// nanoseconds. The audio list is what [`MkvAudio`] reads a sound track from and |
| 784 | -/// sound track from; it and the other codec id are what tell a user why a file | 835 | +/// what [`matroska_audio_tracks`] hands a stream picker; it and the other codec |
| 785 | -/// plays silent ([`crate::audio::AudioSession::unsupported`]) or refuses to | 836 | +/// id are what tell a user why a file plays silent |
| 786 | -/// open at all. | 837 | +/// ([`crate::audio::AudioSession::unsupported`]) or refuses to open at all. |
| 787 | /// | 838 | /// |
| 788 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful | 839 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful |
| 789 | /// of seeks whatever the file weighs. | 840 | /// of seeks whatever the file weighs. |
| 790 | fn mkv_tracks( | 841 | fn mkv_tracks( |
| 791 | file: &mut File, | 842 | file: &mut File, |
| 792 | segment: (u64, u64), | 843 | segment: (u64, u64), |
| 793 | -) -> crate::Result<( | 844 | +) -> crate::Result<(Option<MkvVideo>, Vec<MkvAudioTrack>, Option<String>, u64)> { |
| 794 | - Option<MkvVideo>, | 845 | + let (mut video, mut other) = (None, None); |
| 795 | - Option<(u64, String, Unpack)>, | 846 | + let mut audio = Vec::new(); |
| 796 | - Option<String>, | ||
| 797 | - u64, | ||
| 798 | -)> { | ||
| 799 | - let (mut video, mut audio, mut other) = (None, None, None); | ||
| 800 | let mut timestamp_scale = 1_000_000; | 847 | let mut timestamp_scale = 1_000_000; |
| 801 | let mut at = segment.0; | 848 | let mut at = segment.0; |
| 802 | while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { | 849 | while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { |
| @@ -818,9 +865,11 @@ fn mkv_tracks( | |||
| 818 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { | 865 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { |
| 819 | MkvEntry::Video(track) if video.is_none() => video = Some(track), | 866 | MkvEntry::Video(track) if video.is_none() => video = Some(track), |
| 820 | MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), | 867 | MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), |
| 821 | - MkvEntry::Audio(number, codec, unpack) if audio.is_none() => { | 868 | + // Every one of them, in the order the `Tracks` |
| 822 | - audio = Some((number, codec, unpack)) | 869 | + // element lists them: that order *is* the stream |
| 823 | - } | 870 | + // numbering everything above hands out, so a |
| 871 | + // careless filter here plays the wrong language. | ||
| 872 | + MkvEntry::Audio(track) => audio.push(track), | ||
| 824 | _ => {} | 873 | _ => {} |
| 825 | } | 874 | } |
| 826 | } | 875 | } |
| @@ -839,10 +888,7 @@ enum MkvEntry { | |||
| 839 | Video(MkvVideo), | 888 | Video(MkvVideo), |
| 840 | /// A video track in a codec this does not read, by the name it gives itself. | 889 | /// A video track in a codec this does not read, by the name it gives itself. |
| 841 | OtherVideo(String), | 890 | OtherVideo(String), |
| 842 | - /// An audio track: its track number, which is what [`MkvAudio`] indexes the | 891 | + Audio(MkvAudioTrack), |
| 843 | - /// blocks of, its codec id (`A_AAC`, `A_EAC3`, ...), and what its blocks | ||
| 844 | - /// have to be put back through. | ||
| 845 | - Audio(u64, String, Unpack), | ||
| 846 | /// Subtitles, buttons: nobody's here. | 892 | /// Subtitles, buttons: nobody's here. |
| 847 | Other, | 893 | Other, |
| 848 | } | 894 | } |
| @@ -856,6 +902,7 @@ fn mkv_track_entry( | |||
| 856 | ) -> crate::Result<MkvEntry> { | 902 | ) -> crate::Result<MkvEntry> { |
| 857 | let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); | 903 | let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); |
| 858 | let (mut width, mut height, mut config) = (0, 0, Vec::new()); | 904 | let (mut width, mut height, mut config) = (0, 0, Vec::new()); |
| 905 | + let (mut language, mut name) = (String::new(), String::new()); | ||
| 859 | let mut unpack = Unpack::None; | 906 | let mut unpack = Unpack::None; |
| 860 | let mut at = body; | 907 | let mut at = body; |
| 861 | while let Some((id, body, stop)) = ebml_element(file, at, end)? { | 908 | while let Some((id, body, stop)) = ebml_element(file, at, end)? { |
| @@ -863,6 +910,8 @@ fn mkv_track_entry( | |||
| 863 | TRACK_NUMBER => number = ebml_uint(file, body, stop)?, | 910 | TRACK_NUMBER => number = ebml_uint(file, body, stop)?, |
| 864 | CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?, | 911 | CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?, |
| 865 | TRACK_TYPE => kind = ebml_uint(file, body, stop)?, | 912 | TRACK_TYPE => kind = ebml_uint(file, body, stop)?, |
| 913 | + TRACK_LANGUAGE => language = string_of(file, body, stop)?, | ||
| 914 | + TRACK_NAME => name = string_of(file, body, stop)?, | ||
| 866 | DEFAULT_DURATION => { | 915 | DEFAULT_DURATION => { |
| 867 | default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0) | 916 | default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0) |
| 868 | } | 917 | } |
| @@ -906,7 +955,21 @@ fn mkv_track_entry( | |||
| 906 | (Codec::H264, nal_length, sets, 8) | 955 | (Codec::H264, nal_length, sets, 8) |
| 907 | } | 956 | } |
| 908 | (1, _) => return Ok(MkvEntry::OtherVideo(codec)), | 957 | (1, _) => return Ok(MkvEntry::OtherVideo(codec)), |
| 909 | - (2, _) => return Ok(MkvEntry::Audio(number, codec, unpack)), | 958 | + (2, _) => { |
| 959 | + return Ok(MkvEntry::Audio(MkvAudioTrack { | ||
| 960 | + number, | ||
| 961 | + codec, | ||
| 962 | + // What a `TrackEntry` without a `Language` element means, by | ||
| 963 | + // spec -- the same default the subtitle walk applies. | ||
| 964 | + language: if language.is_empty() { | ||
| 965 | + "und".into() | ||
| 966 | + } else { | ||
| 967 | + language | ||
| 968 | + }, | ||
| 969 | + name, | ||
| 970 | + unpack, | ||
| 971 | + })); | ||
| 972 | + } | ||
| 910 | _ => return Ok(MkvEntry::Other), | 973 | _ => return Ok(MkvEntry::Other), |
| 911 | }; | 974 | }; |
| 912 | Ok(MkvEntry::Video(MkvVideo { | 975 | Ok(MkvEntry::Video(MkvVideo { |
| @@ -1667,8 +1730,6 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> { | |||
| 1667 | 1730 | ||
| 1668 | /// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles. | 1731 | /// One `TrackEntry`, `Some` only for track type 0x11 -- the subtitles. |
| 1669 | fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> { | 1732 | fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Option<MkvSubtitle>> { |
| 1670 | - const TRACK_LANGUAGE: u32 = 0x22B59C; | ||
| 1671 | - const TRACK_NAME: u32 = 0x536E; | ||
| 1672 | const SUBTITLE: u64 = 0x11; | 1733 | const SUBTITLE: u64 = 0x11; |
| 1673 | let (mut number, mut kind, mut codec) = (0, 0, String::new()); | 1734 | let (mut number, mut kind, mut codec) = (0, 0, String::new()); |
| 1674 | let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new()); | 1735 | let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new()); |
crates/engine/tests/audio_streams.rsmodified+126 -0
| @@ -11,6 +11,11 @@ use engine::audio::{AudioSession, StreamInfo}; | |||
| 11 | /// See `scripts/gen_fixtures.sh`. | 11 | /// See `scripts/gen_fixtures.sh`. |
| 12 | const MULTI: &str = "test_multiaudio.mp4"; | 12 | const MULTI: &str = "test_multiaudio.mp4"; |
| 13 | 13 | ||
| 14 | +/// Two audio streams in **Matroska**, the shape a dual-audio remux has: 0 is | ||
| 15 | +/// AAC 44.1k stereo 440/880 Hz English, 1 is the same shape at 220/330 Hz | ||
| 16 | +/// French. See `scripts/gen_fixtures.sh`. | ||
| 17 | +const MULTI_MKV: &str = "test_multiaudio.mkv"; | ||
| 18 | + | ||
| 14 | fn asset(name: &str) -> PathBuf { | 19 | fn asset(name: &str) -> PathBuf { |
| 15 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) | 20 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 16 | .join("../../assets") | 21 | .join("../../assets") |
| @@ -90,6 +95,127 @@ fn probe_streams_lists_every_audio_track_in_file_order() { | |||
| 90 | } | 95 | } |
| 91 | } | 96 | } |
| 92 | 97 | ||
| 98 | +/// The same listing for the container a film actually arrives in. A Matroska | ||
| 99 | +/// file used to be worth exactly one row here -- whichever track the readers | ||
| 100 | +/// stumbled on first -- so the second language of a dual-audio remux was | ||
| 101 | +/// invisible, and the language it is in was never shown at all. | ||
| 102 | +#[test] | ||
| 103 | +fn probe_streams_lists_every_matroska_audio_track_with_its_language() { | ||
| 104 | + let streams = AudioSession::probe_streams(asset(MULTI_MKV)).expect("probes"); | ||
| 105 | + assert_eq!( | ||
| 106 | + streams, | ||
| 107 | + vec![ | ||
| 108 | + StreamInfo { | ||
| 109 | + index: 0, | ||
| 110 | + codec: "aac".into(), | ||
| 111 | + channels: 2, | ||
| 112 | + sample_rate: 44100, | ||
| 113 | + lang: Some("eng".into()), | ||
| 114 | + decodable: true, | ||
| 115 | + }, | ||
| 116 | + StreamInfo { | ||
| 117 | + index: 1, | ||
| 118 | + codec: "aac".into(), | ||
| 119 | + channels: 2, | ||
| 120 | + sample_rate: 44100, | ||
| 121 | + lang: Some("fra".into()), | ||
| 122 | + decodable: true, | ||
| 123 | + }, | ||
| 124 | + ] | ||
| 125 | + ); | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +/// The stream index is a position in the file's `Tracks` element and the reader | ||
| 129 | +/// is pointed at that entry's *track number*; a mapping that drifts plays the | ||
| 130 | +/// other language and saves it into the project, so it is measured by the tones | ||
| 131 | +/// each track carries. | ||
| 132 | +#[test] | ||
| 133 | +fn a_named_matroska_stream_decodes_that_stream_and_not_the_first() { | ||
| 134 | + // The left channel of each stream: 440 Hz on stream 0, 220 Hz on stream 1. | ||
| 135 | + for (stream, hz) in [(0usize, 440.0f64), (1, 220.0)] { | ||
| 136 | + let (meta, samples) = decode(MULTI_MKV, stream); | ||
| 137 | + assert_eq!((meta.sample_rate, meta.channels), (44100, 2)); | ||
| 138 | + let left: Vec<f32> = samples.chunks(2).map(|c| c[0]).collect(); | ||
| 139 | + let middle = &left[left.len() / 4..left.len() * 3 / 4]; | ||
| 140 | + let expected = 2.0 * hz * middle.len() as f64 / 44100.0; | ||
| 141 | + let crossings = zero_crossings(middle) as f64; | ||
| 142 | + assert!( | ||
| 143 | + (crossings - expected).abs() < 0.05 * expected, | ||
| 144 | + "stream {stream} is {crossings} crossings, {hz} Hz would be {expected}" | ||
| 145 | + ); | ||
| 146 | + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() | ||
| 147 | + / samples.len() as f64) | ||
| 148 | + .sqrt(); | ||
| 149 | + assert!(rms > 0.01, "stream {stream} decoded silent: RMS {rms:.6}"); | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + // Stream 0 is what the file has always played: the wrapper that names no | ||
| 153 | + // stream and stream 0 are the same track, sample for sample. | ||
| 154 | + let (wrapped, rx) = AudioSession::open(asset(MULTI_MKV)) | ||
| 155 | + .expect("opens") | ||
| 156 | + .expect("audio"); | ||
| 157 | + let plain: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect(); | ||
| 158 | + let (meta, named) = decode(MULTI_MKV, 0); | ||
| 159 | + assert_eq!(wrapped, meta); | ||
| 160 | + assert_eq!(plain, named); | ||
| 161 | + | ||
| 162 | + // ...and a stream the file does not have is refused, not quietly served the | ||
| 163 | + // first track. | ||
| 164 | + let err = AudioSession::open_multi_streams(&[(asset(MULTI_MKV), 2)], &[(Some(0), 0.0, 1.0)]) | ||
| 165 | + .expect_err("stream 2 of 2 does not exist"); | ||
| 166 | + assert!( | ||
| 167 | + err.to_string().contains("audio stream 2 of 2 streams"), | ||
| 168 | + "unhelpful refusal: {err}" | ||
| 169 | + ); | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +/// The file the ask came from: a dual-audio Blu-ray rip, two AAC tracks, and | ||
| 173 | +/// the second one has to play. Existence-gated -- it is not in the repo. | ||
| 174 | +#[test] | ||
| 175 | +fn a_real_dual_audio_remux_lists_both_tracks_and_plays_the_second() { | ||
| 176 | + let path = PathBuf::from( | ||
| 177 | + "/path/to/\ | ||
| 178 | +a-real-h264-dual-audio-film.mkv", | ||
| 179 | + ); | ||
| 180 | + if !path.exists() { | ||
| 181 | + eprintln!("skipped: {} is not on this machine", path.display()); | ||
| 182 | + return; | ||
| 183 | + } | ||
| 184 | + let streams = AudioSession::probe_streams(&path).expect("probes"); | ||
| 185 | + assert_eq!(streams.len(), 2, "two audio tracks: {streams:?}"); | ||
| 186 | + for (index, info) in streams.iter().enumerate() { | ||
| 187 | + assert_eq!(info.index, index); | ||
| 188 | + assert_eq!(info.codec, "aac", "{info:?}"); | ||
| 189 | + assert!(info.decodable, "{info:?}"); | ||
| 190 | + } | ||
| 191 | + // A second of each track, ten seconds in (past the silence a title card | ||
| 192 | + // opens on): both have to carry sound and they have to be *different* | ||
| 193 | + // sound. The failure this guards against is a stream index that resolves to | ||
| 194 | + // nothing, or to the first track again. | ||
| 195 | + let mut takes = Vec::new(); | ||
| 196 | + for stream in [0, 1] { | ||
| 197 | + let (meta, rx) = | ||
| 198 | + AudioSession::open_multi_streams(&[(path.clone(), stream)], &[(Some(0), 10.0, 11.0)]) | ||
| 199 | + .expect("the stream opens") | ||
| 200 | + .expect("the stream is there"); | ||
| 201 | + let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect(); | ||
| 202 | + assert!( | ||
| 203 | + samples.len() > meta.sample_rate as usize / 2, | ||
| 204 | + "half a second of stream {stream} at least, got {}", | ||
| 205 | + samples.len() | ||
| 206 | + ); | ||
| 207 | + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() | ||
| 208 | + / samples.len() as f64) | ||
| 209 | + .sqrt(); | ||
| 210 | + assert!(rms > 1e-4, "stream {stream} came out silent: RMS {rms:.8}"); | ||
| 211 | + takes.push(samples); | ||
| 212 | + } | ||
| 213 | + assert_ne!( | ||
| 214 | + takes[0], takes[1], | ||
| 215 | + "the two languages decoded to the same samples: the stream index picked one track twice" | ||
| 216 | + ); | ||
| 217 | +} | ||
| 218 | + | ||
| 93 | #[test] | 219 | #[test] |
| 94 | fn probe_streams_on_one_track_and_on_none() { | 220 | fn probe_streams_on_one_track_and_on_none() { |
| 95 | let one = AudioSession::probe_streams(asset("test_av.mp4")).expect("probes"); | 221 | let one = AudioSession::probe_streams(asset("test_av.mp4")).expect("probes"); |
scripts/gen_fixtures.shmodified+18 -0
| @@ -195,6 +195,24 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | |||
| 195 | -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | 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 \ | 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 | 197 | -ac 6 -c:a eac3 -b:a 384k assets/test_eac3.mkv |
| 198 | +# Dual audio in Matroska: the shape an anime remux has -- one picture and two | ||
| 199 | +# AAC tracks that differ in language and content and *agree* on rate and layout | ||
| 200 | +# (44.1k stereo), so either one can go on the same timeline. Stream 0 is | ||
| 201 | +# 440/880 Hz English, stream 1 is 220/330 Hz French; the tones are what a test | ||
| 202 | +# tells the two apart by, and getting the mapping wrong plays the other | ||
| 203 | +# language. test_multilang.mp4 is this file's mp4 twin. | ||
| 204 | +ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \ | ||
| 205 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 206 | + -f lavfi -i "sine=frequency=880:duration=2" \ | ||
| 207 | + -f lavfi -i "sine=frequency=220:duration=2" \ | ||
| 208 | + -f lavfi -i "sine=frequency=330:duration=2" \ | ||
| 209 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a0];\ | ||
| 210 | +[3:a][4:a]join=inputs=2:channel_layout=stereo[a1]" \ | ||
| 211 | + -map 0:v -map "[a0]" -map "[a1]" \ | ||
| 212 | + -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | ||
| 213 | + -c:a aac -ar 44100 -ac 2 \ | ||
| 214 | + -metadata:s:a:0 language=eng -metadata:s:a:1 language=fra \ | ||
| 215 | + assets/test_multiaudio.mkv | ||
| 198 | # Sync fixture: one flash and one beep, at the same instant. Black picture with | 216 | # Sync fixture: one flash and one beep, at the same instant. Black picture with |
| 199 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that | 217 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that |
| 200 | # stretch — so a test can find each of them and say how far apart they came out. | 218 | # stretch — so a test can find each of them and say how far apart they came out. |