Skip to main content

waft_embedder/
video_decoders.rs

1//! The system's video decoders, as a host hands them to the app. Not a dart:ui file: the
2//! framework's own video is the system's players ([`Players`](crate::Players)), which read and
3//! decode a file themselves. These are the decoders alone, for an app that reads a file or a
4//! stream itself and hands over one encoded picture at a time: Apple's VideoToolbox, Android's
5//! MediaCodec, Windows' Media Foundation. They follow `wasdk:media/video-decoders` and
6//! `wasdk:media/video-streams` one to one, and are a module of their own, named as that
7//! interface is.
8//!
9//! A stream is its codec and its setup bytes, as a container holds them or the stream carries
10//! them: every system's decoder is configured from those bytes and reads the profile, the level
11//! and the picture's size out of them, so nothing here says them a second time.
12//!
13//! Chunks go in and frames come out. [`VideoDecoder::decode`] takes a chunk when the decoder has
14//! room; its picture comes later from [`VideoDecoder::next_frame`], in the order pictures are
15//! shown, which is not the order chunks go in where a stream reorders. A frame is the decoder's
16//! own picture, lent from its pool ([`VideoFrame`](crate::VideoFrame)), and says what its stream
17//! says of it.
18//!
19//! The invariants a host keeps: each future resolves, once, whether or not the app still holds
20//! the decoder; frames come out in the order they are shown; and a chunk the decoder cannot
21//! decode is answered [`DecoderError::BadData`] and leaves the decoder taking chunks, from the
22//! next key frame on.
23
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::Arc;
27
28use crate::VideoFrame;
29
30/// A GPU's video decoders, or `None` from
31/// [`SystemGpu::video_decoders`](crate::SystemGpu::video_decoders) where the system decodes no
32/// video for the app.
33pub trait VideoDecoders {
34    /// What the system can tell, without trying, about decoding a stream like `description`. It
35    /// is answered later, as the WIT's `support` and WebCodecs' `isConfigSupported` are, so a host
36    /// that asks a system which answers later (a browser's) can serve it; a host that knows at
37    /// once answers with a ready future.
38    fn support(&self, description: &VideoStreamDescription) -> VideoDecodeSupportFuture;
39
40    /// A decoder for the stream `setup` begins: [`DecoderError::Unsupported`] where the system
41    /// has none of the kind chosen for it, [`DecoderError::Busy`] where every such decoder is in
42    /// use.
43    fn open(&self, setup: VideoStreamSetup, options: VideoDecoderOptions)
44    -> VideoDecoderOpenFuture;
45}
46
47/// One decoder the system opened for the app. Dropping it ends its frames; the frames the app
48/// still holds stay the system's until they are dropped.
49pub trait VideoDecoder {
50    /// Where it runs.
51    fn kind(&self) -> CodecKind;
52
53    /// Hands `chunk` to the decoder, resolving once it has room for the next; its picture comes
54    /// from [`next_frame`](Self::next_frame). [`DecoderError::BadData`] for a chunk it cannot
55    /// decode, a chunk that is no key frame where one is due among them: at the stream's start,
56    /// and after a [`drain`](Self::drain), a [`reset`](Self::reset), a
57    /// [`configure`](Self::configure) and a damaged chunk.
58    fn decode(&self, chunk: EncodedChunk) -> VideoDecoderFuture;
59
60    /// The next decoded picture, in the order pictures are shown; `None` once the decoder has
61    /// ended. One is asked for at a time.
62    fn next_frame(&self) -> DecodedFrameFuture;
63
64    /// Why the decoder ended by itself, as the system taking it away; never resolves for a
65    /// decoder that ends only as the app drops it.
66    fn ended(&self) -> Pin<Box<dyn Future<Output = DecoderError>>>;
67
68    /// Resolves once every chunk given has come out as a picture, as at a file's end.
69    fn drain(&self) -> VideoDecoderFuture;
70
71    /// Drops every chunk and picture the decoder holds, as for a seek.
72    fn reset(&self);
73
74    /// The stream's setup from the next chunk on: another size or other parameter sets of the
75    /// same codec, as a stream that adapts its quality changes them.
76    fn configure(&self, setup: VideoStreamSetup) -> VideoDecoderFuture;
77}
78
79/// A family of video streams.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
81pub enum VideoCodec {
82    H264,
83    Hevc,
84    Vp8,
85    Vp9,
86    Av1,
87}
88
89/// How an H.264 or HEVC stream frames its units, with its setup in that form. Files hold one
90/// form and broadcasts, cameras and calls the other; each system's decoder takes one of them,
91/// and the host converts.
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub enum NalFormat {
94    /// As MP4, FLV and Matroska hold it: each unit after its length. The configuration record
95    /// (`avcC`, `hvcC`) gives the length's size and the parameter sets, which the stream may
96    /// carry too.
97    LengthPrefixed(Vec<u8>),
98    /// Annex B, as transport streams, RTSP and cameras send it: each unit after a start code.
99    /// The parameter sets are in the stream, or given ahead here in the same form.
100    StartCodes(Option<Vec<u8>>),
101}
102
103/// A stream's codec with what a decoder needs to begin on it.
104#[derive(Clone, Debug, PartialEq, Eq)]
105pub enum VideoStreamSetup {
106    H264(NalFormat),
107    Hevc(NalFormat),
108    Vp8,
109    /// With its `vpcC` record, where the container has one.
110    Vp9(Option<Vec<u8>>),
111    /// With its `av1C` record, where the container has one. The chunks are AV1's low-overhead
112    /// form, as MP4 and WebM hold them.
113    Av1(Option<Vec<u8>>),
114}
115
116impl VideoStreamSetup {
117    pub fn codec(&self) -> VideoCodec {
118        match self {
119            VideoStreamSetup::H264(_) => VideoCodec::H264,
120            VideoStreamSetup::Hevc(_) => VideoCodec::Hevc,
121            VideoStreamSetup::Vp8 => VideoCodec::Vp8,
122            VideoStreamSetup::Vp9(_) => VideoCodec::Vp9,
123            VideoStreamSetup::Av1(_) => VideoCodec::Av1,
124        }
125    }
126}
127
128/// One picture of a stream, encoded.
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct EncodedChunk {
131    /// The whole of one picture (an access unit), framed as the stream's setup says.
132    pub data: Vec<u8>,
133    /// When the picture is shown, in nanoseconds on the stream's own timeline, which may begin
134    /// before zero: carried to the picture's frame unchanged. A decoder does not order by it:
135    /// frames come out in the stream's own order, whatever the times say.
136    pub timestamp: i64,
137    /// How long it is shown, in nanoseconds, where the stream says.
138    pub duration: Option<u64>,
139    /// Whether it decodes with nothing before it.
140    pub key_frame: bool,
141}
142
143/// Which of the system's codecs the app accepts.
144#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
145pub enum CodecChoice {
146    /// Whichever the system picks, hardware first.
147    #[default]
148    Any,
149    /// One that runs on the system's video hardware, or none.
150    Hardware,
151    /// One that runs on the processor, or none.
152    Software,
153}
154
155/// Where a codec runs.
156#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
157pub enum CodecKind {
158    Hardware,
159    Software,
160}
161
162/// A picture's size in pixels.
163#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
164pub struct PictureSize {
165    pub width: u32,
166    pub height: u32,
167}
168
169/// How much of a picture's colour is kept beside its brightness.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171pub enum ChromaSampling {
172    /// Half in each direction, 4:2:0: nearly all video.
173    Yuv420,
174    /// Half across, 4:2:2.
175    Yuv422,
176    /// All of it, 4:4:4.
177    Yuv444,
178    /// None: a grey picture.
179    Gray,
180}
181
182/// A stream as an app knows it before it has a decoder, from a manifest or a file's header: what
183/// the systems need to say whether they decode it.
184#[derive(Clone, Debug, PartialEq)]
185pub struct VideoStreamDescription {
186    pub codec: VideoCodec,
187    /// The profile as the codec numbers it (H.264's `profile_idc`, HEVC's
188    /// `general_profile_idc`, VP9's and AV1's profile); `None` where the app does not know.
189    pub profile: Option<u32>,
190    /// The level as the codec numbers it; `None` where the app does not know.
191    pub level: Option<u32>,
192    /// Bits in each sample: 8, 10 or 12.
193    pub bit_depth: u8,
194    pub chroma: ChromaSampling,
195    pub size: PictureSize,
196    /// Pictures a second, where the app knows.
197    pub frame_rate: Option<f32>,
198}
199
200/// What a system says of decoding a stream, for each kind of decoder.
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202pub struct VideoDecodeSupport {
203    pub hardware: DecodeSupport,
204    pub software: DecodeSupport,
205}
206
207/// What a system can tell without trying. Android answers from its decoders' own lists; Apple's
208/// systems tell only whether a codec has hardware at all, so a profile or a size is
209/// [`Unknown`](DecodeSupport::Unknown) there until a decoder is opened.
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211pub enum DecodeSupport {
212    Yes,
213    No,
214    Unknown,
215}
216
217#[derive(Clone, Debug, PartialEq)]
218pub struct VideoDecoderOptions {
219    /// Which decoder the app accepts.
220    pub decoder: CodecChoice,
221    /// What the pictures are for.
222    pub purpose: DecodingPurpose,
223    /// The most frames the app has at one time: what a system that sizes a decoder's pool as it
224    /// is made sizes it for.
225    pub frame_limit: u32,
226    /// The largest size the stream will reach, where the app knows: what lets Android's decoders
227    /// change size in place.
228    pub largest_size: Option<PictureSize>,
229    /// The colour a file gives for the stream. It fills in only what the stream itself leaves
230    /// unsaid: the stream describes its own pixels, and a file's header is often wrong.
231    pub default_color: Option<crate::VideoColor>,
232}
233
234/// What the pictures are for, which decides how the system runs the decoder. These are settings
235/// the systems take, not promises.
236#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
237pub enum DecodingPurpose {
238    /// Shown as they arrive, as in a call: each picture comes out as soon as the stream's order
239    /// allows.
240    Live,
241    /// Played at the video's own rate.
242    #[default]
243    Playback,
244    /// Not watched while decoding, as an export or thumbnails: the system may take its time to
245    /// save power.
246    Background,
247}
248
249/// Why a decoder was not opened, a chunk not decoded, or a decoder ended. Only
250/// [`BadData`](DecoderError::BadData) leaves the decoder taking chunks.
251#[derive(Clone, Debug, PartialEq, Eq)]
252pub enum DecoderError {
253    /// The system has no decoder of the kind chosen for this stream; another choice may work.
254    Unsupported(String),
255    /// Every such decoder is in use now; fewer at once, or software, may work.
256    Busy,
257    /// The stream is damaged, or began without a key frame. The decoder goes on from the next
258    /// key frame.
259    BadData(String),
260    /// The system took the decoder away. Another decoder goes on from a key frame.
261    Lost,
262    /// The system's decoder failed.
263    Failed(String),
264}
265
266/// What [`VideoDecoders::support`] answers, once the system has told.
267pub type VideoDecodeSupportFuture = Pin<Box<dyn Future<Output = VideoDecodeSupport>>>;
268
269pub type VideoDecoderOpenFuture =
270    Pin<Box<dyn Future<Output = Result<Arc<dyn VideoDecoder>, DecoderError>>>>;
271
272pub type VideoDecoderFuture = Pin<Box<dyn Future<Output = Result<(), DecoderError>>>>;
273
274pub type DecodedFrameFuture = Pin<Box<dyn Future<Output = Option<Arc<dyn VideoFrame>>>>>;