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/// Why a video source is decoded in software instead of on the GPU, recorded per source.
33#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
34pub enum HardwareDecodeFallback {
35    /// No shared GPU decode context was created for this run.
36    ContextUnavailable,
37    /// The codec exposes no hardware configuration for this backend.
38    NoHardwareConfig,
39    /// The stream declares a color space the hardware path does not present.
40    UnsupportedColor,
41    /// The stream's subsampling or bit depth has no resident path on this device (4:2:2,
42    /// 4:4:4, or 10-bit without P010).
43    UnsupportedProfile,
44    /// The decoder produced a surface format that cannot be imported.
45    UnsupportedSurfaceFormat,
46    /// The container or stream could not be opened at all.
47    SourceUnavailable,
48    /// The hardware decoder rejected this stream while opening.
49    DecoderOpenFailed,
50    /// Reverse playback keeps this cursor on the software decoder.
51    ReverseWindow,
52    /// The SPS crops the left or top edge, which this backend's surfaces lose (`VideoToolbox`
53    /// clears the crop and returns the top-left corner). A D3D12VA picture larger than its
54    /// surface is refused the same way.
55    UnsupportedCrop,
56    /// The renderer could not import a decoded surface, so its pixels went through the CPU.
57    ImportFailed,
58    /// The stream carries alpha, which a hardware session would drop (VP9 block additions, an HEVC
59    /// auxiliary layer, or an alpha plane).
60    AlphaChannel,
61}
62
63impl HardwareDecodeFallback {
64    /// Stable key used when reporting fallback counts.
65    #[must_use]
66    pub const fn as_str(self) -> &'static str {
67        match self {
68            Self::ContextUnavailable => "contextUnavailable",
69            Self::NoHardwareConfig => "noHardwareConfig",
70            Self::UnsupportedColor => "unsupportedColor",
71            Self::UnsupportedProfile => "unsupportedProfile",
72            Self::UnsupportedSurfaceFormat => "unsupportedSurfaceFormat",
73            Self::SourceUnavailable => "sourceUnavailable",
74            Self::DecoderOpenFailed => "decoderOpenFailed",
75            Self::ReverseWindow => "reverseWindow",
76            Self::UnsupportedCrop => "unsupportedCrop",
77            Self::ImportFailed => "importFailed",
78            Self::AlphaChannel => "alphaChannel",
79        }
80    }
81}
82
83/// A hardware decode session that could not be opened, with its typed reason.
84#[derive(Debug)]
85pub struct HardwareOpenError {
86    /// Why the hardware path is unavailable for this source.
87    pub reason: HardwareDecodeFallback,
88    /// The underlying decode failure.
89    pub source: DecodeError,
90}
91
92impl HardwareOpenError {
93    /// Pairs a decode failure with the reason a caller should record.
94    #[must_use]
95    pub const fn new(reason: HardwareDecodeFallback, source: DecodeError) -> Self {
96        Self { reason, source }
97    }
98}
99
100impl std::fmt::Display for HardwareOpenError {
101    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        write!(formatter, "{}: {:?}", self.reason.as_str(), self.source)
103    }
104}
105
106impl std::error::Error for HardwareOpenError {}
107
108/// One backend's hardware-decoder negotiation parameters.
109#[cfg(all(
110    any(target_os = "linux", target_os = "macos", target_os = "windows"),
111    feature = "hwdecode"
112))]
113pub(crate) struct HardwareDecoderSpec<'a> {
114    /// `FFmpeg` hardware device type to match in the codec's configurations.
115    pub device_type: ffi::AVHWDeviceType,
116    /// Opaque hardware pixel format the decoder must produce.
117    pub pixel_format: ffi::AVPixelFormat,
118    /// Backend name used in diagnostics.
119    pub backend: &'static str,
120    /// Whether the configuration must accept a shared device context.
121    pub require_device_context: bool,
122    /// Whether the renderer can present 10-bit planes from this backend.
123    pub ten_bit: bool,
124    /// Whether this backend's frames keep an SPS's left and top crop.
125    ///
126    /// `FFmpeg`'s `VideoToolbox` hwaccel clears the crop, but the session only trims right/bottom
127    /// (H.264) or rescales (HEVC), so a leading crop would show wrong pixels. D3D12VA keeps the
128    /// crop as long as surfaces are the coded size (`alpha2_d3d12_get_format`), since `FFmpeg`
129    /// 8.1.3 would size them to the visible size.
130    pub keeps_leading_crop: bool,
131    /// The codecs the device decodes in hardware, by `FFmpeg` name, when it lists them; others are
132    /// refused before a session opens. Needed for `VideoToolbox`, where `FFmpeg`'s HEVC request
133    /// lets a Mac without the hardware decoder run in software.
134    pub hardware_codecs: Option<&'a [&'static str]>,
135    /// Callback that selects `pixel_format` during negotiation.
136    pub get_format: unsafe extern "C" fn(
137        *mut ffi::AVCodecContext,
138        *const ffi::AVPixelFormat,
139    ) -> ffi::AVPixelFormat,
140}
141
142/// Plane organization of a native export frame.
143#[derive(Copy, Clone, Debug, Eq, PartialEq)]
144pub enum NativePlaneLayout {
145    /// Owned CPU YCbCr planes.
146    CpuYuv(alpha2_media::YuvFormat),
147    /// Owned CPU straight-alpha 8-bit RGBA ([`PixelFormat::Rgba8`]).
148    CpuRgba8,
149    /// Owned CPU premultiplied linear-light half-float RGBA ([`PixelFormat::LinearRgbaF16`]).
150    CpuLinearRgbaF16,
151    /// Three imported R8 GPU planes.
152    GpuI420,
153    /// Imported R8 luma and RG8 chroma planes.
154    GpuNv12,
155    /// Imported R16 luma and RG16 chroma planes holding 10 significant bits.
156    GpuP010,
157}
158
159impl NativePlaneLayout {
160    /// Significant bits per component for this layout.
161    #[must_use]
162    pub const fn bit_depth(self) -> u8 {
163        match self {
164            Self::CpuRgba8 | Self::GpuI420 | Self::GpuNv12 => 8,
165            Self::CpuLinearRgbaF16 => 16,
166            Self::CpuYuv(format) => format.bit_depth,
167            Self::GpuP010 => 10,
168        }
169    }
170
171    /// Bytes one coded pixel occupies across every plane of this layout.
172    #[cfg_attr(
173        not(all(
174            any(target_os = "linux", target_os = "macos", target_os = "windows"),
175            feature = "hwdecode"
176        )),
177        allow(dead_code)
178    )]
179    const fn bytes_per_pixel_numerator(self) -> u64 {
180        match self {
181            Self::CpuRgba8 => 8,
182            Self::CpuLinearRgbaF16 => 16,
183            Self::GpuI420 | Self::GpuNv12 => 3,
184            Self::GpuP010 => 6,
185            // Luma, then two chroma planes of 4 >> (shift x + shift y) its area each,
186            // in half bytes per sample.
187            Self::CpuYuv(format) => {
188                format.bytes_per_sample() as u64
189                    * (2 + (4 >> (format.chroma_shift_x + format.chroma_shift_y)))
190            }
191        }
192    }
193}
194
195/// Maps a hardware surface's software pixel format to its plane layout; `None` makes the caller
196/// report a typed fallback instead of presenting it as 4:2:0.
197#[cfg(all(
198    any(target_os = "linux", target_os = "macos", target_os = "windows"),
199    feature = "hwdecode"
200))]
201pub(crate) const fn surface_plane_layout(format: ffi::AVPixelFormat) -> Option<NativePlaneLayout> {
202    match format {
203        ffi::AV_PIX_FMT_NV12 => Some(NativePlaneLayout::GpuNv12),
204        ffi::AV_PIX_FMT_P010LE => Some(NativePlaneLayout::GpuP010),
205        _ => None,
206    }
207}
208
209/// The visible rectangle of a hardware frame with `crop` (left, top, right, bottom) still on it, or
210/// `None` when it reaches past the `surface_width` x `surface_height` texture.
211///
212/// `FFmpeg` applies only the right and bottom crop to a hardware frame's size. A surface smaller
213/// than that never held the last columns or rows; this guards against a decoder making surfaces
214/// visible-sized (as `FFmpeg` 8.1.3 D3D12VA would without `alpha2_d3d12_get_format`).
215#[cfg_attr(
216    not(all(target_os = "windows", feature = "hwdecode")),
217    allow(dead_code)
218)]
219pub(crate) fn visible_rect_within_surface(
220    width: u32,
221    height: u32,
222    [left, top, right, bottom]: [usize; 4],
223    surface_width: u32,
224    surface_height: u32,
225) -> Option<Rect> {
226    let x = u32::try_from(left).ok()?;
227    let y = u32::try_from(top).ok()?;
228    let visible = Rect {
229        x,
230        y,
231        width: width
232            .checked_sub(x)?
233            .checked_sub(u32::try_from(right).ok()?)?,
234        height: height
235            .checked_sub(y)?
236            .checked_sub(u32::try_from(bottom).ok()?)?,
237    };
238    (u64::from(x) + u64::from(visible.width) <= u64::from(surface_width)
239        && u64::from(y) + u64::from(visible.height) <= u64::from(surface_height))
240    .then_some(visible)
241}
242
243/// Platform-neutral metadata carried identically by CPU and hardware frames.
244///
245/// It says nothing about backing memory: a hardware surface may be larger (1088 rows for 1080p
246/// H.264), and an importer reports the extent it samples.
247#[derive(Clone, Debug, PartialEq)]
248pub struct NativeVideoFrameMetadata {
249    /// Presentation timestamp.
250    pub pts: MediaTime,
251    /// Decode timestamp when available.
252    pub dts: Option<MediaTime>,
253    /// Nominal duration when available.
254    pub duration: Option<MediaTime>,
255    /// Visible crop.
256    pub visible_rect: Rect,
257    /// How the picture is shown upright.
258    pub orientation: Orientation,
259    /// Pixel aspect ratio.
260    pub sample_aspect_ratio: SampleAspectRatio,
261    /// Color declaration.
262    pub color: Option<ColorMetadata>,
263    /// Chroma sample position.
264    pub chroma_location: ChromaLocation,
265    /// Significant component bits.
266    pub bit_depth: u8,
267    /// Memory plane organization.
268    pub plane_layout: NativePlaneLayout,
269    /// GPU device identity, zero for CPU frames.
270    pub device_identity: u64,
271    /// Decoder or surface-pool generation.
272    pub decoder_generation: u64,
273    /// Physical picture identity within the generation.
274    pub picture_identity: u64,
275}
276
277/// Opaque decoder surface retained until GPU completion.
278pub trait HardwareFrameLease: Debug + Send + Sync + 'static {
279    /// Approximate allocation size charged to the surface budget.
280    fn retained_bytes(&self) -> u64;
281
282    /// Allows the platform interop crate to recover its private lease type.
283    fn as_any(&self) -> &dyn Any;
284
285    /// Converts a retained lease for platform-specific import without exposing the backend type.
286    fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
287}
288
289#[cfg(all(target_os = "linux", feature = "hwdecode"))]
290impl HardwareFrameLease for alpha2_ffmpeg_bridge::VulkanFrameLease {
291    fn retained_bytes(&self) -> u64 {
292        self.info().map_or(0, |info| {
293            let pixels = u64::try_from(info.width)
294                .unwrap_or(0)
295                .saturating_mul(u64::try_from(info.height).unwrap_or(0));
296            // An unrecognized layout is charged as 8-bit 4:2:0; the frame is
297            // rejected before import anyway.
298            let numerator = surface_plane_layout(info.software_format)
299                .unwrap_or(NativePlaneLayout::GpuNv12)
300                .bytes_per_pixel_numerator();
301            pixels.saturating_mul(numerator).div_ceil(2)
302        })
303    }
304
305    fn as_any(&self) -> &dyn Any {
306        self
307    }
308
309    fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
310        self
311    }
312}
313
314#[cfg(all(target_os = "macos", feature = "hwdecode"))]
315impl HardwareFrameLease for alpha2_ffmpeg_bridge::VideoToolboxFrameLease {
316    fn retained_bytes(&self) -> u64 {
317        self.info().map_or(0, |info| {
318            let pixels = u64::try_from(info.width)
319                .unwrap_or(0)
320                .saturating_mul(u64::try_from(info.height).unwrap_or(0));
321            // An unrecognized layout is charged as 8-bit 4:2:0; the frame is
322            // rejected before import anyway.
323            let numerator = surface_plane_layout(info.software_format)
324                .unwrap_or(NativePlaneLayout::GpuNv12)
325                .bytes_per_pixel_numerator();
326            pixels.saturating_mul(numerator).div_ceil(2)
327        })
328    }
329
330    fn as_any(&self) -> &dyn Any {
331        self
332    }
333
334    fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
335        self
336    }
337}
338
339#[cfg(all(target_os = "windows", feature = "hwdecode"))]
340impl HardwareFrameLease for alpha2_ffmpeg_bridge::D3D12FrameLease {
341    fn retained_bytes(&self) -> u64 {
342        self.info().map_or(0, |info| {
343            let pixels = u64::try_from(info.width)
344                .unwrap_or(0)
345                .saturating_mul(u64::try_from(info.height).unwrap_or(0));
346            // An unrecognized layout is charged as 8-bit 4:2:0; the frame is
347            // rejected before import anyway.
348            let numerator = surface_plane_layout(info.software_format)
349                .unwrap_or(NativePlaneLayout::GpuNv12)
350                .bytes_per_pixel_numerator();
351            pixels.saturating_mul(numerator).div_ceil(2)
352        })
353    }
354
355    fn as_any(&self) -> &dyn Any {
356        self
357    }
358
359    fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
360        self
361    }
362}
363
364/// One decoded export frame with either owned CPU pixels or an opaque surface.
365#[derive(Debug)]
366pub enum NativeVideoFrame {
367    /// Software-decoded frame.
368    Cpu(DecodedVideoFrame),
369    /// Hardware-decoded frame whose platform details remain behind its lease.
370    Hardware {
371        /// Presentation and cache identity.
372        metadata: NativeVideoFrameMetadata,
373        /// Ref-counted decoder-surface ownership.
374        surface: Arc<dyn HardwareFrameLease>,
375    },
376}
377
378impl NativeVideoFrame {
379    /// Presentation timestamp.
380    #[must_use]
381    pub fn pts(&self) -> MediaTime {
382        match self {
383            Self::Cpu(frame) => frame.pts,
384            Self::Hardware { metadata, .. } => metadata.pts,
385        }
386    }
387
388    /// Nominal frame duration when known.
389    #[must_use]
390    pub fn duration(&self) -> Option<MediaTime> {
391        match self {
392            Self::Cpu(frame) => frame.duration,
393            Self::Hardware { metadata, .. } => metadata.duration,
394        }
395    }
396
397    /// Returns metadata without exposing the backing representation.
398    #[must_use]
399    pub fn metadata(&self) -> NativeVideoFrameMetadata {
400        match self {
401            Self::Cpu(frame) => metadata_from_cpu(frame),
402            Self::Hardware { metadata, .. } => metadata.clone(),
403        }
404    }
405
406    /// Whether this frame is backed by a decoder surface rather than CPU pixels.
407    #[must_use]
408    pub const fn is_hardware(&self) -> bool {
409        matches!(self, Self::Hardware { .. })
410    }
411
412    /// Returns the software frame when this is the CPU variant.
413    #[must_use]
414    pub fn as_cpu(&self) -> Option<&DecodedVideoFrame> {
415        match self {
416            Self::Cpu(frame) => Some(frame),
417            Self::Hardware { .. } => None,
418        }
419    }
420
421    /// A CPU copy of this frame: itself, or the decoder surface downloaded through `FFmpeg`.
422    ///
423    /// The fallback for a surface the renderer could not import. Timing comes from this frame's
424    /// metadata; pixels go through the same conversion as software frames.
425    ///
426    /// # Errors
427    /// Returns a native decode error when the surface cannot be downloaded or converted.
428    pub fn to_cpu(&self) -> Result<DecodedVideoFrame, DecodeError> {
429        let (metadata, surface) = match self {
430            Self::Cpu(frame) => return Ok(frame.clone()),
431            Self::Hardware { metadata, surface } => (metadata, surface),
432        };
433        let mut software = download_surface(surface.as_ref())?;
434        // In tick units so the timestamp cannot overflow; the metadata replaces it below.
435        software.set_pts(metadata.pts.ticks());
436        let mut scaler = crate::convert::FrameScaler::default();
437        // The surface's own siting replaces the conversion's below.
438        let mut frame = crate::convert::convert_video_frame(
439            &software,
440            rsmpeg::ffi::AV_CODEC_ID_NONE,
441            crate::convert::tick_base(),
442            metadata.color.unwrap_or_default(),
443            &mut scaler,
444        )?;
445        frame.pts = metadata.pts;
446        frame.duration = metadata.duration;
447        frame.orientation = metadata.orientation;
448        frame.sample_aspect_ratio = metadata.sample_aspect_ratio;
449        frame.chroma_location = metadata.chroma_location;
450        // The conversion keeps the given color unless it repacked RGB under the identity matrix; an
451        // untagged surface stays untagged.
452        if metadata.color.is_none() {
453            frame.color = None;
454        }
455        Ok(frame)
456    }
457
458    /// Approximate retained bytes for separate CPU and surface budgets.
459    #[must_use]
460    pub fn retained_bytes(&self) -> u64 {
461        match self {
462            Self::Cpu(frame) => frame.planes.iter().fold(0_u64, |total, plane| {
463                total.saturating_add(u64::try_from(plane.bytes.len()).unwrap_or(u64::MAX))
464            }),
465            Self::Hardware { surface, .. } => surface.retained_bytes(),
466        }
467    }
468}
469
470/// Downloads a decoder surface of whichever platform lease this build knows.
471#[cfg_attr(
472    not(all(
473        any(target_os = "linux", target_os = "macos", target_os = "windows"),
474        feature = "hwdecode"
475    )),
476    allow(clippy::unnecessary_wraps)
477)]
478fn download_surface(
479    surface: &dyn HardwareFrameLease,
480) -> Result<alpha2_ffmpeg_bridge::DecodedFrame, DecodeError> {
481    let any = surface.as_any();
482    let downloaded: Option<
483        Result<alpha2_ffmpeg_bridge::DecodedFrame, alpha2_ffmpeg_bridge::BridgeError>,
484    > = None;
485    #[cfg(all(target_os = "linux", feature = "hwdecode"))]
486    let downloaded = downloaded.or_else(|| {
487        any.downcast_ref::<alpha2_ffmpeg_bridge::VulkanFrameLease>()
488            .map(alpha2_ffmpeg_bridge::VulkanFrameLease::download)
489    });
490    #[cfg(all(target_os = "macos", feature = "hwdecode"))]
491    let downloaded = downloaded.or_else(|| {
492        any.downcast_ref::<alpha2_ffmpeg_bridge::VideoToolboxFrameLease>()
493            .map(alpha2_ffmpeg_bridge::VideoToolboxFrameLease::download)
494    });
495    #[cfg(all(target_os = "windows", feature = "hwdecode"))]
496    let downloaded = downloaded.or_else(|| {
497        any.downcast_ref::<alpha2_ffmpeg_bridge::D3D12FrameLease>()
498            .map(alpha2_ffmpeg_bridge::D3D12FrameLease::download)
499    });
500    let _ = any;
501    downloaded
502        .ok_or_else(|| {
503            DecodeError::Unsupported("this hardware surface cannot be downloaded".into())
504        })?
505        .map_err(|error| DecodeError::Adapter(error.to_string()))
506}
507
508/// Export decoder producing [`NativeVideoFrame`]s from one `FFmpeg` session.
509///
510/// Software and hardware sessions share demux, seek and timing ([`NativeDecoder`]); the backend
511/// only changes where pixels live.
512pub struct NativeExportDecoder {
513    backend: ExportDecoderBackend,
514    hardware_frames: u64,
515    /// Why the hardware path gave up, once it has.
516    hardware_failure: Option<HardwareDecodeFallback>,
517}
518
519enum ExportDecoderBackend {
520    Software(NativeDecoder),
521    #[cfg(all(target_os = "linux", feature = "hwdecode"))]
522    Vulkan {
523        decoder: NativeDecoder,
524        generation: u64,
525    },
526    #[cfg(all(target_os = "macos", feature = "hwdecode"))]
527    VideoToolbox {
528        decoder: NativeDecoder,
529        generation: u64,
530        device_identity: u64,
531    },
532    #[cfg(all(target_os = "windows", feature = "hwdecode"))]
533    D3D12 {
534        decoder: NativeDecoder,
535        generation: u64,
536        device_identity: u64,
537    },
538}
539
540impl NativeExportDecoder {
541    /// Takes the decode-stage spans accumulated since the last call. Hardware sessions report no
542    /// conversion time; their cost is in `receive_frame`.
543    pub fn take_stage_timings(&mut self) -> DecodeStageTimings {
544        match &mut self.backend {
545            ExportDecoderBackend::Software(decoder) => decoder.take_stage_timings(),
546            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
547            ExportDecoderBackend::Vulkan { decoder, .. } => decoder.take_stage_timings(),
548            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
549            ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.take_stage_timings(),
550            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
551            ExportDecoderBackend::D3D12 { decoder, .. } => decoder.take_stage_timings(),
552        }
553    }
554
555    /// Whether this session currently produces device-resident frames.
556    #[must_use]
557    pub const fn is_hardware(&self) -> bool {
558        match &self.backend {
559            ExportDecoderBackend::Software(_) => false,
560            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
561            ExportDecoderBackend::Vulkan { .. } => true,
562            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
563            ExportDecoderBackend::VideoToolbox { .. } => true,
564            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
565            ExportDecoderBackend::D3D12 { .. } => true,
566        }
567    }
568
569    /// Opens the selected video stream using the software implementation.
570    ///
571    /// # Errors
572    /// Returns a native decode error if the input or selected stream cannot be opened.
573    pub fn open(
574        source: impl Into<alpha2_host_core::remote::SourceLocation>,
575    ) -> Result<Self, DecodeError> {
576        NativeDecoder::open(source).map(|decoder| Self {
577            backend: ExportDecoderBackend::Software(decoder),
578            hardware_frames: 0,
579            hardware_failure: None,
580        })
581    }
582
583    /// Opens with an explicit codec worker allocation.
584    ///
585    /// # Errors
586    /// Returns a native decode error for invalid worker counts or stream setup failures.
587    pub fn open_with_threads(
588        source: impl Into<alpha2_host_core::remote::SourceLocation>,
589        threads: i64,
590    ) -> Result<Self, DecodeError> {
591        NativeDecoder::open_with_threads(source, threads).map(|decoder| Self {
592            backend: ExportDecoderBackend::Software(decoder),
593            hardware_frames: 0,
594            hardware_failure: None,
595        })
596    }
597
598    /// Opens a Vulkan hardware decoder on the renderer's logical device.
599    ///
600    /// # Errors
601    /// Returns a native decode error if the stream lacks a compatible Vulkan configuration or the
602    /// decoder cannot use the shared device.
603    #[cfg(all(target_os = "linux", feature = "hwdecode"))]
604    pub fn open_vulkan(
605        source: impl Into<alpha2_host_core::remote::SourceLocation>,
606        threads: i64,
607        context: &SharedVulkanContext,
608        generation: u64,
609    ) -> Result<Self, HardwareOpenError> {
610        let spec = HardwareDecoderSpec {
611            device_type: ffi::AV_HWDEVICE_TYPE_VULKAN,
612            pixel_format: ffi::AV_PIX_FMT_VULKAN,
613            backend: "Vulkan",
614            require_device_context: true,
615            ten_bit: context.supports_ten_bit(),
616            keeps_leading_crop: true,
617            // The device has decode extensions only for these codecs; `FFmpeg` would open a session
618            // for any other and fail on its first packet.
619            hardware_codecs: Some(context.decode_codecs()),
620            get_format: alpha2_ffmpeg_bridge::vulkan_get_format_callback(),
621        };
622        NativeDecoder::open_hardware(source, threads, context.ffmpeg_device(), &spec).map(
623            |decoder| Self {
624                backend: ExportDecoderBackend::Vulkan {
625                    decoder,
626                    generation,
627                },
628                hardware_frames: 0,
629                hardware_failure: None,
630            },
631        )
632    }
633
634    /// Opens a `VideoToolbox` hardware decoder producing `CoreVideo` surfaces.
635    ///
636    /// # Errors
637    /// Returns a native decode error if the stream cannot negotiate `AV_PIX_FMT_VIDEOTOOLBOX` or
638    /// create a hardware session.
639    #[cfg(all(target_os = "macos", feature = "hwdecode"))]
640    pub fn open_videotoolbox(
641        source: impl Into<alpha2_host_core::remote::SourceLocation>,
642        threads: i64,
643        context: &SharedMetalContext,
644        generation: u64,
645    ) -> Result<Self, HardwareOpenError> {
646        // `VideoToolbox` creates its own session rather than adopting the renderer's device; Metal
647        // interop happens at import.
648        alpha2_ffmpeg_bridge::check_hardware_interop()
649            .map_err(crate::convert::adapter_error)
650            .map_err(|error| {
651                HardwareOpenError::new(HardwareDecodeFallback::DecoderOpenFailed, error)
652            })?;
653        let mark = alpha2_ffmpeg_bridge::log_mark();
654        let device = rsmpeg::avutil::AVHWDeviceContext::create(
655            ffi::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
656            None,
657            None,
658            0,
659        )
660        .map_err(crate::convert::adapter_error)
661        .map_err(|error| {
662            HardwareOpenError::new(HardwareDecodeFallback::DecoderOpenFailed, error)
663        })?;
664        let spec = HardwareDecoderSpec {
665            device_type: ffi::AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
666            pixel_format: ffi::AV_PIX_FMT_VIDEOTOOLBOX,
667            backend: "VideoToolbox",
668            require_device_context: false,
669            ten_bit: context.supports_ten_bit(),
670            keeps_leading_crop: false,
671            hardware_codecs: Some(context.decode_codecs()),
672            get_format: alpha2_ffmpeg_bridge::videotoolbox_get_format_callback(),
673        };
674        NativeDecoder::open_hardware(source, threads, device, &spec)
675            .map(|decoder| Self {
676                backend: ExportDecoderBackend::VideoToolbox {
677                    decoder,
678                    generation,
679                    device_identity: context.identity().device,
680                },
681                hardware_frames: 0,
682                hardware_failure: None,
683            })
684            .map_err(|mut error| {
685                error.source = with_videotoolbox_log(error.source, mark);
686                error
687            })
688    }
689
690    /// Opens a D3D12VA hardware decoder on the renderer's D3D12 device.
691    ///
692    /// # Errors
693    /// Returns a native decode error if the stream lacks a compatible D3D12VA configuration or the
694    /// shared device cannot create a decode session.
695    #[cfg(all(target_os = "windows", feature = "hwdecode"))]
696    pub fn open_d3d12(
697        source: impl Into<alpha2_host_core::remote::SourceLocation>,
698        threads: i64,
699        context: &SharedD3D12Context,
700        generation: u64,
701    ) -> Result<Self, HardwareOpenError> {
702        let spec = HardwareDecoderSpec {
703            device_type: ffi::AV_HWDEVICE_TYPE_D3D12VA,
704            pixel_format: ffi::AV_PIX_FMT_D3D12,
705            backend: "D3D12VA",
706            require_device_context: true,
707            ten_bit: context.supports_ten_bit(),
708            keeps_leading_crop: true,
709            hardware_codecs: None,
710            get_format: alpha2_ffmpeg_bridge::d3d12_get_format_callback(),
711        };
712        NativeDecoder::open_hardware(source, threads, context.ffmpeg_device(), &spec).map(
713            |decoder| Self {
714                backend: ExportDecoderBackend::D3D12 {
715                    decoder,
716                    generation,
717                    device_identity: context.identity().device,
718                },
719                hardware_frames: 0,
720                hardware_failure: None,
721            },
722        )
723    }
724
725    /// Stream descriptions from the common decode session.
726    #[must_use]
727    pub fn streams(&self) -> &[StreamInfo] {
728        match &self.backend {
729            ExportDecoderBackend::Software(decoder) => decoder.streams(),
730            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
731            ExportDecoderBackend::Vulkan { decoder, .. } => decoder.streams(),
732            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
733            ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.streams(),
734            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
735            ExportDecoderBackend::D3D12 { decoder, .. } => decoder.streams(),
736        }
737    }
738
739    /// What the decoder leaves out ([`crate::NativeDecoder::dropped_layer`]); hardware sessions
740    /// never open for alpha streams, so they drop nothing.
741    #[must_use]
742    pub fn dropped_layer(&self) -> Option<&crate::DroppedLayer> {
743        match &self.backend {
744            ExportDecoderBackend::Software(decoder) => decoder.dropped_layer(),
745            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
746            ExportDecoderBackend::Vulkan { .. } => None,
747            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
748            ExportDecoderBackend::VideoToolbox { .. } => None,
749            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
750            ExportDecoderBackend::D3D12 { .. } => None,
751        }
752    }
753
754    /// Effective end of the selected video source.
755    #[must_use]
756    pub fn video_duration(&self) -> Option<MediaTime> {
757        match &self.backend {
758            ExportDecoderBackend::Software(decoder) => decoder.video_duration(),
759            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
760            ExportDecoderBackend::Vulkan { decoder, .. } => decoder.video_duration(),
761            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
762            ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.video_duration(),
763            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
764            ExportDecoderBackend::D3D12 { decoder, .. } => decoder.video_duration(),
765        }
766    }
767
768    /// Resets codec and demux state.
769    ///
770    /// # Errors
771    /// Returns a native decode error if the codec state cannot be reset.
772    pub fn flush(&mut self) -> Result<(), DecodeError> {
773        match &mut self.backend {
774            ExportDecoderBackend::Software(decoder) => decoder.flush(),
775            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
776            ExportDecoderBackend::Vulkan { decoder, .. } => decoder.flush(),
777            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
778            ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder.flush(),
779            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
780            ExportDecoderBackend::D3D12 { decoder, .. } => decoder.flush(),
781        }
782    }
783
784    /// Seeks and returns the selected native frame.
785    ///
786    /// # Errors
787    /// Returns a native decode error for cancellation, seek, decode, or timestamp failures.
788    pub fn seek_video(
789        &mut self,
790        request: DecodeRequest,
791        cancel: &CancelToken,
792    ) -> Result<NativeVideoFrame, DecodeError> {
793        let result = self.seek_video_on_backend(request, cancel);
794        self.observe(result, |_| true)
795    }
796
797    /// Decodes the next native frame, or `None` at end of stream.
798    ///
799    /// # Errors
800    /// Returns a native decode error for cancellation or codec failures.
801    pub fn decode_video_next(
802        &mut self,
803        cancel: &CancelToken,
804    ) -> Result<Option<NativeVideoFrame>, DecodeError> {
805        let result = self.decode_video_next_on_backend(cancel);
806        self.observe(result, Option::is_some)
807    }
808
809    /// When the frame [`Self::decode_video_next`] returns next is presented, or `None` at the end.
810    ///
811    /// The frame is decoded now and kept, so a caller can find the frame shown at a time
812    /// without consuming the next one.
813    ///
814    /// # Errors
815    /// Returns a native decode error for cancellation or codec failures.
816    pub fn peek_video_pts(
817        &mut self,
818        cancel: &CancelToken,
819    ) -> Result<Option<MediaTime>, DecodeError> {
820        let result = self.native_decoder().peek_raw_pts(cancel);
821        self.observe(result, |_| false)
822    }
823
824    /// Configures corruption handling on the selected native backend.
825    pub fn set_decode_policy(&mut self, policy: crate::DecodePolicy) {
826        self.native_decoder().set_decode_policy(policy);
827    }
828
829    /// Sets the project's declared color for this source ([`NativeDecoder::declare_color`]).
830    ///
831    /// # Errors
832    /// Returns [`HardwareDecodeFallback::UnsupportedColor`] for HDR on a hardware
833    /// session, which presents SDR only.
834    pub fn with_declared_color(
835        mut self,
836        color: Option<ColorMetadata>,
837    ) -> Result<Self, HardwareOpenError> {
838        if self.is_hardware() && color.is_some_and(ColorMetadata::is_hdr) {
839            return Err(HardwareOpenError::new(
840                HardwareDecodeFallback::UnsupportedColor,
841                DecodeError::Unsupported("hardware export currently supports SDR only".into()),
842            ));
843        }
844        self.native_decoder().declare_color(color);
845        Ok(self)
846    }
847
848    /// Reports damage before any recovery or terminal error.
849    pub fn set_decode_reporter(
850        &mut self,
851        reporter: impl Fn(crate::DecodeDiagnostic) + Send + Sync + 'static,
852    ) {
853        self.native_decoder().set_decode_reporter(reporter);
854    }
855
856    /// Cumulative corruption diagnostics for this session.
857    pub fn decode_diagnostics(&mut self) -> &crate::DecodeDiagnostics {
858        self.native_decoder().decode_diagnostics()
859    }
860
861    /// The latest timestamp a frame may carry and still be shown at `time`
862    /// ([`NativeDecoder::presentation_deadline`]).
863    #[must_use]
864    pub fn presentation_deadline(&self, time: MediaTime) -> MediaTime {
865        match &self.backend {
866            ExportDecoderBackend::Software(decoder) => decoder,
867            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
868            ExportDecoderBackend::Vulkan { decoder, .. } => decoder,
869            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
870            ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder,
871            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
872            ExportDecoderBackend::D3D12 { decoder, .. } => decoder,
873        }
874        .presentation_deadline(time)
875    }
876
877    fn native_decoder(&mut self) -> &mut NativeDecoder {
878        match &mut self.backend {
879            ExportDecoderBackend::Software(decoder) => decoder,
880            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
881            ExportDecoderBackend::Vulkan { decoder, .. } => decoder,
882            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
883            ExportDecoderBackend::VideoToolbox { decoder, .. } => decoder,
884            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
885            ExportDecoderBackend::D3D12 { decoder, .. } => decoder,
886        }
887    }
888
889    /// Why this session's hardware path gave up, once a call returned [`DecodeError::Unsupported`].
890    #[must_use]
891    pub const fn hardware_failure(&self) -> Option<HardwareDecodeFallback> {
892        self.hardware_failure
893    }
894
895    /// Classifies a hardware session's failures so a caller can fall back.
896    ///
897    /// `FFmpeg` initializes a hardware decoder lazily in `get_format`, so an unsupported profile or
898    /// codec (VP9 without VP9 decode, 10-bit H.264 on NVDEC) fails on the first packet with a
899    /// generic error. Before the first frame such an error becomes [`DecodeError::Unsupported`]
900    /// with [`HardwareDecodeFallback::DecoderOpenFailed`]; afterwards it stays a real failure.
901    fn observe<T>(
902        &mut self,
903        result: Result<T, DecodeError>,
904        produced: impl Fn(&T) -> bool,
905    ) -> Result<T, DecodeError> {
906        if !self.is_hardware() {
907            return result;
908        }
909        match result {
910            Ok(value) => {
911                if produced(&value) {
912                    self.hardware_frames = self.hardware_frames.saturating_add(1);
913                }
914                Ok(value)
915            }
916            Err(DecodeError::Adapter(message)) if self.hardware_frames == 0 => {
917                self.hardware_failure = Some(HardwareDecodeFallback::DecoderOpenFailed);
918                Err(DecodeError::Unsupported(format!(
919                    "the hardware decoder failed before its first frame: {message}"
920                )))
921            }
922            Err(DecodeError::Unsupported(message)) => {
923                self.hardware_failure
924                    .get_or_insert(HardwareDecodeFallback::UnsupportedSurfaceFormat);
925                Err(DecodeError::Unsupported(message))
926            }
927            Err(error) => Err(error),
928        }
929    }
930
931    fn seek_video_on_backend(
932        &mut self,
933        request: DecodeRequest,
934        cancel: &CancelToken,
935    ) -> Result<NativeVideoFrame, DecodeError> {
936        match &mut self.backend {
937            ExportDecoderBackend::Software(decoder) => match decoder.seek(request, cancel)?.event {
938                DecodeEvent::Video(frame) => Ok(NativeVideoFrame::Cpu(frame)),
939                _ => Err(DecodeError::Adapter(
940                    "video decoder returned a non-video event".into(),
941                )),
942            },
943            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
944            ExportDecoderBackend::Vulkan {
945                decoder,
946                generation,
947            } => {
948                let frame = decoder.seek_raw(request.time, cancel)?;
949                hardware_frame(decoder, frame.into_frame(), *generation)
950            }
951            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
952            ExportDecoderBackend::VideoToolbox {
953                decoder,
954                generation,
955                device_identity,
956            } => {
957                let mark = alpha2_ffmpeg_bridge::log_mark();
958                let frame = decoder
959                    .seek_raw(request.time, cancel)
960                    .map_err(|error| with_videotoolbox_log(error, mark))?;
961                videotoolbox_frame(decoder, frame.into_frame(), *generation, *device_identity)
962            }
963            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
964            ExportDecoderBackend::D3D12 {
965                decoder,
966                generation,
967                device_identity,
968            } => {
969                let frame = decoder.seek_raw(request.time, cancel)?;
970                d3d12_frame(
971                    decoder,
972                    frame.into_frame(),
973                    *generation,
974                    *device_identity,
975                    &mut self.hardware_failure,
976                )
977            }
978        }
979    }
980
981    fn decode_video_next_on_backend(
982        &mut self,
983        cancel: &CancelToken,
984    ) -> Result<Option<NativeVideoFrame>, DecodeError> {
985        match &mut self.backend {
986            ExportDecoderBackend::Software(decoder) => match decoder.decode_next(cancel)? {
987                DecodeEvent::Video(frame) => Ok(Some(NativeVideoFrame::Cpu(frame))),
988                DecodeEvent::EndOfStream => Ok(None),
989                _ => Err(DecodeError::Adapter(
990                    "video decoder returned a non-video event".into(),
991                )),
992            },
993            #[cfg(all(target_os = "linux", feature = "hwdecode"))]
994            ExportDecoderBackend::Vulkan {
995                decoder,
996                generation,
997            } => decoder
998                .decode_raw_next(cancel)?
999                .map(|frame| hardware_frame(decoder, frame.into_frame(), *generation))
1000                .transpose(),
1001            #[cfg(all(target_os = "macos", feature = "hwdecode"))]
1002            ExportDecoderBackend::VideoToolbox {
1003                decoder,
1004                generation,
1005                device_identity,
1006            } => {
1007                let mark = alpha2_ffmpeg_bridge::log_mark();
1008                decoder
1009                    .decode_raw_next(cancel)
1010                    .map_err(|error| with_videotoolbox_log(error, mark))?
1011                    .map(|frame| {
1012                        videotoolbox_frame(
1013                            decoder,
1014                            frame.into_frame(),
1015                            *generation,
1016                            *device_identity,
1017                        )
1018                    })
1019                    .transpose()
1020            }
1021            #[cfg(all(target_os = "windows", feature = "hwdecode"))]
1022            ExportDecoderBackend::D3D12 {
1023                decoder,
1024                generation,
1025                device_identity,
1026            } => decoder
1027                .decode_raw_next(cancel)?
1028                .map(|frame| {
1029                    d3d12_frame(
1030                        decoder,
1031                        frame.into_frame(),
1032                        *generation,
1033                        *device_identity,
1034                        &mut self.hardware_failure,
1035                    )
1036                })
1037                .transpose(),
1038        }
1039    }
1040}
1041
1042/// A decoded D3D12VA frame as a [`NativeVideoFrame`]. A picture reaching past its surface
1043/// ([`visible_rect_within_surface`]) is refused with [`HardwareDecodeFallback::UnsupportedCrop`] so
1044/// the source continues in software.
1045#[cfg(all(target_os = "windows", feature = "hwdecode"))]
1046fn d3d12_frame(
1047    decoder: &NativeDecoder,
1048    frame: AVFrame,
1049    generation: u64,
1050    device_identity: u64,
1051    failure: &mut Option<HardwareDecodeFallback>,
1052) -> Result<NativeVideoFrame, DecodeError> {
1053    let info = alpha2_ffmpeg_bridge::d3d12_frame_info(&frame)
1054        .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1055    let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1056        DecodeError::Unsupported(format!(
1057            "D3D12VA output {} is not an importable 4:2:0 surface",
1058            info.software_format
1059        ))
1060    })?;
1061    let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
1062    let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
1063    let crop = [
1064        frame.crop_left,
1065        frame.crop_top,
1066        frame.crop_right,
1067        frame.crop_bottom,
1068    ];
1069    let Some(visible_rect) =
1070        visible_rect_within_surface(width, height, crop, info.surface_width, info.surface_height)
1071    else {
1072        *failure = Some(HardwareDecodeFallback::UnsupportedCrop);
1073        return Err(DecodeError::Unsupported(format!(
1074            "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",
1075            frame.crop_left, frame.crop_top, info.surface_width, info.surface_height
1076        )));
1077    };
1078    let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1079        frame.pts
1080    } else {
1081        frame.best_effort_timestamp
1082    };
1083    let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1084    let metadata = NativeVideoFrameMetadata {
1085        pts,
1086        dts: None,
1087        duration: timestamp(frame.duration, decoder.time_base),
1088        visible_rect,
1089        orientation: decoder.orientation,
1090        sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1091        color: decoder.picture_color(&frame),
1092        chroma_location: decoder.picture_chroma_location(&frame),
1093        bit_depth: plane_layout.bit_depth(),
1094        plane_layout,
1095        device_identity,
1096        decoder_generation: generation,
1097        picture_identity: info.resource
1098            ^ info.fence_value
1099            ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1100    };
1101    Ok(NativeVideoFrame::Hardware {
1102        metadata,
1103        surface: Arc::new(alpha2_ffmpeg_bridge::D3D12FrameLease::new(frame)),
1104    })
1105}
1106
1107/// The log classes of a `VideoToolbox` decode: the codec context (where the hwaccel logs
1108/// `OSStatus`) and the hardware device and frames contexts.
1109#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1110const VIDEOTOOLBOX_DECODE_LOG_CLASSES: &[&str] = &[
1111    "h264",
1112    "hevc",
1113    "vp9",
1114    "av1",
1115    "AVHWDeviceContext",
1116    "AVHWFramesContext",
1117];
1118
1119/// `error` with the `VideoToolbox` lines logged since `mark` appended, so the session's `OSStatus`
1120/// reaches the typed error. Errors without a message are returned unchanged.
1121#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1122fn with_videotoolbox_log(error: DecodeError, mark: alpha2_ffmpeg_bridge::LogMark) -> DecodeError {
1123    let detail = alpha2_ffmpeg_bridge::log_detail(&alpha2_ffmpeg_bridge::log_since(
1124        mark,
1125        VIDEOTOOLBOX_DECODE_LOG_CLASSES,
1126    ));
1127    if detail.is_empty() {
1128        return error;
1129    }
1130    match error {
1131        DecodeError::Adapter(message) => DecodeError::Adapter(format!("{message}{detail}")),
1132        DecodeError::Unsupported(message) => DecodeError::Unsupported(format!("{message}{detail}")),
1133        DecodeError::Gpu { fault, message } => DecodeError::Gpu {
1134            fault,
1135            message: format!("{message}{detail}"),
1136        },
1137        other => other,
1138    }
1139}
1140
1141#[cfg(all(target_os = "macos", feature = "hwdecode"))]
1142fn videotoolbox_frame(
1143    decoder: &NativeDecoder,
1144    frame: AVFrame,
1145    generation: u64,
1146    device_identity: u64,
1147) -> Result<NativeVideoFrame, DecodeError> {
1148    let info = alpha2_ffmpeg_bridge::videotoolbox_frame_info(&frame)
1149        .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1150    let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1151        DecodeError::Unsupported(format!(
1152            "VideoToolbox output {} is not an importable 4:2:0 surface",
1153            info.software_format
1154        ))
1155    })?;
1156    let width = u32::try_from(info.width).map_err(|_| DecodeError::OutOfRange)?;
1157    let height = u32::try_from(info.height).map_err(|_| DecodeError::OutOfRange)?;
1158    let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1159        frame.pts
1160    } else {
1161        frame.best_effort_timestamp
1162    };
1163    let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1164    let metadata = NativeVideoFrameMetadata {
1165        pts,
1166        dts: None,
1167        duration: timestamp(frame.duration, decoder.time_base),
1168        visible_rect: Rect {
1169            x: u32::try_from(frame.crop_left).unwrap_or(0),
1170            y: u32::try_from(frame.crop_top).unwrap_or(0),
1171            width: width.saturating_sub(
1172                u32::try_from(frame.crop_left.saturating_add(frame.crop_right)).unwrap_or(0),
1173            ),
1174            height: height.saturating_sub(
1175                u32::try_from(frame.crop_top.saturating_add(frame.crop_bottom)).unwrap_or(0),
1176            ),
1177        },
1178        orientation: decoder.orientation,
1179        sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1180        color: decoder.picture_color(&frame),
1181        chroma_location: decoder.picture_chroma_location(&frame),
1182        bit_depth: plane_layout.bit_depth(),
1183        plane_layout,
1184        device_identity,
1185        decoder_generation: generation,
1186        picture_identity: info.pixel_buffer ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1187    };
1188    Ok(NativeVideoFrame::Hardware {
1189        metadata,
1190        surface: Arc::new(alpha2_ffmpeg_bridge::VideoToolboxFrameLease::new(frame)),
1191    })
1192}
1193
1194#[cfg(all(target_os = "linux", feature = "hwdecode"))]
1195fn hardware_frame(
1196    decoder: &NativeDecoder,
1197    frame: AVFrame,
1198    generation: u64,
1199) -> Result<NativeVideoFrame, DecodeError> {
1200    let info = alpha2_ffmpeg_bridge::vulkan_frame_info(&frame)
1201        .map_err(|error| DecodeError::Adapter(error.to_string()))?;
1202    let plane_layout = surface_plane_layout(info.software_format).ok_or_else(|| {
1203        DecodeError::Unsupported(format!(
1204            "Vulkan output {} is not an importable 4:2:0 surface",
1205            info.software_format
1206        ))
1207    })?;
1208    // For hardware formats `av_frame_apply_cropping` only subtracts right and bottom crop; the
1209    // surface keeps the padded extent, so the visible rectangle sits inside it.
1210    let width = u32::try_from(frame.width).map_err(|_| DecodeError::OutOfRange)?;
1211    let height = u32::try_from(frame.height).map_err(|_| DecodeError::OutOfRange)?;
1212    let coded_width = u32::try_from(info.coded_width).map_err(|_| DecodeError::OutOfRange)?;
1213    let coded_height = u32::try_from(info.coded_height).map_err(|_| DecodeError::OutOfRange)?;
1214    if coded_width < width || coded_height < height {
1215        return Err(DecodeError::Adapter(
1216            "Vulkan frame is larger than its allocated surface".into(),
1217        ));
1218    }
1219    let raw_pts = if frame.best_effort_timestamp == ffi::AV_NOPTS_VALUE {
1220        frame.pts
1221    } else {
1222        frame.best_effort_timestamp
1223    };
1224    let pts = timestamp(raw_pts, decoder.time_base).ok_or(DecodeError::OutOfRange)?;
1225    let metadata = NativeVideoFrameMetadata {
1226        pts,
1227        dts: None,
1228        duration: timestamp(frame.duration, decoder.time_base),
1229        visible_rect: Rect {
1230            x: u32::try_from(frame.crop_left).unwrap_or(0),
1231            y: u32::try_from(frame.crop_top).unwrap_or(0),
1232            width: width.saturating_sub(
1233                u32::try_from(frame.crop_left.saturating_add(frame.crop_right)).unwrap_or(0),
1234            ),
1235            height: height.saturating_sub(
1236                u32::try_from(frame.crop_top.saturating_add(frame.crop_bottom)).unwrap_or(0),
1237            ),
1238        },
1239        orientation: decoder.orientation,
1240        sample_aspect_ratio: decoder.picture_sample_aspect_ratio(&frame),
1241        color: decoder.picture_color(&frame),
1242        chroma_location: decoder.picture_chroma_location(&frame),
1243        bit_depth: plane_layout.bit_depth(),
1244        plane_layout,
1245        device_identity: info.device,
1246        decoder_generation: generation,
1247        picture_identity: info.images[0] ^ u64::from_ne_bytes(pts.ticks().to_ne_bytes()),
1248    };
1249    Ok(NativeVideoFrame::Hardware {
1250        metadata,
1251        surface: Arc::new(alpha2_ffmpeg_bridge::VulkanFrameLease::new(frame)),
1252    })
1253}
1254
1255fn metadata_from_cpu(frame: &DecodedVideoFrame) -> NativeVideoFrameMetadata {
1256    let plane_layout = match frame.pixel_format {
1257        PixelFormat::Yuv(format) => NativePlaneLayout::CpuYuv(format),
1258        PixelFormat::LinearRgbaF16 => NativePlaneLayout::CpuLinearRgbaF16,
1259        _ => NativePlaneLayout::CpuRgba8,
1260    };
1261    NativeVideoFrameMetadata {
1262        pts: frame.pts,
1263        dts: frame.dts,
1264        duration: frame.duration,
1265        visible_rect: frame.visible_rect,
1266        orientation: frame.orientation,
1267        sample_aspect_ratio: frame.sample_aspect_ratio,
1268        color: frame.color,
1269        chroma_location: frame.chroma_location,
1270        bit_depth: plane_layout.bit_depth(),
1271        plane_layout,
1272        device_identity: 0,
1273        decoder_generation: 0,
1274        picture_identity: u64::from_ne_bytes(frame.pts.ticks().to_ne_bytes()),
1275    }
1276}