forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

avi.rs736 lines, 23.4 KiBHistoryRawDownload
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
6use std::collections::VecDeque;
7use std::io::{Read, Seek, SeekFrom};
8
9use ec_core::{Error, Result};
10
11const FALLBACK_SCAN: usize = 4 << 20;
12
13/// One audio stream declared by an AVI file.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct AviAudioStream {
16 /// AVI stream number, the two decimal digits at the start of chunk ids.
17 pub index: u32,
18 /// WAVE format tag from this stream's `strf` body.
19 pub format_tag: u16,
20 /// Channel count stated by the WAVEFORMAT header.
21 pub channels: u16,
22 /// Samples per second stated by the WAVEFORMAT header.
23 pub sample_rate: u32,
24 /// Block alignment stated by the WAVEFORMAT header.
25 pub block_align: u16,
26 /// Bits per sample stated by the WAVEFORMAT header.
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,
36}
37
38/// One audio chunk from `movi`.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct AviPacket {
41 /// AVI stream number.
42 pub stream: u32,
43 /// Chunk payload.
44 pub data: Vec<u8>,
45}
46
47#[derive(Debug, Clone, Copy)]
48struct RawIndexEntry {
49 stream: u32,
50 id: [u8; 4],
51 offset: u64,
52 size: u32,
53}
54
55#[derive(Debug, Clone, Copy)]
56struct 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)]
63pub 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)]
74struct OdmlRef {
75 offset: u64,
76 size: u32,
77}
78
79#[derive(Debug, Default)]
80struct Hdrl {
81 streams: Vec<AviAudioStream>,
82 odml: Vec<OdmlRef>,
83}
84
85/// A reader over AVI audio chunks.
86pub struct AviReader<R> {
87 inner: R,
88 streams: Vec<AviAudioStream>,
89 movi_start: u64,
90 movi_end: u64,
91 pos: u64,
92 index: Vec<AviSeekPoint>,
93 pending: VecDeque<AviPacket>,
94}
95
96impl<R: Read + Seek> AviReader<R> {
97 /// Parse the RIFF/AVI headers, leaving the reader at the start of `movi`.
98 pub fn new(mut inner: R) -> Result<AviReader<R>> {
99 let end = inner.seek(SeekFrom::End(0))?;
100 inner.rewind()?;
101 let mut head = [0u8; 12];
102 read_full(&mut inner, &mut head)?;
103 if &head[0..4] != b"RIFF" || &head[8..12] != b"AVI " {
104 return Err(Error::corrupt("not a RIFF/AVI file"));
105 }
106
107 let mut hdrl = Hdrl::default();
108 let mut movi = None;
109 let mut idx1 = Vec::new();
110 let mut pos = 12u64;
111 while pos + 8 <= end {
112 inner.seek(SeekFrom::Start(pos))?;
113 let mut chunk = [0u8; 8];
114 let got = read_some(&mut inner, &mut chunk)?;
115 if got == 0 {
116 break;
117 }
118 if got < 8 {
119 return Err(Error::corrupt("AVI chunk header ends mid-field"));
120 }
121 let id = [chunk[0], chunk[1], chunk[2], chunk[3]];
122 let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64;
123 let data = pos + 8;
124 let next = data.saturating_add(size).saturating_add(size & 1);
125 if &id == b"LIST" {
126 let mut kind = [0u8; 4];
127 if size < 4 || read_some(&mut inner, &mut kind)? < 4 {
128 return Err(Error::corrupt("AVI LIST header ends mid-field"));
129 }
130 let body_start = data + 4;
131 let body_end = data.saturating_add(size).min(end);
132 match &kind {
133 b"hdrl" => hdrl = parse_hdrl(&mut inner, body_start, body_end)?,
134 b"movi" => movi = Some((body_start, body_end)),
135 _ => {}
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);
141 }
142 pos = next;
143 }
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);
164 Ok(AviReader {
165 inner,
166 streams: hdrl.streams,
167 movi_start: pos,
168 movi_end,
169 pos,
170 index,
171 pending: VecDeque::new(),
172 })
173 }
174
175 /// Audio streams declared in the header.
176 pub fn audio_streams(&self) -> &[AviAudioStream] {
177 &self.streams
178 }
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
260 /// The next audio chunk, or [`Error::Eof`] at the end.
261 pub fn next_packet(&mut self) -> Result<AviPacket> {
262 if let Some(packet) = self.pending.pop_front() {
263 return Ok(packet);
264 }
265 while self.pos + 8 <= self.movi_end {
266 self.inner.seek(SeekFrom::Start(self.pos))?;
267 let mut chunk = [0u8; 8];
268 let got = read_some(&mut self.inner, &mut chunk)?;
269 if got == 0 || got < 8 {
270 self.pos = self.movi_end;
271 return Err(Error::Eof);
272 }
273 let id = [chunk[0], chunk[1], chunk[2], chunk[3]];
274 let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64;
275 let data = self.pos + 8;
276 let padded = size.saturating_add(size & 1);
277 let next = data.saturating_add(padded);
278 if next > self.movi_end {
279 self.pos = self.movi_end;
280 return Err(Error::Eof);
281 }
282 self.pos = next;
283 if &id == b"LIST" {
284 if size >= 4 {
285 let mut kind = [0u8; 4];
286 if read_some(&mut self.inner, &mut kind)? < 4 {
287 self.pos = self.movi_end;
288 return Err(Error::Eof);
289 }
290 if &kind == b"rec " {
291 self.queue_packets_in(data + 4, data + size)?;
292 if let Some(packet) = self.pending.pop_front() {
293 return Ok(packet);
294 }
295 }
296 }
297 continue;
298 }
299 let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb") else {
300 continue;
301 };
302 if !self.streams.iter().any(|s| s.index == stream) {
303 continue;
304 }
305 let data_buf = self.read_packet_body(data, size)?;
306 return Ok(AviPacket {
307 stream,
308 data: data_buf,
309 });
310 }
311 Err(Error::Eof)
312 }
313
314 fn queue_packets_in(&mut self, start: u64, end: u64) -> Result<()> {
315 let mut pos = start;
316 while pos + 8 <= end {
317 self.inner.seek(SeekFrom::Start(pos))?;
318 let mut chunk = [0u8; 8];
319 if read_some(&mut self.inner, &mut chunk)? < 8 {
320 break;
321 }
322 let id = [chunk[0], chunk[1], chunk[2], chunk[3]];
323 let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64;
324 let data = pos + 8;
325 let next = data.saturating_add(size).saturating_add(size & 1);
326 if next > end {
327 break;
328 }
329 if &id == b"LIST" {
330 if size >= 4 {
331 let mut kind = [0u8; 4];
332 if read_some(&mut self.inner, &mut kind)? < 4 {
333 break;
334 }
335 if &kind == b"rec " {
336 self.queue_packets_in(data + 4, data + size)?;
337 }
338 }
339 } else if let Some(stream) = stream_number(&id).filter(|_| &id[2..4] == b"wb")
340 && self.streams.iter().any(|s| s.index == stream)
341 {
342 let data_buf = self.read_packet_body(data, size)?;
343 self.pending.push_back(AviPacket {
344 stream,
345 data: data_buf,
346 });
347 }
348 pos = next;
349 }
350 Ok(())
351 }
352
353 fn read_packet_body(&mut self, data: u64, size: u64) -> Result<Vec<u8>> {
354 let mut data_buf = vec![0u8; size as usize];
355 self.inner.seek(SeekFrom::Start(data))?;
356 if read_some(&mut self.inner, &mut data_buf)? < data_buf.len() {
357 self.pos = self.movi_end;
358 return Err(Error::Eof);
359 }
360 Ok(data_buf)
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
399fn 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
416}
417
418fn 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
425fn parse_hdrl<R: Read + Seek>(inner: &mut R, start: u64, end: u64) -> Result<Hdrl> {
426 let mut hdrl = Hdrl::default();
427 let mut stream_no = 0u32;
428 let mut pos = start;
429 while pos + 8 <= end {
430 inner.seek(SeekFrom::Start(pos))?;
431 let mut chunk = [0u8; 8];
432 if read_some(inner, &mut chunk)? < 8 {
433 break;
434 }
435 let id = [chunk[0], chunk[1], chunk[2], chunk[3]];
436 let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64;
437 let data = pos + 8;
438 let next = data.saturating_add(size).saturating_add(size & 1);
439 if &id == b"LIST" {
440 let mut kind = [0u8; 4];
441 if size >= 4 && read_some(inner, &mut kind)? == 4 && &kind == b"strl" {
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);
446 }
447 stream_no += 1;
448 }
449 }
450 pos = next;
451 }
452 Ok(hdrl)
453}
454
455#[derive(Default)]
456struct Strl {
457 stream: Option<AviAudioStream>,
458 odml: Vec<OdmlRef>,
459}
460
461#[derive(Clone, Copy)]
462struct StreamTiming {
463 scale: u32,
464 rate: u32,
465 sample_size: u32,
466 length: u32,
467}
468
469impl 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
480fn parse_strl<R: Read + Seek>(inner: &mut R, stream_no: u32, start: u64, end: u64) -> Result<Strl> {
481 let mut audio = false;
482 let mut fmt = None;
483 let mut timing = StreamTiming::default();
484 let mut odml = Vec::new();
485 let mut pos = start;
486 while pos + 8 <= end {
487 inner.seek(SeekFrom::Start(pos))?;
488 let mut chunk = [0u8; 8];
489 if read_some(inner, &mut chunk)? < 8 {
490 break;
491 }
492 let id = [chunk[0], chunk[1], chunk[2], chunk[3]];
493 let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64;
494 let data = pos + 8;
495 let next = data.saturating_add(size).saturating_add(size & 1);
496 match &id {
497 b"strh" => {
498 let mut body = vec![0u8; size.min(64) as usize];
499 read_full(inner, &mut body)?;
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 }
509 }
510 b"strf" => {
511 let mut body = vec![0u8; size.min(18) as usize];
512 read_full(inner, &mut body)?;
513 if body.len() >= 16 {
514 fmt = Some(AviAudioStream {
515 index: stream_no,
516 format_tag: u16::from_le_bytes([body[0], body[1]]),
517 channels: u16::from_le_bytes([body[2], body[3]]),
518 sample_rate: u32::from_le_bytes([body[4], body[5], body[6], body[7]]),
519 block_align: u16::from_le_bytes([body[12], body[13]]),
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,
525 });
526 }
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 }
533 _ => {}
534 }
535 pos = next;
536 }
537 Ok(Strl {
538 stream: audio.then_some(fmt).flatten(),
539 odml,
540 })
541}
542
543fn 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
562fn 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
595fn 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
616fn 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
640fn 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
672fn 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
685fn 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)
701}
702
703fn stream_number(id: &[u8; 4]) -> Option<u32> {
704 let a = id[0].checked_sub(b'0')?;
705 let b = id[1].checked_sub(b'0')?;
706 (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b))
707}
708
709fn le_u32(data: &[u8], at: usize) -> Option<u32> {
710 Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?))
711}
712
713fn le_u64(data: &[u8], at: usize) -> Option<u64> {
714 Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?))
715}
716
717fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
718 let mut at = 0;
719 while at < buf.len() {
720 match r.read(&mut buf[at..]) {
721 Ok(0) => break,
722 Ok(n) => at += n,
723 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
724 Err(e) => return Err(Error::Io(e)),
725 }
726 }
727 Ok(at)
728}
729
730fn read_full(r: &mut impl Read, buf: &mut [u8]) -> Result<()> {
731 if read_some(r, buf)? == buf.len() {
732 Ok(())
733 } else {
734 Err(Error::corrupt("AVI header ends mid-field"))
735 }
736}