zvidlib-core 0.5.25

Shared types, I/O, codec traits and the SIMD override for zvidlib
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use crate::{Error, ErrorKind, Limits, Result, SampleRange};

/// Container formats understood by capability discovery.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Container {
    Mp4,
    /// The WebM subset of Matroska, read by `crate::WebmDemuxer` and
    /// written by `crate::webm::WebmMuxer`.
    WebM,
}

impl Container {
    /// Every container, in the order capability discovery reports them.
    pub const ALL: [Self; 2] = [Self::Mp4, Self::WebM];

    /// The lowercase name the browser API uses: `"mp4"` or `"webm"`.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Mp4 => "mp4",
            Self::WebM => "webm",
        }
    }

    /// The MIME type of a file in this container.
    pub const fn mime_type(self) -> &'static str {
        match self {
            Self::Mp4 => "video/mp4",
            Self::WebM => "video/webm",
        }
    }

    /// Looks a container up by [`Self::name`], ignoring ASCII case.
    pub fn from_name(name: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|container| container.name().eq_ignore_ascii_case(name))
    }
}

/// Normalized codec identifiers used across containers and backends.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Codec {
    UncompressedVideo,
    /// H.264/AVC video. `crate::Mp4Demuxer` reads `avc1`/`avc3` sample
    /// entries and `crate::mp4::Mp4Muxer` writes `avc1`, with an `avcC` box
    /// (see [`crate::AvcConfigurationRecord`]) as the decoder configuration.
    /// `crate::native_h264_video_decoder_factory` decodes it through the
    /// platform's hardware decoder; no encoder factory accepts it.
    H264,
    Hevc,
    Av1,
    /// VP8 video, as carried in WebM (`V_VP8`). It has no decoder
    /// configuration record. `crate::native_vp8_video_decoder_factory`
    /// decodes it; no encoder factory accepts it.
    Vp8,
    /// VP9 video, carried in MP4 as a `vp09` sample entry whose decoder
    /// configuration is the complete `vpcC` box (see
    /// [`crate::Vp9CodecConfig`]).
    Vp9,
    Aac,
    /// Opus audio (RFC 6716). MP4 carries it in an `Opus` sample entry whose
    /// decoder configuration is a `dOps` box; Matroska and WebM carry the
    /// RFC 7845 `OpusHead` identification header as `CodecPrivate`. See
    /// `crate::OpusHead`.
    Opus,
    /// Vorbis I audio. There is no widely supported MP4 mapping for Vorbis, so
    /// it has no MP4 sample entry; Matroska and WebM carry its three setup
    /// headers Xiph-laced as `CodecPrivate`. See `crate::VorbisConfig`.
    Vorbis,
}

/// CPU video pixel formats supported by the portable media layer.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum PixelFormat {
    Rgba8,
    Bgra8,
    Rgb8,
    Gray8,
    Yuv420p8,
    /// Planar 4:2:0 Y, U and V with 10-bit samples, each stored in the low
    /// bits of a little-endian 16-bit word: FFmpeg's `yuv420p10le` layout.
    /// Each plane's row is two bytes per sample, and `Plane::stride` is in
    /// bytes.
    Yuv420p10,
}

/// Whether component values use the full numeric range or video range.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ColorRange {
    Full,
    Limited,
}

/// Validated coded dimensions for a video frame.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct VideoDimensions {
    pub width: u32,
    pub height: u32,
}

impl VideoDimensions {
    pub fn new(width: u32, height: u32, limits: &Limits) -> Result<Self> {
        if width == 0 || height == 0 {
            return Err(invalid_media("video dimensions must be nonzero"));
        }
        if width > limits.max_width || height > limits.max_height {
            return Err(resource_limit("video dimensions exceed configured limits"));
        }
        Ok(Self { width, height })
    }
}

/// One owned CPU image plane with an explicit row stride.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Plane {
    pub data: Vec<u8>,
    pub stride: usize,
}

/// A validated, owned CPU video frame.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VideoFrame {
    pub dimensions: VideoDimensions,
    pub pixel_format: PixelFormat,
    pub color_range: ColorRange,
    pub planes: Vec<Plane>,
}

