forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

stream.rs134 lines, 4.9 KiBHistoryRawDownload
1//! Whole-stream decoding: an IVF file in, decoded pictures out.
2//!
3//! VP8 frames are not self-delimiting — a bare frame is a 3-byte
4//! uncompressed tag followed by partitions whose total size only the
5//! container knows — so the whole-stream API takes the stream in the
6//! container VP8 actually ships in: IVF (the RFC's companion container,
7//! `DKIF`/`VP80`; also what vpxenc, ffmpeg and the WebM toolchain emit
8//! for raw VP8 elementaries). Single frames from any other demuxer feed
9//! [`crate::decode::Decoder::decode`] directly.
10//!
11//! The shape mirrors `ec_av1::stream`: [`decode_stream`] collects every
12//! shown picture into a `Vec`, and [`decode_stream_with`] hands each
13//! picture to a sink the moment it exists.
14
15use crate::decode::{Decoder, Picture};
16use crate::{Error, Result};
17
18/// The IVF file magic, `DKIF`.
19const DKIF: &[u8; 4] = b"DKIF";
20/// The fourcc for VP8 video (`VP80`; `VP8L`/`VP8x` are WebP-lossless/alpha).
21const VP80: &[u8; 4] = b"VP80";
22
23/// One demuxed IVF frame: presentation timestamp plus the compressed
24/// VP8 payload.
25struct IvfFrame<'a> {
26 pts: u64,
27 data: &'a [u8],
28}
29
30/// Split an IVF byte stream into its frames, validating the container
31/// envelope (magic, fourcc, framing arithmetic) as [`Error`]s rather
32/// than panics.
33fn demux(data: &[u8]) -> Result<Vec<IvfFrame<'_>>> {
34 if data.len() < 32 || &data[0..4] != DKIF {
35 return Err(Error::corrupt("not an IVF stream (missing DKIF magic)"));
36 }
37 // Bytes 4..6 version (informational), 6..8 header length, 8..12 fourcc.
38 let hdr_len = u16::from_le_bytes([data[6], data[7]]) as usize;
39 if data.len() < hdr_len || hdr_len < 12 {
40 return Err(Error::corrupt("IVF header length out of range"));
41 }
42 if &data[8..12] != VP80 {
43 return Err(Error::unsupported(
44 "IVF fourcc",
45 "the stream is not VP80 (VP8 video)",
46 ));
47 }
48 // Bytes 12..16 carry the nominal width/height; VP8 streams set them
49 // to 0 and take the real dimensions from the key frame, so the
50 // decoder does not consult them.
51 let _ = u16::from_le_bytes([data[12], data[13]]);
52 let _ = u16::from_le_bytes([data[14], data[15]]);
53 let mut frames = Vec::new();
54 let mut pos = hdr_len;
55 while pos + 12 <= data.len() {
56 let sz =
57 u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]])
58 as usize;
59 let pts = u64::from_le_bytes([
60 data[pos + 4],
61 data[pos + 5],
62 data[pos + 6],
63 data[pos + 7],
64 data[pos + 8],
65 data[pos + 9],
66 data[pos + 10],
67 data[pos + 11],
68 ]);
69 pos += 12;
70 if pos + sz > data.len() {
71 return Err(Error::corrupt(format!(
72 "IVF frame {} extends past end of stream (need {} bytes \
73 at offset {})",
74 frames.len(),
75 sz,
76 pos
77 )));
78 }
79 frames.push(IvfFrame {
80 pts,
81 data: &data[pos..pos + sz],
82 });
83 pos += sz;
84 }
85 Ok(frames)
86}
87
88/// Decode every frame in an IVF VP8 stream, in presentation order.
89///
90/// The stream must start with a key frame; hidden frames (alternate
91/// references, `show_frame == 0`) update the reference buffers but are
92/// not part of the output, exactly as a player would not display them.
93///
94/// # Errors
95/// Returns an error when the container is truncated or not VP80 (as
96/// [`demux`] reports it), when a frame is malformed (as
97/// [`crate::decode::Decoder::decode`] reports it), or when an inter
98/// frame appears before any key frame has supplied references.
99pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
100 let mut pictures: Vec<Picture> = Vec::new();
101 decode_stream_with(data, |picture, _decode_idx, _pts| {
102 pictures.push(picture.clone());
103 Ok(())
104 })?;
105 Ok(pictures)
106}
107
108/// Streaming form of [`decode_stream`]: hand every shown picture to
109/// `sink` the moment it exists and drop it right after, so peak memory
110/// is one output picture plus the reference frames instead of the whole
111/// decoded stream. `decode_stream` itself is this function collecting
112/// into a `Vec`.
113///
114/// `sink` is called with the picture, the decode-order index of the
115/// coded frame it came from, and the IVF presentation timestamp. A
116/// hidden frame (`show_frame == 0`) updates the decoder state but
117/// produces no picture, so the sink is not called for it. An `Err` the
118/// sink returns aborts the decode and is returned unchanged.
119///
120/// # Errors
121/// As [`decode_stream`], plus whatever `sink` returns.
122pub fn decode_stream_with(
123 data: &[u8],
124 mut sink: impl FnMut(&Picture, usize, u64) -> Result<()>,
125) -> Result<()> {
126 let frames = demux(data)?;
127 let mut dec = Decoder::new();
128 for (decode_idx, frame) in frames.iter().enumerate() {
129 if let Some(picture) = dec.decode(frame.data)? {
130 sink(&picture, decode_idx, frame.pts)?;
131 }
132 }
133 Ok(())
134}