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    /// Planar 4:2:0 Y, U and V with 10-bit samples, each stored in the low
84    /// bits of a little-endian 16-bit word: FFmpeg's `yuv420p10le` layout.
85    /// Each plane's row is two bytes per sample, and `Plane::stride` is in
86    /// bytes.
87    Yuv420p10,
88}
89
90/// Whether component values use the full numeric range or video range.
91#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
92#[non_exhaustive]
93pub enum ColorRange {
94    Full,
95    Limited,
96}
97
98/// Validated coded dimensions for a video frame.
99#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
100pub struct VideoDimensions {
101    pub width: u32,
102    pub height: u32,
103}
104
105impl VideoDimensions {
106    pub fn new(width: u32, height: u32, limits: &Limits) -> Result<Self> {
107        if width == 0 || height == 0 {
108            return Err(invalid_media("video dimensions must be nonzero"));
109        }
110        if width > limits.max_width || height > limits.max_height {
111            return Err(resource_limit("video dimensions exceed configured limits"));
112        }
113        Ok(Self { width, height })
114    }
115}
116
117/// One owned CPU image plane with an explicit row stride.
118#[derive(Clone, Debug, Eq, PartialEq)]
119pub struct Plane {
120    pub data: Vec<u8>,
121    pub stride: usize,
122}
123
124/// A validated, owned CPU video frame.
125#[derive(Clone, Debug, Eq, PartialEq)]
126pub struct VideoFrame {
127    pub dimensions: VideoDimensions,
128    pub pixel_format: PixelFormat,
129    pub color_range: ColorRange,
130    pub planes: Vec<Plane>,
131}
132
133impl VideoFrame {
134    pub fn new(
135        dimensions: VideoDimensions,
136        pixel_format: PixelFormat,
137        color_range: ColorRange,
138        planes: Vec<Plane>,
139        limits: &Limits,
140    ) -> Result<Self> {
141        let layouts = required_plane_layouts(dimensions, pixel_format)?;
142        if planes.len() != layouts.len() {
143            return Err(invalid_media("plane count does not match the pixel format"));
144        }
145
146        let mut allocation = 0_u64;
147        for (plane, (row_bytes, rows)) in planes.iter().zip(layouts) {
148            if plane.stride < row_bytes {
149                return Err(invalid_media("a video plane stride is too small"));
150            }
151            let required = plane
152                .stride
153                .checked_mul(rows)
154                .ok_or_else(|| resource_limit("video plane size overflow"))?;
155            if plane.data.len() < required {
156                return Err(invalid_media(
157                    "a video plane is shorter than its stride and height",
158                ));
159            }
160            allocation =
161                allocation
162                    .checked_add(u64::try_from(plane.data.len()).map_err(|_| {
163                        resource_limit("video frame allocation cannot be represented")
164                    })?)
165                    .ok_or_else(|| resource_limit("video frame allocation overflow"))?;
166        }
167        if allocation > limits.max_allocation_bytes {
168            return Err(resource_limit("video frame exceeds the allocation limit"));
169        }
170
171        Ok(Self {
172            dimensions,
173            pixel_format,
174            color_range,
175            planes,
176        })
177    }
178}
179
180/// Interleaved, normalized `f32` audio samples for an exact sample interval.
181#[derive(Clone, Debug, PartialEq)]
182pub struct AudioBuffer {
183    pub range: SampleRange,
184    pub sample_rate: u32,
185    pub channels: u16,
186    pub samples: Vec<f32>,
187}
188
189impl AudioBuffer {
190    pub fn new(
191        range: SampleRange,
192        sample_rate: u32,
193        channels: u16,
194        samples: Vec<f32>,
195        limits: &Limits,
196    ) -> Result<Self> {
197        if sample_rate == 0 || sample_rate > limits.max_sample_rate {
198            return Err(resource_limit(
199                "audio sample rate is outside configured limits",
200            ));
201        }
202        if channels == 0 || channels > limits.max_audio_channels {
203            return Err(resource_limit(
204                "audio channel count is outside configured limits",
205            ));
206        }
207        let expected = range
208            .len()
209            .checked_mul(u64::from(channels))
210            .ok_or_else(|| resource_limit("audio sample count overflow"))?;
211        if u64::try_from(samples.len()).ok() != Some(expected) {
212            return Err(invalid_media(
213                "audio data length does not match its range and channels",
214            ));
215        }
216        let bytes = expected
217            .checked_mul(std::mem::size_of::<f32>() as u64)
218            .ok_or_else(|| resource_limit("audio allocation size overflow"))?;
219        if bytes > limits.max_allocation_bytes {
220            return Err(resource_limit("audio buffer exceeds the allocation limit"));
221        }
222        Ok(Self {
223            range,
224            sample_rate,
225            channels,
226            samples,
227        })
228    }
229}
230
231#[doc(hidden)]
232pub fn required_plane_layouts(
233    dimensions: VideoDimensions,
234    pixel_format: PixelFormat,
235) -> Result<Vec<(usize, usize)>> {
236    let width = usize::try_from(dimensions.width)
237        .map_err(|_| resource_limit("video width cannot be represented"))?;
238    let height = usize::try_from(dimensions.height)
239        .map_err(|_| resource_limit("video height cannot be represented"))?;
240    let packed = |bytes_per_pixel: usize| -> Result<Vec<(usize, usize)>> {
241        Ok(vec![(
242            width
243                .checked_mul(bytes_per_pixel)
244                .ok_or_else(|| resource_limit("video row size overflow"))?,
245            height,
246        )])
247    };
248    match pixel_format {
249        PixelFormat::Rgba8 | PixelFormat::Bgra8 => packed(4),
250        PixelFormat::Rgb8 => packed(3),
251        PixelFormat::Gray8 => packed(1),
252        PixelFormat::Yuv420p8 => Ok(vec![
253            (width, height),
254            (width.div_ceil(2), height.div_ceil(2)),
255            (width.div_ceil(2), height.div_ceil(2)),
256        ]),
257        PixelFormat::Yuv420p10 => {
258            let luma_row = width
259                .checked_mul(2)
260                .ok_or_else(|| resource_limit("video row size overflow"))?;
261            let chroma_row = width.div_ceil(2) * 2;
262            Ok(vec![
263                (luma_row, height),
264                (chroma_row, height.div_ceil(2)),
265                (chroma_row, height.div_ceil(2)),
266            ])
267        }
268    }
269}
270
271fn invalid_media(message: &str) -> Error {
272    Error::new(ErrorKind::InvalidInput, message)
273}
274
275fn resource_limit(message: &str) -> Error {
276    Error::new(ErrorKind::ResourceLimit, message)
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    #[test]
284    fn dimensions_apply_resource_limits() {
285        let limits = Limits {
286            max_width: 1_920,
287            max_height: 1_080,
288            ..Limits::default()
289        };
290        assert!(VideoDimensions::new(1_920, 1_080, &limits).is_ok());
291        assert_eq!(
292            VideoDimensions::new(3_840, 2_160, &limits)
293                .unwrap_err()
294                .kind(),
295            ErrorKind::ResourceLimit
296        );
297    }
298
299    #[test]
300    fn packed_frame_validates_stride_and_length() {
301        let limits = Limits::default();
302        let dimensions = VideoDimensions::new(2, 2, &limits).unwrap();
303        let frame = VideoFrame::new(
304            dimensions,
305            PixelFormat::Rgba8,
306            ColorRange::Full,
307            vec![Plane {
308                data: vec![0; 16],
309                stride: 8,
310            }],
311            &limits,
312        );
313        assert!(frame.is_ok());
314
315        let error = VideoFrame::new(
316            dimensions,
317            PixelFormat::Rgba8,
318            ColorRange::Full,
319            vec![Plane {
320                data: vec![0; 14],
321                stride: 8,
322            }],
323            &limits,
324        )
325        .unwrap_err();
326        assert_eq!(error.kind(), ErrorKind::InvalidInput);
327    }
328
329    #[test]
330    fn planar_frame_supports_odd_chroma_dimensions() {
331        let limits = Limits::default();
332        let dimensions = VideoDimensions::new(3, 3, &limits).unwrap();
333        let frame = VideoFrame::new(
334            dimensions,
335            PixelFormat::Yuv420p8,
336            ColorRange::Limited,
337            vec![
338                Plane {
339                    data: vec![0; 9],
340                    stride: 3,
341                },
342                Plane {
343                    data: vec![0; 4],
344                    stride: 2,
345                },
346                Plane {
347                    data: vec![0; 4],
348                    stride: 2,
349                },
350            ],
351            &limits,
352        );
353        assert!(frame.is_ok());
354    }
355
356    #[test]
357    fn ten_bit_planar_rows_hold_two_bytes_per_sample() {
358        let limits = Limits::default();
359        let dimensions = VideoDimensions::new(3, 3, &limits).unwrap();
360        let planes = |luma_stride: usize, chroma_stride: usize| {
361            vec![
362                Plane {
363                    data: vec![0; luma_stride * 3],
364                    stride: luma_stride,
365                },
366                Plane {
367                    data: vec![0; chroma_stride * 2],
368                    stride: chroma_stride,
369                },
370                Plane {
371                    data: vec![0; chroma_stride * 2],
372                    stride: chroma_stride,
373                },
374            ]
375        };
376        let frame = |planes| {
377            VideoFrame::new(
378                dimensions,
379                PixelFormat::Yuv420p10,
380                ColorRange::Limited,
381                planes,
382                &limits,
383            )
384        };
385        assert!(frame(planes(6, 4)).is_ok());
386        assert_eq!(
387            frame(planes(3, 4)).unwrap_err().kind(),
388            ErrorKind::InvalidInput
389        );
390        assert_eq!(
391            frame(planes(6, 2)).unwrap_err().kind(),
392            ErrorKind::InvalidInput
393        );
394    }
395
396    #[test]
397    fn audio_length_must_match_range_and_channels() {
398        let limits = Limits::default();
399        let range = SampleRange::new(100, 103).unwrap();
400        assert!(AudioBuffer::new(range, 48_000, 2, vec![0.0; 6], &limits).is_ok());
401        let error = AudioBuffer::new(range, 48_000, 2, vec![0.0; 5], &limits).unwrap_err();
402        assert_eq!(error.kind(), ErrorKind::InvalidInput);
403    }
404}