1 use dav1d_sys::*;
2
3 use std::ffi::c_void;
4 use std::fmt;
5 use std::i64;
6 use std::mem;
7 use std::ptr;
8 use std::sync::Arc;
9
10 #[derive(Debug)]
11 pub struct Error(i32);
12
13 impl Error {
is_again(&self) -> bool14 pub const fn is_again(&self) -> bool {
15 const AGAIN: i32 = EAGAIN as i32;
16 if AGAIN < 0 {
17 self.0 == AGAIN
18 } else {
19 self.0 == -AGAIN
20 }
21 }
22 }
23
24 impl fmt::Display for Error {
fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result25 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
26 write!(fmt, "{}", self.0)
27 }
28 }
29
30 impl std::error::Error for Error {}
31
32 #[derive(Debug)]
33 pub struct Decoder {
34 dec: *mut Dav1dContext,
35 }
36
release_wrapped_data(_data: *const u8, cookie: *mut c_void)37 unsafe extern "C" fn release_wrapped_data(_data: *const u8, cookie: *mut c_void) {
38 let closure: &mut &mut dyn FnMut() = &mut *(cookie as *mut &mut dyn std::ops::FnMut());
39 closure();
40 }
41
42 impl Default for Decoder {
default() -> Self43 fn default() -> Self {
44 Self::new()
45 }
46 }
47
48 impl Decoder {
new() -> Self49 pub fn new() -> Self {
50 unsafe {
51 let mut settings = mem::MaybeUninit::uninit();
52 let mut dec = mem::MaybeUninit::uninit();
53
54 dav1d_default_settings(settings.as_mut_ptr());
55
56 let settings = settings.assume_init();
57
58 let ret = dav1d_open(dec.as_mut_ptr(), &settings);
59
60 if ret != 0 {
61 panic!("Cannot instantiate the default decoder {}", ret);
62 }
63
64 Decoder {
65 dec: dec.assume_init(),
66 }
67 }
68 }
69
flush(&self)70 pub fn flush(&self) {
71 unsafe {
72 dav1d_flush(self.dec);
73 }
74 }
75
send_data<T: AsRef<[u8]>>( &mut self, buf: T, offset: Option<i64>, timestamp: Option<i64>, duration: Option<i64>, ) -> Result<(), Error>76 pub fn send_data<T: AsRef<[u8]>>(
77 &mut self,
78 buf: T,
79 offset: Option<i64>,
80 timestamp: Option<i64>,
81 duration: Option<i64>,
82 ) -> Result<(), Error> {
83 let buf = buf.as_ref();
84 let len = buf.len();
85 unsafe {
86 let mut data: Dav1dData = mem::zeroed();
87 let ptr = dav1d_data_create(&mut data, len);
88 ptr::copy_nonoverlapping(buf.as_ptr(), ptr, len);
89 if let Some(offset) = offset {
90 data.m.offset = offset;
91 }
92 if let Some(timestamp) = timestamp {
93 data.m.timestamp = timestamp;
94 }
95 if let Some(duration) = duration {
96 data.m.duration = duration;
97 }
98 let ret = dav1d_send_data(self.dec, &mut data);
99 if ret < 0 {
100 Err(Error(ret))
101 } else {
102 Ok(())
103 }
104 }
105 }
106
get_picture(&mut self) -> Result<Picture, Error>107 pub fn get_picture(&mut self) -> Result<Picture, Error> {
108 unsafe {
109 let mut pic: Dav1dPicture = mem::zeroed();
110 let ret = dav1d_get_picture(self.dec, &mut pic);
111
112 if ret < 0 {
113 Err(Error(ret))
114 } else {
115 let inner = InnerPicture { pic };
116 Ok(Picture {
117 inner: Arc::new(inner),
118 })
119 }
120 }
121 }
122
decode<T: AsRef<[u8]>, F: FnMut()>( &mut self, buf: T, offset: Option<i64>, timestamp: Option<i64>, duration: Option<i64>, mut destroy_notify: F, ) -> Result<Vec<Picture>, Error>123 pub fn decode<T: AsRef<[u8]>, F: FnMut()>(
124 &mut self,
125 buf: T,
126 offset: Option<i64>,
127 timestamp: Option<i64>,
128 duration: Option<i64>,
129 mut destroy_notify: F,
130 ) -> Result<Vec<Picture>, Error> {
131 let buf = buf.as_ref();
132 let len = buf.len();
133 unsafe {
134 let mut data: Dav1dData = mem::zeroed();
135 let mut cb: &mut dyn FnMut() = &mut destroy_notify;
136 let cb = &mut cb;
137 let _ret = dav1d_data_wrap(
138 &mut data,
139 buf.as_ptr(),
140 len,
141 Some(release_wrapped_data),
142 cb as *mut _ as *mut c_void,
143 );
144 if let Some(offset) = offset {
145 data.m.offset = offset;
146 }
147 if let Some(timestamp) = timestamp {
148 data.m.timestamp = timestamp;
149 }
150 if let Some(duration) = duration {
151 data.m.duration = duration;
152 }
153 let mut pictures: Vec<Picture> = Vec::new();
154 while data.sz > 0 {
155 let ret = dav1d_send_data(self.dec, &mut data);
156 let err = Error(ret);
157 if ret < 0 && !err.is_again() {
158 return Err(err);
159 }
160 match self.get_picture() {
161 Ok(p) => pictures.push(p),
162 Err(e) => {
163 if e.is_again() {
164 continue;
165 } else {
166 break;
167 }
168 }
169 };
170 }
171 Ok(pictures)
172 }
173 }
174 }
175
176 impl Drop for Decoder {
drop(&mut self)177 fn drop(&mut self) {
178 unsafe { dav1d_close(&mut self.dec) };
179 }
180 }
181
182 unsafe impl Send for Decoder {}
183
184 #[derive(Debug)]
185 struct InnerPicture {
186 pub pic: Dav1dPicture,
187 }
188
189 #[derive(Debug, Clone)]
190 pub struct Picture {
191 inner: Arc<InnerPicture>,
192 }
193
194 #[derive(Debug, Eq, PartialEq, Copy, Clone)]
195 pub enum PixelLayout {
196 I400,
197 I420,
198 I422,
199 I444,
200 Unknown,
201 }
202
203 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
204 pub enum PlanarImageComponent {
205 Y,
206 U,
207 V,
208 }
209
210 impl std::convert::From<usize> for PlanarImageComponent {
from(index: usize) -> Self211 fn from(index: usize) -> Self {
212 match index {
213 0 => PlanarImageComponent::Y,
214 1 => PlanarImageComponent::U,
215 2 => PlanarImageComponent::V,
216 _ => panic!("Invalid YUV index: {}", index),
217 }
218 }
219 }
220
221 impl std::convert::From<PlanarImageComponent> for usize {
from(component: PlanarImageComponent) -> Self222 fn from(component: PlanarImageComponent) -> Self {
223 match component {
224 PlanarImageComponent::Y => 0,
225 PlanarImageComponent::U => 1,
226 PlanarImageComponent::V => 2,
227 }
228 }
229 }
230
231 #[derive(Clone, Debug)]
232 pub struct Plane(Picture, PlanarImageComponent);
233
234 impl AsRef<[u8]> for Plane {
as_ref(&self) -> &[u8]235 fn as_ref(&self) -> &[u8] {
236 let (stride, height) = self.0.plane_data_geometry(self.1);
237 unsafe {
238 std::slice::from_raw_parts(
239 self.0.plane_data_ptr(self.1) as *const u8,
240 (stride * height) as usize,
241 )
242 }
243 }
244 }
245 unsafe impl Send for Plane {}
246 unsafe impl Sync for Plane {}
247
248 #[derive(Copy, Clone, Debug)]
249 pub struct BitsPerComponent(pub usize);
250
251 impl Picture {
stride(&self, component: PlanarImageComponent) -> u32252 pub fn stride(&self, component: PlanarImageComponent) -> u32 {
253 let s = match component {
254 PlanarImageComponent::Y => 0,
255 _ => 1,
256 };
257 (*self.inner).pic.stride[s] as u32
258 }
259
plane_data_ptr(&self, component: PlanarImageComponent) -> *mut c_void260 pub fn plane_data_ptr(&self, component: PlanarImageComponent) -> *mut c_void {
261 let index: usize = component.into();
262 (*self.inner).pic.data[index]
263 }
264
plane_data_geometry(&self, component: PlanarImageComponent) -> (u32, u32)265 pub fn plane_data_geometry(&self, component: PlanarImageComponent) -> (u32, u32) {
266 let height = match component {
267 PlanarImageComponent::Y => self.height(),
268 _ => match self.pixel_layout() {
269 PixelLayout::I420 => (self.height() + 1) / 2,
270 PixelLayout::I400 | PixelLayout::I422 | PixelLayout::I444 => self.height(),
271 PixelLayout::Unknown => unreachable!(),
272 },
273 };
274 (self.stride(component) as u32, height)
275 }
276
plane(&self, component: PlanarImageComponent) -> Plane277 pub fn plane(&self, component: PlanarImageComponent) -> Plane {
278 Plane(self.clone(), component)
279 }
280
bit_depth(&self) -> usize281 pub fn bit_depth(&self) -> usize {
282 (*self.inner).pic.p.bpc as usize
283 }
284
bits_per_component(&self) -> Option<BitsPerComponent>285 pub fn bits_per_component(&self) -> Option<BitsPerComponent> {
286 unsafe {
287 match (*(*self.inner).pic.seq_hdr).hbd {
288 0 => Some(BitsPerComponent(8)),
289 1 => Some(BitsPerComponent(10)),
290 2 => Some(BitsPerComponent(12)),
291 _ => None,
292 }
293 }
294 }
295
width(&self) -> u32296 pub fn width(&self) -> u32 {
297 (*self.inner).pic.p.w as u32
298 }
299
height(&self) -> u32300 pub fn height(&self) -> u32 {
301 (*self.inner).pic.p.h as u32
302 }
303
pixel_layout(&self) -> PixelLayout304 pub fn pixel_layout(&self) -> PixelLayout {
305 #[allow(non_upper_case_globals)]
306 match (*self.inner).pic.p.layout {
307 Dav1dPixelLayout_DAV1D_PIXEL_LAYOUT_I400 => PixelLayout::I400,
308 Dav1dPixelLayout_DAV1D_PIXEL_LAYOUT_I420 => PixelLayout::I420,
309 Dav1dPixelLayout_DAV1D_PIXEL_LAYOUT_I422 => PixelLayout::I422,
310 Dav1dPixelLayout_DAV1D_PIXEL_LAYOUT_I444 => PixelLayout::I444,
311 _ => PixelLayout::Unknown,
312 }
313 }
314
timestamp(&self) -> Option<i64>315 pub fn timestamp(&self) -> Option<i64> {
316 let ts = (*self.inner).pic.m.timestamp;
317 if ts == i64::MIN {
318 None
319 } else {
320 Some(ts)
321 }
322 }
323
duration(&self) -> i64324 pub fn duration(&self) -> i64 {
325 (*self.inner).pic.m.duration as i64
326 }
327
offset(&self) -> i64328 pub fn offset(&self) -> i64 {
329 (*self.inner).pic.m.offset
330 }
331 }
332
333 unsafe impl Send for Picture {}
334 unsafe impl Sync for Picture {}
335
336 impl Drop for InnerPicture {
drop(&mut self)337 fn drop(&mut self) {
338 unsafe {
339 dav1d_picture_unref(&mut self.pic);
340 }
341 }
342 }
343
parse_sequence_header<T: AsRef<[u8]>>(buf: T) -> Result<SequenceHeader, Error>344 pub fn parse_sequence_header<T: AsRef<[u8]>>(buf: T) -> Result<SequenceHeader, Error> {
345 let buf = buf.as_ref();
346 let len = buf.len();
347 unsafe {
348 let mut seq: Dav1dSequenceHeader = mem::zeroed();
349 let ret = dav1d_parse_sequence_header(&mut seq, buf.as_ptr(), len);
350 if ret < 0 {
351 Err(Error(ret))
352 } else {
353 Ok(SequenceHeader { seq: Arc::new(seq) })
354 }
355 }
356 }
357
358 #[derive(Debug)]
359 pub struct SequenceHeader {
360 seq: Arc<Dav1dSequenceHeader>,
361 }
362
363 impl SequenceHeader {}
364
365 impl Drop for SequenceHeader {
drop(&mut self)366 fn drop(&mut self) {
367 Arc::get_mut(&mut self.seq).unwrap();
368 }
369 }
370