Merge branch 'lane-sweep': AVI audio through ec-riff/ec-probe with cross-chunk frame assembly; RIFF rejected cleanly by the mp4 door; truncated mp4/mkv tails end as incomplete, never corrupt
Browse files at this commit11 changed files +885 -36
- crates/ec-matroska/tests/matroska.rs +38 -1
- crates/ec-mp4/src/boxes.rs +10 -7
- crates/ec-mp4/src/demux.rs +26 -13
- crates/ec-mp4/tests/mp4.rs +60 -0
- crates/ec-probe/Cargo.toml +1 -1
- crates/ec-probe/src/lib.rs +237 -8
- crates/ec-probe/tests/library.rs +131 -1
- crates/ec-riff/Cargo.toml +1 -1
- crates/ec-riff/src/avi.rs +307 -0
- crates/ec-riff/src/lib.rs +5 -3
- crates/ec-riff/tests/wav.rs +69 -1
crates/ec-matroska/tests/matroska.rsmodified+38 -1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | //! was opened with. |
| 5 | 5 | |
| 6 | 6 | use std::fs::File; |
| 7 | -use std::io::BufReader; | |
| 7 | +use std::io::{BufReader, Cursor}; | |
| 8 | 8 | use std::path::{Path, PathBuf}; |
| 9 | 9 | use std::process::Command; |
| 10 | 10 | |
| @@ -786,6 +786,43 @@ fn the_first_cluster_is_reachable_when_no_cue_names_it() { | ||
| 786 | 786 | } |
| 787 | 787 | } |
| 788 | 788 | |
| 789 | +#[test] | |
| 790 | +fn truncated_prefixes_are_eof_not_corrupt() { | |
| 791 | + let path = fixtures().join("audio/av-h264-aac-stereo-48000.mkv"); | |
| 792 | + let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); | |
| 793 | + let mut table = Vec::new(); | |
| 794 | + for i in 1..=64usize { | |
| 795 | + let cut = data.len() * i / 64; | |
| 796 | + let (class, packets) = matroska_prefix_class(&data[..cut]); | |
| 797 | + table.push(format!("{i:02},{cut},{class},{packets}")); | |
| 798 | + assert!( | |
| 799 | + matches!(class, "NeedMore" | "Open+Eof"), | |
| 800 | + "{}\nidx,cut,class,packets\n{}", | |
| 801 | + path.display(), | |
| 802 | + table.join("\n") | |
| 803 | + ); | |
| 804 | + } | |
| 805 | + println!("{}\nidx,cut,class,packets\n{}", path.display(), table.join("\n")); | |
| 806 | +} | |
| 807 | + | |
| 808 | +fn matroska_prefix_class(data: &[u8]) -> (&'static str, u64) { | |
| 809 | + let mut demuxer = match MatroskaDemuxer::new(Cursor::new(data.to_vec())) { | |
| 810 | + Ok(demuxer) => demuxer, | |
| 811 | + Err(Error::NeedMore) => return ("NeedMore", 0), | |
| 812 | + Err(Error::Corrupt { .. }) => return ("Corrupt", 0), | |
| 813 | + Err(e) => panic!("unexpected Matroska prefix error: {e}"), | |
| 814 | + }; | |
| 815 | + let mut packets = 0; | |
| 816 | + loop { | |
| 817 | + match demuxer.next_packet() { | |
| 818 | + Ok(_) => packets += 1, | |
| 819 | + Err(Error::Eof) => return ("Open+Eof", packets), | |
| 820 | + Err(Error::NeedMore | Error::Corrupt { .. }) => return ("Corrupt", packets), | |
| 821 | + Err(e) => panic!("unexpected Matroska packet error: {e}"), | |
| 822 | + } | |
| 823 | + } | |
| 824 | +} | |
| 825 | + | |
| 789 | 826 | |
| 790 | 827 | /// Where our own demuxer's seek lands on a real 5.1 E-AC-3 Matroska, in |
| 791 | 828 | /// *timestamp* -- split from decode, per the round's charter: this measures |
crates/ec-mp4/src/boxes.rsmodified+10 -7
| @@ -179,9 +179,10 @@ impl<R: Read + Seek> Src<R> { | ||
| 179 | 179 | Ok(out) |
| 180 | 180 | } |
| 181 | 181 | |
| 182 | - /// The header of the box at `at`: its type, where its body starts and where | |
| 183 | - /// it ends. `None` once `at` reaches `end`. | |
| 184 | - pub fn header_at(&mut self, at: u64, end: u64) -> Result<Option<(FourCc, u64, u64)>> { | |
| 182 | + /// The header of the box at `at`: its type, where its body starts, where | |
| 183 | + /// the readable bytes end, and whether the stated size fits inside `end`. | |
| 184 | + /// `None` once `at` reaches `end` or a final header is cut off by EOF. | |
| 185 | + pub fn header_at(&mut self, at: u64, end: u64) -> Result<Option<(FourCc, u64, u64, bool)>> { | |
| 185 | 186 | if at.saturating_add(8) > end { |
| 186 | 187 | return Ok(None); |
| 187 | 188 | } |
| @@ -196,7 +197,7 @@ impl<R: Read + Seek> Src<R> { | ||
| 196 | 197 | let mut head_len = 8u64; |
| 197 | 198 | if size == 1 { |
| 198 | 199 | if got < 16 { |
| 199 | - return Err(Error::corrupt("mp4: 64-bit box size past the end of file")); | |
| 200 | + return Ok(None); | |
| 200 | 201 | } |
| 201 | 202 | size = u64::from_be_bytes(head[8..16].try_into().unwrap()); |
| 202 | 203 | head_len = 16; |
| @@ -209,9 +210,11 @@ impl<R: Read + Seek> Src<R> { | ||
| 209 | 210 | "mp4: box '{name}' is {size} bytes, shorter than its own header" |
| 210 | 211 | ))); |
| 211 | 212 | } |
| 212 | - let body = at + head_len; | |
| 213 | - let stop = at.saturating_add(size).min(end); | |
| 214 | - Ok(Some((kind, body, stop))) | |
| 213 | + let body = at.saturating_add(head_len); | |
| 214 | + let full_stop = at.saturating_add(size); | |
| 215 | + let complete = full_stop <= end; | |
| 216 | + let stop = full_stop.min(end); | |
| 217 | + Ok(Some((kind, body, stop, complete))) | |
| 215 | 218 | } |
| 216 | 219 | } |
| 217 | 220 |
crates/ec-mp4/src/demux.rsmodified+26 -13
| @@ -123,6 +123,14 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 123 | 123 | /// Read the movie header of `r` and build its sample tables. |
| 124 | 124 | pub fn new(r: R) -> Result<Mp4Demuxer<R>> { |
| 125 | 125 | let mut src = Src::new(r)?; |
| 126 | + let mut head = [0u8; 12]; | |
| 127 | + let got = src.read_upto(0, &mut head)?; | |
| 128 | + if got >= 8 && !crate::is_mp4(&head[..got]) { | |
| 129 | + return Err(Error::unsupported( | |
| 130 | + "this file", | |
| 131 | + "it is not an mp4 or QuickTime container", | |
| 132 | + )); | |
| 133 | + } | |
| 126 | 134 | let end = src.len; |
| 127 | 135 | let mut moov = None; |
| 128 | 136 | let mut moofs = Vec::new(); |
| @@ -130,10 +138,10 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 130 | 138 | // The top level, box by box: the header of each is 8 bytes and the rest |
| 131 | 139 | // is skipped by seeking, so opening a 12 GB film costs a handful of |
| 132 | 140 | // reads. |
| 133 | - while let Some((kind, body, stop)) = src.header_at(at, end)? { | |
| 141 | + while let Some((kind, body, stop, complete)) = src.header_at(at, end)? { | |
| 134 | 142 | match &kind { |
| 135 | - b"moov" => moov = Some((body, stop)), | |
| 136 | - b"moof" => moofs.push((at, body, stop)), | |
| 143 | + b"moov" if complete => moov = Some((body, stop)), | |
| 144 | + b"moof" if complete => moofs.push((at, body, stop)), | |
| 137 | 145 | _ => {} |
| 138 | 146 | } |
| 139 | 147 | if stop <= at { |
| @@ -141,12 +149,7 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 141 | 149 | } |
| 142 | 150 | at = stop; |
| 143 | 151 | } |
| 144 | - let (body, stop) = moov.ok_or_else(|| match moofs.is_empty() { | |
| 145 | - // A file that ends before its trailing moov is a truncated | |
| 146 | - // download, not a broken container. | |
| 147 | - true => Error::NeedMore, | |
| 148 | - false => Error::corrupt("mp4: fragments with no moov to describe them"), | |
| 149 | - })?; | |
| 152 | + let (body, stop) = moov.ok_or(Error::NeedMore)?; | |
| 150 | 153 | let data = src.read_vec(body, stop.saturating_sub(body), MOOV_LIMIT)?; |
| 151 | 154 | let mut me = Mp4Demuxer { |
| 152 | 155 | src, |
| @@ -260,9 +263,14 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 260 | 263 | return Err(Error::Eof); |
| 261 | 264 | }; |
| 262 | 265 | let time_base = trak.time_base; |
| 263 | - let data = self | |
| 266 | + let data = match self | |
| 264 | 267 | .src |
| 265 | - .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)?; | |
| 268 | + .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT) | |
| 269 | + { | |
| 270 | + Ok(data) => data, | |
| 271 | + Err(e) if e.is_need_more() => return Err(Error::Eof), | |
| 272 | + Err(e) => return Err(e), | |
| 273 | + }; | |
| 266 | 274 | Ok(packet_of(stream, time_base, &sample, data)) |
| 267 | 275 | } |
| 268 | 276 | |
| @@ -637,9 +645,14 @@ impl<R: Read + Seek + Send> Demuxer for Mp4Demuxer<R> { | ||
| 637 | 645 | trak.cursor += 1; |
| 638 | 646 | let stream = trak.stream.unwrap_or(0); |
| 639 | 647 | let time_base = trak.time_base; |
| 640 | - let data = self | |
| 648 | + let data = match self | |
| 641 | 649 | .src |
| 642 | - .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)?; | |
| 650 | + .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT) | |
| 651 | + { | |
| 652 | + Ok(data) => data, | |
| 653 | + Err(e) if e.is_need_more() => return Err(Error::Eof), | |
| 654 | + Err(e) => return Err(e), | |
| 655 | + }; | |
| 643 | 656 | Ok(packet_of(stream, time_base, &sample, data)) |
| 644 | 657 | } |
| 645 | 658 |
crates/ec-mp4/tests/mp4.rsmodified+60 -0
| @@ -32,6 +32,18 @@ fn open(path: &Path) -> Mp4Demuxer<BufReader<File>> { | ||
| 32 | 32 | .unwrap_or_else(|e| panic!("{}: {e}", path.display())) |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | +#[test] | |
| 36 | +fn riff_avi_is_not_reported_as_a_truncated_mp4() { | |
| 37 | + let err = match Mp4Demuxer::new(Cursor::new(b"RIFF\x10\0\0\0AVI ".to_vec())) { | |
| 38 | + Ok(_) => panic!("RIFF/AVI opened as mp4"), | |
| 39 | + Err(e) => e, | |
| 40 | + }; | |
| 41 | + assert!( | |
| 42 | + matches!(err, Error::Unsupported { .. }), | |
| 43 | + "wrong-container open error: {err}" | |
| 44 | + ); | |
| 45 | +} | |
| 46 | + | |
| 35 | 47 | /// What ffprobe calls each of our codec ids. |
| 36 | 48 | fn ffmpeg_name(codec: CodecId) -> &'static str { |
| 37 | 49 | match codec { |
| @@ -609,6 +621,54 @@ fn a_truncated_file_is_need_more() { | ||
| 609 | 621 | assert!(Mp4Demuxer::new(Cursor::new(b"not an mp4 at all".to_vec())).is_err()); |
| 610 | 622 | } |
| 611 | 623 | |
| 624 | +#[test] | |
| 625 | +fn truncated_prefixes_are_need_more_or_eof() { | |
| 626 | + let mut paths = vec![fixtures().join("audio/aac-mp4-stereo-48000.mp4")]; | |
| 627 | + let real = PathBuf::from("/home/user/Downloads/reelj (11).mp4"); | |
| 628 | + if real.exists() { | |
| 629 | + paths.push(real); | |
| 630 | + } | |
| 631 | + | |
| 632 | + for path in paths { | |
| 633 | + let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); | |
| 634 | + let mut table = Vec::new(); | |
| 635 | + for i in 1..=64usize { | |
| 636 | + let cut = data.len() * i / 64; | |
| 637 | + let (class, packets) = mp4_prefix_class(&data[..cut]); | |
| 638 | + table.push(format!("{i:02},{cut},{class},{packets}")); | |
| 639 | + assert!( | |
| 640 | + matches!(class, "NeedMore" | "Open+Eof"), | |
| 641 | + "{}\nidx,cut,class,packets\n{}", | |
| 642 | + path.display(), | |
| 643 | + table.join("\n") | |
| 644 | + ); | |
| 645 | + } | |
| 646 | + println!( | |
| 647 | + "{}\nidx,cut,class,packets\n{}", | |
| 648 | + path.display(), | |
| 649 | + table.join("\n") | |
| 650 | + ); | |
| 651 | + } | |
| 652 | +} | |
| 653 | + | |
| 654 | +fn mp4_prefix_class(data: &[u8]) -> (&'static str, u64) { | |
| 655 | + let mut demuxer = match Mp4Demuxer::new(Cursor::new(data.to_vec())) { | |
| 656 | + Ok(demuxer) => demuxer, | |
| 657 | + Err(Error::NeedMore) => return ("NeedMore", 0), | |
| 658 | + Err(Error::Corrupt { .. }) => return ("Corrupt", 0), | |
| 659 | + Err(e) => panic!("unexpected mp4 prefix error: {e}"), | |
| 660 | + }; | |
| 661 | + let mut packets = 0; | |
| 662 | + loop { | |
| 663 | + match demuxer.next_packet() { | |
| 664 | + Ok(_) => packets += 1, | |
| 665 | + Err(Error::Eof) => return ("Open+Eof", packets), | |
| 666 | + Err(Error::NeedMore | Error::Corrupt { .. }) => return ("Corrupt", packets), | |
| 667 | + Err(e) => panic!("unexpected mp4 packet error: {e}"), | |
| 668 | + } | |
| 669 | + } | |
| 670 | +} | |
| 671 | + | |
| 612 | 672 | /// A muxer round trip in memory, with the timing checked at the tick: the file |
| 613 | 673 | /// this writes states 1001 ticks a frame on a 24000 clock, which is the only way |
| 614 | 674 | /// 23.976 stays itself. |
crates/ec-probe/Cargo.tomlmodified+1 -1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [package] |
| 2 | 2 | name = "ec-probe" |
| 3 | -description = "Format detection and one unified audio reader: WAV/MP3/FLAC/ADTS in-crate, Ogg/mp4/Matroska delegated to their own crates." | |
| 3 | +description = "Format detection and one unified audio reader: WAV/AVI/MP3/FLAC/ADTS in-crate, Ogg/mp4/Matroska delegated to their own crates." | |
| 4 | 4 | version.workspace = true |
| 5 | 5 | edition.workspace = true |
| 6 | 6 | license.workspace = true |
crates/ec-probe/src/lib.rsmodified+237 -8
| @@ -8,9 +8,9 @@ | ||
| 8 | 8 | //! |
| 9 | 9 | //! What this crate does *not* do is parse containers a sibling crate already |
| 10 | 10 | //! parses. Matroska goes to [`ec_matroska`], mp4 to [`ec_mp4`], Ogg to |
| 11 | -//! [`ec_ogg`]; there is exactly one EBML parser in this family and it is not | |
| 12 | -//! here. What is implemented in [`raw`] is the four formats that are a codec | |
| 13 | -//! and nothing else: WAV, MP3, FLAC and ADTS. | |
| 11 | +//! [`ec_ogg`], and RIFF/WAVE/AVI to [`ec_riff`]; there is exactly one parser | |
| 12 | +//! for each container family. What is implemented in [`raw`] is the three | |
| 13 | +//! formats that are a codec and nothing else: MP3, FLAC and ADTS. | |
| 14 | 14 | //! |
| 15 | 15 | //! Two contracts worth knowing: |
| 16 | 16 | //! |
| @@ -36,9 +36,13 @@ use std::io::{BufReader, Read, Seek, SeekFrom}; | ||
| 36 | 36 | use std::path::Path; |
| 37 | 37 | |
| 38 | 38 | use ec_core::error::{Error, Result}; |
| 39 | -use ec_core::packet::Packet; | |
| 40 | -use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode, StreamInfo}; | |
| 39 | +use ec_core::packet::{Buf, Packet, PacketFlags}; | |
| 40 | +use ec_core::registry::{ | |
| 41 | + AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, MediaType, SeekMode, | |
| 42 | + StreamInfo, | |
| 43 | +}; | |
| 41 | 44 | use ec_core::timebase::{Rounding, TimeBase, Timestamp}; |
| 45 | +use ec_core::{ChannelLayout, SampleFormat}; | |
| 42 | 46 | |
| 43 | 47 | pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip}; |
| 44 | 48 | pub use tags::Tags; |
| @@ -67,6 +71,8 @@ pub enum Format { | ||
| 67 | 71 | Ogg, |
| 68 | 72 | /// ISO base media: mp4, m4a, mov. |
| 69 | 73 | Mp4, |
| 74 | + /// RIFF/AVI. | |
| 75 | + Avi, | |
| 70 | 76 | /// Matroska and WebM. |
| 71 | 77 | Matroska, |
| 72 | 78 | } |
| @@ -82,6 +88,7 @@ impl Format { | ||
| 82 | 88 | Format::Ogg => "ogg", |
| 83 | 89 | Format::Mp4 => "mp4", |
| 84 | 90 | Format::Matroska => "matroska", |
| 91 | + Format::Avi => "avi", | |
| 85 | 92 | } |
| 86 | 93 | } |
| 87 | 94 | |
| @@ -96,6 +103,7 @@ impl Format { | ||
| 96 | 103 | Format::Ogg => &["ogg", "oga", "opus"], |
| 97 | 104 | Format::Mp4 => &["mp4", "m4a", "m4v", "mov"], |
| 98 | 105 | Format::Matroska => &["mkv", "mka", "mks", "mk3d", "webm"], |
| 106 | + Format::Avi => &["avi"], | |
| 99 | 107 | } |
| 100 | 108 | } |
| 101 | 109 | } |
| @@ -107,8 +115,12 @@ impl Format { | ||
| 107 | 115 | pub fn sniff(head: &[u8]) -> Option<Format> { |
| 108 | 116 | let at = tags::id3v2_len(head).unwrap_or(0) as usize; |
| 109 | 117 | let data = head.get(at..).filter(|d| !d.is_empty()).unwrap_or(head); |
| 110 | - if data.len() >= 12 && &data[..4] == b"RIFF" && &data[8..12] == b"WAVE" { | |
| 111 | - return Some(Format::Wav); | |
| 118 | + if data.len() >= 12 && &data[..4] == b"RIFF" { | |
| 119 | + match &data[8..12] { | |
| 120 | + b"WAVE" => return Some(Format::Wav), | |
| 121 | + b"AVI " => return Some(Format::Avi), | |
| 122 | + _ => {} | |
| 123 | + } | |
| 112 | 124 | } |
| 113 | 125 | if data.starts_with(b"fLaC") { |
| 114 | 126 | return Some(Format::Flac); |
| @@ -223,6 +235,7 @@ impl Reader { | ||
| 223 | 235 | Format::Ogg, |
| 224 | 236 | Format::Mp4, |
| 225 | 237 | Format::Matroska, |
| 238 | + Format::Avi, | |
| 226 | 239 | ] |
| 227 | 240 | .into_iter() |
| 228 | 241 | .find(|f| f.extensions().contains(&hint.as_str())) |
| @@ -230,7 +243,7 @@ impl Reader { | ||
| 230 | 243 | .ok_or_else(|| { |
| 231 | 244 | Error::unsupported( |
| 232 | 245 | "this file", |
| 233 | - "its first bytes match no format this build reads (wav, flac, mp3, adts, ogg, mp4, matroska)", | |
| 246 | + "its first bytes match no format this build reads (wav, flac, mp3, adts, ogg, mp4, avi, matroska)", | |
| 234 | 247 | ) |
| 235 | 248 | })?; |
| 236 | 249 | src.rewind()?; |
| @@ -275,6 +288,7 @@ impl Reader { | ||
| 275 | 288 | Ok(Reader::wrap(format, Box::new(demuxer), tags, native)) |
| 276 | 289 | } |
| 277 | 290 | Format::Wav => open_wav(src, end), |
| 291 | + Format::Avi => open_avi(src), | |
| 278 | 292 | Format::Flac => open_flac(src, &head, end), |
| 279 | 293 | Format::Mp3 => open_mp3(src, &head, end), |
| 280 | 294 | Format::Adts => open_adts(src, &head, end), |
| @@ -635,6 +649,221 @@ fn open_adts<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) | ||
| 635 | 649 | Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0])) |
| 636 | 650 | } |
| 637 | 651 | |
| 652 | +fn open_avi<R: Read + Seek + Send + 'static>(src: R) -> Result<Reader> { | |
| 653 | + let reader = ec_riff::AviReader::new(src)?; | |
| 654 | + let demuxer = AviDemuxer::new(reader)?; | |
| 655 | + let native = demuxer | |
| 656 | + .stream_numbers | |
| 657 | + .iter() | |
| 658 | + .map(|&n| u64::from(n)) | |
| 659 | + .collect(); | |
| 660 | + Ok(Reader::wrap( | |
| 661 | + Format::Avi, | |
| 662 | + Box::new(demuxer), | |
| 663 | + Tags::default(), | |
| 664 | + native, | |
| 665 | + )) | |
| 666 | +} | |
| 667 | + | |
| 668 | +struct AviDemuxer<R> { | |
| 669 | + reader: ec_riff::AviReader<R>, | |
| 670 | + streams: Vec<StreamInfo>, | |
| 671 | + stream_numbers: Vec<u32>, | |
| 672 | + samples: Vec<u64>, | |
| 673 | + pending: VecDeque<Packet>, | |
| 674 | + carry: Vec<Vec<u8>>, | |
| 675 | +} | |
| 676 | + | |
| 677 | +impl<R: Read + Seek> AviDemuxer<R> { | |
| 678 | + fn new(reader: ec_riff::AviReader<R>) -> Result<AviDemuxer<R>> { | |
| 679 | + let mut streams = Vec::new(); | |
| 680 | + let mut stream_numbers = Vec::new(); | |
| 681 | + for (index, s) in reader.audio_streams().iter().enumerate() { | |
| 682 | + let codec = match s.format_tag { | |
| 683 | + 0x0001 if s.bits_per_sample <= 8 => CodecId::PcmU8, | |
| 684 | + 0x0001 => CodecId::PcmS16Le, | |
| 685 | + 0x0055 => CodecId::Mp3, | |
| 686 | + 0x00ff => CodecId::Aac, | |
| 687 | + 0x2000 => CodecId::Ac3, | |
| 688 | + tag => { | |
| 689 | + return Err(Error::unsupported( | |
| 690 | + format!("AVI audio format tag {tag:#06x}"), | |
| 691 | + "no decoder for it exists in this family yet", | |
| 692 | + )); | |
| 693 | + } | |
| 694 | + }; | |
| 695 | + let mut params = CodecParameters::new(codec); | |
| 696 | + params.media = MediaParameters::Audio(AudioParameters { | |
| 697 | + sample_rate: s.sample_rate, | |
| 698 | + layout: ChannelLayout::from_count(usize::from(s.channels).max(1)), | |
| 699 | + format: match codec { | |
| 700 | + CodecId::PcmU8 => Some(SampleFormat::U8), | |
| 701 | + CodecId::PcmS16Le => Some(SampleFormat::S16), | |
| 702 | + _ => None, | |
| 703 | + }, | |
| 704 | + bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)), | |
| 705 | + }); | |
| 706 | + streams.push(StreamInfo::new( | |
| 707 | + index as u32, | |
| 708 | + TimeBase::from_rate(s.sample_rate.max(1)), | |
| 709 | + params, | |
| 710 | + )); | |
| 711 | + stream_numbers.push(s.index); | |
| 712 | + } | |
| 713 | + if streams.is_empty() { | |
| 714 | + return Err(Error::unsupported( | |
| 715 | + "this AVI file", | |
| 716 | + "it declares no audio stream this reader can hand out", | |
| 717 | + )); | |
| 718 | + } | |
| 719 | + let samples = vec![0; streams.len()]; | |
| 720 | + let carry = vec![Vec::new(); streams.len()]; | |
| 721 | + Ok(AviDemuxer { | |
| 722 | + reader, | |
| 723 | + streams, | |
| 724 | + stream_numbers, | |
| 725 | + samples, | |
| 726 | + pending: VecDeque::new(), | |
| 727 | + carry, | |
| 728 | + }) | |
| 729 | + } | |
| 730 | + | |
| 731 | + fn queue_chunk(&mut self, chunk: ec_riff::AviPacket) -> Result<()> { | |
| 732 | + let Some(stream) = self.stream_numbers.iter().position(|&n| n == chunk.stream) else { | |
| 733 | + return Ok(()); | |
| 734 | + }; | |
| 735 | + let codec = self.streams[stream].params.codec; | |
| 736 | + match codec { | |
| 737 | + CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac => { | |
| 738 | + self.queue_elementary_chunk(stream, chunk.data, codec) | |
| 739 | + } | |
| 740 | + _ => { | |
| 741 | + let frames = match codec { | |
| 742 | + CodecId::PcmU8 | CodecId::PcmS16Le => { | |
| 743 | + let block = self | |
| 744 | + .reader | |
| 745 | + .audio_streams() | |
| 746 | + .get(stream) | |
| 747 | + .map_or(1usize, |s| usize::from(s.block_align).max(1)); | |
| 748 | + (chunk.data.len() / block) as u64 | |
| 749 | + } | |
| 750 | + _ => 0, | |
| 751 | + }; | |
| 752 | + self.push_packet(stream, Buf::from_vec(chunk.data), frames); | |
| 753 | + Ok(()) | |
| 754 | + } | |
| 755 | + } | |
| 756 | + } | |
| 757 | + | |
| 758 | + fn queue_elementary_chunk( | |
| 759 | + &mut self, | |
| 760 | + stream: usize, | |
| 761 | + chunk: Vec<u8>, | |
| 762 | + codec: CodecId, | |
| 763 | + ) -> Result<()> { | |
| 764 | + let mut data = std::mem::take(&mut self.carry[stream]); | |
| 765 | + data.extend_from_slice(&chunk); | |
| 766 | + let mut at = 0usize; | |
| 767 | + while at < data.len() { | |
| 768 | + match avi_elementary_frame(codec, &data[at..]) { | |
| 769 | + Ok(Some((size, frames))) if at + size <= data.len() => { | |
| 770 | + self.push_packet(stream, Buf::copy_from_slice(&data[at..at + size]), frames); | |
| 771 | + at += size; | |
| 772 | + } | |
| 773 | + Ok(Some(_)) => break, | |
| 774 | + Ok(None) => at += 1, | |
| 775 | + Err(e) if e.is_need_more() => break, | |
| 776 | + Err(_) => at += 1, | |
| 777 | + } | |
| 778 | + } | |
| 779 | + self.carry[stream].extend_from_slice(&data[at..]); | |
| 780 | + Ok(()) | |
| 781 | + } | |
| 782 | + | |
| 783 | + fn push_packet(&mut self, stream: usize, data: Buf, frames: u64) { | |
| 784 | + let base = self.streams[stream].time_base; | |
| 785 | + let pts = self.samples[stream]; | |
| 786 | + self.samples[stream] = self.samples[stream].saturating_add(frames); | |
| 787 | + let mut packet = Packet::new(stream as u32, base, data); | |
| 788 | + packet.pts = Some(pts as i64); | |
| 789 | + packet.dts = Some(pts as i64); | |
| 790 | + packet.duration = Some(frames as i64); | |
| 791 | + packet.flags = PacketFlags { | |
| 792 | + keyframe: true, | |
| 793 | + ..PacketFlags::default() | |
| 794 | + }; | |
| 795 | + self.pending.push_back(packet); | |
| 796 | + } | |
| 797 | +} | |
| 798 | +fn avi_elementary_frame(codec: CodecId, data: &[u8]) -> Result<Option<(usize, u64)>> { | |
| 799 | + match codec { | |
| 800 | + CodecId::Ac3 | CodecId::EAc3 => { | |
| 801 | + if data.len() < 2 { | |
| 802 | + return Err(Error::NeedMore); | |
| 803 | + } | |
| 804 | + if data[0] != 0x0b || data[1] != 0x77 { | |
| 805 | + return Ok(None); | |
| 806 | + } | |
| 807 | + ec_ac3::frame_size(data).map(|size| Some((size, 1536))) | |
| 808 | + } | |
| 809 | + CodecId::Mp3 => { | |
| 810 | + if data.len() < 2 { | |
| 811 | + return Err(Error::NeedMore); | |
| 812 | + } | |
| 813 | + if data[0] != 0xff || data[1] & 0xe0 != 0xe0 { | |
| 814 | + return Ok(None); | |
| 815 | + } | |
| 816 | + let header = ec_mp3::FrameHeader::parse(data)?; | |
| 817 | + if header.layer != 3 { | |
| 818 | + return Ok(None); | |
| 819 | + } | |
| 820 | + Ok(header | |
| 821 | + .frame_len() | |
| 822 | + .map(|size| (size, header.samples_per_frame() as u64))) | |
| 823 | + } | |
| 824 | + CodecId::Aac => { | |
| 825 | + if data.len() < 2 { | |
| 826 | + return Err(Error::NeedMore); | |
| 827 | + } | |
| 828 | + if !ec_aac::is_adts(data) { | |
| 829 | + return Ok(None); | |
| 830 | + } | |
| 831 | + let header = ec_aac::parse_adts(data)?; | |
| 832 | + Ok(Some(( | |
| 833 | + header.frame_length, | |
| 834 | + (u64::from(header.raw_blocks) + 1) * ec_aac::FRAME_LEN as u64, | |
| 835 | + ))) | |
| 836 | + } | |
| 837 | + _ => Ok(None), | |
| 838 | + } | |
| 839 | +} | |
| 840 | + | |
| 841 | +impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> { | |
| 842 | + fn streams(&self) -> &[StreamInfo] { | |
| 843 | + &self.streams | |
| 844 | + } | |
| 845 | + | |
| 846 | + fn next_packet(&mut self) -> Result<Packet> { | |
| 847 | + loop { | |
| 848 | + if let Some(packet) = self.pending.pop_front() { | |
| 849 | + return Ok(packet); | |
| 850 | + } | |
| 851 | + match self.reader.next_packet() { | |
| 852 | + Ok(chunk) => self.queue_chunk(chunk)?, | |
| 853 | + Err(e) if e.is_eof() => return Err(Error::Eof), | |
| 854 | + Err(e) => return Err(e), | |
| 855 | + } | |
| 856 | + } | |
| 857 | + } | |
| 858 | + | |
| 859 | + fn seek(&mut self, _stream: u32, _to: Timestamp, _mode: SeekMode) -> Result<()> { | |
| 860 | + Err(Error::unsupported( | |
| 861 | + "AVI audio seek", | |
| 862 | + "this reader only walks AVI sound chunks in storage order", | |
| 863 | + )) | |
| 864 | + } | |
| 865 | +} | |
| 866 | + | |
| 638 | 867 | /// Skip an ID3v2 tag at the head of a stream, reading its text on the way past. |
| 639 | 868 | fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> { |
| 640 | 869 | let mut tags = Tags::default(); |
crates/ec-probe/tests/library.rsmodified+131 -1
| @@ -61,6 +61,56 @@ fn decode_some(reader: &mut Reader, stream: u32, secs: f64) -> Result<u64, Strin | ||
| 61 | 61 | Ok(frames) |
| 62 | 62 | } |
| 63 | 63 | |
| 64 | +fn decode_stream_to_eof( | |
| 65 | + reader: &mut Reader, | |
| 66 | + stream: u32, | |
| 67 | + collect: bool, | |
| 68 | +) -> Result<(u64, u64, Vec<f32>), String> { | |
| 69 | + let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?; | |
| 70 | + let mut scratch = Vec::new(); | |
| 71 | + let mut pcm = Vec::new(); | |
| 72 | + let mut packets = 0u64; | |
| 73 | + let mut frames = 0u64; | |
| 74 | + loop { | |
| 75 | + let packet = match reader.next_packet() { | |
| 76 | + Ok(p) => p, | |
| 77 | + Err(e) if e.is_eof() => break, | |
| 78 | + Err(e) => return Err(format!("demux: {e}")), | |
| 79 | + }; | |
| 80 | + if packet.stream != stream { | |
| 81 | + continue; | |
| 82 | + } | |
| 83 | + decoder | |
| 84 | + .decode(&packet, &mut scratch) | |
| 85 | + .map_err(|e| format!("decode: {e}"))?; | |
| 86 | + packets += 1; | |
| 87 | + frames += (scratch.len() / decoder.channels().max(1)) as u64; | |
| 88 | + if collect { | |
| 89 | + pcm.extend_from_slice(&scratch); | |
| 90 | + } | |
| 91 | + } | |
| 92 | + decoder | |
| 93 | + .flush(&mut scratch) | |
| 94 | + .map_err(|e| format!("flush: {e}"))?; | |
| 95 | + frames += (scratch.len() / decoder.channels().max(1)) as u64; | |
| 96 | + if collect { | |
| 97 | + pcm.extend_from_slice(&scratch); | |
| 98 | + } | |
| 99 | + Ok((packets, frames, pcm)) | |
| 100 | +} | |
| 101 | + | |
| 102 | +fn corr(a: &[f32], b: &[f32]) -> f64 { | |
| 103 | + let n = a.len().min(b.len()); | |
| 104 | + let (mut num, mut a2, mut b2) = (0.0f64, 0.0f64, 0.0f64); | |
| 105 | + for i in 0..n { | |
| 106 | + let (x, y) = (a[i] as f64, b[i] as f64); | |
| 107 | + num += x * y; | |
| 108 | + a2 += x * x; | |
| 109 | + b2 += y * y; | |
| 110 | + } | |
| 111 | + num / (a2.sqrt() * b2.sqrt()).max(1e-12) | |
| 112 | +} | |
| 113 | + | |
| 64 | 114 | /// Ten files with sound, standalone audio first, then Matroska — opened, |
| 65 | 115 | /// decoded and seeked, with a per-file row in the report. |
| 66 | 116 | #[test] |
| @@ -197,6 +247,82 @@ fn a_real_library_sweep() { | ||
| 197 | 247 | assert!(failures.is_empty(), "{}", failures.join("\n")); |
| 198 | 248 | } |
| 199 | 249 | |
| 250 | +#[test] | |
| 251 | +fn avi_audio_chunks_end_cleanly_on_real_files() { | |
| 252 | + let files = [ | |
| 253 | + "/home/user/Downloads/reele/reele.avi", | |
| 254 | + "/home/user/Downloads/reele/sample.avi", | |
| 255 | + ]; | |
| 256 | + let mut present = 0; | |
| 257 | + for path in files { | |
| 258 | + let path = Path::new(path); | |
| 259 | + if !path.exists() { | |
| 260 | + continue; | |
| 261 | + } | |
| 262 | + present += 1; | |
| 263 | + let mut reader = Reader::open(path).expect("AVI opens"); | |
| 264 | + let audio = reader | |
| 265 | + .default_stream(MediaType::Audio) | |
| 266 | + .expect("AVI audio stream") | |
| 267 | + .index; | |
| 268 | + let (packets, frames, _) = | |
| 269 | + decode_stream_to_eof(&mut reader, audio, false).unwrap_or_else(|e| { | |
| 270 | + panic!("{}: {e}", path.display()); | |
| 271 | + }); | |
| 272 | + eprintln!( | |
| 273 | + "{}: open ok, packets {packets}, decode-to-EOF {frames} frames", | |
| 274 | + path.display() | |
| 275 | + ); | |
| 276 | + assert!(packets > 0, "{}: no audio packets", path.display()); | |
| 277 | + assert!(frames > 0, "{}: no decoded audio", path.display()); | |
| 278 | + } | |
| 279 | + assert!(present > 0, "AVI files absent"); | |
| 280 | +} | |
| 281 | + | |
| 282 | +#[test] | |
| 283 | +fn avi_ac3_matches_reference_decoder_on_real_sample() { | |
| 284 | + let path = Path::new( | |
| 285 | + "/home/user/Downloads/reele/sample.avi", | |
| 286 | + ); | |
| 287 | + if !path.exists() { | |
| 288 | + eprintln!("file not present, skipping"); | |
| 289 | + return; | |
| 290 | + } | |
| 291 | + | |
| 292 | + let mut reader = Reader::open(path).expect("AVI opens"); | |
| 293 | + let audio = reader | |
| 294 | + .default_stream(MediaType::Audio) | |
| 295 | + .expect("AVI audio stream") | |
| 296 | + .index; | |
| 297 | + let (packets, frames, ours) = | |
| 298 | + decode_stream_to_eof(&mut reader, audio, true).expect("AVI decodes to EOF"); | |
| 299 | + assert!(packets > 0, "no packets"); | |
| 300 | + assert!(frames > 0, "no decoded frames"); | |
| 301 | + | |
| 302 | + let out = Command::new("ffmpeg") | |
| 303 | + .args(["-v", "error", "-i"]) | |
| 304 | + .arg(path) | |
| 305 | + .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) | |
| 306 | + .output() | |
| 307 | + .expect("reference decoder runs"); | |
| 308 | + assert!( | |
| 309 | + out.status.success(), | |
| 310 | + "{}", | |
| 311 | + String::from_utf8_lossy(&out.stderr) | |
| 312 | + ); | |
| 313 | + let theirs: Vec<f32> = out | |
| 314 | + .stdout | |
| 315 | + .chunks_exact(4) | |
| 316 | + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) | |
| 317 | + .collect(); | |
| 318 | + let score = corr(&ours, &theirs); | |
| 319 | + eprintln!( | |
| 320 | + "{}: open ok, packets {packets}, decode-to-EOF {frames} frames, corr {score:.6}", | |
| 321 | + path.display() | |
| 322 | + ); | |
| 323 | + assert!(score > 0.999, "corr vs reference decoder = {score}"); | |
| 324 | +} | |
| 325 | + | |
| 200 | 326 | /// The TrueHD remux in his library: the track decodes through the unified |
| 201 | 327 | /// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too. |
| 202 | 328 | #[test] |
| @@ -312,7 +438,11 @@ fn a_cover_art_tagged_mp3_opens() { | ||
| 312 | 438 | .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) |
| 313 | 439 | .output() |
| 314 | 440 | .expect("ffmpeg runs"); |
| 315 | - assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); | |
| 441 | + assert!( | |
| 442 | + out.status.success(), | |
| 443 | + "{}", | |
| 444 | + String::from_utf8_lossy(&out.stderr) | |
| 445 | + ); | |
| 316 | 446 | let theirs: Vec<f32> = out |
| 317 | 447 | .stdout |
| 318 | 448 | .chunks_exact(4) |
crates/ec-riff/Cargo.tomlmodified+1 -1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [package] |
| 2 | 2 | name = "ec-riff" |
| 3 | -description = "RIFF/WAVE reader and writer: integer and float PCM, mono through 7.1, WAVE_FORMAT_EXTENSIBLE." | |
| 3 | +description = "RIFF/WAVE reader and writer plus RIFF/AVI audio chunk reader." | |
| 4 | 4 | version.workspace = true |
| 5 | 5 | edition.workspace = true |
| 6 | 6 | license.workspace = true |
crates/ec-riff/src/avi.rsadded+307 -0
| @@ -0,0 +1,307 @@ | ||
| 1 | +//! RIFF/AVI audio chunk reader. | |
| 2 | +//! | |
| 3 | +//! This is the small half an audio probe needs: stream headers plus `movi` | |
| 4 | +//! sound chunks. Picture chunks are skipped. | |
| 5 | + | |
| 6 | +use std::collections::VecDeque; | |
| 7 | +use std::io::{Read, Seek, SeekFrom}; | |
| 8 | + | |
| 9 | +use ec_core::{Error, Result}; | |
| 10 | + | |
| 11 | +/// One audio stream declared by an AVI file. | |
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 13 | +pub struct AviAudioStream { | |
| 14 | + /// AVI stream number, the two decimal digits at the start of chunk ids. | |
| 15 | + pub index: u32, | |
| 16 | + /// WAVE format tag from this stream's `strf` body. | |
| 17 | + pub format_tag: u16, | |
| 18 | + /// Channel count stated by the WAVEFORMAT header. | |
| 19 | + pub channels: u16, | |
| 20 | + /// Samples per second stated by the WAVEFORMAT header. | |
| 21 | + pub sample_rate: u32, | |
| 22 | + /// Block alignment stated by the WAVEFORMAT header. | |
| 23 | + pub block_align: u16, | |
| 24 | + /// Bits per sample stated by the WAVEFORMAT header. | |
| 25 | + pub bits_per_sample: u16, | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// One audio chunk from `movi`. | |
| 29 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 30 | +pub struct AviPacket { | |
| 31 | + /// AVI stream number. | |
| 32 | + pub stream: u32, | |
| 33 | + /// Chunk payload. | |
| 34 | + pub data: Vec<u8>, | |
| 35 | +} | |
| 36 | + | |
| 37 | +/// A reader over AVI audio chunks. | |
| 38 | +pub struct AviReader<R> { | |
| 39 | + inner: R, | |
| 40 | + streams: Vec<AviAudioStream>, | |
| 41 | + movi_end: u64, | |
| 42 | + pos: u64, | |
| 43 | + pending: VecDeque<AviPacket>, | |
| 44 | +} | |
| 45 | + | |
| 46 | +impl<R: Read + Seek> AviReader<R> { | |
| 47 | + /// Parse the RIFF/AVI headers, leaving the reader at the start of `movi`. | |
| 48 | + pub fn new(mut inner: R) -> Result<AviReader<R>> { | |
| 49 | + let end = inner.seek(SeekFrom::End(0))?; | |
| 50 | + inner.rewind()?; | |
| 51 | + let mut head = [0u8; 12]; | |
| 52 | + read_full(&mut inner, &mut head)?; | |
| 53 | + if &head[0..4] != b"RIFF" || &head[8..12] != b"AVI " { | |
| 54 | + return Err(Error::corrupt("not a RIFF/AVI file")); | |
| 55 | + } | |
| 56 | + | |
| 57 | + let mut streams = Vec::new(); | |
| 58 | + let mut movi = None; | |
| 59 | + let mut pos = 12u64; | |
| 60 | + while pos + 8 <= end { | |
| 61 | + inner.seek(SeekFrom::Start(pos))?; | |
| 62 | + let mut chunk = [0u8; 8]; | |
| 63 | + let got = read_some(&mut inner, &mut chunk)?; | |
| 64 | + if got == 0 { | |
| 65 | + break; | |
| 66 | + } | |
| 67 | + if got < 8 { | |
| 68 | + return Err(Error::corrupt("AVI chunk header ends mid-field")); | |
| 69 | + } | |
| 70 | + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; | |
| 71 | + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; | |
| 72 | + let data = pos + 8; | |
| 73 | + let next = data.saturating_add(size).saturating_add(size & 1); | |
| 74 | + if &id == b"LIST" { | |
| 75 | + let mut kind = [0u8; 4]; | |
| 76 | + if size < 4 || read_some(&mut inner, &mut kind)? < 4 { | |
| 77 | + return Err(Error::corrupt("AVI LIST header ends mid-field")); | |
| 78 | + } | |
| 79 | + let body_start = data + 4; | |
| 80 | + let body_end = data.saturating_add(size).min(end); | |
| 81 | + match &kind { | |
| 82 | + b"hdrl" => streams = parse_hdrl(&mut inner, body_start, body_end)?, | |
| 83 | + b"movi" => movi = Some((body_start, body_end)), | |
| 84 | + _ => {} | |
| 85 | + } | |
| 86 | + } | |
| 87 | + pos = next; | |
| 88 | + } | |
| 89 | + let (pos, movi_end) = movi.ok_or_else(|| Error::corrupt("AVI: no movi list"))?; | |
| 90 | + Ok(AviReader { | |
| 91 | + inner, | |
| 92 | + streams, | |
| 93 | + movi_end, | |
| 94 | + pos, | |
| 95 | + pending: VecDeque::new(), | |
| 96 | + }) | |
| 97 | + } | |
| 98 | + | |
| 99 | + /// Audio streams declared in the header. | |
| 100 | + pub fn audio_streams(&self) -> &[AviAudioStream] { | |
| 101 | + &self.streams | |
| 102 | + } | |
| 103 | + | |
| 104 | + /// The next audio chunk, or [`Error::Eof`] at the end. | |
| 105 | + pub fn next_packet(&mut self) -> Result<AviPacket> { | |
| 106 | + if let Some(packet) = self.pending.pop_front() { | |
| 107 | + return Ok(packet); | |
| 108 | + } | |
| 109 | + while self.pos + 8 <= self.movi_end { | |
| 110 | + self.inner.seek(SeekFrom::Start(self.pos))?; | |
| 111 | + let mut chunk = [0u8; 8]; | |
| 112 | + let got = read_some(&mut self.inner, &mut chunk)?; | |
| 113 | + if got == 0 || got < 8 { | |
| 114 | + self.pos = self.movi_end; | |
| 115 | + return Err(Error::Eof); | |
| 116 | + } | |
| 117 | + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; | |
| 118 | + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; | |
| 119 | + let data = self.pos + 8; | |
| 120 | + let padded = size.saturating_add(size & 1); | |
| 121 | + let next = data.saturating_add(padded); | |
| 122 | + if next > self.movi_end { | |
| 123 | + self.pos = self.movi_end; | |
| 124 | + return Err(Error::Eof); | |
| 125 | + } | |
| 126 | + self.pos = next; | |
| 127 | + if &id == b"LIST" { | |
| 128 | + if size >= 4 { | |
| 129 | + let mut kind = [0u8; 4]; | |
| 130 | + if read_some(&mut self.inner, &mut kind)? < 4 { | |
| 131 | + self.pos = self.movi_end; | |
| 132 | + return Err(Error::Eof); | |
| 133 | + } | |
| 134 | + if &kind == b"rec " { | |
| 135 | + self.queue_packets_in(data + 4, data + size)?; | |
| 136 | + if let Some(packet) = self.pending.pop_front() { | |
| 137 | + return Ok(packet); | |
| 138 | + } | |
| 139 | + } | |
| 140 | + } | |
| 141 | + continue; | |
| 142 | + } | |
| 143 | + let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else { | |
| 144 | + continue; | |
| 145 | + }; | |
| 146 | + if !self.streams.iter().any(|s| s.index == stream) { | |
| 147 | + continue; | |
| 148 | + } | |
| 149 | + let data_buf = self.read_packet_body(data, size)?; | |
| 150 | + return Ok(AviPacket { | |
| 151 | + stream, | |
| 152 | + data: data_buf, | |
| 153 | + }); | |
| 154 | + } | |
| 155 | + Err(Error::Eof) | |
| 156 | + } | |
| 157 | + | |
| 158 | + fn queue_packets_in(&mut self, start: u64, end: u64) -> Result<()> { | |
| 159 | + let mut pos = start; | |
| 160 | + while pos + 8 <= end { | |
| 161 | + self.inner.seek(SeekFrom::Start(pos))?; | |
| 162 | + let mut chunk = [0u8; 8]; | |
| 163 | + if read_some(&mut self.inner, &mut chunk)? < 8 { | |
| 164 | + break; | |
| 165 | + } | |
| 166 | + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; | |
| 167 | + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; | |
| 168 | + let data = pos + 8; | |
| 169 | + let next = data.saturating_add(size).saturating_add(size & 1); | |
| 170 | + if next > end { | |
| 171 | + break; | |
| 172 | + } | |
| 173 | + if &id == b"LIST" { | |
| 174 | + if size >= 4 { | |
| 175 | + let mut kind = [0u8; 4]; | |
| 176 | + if read_some(&mut self.inner, &mut kind)? < 4 { | |
| 177 | + break; | |
| 178 | + } | |
| 179 | + if &kind == b"rec " { | |
| 180 | + self.queue_packets_in(data + 4, data + size)?; | |
| 181 | + } | |
| 182 | + } | |
| 183 | + } else if let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") | |
| 184 | + && self.streams.iter().any(|s| s.index == stream) | |
| 185 | + { | |
| 186 | + let data_buf = self.read_packet_body(data, size)?; | |
| 187 | + self.pending.push_back(AviPacket { | |
| 188 | + stream, | |
| 189 | + data: data_buf, | |
| 190 | + }); | |
| 191 | + } | |
| 192 | + pos = next; | |
| 193 | + } | |
| 194 | + Ok(()) | |
| 195 | + } | |
| 196 | + | |
| 197 | + fn read_packet_body(&mut self, data: u64, size: u64) -> Result<Vec<u8>> { | |
| 198 | + let mut data_buf = vec![0u8; size as usize]; | |
| 199 | + self.inner.seek(SeekFrom::Start(data))?; | |
| 200 | + if read_some(&mut self.inner, &mut data_buf)? < data_buf.len() { | |
| 201 | + self.pos = self.movi_end; | |
| 202 | + return Err(Error::Eof); | |
| 203 | + } | |
| 204 | + Ok(data_buf) | |
| 205 | + } | |
| 206 | +} | |
| 207 | + | |
| 208 | +fn parse_hdrl<R: Read + Seek>(inner: &mut R, start: u64, end: u64) -> Result<Vec<AviAudioStream>> { | |
| 209 | + let mut streams = Vec::new(); | |
| 210 | + let mut stream_no = 0u32; | |
| 211 | + let mut pos = start; | |
| 212 | + while pos + 8 <= end { | |
| 213 | + inner.seek(SeekFrom::Start(pos))?; | |
| 214 | + let mut chunk = [0u8; 8]; | |
| 215 | + if read_some(inner, &mut chunk)? < 8 { | |
| 216 | + break; | |
| 217 | + } | |
| 218 | + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; | |
| 219 | + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; | |
| 220 | + let data = pos + 8; | |
| 221 | + let next = data.saturating_add(size).saturating_add(size & 1); | |
| 222 | + if &id == b"LIST" { | |
| 223 | + let mut kind = [0u8; 4]; | |
| 224 | + if size >= 4 && read_some(inner, &mut kind)? == 4 && &kind == b"strl" { | |
| 225 | + if let Some(stream) = parse_strl(inner, stream_no, data + 4, data + size)? { | |
| 226 | + streams.push(stream); | |
| 227 | + } | |
| 228 | + stream_no += 1; | |
| 229 | + } | |
| 230 | + } | |
| 231 | + pos = next; | |
| 232 | + } | |
| 233 | + Ok(streams) | |
| 234 | +} | |
| 235 | + | |
| 236 | +fn parse_strl<R: Read + Seek>( | |
| 237 | + inner: &mut R, | |
| 238 | + stream_no: u32, | |
| 239 | + start: u64, | |
| 240 | + end: u64, | |
| 241 | +) -> Result<Option<AviAudioStream>> { | |
| 242 | + let mut audio = false; | |
| 243 | + let mut fmt = None; | |
| 244 | + let mut pos = start; | |
| 245 | + while pos + 8 <= end { | |
| 246 | + inner.seek(SeekFrom::Start(pos))?; | |
| 247 | + let mut chunk = [0u8; 8]; | |
| 248 | + if read_some(inner, &mut chunk)? < 8 { | |
| 249 | + break; | |
| 250 | + } | |
| 251 | + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; | |
| 252 | + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; | |
| 253 | + let data = pos + 8; | |
| 254 | + let next = data.saturating_add(size).saturating_add(size & 1); | |
| 255 | + match &id { | |
| 256 | + b"strh" => { | |
| 257 | + let mut body = vec![0u8; size.min(64) as usize]; | |
| 258 | + read_full(inner, &mut body)?; | |
| 259 | + audio = body.get(0..4) == Some(&b"auds"[..]); | |
| 260 | + } | |
| 261 | + b"strf" => { | |
| 262 | + let mut body = vec![0u8; size.min(18) as usize]; | |
| 263 | + read_full(inner, &mut body)?; | |
| 264 | + if body.len() >= 16 { | |
| 265 | + fmt = Some(AviAudioStream { | |
| 266 | + index: stream_no, | |
| 267 | + format_tag: u16::from_le_bytes([body[0], body[1]]), | |
| 268 | + channels: u16::from_le_bytes([body[2], body[3]]), | |
| 269 | + sample_rate: u32::from_le_bytes([body[4], body[5], body[6], body[7]]), | |
| 270 | + block_align: u16::from_le_bytes([body[12], body[13]]), | |
| 271 | + bits_per_sample: u16::from_le_bytes([body[14], body[15]]), | |
| 272 | + }); | |
| 273 | + } | |
| 274 | + } | |
| 275 | + _ => {} | |
| 276 | + } | |
| 277 | + pos = next; | |
| 278 | + } | |
| 279 | + Ok(audio.then_some(fmt).flatten()) | |
| 280 | +} | |
| 281 | + | |
| 282 | +fn stream_number(id: &[u8; 4]) -> Option<u32> { | |
| 283 | + let a = id[0].checked_sub(b'0')?; | |
| 284 | + let b = id[1].checked_sub(b'0')?; | |
| 285 | + (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b)) | |
| 286 | +} | |
| 287 | + | |
| 288 | +fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> { | |
| 289 | + let mut at = 0; | |
| 290 | + while at < buf.len() { | |
| 291 | + match r.read(&mut buf[at..]) { | |
| 292 | + Ok(0) => break, | |
| 293 | + Ok(n) => at += n, | |
| 294 | + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} | |
| 295 | + Err(e) => return Err(Error::Io(e)), | |
| 296 | + } | |
| 297 | + } | |
| 298 | + Ok(at) | |
| 299 | +} | |
| 300 | + | |
| 301 | +fn read_full(r: &mut impl Read, buf: &mut [u8]) -> Result<()> { | |
| 302 | + if read_some(r, buf)? == buf.len() { | |
| 303 | + Ok(()) | |
| 304 | + } else { | |
| 305 | + Err(Error::corrupt("AVI header ends mid-field")) | |
| 306 | + } | |
| 307 | +} |
crates/ec-riff/src/lib.rsmodified+5 -3
| @@ -1,4 +1,4 @@ | ||
| 1 | -//! RIFF/WAVE: the container edith writes PCM into and reads PCM back from. | |
| 1 | +//! RIFF/WAVE and AVI audio chunk reading. | |
| 2 | 2 | //! |
| 3 | 3 | //! [`WavWriter`] streams samples as they arrive and patches the RIFF, `data` |
| 4 | 4 | //! and `fact` sizes in [`WavWriter::finalize`] — a dropped writer therefore |
| @@ -16,8 +16,8 @@ | ||
| 16 | 16 | //! declares. |
| 17 | 17 | //! |
| 18 | 18 | //! Not covered: RF64/BW64 (>4 GiB), ADPCM and other compressed WAVE tags, |
| 19 | -//! 64-bit float. Each is [`Error::Unsupported`] naming itself, never a silent | |
| 20 | -//! misread. | |
| 19 | +//! 64-bit float, AVI video frames, and non-audio AVI chunks. Each unsupported | |
| 20 | +//! WAVE tag is [`Error::Unsupported`] naming itself, never a silent misread. | |
| 21 | 21 | //! |
| 22 | 22 | //! The crate stands alone — [`WavSpec`] is its own type — but converts into the |
| 23 | 23 | //! family IR on request: [`WavSpec::sample_format`] and [`WavSpec::layout`]. |
| @@ -25,9 +25,11 @@ | ||
| 25 | 25 | #![forbid(unsafe_code)] |
| 26 | 26 | #![warn(missing_docs)] |
| 27 | 27 | |
| 28 | +mod avi; | |
| 28 | 29 | mod read; |
| 29 | 30 | mod write; |
| 30 | 31 | |
| 32 | +pub use avi::{AviAudioStream, AviPacket, AviReader}; | |
| 31 | 33 | pub use ec_core::{Error, Result}; |
| 32 | 34 | pub use read::WavReader; |
| 33 | 35 | pub use write::{Sample, WavWriter}; |
crates/ec-riff/tests/wav.rsmodified+69 -1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | |
| 8 | 8 | use std::io::Cursor; |
| 9 | 9 | |
| 10 | -use ec_riff::{SampleType, WavReader, WavSpec, WavWriter}; | |
| 10 | +use ec_riff::{AviReader, Error, SampleType, WavReader, WavSpec, WavWriter}; | |
| 11 | 11 | |
| 12 | 12 | /// Deterministic samples in `bits`-bit range: a walking pattern that exercises |
| 13 | 13 | /// both signs and the extremes of the depth. |
| @@ -196,6 +196,74 @@ fn truncated_and_placeholder_sizes_read_what_is_there() { | ||
| 196 | 196 | assert_eq!(r.read_all_i32().unwrap(), samples); |
| 197 | 197 | } |
| 198 | 198 | |
| 199 | +#[test] | |
| 200 | +fn avi_truncated_tail_is_end_of_stream() { | |
| 201 | + fn chunk(out: &mut Vec<u8>, id: &[u8; 4], body: &[u8]) { | |
| 202 | + out.extend_from_slice(id); | |
| 203 | + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); | |
| 204 | + out.extend_from_slice(body); | |
| 205 | + if body.len() % 2 == 1 { | |
| 206 | + out.push(0); | |
| 207 | + } | |
| 208 | + } | |
| 209 | + | |
| 210 | + fn list(out: &mut Vec<u8>, kind: &[u8; 4], body: &[u8]) { | |
| 211 | + out.extend_from_slice(b"LIST"); | |
| 212 | + out.extend_from_slice(&((body.len() + 4) as u32).to_le_bytes()); | |
| 213 | + out.extend_from_slice(kind); | |
| 214 | + out.extend_from_slice(body); | |
| 215 | + if body.len() % 2 == 1 { | |
| 216 | + out.push(0); | |
| 217 | + } | |
| 218 | + } | |
| 219 | + | |
| 220 | + let mut strh = Vec::new(); | |
| 221 | + strh.extend_from_slice(b"auds"); | |
| 222 | + strh.extend_from_slice(&[0; 52]); | |
| 223 | + let mut strf = Vec::new(); | |
| 224 | + strf.extend_from_slice(&0x2000u16.to_le_bytes()); | |
| 225 | + strf.extend_from_slice(&2u16.to_le_bytes()); | |
| 226 | + strf.extend_from_slice(&48_000u32.to_le_bytes()); | |
| 227 | + strf.extend_from_slice(&0u32.to_le_bytes()); | |
| 228 | + strf.extend_from_slice(&0u16.to_le_bytes()); | |
| 229 | + strf.extend_from_slice(&0u16.to_le_bytes()); | |
| 230 | + let mut strl = Vec::new(); | |
| 231 | + chunk(&mut strl, b"strh", &strh); | |
| 232 | + chunk(&mut strl, b"strf", &strf); | |
| 233 | + let mut hdrl = Vec::new(); | |
| 234 | + list(&mut hdrl, b"strl", &strl); | |
| 235 | + chunk(&mut hdrl, b"dmlh", &[0, 0, 0, 0]); | |
| 236 | + | |
| 237 | + let mut rec = Vec::new(); | |
| 238 | + chunk(&mut rec, b"00wb", &[1, 2, 3]); | |
| 239 | + let mut movi = Vec::new(); | |
| 240 | + chunk(&mut movi, b"00wb", &[0x0b, 0x77, 0, 0]); | |
| 241 | + chunk(&mut movi, b"indx", &[0; 16]); | |
| 242 | + list(&mut movi, b"rec ", &rec); | |
| 243 | + movi.extend_from_slice(b"00"); | |
| 244 | + | |
| 245 | + let mut body = Vec::new(); | |
| 246 | + list(&mut body, b"hdrl", &hdrl); | |
| 247 | + list(&mut body, b"movi", &movi); | |
| 248 | + let mut avi = Vec::new(); | |
| 249 | + avi.extend_from_slice(b"RIFF"); | |
| 250 | + avi.extend_from_slice(&((body.len() + 4) as u32).to_le_bytes()); | |
| 251 | + avi.extend_from_slice(b"AVI "); | |
| 252 | + avi.extend_from_slice(&body); | |
| 253 | + | |
| 254 | + let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens"); | |
| 255 | + assert_eq!(reader.audio_streams()[0].format_tag, 0x2000); | |
| 256 | + assert_eq!( | |
| 257 | + reader.next_packet().expect("first packet").data, | |
| 258 | + [0x0b, 0x77, 0, 0] | |
| 259 | + ); | |
| 260 | + assert_eq!(reader.next_packet().expect("nested packet").data, [1, 2, 3]); | |
| 261 | + let err = reader | |
| 262 | + .next_packet() | |
| 263 | + .expect_err("truncated tail ends the stream"); | |
| 264 | + assert!(matches!(err, Error::Eof)); | |
| 265 | +} | |
| 266 | + | |
| 199 | 267 | #[test] |
| 200 | 268 | fn refusals_name_a_real_absence() { |
| 201 | 269 | // Not RIFF at all. |