forge
Explore
Log in

Don't you dare go Hollow

Bound avi audio seeking

Browse files at this commit

63bf445295bf38c6252336708a059335131228cdAhmet Kaan GümüşParent: a8db269
  • fix
    • bound avi audio seeking
Show full message
fix: bound avi audio seeking
crates/ec-probe/src/lib.rsmodified+162 -11
@@ -672,10 +672,11 @@ struct AviDemuxer<R> {
672 samples: Vec<u64>,672 samples: Vec<u64>,
673 pending: VecDeque<Packet>,673 pending: VecDeque<Packet>,
674 carry: Vec<Vec<u8>>,674 carry: Vec<Vec<u8>>,
675+ sync_bias: Vec<u64>,
675 }676 }
676 677
677 impl<R: Read + Seek> AviDemuxer<R> {678 impl<R: Read + Seek> AviDemuxer<R> {
678- fn new(reader: ec_riff::AviReader<R>) -> Result<AviDemuxer<R>> {679+ fn new(mut reader: ec_riff::AviReader<R>) -> Result<AviDemuxer<R>> {
679 let mut streams = Vec::new();680 let mut streams = Vec::new();
680 let mut stream_numbers = Vec::new();681 let mut stream_numbers = Vec::new();
681 for (index, s) in reader.audio_streams().iter().enumerate() {682 for (index, s) in reader.audio_streams().iter().enumerate() {
@@ -703,11 +704,15 @@ impl<R: Read + Seek> AviDemuxer<R> {
703 },704 },
704 bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)),705 bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)),
705 });706 });
706- streams.push(StreamInfo::new(707+ let mut info = StreamInfo::new(
707 index as u32,708 index as u32,
708 TimeBase::from_rate(s.sample_rate.max(1)),709 TimeBase::from_rate(s.sample_rate.max(1)),
709 params,710 params,
710- ));711+ );
712+ if s.length > 0 {
713+ info.duration = Some(avi_units_to_samples(*s, u64::from(s.length)) as i64);
714+ }
715+ streams.push(info);
711 stream_numbers.push(s.index);716 stream_numbers.push(s.index);
712 }717 }
713 if streams.is_empty() {718 if streams.is_empty() {
@@ -718,6 +723,8 @@ impl<R: Read + Seek> AviDemuxer<R> {
718 }723 }
719 let samples = vec![0; streams.len()];724 let samples = vec![0; streams.len()];
720 let carry = vec![Vec::new(); streams.len()];725 let carry = vec![Vec::new(); streams.len()];
726+ let sync_bias = avi_sync_biases(&mut reader, &streams, &stream_numbers)?;
727+ reader.rewind();
721 Ok(AviDemuxer {728 Ok(AviDemuxer {
722 reader,729 reader,
723 streams,730 streams,
@@ -725,6 +732,7 @@ impl<R: Read + Seek> AviDemuxer<R> {
725 samples,732 samples,
726 pending: VecDeque::new(),733 pending: VecDeque::new(),
727 carry,734 carry,
735+ sync_bias,
728 })736 })
729 }737 }
730 738
@@ -761,19 +769,52 @@ impl<R: Read + Seek> AviDemuxer<R> {
761 chunk: Vec<u8>,769 chunk: Vec<u8>,
762 codec: CodecId,770 codec: CodecId,
763 ) -> Result<()> {771 ) -> Result<()> {
772+ let avi_stream = self
773+ .stream_numbers
774+ .get(stream)
775+ .and_then(|n| self.reader.audio_streams().iter().find(|s| s.index == *n))
776+ .copied();
764 let mut data = std::mem::take(&mut self.carry[stream]);777 let mut data = std::mem::take(&mut self.carry[stream]);
765 data.extend_from_slice(&chunk);778 data.extend_from_slice(&chunk);
766 let mut at = 0usize;779 let mut at = 0usize;
780+ let mut skipped = 0usize;
767 while at < data.len() {781 while at < data.len() {
768 match avi_elementary_frame(codec, &data[at..]) {782 match avi_elementary_frame(codec, &data[at..]) {
769 Ok(Some((size, frames))) if at + size <= data.len() => {783 Ok(Some((size, frames))) if at + size <= data.len() => {
784+ if skipped > 0
785+ && matches!(codec, CodecId::Ac3 | CodecId::EAc3)
786+ && ec_ac3::Ac3Decoder::new()
787+ .decode_frame(&data[at..at + size])
788+ .is_err()
789+ {
790+ at += 1;
791+ skipped += 1;
792+ continue;
793+ }
794+ if skipped > 0 {
795+ if let Some(s) = avi_stream {
796+ let skipped_samples = avi_units_to_samples(s, skipped as u64);
797+ let initial = self.sync_bias.get(stream).copied().unwrap_or(0);
798+ if self.samples[stream] != 0 || skipped_samples > initial {
799+ self.samples[stream] =
800+ self.samples[stream].saturating_add(skipped_samples);
801+ }
802+ }
803+ skipped = 0;
804+ }
770 self.push_packet(stream, Buf::copy_from_slice(&data[at..at + size]), frames);805 self.push_packet(stream, Buf::copy_from_slice(&data[at..at + size]), frames);
771 at += size;806 at += size;
772 }807 }
773 Ok(Some(_)) => break,808 Ok(Some(_)) => break,
774- Ok(None) => at += 1,809+ Ok(None) => {
810+ at += 1;
811+ skipped += 1;
812+ }
775 Err(e) if e.is_need_more() => break,813 Err(e) if e.is_need_more() => break,
776- Err(_) => at += 1,814+ Err(_) => {
815+ at += 1;
816+ skipped += 1;
817+ }
777 }818 }
778 }819 }
779 self.carry[stream].extend_from_slice(&data[at..]);820 self.carry[stream].extend_from_slice(&data[at..]);
@@ -804,7 +845,13 @@ fn avi_elementary_frame(codec: CodecId, data: &[u8]) -> Result<Option<(usize, u6
804 if data[0] != 0x0b || data[1] != 0x77 {845 if data[0] != 0x0b || data[1] != 0x77 {
805 return Ok(None);846 return Ok(None);
806 }847 }
807- ec_ac3::frame_size(data).map(|size| Some((size, 1536)))848+ ec_ac3::frame_size(data).map(|size| {
849+ if data.len() >= size + 2 && data[size..size + 2] != [0x0b, 0x77] {
850+ None
851+ } else {
852+ Some((size, 1536))
853+ }
854+ })
808 }855 }
809 CodecId::Mp3 => {856 CodecId::Mp3 => {
810 if data.len() < 2 {857 if data.len() < 2 {
@@ -838,6 +885,77 @@ fn avi_elementary_frame(codec: CodecId, data: &[u8]) -> Result<Option<(usize, u6
838 }885 }
839 }886 }
840 887
888+fn avi_sync_biases<R: Read + Seek>(
889+ reader: &mut ec_riff::AviReader<R>,
890+ streams: &[StreamInfo],
891+ stream_numbers: &[u32],
892+) -> Result<Vec<u64>> {
893+ let mut out = vec![0; streams.len()];
894+ for (i, info) in streams.iter().enumerate() {
895+ if !matches!(
896+ info.params.codec,
897+ CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac
898+ ) {
899+ continue;
900+ }
901+ let Some(&native) = stream_numbers.get(i) else {
902+ continue;
903+ };
904+ let Some(avi_stream) = reader
905+ .audio_streams()
906+ .iter()
907+ .find(|s| s.index == native)
908+ .copied()
909+ else {
910+ continue;
911+ };
912+ reader.seek_to_stream_time(native, 0, false)?;
913+ for _ in 0..16 {
914+ let chunk = match reader.next_packet() {
915+ Ok(chunk) => chunk,
916+ Err(e) if e.is_eof() => break,
917+ Err(e) => return Err(e),
918+ };
919+ if chunk.stream != native {
920+ continue;
921+ }
922+ let skip = avi_elementary_leading_skip(info.params.codec, &chunk.data);
923+ out[i] = avi_units_to_samples(avi_stream, skip as u64);
924+ break;
925+ }
926+ }
927+ Ok(out)
928+}
929+
930+fn avi_elementary_leading_skip(codec: CodecId, data: &[u8]) -> usize {
931+ for at in 0..data.len() {
932+ match avi_elementary_frame(codec, &data[at..]) {
933+ Ok(Some((size, _))) if at + size <= data.len() => return at,
934+ Ok(Some(_)) | Err(Error::NeedMore) => return at,
935+ Ok(None) | Err(_) => {}
936+ }
937+ }
938+ 0
939+}
940+
941+fn samples_to_avi_units(stream: ec_riff::AviAudioStream, samples: u64) -> u64 {
942+ let scale = u128::from(stream.scale.max(1));
943+ let rate = u128::from(stream.rate.max(1));
944+ let sample_rate = u128::from(stream.sample_rate.max(1));
945+ let units = u128::from(samples).saturating_mul(rate) / (scale * sample_rate);
946+ let units = units.min(u128::from(u64::MAX)) as u64;
947+ match stream.length {
948+ 0 => units,
949+ n => units.min(u64::from(n)),
950+ }
951+}
952+fn avi_units_to_samples(stream: ec_riff::AviAudioStream, units: u64) -> u64 {
953+ let n = u128::from(units)
954+ .saturating_mul(u128::from(stream.scale.max(1)))
955+ .saturating_mul(u128::from(stream.sample_rate.max(1)));
956+ (n / u128::from(stream.rate.max(1))).min(u128::from(u64::MAX)) as u64
957+}
958+
841 impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> {959 impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> {
842 fn streams(&self) -> &[StreamInfo] {960 fn streams(&self) -> &[StreamInfo] {
843 &self.streams961 &self.streams
@@ -856,11 +974,44 @@ impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> {
856 }974 }
857 }975 }
858 976
859- fn seek(&mut self, _stream: u32, _to: Timestamp, _mode: SeekMode) -> Result<()> {977+ fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
860- Err(Error::unsupported(978+ let local = self
861- "AVI audio seek",979+ .streams
862- "this reader only walks AVI sound chunks in storage order",980+ .iter()
863- ))981+ .position(|s| s.index == stream)
982+ .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?;
983+ let avi_stream_no = self.stream_numbers[local];
984+ let avi_stream = *self
985+ .reader
986+ .audio_streams()
987+ .iter()
988+ .find(|s| s.index == avi_stream_no)
989+ .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {avi_stream_no}")))?;
990+ let base = self.streams[local].time_base;
991+ let target_samples = to.rescale(base, Rounding::Down).ticks.max(0) as u64;
992+ let target_units = samples_to_avi_units(avi_stream, target_samples);
993+ let seek_units = if matches!(
994+ self.streams[local].params.codec,
995+ CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac
996+ ) {
997+ target_units.saturating_sub(u64::from(
998+ (avi_stream.rate / avi_stream.scale.max(1)).max(1),
999+ ))
1000+ } else {
1001+ target_units
1002+ };
1003+ let landed_units = self.reader.seek_to_stream_time(
1004+ avi_stream_no,
1005+ seek_units,
1006+ matches!(mode, SeekMode::SyncAfter),
1007+ )?;
1008+ self.pending.clear();
1009+ for carry in &mut self.carry {
1010+ carry.clear();
1011+ }
1012+ self.samples[local] = avi_units_to_samples(avi_stream, landed_units)
1013+ .saturating_sub(self.sync_bias.get(local).copied().unwrap_or(0));
1014+ Ok(())
864 }1015 }
865 }1016 }
866 1017
crates/ec-probe/tests/library.rsmodified+209 -0
@@ -5,8 +5,15 @@
5 //! `scripts/scan-real-library.sh`). Files that have since moved are skipped and5 //! `scripts/scan-real-library.sh`). Files that have since moved are skipped and
6 //! reported, never failed — the manifest is a snapshot of a moving library.6 //! reported, never failed — the manifest is a snapshot of a moving library.
7 7
8+use std::fs::File;
9+use std::io::{Read, Seek, SeekFrom};
8 use std::path::{Path, PathBuf};10 use std::path::{Path, PathBuf};
9 use std::process::Command;11 use std::process::Command;
12+use std::sync::{
13+ Arc,
14+ atomic::{AtomicU64, Ordering},
15+};
16+use std::time::Instant;
10 17
11 use ec_core::registry::{MediaType, SeekMode};18 use ec_core::registry::{MediaType, SeekMode};
12 use ec_core::timebase::{TimeBase, Timestamp};19 use ec_core::timebase::{TimeBase, Timestamp};
@@ -61,6 +68,128 @@ fn decode_some(reader: &mut Reader, stream: u32, secs: f64) -> Result<u64, Strin
61 Ok(frames)68 Ok(frames)
62 }69 }
63 70
71+fn decode_window(reader: &mut Reader, stream: u32, secs: f64) -> Result<Vec<f32>, String> {
72+ let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;
73+ let channels = decoder.channels().max(1);
74+ let want = (secs * f64::from(decoder.sample_rate().max(1)) * channels as f64) as usize;
75+ let mut scratch = Vec::new();
76+ let mut pcm = Vec::new();
77+ while pcm.len() < want {
78+ let packet = match reader.next_packet() {
79+ Ok(p) => p,
80+ Err(e) if e.is_eof() => break,
81+ Err(e) => return Err(format!("demux: {e}")),
82+ };
83+ if packet.stream != stream {
84+ continue;
85+ }
86+ decoder
87+ .decode(&packet, &mut scratch)
88+ .map_err(|e| format!("decode: {e}"))?;
89+ pcm.extend_from_slice(&scratch);
90+ }
91+ pcm.truncate(want);
92+ Ok(pcm)
93+}
94+
95+fn reference_window(path: &Path, at: f64, rate: u32, channels: usize) -> Vec<f32> {
96+ if std::fs::metadata(path).map(|m| m.len()).unwrap_or(u64::MAX) < 128 * 1024 * 1024 {
97+ let out = Command::new("ffmpeg")
98+ .args(["-v", "error", "-i"])
99+ .arg(path)
100+ .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
101+ .output()
102+ .expect("reference decoder runs");
103+ assert!(
104+ out.status.success(),
105+ "{}",
106+ String::from_utf8_lossy(&out.stderr)
107+ );
108+ let all: Vec<f32> = out
109+ .stdout
110+ .chunks_exact(4)
111+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
112+ .collect();
113+ let start = (at * f64::from(rate) * channels as f64) as usize;
114+ let end = (start + 2 * rate as usize * channels).min(all.len());
115+ return all.get(start..end).unwrap_or(&[]).to_vec();
116+ }
117+ let out = Command::new("ffmpeg")
118+ .args(["-v", "error", "-i"])
119+ .arg(path)
120+ .args(["-ss", &format!("{at:.6}")])
121+ .args([
122+ "-map",
123+ "0:a:0",
124+ "-t",
125+ "2",
126+ "-f",
127+ "f32le",
128+ "-acodec",
129+ "pcm_f32le",
130+ "-",
131+ ])
132+ .output()
133+ .expect("reference decoder runs");
134+ assert!(
135+ out.status.success(),
136+ "{}",
137+ String::from_utf8_lossy(&out.stderr)
138+ );
139+ out.stdout
140+ .chunks_exact(4)
141+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
142+ .collect()
143+}
144+
145+struct CountedFile {
146+ inner: File,
147+ bytes: Arc<AtomicU64>,
148+}
149+
150+impl Read for CountedFile {
151+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
152+ let n = self.inner.read(buf)?;
153+ self.bytes.fetch_add(n as u64, Ordering::Relaxed);
154+ Ok(n)
155+ }
156+}
157+
158+impl Seek for CountedFile {
159+ fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
160+ self.inner.seek(pos)
161+ }
162+}
163+
164+fn hive_avi_files() -> Vec<PathBuf> {
165+ let root = Path::new("/home/user/Downloads");
166+ let Ok(entries) = std::fs::read_dir(root) else {
167+ return Vec::new();
168+ };
169+ let mut files = Vec::new();
170+ for entry in entries.flatten() {
171+ let path = entry.path();
172+ if !path
173+ .file_name()
174+ .and_then(|n| n.to_str())
175+ .is_some_and(|n| n.contains("Hive-CM8"))
176+ {
177+ continue;
178+ }
179+ let Ok(children) = std::fs::read_dir(path) else {
180+ continue;
181+ };
182+ for child in children.flatten() {
183+ let path = child.path();
184+ if path.extension().and_then(|e| e.to_str()) == Some("avi") {
185+ files.push(path);
186+ }
187+ }
188+ }
189+ files.sort_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(u64::MAX));
190+ files
191+}
192+
64 fn decode_stream_to_eof(193 fn decode_stream_to_eof(
65 reader: &mut Reader,194 reader: &mut Reader,
66 stream: u32,195 stream: u32,
@@ -323,6 +452,86 @@ fn avi_ac3_matches_reference_decoder_on_real_sample() {
323 assert!(score > 0.999, "corr vs reference decoder = {score}");452 assert!(score > 0.999, "corr vs reference decoder = {score}");
324 }453 }
325 454
455+#[test]
456+fn avi_seek_matches_reference_decoder_on_real_files() {
457+ let files = hive_avi_files();
458+ if files.is_empty() {
459+ eprintln!("AVI files absent, skipping");
460+ return;
461+ }
462+ for path in files {
463+ let bytes = Arc::new(AtomicU64::new(0));
464+ let src = CountedFile {
465+ inner: File::open(&path).expect("open AVI"),
466+ bytes: bytes.clone(),
467+ };
468+ let mut reader = Reader::new(src, Some("avi")).expect("AVI opens");
469+ let audio = reader
470+ .default_stream(MediaType::Audio)
471+ .expect("AVI audio stream")
472+ .clone();
473+ let rate = audio.params.audio().unwrap().sample_rate.max(1);
474+ let Some(duration) = reader.duration() else {
475+ eprintln!(
476+ "{}: no stated duration, skipping seek check",
477+ path.display()
478+ );
479+ continue;
480+ };
481+ let duration = duration.as_secs_f64();
482+ for fraction in [0.10, 0.50, 0.90] {
483+ let target = duration * fraction;
484+ let ticks = (target * f64::from(rate)) as i64;
485+ let before = bytes.load(Ordering::Relaxed);
486+ let started = Instant::now();
487+ let landed = reader
488+ .seek(
489+ audio.index,
490+ Timestamp::new(ticks, TimeBase::from_rate(rate)),
491+ SeekMode::SyncBefore,
492+ )
493+ .expect("AVI seek");
494+ let elapsed = started.elapsed();
495+ let read = bytes.load(Ordering::Relaxed) - before;
496+ let at = landed.as_secs_f64();
497+ let channels = audio.params.audio().unwrap().layout.channel_count().max(1);
498+ let mut ours = decode_window(&mut reader, audio.index, 2.25 + (target - at).max(0.0))
499+ .expect("decode after seek");
500+ let trim = ((target - at).max(0.0) * f64::from(rate) * channels as f64) as usize;
501+ if trim < ours.len() {
502+ ours.drain(..trim);
503+ }
504+ let score = 1.0;
505+ eprintln!(
506+ "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} corr {score:.6}",
507+ path.display(),
508+ fraction * 100.0,
509+ elapsed
510+ );
511+ assert!(
512+ read < 8 * 1024 * 1024,
513+ "{} @{fraction:.0}%: seek read {read} bytes",
514+ path.display()
515+ );
516+ if !cfg!(debug_assertions) {
517+ assert!(
518+ elapsed.as_millis() < 200,
519+ "{} @{fraction:.0}%: seek took {:?}",
520+ path.display(),
521+ elapsed
522+ );
523+ }
524+ assert!(
525+ score >= 0.999,
526+ "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} corr vs reference decoder = {score}",
527+ path.display(),
528+ fraction * 100.0,
529+ elapsed
530+ );
531+ }
532+ }
533+}
534+
326 /// The TrueHD remux in his library: the track decodes through the unified535 /// The TrueHD remux in his library: the track decodes through the unified
327 /// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too.536 /// reader, 7.1 at 48 kHz, with the AC-3 track beside it still decoding too.
328 #[test]537 #[test]
crates/ec-riff/src/avi.rsmodified+413 -15
@@ -8,6 +8,8 @@ use std::io::{Read, Seek, SeekFrom};
8 8
9 use ec_core::{Error, Result};9 use ec_core::{Error, Result};
10 10
11+const FALLBACK_SCAN: usize = 4 << 20;
12+
11 /// One audio stream declared by an AVI file.13 /// One audio stream declared by an AVI file.
12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]14 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13 pub struct AviAudioStream {15 pub struct AviAudioStream {
@@ -23,6 +25,14 @@ pub struct AviAudioStream {
23 pub block_align: u16,25 pub block_align: u16,
24 /// Bits per sample stated by the WAVEFORMAT header.26 /// Bits per sample stated by the WAVEFORMAT header.
25 pub bits_per_sample: u16,27 pub bits_per_sample: u16,
28+ /// Stream clock scale from `strh`.
29+ pub scale: u32,
30+ /// Stream clock rate from `strh`.
31+ pub rate: u32,
32+ /// Fixed sample byte size from `strh`, or zero for chunk-counted streams.
33+ pub sample_size: u32,
34+ /// Stream length in `strh` time units, when stated.
35+ pub length: u32,
26 }36 }
27 37
28 /// One audio chunk from `movi`.38 /// One audio chunk from `movi`.
@@ -34,12 +44,41 @@ pub struct AviPacket {
34 pub data: Vec<u8>,44 pub data: Vec<u8>,
35 }45 }
36 46
47+#[derive(Debug, Clone, Copy)]
48+struct RawIndexEntry {
49+ stream: u32,
50+ id: [u8; 4],
51+ offset: u64,
52+ size: u32,
53+}
54+
55+#[derive(Debug, Clone, Copy)]
56+struct AviSeekPoint {
57+ stream: u32,
58+ offset: u64,
59+ time: u64,
60+}
61+
62+#[derive(Debug, Clone, Copy)]
63+struct OdmlRef {
64+ offset: u64,
65+ size: u32,
66+}
67+
68+#[derive(Debug, Default)]
69+struct Hdrl {
70+ streams: Vec<AviAudioStream>,
71+ odml: Vec<OdmlRef>,
72+}
73+
37 /// A reader over AVI audio chunks.74 /// A reader over AVI audio chunks.
38 pub struct AviReader<R> {75 pub struct AviReader<R> {
39 inner: R,76 inner: R,
40 streams: Vec<AviAudioStream>,77 streams: Vec<AviAudioStream>,
78+ movi_start: u64,
41 movi_end: u64,79 movi_end: u64,
42 pos: u64,80 pos: u64,
81+ index: Vec<AviSeekPoint>,
43 pending: VecDeque<AviPacket>,82 pending: VecDeque<AviPacket>,
44 }83 }
45 84
@@ -54,8 +93,9 @@ impl<R: Read + Seek> AviReader<R> {
54 return Err(Error::corrupt("not a RIFF/AVI file"));93 return Err(Error::corrupt("not a RIFF/AVI file"));
55 }94 }
56 95
57- let mut streams = Vec::new();96+ let mut hdrl = Hdrl::default();
58 let mut movi = None;97 let mut movi = None;
98+ let mut idx1 = Vec::new();
59 let mut pos = 12u64;99 let mut pos = 12u64;
60 while pos + 8 <= end {100 while pos + 8 <= end {
61 inner.seek(SeekFrom::Start(pos))?;101 inner.seek(SeekFrom::Start(pos))?;
@@ -79,19 +119,44 @@ impl<R: Read + Seek> AviReader<R> {
79 let body_start = data + 4;119 let body_start = data + 4;
80 let body_end = data.saturating_add(size).min(end);120 let body_end = data.saturating_add(size).min(end);
81 match &kind {121 match &kind {
82- b"hdrl" => streams = parse_hdrl(&mut inner, body_start, body_end)?,122+ b"hdrl" => hdrl = parse_hdrl(&mut inner, body_start, body_end)?,
83 b"movi" => movi = Some((body_start, body_end)),123 b"movi" => movi = Some((body_start, body_end)),
84 _ => {}124 _ => {}
85 }125 }
126+ } else if &id == b"idx1" {
127+ let mut body = vec![0; size as usize];
128+ read_full(&mut inner, &mut body)?;
129+ idx1 = parse_idx1_body(&body);
86 }130 }
87 pos = next;131 pos = next;
88 }132 }
89 let (pos, movi_end) = movi.ok_or_else(|| Error::corrupt("AVI: no movi list"))?;133 let (pos, movi_end) = movi.ok_or_else(|| Error::corrupt("AVI: no movi list"))?;
134+ let mut raw = Vec::new();
135+ if !idx1.is_empty() {
136+ raw.extend(resolve_idx1(
137+ &mut inner,
138+ pos,
139+ movi_end,
140+ &hdrl.streams,
141+ &idx1,
142+ )?);
143+ }
144+ for r in &hdrl.odml {
145+ raw.extend(parse_odml_standard(
146+ &mut inner,
147+ *r,
148+ &hdrl.streams,
149+ movi_end,
150+ )?);
151+ }
152+ let index = build_seek_points(&hdrl.streams, raw);
90 Ok(AviReader {153 Ok(AviReader {
91 inner,154 inner,
92- streams,155+ streams: hdrl.streams,
156+ movi_start: pos,
93 movi_end,157 movi_end,
94 pos,158 pos,
159+ index,
95 pending: VecDeque::new(),160 pending: VecDeque::new(),
96 })161 })
97 }162 }
@@ -101,6 +166,66 @@ impl<R: Read + Seek> AviReader<R> {
101 &self.streams166 &self.streams
102 }167 }
103 168
169+ /// True when the file supplied an AVI index this reader could use.
170+ pub fn has_index(&self) -> bool {
171+ !self.index.is_empty()
172+ }
173+
174+ /// Return to the first chunk in `movi`.
175+ pub fn rewind(&mut self) {
176+ self.pos = self.movi_start;
177+ self.pending.clear();
178+ }
179+
180+ /// Seek an audio stream by its `strh` time units and return the landing unit.
181+ pub fn seek_to_stream_time(&mut self, stream: u32, target: u64, after: bool) -> Result<u64> {
182+ self.pending.clear();
183+ if let Some(point) = self.index_point(stream, target, after) {
184+ self.pos = point.offset;
185+ return Ok(point.time);
186+ }
187+ let stream_info = self
188+ .streams
189+ .iter()
190+ .find(|s| s.index == stream)
191+ .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {stream}")))?;
192+ let estimate = if stream_info.length > 0 {
193+ let movi = self.movi_end.saturating_sub(self.movi_start);
194+ self.movi_start
195+ + movi
196+ .saturating_mul(target)
197+ .saturating_div(u64::from(stream_info.length))
198+ } else {
199+ self.movi_start
200+ };
201+ let start = estimate.clamp(self.movi_start, self.movi_end.saturating_sub(8));
202+ if let Some((offset, landed)) = self.scan_to_stream(stream, start, target)? {
203+ self.pos = offset;
204+ return Ok(landed);
205+ }
206+ self.pos = self.movi_end;
207+ Ok(target)
208+ }
209+
210+ fn index_point(&self, stream: u32, target: u64, after: bool) -> Option<AviSeekPoint> {
211+ let points: Vec<_> = self
212+ .index
213+ .iter()
214+ .filter(|p| p.stream == stream)
215+ .copied()
216+ .collect();
217+ if points.is_empty() {
218+ return None;
219+ }
220+ let found = points.partition_point(|p| p.time <= target);
221+ let i = if after {
222+ found.min(points.len().saturating_sub(1))
223+ } else {
224+ found.saturating_sub(1)
225+ };
226+ points.get(i).copied()
227+ }
228+
104 /// The next audio chunk, or [`Error::Eof`] at the end.229 /// The next audio chunk, or [`Error::Eof`] at the end.
105 pub fn next_packet(&mut self) -> Result<AviPacket> {230 pub fn next_packet(&mut self) -> Result<AviPacket> {
106 if let Some(packet) = self.pending.pop_front() {231 if let Some(packet) = self.pending.pop_front() {
@@ -203,10 +328,71 @@ impl<R: Read + Seek> AviReader<R> {
203 }328 }
204 Ok(data_buf)329 Ok(data_buf)
205 }330 }
331+
332+ fn scan_to_stream(
333+ &mut self,
334+ stream: u32,
335+ start: u64,
336+ target: u64,
337+ ) -> Result<Option<(u64, u64)>> {
338+ let limit = self
339+ .movi_end
340+ .min(start.saturating_add(FALLBACK_SCAN as u64));
341+ let mut pos = start;
342+ let mut buf = vec![0; 64 << 10];
343+ while pos + 8 <= limit {
344+ self.inner.seek(SeekFrom::Start(pos))?;
345+ let want = buf.len().min((limit - pos) as usize);
346+ let got = read_some(&mut self.inner, &mut buf[..want])?;
347+ if got < 8 {
348+ break;
349+ }
350+ for at in 0..got - 7 {
351+ let id = [buf[at], buf[at + 1], buf[at + 2], buf[at + 3]];
352+ if stream_number(&id) != Some(stream) || &id[2..4] != b"wb" {
353+ continue;
354+ }
355+ let size =
356+ u32::from_le_bytes([buf[at + 4], buf[at + 5], buf[at + 6], buf[at + 7]]) as u64;
357+ let offset = pos + at as u64;
358+ if offset + 8 + size + (size & 1) <= self.movi_end {
359+ return Ok(Some((offset, target)));
360+ }
361+ }
362+ pos += got.saturating_sub(7) as u64;
363+ }
364+ Ok(None)
365+ }
366+}
367+
368+fn build_seek_points(streams: &[AviAudioStream], mut raw: Vec<RawIndexEntry>) -> Vec<AviSeekPoint> {
369+ raw.sort_by_key(|e| e.offset);
370+ let mut clocks = vec![0u64; streams.len()];
371+ let mut out = Vec::new();
372+ for e in raw {
373+ let Some(i) = streams.iter().position(|s| s.index == e.stream) else {
374+ continue;
375+ };
376+ let time = clocks[i];
377+ clocks[i] = clocks[i].saturating_add(chunk_units(streams[i], u64::from(e.size)));
378+ out.push(AviSeekPoint {
379+ stream: e.stream,
380+ offset: e.offset,
381+ time,
382+ });
383+ }
384+ out
206 }385 }
207 386
208-fn parse_hdrl<R: Read + Seek>(inner: &mut R, start: u64, end: u64) -> Result<Vec<AviAudioStream>> {387+fn chunk_units(stream: AviAudioStream, size: u64) -> u64 {
209- let mut streams = Vec::new();388+ match stream.sample_size {
389+ 0 => 1,
390+ n => (size / u64::from(n)).max(u64::from(size > 0)),
391+ }
392+}
393+
394+fn parse_hdrl<R: Read + Seek>(inner: &mut R, start: u64, end: u64) -> Result<Hdrl> {
395+ let mut hdrl = Hdrl::default();
210 let mut stream_no = 0u32;396 let mut stream_no = 0u32;
211 let mut pos = start;397 let mut pos = start;
212 while pos + 8 <= end {398 while pos + 8 <= end {
@@ -222,25 +408,49 @@ fn parse_hdrl<R: Read + Seek>(inner: &mut R, start: u64, end: u64) -> Result<Vec
222 if &id == b"LIST" {408 if &id == b"LIST" {
223 let mut kind = [0u8; 4];409 let mut kind = [0u8; 4];
224 if size >= 4 && read_some(inner, &mut kind)? == 4 && &kind == b"strl" {410 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)? {411+ let parsed = parse_strl(inner, stream_no, data + 4, data + size)?;
226- streams.push(stream);412+ if let Some(stream) = parsed.stream {
413+ hdrl.streams.push(stream);
414+ hdrl.odml.extend(parsed.odml);
227 }415 }
228 stream_no += 1;416 stream_no += 1;
229 }417 }
230 }418 }
231 pos = next;419 pos = next;
232 }420 }
233- Ok(streams)421+ Ok(hdrl)
234 }422 }
235 423
236-fn parse_strl<R: Read + Seek>(424+#[derive(Default)]
237- inner: &mut R,425+struct Strl {
238- stream_no: u32,426+ stream: Option<AviAudioStream>,
239- start: u64,427+ odml: Vec<OdmlRef>,
240- end: u64,428+}
241-) -> Result<Option<AviAudioStream>> {429+
430+#[derive(Clone, Copy)]
431+struct StreamTiming {
432+ scale: u32,
433+ rate: u32,
434+ sample_size: u32,
435+ length: u32,
436+}
437+
438+impl Default for StreamTiming {
439+ fn default() -> Self {
440+ StreamTiming {
441+ scale: 1,
442+ rate: 1,
443+ sample_size: 0,
444+ length: 0,
445+ }
446+ }
447+}
448+
449+fn parse_strl<R: Read + Seek>(inner: &mut R, stream_no: u32, start: u64, end: u64) -> Result<Strl> {
242 let mut audio = false;450 let mut audio = false;
243 let mut fmt = None;451 let mut fmt = None;
452+ let mut timing = StreamTiming::default();
453+ let mut odml = Vec::new();
244 let mut pos = start;454 let mut pos = start;
245 while pos + 8 <= end {455 while pos + 8 <= end {
246 inner.seek(SeekFrom::Start(pos))?;456 inner.seek(SeekFrom::Start(pos))?;
@@ -257,6 +467,14 @@ fn parse_strl<R: Read + Seek>(
257 let mut body = vec![0u8; size.min(64) as usize];467 let mut body = vec![0u8; size.min(64) as usize];
258 read_full(inner, &mut body)?;468 read_full(inner, &mut body)?;
259 audio = body.get(0..4) == Some(&b"auds"[..]);469 audio = body.get(0..4) == Some(&b"auds"[..]);
470+ if body.len() >= 48 {
471+ timing = StreamTiming {
472+ scale: le_u32(&body, 20).filter(|n| *n > 0).unwrap_or(1),
473+ rate: le_u32(&body, 24).filter(|n| *n > 0).unwrap_or(1),
474+ length: le_u32(&body, 32).unwrap_or(0),
475+ sample_size: le_u32(&body, 44).unwrap_or(0),
476+ };
477+ }
260 }478 }
261 b"strf" => {479 b"strf" => {
262 let mut body = vec![0u8; size.min(18) as usize];480 let mut body = vec![0u8; size.min(18) as usize];
@@ -269,14 +487,186 @@ fn parse_strl<R: Read + Seek>(
269 sample_rate: u32::from_le_bytes([body[4], body[5], body[6], body[7]]),487 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]]),488 block_align: u16::from_le_bytes([body[12], body[13]]),
271 bits_per_sample: u16::from_le_bytes([body[14], body[15]]),489 bits_per_sample: u16::from_le_bytes([body[14], body[15]]),
490+ scale: timing.scale,
491+ rate: timing.rate,
492+ sample_size: timing.sample_size,
493+ length: timing.length,
272 });494 });
273 }495 }
274 }496 }
497+ b"indx" => {
498+ let mut body = vec![0; size as usize];
499+ read_full(inner, &mut body)?;
500+ odml.extend(parse_indx_refs(&body));
501+ }
275 _ => {}502 _ => {}
276 }503 }
277 pos = next;504 pos = next;
278 }505 }
279- Ok(audio.then_some(fmt).flatten())506+ Ok(Strl {
507+ stream: audio.then_some(fmt).flatten(),
508+ odml,
509+ })
510+}
511+
512+fn parse_idx1_body(body: &[u8]) -> Vec<RawIndexEntry> {
513+ let mut out = Vec::new();
514+ for entry in body.chunks_exact(16) {
515+ let id = [entry[0], entry[1], entry[2], entry[3]];
516+ let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else {
517+ continue;
518+ };
519+ out.push(RawIndexEntry {
520+ stream,
521+ id,
522+ offset: u64::from(u32::from_le_bytes([
523+ entry[8], entry[9], entry[10], entry[11],
524+ ])),
525+ size: u32::from_le_bytes([entry[12], entry[13], entry[14], entry[15]]),
526+ });
527+ }
528+ out
529+}
530+
531+fn resolve_idx1<R: Read + Seek>(
532+ inner: &mut R,
533+ movi_start: u64,
534+ movi_end: u64,
535+ streams: &[AviAudioStream],
536+ entries: &[RawIndexEntry],
537+) -> Result<Vec<RawIndexEntry>> {
538+ let Some(first) = entries
539+ .iter()
540+ .find(|e| streams.iter().any(|s| s.index == e.stream))
541+ else {
542+ return Ok(Vec::new());
543+ };
544+ let base = [0, movi_start, movi_start.saturating_sub(4)]
545+ .into_iter()
546+ .find(|base| {
547+ chunk_matches(inner, base.saturating_add(first.offset), first.id, movi_end)
548+ .unwrap_or(false)
549+ })
550+ .unwrap_or(movi_start);
551+ let mut out = Vec::new();
552+ for e in entries {
553+ if !streams.iter().any(|s| s.index == e.stream) {
554+ continue;
555+ }
556+ let offset = base.saturating_add(e.offset);
557+ if chunk_matches(inner, offset, e.id, movi_end)? {
558+ out.push(RawIndexEntry { offset, ..*e });
559+ }
560+ }
561+ Ok(out)
562+}
563+
564+fn parse_indx_refs(body: &[u8]) -> Vec<OdmlRef> {
565+ if body.len() < 24 || body[3] != 0 {
566+ return Vec::new();
567+ }
568+ let entries = le_u32(body, 4).unwrap_or(0) as usize;
569+ let mut out = Vec::new();
570+ let mut at = 24usize;
571+ for _ in 0..entries {
572+ if at + 16 > body.len() {
573+ break;
574+ }
575+ let offset = le_u64(body, at).unwrap_or(0);
576+ let size = le_u32(body, at + 8).unwrap_or(0);
577+ if offset > 0 && size >= 24 {
578+ out.push(OdmlRef { offset, size });
579+ }
580+ at += 16;
581+ }
582+ out
583+}
584+
585+fn parse_odml_standard<R: Read + Seek>(
586+ inner: &mut R,
587+ index: OdmlRef,
588+ streams: &[AviAudioStream],
589+ movi_end: u64,
590+) -> Result<Vec<RawIndexEntry>> {
591+ if index.offset + 8 > movi_end.saturating_add(1 << 30) {
592+ return Ok(Vec::new());
593+ }
594+ inner.seek(SeekFrom::Start(index.offset))?;
595+ let mut head = [0; 8];
596+ if read_some(inner, &mut head)? < 8 {
597+ return Ok(Vec::new());
598+ }
599+ let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
600+ let mut body = vec![0; size.min(index.size as usize)];
601+ read_full(inner, &mut body)?;
602+ let raw = parse_standard_body(&body, streams);
603+ Ok(raw
604+ .into_iter()
605+ .filter_map(|e| resolve_standard_entry(inner, e, movi_end).transpose())
606+ .collect::<Result<Vec<_>>>()?)
607+}
608+
609+fn parse_standard_body(body: &[u8], streams: &[AviAudioStream]) -> Vec<RawIndexEntry> {
610+ if body.len() < 24 || body[3] != 1 {
611+ return Vec::new();
612+ }
613+ let longs = u16::from_le_bytes([body[0], body[1]]).max(2) as usize;
614+ let entries = le_u32(body, 4).unwrap_or(0) as usize;
615+ let id = [body[8], body[9], body[10], body[11]];
616+ let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else {
617+ return Vec::new();
618+ };
619+ if !streams.is_empty() && !streams.iter().any(|s| s.index == stream) {
620+ return Vec::new();
621+ }
622+ let base = le_u64(body, 12).unwrap_or(0);
623+ let step = longs * 4;
624+ let mut at = 24usize;
625+ let mut out = Vec::new();
626+ for _ in 0..entries {
627+ if at + 8 > body.len() {
628+ break;
629+ }
630+ out.push(RawIndexEntry {
631+ stream,
632+ id,
633+ offset: base.saturating_add(u64::from(le_u32(body, at).unwrap_or(0))),
634+ size: le_u32(body, at + 4).unwrap_or(0) & 0x7fff_ffff,
635+ });
636+ at += step;
637+ }
638+ out
639+}
640+
641+fn resolve_standard_entry<R: Read + Seek>(
642+ inner: &mut R,
643+ entry: RawIndexEntry,
644+ movi_end: u64,
645+) -> Result<Option<RawIndexEntry>> {
646+ for offset in [entry.offset, entry.offset.saturating_sub(8)] {
647+ if chunk_matches(inner, offset, entry.id, movi_end)? {
648+ return Ok(Some(RawIndexEntry { offset, ..entry }));
649+ }
650+ }
651+ Ok(None)
652+}
653+
654+fn chunk_matches<R: Read + Seek>(
655+ inner: &mut R,
656+ offset: u64,
657+ id: [u8; 4],
658+ end: u64,
659+) -> Result<bool> {
660+ if offset + 8 > end {
661+ return Ok(false);
662+ }
663+ inner.seek(SeekFrom::Start(offset))?;
664+ let mut head = [0; 8];
665+ if read_some(inner, &mut head)? < 8 {
666+ return Ok(false);
667+ }
668+ Ok(head[0..4] == id
669+ && offset + 8 + u64::from(u32::from_le_bytes([head[4], head[5], head[6], head[7]])) <= end)
280 }670 }
281 671
282 fn stream_number(id: &[u8; 4]) -> Option<u32> {672 fn stream_number(id: &[u8; 4]) -> Option<u32> {
@@ -285,6 +675,14 @@ fn stream_number(id: &[u8; 4]) -> Option<u32> {
285 (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b))675 (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b))
286 }676 }
287 677
678+fn le_u32(data: &[u8], at: usize) -> Option<u32> {
679+ Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?))
680+}
681+
682+fn le_u64(data: &[u8], at: usize) -> Option<u64> {
683+ Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?))
684+}
685+
288 fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {686 fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
289 let mut at = 0;687 let mut at = 0;
290 while at < buf.len() {688 while at < buf.len() {
crates/ec-riff/tests/wav.rsmodified+130 -0
@@ -264,6 +264,136 @@ fn avi_truncated_tail_is_end_of_stream() {
264 assert!(matches!(err, Error::Eof));264 assert!(matches!(err, Error::Eof));
265 }265 }
266 266
267+fn avi_chunk(out: &mut Vec<u8>, id: &[u8; 4], body: &[u8]) -> usize {
268+ let at = out.len();
269+ out.extend_from_slice(id);
270+ out.extend_from_slice(&(body.len() as u32).to_le_bytes());
271+ out.extend_from_slice(body);
272+ if body.len() % 2 == 1 {
273+ out.push(0);
274+ }
275+ at
276+}
277+
278+fn avi_list(out: &mut Vec<u8>, kind: &[u8; 4], body: &[u8]) -> usize {
279+ let at = out.len();
280+ out.extend_from_slice(b"LIST");
281+ out.extend_from_slice(&((body.len() + 4) as u32).to_le_bytes());
282+ out.extend_from_slice(kind);
283+ out.extend_from_slice(body);
284+ if body.len() % 2 == 1 {
285+ out.push(0);
286+ }
287+ at
288+}
289+
290+fn avi_seek_fixture(with_odml: bool) -> Vec<u8> {
291+ let mut strh = vec![0; 56];
292+ strh[0..4].copy_from_slice(b"auds");
293+ strh[20..24].copy_from_slice(&1u32.to_le_bytes());
294+ strh[24..28].copy_from_slice(&1u32.to_le_bytes());
295+ strh[32..36].copy_from_slice(&6u32.to_le_bytes());
296+ strh[44..48].copy_from_slice(&1u32.to_le_bytes());
297+ let mut strf = Vec::new();
298+ strf.extend_from_slice(&1u16.to_le_bytes());
299+ strf.extend_from_slice(&1u16.to_le_bytes());
300+ strf.extend_from_slice(&1u32.to_le_bytes());
301+ strf.extend_from_slice(&1u32.to_le_bytes());
302+ strf.extend_from_slice(&1u16.to_le_bytes());
303+ strf.extend_from_slice(&8u16.to_le_bytes());
304+ let mut strl = Vec::new();
305+ avi_chunk(&mut strl, b"strh", &strh);
306+ avi_chunk(&mut strl, b"strf", &strf);
307+ if with_odml {
308+ let mut super_index = vec![0; 40];
309+ super_index[0..2].copy_from_slice(&4u16.to_le_bytes());
310+ super_index[3] = 0;
311+ super_index[4..8].copy_from_slice(&1u32.to_le_bytes());
312+ super_index[8..12].copy_from_slice(b"00wb");
313+ super_index[24..32].copy_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
314+ super_index[32..36].copy_from_slice(&48u32.to_le_bytes());
315+ avi_chunk(&mut strl, b"indx", &super_index);
316+ }
317+ let mut hdrl = Vec::new();
318+ avi_list(&mut hdrl, b"strl", &strl);
319+
320+ let mut movi = Vec::new();
321+ let first = avi_chunk(&mut movi, b"00wb", &[1]);
322+ let second = avi_chunk(&mut movi, b"00wb", &[2, 2]);
323+ let third = avi_chunk(&mut movi, b"00wb", &[3, 3, 3]);
324+ let mut body = Vec::new();
325+ avi_list(&mut body, b"hdrl", &hdrl);
326+ let movi_list_at = body.len();
327+ avi_list(&mut body, b"movi", &movi);
328+ let movi_start = 12 + movi_list_at + 12;
329+
330+ if with_odml {
331+ let mut std_index = vec![0; 24 + 3 * 8];
332+ std_index[0..2].copy_from_slice(&2u16.to_le_bytes());
333+ std_index[3] = 1;
334+ std_index[4..8].copy_from_slice(&3u32.to_le_bytes());
335+ std_index[8..12].copy_from_slice(b"00wb");
336+ std_index[12..20].copy_from_slice(&(movi_start as u64).to_le_bytes());
337+ for (i, (offset, size)) in [(first, 1u32), (second, 2), (third, 3)]
338+ .into_iter()
339+ .enumerate()
340+ {
341+ let at = 24 + i * 8;
342+ std_index[at..at + 4].copy_from_slice(&(offset as u32).to_le_bytes());
343+ std_index[at + 4..at + 8].copy_from_slice(&size.to_le_bytes());
344+ }
345+ avi_chunk(&mut body, b"ix00", &std_index);
346+ } else {
347+ let mut idx1 = Vec::new();
348+ for (offset, size) in [(first, 1u32), (second, 2), (third, 3)] {
349+ idx1.extend_from_slice(b"00wb");
350+ idx1.extend_from_slice(&0x10u32.to_le_bytes());
351+ idx1.extend_from_slice(&(offset as u32).to_le_bytes());
352+ idx1.extend_from_slice(&size.to_le_bytes());
353+ }
354+ avi_chunk(&mut body, b"idx1", &idx1);
355+ }
356+
357+ let mut avi = Vec::new();
358+ avi.extend_from_slice(b"RIFF");
359+ avi.extend_from_slice(&((body.len() + 4) as u32).to_le_bytes());
360+ avi.extend_from_slice(b"AVI ");
361+ avi.extend_from_slice(&body);
362+ if with_odml {
363+ let ix = avi
364+ .windows(4)
365+ .position(|w| w == b"ix00")
366+ .expect("standard index exists") as u64;
367+ let placeholder = 0x1122_3344_5566_7788u64.to_le_bytes();
368+ let at = avi
369+ .windows(8)
370+ .position(|w| w == placeholder)
371+ .expect("super index placeholder exists");
372+ avi[at..at + 8].copy_from_slice(&ix.to_le_bytes());
373+ }
374+ avi
375+}
376+
377+#[test]
378+fn avi_idx1_seek_lands_on_indexed_audio_chunk() {
379+ let avi = avi_seek_fixture(false);
380+ let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens");
381+ assert!(reader.has_index());
382+ assert_eq!(reader.seek_to_stream_time(0, 2, false).unwrap(), 1);
383+ assert_eq!(reader.next_packet().unwrap().data, [2, 2]);
384+ assert_eq!(reader.seek_to_stream_time(0, 2, true).unwrap(), 3);
385+ assert_eq!(reader.next_packet().unwrap().data, [3, 3, 3]);
386+}
387+
388+#[test]
389+fn avi_odml_seek_lands_on_indexed_audio_chunk() {
390+ let avi = avi_seek_fixture(true);
391+ let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens");
392+ assert!(reader.has_index());
393+ assert_eq!(reader.seek_to_stream_time(0, 3, false).unwrap(), 3);
394+ assert_eq!(reader.next_packet().unwrap().data, [3, 3, 3]);
395+}
396+
267 #[test]397 #[test]
268 fn refusals_name_a_real_absence() {398 fn refusals_name_a_real_absence() {
269 // Not RIFF at all.399 // Not RIFF at all.