impl VideoFrame {
    pub fn new(
        dimensions: VideoDimensions,
        pixel_format: PixelFormat,
        color_range: ColorRange,
        planes: Vec<Plane>,
        limits: &Limits,
    ) -> Result<Self> {
        let layouts = required_plane_layouts(dimensions, pixel_format)?;
        if planes.len() != layouts.len() {
            return Err(invalid_media("plane count does not match the pixel format"));
        }

        let mut allocation = 0_u64;
        for (plane, (row_bytes, rows)) in planes.iter().zip(layouts) {
            if plane.stride < row_bytes {
                return Err(invalid_media("a video plane stride is too small"));
            }
            let required = plane
                .stride
                .checked_mul(rows)
                .ok_or_else(|| resource_limit("video plane size overflow"))?;
            if plane.data.len() < required {
                return Err(invalid_media(
                    "a video plane is shorter than its stride and height",
                ));
            }
            allocation =
                allocation
                    .checked_add(u64::try_from(plane.data.len()).map_err(|_| {
                        resource_limit("video frame allocation cannot be represented")
                    })?)
                    .ok_or_else(|| resource_limit("video frame allocation overflow"))?;
        }
        if allocation > limits.max_allocation_bytes {
            return Err(resource_limit("video frame exceeds the allocation limit"));
        }

        Ok(Self {
            dimensions,
            pixel_format,
            color_range,
            planes,
        })
    }
}

/// Interleaved, normalized `f32` audio samples for an exact sample interval.
#[derive(Clone, Debug, PartialEq)]
pub struct AudioBuffer {
    pub range: SampleRange,
    pub sample_rate: u32,
    pub channels: u16,
    pub samples: Vec<f32>,
}

impl AudioBuffer {
    pub fn new(
        range: SampleRange,
        sample_rate: u32,
        channels: u16,
        samples: Vec<f32>,
        limits: &Limits,
    ) -> Result<Self> {
        if sample_rate == 0 || sample_rate > limits.max_sample_rate {
            return Err(resource_limit(
                "audio sample rate is outside configured limits",
            ));
        }
        if channels == 0 || channels > limits.max_audio_channels {
            return Err(resource_limit(
                "audio channel count is outside configured limits",
            ));
        }
        let expected = range
            .len()
            .checked_mul(u64::from(channels))
            .ok_or_else(|| resource_limit("audio sample count overflow"))?;
        if u64::try_from(samples.len()).ok() != Some(expected) {
            return Err(invalid_media(
                "audio data length does not match its range and channels",
            ));
        }
        let bytes = expected
            .checked_mul(std::mem::size_of::<f32>() as u64)
            .ok_or_else(|| resource_limit("audio allocation size overflow"))?;
        if bytes > limits.max_allocation_bytes {
            return Err(resource_limit("audio buffer exceeds the allocation limit"));
        }
        Ok(Self {
            range,
            sample_rate,
            channels,
            samples,
        })
    }
}

#[doc(hidden)]
pub fn required_plane_layouts(
    dimensions: VideoDimensions,
    pixel_format: PixelFormat,
) -> Result<Vec<(usize, usize)>> {
    let width = usize::try_from(dimensions.width)
        .map_err(|_| resource_limit("video width cannot be represented"))?;
    let height = usize::try_from(dimensions.height)
        .map_err(|_| resource_limit("video height cannot be represented"))?;
    let packed = |bytes_per_pixel: usize| -> Result<Vec<(usize, usize)>> {
        Ok(vec![(
            width
                .checked_mul(bytes_per_pixel)
                .ok_or_else(|| resource_limit("video row size overflow"))?,
            height,
        )])
    };
    match pixel_format {
        PixelFormat::Rgba8 | PixelFormat::Bgra8 => packed(4),
        PixelFormat::Rgb8 => packed(3),
        PixelFormat::Gray8 => packed(1),
        PixelFormat::Yuv420p8 => Ok(vec![
            (width, height),
            (width.div_ceil(2), height.div_ceil(2)),
            (width.div_ceil(2), height.div_ceil(2)),
        ]),
        PixelFormat::Yuv420p10 => {
            let luma_row = width
                .checked_mul(2)
                .ok_or_else(|| resource_limit("video row size overflow"))?;
            let chroma_row = width.div_ceil(2) * 2;
            Ok(vec![
                (luma_row, height),
                (chroma_row, height.div_ceil(2)),
                (chroma_row, height.div_ceil(2)),
            ])
        }
    }
}

