Skip to main content

alpha2_native/
video_frame.rs

1//! Native export frame contract shared by software and hardware decoders.
2
3use 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/// Why a video source is decoded in software instead of on the GPU, recorded per source.
39#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
40pub enum HardwareDecodeFallback {
41    /// No shared GPU decode context was created for this run.
42    ContextUnavailable,
43    /// The codec exposes no hardware configuration for this backend.
44    NoHardwareConfig,
45    /// The stream declares a color space the hardware path does not present.
46    UnsupportedColor,
47    /// The stream's subsampling or bit depth has no resident path on this device (4:2:2,
48    /// 4:4:4, or 10-bit without P010).
49    UnsupportedProfile,
50    /// The decoder produced a surface format that cannot be imported.
51    UnsupportedSurfaceFormat,
52    /// The container or stream could not be opened at all.
53    SourceUnavailable,
54    /// The hardware decoder rejected this stream while opening.
55    DecoderOpenFailed,
56    /// Reverse playback keeps this cursor on the software decoder.
57    ReverseWindow,
58    /// The SPS crops the left or top edge, which this backend's surfaces lose (`VideoToolbox`
59    /// clears the crop and returns the top-left corner). A D3D12VA picture larger than its
60    /// surface is refused the same way.
61    UnsupportedCrop,
62    /// The renderer could not import a decoded surface, so its pixels went through the CPU.
63    ImportFailed,
64    /// The stream carries alpha, which a hardware session would drop (VP9 block additions, an HEVC
65    /// auxiliary layer, or an alpha plane).
66    AlphaChannel,
67}
68
69impl HardwareDecodeFallback {
70    /// Stable key used when reporting fallback counts.
71    #[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/// A hardware decode session that could not be opened, with its typed reason.
90#[derive(Debug)]
91pub struct HardwareOpenError {
92    /// Why the hardware path is unavailable for this source.
93    pub reason: HardwareDecodeFallback,
94    /// The underlying decode failure.
95    pub source: DecodeError,
96}
97
98impl HardwareOpenError {
99    /// Pairs a decode failure with the reason a caller should record.
100    #[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/// One backend's hardware-decoder negotiation parameters.
115#[cfg(all(
116    any(target_os = "linux", target_os = "macos", target_os = "windows"),
117    feature = "hwdecode"
118))]
119pub(crate) struct HardwareDecoderSpec<'a> {
120    /// `FFmpeg` hardware device type to match in the codec's configurations.
121    pub device_type: ffi::AVHWDeviceType,
122    /// Opaque hardware pixel format the decoder must produce.
123    pub pixel_format: ffi::AVPixelFormat,
124    /// Backend name used in diagnostics.
125    pub backend: &'static str,
126    /// Whether the configuration must accept a shared device context.
127    pub require_device_context: bool,
128    /// Whether the renderer can present 10-bit planes from this backend.
129    pub ten_bit: bool,
130    /// Whether this backend's frames keep an SPS's left and top crop.
131    ///
132    /// `FFmpeg`'s `VideoToolbox` hwaccel clears the crop, but the session only trims right/bottom
133    /// (H.264) or rescales (HEVC), so a leading crop would show wrong pixels. D3D12VA keeps the
134    /// crop as long as surfaces are the coded size (`alpha2_d3d12_get_format`), since `FFmpeg`
135    /// 8.1.3 would size them to the visible size.
136    pub keeps_leading_crop: bool,
137    /// How this backend returns the base layer of an HEVC stream with an alpha layer.
138    pub hevc_alpha_base_layer: HevcAlphaBaseLayer,
139    /// The codecs the device decodes in hardware, by `FFmpeg` name, when it lists them; others are
140    /// refused before a session opens. Needed for `VideoToolbox`, where `FFmpeg`'s HEVC request
141    /// lets a Mac without the hardware decoder run in software.
142    pub hardware_codecs: Option<&'a [&'static str]>,
143    /// Callback that selects `pixel_format` during negotiation.
144    pub get_format: unsafe extern "C" fn(
145        *mut ffi::AVCodecContext,
146        *const ffi::AVPixelFormat,
147    ) -> ffi::AVPixelFormat,
148}
149
150/// What a hardware decoder returns for the base layer of an HEVC stream with an alpha layer.
151#[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    /// Its samples as coded, as a software decoder returns them.
158    AsCoded,
159    /// Its samples mapped as if full range into video range (`VideoToolbox`).
160    #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
161    RangeConverted,
162}
163
164/// Plane organization of a native export frame.
165#[derive(Copy, Clone, Debug, Eq, PartialEq)]
166pub enum NativePlaneLayout {
167    /// Owned CPU YCbCr planes.
168    CpuYuv(alpha2_media::YuvFormat),
169    /// Owned CPU 8-bit RGBA, straight or premultiplied ([`PixelFormat`]).
170    CpuRgba8,
171    /// Owned CPU premultiplied linear-light half-float RGBA ([`PixelFormat::LinearRgbaF16`]).
172    CpuLinearRgbaF16,
173    /// Three imported R8 GPU planes.
174    GpuI420,
175    /// Imported R8 luma and RG8 chroma planes.
176    GpuNv12,
177    /// Imported R16 luma and RG16 chroma planes holding 10 significant bits.
178    GpuP010,
179}
180
181impl NativePlaneLayout {
182    /// Significant bits per component for this layout.
183    #[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    /// Bytes one coded pixel occupies across every plane of this layout.
194    #[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            // Luma, then two chroma planes of 4 >> (shift x + shift y) its area each,
208            // in half bytes per sample.
209            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/// Maps a hardware surface's software pixel format to its plane layout; `None` makes the caller
218/// report a typed fallback instead of presenting it as 4:2:0.
219#[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/// The visible rectangle of a hardware frame with `crop` (left, top, right, bottom) still on it, or
232/// `None` when it reaches past the `surface_width` x `surface_height` texture.
233///
234/// `FFmpeg` applies only the right and bottom crop to a hardware frame's size. A surface smaller
235/// than that never held the last columns or rows; this guards against a decoder making surfaces
236/// visible-sized (as `FFmpeg` 8.1.3 D3D12VA would without `alpha2_d3d12_get_format`).
237#[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/// Platform-neutral metadata carried identically by CPU and hardware frames.
266///
267/// It says nothing about backing memory: a hardware surface may be larger (1088 rows for 1080p
268/// H.264), and an importer reports the extent it samples.
269#[derive(Clone, Debug, PartialEq)]
270pub struct NativeVideoFrameMetadata {
271    /// Presentation timestamp.
272    pub pts: MediaTime,
273    /// Decode timestamp when available.
274    pub dts: Option<MediaTime>,
275    /// Nominal duration when available.
276    pub duration: Option<MediaTime>,
277    /// Visible crop.
278    pub visible_rect: Rect,
279    /// How the picture is shown upright.
280    pub orientation: Orientation,
281    /// Pixel aspect ratio.
282    pub sample_aspect_ratio: SampleAspectRatio,
283    /// Color declaration.
284    pub color: Option<ColorMetadata>,
285    /// Chroma sample position.
286    pub chroma_location: ChromaLocation,
287    /// Significant component bits.
288    pub bit_depth: u8,
289    /// Memory plane organization.
290    pub plane_layout: NativePlaneLayout,
291    /// GPU device identity, zero for CPU frames.
292    pub device_identity: u64,
293    /// Decoder or surface-pool generation.
294    pub decoder_generation: u64,
295    /// Physical picture identity within the generation.
296    pub picture_identity: u64,
297    /// Whether a straight alpha plane comes with the picture.
298    pub alpha_plane: bool,
299}
300
301/// Opaque decoder surface retained until GPU completion.
302pub trait HardwareFrameLease: Debug + Send + Sync + 'static {
303    /// Approximate allocation size charged to the surface budget.
304    fn retained_bytes(&self) -> u64;
305
306    /// Allows the platform interop crate to recover its private lease type.
307    fn as_any(&self) -> &dyn Any;
308
309    /// Converts a retained lease for platform-specific import without exposing the backend type.
310    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            // An unrecognized layout is charged as 8-bit 4:2:0; the frame is
321            // rejected before import anyway.
322            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            // An unrecognized layout is charged as 8-bit 4:2:0; the frame is
346            // rejected before import anyway.
347            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            // An unrecognized layout is charged as 8-bit 4:2:0; the frame is
371            // rejected before import anyway.
372            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/// One decoded export frame with either owned CPU pixels or an opaque surface.
389#[derive(Debug)]
390pub enum NativeVideoFrame {
391    /// Software-decoded frame.
392    Cpu(DecodedVideoFrame),
393    /// Hardware-decoded frame whose platform details remain behind its lease.
394    Hardware {
395        /// Presentation and cache identity.
396        metadata: NativeVideoFrameMetadata,
397        /// Ref-counted decoder-surface ownership.
398        surface: Arc<dyn HardwareFrameLease>,
399        /// The straight alpha plane, decoded on the CPU, at the surface's luma size, depth and
400        /// alignment ([`NativeVideoFrameMetadata::alpha_plane`]).
401        alpha: Option<alpha2_media::Plane>,
402    },
403}
404
405impl NativeVideoFrame {
406    /// Presentation timestamp.
407    #[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    /// Nominal frame duration when known.
416    #[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    /// Returns metadata without exposing the backing representation.
425    #[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    /// Whether this frame is backed by a decoder surface rather than CPU pixels.
434    #[must_use]
435    pub const fn is_hardware(&self) -> bool {
436        matches!(self, Self::Hardware { .. })
437    }
438
439    /// Returns the software frame when this is the CPU variant.
440    #[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    /// A CPU copy of this frame: itself, or the decoder surface downloaded through `FFmpeg`.
449    ///
450    /// The fallback for a surface the renderer could not import. Timing comes from this frame's
451    /// metadata; pixels go through the same conversion as software frames.
452    ///
453    /// # Errors
454    /// Returns a native decode error when the surface cannot be downloaded or converted.
455    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        // In tick units so the timestamp cannot overflow; the metadata replaces it below.
466        software.set_pts(metadata.pts.ticks());
467        let mut scaler = crate::convert::FrameScaler::default();
468        // The surface's own siting replaces the conversion's below.
469        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        // The conversion keeps the given color unless it repacked RGB under the identity matrix; an
483        // untagged surface stays untagged.
484        if metadata.color.is_none() {
485            frame.color = None;
486        }
487        Ok(frame)
488    }
489
490    /// Approximate retained bytes for separate CPU and surface budgets: a hardware frame's
491    /// surface and its alpha plane.
492    #[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    /// The bytes of a hardware frame's alpha plane; zero for other frames.
505    #[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/// Downloads a decoder surface of whichever platform lease this build knows.
517#[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
554/// Export decoder producing [`NativeVideoFrame`]s from one `FFmpeg` session.
555///
556/// Software and hardware sessions share demux, seek and timing ([`NativeDecoder`]); the backend
557/// only changes where pixels live.
558pub struct NativeExportDecoder {
559    backend: ExportDecoderBackend,
560    hardware_frames: u64,
561    /// Why the hardware path gave up, once it has.
562    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    /// Takes the decode-stage spans accumulated since the last call. Hardware sessions report no
588    /// conversion time; their cost is in `receive_frame`.
589    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    /// Whether this session currently produces device-resident frames.
602    #[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    /// Opens the selected video stream using the software implementation.
616    ///
617    /// # Errors
618    /// Returns a native decode error if the input or selected stream cannot be opened.
619    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    /// Opens with an explicit codec worker allocation.
630    ///
631    /// # Errors
632    /// Returns a native decode error for invalid worker counts or stream setup failures.
633    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    /// Opens a Vulkan hardware decoder on the renderer's logical device.
645    ///
646    /// # Errors
647    /// Returns a native decode error if the stream lacks a compatible Vulkan configuration or the
648    /// decoder cannot use the shared device.
649    #[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            // The device has decode extensions only for these codecs; `FFmpeg` would open a session
665            // for any other and fail on its first packet.
666            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    /// Opens a `VideoToolbox` hardware decoder producing `CoreVideo` surfaces.
682    ///
683    /// # Errors
684    /// Returns a native decode error if the stream cannot negotiate `AV_PIX_FMT_VIDEOTOOLBOX` or
685    /// create a hardware session.
686    #[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        // `VideoToolbox` creates its own session rather than adopting the renderer's device; Metal
694        // interop happens at import.
695        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    /// Opens a D3D12VA hardware decoder on the renderer's D3D12 device.
739    ///
740    /// # Errors
741    /// Returns a native decode error if the stream lacks a compatible D3D12VA configuration or the
742    /// shared device cannot create a decode session.
743    #[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    /// Stream descriptions from the common decode session.
775    #[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    /// What the decoder leaves out ([`crate::NativeDecoder::dropped_layer`]).
789    #[must_use]
790    pub fn dropped_layer(&self) -> Option<&crate::DroppedLayer> {
791        self.decoder().dropped_layer()
792    }
793
794    /// Whether the session decodes an alpha stream on the CPU beside its pictures (VP9 alpha).
795    #[must_use]
796    pub const fn decodes_alpha_stream(&self) -> bool {
797        self.decoder().decodes_alpha_stream()
798    }
799
800    /// Effective end of the selected video source.
801    #[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    /// Resets codec and demux state.
815    ///
816    /// # Errors
817    /// Returns a native decode error if the codec state cannot be reset.
818    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    /// Seeks and returns the selected native frame.
831    ///
832    /// # Errors
833    /// Returns a native decode error for cancellation, seek, decode, or timestamp failures.
834    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    /// Decodes the next native frame, or `None` at end of stream.
844    ///
845    /// # Errors
846    /// Returns a native decode error for cancellation or codec failures.
847    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    /// When the frame [`Self::decode_video_next`] returns next is presented, or `None` at the end.
856    ///
857    /// The frame is decoded now and kept, so a caller can find the frame shown at a time
858    /// without consuming the next one.
859    ///
860    /// # Errors
861    /// Returns a native decode error for cancellation or codec failures.
862    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    /// Configures corruption handling on the selected native backend.
871    pub fn set_decode_policy(&mut self, policy: crate::DecodePolicy) {
872        self.native_decoder().set_decode_policy(policy);
873    }
874
875    /// Sets the project's declared color for this source ([`NativeDecoder::declare_color`]).
876    ///
877    /// # Errors
878    /// Returns [`HardwareDecodeFallback::UnsupportedColor`] for HDR on a hardware
879    /// session, which presents SDR only.
880    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    /// Reports damage before any recovery or terminal error.
895    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    /// Cumulative corruption diagnostics for this session.
903    pub fn decode_diagnostics(&mut self) -> &crate::DecodeDiagnostics {
904        self.native_decoder().decode_diagnostics()
905    }
906
907    /// The latest timestamp a frame may carry and still be shown at `time`
908    /// ([`NativeDecoder::presentation_deadline`]).
909    #[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    /// Why this session's hardware path gave up, once a call returned [`DecodeError::Unsupported`].
939    #[must_use]
940    pub const fn hardware_failure(&self) -> Option<HardwareDecodeFallback> {
941        self.hardware_failure
942    }
943
944    /// Classifies a hardware session's failures so a caller can fall back.
945    ///
946    /// `FFmpeg` initializes a hardware decoder lazily in `get_format`, so an unsupported profile or
947    /// codec (VP9 without VP9 decode, 10-bit H.264 on NVDEC) fails on the first packet with a
948    /// generic error. Before the first frame such an error becomes [`DecodeError::Unsupported`]
949    /// with [`HardwareDecodeFallback::DecoderOpenFailed`]; afterwards it stays a real failure.
950    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/// A decoded D3D12VA frame as a [`NativeVideoFrame`]. A picture reaching past its surface
1085/// ([`visible_rect_within_surface`]) is refused with [`HardwareDecodeFallback::UnsupportedCrop`] so
1086/// the source continues in software.
1087#[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/// The log classes of a `VideoToolbox` decode: the codec context (where the hwaccel logs
1155/// `OSStatus`) and the hardware device and frames contexts.
1156#[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/// `error` with the `VideoToolbox` lines logged since `mark` appended, so the session's `OSStatus`
1167/// reaches the typed error. Errors without a message are returned unchanged.
1168#[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    // For hardware formats `av_frame_apply_cropping` only subtracts right and bottom crop; the
1263    // surface keeps the padded extent, so the visible rectangle sits inside it.
1264    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}