forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

demux.rs1294 lines, 45.7 KiBHistoryRawDownload
1//! RIFF/AVI audio and video demuxer.
2//!
3//! [`AviDemuxer`] reads the stream headers (`strh`/`strf`/`vprp`/`indx`), builds a complete
4//! chunk table at open and then serves packets in file order through the family's
5//! [`Demuxer`] trait. The older, audio-only [`crate::AviReader`] is untouched.
6//!
7//! Index sources, in order of preference:
8//! 1. OpenDML: the `indx` super-index and its `ix##` standard indices (files over 1 GB are
9//! split into `RIFF AVI ` plus `RIFF AVIX` chunks and only this index spans them);
10//! 2. the legacy `idx1`;
11//! 3. a linear walk of every `movi` list (and `rec ` lists in them) when there is no index, or
12//! when the index names no chunk of any known stream. A truncated file ends at the last whole
13//! chunk.
14//!
15//! Timestamps. Every stream's time base is its `dwScale/dwRate`. A video packet's pts is its
16//! frame slot number: the n-th chunk of the stream is frame n, so a zero-size chunk (a dropped
17//! or repeated frame) emits no packet but still takes its slot and the following pts jumps.
18//! An audio stream with a fixed `dwSampleSize` counts samples (bytes / sample size); any other
19//! audio chunk is one unit. `dts == pts` always.
20//!
21//! Limit, B-frames: AVI has no per-packet timestamps. Packets come in decode order, so for an
22//! H.264 or MPEG-2 stream with B-frames the pts is the *decode-order slot*, not the true
23//! presentation time; only the decoder (POC / temporal reference) knows the display order.
24//! MPEG-4 Part 2 "packed bitstream" (a P-VOP and a B-VOP in one chunk, the B slot filled by a
25//! tiny N-VOP) is carried as is: `ec-mpeg4` unpacks it, and its pts is again the slot number.
26//!
27//! Keyframes come from the index (`AVIIF_KEYFRAME`, or the size's top bit in OpenDML). Without
28//! one the reader sniffs the packet: H.264 key means an IDR (or SPS) NAL precedes the first
29//! slice; MPEG-2 key means an I picture; MPEG-4 Part 2 key means an I-VOP. Audio and intra-only video (Mjpeg, ProRes) are
30//! always key.
31
32use std::collections::VecDeque;
33use std::io::{Read, Seek, SeekFrom};
34
35use crate::rawvideo;
36
37use ec_core::frame::{ChannelLayout, Interlace, SampleFormat};
38use ec_core::registry::{
39 AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, MediaType, Rotation,
40 SeekMode, StreamInfo, VideoParameters,
41};
42use ec_core::{Buf, Error, Packet, PacketFlags, Result, Rounding, TimeBase, Timestamp};
43
44/// Hard cap on chunks held in the table.
45const MAX_ENTRIES: usize = 1 << 24;
46/// Deepest `rec ` list nesting the scan walks.
47const MAX_REC_DEPTH: usize = 16;
48/// Largest header-chunk body kept in memory.
49const MAX_HEADER_BODY: u64 = 16 << 20;
50
51/// True when `head` (the first 12 bytes or more) starts an AVI file.
52pub fn is_avi(head: &[u8]) -> bool {
53 head.len() >= 12 && &head[0..4] == b"RIFF" && &head[8..12] == b"AVI "
54}
55
56/// Which index the chunk table came from.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum AviIndexKind {
59 /// OpenDML super-index and standard indices.
60 OpenDml,
61 /// Legacy `idx1`.
62 Idx1,
63 /// No usable index: the table was built by walking `movi`.
64 Scan,
65}
66
67/// What the file said about one `strl` stream, supported or not.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct AviTrackInfo {
70 /// AVI stream number (the two digits in chunk ids).
71 pub number: u32,
72 /// Audio or video; `None` for a stream type this reader does not carry (text, midi).
73 pub media: Option<MediaType>,
74 /// Video: `biCompression` (or the `strh` handler when that is zero). Audio: `wFormatTag`
75 /// in the first two bytes. Zero when unknown.
76 pub tag: [u8; 4],
77 /// Index in [`AviDemuxer::streams`], or `None` when the stream is refused.
78 pub stream: Option<u32>,
79 /// Why the stream is refused, by name.
80 pub unsupported: Option<String>,
81}
82
83#[derive(Debug, Clone, Copy)]
84struct Entry {
85 track: u32,
86 /// File offset of the chunk header.
87 offset: u64,
88 size: u32,
89 key: bool,
90 /// Stream units at the chunk start.
91 pts: i64,
92 units: u32,
93}
94
95struct Track {
96 info: AviTrackInfo,
97 time_base: TimeBase,
98 sample_size: u32,
99 video_codec: Option<CodecId>,
100 field_order: Option<Interlace>,
101 /// Entry indices of this track in file order.
102 idxs: Vec<u32>,
103 cursor: usize,
104 /// DV type-1 (`iavs`) stream: the audio streams split out of each frame chunk.
105 dv: Option<DvTrack>,
106}
107
108#[derive(Default)]
109struct DvTrack {
110 /// `(stream index, DIF stereo pair)` for every audio stream split off this track.
111 audio: Vec<(u32, usize)>,
112 next_audio_pts: i64,
113}
114
115/// A demuxer over an AVI file: audio and video.
116pub struct AviDemuxer<R> {
117 inner: R,
118 streams: Vec<StreamInfo>,
119 tracks: Vec<Track>,
120 entries: Vec<Entry>,
121 kind: AviIndexKind,
122 pending: VecDeque<Packet>,
123}
124
125struct Strl {
126 handler: [u8; 4],
127 kind: [u8; 4],
128 scale: u32,
129 rate: u32,
130 length: u32,
131 sample_size: u32,
132 strf: Vec<u8>,
133 indx: Vec<u8>,
134 vprp: Option<Interlace>,
135 progressive_vprp: bool,
136}
137
138struct Raw {
139 number: u32,
140 id: [u8; 4],
141 offset: u64,
142 size: u32,
143 key: bool,
144}
145
146impl<R: Read + Seek> AviDemuxer<R> {
147 /// Parse the headers and build the chunk table.
148 pub fn new(mut inner: R) -> Result<AviDemuxer<R>> {
149 let end = inner.seek(SeekFrom::End(0))?;
150 inner.rewind()?;
151 let mut head = [0u8; 12];
152 read_full(&mut inner, &mut head)?;
153 if !is_avi(&head) {
154 return Err(Error::corrupt("not a RIFF/AVI file"));
155 }
156 let mut strls: Vec<Strl> = Vec::new();
157 let mut total_frames = 0u32;
158 let mut movis: Vec<(u64, u64)> = Vec::new();
159 let mut idx1: Vec<u8> = Vec::new();
160 let mut pos = 12u64;
161 while pos + 8 <= end {
162 let Some((id, size)) = chunk_head(&mut inner, pos)? else {
163 break;
164 };
165 let data = pos + 8;
166 let next = data.saturating_add(size).saturating_add(size & 1);
167 match &id {
168 // A second RIFF (AVIX) is walked flat: its children follow its form type.
169 b"RIFF" => {
170 pos = data + 4;
171 continue;
172 }
173 b"LIST" => {
174 let mut kind = [0u8; 4];
175 if size >= 4 && read_some(&mut inner, &mut kind)? == 4 {
176 let body = data + 4;
177 let body_end = data.saturating_add(size).min(end);
178 match &kind {
179 b"hdrl" => parse_hdrl(
180 &mut inner,
181 body,
182 body_end,
183 &mut strls,
184 &mut total_frames,
185 )?,
186 b"movi" => movis.push((body, body_end)),
187 _ => {}
188 }
189 }
190 }
191 b"idx1" if idx1.is_empty() => {
192 let n = size.min(end.saturating_sub(data));
193 idx1 = read_body(&mut inner, n)?;
194 }
195 _ => {}
196 }
197 pos = next;
198 }
199 if movis.is_empty() {
200 return Err(Error::corrupt("AVI: no movi list"));
201 }
202
203 // Streams and tracks.
204 let mut tracks: Vec<Track> = Vec::new();
205 let mut streams: Vec<StreamInfo> = Vec::new();
206 let mut first_refusal: Option<String> = None;
207 for (number, s) in strls.iter().enumerate() {
208 let number = number as u32;
209 let (info, params, time_base, codec, field_order) = describe(number, s);
210 let mut info = info;
211 if let Some(p) = params {
212 let index = streams.len() as u32;
213 info.stream = Some(index);
214 streams.push(StreamInfo {
215 index,
216 time_base,
217 params: p,
218 start_time: Some(0),
219 duration: (s.length > 0).then_some(i64::from(s.length)),
220 language: None,
221 initial_padding: 0,
222 default: false,
223 rotation: Rotation::None,
224 });
225 } else if first_refusal.is_none() {
226 first_refusal = info.unsupported.clone();
227 }
228 tracks.push(Track {
229 info,
230 time_base,
231 sample_size: s.sample_size,
232 video_codec: codec,
233 field_order,
234 idxs: Vec::new(),
235 cursor: 0,
236 dv: (&s.kind == b"iavs").then(DvTrack::default),
237 });
238 }
239 if streams.is_empty() {
240 return Err(Error::unsupported(
241 first_refusal.unwrap_or_else(|| "AVI without audio or video streams".into()),
242 "ec-riff carries the audio and video streams it has a codec id for",
243 ));
244 }
245
246 // Index.
247 let movi0 = movis[0].0;
248 let mut raw: Vec<Raw> = Vec::new();
249 let mut kind = AviIndexKind::Scan;
250 let mut odml: Vec<Raw> = Vec::new();
251 for (n, s) in strls.iter().enumerate() {
252 if !s.indx.is_empty() {
253 odml.extend(read_odml(&mut inner, &s.indx, n as u32, end)?);
254 }
255 }
256 if has_known(&odml, &tracks) {
257 raw = odml;
258 kind = AviIndexKind::OpenDml;
259 } else if !idx1.is_empty() {
260 let legacy = resolve_idx1(&mut inner, movi0, end, &tracks, &idx1)?;
261 if has_known(&legacy, &tracks) {
262 raw = legacy;
263 kind = AviIndexKind::Idx1;
264 }
265 }
266 if kind == AviIndexKind::Scan {
267 for &(start, stop) in &movis {
268 scan_range(&mut inner, start, stop, &tracks, &mut raw, 0)?;
269 }
270 }
271 let sniff = kind == AviIndexKind::Scan;
272
273 // Chunk table: file order, deduplicated, with per-stream clocks.
274 raw.retain(|r| {
275 tracks
276 .get(r.number as usize)
277 .is_some_and(|t| t.info.stream.is_some())
278 && r.offset.saturating_add(8).saturating_add(u64::from(r.size)) <= end
279 });
280 raw.sort_by_key(|r| r.offset);
281 raw.dedup_by_key(|r| r.offset);
282 if raw.len() > MAX_ENTRIES {
283 return Err(Error::corrupt("AVI: too many chunks"));
284 }
285 let mut clocks = vec![0i64; tracks.len()];
286 let mut entries = Vec::with_capacity(raw.len());
287 for r in &raw {
288 let t = r.number as usize;
289 let video = tracks[t].video_codec.is_some();
290 // A zero-size video chunk is a dropped frame and keeps its slot; an empty audio chunk
291 // (ffmpeg pads B-frame interleave with them) is not an audio frame at all.
292 let units = match tracks[t].sample_size {
293 _ if r.size == 0 && !video => 0u32,
294 0 => 1u32,
295 n if !video => r.size / n,
296 _ => 1,
297 };
298 let mut key = r.key;
299 match tracks[t].video_codec {
300 None
301 | Some(CodecId::Mjpeg | CodecId::ProRes | CodecId::DvVideo | CodecId::RawVideo) => {
302 key = true
303 }
304 Some(codec) if sniff && r.size > 0 => {
305 key = sniff_key(&mut inner, codec, r.offset + 8, r.size)?;
306 }
307 _ => {}
308 }
309 let idx = entries.len() as u32;
310 entries.push(Entry {
311 track: r.number,
312 offset: r.offset,
313 size: r.size,
314 key,
315 pts: clocks[t],
316 units,
317 });
318 clocks[t] += i64::from(units);
319 tracks[t].idxs.push(idx);
320 }
321 // Duration: the frame count the index shows (OpenDML `dmlh` for the first video).
322 for (t, track) in tracks.iter().enumerate() {
323 if let Some(si) = track.info.stream {
324 let mut d = clocks[t];
325 if d == 0 {
326 d = streams[si as usize].duration.unwrap_or(0);
327 }
328 if track.video_codec.is_some() && total_frames > 0 && kind == AviIndexKind::OpenDml
329 {
330 d = d.max(i64::from(total_frames));
331 }
332 streams[si as usize].duration = (d > 0).then_some(d);
333 }
334 }
335 // DV type-1: the first frame names the picture and the audio pairs.
336 for track in tracks.iter_mut() {
337 let Some(si) = track.info.stream else {
338 continue;
339 };
340 if track.dv.is_none() {
341 continue;
342 }
343 let first = track
344 .idxs
345 .iter()
346 .map(|&i| entries[i as usize])
347 .find(|e| e.size > 0);
348 let Some(e) = first else { continue };
349 inner.seek(SeekFrom::Start(e.offset + 8))?;
350 let mut data = vec![0u8; e.size as usize];
351 if read_some(&mut inner, &mut data)? < data.len() {
352 continue;
353 }
354 let Some(sys) = ec_dv::frame_profile(None, &data) else {
355 continue;
356 };
357 if let MediaParameters::Video(v) = &mut streams[si as usize].params.media {
358 v.width = sys.width;
359 v.height = sys.height;
360 v.format = Some(ec_dv::output_format(sys.chroma));
361 v.sample_aspect_ratio = Some(TimeBase::new(
362 i64::from(sys.sar[0].0),
363 i64::from(sys.sar[0].1),
364 ));
365 }
366 if let Some(a) = ec_dv::extract_audio(&data) {
367 for pair in 0..a.pairs.len() {
368 let mut ap = CodecParameters::new(CodecId::PcmS16Le);
369 ap.media = MediaParameters::Audio(AudioParameters {
370 sample_rate: a.sample_rate,
371 layout: ChannelLayout::Stereo,
372 format: Some(SampleFormat::S16),
373 bits_per_sample: Some(16),
374 });
375 let index = streams.len() as u32;
376 let mut st = StreamInfo::new(index, TimeBase::from_rate(a.sample_rate), ap);
377 st.start_time = Some(0);
378 streams.push(st);
379 if let Some(dv) = &mut track.dv {
380 dv.audio.push((index, pair));
381 }
382 }
383 }
384 }
385 Ok(AviDemuxer {
386 inner,
387 streams,
388 tracks,
389 entries,
390 kind,
391 pending: VecDeque::new(),
392 })
393 }
394
395 /// Every stream the file declared, including the refused ones.
396 pub fn tracks(&self) -> Vec<AviTrackInfo> {
397 self.tracks.iter().map(|t| t.info.clone()).collect()
398 }
399
400 /// Scan order for `stream`: the interlace the file states. [`Interlace::BottomFieldFirst`]
401 /// for every Mjpeg stream (ffmpeg's convention for AVI: the first JPEG of a two-field
402 /// packet holds the bottom lines; harmless for progressive packets). Otherwise from the
403 /// `vprp` header: [`Interlace::Progressive`] for one field per frame, the field with the
404 /// smaller `VideoYValidStartLine` first for two. `None` where the file states nothing.
405 pub fn field_order(&self, stream: u32) -> Option<Interlace> {
406 self.tracks
407 .iter()
408 .find(|t| t.info.stream == Some(stream))
409 .and_then(|t| t.field_order)
410 }
411
412 /// Where the chunk table came from.
413 pub fn index_kind(&self) -> AviIndexKind {
414 self.kind
415 }
416
417 /// Chunks (zero-size ones included) of `stream`.
418 pub fn chunk_count(&self, stream: u32) -> usize {
419 self.tracks
420 .iter()
421 .find(|t| t.info.stream == Some(stream))
422 .map_or(0, |t| t.idxs.len())
423 }
424
425 /// Back to the first packet of every stream.
426 pub fn rewind(&mut self) {
427 self.pending.clear();
428 for t in &mut self.tracks {
429 t.cursor = 0;
430 if let Some(dv) = &mut t.dv {
431 dv.next_audio_pts = 0;
432 }
433 }
434 }
435
436 /// Seek `stream` as [`Demuxer::seek`] and return the instant it landed on (the chosen
437 /// packet's pts, in that stream's time base). Other streams resume at the same instant.
438 pub fn seek_stream(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<Timestamp> {
439 let Some(ti) = self.tracks.iter().position(|t| {
440 t.info.stream == Some(stream)
441 || t.dv
442 .as_ref()
443 .is_some_and(|d| d.audio.iter().any(|a| a.0 == stream))
444 }) else {
445 return Err(Error::corrupt(format!("avi: no stream {stream} to seek")));
446 };
447 self.pending.clear();
448 if let Some(dv) = &mut self.tracks[ti].dv {
449 dv.next_audio_pts = 0;
450 }
451 let tb = self.tracks[ti].time_base;
452 let target = to.rescale(tb, Rounding::Nearest).ticks;
453 let entries = &self.entries;
454 let idxs = &self.tracks[ti].idxs;
455 if idxs.is_empty() {
456 return Err(Error::Eof);
457 }
458 let mut at = idxs
459 .partition_point(|&i| entries[i as usize].pts <= target)
460 .saturating_sub(1);
461 match mode {
462 SeekMode::Exact => {}
463 SeekMode::SyncBefore => {
464 while at > 0 && !entries[idxs[at] as usize].key {
465 at -= 1;
466 }
467 }
468 SeekMode::SyncAfter => {
469 while at + 1 < idxs.len() && !entries[idxs[at] as usize].key {
470 at += 1;
471 }
472 }
473 }
474 let landed = Timestamp::new(entries[idxs[at] as usize].pts, tb);
475 self.tracks[ti].cursor = at;
476 for j in 0..self.tracks.len() {
477 if j == ti {
478 continue;
479 }
480 let want = landed
481 .rescale(self.tracks[j].time_base, Rounding::Nearest)
482 .ticks;
483 let entries = &self.entries;
484 let t = &mut self.tracks[j];
485 t.cursor = t.idxs.partition_point(|&i| entries[i as usize].pts < want);
486 }
487 Ok(landed)
488 }
489
490 fn read_next(&mut self) -> Result<Packet> {
491 if let Some(p) = self.pending.pop_front() {
492 return Ok(p);
493 }
494 loop {
495 let mut pick: Option<(usize, u64)> = None;
496 for (i, t) in self.tracks.iter_mut().enumerate() {
497 // Zero-size chunks are dropped frames: they hold a slot but yield no packet.
498 while let Some(&e) = t.idxs.get(t.cursor) {
499 if self.entries[e as usize].size == 0 {
500 t.cursor += 1;
501 } else {
502 break;
503 }
504 }
505 if let Some(&e) = t.idxs.get(t.cursor) {
506 let off = self.entries[e as usize].offset;
507 if pick.is_none_or(|(_, best)| off < best) {
508 pick = Some((i, off));
509 }
510 }
511 }
512 let Some((ti, _)) = pick else {
513 return Err(Error::Eof);
514 };
515 let e = self.entries[self.tracks[ti].idxs[self.tracks[ti].cursor] as usize];
516 self.tracks[ti].cursor += 1;
517 self.inner.seek(SeekFrom::Start(e.offset))?;
518 let mut head = [0u8; 8];
519 if read_some(&mut self.inner, &mut head)? < 8 {
520 return Err(Error::Eof);
521 }
522 let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]);
523 // A stale index entry (id or size not matching the chunk): skip it.
524 if stream_number(&[head[0], head[1], head[2], head[3]]) != Some(e.track)
525 || size != e.size
526 {
527 continue;
528 }
529 let mut data = vec![0u8; e.size as usize];
530 if read_some(&mut self.inner, &mut data)? < data.len() {
531 return Err(Error::Eof);
532 }
533 let stream = self.tracks[ti].info.stream.unwrap_or(0);
534 let vtb = self.tracks[ti].time_base;
535 if let Some(dv) = &mut self.tracks[ti].dv
536 && let Some(a) = ec_dv::extract_audio(&data)
537 {
538 {
539 // Same clock rule as the raw DV demuxer: follow the video unless the audio
540 // runs within a frame of it.
541 let tb = TimeBase::from_rate(a.sample_rate);
542 let dur = a.samples as i64;
543 let vpts = vtb.rescale(e.pts, tb, Rounding::Nearest);
544 let pts = if (vpts - dv.next_audio_pts).abs() >= dur {
545 vpts
546 } else {
547 dv.next_audio_pts
548 };
549 dv.next_audio_pts = pts + dur;
550 for &(si, pair) in &dv.audio {
551 let Some(pcm) = a.pairs.get(pair).filter(|p| !p.is_empty()) else {
552 continue;
553 };
554 let mut bytes = Vec::with_capacity(pcm.len() * 2);
555 for s in pcm {
556 bytes.extend_from_slice(&s.to_le_bytes());
557 }
558 let mut ap = Packet::new(si, tb, Buf::from(bytes));
559 ap.pts = Some(pts);
560 ap.dts = Some(pts);
561 ap.duration = Some(dur);
562 ap.flags = PacketFlags {
563 keyframe: true,
564 ..PacketFlags::default()
565 };
566 self.pending.push_back(ap);
567 }
568 }
569 }
570 let mut p = Packet::new(stream, self.tracks[ti].time_base, Buf::from(data));
571 p.pts = Some(e.pts);
572 p.dts = Some(e.pts);
573 p.duration = Some(i64::from(e.units));
574 p.flags = PacketFlags {
575 keyframe: e.key,
576 ..PacketFlags::default()
577 };
578 return Ok(p);
579 }
580 }
581}
582
583impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> {
584 fn streams(&self) -> &[StreamInfo] {
585 &self.streams
586 }
587
588 fn next_packet(&mut self) -> Result<Packet> {
589 self.read_next()
590 }
591
592 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
593 self.seek_stream(stream, to, mode).map(|_| ())
594 }
595}
596
597// ---------------------------------------------------------------------------------------------
598// Stream description
599
600type Described = (
601 AviTrackInfo,
602 Option<CodecParameters>,
603 TimeBase,
604 Option<CodecId>,
605 Option<Interlace>,
606);
607
608fn describe(number: u32, s: &Strl) -> Described {
609 let scale = i64::from(s.scale.max(1));
610 let rate = i64::from(s.rate.max(1));
611 let mut info = AviTrackInfo {
612 number,
613 media: None,
614 tag: [0; 4],
615 stream: None,
616 unsupported: None,
617 };
618 let mut tb = TimeBase::new(scale, rate);
619 match &s.kind {
620 b"vids" => {
621 info.media = Some(MediaType::Video);
622 let f = &s.strf;
623 if f.len() < 40 {
624 info.unsupported = Some("video stream with a short BITMAPINFOHEADER".into());
625 return (info, None, tb, None, None);
626 }
627 let width = le_u32(f, 4).unwrap_or(0);
628 let height = (le_u32(f, 8).unwrap_or(0) as i32).unsigned_abs();
629 let bits = u16::from_le_bytes([f[14], f[15]]);
630 let comp = [f[16], f[17], f[18], f[19]];
631 info.tag = if comp == [0; 4] { s.handler } else { comp };
632 let codec = match map_video(&comp, bits) {
633 Ok(c) => Ok(c),
634 // biCompression unknown: some muxers only fill the `strh` handler.
635 Err(e) => map_video(&s.handler, bits).map_err(|_| e),
636 };
637 if s.scale == 0 || s.rate == 0 {
638 tb = TimeBase::new(1, 25);
639 }
640 match codec {
641 Ok(codec) => {
642 let mut p = CodecParameters::new(codec);
643 if let MediaParameters::Video(v) = &mut p.media {
644 let VideoParameters {
645 width: w,
646 height: h,
647 frame_rate,
648 ..
649 } = v;
650 *w = width;
651 *h = height;
652 *frame_rate = Some(TimeBase::new(tb.den(), tb.num()));
653 }
654 let bih = le_u32(f, 0).unwrap_or(40) as usize;
655 if codec == CodecId::RawVideo {
656 let signed = le_u32(f, 8).unwrap_or(0) as i32;
657 let Some(layout) = rawvideo::layout_of(&comp, bits, signed) else {
658 info.unsupported = Some(format!(
659 "uncompressed video (FourCC '{}', {bits} bpp): raw layout not carried",
660 fourcc_str(&comp)
661 ));
662 return (info, None, tb, None, None);
663 };
664 if let MediaParameters::Video(v) = &mut p.media {
665 v.format = Some(layout.format());
666 }
667 let keep = if bits == 8 {
668 (40 + 4 * 256).min(f.len())
669 } else {
670 40
671 };
672 p.extradata = Some(Buf::from(&f[..keep]));
673 } else if f.len() > bih.max(40) && codec != CodecId::Mjpeg {
674 p.extradata = Some(Buf::from(&f[bih.max(40)..]));
675 }
676 let fo = if codec == CodecId::Mjpeg {
677 Some(Interlace::BottomFieldFirst)
678 } else if s.progressive_vprp {
679 Some(Interlace::Progressive)
680 } else {
681 s.vprp
682 };
683 (info, Some(p), tb, Some(codec), fo)
684 }
685 Err(why) => {
686 info.unsupported = Some(why.to_string());
687 (info, None, tb, None, None)
688 }
689 }
690 }
691 b"auds" => {
692 info.media = Some(MediaType::Audio);
693 if s.scale == 0 || s.rate == 0 {
694 tb = TimeBase::new(1, i64::from(le_u32(&s.strf, 4).unwrap_or(0).max(1)));
695 }
696 match map_audio(&s.strf) {
697 Ok((tag, p)) => {
698 info.tag = [tag as u8, (tag >> 8) as u8, 0, 0];
699 (info, Some(p), tb, None, None)
700 }
701 Err((tag, why)) => {
702 info.tag = [tag as u8, (tag >> 8) as u8, 0, 0];
703 info.unsupported = Some(why);
704 (info, None, tb, None, None)
705 }
706 }
707 }
708 b"iavs" => {
709 // DV type-1: whole DV frames; the picture size and the audio pairs come from the
710 // first frame once the chunk table exists.
711 info.media = Some(MediaType::Video);
712 info.tag = s.handler;
713 if s.scale == 0 || s.rate == 0 {
714 tb = TimeBase::new(1001, 30000);
715 }
716 let mut p = CodecParameters::new(CodecId::DvVideo);
717 if let MediaParameters::Video(v) = &mut p.media {
718 v.frame_rate = Some(TimeBase::new(tb.den(), tb.num()));
719 }
720 (info, Some(p), tb, Some(CodecId::DvVideo), None)
721 }
722 other => {
723 info.unsupported = Some(format!(
724 "AVI stream type '{}'",
725 String::from_utf8_lossy(other)
726 ));
727 (info, None, tb, None, None)
728 }
729 }
730}
731
732fn fourcc_str(c: &[u8; 4]) -> String {
733 c.iter()
734 .map(|&b| {
735 if (0x20..0x7f).contains(&b) {
736 b as char
737 } else {
738 '?'
739 }
740 })
741 .collect()
742}
743
744/// Video FourCC to codec id. `Err` names the refusal.
745fn map_video(c: &[u8; 4], bits: u16) -> std::result::Result<CodecId, String> {
746 let up: Vec<u8> = c.iter().map(|b| b.to_ascii_uppercase()).collect();
747 let name = fourcc_str(c);
748 Ok(match (&up[..], &c[..]) {
749 (b"MJPG" | b"JPEG" | b"DMB1" | b"AVRN" | b"AVDJ" | b"MJPA" | b"IJPG", _) => CodecId::Mjpeg,
750 (b"H264" | b"X264" | b"AVC1" | b"DAVC" | b"VSSH" | b"HD10", _) => CodecId::H264,
751 (b"MPG2" | b"MPEG" | b"MPG1" | b"MP2V" | b"M2V1" | b"HDV1" | b"HDV2", _) => {
752 CodecId::Mpeg2Video
753 }
754 (_, b"apco" | b"apcs" | b"apcn" | b"apch" | b"ap4h" | b"ap4x") => CodecId::ProRes,
755 (b"AVDN" | b"AVDH", _) => CodecId::Dnxhd,
756 (
757 b"XVID" | b"XVIX" | b"DIVX" | b"DX50" | b"FMP4" | b"MP4V" | b"M4S2" | b"MP4S" | b"RMP4"
758 | b"DVX1" | b"BLZ0" | b"UMP4",
759 _,
760 ) => CodecId::Mpeg4Part2,
761 (b"MPG4" | b"DIV1", _) => CodecId::MsMpeg4V1,
762 (b"MP42" | b"DIV2" | b"MP41", _) => CodecId::MsMpeg4V2,
763 (
764 b"DIV3" | b"MP43" | b"DIV4" | b"DIV5" | b"DIV6" | b"AP41" | b"COL1" | b"COL0" | b"3IVD",
765 _,
766 ) => CodecId::MsMpeg4V3,
767 (b"3IV2" | b"SEDG", _) => {
768 return Err(format!(
769 "MPEG-4 variant video (FourCC '{name}'): no decoder"
770 ));
771 }
772 (
773 b"DVSD" | b"DV25" | b"DVH1" | b"DVHD" | b"DVSL" | b"DV50" | b"DVC " | b"CDVC" | b"DVCS"
774 | b"DVPP",
775 _,
776 ) => CodecId::DvVideo,
777 (
778 b"YUY2" | b"YUYV" | b"YUV2" | b"V422" | b"UYVY" | b"2VUY" | b"I420" | b"IYUV" | b"YV12"
779 | b"YVYU" | b"NV12" | b"Y800" | b"Y8 " | b"GREY" | b"V210",
780 _,
781 ) => CodecId::RawVideo,
782 (_, [0, 0, 0, 0]) | (b"RGB " | b"BGR " | b"RAW ", _)
783 if matches!(bits, 8 | 15 | 16 | 24 | 32) =>
784 {
785 CodecId::RawVideo
786 }
787 (_, [0, 0, 0, 0]) => {
788 return Err(format!(
789 "uncompressed DIB video ({bits} bpp): raw layout is not carried"
790 ));
791 }
792 (b"RGB " | b"BGR " | b"RAW ", _) => {
793 return Err(format!(
794 "uncompressed video (FourCC '{name}'): raw video is not carried"
795 ));
796 }
797 _ => return Err(format!("video FourCC '{name}'")),
798 })
799}
800
801/// Audio `strf` to parameters. `Err` carries the tag and a reason.
802fn map_audio(f: &[u8]) -> std::result::Result<(u16, CodecParameters), (u16, String)> {
803 if f.len() < 16 {
804 return Err((0, "audio stream with a short WAVEFORMAT".into()));
805 }
806 let mut tag = u16::from_le_bytes([f[0], f[1]]);
807 let channels = u16::from_le_bytes([f[2], f[3]]);
808 let sample_rate = le_u32(f, 4).unwrap_or(0);
809 let bits = u16::from_le_bytes([f[14], f[15]]);
810 let cb = if f.len() >= 18 {
811 usize::from(u16::from_le_bytes([f[16], f[17]]))
812 } else {
813 0
814 };
815 let extra = f
816 .get(18..18 + cb.min(f.len().saturating_sub(18)))
817 .unwrap_or(&[]);
818 if tag == 0xFFFE && extra.len() >= 22 {
819 tag = u16::from_le_bytes([extra[8], extra[9]]);
820 }
821 if channels == 0 || sample_rate == 0 {
822 return Err((
823 tag,
824 format!("audio tag {tag:#06x} with zero channels or rate"),
825 ));
826 }
827 let (codec, format, depth) = match (tag, bits) {
828 (1, 8) => (CodecId::PcmU8, Some(SampleFormat::U8), Some(8)),
829 (1, 16) => (CodecId::PcmS16Le, Some(SampleFormat::S16), Some(16)),
830 (1, 24) => (CodecId::PcmS24Le, Some(SampleFormat::S32), Some(24)),
831 (1, 32) => (CodecId::PcmS32Le, Some(SampleFormat::S32), Some(32)),
832 (3, 32) => (CodecId::PcmF32Le, Some(SampleFormat::F32), Some(32)),
833 (0x0011 | 0x0002 | 0x0006 | 0x0007, _) => (
834 crate::WavCompressed::codec_of(tag).unwrap_or(CodecId::PcmAlaw),
835 Some(SampleFormat::S16),
836 Some(16),
837 ),
838 (0x50, _) => (CodecId::Mp2, None, None),
839 (0x55, _) => (CodecId::Mp3, None, None),
840 (0x2000, _) => (CodecId::Ac3, None, None),
841 (0x2001, _) => (CodecId::Dts, None, None),
842 (0xFF | 0x706D, _) => (CodecId::Aac, None, None),
843 _ => {
844 return Err((tag, format!("audio format tag {tag:#06x} ({bits}-bit)")));
845 }
846 };
847 let mut p = CodecParameters::new(codec);
848 p.media = MediaParameters::Audio(AudioParameters {
849 sample_rate,
850 layout: ChannelLayout::from_count(usize::from(channels)),
851 format,
852 bits_per_sample: depth,
853 });
854 if (codec == CodecId::Aac || crate::WavCompressed::codec_of(tag).is_some()) && !extra.is_empty()
855 {
856 p.extradata = Some(Buf::from(extra));
857 }
858 Ok((tag, p))
859}
860
861// ---------------------------------------------------------------------------------------------
862// Header parsing
863
864fn parse_hdrl<R: Read + Seek>(
865 inner: &mut R,
866 start: u64,
867 end: u64,
868 strls: &mut Vec<Strl>,
869 total_frames: &mut u32,
870) -> Result<()> {
871 let mut pos = start;
872 while pos + 8 <= end {
873 let Some((id, size)) = chunk_head(inner, pos)? else {
874 break;
875 };
876 let data = pos + 8;
877 if &id == b"LIST" {
878 let mut kind = [0u8; 4];
879 if size >= 4 && read_some(inner, &mut kind)? == 4 {
880 match &kind {
881 b"strl" => strls.push(parse_strl(
882 inner,
883 data + 4,
884 data.saturating_add(size).min(end),
885 )?),
886 b"odml" => {
887 // `dmlh`: dwTotalFrames.
888 let mut h = [0u8; 12];
889 if read_some(inner, &mut h)? == 12 && &h[0..4] == b"dmlh" {
890 *total_frames = le_u32(&h, 8).unwrap_or(0);
891 }
892 }
893 _ => {}
894 }
895 }
896 }
897 pos = data.saturating_add(size).saturating_add(size & 1);
898 }
899 Ok(())
900}
901
902fn parse_strl<R: Read + Seek>(inner: &mut R, start: u64, end: u64) -> Result<Strl> {
903 let mut s = Strl {
904 handler: [0; 4],
905 kind: [0; 4],
906 scale: 1,
907 rate: 1,
908 length: 0,
909 sample_size: 0,
910 strf: Vec::new(),
911 indx: Vec::new(),
912 vprp: None,
913 progressive_vprp: false,
914 };
915 let mut pos = start;
916 while pos + 8 <= end {
917 let Some((id, size)) = chunk_head(inner, pos)? else {
918 break;
919 };
920 let data = pos + 8;
921 let cap = size.min(end.saturating_sub(data)).min(MAX_HEADER_BODY);
922 match &id {
923 b"strh" => {
924 let b = read_body(inner, cap.min(64))?;
925 if b.len() >= 48 {
926 s.kind = [b[0], b[1], b[2], b[3]];
927 s.handler = [b[4], b[5], b[6], b[7]];
928 s.scale = le_u32(&b, 20).unwrap_or(0);
929 s.rate = le_u32(&b, 24).unwrap_or(0);
930 s.length = le_u32(&b, 32).unwrap_or(0);
931 s.sample_size = le_u32(&b, 44).unwrap_or(0);
932 }
933 }
934 b"strf" => s.strf = read_body(inner, cap)?,
935 b"indx" => s.indx = read_body(inner, cap)?,
936 b"vprp" => {
937 let b = read_body(inner, cap)?;
938 let nb = le_u32(&b, 32).unwrap_or(0);
939 if nb == 1 {
940 s.progressive_vprp = true;
941 } else if nb == 2 {
942 // VIDEO_FIELD_DESC is 8 dwords at 36; VideoYValidStartLine is the last.
943 let l0 = le_u32(&b, 36 + 28);
944 let l1 = le_u32(&b, 36 + 32 + 28);
945 s.vprp = Some(match (l0, l1) {
946 (Some(a), Some(b)) if b < a => Interlace::BottomFieldFirst,
947 _ => Interlace::TopFieldFirst,
948 });
949 }
950 }
951 _ => {}
952 }
953 pos = data.saturating_add(size).saturating_add(size & 1);
954 }
955 Ok(s)
956}
957
958// ---------------------------------------------------------------------------------------------
959// Index
960
961fn has_known(raw: &[Raw], tracks: &[Track]) -> bool {
962 raw.iter().any(|r| {
963 tracks
964 .get(r.number as usize)
965 .is_some_and(|t| t.info.stream.is_some())
966 })
967}
968
969fn is_media_id(id: &[u8; 4]) -> bool {
970 matches!(&id[2..4], b"dc" | b"db" | b"wb")
971}
972
973fn resolve_idx1<R: Read + Seek>(
974 inner: &mut R,
975 movi_body: u64,
976 end: u64,
977 tracks: &[Track],
978 body: &[u8],
979) -> Result<Vec<Raw>> {
980 let mut entries = Vec::new();
981 for e in body.as_chunks::<16>().0 {
982 let id = [e[0], e[1], e[2], e[3]];
983 let Some(number) = stream_number(&id).filter(|_| is_media_id(&id)) else {
984 continue;
985 };
986 if !tracks
987 .get(number as usize)
988 .is_some_and(|t| t.info.stream.is_some())
989 {
990 continue;
991 }
992 entries.push(Raw {
993 number,
994 id,
995 offset: u64::from(u32::from_le_bytes([e[8], e[9], e[10], e[11]])),
996 size: u32::from_le_bytes([e[12], e[13], e[14], e[15]]),
997 key: u32::from_le_bytes([e[4], e[5], e[6], e[7]]) & 0x10 != 0,
998 });
999 }
1000 let Some(first) = entries.first() else {
1001 return Ok(entries);
1002 };
1003 // idx1 offsets are relative to the `movi` fourcc, or absolute in some files.
1004 let mut base = None;
1005 for b in [movi_body.saturating_sub(4), 0, movi_body] {
1006 if chunk_matches(inner, b.saturating_add(first.offset), &first.id, end)? {
1007 base = Some(b);
1008 break;
1009 }
1010 }
1011 let Some(base) = base else {
1012 return Ok(Vec::new());
1013 };
1014 for e in &mut entries {
1015 e.offset = base.saturating_add(e.offset);
1016 }
1017 Ok(entries)
1018}
1019
1020fn read_odml<R: Read + Seek>(
1021 inner: &mut R,
1022 indx: &[u8],
1023 number: u32,
1024 end: u64,
1025) -> Result<Vec<Raw>> {
1026 if indx.len() < 24 {
1027 return Ok(Vec::new());
1028 }
1029 match indx[3] {
1030 1 => Ok(parse_standard(inner, indx, number, end)?),
1031 0 => {
1032 let n = le_u32(indx, 4).unwrap_or(0) as usize;
1033 let mut out = Vec::new();
1034 for i in 0..n {
1035 let at = 24 + i * 16;
1036 if at + 16 > indx.len() {
1037 break;
1038 }
1039 let off = le_u64(indx, at).unwrap_or(0);
1040 let size = u64::from(le_u32(indx, at + 8).unwrap_or(0));
1041 if off == 0 || size < 24 || off.saturating_add(8) > end {
1042 continue;
1043 }
1044 let Some((_, body_size)) = chunk_head(inner, off)? else {
1045 continue;
1046 };
1047 let body = read_body(inner, body_size.min(end - off - 8).min(MAX_HEADER_BODY))?;
1048 if body.len() >= 24 && body[3] == 1 {
1049 out.extend(parse_standard(inner, &body, number, end)?);
1050 }
1051 if out.len() > MAX_ENTRIES {
1052 return Err(Error::corrupt("AVI: too many chunks"));
1053 }
1054 }
1055 Ok(out)
1056 }
1057 _ => Ok(Vec::new()),
1058 }
1059}
1060
1061/// An `AVI_INDEX_OF_CHUNKS` body: offsets are relative to `qwBaseOffset` and point at chunk
1062/// data; the top bit of the size marks a non-key chunk.
1063fn parse_standard<R: Read + Seek>(
1064 inner: &mut R,
1065 body: &[u8],
1066 number: u32,
1067 end: u64,
1068) -> Result<Vec<Raw>> {
1069 let longs = usize::from(u16::from_le_bytes([body[0], body[1]])).max(2);
1070 let n = le_u32(body, 4).unwrap_or(0) as usize;
1071 let id = [body[8], body[9], body[10], body[11]];
1072 let base = le_u64(body, 12).unwrap_or(0);
1073 let step = longs * 4;
1074 let mut out = Vec::new();
1075 // Offset to the chunk header: spec says data - 8; some writers point at the header.
1076 let mut back = 8u64;
1077 for i in 0..n {
1078 let at = 24 + i * step;
1079 if at + 8 > body.len() {
1080 break;
1081 }
1082 let off = base.saturating_add(u64::from(le_u32(body, at).unwrap_or(0)));
1083 let sz = le_u32(body, at + 4).unwrap_or(0);
1084 if i == 0 {
1085 let size = sz & 0x7fff_ffff;
1086 if !chunk_matches_sized(inner, off.saturating_sub(8), &id, size, end)?
1087 && chunk_matches_sized(inner, off, &id, size, end)?
1088 {
1089 back = 0;
1090 }
1091 }
1092 out.push(Raw {
1093 number,
1094 id,
1095 offset: off.saturating_sub(back),
1096 size: sz & 0x7fff_ffff,
1097 key: sz & 0x8000_0000 == 0,
1098 });
1099 }
1100 Ok(out)
1101}
1102
1103fn chunk_matches<R: Read + Seek>(
1104 inner: &mut R,
1105 offset: u64,
1106 id: &[u8; 4],
1107 end: u64,
1108) -> Result<bool> {
1109 let Some((got, size)) = chunk_head(inner, offset)? else {
1110 return Ok(false);
1111 };
1112 Ok(&got == id && offset.saturating_add(8).saturating_add(size) <= end)
1113}
1114
1115fn chunk_matches_sized<R: Read + Seek>(
1116 inner: &mut R,
1117 offset: u64,
1118 id: &[u8; 4],
1119 size: u32,
1120 end: u64,
1121) -> Result<bool> {
1122 if offset.saturating_add(8) > end {
1123 return Ok(false);
1124 }
1125 Ok(chunk_matches(inner, offset, id, end)?
1126 && chunk_head(inner, offset)?.is_some_and(|(_, s)| s == u64::from(size)))
1127}
1128
1129/// Walk `start..end` chunk by chunk, descending into `rec ` lists.
1130fn scan_range<R: Read + Seek>(
1131 inner: &mut R,
1132 start: u64,
1133 end: u64,
1134 tracks: &[Track],
1135 out: &mut Vec<Raw>,
1136 depth: usize,
1137) -> Result<()> {
1138 if depth > MAX_REC_DEPTH {
1139 return Err(Error::corrupt("AVI rec lists nested too deeply"));
1140 }
1141 let mut pos = start;
1142 while pos + 8 <= end {
1143 let Some((id, size)) = chunk_head(inner, pos)? else {
1144 break;
1145 };
1146 let data = pos + 8;
1147 // A chunk running past the range is a truncated tail: stop.
1148 if data.saturating_add(size) > end {
1149 break;
1150 }
1151 if &id == b"LIST" {
1152 let mut kind = [0u8; 4];
1153 if size >= 4 && read_some(inner, &mut kind)? == 4 && &kind == b"rec " {
1154 scan_range(inner, data + 4, data + size, tracks, out, depth + 1)?;
1155 }
1156 } else if let Some(number) = stream_number(&id).filter(|_| is_media_id(&id))
1157 && tracks
1158 .get(number as usize)
1159 .is_some_and(|t| t.info.stream.is_some())
1160 {
1161 if out.len() >= MAX_ENTRIES {
1162 return Err(Error::corrupt("AVI: too many chunks"));
1163 }
1164 out.push(Raw {
1165 number,
1166 id,
1167 offset: pos,
1168 size: size as u32,
1169 key: true,
1170 });
1171 }
1172 pos = data + size + (size & 1);
1173 }
1174 Ok(())
1175}
1176
1177// ---------------------------------------------------------------------------------------------
1178// Keyframe sniffing (no index)
1179
1180fn sniff_key<R: Read + Seek>(inner: &mut R, codec: CodecId, data: u64, size: u32) -> Result<bool> {
1181 inner.seek(SeekFrom::Start(data))?;
1182 let mut buf = vec![0u8; (size as usize).min(4096)];
1183 let got = read_some(inner, &mut buf)?;
1184 buf.truncate(got);
1185 Ok(match codec {
1186 CodecId::H264 => h264_key(&buf),
1187 CodecId::Mpeg2Video => mpeg2_key(&buf),
1188 CodecId::Mpeg4Part2 => mpeg4_key(&buf),
1189 // MS-MPEG4: the first two bits are the picture type, 0 = I.
1190 CodecId::MsMpeg4V2 | CodecId::MsMpeg4V3 => buf.first().is_some_and(|b| b >> 6 == 0),
1191 _ => true,
1192 })
1193}
1194
1195fn start_codes(buf: &[u8]) -> impl Iterator<Item = usize> + '_ {
1196 buf.windows(4)
1197 .enumerate()
1198 .filter(|(_, w)| w[0] == 0 && w[1] == 0 && w[2] == 1)
1199 .map(|(i, _)| i + 3)
1200}
1201
1202fn h264_key(buf: &[u8]) -> bool {
1203 for at in start_codes(buf) {
1204 match buf[at] & 0x1f {
1205 5 | 7 => return true,
1206 1 => return false,
1207 _ => {}
1208 }
1209 }
1210 false
1211}
1212
1213fn mpeg2_key(buf: &[u8]) -> bool {
1214 for at in start_codes(buf) {
1215 if buf[at] == 0x00
1216 && let Some(b) = buf.get(at + 2)
1217 {
1218 return (b >> 3) & 7 == 1;
1219 }
1220 }
1221 false
1222}
1223
1224/// MPEG-4 Part 2: the first VOP (`00 00 01 B6`) is an I-VOP (`vop_coding_type` 0).
1225fn mpeg4_key(buf: &[u8]) -> bool {
1226 for at in start_codes(buf) {
1227 if buf[at] == 0xB6 {
1228 return buf.get(at + 1).is_some_and(|b| b >> 6 == 0);
1229 }
1230 }
1231 false
1232}
1233
1234// ---------------------------------------------------------------------------------------------
1235// Byte helpers
1236
1237fn chunk_head<R: Read + Seek>(inner: &mut R, pos: u64) -> Result<Option<([u8; 4], u64)>> {
1238 inner.seek(SeekFrom::Start(pos))?;
1239 let mut h = [0u8; 8];
1240 if read_some(inner, &mut h)? < 8 {
1241 return Ok(None);
1242 }
1243 Ok(Some((
1244 [h[0], h[1], h[2], h[3]],
1245 u64::from(u32::from_le_bytes([h[4], h[5], h[6], h[7]])),
1246 )))
1247}
1248
1249fn stream_number(id: &[u8; 4]) -> Option<u32> {
1250 let a = id[0].checked_sub(b'0')?;
1251 let b = id[1].checked_sub(b'0')?;
1252 (a < 10 && b < 10).then_some(u32::from(a) * 10 + u32::from(b))
1253}
1254
1255fn le_u32(data: &[u8], at: usize) -> Option<u32> {
1256 Some(u32::from_le_bytes(
1257 data.get(at..at.checked_add(4)?)?.try_into().ok()?,
1258 ))
1259}
1260
1261fn le_u64(data: &[u8], at: usize) -> Option<u64> {
1262 Some(u64::from_le_bytes(
1263 data.get(at..at.checked_add(8)?)?.try_into().ok()?,
1264 ))
1265}
1266
1267fn read_some(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
1268 let mut at = 0;
1269 while at < buf.len() {
1270 match r.read(&mut buf[at..]) {
1271 Ok(0) => break,
1272 Ok(n) => at += n,
1273 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
1274 Err(e) => return Err(Error::Io(e)),
1275 }
1276 }
1277 Ok(at)
1278}
1279
1280fn read_full(r: &mut impl Read, buf: &mut [u8]) -> Result<()> {
1281 if read_some(r, buf)? == buf.len() {
1282 Ok(())
1283 } else {
1284 Err(Error::corrupt("AVI header ends mid-field"))
1285 }
1286}
1287
1288/// Read up to `size` bytes, growing as bytes arrive (a lying size costs only what exists).
1289/// A short body is not an error here: header chunks may be cut by truncation.
1290fn read_body(r: &mut impl Read, size: u64) -> Result<Vec<u8>> {
1291 let mut body = Vec::new();
1292 r.by_ref().take(size).read_to_end(&mut body)?;
1293 Ok(body)
1294}