Bound indexed AVI seeks
Browse files at this commitee1a9140a16d66b05ed682799707cfa39bab9804Parent: 555c86a- fix
- bound indexed AVI seeks
5 changed files +187 -68
- crates/ec-probe/src/lib.rs +13 -13
- crates/ec-probe/tests/library.rs +129 -37
- crates/ec-riff/src/avi.rs +43 -17
- crates/ec-riff/src/lib.rs +1 -1
- crates/ec-riff/tests/wav.rs +1 -0
crates/ec-probe/src/lib.rsmodified+13 -13
| @@ -951,11 +951,17 @@ fn avi_elementary_leading_skip(codec: CodecId, data: &[u8]) -> usize { | |||
| 951 | 0 | 951 | 0 |
| 952 | } | 952 | } |
| 953 | 953 | ||
| 954 | -fn samples_to_avi_units(stream: ec_riff::AviAudioStream, samples: u64) -> u64 { | 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)); | 955 | let scale = u128::from(stream.scale.max(1)); |
| 956 | let rate = u128::from(stream.rate.max(1)); | 956 | let rate = u128::from(stream.rate.max(1)); |
| 957 | let sample_rate = u128::from(stream.sample_rate.max(1)); | 957 | let sample_rate = u128::from(stream.sample_rate.max(1)); |
| 958 | - let units = u128::from(samples).saturating_mul(rate) / (scale * sample_rate); | 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 | + }; | ||
| 959 | let units = units.min(u128::from(u64::MAX)) as u64; | 965 | let units = units.min(u128::from(u64::MAX)) as u64; |
| 960 | match stream.length { | 966 | match stream.length { |
| 961 | 0 => units, | 967 | 0 => units, |
| @@ -1002,17 +1008,11 @@ impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> { | |||
| 1002 | .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {avi_stream_no}")))?; | 1008 | .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {avi_stream_no}")))?; |
| 1003 | let base = self.streams[local].time_base; | 1009 | let base = self.streams[local].time_base; |
| 1004 | let target_samples = to.rescale(base, Rounding::Down).ticks.max(0) as u64; | 1010 | let target_samples = to.rescale(base, Rounding::Down).ticks.max(0) as u64; |
| 1005 | - let target_units = samples_to_avi_units(avi_stream, target_samples); | 1011 | + let seek_units = samples_to_avi_units( |
| 1006 | - let seek_units = if matches!( | 1012 | + avi_stream, |
| 1007 | - self.streams[local].params.codec, | 1013 | + target_samples, |
| 1008 | - CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac | 1014 | + matches!(mode, SeekMode::SyncAfter), |
| 1009 | - ) { | 1015 | + ); |
| 1010 | - target_units.saturating_sub(u64::from( | ||
| 1011 | - (avi_stream.rate / avi_stream.scale.max(1)).max(1), | ||
| 1012 | - )) | ||
| 1013 | - } else { | ||
| 1014 | - target_units | ||
| 1015 | - }; | ||
| 1016 | let landed_units = self.reader.seek_to_stream_time( | 1016 | let landed_units = self.reader.seek_to_stream_time( |
| 1017 | avi_stream_no, | 1017 | avi_stream_no, |
| 1018 | seek_units, | 1018 | seek_units, |
crates/ec-probe/tests/library.rsmodified+129 -37
| @@ -184,6 +184,44 @@ fn assert_avi_index_is_bounded(path: &Path) { | |||
| 184 | ); | 184 | ); |
| 185 | } | 185 | } |
| 186 | 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 | + | ||
| 187 | fn decode_stream_to_eof( | 225 | fn decode_stream_to_eof( |
| 188 | reader: &mut Reader, | 226 | reader: &mut Reader, |
| 189 | stream: u32, | 227 | stream: u32, |
| @@ -273,51 +311,105 @@ fn assert_avi_seeks_match_reference(path: &Path) { | |||
| 273 | CodecId::Mp3 => 1152, | 311 | CodecId::Mp3 => 1152, |
| 274 | _ => 1, | 312 | _ => 1, |
| 275 | }; | 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"); | ||
| 276 | let duration = reader.duration().expect("AVI duration").as_secs_f64(); | 319 | let duration = reader.duration().expect("AVI duration").as_secs_f64(); |
| 320 | + let codec_preroll = avi_codec_preroll(audio.params.codec, rate); | ||
| 277 | for fraction in [0.10, 0.50, 0.90] { | 321 | for fraction in [0.10, 0.50, 0.90] { |
| 278 | let target = duration * fraction; | 322 | let target = duration * fraction; |
| 279 | let ticks = (target * f64::from(rate)) as i64; | 323 | let ticks = (target * f64::from(rate)) as i64; |
| 280 | - let before = bytes.load(Ordering::Relaxed); | 324 | + for (mode, label) in [ |
| 281 | - let started = Instant::now(); | 325 | + (SeekMode::SyncBefore, "before"), |
| 282 | - let landed = reader | 326 | + (SeekMode::SyncAfter, "after"), |
| 283 | - .seek( | 327 | + ] { |
| 284 | - audio.index, | 328 | + let target_units = samples_to_avi_units( |
| 285 | - Timestamp::new(ticks, TimeBase::from_rate(rate)), | 329 | + avi_stream, |
| 286 | - SeekMode::SyncBefore, | 330 | + ticks.max(0) as u64, |
| 287 | - ) | 331 | + matches!(mode, SeekMode::SyncAfter), |
| 288 | - .expect("AVI seek"); | 332 | + ); |
| 289 | - let elapsed = started.elapsed(); | 333 | + let (point, chunk_interval) = |
| 290 | - let read = bytes.load(Ordering::Relaxed) - before; | 334 | + avi_indexed_point(path, target_units, matches!(mode, SeekMode::SyncAfter)); |
| 291 | - let at = landed.as_secs_f64(); | 335 | + let before = bytes.load(Ordering::Relaxed); |
| 292 | - let ours = decode_window(&mut reader, audio.index, 2.0).expect("decode after seek"); | 336 | + let started = Instant::now(); |
| 293 | - let theirs = reference_seek_window(path, at); | 337 | + let landed = reader |
| 294 | - let (lag, score) = best_frame_corr(&ours, &theirs, channels, frame_samples); | 338 | + .seek( |
| 295 | - eprintln!( | 339 | + audio.index, |
| 296 | - "{} @{:.0}%: target {target:.3}s landed {at:.3}s read {read} bytes seek {:?} lag {lag} frames corr {score:.6}", | 340 | + Timestamp::new(ticks, TimeBase::from_rate(rate)), |
| 297 | - path.display(), | 341 | + mode, |
| 298 | - fraction * 100.0, | 342 | + ) |
| 299 | - elapsed | 343 | + .expect("AVI seek"); |
| 300 | - ); | 344 | + let elapsed = started.elapsed(); |
| 301 | - assert!( | 345 | + let read = bytes.load(Ordering::Relaxed) - before; |
| 302 | - read < 8 * 1024 * 1024, | 346 | + let at = landed.as_secs_f64(); |
| 303 | - "{} @{fraction:.0}%: seek read {read} bytes", | 347 | + eprintln!( |
| 304 | - path.display() | 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 {:?}", |
| 305 | - ); | ||
| 306 | - if !cfg!(debug_assertions) { | ||
| 307 | - assert!( | ||
| 308 | - elapsed.as_millis() < 200, | ||
| 309 | - "{} @{:.0}%: seek took {:?}", | ||
| 310 | path.display(), | 349 | path.display(), |
| 311 | fraction * 100.0, | 350 | fraction * 100.0, |
| 312 | - elapsed | 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() | ||
| 313 | ); | 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 | + } | ||
| 314 | } | 412 | } |
| 315 | - assert!( | ||
| 316 | - score >= 0.999, | ||
| 317 | - "{} @{:.0}%: target {target:.3}s landed {at:.3}s lag {lag} frames corr vs reference decoder = {score}", | ||
| 318 | - path.display(), | ||
| 319 | - fraction * 100.0, | ||
| 320 | - ); | ||
| 321 | } | 413 | } |
| 322 | } | 414 | } |
| 323 | 415 | ||
crates/ec-riff/src/avi.rsmodified+43 -17
| @@ -58,6 +58,17 @@ struct AviSeekPoint { | |||
| 58 | offset: u64, | 58 | offset: u64, |
| 59 | time: u64, | 59 | time: u64, |
| 60 | } | 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 | + | ||
| 61 | 72 | ||
| 62 | #[derive(Debug, Clone, Copy)] | 73 | #[derive(Debug, Clone, Copy)] |
| 63 | struct OdmlRef { | 74 | struct OdmlRef { |
| @@ -185,7 +196,7 @@ impl<R: Read + Seek> AviReader<R> { | |||
| 185 | /// Seek an audio stream by its `strh` time units and return the landing unit. | 196 | /// Seek an audio stream by its `strh` time units and return the landing unit. |
| 186 | pub fn seek_to_stream_time(&mut self, stream: u32, target: u64, after: bool) -> Result<u64> { | 197 | pub fn seek_to_stream_time(&mut self, stream: u32, target: u64, after: bool) -> Result<u64> { |
| 187 | self.pending.clear(); | 198 | self.pending.clear(); |
| 188 | - if let Some(point) = self.index_point(stream, target, after) { | 199 | + if let Some(point) = self.seek_point(stream, target, after) { |
| 189 | self.pos = point.offset; | 200 | self.pos = point.offset; |
| 190 | return Ok(point.time); | 201 | return Ok(point.time); |
| 191 | } | 202 | } |
| @@ -212,23 +223,38 @@ impl<R: Read + Seek> AviReader<R> { | |||
| 212 | Ok(target) | 223 | Ok(target) |
| 213 | } | 224 | } |
| 214 | 225 | ||
| 215 | - fn index_point(&self, stream: u32, target: u64, after: bool) -> Option<AviSeekPoint> { | 226 | + /// Return the indexed chunk this seek would select. |
| 216 | - let points: Vec<_> = self | 227 | + pub fn indexed_point(&self, stream: u32, target: u64, after: bool) -> Option<AviIndexPoint> { |
| 217 | - .index | 228 | + let mut before = None; |
| 218 | - .iter() | 229 | + let mut last = None; |
| 219 | - .filter(|p| p.stream == stream) | 230 | + for (index, point) in self.index.iter().filter(|point| point.stream == stream).enumerate() { |
| 220 | - .copied() | 231 | + let point = AviIndexPoint { |
| 221 | - .collect(); | 232 | + index, |
| 222 | - if points.is_empty() { | 233 | + offset: point.offset, |
| 223 | - return None; | 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 | + } | ||
| 224 | } | 246 | } |
| 225 | - let found = points.partition_point(|p| p.time <= target); | 247 | + if after { last } else { before } |
| 226 | - let i = if after { | 248 | + } |
| 227 | - found.min(points.len().saturating_sub(1)) | 249 | + |
| 228 | - } else { | 250 | + |
| 229 | - found.saturating_sub(1) | 251 | + fn seek_point(&self, stream: u32, target: u64, after: bool) -> Option<AviSeekPoint> { |
| 230 | - }; | 252 | + let point = self.indexed_point(stream, target, after)?; |
| 231 | - points.get(i).copied() | 253 | + Some(AviSeekPoint { |
| 254 | + stream, | ||
| 255 | + offset: point.offset, | ||
| 256 | + time: point.time, | ||
| 257 | + }) | ||
| 232 | } | 258 | } |
| 233 | 259 | ||
| 234 | /// The next audio chunk, or [`Error::Eof`] at the end. | 260 | /// The next audio chunk, or [`Error::Eof`] at the end. |
crates/ec-riff/src/lib.rsmodified+1 -1
| @@ -29,7 +29,7 @@ mod avi; | |||
| 29 | mod read; | 29 | mod read; |
| 30 | mod write; | 30 | mod write; |
| 31 | 31 | ||
| 32 | -pub use avi::{AviAudioStream, AviPacket, AviReader}; | 32 | +pub use avi::{AviAudioStream, AviIndexPoint, AviPacket, AviReader}; |
| 33 | pub use ec_core::{Error, Result}; | 33 | pub use ec_core::{Error, Result}; |
| 34 | pub use read::WavReader; | 34 | pub use read::WavReader; |
| 35 | pub use write::{Sample, WavWriter}; | 35 | pub use write::{Sample, WavWriter}; |
crates/ec-riff/tests/wav.rsmodified+1 -0
| @@ -379,6 +379,7 @@ fn avi_idx1_seek_lands_on_indexed_audio_chunk() { | |||
| 379 | let avi = avi_seek_fixture(false); | 379 | let avi = avi_seek_fixture(false); |
| 380 | let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens"); | 380 | let mut reader = AviReader::new(Cursor::new(&avi)).expect("AVI opens"); |
| 381 | assert!(reader.has_index()); | 381 | assert!(reader.has_index()); |
| 382 | + assert_eq!(reader.indexed_point(0, 1, true).unwrap().time, 1); | ||
| 382 | assert_eq!(reader.seek_to_stream_time(0, 2, false).unwrap(), 1); | 383 | 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.next_packet().unwrap().data, [2, 2]); |
| 384 | assert_eq!(reader.seek_to_stream_time(0, 2, true).unwrap(), 3); | 385 | assert_eq!(reader.seek_to_stream_time(0, 2, true).unwrap(), 3); |