edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 1 | //! RIFF/AVI audio chunk reader. |
| 2 | //! |
| 3 | //! This is the small half an audio probe needs: stream headers plus `movi` |
| 4 | //! sound chunks. Picture chunks are skipped. |
| 5 | |
| 6 | use std::collections::VecDeque; |
| 7 | use std::io::{Read, Seek, SeekFrom}; |
| 8 | |
| 9 | use ec_core::{Error, Result}; |
| 10 | |
| 11 | const FALLBACK_SCAN: usize = 4 << 20; |
| 12 | /// Deepest `rec ` list nesting `next_packet` will walk. Real files nest one level. |
| 13 | const MAX_REC_DEPTH: usize = 16; |
| 14 | |
| 15 | /// One audio stream declared by an AVI file. |
| 16 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 17 | pub struct AviAudioStream { |
| 18 | /// AVI stream number, the two decimal digits at the start of chunk ids. |
| 19 | pub index: u32, |
| 20 | /// WAVE format tag from this stream's `strf` body. |
| 21 | pub format_tag: u16, |
| 22 | /// Channel count stated by the WAVEFORMAT header. |
| 23 | pub channels: u16, |
| 24 | /// Samples per second stated by the WAVEFORMAT header. |
| 25 | pub sample_rate: u32, |
| 26 | /// Block alignment stated by the WAVEFORMAT header. |
| 27 | pub block_align: u16, |
| 28 | /// Bits per sample stated by the WAVEFORMAT header. |
| 29 | pub bits_per_sample: u16, |
| 30 | /// Stream clock scale from `strh`. |
| 31 | pub scale: u32, |
| 32 | /// Stream clock rate from `strh`. |
| 33 | pub rate: u32, |
| 34 | /// Fixed sample byte size from `strh`, or zero for chunk-counted streams. |
| 35 | pub sample_size: u32, |
| 36 | /// Stream length in `strh` time units, when stated. |
| 37 | pub length: u32, |
| 38 | } |
| 39 | |
| 40 | /// One audio chunk from `movi`. |
| 41 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 42 | pub struct AviPacket { |
| 43 | /// AVI stream number. |
| 44 | pub stream: u32, |
| 45 | /// Chunk payload. |
| 46 | pub data: Vec<u8>, |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, Copy)] |
| 50 | struct RawIndexEntry { |
| 51 | stream: u32, |
| 52 | id: [u8; 4], |
| 53 | offset: u64, |
| 54 | size: u32, |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, Copy)] |
| 58 | struct AviSeekPoint { |
| 59 | stream: u32, |
| 60 | offset: u64, |
| 61 | time: u64, |
| 62 | } |
| 63 | /// An indexed audio chunk selected for a seek. |
| 64 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 65 | pub struct AviIndexPoint { |
| 66 | /// This stream's zero-based index entry number. |
| 67 | pub index: usize, |
| 68 | /// File offset of the chunk header. |
| 69 | pub offset: u64, |
| 70 | /// Stream time units at the chunk's start. |
| 71 | pub time: u64, |
| 72 | } |
| 73 | |
| 74 | |
| 75 | #[derive(Debug, Clone, Copy)] |
| 76 | struct OdmlRef { |
| 77 | offset: u64, |
| 78 | size: u32, |
| 79 | } |
| 80 | |
| 81 | #[derive(Debug, Default)] |
| 82 | struct Hdrl { |
| 83 | streams: Vec<AviAudioStream>, |
| 84 | extras: Vec<Vec<u8>>, |
| 85 | odml: Vec<OdmlRef>, |
| 86 | } |
| 87 | |
| 88 | /// A reader over AVI audio chunks. |
| 89 | pub struct AviReader<R> { |
| 90 | inner: R, |
| 91 | streams: Vec<AviAudioStream>, |
| 92 | extras: Vec<Vec<u8>>, |
| 93 | movi_start: u64, |
| 94 | movi_end: u64, |
| 95 | pos: u64, |
| 96 | index: Vec<AviSeekPoint>, |
| 97 | pending: VecDeque<AviPacket>, |
| 98 | } |
| 99 | |
| 100 | impl<R: Read + Seek> AviReader<R> { |
| 101 | /// Parse the RIFF/AVI headers, leaving the reader at the start of `movi`. |
| 102 | pub fn new(mut inner: R) -> Result<AviReader<R>> { |
| 103 | let end = inner.seek(SeekFrom::End(0))?; |
| 104 | inner.rewind()?; |
| 105 | let mut head = [0u8; 12]; |
| 106 | read_full(&mut inner, &mut head)?; |
| 107 | if &head[0..4] != b"RIFF" || &head[8..12] != b"AVI " { |
| 108 | return Err(Error::corrupt("not a RIFF/AVI file")); |
| 109 | } |
| 110 | |
| 111 | let mut hdrl = Hdrl::default(); |
| 112 | let mut movi = None; |
| 113 | let mut idx1 = Vec::new(); |
| 114 | let mut pos = 12u64; |
| 115 | while pos + 8 <= end { |
| 116 | inner.seek(SeekFrom::Start(pos))?; |
| 117 | let mut chunk = [0u8; 8]; |
| 118 | let got = read_some(&mut inner, &mut chunk)?; |
| 119 | if got == 0 { |
| 120 | break; |
| 121 | } |
| 122 | if got < 8 { |
| 123 | return Err(Error::corrupt("AVI chunk header ends mid-field")); |
| 124 | } |
| 125 | let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; |
| 126 | let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; |
| 127 | let data = pos + 8; |
| 128 | let next = data.saturating_add(size).saturating_add(size & 1); |
| 129 | if &id == b"LIST" { |
| 130 | let mut kind = [0u8; 4]; |
| 131 | if size < 4 || read_some(&mut inner, &mut kind)? < 4 { |
| 132 | return Err(Error::corrupt("AVI LIST header ends mid-field")); |
| 133 | } |
| 134 | let body_start = data + 4; |
| 135 | let body_end = data.saturating_add(size).min(end); |
| 136 | match &kind { |
| 137 | b"hdrl" => hdrl = parse_hdrl(&mut inner, body_start, body_end)?, |
| 138 | b"movi" => movi = Some((body_start, body_end)), |
| 139 | _ => {} |
| 140 | } |
| 141 | } else if &id == b"idx1" { |
| 142 | let body = read_body(&mut inner, size)?; |
| 143 | idx1 = parse_idx1_body(&body); |
| 144 | } |
| 145 | pos = next; |
| 146 | } |
| 147 | let (pos, movi_end) = movi.ok_or_else(|| Error::corrupt("AVI: no movi list"))?; |
| 148 | let mut raw = Vec::new(); |
| 149 | if !idx1.is_empty() { |
| 150 | raw.extend(resolve_idx1( |
| 151 | &mut inner, |
| 152 | pos, |
| 153 | movi_end, |
| 154 | &hdrl.streams, |
| 155 | &idx1, |
| 156 | )?); |
| 157 | } |
| 158 | for r in &hdrl.odml { |
| 159 | raw.extend(parse_odml_standard( |
| 160 | &mut inner, |
| 161 | *r, |
| 162 | &hdrl.streams, |
| 163 | movi_end, |
| 164 | )?); |
| 165 | } |
| 166 | let index = build_seek_points(&hdrl.streams, raw); |
| 167 | Ok(AviReader { |
| 168 | inner, |
| 169 | streams: hdrl.streams, |
| 170 | extras: hdrl.extras, |
| 171 | movi_start: pos, |
| 172 | movi_end, |
| 173 | pos, |
| 174 | index, |
| 175 | pending: VecDeque::new(), |
| 176 | }) |
| 177 | } |
| 178 | |
| 179 | /// Audio streams declared in the header. |
| 180 | pub fn audio_streams(&self) -> &[AviAudioStream] { |
| 181 | &self.streams |
| 182 | } |
| 183 | |
| 184 | /// The `cbSize` tail of audio stream `i`'s WAVEFORMATEX (MS ADPCM's |
| 185 | /// coefficient table, IMA's samples per block), empty when it has none. |
| 186 | pub fn audio_extradata(&self, i: usize) -> &[u8] { |
| 187 | self.extras.get(i).map_or(&[], Vec::as_slice) |
| 188 | } |
| 189 | |
| 190 | /// True when the file supplied an AVI index this reader could use. |
| 191 | pub fn has_index(&self) -> bool { |
| 192 | !self.index.is_empty() |
| 193 | } |
| 194 | |
| 195 | /// Number of indexed audio chunks available for seeking. |
| 196 | pub fn index_len(&self) -> usize { |
| 197 | self.index.len() |
| 198 | } |
| 199 | |
| 200 | /// Return to the first chunk in `movi`. |
| 201 | pub fn rewind(&mut self) { |
| 202 | self.pos = self.movi_start; |
| 203 | self.pending.clear(); |
| 204 | } |
| 205 | |
| 206 | /// Seek an audio stream by its `strh` time units and return the landing unit. |
| 207 | pub fn seek_to_stream_time(&mut self, stream: u32, target: u64, after: bool) -> Result<u64> { |
| 208 | self.pending.clear(); |
| 209 | if let Some(point) = self.seek_point(stream, target, after) { |
| 210 | self.pos = point.offset; |
| 211 | return Ok(point.time); |
| 212 | } |
| 213 | let stream_info = self |
| 214 | .streams |
| 215 | .iter() |
| 216 | .find(|s| s.index == stream) |
| 217 | .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {stream}")))?; |
| 218 | let estimate = if stream_info.length > 0 { |
| 219 | let movi = self.movi_end.saturating_sub(self.movi_start); |
| 220 | self.movi_start.saturating_add( |
| 221 | movi.saturating_mul(target) |
| 222 | .saturating_div(u64::from(stream_info.length)), |
| 223 | ) |
| 224 | } else { |
| 225 | self.movi_start |
| 226 | }; |
| 227 | // Not `clamp`: it panics when the movi list is shorter than 8 bytes and the bounds cross. |
| 228 | let start = estimate |
| 229 | .min(self.movi_end.saturating_sub(8)) |
| 230 | .max(self.movi_start); |
| 231 | if let Some((offset, landed)) = self.scan_to_stream(stream, start, target)? { |
| 232 | self.pos = offset; |
| 233 | return Ok(landed); |
| 234 | } |
| 235 | self.pos = self.movi_end; |
| 236 | Ok(target) |
| 237 | } |
| 238 | |
| 239 | /// Return the indexed chunk this seek would select. |
| 240 | pub fn indexed_point(&self, stream: u32, target: u64, after: bool) -> Option<AviIndexPoint> { |
| 241 | let mut before = None; |
| 242 | let mut last = None; |
| 243 | for (index, point) in self.index.iter().filter(|point| point.stream == stream).enumerate() { |
| 244 | let point = AviIndexPoint { |
| 245 | index, |
| 246 | offset: point.offset, |
| 247 | time: point.time, |
| 248 | }; |
| 249 | if after { |
| 250 | if point.time >= target { |
| 251 | return Some(point); |
| 252 | } |
| 253 | last = Some(point); |
| 254 | } else if point.time <= target { |
| 255 | before = Some(point); |
| 256 | } else { |
| 257 | break; |
| 258 | } |
| 259 | } |
| 260 | if after { last } else { before } |
| 261 | } |
| 262 | |
| 263 | |
| 264 | fn seek_point(&self, stream: u32, target: u64, after: bool) -> Option<AviSeekPoint> { |
| 265 | let point = self.indexed_point(stream, target, after)?; |
| 266 | Some(AviSeekPoint { |
| 267 | stream, |
| 268 | offset: point.offset, |
| 269 | time: point.time, |
| 270 | }) |
| 271 | } |
| 272 | |
| 273 | /// The next audio chunk, or [`Error::Eof`] at the end. |
| 274 | pub fn next_packet(&mut self) -> Result<AviPacket> { |
| 275 | if let Some(packet) = self.pending.pop_front() { |
| 276 | return Ok(packet); |
| 277 | } |
| 278 | while self.pos + 8 <= self.movi_end { |
| 279 | self.inner.seek(SeekFrom::Start(self.pos))?; |
| 280 | let mut chunk = [0u8; 8]; |
| 281 | let got = read_some(&mut self.inner, &mut chunk)?; |
| 282 | if got == 0 || got < 8 { |
| 283 | self.pos = self.movi_end; |
| 284 | return Err(Error::Eof); |
| 285 | } |
| 286 | let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; |
| 287 | let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; |
| 288 | let data = self.pos + 8; |
| 289 | let padded = size.saturating_add(size & 1); |
| 290 | let next = data.saturating_add(padded); |
| 291 | if next > self.movi_end { |
| 292 | self.pos = self.movi_end; |
| 293 | return Err(Error::Eof); |
| 294 | } |
| 295 | self.pos = next; |
| 296 | if &id == b"LIST" { |
| 297 | if size >= 4 { |
| 298 | let mut kind = [0u8; 4]; |
| 299 | if read_some(&mut self.inner, &mut kind)? < 4 { |
| 300 | self.pos = self.movi_end; |
| 301 | return Err(Error::Eof); |
| 302 | } |
| 303 | if &kind == b"rec " { |
| 304 | self.queue_packets_in(data + 4, data + size, 0)?; |
| 305 | if let Some(packet) = self.pending.pop_front() { |
| 306 | return Ok(packet); |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | continue; |
| 311 | } |
| 312 | let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else { |
| 313 | continue; |
| 314 | }; |
| 315 | if !self.streams.iter().any(|s| s.index == stream) { |
| 316 | continue; |
| 317 | } |
| 318 | let data_buf = self.read_packet_body(data, size)?; |
| 319 | return Ok(AviPacket { |
| 320 | stream, |
| 321 | data: data_buf, |
| 322 | }); |
| 323 | } |
| 324 | Err(Error::Eof) |
| 325 | } |
| 326 | |
| 327 | fn queue_packets_in(&mut self, start: u64, end: u64, depth: usize) -> Result<()> { |
| 328 | // Each nested `rec ` list recurses once; cap it so a hostile file cannot exhaust the stack. |
| 329 | if depth > MAX_REC_DEPTH { |
| 330 | return Err(Error::corrupt("AVI rec lists nested too deeply")); |
| 331 | } |
| 332 | let mut pos = start; |
| 333 | while pos + 8 <= end { |
| 334 | self.inner.seek(SeekFrom::Start(pos))?; |
| 335 | let mut chunk = [0u8; 8]; |
| 336 | if read_some(&mut self.inner, &mut chunk)? < 8 { |
| 337 | break; |
| 338 | } |
| 339 | let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; |
| 340 | let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; |
| 341 | let data = pos + 8; |
| 342 | let next = data.saturating_add(size).saturating_add(size & 1); |
| 343 | if next > end { |
| 344 | break; |
| 345 | } |
| 346 | if &id == b"LIST" { |
| 347 | if size >= 4 { |
| 348 | let mut kind = [0u8; 4]; |
| 349 | if read_some(&mut self.inner, &mut kind)? < 4 { |
| 350 | break; |
| 351 | } |
| 352 | if &kind == b"rec " { |
| 353 | self.queue_packets_in(data + 4, data + size, depth + 1)?; |
| 354 | } |
| 355 | } |
| 356 | } else if let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") |
| 357 | && self.streams.iter().any(|s| s.index == stream) |
| 358 | { |
| 359 | let data_buf = self.read_packet_body(data, size)?; |
| 360 | self.pending.push_back(AviPacket { |
| 361 | stream, |
| 362 | data: data_buf, |
| 363 | }); |
| 364 | } |
| 365 | pos = next; |
| 366 | } |
| 367 | Ok(()) |
| 368 | } |
| 369 | |
| 370 | fn read_packet_body(&mut self, data: u64, size: u64) -> Result<Vec<u8>> { |
| 371 | let mut data_buf = vec![0u8; size as usize]; |
| 372 | self.inner.seek(SeekFrom::Start(data))?; |
| 373 | if read_some(&mut self.inner, &mut data_buf)? < data_buf.len() { |
| 374 | self.pos = self.movi_end; |
| 375 | return Err(Error::Eof); |
| 376 | } |
| 377 | Ok(data_buf) |
| 378 | } |
| 379 | |
| 380 | fn scan_to_stream( |
| 381 | &mut self, |
| 382 | stream: u32, |
| 383 | start: u64, |
| 384 | target: u64, |
| 385 | ) -> Result<Option<(u64, u64)>> { |
| 386 | let limit = self |
| 387 | .movi_end |
| 388 | .min(start.saturating_add(FALLBACK_SCAN as u64)); |
| 389 | let mut pos = start; |
| 390 | let mut buf = vec![0; 64 << 10]; |
| 391 | while pos + 8 <= limit { |
| 392 | self.inner.seek(SeekFrom::Start(pos))?; |
| 393 | let want = buf.len().min((limit - pos) as usize); |
| 394 | let got = read_some(&mut self.inner, &mut buf[..want])?; |
| 395 | if got < 8 { |
| 396 | break; |
| 397 | } |
| 398 | for at in 0..got - 7 { |
| 399 | let id = [buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]; |
| 400 | if stream_number(&id) != Some(stream) || &id[2..4] != b"wb" { |
| 401 | continue; |
| 402 | } |
| 403 | let size = |
| 404 | u32::from_le_bytes([buf[at + 4], buf[at + 5], buf[at + 6], buf[at + 7]]) as u64; |
| 405 | let offset = pos + at as u64; |
| 406 | if offset + 8 + size + (size & 1) <= self.movi_end { |
| 407 | return Ok(Some((offset, target))); |
| 408 | } |
| 409 | } |
| 410 | pos += got.saturating_sub(7) as u64; |
| 411 | } |
| 412 | Ok(None) |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | fn build_seek_points(streams: &[AviAudioStream], mut raw: Vec<RawIndexEntry>) -> Vec<AviSeekPoint> { |
| 417 | raw.sort_by_key(|e| e.offset); |
| 418 | let mut clocks = vec![0u64; streams.len()]; |
| 419 | let mut out = Vec::new(); |
| 420 | for e in raw { |
| 421 | let Some(i) = streams.iter().position(|s| s.index == e.stream) else { |
| 422 | continue; |
| 423 | }; |
| 424 | let time = clocks[i]; |
| 425 | clocks[i] = clocks[i].saturating_add(chunk_units(streams[i], u64::from(e.size))); |
| 426 | out.push(AviSeekPoint { |
| 427 | stream: e.stream, |
| 428 | offset: e.offset, |
| 429 | time, |
| 430 | }); |
| 431 | } |
| 432 | out |
| 433 | } |
| 434 | |
| 435 | fn chunk_units(stream: AviAudioStream, size: u64) -> u64 { |
| 436 | match stream.sample_size { |
| 437 | 0 => 1, |
| 438 | n => (size / u64::from(n)).max(u64::from(size > 0)), |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | fn parse_hdrl<R: Read + Seek>(inner: &mut R, start: u64, end: u64) -> Result<Hdrl> { |
| 443 | let mut hdrl = Hdrl::default(); |
| 444 | let mut stream_no = 0u32; |
| 445 | let mut pos = start; |
| 446 | while pos + 8 <= end { |
| 447 | inner.seek(SeekFrom::Start(pos))?; |
| 448 | let mut chunk = [0u8; 8]; |
| 449 | if read_some(inner, &mut chunk)? < 8 { |
| 450 | break; |
| 451 | } |
| 452 | let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; |
| 453 | let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; |
| 454 | let data = pos + 8; |
| 455 | let next = data.saturating_add(size).saturating_add(size & 1); |
| 456 | if &id == b"LIST" { |
| 457 | let mut kind = [0u8; 4]; |
| 458 | if size >= 4 && read_some(inner, &mut kind)? == 4 && &kind == b"strl" { |
| 459 | let parsed = parse_strl(inner, stream_no, data + 4, data + size)?; |
| 460 | if let Some(stream) = parsed.stream { |
| 461 | hdrl.streams.push(stream); |
| 462 | hdrl.extras.push(parsed.extra); |
| 463 | hdrl.odml.extend(parsed.odml); |
| 464 | } |
| 465 | stream_no += 1; |
| 466 | } |
| 467 | } |
| 468 | pos = next; |
| 469 | } |
| 470 | Ok(hdrl) |
| 471 | } |
| 472 | |
| 473 | #[derive(Default)] |
| 474 | struct Strl { |
| 475 | stream: Option<AviAudioStream>, |
| 476 | extra: Vec<u8>, |
| 477 | odml: Vec<OdmlRef>, |
| 478 | } |
| 479 | |
| 480 | #[derive(Clone, Copy)] |
| 481 | struct StreamTiming { |
| 482 | scale: u32, |
| 483 | rate: u32, |
| 484 | sample_size: u32, |
| 485 | length: u32, |
| 486 | } |
| 487 | |
| 488 | impl Default for StreamTiming { |
| 489 | fn default() -> Self { |
| 490 | StreamTiming { |
| 491 | scale: 1, |
| 492 | rate: 1, |
| 493 | sample_size: 0, |
| 494 | length: 0, |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | fn parse_strl<R: Read + Seek>(inner: &mut R, stream_no: u32, start: u64, end: u64) -> Result<Strl> { |
| 500 | let mut audio = false; |
| 501 | let mut fmt = None; |
| 502 | let mut timing = StreamTiming::default(); |
| 503 | let mut odml = Vec::new(); |
| 504 | let mut extra = Vec::new(); |
| 505 | let mut pos = start; |
| 506 | while pos + 8 <= end { |
| 507 | inner.seek(SeekFrom::Start(pos))?; |
| 508 | let mut chunk = [0u8; 8]; |
| 509 | if read_some(inner, &mut chunk)? < 8 { |
| 510 | break; |
| 511 | } |
| 512 | let id = [chunk[0], chunk[1], chunk[2], chunk[3]]; |
| 513 | let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; |
| 514 | let data = pos + 8; |
| 515 | let next = data.saturating_add(size).saturating_add(size & 1); |
| 516 | match &id { |
| 517 | b"strh" => { |
| 518 | let mut body = vec![0u8; size.min(64) as usize]; |
| 519 | read_full(inner, &mut body)?; |
| 520 | audio = body.get(0..4) == Some(&b"auds"[..]); |
| 521 | if body.len() >= 48 { |
| 522 | timing = StreamTiming { |
| 523 | scale: le_u32(&body, 20).filter(|n| *n > 0).unwrap_or(1), |
| 524 | rate: le_u32(&body, 24).filter(|n| *n > 0).unwrap_or(1), |
| 525 | length: le_u32(&body, 32).unwrap_or(0), |
| 526 | sample_size: le_u32(&body, 44).unwrap_or(0), |
| 527 | }; |
| 528 | } |
| 529 | } |
| 530 | b"strf" => { |
| 531 | let mut body = vec![0u8; size.min(18) as usize]; |
| 532 | read_full(inner, &mut body)?; |
| 533 | if body.len() >= 18 { |
| 534 | let cb = u64::from(u16::from_le_bytes([body[16], body[17]])) |
| 535 | .min(size.saturating_sub(18)) |
| 536 | .min(4096); |
| 537 | extra.resize(cb as usize, 0); |
| 538 | read_full(inner, &mut extra)?; |
| 539 | } |
| 540 | if body.len() >= 16 { |
| 541 | fmt = Some(AviAudioStream { |
| 542 | index: stream_no, |
| 543 | format_tag: u16::from_le_bytes([body[0], body[1]]), |
| 544 | channels: u16::from_le_bytes([body[2], body[3]]), |
| 545 | sample_rate: u32::from_le_bytes([body[4], body[5], body[6], body[7]]), |
| 546 | block_align: u16::from_le_bytes([body[12], body[13]]), |
| 547 | bits_per_sample: u16::from_le_bytes([body[14], body[15]]), |
| 548 | scale: timing.scale, |
| 549 | rate: timing.rate, |
| 550 | sample_size: timing.sample_size, |
| 551 | length: timing.length, |
| 552 | }); |
| 553 | } |
| 554 | } |
| 555 | b"indx" => { |
| 556 | let body = read_body(inner, size)?; |
| 557 | odml.extend(parse_indx_refs(&body)); |
| 558 | } |
| 559 | _ => {} |
| 560 | } |
| 561 | pos = next; |
| 562 | } |
| 563 | Ok(Strl { |
| 564 | stream: audio.then_some(fmt).flatten(), |
| 565 | extra, |
| 566 | odml, |
| 567 | }) |
| 568 | } |
| 569 | |
| 570 | fn parse_idx1_body(body: &[u8]) -> Vec<RawIndexEntry> { |
| 571 | let mut out = Vec::new(); |
| 572 | for entry in body.as_chunks::<16>().0.iter() { |
| 573 | let id = [entry[0], entry[1], entry[2], entry[3]]; |
| 574 | let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else { |
| 575 | continue; |
| 576 | }; |
| 577 | out.push(RawIndexEntry { |
| 578 | stream, |
| 579 | id, |
| 580 | offset: u64::from(u32::from_le_bytes([ |
| 581 | entry[8], entry[9], entry[10], entry[11], |
| 582 | ])), |
| 583 | size: u32::from_le_bytes([entry[12], entry[13], entry[14], entry[15]]), |
| 584 | }); |
| 585 | } |
| 586 | out |
| 587 | } |
| 588 | |
| 589 | fn resolve_idx1<R: Read + Seek>( |
| 590 | inner: &mut R, |
| 591 | movi_start: u64, |
| 592 | movi_end: u64, |
| 593 | streams: &[AviAudioStream], |
| 594 | entries: &[RawIndexEntry], |
| 595 | ) -> Result<Vec<RawIndexEntry>> { |
| 596 | let Some(first) = entries |
| 597 | .iter() |
| 598 | .find(|e| streams.iter().any(|s| s.index == e.stream)) |
| 599 | else { |
| 600 | return Ok(Vec::new()); |
| 601 | }; |
| 602 | let base = [0, movi_start, movi_start.saturating_sub(4)] |
| 603 | .into_iter() |
| 604 | .find(|base| { |
| 605 | chunk_matches(inner, base.saturating_add(first.offset), first.id, movi_end) |
| 606 | .unwrap_or(false) |
| 607 | }) |
| 608 | .unwrap_or(movi_start); |
| 609 | let mut out = Vec::new(); |
| 610 | for e in entries { |
| 611 | if !streams.iter().any(|s| s.index == e.stream) { |
| 612 | continue; |
| 613 | } |
| 614 | let offset = base.saturating_add(e.offset); |
| 615 | if chunk_matches(inner, offset, e.id, movi_end)? { |
| 616 | out.push(RawIndexEntry { offset, ..*e }); |
| 617 | } |
| 618 | } |
| 619 | Ok(out) |
| 620 | } |
| 621 | |
| 622 | fn parse_indx_refs(body: &[u8]) -> Vec<OdmlRef> { |
| 623 | if body.len() < 24 || body[3] != 0 { |
| 624 | return Vec::new(); |
| 625 | } |
| 626 | let entries = le_u32(body, 4).unwrap_or(0) as usize; |
| 627 | let mut out = Vec::new(); |
| 628 | let mut at = 24usize; |
| 629 | for _ in 0..entries { |
| 630 | if at + 16 > body.len() { |
| 631 | break; |
| 632 | } |
| 633 | let offset = le_u64(body, at).unwrap_or(0); |
| 634 | let size = le_u32(body, at + 8).unwrap_or(0); |
| 635 | if offset > 0 && size >= 24 { |
| 636 | out.push(OdmlRef { offset, size }); |
| 637 | } |
| 638 | at += 16; |
| 639 | } |
| 640 | out |
| 641 | } |
| 642 | |
| 643 | fn parse_odml_standard<R: Read + Seek>( |
| 644 | inner: &mut R, |
| 645 | index: OdmlRef, |
| 646 | streams: &[AviAudioStream], |
| 647 | movi_end: u64, |
| 648 | ) -> Result<Vec<RawIndexEntry>> { |
| 649 | if index.offset.saturating_add(8) > movi_end.saturating_add(1 << 30) { |
| 650 | return Ok(Vec::new()); |
| 651 | } |
| 652 | inner.seek(SeekFrom::Start(index.offset))?; |
| 653 | let mut head = [0; 8]; |
| 654 | if read_some(inner, &mut head)? < 8 { |
| 655 | return Ok(Vec::new()); |
| 656 | } |
| 657 | let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as u64; |
| 658 | let body = read_body(inner, size.min(u64::from(index.size)))?; |
| 659 | let raw = parse_standard_body(&body, streams); |
| 660 | raw.into_iter() |
| 661 | .filter_map(|e| resolve_standard_entry(inner, e, movi_end).transpose()) |
| 662 | .collect() |
| 663 | } |
| 664 | |
| 665 | fn parse_standard_body(body: &[u8], streams: &[AviAudioStream]) -> Vec<RawIndexEntry> { |
| 666 | if body.len() < 24 || body[3] != 1 { |
| 667 | return Vec::new(); |
| 668 | } |
| 669 | let longs = u16::from_le_bytes([body[0], body[1]]).max(2) as usize; |
| 670 | let entries = le_u32(body, 4).unwrap_or(0) as usize; |
| 671 | let id = [body[8], body[9], body[10], body[11]]; |
| 672 | let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else { |
| 673 | return Vec::new(); |
| 674 | }; |
| 675 | if !streams.is_empty() && !streams.iter().any(|s| s.index == stream) { |
| 676 | return Vec::new(); |
| 677 | } |
| 678 | let base = le_u64(body, 12).unwrap_or(0); |
| 679 | let step = longs * 4; |
| 680 | let mut at = 24usize; |
| 681 | let mut out = Vec::new(); |
| 682 | for _ in 0..entries { |
| 683 | if at + 8 > body.len() { |
| 684 | break; |
| 685 | } |
| 686 | out.push(RawIndexEntry { |
| 687 | stream, |
| 688 | id, |
| 689 | offset: base.saturating_add(u64::from(le_u32(body, at).unwrap_or(0))), |
| 690 | size: le_u32(body, at + 4).unwrap_or(0) & 0x7fff_ffff, |
| 691 | }); |
| 692 | at += step; |
| 693 | } |
| 694 | out |
| 695 | } |
| 696 | |
| 697 | fn resolve_standard_entry<R: Read + Seek>( |
| 698 | inner: &mut R, |
| 699 | entry: RawIndexEntry, |
| 700 | movi_end: u64, |
| 701 | ) -> Result<Option<RawIndexEntry>> { |
| 702 | for offset in [entry.offset, entry.offset.saturating_sub(8)] { |
| 703 | if chunk_matches(inner, offset, entry.id, movi_end)? { |
| 704 | return Ok(Some(RawIndexEntry { offset, ..entry })); |
| 705 | } |
| 706 | } |
| 707 | Ok(None) |
| 708 | } |
| 709 | |
| 710 | fn chunk_matches<R: Read + Seek>( |
| 711 | inner: &mut R, |
| 712 | offset: u64, |
| 713 | id: [u8; 4], |
| 714 | end: u64, |
| 715 | ) -> Result<bool> { |
| 716 | if offset.saturating_add(8) > end { |
| 717 | return Ok(false); |
| 718 | } |
| 719 | inner.seek(SeekFrom::Start(offset))?; |
| 720 | let mut head = [0; 8]; |
| 721 | if read_some(inner, &mut head)? < 8 { |
| 722 | return Ok(false); |
| 723 | } |
| 724 | let size = u64::from(u32::from_le_bytes([head[4], head[5], head[6], head[7]])); |
| 725 | Ok(head[0..4] == id && offset.saturating_add(8).saturating_add(size) <= end) |
| 726 | } |
| 727 | |
| 728 | fn stream_number(id: &[u8; 4]) -> Option<u32> { |
| 729 | let a = id[0].checked_sub(b'0')?; |
| 730 | let b = id[1].checked_sub(b'0')?; |
| 731 | (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b)) |
| 732 | } |
| 733 | |
| 734 | fn le_u32(data: &[u8], at: usize) -> Option<u32> { |
| 735 | Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?)) |
| 736 | } |
| 737 | |
| 738 | fn le_u64(data: &[u8], at: usize) -> Option<u64> { |
| 739 | Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?)) |
| 740 | } |
| 741 | |
| 742 | fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> { |
| 743 | let mut at = 0; |
| 744 | while at < buf.len() { |
| 745 | match r.read(&mut buf[at..]) { |
| 746 | Ok(0) => break, |
| 747 | Ok(n) => at += n, |
| 748 | Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} |
| 749 | Err(e) => return Err(Error::Io(e)), |
| 750 | } |
| 751 | } |
| 752 | Ok(at) |
| 753 | } |
| 754 | |
| 755 | fn read_full(r: &mut impl Read, buf: &mut [u8]) -> Result<()> { |
| 756 | if read_some(r, buf)? == buf.len() { |
| 757 | Ok(()) |
| 758 | } else { |
| 759 | Err(Error::corrupt("AVI header ends mid-field")) |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | /// Read a `size`-byte body. The buffer grows as bytes arrive, so a size field far past the end |
| 764 | /// of the file costs only what the file holds, never a `size`-byte allocation up front. |
| 765 | fn read_body(r: &mut impl Read, size: u64) -> Result<Vec<u8>> { |
| 766 | let mut body = Vec::new(); |
| 767 | r.by_ref().take(size).read_to_end(&mut body)?; |
| 768 | if body.len() as u64 != size { |
| 769 | return Err(Error::corrupt("AVI chunk body ends mid-field")); |
| 770 | } |
| 771 | Ok(body) |
| 772 | } |