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