forge
Explore
Log in

Don't you dare go Hollow

End AVI audio chunks cleanly

Browse files at this commit

57f47907a7ddd46a75ec2f1536fdd7a075dd2bb4Ahmet Kaan GümüşParent: e44f0f4
  • fix
    • end AVI audio chunks cleanly
Show full message
fix(riff): end AVI audio chunks cleanly
crates/ec-probe/Cargo.tomlmodified+1 -1
@@ -1,6 +1,6 @@
1 [package]1 [package]
2 name = "ec-probe"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 version.workspace = true4 version.workspace = true
5 edition.workspace = true5 edition.workspace = true
6 license.workspace = true6 license.workspace = true
crates/ec-probe/src/lib.rsmodified+187 -8
@@ -8,9 +8,9 @@
8 //!8 //!
9 //! What this crate does *not* do is parse containers a sibling crate already9 //! What this crate does *not* do is parse containers a sibling crate already
10 //! parses. Matroska goes to [`ec_matroska`], mp4 to [`ec_mp4`], Ogg to10 //! 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 not11+//! [`ec_ogg`], and RIFF/WAVE/AVI to [`ec_riff`]; there is exactly one parser
12-//! here. What is implemented in [`raw`] is the four formats that are a codec12+//! for each container family. What is implemented in [`raw`] is the three
13-//! and nothing else: WAV, MP3, FLAC and ADTS.13+//! formats that are a codec and nothing else: MP3, FLAC and ADTS.
14 //!14 //!
15 //! Two contracts worth knowing:15 //! Two contracts worth knowing:
16 //!16 //!
@@ -36,9 +36,13 @@ use std::io::{BufReader, Read, Seek, SeekFrom};
36 use std::path::Path;36 use std::path::Path;
37 37
38 use ec_core::error::{Error, Result};38 use ec_core::error::{Error, Result};
39-use ec_core::packet::Packet;39+use ec_core::packet::{Buf, Packet, PacketFlags};
40-use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode, StreamInfo};40+use ec_core::registry::{
41+ AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, MediaType, SeekMode,
42+ StreamInfo,
43+};
41 use ec_core::timebase::{Rounding, TimeBase, Timestamp};44 use ec_core::timebase::{Rounding, TimeBase, Timestamp};
45+use ec_core::{ChannelLayout, SampleFormat};
42 46
43 pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip};47 pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip};
44 pub use tags::Tags;48 pub use tags::Tags;
@@ -67,6 +71,8 @@ pub enum Format {
67 Ogg,71 Ogg,
68 /// ISO base media: mp4, m4a, mov.72 /// ISO base media: mp4, m4a, mov.
69 Mp4,73 Mp4,
74+ /// RIFF/AVI.
75+ Avi,
70 /// Matroska and WebM.76 /// Matroska and WebM.
71 Matroska,77 Matroska,
72 }78 }
@@ -82,6 +88,7 @@ impl Format {
82 Format::Ogg => "ogg",88 Format::Ogg => "ogg",
83 Format::Mp4 => "mp4",89 Format::Mp4 => "mp4",
84 Format::Matroska => "matroska",90 Format::Matroska => "matroska",
91+ Format::Avi => "avi",
85 }92 }
86 }93 }
87 94
@@ -96,6 +103,7 @@ impl Format {
96 Format::Ogg => &["ogg", "oga", "opus"],103 Format::Ogg => &["ogg", "oga", "opus"],
97 Format::Mp4 => &["mp4", "m4a", "m4v", "mov"],104 Format::Mp4 => &["mp4", "m4a", "m4v", "mov"],
98 Format::Matroska => &["mkv", "mka", "mks", "mk3d", "webm"],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 pub fn sniff(head: &[u8]) -> Option<Format> {115 pub fn sniff(head: &[u8]) -> Option<Format> {
108 let at = tags::id3v2_len(head).unwrap_or(0) as usize;116 let at = tags::id3v2_len(head).unwrap_or(0) as usize;
109 let data = head.get(at..).filter(|d| !d.is_empty()).unwrap_or(head);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" {118+ if data.len() >= 12 && &data[..4] == b"RIFF" {
111- return Some(Format::Wav);119+ match &data[8..12] {
120+ b"WAVE" => return Some(Format::Wav),
121+ b"AVI " => return Some(Format::Avi),
122+ _ => {}
123+ }
112 }124 }
113 if data.starts_with(b"fLaC") {125 if data.starts_with(b"fLaC") {
114 return Some(Format::Flac);126 return Some(Format::Flac);
@@ -223,6 +235,7 @@ impl Reader {
223 Format::Ogg,235 Format::Ogg,
224 Format::Mp4,236 Format::Mp4,
225 Format::Matroska,237 Format::Matroska,
238+ Format::Avi,
226 ]239 ]
227 .into_iter()240 .into_iter()
228 .find(|f| f.extensions().contains(&hint.as_str()))241 .find(|f| f.extensions().contains(&hint.as_str()))
@@ -230,7 +243,7 @@ impl Reader {
230 .ok_or_else(|| {243 .ok_or_else(|| {
231 Error::unsupported(244 Error::unsupported(
232 "this file",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 src.rewind()?;249 src.rewind()?;
@@ -275,6 +288,7 @@ impl Reader {
275 Ok(Reader::wrap(format, Box::new(demuxer), tags, native))288 Ok(Reader::wrap(format, Box::new(demuxer), tags, native))
276 }289 }
277 Format::Wav => open_wav(src, end),290 Format::Wav => open_wav(src, end),
291+ Format::Avi => open_avi(src),
278 Format::Flac => open_flac(src, &head, end),292 Format::Flac => open_flac(src, &head, end),
279 Format::Mp3 => open_mp3(src, &head, end),293 Format::Mp3 => open_mp3(src, &head, end),
280 Format::Adts => open_adts(src, &head, end),294 Format::Adts => open_adts(src, &head, end),
@@ -635,6 +649,171 @@ fn open_adts<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64)
635 Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0]))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+}
675+
676+impl<R: Read + Seek> AviDemuxer<R> {
677+ fn new(reader: ec_riff::AviReader<R>) -> Result<AviDemuxer<R>> {
678+ let mut streams = Vec::new();
679+ let mut stream_numbers = Vec::new();
680+ for (index, s) in reader.audio_streams().iter().enumerate() {
681+ let codec = match s.format_tag {
682+ 0x0001 if s.bits_per_sample <= 8 => CodecId::PcmU8,
683+ 0x0001 => CodecId::PcmS16Le,
684+ 0x0055 => CodecId::Mp3,
685+ 0x00ff => CodecId::Aac,
686+ 0x2000 => CodecId::Ac3,
687+ tag => {
688+ return Err(Error::unsupported(
689+ format!("AVI audio format tag {tag:#06x}"),
690+ "no decoder for it exists in this family yet",
691+ ));
692+ }
693+ };
694+ let mut params = CodecParameters::new(codec);
695+ params.media = MediaParameters::Audio(AudioParameters {
696+ sample_rate: s.sample_rate,
697+ layout: ChannelLayout::from_count(usize::from(s.channels).max(1)),
698+ format: match codec {
699+ CodecId::PcmU8 => Some(SampleFormat::U8),
700+ CodecId::PcmS16Le => Some(SampleFormat::S16),
701+ _ => None,
702+ },
703+ bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)),
704+ });
705+ streams.push(StreamInfo::new(
706+ index as u32,
707+ TimeBase::from_rate(s.sample_rate.max(1)),
708+ params,
709+ ));
710+ stream_numbers.push(s.index);
711+ }
712+ if streams.is_empty() {
713+ return Err(Error::unsupported(
714+ "this AVI file",
715+ "it declares no audio stream this reader can hand out",
716+ ));
717+ }
718+ let samples = vec![0; streams.len()];
719+ Ok(AviDemuxer {
720+ reader,
721+ streams,
722+ stream_numbers,
723+ samples,
724+ pending: VecDeque::new(),
725+ })
726+ }
727+
728+ fn queue_chunk(&mut self, chunk: ec_riff::AviPacket) -> Result<()> {
729+ let Some(stream) = self.stream_numbers.iter().position(|&n| n == chunk.stream) else {
730+ return Ok(());
731+ };
732+ let codec = self.streams[stream].params.codec;
733+ match codec {
734+ CodecId::Ac3 | CodecId::EAc3 => {
735+ let mut at = 0usize;
736+ while at + 6 <= chunk.data.len() {
737+ if chunk.data[at] != 0x0b || chunk.data[at + 1] != 0x77 {
738+ at += 1;
739+ continue;
740+ }
741+ let size = match ec_ac3::frame_size(&chunk.data[at..]) {
742+ Ok(size) if at + size <= chunk.data.len() => size,
743+ Ok(_) | Err(Error::NeedMore) => break,
744+ Err(_) => {
745+ at += 1;
746+ continue;
747+ }
748+ };
749+ self.push_packet(
750+ stream,
751+ Buf::copy_from_slice(&chunk.data[at..at + size]),
752+ 1536,
753+ );
754+ at += size;
755+ }
756+ }
757+ _ => {
758+ let frames = match codec {
759+ CodecId::PcmU8 | CodecId::PcmS16Le => {
760+ let block = self
761+ .reader
762+ .audio_streams()
763+ .get(stream)
764+ .map_or(1usize, |s| usize::from(s.block_align).max(1));
765+ (chunk.data.len() / block) as u64
766+ }
767+ _ => 0,
768+ };
769+ self.push_packet(stream, Buf::from_vec(chunk.data), frames);
770+ }
771+ }
772+ Ok(())
773+ }
774+
775+ fn push_packet(&mut self, stream: usize, data: Buf, frames: u64) {
776+ let base = self.streams[stream].time_base;
777+ let pts = self.samples[stream];
778+ self.samples[stream] = self.samples[stream].saturating_add(frames);
779+ let mut packet = Packet::new(stream as u32, base, data);
780+ packet.pts = Some(pts as i64);
781+ packet.dts = Some(pts as i64);
782+ packet.duration = Some(frames as i64);
783+ packet.flags = PacketFlags {
784+ keyframe: true,
785+ ..PacketFlags::default()
786+ };
787+ self.pending.push_back(packet);
788+ }
789+}
790+
791+impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> {
792+ fn streams(&self) -> &[StreamInfo] {
793+ &self.streams
794+ }
795+
796+ fn next_packet(&mut self) -> Result<Packet> {
797+ loop {
798+ if let Some(packet) = self.pending.pop_front() {
799+ return Ok(packet);
800+ }
801+ match self.reader.next_packet() {
802+ Ok(chunk) => self.queue_chunk(chunk)?,
803+ Err(e) if e.is_eof() => return Err(Error::Eof),
804+ Err(e) => return Err(e),
805+ }
806+ }
807+ }
808+
809+ fn seek(&mut self, _stream: u32, _to: Timestamp, _mode: SeekMode) -> Result<()> {
810+ Err(Error::unsupported(
811+ "AVI audio seek",
812+ "this reader only walks AVI sound chunks in storage order",
813+ ))
814+ }
815+}
816+
638 /// Skip an ID3v2 tag at the head of a stream, reading its text on the way past.817 /// Skip an ID3v2 tag at the head of a stream, reading its text on the way past.
639 fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> {818 fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> {
640 let mut tags = Tags::default();819 let mut tags = Tags::default();
crates/ec-probe/tests/library.rsmodified+37 -1
@@ -197,6 +197,38 @@ fn a_real_library_sweep() {
197 assert!(failures.is_empty(), "{}", failures.join("\n"));197 assert!(failures.is_empty(), "{}", failures.join("\n"));
198 }198 }
199 199
200+#[test]
201+fn avi_audio_chunks_end_cleanly_on_real_files() {
202+ let files = [
203+ "/home/user/Downloads/reele/reele.avi",
204+ "/home/user/Downloads/reele/sample.avi",
205+ ];
206+ let mut present = 0;
207+ for path in files {
208+ let path = Path::new(path);
209+ if !path.exists() {
210+ continue;
211+ }
212+ present += 1;
213+ let mut reader = Reader::open(path).expect("AVI opens");
214+ let audio = reader
215+ .default_stream(MediaType::Audio)
216+ .expect("AVI audio stream")
217+ .index;
218+ let mut packets = 0;
219+ loop {
220+ match reader.next_packet() {
221+ Ok(packet) if packet.stream == audio => packets += 1,
222+ Ok(_) => {}
223+ Err(e) if e.is_eof() => break,
224+ Err(e) => panic!("{}: {e}", path.display()),
225+ }
226+ }
227+ assert!(packets > 0, "{}: no audio packets", path.display());
228+ }
229+ assert!(present > 0, "AVI files absent");
230+}
231+
200 /// The TrueHD remux in his library: the track decodes through the unified232 /// The TrueHD remux in his library: the track decodes through the unified
201 /// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too.233 /// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too.
202 #[test]234 #[test]
@@ -312,7 +344,11 @@ fn a_cover_art_tagged_mp3_opens() {
312 .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])344 .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
313 .output()345 .output()
314 .expect("ffmpeg runs");346 .expect("ffmpeg runs");
315- assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));347+ assert!(
348+ out.status.success(),
349+ "{}",
350+ String::from_utf8_lossy(&out.stderr)
351+ );
316 let theirs: Vec<f32> = out352 let theirs: Vec<f32> = out
317 .stdout353 .stdout
318 .chunks_exact(4)354 .chunks_exact(4)
crates/ec-riff/Cargo.tomlmodified+1 -1
@@ -1,6 +1,6 @@
1 [package]1 [package]
2 name = "ec-riff"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 version.workspace = true4 version.workspace = true
5 edition.workspace = true5 edition.workspace = true
6 license.workspace = true6 license.workspace = true
crates/ec-riff/src/avi.rsadded+246 -0
@@ -0,0 +1,246 @@
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+ let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else {
128+ continue;
129+ };
130+ if !self.streams.iter().any(|s| s.index == stream) {
131+ continue;
132+ }
133+ let mut data_buf = vec![0u8; size as usize];
134+ if read_some(&mut self.inner, &mut data_buf)? < data_buf.len() {
135+ self.pos = self.movi_end;
136+ return Err(Error::Eof);
137+ }
138+ return Ok(AviPacket {
139+ stream,
140+ data: data_buf,
141+ });
142+ }
143+ Err(Error::Eof)
144+ }
145+}
146+
147+fn parse_hdrl<R: Read + Seek>(inner: &mut R, start: u64, end: u64) -> Result<Vec<AviAudioStream>> {
148+ let mut streams = Vec::new();
149+ let mut stream_no = 0u32;
150+ let mut pos = start;
151+ while pos + 8 <= end {
152+ inner.seek(SeekFrom::Start(pos))?;
153+ let mut chunk = [0u8; 8];
154+ if read_some(inner, &mut chunk)? < 8 {
155+ break;
156+ }
157+ let id = [chunk[0], chunk[1], chunk[2], chunk[3]];
158+ let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64;
159+ let data = pos + 8;
160+ let next = data.saturating_add(size).saturating_add(size & 1);
161+ if &id == b"LIST" {
162+ let mut kind = [0u8; 4];
163+ if size >= 4 && read_some(inner, &mut kind)? == 4 && &kind == b"strl" {
164+ if let Some(stream) = parse_strl(inner, stream_no, data + 4, data + size)? {
165+ streams.push(stream);
166+ }
167+ stream_no += 1;
168+ }
169+ }
170+ pos = next;
171+ }
172+ Ok(streams)
173+}
174+
175+fn parse_strl<R: Read + Seek>(
176+ inner: &mut R,
177+ stream_no: u32,
178+ start: u64,
179+ end: u64,
180+) -> Result<Option<AviAudioStream>> {
181+ let mut audio = false;
182+ let mut fmt = None;
183+ let mut pos = start;
184+ while pos + 8 <= end {
185+ inner.seek(SeekFrom::Start(pos))?;
186+ let mut chunk = [0u8; 8];
187+ if read_some(inner, &mut chunk)? < 8 {
188+ break;
189+ }
190+ let id = [chunk[0], chunk[1], chunk[2], chunk[3]];
191+ let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64;
192+ let data = pos + 8;
193+ let next = data.saturating_add(size).saturating_add(size & 1);
194+ match &id {
195+ b"strh" => {
196+ let mut body = vec![0u8; size.min(64) as usize];
197+ read_full(inner, &mut body)?;
198+ audio = body.get(0..4) == Some(&b"auds"[..]);
199+ }
200+ b"strf" => {
201+ let mut body = vec![0u8; size.min(18) as usize];
202+ read_full(inner, &mut body)?;
203+ if body.len() >= 16 {
204+ fmt = Some(AviAudioStream {
205+ index: stream_no,
206+ format_tag: u16::from_le_bytes([body[0], body[1]]),
207+ channels: u16::from_le_bytes([body[2], body[3]]),
208+ sample_rate: u32::from_le_bytes([body[4], body[5], body[6], body[7]]),
209+ block_align: u16::from_le_bytes([body[12], body[13]]),
210+ bits_per_sample: u16::from_le_bytes([body[14], body[15]]),
211+ });
212+ }
213+ }
214+ _ => {}
215+ }
216+ pos = next;
217+ }
218+ Ok(audio.then_some(fmt).flatten())
219+}
220+
221+fn stream_number(id: &[u8; 4]) -> Option<u32> {
222+ let a = id[0].checked_sub(b'0')?;
223+ let b = id[1].checked_sub(b'0')?;
224+ (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b))
225+}
226+
227+fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
228+ let mut at = 0;
229+ while at < buf.len() {
230+ match r.read(&mut buf[at..]) {
231+ Ok(0) => break,
232+ Ok(n) => at += n,
233+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
234+ Err(e) => return Err(Error::Io(e)),
235+ }
236+ }
237+ Ok(at)
238+}
239+
240+fn read_full(r: &mut impl Read, buf: &mut [u8]) -> Result<()> {
241+ if read_some(r, buf)? == buf.len() {
242+ Ok(())
243+ } else {
244+ Err(Error::corrupt("AVI header ends mid-field"))
245+ }
246+}
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 //! [`WavWriter`] streams samples as they arrive and patches the RIFF, `data`3 //! [`WavWriter`] streams samples as they arrive and patches the RIFF, `data`
4 //! and `fact` sizes in [`WavWriter::finalize`] — a dropped writer therefore4 //! and `fact` sizes in [`WavWriter::finalize`] — a dropped writer therefore
@@ -16,8 +16,8 @@
16 //! declares.16 //! declares.
17 //!17 //!
18 //! Not covered: RF64/BW64 (>4 GiB), ADPCM and other compressed WAVE tags,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 silent19+//! 64-bit float, AVI video frames, and non-audio AVI chunks. Each unsupported
20-//! misread.20+//! WAVE tag is [`Error::Unsupported`] naming itself, never a silent misread.
21 //!21 //!
22 //! The crate stands alone — [`WavSpec`] is its own type — but converts into the22 //! The crate stands alone — [`WavSpec`] is its own type — but converts into the
23 //! family IR on request: [`WavSpec::sample_format`] and [`WavSpec::layout`].23 //! family IR on request: [`WavSpec::sample_format`] and [`WavSpec::layout`].
@@ -25,9 +25,11 @@
25 #![forbid(unsafe_code)]25 #![forbid(unsafe_code)]
26 #![warn(missing_docs)]26 #![warn(missing_docs)]
27 27
28+mod avi;
28 mod read;29 mod read;
29 mod write;30 mod write;
30 31
32+pub use avi::{AviAudioStream, AviPacket, AviReader};
31 pub use ec_core::{Error, Result};33 pub use ec_core::{Error, Result};
32 pub use read::WavReader;34 pub use read::WavReader;
33 pub use write::{Sample, WavWriter};35 pub use write::{Sample, WavWriter};
crates/ec-riff/tests/wav.rsmodified+63 -1
@@ -7,7 +7,7 @@
7 7
8 use std::io::Cursor;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 /// Deterministic samples in `bits`-bit range: a walking pattern that exercises12 /// Deterministic samples in `bits`-bit range: a walking pattern that exercises
13 /// both signs and the extremes of the depth.13 /// both signs and the extremes of the depth.
@@ -196,6 +196,68 @@ fn truncated_and_placeholder_sizes_read_what_is_there() {
196 assert_eq!(r.read_all_i32().unwrap(), samples);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+
236+ let mut movi = Vec::new();
237+ chunk(&mut movi, b"00wb", &[0x0b, 0x77, 0, 0]);
238+ movi.extend_from_slice(b"00");
239+
240+ let mut body = Vec::new();
241+ list(&mut body, b"hdrl", &hdrl);
242+ list(&mut body, b"movi", &movi);
243+ let mut avi = Vec::new();
244+ avi.extend_from_slice(b"RIFF");
245+ avi.extend_from_slice(&((body.len() + 4) as u32).to_le_bytes());
246+ avi.extend_from_slice(b"AVI ");
247+ avi.extend_from_slice(&body);
248+
249+ let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens");
250+ assert_eq!(reader.audio_streams()[0].format_tag, 0x2000);
251+ assert_eq!(
252+ reader.next_packet().expect("first packet").data,
253+ [0x0b, 0x77, 0, 0]
254+ );
255+ let err = reader
256+ .next_packet()
257+ .expect_err("truncated tail ends the stream");
258+ assert!(matches!(err, Error::Eof));
259+}
260+
199 #[test]261 #[test]
200 fn refusals_name_a_real_absence() {262 fn refusals_name_a_real_absence() {
201 // Not RIFF at all.263 // Not RIFF at all.