Skip to main content

vpx/
lib.rs

1use std::borrow::Cow;
2use std::ffi::CStr;
3use std::mem::transmute;
4use std::ptr;
5
6pub use crate::ffi::vpx_bit_depth::*;
7pub use crate::ffi::vpx_codec_err_t::*;
8pub use crate::ffi::vpx_rational;
9pub use crate::ffi::vpx_rc_mode::*;
10
11use vpx_sys as ffi;
12
13pub mod encoder;
14
15#[derive(Clone, Copy, Eq, PartialEq, Debug)]
16pub enum Error {
17    Generic(u32),
18    Mem,
19    AbiMismatch,
20    Incapable,
21    /// The bitstream was unable to be parsed at the highest level. The decoder is unable to proceed. This error SHOULD be treated as fatal to the stream.
22    UnsupportedBitstream,
23    /// The decoder does not implement a feature required by the encoder. This return code should only be used for features that prevent future pictures from being properly decoded. This error MAY be treated as fatal to the stream or MAY be treated as fatal to the current GOP.
24    UnsupportedFrame,
25    /// There was a problem decoding the current frame. This return code should only be used for failures that prevent future pictures from being properly decoded. This error MAY be treated as fatal to the stream or MAY be treated as fatal to the current GOP. If decoding is continued for the current GOP, artifacts may be present.
26    CorruptFrame,
27    InvalidParam,
28    ListEnd,
29}
30
31use crate::ffi::vpx_codec_err_t as ErrorEnum;
32impl From<ErrorEnum> for Error {
33    fn from(v: ErrorEnum) -> Self {
34        match v {
35            ffi::VPX_CODEC_MEM_ERROR => Self::Mem,
36            ffi::VPX_CODEC_ABI_MISMATCH => Self::AbiMismatch,
37            ffi::VPX_CODEC_INCAPABLE => Self::Incapable,
38            ffi::VPX_CODEC_UNSUP_BITSTREAM => Self::UnsupportedBitstream,
39            ffi::VPX_CODEC_UNSUP_FEATURE => Self::UnsupportedFrame,
40            ffi::VPX_CODEC_CORRUPT_FRAME => Self::CorruptFrame,
41            ffi::VPX_CODEC_INVALID_PARAM => Self::InvalidParam,
42            ffi::VPX_CODEC_LIST_END => Self::ListEnd,
43            n => Self::Generic(n as u32),
44        }
45    }
46}
47
48impl std::fmt::Display for Error {
49    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        <Self as std::fmt::Debug>::fmt(self, fmt)
51    }
52}
53
54impl std::error::Error for Error {
55    fn description(&self) -> &str {
56        match *self {
57            Self::Generic(_) => "Unspecified error",
58            Self::Mem => "Memory operation failed",
59            Self::AbiMismatch => "ABI version mismatch",
60            Self::Incapable => "Algorithm does not have required capability",
61            Self::UnsupportedBitstream => "The given bitstream is not supported",
62            Self::UnsupportedFrame => "Encoded bitstream uses an unsupported feature",
63            Self::CorruptFrame => "The coded data for this stream is corrupt or incomplete",
64            Self::InvalidParam => "An application-supplied parameter is not valid",
65            Self::ListEnd => "An iterator reached the end of list",
66        }
67    }
68}
69
70pub type Rect = ffi::vpx_image_rect_t;
71
72#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
73#[allow(non_camel_case_types)]
74pub enum Format {
75    YV12_VPX,
76    I420_VPX,
77
78    YV12,
79
80    I420 { hi_bit_depth: bool },
81    I422 { hi_bit_depth: bool },
82    I440 { hi_bit_depth: bool },
83    I444 { hi_bit_depth: bool },
84}
85
86impl From<Format> for ffi::vpx_img_fmt_t {
87    fn from(val: Format) -> Self {
88        use crate::Format::{I420, I420_VPX, I422, I440, I444, YV12, YV12_VPX};
89        use crate::ffi::vpx_img_fmt::*;
90
91        match val {
92            I420_VPX => VPX_IMG_FMT_I420,
93            YV12 | YV12_VPX => VPX_IMG_FMT_YV12,
94
95            I420 { hi_bit_depth: false } => VPX_IMG_FMT_I420,
96            I422 { hi_bit_depth: false } => VPX_IMG_FMT_I422,
97            I440 { hi_bit_depth: false } => VPX_IMG_FMT_I440,
98            I444 { hi_bit_depth: false } => VPX_IMG_FMT_I444,
99
100            I420 { hi_bit_depth: true } => VPX_IMG_FMT_I42016,
101            I422 { hi_bit_depth: true } => VPX_IMG_FMT_I42216,
102            I440 { hi_bit_depth: true } => VPX_IMG_FMT_I44016,
103            I444 { hi_bit_depth: true } => VPX_IMG_FMT_I44416,
104        }
105    }
106}
107
108#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
109#[allow(non_camel_case_types)]
110pub enum ColorSpace {
111    BT601,
112    BT709,
113    SMPTE170,
114    SMPTE240,
115    BT2020,
116    SRGB,
117}
118
119impl From<ColorSpace> for ffi::vpx_color_space_t {
120    fn from(val: ColorSpace) -> Self {
121        match val {
122            ColorSpace::BT601 => Self::VPX_CS_BT_601,
123            ColorSpace::BT709 => Self::VPX_CS_BT_709,
124            ColorSpace::SMPTE170 => Self::VPX_CS_SMPTE_170,
125            ColorSpace::SMPTE240 => Self::VPX_CS_SMPTE_240,
126            ColorSpace::BT2020 => Self::VPX_CS_BT_2020,
127            ColorSpace::SRGB => Self::VPX_CS_SRGB,
128        }
129    }
130}
131
132pub struct Image<'a>(ffi::vpx_image_t, Format, #[allow(unused)] Cow<'a, [u8]>);
133
134impl<'a> Image<'a> {
135    /// Wraps `data` as an image of the given format, without copying it.
136    ///
137    /// # Panics
138    ///
139    /// Panics if `vpx_img_wrap` rejects the parameters (`stride` must be
140    /// 0, 1, or a power of two), or if `data` is too small to hold the whole
141    /// image for the given format and dimensions.
142    #[must_use]
143    pub fn new(data: Cow<'a, [u8]>, fmt: Format,
144               color_space: ColorSpace,
145               width: u32, height: u32,
146               stride: u32) -> Self
147    {
148        Self::try_new(data, fmt, color_space, width, height, stride).expect("Image::new")
149    }
150
151    /// Wraps `data` as an image of the given format, without copying it.
152    #[must_use]
153    pub fn try_new(data: Cow<'a, [u8]>, fmt: Format,
154               color_space: ColorSpace,
155               width: u32, height: u32,
156               stride: u32) -> Result<Self, Error>
157    {
158        let mut t = ffi::vpx_image_t::default();
159        let wrapped = unsafe {
160            ffi::vpx_img_wrap(ptr::from_mut(&mut t),
161                              fmt.into(), width,
162                              height, stride,
163                              data.as_ptr().cast_mut())
164        };
165        if wrapped.is_null() {
166            return Err(Error::Generic(0));
167        }
168
169        // vpx_img_wrap computed the plane strides; use them to verify the
170        // caller's buffer covers the whole image (Y + U/V planes).
171        let uv_planes = if t.fmt == ffi::vpx_img_fmt::VPX_IMG_FMT_NV12 { 1 } else { 2 };
172        let required = (u64::from(t.h) * t.stride[ffi::VPX_PLANE_Y as usize] as u64
173            + uv_planes * (u64::from(t.h) >> t.y_chroma_shift) * t.stride[ffi::VPX_PLANE_U as usize] as u64) as usize;
174        if data.len() < required {
175            debug_assert!(false, "buffer too small for {fmt:?} {width}x{height}: needs {required} bytes, got {}", data.len());
176            return Err(Error::InvalidParam);
177        }
178
179        t.cs = color_space.into();
180        Ok(Image(t, fmt, data))
181    }
182
183    #[must_use]
184    pub fn get_format(&self) -> Format { self.1 }
185
186    pub fn set_rect(&mut self, rect: Rect) -> Result<(), ()> {
187        let res = unsafe { ffi::vpx_img_set_rect(ptr::from_mut(&mut self.0), rect.x, rect.y, rect.w, rect.h) };
188        if res == 0 {
189            Ok(())
190        } else {
191            Err(())
192        }
193    }
194
195    pub fn flip(&mut self) {
196        unsafe {
197            ffi::vpx_img_flip(ptr::from_mut(&mut self.0));
198        }
199    }
200}
201
202impl Drop for Image<'_> {
203    fn drop(&mut self) {
204        unsafe { ffi::vpx_img_free(ptr::from_mut(&mut self.0)) }
205    }
206}
207#[derive(Debug, Clone)]
208pub struct Frame<'a> {
209    data: &'a [u8],
210    pub pts: u64,
211    pub duration: u64,
212    pub flags: ffi::vpx_codec_frame_flags_t,
213    pub partition_id: i32,
214}
215pub const FRAME_IS_KEY: u32 = 0x1;
216pub const FRAME_IS_DROPPABLE: u32 = 0x2;
217pub const FRAME_IS_INVISIBLE: u32 = 0x4;
218pub const FRAME_IS_FRAGMENT: u32 = 0x8;
219impl<'a> Frame<'a> {
220    #[must_use]
221    pub fn data(&self) -> &'a [u8] { self.data }
222
223    #[must_use]
224    pub fn is_keyframe(&self) -> bool {
225        self.flags & FRAME_IS_KEY != 0
226    }
227
228    #[must_use]
229    pub fn is_droppable(&self) -> bool {
230        self.flags & FRAME_IS_DROPPABLE != 0
231    }
232
233    #[must_use]
234    pub fn is_invisible(&self) -> bool {
235        self.flags & FRAME_IS_INVISIBLE != 0
236    }
237
238    #[must_use]
239    pub fn is_fragment(&self) -> bool {
240        self.flags & FRAME_IS_FRAGMENT != 0
241    }
242}
243
244impl<'a> From<&'a ffi::vpx_codec_cx_pkt__bindgen_ty_1__bindgen_ty_1> for Frame<'a> {
245    fn from(v: &'a ffi::vpx_codec_cx_pkt__bindgen_ty_1__bindgen_ty_1) -> Self {
246        let data: &'a [u8] = unsafe { std::slice::from_raw_parts(v.buf as *const u8, v.sz) };
247
248        Frame {
249            data,
250            pts: v.pts as u64,
251            duration: v.duration,
252            flags: v.flags,
253            partition_id: v.partition_id,
254        }
255    }
256}
257
258#[derive(Copy, Clone, Eq, PartialEq, Debug)]
259pub enum Kind {
260    Decoder,
261    Encoder,
262}
263
264pub trait Interface: InternalInterface + Default {
265    type Context;
266    type Cfg;
267
268    fn name(&self) -> &'static str {
269        let pname = unsafe { ffi::vpx_codec_iface_name(self.iface()) };
270        let str = unsafe { CStr::from_ptr(pname).to_str().unwrap() };
271        unsafe { transmute(str) }
272    }
273    fn kind(&self) -> Kind;
274
275    fn create(
276        &self, cfg: <Self as Interface>::Cfg, flags: ffi::vpx_codec_flags_t,
277    ) -> Result<<Self as Interface>::Context, Error>;
278}
279
280#[doc(hidden)]
281pub trait InternalInterface {
282    fn iface(&self) -> *mut ffi::vpx_codec_iface_t;
283}