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#[cfg(all(
33 any(target_os = "linux", target_os = "macos", target_os = "windows"),
34 feature = "hwdecode"
35))]
36use crate::alpha::RawFrame;
37
38#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
40pub enum HardwareDecodeFallback {
41 ContextUnavailable,
43 NoHardwareConfig,
45 UnsupportedColor,
47 UnsupportedProfile,
50 UnsupportedSurfaceFormat,
52 SourceUnavailable,
54 DecoderOpenFailed,
56 ReverseWindow,
58 UnsupportedCrop,
62 ImportFailed,
64 AlphaChannel,
67}
68
69impl HardwareDecodeFallback {
70 #[must_use]
72 pub const fn as_str(self) -> &'static str {
73 match self {
74 Self::ContextUnavailable => "contextUnavailable",
75 Self::NoHardwareConfig => "noHardwareConfig",
76 Self::UnsupportedColor => "unsupportedColor",
77 Self::UnsupportedProfile => "unsupportedProfile",
78 Self::UnsupportedSurfaceFormat => "unsupportedSurfaceFormat",
79 Self::SourceUnavailable => "sourceUnavailable",
80 Self::DecoderOpenFailed => "decoderOpenFailed",
81 Self::ReverseWindow => "reverseWindow",
82 Self::UnsupportedCrop => "unsupportedCrop",
83 Self::ImportFailed => "importFailed",
84 Self::AlphaChannel => "alphaChannel",
85 }
86 }
87}
88
89#[derive(Debug)]
91pub struct HardwareOpenError {
92 pub reason: HardwareDecodeFallback,
94 pub source: DecodeError,
96}
97
98impl HardwareOpenError {
99 #[must_use]
101 pub const fn new(reason: HardwareDecodeFallback, source: DecodeError) -> Self {
102 Self { reason, source }
103 }
104}
105
106impl std::fmt::Display for HardwareOpenError {
107 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 write!(formatter, "{}: {:?}", self.reason.as_str(), self.source)
109 }
110}
111
112impl std::error::Error for HardwareOpenError {}
113
114#[cfg(all(
116 any(target_os = "linux", target_os = "macos", target_os = "windows"),
117 feature = "hwdecode"
118))]
119pub(crate) struct HardwareDecoderSpec<'a> {
120 pub device_type: ffi::AVHWDeviceType,
122 pub pixel_format: ffi::AVPixelFormat,
124 pub backend: &'static str,
126 pub require_device_context: bool,
128 pub ten_bit: bool,
130 pub keeps_leading_crop: bool,
137 pub hevc_alpha_base_layer: HevcAlphaBaseLayer,
139 pub hardware_codecs: Option<&'a [&'static str]>,
143 pub get_format: unsafe extern "C" fn(
145 *mut ffi::AVCodecContext,
146 *const ffi::AVPixelFormat,
147 ) -> ffi::AVPixelFormat,
148}
149
150#[cfg(all(
152 any(target_os = "linux", target_os = "macos", target_os = "windows"),
153 feature = "hwdecode"
154))]
155#[derive(Copy, Clone, Debug, Eq, PartialEq)]
156pub(crate) enum HevcAlphaBaseLayer {
157 AsCoded,
159 #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
161 RangeConverted,
162}
163
164#[derive(Copy, Clone, Debug, Eq, PartialEq)]
166pub enum NativePlaneLayout {
167 CpuYuv(alpha2_media::YuvFormat),
169 CpuRgba8,
171 CpuLinearRgbaF16,
173 GpuI420,
175 GpuNv12,
177 GpuP010,
179}
180
181impl NativePlaneLayout {
182 #[must_use]
184 pub const fn bit_depth(self) -> u8 {
185 match self {
186 Self::CpuRgba8 | Self::GpuI420 | Self::GpuNv12 => 8,
187 Self::CpuLinearRgbaF16 => 16,
188 Self::CpuYuv(format) => format.bit_depth,
189 Self::GpuP010 => 10,
190 }
191 }
192
193 #[cfg_attr(
195 not(all(
196 any(target_os = "linux", target_os = "macos", target_os = "windows"),
197 feature = "hwdecode"
198 )),
199 allow(dead_code)
200 )]
201 const fn bytes_per_pixel_numerator(self) -> u64 {
202 match self {
203 Self::CpuRgba8 => 8,
204 Self::CpuLinearRgbaF16 => 16,
205 Self::GpuI420 | Self::GpuNv12 => 3,
206 Self::GpuP010 => 6,
207 Self::CpuYuv(format) => {
210 format.bytes_per_sample() as u64
211 * (2 + (4 >> (format.chroma_shift_x + format.chroma_shift_y)))
212 }
213 }
214 }
215}
216
217#[cfg(all(
220 any(target_os = "linux", target_os = "macos", target_os = "windows"),
221 feature = "hwdecode"
222))]
223pub(crate) const fn surface_plane_layout(format: ffi::AVPixelFormat) -> Option<NativePlaneLayout> {
224 match format {
225 ffi::AV_PIX_FMT_NV12 => Some(NativePlaneLayout::GpuNv12),
226 ffi::AV_PIX_FMT_P010LE => Some(NativePlaneLayout::GpuP010),
227 _ => None,
228 }
229}
230
231#[cfg_attr(
238 not(all(target_os = "windows", feature = "hwdecode")),
239 allow(dead_code)
240)]
241pub(crate) fn visible_rect_within_surface(
242 width: u32,
243 height: u32,
244 [left, top, right, bottom]: [usize; 4],
245 surface_width: u32,
246 surface_height: u32,
247) -> Option<Rect> {
248 let x = u32::try_from(left).ok()?;
249 let y = u32::try_from(top).ok()?;
250 let visible = Rect {
251 x,
252 y,
253 width: width
254 .checked_sub(x)?
255 .checked_sub(u32::try_from(right).ok()?)?,
256 height: height
257 .checked_sub(y)?
258 .checked_sub(u32::try_from(bottom).ok()?)?,
259 };
260 (u64::from(x) + u64::from(visible.width) <= u64::from(surface_width)
261 && u64::from(y) + u64::from(visible.height) <= u64::from(surface_height))
262 .then_some(visible)
263}
264
265#[derive(Clone, Debug, PartialEq)]
270pub struct NativeVideoFrameMetadata {
271 pub pts: MediaTime,
273 pub dts: Option<MediaTime>,
275 pub duration: Option<MediaTime>,
277 pub visible_rect: Rect,
279 pub orientation: Orientation,
281 pub sample_aspect_ratio: SampleAspectRatio,
283 pub color: Option<ColorMetadata>,
285 pub chroma_location: ChromaLocation,
287 pub bit_depth: u8,
289 pub plane_layout: NativePlaneLayout,
291 pub device_identity: u64,
293 pub decoder_generation: u64,
295 pub picture_identity: u64,
297 pub alpha_plane: bool,
299}
300
301pub trait HardwareFrameLease: Debug + Send + Sync + 'static {
303 fn retained_bytes(&self) -> u64;
305
306 fn as_any(&self) -> &dyn Any;
308
309 fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
311}
312
313#[cfg(all(target_os = "linux", feature = "hwdecode"))]
314impl HardwareFrameLease for alpha2_ffmpeg_bridge::VulkanFrameLease {
315 fn retained_bytes(&self) -> u64 {
316 self.info().map_or(0, |info| {
317 let pixels = u64::try_from(info.width)
318 .unwrap_or(0)
319 .saturating_mul(u64::try_from(info.height).unwrap_or(0));
320 let numerator = surface_plane_layout(info.software_format)
323 .unwrap_or(NativePlaneLayout::GpuNv12)
324 .bytes_per_pixel_numerator();
325 pixels.saturating_mul(numerator).div_ceil(2)
326 })
327 }
328
329 fn as_any(&self) -> &dyn Any {
330 self
331 }
332
333 fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
334 self
335 }
336}
337
338#[cfg(all(target_os = "macos", feature = "hwdecode"))]
339impl HardwareFrameLease for alpha2_ffmpeg_bridge::VideoToolboxFrameLease {
340 fn retained_bytes(&self) -> u64 {
341 self.info().map_or(0, |info| {
342 let pixels = u64::try_from(info.width)
343 .unwrap_or(0)
344 .saturating_mul(u64::try_from(info.height).unwrap_or(0));
345 let numerator = surface_plane_layout(info.software_format)
348 .unwrap_or(NativePlaneLayout::GpuNv12)
349 .bytes_per_pixel_numerator();
350 pixels.saturating_mul(numerator).div_ceil(2)
351 })
352 }
353
354 fn as_any(&self) -> &dyn Any {
355 self
356 }
357
358 fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
359 self
360 }
361}
362
363#[cfg(all(target_os = "windows", feature = "hwdecode"))]
364impl HardwareFrameLease for alpha2_ffmpeg_bridge::D3D12FrameLease {
365 fn retained_bytes(&self) -> u64 {
366 self.info().map_or(0, |info| {
367 let pixels = u64::try_from(info.width)
368 .unwrap_or(0)
369 .saturating_mul(u64::try_from(info.height).unwrap_or(0));
370 let numerator = surface_plane_layout(info.software_format)
373 .unwrap_or(NativePlaneLayout::GpuNv12)
374 .bytes_per_pixel_numerator();
375 pixels.saturating_mul(numerator).div_ceil(2)
376 })
377 }
378
379 fn as_any(&self) -> &dyn Any {
380 self
381 }
382
383 fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
384 self
385 }
386}
387
388#[derive(Debug)]
390pub enum NativeVideoFrame {
391 Cpu(DecodedVideoFrame),
393 Hardware {
395 metadata: NativeVideoFrameMetadata,
397 surface: Arc<dyn HardwareFrameLease>,
399 alpha: Option<alpha2_media::Plane>,
402 },
403}
404
405impl NativeVideoFrame {
406 #[must_use]
408 pub fn pts(&self) -> MediaTime {
409 match self {
410 Self::Cpu(frame) => frame.pts,
411 Self::Hardware { metadata, .. } => metadata.pts,
412 }
413 }
414
415 #[must_use]
417 pub fn duration(&self) -> Option<MediaTime> {
418 match self {
419 Self::Cpu(frame) => frame.duration,
420 Self::Hardware { metadata, .. } => metadata.duration,
421 }
422 }
423
424 #[must_use]
426 pub fn metadata(&self) -> NativeVideoFrameMetadata {
427 match self {
428 Self::Cpu(frame) => metadata_from_cpu(frame),
429 Self::Hardware { metadata, .. } => metadata.clone(),
430 }
431 }
432
433 #[must_use]
435 pub const fn is_hardware(&self) -> bool {
436 matches!(self, Self::Hardware { .. })
437 }
438
439 #[must_use]
441 pub fn as_cpu(&self) -> Option<&DecodedVideoFrame> {
442 match self {
443 Self::Cpu(frame) => Some(frame),
444 Self::Hardware { .. } => None,
445 }
446 }
447
448 pub fn to_cpu(&self) -> Result<DecodedVideoFrame, DecodeError> {
456 let (metadata, surface, alpha) = match self {
457 Self::Cpu(frame) => return Ok(frame.clone()),
458 Self::Hardware {
459 metadata,
460 surface,
461 alpha,
462 } => (metadata, surface, alpha),
463 };
464 let mut software = download_surface(surface.as_ref())?;
465 software.set_pts(metadata.pts.ticks());
467 let mut scaler = crate::convert::FrameScaler::default();
468 let mut frame = crate::convert::convert_video_frame(
470 &software,
471 alpha.as_ref().map(crate::alpha::FrameAlpha::AtLumaLayout),
472 rsmpeg::ffi::AV_CODEC_ID_NONE,
473 crate::convert::tick_base(),
474 metadata.color.unwrap_or_default(),
475 &mut scaler,
476 )?;
477 frame.pts = metadata.pts;
478 frame.duration = metadata.duration;
479 frame.orientation = metadata.orientation;
480 frame.sample_aspect_ratio = metadata.sample_aspect_ratio;
481 frame.chroma_location = metadata.chroma_location;
482 if metadata.color.is_none() {
485 frame.color = None;
486 }
487 Ok(frame)
488 }
489
490 #[must_use]
493 pub fn retained_bytes(&self) -> u64 {
494 match self {
495 Self::Cpu(frame) => frame.planes.iter().fold(0_u64, |total, plane| {
496 total.saturating_add(u64::try_from(plane.bytes.len()).unwrap_or(u64::MAX))
497 }),
498 Self::Hardware { surface, .. } => surface
499 .retained_bytes()
500 .saturating_add(self.hardware_alpha_bytes()),
501 }
502 }
503
504 #[must_use]
506 pub fn hardware_alpha_bytes(&self) -> u64 {
507 match self {
508 Self::Hardware {
509 alpha: Some(alpha), ..
510 } => u64::try_from(alpha.bytes.len()).unwrap_or(u64::MAX),
511 _ => 0,
512 }
513 }
514}
515
516#[cfg_attr(
518 not(all(
519 any(target_os = "linux", target_os = "macos", target_os = "windows"),
520 feature = "hwdecode"
521 )),
522 allow(clippy::unnecessary_wraps)
523)]
524fn download_surface(
525 surface: &dyn HardwareFrameLease,
526) -> Result<alpha2_ffmpeg_bridge::DecodedFrame, DecodeError> {
527 let any = surface.as_any();
528 let downloaded: Option<
529 Result<alpha2_ffmpeg_bridge::DecodedFrame, alpha2_ffmpeg_bridge::BridgeError>,
530 > = None;
531 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
532 let downloaded = downloaded.or_else(|| {
533 any.downcast_ref::<alpha2_ffmpeg_bridge::VulkanFrameLease>()
534 .map(alpha2_ffmpeg_bridge::VulkanFrameLease::download)
535 });
536 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
537 let downloaded = downloaded.or_else(|| {
538 any.downcast_ref::<alpha2_ffmpeg_bridge::VideoToolboxFrameLease>()
539 .map(alpha2_ffmpeg_bridge::VideoToolboxFrameLease::download)
540 });
541 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
542 let downloaded = downloaded.or_else(|| {
543 any.downcast_ref::<alpha2_ffmpeg_bridge::D3D12FrameLease>()
544 .map(alpha2_ffmpeg_bridge::D3D12FrameLease::download)
545 });
546 let _ = any;
547 downloaded
548 .ok_or_else(|| {
549 DecodeError::Unsupported("this hardware surface cannot be downloaded".into())
550 })?
551 .map_err(|error| DecodeError::Adapter(error.to_string()))
552}
553
554pub struct NativeExportDecoder {
559 backend: ExportDecoderBackend,
560 hardware_frames: u64,
561 hardware_failure: Option<HardwareDecodeFallback>,
563}
564
565enum ExportDecoderBackend {
566 Software(NativeDecoder),
567 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
568 Vulkan {
569 decoder: NativeDecoder,
570 generation: u64,
571 },
572 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
573 VideoToolbox {
574 decoder: NativeDecoder,
575 generation: u64,
576 device_identity: u64,
577 },
578 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
579 D3D12 {
580 decoder: NativeDecoder,
581 generation: u64,
582 device_identity: u64,
583 },
584}
585
586impl NativeExportDecoder {
587 pub fn take_stage_timings(&mut self) -> DecodeStageTimings {
590 match &mut self.backend {
591 ExportDecoderBackend::Software(decoder) => decoder.take_stage_timings(),
592 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
593 ExportDecoderBackend::Vulkan { decoder, .. } => decoder.take_stage_timings(),
594 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
595 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.take_stage_timings(),
596 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
597 ExportDecoderBackend::D3D12 { decoder, .. } => decoder.take_stage_timings(),
598 }
599 }
600
601 #[must_use]
603 pub const fn is_hardware(&self) -> bool {
604 match &self.backend {
605 ExportDecoderBackend::Software(_) => false,
606 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
607 ExportDecoderBackend::Vulkan { .. } => true,
608 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
609 ExportDecoderBackend::VideoToolbox { .. } => true,
610 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
611 ExportDecoderBackend::D3D12 { .. } => true,
612 }
613 }
614
615 pub fn open(
620 source: impl Into<alpha2_host_core::remote::SourceLocation>,
621 ) -> Result<Self, DecodeError> {
622 NativeDecoder::open(source).map(|decoder| Self {
623 backend: ExportDecoderBackend::Software(decoder),
624 hardware_frames: 0,
625 hardware_failure: None,
626 })
627 }
628
629 pub fn open_with_threads(
634 source: impl Into<alpha2_host_core::remote::SourceLocation>,
635 threads: i64,
636 ) -> Result<Self, DecodeError> {
637 NativeDecoder::open_with_threads(source, threads).map(|decoder| Self {
638 backend: ExportDecoderBackend::Software(decoder),
639 hardware_frames: 0,
640 hardware_failure: None,
641 })
642 }
643
644 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
650 pub fn open_vulkan(
651 source: impl Into<alpha2_host_core::remote::SourceLocation>,
652 threads: i64,
653 context: &SharedVulkanContext,
654 generation: u64,
655 ) -> Result<Self, HardwareOpenError> {
656 let spec = HardwareDecoderSpec {
657 device_type: ffi::AV_HWDEVICE_TYPE_VULKAN,
658 pixel_format: ffi::AV_PIX_FMT_VULKAN,
659 backend: "Vulkan",
660 require_device_context: true,
661 ten_bit: context.supports_ten_bit(),
662 keeps_leading_crop: true,
663 hevc_alpha_base_layer: HevcAlphaBaseLayer::AsCoded,
664 hardware_codecs: Some(context.decode_codecs()),
667 get_format: alpha2_ffmpeg_bridge::vulkan_get_format_callback(),
668 };
669 NativeDecoder::open_hardware(source, threads, context.ffmpeg_device(), &spec).map(
670 |decoder| Self {
671 backend: ExportDecoderBackend::Vulkan {
672 decoder,
673 generation,
674 },
675 hardware_frames: 0,
676 hardware_failure: None,
677 },
678 )
679 }
680
681 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
687 pub fn open_videotoolbox(
688 source: impl Into<alpha2_host_core::remote::SourceLocation>,
689 threads: i64,
690 context: &SharedMetalContext,
691 generation: u64,
692 ) -> Result<Self, HardwareOpenError> {
693 alpha2_ffmpeg_bridge::check_hardware_interop()
696 .map_err(crate::convert::adapter_error)
697 .map_err(|error| {
698 HardwareOpenError::new(HardwareDecodeFallback::DecoderOpenFailed, error)
699 })?;
700 let mark = alpha2_ffmpeg_bridge::log_mark();
701 let device = rsmpeg::avutil::AVHWDeviceContext::create(
702 ffi::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
703 None,
704 None,
705 0,
706 )
707 .map_err(crate::convert::adapter_error)
708 .map_err(|error| {
709 HardwareOpenError::new(HardwareDecodeFallback::DecoderOpenFailed, error)
710 })?;
711 let spec = HardwareDecoderSpec {
712 device_type: ffi::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
713 pixel_format: ffi::AV_PIX_FMT_VIDEOTOOLBOX,
714 backend: "VideoToolbox",
715 require_device_context: false,
716 ten_bit: context.supports_ten_bit(),
717 keeps_leading_crop: false,
718 hevc_alpha_base_layer: HevcAlphaBaseLayer::RangeConverted,
719 hardware_codecs: Some(context.decode_codecs()),
720 get_format: alpha2_ffmpeg_bridge::videotoolbox_get_format_callback(),
721 };
722 NativeDecoder::open_hardware(source, threads, device, &spec)
723 .map(|decoder| Self {
724 backend: ExportDecoderBackend::VideoToolbox {
725 decoder,
726 generation,
727 device_identity: context.identity().device,
728 },
729 hardware_frames: 0,
730 hardware_failure: None,
731 })
732 .map_err(|mut error| {
733 error.source = with_videotoolbox_log(error.source, mark);
734 error
735 })
736 }
737
738 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
744 pub fn open_d3d12(
745 source: impl Into<alpha2_host_core::remote::SourceLocation>,
746 threads: i64,
747 context: &SharedD3D12Context,
748 generation: u64,
749 ) -> Result<Self, HardwareOpenError> {
750 let spec = HardwareDecoderSpec {
751 device_type: ffi::AV_HWDEVICE_TYPE_D3D12VA,
752 pixel_format: ffi::AV_PIX_FMT_D3D12,
753 backend: "D3D12VA",
754 require_device_context: true,
755 ten_bit: context.supports_ten_bit(),
756 keeps_leading_crop: true,
757 hevc_alpha_base_layer: HevcAlphaBaseLayer::AsCoded,
758 hardware_codecs: None,
759 get_format: alpha2_ffmpeg_bridge::d3d12_get_format_callback(),
760 };
761 NativeDecoder::open_hardware(source, threads, context.ffmpeg_device(), &spec).map(
762 |decoder| Self {
763 backend: ExportDecoderBackend::D3D12 {
764 decoder,
765 generation,
766 device_identity: context.identity().device,
767 },
768 hardware_frames: 0,
769 hardware_failure: None,
770 },
771 )
772 }
773
774 #[must_use]
776 pub fn streams(&self) -> &[StreamInfo] {
777 match &self.backend {
778 ExportDecoderBackend::Software(decoder) => decoder.streams(),
779 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
780 ExportDecoderBackend::Vulkan { decoder, .. } => decoder.streams(),
781 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
782 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.streams(),
783 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
784 ExportDecoderBackend::D3D12 { decoder, .. } => decoder.streams(),
785 }
786 }
787
788 #[must_use]
790 pub fn dropped_layer(&self) -> Option<&crate::DroppedLayer> {
791 self.decoder().dropped_layer()
792 }
793
794 #[must_use]
796 pub const fn decodes_alpha_stream(&self) -> bool {
797 self.decoder().decodes_alpha_stream()
798 }
799
800 #[must_use]
802 pub fn video_duration(&self) -> Option<MediaTime> {
803 match &self.backend {
804 ExportDecoderBackend::Software(decoder) => decoder.video_duration(),
805 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
806 ExportDecoderBackend::Vulkan { decoder, .. } => decoder.video_duration(),
807 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
808 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.video_duration(),
809 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
810 ExportDecoderBackend::D3D12 { decoder, .. } => decoder.video_duration(),
811 }
812 }
813
814 pub fn flush(&mut self) -> Result<(), DecodeError> {
819 match &mut self.backend {
820 ExportDecoderBackend::Software(decoder) => decoder.flush(),
821 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
822 ExportDecoderBackend::Vulkan { decoder, .. } => decoder.flush(),
823 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
824 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.flush(),
825 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
826 ExportDecoderBackend::D3D12 { decoder, .. } => decoder.flush(),
827 }
828 }
829
830 pub fn seek_video(
835 &mut self,
836 request: DecodeRequest,
837 cancel: &CancelToken,
838 ) -> Result<NativeVideoFrame, DecodeError> {
839 let result = self.seek_video_on_backend(request, cancel);
840 self.observe(result, |_| true)
841 }
842
843 pub fn decode_video_next(
848 &mut self,
849 cancel: &CancelToken,
850 ) -> Result<Option<NativeVideoFrame>, DecodeError> {
851 let result = self.decode_video_next_on_backend(cancel);
852 self.observe(result, Option::is_some)
853 }
854
855 pub fn peek_video_pts(
863 &mut self,
864 cancel: &CancelToken,
865 ) -> Result<Option<MediaTime>, DecodeError> {
866 let result = self.native_decoder().peek_raw_pts(cancel);
867 self.observe(result, |_| false)
868 }
869
870 pub fn set_decode_policy(&mut self, policy: crate::DecodePolicy) {
872 self.native_decoder().set_decode_policy(policy);
873 }
874
875 pub fn with_declared_color(
881 mut self,
882 color: Option<ColorMetadata>,
883 ) -> Result<Self, HardwareOpenError> {
884 if self.is_hardware() && color.is_some_and(ColorMetadata::is_hdr) {
885 return Err(HardwareOpenError::new(
886 HardwareDecodeFallback::UnsupportedColor,
887 DecodeError::Unsupported("hardware export currently supports SDR only".into()),
888 ));
889 }
890 self.native_decoder().declare_color(color);
891 Ok(self)
892 }
893
894 pub fn set_decode_reporter(
896 &mut self,
897 reporter: impl Fn(crate::DecodeDiagnostic) + Send + Sync + 'static,
898 ) {
899 self.native_decoder().set_decode_reporter(reporter);
900 }
901
902 pub fn decode_diagnostics(&mut self) -> &crate::DecodeDiagnostics {
904 self.native_decoder().decode_diagnostics()
905 }
906
907 #[must_use]
910 pub fn presentation_deadline(&self, time: MediaTime) -> MediaTime {
911 self.decoder().presentation_deadline(time)
912 }
913
914 const fn decoder(&self) -> &NativeDecoder {
915 match &self.backend {
916 ExportDecoderBackend::Software(decoder) => decoder,
917 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
918 ExportDecoderBackend::Vulkan { decoder, .. } => decoder,
919 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
920 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder,
921 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
922 ExportDecoderBackend::D3D12 { decoder, .. } => decoder,
923 }
924 }
925
926 fn native_decoder(&mut self) -> &mut NativeDecoder {
927 match &mut self.backend {
928 ExportDecoderBackend::Software(decoder) => decoder,
929 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
930 ExportDecoderBackend::Vulkan { decoder, .. } => decoder,
931 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
932 ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder,
933 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
934 ExportDecoderBackend::D3D12 { decoder, .. } => decoder,
935 }
936 }
937
938 #[must_use]
940 pub const fn hardware_failure(&self) -> Option<HardwareDecodeFallback> {
941 self.hardware_failure
942 }
943
944 fn observe<T>(
951 &mut self,
952 result: Result<T, DecodeError>,
953 produced: impl Fn(&T) -> bool,
954 ) -> Result<T, DecodeError> {
955 if !self.is_hardware() {
956 return result;
957 }
958 match result {
959 Ok(value) => {
960 if produced(&value) {
961 self.hardware_frames = self.hardware_frames.saturating_add(1);
962 }
963 Ok(value)
964 }
965 Err(DecodeError::Adapter(message)) if self.hardware_frames == 0 => {
966 self.hardware_failure = Some(HardwareDecodeFallback::DecoderOpenFailed);
967 Err(DecodeError::Unsupported(format!(
968 "the hardware decoder failed before its first frame: {message}"
969 )))
970 }
971 Err(DecodeError::Unsupported(message)) => {
972 self.hardware_failure
973 .get_or_insert(HardwareDecodeFallback::UnsupportedSurfaceFormat);
974 Err(DecodeError::Unsupported(message))
975 }
976 Err(error) => Err(error),
977 }
978 }
979
980 fn seek_video_on_backend(
981 &mut self,
982 request: DecodeRequest,
983 cancel: &CancelToken,
984 ) -> Result<NativeVideoFrame, DecodeError> {
985 match &mut self.backend {
986 ExportDecoderBackend::Software(decoder) => match decoder.seek(request, cancel)?.event {
987 DecodeEvent::Video(frame) => Ok(NativeVideoFrame::Cpu(frame)),
988 _ => Err(DecodeError::Adapter(
989 "video decoder returned a non-video event".into(),
990 )),
991 },
992 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
993 ExportDecoderBackend::Vulkan {
994 decoder,
995 generation,
996 } => {
997 let frame = decoder.seek_raw(request.time, cancel)?;
998 hardware_frame(decoder, frame, *generation)
999 }
1000 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
1001 ExportDecoderBackend::VideoToolbox {
1002 decoder,
1003 generation,
1004 device_identity,
1005 } => {
1006 let mark = alpha2_ffmpeg_bridge::log_mark();
1007 let frame = decoder
1008 .seek_raw(request.time, cancel)
1009 .map_err(|error| with_videotoolbox_log(error, mark))?;
1010 videotoolbox_frame(decoder, frame, *generation, *device_identity)
1011 }
1012 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
1013 ExportDecoderBackend::D3D12 {
1014 decoder,
1015 generation,
1016 device_identity,
1017 } => {
1018 let frame = decoder.seek_raw(request.time, cancel)?;
1019 d3d12_frame(
1020 decoder,
1021 frame,
1022 *generation,
1023 *device_identity,
1024 &mut self.hardware_failure,
1025 )
1026 }
1027 }
1028 }
1029
1030 fn decode_video_next_on_backend(
1031 &mut self,
1032 cancel: &CancelToken,
1033 ) -> Result<Option<NativeVideoFrame>, DecodeError> {
1034 match &mut self.backend {
1035 ExportDecoderBackend::Software(decoder) => match decoder.decode_next(cancel)? {
1036 DecodeEvent::Video(frame) => Ok(Some(NativeVideoFrame::Cpu(frame))),
1037 DecodeEvent::EndOfStream => Ok(None),
1038 _ => Err(DecodeError::Adapter(
1039 "video decoder returned a non-video event".into(),
1040 )),
1041 },
1042 #[cfg(all(target_os = "linux", feature = "hwdecode"))]
1043 ExportDecoderBackend::Vulkan {
1044 decoder,
1045 generation,
1046 } => decoder
1047 .decode_raw_next(cancel)?
1048 .map(|frame| hardware_frame(decoder, frame, *generation))
1049 .transpose(),
1050 #[cfg(all(target_os = "macos", feature = "hwdecode"))]
1051 ExportDecoderBackend::VideoToolbox {
1052 decoder,
1053 generation,
1054 device_identity,
1055 } => {
1056 let mark = alpha2_ffmpeg_bridge::log_mark();
1057 decoder
1058 .decode_raw_next(cancel)
1059 .map_err(|error| with_videotoolbox_log(error, mark))?
1060 .map(|frame| videotoolbox_frame(decoder, frame, *generation, *device_identity))
1061 .transpose()
1062 }
1063 #[cfg(all(target_os = "windows", feature = "hwdecode"))]
1064 ExportDecoderBackend::D3D12 {
1065 decoder,
1066 generation,
1067 device_identity,
1068 } => decoder
1069 .decode_raw_next(cancel)?
1070 .map(|frame| {
1071 d3d12_frame(
1072 decoder,
1073 frame,
1074 *generation,
1075 *device_identity,
1076 &mut self.hardware_failure,
1077 )
1078 })
1079 .transpose(),
1080 }
1081 }
1082}
1083
1084#[cfg(all(target_os = "windows", feature = "hwdecode"))]
1088fn d3d12_frame(
1089 decoder: &NativeDecoder,
1090 frame: RawFrame,
1091 generation: u64,
1092 device_identity: u64,
1093 failure: &mut Option<HardwareDecodeFallback>,
1094) -> Result<NativeVideoFrame, DecodeError> {
1095 let (frame, alpha) = frame.into_parts();
1096 let frame = frame.into_frame();
1097 let info = alpha2_ffmpeg_bridge::d3d12_frame_info(&frame)
1098 .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1099 let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1100 DecodeError::Unsupported(format!(
1101 "D3D12VA output {} is not an importable 4:2:0 surface",
1102 info.software_format
1103 ))
1104 })?;
1105 let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
1106 let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
1107 let crop = [
1108 frame.crop_left,
1109 frame.crop_top,
1110 frame.crop_right,
1111 frame.crop_bottom,
1112 ];
1113 let Some(visible_rect) =
1114 visible_rect_within_surface(width, height, crop, info.surface_width, info.surface_height)
1115 else {
1116 *failure = Some(HardwareDecodeFallback::UnsupportedCrop);
1117 return Err(DecodeError::Unsupported(format!(
1118 "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",
1119 frame.crop_left, frame.crop_top, info.surface_width, info.surface_height
1120 )));
1121 };
1122 let alpha = surface_alpha_plane(alpha.as_ref(), &frame, plane_layout)?;
1123 let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1124 frame.pts
1125 } else {
1126 frame.best_effort_timestamp
1127 };
1128 let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1129 let metadata = NativeVideoFrameMetadata {
1130 pts,
1131 dts: None,
1132 duration: timestamp(frame.duration, decoder.time_base),
1133 visible_rect,
1134 orientation: decoder.orientation,
1135 sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1136 color: decoder.picture_color(&frame),
1137 chroma_location: decoder.picture_chroma_location(&frame),
1138 bit_depth: plane_layout.bit_depth(),
1139 plane_layout,
1140 device_identity,
1141 decoder_generation: generation,
1142 picture_identity: info.resource
1143 ^ info.fence_value
1144 ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1145 alpha_plane: alpha.is_some(),
1146 };
1147 Ok(NativeVideoFrame::Hardware {
1148 metadata,
1149 surface: Arc::new(alpha2_ffmpeg_bridge::D3D12FrameLease::new(frame)),
1150 alpha,
1151 })
1152}
1153
1154#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1157const VIDEOTOOLBOX_DECODE_LOG_CLASSES: &[&str] = &[
1158 "h264",
1159 "hevc",
1160 "vp9",
1161 "av1",
1162 "AVHWDeviceContext",
1163 "AVHWFramesContext",
1164];
1165
1166#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1169fn with_videotoolbox_log(error: DecodeError, mark: alpha2_ffmpeg_bridge::LogMark) -> DecodeError {
1170 let detail = alpha2_ffmpeg_bridge::log_detail(&alpha2_ffmpeg_bridge::log_since(
1171 mark,
1172 VIDEOTOOLBOX_DECODE_LOG_CLASSES,
1173 ));
1174 if detail.is_empty() {
1175 return error;
1176 }
1177 match error {
1178 DecodeError::Adapter(message) => DecodeError::Adapter(format!("{message}{detail}")),
1179 DecodeError::Unsupported(message) => DecodeError::Unsupported(format!("{message}{detail}")),
1180 DecodeError::Gpu { fault, message } => DecodeError::Gpu {
1181 fault,
1182 message: format!("{message}{detail}"),
1183 },
1184 other => other,
1185 }
1186}
1187
1188#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1189fn videotoolbox_frame(
1190 decoder: &NativeDecoder,
1191 frame: RawFrame,
1192 generation: u64,
1193 device_identity: u64,
1194) -> Result<NativeVideoFrame, DecodeError> {
1195 let (frame, alpha) = frame.into_parts();
1196 let frame = frame.into_frame();
1197 let info = alpha2_ffmpeg_bridge::videotoolbox_frame_info(&frame)
1198 .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1199 let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1200 DecodeError::Unsupported(format!(
1201 "VideoToolbox output {} is not an importable 4:2:0 surface",
1202 info.software_format
1203 ))
1204 })?;
1205 let width = u32::try_from(info.width).map_err(|_| DecodeError::OutOfRange)?;
1206 let height = u32::try_from(info.height).map_err(|_| DecodeError::OutOfRange)?;
1207 let alpha = surface_alpha_plane(alpha.as_ref(), &frame, plane_layout)?;
1208 let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1209 frame.pts
1210 } else {
1211 frame.best_effort_timestamp
1212 };
1213 let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1214 let metadata = NativeVideoFrameMetadata {
1215 pts,
1216 dts: None,
1217 duration: timestamp(frame.duration, decoder.time_base),
1218 visible_rect: Rect {
1219 x: u32::try_from(frame.crop_left).unwrap_or(0),
1220 y: u32::try_from(frame.crop_top).unwrap_or(0),
1221 width: width.saturating_sub(
1222 u32::try_from(frame.crop_left.saturating_add(frame.crop_right)).unwrap_or(0),
1223 ),
1224 height: height.saturating_sub(
1225 u32::try_from(frame.crop_top.saturating_add(frame.crop_bottom)).unwrap_or(0),
1226 ),
1227 },
1228 orientation: decoder.orientation,
1229 sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1230 color: decoder.picture_color(&frame),
1231 chroma_location: decoder.picture_chroma_location(&frame),
1232 bit_depth: plane_layout.bit_depth(),
1233 plane_layout,
1234 device_identity,
1235 decoder_generation: generation,
1236 picture_identity: info.pixel_buffer ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1237 alpha_plane: alpha.is_some(),
1238 };
1239 Ok(NativeVideoFrame::Hardware {
1240 metadata,
1241 surface: Arc::new(alpha2_ffmpeg_bridge::VideoToolboxFrameLease::new(frame)),
1242 alpha,
1243 })
1244}
1245
1246#[cfg(all(target_os = "linux", feature = "hwdecode"))]
1247fn hardware_frame(
1248 decoder: &NativeDecoder,
1249 frame: RawFrame,
1250 generation: u64,
1251) -> Result<NativeVideoFrame, DecodeError> {
1252 let (frame, alpha) = frame.into_parts();
1253 let frame = frame.into_frame();
1254 let info = alpha2_ffmpeg_bridge::vulkan_frame_info(&frame)
1255 .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1256 let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1257 DecodeError::Unsupported(format!(
1258 "Vulkan output {} is not an importable 4:2:0 surface",
1259 info.software_format
1260 ))
1261 })?;
1262 let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
1265 let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
1266 let coded_width = u32::try_from(info.coded_width).map_err(|_| DecodeError::OutOfRange)?;
1267 let coded_height = u32::try_from(info.coded_height).map_err(|_| DecodeError::OutOfRange)?;
1268 if coded_width < width || coded_height < height {
1269 return Err(DecodeError::Adapter(
1270 "Vulkan frame is larger than its allocated surface".into(),
1271 ));
1272 }
1273 let alpha = surface_alpha_plane(alpha.as_ref(), &frame, plane_layout)?;
1274 let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1275 frame.pts
1276 } else {
1277 frame.best_effort_timestamp
1278 };
1279 let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1280 let metadata = NativeVideoFrameMetadata {
1281 pts,
1282 dts: None,
1283 duration: timestamp(frame.duration, decoder.time_base),
1284 visible_rect: Rect {
1285 x: u32::try_from(frame.crop_left).unwrap_or(0),
1286 y: u32::try_from(frame.crop_top).unwrap_or(0),
1287 width: width.saturating_sub(
1288 u32::try_from(frame.crop_left.saturating_add(frame.crop_right)).unwrap_or(0),
1289 ),
1290 height: height.saturating_sub(
1291 u32::try_from(frame.crop_top.saturating_add(frame.crop_bottom)).unwrap_or(0),
1292 ),
1293 },
1294 orientation: decoder.orientation,
1295 sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1296 color: decoder.picture_color(&frame),
1297 chroma_location: decoder.picture_chroma_location(&frame),
1298 bit_depth: plane_layout.bit_depth(),
1299 plane_layout,
1300 device_identity: info.device,
1301 decoder_generation: generation,
1302 picture_identity: info.images[0] ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1303 alpha_plane: alpha.is_some(),
1304 };
1305 Ok(NativeVideoFrame::Hardware {
1306 metadata,
1307 surface: Arc::new(alpha2_ffmpeg_bridge::VulkanFrameLease::new(frame)),
1308 alpha,
1309 })
1310}
1311
1312#[cfg(all(
1313 any(target_os = "linux", target_os = "macos", target_os = "windows"),
1314 feature = "hwdecode"
1315))]
1316fn surface_alpha_plane(
1317 alpha: Option<&alpha2_ffmpeg_bridge::DecodedFrame>,
1318 picture: &AVFrame,
1319 layout: NativePlaneLayout,
1320) -> Result<Option<alpha2_media::Plane>, DecodeError> {
1321 let size = (
1322 u32::try_from(picture.width).map_err(|_| DecodeError::OutOfRange)?,
1323 u32::try_from(picture.height).map_err(|_| DecodeError::OutOfRange)?,
1324 );
1325 alpha
1326 .map(|alpha| {
1327 crate::alpha::FrameAlpha::Decoded(alpha).plane(
1328 size,
1329 layout.bit_depth(),
1330 layout == NativePlaneLayout::GpuP010,
1331 )
1332 })
1333 .transpose()
1334}
1335
1336fn metadata_from_cpu(frame: &DecodedVideoFrame) -> NativeVideoFrameMetadata {
1337 let plane_layout = match frame.pixel_format {
1338 PixelFormat::Yuv(format) => NativePlaneLayout::CpuYuv(format),
1339 PixelFormat::LinearRgbaF16 => NativePlaneLayout::CpuLinearRgbaF16,
1340 _ => NativePlaneLayout::CpuRgba8,
1341 };
1342 NativeVideoFrameMetadata {
1343 pts: frame.pts,
1344 dts: frame.dts,
1345 duration: frame.duration,
1346 visible_rect: frame.visible_rect,
1347 orientation: frame.orientation,
1348 sample_aspect_ratio: frame.sample_aspect_ratio,
1349 color: frame.color,
1350 chroma_location: frame.chroma_location,
1351 bit_depth: plane_layout.bit_depth(),
1352 plane_layout,
1353 device_identity: 0,
1354 decoder_generation: 0,
1355 picture_identity: u64::from_ne_bytes(frame.pts.ticks().to_ne_bytes()),
1356 alpha_plane: matches!(frame.pixel_format, PixelFormat::Yuv(format) if format.alpha),
1357 }
1358}