From 57f47907a7ddd46a75ec2f1536fdd7a075dd2bb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 12:54:34 +0300 Subject: [PATCH] fix(riff): end AVI audio chunks cleanly --- crates/ec-probe/Cargo.toml | 2 +- crates/ec-probe/src/lib.rs | 195 +++++++++++++++++++++++- crates/ec-probe/tests/library.rs | 38 ++++- crates/ec-riff/Cargo.toml | 2 +- crates/ec-riff/src/avi.rs | 246 +++++++++++++++++++++++++++++++ crates/ec-riff/src/lib.rs | 8 +- crates/ec-riff/tests/wav.rs | 64 +++++++- 7 files changed, 540 insertions(+), 15 deletions(-) create mode 100644 crates/ec-riff/src/avi.rs diff --git a/crates/ec-probe/Cargo.toml b/crates/ec-probe/Cargo.toml index 9e09d54c..a623b4eb 100644 --- a/crates/ec-probe/Cargo.toml +++ b/crates/ec-probe/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ec-probe" -description = "Format detection and one unified audio reader: WAV/MP3/FLAC/ADTS in-crate, Ogg/mp4/Matroska delegated to their own crates." +description = "Format detection and one unified audio reader: WAV/AVI/MP3/FLAC/ADTS in-crate, Ogg/mp4/Matroska delegated to their own crates." version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ec-probe/src/lib.rs b/crates/ec-probe/src/lib.rs index 2d4ec83e..4fbf807d 100644 --- a/crates/ec-probe/src/lib.rs +++ b/crates/ec-probe/src/lib.rs @@ -8,9 +8,9 @@ //! //! What this crate does *not* do is parse containers a sibling crate already //! parses. Matroska goes to [`ec_matroska`], mp4 to [`ec_mp4`], Ogg to -//! [`ec_ogg`]; there is exactly one EBML parser in this family and it is not -//! here. What is implemented in [`raw`] is the four formats that are a codec -//! and nothing else: WAV, MP3, FLAC and ADTS. +//! [`ec_ogg`], and RIFF/WAVE/AVI to [`ec_riff`]; there is exactly one parser +//! for each container family. What is implemented in [`raw`] is the three +//! formats that are a codec and nothing else: MP3, FLAC and ADTS. //! //! Two contracts worth knowing: //! @@ -36,9 +36,13 @@ use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::Path; use ec_core::error::{Error, Result}; -use ec_core::packet::Packet; -use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode, StreamInfo}; +use ec_core::packet::{Buf, Packet, PacketFlags}; +use ec_core::registry::{ + AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, MediaType, SeekMode, + StreamInfo, +}; use ec_core::timebase::{Rounding, TimeBase, Timestamp}; +use ec_core::{ChannelLayout, SampleFormat}; pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip}; pub use tags::Tags; @@ -67,6 +71,8 @@ pub enum Format { Ogg, /// ISO base media: mp4, m4a, mov. Mp4, + /// RIFF/AVI. + Avi, /// Matroska and WebM. Matroska, } @@ -82,6 +88,7 @@ impl Format { Format::Ogg => "ogg", Format::Mp4 => "mp4", Format::Matroska => "matroska", + Format::Avi => "avi", } } @@ -96,6 +103,7 @@ impl Format { Format::Ogg => &["ogg", "oga", "opus"], Format::Mp4 => &["mp4", "m4a", "m4v", "mov"], Format::Matroska => &["mkv", "mka", "mks", "mk3d", "webm"], + Format::Avi => &["avi"], } } } @@ -107,8 +115,12 @@ impl Format { pub fn sniff(head: &[u8]) -> Option { let at = tags::id3v2_len(head).unwrap_or(0) as usize; let data = head.get(at..).filter(|d| !d.is_empty()).unwrap_or(head); - if data.len() >= 12 && &data[..4] == b"RIFF" && &data[8..12] == b"WAVE" { - return Some(Format::Wav); + if data.len() >= 12 && &data[..4] == b"RIFF" { + match &data[8..12] { + b"WAVE" => return Some(Format::Wav), + b"AVI " => return Some(Format::Avi), + _ => {} + } } if data.starts_with(b"fLaC") { return Some(Format::Flac); @@ -223,6 +235,7 @@ impl Reader { Format::Ogg, Format::Mp4, Format::Matroska, + Format::Avi, ] .into_iter() .find(|f| f.extensions().contains(&hint.as_str())) @@ -230,7 +243,7 @@ impl Reader { .ok_or_else(|| { Error::unsupported( "this file", - "its first bytes match no format this build reads (wav, flac, mp3, adts, ogg, mp4, matroska)", + "its first bytes match no format this build reads (wav, flac, mp3, adts, ogg, mp4, avi, matroska)", ) })?; src.rewind()?; @@ -275,6 +288,7 @@ impl Reader { Ok(Reader::wrap(format, Box::new(demuxer), tags, native)) } Format::Wav => open_wav(src, end), + Format::Avi => open_avi(src), Format::Flac => open_flac(src, &head, end), Format::Mp3 => open_mp3(src, &head, end), Format::Adts => open_adts(src, &head, end), @@ -635,6 +649,171 @@ fn open_adts(mut src: R, head: &[u8], end: u64) Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0])) } +fn open_avi(src: R) -> Result { + let reader = ec_riff::AviReader::new(src)?; + let demuxer = AviDemuxer::new(reader)?; + let native = demuxer + .stream_numbers + .iter() + .map(|&n| u64::from(n)) + .collect(); + Ok(Reader::wrap( + Format::Avi, + Box::new(demuxer), + Tags::default(), + native, + )) +} + +struct AviDemuxer { + reader: ec_riff::AviReader, + streams: Vec, + stream_numbers: Vec, + samples: Vec, + pending: VecDeque, +} + +impl AviDemuxer { + fn new(reader: ec_riff::AviReader) -> Result> { + let mut streams = Vec::new(); + let mut stream_numbers = Vec::new(); + for (index, s) in reader.audio_streams().iter().enumerate() { + let codec = match s.format_tag { + 0x0001 if s.bits_per_sample <= 8 => CodecId::PcmU8, + 0x0001 => CodecId::PcmS16Le, + 0x0055 => CodecId::Mp3, + 0x00ff => CodecId::Aac, + 0x2000 => CodecId::Ac3, + tag => { + return Err(Error::unsupported( + format!("AVI audio format tag {tag:#06x}"), + "no decoder for it exists in this family yet", + )); + } + }; + let mut params = CodecParameters::new(codec); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate: s.sample_rate, + layout: ChannelLayout::from_count(usize::from(s.channels).max(1)), + format: match codec { + CodecId::PcmU8 => Some(SampleFormat::U8), + CodecId::PcmS16Le => Some(SampleFormat::S16), + _ => None, + }, + bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)), + }); + streams.push(StreamInfo::new( + index as u32, + TimeBase::from_rate(s.sample_rate.max(1)), + params, + )); + stream_numbers.push(s.index); + } + if streams.is_empty() { + return Err(Error::unsupported( + "this AVI file", + "it declares no audio stream this reader can hand out", + )); + } + let samples = vec![0; streams.len()]; + Ok(AviDemuxer { + reader, + streams, + stream_numbers, + samples, + pending: VecDeque::new(), + }) + } + + fn queue_chunk(&mut self, chunk: ec_riff::AviPacket) -> Result<()> { + let Some(stream) = self.stream_numbers.iter().position(|&n| n == chunk.stream) else { + return Ok(()); + }; + let codec = self.streams[stream].params.codec; + match codec { + CodecId::Ac3 | CodecId::EAc3 => { + let mut at = 0usize; + while at + 6 <= chunk.data.len() { + if chunk.data[at] != 0x0b || chunk.data[at + 1] != 0x77 { + at += 1; + continue; + } + let size = match ec_ac3::frame_size(&chunk.data[at..]) { + Ok(size) if at + size <= chunk.data.len() => size, + Ok(_) | Err(Error::NeedMore) => break, + Err(_) => { + at += 1; + continue; + } + }; + self.push_packet( + stream, + Buf::copy_from_slice(&chunk.data[at..at + size]), + 1536, + ); + at += size; + } + } + _ => { + let frames = match codec { + CodecId::PcmU8 | CodecId::PcmS16Le => { + let block = self + .reader + .audio_streams() + .get(stream) + .map_or(1usize, |s| usize::from(s.block_align).max(1)); + (chunk.data.len() / block) as u64 + } + _ => 0, + }; + self.push_packet(stream, Buf::from_vec(chunk.data), frames); + } + } + Ok(()) + } + + fn push_packet(&mut self, stream: usize, data: Buf, frames: u64) { + let base = self.streams[stream].time_base; + let pts = self.samples[stream]; + self.samples[stream] = self.samples[stream].saturating_add(frames); + let mut packet = Packet::new(stream as u32, base, data); + packet.pts = Some(pts as i64); + packet.dts = Some(pts as i64); + packet.duration = Some(frames as i64); + packet.flags = PacketFlags { + keyframe: true, + ..PacketFlags::default() + }; + self.pending.push_back(packet); + } +} + +impl Demuxer for AviDemuxer { + fn streams(&self) -> &[StreamInfo] { + &self.streams + } + + fn next_packet(&mut self) -> Result { + loop { + if let Some(packet) = self.pending.pop_front() { + return Ok(packet); + } + match self.reader.next_packet() { + Ok(chunk) => self.queue_chunk(chunk)?, + Err(e) if e.is_eof() => return Err(Error::Eof), + Err(e) => return Err(e), + } + } + } + + fn seek(&mut self, _stream: u32, _to: Timestamp, _mode: SeekMode) -> Result<()> { + Err(Error::unsupported( + "AVI audio seek", + "this reader only walks AVI sound chunks in storage order", + )) + } +} + /// Skip an ID3v2 tag at the head of a stream, reading its text on the way past. fn id3(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> { let mut tags = Tags::default(); diff --git a/crates/ec-probe/tests/library.rs b/crates/ec-probe/tests/library.rs index e26e64b8..058e6907 100644 --- a/crates/ec-probe/tests/library.rs +++ b/crates/ec-probe/tests/library.rs @@ -197,6 +197,38 @@ fn a_real_library_sweep() { assert!(failures.is_empty(), "{}", failures.join("\n")); } +#[test] +fn avi_audio_chunks_end_cleanly_on_real_files() { + let files = [ + "/home/user/Downloads/reele/reele.avi", + "/home/user/Downloads/reele/sample.avi", + ]; + let mut present = 0; + for path in files { + let path = Path::new(path); + if !path.exists() { + continue; + } + present += 1; + let mut reader = Reader::open(path).expect("AVI opens"); + let audio = reader + .default_stream(MediaType::Audio) + .expect("AVI audio stream") + .index; + let mut packets = 0; + loop { + match reader.next_packet() { + Ok(packet) if packet.stream == audio => packets += 1, + Ok(_) => {} + Err(e) if e.is_eof() => break, + Err(e) => panic!("{}: {e}", path.display()), + } + } + assert!(packets > 0, "{}: no audio packets", path.display()); + } + assert!(present > 0, "AVI files absent"); +} + /// The TrueHD remux in his library: the track decodes through the unified /// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too. #[test] @@ -312,7 +344,11 @@ fn a_cover_art_tagged_mp3_opens() { .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) .output() .expect("ffmpeg runs"); - assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); let theirs: Vec = out .stdout .chunks_exact(4) diff --git a/crates/ec-riff/Cargo.toml b/crates/ec-riff/Cargo.toml index 697b3fc8..188e95a4 100644 --- a/crates/ec-riff/Cargo.toml +++ b/crates/ec-riff/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ec-riff" -description = "RIFF/WAVE reader and writer: integer and float PCM, mono through 7.1, WAVE_FORMAT_EXTENSIBLE." +description = "RIFF/WAVE reader and writer plus RIFF/AVI audio chunk reader." version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ec-riff/src/avi.rs b/crates/ec-riff/src/avi.rs new file mode 100644 index 00000000..da3da732 --- /dev/null +++ b/crates/ec-riff/src/avi.rs @@ -0,0 +1,246 @@ +//! RIFF/AVI audio chunk reader. +//! +//! This is the small half an audio probe needs: stream headers plus `movi` +//! sound chunks. Picture chunks are skipped. + +use std::collections::VecDeque; +use std::io::{Read, Seek, SeekFrom}; + +use ec_core::{Error, Result}; + +/// One audio stream declared by an AVI file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AviAudioStream { + /// AVI stream number, the two decimal digits at the start of chunk ids. + pub index: u32, + /// WAVE format tag from this stream's `strf` body. + pub format_tag: u16, + /// Channel count stated by the WAVEFORMAT header. + pub channels: u16, + /// Samples per second stated by the WAVEFORMAT header. + pub sample_rate: u32, + /// Block alignment stated by the WAVEFORMAT header. + pub block_align: u16, + /// Bits per sample stated by the WAVEFORMAT header. + pub bits_per_sample: u16, +} + +/// One audio chunk from `movi`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AviPacket { + /// AVI stream number. + pub stream: u32, + /// Chunk payload. + pub data: Vec, +} + +/// A reader over AVI audio chunks. +pub struct AviReader { + inner: R, + streams: Vec, + movi_end: u64, + pos: u64, + pending: VecDeque, +} + +impl AviReader { + /// Parse the RIFF/AVI headers, leaving the reader at the start of `movi`. + pub fn new(mut inner: R) -> Result> { + let end = inner.seek(SeekFrom::End(0))?; + inner.rewind()?; + let mut head = [0u8; 12]; + read_full(&mut inner, &mut head)?; + if &head[0..4] != b"RIFF" || &head[8..12] != b"AVI " { + return Err(Error::corrupt("not a RIFF/AVI file")); + } + + let mut streams = Vec::new(); + let mut movi = None; + let mut pos = 12u64; + while pos + 8 <= end { + inner.seek(SeekFrom::Start(pos))?; + let mut chunk = [0u8; 8]; + let got = read_some(&mut inner, &mut chunk)?; + if got == 0 { + break; + } + if got < 8 { + return Err(Error::corrupt("AVI chunk header ends mid-field")); + } + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; + let data = pos + 8; + let next = data.saturating_add(size).saturating_add(size & 1); + if &id == b"LIST" { + let mut kind = [0u8; 4]; + if size < 4 || read_some(&mut inner, &mut kind)? < 4 { + return Err(Error::corrupt("AVI LIST header ends mid-field")); + } + let body_start = data + 4; + let body_end = data.saturating_add(size).min(end); + match &kind { + b"hdrl" => streams = parse_hdrl(&mut inner, body_start, body_end)?, + b"movi" => movi = Some((body_start, body_end)), + _ => {} + } + } + pos = next; + } + let (pos, movi_end) = movi.ok_or_else(|| Error::corrupt("AVI: no movi list"))?; + Ok(AviReader { + inner, + streams, + movi_end, + pos, + pending: VecDeque::new(), + }) + } + + /// Audio streams declared in the header. + pub fn audio_streams(&self) -> &[AviAudioStream] { + &self.streams + } + + /// The next audio chunk, or [`Error::Eof`] at the end. + pub fn next_packet(&mut self) -> Result { + if let Some(packet) = self.pending.pop_front() { + return Ok(packet); + } + while self.pos + 8 <= self.movi_end { + self.inner.seek(SeekFrom::Start(self.pos))?; + let mut chunk = [0u8; 8]; + let got = read_some(&mut self.inner, &mut chunk)?; + if got == 0 || got < 8 { + self.pos = self.movi_end; + return Err(Error::Eof); + } + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; + let data = self.pos + 8; + let padded = size.saturating_add(size & 1); + let next = data.saturating_add(padded); + if next > self.movi_end { + self.pos = self.movi_end; + return Err(Error::Eof); + } + self.pos = next; + let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else { + continue; + }; + if !self.streams.iter().any(|s| s.index == stream) { + continue; + } + let mut data_buf = vec![0u8; size as usize]; + if read_some(&mut self.inner, &mut data_buf)? < data_buf.len() { + self.pos = self.movi_end; + return Err(Error::Eof); + } + return Ok(AviPacket { + stream, + data: data_buf, + }); + } + Err(Error::Eof) + } +} + +fn parse_hdrl(inner: &mut R, start: u64, end: u64) -> Result> { + let mut streams = Vec::new(); + let mut stream_no = 0u32; + let mut pos = start; + while pos + 8 <= end { + inner.seek(SeekFrom::Start(pos))?; + let mut chunk = [0u8; 8]; + if read_some(inner, &mut chunk)? < 8 { + break; + } + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; + let data = pos + 8; + let next = data.saturating_add(size).saturating_add(size & 1); + if &id == b"LIST" { + let mut kind = [0u8; 4]; + if size >= 4 && read_some(inner, &mut kind)? == 4 && &kind == b"strl" { + if let Some(stream) = parse_strl(inner, stream_no, data + 4, data + size)? { + streams.push(stream); + } + stream_no += 1; + } + } + pos = next; + } + Ok(streams) +} + +fn parse_strl( + inner: &mut R, + stream_no: u32, + start: u64, + end: u64, +) -> Result> { + let mut audio = false; + let mut fmt = None; + let mut pos = start; + while pos + 8 <= end { + inner.seek(SeekFrom::Start(pos))?; + let mut chunk = [0u8; 8]; + if read_some(inner, &mut chunk)? < 8 { + break; + } + let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; + let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; + let data = pos + 8; + let next = data.saturating_add(size).saturating_add(size & 1); + match &id { + b"strh" => { + let mut body = vec![0u8; size.min(64) as usize]; + read_full(inner, &mut body)?; + audio = body.get(0..4) == Some(&b"auds"[..]); + } + b"strf" => { + let mut body = vec![0u8; size.min(18) as usize]; + read_full(inner, &mut body)?; + if body.len() >= 16 { + fmt = Some(AviAudioStream { + index: stream_no, + format_tag: u16::from_le_bytes([body[0], body[1]]), + channels: u16::from_le_bytes([body[2], body[3]]), + sample_rate: u32::from_le_bytes([body[4], body[5], body[6], body[7]]), + block_align: u16::from_le_bytes([body[12], body[13]]), + bits_per_sample: u16::from_le_bytes([body[14], body[15]]), + }); + } + } + _ => {} + } + pos = next; + } + Ok(audio.then_some(fmt).flatten()) +} + +fn stream_number(id: &[u8; 4]) -> Option { + let a = id[0].checked_sub(b'0')?; + let b = id[1].checked_sub(b'0')?; + (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b)) +} + +fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result { + let mut at = 0; + while at < buf.len() { + match r.read(&mut buf[at..]) { + Ok(0) => break, + Ok(n) => at += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(Error::Io(e)), + } + } + Ok(at) +} + +fn read_full(r: &mut impl Read, buf: &mut [u8]) -> Result<()> { + if read_some(r, buf)? == buf.len() { + Ok(()) + } else { + Err(Error::corrupt("AVI header ends mid-field")) + } +} diff --git a/crates/ec-riff/src/lib.rs b/crates/ec-riff/src/lib.rs index 3f6f6cb7..46875a6a 100644 --- a/crates/ec-riff/src/lib.rs +++ b/crates/ec-riff/src/lib.rs @@ -1,4 +1,4 @@ -//! RIFF/WAVE: the container edith writes PCM into and reads PCM back from. +//! RIFF/WAVE and AVI audio chunk reading. //! //! [`WavWriter`] streams samples as they arrive and patches the RIFF, `data` //! and `fact` sizes in [`WavWriter::finalize`] — a dropped writer therefore @@ -16,8 +16,8 @@ //! declares. //! //! Not covered: RF64/BW64 (>4 GiB), ADPCM and other compressed WAVE tags, -//! 64-bit float. Each is [`Error::Unsupported`] naming itself, never a silent -//! misread. +//! 64-bit float, AVI video frames, and non-audio AVI chunks. Each unsupported +//! WAVE tag is [`Error::Unsupported`] naming itself, never a silent misread. //! //! The crate stands alone — [`WavSpec`] is its own type — but converts into the //! family IR on request: [`WavSpec::sample_format`] and [`WavSpec::layout`]. @@ -25,9 +25,11 @@ #![forbid(unsafe_code)] #![warn(missing_docs)] +mod avi; mod read; mod write; +pub use avi::{AviAudioStream, AviPacket, AviReader}; pub use ec_core::{Error, Result}; pub use read::WavReader; pub use write::{Sample, WavWriter}; diff --git a/crates/ec-riff/tests/wav.rs b/crates/ec-riff/tests/wav.rs index dd7bd9d0..e70cccdd 100644 --- a/crates/ec-riff/tests/wav.rs +++ b/crates/ec-riff/tests/wav.rs @@ -7,7 +7,7 @@ use std::io::Cursor; -use ec_riff::{SampleType, WavReader, WavSpec, WavWriter}; +use ec_riff::{AviReader, Error, SampleType, WavReader, WavSpec, WavWriter}; /// Deterministic samples in `bits`-bit range: a walking pattern that exercises /// both signs and the extremes of the depth. @@ -196,6 +196,68 @@ fn truncated_and_placeholder_sizes_read_what_is_there() { assert_eq!(r.read_all_i32().unwrap(), samples); } +#[test] +fn avi_truncated_tail_is_end_of_stream() { + fn chunk(out: &mut Vec, id: &[u8; 4], body: &[u8]) { + out.extend_from_slice(id); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(body); + if body.len() % 2 == 1 { + out.push(0); + } + } + + fn list(out: &mut Vec, kind: &[u8; 4], body: &[u8]) { + out.extend_from_slice(b"LIST"); + out.extend_from_slice(&((body.len() + 4) as u32).to_le_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(body); + if body.len() % 2 == 1 { + out.push(0); + } + } + + let mut strh = Vec::new(); + strh.extend_from_slice(b"auds"); + strh.extend_from_slice(&[0; 52]); + let mut strf = Vec::new(); + strf.extend_from_slice(&0x2000u16.to_le_bytes()); + strf.extend_from_slice(&2u16.to_le_bytes()); + strf.extend_from_slice(&48_000u32.to_le_bytes()); + strf.extend_from_slice(&0u32.to_le_bytes()); + strf.extend_from_slice(&0u16.to_le_bytes()); + strf.extend_from_slice(&0u16.to_le_bytes()); + let mut strl = Vec::new(); + chunk(&mut strl, b"strh", &strh); + chunk(&mut strl, b"strf", &strf); + let mut hdrl = Vec::new(); + list(&mut hdrl, b"strl", &strl); + + let mut movi = Vec::new(); + chunk(&mut movi, b"00wb", &[0x0b, 0x77, 0, 0]); + movi.extend_from_slice(b"00"); + + let mut body = Vec::new(); + list(&mut body, b"hdrl", &hdrl); + list(&mut body, b"movi", &movi); + let mut avi = Vec::new(); + avi.extend_from_slice(b"RIFF"); + avi.extend_from_slice(&((body.len() + 4) as u32).to_le_bytes()); + avi.extend_from_slice(b"AVI "); + avi.extend_from_slice(&body); + + let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens"); + assert_eq!(reader.audio_streams()[0].format_tag, 0x2000); + assert_eq!( + reader.next_packet().expect("first packet").data, + [0x0b, 0x77, 0, 0] + ); + let err = reader + .next_packet() + .expect_err("truncated tail ends the stream"); + assert!(matches!(err, Error::Eof)); +} + #[test] fn refusals_name_a_real_absence() { // Not RIFF at all.