Skip to main content

zvidlib_core/
media.rs

1use crate::{Error, ErrorKind, Limits, Result, SampleRange};
2
3/// Container formats understood by capability discovery.
4#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
5#[non_exhaustive]
6pub enum Container {
7    Mp4,
8    /// The WebM subset of Matroska, read by `crate::WebmDemuxer` and
9    /// written by `crate::webm::WebmMuxer`.
10    WebM,
11}
12
13impl Container {
14    /// Every container, in the order capability discovery reports them.
15    pub const ALL: [Self; 2] = [Self::Mp4, Self::WebM];
16
17    /// The lowercase name the browser API uses: `"mp4"` or `"webm"`.
18    pub const fn name(self) -> &'static str {
19        match self {
20            Self::Mp4 => "mp4",
21            Self::WebM => "webm",
22        }
23    }
24
25    /// The MIME type of a file in this container.
26    pub const fn mime_type(self) -> &'static str {
27        match self {
28            Self::Mp4 => "video/mp4",
29            Self::WebM => "video/webm",
30        }
31    }
32
33    /// Looks a container up by [`Self::name`], ignoring ASCII case.
34    pub fn from_name(name: &str) -> Option<Self> {
35        Self::ALL
36            .into_iter()
37            .find(|container| container.name().eq_ignore_ascii_case(name))
38    }
39}
40
41/// Normalized codec identifiers used across containers and backends.
42#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
43#[non_exhaustive]
44pub enum Codec {
45    UncompressedVideo,
46    /// H.264/AVC video. `crate::Mp4Demuxer` reads `avc1`/`avc3` sample
47    /// entries and `crate::mp4::Mp4Muxer` writes `avc1`, with an `avcC` box
48    /// (see [`crate::AvcConfigurationRecord`]) as the decoder configuration.
49    /// `crate::native_h264_video_decoder_factory` decodes it through the
50    /// platform's hardware decoder; no encoder factory accepts it.
51    H264,
52    Hevc,
53    Av1,
54    /// VP8 video, as carried in WebM (`V_VP8`). It has no decoder
55    /// configuration record. `crate::native_vp8_video_decoder_factory`
56    /// decodes it; no encoder factory accepts it.
57    Vp8,
58    /// VP9 video, carried in MP4 as a `vp09` sample entry whose decoder
59    /// configuration is the complete `vpcC` box (see
60    /// [`crate::Vp9CodecConfig`]).
61    Vp9,
62    Aac,
63    /// Opus audio (RFC 6716). MP4 carries it in an `Opus` sample entry whose
64    /// decoder configuration is a `dOps` box; Matroska and WebM carry the
65    /// RFC 7845 `OpusHead` identification header as `CodecPrivate`. See
66    /// `crate::OpusHead`.
67    Opus,
68    /// Vorbis I audio. There is no widely supported MP4 mapping for Vorbis, so
69    /// it has no MP4 sample entry; Matroska and WebM carry its three setup
70    /// headers Xiph-laced as `CodecPrivate`. See `crate::VorbisConfig`.
71    Vorbis,
72}
73
74/// CPU video pixel formats supported by the portable media layer.
75#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
76#[non_exhaustive]
77pub enum PixelFormat {
78    Rgba8,
79    Bgra8,
80    Rgb8,
81    Gray8,
82    Yuv420p8,
83}
84
85/// Whether component values use the full numeric range or video range.
86#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
87#[non_exhaustive]
88pub enum ColorRange {
89    Full,
90    Limited,
91}
92
93/// Validated coded dimensions for a video frame.
94#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
95pub struct VideoDimensions {
96    pub width: u32,
97    pub height: u32,
98}
99
100impl VideoDimensions {
101    pub fn new(width: u32, height: u32, limits: &Limits) -> Result<Self> {
102        if width == 0 || height == 0 {
103            return Err(invalid_media("video dimensions must be nonzero"));
104        }
105        if width > limits.max_width || height > limits.max_height {
106            return Err(resource_limit("video dimensions exceed configured limits"));
107        }
108        Ok(Self { width, height })
109    }
110}
111
112/// One owned CPU image plane with an explicit row stride.
113#[derive(Clone, Debug, Eq, PartialEq)]
114pub struct Plane {
115    pub data: Vec<u8>,
116    pub stride: usize,
117}
118
119/// A validated, owned CPU video frame.
120#[derive(Clone, Debug, Eq, PartialEq)]
121pub struct VideoFrame {
122    pub dimensions: VideoDimensions,
123    pub pixel_format: PixelFormat,
124    pub color_range: ColorRange,
125    pub planes: Vec<Plane>,
126}
127
128impl VideoFrame {
129    pub fn new(
130        dimensions: VideoDimensions,
131        pixel_format: PixelFormat,
132        color_range: ColorRange,
133        planes: Vec<Plane>,
134        limits: &Limits,
135    ) -> Result<Self> {
136        let layouts = required_plane_layouts(dimensions, pixel_format)?;
137        if planes.len() != layouts.len() {
138            return Err(invalid_media("plane count does not match the pixel format"));
139        }
140
141        let mut allocation = 0_u64;
142        for (plane, (row_bytes, rows)) in planes.iter().zip(layouts) {
143            if plane.stride < row_bytes {
144                return Err(invalid_media("a video plane stride is too small"));
145            }
146            let required = plane
147                .stride
148                .checked_mul(rows)
149                .ok_or_else(|| resource_limit("video plane size overflow"))?;
150            if plane.data.len() < required {
151                return Err(invalid_media(
152                    "a video plane is shorter than its stride and height",
153                ));
154            }
155            allocation =
156                allocation
157                    .checked_add(u64::try_from(plane.data.len()).map_err(|_| {
158                        resource_limit("video frame allocation cannot be represented")
159                    })?)
160                    .ok_or_else(|| resource_limit("video frame allocation overflow"))?;
161        }
162        if allocation > limits.max_allocation_bytes {
163            return Err(resource_limit("video frame exceeds the allocation limit"));
164        }
165
166        Ok(Self {
167            dimensions,
168            pixel_format,
169            color_range,
170            planes,
171        })
172    }
173}
174
175/// Interleaved, normalized `f32` audio samples for an exact sample interval.
176#[derive(Clone, Debug, PartialEq)]
177pub struct AudioBuffer {
178    pub range: SampleRange,
179    pub sample_rate: u32,
180    pub channels: u16,
181    pub samples: Vec<f32>,
182}
183
184impl AudioBuffer {
185    pub fn new(
186        range: SampleRange,
187        sample_rate: u32,
188        channels: u16,
189        samples: Vec<f32>,
190        limits: &Limits,
191    ) -> Result<Self> {
192        if sample_rate == 0 || sample_rate > limits.max_sample_rate {
193            return Err(resource_limit(
194                "audio sample rate is outside configured limits",
195            ));
196        }
197        if channels == 0 || channels > limits.max_audio_channels {
198            return Err(resource_limit(
199                "audio channel count is outside configured limits",
200            ));
201        }
202        let expected = range
203            .len()
204            .checked_mul(u64::from(channels))
205            .ok_or_else(|| resource_limit("audio sample count overflow"))?;
206        if u64::try_from(samples.len()).ok() != Some(expected) {
207            return Err(invalid_media(
208                "audio data length does not match its range and channels",
209            ));
210        }
211        let bytes = expected
212            .checked_mul(std::mem::size_of::<f32>() as u64)
213            .ok_or_else(|| resource_limit("audio allocation size overflow"))?;
214        if bytes > limits.max_allocation_bytes {
215            return Err(resource_limit("audio buffer exceeds the allocation limit"));
216        }
217        Ok(Self {
218            range,
219            sample_rate,
220            channels,
221            samples,
222        })
223    }
224}
225
226#[doc(hidden)]
227pub fn required_plane_layouts(
228    dimensions: VideoDimensions,
229    pixel_format: PixelFormat,
230) -> Result<Vec<(usize, usize)>> {
231    let width = usize::try_from(dimensions.width)
232        .map_err(|_| resource_limit("video width cannot be represented"))?;
233    let height = usize::try_from(dimensions.height)
234        .map_err(|_| resource_limit("video height cannot be represented"))?;
235    let packed = |bytes_per_pixel: usize| -> Result<Vec<(usize, usize)>> {
236        Ok(vec![(
237            width
238                .checked_mul(bytes_per_pixel)
239                .ok_or_else(|| resource_limit("video row size overflow"))?,
240            height,
241        )])
242    };
243    match pixel_format {
244        PixelFormat::Rgba8 | PixelFormat::Bgra8 => packed(4),
245        PixelFormat::Rgb8 => packed(3),
246        PixelFormat::Gray8 => packed(1),
247        PixelFormat::Yuv420p8 => Ok(vec![
248            (width, height),
249            (width.div_ceil(2), height.div_ceil(2)),
250            (width.div_ceil(2), height.div_ceil(2)),
251        ]),
252    }
253}
254
255fn invalid_media(message: &str) -> Error {
256    Error::new(ErrorKind::InvalidInput, message)
257}
258
259fn resource_limit(message: &str) -> Error {
260    Error::new(ErrorKind::ResourceLimit, message)
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn dimensions_apply_resource_limits() {
269        let limits = Limits {
270            max_width: 1_920,
271            max_height: 1_080,
272            ..Limits::default()
273        };
274        assert!(VideoDimensions::new(1_920, 1_080, &limits).is_ok());
275        assert_eq!(
276            VideoDimensions::new(3_840, 2_160, &limits)
277                .unwrap_err()
278                .kind(),
279            ErrorKind::ResourceLimit
280        );
281    }
282
283    #[test]
284    fn packed_frame_validates_stride_and_length() {
285        let limits = Limits::default();
286        let dimensions = VideoDimensions::new(2, 2, &limits).unwrap();
287        let frame = VideoFrame::new(
288            dimensions,
289            PixelFormat::Rgba8,
290            ColorRange::Full,
291            vec![Plane {
292                data: vec![0; 16],
293                stride: 8,
294            }],
295            &limits,
296        );
297        assert!(frame.is_ok());
298
299        let error = VideoFrame::new(
300            dimensions,
301            PixelFormat::Rgba8,
302            ColorRange::Full,
303            vec![Plane {
304                data: vec![0; 14],
305                stride: 8,
306            }],
307            &limits,
308        )
309        .unwrap_err();
310        assert_eq!(error.kind(), ErrorKind::InvalidInput);
311    }
312
313    #[test]
314    fn planar_frame_supports_odd_chroma_dimensions() {
315        let limits = Limits::default();
316        let dimensions = VideoDimensions::new(3, 3, &limits).unwrap();
317        let frame = VideoFrame::new(
318            dimensions,
319            PixelFormat::Yuv420p8,
320            ColorRange::Limited,
321            vec![
322                Plane {
323                    data: vec![0; 9],
324                    stride: 3,
325                },
326                Plane {
327                    data: vec![0; 4],
328                    stride: 2,
329                },
330                Plane {
331                    data: vec![0; 4],
332                    stride: 2,
333                },
334            ],
335            &limits,
336        );
337        assert!(frame.is_ok());
338    }
339
340    #[test]
341    fn audio_length_must_match_range_and_channels() {
342        let limits = Limits::default();
343        let range = SampleRange::new(100, 103).unwrap();
344        assert!(AudioBuffer::new(range, 48_000, 2, vec![0.0; 6], &limits).is_ok());
345        let error = AudioBuffer::new(range, 48_000, 2, vec![0.0; 5], &limits).unwrap_err();
346        assert_eq!(error.kind(), ErrorKind::InvalidInput);
347    }
348}