fn invalid_media(message: &str) -> Error {
    Error::new(ErrorKind::InvalidInput, message)
}

fn resource_limit(message: &str) -> Error {
    Error::new(ErrorKind::ResourceLimit, message)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dimensions_apply_resource_limits() {
        let limits = Limits {
            max_width: 1_920,
            max_height: 1_080,
            ..Limits::default()
        };
        assert!(VideoDimensions::new(1_920, 1_080, &limits).is_ok());
        assert_eq!(
            VideoDimensions::new(3_840, 2_160, &limits)
                .unwrap_err()
                .kind(),
            ErrorKind::ResourceLimit
        );
    }

    #[test]
    fn packed_frame_validates_stride_and_length() {
        let limits = Limits::default();
        let dimensions = VideoDimensions::new(2, 2, &limits).unwrap();
        let frame = VideoFrame::new(
            dimensions,
            PixelFormat::Rgba8,
            ColorRange::Full,
            vec![Plane {
                data: vec![0; 16],
                stride: 8,
            }],
            &limits,
        );
        assert!(frame.is_ok());

        let error = VideoFrame::new(
            dimensions,
            PixelFormat::Rgba8,
            ColorRange::Full,
            vec![Plane {
                data: vec![0; 14],
                stride: 8,
            }],
            &limits,
        )
        .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput);
    }

    #[test]
    fn planar_frame_supports_odd_chroma_dimensions() {
        let limits = Limits::default();
        let dimensions = VideoDimensions::new(3, 3, &limits).unwrap();
        let frame = VideoFrame::new(
            dimensions,
            PixelFormat::Yuv420p8,
            ColorRange::Limited,
            vec![
                Plane {
                    data: vec![0; 9],
                    stride: 3,
                },
                Plane {
                    data: vec![0; 4],
                    stride: 2,
                },
                Plane {
                    data: vec![0; 4],
                    stride: 2,
                },
            ],
            &limits,
        );
        assert!(frame.is_ok());
    }

    #[test]
    fn ten_bit_planar_rows_hold_two_bytes_per_sample() {
        let limits = Limits::default();
        let dimensions = VideoDimensions::new(3, 3, &limits).unwrap();
        let planes = |luma_stride: usize, chroma_stride: usize| {
            vec![
                Plane {
                    data: vec![0; luma_stride * 3],
                    stride: luma_stride,
                },
                Plane {
                    data: vec![0; chroma_stride * 2],
                    stride: chroma_stride,
                },
                Plane {
                    data: vec![0; chroma_stride * 2],
                    stride: chroma_stride,
                },
            ]
        };
        let frame = |planes| {
            VideoFrame::new(
                dimensions,
                PixelFormat::Yuv420p10,
                ColorRange::Limited,
                planes,
                &limits,
            )
        };
        assert!(frame(planes(6, 4)).is_ok());
        assert_eq!(
            frame(planes(3, 4)).unwrap_err().kind(),
            ErrorKind::InvalidInput
        );
        assert_eq!(
            frame(planes(6, 2)).unwrap_err().kind(),
            ErrorKind::InvalidInput
        );
    }

    #[test]
    fn audio_length_must_match_range_and_channels() {
        let limits = Limits::default();
        let range = SampleRange::new(100, 103).unwrap();
        assert!(AudioBuffer::new(range, 48_000, 2, vec![0.0; 6], &limits).is_ok());
        let error = AudioBuffer::new(range, 48_000, 2, vec![0.0; 5], &limits).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput);
    }
}