1use std::any::Any;
4use std::fmt::Debug;
5use std::sync::Arc;
6
7use alpha2_media::{
8 CancelToken, ChromaLocation, ColorMetadata, DecodeError, DecodeEvent, DecodeRequest,
9 DecodedVideoFrame, Decoder, Orientation, PixelFormat, Rect, SampleAspectRatio, StreamInfo,
10};
11use alpha2_time::MediaTime;
12
13use crate::NativeDecoder;
14#[cfg(all(
15 any(target_os = "linux", target_os = "macos", target_os = "windows"),
16 feature = "hwdecode"
17))]
18use crate::convert::timestamp;
19use crate::decode::DecodeStageTimings;
20#[cfg(all(target_os = "windows", feature = "hwdecode"))]
21use alpha2_native_gpu::SharedD3D12Context;
22#[cfg(all(target_os = "macos", feature = "hwdecode"))]
23use alpha2_native_gpu::SharedMetalContext;
24#[cfg(all(target_os = "linux", feature = "hwdecode"))]
25use alpha2_native_gpu::SharedVulkanContext;
26#[cfg(all(
27 any(target_os = "linux", target_os = "macos", target_os = "windows"),
28 feature = "hwdecode"
29))]
30use rsmpeg::{avutil::AVFrame, ffi};
31
32#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
34pub enum HardwareDecodeFallback {
35 ContextUnavailable,
37 NoHardwareConfig,
39 UnsupportedColor,
41 UnsupportedProfile,
44 UnsupportedSurfaceFormat,
46 SourceUnavailable,
48 DecoderOpenFailed,
50 ReverseWindow,
52 UnsupportedCrop,
56 ImportFailed,
58 AlphaChannel,
61}
62
63impl HardwareDecodeFallback {
64 #[must_use]
66 pub const fn as_str(self) -> &'static str {
67 match self {
68 Self::ContextUnavailable => "contextUnavailable",
69 Self::NoHardwareConfig => "noHardwareConfig",
70 Self::UnsupportedColor => "unsupportedColor",
71 Self::UnsupportedProfile => "unsupportedProfile",
72 Self::UnsupportedSurfaceFormat => "unsupportedSurfaceFormat",
73 Self::SourceUnavailable => "sourceUnavailable",
74 Self::DecoderOpenFailed => "decoderOpenFailed",
75 Self::ReverseWindow => "reverseWindow",
76 Self::UnsupportedCrop => "unsupportedCrop",
77 Self::ImportFailed => "importFailed",
78 Self::AlphaChannel => "alphaChannel",
79 }
80 }
81}
82
83#[derive(Debug)]
85pub struct HardwareOpenError {
86 pub reason: HardwareDecodeFallback,
88 pub source: DecodeError,
90}
91
92impl HardwareOpenError {
93 #[must_use]
95 pub const fn new(reason: HardwareDecodeFallback, source: DecodeError) -> Self {
96 Self { reason, source }
97 }
98}
99
100impl std::fmt::Display for HardwareOpenError {
101 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102 write!(formatter, "{}: {:?}", self.reason.as_str(), self.source)
103 }
104}
105
106impl std::error::Error for HardwareOpenError {}
107
108#[cfg(all(
110 any(target_os = "linux", target_os = "macos", target_os = "windows"),
111 feature = "hwdecode"
112))]
113pub(crate) struct HardwareDecoderSpec<'a> {
114 pub device_type: ffi::AVHWDeviceType,
116 pub pixel_format: ffi::AVPixelFormat,
118 pub backend: &'static str,
120 pub require_device_context: bool,
122 pub ten_bit: bool,
124 pub keeps_leading_crop: bool,
131 pub hardware_codecs: Option<&'a [&'static str]>,
135 pub get_format: unsafe extern "C" fn(
137 *mut ffi::AVCodecContext,
138 *const ffi::AVPixelFormat,
139 ) -> ffi::AVPixelFormat,
140}
141
142#[derive(Copy, Clone, Debug, Eq, PartialEq)]
144pub enum NativePlaneLayout {
145 CpuYuv(alpha2_media::YuvFormat),
147 CpuRgba8,
149 CpuLinearRgbaF16,
151 GpuI420,
153 GpuNv12,
155 GpuP010,
157}
158
159impl NativePlaneLayout {
160 #[must_use]
162 pub const fn bit_depth(self) -> u8 {
163 match self {
164 Self::CpuRgba8 | Self::GpuI420 | Self::GpuNv12 => 8,
165 Self::CpuLinearRgbaF16 => 16,
166 Self::CpuYuv(format) => format.bit_depth,
167 Self::GpuP010 => 10,
168 }
169 }
170
171 #[cfg_attr(
173 not(all(
174 any(target_os = "linux", target_os = "macos", target_os = "windows"),
175 feature = "hwdecode"
176 )),
177 allow(dead_code)
178 )]
179 const fn bytes_per_pixel_numerator(self) -> u64 {
180 match self {
181 Self::CpuRgba8 => 8,
182 Self::CpuLinearRgbaF16 => 16,
183 Self::GpuI420 | Self::GpuNv12 => 3,
184 Self::GpuP010 => 6,
185 Self::CpuYuv(format) => {
188 format.bytes_per_sample() as u64
189 * (2 + (4 >> (format.chroma_shift_x + format.chroma_shift_y)))
190 }
191 }
192 }
193}
194
195#[cfg(all(
198 any(target_os = "linux", target_os = "macos", target_os = "windows"),
199 feature = "hwdecode"
200))]
201pub(crate) const fn surface_plane_layout(format: ffi::AVPixelFormat) -> Option<NativePlaneLayout> {
202 match format {
203 ffi::AV_PIX_FMT_NV12 => Some(NativePlaneLayout::GpuNv12),
204 ffi::AV_PIX_FMT_P010LE => Some(NativePlaneLayout::GpuP010),
205 _ => None,
206 }
207}
208
209#[cfg_attr(
216 not(all(target_os = "windows", feature = "hwdecode")),
217 allow(dead_code)
218)]
219pub(crate) fn visible_rect_within_surface(
220 width: u32,
221 height: u32,
222 [left, top, right, bottom]: [usize; 4],
223 surface_width: u32,
224 surface_height: u32,
225) -> Option<Rect> {
226 let x = u32::try_from(left).ok()?;
227 let y = u32::try_from(top).ok()?;
228 let visible = Rect {
229 x,
230 y,
231 width: width
232 .checked_sub(x)?
233 .checked_sub(u32::try_from(right).ok()?)?,
234 height: height
235 .checked_sub(y)?
236 .checked_sub(u32::try_from(bottom).ok()?)?,
237 };
238 (u64::from(x) + u64::from(visible.width) <= u64::from(surface_width)
239 && u64::from(y) + u64::from(visible.height) <= u64::from(surface_height))
240 .then_some(visible)
241}
242
243#[derive(Clone, Debug, PartialEq)]
248pub struct NativeVideoFrameMetadata {
249 pub pts: MediaTime,
251 pub dts: Option<MediaTime>,
253 pub duration: Option<MediaTime>,
255 pub visible_rect: Rect,
257 pub orientation: Orientation,
259 pub sample_aspect_ratio: SampleAspectRatio,
261 pub color: Option<ColorMetadata>,
263 pub chroma_location: ChromaLocation,
265 pub bit_depth: u8,
267 pub plane_layout: NativePlaneLayout,
269 pub device_identity: u64,
271 pub decoder_generation: u64,
273 pub picture_identity: u64,
275}
276
277pub trait HardwareFrameLease: Debug + Send + Sync + 'static {
279 fn retained_bytes(&self) -> u64;
281
282 fn as_any(&self) -> &dyn Any;
284
285 fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
287}
288
289#[cfg(all(target_os = "linux", feature = "hwdecode"))]
290impl HardwareFrameLease for alpha2_ffmpeg_bridge::VulkanFrameLease {
291 fn retained_bytes(&self) -> u64 {
292 self.info().map_or(0, |info| {
293 let pixels = u64::try_from(info.width)
294 .unwrap_or(0)
295 .saturating_mul(u64::try_from(info.height).unwrap_or(0));
296 let numerator = surface_plane_layout(info.software_format)
299 .unwrap_or(NativePlaneLayout::GpuNv12)
300 .bytes_per_pixel_numerator();
301 pixels.saturating_mul(numerator).div_ceil(2)
302 })
303 }
304
305 fn as_any(&self) -> &dyn Any {
306 self
307 }
308
309 fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
310 self
311 }
312}
313
314#[cfg(all(target_os = "macos", feature = "hwdecode"))]
315impl HardwareFrameLease for alpha2_ffmpeg_bridge::VideoToolboxFrameLease {
316 fn retained_bytes(&self) -> u64 {
317 self.info().map_or(0, |info| {
318 let pixels = u64::try_from(info.width)
319 .unwrap_or(0)
320 .saturating_mul(u64::try_from(info.height).unwrap_or(0));
321 let numerator = surface_plane_layout(info.software_format)
324 .unwrap_or(NativePlaneLayout::GpuNv12)
325 .bytes_per_pixel_numerator();
326 pixels.saturating_mul(numerator).div_ceil(2)
327 })
328 }
329
330 fn as_any(&self) -> &dyn Any {
331 self
332 }
333
334 fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
335 self
336 }
337}
338
339#[cfg(all(target_os = "windows", feature = "hwdecode"))]
340impl HardwareFrameLease for alpha2_ffmpeg_bridge::D3D12FrameLease {
341 fn retained_bytes(&self) -> u64 {
342 self.info().map_or(0, |info| {
343 let pixels = u64::try_from(info.width)
344 .unwrap_or(0)
345 .saturating_mul(u64::try_from(info.height).unwrap_or(0));
346 let numerator = surface_plane_layout(info.software_format)
349 .unwrap_or(NativePlaneLayout::GpuNv12)
350 .bytes_per_pixel_numerator();
351 pixels.saturating_mul(numerator).div_ceil(2)
352 })
353 }
354
355 fn as_any(&self) -> &dyn Any {
356 self
357 }
358
359 fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
360 self
361 }
362}
363
364#[derive(Debug)]
366pub enum NativeVideoFrame {
367 Cpu(DecodedVideoFrame),
369 Hardware {
371 metadata: NativeVideoFrameMetadata,
373 surface: Arc<dyn HardwareFrameLease>,
375 },
376}
377
378impl NativeVideoFrame {
379 #[must_use]
381 pub fn pts(&self) -> MediaTime {
382 match self {
383 Self::Cpu(frame) => frame.pts,
384 Self::Hardware { metadata, .. } => metadata.pts,
385 }
386 }
387
388 #[must_use]
390 pub fn duration(&self) -> Option<MediaTime> {
391 match self {
392 Self::Cpu(frame) => frame.duration,
393 Self::Hardware { metadata, .. } => metadata.duration,
394 }
395 }
396
397 #[must_use]
399 pub fn metadata(&self) -> NativeVideoFrameMetadata {
400 match self {
401 Self::Cpu(frame) => metadata_from_cpu(frame),
402 Self::Hardware { metadata, .. } => metadata.clone(),
403 }
404 }
405
406 #[must_use]
408 pub const fn is_hardware(&self) -> bool {
409 matches!(self, Self::Hardware { .. })
410 }
411
412 #[must_use]
414 pub fn as_cpu(&self) -> Option<&DecodedVideoFrame> {
415 match self {
416 Self::Cpu(frame) => Some(frame),
417 Self::Hardware { .. } => None,
418 }
419 }
420
421 pub fn to_cpu(&self) -> Result<DecodedVideoFrame, DecodeError> {
429 let (metadata, surface) = match self {
430 Self::Cpu(frame) => return Ok(frame.clone()),
431 Self::Hardware { metadata, surface } => (metadata, surface),
432 };
433 let mut software = download_surface(surface.as_ref())?;
434 software.set_pts(metadata.pts.ticks());
436 let mut scaler = crate::convert::FrameScaler::default();
437 let mut frame = crate::convert::convert_video_frame(
439 &software,
440 rsmpeg::ffi::AV_CODEC_ID_NONE,
441 crate::convert::tick_base(),
442 metadata.color.unwrap_or_default(),
443 &mut scaler,
444 )?;
445 frame.pts = metadata.pts;
446 frame.duration = metadata.duration;
447 frame.orientation = metadata.orientation;
448 frame.sample_aspect_ratio = metadata.sample_aspect_ratio;
449 frame.chroma_location = metadata.chroma_location;
450 if metadata.color.is_none() {
453 frame.color = None;
454 }
455 Ok(frame)
456 }
457
458 #[must_use]
460 pub fn retained_bytes(&self) -> u64 {
461 match self {
462 Self::Cpu(frame) => frame.planes.iter().fold(0_u64, |total, plane| {
463 total.saturating_add(u64::try_from(plane.bytes.len()).unwrap_or(u64::MAX))
464 }),
465 Self::Hardware { surface, .. } => surface.retained_bytes(),
466 }
467 }
468}
469
470#[cfg_attr(
472 not(all(
473 any(target_os = "linux", target_os = "macos", target_os = "windows"),
474 feature = "hwdecode"
475 )),
476 allow(clippy::unnecessary_wraps)
477)]
478fn download_surface(
479 surface: &dyn HardwareFrameLease,
480) -> Result<alpha2_ffmpeg_bridge::DecodedFrame, DecodeError> {
481 let any = surface.as_any();
482 let downloaded: Option<
483 Result<alpha2_ffmpeg_bridge::DecodedFrame, alpha2_ffmpeg_bridge::BridgeError>,
484 > = None;
485 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
486 let downloaded = downloaded.or_else(|| {
487 any.downcast_ref::<alpha2_ffmpeg_bridge::VulkanFrameLease>()
488 .map(alpha2_ffmpeg_bridge::VulkanFrameLease::download)
489 });
490 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
491 let downloaded = downloaded.or_else(|| {
492 any.downcast_ref::<alpha2_ffmpeg_bridge::VideoToolboxFrameLease>()
493 .map(alpha2_ffmpeg_bridge::VideoToolboxFrameLease::download)
494 });
495 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
496 let downloaded = downloaded.or_else(|| {
497 any.downcast_ref::<alpha2_ffmpeg_bridge::D3D12FrameLease>()
498 .map(alpha2_ffmpeg_bridge::D3D12FrameLease::download)
499 });
500 let _ = any;
501 downloaded
502 .ok_or_else(|| {
503 DecodeError::Unsupported("this hardware surface cannot be downloaded".into())
504 })?
505 .map_err(|error| DecodeError::Adapter(error.to_string()))
506}
507
508pub struct NativeExportDecoder {
513 backend: ExportDecoderBackend,
514 hardware_frames: u64,
515 hardware_failure: Option<HardwareDecodeFallback>,
517}
518
519enum ExportDecoderBackend {
520 Software(NativeDecoder),
521 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
522 Vulkan {
523 decoder: NativeDecoder,
524 generation: u64,
525 },
526 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
527 VideoToolbox {
528 decoder: NativeDecoder,
529 generation: u64,
530 device_identity: u64,
531 },
532 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
533 D3D12 {
534 decoder: NativeDecoder,
535 generation: u64,
536 device_identity: u64,
537 },
538}
539
540impl NativeExportDecoder {
541 pub fn take_stage_timings(&mut self) -> DecodeStageTimings {
544 match &mut self.backend {
545 ExportDecoderBackend::Software(decoder) => decoder.take_stage_timings(),
546 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
547 ExportDecoderBackend::Vulkan { decoder, .. } => decoder.take_stage_timings(),
548 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
549 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.take_stage_timings(),
550 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
551 ExportDecoderBackend::D3D12 { decoder, .. } => decoder.take_stage_timings(),
552 }
553 }
554
555 #[must_use]
557 pub const fn is_hardware(&self) -> bool {
558 match &self.backend {
559 ExportDecoderBackend::Software(_) => false,
560 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
561 ExportDecoderBackend::Vulkan { .. } => true,
562 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
563 ExportDecoderBackend::VideoToolbox { .. } => true,
564 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
565 ExportDecoderBackend::D3D12 { .. } => true,
566 }
567 }
568
569 pub fn open(path: impl AsRef<std::path::Path>) -> Result<Self, DecodeError> {
574 NativeDecoder::open(path).map(|decoder| Self {
575 backend: ExportDecoderBackend::Software(decoder),
576 hardware_frames: 0,
577 hardware_failure: None,
578 })
579 }
580
581 pub fn open_with_threads(
586 path: impl AsRef<std::path::Path>,
587 threads: i64,
588 ) -> Result<Self, DecodeError> {
589 NativeDecoder::open_with_threads(path, threads).map(|decoder| Self {
590 backend: ExportDecoderBackend::Software(decoder),
591 hardware_frames: 0,
592 hardware_failure: None,
593 })
594 }
595
596 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
602 pub fn open_vulkan(
603 path: impl AsRef<std::path::Path>,
604 threads: i64,
605 context: &SharedVulkanContext,
606 generation: u64,
607 ) -> Result<Self, HardwareOpenError> {
608 let spec = HardwareDecoderSpec {
609 device_type: ffi::AV_HWDEVICE_TYPE_VULKAN,
610 pixel_format: ffi::AV_PIX_FMT_VULKAN,
611 backend: "Vulkan",
612 require_device_context: true,
613 ten_bit: context.supports_ten_bit(),
614 keeps_leading_crop: true,
615 hardware_codecs: Some(context.decode_codecs()),
618 get_format: alpha2_ffmpeg_bridge::vulkan_get_format_callback(),
619 };
620 NativeDecoder::open_hardware(path, threads, context.ffmpeg_device(), &spec).map(|decoder| {
621 Self {
622 backend: ExportDecoderBackend::Vulkan {
623 decoder,
624 generation,
625 },
626 hardware_frames: 0,
627 hardware_failure: None,
628 }
629 })
630 }
631
632 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
638 pub fn open_videotoolbox(
639 path: impl AsRef<std::path::Path>,
640 threads: i64,
641 context: &SharedMetalContext,
642 generation: u64,
643 ) -> Result<Self, HardwareOpenError> {
644 alpha2_ffmpeg_bridge::check_hardware_interop()
647 .map_err(crate::convert::adapter_error)
648 .map_err(|error| {
649 HardwareOpenError::new(HardwareDecodeFallback::DecoderOpenFailed, error)
650 })?;
651 let mark = alpha2_ffmpeg_bridge::log_mark();
652 let device = rsmpeg::avutil::AVHWDeviceContext::create(
653 ffi::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
654 None,
655 None,
656 0,
657 )
658 .map_err(crate::convert::adapter_error)
659 .map_err(|error| {
660 HardwareOpenError::new(HardwareDecodeFallback::DecoderOpenFailed, error)
661 })?;
662 let spec = HardwareDecoderSpec {
663 device_type: ffi::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
664 pixel_format: ffi::AV_PIX_FMT_VIDEOTOOLBOX,
665 backend: "VideoToolbox",
666 require_device_context: false,
667 ten_bit: context.supports_ten_bit(),
668 keeps_leading_crop: false,
669 hardware_codecs: Some(context.decode_codecs()),
670 get_format: alpha2_ffmpeg_bridge::videotoolbox_get_format_callback(),
671 };
672 NativeDecoder::open_hardware(path, threads, device, &spec)
673 .map(|decoder| Self {
674 backend: ExportDecoderBackend::VideoToolbox {
675 decoder,
676 generation,
677 device_identity: context.identity().device,
678 },
679 hardware_frames: 0,
680 hardware_failure: None,
681 })
682 .map_err(|mut error| {
683 error.source = with_videotoolbox_log(error.source, mark);
684 error
685 })
686 }
687
688 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
694 pub fn open_d3d12(
695 path: impl AsRef<std::path::Path>,
696 threads: i64,
697 context: &SharedD3D12Context,
698 generation: u64,
699 ) -> Result<Self, HardwareOpenError> {
700 let spec = HardwareDecoderSpec {
701 device_type: ffi::AV_HWDEVICE_TYPE_D3D12VA,
702 pixel_format: ffi::AV_PIX_FMT_D3D12,
703 backend: "D3D12VA",
704 require_device_context: true,
705 ten_bit: context.supports_ten_bit(),
706 keeps_leading_crop: true,
707 hardware_codecs: None,
708 get_format: alpha2_ffmpeg_bridge::d3d12_get_format_callback(),
709 };
710 NativeDecoder::open_hardware(path, threads, context.ffmpeg_device(), &spec).map(|decoder| {
711 Self {
712 backend: ExportDecoderBackend::D3D12 {
713 decoder,
714 generation,
715 device_identity: context.identity().device,
716 },
717 hardware_frames: 0,
718 hardware_failure: None,
719 }
720 })
721 }
722
723 #[must_use]
725 pub fn streams(&self) -> &[StreamInfo] {
726 match &self.backend {
727 ExportDecoderBackend::Software(decoder) => decoder.streams(),
728 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
729 ExportDecoderBackend::Vulkan { decoder, .. } => decoder.streams(),
730 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
731 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.streams(),
732 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
733 ExportDecoderBackend::D3D12 { decoder, .. } => decoder.streams(),
734 }
735 }
736
737 #[must_use]
740 pub fn dropped_layer(&self) -> Option<&crate::DroppedLayer> {
741 match &self.backend {
742 ExportDecoderBackend::Software(decoder) => decoder.dropped_layer(),
743 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
744 ExportDecoderBackend::Vulkan { .. } => None,
745 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
746 ExportDecoderBackend::VideoToolbox { .. } => None,
747 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
748 ExportDecoderBackend::D3D12 { .. } => None,
749 }
750 }
751
752 #[must_use]
754 pub fn video_duration(&self) -> Option<MediaTime> {
755 match &self.backend {
756 ExportDecoderBackend::Software(decoder) => decoder.video_duration(),
757 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
758 ExportDecoderBackend::Vulkan { decoder, .. } => decoder.video_duration(),
759 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
760 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.video_duration(),
761 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
762 ExportDecoderBackend::D3D12 { decoder, .. } => decoder.video_duration(),
763 }
764 }
765
766 pub fn flush(&mut self) -> Result<(), DecodeError> {
771 match &mut self.backend {
772 ExportDecoderBackend::Software(decoder) => decoder.flush(),
773 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
774 ExportDecoderBackend::Vulkan { decoder, .. } => decoder.flush(),
775 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
776 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.flush(),
777 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
778 ExportDecoderBackend::D3D12 { decoder, .. } => decoder.flush(),
779 }
780 }
781
782 pub fn seek_video(
787 &mut self,
788 request: DecodeRequest,
789 cancel: &CancelToken,
790 ) -> Result<NativeVideoFrame, DecodeError> {
791 let result = self.seek_video_on_backend(request, cancel);
792 self.observe(result, |_| true)
793 }
794
795 pub fn decode_video_next(
800 &mut self,
801 cancel: &CancelToken,
802 ) -> Result<Option<NativeVideoFrame>, DecodeError> {
803 let result = self.decode_video_next_on_backend(cancel);
804 self.observe(result, Option::is_some)
805 }
806
807 pub fn peek_video_pts(
815 &mut self,
816 cancel: &CancelToken,
817 ) -> Result<Option<MediaTime>, DecodeError> {
818 let result = self.native_decoder().peek_raw_pts(cancel);
819 self.observe(result, |_| false)
820 }
821
822 pub fn set_decode_policy(&mut self, policy: crate::DecodePolicy) {
824 self.native_decoder().set_decode_policy(policy);
825 }
826
827 pub fn with_declared_color(
833 mut self,
834 color: Option<ColorMetadata>,
835 ) -> Result<Self, HardwareOpenError> {
836 if self.is_hardware() && color.is_some_and(ColorMetadata::is_hdr) {
837 return Err(HardwareOpenError::new(
838 HardwareDecodeFallback::UnsupportedColor,
839 DecodeError::Unsupported("hardware export currently supports SDR only".into()),
840 ));
841 }
842 self.native_decoder().declare_color(color);
843 Ok(self)
844 }
845
846 pub fn set_decode_reporter(
848 &mut self,
849 reporter: impl Fn(crate::DecodeDiagnostic) + Send + Sync + 'static,
850 ) {
851 self.native_decoder().set_decode_reporter(reporter);
852 }
853
854 pub fn decode_diagnostics(&mut self) -> &crate::DecodeDiagnostics {
856 self.native_decoder().decode_diagnostics()
857 }
858
859 #[must_use]
862 pub fn presentation_deadline(&self, time: MediaTime) -> MediaTime {
863 match &self.backend {
864 ExportDecoderBackend::Software(decoder) => decoder,
865 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
866 ExportDecoderBackend::Vulkan { decoder, .. } => decoder,
867 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
868 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder,
869 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
870 ExportDecoderBackend::D3D12 { decoder, .. } => decoder,
871 }
872 .presentation_deadline(time)
873 }
874
875 fn native_decoder(&mut self) -> &mut NativeDecoder {
876 match &mut self.backend {
877 ExportDecoderBackend::Software(decoder) => decoder,
878 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
879 ExportDecoderBackend::Vulkan { decoder, .. } => decoder,
880 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
881 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder,
882 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
883 ExportDecoderBackend::D3D12 { decoder, .. } => decoder,
884 }
885 }
886
887 #[must_use]
889 pub const fn hardware_failure(&self) -> Option<HardwareDecodeFallback> {
890 self.hardware_failure
891 }
892
893 fn observe<T>(
900 &mut self,
901 result: Result<T, DecodeError>,
902 produced: impl Fn(&T) -> bool,
903 ) -> Result<T, DecodeError> {
904 if !self.is_hardware() {
905 return result;
906 }
907 match result {
908 Ok(value) => {
909 if produced(&value) {
910 self.hardware_frames = self.hardware_frames.saturating_add(1);
911 }
912 Ok(value)
913 }
914 Err(DecodeError::Adapter(message)) if self.hardware_frames == 0 => {
915 self.hardware_failure = Some(HardwareDecodeFallback::DecoderOpenFailed);
916 Err(DecodeError::Unsupported(format!(
917 "the hardware decoder failed before its first frame: {message}"
918 )))
919 }
920 Err(DecodeError::Unsupported(message)) => {
921 self.hardware_failure
922 .get_or_insert(HardwareDecodeFallback::UnsupportedSurfaceFormat);
923 Err(DecodeError::Unsupported(message))
924 }
925 Err(error) => Err(error),
926 }
927 }
928
929 fn seek_video_on_backend(
930 &mut self,
931 request: DecodeRequest,
932 cancel: &CancelToken,
933 ) -> Result<NativeVideoFrame, DecodeError> {
934 match &mut self.backend {
935 ExportDecoderBackend::Software(decoder) => match decoder.seek(request, cancel)?.event {
936 DecodeEvent::Video(frame) => Ok(NativeVideoFrame::Cpu(frame)),
937 _ => Err(DecodeError::Adapter(
938 "video decoder returned a non-video event".into(),
939 )),
940 },
941 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
942 ExportDecoderBackend::Vulkan {
943 decoder,
944 generation,
945 } => {
946 let frame = decoder.seek_raw(request.time, cancel)?;
947 hardware_frame(decoder, frame.into_frame(), *generation)
948 }
949 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
950 ExportDecoderBackend::VideoToolbox {
951 decoder,
952 generation,
953 device_identity,
954 } => {
955 let mark = alpha2_ffmpeg_bridge::log_mark();
956 let frame = decoder
957 .seek_raw(request.time, cancel)
958 .map_err(|error| with_videotoolbox_log(error, mark))?;
959 videotoolbox_frame(decoder, frame.into_frame(), *generation, *device_identity)
960 }
961 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
962 ExportDecoderBackend::D3D12 {
963 decoder,
964 generation,
965 device_identity,
966 } => {
967 let frame = decoder.seek_raw(request.time, cancel)?;
968 d3d12_frame(
969 decoder,
970 frame.into_frame(),
971 *generation,
972 *device_identity,
973 &mut self.hardware_failure,
974 )
975 }
976 }
977 }
978
979 fn decode_video_next_on_backend(
980 &mut self,
981 cancel: &CancelToken,
982 ) -> Result<Option<NativeVideoFrame>, DecodeError> {
983 match &mut self.backend {
984 ExportDecoderBackend::Software(decoder) => match decoder.decode_next(cancel)? {
985 DecodeEvent::Video(frame) => Ok(Some(NativeVideoFrame::Cpu(frame))),
986 DecodeEvent::EndOfStream => Ok(None),
987 _ => Err(DecodeError::Adapter(
988 "video decoder returned a non-video event".into(),
989 )),
990 },
991 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
992 ExportDecoderBackend::Vulkan {
993 decoder,
994 generation,
995 } => decoder
996 .decode_raw_next(cancel)?
997 .map(|frame| hardware_frame(decoder, frame.into_frame(), *generation))
998 .transpose(),
999 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
1000 ExportDecoderBackend::VideoToolbox {
1001 decoder,
1002 generation,
1003 device_identity,
1004 } => {
1005 let mark = alpha2_ffmpeg_bridge::log_mark();
1006 decoder
1007 .decode_raw_next(cancel)
1008 .map_err(|error| with_videotoolbox_log(error, mark))?
1009 .map(|frame| {
1010 videotoolbox_frame(
1011 decoder,
1012 frame.into_frame(),
1013 *generation,
1014 *device_identity,
1015 )
1016 })
1017 .transpose()
1018 }
1019 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
1020 ExportDecoderBackend::D3D12 {
1021 decoder,
1022 generation,
1023 device_identity,
1024 } => decoder
1025 .decode_raw_next(cancel)?
1026 .map(|frame| {
1027 d3d12_frame(
1028 decoder,
1029 frame.into_frame(),
1030 *generation,
1031 *device_identity,
1032 &mut self.hardware_failure,
1033 )
1034 })
1035 .transpose(),
1036 }
1037 }
1038}
1039
1040#[cfg(all(target_os = "windows", feature = "hwdecode"))]
1044fn d3d12_frame(
1045 decoder: &NativeDecoder,
1046 frame: AVFrame,
1047 generation: u64,
1048 device_identity: u64,
1049 failure: &mut Option<HardwareDecodeFallback>,
1050) -> Result<NativeVideoFrame, DecodeError> {
1051 let info = alpha2_ffmpeg_bridge::d3d12_frame_info(&frame)
1052 .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1053 let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1054 DecodeError::Unsupported(format!(
1055 "D3D12VA output {} is not an importable 4:2:0 surface",
1056 info.software_format
1057 ))
1058 })?;
1059 let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
1060 let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
1061 let crop = [
1062 frame.crop_left,
1063 frame.crop_top,
1064 frame.crop_right,
1065 frame.crop_bottom,
1066 ];
1067 let Some(visible_rect) =
1068 visible_rect_within_surface(width, height, crop, info.surface_width, info.surface_height)
1069 else {
1070 *failure = Some(HardwareDecodeFallback::UnsupportedCrop);
1071 return Err(DecodeError::Unsupported(format!(
1072 "D3D12VA decoded a {width}x{height} picture cropped {} columns from the left and {} rows from the top into a {}x{} surface, which does not hold it",
1073 frame.crop_left, frame.crop_top, info.surface_width, info.surface_height
1074 )));
1075 };
1076 let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1077 frame.pts
1078 } else {
1079 frame.best_effort_timestamp
1080 };
1081 let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1082 let metadata = NativeVideoFrameMetadata {
1083 pts,
1084 dts: None,
1085 duration: timestamp(frame.duration, decoder.time_base),
1086 visible_rect,
1087 orientation: decoder.orientation,
1088 sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1089 color: decoder.picture_color(&frame),
1090 chroma_location: decoder.picture_chroma_location(&frame),
1091 bit_depth: plane_layout.bit_depth(),
1092 plane_layout,
1093 device_identity,
1094 decoder_generation: generation,
1095 picture_identity: info.resource
1096 ^ info.fence_value
1097 ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1098 };
1099 Ok(NativeVideoFrame::Hardware {
1100 metadata,
1101 surface: Arc::new(alpha2_ffmpeg_bridge::D3D12FrameLease::new(frame)),
1102 })
1103}
1104
1105#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1108const VIDEOTOOLBOX_DECODE_LOG_CLASSES: &[&str] = &[
1109 "h264",
1110 "hevc",
1111 "vp9",
1112 "av1",
1113 "AVHWDeviceContext",
1114 "AVHWFramesContext",
1115];
1116
1117#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1120fn with_videotoolbox_log(error: DecodeError, mark: alpha2_ffmpeg_bridge::LogMark) -> DecodeError {
1121 let detail = alpha2_ffmpeg_bridge::log_detail(&alpha2_ffmpeg_bridge::log_since(
1122 mark,
1123 VIDEOTOOLBOX_DECODE_LOG_CLASSES,
1124 ));
1125 if detail.is_empty() {
1126 return error;
1127 }
1128 match error {
1129 DecodeError::Adapter(message) => DecodeError::Adapter(format!("{message}{detail}")),
1130 DecodeError::Unsupported(message) => DecodeError::Unsupported(format!("{message}{detail}")),
1131 DecodeError::Gpu { fault, message } => DecodeError::Gpu {
1132 fault,
1133 message: format!("{message}{detail}"),
1134 },
1135 other => other,
1136 }
1137}
1138
1139#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1140fn videotoolbox_frame(
1141 decoder: &NativeDecoder,
1142 frame: AVFrame,
1143 generation: u64,
1144 device_identity: u64,
1145) -> Result<NativeVideoFrame, DecodeError> {
1146 let info = alpha2_ffmpeg_bridge::videotoolbox_frame_info(&frame)
1147 .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1148 let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1149 DecodeError::Unsupported(format!(
1150 "VideoToolbox output {} is not an importable 4:2:0 surface",
1151 info.software_format
1152 ))
1153 })?;
1154 let width = u32::try_from(info.width).map_err(|_| DecodeError::OutOfRange)?;
1155 let height = u32::try_from(info.height).map_err(|_| DecodeError::OutOfRange)?;
1156 let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1157 frame.pts
1158 } else {
1159 frame.best_effort_timestamp
1160 };
1161 let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1162 let metadata = NativeVideoFrameMetadata {
1163 pts,
1164 dts: None,
1165 duration: timestamp(frame.duration, decoder.time_base),
1166 visible_rect: Rect {
1167 x: u32::try_from(frame.crop_left).unwrap_or(0),
1168 y: u32::try_from(frame.crop_top).unwrap_or(0),
1169 width: width.saturating_sub(
1170 u32::try_from(frame.crop_left.saturating_add(frame.crop_right)).unwrap_or(0),
1171 ),
1172 height: height.saturating_sub(
1173 u32::try_from(frame.crop_top.saturating_add(frame.crop_bottom)).unwrap_or(0),
1174 ),
1175 },
1176 orientation: decoder.orientation,
1177 sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1178 color: decoder.picture_color(&frame),
1179 chroma_location: decoder.picture_chroma_location(&frame),
1180 bit_depth: plane_layout.bit_depth(),
1181 plane_layout,
1182 device_identity,
1183 decoder_generation: generation,
1184 picture_identity: info.pixel_buffer ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1185 };
1186 Ok(NativeVideoFrame::Hardware {
1187 metadata,
1188 surface: Arc::new(alpha2_ffmpeg_bridge::VideoToolboxFrameLease::new(frame)),
1189 })
1190}
1191
1192#[cfg(all(target_os = "linux", feature = "hwdecode"))]
1193fn hardware_frame(
1194 decoder: &NativeDecoder,
1195 frame: AVFrame,
1196 generation: u64,
1197) -> Result<NativeVideoFrame, DecodeError> {
1198 let info = alpha2_ffmpeg_bridge::vulkan_frame_info(&frame)
1199 .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1200 let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1201 DecodeError::Unsupported(format!(
1202 "Vulkan output {} is not an importable 4:2:0 surface",
1203 info.software_format
1204 ))
1205 })?;
1206 let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
1209 let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
1210 let coded_width = u32::try_from(info.coded_width).map_err(|_| DecodeError::OutOfRange)?;
1211 let coded_height = u32::try_from(info.coded_height).map_err(|_| DecodeError::OutOfRange)?;
1212 if coded_width < width || coded_height < height {
1213 return Err(DecodeError::Adapter(
1214 "Vulkan frame is larger than its allocated surface".into(),
1215 ));
1216 }
1217 let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1218 frame.pts
1219 } else {
1220 frame.best_effort_timestamp
1221 };
1222 let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1223 let metadata = NativeVideoFrameMetadata {
1224 pts,
1225 dts: None,
1226 duration: timestamp(frame.duration, decoder.time_base),
1227 visible_rect: Rect {
1228 x: u32::try_from(frame.crop_left).unwrap_or(0),
1229 y: u32::try_from(frame.crop_top).unwrap_or(0),
1230 width: width.saturating_sub(
1231 u32::try_from(frame.crop_left.saturating_add(frame.crop_right)).unwrap_or(0),
1232 ),
1233 height: height.saturating_sub(
1234 u32::try_from(frame.crop_top.saturating_add(frame.crop_bottom)).unwrap_or(0),
1235 ),
1236 },
1237 orientation: decoder.orientation,
1238 sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1239 color: decoder.picture_color(&frame),
1240 chroma_location: decoder.picture_chroma_location(&frame),
1241 bit_depth: plane_layout.bit_depth(),
1242 plane_layout,
1243 device_identity: info.device,
1244 decoder_generation: generation,
1245 picture_identity: info.images[0] ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1246 };
1247 Ok(NativeVideoFrame::Hardware {
1248 metadata,
1249 surface: Arc::new(alpha2_ffmpeg_bridge::VulkanFrameLease::new(frame)),
1250 })
1251}
1252
1253fn metadata_from_cpu(frame: &DecodedVideoFrame) -> NativeVideoFrameMetadata {
1254 let plane_layout = match frame.pixel_format {
1255 PixelFormat::Yuv(format) => NativePlaneLayout::CpuYuv(format),
1256 PixelFormat::LinearRgbaF16 => NativePlaneLayout::CpuLinearRgbaF16,
1257 _ => NativePlaneLayout::CpuRgba8,
1258 };
1259 NativeVideoFrameMetadata {
1260 pts: frame.pts,
1261 dts: frame.dts,
1262 duration: frame.duration,
1263 visible_rect: frame.visible_rect,
1264 orientation: frame.orientation,
1265 sample_aspect_ratio: frame.sample_aspect_ratio,
1266 color: frame.color,
1267 chroma_location: frame.chroma_location,
1268 bit_depth: plane_layout.bit_depth(),
1269 plane_layout,
1270 device_identity: 0,
1271 decoder_generation: 0,
1272 picture_identity: u64::from_ne_bytes(frame.pts.ticks().to_ne_bytes()),
1273 }
1274}