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