Debian Codegraph @

debian/missing-sources/dav1d/src/lib.rs

raw
1 use dav1d_sys::*;
2
3 pub use av_data::pixel;
4 use std::ffi::{c_int, c_void};
5 use std::fmt::{self, Debug};
6 use std::i64;
7 use std::mem;
8 use std::ptr;
9 use std::sync::Arc;
10
11 /// Error enum return by various `dav1d` operations.
12 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
13 #[non_exhaustive]
14 pub enum Error {
15 /// Try again.
16 ///
17 /// If this is returned by [`Decoder::send_data`] or [`Decoder::send_pending_data`] then there
18 /// are decoded frames pending that first have to be retrieved via [`Decoder::get_picture`]
19 /// before processing any further pending data.
20 ///
21 /// If this is returned by [`Decoder::get_picture`] then no decoded frames are pending
22 /// currently and more data needs to be sent to the decoder.
23 Again,
24 /// Invalid argument.
25 ///
26 /// One of the arguments passed to the function was invalid.
27 InvalidArgument,
28 /// Not enough memory.
29 ///
30 /// Not enough memory is currently available for performing this operation.
31 NotEnoughMemory,
32 /// Unsupported bitstream.
33 ///
34 /// The provided bitstream is not supported by `dav1d`.
35 UnsupportedBitstream,
36 /// Unknown error.
37 UnknownError(i32),
38 }
39
40 impl From<i32> for Error {
41 fn from(err: i32) -> Self {
42 assert!(err < 0);
43
44 match err {
45 DAV1D_ERR_AGAIN => Error::Again,
46 DAV1D_ERR_INVAL => Error::InvalidArgument,
47 DAV1D_ERR_NOMEM => Error::NotEnoughMemory,
48 DAV1D_ERR_NOPROTOOPT => Error::UnsupportedBitstream,
49 _ => Error::UnknownError(err),
50 }
51 }
52 }
53
54 impl Error {
55 pub const fn is_again(&self) -> bool {
56 matches!(self, Error::Again)
57 }
58 }
59
60 impl fmt::Display for Error {
61 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
62 match self {
63 Error::Again => write!(fmt, "Try again"),
64 Error::InvalidArgument => write!(fmt, "Invalid argument"),
65 Error::NotEnoughMemory => write!(fmt, "Not enough memory available"),
66 Error::UnsupportedBitstream => write!(fmt, "Unsupported bitstream"),
67 Error::UnknownError(err) => write!(fmt, "Unknown error {}", err),
68 }
69 }
70 }
71
72 impl std::error::Error for Error {}
73
74 /// Picture parameters used for allocation.
75 #[derive(Debug)]
76 pub struct PictureParameters {
77 pic: ptr::NonNull<Dav1dPicture>,
78 }
79
80 impl PictureParameters {
81 /// Bit depth of the plane data.
82 ///
83 /// This returns 8 or 16 for the underlying integer type used for the plane data.
84 ///
85 /// Check [`PictureParameters::bits_per_component`] for the number of bits that are used.
86 pub fn bit_depth(&self) -> usize {
87 unsafe { self.pic.as_ref().p.bpc as usize }
88 }
89
90 /// Bits used per component of the plane data.
91 ///
92 /// Check [`PictureParameters::bit_depth`] for the number of storage bits.
93 pub fn bits_per_component(&self) -> Option<BitsPerComponent> {
94 unsafe {
95 match (*self.pic.as_ref().seq_hdr).hbd {
96 0 => Some(BitsPerComponent(8)),
97 1 => Some(BitsPerComponent(10)),
98 2 => Some(BitsPerComponent(12)),
99 _ => None,
100 }
101 }
102 }
103
104 /// Width of the frame.
105 pub fn width(&self) -> u32 {
106 unsafe { self.pic.as_ref().p.w as u32 }
107 }
108
109 /// Height of the frame.
110 pub fn height(&self) -> u32 {
111 unsafe { self.pic.as_ref().p.h as u32 }
112 }
113
114 /// Pixel layout of the frame.
115 pub fn pixel_layout(&self) -> PixelLayout {
116 unsafe {
117 #[allow(non_upper_case_globals)]
118 match self.pic.as_ref().p.layout {
119 DAV1D_PIXEL_LAYOUT_I400 => PixelLayout::I400,
120 DAV1D_PIXEL_LAYOUT_I420 => PixelLayout::I420,
121 DAV1D_PIXEL_LAYOUT_I422 => PixelLayout::I422,
122 DAV1D_PIXEL_LAYOUT_I444 => PixelLayout::I444,
123 _ => unreachable!(),
124 }
125 }
126 }
127
128 /// Chromaticity coordinates of the source colour primaries.
129 pub fn color_primaries(&self) -> pixel::ColorPrimaries {
130 unsafe {
131 #[allow(non_upper_case_globals)]
132 match (*self.pic.as_ref().seq_hdr).pri {
133 DAV1D_COLOR_PRI_BT709 => pixel::ColorPrimaries::BT709,
134 DAV1D_COLOR_PRI_UNKNOWN => pixel::ColorPrimaries::Unspecified,
135 DAV1D_COLOR_PRI_BT470M => pixel::ColorPrimaries::BT470M,
136 DAV1D_COLOR_PRI_BT470BG => pixel::ColorPrimaries::BT470BG,
137 DAV1D_COLOR_PRI_BT601 => pixel::ColorPrimaries::BT470BG,
138 DAV1D_COLOR_PRI_SMPTE240 => pixel::ColorPrimaries::ST240M,
139 DAV1D_COLOR_PRI_FILM => pixel::ColorPrimaries::Film,
140 DAV1D_COLOR_PRI_BT2020 => pixel::ColorPrimaries::BT2020,
141 DAV1D_COLOR_PRI_XYZ => pixel::ColorPrimaries::ST428,
142 DAV1D_COLOR_PRI_SMPTE431 => pixel::ColorPrimaries::P3DCI,
143 DAV1D_COLOR_PRI_SMPTE432 => pixel::ColorPrimaries::P3Display,
144 DAV1D_COLOR_PRI_EBU3213 => pixel::ColorPrimaries::Tech3213,
145 23..=DAV1D_COLOR_PRI_RESERVED => pixel::ColorPrimaries::Unspecified,
146 _ => unreachable!(),
147 }
148 }
149 }
150
151 /// Transfer characteristics function.
152 pub fn transfer_characteristic(&self) -> pixel::TransferCharacteristic {
153 unsafe {
154 #[allow(non_upper_case_globals)]
155 match (*self.pic.as_ref().seq_hdr).trc {
156 DAV1D_TRC_BT709 => pixel::TransferCharacteristic::BT1886,
157 DAV1D_TRC_UNKNOWN => pixel::TransferCharacteristic::Unspecified,
158 DAV1D_TRC_BT470M => pixel::TransferCharacteristic::BT470M,
159 DAV1D_TRC_BT470BG => pixel::TransferCharacteristic::BT470BG,
160 DAV1D_TRC_BT601 => pixel::TransferCharacteristic::ST170M,
161 DAV1D_TRC_SMPTE240 => pixel::TransferCharacteristic::ST240M,
162 DAV1D_TRC_LINEAR => pixel::TransferCharacteristic::Linear,
163 DAV1D_TRC_LOG100 => pixel::TransferCharacteristic::Logarithmic100,
164 DAV1D_TRC_LOG100_SQRT10 => pixel::TransferCharacteristic::Logarithmic316,
165 DAV1D_TRC_IEC61966 => pixel::TransferCharacteristic::SRGB,
166 DAV1D_TRC_BT1361 => pixel::TransferCharacteristic::BT1886,
167 DAV1D_TRC_SRGB => pixel::TransferCharacteristic::SRGB,
168 DAV1D_TRC_BT2020_10BIT => pixel::TransferCharacteristic::BT2020Ten,
169 DAV1D_TRC_BT2020_12BIT => pixel::TransferCharacteristic::BT2020Twelve,
170 DAV1D_TRC_SMPTE2084 => pixel::TransferCharacteristic::PerceptualQuantizer,
171 DAV1D_TRC_SMPTE428 => pixel::TransferCharacteristic::ST428,
172 DAV1D_TRC_HLG => pixel::TransferCharacteristic::HybridLogGamma,
173 19..=DAV1D_TRC_RESERVED => pixel::TransferCharacteristic::Unspecified,
174 _ => unreachable!(),
175 }
176 }
177 }
178
179 /// Matrix coefficients used in deriving luma and chroma signals from the
180 /// green, blue and red or X, Y and Z primaries.
181 pub fn matrix_coefficients(&self) -> pixel::MatrixCoefficients {
182 unsafe {
183 #[allow(non_upper_case_globals)]
184 match (*self.pic.as_ref().seq_hdr).mtrx {
185 DAV1D_MC_IDENTITY => pixel::MatrixCoefficients::Identity,
186 DAV1D_MC_BT709 => pixel::MatrixCoefficients::BT709,
187 DAV1D_MC_UNKNOWN => pixel::MatrixCoefficients::Unspecified,
188 DAV1D_MC_FCC => pixel::MatrixCoefficients::BT470M,
189 DAV1D_MC_BT470BG => pixel::MatrixCoefficients::BT470BG,
190 DAV1D_MC_BT601 => pixel::MatrixCoefficients::BT470BG,
191 DAV1D_MC_SMPTE240 => pixel::MatrixCoefficients::ST240M,
192 DAV1D_MC_SMPTE_YCGCO => pixel::MatrixCoefficients::YCgCo,
193 DAV1D_MC_BT2020_NCL => pixel::MatrixCoefficients::BT2020NonConstantLuminance,
194 DAV1D_MC_BT2020_CL => pixel::MatrixCoefficients::BT2020ConstantLuminance,
195 DAV1D_MC_SMPTE2085 => pixel::MatrixCoefficients::ST2085,
196 DAV1D_MC_CHROMAT_NCL => {
197 pixel::MatrixCoefficients::ChromaticityDerivedNonConstantLuminance
198 }
199 DAV1D_MC_CHROMAT_CL => {
200 pixel::MatrixCoefficients::ChromaticityDerivedConstantLuminance
201 }
202 DAV1D_MC_ICTCP => pixel::MatrixCoefficients::ICtCp,
203 15..=DAV1D_MC_RESERVED => pixel::MatrixCoefficients::Unspecified,
204 _ => unreachable!(),
205 }
206 }
207 }
208
209 /// YUV color range.
210 pub fn color_range(&self) -> pixel::YUVRange {
211 unsafe {
212 match (*self.pic.as_ref().seq_hdr).color_range {
213 0 => pixel::YUVRange::Limited,
214 _ => pixel::YUVRange::Full,
215 }
216 }
217 }
218
219 /// Sample position for subsampled chroma.
220 pub fn chroma_location(&self) -> pixel::ChromaLocation {
221 // According to y4m mapping declared in dav1d's output/y4m2.c and applied from FFmpeg's yuv4mpegdec.c
222 unsafe {
223 match (*self.pic.as_ref().seq_hdr).chr {
224 DAV1D_CHR_UNKNOWN | DAV1D_CHR_COLOCATED => pixel::ChromaLocation::Center,
225 DAV1D_CHR_VERTICAL => pixel::ChromaLocation::Left,
226 _ => unreachable!(),
227 }
228 }
229 }
230 }
231
232 // Number of bytes to align AND pad picture memory buffers by, so that SIMD
233 // implementations can over-read by a few bytes, and use aligned read/write
234 // instructions.
235 pub const PICTURE_ALIGNMENT: usize = 64;
236
237 /// Allocation for a picture.
238 #[derive(Debug, PartialEq, Eq)]
239 pub struct PictureAllocation<D: Send + 'static> {
240 /// Pointers to planar image data.
241 ///
242 /// Y is `data[0]`, U is `data[1]`, V is `data[2]`.
243 ///
244 /// The data should be `u8` (for 8 bits) or `u16` (for 10 bits).
245 ///
246 /// The `data[0]`, `data[1]` and `data[2]` must be [`PICTURE_ALIGNMENT`] byte aligned and with a pixel
247 /// width/height multiple of 128 pixels. Any allocated memory area should also be padded by
248 /// [`PICTURE_ALIGNMENT`] bytes.
249 ///
250 /// `data[1]` and `data[2]` must share the same `stride[1]`.
251 pub data: [*mut u8; 3],
252
253 /// Number of bytes between 2 lines in `data[]` for luma in case of `stride[0]` or chroma in
254 /// case of `stride[1]`.
255 pub stride: [isize; 2],
256
257 /// Allocator data that can be retrieved back from the picture later.
258 pub allocator_data: D,
259 }
260
261 unsafe impl<D: Send + 'static> Send for PictureAllocation<D> {}
262
263 /// Picture allocator trait.
264 ///
265 /// # Safety
266 ///
267 /// See documentation of [`PictureAllocator::alloc_picture`] and
268 /// [`PictureAllocator::release_picture`] for the requirements of this trait.
269 pub unsafe trait PictureAllocator: Send + Sync + 'static {
270 /// Allocator data that is stored together with the [`Picture`].
271 ///
272 /// This can be retrieved from the picture via [`Picture::allocator_data()`].
273 type AllocatorData: Send + 'static;
274
275 /// Allocate the picture buffer based on `pic_params`.
276 ///
277 /// See the [`PictureAllocation`] documentation for the requirements on the allocated memory.
278 ///
279 /// This function will be called on the main thread (the thread which calls
280 /// [`Decoder::get_picture()`]).
281 ///
282 /// # Safety
283 ///
284 /// This function needs to allocate enough memory with the constraints outlined in the
285 /// [`PictureAllocation`] documentation.
286 unsafe fn alloc_picture(
287 &self,
288 pic_params: &PictureParameters,
289 ) -> Result<PictureAllocation<Self::AllocatorData>, Error>;
290
291 /// Release the picture buffer.
292 ///
293 /// If frame threading is used, this function may be called by the main
294 /// thread (the thread which calls [`Decoder::get_picture()`]) or any of the frame
295 /// threads and thus must be thread-safe. If frame threading is not used,
296 /// this function will only be called on the main thread.
297 ///
298 /// # Safety
299 ///
300 /// This function needs to release the memory in `allocation` and can assume that it
301 /// corresponds to a previous call to [`PictureAllocator::alloc_picture()`].
302 unsafe fn release_picture(&self, allocation: PictureAllocation<Self::AllocatorData>);
303 }
304
305 /// Default allocator.
306 ///
307 /// Note that this allocator can't be directly instantiated.
308 #[derive(Debug)]
309 pub struct DefaultAllocator(());
310
311 unsafe impl PictureAllocator for DefaultAllocator {
312 type AllocatorData = ();
313
314 unsafe fn alloc_picture(
315 &self,
316 _pic_params: &PictureParameters,
317 ) -> Result<PictureAllocation<Self::AllocatorData>, Error> {
318 unimplemented!()
319 }
320
321 unsafe fn release_picture(&self, _allocation: PictureAllocation<Self::AllocatorData>) {
322 unimplemented!()
323 }
324 }
325
326 /// Settings for creating a new [`Decoder`] instance.
327 /// See documentation for native `Dav1dSettings` struct.
328 #[derive(Debug)]
329 pub struct Settings {
330 dav1d_settings: Dav1dSettings,
331 }
332
333 unsafe impl Send for Settings {}
334 unsafe impl Sync for Settings {}
335
336 impl Default for Settings {
337 fn default() -> Self {
338 Self::new()
339 }
340 }
341
342 impl Settings {
343 /// Creates a new [`Settings`] instance with default settings.
344 pub fn new() -> Self {
345 unsafe {
346 let mut dav1d_settings = mem::MaybeUninit::uninit();
347
348 dav1d_default_settings(dav1d_settings.as_mut_ptr());
349
350 Self {
351 dav1d_settings: dav1d_settings.assume_init(),
352 }
353 }
354 }
355
356 pub fn set_n_threads(&mut self, n_threads: u32) {
357 self.dav1d_settings.n_threads = n_threads as i32;
358 }
359
360 pub fn get_n_threads(&self) -> u32 {
361 self.dav1d_settings.n_threads as u32
362 }
363
364 pub fn set_max_frame_delay(&mut self, max_frame_delay: u32) {
365 self.dav1d_settings.max_frame_delay = max_frame_delay as i32;
366 }
367
368 pub fn get_max_frame_delay(&self) -> u32 {
369 self.dav1d_settings.max_frame_delay as u32
370 }
371
372 pub fn set_apply_grain(&mut self, apply_grain: bool) {
373 self.dav1d_settings.apply_grain = i32::from(apply_grain);
374 }
375
376 pub fn get_apply_grain(&self) -> bool {
377 self.dav1d_settings.apply_grain != 0
378 }
379
380 pub fn set_operating_point(&mut self, operating_point: u32) {
381 self.dav1d_settings.operating_point = operating_point as i32;
382 }
383
384 pub fn get_operating_point(&self) -> u32 {
385 self.dav1d_settings.operating_point as u32
386 }
387
388 pub fn set_all_layers(&mut self, all_layers: bool) {
389 self.dav1d_settings.all_layers = i32::from(all_layers);
390 }
391
392 pub fn get_all_layers(&self) -> bool {
393 self.dav1d_settings.all_layers != 0
394 }
395
396 pub fn set_frame_size_limit(&mut self, frame_size_limit: u32) {
397 self.dav1d_settings.frame_size_limit = frame_size_limit;
398 }
399
400 pub fn get_frame_size_limit(&self) -> u32 {
401 self.dav1d_settings.frame_size_limit
402 }
403
404 pub fn set_strict_std_compliance(&mut self, strict_std_compliance: bool) {
405 self.dav1d_settings.strict_std_compliance = i32::from(strict_std_compliance);
406 }
407
408 pub fn get_strict_std_compliance(&self) -> bool {
409 self.dav1d_settings.strict_std_compliance != 0
410 }
411
412 pub fn set_output_invisible_frames(&mut self, output_invisible_frames: bool) {
413 self.dav1d_settings.output_invisible_frames = i32::from(output_invisible_frames);
414 }
415
416 pub fn get_output_invisible_frames(&self) -> bool {
417 self.dav1d_settings.output_invisible_frames != 0
418 }
419
420 pub fn set_inloop_filters(&mut self, inloop_filters: InloopFilterType) {
421 self.dav1d_settings.inloop_filters = inloop_filters.bits();
422 }
423
424 pub fn get_inloop_filters(&self) -> InloopFilterType {
425 InloopFilterType::from_bits_truncate(self.dav1d_settings.inloop_filters)
426 }
427
428 pub fn set_decode_frame_type(&mut self, decode_frame_type: DecodeFrameType) {
429 self.dav1d_settings.decode_frame_type = decode_frame_type.into();
430 }
431
432 pub fn get_decode_frame_type(&self) -> DecodeFrameType {
433 DecodeFrameType::try_from(self.dav1d_settings.decode_frame_type)
434 .expect("Invalid Dav1dDecodeFrameType")
435 }
436 }
437
438 bitflags::bitflags! {
439 #[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
440 pub struct InloopFilterType: u32 {
441 const DEBLOCK = DAV1D_INLOOPFILTER_DEBLOCK;
442 const CDEF = DAV1D_INLOOPFILTER_CDEF;
443 const RESTORATION = DAV1D_INLOOPFILTER_RESTORATION;
444 }
445 }
446
447 #[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
448 pub enum DecodeFrameType {
449 #[default]
450 All,
451 Reference,
452 Intra,
453 Key,
454 }
455
456 impl TryFrom<u32> for DecodeFrameType {
457 type Error = TryFromEnumError;
458
459 fn try_from(value: u32) -> Result<Self, Self::Error> {
460 match value {
461 DAV1D_DECODEFRAMETYPE_ALL => Ok(DecodeFrameType::All),
462 DAV1D_DECODEFRAMETYPE_REFERENCE => Ok(DecodeFrameType::Reference),
463 DAV1D_DECODEFRAMETYPE_INTRA => Ok(DecodeFrameType::Intra),
464 DAV1D_DECODEFRAMETYPE_KEY => Ok(DecodeFrameType::Key),
465 _ => Err(TryFromEnumError(())),
466 }
467 }
468 }
469
470 impl From<DecodeFrameType> for u32 {
471 fn from(v: DecodeFrameType) -> u32 {
472 match v {
473 DecodeFrameType::All => DAV1D_DECODEFRAMETYPE_ALL,
474 DecodeFrameType::Reference => DAV1D_DECODEFRAMETYPE_REFERENCE,
475 DecodeFrameType::Intra => DAV1D_DECODEFRAMETYPE_INTRA,
476 DecodeFrameType::Key => DAV1D_DECODEFRAMETYPE_KEY,
477 }
478 }
479 }
480
481 /// The error type returned when a conversion from a C enum fails.
482 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
483 pub struct TryFromEnumError(());
484
485 impl std::fmt::Display for TryFromEnumError {
486 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
487 fmt.write_str("Invalid enum value")
488 }
489 }
490
491 impl From<std::convert::Infallible> for TryFromEnumError {
492 fn from(x: std::convert::Infallible) -> TryFromEnumError {
493 match x {}
494 }
495 }
496
497 impl std::error::Error for TryFromEnumError {}
498
499 /// A `dav1d` decoder instance.
500 #[derive(Debug)]
501 pub struct Decoder<A: PictureAllocator = DefaultAllocator> {
502 dec: ptr::NonNull<Dav1dContext>,
503 pending_data: Option<Dav1dData>,
504 allocator: Option<Arc<A>>,
505 }
506
507 static_assertions::assert_impl_all!(Decoder<DefaultAllocator>: Send, Sync, Debug);
508
509 unsafe extern "C" fn release_wrapped_data<T: AsRef<[u8]>>(_data: *const u8, cookie: *mut c_void) {
510 let buf = Box::from_raw(cookie as *mut T);
511 drop(buf);
512 }
513
514 impl Decoder {
515 /// Creates a new [`Decoder`] instance with given [`Settings`].
516 pub fn with_settings(settings: &Settings) -> Result<Self, Error> {
517 unsafe {
518 let mut dec = mem::MaybeUninit::uninit();
519
520 let ret = dav1d_open(dec.as_mut_ptr(), &settings.dav1d_settings);
521
522 if ret < 0 {
523 return Err(Error::from(ret));
524 }
525
526 Ok(Decoder {
527 dec: ptr::NonNull::new(dec.assume_init()).unwrap(),
528 pending_data: None,
529 allocator: None,
530 })
531 }
532 }
533
534 /// Creates a new [`Decoder`] instance with the default settings.
535 pub fn new() -> Result<Self, Error> {
536 Self::with_settings(&Settings::default())
537 }
538 }
539
540 unsafe extern "C" fn alloc_picture_callback<A: PictureAllocator>(
541 pic: *mut Dav1dPicture,
542 cookie: *mut c_void,
543 ) -> c_int {
544 let allocator = &*(cookie as *const A);
545
546 let pic_parameters = PictureParameters {
547 pic: ptr::NonNull::new_unchecked(pic),
548 };
549
550 let res = allocator.alloc_picture(&pic_parameters);
551 match res {
552 Ok(allocation) => {
553 (*pic).data[0] = allocation.data[0] as *mut c_void;
554 (*pic).data[1] = allocation.data[1] as *mut c_void;
555 (*pic).data[2] = allocation.data[2] as *mut c_void;
556 (*pic).stride[0] = allocation.stride[0];
557 (*pic).stride[1] = allocation.stride[1];
558 (*pic).allocator_data =
559 Box::into_raw(Box::new(allocation.allocator_data)) as *mut c_void;
560
561 0
562 }
563 Err(err) => match err {
564 Error::Again => DAV1D_ERR_AGAIN,
565 Error::InvalidArgument => DAV1D_ERR_INVAL,
566 Error::NotEnoughMemory => DAV1D_ERR_NOMEM,
567 Error::UnsupportedBitstream => DAV1D_ERR_NOPROTOOPT,
568 Error::UnknownError(err) => {
569 assert!(err < 0);
570 err
571 }
572 },
573 }
574 }
575
576 unsafe extern "C" fn release_picture_callback<A: PictureAllocator>(
577 pic: *mut Dav1dPicture,
578 cookie: *mut c_void,
579 ) {
580 let allocator = &*(cookie as *const A);
581 let allocator_data = Box::from_raw((*pic).allocator_data as *mut A::AllocatorData);
582 let allocation = PictureAllocation {
583 data: [
584 (*pic).data[0] as *mut u8,
585 (*pic).data[1] as *mut u8,
586 (*pic).data[2] as *mut u8,
587 ],
588 stride: (*pic).stride,
589 allocator_data: *allocator_data,
590 };
591 allocator.release_picture(allocation);
592 }
593
594 impl<A: PictureAllocator> Decoder<A> {
595 /// Creates a new [`Decoder`] instance with given [`Settings`] and [`PictureAllocator`].
596 pub fn with_settings_and_allocator(settings: &Settings, allocator: A) -> Result<Self, Error> {
597 unsafe {
598 let allocator = Arc::new(allocator);
599
600 let mut dec = mem::MaybeUninit::uninit();
601
602 let settings = Dav1dSettings {
603 allocator: Dav1dPicAllocator {
604 cookie: &*allocator as *const A as *mut c_void,
605 alloc_picture_callback: Some(alloc_picture_callback::<A>),
606 release_picture_callback: Some(release_picture_callback::<A>),
607 },
608 ..settings.dav1d_settings
609 };
610 let ret = dav1d_open(dec.as_mut_ptr(), &settings);
611
612 if ret < 0 {
613 return Err(Error::from(ret));
614 }
615
616 Ok(Decoder {
617 dec: ptr::NonNull::new(dec.assume_init()).unwrap(),
618 pending_data: None,
619 allocator: Some(allocator),
620 })
621 }
622 }
623
624 /// Creates a new [`Decoder`] instance with the default settings and the given
625 /// [`PictureAllocator`].
626 pub fn with_allocator(allocator: A) -> Result<Self, Error> {
627 Self::with_settings_and_allocator(&Settings::default(), allocator)
628 }
629 }
630
631 impl<A: PictureAllocator> Decoder<A> {
632 /// Flush the decoder.
633 ///
634 /// This flushes all delayed frames in the decoder and clears the internal decoder state.
635 ///
636 /// All currently pending frames are available afterwards via [`Decoder::get_picture`].
637 pub fn flush(&mut self) {
638 unsafe {
639 dav1d_flush(self.dec.as_ptr());
640 if let Some(mut pending_data) = self.pending_data.take() {
641 dav1d_data_unref(&mut pending_data);
642 }
643 }
644 }
645
646 /// Send new AV1 data to the decoder.
647 ///
648 /// After this returned `Ok(())` or `Err([Error::Again])` there might be decoded frames
649 /// available via [`Decoder::get_picture`].
650 ///
651 /// # Panics
652 ///
653 /// If a previous call returned [`Error::Again`] then this must not be called again until
654 /// [`Decoder::send_pending_data`] has returned `Ok(())`.
655 pub fn send_data<T: AsRef<[u8]> + Send + 'static>(
656 &mut self,
657 buf: T,
658 offset: Option<i64>,
659 timestamp: Option<i64>,
660 duration: Option<i64>,
661 ) -> Result<(), Error> {
662 assert!(
663 self.pending_data.is_none(),
664 "Have pending data that needs to be handled first"
665 );
666
667 let buf = Box::new(buf);
668 let slice = (*buf).as_ref();
669 let len = slice.len();
670
671 unsafe {
672 let mut data: Dav1dData = mem::zeroed();
673 let _ret = dav1d_data_wrap(
674 &mut data,
675 slice.as_ptr(),
676 len,
677 Some(release_wrapped_data::<T>),
678 Box::into_raw(buf) as *mut c_void,
679 );
680 if let Some(offset) = offset {
681 data.m.offset = offset;
682 }
683 if let Some(timestamp) = timestamp {
684 data.m.timestamp = timestamp;
685 }
686 if let Some(duration) = duration {
687 data.m.duration = duration;
688 }
689
690 let ret = dav1d_send_data(self.dec.as_ptr(), &mut data);
691 if ret < 0 {
692 let ret = Error::from(ret);
693
694 if ret.is_again() {
695 self.pending_data = Some(data);
696 } else {
697 dav1d_data_unref(&mut data);
698 }
699
700 return Err(ret);
701 }
702
703 if data.sz > 0 {
704 self.pending_data = Some(data);
705 return Err(Error::Again);
706 }
707
708 Ok(())
709 }
710 }
711
712 /// Sends any pending data to the decoder.
713 ///
714 /// This has to be called after [`Decoder::send_data`] has returned `Err([Error::Again])` to
715 /// consume any futher pending data.
716 ///
717 /// After this returned `Ok(())` or `Err([Error::Again])` there might be decoded frames
718 /// available via [`Decoder::get_picture`].
719 pub fn send_pending_data(&mut self) -> Result<(), Error> {
720 let mut data = match self.pending_data.take() {
721 None => {
722 return Ok(());
723 }
724 Some(data) => data,
725 };
726
727 unsafe {
728 let ret = dav1d_send_data(self.dec.as_ptr(), &mut data);
729 if ret < 0 {
730 let ret = Error::from(ret);
731
732 if ret.is_again() {
733 self.pending_data = Some(data);
734 } else {
735 dav1d_data_unref(&mut data);
736 }
737
738 return Err(ret);
739 }
740
741 if data.sz > 0 {
742 self.pending_data = Some(data);
743 return Err(Error::Again);
744 }
745
746 Ok(())
747 }
748 }
749
750 /// Get the next decoded frame from the decoder.
751 ///
752 /// If this returns `Err([Error::Again])` then further data has to be sent to the decoder
753 /// before further decoded frames become available.
754 ///
755 /// To make most use of frame threading this function should only be called once per submitted
756 /// input frame and not until it returns `Err([Error::Again])`. Calling it in a loop should
757 /// only be done to drain all pending frames at the end.
758 pub fn get_picture(&mut self) -> Result<Picture<A>, Error> {
759 unsafe {
760 let mut pic: Dav1dPicture = mem::zeroed();
761 let ret = dav1d_get_picture(self.dec.as_ptr(), &mut pic);
762
763 if ret < 0 {
764 Err(Error::from(ret))
765 } else {
766 let inner = InnerPicture { pic };
767 Ok(Picture {
768 inner: Arc::new(inner),
769 allocator: self.allocator.clone(),
770 })
771 }
772 }
773 }
774
775 /// Get the decoder delay.
776 pub fn get_frame_delay(&self) -> Result<u32, Error> {
777 unsafe {
778 let ret = dav1d_get_frame_delay(self.dec.as_ptr());
779 if ret < 0 {
780 Err(Error::from(ret))
781 } else {
782 Ok(ret as u32)
783 }
784 }
785 }
786 }
787
788 impl<A: PictureAllocator> Drop for Decoder<A> {
789 fn drop(&mut self) {
790 unsafe {
791 if let Some(mut pending_data) = self.pending_data.take() {
792 dav1d_data_unref(&mut pending_data);
793 }
794 let mut dec = self.dec.as_ptr();
795 dav1d_close(&mut dec);
796 };
797 }
798 }
799
800 unsafe impl<A: PictureAllocator> Send for Decoder<A> {}
801 unsafe impl<A: PictureAllocator> Sync for Decoder<A> {}
802
803 #[derive(Debug)]
804 struct InnerPicture {
805 pub pic: Dav1dPicture,
806 }
807
808 /// A decoded frame.
809 #[derive(Debug)]
810 pub struct Picture<A: PictureAllocator = DefaultAllocator> {
811 inner: Arc<InnerPicture>,
812 allocator: Option<Arc<A>>,
813 }
814
815 impl<A: PictureAllocator> Clone for Picture<A> {
816 fn clone(&self) -> Self {
817 Picture {
818 inner: self.inner.clone(),
819 allocator: self.allocator.clone(),
820 }
821 }
822 }
823
824 /// Pixel layout of a frame.
825 #[derive(Debug, Eq, PartialEq, Copy, Clone)]
826 pub enum PixelLayout {
827 /// Monochrome.
828 I400,
829 /// 4:2:0 planar.
830 I420,
831 /// 4:2:2 planar.
832 I422,
833 /// 4:4:4 planar.
834 I444,
835 }
836
837 /// Frame component.
838 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
839 pub enum PlanarImageComponent {
840 /// Y component.
841 Y,
842 /// U component.
843 U,
844 /// V component.
845 V,
846 }
847
848 impl From<usize> for PlanarImageComponent {
849 fn from(index: usize) -> Self {
850 match index {
851 0 => PlanarImageComponent::Y,
852 1 => PlanarImageComponent::U,
853 2 => PlanarImageComponent::V,
854 _ => panic!("Invalid YUV index: {}", index),
855 }
856 }
857 }
858
859 impl From<PlanarImageComponent> for usize {
860 fn from(component: PlanarImageComponent) -> Self {
861 match component {
862 PlanarImageComponent::Y => 0,
863 PlanarImageComponent::U => 1,
864 PlanarImageComponent::V => 2,
865 }
866 }
867 }
868
869 /// A single plane of a decoded frame.
870 ///
871 /// This can be used like a `&[u8]`.
872 #[derive(Debug)]
873 pub struct Plane<A: PictureAllocator = DefaultAllocator>(Picture<A>, PlanarImageComponent);
874
875 impl<A: PictureAllocator> Clone for Plane<A> {
876 fn clone(&self) -> Self {
877 Plane(self.0.clone(), self.1)
878 }
879 }
880
881 impl<A: PictureAllocator> AsRef<[u8]> for Plane<A> {
882 fn as_ref(&self) -> &[u8] {
883 let (stride, height) = self.0.plane_data_geometry(self.1);
884 let data = self.0.plane_data_ptr(self.1) as *const u8;
885 if stride == 0 || data.is_null() {
886 return &[];
887 }
888 unsafe { std::slice::from_raw_parts(data, stride as usize * height as usize) }
889 }
890 }
891
892 impl<A: PictureAllocator> std::ops::Deref for Plane<A> {
893 type Target = [u8];
894
895 fn deref(&self) -> &Self::Target {
896 self.as_ref()
897 }
898 }
899
900 static_assertions::assert_impl_all!(Plane<DefaultAllocator>: Send, Sync, Clone, Debug);
901
902 /// Number of bits per component.
903 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
904 pub struct BitsPerComponent(pub usize);
905
906 impl<A: PictureAllocator> Picture<A> {
907 /// Stride in pixels of the `component` for the decoded frame.
908 pub fn stride(&self, component: PlanarImageComponent) -> u32 {
909 let s = match component {
910 PlanarImageComponent::Y => 0,
911 _ => 1,
912 };
913 self.inner.pic.stride[s] as u32
914 }
915
916 /// Raw pointer to the data of the `component` for the decoded frame.
917 pub fn plane_data_ptr(&self, component: PlanarImageComponent) -> *mut c_void {
918 let index: usize = component.into();
919 self.inner.pic.data[index]
920 }
921
922 /// Plane geometry of the `component` for the decoded frame.
923 ///
924 /// This returns the stride and height.
925 pub fn plane_data_geometry(&self, component: PlanarImageComponent) -> (u32, u32) {
926 let height = match component {
927 PlanarImageComponent::Y => self.height(),
928 _ => match self.pixel_layout() {
929 PixelLayout::I420 => (self.height() + 1) / 2,
930 PixelLayout::I400 | PixelLayout::I422 | PixelLayout::I444 => self.height(),
931 },
932 };
933 (self.stride(component), height)
934 }
935
936 /// Plane data of the `component` for the decoded frame.
937 pub fn plane(&self, component: PlanarImageComponent) -> Plane<A> {
938 Plane(self.clone(), component)
939 }
940
941 /// Bit depth of the plane data.
942 ///
943 /// This returns 8 or 16 for the underlying integer type used for the plane data.
944 ///
945 /// Check [`Picture::bits_per_component`] for the number of bits that are used.
946 pub fn bit_depth(&self) -> usize {
947 self.inner.pic.p.bpc as usize
948 }
949
950 /// Bits used per component of the plane data.
951 ///
952 /// Check [`Picture::bit_depth`] for the number of storage bits.
953 pub fn bits_per_component(&self) -> Option<BitsPerComponent> {
954 unsafe {
955 match (*self.inner.pic.seq_hdr).hbd {
956 0 => Some(BitsPerComponent(8)),
957 1 => Some(BitsPerComponent(10)),
958 2 => Some(BitsPerComponent(12)),
959 _ => None,
960 }
961 }
962 }
963
964 /// Width of the frame.
965 pub fn width(&self) -> u32 {
966 self.inner.pic.p.w as u32
967 }
968
969 /// Height of the frame.
970 pub fn height(&self) -> u32 {
971 self.inner.pic.p.h as u32
972 }
973
974 /// Pixel layout of the frame.
975 pub fn pixel_layout(&self) -> PixelLayout {
976 #[allow(non_upper_case_globals)]
977 match self.inner.pic.p.layout {
978 DAV1D_PIXEL_LAYOUT_I400 => PixelLayout::I400,
979 DAV1D_PIXEL_LAYOUT_I420 => PixelLayout::I420,
980 DAV1D_PIXEL_LAYOUT_I422 => PixelLayout::I422,
981 DAV1D_PIXEL_LAYOUT_I444 => PixelLayout::I444,
982 _ => unreachable!(),
983 }
984 }
985
986 /// Timestamp of the frame.
987 ///
988 /// This is the same timestamp as the one provided to [`Decoder::send_data`].
989 pub fn timestamp(&self) -> Option<i64> {
990 let ts = self.inner.pic.m.timestamp;
991 if ts == i64::MIN {
992 None
993 } else {
994 Some(ts)
995 }
996 }
997
998 /// Duration of the frame.
999 ///
1000 /// This is the same duration as the one provided to [`Decoder::send_data`] or `0` if none was
1001 /// provided.
1002 pub fn duration(&self) -> i64 {
1003 self.inner.pic.m.duration
1004 }
1005
1006 /// Offset of the frame.
1007 ///
1008 /// This is the same offset as the one provided to [`Decoder::send_data`] or `-1` if none was
1009 /// provided.
1010 pub fn offset(&self) -> i64 {
1011 self.inner.pic.m.offset
1012 }
1013
1014 /// Chromaticity coordinates of the source colour primaries.
1015 pub fn color_primaries(&self) -> pixel::ColorPrimaries {
1016 unsafe {
1017 #[allow(non_upper_case_globals)]
1018 match (*self.inner.pic.seq_hdr).pri {
1019 DAV1D_COLOR_PRI_BT709 => pixel::ColorPrimaries::BT709,
1020 DAV1D_COLOR_PRI_UNKNOWN => pixel::ColorPrimaries::Unspecified,
1021 DAV1D_COLOR_PRI_BT470M => pixel::ColorPrimaries::BT470M,
1022 DAV1D_COLOR_PRI_BT470BG => pixel::ColorPrimaries::BT470BG,
1023 DAV1D_COLOR_PRI_BT601 => pixel::ColorPrimaries::BT470BG,
1024 DAV1D_COLOR_PRI_SMPTE240 => pixel::ColorPrimaries::ST240M,
1025 DAV1D_COLOR_PRI_FILM => pixel::ColorPrimaries::Film,
1026 DAV1D_COLOR_PRI_BT2020 => pixel::ColorPrimaries::BT2020,
1027 DAV1D_COLOR_PRI_XYZ => pixel::ColorPrimaries::ST428,
1028 DAV1D_COLOR_PRI_SMPTE431 => pixel::ColorPrimaries::P3DCI,
1029 DAV1D_COLOR_PRI_SMPTE432 => pixel::ColorPrimaries::P3Display,
1030 DAV1D_COLOR_PRI_EBU3213 => pixel::ColorPrimaries::Tech3213,
1031 23..=DAV1D_COLOR_PRI_RESERVED => pixel::ColorPrimaries::Unspecified,
1032 _ => unreachable!(),
1033 }
1034 }
1035 }
1036
1037 /// Transfer characteristics function.
1038 pub fn transfer_characteristic(&self) -> pixel::TransferCharacteristic {
1039 unsafe {
1040 #[allow(non_upper_case_globals)]
1041 match (*self.inner.pic.seq_hdr).trc {
1042 DAV1D_TRC_BT709 => pixel::TransferCharacteristic::BT1886,
1043 DAV1D_TRC_UNKNOWN => pixel::TransferCharacteristic::Unspecified,
1044 DAV1D_TRC_BT470M => pixel::TransferCharacteristic::BT470M,
1045 DAV1D_TRC_BT470BG => pixel::TransferCharacteristic::BT470BG,
1046 DAV1D_TRC_BT601 => pixel::TransferCharacteristic::ST170M,
1047 DAV1D_TRC_SMPTE240 => pixel::TransferCharacteristic::ST240M,
1048 DAV1D_TRC_LINEAR => pixel::TransferCharacteristic::Linear,
1049 DAV1D_TRC_LOG100 => pixel::TransferCharacteristic::Logarithmic100,
1050 DAV1D_TRC_LOG100_SQRT10 => pixel::TransferCharacteristic::Logarithmic316,
1051 DAV1D_TRC_IEC61966 => pixel::TransferCharacteristic::SRGB,
1052 DAV1D_TRC_BT1361 => pixel::TransferCharacteristic::BT1886,
1053 DAV1D_TRC_SRGB => pixel::TransferCharacteristic::SRGB,
1054 DAV1D_TRC_BT2020_10BIT => pixel::TransferCharacteristic::BT2020Ten,
1055 DAV1D_TRC_BT2020_12BIT => pixel::TransferCharacteristic::BT2020Twelve,
1056 DAV1D_TRC_SMPTE2084 => pixel::TransferCharacteristic::PerceptualQuantizer,
1057 DAV1D_TRC_SMPTE428 => pixel::TransferCharacteristic::ST428,
1058 DAV1D_TRC_HLG => pixel::TransferCharacteristic::HybridLogGamma,
1059 19..=DAV1D_TRC_RESERVED => pixel::TransferCharacteristic::Unspecified,
1060 _ => unreachable!(),
1061 }
1062 }
1063 }
1064
1065 /// Matrix coefficients used in deriving luma and chroma signals from the
1066 /// green, blue and red or X, Y and Z primaries.
1067 pub fn matrix_coefficients(&self) -> pixel::MatrixCoefficients {
1068 unsafe {
1069 #[allow(non_upper_case_globals)]
1070 match (*self.inner.pic.seq_hdr).mtrx {
1071 DAV1D_MC_IDENTITY => pixel::MatrixCoefficients::Identity,
1072 DAV1D_MC_BT709 => pixel::MatrixCoefficients::BT709,
1073 DAV1D_MC_UNKNOWN => pixel::MatrixCoefficients::Unspecified,
1074 DAV1D_MC_FCC => pixel::MatrixCoefficients::BT470M,
1075 DAV1D_MC_BT470BG => pixel::MatrixCoefficients::BT470BG,
1076 DAV1D_MC_BT601 => pixel::MatrixCoefficients::BT470BG,
1077 DAV1D_MC_SMPTE240 => pixel::MatrixCoefficients::ST240M,
1078 DAV1D_MC_SMPTE_YCGCO => pixel::MatrixCoefficients::YCgCo,
1079 DAV1D_MC_BT2020_NCL => pixel::MatrixCoefficients::BT2020NonConstantLuminance,
1080 DAV1D_MC_BT2020_CL => pixel::MatrixCoefficients::BT2020ConstantLuminance,
1081 DAV1D_MC_SMPTE2085 => pixel::MatrixCoefficients::ST2085,
1082 DAV1D_MC_CHROMAT_NCL => {
1083 pixel::MatrixCoefficients::ChromaticityDerivedNonConstantLuminance
1084 }
1085 DAV1D_MC_CHROMAT_CL => {
1086 pixel::MatrixCoefficients::ChromaticityDerivedConstantLuminance
1087 }
1088 DAV1D_MC_ICTCP => pixel::MatrixCoefficients::ICtCp,
1089 15..=DAV1D_MC_RESERVED => pixel::MatrixCoefficients::Unspecified,
1090 _ => unreachable!(),
1091 }
1092 }
1093 }
1094
1095 /// YUV color range.
1096 pub fn color_range(&self) -> pixel::YUVRange {
1097 unsafe {
1098 match (*self.inner.pic.seq_hdr).color_range {
1099 0 => pixel::YUVRange::Limited,
1100 _ => pixel::YUVRange::Full,
1101 }
1102 }
1103 }
1104
1105 /// Sample position for subsampled chroma.
1106 pub fn chroma_location(&self) -> pixel::ChromaLocation {
1107 // According to y4m mapping declared in dav1d's output/y4m2.c and applied from FFmpeg's yuv4mpegdec.c
1108 unsafe {
1109 match (*self.inner.pic.seq_hdr).chr {
1110 DAV1D_CHR_UNKNOWN | DAV1D_CHR_COLOCATED => pixel::ChromaLocation::Center,
1111 DAV1D_CHR_VERTICAL => pixel::ChromaLocation::Left,
1112 _ => unreachable!(),
1113 }
1114 }
1115 }
1116
1117 /// Allocator data of the picture.
1118 pub fn allocator_data(&self) -> Option<&A::AllocatorData> {
1119 unsafe {
1120 if self.inner.pic.allocator_data.is_null() {
1121 None
1122 } else {
1123 Some(&*(self.inner.pic.allocator_data as *const A::AllocatorData))
1124 }
1125 }
1126 }
1127
1128 /// Content light level information.
1129 pub fn content_light(&self) -> Option<ContentLightLevel> {
1130 unsafe {
1131 if self.inner.pic.content_light.is_null() {
1132 None
1133 } else {
1134 Some(ContentLightLevel {
1135 max_content_light_level: (*self.inner.pic.content_light)
1136 .max_content_light_level,
1137 max_frame_average_light_level: (*self.inner.pic.content_light)
1138 .max_frame_average_light_level,
1139 })
1140 }
1141 }
1142 }
1143
1144 ///Mastering display information.
1145 pub fn mastering_display(&self) -> Option<MasteringDisplay> {
1146 unsafe {
1147 if self.inner.pic.mastering_display.is_null() {
1148 None
1149 } else {
1150 Some(MasteringDisplay {
1151 primaries: (*self.inner.pic.mastering_display).primaries,
1152 white_point: (*self.inner.pic.mastering_display).white_point,
1153 max_luminance: (*self.inner.pic.mastering_display).max_luminance,
1154 min_luminance: (*self.inner.pic.mastering_display).min_luminance,
1155 })
1156 }
1157 }
1158 }
1159 }
1160
1161 static_assertions::assert_impl_all!(Picture<DefaultAllocator>: Send, Sync, Clone, Debug);
1162
1163 unsafe impl Send for InnerPicture {}
1164 unsafe impl Sync for InnerPicture {}
1165
1166 impl Drop for InnerPicture {
1167 fn drop(&mut self) {
1168 unsafe {
1169 dav1d_picture_unref(&mut self.pic);
1170 }
1171 }
1172 }
1173
1174 #[cfg(test)]
1175 mod test {
1176 use std::{
1177 collections::HashSet,
1178 fmt, ptr,
1179 sync::{self, atomic},
1180 };
1181
1182 mod ivf {
1183 use bitstream_io::{ByteRead, ByteReader, LittleEndian};
1184 use std::io;
1185
1186 #[derive(Debug, PartialEq, Eq)]
1187 pub struct Header {
1188 pub tag: [u8; 4],
1189 pub w: u16,
1190 pub h: u16,
1191 pub timebase_num: u32,
1192 pub timebase_den: u32,
1193 }
1194
1195 pub fn read_header(r: &mut dyn io::Read) -> io::Result<Header> {
1196 let mut br = ByteReader::endian(r, LittleEndian);
1197
1198 let mut signature = [0u8; 4];
1199 let mut tag = [0u8; 4];
1200
1201 br.read_bytes(&mut signature)?;
1202 let _v0 = br.read::<u16>()?;
1203 let _v1 = br.read::<u16>()?;
1204 br.read_bytes(&mut tag)?;
1205
1206 let w = br.read::<u16>()?;
1207 let h = br.read::<u16>()?;
1208
1209 let timebase_den = br.read::<u32>()?;
1210 let timebase_num = br.read::<u32>()?;
1211
1212 let _ = br.read::<u32>()?;
1213 let _ = br.read::<u32>()?;
1214
1215 Ok(Header {
1216 tag,
1217 w,
1218 h,
1219 timebase_num,
1220 timebase_den,
1221 })
1222 }
1223
1224 pub struct Packet {
1225 pub data: Box<[u8]>,
1226 pub pts: u64,
1227 }
1228
1229 pub fn read_packet(r: &mut dyn io::Read) -> io::Result<Packet> {
1230 let mut br = ByteReader::endian(r, LittleEndian);
1231
1232 let len = br.read::<u32>()?;
1233 let pts = br.read::<u64>()?;
1234 let mut buf = vec![0u8; len as usize];
1235
1236 br.read_bytes(&mut buf)?;
1237
1238 Ok(Packet {
1239 data: buf.into_boxed_slice(),
1240 pts,
1241 })
1242 }
1243 }
1244
1245 static TEST_FILE_420_8: &[u8] = include_bytes!("../test-420-8.ivf");
1246 static TEST_FILE_420_12: &[u8] = include_bytes!("../test-420-12.ivf");
1247
1248 fn handle_pending_pictures<A: super::PictureAllocator + fmt::Debug>(
1249 dec: &mut super::Decoder<A>,
1250 pictures: &mut Vec<super::Picture<A>>,
1251 drain: bool,
1252 ) {
1253 loop {
1254 match dec.get_picture() {
1255 Ok(p) => {
1256 println!("{:?}", p);
1257 pictures.push(p);
1258 }
1259 // Need to send more data to the decoder before it can decode new pictures
1260 Err(e) if e.is_again() => return,
1261 Err(e) => {
1262 panic!("Error getting decoded pictures: {}", e);
1263 }
1264 }
1265
1266 if !drain {
1267 break;
1268 }
1269 }
1270 }
1271
1272 fn check_pictures<A: super::PictureAllocator>(pictures: &[super::Picture<A>], bpp: usize) {
1273 assert_eq!(pictures.len(), 5);
1274
1275 let pts = [0, 33, 67, 100, 133];
1276
1277 for (i, picture) in pictures.iter().enumerate() {
1278 assert_eq!(picture.width(), 320);
1279 assert_eq!(picture.height(), 240);
1280 assert_eq!(picture.bit_depth(), bpp);
1281 assert_eq!(
1282 picture.bits_per_component(),
1283 Some(super::BitsPerComponent(bpp))
1284 );
1285 assert_eq!(picture.pixel_layout(), super::PixelLayout::I420);
1286 assert_eq!(
1287 picture.color_primaries(),
1288 super::pixel::ColorPrimaries::BT709
1289 );
1290 assert_eq!(
1291 picture.transfer_characteristic(),
1292 super::pixel::TransferCharacteristic::BT1886
1293 );
1294 assert_eq!(
1295 picture.matrix_coefficients(),
1296 super::pixel::MatrixCoefficients::BT709,
1297 );
1298 assert_eq!(
1299 picture.chroma_location(),
1300 super::pixel::ChromaLocation::Center,
1301 );
1302 assert_eq!(picture.timestamp(), Some(pts[i]));
1303 assert_eq!(picture.offset(), i as i64);
1304
1305 let stride_mult = if bpp == 8 { 1 } else { 2 };
1306
1307 assert!(picture.stride(super::PlanarImageComponent::Y) >= 320 * stride_mult);
1308 assert!(picture.stride(super::PlanarImageComponent::U) >= 160 * stride_mult);
1309 assert!(picture.stride(super::PlanarImageComponent::V) >= 160 * stride_mult);
1310
1311 assert_eq!(
1312 picture
1313 .plane_data_geometry(super::PlanarImageComponent::Y)
1314 .1,
1315 240
1316 );
1317 assert_eq!(
1318 picture
1319 .plane_data_geometry(super::PlanarImageComponent::U)
1320 .1,
1321 120
1322 );
1323 assert_eq!(
1324 picture
1325 .plane_data_geometry(super::PlanarImageComponent::V)
1326 .1,
1327 120
1328 );
1329
1330 assert_eq!(
1331 picture.plane(super::PlanarImageComponent::Y).len(),
1332 picture.stride(super::PlanarImageComponent::Y) as usize * 240
1333 );
1334
1335 assert_eq!(
1336 picture.plane(super::PlanarImageComponent::U).len(),
1337 picture.stride(super::PlanarImageComponent::U) as usize * 120
1338 );
1339
1340 assert_eq!(
1341 picture.plane(super::PlanarImageComponent::V).len(),
1342 picture.stride(super::PlanarImageComponent::V) as usize * 120
1343 );
1344 }
1345 }
1346
1347 fn decode_file<A: super::PictureAllocator + fmt::Debug>(
1348 file: &[u8],
1349 mut dec: super::Decoder<A>,
1350 pictures: &mut Vec<super::Picture<A>>,
1351 ) {
1352 use std::io;
1353
1354 let mut r = io::BufReader::new(file);
1355 let header = ivf::read_header(&mut r).unwrap();
1356 println!("{:?}", header);
1357
1358 let mut idx = 0;
1359
1360 while let Ok(packet) = ivf::read_packet(&mut r) {
1361 println!("Packet {}", packet.pts);
1362
1363 // Let's use millisecond timestamps
1364 let pts =
1365 1000 * packet.pts as i64 * header.timebase_num as i64 / header.timebase_den as i64;
1366
1367 // Send packet to the decoder
1368 match dec.send_data(packet.data, Some(idx), Some(pts), None) {
1369 Err(e) if e.is_again() => {
1370 // If the decoder did not consume all data, output all
1371 // pending pictures and send pending data to the decoder
1372 // until it is all used up.
1373 loop {
1374 handle_pending_pictures(&mut dec, pictures, false);
1375
1376 match dec.send_pending_data() {
1377 Err(e) if e.is_again() => continue,
1378 Err(e) => {
1379 panic!("Error sending pending data to the decoder: {}", e);
1380 }
1381 _ => break,
1382 }
1383 }
1384 }
1385 Err(e) => {
1386 panic!("Error sending data to the decoder: {}", e);
1387 }
1388 _ => (),
1389 }
1390
1391 // Handle all pending pictures before sending the next data.
1392 handle_pending_pictures(&mut dec, pictures, false);
1393
1394 idx += 1;
1395 }
1396
1397 // Handle all pending pictures that were not output yet.
1398 handle_pending_pictures(&mut dec, pictures, true);
1399 }
1400
1401 #[test]
1402 fn test_basic_420_8() {
1403 let dec = super::Decoder::new().expect("failed to create decoder instance");
1404 let mut pictures = vec![];
1405 decode_file(TEST_FILE_420_8, dec, &mut pictures);
1406 check_pictures(&pictures, 8);
1407 }
1408
1409 #[test]
1410 fn test_basic_420_12() {
1411 let dec = super::Decoder::new().expect("failed to create decoder instance");
1412 let mut pictures = vec![];
1413 decode_file(TEST_FILE_420_12, dec, &mut pictures);
1414 check_pictures(&pictures, 12);
1415 }
1416
1417 #[derive(Debug)]
1418 struct TestAllocator {
1419 counter: atomic::AtomicUsize,
1420 allocated: sync::Arc<atomic::AtomicUsize>,
1421 }
1422
1423 impl TestAllocator {
1424 fn new(allocated: &sync::Arc<atomic::AtomicUsize>) -> Self {
1425 TestAllocator {
1426 counter: atomic::AtomicUsize::new(0),
1427 allocated: allocated.clone(),
1428 }
1429 }
1430 }
1431
1432 unsafe impl super::PictureAllocator for TestAllocator {
1433 type AllocatorData = (usize, [std::alloc::Layout; 2]);
1434
1435 unsafe fn alloc_picture(
1436 &self,
1437 pic_params: &crate::PictureParameters,
1438 ) -> Result<crate::PictureAllocation<Self::AllocatorData>, crate::Error> {
1439 fn align(x: usize) -> usize {
1440 (x + 128 - 1) & !(128 - 1)
1441 }
1442
1443 let stride_mult = if pic_params.bit_depth() == 8 { 1 } else { 2 };
1444
1445 let (stride, height) = match pic_params.pixel_layout() {
1446 crate::PixelLayout::I400 => (
1447 [align(pic_params.width() as usize) * stride_mult, 0],
1448 [align(pic_params.height() as usize), 0],
1449 ),
1450 crate::PixelLayout::I420 => (
1451 [
1452 align(pic_params.width() as usize) * stride_mult,
1453 align((pic_params.width() as usize + 1) / 2) * stride_mult,
1454 ],
1455 [
1456 align(pic_params.height() as usize),
1457 align((pic_params.height() as usize + 1) / 2),
1458 ],
1459 ),
1460 crate::PixelLayout::I422 => (
1461 [
1462 align(pic_params.width() as usize) * stride_mult,
1463 align((pic_params.width() as usize + 1) / 2) * stride_mult,
1464 ],
1465 [
1466 align(pic_params.height() as usize),
1467 align(pic_params.height() as usize),
1468 ],
1469 ),
1470 crate::PixelLayout::I444 => (
1471 [
1472 align(pic_params.width() as usize) * stride_mult,
1473 align(pic_params.width() as usize) * stride_mult,
1474 ],
1475 [
1476 align(pic_params.height() as usize),
1477 align(pic_params.height() as usize),
1478 ],
1479 ),
1480 };
1481
1482 let layout_0 = std::alloc::Layout::from_size_align(
1483 height[0] * stride[0],
1484 super::PICTURE_ALIGNMENT,
1485 )
1486 .unwrap();
1487
1488 let data_0 = std::alloc::alloc(layout_0);
1489
1490 let layout_1;
1491 let data_1;
1492 let data_2;
1493 if stride[1] > 0 {
1494 layout_1 = std::alloc::Layout::from_size_align(
1495 height[1] * stride[1],
1496 super::PICTURE_ALIGNMENT,
1497 )
1498 .unwrap();
1499 data_1 = std::alloc::alloc(layout_1);
1500 data_2 = std::alloc::alloc(layout_1);
1501 } else {
1502 layout_1 = layout_0;
1503 data_1 = ptr::null_mut();
1504 data_2 = ptr::null_mut();
1505 }
1506
1507 self.allocated.fetch_add(1, atomic::Ordering::SeqCst);
1508
1509 Ok(super::PictureAllocation {
1510 data: [data_0, data_1, data_2],
1511 stride: [stride[0] as isize, stride[1] as isize],
1512 allocator_data: (
1513 self.counter.fetch_add(1, atomic::Ordering::SeqCst),
1514 [layout_0, layout_1],
1515 ),
1516 })
1517 }
1518
1519 unsafe fn release_picture(
1520 &self,
1521 allocation: crate::PictureAllocation<Self::AllocatorData>,
1522 ) {
1523 let prev = self.allocated.fetch_sub(1, atomic::Ordering::SeqCst);
1524 assert!(prev > 0);
1525
1526 std::alloc::dealloc(allocation.data[0], allocation.allocator_data.1[0]);
1527 if !allocation.data[1].is_null() {
1528 std::alloc::dealloc(allocation.data[1], allocation.allocator_data.1[1]);
1529 std::alloc::dealloc(allocation.data[2], allocation.allocator_data.1[1]);
1530 }
1531 }
1532 }
1533
1534 #[test]
1535 fn test_allocator_420_8() {
1536 let allocated = sync::Arc::new(atomic::AtomicUsize::new(0));
1537
1538 let dec = super::Decoder::with_allocator(TestAllocator::new(&allocated))
1539 .expect("failed to create decoder instance");
1540
1541 let mut pictures = vec![];
1542 decode_file(TEST_FILE_420_8, dec, &mut pictures);
1543 check_pictures(&pictures, 8);
1544
1545 let mut indices = HashSet::new();
1546 for picture in &pictures {
1547 let allocator_data = picture.allocator_data().unwrap();
1548 assert!(indices.insert(allocator_data.0));
1549 }
1550 assert_eq!(indices.len(), 5);
1551
1552 assert_eq!(allocated.load(atomic::Ordering::SeqCst), 5);
1553 drop(pictures);
1554 assert_eq!(allocated.load(atomic::Ordering::SeqCst), 0);
1555 }
1556
1557 #[test]
1558 fn test_allocator_420_12() {
1559 let allocated = sync::Arc::new(atomic::AtomicUsize::new(0));
1560
1561 let dec = super::Decoder::with_allocator(TestAllocator::new(&allocated))
1562 .expect("failed to create decoder instance");
1563
1564 let mut pictures = vec![];
1565 decode_file(TEST_FILE_420_12, dec, &mut pictures);
1566 check_pictures(&pictures, 12);
1567
1568 let mut indices = HashSet::new();
1569 for picture in &pictures {
1570 let allocator_data = picture.allocator_data().unwrap();
1571 assert!(indices.insert(allocator_data.0));
1572 }
1573 assert_eq!(indices.len(), 5);
1574
1575 assert_eq!(allocated.load(atomic::Ordering::SeqCst), 5);
1576 drop(pictures);
1577 assert_eq!(allocated.load(atomic::Ordering::SeqCst), 0);
1578 }
1579 }
1580
1581 /// Content light level information as specified in CEA-861.3, Appendix A.
1582 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1583 pub struct ContentLightLevel {
1584 /// Maximum content light level (MaxCLL) in candela per square metre.
1585 pub max_content_light_level: u16,
1586 /// Maximum frame average light level (MaxFLL) in candela per square metre.
1587 pub max_frame_average_light_level: u16,
1588 }
1589
1590 /// Mastering display information as specified in SMPTE ST 2086.
1591 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1592 pub struct MasteringDisplay {
1593 /// Red/green/blue XY coordinates of primaries in CIE 1931 color space as 0.16 fixed-point number.
1594 pub primaries: [[u16; 2usize]; 3usize],
1595 /// XY coordinates of white point in CIE 1931 color space as 0.16 fixed-point number.
1596 pub white_point: [u16; 2usize],
1597 /// Maximum luminance in candela per square metre as 24.8 fixed-point number.
1598 pub max_luminance: u32,
1599 /// Minimum luminance in candela per square metre as 18.14 fixed-point number.
1600 pub min_luminance: u32,
1601 }