Skip to main content

media_codec_vpx/
decoder.rs

1use std::{
2    mem::MaybeUninit,
3    os::raw::{c_int, c_void},
4    ptr, slice,
5    sync::{
6        atomic::{AtomicBool, Ordering},
7        Arc,
8    },
9};
10
11use ctor::ctor;
12use media_codec::{
13    decoder::{register_decoder, Decoder, DecoderBuilder, VideoDecoder, VideoDecoderParameters},
14    packet::Packet,
15    Codec, CodecBuilder, CodecID, CodecInformation, CodecParameters,
16};
17use media_core::{
18    buffer::{Buffer, BufferPool},
19    error::Error,
20    frame::SharedFrame,
21    frame_pool::{FrameCreator, FramePool},
22    unsupported_error,
23    variant::Variant,
24    video::{ColorMatrix, ColorRange, PixelFormat, VideoFrame, VideoFrameDescriptor},
25    Result,
26};
27use smallvec::SmallVec;
28
29use crate::{
30    vpx_error_string,
31    vpx_sys::{
32        self, vpx_codec_ctx_t, vpx_codec_err_t::VPX_CODEC_OK, vpx_codec_frame_buffer_t, vpx_codec_iter_t, vpx_color_range, vpx_color_space,
33        vpx_image_t, vpx_img_fmt, VPX_DECODER_ABI_VERSION,
34    },
35};
36
37const CODEC_NAME: &str = "vpx";
38
39fn vpx_img_fmt_to_pixel_format(fmt: vpx_img_fmt, depth: u32) -> Option<PixelFormat> {
40    use vpx_img_fmt::*;
41
42    match (fmt, depth) {
43        (VPX_IMG_FMT_YV12, _) => Some(PixelFormat::YV12),
44        (VPX_IMG_FMT_I420, _) => Some(PixelFormat::I420),
45        (VPX_IMG_FMT_I422, _) => Some(PixelFormat::I422),
46        (VPX_IMG_FMT_I444, _) => Some(PixelFormat::I444),
47        (VPX_IMG_FMT_NV12, _) => Some(PixelFormat::NV12),
48        (VPX_IMG_FMT_I42016, 10) => Some(PixelFormat::I010),
49        (VPX_IMG_FMT_I42016, 12) => Some(PixelFormat::I012),
50        (VPX_IMG_FMT_I42216, 10) => Some(PixelFormat::I210),
51        (VPX_IMG_FMT_I42216, 12) => Some(PixelFormat::I212),
52        (VPX_IMG_FMT_I44416, 10) => Some(PixelFormat::I410),
53        (VPX_IMG_FMT_I44416, 12) => Some(PixelFormat::I412),
54        _ => None,
55    }
56}
57
58fn vpx_color_range_to_color_range(color_range: vpx_color_range) -> ColorRange {
59    use vpx_color_range::*;
60
61    match color_range {
62        VPX_CR_STUDIO_RANGE => ColorRange::Video,
63        VPX_CR_FULL_RANGE => ColorRange::Full,
64    }
65}
66
67fn vpx_color_space_to_color_matrix(color_space: vpx_color_space) -> ColorMatrix {
68    use vpx_color_space::*;
69
70    match color_space {
71        VPX_CS_UNKNOWN => ColorMatrix::Unspecified,
72        VPX_CS_BT_601 => ColorMatrix::BT470BG,
73        VPX_CS_BT_709 => ColorMatrix::BT709,
74        VPX_CS_SMPTE_170 => ColorMatrix::SMPTE170M,
75        VPX_CS_SMPTE_240 => ColorMatrix::SMPTE240M,
76        VPX_CS_BT_2020 => ColorMatrix::BT2020NCL,
77        VPX_CS_RESERVED => ColorMatrix::Reserved,
78        VPX_CS_SRGB => ColorMatrix::Identity,
79    }
80}
81
82const DEFAULT_MAX_VIDEO_PLANES: usize = 4;
83
84type BufferPlaneVec = SmallVec<[(usize, u32); DEFAULT_MAX_VIDEO_PLANES]>;
85
86struct VpxImage(vpx_image_t);
87
88impl VpxImage {
89    fn has_frame_buffer(&self) -> bool {
90        !self.0.fb_priv.is_null()
91    }
92
93    fn descriptor(&self) -> Result<VideoFrameDescriptor> {
94        let img = &self.0;
95        let frame_width = img.d_w;
96        let frame_height = img.d_h;
97        let pix_fmt = img.fmt;
98        let depth = img.bit_depth;
99
100        let pixel_format = vpx_img_fmt_to_pixel_format(pix_fmt, depth).ok_or_else(|| unsupported_error!(pix_fmt))?;
101
102        let mut desc = VideoFrameDescriptor::try_new(pixel_format, frame_width, frame_height)?;
103        desc.color_range = vpx_color_range_to_color_range(img.range);
104        desc.color_matrix = vpx_color_space_to_color_matrix(img.cs);
105
106        Ok(desc)
107    }
108
109    fn convert_to_frame(&self) -> Result<VideoFrame<'_>> {
110        let img = &self.0;
111        let desc = self.descriptor()?;
112        let planes_num = desc.format.components() as usize;
113        let mut buffers = SmallVec::<[(&[u8], u32); DEFAULT_MAX_VIDEO_PLANES]>::with_capacity(planes_num);
114
115        for plane in 0..planes_num {
116            let height = desc.format.calc_plane_height(plane, desc.height().get()) as usize;
117            let stride = img.stride[plane] as usize;
118            let buffer = unsafe { slice::from_raw_parts(img.planes[plane], stride * height) };
119            buffers.push((buffer, stride as u32));
120        }
121
122        let frame = VideoFrame::from_buffers_with_descriptor(desc, &buffers)?;
123
124        Ok(frame)
125    }
126
127    fn convert_to_buffer(&self) -> Result<(Arc<Buffer>, BufferPlaneVec, VideoFrameDescriptor)> {
128        let img = &self.0;
129        let desc = self.descriptor()?;
130        let planes_num = desc.format.components() as usize;
131        let buffer = unsafe { Arc::from_raw(img.fb_priv as *const Buffer) };
132
133        let mut buffers = SmallVec::with_capacity(planes_num);
134
135        for plane in 0..planes_num {
136            let offset = img.planes[plane] as usize - buffer.data().as_ptr() as usize;
137
138            if offset >= buffer.len() {
139                let _ = Arc::into_raw(buffer);
140                return Err(Error::Invalid("invalid frame buffer offset".into()));
141            }
142
143            let stride = img.stride[plane] as usize;
144            buffers.push((offset, stride as u32));
145        }
146
147        let buffer_clone = buffer.clone();
148        let _ = Arc::into_raw(buffer);
149
150        Ok((buffer_clone, buffers, desc))
151    }
152}
153
154struct EmptyFrameCreator;
155
156impl FrameCreator<VideoFrameDescriptor> for EmptyFrameCreator {
157    fn create_frame(&self, desc: VideoFrameDescriptor) -> Result<VideoFrame<'static>> {
158        VideoFrame::new_empty_with_descriptor(desc)
159    }
160}
161
162pub struct VpxDecoder {
163    id: CodecID,
164    ctx: vpx_codec_ctx_t,
165    iter: vpx_codec_iter_t,
166    buffer_pool_ptr: *const BufferPool,
167    frame_pool_initialized: AtomicBool,
168}
169
170unsafe impl Send for VpxDecoder {}
171unsafe impl Sync for VpxDecoder {}
172
173impl CodecInformation for VpxDecoder {
174    fn id(&self) -> CodecID {
175        self.id
176    }
177
178    fn name(&self) -> &'static str {
179        CODEC_NAME
180    }
181}
182
183impl Codec<VideoDecoder> for VpxDecoder {
184    fn configure(&mut self, _params: Option<&CodecParameters>, _options: Option<&Variant>) -> Result<()> {
185        Ok(())
186    }
187
188    fn set_option(&mut self, _name: &str, _value: &Variant) -> Result<()> {
189        Ok(())
190    }
191}
192
193impl Decoder<VideoDecoder> for VpxDecoder {
194    fn send_packet(&mut self, _config: &VideoDecoder, _pool: Option<&Arc<FramePool<VideoFrame<'static>>>>, packet: &Packet) -> Result<()> {
195        let packet_data = packet.data();
196        let ret = unsafe { vpx_sys::vpx_codec_decode(&mut self.ctx, packet_data.as_ptr(), packet_data.len() as u32, ptr::null_mut(), 0) };
197
198        self.iter = ptr::null_mut();
199
200        if ret != VPX_CODEC_OK {
201            return Err(Error::Invalid(vpx_error_string(ret)));
202        }
203
204        Ok(())
205    }
206
207    fn receive_frame(
208        &mut self,
209        _config: &VideoDecoder,
210        pool: Option<&Arc<FramePool<VideoFrame<'static>>>>,
211    ) -> Result<SharedFrame<VideoFrame<'static>>> {
212        let img = &self.get_image()?;
213
214        let pool = if let Some(pool) = pool {
215            pool
216        } else {
217            if !img.has_frame_buffer() {
218                return img.convert_to_frame().map(SharedFrame::<VideoFrame<'static>>::new);
219            }
220
221            let (buffer, buffer_planes, desc) = img.convert_to_buffer()?;
222            let frame = VideoFrame::from_shared_buffer_with_descriptor(desc, buffer, &buffer_planes)?;
223            return Ok(SharedFrame::<VideoFrame<'static>>::new(frame));
224        };
225
226        if !img.has_frame_buffer() {
227            let desc = img.descriptor()?;
228
229            self.init_pool(&desc, pool, None);
230
231            let frame = img.convert_to_frame()?;
232            let mut pooled_frame = pool.get_frame_with_descriptor(desc)?;
233            frame.convert_to(pooled_frame.write().unwrap())?;
234
235            Ok(pooled_frame)
236        } else {
237            let (buffer, buffer_planes, desc) = img.convert_to_buffer()?;
238
239            self.init_pool(&desc, pool, Some(Box::new(EmptyFrameCreator)));
240
241            let mut pooled_frame = pool.get_frame_with_descriptor(desc.clone())?;
242            pooled_frame.write().unwrap().attach_shared_buffer_with_descriptor(desc, buffer, &buffer_planes)?;
243
244            Ok(pooled_frame)
245        }
246    }
247
248    fn flush(&mut self, _config: &VideoDecoder) -> Result<()> {
249        let ret = unsafe { vpx_sys::vpx_codec_decode(&mut self.ctx, ptr::null(), 0, ptr::null_mut(), 0) };
250
251        self.iter = ptr::null_mut();
252
253        if ret != VPX_CODEC_OK {
254            return Err(Error::Invalid(vpx_error_string(ret)));
255        }
256
257        Ok(())
258    }
259}
260
261unsafe extern "C" fn get_frame_buffer(priv_: *mut c_void, min_size: usize, fb: *mut vpx_codec_frame_buffer_t) -> c_int {
262    let pool = Arc::from_raw(priv_ as *const BufferPool);
263
264    if pool.get_buffer_capacity() < min_size {
265        pool.set_buffer_capacity(min_size);
266    }
267
268    let buffer = pool.get_buffer();
269
270    (*fb).data = buffer.data().as_ptr() as *mut u8;
271    (*fb).size = buffer.len();
272    (*fb).priv_ = Arc::into_raw(buffer) as *mut c_void;
273
274    let _ = Arc::into_raw(pool);
275
276    0
277}
278
279unsafe extern "C" fn release_frame_buffer(_priv_: *mut c_void, fb: *mut vpx_codec_frame_buffer_t) -> c_int {
280    if !(*fb).priv_.is_null() {
281        let buffer = Arc::from_raw((*fb).priv_ as *const Buffer);
282        drop(buffer);
283    }
284
285    0
286}
287
288impl VpxDecoder {
289    pub fn new(id: CodecID, _params: &VideoDecoderParameters, _options: Option<&Variant>) -> Result<Self> {
290        let iface = match id {
291            CodecID::VP8 => unsafe { vpx_sys::vpx_codec_vp8_dx() },
292            CodecID::VP9 => unsafe { vpx_sys::vpx_codec_vp9_dx() },
293            _ => return Err(unsupported_error!(id)),
294        };
295
296        let mut ctx = MaybeUninit::uninit();
297        let cfg = MaybeUninit::zeroed();
298        let ver = VPX_DECODER_ABI_VERSION as i32;
299        let ret = unsafe { vpx_sys::vpx_codec_dec_init_ver(ctx.as_mut_ptr(), iface, cfg.as_ptr(), 0, ver) };
300
301        if ret != VPX_CODEC_OK {
302            return Err(Error::Invalid(vpx_error_string(ret)));
303        }
304
305        let pool = BufferPool::new(0);
306        let pool_ptr = Arc::into_raw(pool);
307
308        if id == CodecID::VP9 {
309            unsafe {
310                vpx_sys::vpx_codec_set_frame_buffer_functions(
311                    ctx.as_mut_ptr(),
312                    Some(get_frame_buffer),
313                    Some(release_frame_buffer),
314                    pool_ptr as *mut c_void,
315                );
316            }
317        }
318
319        Ok(Self {
320            id,
321            ctx: unsafe { ctx.assume_init() },
322            iter: ptr::null_mut(),
323            buffer_pool_ptr: pool_ptr,
324            frame_pool_initialized: AtomicBool::new(false),
325        })
326    }
327
328    fn init_pool(
329        &self,
330        desc: &VideoFrameDescriptor,
331        pool: &Arc<FramePool<VideoFrame<'static>>>,
332        creator: Option<Box<dyn FrameCreator<VideoFrameDescriptor>>>,
333    ) {
334        if !self.frame_pool_initialized.load(Ordering::Relaxed) {
335            pool.configure(Some(desc.clone()), creator);
336            self.frame_pool_initialized.store(true, Ordering::Relaxed);
337        }
338    }
339
340    fn get_image(&mut self) -> Result<VpxImage> {
341        let img = unsafe { vpx_sys::vpx_codec_get_frame(&mut self.ctx as *const _ as *mut _, &mut self.iter) };
342        if img.is_null() {
343            return Err(Error::Again("no frame available".into()));
344        }
345
346        let img = unsafe { *img };
347
348        Ok(VpxImage(img))
349    }
350}
351
352impl Drop for VpxDecoder {
353    fn drop(&mut self) {
354        unsafe {
355            vpx_sys::vpx_codec_destroy(&mut self.ctx);
356
357            if !self.buffer_pool_ptr.is_null() {
358                let pool = Arc::from_raw(self.buffer_pool_ptr);
359                drop(pool);
360            }
361        };
362    }
363}
364
365pub struct VpxDecoderBuilder;
366
367impl DecoderBuilder<VideoDecoder> for VpxDecoderBuilder {
368    fn new_decoder(&self, codec_id: CodecID, params: &CodecParameters, options: Option<&Variant>) -> Result<Box<dyn Decoder<VideoDecoder>>> {
369        Ok(Box::new(VpxDecoder::new(codec_id, &params.try_into()?, options)?))
370    }
371}
372
373impl CodecBuilder<VideoDecoder> for VpxDecoderBuilder {
374    fn ids(&self) -> &[CodecID] {
375        &[CodecID::VP8, CodecID::VP9]
376    }
377
378    fn name(&self) -> &'static str {
379        CODEC_NAME
380    }
381}
382
383#[ctor]
384pub fn initialize() {
385    register_decoder(Arc::new(VpxDecoderBuilder), false);
386}