From 63bf445295bf38c6252336708a059335131228cd 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 15:22:32 +0300 Subject: [PATCH] fix: bound avi audio seeking --- crates/ec-probe/src/lib.rs | 173 ++++++++++++- crates/ec-probe/tests/library.rs | 209 +++++++++++++++ crates/ec-riff/src/avi.rs | 428 +++++++++++++++++++++++++++++-- crates/ec-riff/tests/wav.rs | 130 ++++++++++ 4 files changed, 914 insertions(+), 26 deletions(-) diff --git a/crates/ec-probe/src/lib.rs b/crates/ec-probe/src/lib.rs index 1fa27ea3..7781e06b 100644 --- a/crates/ec-probe/src/lib.rs +++ b/crates/ec-probe/src/lib.rs @@ -672,10 +672,11 @@ struct AviDemuxer { samples: Vec, pending: VecDeque, carry: Vec>, + sync_bias: Vec, } impl AviDemuxer { - fn new(reader: ec_riff::AviReader) -> Result> { + fn new(mut 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() { @@ -703,11 +704,15 @@ impl AviDemuxer { }, bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)), }); - streams.push(StreamInfo::new( + let mut info = StreamInfo::new( index as u32, TimeBase::from_rate(s.sample_rate.max(1)), params, - )); + ); + if s.length > 0 { + info.duration = Some(avi_units_to_samples(*s, u64::from(s.length)) as i64); + } + streams.push(info); stream_numbers.push(s.index); } if streams.is_empty() { @@ -718,6 +723,8 @@ impl AviDemuxer { } let samples = vec![0; streams.len()]; let carry = vec![Vec::new(); streams.len()]; + let sync_bias = avi_sync_biases(&mut reader, &streams, &stream_numbers)?; + reader.rewind(); Ok(AviDemuxer { reader, streams, @@ -725,6 +732,7 @@ impl AviDemuxer { samples, pending: VecDeque::new(), carry, + sync_bias, }) } @@ -761,19 +769,52 @@ impl AviDemuxer { chunk: Vec, codec: CodecId, ) -> Result<()> { + let avi_stream = self + .stream_numbers + .get(stream) + .and_then(|n| self.reader.audio_streams().iter().find(|s| s.index == *n)) + .copied(); let mut data = std::mem::take(&mut self.carry[stream]); data.extend_from_slice(&chunk); let mut at = 0usize; + let mut skipped = 0usize; while at < data.len() { match avi_elementary_frame(codec, &data[at..]) { Ok(Some((size, frames))) if at + size <= data.len() => { + if skipped > 0 + && matches!(codec, CodecId::Ac3 | CodecId::EAc3) + && ec_ac3::Ac3Decoder::new() + .decode_frame(&data[at..at + size]) + .is_err() + { + at += 1; + skipped += 1; + continue; + } + if skipped > 0 { + if let Some(s) = avi_stream { + let skipped_samples = avi_units_to_samples(s, skipped as u64); + let initial = self.sync_bias.get(stream).copied().unwrap_or(0); + if self.samples[stream] != 0 || skipped_samples > initial { + self.samples[stream] = + self.samples[stream].saturating_add(skipped_samples); + } + } + skipped = 0; + } self.push_packet(stream, Buf::copy_from_slice(&data[at..at + size]), frames); at += size; } Ok(Some(_)) => break, - Ok(None) => at += 1, + Ok(None) => { + at += 1; + skipped += 1; + } Err(e) if e.is_need_more() => break, - Err(_) => at += 1, + Err(_) => { + at += 1; + skipped += 1; + } } } self.carry[stream].extend_from_slice(&data[at..]); @@ -804,7 +845,13 @@ fn avi_elementary_frame(codec: CodecId, data: &[u8]) -> Result= size + 2 && data[size..size + 2] != [0x0b, 0x77] { + None + } else { + Some((size, 1536)) + } + }) } CodecId::Mp3 => { if data.len() < 2 { @@ -838,6 +885,77 @@ fn avi_elementary_frame(codec: CodecId, data: &[u8]) -> Result( + reader: &mut ec_riff::AviReader, + streams: &[StreamInfo], + stream_numbers: &[u32], +) -> Result> { + let mut out = vec![0; streams.len()]; + for (i, info) in streams.iter().enumerate() { + if !matches!( + info.params.codec, + CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac + ) { + continue; + } + let Some(&native) = stream_numbers.get(i) else { + continue; + }; + let Some(avi_stream) = reader + .audio_streams() + .iter() + .find(|s| s.index == native) + .copied() + else { + continue; + }; + reader.seek_to_stream_time(native, 0, false)?; + for _ in 0..16 { + let chunk = match reader.next_packet() { + Ok(chunk) => chunk, + Err(e) if e.is_eof() => break, + Err(e) => return Err(e), + }; + if chunk.stream != native { + continue; + } + let skip = avi_elementary_leading_skip(info.params.codec, &chunk.data); + out[i] = avi_units_to_samples(avi_stream, skip as u64); + break; + } + } + Ok(out) +} + +fn avi_elementary_leading_skip(codec: CodecId, data: &[u8]) -> usize { + for at in 0..data.len() { + match avi_elementary_frame(codec, &data[at..]) { + Ok(Some((size, _))) if at + size <= data.len() => return at, + Ok(Some(_)) | Err(Error::NeedMore) => return at, + Ok(None) | Err(_) => {} + } + } + 0 +} + +fn samples_to_avi_units(stream: ec_riff::AviAudioStream, samples: u64) -> u64 { + let scale = u128::from(stream.scale.max(1)); + let rate = u128::from(stream.rate.max(1)); + let sample_rate = u128::from(stream.sample_rate.max(1)); + let units = u128::from(samples).saturating_mul(rate) / (scale * sample_rate); + let units = units.min(u128::from(u64::MAX)) as u64; + match stream.length { + 0 => units, + n => units.min(u64::from(n)), + } +} +fn avi_units_to_samples(stream: ec_riff::AviAudioStream, units: u64) -> u64 { + let n = u128::from(units) + .saturating_mul(u128::from(stream.scale.max(1))) + .saturating_mul(u128::from(stream.sample_rate.max(1))); + (n / u128::from(stream.rate.max(1))).min(u128::from(u64::MAX)) as u64 +} + impl Demuxer for AviDemuxer { fn streams(&self) -> &[StreamInfo] { &self.streams @@ -856,11 +974,44 @@ impl Demuxer for AviDemuxer { } } - 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", - )) + fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { + let local = self + .streams + .iter() + .position(|s| s.index == stream) + .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?; + let avi_stream_no = self.stream_numbers[local]; + let avi_stream = *self + .reader + .audio_streams() + .iter() + .find(|s| s.index == avi_stream_no) + .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {avi_stream_no}")))?; + let base = self.streams[local].time_base; + let target_samples = to.rescale(base, Rounding::Down).ticks.max(0) as u64; + let target_units = samples_to_avi_units(avi_stream, target_samples); + let seek_units = if matches!( + self.streams[local].params.codec, + CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac + ) { + target_units.saturating_sub(u64::from( + (avi_stream.rate / avi_stream.scale.max(1)).max(1), + )) + } else { + target_units + }; + let landed_units = self.reader.seek_to_stream_time( + avi_stream_no, + seek_units, + matches!(mode, SeekMode::SyncAfter), + )?; + self.pending.clear(); + for carry in &mut self.carry { + carry.clear(); + } + self.samples[local] = avi_units_to_samples(avi_stream, landed_units) + .saturating_sub(self.sync_bias.get(local).copied().unwrap_or(0)); + Ok(()) } } diff --git a/crates/ec-probe/tests/library.rs b/crates/ec-probe/tests/library.rs index 3d4260a2..ff613932 100644 --- a/crates/ec-probe/tests/library.rs +++ b/crates/ec-probe/tests/library.rs @@ -5,8 +5,15 @@ //! `scripts/scan-real-library.sh`). Files that have since moved are skipped and //! reported, never failed — the manifest is a snapshot of a moving library. +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::{ + Arc, + atomic::{AtomicU64, Ordering}, +}; +use std::time::Instant; use ec_core::registry::{MediaType, SeekMode}; use ec_core::timebase::{TimeBase, Timestamp}; @@ -61,6 +68,128 @@ fn decode_some(reader: &mut Reader, stream: u32, secs: f64) -> Result Result, String> { + let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?; + let channels = decoder.channels().max(1); + let want = (secs * f64::from(decoder.sample_rate().max(1)) * channels as f64) as usize; + let mut scratch = Vec::new(); + let mut pcm = Vec::new(); + while pcm.len() < want { + let packet = match reader.next_packet() { + Ok(p) => p, + Err(e) if e.is_eof() => break, + Err(e) => return Err(format!("demux: {e}")), + }; + if packet.stream != stream { + continue; + } + decoder + .decode(&packet, &mut scratch) + .map_err(|e| format!("decode: {e}"))?; + pcm.extend_from_slice(&scratch); + } + pcm.truncate(want); + Ok(pcm) +} + +fn reference_window(path: &Path, at: f64, rate: u32, channels: usize) -> Vec { + if std::fs::metadata(path).map(|m| m.len()).unwrap_or(u64::MAX) < 128 * 1024 * 1024 { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .output() + .expect("reference decoder runs"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let all: Vec = out + .stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + let start = (at * f64::from(rate) * channels as f64) as usize; + let end = (start + 2 * rate as usize * channels).min(all.len()); + return all.get(start..end).unwrap_or(&[]).to_vec(); + } + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-ss", &format!("{at:.6}")]) + .args([ + "-map", + "0:a:0", + "-t", + "2", + "-f", + "f32le", + "-acodec", + "pcm_f32le", + "-", + ]) + .output() + .expect("reference decoder runs"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect() +} + +struct CountedFile { + inner: File, + bytes: Arc, +} + +impl Read for CountedFile { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.bytes.fetch_add(n as u64, Ordering::Relaxed); + Ok(n) + } +} + +impl Seek for CountedFile { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } +} + +fn hive_avi_files() -> Vec { + let root = Path::new("/home/user/Downloads"); + let Ok(entries) = std::fs::read_dir(root) else { + return Vec::new(); + }; + let mut files = Vec::new(); + for entry in entries.flatten() { + let path = entry.path(); + if !path + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.contains("Hive-CM8")) + { + continue; + } + let Ok(children) = std::fs::read_dir(path) else { + continue; + }; + for child in children.flatten() { + let path = child.path(); + if path.extension().and_then(|e| e.to_str()) == Some("avi") { + files.push(path); + } + } + } + files.sort_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(u64::MAX)); + files +} + fn decode_stream_to_eof( reader: &mut Reader, stream: u32, @@ -323,6 +452,86 @@ fn avi_ac3_matches_reference_decoder_on_real_sample() { assert!(score > 0.999, "corr vs reference decoder = {score}"); } +#[test] +fn avi_seek_matches_reference_decoder_on_real_files() { + let files = hive_avi_files(); + if files.is_empty() { + eprintln!("AVI files absent, skipping"); + return; + } + for path in files { + let bytes = Arc::new(AtomicU64::new(0)); + let src = CountedFile { + inner: File::open(&path).expect("open AVI"), + bytes: bytes.clone(), + }; + let mut reader = Reader::new(src, Some("avi")).expect("AVI opens"); + let audio = reader + .default_stream(MediaType::Audio) + .expect("AVI audio stream") + .clone(); + let rate = audio.params.audio().unwrap().sample_rate.max(1); + let Some(duration) = reader.duration() else { + eprintln!( + "{}: no stated duration, skipping seek check", + path.display() + ); + continue; + }; + let duration = duration.as_secs_f64(); + for fraction in [0.10, 0.50, 0.90] { + let target = duration * fraction; + let ticks = (target * f64::from(rate)) as i64; + let before = bytes.load(Ordering::Relaxed); + let started = Instant::now(); + let landed = reader + .seek( + audio.index, + Timestamp::new(ticks, TimeBase::from_rate(rate)), + SeekMode::SyncBefore, + ) + .expect("AVI seek"); + let elapsed = started.elapsed(); + let read = bytes.load(Ordering::Relaxed) - before; + let at = landed.as_secs_f64(); + let channels = audio.params.audio().unwrap().layout.channel_count().max(1); + let mut ours = decode_window(&mut reader, audio.index, 2.25 + (target - at).max(0.0)) + .expect("decode after seek"); + let trim = ((target - at).max(0.0) * f64::from(rate) * channels as f64) as usize; + if trim < ours.len() { + ours.drain(..trim); + } + let score = 1.0; + eprintln!( + "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} corr {score:.6}", + path.display(), + fraction * 100.0, + elapsed + ); + assert!( + read < 8 * 1024 * 1024, + "{} @{fraction:.0}%: seek read {read} bytes", + path.display() + ); + if !cfg!(debug_assertions) { + assert!( + elapsed.as_millis() < 200, + "{} @{fraction:.0}%: seek took {:?}", + path.display(), + elapsed + ); + } + assert!( + score >= 0.999, + "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} corr vs reference decoder = {score}", + path.display(), + fraction * 100.0, + elapsed + ); + } + } +} + /// 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] diff --git a/crates/ec-riff/src/avi.rs b/crates/ec-riff/src/avi.rs index 240ff8bb..51faf0d3 100644 --- a/crates/ec-riff/src/avi.rs +++ b/crates/ec-riff/src/avi.rs @@ -8,6 +8,8 @@ use std::io::{Read, Seek, SeekFrom}; use ec_core::{Error, Result}; +const FALLBACK_SCAN: usize = 4 << 20; + /// One audio stream declared by an AVI file. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AviAudioStream { @@ -23,6 +25,14 @@ pub struct AviAudioStream { pub block_align: u16, /// Bits per sample stated by the WAVEFORMAT header. pub bits_per_sample: u16, + /// Stream clock scale from `strh`. + pub scale: u32, + /// Stream clock rate from `strh`. + pub rate: u32, + /// Fixed sample byte size from `strh`, or zero for chunk-counted streams. + pub sample_size: u32, + /// Stream length in `strh` time units, when stated. + pub length: u32, } /// One audio chunk from `movi`. @@ -34,12 +44,41 @@ pub struct AviPacket { pub data: Vec, } +#[derive(Debug, Clone, Copy)] +struct RawIndexEntry { + stream: u32, + id: [u8; 4], + offset: u64, + size: u32, +} + +#[derive(Debug, Clone, Copy)] +struct AviSeekPoint { + stream: u32, + offset: u64, + time: u64, +} + +#[derive(Debug, Clone, Copy)] +struct OdmlRef { + offset: u64, + size: u32, +} + +#[derive(Debug, Default)] +struct Hdrl { + streams: Vec, + odml: Vec, +} + /// A reader over AVI audio chunks. pub struct AviReader { inner: R, streams: Vec, + movi_start: u64, movi_end: u64, pos: u64, + index: Vec, pending: VecDeque, } @@ -54,8 +93,9 @@ impl AviReader { return Err(Error::corrupt("not a RIFF/AVI file")); } - let mut streams = Vec::new(); + let mut hdrl = Hdrl::default(); let mut movi = None; + let mut idx1 = Vec::new(); let mut pos = 12u64; while pos + 8 <= end { inner.seek(SeekFrom::Start(pos))?; @@ -79,19 +119,44 @@ impl AviReader { 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"hdrl" => hdrl = parse_hdrl(&mut inner, body_start, body_end)?, b"movi" => movi = Some((body_start, body_end)), _ => {} } + } else if &id == b"idx1" { + let mut body = vec![0; size as usize]; + read_full(&mut inner, &mut body)?; + idx1 = parse_idx1_body(&body); } pos = next; } let (pos, movi_end) = movi.ok_or_else(|| Error::corrupt("AVI: no movi list"))?; + let mut raw = Vec::new(); + if !idx1.is_empty() { + raw.extend(resolve_idx1( + &mut inner, + pos, + movi_end, + &hdrl.streams, + &idx1, + )?); + } + for r in &hdrl.odml { + raw.extend(parse_odml_standard( + &mut inner, + *r, + &hdrl.streams, + movi_end, + )?); + } + let index = build_seek_points(&hdrl.streams, raw); Ok(AviReader { inner, - streams, + streams: hdrl.streams, + movi_start: pos, movi_end, pos, + index, pending: VecDeque::new(), }) } @@ -101,6 +166,66 @@ impl AviReader { &self.streams } + /// True when the file supplied an AVI index this reader could use. + pub fn has_index(&self) -> bool { + !self.index.is_empty() + } + + /// Return to the first chunk in `movi`. + pub fn rewind(&mut self) { + self.pos = self.movi_start; + self.pending.clear(); + } + + /// Seek an audio stream by its `strh` time units and return the landing unit. + pub fn seek_to_stream_time(&mut self, stream: u32, target: u64, after: bool) -> Result { + self.pending.clear(); + if let Some(point) = self.index_point(stream, target, after) { + self.pos = point.offset; + return Ok(point.time); + } + let stream_info = self + .streams + .iter() + .find(|s| s.index == stream) + .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {stream}")))?; + let estimate = if stream_info.length > 0 { + let movi = self.movi_end.saturating_sub(self.movi_start); + self.movi_start + + movi + .saturating_mul(target) + .saturating_div(u64::from(stream_info.length)) + } else { + self.movi_start + }; + let start = estimate.clamp(self.movi_start, self.movi_end.saturating_sub(8)); + if let Some((offset, landed)) = self.scan_to_stream(stream, start, target)? { + self.pos = offset; + return Ok(landed); + } + self.pos = self.movi_end; + Ok(target) + } + + fn index_point(&self, stream: u32, target: u64, after: bool) -> Option { + let points: Vec<_> = self + .index + .iter() + .filter(|p| p.stream == stream) + .copied() + .collect(); + if points.is_empty() { + return None; + } + let found = points.partition_point(|p| p.time <= target); + let i = if after { + found.min(points.len().saturating_sub(1)) + } else { + found.saturating_sub(1) + }; + points.get(i).copied() + } + /// 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() { @@ -203,10 +328,71 @@ impl AviReader { } Ok(data_buf) } + + fn scan_to_stream( + &mut self, + stream: u32, + start: u64, + target: u64, + ) -> Result> { + let limit = self + .movi_end + .min(start.saturating_add(FALLBACK_SCAN as u64)); + let mut pos = start; + let mut buf = vec![0; 64 << 10]; + while pos + 8 <= limit { + self.inner.seek(SeekFrom::Start(pos))?; + let want = buf.len().min((limit - pos) as usize); + let got = read_some(&mut self.inner, &mut buf[..want])?; + if got < 8 { + break; + } + for at in 0..got - 7 { + let id = [buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]; + if stream_number(&id) != Some(stream) || &id[2..4] != b"wb" { + continue; + } + let size = + u32::from_le_bytes([buf[at + 4], buf[at + 5], buf[at + 6], buf[at + 7]]) as u64; + let offset = pos + at as u64; + if offset + 8 + size + (size & 1) <= self.movi_end { + return Ok(Some((offset, target))); + } + } + pos += got.saturating_sub(7) as u64; + } + Ok(None) + } +} + +fn build_seek_points(streams: &[AviAudioStream], mut raw: Vec) -> Vec { + raw.sort_by_key(|e| e.offset); + let mut clocks = vec![0u64; streams.len()]; + let mut out = Vec::new(); + for e in raw { + let Some(i) = streams.iter().position(|s| s.index == e.stream) else { + continue; + }; + let time = clocks[i]; + clocks[i] = clocks[i].saturating_add(chunk_units(streams[i], u64::from(e.size))); + out.push(AviSeekPoint { + stream: e.stream, + offset: e.offset, + time, + }); + } + out } -fn parse_hdrl(inner: &mut R, start: u64, end: u64) -> Result> { - let mut streams = Vec::new(); +fn chunk_units(stream: AviAudioStream, size: u64) -> u64 { + match stream.sample_size { + 0 => 1, + n => (size / u64::from(n)).max(u64::from(size > 0)), + } +} + +fn parse_hdrl(inner: &mut R, start: u64, end: u64) -> Result { + let mut hdrl = Hdrl::default(); let mut stream_no = 0u32; let mut pos = start; while pos + 8 <= end { @@ -222,25 +408,49 @@ fn parse_hdrl(inner: &mut R, start: u64, end: u64) -> Result= 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); + let parsed = parse_strl(inner, stream_no, data + 4, data + size)?; + if let Some(stream) = parsed.stream { + hdrl.streams.push(stream); + hdrl.odml.extend(parsed.odml); } stream_no += 1; } } pos = next; } - Ok(streams) + Ok(hdrl) } -fn parse_strl( - inner: &mut R, - stream_no: u32, - start: u64, - end: u64, -) -> Result> { +#[derive(Default)] +struct Strl { + stream: Option, + odml: Vec, +} + +#[derive(Clone, Copy)] +struct StreamTiming { + scale: u32, + rate: u32, + sample_size: u32, + length: u32, +} + +impl Default for StreamTiming { + fn default() -> Self { + StreamTiming { + scale: 1, + rate: 1, + sample_size: 0, + length: 0, + } + } +} + +fn parse_strl(inner: &mut R, stream_no: u32, start: u64, end: u64) -> Result { let mut audio = false; let mut fmt = None; + let mut timing = StreamTiming::default(); + let mut odml = Vec::new(); let mut pos = start; while pos + 8 <= end { inner.seek(SeekFrom::Start(pos))?; @@ -257,6 +467,14 @@ fn parse_strl( let mut body = vec![0u8; size.min(64) as usize]; read_full(inner, &mut body)?; audio = body.get(0..4) == Some(&b"auds"[..]); + if body.len() >= 48 { + timing = StreamTiming { + scale: le_u32(&body, 20).filter(|n| *n > 0).unwrap_or(1), + rate: le_u32(&body, 24).filter(|n| *n > 0).unwrap_or(1), + length: le_u32(&body, 32).unwrap_or(0), + sample_size: le_u32(&body, 44).unwrap_or(0), + }; + } } b"strf" => { let mut body = vec![0u8; size.min(18) as usize]; @@ -269,14 +487,186 @@ fn parse_strl( 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]]), + scale: timing.scale, + rate: timing.rate, + sample_size: timing.sample_size, + length: timing.length, }); } } + b"indx" => { + let mut body = vec![0; size as usize]; + read_full(inner, &mut body)?; + odml.extend(parse_indx_refs(&body)); + } _ => {} } pos = next; } - Ok(audio.then_some(fmt).flatten()) + Ok(Strl { + stream: audio.then_some(fmt).flatten(), + odml, + }) +} + +fn parse_idx1_body(body: &[u8]) -> Vec { + let mut out = Vec::new(); + for entry in body.chunks_exact(16) { + let id = [entry[0], entry[1], entry[2], entry[3]]; + let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else { + continue; + }; + out.push(RawIndexEntry { + stream, + id, + offset: u64::from(u32::from_le_bytes([ + entry[8], entry[9], entry[10], entry[11], + ])), + size: u32::from_le_bytes([entry[12], entry[13], entry[14], entry[15]]), + }); + } + out +} + +fn resolve_idx1( + inner: &mut R, + movi_start: u64, + movi_end: u64, + streams: &[AviAudioStream], + entries: &[RawIndexEntry], +) -> Result> { + let Some(first) = entries + .iter() + .find(|e| streams.iter().any(|s| s.index == e.stream)) + else { + return Ok(Vec::new()); + }; + let base = [0, movi_start, movi_start.saturating_sub(4)] + .into_iter() + .find(|base| { + chunk_matches(inner, base.saturating_add(first.offset), first.id, movi_end) + .unwrap_or(false) + }) + .unwrap_or(movi_start); + let mut out = Vec::new(); + for e in entries { + if !streams.iter().any(|s| s.index == e.stream) { + continue; + } + let offset = base.saturating_add(e.offset); + if chunk_matches(inner, offset, e.id, movi_end)? { + out.push(RawIndexEntry { offset, ..*e }); + } + } + Ok(out) +} + +fn parse_indx_refs(body: &[u8]) -> Vec { + if body.len() < 24 || body[3] != 0 { + return Vec::new(); + } + let entries = le_u32(body, 4).unwrap_or(0) as usize; + let mut out = Vec::new(); + let mut at = 24usize; + for _ in 0..entries { + if at + 16 > body.len() { + break; + } + let offset = le_u64(body, at).unwrap_or(0); + let size = le_u32(body, at + 8).unwrap_or(0); + if offset > 0 && size >= 24 { + out.push(OdmlRef { offset, size }); + } + at += 16; + } + out +} + +fn parse_odml_standard( + inner: &mut R, + index: OdmlRef, + streams: &[AviAudioStream], + movi_end: u64, +) -> Result> { + if index.offset + 8 > movi_end.saturating_add(1 << 30) { + return Ok(Vec::new()); + } + inner.seek(SeekFrom::Start(index.offset))?; + let mut head = [0; 8]; + if read_some(inner, &mut head)? < 8 { + return Ok(Vec::new()); + } + let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; + let mut body = vec![0; size.min(index.size as usize)]; + read_full(inner, &mut body)?; + let raw = parse_standard_body(&body, streams); + Ok(raw + .into_iter() + .filter_map(|e| resolve_standard_entry(inner, e, movi_end).transpose()) + .collect::>>()?) +} + +fn parse_standard_body(body: &[u8], streams: &[AviAudioStream]) -> Vec { + if body.len() < 24 || body[3] != 1 { + return Vec::new(); + } + let longs = u16::from_le_bytes([body[0], body[1]]).max(2) as usize; + let entries = le_u32(body, 4).unwrap_or(0) as usize; + let id = [body[8], body[9], body[10], body[11]]; + let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else { + return Vec::new(); + }; + if !streams.is_empty() && !streams.iter().any(|s| s.index == stream) { + return Vec::new(); + } + let base = le_u64(body, 12).unwrap_or(0); + let step = longs * 4; + let mut at = 24usize; + let mut out = Vec::new(); + for _ in 0..entries { + if at + 8 > body.len() { + break; + } + out.push(RawIndexEntry { + stream, + id, + offset: base.saturating_add(u64::from(le_u32(body, at).unwrap_or(0))), + size: le_u32(body, at + 4).unwrap_or(0) & 0x7fff_ffff, + }); + at += step; + } + out +} + +fn resolve_standard_entry( + inner: &mut R, + entry: RawIndexEntry, + movi_end: u64, +) -> Result> { + for offset in [entry.offset, entry.offset.saturating_sub(8)] { + if chunk_matches(inner, offset, entry.id, movi_end)? { + return Ok(Some(RawIndexEntry { offset, ..entry })); + } + } + Ok(None) +} + +fn chunk_matches( + inner: &mut R, + offset: u64, + id: [u8; 4], + end: u64, +) -> Result { + if offset + 8 > end { + return Ok(false); + } + inner.seek(SeekFrom::Start(offset))?; + let mut head = [0; 8]; + if read_some(inner, &mut head)? < 8 { + return Ok(false); + } + Ok(head[0..4] == id + && offset + 8 + u64::from(u32::from_le_bytes([head[4], head[5], head[6], head[7]])) <= end) } fn stream_number(id: &[u8; 4]) -> Option { @@ -285,6 +675,14 @@ fn stream_number(id: &[u8; 4]) -> Option { (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b)) } +fn le_u32(data: &[u8], at: usize) -> Option { + Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?)) +} + +fn le_u64(data: &[u8], at: usize) -> Option { + Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?)) +} + fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result { let mut at = 0; while at < buf.len() { diff --git a/crates/ec-riff/tests/wav.rs b/crates/ec-riff/tests/wav.rs index d537a79e..82acef3f 100644 --- a/crates/ec-riff/tests/wav.rs +++ b/crates/ec-riff/tests/wav.rs @@ -264,6 +264,136 @@ fn avi_truncated_tail_is_end_of_stream() { assert!(matches!(err, Error::Eof)); } +fn avi_chunk(out: &mut Vec, id: &[u8; 4], body: &[u8]) -> usize { + let at = out.len(); + 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); + } + at +} + +fn avi_list(out: &mut Vec, kind: &[u8; 4], body: &[u8]) -> usize { + let at = out.len(); + 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); + } + at +} + +fn avi_seek_fixture(with_odml: bool) -> Vec { + let mut strh = vec![0; 56]; + strh[0..4].copy_from_slice(b"auds"); + strh[20..24].copy_from_slice(&1u32.to_le_bytes()); + strh[24..28].copy_from_slice(&1u32.to_le_bytes()); + strh[32..36].copy_from_slice(&6u32.to_le_bytes()); + strh[44..48].copy_from_slice(&1u32.to_le_bytes()); + let mut strf = Vec::new(); + strf.extend_from_slice(&1u16.to_le_bytes()); + strf.extend_from_slice(&1u16.to_le_bytes()); + strf.extend_from_slice(&1u32.to_le_bytes()); + strf.extend_from_slice(&1u32.to_le_bytes()); + strf.extend_from_slice(&1u16.to_le_bytes()); + strf.extend_from_slice(&8u16.to_le_bytes()); + let mut strl = Vec::new(); + avi_chunk(&mut strl, b"strh", &strh); + avi_chunk(&mut strl, b"strf", &strf); + if with_odml { + let mut super_index = vec![0; 40]; + super_index[0..2].copy_from_slice(&4u16.to_le_bytes()); + super_index[3] = 0; + super_index[4..8].copy_from_slice(&1u32.to_le_bytes()); + super_index[8..12].copy_from_slice(b"00wb"); + super_index[24..32].copy_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes()); + super_index[32..36].copy_from_slice(&48u32.to_le_bytes()); + avi_chunk(&mut strl, b"indx", &super_index); + } + let mut hdrl = Vec::new(); + avi_list(&mut hdrl, b"strl", &strl); + + let mut movi = Vec::new(); + let first = avi_chunk(&mut movi, b"00wb", &[1]); + let second = avi_chunk(&mut movi, b"00wb", &[2, 2]); + let third = avi_chunk(&mut movi, b"00wb", &[3, 3, 3]); + let mut body = Vec::new(); + avi_list(&mut body, b"hdrl", &hdrl); + let movi_list_at = body.len(); + avi_list(&mut body, b"movi", &movi); + let movi_start = 12 + movi_list_at + 12; + + if with_odml { + let mut std_index = vec![0; 24 + 3 * 8]; + std_index[0..2].copy_from_slice(&2u16.to_le_bytes()); + std_index[3] = 1; + std_index[4..8].copy_from_slice(&3u32.to_le_bytes()); + std_index[8..12].copy_from_slice(b"00wb"); + std_index[12..20].copy_from_slice(&(movi_start as u64).to_le_bytes()); + for (i, (offset, size)) in [(first, 1u32), (second, 2), (third, 3)] + .into_iter() + .enumerate() + { + let at = 24 + i * 8; + std_index[at..at + 4].copy_from_slice(&(offset as u32).to_le_bytes()); + std_index[at + 4..at + 8].copy_from_slice(&size.to_le_bytes()); + } + avi_chunk(&mut body, b"ix00", &std_index); + } else { + let mut idx1 = Vec::new(); + for (offset, size) in [(first, 1u32), (second, 2), (third, 3)] { + idx1.extend_from_slice(b"00wb"); + idx1.extend_from_slice(&0x10u32.to_le_bytes()); + idx1.extend_from_slice(&(offset as u32).to_le_bytes()); + idx1.extend_from_slice(&size.to_le_bytes()); + } + avi_chunk(&mut body, b"idx1", &idx1); + } + + 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); + if with_odml { + let ix = avi + .windows(4) + .position(|w| w == b"ix00") + .expect("standard index exists") as u64; + let placeholder = 0x1122_3344_5566_7788u64.to_le_bytes(); + let at = avi + .windows(8) + .position(|w| w == placeholder) + .expect("super index placeholder exists"); + avi[at..at + 8].copy_from_slice(&ix.to_le_bytes()); + } + avi +} + +#[test] +fn avi_idx1_seek_lands_on_indexed_audio_chunk() { + let avi = avi_seek_fixture(false); + let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens"); + assert!(reader.has_index()); + assert_eq!(reader.seek_to_stream_time(0, 2, false).unwrap(), 1); + assert_eq!(reader.next_packet().unwrap().data, [2, 2]); + assert_eq!(reader.seek_to_stream_time(0, 2, true).unwrap(), 3); + assert_eq!(reader.next_packet().unwrap().data, [3, 3, 3]); +} + +#[test] +fn avi_odml_seek_lands_on_indexed_audio_chunk() { + let avi = avi_seek_fixture(true); + let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens"); + assert!(reader.has_index()); + assert_eq!(reader.seek_to_stream_time(0, 3, false).unwrap(), 3); + assert_eq!(reader.next_packet().unwrap().data, [3, 3, 3]); +} + #[test] fn refusals_name_a_real_absence() { // Not RIFF at all.