Skip to main content

alpha2_ffmpeg_bridge/
lib.rs

1//! The `FFmpeg` calls rsmpeg's safe surface lacks, for the native binding: frame and packet
2//! copies, codec and side-data helpers, container I/O and hardware-frame shims.
3
4use std::{error::Error, ffi::CStr, fmt, ptr, slice};
5
6#[cfg(all(target_os = "linux", feature = "hwdevice"))]
7use std::ffi::CString;
8
9#[cfg(all(
10    any(target_os = "linux", target_os = "macos", target_os = "windows"),
11    feature = "hwdevice"
12))]
13use std::sync::Mutex;
14#[cfg(all(target_os = "linux", feature = "hwdevice"))]
15use std::sync::MutexGuard;
16
17pub use alpha2_media::GpuFault;
18use rsmpeg::{
19    avcodec::{AVCodecContext, AVCodecParameters},
20    avutil::AVFrame,
21    error::RsmpegError,
22    ffi,
23    swscale::SwsContext,
24};
25
26#[cfg(all(any(target_os = "linux", target_os = "windows"), feature = "hwdevice"))]
27use rsmpeg::avutil::AVHWDeviceContext;
28
29mod container;
30mod log;
31
32pub use container::{
33    CreateOutputError, CustomInput, DemuxInput, InputLocation, InputReader, OpenInputError,
34    OutputFile, PathError, file_url, open_input,
35};
36pub use log::{LogLine, LogMark, install_log_capture, log_detail, log_mark, log_since};
37
38/// The C shims' ABI, generated from `include/` by the build script.
39#[allow(
40    dead_code,
41    non_camel_case_types,
42    unreachable_pub,
43    clippy::all,
44    clippy::pedantic,
45    clippy::undocumented_unsafe_blocks
46)]
47mod interop {
48    include!(concat!(env!("OUT_DIR"), "/interop.rs"));
49}
50
51// Pins the layouts of the D3D12 and VideoToolbox interop structs so a header edit fails on every
52// target, not only where those shims compile.
53const _: () = {
54    use interop::{Alpha2D3D12FrameInfo as D3D12, Alpha2VideoToolboxFrameInfo as VideoToolbox};
55    use std::mem::{align_of, offset_of, size_of};
56    assert!(size_of::<D3D12>() == 64 && align_of::<D3D12>() == 8);
57    assert!(offset_of!(D3D12, resource) == 0);
58    assert!(offset_of!(D3D12, fence) == 8);
59    assert!(offset_of!(D3D12, fence_value) == 16);
60    assert!(offset_of!(D3D12, device) == 24);
61    assert!(offset_of!(D3D12, dxgi_format) == 32);
62    assert!(offset_of!(D3D12, width) == 36);
63    assert!(offset_of!(D3D12, height) == 40);
64    assert!(offset_of!(D3D12, hardware_format) == 44);
65    assert!(offset_of!(D3D12, software_format) == 48);
66    assert!(offset_of!(D3D12, surface_width) == 52);
67    assert!(offset_of!(D3D12, surface_height) == 56);
68    assert!(size_of::<VideoToolbox>() == 24 && align_of::<VideoToolbox>() == 8);
69    assert!(offset_of!(VideoToolbox, pixel_buffer) == 0);
70    assert!(offset_of!(VideoToolbox, width) == 8);
71    assert!(offset_of!(VideoToolbox, height) == 12);
72    assert!(offset_of!(VideoToolbox, hardware_format) == 16);
73    assert!(offset_of!(VideoToolbox, software_format) == 20);
74};
75
76/// Copies a hardware frame into a software frame in its `sw_format`, keeping timestamps, crop and
77/// color properties. Used for surfaces the renderer could not import.
78#[cfg(all(
79    any(target_os = "linux", target_os = "macos", target_os = "windows"),
80    feature = "hwdevice"
81))]
82// A frames context's buffer data is the `AVHWFramesContext` FFmpeg allocated, aligned for it.
83#[allow(clippy::cast_ptr_alignment)]
84fn download_hardware_frame(frame: &AVFrame) -> Result<AVFrame, BridgeError> {
85    if frame.hw_frames_ctx.is_null() {
86        return Err(BridgeError::InvalidInput(
87            "hardware frame has no frames context",
88        ));
89    }
90    // SAFETY: a non-null `hw_frames_ctx` is a reference the frame holds to its live
91    // `AVHWFramesContext`; only its size is read.
92    let written = unsafe {
93        let frames = (*frame.hw_frames_ctx).data.cast::<ffi::AVHWFramesContext>();
94        ((*frames).width, (*frames).height)
95    };
96    let mut software = AVFrame::new();
97    software
98        .hwframe_transfer_data(frame)
99        .map_err(BridgeError::Ffmpeg)?;
100    // The copy's row padding is not zeroed and some transfers write only the frames context's
101    // width, but `DecodedFrame::yuv_planes` shares whole rows.
102    zero_row_padding(&mut software, written.0, written.1)?;
103    // SAFETY: both frames are live; `av_frame_copy_props` only reads `frame` and writes metadata
104    // into `software`.
105    let copied = unsafe { ffi::av_frame_copy_props(software.as_mut_ptr(), frame.as_ptr()) };
106    if copied < 0 {
107        return Err(BridgeError::FfmpegCode(copied));
108    }
109    Ok(software)
110}
111
112/// Zeroes each row of the first `height` rows past `width` pixels, up to the linesize.
113///
114/// `frame` must be the only owner of its buffers.
115///
116/// # Errors
117/// Returns an error for a format without a descriptor, a negative size, or rows outside the
118/// frame's buffers.
119#[cfg_attr(not(feature = "hwdevice"), allow(dead_code))]
120fn zero_row_padding(frame: &mut AVFrame, width: i32, height: i32) -> Result<(), BridgeError> {
121    let format = frame.format;
122    // SAFETY: av_pix_fmt_desc_get only reads the static descriptor table; null for unknown formats.
123    let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
124        .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
125    if width < 0 || height < 0 {
126        return Err(BridgeError::InvalidInput("negative frame size"));
127    }
128    // SAFETY: as above.
129    let planes = unsafe { ffi::av_pix_fmt_count_planes(format) };
130    for plane in 0..usize::try_from(planes).unwrap_or(0).min(4) {
131        let plane_index = i32::try_from(plane).unwrap_or(0);
132        // SAFETY: av_image_get_linesize only reads the descriptor table.
133        let written = unsafe { ffi::av_image_get_linesize(format, width, plane_index) };
134        let (Ok(written), Ok(stride)) = (
135            usize::try_from(written),
136            usize::try_from(frame.linesize[plane]),
137        ) else {
138            continue;
139        };
140        let data = frame.data[plane];
141        if data.is_null() || stride <= written {
142            continue;
143        }
144        let shift = if plane == 1 || plane == 2 {
145            descriptor.log2_chroma_h
146        } else {
147            0
148        };
149        let rows = usize::try_from(-((-height) >> shift)).unwrap_or(0);
150        let start = data as usize;
151        let end = stride
152            .checked_mul(rows)
153            .and_then(|len| start.checked_add(len))
154            .ok_or(BridgeError::InvalidInput("frame plane size overflow"))?;
155        let inside = frame.buf.iter().any(|buffer| {
156            // SAFETY: a non-null `AVFrame::buf` entry is a live `AVBufferRef` the frame holds.
157            unsafe { buffer.as_ref() }.is_some_and(|buffer| {
158                let buffer_start = buffer.data as usize;
159                buffer_start <= start && buffer_start.saturating_add(buffer.size) >= end
160            })
161        });
162        if !inside {
163            return Err(BridgeError::InvalidInput(
164                "frame plane lies outside its buffers",
165            ));
166        }
167        for row in 0..rows {
168            // SAFETY: the check above puts every row inside a frame buffer the caller solely owns.
169            unsafe { ptr::write_bytes(data.add(row * stride + written), 0, stride - written) };
170        }
171    }
172    Ok(())
173}
174
175#[cfg(all(target_os = "windows", feature = "hwdevice"))]
176use interop::Alpha2D3D12FrameInfo as D3D12FrameDescriptor;
177
178#[cfg(all(target_os = "windows", feature = "hwdevice"))]
179unsafe extern "C" {
180    fn alpha2_d3d12_device_init(
181        context: *mut ffi::AVHWDeviceContext,
182        device: *mut std::ffi::c_void,
183    ) -> i32;
184    fn alpha2_d3d12_get_format(
185        context: *mut ffi::AVCodecContext,
186        formats: *const ffi::AVPixelFormat,
187    ) -> ffi::AVPixelFormat;
188    fn alpha2_d3d12_frame_info(
189        frame: *const ffi::AVFrame,
190        output: *mut D3D12FrameDescriptor,
191    ) -> i32;
192    fn alpha2_d3d12_frame_set_fence_value(frame: *mut ffi::AVFrame, value: u64) -> i32;
193    fn alpha2_d3d12_frame_fence_value(frame: *const ffi::AVFrame, output: *mut u64) -> i32;
194    fn alpha2_d3d12_frames_configure(
195        frames: *mut ffi::AVBufferRef,
196        dxgi_format: u32,
197        resource_flags: u32,
198    ) -> i32;
199}
200
201/// `DXGI_FORMAT_NV12`, the D3D12VA encoder-input texture format.
202#[cfg(all(target_os = "windows", feature = "hwdevice"))]
203pub const DXGI_FORMAT_NV12: u32 = 103;
204
205/// Sets a D3D12VA frames context's `dxgi_format` and `resource_flags`, with one texture per frame.
206///
207/// Encoder input needs one texture per frame because each frame has its own fence and a copy
208/// addresses its planes as subresources 0 and 1. Call between `av_hwframe_ctx_alloc` and
209/// `av_hwframe_ctx_init`.
210///
211/// # Errors
212/// Returns an error when the context is not a D3D12VA one.
213#[cfg(all(target_os = "windows", feature = "hwdevice"))]
214pub fn d3d12_frames_configure(
215    frames: &mut rsmpeg::avutil::AVHWFramesContext,
216    dxgi_format: u32,
217    resource_flags: u32,
218) -> Result<(), BridgeError> {
219    // SAFETY: `frames` is live; the shim checks the device type before writing D3D12VA fields.
220    let status =
221        unsafe { alpha2_d3d12_frames_configure(frames.as_mut_ptr(), dxgi_format, resource_flags) };
222    if status < 0 {
223        return Err(BridgeError::FfmpegCode(status));
224    }
225    Ok(())
226}
227
228/// D3D12 resource and decode fence retained by one hardware frame.
229///
230/// Defined on every target so a change to the shim's record fails to compile everywhere.
231#[derive(Clone, Copy, Debug, Eq, PartialEq)]
232pub struct D3D12FrameInfo {
233    /// Borrowed `ID3D12Resource` pointer.
234    pub resource: u64,
235    /// Borrowed decode `ID3D12Fence` pointer.
236    pub fence: u64,
237    /// Fence value signaled after decode completes.
238    pub fence_value: u64,
239    /// `ID3D12Device` identity that allocated the resource.
240    pub device: u64,
241    /// Native `DXGI_FORMAT` value.
242    pub dxgi_format: u32,
243    /// Width with the right crop applied but not the left.
244    pub width: i32,
245    /// Height with the bottom crop applied but not the top.
246    pub height: i32,
247    /// Software pixel format represented by the hardware frame.
248    pub software_format: i32,
249    /// Width of the texture the frame was decoded into.
250    pub surface_width: u32,
251    /// Height of the texture the frame was decoded into.
252    pub surface_height: u32,
253}
254
255impl D3D12FrameInfo {
256    #[cfg_attr(
257        not(all(target_os = "windows", feature = "hwdevice")),
258        allow(dead_code)
259    )]
260    const fn from_descriptor(descriptor: &interop::Alpha2D3D12FrameInfo) -> Self {
261        Self {
262            resource: descriptor.resource,
263            fence: descriptor.fence,
264            fence_value: descriptor.fence_value,
265            device: descriptor.device,
266            dxgi_format: descriptor.dxgi_format,
267            width: descriptor.width,
268            height: descriptor.height,
269            software_format: descriptor.software_format,
270            surface_width: descriptor.surface_width,
271            surface_height: descriptor.surface_height,
272        }
273    }
274}
275
276/// Ref-counted ownership of one opaque D3D12 `AVFrame`.
277#[cfg(all(target_os = "windows", feature = "hwdevice"))]
278pub struct D3D12FrameLease {
279    frame: Mutex<AVFrame>,
280}
281
282#[cfg(all(target_os = "windows", feature = "hwdevice"))]
283impl fmt::Debug for D3D12FrameLease {
284    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
285        formatter
286            .debug_struct("D3D12FrameLease")
287            .finish_non_exhaustive()
288    }
289}
290
291#[cfg(all(target_os = "windows", feature = "hwdevice"))]
292impl D3D12FrameLease {
293    /// Takes ownership of one decoded `AV_PIX_FMT_D3D12` frame.
294    #[must_use]
295    pub fn new(frame: AVFrame) -> Self {
296        Self {
297            frame: Mutex::new(frame),
298        }
299    }
300
301    /// Copies this frame's pixels to the CPU. Row padding is zeroed, so the planes can be shared.
302    ///
303    /// # Errors
304    /// Returns [`BridgeError`] when `FFmpeg` cannot transfer the frame.
305    pub fn download(&self) -> Result<DecodedFrame, BridgeError> {
306        let frame = self
307            .frame
308            .lock()
309            .unwrap_or_else(std::sync::PoisonError::into_inner);
310        download_hardware_frame(&frame).map(|frame| DecodedFrame {
311            frame,
312            written: true,
313        })
314    }
315
316    /// Returns the retained frame's resource and synchronization descriptor.
317    ///
318    /// # Errors
319    /// Returns an error when this is not a valid D3D12 hardware frame.
320    pub fn info(&self) -> Result<D3D12FrameInfo, BridgeError> {
321        let frame = self
322            .frame
323            .lock()
324            .unwrap_or_else(std::sync::PoisonError::into_inner);
325        d3d12_frame_info(&frame)
326    }
327}
328
329/// Initializes an `FFmpeg` D3D12VA device context over the renderer's device.
330///
331/// # Safety
332/// `device` must be the address of a live `ID3D12Device`. The context takes its own COM reference.
333///
334/// # Errors
335/// Returns an error if the pointer is null or `FFmpeg` rejects the device.
336#[cfg(all(target_os = "windows", feature = "hwdevice"))]
337#[allow(clippy::cast_ptr_alignment)]
338pub unsafe fn create_d3d12_device_context(device: u64) -> Result<AVHWDeviceContext, BridgeError> {
339    let device = usize::try_from(device)
340        .map_err(|_| BridgeError::InvalidInput("invalid D3D12 device pointer"))?
341        as *mut std::ffi::c_void;
342    if device.is_null() {
343        return Err(BridgeError::InvalidInput("D3D12 device is null"));
344    }
345    let mut context = alloc_hwdevice(ffi::AV_HWDEVICE_TYPE_D3D12VA, "D3D12")?;
346    let device_context = context.data.cast::<ffi::AVHWDeviceContext>();
347    // SAFETY: the allocated context is writable, the caller guarantees `device` is a live
348    // `ID3D12Device`, and the shim takes its own COM reference.
349    let result = unsafe { alpha2_d3d12_device_init(device_context, device) };
350    if result < 0 {
351        return Err(BridgeError::FfmpegCode(result));
352    }
353    context.init().map_err(BridgeError::Ffmpeg)?;
354    Ok(context)
355}
356
357/// Returns the pixel-format selector used by D3D12VA decoders.
358#[cfg(all(target_os = "windows", feature = "hwdevice"))]
359#[must_use]
360pub fn d3d12_get_format_callback()
361-> unsafe extern "C" fn(*mut ffi::AVCodecContext, *const ffi::AVPixelFormat) -> ffi::AVPixelFormat {
362    alpha2_d3d12_get_format
363}
364
365/// Reads one retained D3D12 frame descriptor.
366///
367/// # Errors
368/// Returns an error if the frame is not a valid D3D12VA frame.
369#[cfg(all(target_os = "windows", feature = "hwdevice"))]
370pub fn d3d12_frame_info(frame: &AVFrame) -> Result<D3D12FrameInfo, BridgeError> {
371    let mut descriptor = D3D12FrameDescriptor::default();
372    // SAFETY: the frame remains live for the duration of the descriptor copy.
373    let result = unsafe { alpha2_d3d12_frame_info(frame.as_ptr(), &raw mut descriptor) };
374    if result != 0 {
375        return Err(BridgeError::FfmpegCode(result));
376    }
377    Ok(D3D12FrameInfo::from_descriptor(&descriptor))
378}
379
380/// The fence value `FFmpeg` waits for before next using the frame (`sync_ctx.fence_value`).
381///
382/// # Errors
383/// Returns an error if the frame is not a valid D3D12VA frame.
384#[cfg(all(target_os = "windows", feature = "hwdevice"))]
385pub fn d3d12_frame_fence_value(frame: &AVFrame) -> Result<u64, BridgeError> {
386    let mut value = 0;
387    // SAFETY: the frame is live for the call and the output is a writable local.
388    let result = unsafe { alpha2_d3d12_frame_fence_value(frame.as_ptr(), &raw mut value) };
389    if result != 0 {
390        return Err(BridgeError::FfmpegCode(result));
391    }
392    Ok(value)
393}
394
395/// One encoder-pool D3D12VA frame held open for a native GPU write.
396///
397/// The encoder waits on the frame's fence for `sync_ctx.fence_value` before reading it, so after a
398/// fenced copy is submitted, [`Self::commit`] records the value it signals. A guard dropped without
399/// a commit leaves the frame unchanged.
400#[cfg(all(target_os = "windows", feature = "hwdevice"))]
401pub struct D3D12EncodeFrameAccess<'a> {
402    frame: &'a mut AVFrame,
403    info: D3D12FrameInfo,
404}
405
406#[cfg(all(target_os = "windows", feature = "hwdevice"))]
407impl fmt::Debug for D3D12EncodeFrameAccess<'_> {
408    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
409        formatter
410            .debug_struct("D3D12EncodeFrameAccess")
411            .field("info", &self.info)
412            .finish_non_exhaustive()
413    }
414}
415
416#[cfg(all(target_os = "windows", feature = "hwdevice"))]
417impl<'a> D3D12EncodeFrameAccess<'a> {
418    /// Opens one handoff on an encoder-pool frame.
419    ///
420    /// # Errors
421    /// Returns an error when the frame is not a usable D3D12VA frame.
422    pub fn begin(frame: &'a mut AVFrame) -> Result<Self, BridgeError> {
423        let info = d3d12_frame_info(frame)?;
424        Ok(Self { frame, info })
425    }
426
427    /// The frame's texture, fence and fence value as `begin` read them.
428    #[must_use]
429    pub const fn info(&self) -> &D3D12FrameInfo {
430        &self.info
431    }
432
433    /// Retains the frame's buffers and hardware pool beyond this access guard.
434    ///
435    /// # Errors
436    /// Returns an allocation error if `FFmpeg` cannot create the reference.
437    pub fn retain_frame(&self) -> Result<AVFrame, BridgeError> {
438        // SAFETY: the frame is live; av_frame_clone makes an independent AVFrame with buffer refs.
439        let raw = unsafe { ffi::av_frame_clone(self.frame.as_ptr()) };
440        let raw = std::ptr::NonNull::new(raw)
441            .ok_or(BridgeError::InvalidInput("cannot retain encode frame"))?;
442        // SAFETY: the newly allocated frame is uniquely owned by this value.
443        Ok(unsafe { AVFrame::from_raw(raw) })
444    }
445
446    /// Records the fence value a submitted write into the frame signals.
447    ///
448    /// # Errors
449    /// Returns an error if the frame is not a valid D3D12VA frame (`begin` already checked).
450    pub fn commit(&mut self, fence_value: u64) -> Result<(), BridgeError> {
451        // SAFETY: the guard borrows the frame exclusively; the shim checks its type before writing.
452        let result =
453            unsafe { alpha2_d3d12_frame_set_fence_value(self.frame.as_mut_ptr(), fence_value) };
454        if result != 0 {
455            return Err(BridgeError::FfmpegCode(result));
456        }
457        self.info.fence_value = fence_value;
458        Ok(())
459    }
460}
461
462#[cfg(all(any(target_os = "linux", target_os = "macos"), feature = "hwdevice"))]
463use interop::Alpha2VideoToolboxFrameInfo as VideoToolboxFrameDescriptor;
464
465// The VideoToolbox shim reads only FFmpeg structures, so Linux builds and tests it too.
466#[cfg(all(any(target_os = "linux", target_os = "macos"), feature = "hwdevice"))]
467#[cfg_attr(target_os = "linux", allow(dead_code))]
468unsafe extern "C" {
469    fn alpha2_videotoolbox_get_format(
470        context: *mut ffi::AVCodecContext,
471        formats: *const ffi::AVPixelFormat,
472    ) -> ffi::AVPixelFormat;
473    fn alpha2_videotoolbox_frame_info(
474        frame: *const ffi::AVFrame,
475        output: *mut VideoToolboxFrameDescriptor,
476    ) -> i32;
477}
478
479/// `CoreVideo` pixel-buffer identity retained by one `VideoToolbox` frame.
480///
481/// Defined on every target, like [`D3D12FrameInfo`].
482#[derive(Clone, Copy, Debug, Eq, PartialEq)]
483pub struct VideoToolboxFrameInfo {
484    /// Borrowed `CVPixelBufferRef`, valid while the frame lease is retained.
485    pub pixel_buffer: u64,
486    /// Coded width reported by `FFmpeg`.
487    pub width: i32,
488    /// Coded height reported by `FFmpeg`.
489    pub height: i32,
490    /// Sample layout the frames context allocated, such as NV12 or P010.
491    pub software_format: i32,
492}
493
494impl VideoToolboxFrameInfo {
495    #[cfg_attr(
496        not(all(any(target_os = "linux", target_os = "macos"), feature = "hwdevice")),
497        allow(dead_code)
498    )]
499    const fn from_descriptor(descriptor: &interop::Alpha2VideoToolboxFrameInfo) -> Self {
500        Self {
501            pixel_buffer: descriptor.pixel_buffer,
502            width: descriptor.width,
503            height: descriptor.height,
504            software_format: descriptor.software_format,
505        }
506    }
507}
508
509/// Reads a `VideoToolbox` frame's descriptor, refusing other frames.
510#[cfg(all(any(target_os = "linux", target_os = "macos"), feature = "hwdevice"))]
511#[cfg_attr(target_os = "linux", allow(dead_code))]
512fn read_videotoolbox_frame_info(frame: &AVFrame) -> Result<VideoToolboxFrameInfo, BridgeError> {
513    let mut descriptor = VideoToolboxFrameDescriptor::default();
514    // SAFETY: `frame` is live for the copy; the shim checks each pointer before reading through it.
515    let result = unsafe { alpha2_videotoolbox_frame_info(frame.as_ptr(), &raw mut descriptor) };
516    if result != 0 {
517        return Err(BridgeError::InvalidInput(
518            "frame is not a VideoToolbox frame with a pixel buffer",
519        ));
520    }
521    Ok(VideoToolboxFrameInfo::from_descriptor(&descriptor))
522}
523
524/// Ref-counted ownership of one opaque `VideoToolbox` `AVFrame`.
525#[cfg(all(target_os = "macos", feature = "hwdevice"))]
526pub struct VideoToolboxFrameLease {
527    frame: Mutex<AVFrame>,
528}
529
530#[cfg(all(target_os = "macos", feature = "hwdevice"))]
531impl fmt::Debug for VideoToolboxFrameLease {
532    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
533        formatter
534            .debug_struct("VideoToolboxFrameLease")
535            .finish_non_exhaustive()
536    }
537}
538
539#[cfg(all(target_os = "macos", feature = "hwdevice"))]
540impl VideoToolboxFrameLease {
541    /// Takes ownership of one decoded `AV_PIX_FMT_VIDEOTOOLBOX` frame.
542    #[must_use]
543    pub fn new(frame: AVFrame) -> Self {
544        Self {
545            frame: Mutex::new(frame),
546        }
547    }
548
549    /// Copies this frame's pixels to the CPU. Row padding is zeroed, so the planes can be shared.
550    ///
551    /// # Errors
552    /// Returns [`BridgeError`] when `FFmpeg` cannot transfer the frame.
553    pub fn download(&self) -> Result<DecodedFrame, BridgeError> {
554        let frame = self
555            .frame
556            .lock()
557            .unwrap_or_else(std::sync::PoisonError::into_inner);
558        download_hardware_frame(&frame).map(|frame| DecodedFrame {
559            frame,
560            written: true,
561        })
562    }
563
564    /// Returns the retained frame's `CoreVideo` surface identity.
565    ///
566    /// # Errors
567    /// Returns an error when the frame is not a `VideoToolbox` hardware frame.
568    pub fn info(&self) -> Result<VideoToolboxFrameInfo, BridgeError> {
569        let frame = self
570            .frame
571            .lock()
572            .unwrap_or_else(std::sync::PoisonError::into_inner);
573        read_videotoolbox_frame_info(&frame)
574    }
575}
576
577/// Returns the pixel-format selector used by `VideoToolbox` decoders.
578#[cfg(all(target_os = "macos", feature = "hwdevice"))]
579#[must_use]
580pub fn videotoolbox_get_format_callback()
581-> unsafe extern "C" fn(*mut ffi::AVCodecContext, *const ffi::AVPixelFormat) -> ffi::AVPixelFormat {
582    alpha2_videotoolbox_get_format
583}
584
585/// Reads the `CoreVideo` surface identity without taking ownership of the frame.
586///
587/// # Errors
588/// Returns an error when the frame is not a `VideoToolbox` hardware frame.
589#[cfg(all(target_os = "macos", feature = "hwdevice"))]
590pub fn videotoolbox_frame_info(frame: &AVFrame) -> Result<VideoToolboxFrameInfo, BridgeError> {
591    read_videotoolbox_frame_info(frame)
592}
593
594/// Maximum number of Vulkan images described by an `FFmpeg` hardware frame.
595#[cfg(all(target_os = "linux", feature = "hwdevice"))]
596pub const MAX_VULKAN_PLANES: usize = interop::ALPHA2_MAX_VULKAN_PLANES as usize;
597
598/// Raw shared-device description used to initialize `FFmpeg`'s Vulkan context.
599#[cfg(all(target_os = "linux", feature = "hwdevice"))]
600#[derive(Clone, Debug)]
601pub struct VulkanDeviceInfo {
602    /// Raw `VkInstance`.
603    pub instance: u64,
604    /// Raw `VkPhysicalDevice`.
605    pub physical_device: u64,
606    /// Raw `VkDevice`.
607    pub device: u64,
608    /// Queue family used by wgpu and native barriers.
609    pub graphics_queue_family: u32,
610    /// Enabled graphics queues in that family.
611    pub graphics_queue_count: u32,
612    /// Dedicated video decode queue family.
613    pub decode_queue_family: u32,
614    /// Enabled decode queues in that family.
615    pub decode_queue_count: u32,
616    /// Vulkan video codec-operation flags.
617    pub decode_video_caps: u32,
618    /// Dedicated video encode queue family. Ignored when the count is zero.
619    pub encode_queue_family: u32,
620    /// Enabled encode queues in that family, or zero when this device has none.
621    pub encode_queue_count: u32,
622    /// Vulkan video encode codec-operation flags.
623    pub encode_video_caps: u32,
624    /// Enabled core feature bits required by `FFmpeg`'s context contract.
625    pub core_features: [u32; 4],
626    /// Whether `timelineSemaphore` is enabled on the device; the context is refused without it.
627    pub timeline_semaphore: u32,
628    /// Whether `synchronization2` is enabled on the device.
629    pub synchronization2: u32,
630    /// Whether `samplerYcbcrConversion` is enabled on the device.
631    pub sampler_ycbcr_conversion: u32,
632    /// Whether `videoMaintenance1` is enabled on the device.
633    pub video_maintenance1: u32,
634    /// Whether `videoDecodeVP9` (`VK_KHR_video_decode_vp9`) is enabled on the device.
635    pub video_decode_vp9: u32,
636    /// Enabled instance extension names.
637    pub instance_extensions: Vec<String>,
638    /// Enabled device extension names.
639    pub device_extensions: Vec<String>,
640}
641
642#[cfg(all(target_os = "linux", feature = "hwdevice"))]
643use interop::Alpha2VulkanDeviceInfo as VulkanDeviceDescriptor;
644
645/// Serializes one shared Vulkan queue family across `FFmpeg` and the renderer.
646///
647/// Takes the same recursive lock `FFmpeg` takes around its submissions. Only contexts made by
648/// [`create_vulkan_device_context`] have it.
649#[cfg(all(target_os = "linux", feature = "hwdevice"))]
650pub struct VulkanQueueLock {
651    device: AVHWDeviceContext,
652    queue_family: u32,
653}
654
655// SAFETY: after construction the context is only read to pass its pointer to the shim's lock and
656// unlock, which synchronize on their own mutex. The single owner drops the reference once.
657#[cfg(all(target_os = "linux", feature = "hwdevice"))]
658unsafe impl Sync for VulkanQueueLock {}
659
660#[cfg(all(target_os = "linux", feature = "hwdevice"))]
661impl fmt::Debug for VulkanQueueLock {
662    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
663        formatter
664            .debug_struct("VulkanQueueLock")
665            .field("queue_family", &self.queue_family)
666            .finish_non_exhaustive()
667    }
668}
669
670#[cfg(all(target_os = "linux", feature = "hwdevice"))]
671impl VulkanQueueLock {
672    /// Locks submissions to `queue_family` on `device`.
673    ///
674    /// # Errors
675    /// Returns an input error unless `device` came from [`create_vulkan_device_context`] and has a
676    /// lock for `queue_family`.
677    #[allow(clippy::cast_ptr_alignment)]
678    pub fn new(device: AVHWDeviceContext, queue_family: u32) -> Result<Self, BridgeError> {
679        // SAFETY: `device` keeps the context live; the shim reads only its type, free callback and
680        // its own state.
681        let lockable = unsafe {
682            alpha2_vulkan_queue_lockable(
683                device.data.cast::<ffi::AVHWDeviceContext>().cast_const(),
684                queue_family,
685            )
686        };
687        if lockable == 0 {
688            return Err(BridgeError::InvalidInput(
689                "Vulkan queue lock needs a family of a device the bridge initialized",
690            ));
691        }
692        Ok(Self {
693            device,
694            queue_family,
695        })
696    }
697
698    /// Holds the queue lock until the guard drops; the guard stays on this thread.
699    #[must_use]
700    pub fn lock(&self) -> VulkanQueueGuard<'_> {
701        // SAFETY: the guard is neither Send nor Sync and releases this exactly once.
702        unsafe { self.raw_lock() };
703        VulkanQueueGuard {
704            lock: self,
705            _owning_thread: std::marker::PhantomData,
706        }
707    }
708
709    /// Acquires the queue lock without a guard, for adapters with their own lock/unlock protocol.
710    ///
711    /// # Safety
712    /// The calling thread must release it with exactly one [`Self::raw_unlock`], in reverse order
713    /// of its other holds on this lock.
714    #[allow(clippy::cast_ptr_alignment)]
715    pub unsafe fn raw_lock(&self) {
716        // SAFETY: `new` checked the shim set up this context with a lock for this family, and the
717        // retained context keeps it alive.
718        unsafe {
719            alpha2_vulkan_queue_lock(
720                self.device.data.cast::<ffi::AVHWDeviceContext>(),
721                self.queue_family,
722            );
723        }
724    }
725
726    /// Releases a hold taken by [`Self::raw_lock`].
727    ///
728    /// # Safety
729    /// The calling thread must hold the lock from an unreleased [`Self::raw_lock`], and this must
730    /// be its most recent hold. An unbalanced release lets two submissions reach the queue at once.
731    #[allow(clippy::cast_ptr_alignment)]
732    pub unsafe fn raw_unlock(&self) {
733        // SAFETY: the caller holds this lock on this thread, per the contract above.
734        unsafe {
735            alpha2_vulkan_queue_unlock(
736                self.device.data.cast::<ffi::AVHWDeviceContext>(),
737                self.queue_family,
738            );
739        }
740    }
741}
742
743/// One hold of a [`VulkanQueueLock`], released on drop on the thread that took it.
744#[cfg(all(target_os = "linux", feature = "hwdevice"))]
745#[derive(Debug)]
746pub struct VulkanQueueGuard<'a> {
747    lock: &'a VulkanQueueLock,
748    _owning_thread: std::marker::PhantomData<*const ()>,
749}
750
751#[cfg(all(target_os = "linux", feature = "hwdevice"))]
752impl Drop for VulkanQueueGuard<'_> {
753    fn drop(&mut self) {
754        // SAFETY: `lock` took this hold on this thread (the guard is not Send), and guards drop in
755        // reverse order of creation.
756        unsafe { self.lock.raw_unlock() };
757    }
758}
759
760#[cfg(all(target_os = "linux", feature = "hwdevice"))]
761unsafe extern "C" {
762    fn alpha2_vulkan_queue_lockable(
763        context: *const ffi::AVHWDeviceContext,
764        queue_family: u32,
765    ) -> i32;
766    fn alpha2_vulkan_queue_lock(context: *mut ffi::AVHWDeviceContext, queue_family: u32);
767    fn alpha2_vulkan_queue_unlock(context: *mut ffi::AVHWDeviceContext, queue_family: u32);
768    fn alpha2_vulkan_device_init(
769        context: *mut ffi::AVHWDeviceContext,
770        info: *const VulkanDeviceDescriptor,
771    ) -> i32;
772}
773
774/// Initializes an `FFmpeg` Vulkan device context over an application-owned device.
775///
776/// # Safety
777/// The handles in `info` must be live, belong together, have been created with the queues,
778/// features and extensions `info` names, and outlive the returned context.
779///
780/// # Errors
781/// Returns an input error for invalid extension names or an `FFmpeg` error when the context cannot
782/// be initialized.
783#[cfg(all(target_os = "linux", feature = "hwdevice"))]
784#[allow(clippy::cast_ptr_alignment)]
785pub unsafe fn create_vulkan_device_context(
786    info: &VulkanDeviceInfo,
787) -> Result<AVHWDeviceContext, BridgeError> {
788    let instance = info
789        .instance_extensions
790        .iter()
791        .map(|s| CString::new(s.as_str()))
792        .collect::<Result<Vec<_>, _>>()
793        .map_err(|_| BridgeError::InvalidInput("Vulkan extension contains NUL"))?;
794    let device = info
795        .device_extensions
796        .iter()
797        .map(|s| CString::new(s.as_str()))
798        .collect::<Result<Vec<_>, _>>()
799        .map_err(|_| BridgeError::InvalidInput("Vulkan extension contains NUL"))?;
800    let instance_ptrs = instance.iter().map(|s| s.as_ptr()).collect::<Vec<_>>();
801    let device_ptrs = device.iter().map(|s| s.as_ptr()).collect::<Vec<_>>();
802    let raw = VulkanDeviceDescriptor {
803        instance: info.instance,
804        physical_device: info.physical_device,
805        device: info.device,
806        graphics_queue_family: info.graphics_queue_family,
807        graphics_queue_count: info.graphics_queue_count,
808        decode_queue_family: info.decode_queue_family,
809        decode_queue_count: info.decode_queue_count,
810        decode_video_caps: info.decode_video_caps,
811        encode_queue_family: info.encode_queue_family,
812        encode_queue_count: info.encode_queue_count,
813        encode_video_caps: info.encode_video_caps,
814        shader_image_gather_extended: info.core_features[0],
815        fragment_stores_and_atomics: info.core_features[1],
816        shader_int64: info.core_features[2],
817        vertex_pipeline_stores_and_atomics: info.core_features[3],
818        timeline_semaphore: info.timeline_semaphore,
819        synchronization2: info.synchronization2,
820        sampler_ycbcr_conversion: info.sampler_ycbcr_conversion,
821        video_maintenance1: info.video_maintenance1,
822        video_decode_vp9: info.video_decode_vp9,
823        instance_extensions: instance_ptrs.as_ptr(),
824        instance_extension_count: u32::try_from(instance_ptrs.len())
825            .map_err(|_| BridgeError::InvalidInput("too many Vulkan extensions"))?,
826        device_extensions: device_ptrs.as_ptr(),
827        device_extension_count: u32::try_from(device_ptrs.len())
828            .map_err(|_| BridgeError::InvalidInput("too many Vulkan extensions"))?,
829    };
830    let mut context = alloc_hwdevice(ffi::AV_HWDEVICE_TYPE_VULKAN, "Vulkan")?;
831    let device_context = context.data.cast::<ffi::AVHWDeviceContext>();
832    // SAFETY: the context is freshly allocated and writable, the shim copies the extension names,
833    // and the caller guarantees the handles.
834    let result = unsafe { alpha2_vulkan_device_init(device_context, &raw const raw) };
835    if result < 0 {
836        return Err(BridgeError::FfmpegCode(result));
837    }
838    context.init().map_err(BridgeError::Ffmpeg)?;
839    Ok(context)
840}
841
842/// Opaque Vulkan handles and synchronization state for one `FFmpeg` hardware frame.
843///
844/// The caller must not destroy the handles and must retain the source `AVFrame` while using them.
845#[cfg(all(target_os = "linux", feature = "hwdevice"))]
846#[derive(Clone, Debug, Eq, PartialEq)]
847pub struct VulkanFrameInfo {
848    /// `FFmpeg` hardware pixel format.
849    pub hardware_format: i32,
850    /// Software layout represented by the hardware frames context.
851    pub software_format: i32,
852    /// Visible frame width.
853    pub width: i32,
854    /// Visible frame height.
855    pub height: i32,
856    /// Allocated image width, padded to whole macroblocks.
857    pub coded_width: i32,
858    /// Allocated image height, padded to whole macroblocks.
859    pub coded_height: i32,
860    /// Number of non-null Vulkan images.
861    pub plane_count: u32,
862    /// Whether `FFmpeg` allocated the image with sampled-image usage.
863    pub sampled: bool,
864    /// `VkInstance` identity.
865    pub instance: u64,
866    /// `VkPhysicalDevice` identity.
867    pub physical_device: u64,
868    /// `VkDevice` identity.
869    pub device: u64,
870    /// Per-plane `VkImage` identities.
871    pub images: [u64; MAX_VULKAN_PLANES],
872    /// Per-plane Vulkan formats.
873    pub formats: [u32; MAX_VULKAN_PLANES],
874    /// Current per-plane image layouts.
875    pub layouts: [u32; MAX_VULKAN_PLANES],
876    /// Current per-plane access masks.
877    pub access: [u32; MAX_VULKAN_PLANES],
878    /// Per-plane timeline semaphore identities.
879    pub semaphores: [u64; MAX_VULKAN_PLANES],
880    /// Values that an importing submission must wait for.
881    pub semaphore_values: [u64; MAX_VULKAN_PLANES],
882    /// Current image queue-family ownership.
883    pub queue_families: [u32; MAX_VULKAN_PLANES],
884}
885
886/// Vulkan image and synchronization state of one hardware frame, read under the frame lock.
887#[cfg(all(target_os = "linux", feature = "hwdevice"))]
888pub type VulkanFrameDescriptor = interop::Alpha2VulkanFrameInfo;
889
890/// Locked `FFmpeg` Vulkan surface state passed to the native GPU boundary.
891///
892/// Editing a record changes no frame by itself. The record a guard writes back is reachable only
893/// through the `unsafe` `access_mut`, since its values must describe work actually submitted.
894#[cfg(all(target_os = "linux", feature = "hwdevice"))]
895#[repr(transparent)]
896#[derive(Default)]
897pub struct VulkanFrameAccess(interop::Alpha2VulkanFrameAccess);
898
899#[cfg(all(target_os = "linux", feature = "hwdevice"))]
900impl VulkanFrameAccess {
901    /// The frame's images and their synchronization state.
902    #[must_use]
903    pub const fn frame(&self) -> &VulkanFrameDescriptor {
904        &self.0.frame
905    }
906
907    /// Mutable frame state; see [`VulkanFrameAccessGuard::access_mut`] for what it must hold.
908    pub const fn frame_mut(&mut self) -> &mut VulkanFrameDescriptor {
909        &mut self.0.frame
910    }
911
912    /// The frames context's `VkAllocationCallbacks`, or zero.
913    #[must_use]
914    pub const fn allocator(&self) -> u64 {
915        self.0.allocator
916    }
917
918    /// The queue family the frame's images are owned by.
919    #[must_use]
920    pub const fn queue_family(&self) -> u32 {
921        self.0.queue_family
922    }
923
924    /// Array layers of each image.
925    #[must_use]
926    pub const fn layer_count(&self) -> u32 {
927        self.0.layer_count
928    }
929}
930
931#[cfg(all(target_os = "linux", feature = "hwdevice"))]
932unsafe extern "C" {
933    fn alpha2_vulkan_get_format(
934        context: *mut ffi::AVCodecContext,
935        formats: *const ffi::AVPixelFormat,
936    ) -> ffi::AVPixelFormat;
937    fn alpha2_vulkan_frame_info(
938        frame: *const ffi::AVFrame,
939        output: *mut VulkanFrameDescriptor,
940    ) -> i32;
941    fn alpha2_vulkan_frames_add_usage(frames: *mut ffi::AVBufferRef, usage: u32) -> i32;
942    fn alpha2_vulkan_frames_usage(frames: *const ffi::AVBufferRef) -> u32;
943    fn alpha2_vulkan_frame_access_begin(
944        frame: *mut ffi::AVFrame,
945        output: *mut VulkanFrameAccess,
946    ) -> i32;
947    fn alpha2_vulkan_frame_access_end(
948        begun: *const interop::Alpha2VulkanFrameAccess,
949        updated: *const VulkanFrameAccess,
950    );
951}
952
953/// Why the Vulkan shim refused a frame (its own codes, not `FFmpeg`'s).
954#[cfg(all(target_os = "linux", feature = "hwdevice"))]
955const fn vulkan_frame_refusal(status: i32) -> BridgeError {
956    BridgeError::InvalidInput(match status {
957        -1 => "frame is not a Vulkan hardware frame",
958        -2 => "Vulkan frame has no hardware frames or device context",
959        -3 => "Vulkan frame has no images",
960        -4 => "Vulkan frames context has no frame or queue locks, or no layers",
961        -5 => "Vulkan device has no graphics or compute queue",
962        _ => "Vulkan frame could not be read",
963    })
964}
965
966/// Ref-counted ownership of an opaque `FFmpeg` Vulkan frame.
967#[cfg(all(target_os = "linux", feature = "hwdevice"))]
968pub struct VulkanFrameLease {
969    frame: Mutex<AVFrame>,
970}
971
972#[cfg(all(target_os = "linux", feature = "hwdevice"))]
973impl fmt::Debug for VulkanFrameLease {
974    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
975        formatter
976            .debug_struct("VulkanFrameLease")
977            .finish_non_exhaustive()
978    }
979}
980
981#[cfg(all(target_os = "linux", feature = "hwdevice"))]
982impl VulkanFrameLease {
983    /// Takes ownership of one decoded `AV_PIX_FMT_VULKAN` frame.
984    #[must_use]
985    pub fn new(frame: AVFrame) -> Self {
986        Self {
987            frame: Mutex::new(frame),
988        }
989    }
990
991    /// Copies this frame's pixels to the CPU. Row padding is zeroed, so the planes can be shared.
992    ///
993    /// # Errors
994    /// Returns [`BridgeError`] when `FFmpeg` cannot transfer the frame.
995    pub fn download(&self) -> Result<DecodedFrame, BridgeError> {
996        let frame = self
997            .frame
998            .lock()
999            .unwrap_or_else(std::sync::PoisonError::into_inner);
1000        download_hardware_frame(&frame).map(|frame| DecodedFrame {
1001            frame,
1002            written: true,
1003        })
1004    }
1005
1006    /// Returns a locked snapshot of the frame's native image state.
1007    ///
1008    /// # Errors
1009    /// Returns [`BridgeError`] when the frame or its hardware context is invalid.
1010    pub fn info(&self) -> Result<VulkanFrameInfo, BridgeError> {
1011        let frame = self
1012            .frame
1013            .lock()
1014            .unwrap_or_else(std::sync::PoisonError::into_inner);
1015        vulkan_frame_info(&frame)
1016    }
1017
1018    /// Locks the `FFmpeg` frame and queue for one native GPU handoff.
1019    ///
1020    /// # Errors
1021    /// Returns [`BridgeError`] if the frame has no usable sampled images or queue.
1022    pub fn lock_access(&self) -> Result<VulkanFrameAccessGuard<'_>, BridgeError> {
1023        let mut frame = self
1024            .frame
1025            .lock()
1026            .unwrap_or_else(std::sync::PoisonError::into_inner);
1027        let mut access = VulkanFrameAccess::default();
1028        // SAFETY: the mutex guard borrows the frame exclusively until the end call in Drop.
1029        let result =
1030            unsafe { alpha2_vulkan_frame_access_begin(frame.as_mut_ptr(), &raw mut access) };
1031        if result != 0 {
1032            return Err(vulkan_frame_refusal(result));
1033        }
1034        Ok(VulkanFrameAccessGuard {
1035            _frame: frame,
1036            begun: access.0,
1037            access,
1038            committed: false,
1039        })
1040    }
1041}
1042
1043/// Guard for one locked `FFmpeg` frame and queue handoff.
1044///
1045/// Safe code cannot change what is written back: an unsignaled timeline value hangs later users and
1046/// a wrong layout makes the contents undefined.
1047///
1048/// ```compile_fail,E0133
1049/// # fn forge(lease: &alpha2_ffmpeg_bridge::VulkanFrameLease) {
1050/// let mut guard = lease.lock_access().unwrap();
1051/// guard.access_mut().frame_mut().semaphore_values[0] += 1000;
1052/// guard.commit();
1053/// # }
1054/// ```
1055#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1056pub struct VulkanFrameAccessGuard<'a> {
1057    _frame: MutexGuard<'a, AVFrame>,
1058    // What `begin` locked, which the end call releases and checks the write-back against.
1059    begun: interop::Alpha2VulkanFrameAccess,
1060    access: VulkanFrameAccess,
1061    committed: bool,
1062}
1063
1064#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1065impl VulkanFrameAccessGuard<'_> {
1066    /// The frame's state while its `FFmpeg` locks are held.
1067    #[must_use]
1068    pub const fn access(&self) -> &VulkanFrameAccess {
1069        &self.access
1070    }
1071
1072    /// The record written back on [`Self::commit`]. Planes whose image or semaphore changed and
1073    /// timeline values below the frame's are ignored.
1074    ///
1075    /// # Safety
1076    /// On commit, each layout and access mask must be what the submitted work leaves the image in,
1077    /// and each timeline value one that work submitted before the guard drops signals.
1078    #[must_use]
1079    pub const unsafe fn access_mut(&mut self) -> &mut VulkanFrameAccess {
1080        &mut self.access
1081    }
1082
1083    /// Commits updated synchronization values when the guard is released.
1084    pub fn commit(&mut self) {
1085        self.committed = true;
1086    }
1087}
1088
1089#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1090impl Drop for VulkanFrameAccessGuard<'_> {
1091    fn drop(&mut self) {
1092        let updated = if self.committed {
1093            &raw const self.access
1094        } else {
1095            ptr::null()
1096        };
1097        // SAFETY: `begun` is this frame's begin record on this thread (the guard is not Send), and
1098        // this is the unique end call. `access_mut`'s caller vouched for `access`.
1099        unsafe { alpha2_vulkan_frame_access_end(&raw const self.begun, updated) };
1100    }
1101}
1102
1103/// One encoder-pool frame held open for a native GPU write.
1104///
1105/// Unlike a [`VulkanFrameLease`], an encoder-input frame has one owner, so it is borrowed directly.
1106/// The guard stays on the thread that began it, which holds the frame and queue mutexes.
1107#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1108pub struct VulkanEncodeFrameAccess<'a> {
1109    frame: &'a mut AVFrame,
1110    // What `begin` locked, which the end call releases and checks the write-back against.
1111    begun: interop::Alpha2VulkanFrameAccess,
1112    access: VulkanFrameAccess,
1113    committed: bool,
1114    _owning_thread: std::marker::PhantomData<*const ()>,
1115}
1116
1117#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1118impl<'a> VulkanEncodeFrameAccess<'a> {
1119    /// Retains the frame's buffers and hardware pool beyond this access guard.
1120    ///
1121    /// # Errors
1122    /// Returns an allocation error if `FFmpeg` cannot create the reference.
1123    pub fn retain_frame(&self) -> Result<AVFrame, BridgeError> {
1124        // SAFETY: the frame is live and locked; av_frame_clone makes an independent AVFrame.
1125        let raw = unsafe { ffi::av_frame_clone(self.frame.as_ptr()) };
1126        let raw = std::ptr::NonNull::new(raw)
1127            .ok_or(BridgeError::InvalidInput("cannot retain encode frame"))?;
1128        // SAFETY: the newly allocated frame is uniquely owned by this value.
1129        Ok(unsafe { AVFrame::from_raw(raw) })
1130    }
1131
1132    /// Opens one handoff on an encoder-pool frame.
1133    ///
1134    /// # Errors
1135    /// Returns an error when the frame is not a usable Vulkan frame.
1136    pub fn begin(frame: &'a mut AVFrame) -> Result<Self, BridgeError> {
1137        let mut access = VulkanFrameAccess::default();
1138        // SAFETY: `frame` is borrowed until the guard drops, and Drop is the unique end call.
1139        let result =
1140            unsafe { alpha2_vulkan_frame_access_begin(frame.as_mut_ptr(), &raw mut access) };
1141        if result != 0 {
1142            return Err(vulkan_frame_refusal(result));
1143        }
1144        Ok(Self {
1145            frame,
1146            begun: access.0,
1147            access,
1148            committed: false,
1149            _owning_thread: std::marker::PhantomData,
1150        })
1151    }
1152
1153    /// The frame's state while its `FFmpeg` locks are held.
1154    #[must_use]
1155    pub const fn access(&self) -> &VulkanFrameAccess {
1156        &self.access
1157    }
1158
1159    /// The record written back on [`Self::commit`], checked as in
1160    /// [`VulkanFrameAccessGuard::access_mut`].
1161    ///
1162    /// # Safety
1163    /// As for [`VulkanFrameAccessGuard::access_mut`].
1164    #[must_use]
1165    pub const unsafe fn access_mut(&mut self) -> &mut VulkanFrameAccess {
1166        &mut self.access
1167    }
1168
1169    /// Writes the updated layout and timeline values back when released.
1170    pub fn commit(&mut self) {
1171        self.committed = true;
1172    }
1173}
1174
1175#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1176impl Drop for VulkanEncodeFrameAccess<'_> {
1177    fn drop(&mut self) {
1178        let updated = if self.committed {
1179            &raw const self.access
1180        } else {
1181            ptr::null()
1182        };
1183        // SAFETY: `begun` is this frame's begin record on this thread (the guard is not Send), and
1184        // this is the unique end call. `access_mut`'s caller vouched for `access`.
1185        unsafe { alpha2_vulkan_frame_access_end(&raw const self.begun, updated) };
1186    }
1187}
1188
1189/// Returns the callback used by a Vulkan hardware decoder to select its opaque format.
1190#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1191#[must_use]
1192pub fn vulkan_get_format_callback()
1193-> unsafe extern "C" fn(*mut ffi::AVCodecContext, *const ffi::AVPixelFormat) -> ffi::AVPixelFormat {
1194    alpha2_vulkan_get_format
1195}
1196
1197/// Reads Vulkan image and synchronization metadata from an opaque hardware frame.
1198///
1199/// The shim takes the frame lock while copying layouts and semaphore values.
1200///
1201/// # Errors
1202/// Returns an error if the frame is not a valid Vulkan hardware frame.
1203#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1204pub fn vulkan_frame_info(frame: &AVFrame) -> Result<VulkanFrameInfo, BridgeError> {
1205    let mut raw = VulkanFrameDescriptor::default();
1206    // SAFETY: `frame` is live and `raw` is a writable result; the shim checks FFmpeg's pointers
1207    // before dereferencing them.
1208    let result = unsafe { alpha2_vulkan_frame_info(frame.as_ptr(), &raw mut raw) };
1209    if result != 0 {
1210        return Err(vulkan_frame_refusal(result));
1211    }
1212    Ok(VulkanFrameInfo {
1213        hardware_format: raw.hardware_format,
1214        software_format: raw.software_format,
1215        width: raw.width,
1216        height: raw.height,
1217        coded_width: raw.coded_width,
1218        coded_height: raw.coded_height,
1219        plane_count: raw.plane_count,
1220        sampled: raw.sampled != 0,
1221        instance: raw.instance,
1222        physical_device: raw.physical_device,
1223        device: raw.device,
1224        images: raw.images,
1225        formats: raw.formats,
1226        layouts: raw.layouts,
1227        access: raw.access,
1228        semaphores: raw.semaphores,
1229        semaphore_values: raw.semaphore_values,
1230        queue_families: raw.queue_families,
1231    })
1232}
1233
1234/// Whether the loaded libavutil was built with hardware device type `kind`.
1235#[cfg(all(any(target_os = "linux", target_os = "windows"), feature = "hwdevice"))]
1236fn hwdevice_available(kind: ffi::AVHWDeviceType) -> bool {
1237    let mut each = ffi::AV_HWDEVICE_TYPE_NONE;
1238    loop {
1239        // SAFETY: av_hwdevice_iterate_types only reads FFmpeg's static table of compiled-in types.
1240        each = unsafe { ffi::av_hwdevice_iterate_types(each) };
1241        if each == ffi::AV_HWDEVICE_TYPE_NONE {
1242            return false;
1243        }
1244        if each == kind {
1245            return true;
1246        }
1247    }
1248}
1249
1250/// rsmpeg's `alloc` unwraps the null context returned for a missing type, so check the type first.
1251#[cfg(all(any(target_os = "linux", target_os = "windows"), feature = "hwdevice"))]
1252fn alloc_hwdevice(
1253    kind: ffi::AVHWDeviceType,
1254    name: &'static str,
1255) -> Result<AVHWDeviceContext, BridgeError> {
1256    check_hardware_interop()?;
1257    if !hwdevice_available(kind) {
1258        return Err(BridgeError::MissingHwDevice(name));
1259    }
1260    Ok(AVHWDeviceContext::alloc(kind))
1261}
1262
1263/// Failure returned by an operation of this crate.
1264#[derive(Debug)]
1265#[non_exhaustive]
1266pub enum BridgeError {
1267    /// The caller supplied invalid dimensions or a mismatched byte count.
1268    InvalidInput(&'static str),
1269    /// `FFmpeg` could not allocate or prepare its destination frame.
1270    Ffmpeg(RsmpegError),
1271    /// An `FFmpeg` operation returned a negative `AVERROR` code (platform GPU statuses are
1272    /// [`Self::NativeGpu`]).
1273    FfmpegCode(i32),
1274    /// A platform GPU call in a native interop helper failed.
1275    NativeGpu(NativeGpuFailure),
1276    /// The loaded `FFmpeg` runtime was built without this hardware device type.
1277    MissingHwDevice(&'static str),
1278    /// The loaded libavutil is not the release the shims were compiled for, so hardware interop
1279    /// is off; the text names both versions.
1280    RuntimeMismatch(&'static str),
1281    /// A decoded surface the GPU interop does not take, with its description and the reason.
1282    UnsupportedSurface(String),
1283}
1284
1285/// How a planar or semi-planar YCbCr pixel format stores its samples.
1286#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1287pub struct YuvPlaneLayout {
1288    /// Log2 of the horizontal chroma subsampling.
1289    pub chroma_shift_x: u8,
1290    /// Log2 of the vertical chroma subsampling.
1291    pub chroma_shift_y: u8,
1292    /// Significant bits per sample; above eight, samples are `u16`s.
1293    pub bit_depth: u8,
1294    /// Whether U and V interleave in the second plane.
1295    pub interleaved_chroma: bool,
1296    /// Whether samples sit in the high bits of their `u16`.
1297    pub msb_aligned: bool,
1298}
1299
1300impl YuvPlaneLayout {
1301    /// Bytes per stored sample.
1302    #[must_use]
1303    pub const fn bytes_per_sample(self) -> u32 {
1304        if self.bit_depth > 8 { 2 } else { 1 }
1305    }
1306}
1307
1308/// One plane of a decoded frame.
1309#[derive(Clone, Debug, Eq, PartialEq)]
1310pub struct FramePlane {
1311    /// `stride * height` fully written bytes, either a view of the frame's buffer or a packed copy.
1312    pub bytes: bytes::Bytes,
1313    /// Bytes between rows, at least the row's samples.
1314    pub stride: u32,
1315    /// Sample positions per row (a U, V pair each for interleaved chroma).
1316    pub width: u32,
1317    /// Rows.
1318    pub height: u32,
1319}
1320
1321/// The planes of a YCbCr `AVFrame`: luma first, then chroma.
1322#[derive(Clone, Debug, Eq, PartialEq)]
1323pub struct YuvPlanes {
1324    /// How the planes store their samples.
1325    pub layout: YuvPlaneLayout,
1326    /// Coded luma width.
1327    pub width: u32,
1328    /// Coded luma height.
1329    pub height: u32,
1330    /// Luma, then U and V, or one interleaved chroma plane.
1331    pub planes: Vec<FramePlane>,
1332}
1333
1334impl fmt::Display for BridgeError {
1335    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1336        match self {
1337            Self::InvalidInput(context) => {
1338                write!(formatter, "invalid media buffer input: {context}")
1339            }
1340            Self::Ffmpeg(error) => write!(formatter, "{error}"),
1341            Self::FfmpegCode(code) => write!(formatter, "{}", RsmpegError::AVError(*code)),
1342            Self::NativeGpu(failure) => write!(formatter, "{failure}"),
1343            Self::MissingHwDevice(kind) => {
1344                write!(formatter, "the loaded FFmpeg has no {kind} hardware device")
1345            }
1346            Self::UnsupportedSurface(description) => formatter.write_str(description),
1347            Self::RuntimeMismatch(reason) => formatter.write_str(reason),
1348        }
1349    }
1350}
1351
1352/// Applies explicit matrix and range coefficients to a scaling context.
1353///
1354/// Coefficient arguments are `SWS_CS_*` constants. RGB endpoints still need
1355/// an explicit full-range flag.
1356fn configure_colorspace(
1357    context: &mut SwsContext,
1358    source_coefficients: i32,
1359    source_full_range: bool,
1360    destination_coefficients: i32,
1361    destination_full_range: bool,
1362) -> Result<(), BridgeError> {
1363    // SAFETY: the context is live and exclusively borrowed; both coefficient pointers refer to
1364    // static arrays owned by `libswscale`.
1365    let result = unsafe {
1366        ffi::sws_setColorspaceDetails(
1367            context.as_mut_ptr(),
1368            ffi::sws_getCoefficients(source_coefficients),
1369            i32::from(source_full_range),
1370            ffi::sws_getCoefficients(destination_coefficients),
1371            i32::from(destination_full_range),
1372            0,
1373            1 << 16,
1374            1 << 16,
1375        )
1376    };
1377    if result < 0 {
1378        Err(BridgeError::FfmpegCode(result))
1379    } else {
1380        Ok(())
1381    }
1382}
1383
1384/// Row alignment in bytes of every `sws_scale` destination, the widest SIMD store (16 RGBA pixels).
1385const SCALER_DESTINATION_ALIGN: i32 = 64;
1386
1387/// Converts frames of one size and pixel format into another pixel format at the same size.
1388///
1389/// `sws_scale` writes only into this type's own frame, with rows padded to 64 bytes and zero
1390/// filled, because some converters write whole blocks past a row's last pixel or skip the last
1391/// columns.
1392pub struct PackedScaler {
1393    context: SwsContext,
1394    width: i32,
1395    height: i32,
1396    source: ffi::AVPixelFormat,
1397    target: ffi::AVPixelFormat,
1398    destination: AVFrame,
1399}
1400
1401impl PackedScaler {
1402    /// A scaler from `source` to `target` at `width`x`height`, with bilinear filtering.
1403    ///
1404    /// # Errors
1405    /// Returns an error when `libswscale` has no conversion between the formats or a frame of that
1406    /// size cannot be allocated.
1407    pub fn new(
1408        width: i32,
1409        height: i32,
1410        source: ffi::AVPixelFormat,
1411        target: ffi::AVPixelFormat,
1412    ) -> Result<Self, BridgeError> {
1413        if width <= 0 || height <= 0 {
1414            return Err(BridgeError::InvalidInput("scaler size is not positive"));
1415        }
1416        let context = SwsContext::get_context(
1417            width,
1418            height,
1419            source,
1420            width,
1421            height,
1422            target,
1423            scaler_flags(width, height, source, target),
1424            None,
1425            None,
1426            None,
1427        )
1428        .ok_or(BridgeError::InvalidInput(
1429            "libswscale has no conversion between these pixel formats",
1430        ))?;
1431        let destination = padded_zeroed_frame(width, height, target)?;
1432        Ok(Self {
1433            context,
1434            width,
1435            height,
1436            source,
1437            target,
1438            destination,
1439        })
1440    }
1441
1442    /// Applies explicit matrix and range coefficients (`SWS_CS_*` constants) to the conversion.
1443    /// RGB endpoints still need an explicit full-range flag.
1444    ///
1445    /// # Errors
1446    /// Returns an error when `libswscale` rejects the configuration.
1447    pub fn configure_colorspace(
1448        &mut self,
1449        source_coefficients: i32,
1450        source_full_range: bool,
1451        destination_coefficients: i32,
1452        destination_full_range: bool,
1453    ) -> Result<(), BridgeError> {
1454        configure_colorspace(
1455            &mut self.context,
1456            source_coefficients,
1457            source_full_range,
1458            destination_coefficients,
1459            destination_full_range,
1460        )
1461    }
1462
1463    /// Converts `frame` and returns the target's planes packed without row padding, in plane
1464    /// order (the `av_image_copy_to_buffer` layout at alignment 1).
1465    ///
1466    /// # Errors
1467    /// Returns `InvalidInput` for a frame of another size or format than the scaler's, and an
1468    /// error when `libswscale` fails.
1469    pub fn convert(&mut self, frame: &AVFrame) -> Result<Vec<u8>, BridgeError> {
1470        self.check_source(frame)?;
1471        scale_into(&mut self.context, frame, &mut self.destination, self.height)?;
1472        // SAFETY: a pure size computation over plain values.
1473        let size =
1474            unsafe { ffi::av_image_get_buffer_size(self.target, self.width, self.height, 1) };
1475        let len = usize::try_from(size).map_err(|_| BridgeError::FfmpegCode(size))?;
1476        let mut packed = vec![0_u8; len];
1477        // SAFETY: `packed` holds exactly `size` bytes, and the destination frame's planes hold
1478        // `height` rows of the target format at their linesizes.
1479        let copied = unsafe {
1480            ffi::av_image_copy_to_buffer(
1481                packed.as_mut_ptr(),
1482                size,
1483                self.destination.data.as_ptr().cast(),
1484                self.destination.linesize.as_ptr(),
1485                self.target,
1486                self.width,
1487                self.height,
1488                1,
1489            )
1490        };
1491        if copied < 0 {
1492            return Err(BridgeError::FfmpegCode(copied));
1493        }
1494        Ok(packed)
1495    }
1496
1497    /// Converts `frame` into a new frame of the target format with padded rows, for an encoder
1498    /// that keeps references to its input.
1499    ///
1500    /// # Errors
1501    /// As [`Self::convert`], and when the new frame cannot be allocated.
1502    pub fn convert_to_frame(&mut self, frame: &AVFrame) -> Result<AVFrame, BridgeError> {
1503        self.check_source(frame)?;
1504        let mut output = padded_zeroed_frame(self.width, self.height, self.target)?;
1505        scale_into(&mut self.context, frame, &mut output, self.height)?;
1506        Ok(output)
1507    }
1508
1509    fn check_source(&self, frame: &AVFrame) -> Result<(), BridgeError> {
1510        if frame.width != self.width || frame.height != self.height || frame.format != self.source {
1511            return Err(BridgeError::InvalidInput(
1512                "frame size or format differs from the scaler's",
1513            ));
1514        }
1515        Ok(())
1516    }
1517}
1518
1519impl fmt::Debug for PackedScaler {
1520    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1521        formatter
1522            .debug_struct("PackedScaler")
1523            .field("width", &self.width)
1524            .field("height", &self.height)
1525            .field("source", &self.source)
1526            .field("target", &self.target)
1527            .finish_non_exhaustive()
1528    }
1529}
1530
1531/// Bilinear, plus accurate rounding where `libswscale` would otherwise pick its unscaled
1532/// 4:2:0/4:2:2-to-RGB converter for an odd width: its C version never writes the last column.
1533fn scaler_flags(
1534    width: i32,
1535    height: i32,
1536    source: ffi::AVPixelFormat,
1537    target: ffi::AVPixelFormat,
1538) -> ffi::SwsFlags {
1539    let unscaled_rgb_source = matches!(
1540        source,
1541        ffi::AV_PIX_FMT_YUV420P | ffi::AV_PIX_FMT_YUV422P | ffi::AV_PIX_FMT_YUVA420P
1542    );
1543    // SAFETY: `av_pix_fmt_desc_get` accepts any value and returns null or a static descriptor.
1544    let rgb_target = unsafe { ffi::av_pix_fmt_desc_get(target).as_ref() }
1545        .is_some_and(|descriptor| descriptor.flags & u64::from(ffi::AV_PIX_FMT_FLAG_RGB) != 0);
1546    if unscaled_rgb_source && rgb_target && height % 2 == 0 && width % 2 == 1 {
1547        ffi::SWS_BILINEAR | ffi::SWS_ACCURATE_RND
1548    } else {
1549        ffi::SWS_BILINEAR
1550    }
1551}
1552
1553/// A frame of `format` with rows aligned to [`SCALER_DESTINATION_ALIGN`], every byte zero.
1554fn padded_zeroed_frame(
1555    width: i32,
1556    height: i32,
1557    format: ffi::AVPixelFormat,
1558) -> Result<AVFrame, BridgeError> {
1559    let mut frame = AVFrame::new();
1560    frame.set_format(format);
1561    frame.set_width(width);
1562    frame.set_height(height);
1563    frame.get_buffer(SCALER_DESTINATION_ALIGN)?;
1564    for buffer in frame.buf {
1565        // SAFETY: a non-null `AVFrame::buf` entry is live, and this new frame is its only owner.
1566        if let Some(buffer) = unsafe { buffer.as_ref() } {
1567            // SAFETY: as above.
1568            unsafe { ptr::write_bytes(buffer.data, 0, buffer.size) };
1569        }
1570    }
1571    Ok(frame)
1572}
1573
1574/// The workspace's only `sws_scale` call. `destination` is a frame from [`padded_zeroed_frame`]
1575/// of the context's target format and size.
1576fn scale_into(
1577    context: &mut SwsContext,
1578    source: &AVFrame,
1579    destination: &mut AVFrame,
1580    height: i32,
1581) -> Result<(), BridgeError> {
1582    // SAFETY: the context is exclusively borrowed and was made for this size and both formats,
1583    // the source planes belong to the live `source`, and the destination planes belong to a frame
1584    // this crate allocated for the target format and size with padded rows.
1585    let rows = unsafe {
1586        ffi::sws_scale(
1587            context.as_mut_ptr(),
1588            source.data.as_ptr().cast(),
1589            source.linesize.as_ptr(),
1590            0,
1591            height,
1592            destination.data.as_ptr().cast(),
1593            destination.linesize.as_ptr(),
1594        )
1595    };
1596    if rows < 0 {
1597        return Err(BridgeError::FfmpegCode(rows));
1598    }
1599    if rows != height {
1600        return Err(BridgeError::InvalidInput(
1601            "libswscale wrote fewer rows than the frame has",
1602        ));
1603    }
1604    Ok(())
1605}
1606
1607impl Error for BridgeError {}
1608
1609impl BridgeError {
1610    /// The device fault a failed platform GPU call's status names, if any.
1611    #[must_use]
1612    pub const fn gpu_fault(&self) -> Option<GpuFault> {
1613        match self {
1614            Self::NativeGpu(failure) => failure.fault,
1615            _ => None,
1616        }
1617    }
1618}
1619
1620/// The graphics API a native interop helper called.
1621#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1622pub enum NativeGpuBackend {
1623    /// Vulkan; the status is a `VkResult`.
1624    Vulkan,
1625    /// Direct3D 12; the status is an `HRESULT`.
1626    D3D12,
1627    /// Metal through `CoreVideo`; the status is a `CVReturn`.
1628    Metal,
1629}
1630
1631impl NativeGpuBackend {
1632    /// The API's name.
1633    #[must_use]
1634    pub const fn as_str(self) -> &'static str {
1635        match self {
1636            Self::Vulkan => "Vulkan",
1637            Self::D3D12 => "D3D12",
1638            Self::Metal => "Metal",
1639        }
1640    }
1641}
1642
1643/// A platform GPU call that failed inside a native interop helper.
1644///
1645/// Classify by `fault`, which the backend reads from `status`, not by the message.
1646#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1647pub struct NativeGpuFailure {
1648    /// The API the call belongs to.
1649    pub backend: NativeGpuBackend,
1650    /// What the helper was doing, such as `encode copy`.
1651    pub operation: &'static str,
1652    /// The step of it that failed, such as `queue submit`.
1653    pub step: &'static str,
1654    /// A `VkResult`, `HRESULT` bits, or `CVReturn`; zero when the helper's own check failed.
1655    pub status: i32,
1656    /// What the status is evidence of, when it names a fault.
1657    pub fault: Option<GpuFault>,
1658}
1659
1660impl fmt::Display for NativeGpuFailure {
1661    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1662        let Self {
1663            backend,
1664            operation,
1665            step,
1666            status,
1667            ..
1668        } = *self;
1669        let backend = backend.as_str();
1670        // Use the renderer's timeout sentence so a hung GPU reads the same everywhere.
1671        if self.fault == Some(GpuFault::Timeout) {
1672            write!(
1673                formatter,
1674                "{backend} {operation} ({step}): {}",
1675                alpha2_media::GPU_TIMEOUT_MESSAGE
1676            )?;
1677        } else {
1678            write!(formatter, "{backend} {operation} failed at {step}")?;
1679        }
1680        if status == 0 {
1681            return Ok(());
1682        }
1683        match self.backend {
1684            NativeGpuBackend::Vulkan => write!(formatter, " (VkResult {status})"),
1685            NativeGpuBackend::D3D12 => write!(formatter, " (HRESULT {status:#010X})"),
1686            NativeGpuBackend::Metal => write!(formatter, " (CVReturn {status})"),
1687        }
1688    }
1689}
1690
1691impl From<RsmpegError> for BridgeError {
1692    fn from(error: RsmpegError) -> Self {
1693        Self::Ffmpeg(error)
1694    }
1695}
1696
1697unsafe extern "C" {
1698    fn alpha2_ffmpeg_shim_avutil_version() -> std::ffi::c_uint;
1699}
1700
1701/// Why hardware interop is off in this process, or `None` when the loaded libavutil has the
1702/// major and minor version the shims were compiled against.
1703///
1704/// The shims read `FFmpeg` structures at offsets of one minor release, so every hardware device
1705/// constructor of this crate refuses with [`BridgeError::RuntimeMismatch`] while this is `Some`.
1706#[must_use]
1707pub fn hardware_interop_refusal() -> Option<&'static str> {
1708    static REFUSAL: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
1709    REFUSAL
1710        .get_or_init(|| {
1711            // SAFETY: returns a constant compiled into the shim.
1712            let compiled = unsafe { alpha2_ffmpeg_shim_avutil_version() };
1713            // SAFETY: a pure query of the loaded library.
1714            let loaded = unsafe { ffi::avutil_version() };
1715            interop_version_refusal(compiled, loaded)
1716        })
1717        .as_deref()
1718}
1719
1720/// Refuses interop across a major or minor `AV_VERSION_INT` difference; micro versions may differ.
1721fn interop_version_refusal(compiled: u32, loaded: u32) -> Option<String> {
1722    let version = |value: u32| format!("{}.{}.{}", value >> 16, (value >> 8) & 0xff, value & 0xff);
1723    (compiled >> 8 != loaded >> 8).then(|| {
1724        format!(
1725            "hardware interop is off: the FFmpeg shims were compiled for libavutil {} and the \
1726             loaded libavutil is {}",
1727            version(compiled),
1728            version(loaded)
1729        )
1730    })
1731}
1732
1733/// The refusal of [`hardware_interop_refusal`] as an error.
1734///
1735/// # Errors
1736/// Returns [`BridgeError::RuntimeMismatch`] when the loaded libavutil is another minor release.
1737pub fn check_hardware_interop() -> Result<(), BridgeError> {
1738    hardware_interop_refusal().map_or(Ok(()), |reason| Err(BridgeError::RuntimeMismatch(reason)))
1739}
1740
1741/// Returns the linked `FFmpeg` runtime version string.
1742#[must_use]
1743pub fn runtime_version() -> String {
1744    // SAFETY: FFmpeg returns a process-lifetime, NUL-terminated string.
1745    unsafe { CStr::from_ptr(ffi::av_version_info()) }
1746        .to_string_lossy()
1747        .into_owned()
1748}
1749
1750/// Returns the linked libavcodec configure string.
1751#[must_use]
1752pub fn runtime_configuration() -> String {
1753    // SAFETY: FFmpeg returns a process-lifetime, NUL-terminated string.
1754    unsafe { CStr::from_ptr(ffi::avcodec_configuration()) }
1755        .to_string_lossy()
1756        .into_owned()
1757}
1758
1759/// Whether muxer `format` can store `codec` at normal compliance; `None` when it is not linked.
1760#[must_use]
1761pub fn muxer_accepts_codec(format: &CStr, codec: ffi::AVCodecID) -> Option<bool> {
1762    // SAFETY: `format` is NUL-terminated; FFmpeg returns a registered, process-lifetime muxer
1763    // or null.
1764    let muxer = unsafe { ffi::av_guess_format(format.as_ptr(), ptr::null(), ptr::null()) };
1765    if muxer.is_null() {
1766        return None;
1767    }
1768    // SAFETY: `muxer` is the live registered muxer found above.
1769    let accepted = unsafe {
1770        ffi::avformat_query_codec(
1771            muxer,
1772            codec,
1773            i32::try_from(ffi::FF_COMPLIANCE_NORMAL).unwrap_or(0),
1774        )
1775    };
1776    Some(accepted == 1)
1777}
1778
1779/// Chroma layout, component depth, and alpha of one pixel format.
1780#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1781pub struct SampleProfile {
1782    /// Whether the format is planar/semi-planar YCbCr with 4:2:0 subsampling.
1783    pub is_yuv_420: bool,
1784    /// Largest component depth in bits.
1785    pub bit_depth: u8,
1786    /// Whether the format carries an alpha component.
1787    pub has_alpha: bool,
1788    /// Whether the components are RGB (palettes included) rather than luma and chroma or gray.
1789    pub is_rgb: bool,
1790}
1791
1792/// Describes a pixel format, or `None` when the value has no descriptor.
1793///
1794/// A stream's format may be unset until the first frame decodes, so `None` means "not yet known".
1795#[must_use]
1796pub fn sample_profile(format: ffi::AVPixelFormat) -> Option<SampleProfile> {
1797    if format == ffi::AV_PIX_FMT_NONE {
1798        return None;
1799    }
1800    // SAFETY: `av_pix_fmt_desc_get` accepts any value and returns null or a static descriptor.
1801    let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }?;
1802    let components = usize::from(descriptor.nb_components.min(4));
1803    Some(SampleProfile {
1804        is_yuv_420: descriptor.log2_chroma_w == 1
1805            && descriptor.log2_chroma_h == 1
1806            && descriptor.nb_components >= 3
1807            && descriptor.flags & u64::from(ffi::AV_PIX_FMT_FLAG_RGB) == 0,
1808        bit_depth: descriptor.comp[..components]
1809            .iter()
1810            .map(|component| u8::try_from(component.depth).unwrap_or(u8::MAX))
1811            .max()
1812            .unwrap_or(8),
1813        has_alpha: descriptor.flags & u64::from(ffi::AV_PIX_FMT_FLAG_ALPHA) != 0,
1814        is_rgb: descriptor.flags & u64::from(ffi::AV_PIX_FMT_FLAG_RGB | ffi::AV_PIX_FMT_FLAG_PAL)
1815            != 0,
1816    })
1817}
1818
1819/// Returns `FFmpeg`'s stable name for a pixel-format value.
1820#[must_use]
1821pub fn pixel_format_name(format: ffi::AVPixelFormat) -> Option<String> {
1822    // SAFETY: `av_get_pix_fmt_name` accepts any value and returns null or a static C string.
1823    let name = unsafe { ffi::av_get_pix_fmt_name(format) };
1824    if name.is_null() {
1825        None
1826    } else {
1827        // SAFETY: non-null return values obey the FFmpeg string contract above.
1828        Some(
1829            unsafe { CStr::from_ptr(name) }
1830                .to_string_lossy()
1831                .into_owned(),
1832        )
1833    }
1834}
1835
1836/// Opens `context` with `options`, returning what `FFmpeg` did not consume.
1837///
1838/// `avcodec_open2` frees the dictionary and writes the remainder back on failure as well as
1839/// success. rsmpeg's `AVCodecContext::open` double-frees it on failure, which would abort an
1840/// encoder fallback.
1841///
1842/// # Errors
1843/// Returns the `FFmpeg` status when the encoder or decoder cannot be opened.
1844pub fn open_codec_context(
1845    context: &mut rsmpeg::avcodec::AVCodecContext,
1846    options: rsmpeg::avutil::AVDictionary,
1847) -> Result<Option<rsmpeg::avutil::AVDictionary>, RsmpegError> {
1848    let _media_foundation = media_foundation_lock(context);
1849    let mut dictionary = options.into_raw().as_ptr();
1850    // SAFETY: `context` is live and FFmpeg owns `dictionary`, replacing it with a null or owned
1851    // remainder.
1852    let status = unsafe {
1853        ffi::avcodec_open2(
1854            context.as_mut_ptr(),
1855            ptr::null_mut(),
1856            std::ptr::addr_of_mut!(dictionary),
1857        )
1858    };
1859    // SAFETY: a non-null remainder is a dictionary FFmpeg handed back; this is its only owner.
1860    let unused = ptr::NonNull::new(dictionary)
1861        .map(|dictionary| unsafe { rsmpeg::avutil::AVDictionary::from_raw(dictionary) });
1862    if status < 0 {
1863        return Err(RsmpegError::from(status));
1864    }
1865    Ok(unused)
1866}
1867
1868/// Serializes opening and closing `MediaFoundation` (`_mf`) encoders; `None` for other codecs.
1869///
1870/// `MFTEnumEx` (on open) and `MFShutdown` (on close) take mfplat's critical section and the
1871/// work-queue lock in opposite orders and deadlock across threads, whatever the `MFStartup` count.
1872fn media_foundation_lock(
1873    context: &rsmpeg::avcodec::AVCodecContext,
1874) -> Option<std::sync::MutexGuard<'static, ()>> {
1875    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1876    if !cfg!(target_os = "windows") || context.codec.is_null() {
1877        return None;
1878    }
1879    // SAFETY: a non-null `codec` is a static codec descriptor with a static C-string `name`.
1880    let name = unsafe { CStr::from_ptr((*context.codec).name) };
1881    name.to_bytes().ends_with(b"_mf").then(|| {
1882        LOCK.lock()
1883            .unwrap_or_else(std::sync::PoisonError::into_inner)
1884    })
1885}
1886
1887/// An [`AVCodecContext`] closed under the `MediaFoundation` lock when it is an `_mf` encoder.
1888///
1889/// [`AVCodecContext`]: rsmpeg::avcodec::AVCodecContext
1890pub struct EncoderContext(Option<rsmpeg::avcodec::AVCodecContext>);
1891
1892impl From<rsmpeg::avcodec::AVCodecContext> for EncoderContext {
1893    fn from(context: rsmpeg::avcodec::AVCodecContext) -> Self {
1894        Self(Some(context))
1895    }
1896}
1897
1898impl std::ops::Deref for EncoderContext {
1899    type Target = rsmpeg::avcodec::AVCodecContext;
1900
1901    fn deref(&self) -> &Self::Target {
1902        self.0.as_ref().expect("taken only when dropped")
1903    }
1904}
1905
1906impl std::ops::DerefMut for EncoderContext {
1907    fn deref_mut(&mut self) -> &mut Self::Target {
1908        self.0.as_mut().expect("taken only when dropped")
1909    }
1910}
1911
1912impl Drop for EncoderContext {
1913    fn drop(&mut self) {
1914        if let Some(context) = self.0.take() {
1915            let _media_foundation = media_foundation_lock(&context);
1916            drop(context);
1917        }
1918    }
1919}
1920
1921/// `VkImageUsageFlags` an encoder-input pool needs beyond `FFmpeg`'s own.
1922///
1923/// `TRANSFER_DST` for the renderer's copy, `SAMPLED` for wgpu import, `TRANSFER_SRC` for readback
1924/// checks, `VIDEO_ENCODE_SRC` for the encoder.
1925#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1926pub const VULKAN_ENCODE_INPUT_USAGE: u32 = 0x0000_0001 | 0x0000_0002 | 0x0000_0004 | 0x0000_4000;
1927
1928/// Adds `usage` to a Vulkan frames context before it allocates its pool.
1929///
1930/// Left at zero, `hwcontext_vulkan` picks a default that requires `STORAGE` support. A nonzero
1931/// usage is used exactly as given, so every flag must be supported by the format; encoder-input
1932/// pools ask for [`VULKAN_ENCODE_INPUT_USAGE`]. Call between `av_hwframe_ctx_alloc` and
1933/// `av_hwframe_ctx_init`.
1934///
1935/// # Errors
1936/// Returns an error when the context is not a Vulkan one.
1937#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1938pub fn vulkan_frames_add_usage(
1939    frames: &mut rsmpeg::avutil::AVHWFramesContext,
1940    usage: u32,
1941) -> Result<(), BridgeError> {
1942    // SAFETY: `frames` is live; the shim checks the device type and only ORs into `usage`.
1943    let status = unsafe { alpha2_vulkan_frames_add_usage(frames.as_mut_ptr(), usage) };
1944    if status < 0 {
1945        return Err(BridgeError::FfmpegCode(status));
1946    }
1947    Ok(())
1948}
1949
1950/// Usage the pool was created with, including the default `FFmpeg` picks for zero.
1951#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1952#[must_use]
1953pub fn vulkan_frames_usage(frames: &rsmpeg::avutil::AVHWFramesContext) -> u32 {
1954    // SAFETY: `frames` is live; the shim checks the device type before reading `hwctx`.
1955    unsafe { alpha2_vulkan_frames_usage(frames.as_ptr()) }
1956}
1957
1958/// Copies one packet's payload out of `FFmpeg`'s buffer.
1959#[must_use]
1960pub fn packet_bytes(packet: &rsmpeg::avcodec::AVPacket) -> Vec<u8> {
1961    let size = usize::try_from(packet.size).unwrap_or(0);
1962    if packet.data.is_null() || size == 0 {
1963        return Vec::new();
1964    }
1965    // SAFETY: the borrowed packet owns `size` readable bytes at `data`.
1966    unsafe { slice::from_raw_parts(packet.data.cast_const(), size) }.to_vec()
1967}
1968
1969/// A copy of a stream's codec extradata (parameter sets for H.264 and HEVC).
1970///
1971/// Takes rsmpeg's wrapper because a bare `AVCodecParameters` can carry a forged pointer:
1972///
1973/// ```compile_fail,E0308
1974/// let mut forged: rsmpeg::ffi::AVCodecParameters = *rsmpeg::avcodec::AVCodecParameters::new();
1975/// forged.extradata = 0x10 as *mut u8;
1976/// forged.extradata_size = 64;
1977/// alpha2_ffmpeg_bridge::codec_parameters_extradata(&forged);
1978/// ```
1979#[must_use]
1980pub fn codec_parameters_extradata(parameters: &rsmpeg::avcodec::AVCodecParameters) -> Vec<u8> {
1981    let size = usize::try_from(parameters.extradata_size).unwrap_or(0);
1982    if parameters.extradata.is_null() || size == 0 {
1983        return Vec::new();
1984    }
1985    // SAFETY: the borrowed parameters own `extradata_size` readable bytes at `extradata`.
1986    unsafe { slice::from_raw_parts(parameters.extradata.cast_const(), size) }.to_vec()
1987}
1988
1989/// Whether `packet` carries side data of `kind`.
1990#[must_use]
1991pub fn packet_has_side_data(
1992    packet: &rsmpeg::avcodec::AVPacket,
1993    kind: ffi::AVPacketSideDataType,
1994) -> bool {
1995    let mut size = 0_usize;
1996    // SAFETY: `packet` is live; the result is only compared with null.
1997    !unsafe { ffi::av_packet_get_side_data(packet.as_ptr(), kind, &raw mut size) }.is_null()
1998}
1999
2000/// Removes and returns `packet`'s side data of `kind`.
2001///
2002/// Encoder parameter sets must be taken off, not copied, or the MP4 muxer reads them as a sample
2003/// description change.
2004#[must_use]
2005pub fn take_packet_side_data(
2006    packet: &mut rsmpeg::avcodec::AVPacket,
2007    kind: ffi::AVPacketSideDataType,
2008) -> Option<Vec<u8>> {
2009    let mut size = 0_usize;
2010    // SAFETY: `packet` is live; a non-null result points at `size` bytes the packet owns.
2011    let data = unsafe { ffi::av_packet_get_side_data(packet.as_ptr(), kind, &raw mut size) };
2012    if data.is_null() {
2013        return None;
2014    }
2015    // SAFETY: as above; the bytes are copied before the entry is freed below.
2016    let bytes = unsafe { slice::from_raw_parts(data, size) }.to_vec();
2017    let packet = packet.as_mut_ptr();
2018    // SAFETY: `side_data` and `side_data_elems` are the packet's own array and count, which
2019    // `av_packet_side_data_remove` keeps consistent while freeing the `av_malloc`ed entry.
2020    unsafe {
2021        ffi::av_packet_side_data_remove(
2022            (*packet).side_data,
2023            &raw mut (*packet).side_data_elems,
2024            kind,
2025        );
2026    }
2027    Some(bytes)
2028}
2029
2030/// The payload of `packet`'s Matroska block addition `id` (`FFmpeg` stores each as side data: an
2031/// 8-byte big-endian `BlockAddID`, then the payload).
2032#[must_use]
2033pub fn packet_block_addition(packet: &rsmpeg::avcodec::AVPacket, id: u64) -> Option<&[u8]> {
2034    let count = usize::try_from(packet.side_data_elems).ok()?;
2035    if count == 0 || packet.side_data.is_null() {
2036        return None;
2037    }
2038    // SAFETY: the borrowed packet owns `side_data_elems` entries at `side_data`.
2039    let entries = unsafe { slice::from_raw_parts(packet.side_data, count) };
2040    entries
2041        .iter()
2042        .filter(|entry| {
2043            entry.type_ == ffi::AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL
2044                && !entry.data.is_null()
2045                && entry.size >= 8
2046        })
2047        // SAFETY: a non-null entry holds `size` bytes the borrowed packet owns.
2048        .map(|entry| unsafe { slice::from_raw_parts(entry.data, entry.size) })
2049        .find(|data| data[..8] == id.to_be_bytes())
2050        .map(|data| &data[8..])
2051}
2052
2053/// Whether `data`, a VP9 frame or superframe, starts with a key frame, from which a decoder can
2054/// start (VP9 6.2: `frame_marker`, the profile bits, `show_existing_frame`, `frame_type`).
2055#[must_use]
2056pub fn vp9_frame_is_keyframe(data: &[u8]) -> bool {
2057    let Some(&header) = data.first() else {
2058        return false;
2059    };
2060    let bit = |index: u32| (header >> (7 - index)) & 1 == 1;
2061    if header >> 6 != 0b10 {
2062        return false;
2063    }
2064    let profile = u8::from(bit(2)) | (u8::from(bit(3)) << 1);
2065    let next = if profile == 3 { 5 } else { 4 };
2066    !bit(next) && !bit(next + 1)
2067}
2068
2069/// Tags `frame` with `FFmpeg`'s colour properties, which some encoders (`ProRes`) write into each
2070/// frame header.
2071pub fn set_frame_color(
2072    frame: &mut rsmpeg::avutil::AVFrame,
2073    (primaries, transfer, space, range): (
2074        ffi::AVColorPrimaries,
2075        ffi::AVColorTransferCharacteristic,
2076        ffi::AVColorSpace,
2077        ffi::AVColorRange,
2078    ),
2079) {
2080    let raw = frame.as_mut_ptr();
2081    // SAFETY: `frame` is mutably borrowed; the fields are plain values.
2082    unsafe {
2083        (*raw).color_primaries = primaries;
2084        (*raw).color_trc = transfer;
2085        (*raw).colorspace = space;
2086        (*raw).color_range = range;
2087    }
2088}
2089
2090/// Gives `packet` side data of `kind` holding `data`, replacing any it had.
2091///
2092/// # Errors
2093/// When the side data cannot be allocated or `data` is too large.
2094pub fn set_packet_side_data(
2095    packet: &mut rsmpeg::avcodec::AVPacket,
2096    kind: ffi::AVPacketSideDataType,
2097    data: &[u8],
2098) -> Result<(), BridgeError> {
2099    let _ = take_packet_side_data(packet, kind);
2100    // SAFETY: `packet` is mutably borrowed; `av_packet_new_side_data` returns null or a padded
2101    // entry of `data.len()` bytes.
2102    let entry = unsafe { ffi::av_packet_new_side_data(packet.as_mut_ptr(), kind, data.len()) };
2103    if entry.is_null() {
2104        return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2105    }
2106    // SAFETY: the entry just made holds `data.len()` writable bytes.
2107    unsafe { ptr::copy_nonoverlapping(data.as_ptr(), entry, data.len()) };
2108    Ok(())
2109}
2110
2111/// Replaces the extradata of `output`'s stream `index` before the header is written.
2112///
2113/// rsmpeg exposes an output's streams read-only. `FFmpeg` needs padded `av_malloc` memory here, not
2114/// a Rust buffer.
2115///
2116/// # Errors
2117/// When there is no stream `index`, or `data` is too large or cannot be allocated.
2118pub fn set_output_stream_extradata(
2119    output: &mut rsmpeg::avformat::AVFormatContextOutput,
2120    index: usize,
2121    data: &[u8],
2122) -> Result<(), BridgeError> {
2123    let parameters = output
2124        .streams()
2125        .get(index)
2126        .ok_or(BridgeError::InvalidInput("the output has no such stream"))?
2127        .codecpar;
2128    let size = i32::try_from(data.len())
2129        .map_err(|_| BridgeError::InvalidInput("extradata is larger than FFmpeg holds"))?;
2130    let padding = usize::try_from(ffi::AV_INPUT_BUFFER_PADDING_SIZE).unwrap_or(64);
2131    // SAFETY: `av_mallocz` returns null or a zeroed buffer of the size asked for.
2132    let buffer = unsafe { ffi::av_mallocz(data.len() + padding) }.cast::<u8>();
2133    if buffer.is_null() {
2134        return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2135    }
2136    // SAFETY: `buffer` holds `data.len()` writable bytes and does not overlap `data`.
2137    unsafe { ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len()) };
2138    // SAFETY: the stream owns its codec parameters and the output is mutably borrowed. The old
2139    // extradata is null or `av_malloc`ed and is freed; the parameters now own `buffer`.
2140    unsafe {
2141        ffi::av_freep((&raw mut (*parameters).extradata).cast());
2142        (*parameters).extradata = buffer;
2143        (*parameters).extradata_size = size;
2144    }
2145    Ok(())
2146}
2147
2148/// A packet holding a copy of `data`, every other field at its default.
2149///
2150/// # Errors
2151/// When `data` is too large or the packet cannot be allocated.
2152pub fn packet_from_bytes(data: &[u8]) -> Result<rsmpeg::avcodec::AVPacket, BridgeError> {
2153    let size = i32::try_from(data.len())
2154        .map_err(|_| BridgeError::InvalidInput("a packet is larger than FFmpeg holds"))?;
2155    let mut packet = rsmpeg::avcodec::AVPacket::new();
2156    // SAFETY: `packet` is fresh and empty; `av_new_packet` gives it a padded buffer or fails.
2157    let status = unsafe { ffi::av_new_packet(packet.as_mut_ptr(), size) };
2158    if status < 0 {
2159        return Err(BridgeError::FfmpegCode(status));
2160    }
2161    if !data.is_empty() {
2162        // SAFETY: the packet's buffer holds `size` writable bytes and does not overlap `data`.
2163        unsafe { ptr::copy_nonoverlapping(data.as_ptr(), packet.data, data.len()) };
2164    }
2165    Ok(packet)
2166}
2167
2168/// Replaces `packet`'s payload with `data`, no longer than it, keeping timestamps and side data.
2169///
2170/// # Errors
2171/// When `data` is longer than the payload or the buffer cannot be made writable.
2172pub fn shrink_packet_to(
2173    packet: &mut rsmpeg::avcodec::AVPacket,
2174    data: &[u8],
2175) -> Result<(), BridgeError> {
2176    let size = i32::try_from(data.len())
2177        .ok()
2178        .filter(|size| *size <= packet.size)
2179        .ok_or(BridgeError::InvalidInput("a packet cannot grow in place"))?;
2180    // SAFETY: `packet` is live; `av_packet_make_writable` gives it an unshared buffer of its size.
2181    let status = unsafe { ffi::av_packet_make_writable(packet.as_mut_ptr()) };
2182    if status < 0 {
2183        return Err(BridgeError::FfmpegCode(status));
2184    }
2185    if !data.is_empty() {
2186        // SAFETY: the writable buffer holds at least `data.len()` bytes and cannot overlap `data`.
2187        unsafe { ptr::copy_nonoverlapping(data.as_ptr(), packet.data, data.len()) };
2188    }
2189    // SAFETY: `size` is not above the packet's size; FFmpeg zeroes the padding after it.
2190    unsafe { ffi::av_shrink_packet(packet.as_mut_ptr(), size) };
2191    Ok(())
2192}
2193
2194/// Codec parameters for a video stream not produced by an `FFmpeg` encoder.
2195#[derive(Clone, Copy, Debug)]
2196pub struct VideoStreamDescription<'a> {
2197    /// The codec.
2198    pub codec_id: ffi::AVCodecID,
2199    /// Coded width.
2200    pub width: i32,
2201    /// Coded height.
2202    pub height: i32,
2203    /// The pixel format the stream decodes to.
2204    pub pixel_format: ffi::AVPixelFormat,
2205    /// `AV_PROFILE_*` for the codec.
2206    pub profile: i32,
2207    /// The codec's level number.
2208    pub level: i32,
2209    /// Colour primaries tag.
2210    pub color_primaries: ffi::AVColorPrimaries,
2211    /// Transfer characteristics tag.
2212    pub color_trc: ffi::AVColorTransferCharacteristic,
2213    /// Matrix coefficients tag.
2214    pub color_space: ffi::AVColorSpace,
2215    /// Sample range.
2216    pub color_range: ffi::AVColorRange,
2217    /// Pixel aspect ratio; `0/1` when undeclared.
2218    pub sample_aspect_ratio: ffi::AVRational,
2219    /// Frames per second.
2220    pub frame_rate: ffi::AVRational,
2221    /// Average bitrate, `0` when unknown.
2222    pub bit_rate: i64,
2223    /// The sample description (`avcC` for H.264).
2224    pub extradata: &'a [u8],
2225}
2226
2227/// Codec parameters for a video stream `description` describes.
2228///
2229/// # Errors
2230/// When the extradata is larger than `FFmpeg` holds or cannot be allocated.
2231pub fn video_codec_parameters(
2232    description: &VideoStreamDescription<'_>,
2233) -> Result<rsmpeg::avcodec::AVCodecParameters, BridgeError> {
2234    let extradata_size = i32::try_from(description.extradata.len())
2235        .map_err(|_| BridgeError::InvalidInput("extradata is larger than FFmpeg holds"))?;
2236    let mut parameters = rsmpeg::avcodec::AVCodecParameters::new();
2237    let raw = parameters.as_mut_ptr();
2238    // SAFETY: `raw` is freshly allocated and uniquely owned; the fields are plain values.
2239    unsafe {
2240        (*raw).codec_type = ffi::AVMEDIA_TYPE_VIDEO;
2241        (*raw).codec_id = description.codec_id;
2242        (*raw).width = description.width;
2243        (*raw).height = description.height;
2244        (*raw).format = description.pixel_format;
2245        (*raw).profile = description.profile;
2246        (*raw).level = description.level;
2247        (*raw).color_primaries = description.color_primaries;
2248        (*raw).color_trc = description.color_trc;
2249        (*raw).color_space = description.color_space;
2250        (*raw).color_range = description.color_range;
2251        (*raw).sample_aspect_ratio = description.sample_aspect_ratio;
2252        (*raw).framerate = description.frame_rate;
2253        (*raw).bit_rate = description.bit_rate;
2254        (*raw).field_order = ffi::AV_FIELD_PROGRESSIVE;
2255    }
2256    if !description.extradata.is_empty() {
2257        let padding = usize::try_from(ffi::AV_INPUT_BUFFER_PADDING_SIZE).unwrap_or(64);
2258        // SAFETY: `av_mallocz` returns null or a zeroed buffer of the size asked for.
2259        let buffer = unsafe { ffi::av_mallocz(description.extradata.len() + padding) }.cast::<u8>();
2260        if buffer.is_null() {
2261            return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2262        }
2263        // SAFETY: `buffer` holds the extradata's length and does not overlap it. The parameters
2264        // had no extradata and now own `buffer`.
2265        unsafe {
2266            ptr::copy_nonoverlapping(
2267                description.extradata.as_ptr(),
2268                buffer,
2269                description.extradata.len(),
2270            );
2271            (*raw).extradata = buffer;
2272            (*raw).extradata_size = extradata_size;
2273        }
2274    }
2275    Ok(parameters)
2276}
2277
2278/// Opens a bitstream filter chain in `ffmpeg -bsf` list syntax for a stream described by
2279/// `parameters` with packets in `time_base`.
2280///
2281/// rsmpeg cannot parse a list or set a filter's private options.
2282///
2283/// # Errors
2284/// Returns the `FFmpeg` status when the list does not parse, names a filter or option the runtime
2285/// lacks, or a filter refuses the stream.
2286pub fn bitstream_filter_list(
2287    spec: &CStr,
2288    parameters: &AVCodecParameters,
2289    time_base: rsmpeg::avutil::AVRational,
2290) -> Result<rsmpeg::avcodec::AVBSFContext, BridgeError> {
2291    let mut raw = ptr::null_mut();
2292    // SAFETY: `spec` is NUL-terminated; on success `raw` holds a new context taken over below.
2293    let status = unsafe { ffi::av_bsf_list_parse_str(spec.as_ptr(), &raw mut raw) };
2294    if status < 0 {
2295        return Err(BridgeError::FfmpegCode(status));
2296    }
2297    let raw = ptr::NonNull::new(raw).ok_or(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)))?;
2298    // SAFETY: `raw` was just allocated and is unshared; the wrapper frees it with `av_bsf_free`.
2299    let mut context = unsafe { rsmpeg::avcodec::AVBSFContextUninit::from_raw(raw) };
2300    // rsmpeg's `set_par_in` panics when the copy cannot allocate.
2301    // SAFETY: `par_in` is the context's own parameter set and `parameters` is live;
2302    // `avcodec_parameters_copy` deep-copies into it.
2303    let status = unsafe { ffi::avcodec_parameters_copy(context.par_in, parameters.as_ptr()) };
2304    if status < 0 {
2305        return Err(BridgeError::FfmpegCode(status));
2306    }
2307    context.set_time_base_in(time_base);
2308    context.init().map_err(BridgeError::Ffmpeg)
2309}
2310
2311/// Sets a stream's codec tag (sample entry); zero lets the muxer pick its default.
2312pub fn set_stream_codec_tag(stream: &mut rsmpeg::avformat::AVStreamMut<'_>, tag: u32) {
2313    let mut parameters = stream.codecpar_mut();
2314    // SAFETY: the mutably borrowed stream owns its codec parameters; `codec_tag` is a plain field.
2315    unsafe { (*parameters.as_mut_ptr()).codec_tag = tag };
2316}
2317
2318/// Replaces a stream's display matrix (MP4's `tkhd` matrix) with `display`'s rotation and flip, as
2319/// [`display_rotation`] reads it back.
2320///
2321/// # Errors
2322/// When the side data cannot be allocated.
2323pub fn set_stream_display_matrix(
2324    stream: &mut rsmpeg::avformat::AVStreamMut<'_>,
2325    display: DisplayRotation,
2326) -> Result<(), BridgeError> {
2327    let mut parameters = stream.codecpar_mut();
2328    let parameters = parameters.as_mut_ptr();
2329    // SAFETY: the mutably borrowed stream owns its codec parameters; `av_packet_side_data_new`
2330    // keeps the array and count consistent and returns null only on allocation failure.
2331    let entry = unsafe {
2332        ffi::av_packet_side_data_new(
2333            &raw mut (*parameters).coded_side_data,
2334            &raw mut (*parameters).nb_coded_side_data,
2335            ffi::AV_PKT_DATA_DISPLAYMATRIX,
2336            size_of::<[i32; 9]>(),
2337            0,
2338        )
2339    };
2340    if entry.is_null() {
2341        return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2342    }
2343    let mut matrix = [0_i32; 9];
2344    // `av_display_rotation_set` turns clockwise, opposite to `av_display_rotation_get`.
2345    // SAFETY: `matrix` is a complete, aligned 3x3 display matrix.
2346    unsafe {
2347        ffi::av_display_rotation_set(matrix.as_mut_ptr(), -display.counter_clockwise_degrees);
2348        if display.flipped {
2349            ffi::av_display_matrix_flip(matrix.as_mut_ptr(), 1, 0);
2350        }
2351    }
2352    // SAFETY: the new entry holds `size_of::<[i32; 9]>()` writable bytes; a byte copy needs no
2353    // alignment.
2354    unsafe {
2355        ptr::copy_nonoverlapping(
2356            matrix.as_ptr().cast::<u8>(),
2357            (*entry).data,
2358            size_of::<[i32; 9]>(),
2359        );
2360    }
2361    Ok(())
2362}
2363
2364/// Returns `FFmpeg`'s stable name for a hardware device type.
2365#[must_use]
2366pub fn hardware_device_type_name(device_type: ffi::AVHWDeviceType) -> Option<String> {
2367    // SAFETY: `av_hwdevice_get_type_name` accepts any value and returns null or a static C string.
2368    let name = unsafe { ffi::av_hwdevice_get_type_name(device_type) };
2369    if name.is_null() {
2370        None
2371    } else {
2372        // SAFETY: non-null return values obey the FFmpeg string contract above.
2373        Some(
2374            unsafe { CStr::from_ptr(name) }
2375                .to_string_lossy()
2376                .into_owned(),
2377        )
2378    }
2379}
2380
2381/// The plane layout of a YCbCr format the renderer samples directly, or `None`.
2382///
2383/// Accepts three components of one depth from 8 to 16 bits, chroma subsampled by at most four per
2384/// axis, three planes or U, V interleaved in the second, native byte order, low- or (above eight
2385/// bits) high-bit aligned. Rejects RGB, alpha, gray, palette, Bayer, float, XYZ, bitstream,
2386/// hardware formats and NV21.
2387#[must_use]
2388pub fn yuv_layout(format: ffi::AVPixelFormat) -> Option<YuvPlaneLayout> {
2389    if format == ffi::AV_PIX_FMT_NONE {
2390        return None;
2391    }
2392    // SAFETY: `av_pix_fmt_desc_get` accepts any value and returns null or a static descriptor.
2393    let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }?;
2394    let foreign_endian = if cfg!(target_endian = "little") {
2395        ffi::AV_PIX_FMT_FLAG_BE
2396    } else {
2397        0
2398    };
2399    let rejected = foreign_endian
2400        | ffi::AV_PIX_FMT_FLAG_PAL
2401        | ffi::AV_PIX_FMT_FLAG_BITSTREAM
2402        | ffi::AV_PIX_FMT_FLAG_HWACCEL
2403        | ffi::AV_PIX_FMT_FLAG_RGB
2404        | ffi::AV_PIX_FMT_FLAG_ALPHA
2405        | ffi::AV_PIX_FMT_FLAG_BAYER
2406        | ffi::AV_PIX_FMT_FLAG_FLOAT
2407        | ffi::AV_PIX_FMT_FLAG_XYZ;
2408    if descriptor.flags & u64::from(rejected) != 0 || descriptor.nb_components != 3 {
2409        return None;
2410    }
2411    let [luma, u, v, _] = descriptor.comp;
2412    let depth = luma.depth;
2413    if !(8..=16).contains(&depth) || u.depth != depth || v.depth != depth {
2414        return None;
2415    }
2416    if descriptor.log2_chroma_w > 2 || descriptor.log2_chroma_h > 2 {
2417        return None;
2418    }
2419    let bytes = if depth > 8 { 2 } else { 1 };
2420    let shift = luma.shift;
2421    let msb_aligned = match shift {
2422        0 => false,
2423        _ if depth > 8 && shift == 16 - depth => true,
2424        _ => return None,
2425    };
2426    let planar = u.plane == 1
2427        && v.plane == 2
2428        && u.step == bytes
2429        && v.step == bytes
2430        && u.offset == 0
2431        && v.offset == 0;
2432    let interleaved = u.plane == 1
2433        && v.plane == 1
2434        && u.step == 2 * bytes
2435        && v.step == 2 * bytes
2436        && u.offset == 0
2437        && v.offset == bytes;
2438    if luma.plane != 0
2439        || luma.step != bytes
2440        || luma.offset != 0
2441        || u.shift != shift
2442        || v.shift != shift
2443        || !(planar || interleaved)
2444    {
2445        return None;
2446    }
2447    Some(YuvPlaneLayout {
2448        chroma_shift_x: descriptor.log2_chroma_w,
2449        chroma_shift_y: descriptor.log2_chroma_h,
2450        bit_depth: u8::try_from(depth).ok()?,
2451        interleaved_chroma: interleaved,
2452        msb_aligned,
2453    })
2454}
2455
2456/// Copies the samples of a frame whose format [`yuv_layout`] accepts into packed forward rows, or
2457/// returns `Ok(None)` for other formats. Odd dimensions round chroma up.
2458///
2459/// Row padding is never read since it may be uninitialized; [`DecodedFrame::yuv_planes`] can share
2460/// fully written frames instead.
2461///
2462/// # Errors
2463/// Returns an error for invalid dimensions, null planes, or linesizes shorter than the plane width.
2464pub fn yuv_planes(frame: &AVFrame) -> Result<Option<YuvPlanes>, BridgeError> {
2465    frame_yuv_planes(frame, false)
2466}
2467
2468/// A decoded frame, and whether every byte of its buffers, row padding included, is written.
2469///
2470/// Only this crate constructs one; frames from elsewhere go to [`yuv_planes`].
2471pub struct DecodedFrame {
2472    frame: AVFrame,
2473    written: bool,
2474}
2475
2476impl DecodedFrame {
2477    /// Takes the next frame `decoder` has ready.
2478    ///
2479    /// # Errors
2480    /// Returns what `avcodec_receive_frame` does for a drained decoder or a decode failure.
2481    pub fn receive(decoder: &mut AVCodecContext) -> Result<Self, RsmpegError> {
2482        let written = decoder_frames_are_initialized(decoder);
2483        let frame = decoder.receive_frame()?;
2484        Ok(Self { frame, written })
2485    }
2486
2487    /// Like [`yuv_planes`], but shares the frame's buffer when it is fully written. Planes with a
2488    /// negative linesize or outside the frame's buffers are still copied.
2489    ///
2490    /// # Errors
2491    /// Returns an error for invalid dimensions, null planes, or linesizes shorter than the plane
2492    /// width.
2493    pub fn yuv_planes(&self) -> Result<Option<YuvPlanes>, BridgeError> {
2494        frame_yuv_planes(&self.frame, self.written)
2495    }
2496
2497    /// Sets the frame's presentation timestamp.
2498    pub fn set_pts(&mut self, pts: i64) {
2499        self.frame.set_pts(pts);
2500    }
2501
2502    /// Takes ownership of the frame.
2503    #[must_use]
2504    pub fn into_frame(self) -> AVFrame {
2505        self.frame
2506    }
2507}
2508
2509impl std::ops::Deref for DecodedFrame {
2510    type Target = AVFrame;
2511
2512    fn deref(&self) -> &AVFrame {
2513        &self.frame
2514    }
2515}
2516
2517impl fmt::Debug for DecodedFrame {
2518    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2519        formatter
2520            .debug_struct("DecodedFrame")
2521            .field("format", &self.frame.format)
2522            .field("width", &self.frame.width)
2523            .field("height", &self.frame.height)
2524            .field("pts", &self.frame.pts)
2525            .field("written", &self.written)
2526            .finish_non_exhaustive()
2527    }
2528}
2529
2530/// Whether `decoder`'s frame buffers are fully initialized, so they may be shared.
2531///
2532/// The default `get_buffer2` uses zeroed pools. Wrapped external decoders (`wrapper_name`, such as
2533/// libdav1d) and replaced `get_buffer2` callbacks do not qualify.
2534fn decoder_frames_are_initialized(decoder: &AVCodecContext) -> bool {
2535    static DEFAULT_GET_BUFFER2: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2536    // Read the default from a new context; Rust's address of the function could be a linker stub.
2537    let default = *DEFAULT_GET_BUFFER2.get_or_init(|| {
2538        // SAFETY: a context allocated without a codec is only read and then freed.
2539        unsafe {
2540            let mut context = ffi::avcodec_alloc_context3(ptr::null());
2541            let get_buffer2 = context
2542                .as_ref()
2543                .and_then(|context| context.get_buffer2)
2544                .map_or(0, |function| function as usize);
2545            ffi::avcodec_free_context(&raw mut context);
2546            get_buffer2
2547        }
2548    });
2549    // SAFETY: a context's `codec` is null or a static, read-only description.
2550    let wrapped =
2551        unsafe { decoder.codec.as_ref() }.is_none_or(|codec| !codec.wrapper_name.is_null());
2552    let get_buffer2 = decoder.get_buffer2.map_or(0, |function| function as usize);
2553    !wrapped && default != 0 && get_buffer2 == default
2554}
2555
2556/// The planes of `frame`; `share` only for fully initialized frames.
2557fn frame_yuv_planes(frame: &AVFrame, share: bool) -> Result<Option<YuvPlanes>, BridgeError> {
2558    let Some(layout) = yuv_layout(frame.format) else {
2559        return Ok(None);
2560    };
2561    let width =
2562        u32::try_from(frame.width).map_err(|_| BridgeError::InvalidInput("negative YUV width"))?;
2563    let height = u32::try_from(frame.height)
2564        .map_err(|_| BridgeError::InvalidInput("negative YUV height"))?;
2565    if width == 0 || height == 0 {
2566        return Err(BridgeError::InvalidInput("empty YUV frame"));
2567    }
2568    let bytes = layout.bytes_per_sample();
2569    let chroma_width = width.div_ceil(1 << layout.chroma_shift_x);
2570    let chroma_height = height.div_ceil(1 << layout.chroma_shift_y);
2571    // Only a vouched-for, reference-counted frame is shared; `AVFrame::clone` adds buffer refs.
2572    let shared =
2573        (share && !frame.buf[0].is_null()).then(|| std::sync::Arc::new(SharedFrame(frame.clone())));
2574    let copy = |index: usize,
2575                samples: u32,
2576                pairs: u32,
2577                rows: u32,
2578                context: &'static str|
2579     -> Result<FramePlane, BridgeError> {
2580        let row_bytes = samples
2581            .checked_mul(bytes)
2582            .and_then(|row| row.checked_mul(pairs))
2583            .ok_or(BridgeError::InvalidInput(context))?;
2584        if let Some(view) = shared
2585            .as_ref()
2586            .and_then(|frame| PlaneView::new(frame, index, row_bytes, rows))
2587        {
2588            let stride =
2589                u32::try_from(view.stride).map_err(|_| BridgeError::InvalidInput(context))?;
2590            return Ok(FramePlane {
2591                bytes: bytes::Bytes::from_owner(view),
2592                stride,
2593                width: samples,
2594                height: rows,
2595            });
2596        }
2597        Ok(FramePlane {
2598            bytes: copy_video_plane(frame, index, row_bytes, rows, context)?.into(),
2599            stride: row_bytes,
2600            width: samples,
2601            height: rows,
2602        })
2603    };
2604    let mut planes = vec![copy(0, width, 1, height, "invalid Y plane")?];
2605    if layout.interleaved_chroma {
2606        planes.push(copy(1, chroma_width, 2, chroma_height, "invalid UV plane")?);
2607    } else {
2608        planes.push(copy(1, chroma_width, 1, chroma_height, "invalid U plane")?);
2609        planes.push(copy(2, chroma_width, 1, chroma_height, "invalid V plane")?);
2610    }
2611    Ok(Some(YuvPlanes {
2612        layout,
2613        width,
2614        height,
2615        planes,
2616    }))
2617}
2618
2619/// A decoded frame whose buffers several plane views share.
2620struct SharedFrame(AVFrame);
2621
2622// SAFETY: the wrapped frame is only read. FFmpeg never writes to a buffer with more than one
2623// reference, so nothing mutates it while shared.
2624unsafe impl Sync for SharedFrame {}
2625
2626/// `stride * rows` bytes of one plane of a fully written [`SharedFrame`], which it keeps alive.
2627struct PlaneView {
2628    frame: std::sync::Arc<SharedFrame>,
2629    data: *const u8,
2630    len: usize,
2631    stride: usize,
2632}
2633
2634// SAFETY: the view reads immutable memory in `frame`'s buffers, which it keeps alive;
2635// `SharedFrame` is `Send + Sync`.
2636unsafe impl Send for PlaneView {}
2637
2638impl PlaneView {
2639    /// `None` unless the linesize is positive, covers `row_bytes`, and all rows lie in one buffer.
2640    fn new(
2641        frame: &std::sync::Arc<SharedFrame>,
2642        index: usize,
2643        row_bytes: u32,
2644        rows: u32,
2645    ) -> Option<Self> {
2646        let inner = &frame.0;
2647        let data = inner.data[index].cast_const();
2648        let stride = usize::try_from(inner.linesize[index]).ok()?;
2649        let row_bytes = usize::try_from(row_bytes).ok()?;
2650        if data.is_null() || stride < row_bytes || rows == 0 {
2651            return None;
2652        }
2653        let len = stride.checked_mul(usize::try_from(rows).ok()?)?;
2654        in_frame_buffer(inner, data as usize, len).then(|| Self {
2655            frame: std::sync::Arc::clone(frame),
2656            data,
2657            len,
2658            stride,
2659        })
2660    }
2661}
2662
2663impl AsRef<[u8]> for PlaneView {
2664    fn as_ref(&self) -> &[u8] {
2665        let _ = &self.frame;
2666        // SAFETY: `new` checked `data..data + len` lies in a buffer of the frame `self` holds.
2667        unsafe { slice::from_raw_parts(self.data, self.len) }
2668    }
2669}
2670
2671/// Copies plane `index` of `frame`, refusing rows outside the frame's buffers when it has any.
2672fn copy_video_plane(
2673    frame: &AVFrame,
2674    index: usize,
2675    width: u32,
2676    height: u32,
2677    context: &'static str,
2678) -> Result<Vec<u8>, BridgeError> {
2679    let (data, linesize) = (frame.data[index].cast_const(), frame.linesize[index]);
2680    let has_buffers = frame.buf.iter().any(|buffer| !buffer.is_null());
2681    if has_buffers && !plane_rows_in_frame_buffer(frame, data, linesize, width, height) {
2682        return Err(BridgeError::InvalidInput(context));
2683    }
2684    // SAFETY: the rows lie in one of the frame's buffers, or a frame without buffers vouches for
2685    // its own planes.
2686    unsafe { copy_plane_rows(data, linesize, width, height, context) }
2687}
2688
2689/// Whether `height` rows of `width` bytes at the signed `linesize` from `data` lie in one buffer.
2690fn plane_rows_in_frame_buffer(
2691    frame: &AVFrame,
2692    data: *const u8,
2693    linesize: i32,
2694    width: u32,
2695    height: u32,
2696) -> bool {
2697    let (Ok(row_bytes), Ok(rows)) = (usize::try_from(width), usize::try_from(height)) else {
2698        return false;
2699    };
2700    let Ok(stride) = usize::try_from(linesize.unsigned_abs()) else {
2701        return false;
2702    };
2703    let Some(span) = stride
2704        .checked_mul(rows.saturating_sub(1))
2705        .and_then(|before| before.checked_add(row_bytes))
2706    else {
2707        return false;
2708    };
2709    // A negative linesize walks back from the first row, so the lowest address is the last row.
2710    let start = if linesize < 0 {
2711        (data as usize).checked_sub(span - row_bytes)
2712    } else {
2713        Some(data as usize)
2714    };
2715    !data.is_null() && rows > 0 && start.is_some_and(|start| in_frame_buffer(frame, start, span))
2716}
2717
2718/// # Safety
2719/// A non-null `data` must have `height` rows at the signed `linesize`, each `width` bytes long.
2720unsafe fn copy_plane_rows(
2721    data: *const u8,
2722    linesize: i32,
2723    width: u32,
2724    height: u32,
2725    context: &'static str,
2726) -> Result<Vec<u8>, BridgeError> {
2727    let row_bytes = usize::try_from(width).map_err(|_| BridgeError::InvalidInput(context))?;
2728    let rows = usize::try_from(height).map_err(|_| BridgeError::InvalidInput(context))?;
2729    let stride =
2730        usize::try_from(linesize.unsigned_abs()).map_err(|_| BridgeError::InvalidInput(context))?;
2731    if data.is_null() || linesize == 0 || stride < row_bytes {
2732        return Err(BridgeError::InvalidInput(context));
2733    }
2734    let byte_len = row_bytes
2735        .checked_mul(rows)
2736        .ok_or(BridgeError::InvalidInput(context))?;
2737    // Append row by row to avoid an extra zeroing pass over the buffer.
2738    let mut output = Vec::with_capacity(byte_len);
2739    let signed_stride =
2740        isize::try_from(linesize).map_err(|_| BridgeError::InvalidInput(context))?;
2741    for row in 0..rows {
2742        let row = isize::try_from(row).map_err(|_| BridgeError::InvalidInput(context))?;
2743        let offset = row
2744            .checked_mul(signed_stride)
2745            .ok_or(BridgeError::InvalidInput(context))?;
2746        // SAFETY: delegated to this function's contract; the linesize covers `row_bytes`.
2747        let source = unsafe { slice::from_raw_parts(data.offset(offset), row_bytes) };
2748        output.extend_from_slice(source);
2749    }
2750    debug_assert_eq!(output.len(), byte_len);
2751    Ok(output)
2752}
2753
2754/// Copies tightly packed RGBA bytes into an owned `FFmpeg` frame.
2755///
2756/// # Errors
2757/// Returns an `FFmpeg` error when its frame buffer cannot be allocated.
2758pub fn rgba_frame(bytes: &[u8], width: i32, height: i32) -> Result<AVFrame, BridgeError> {
2759    let row_bytes = usize::try_from(width)
2760        .ok()
2761        .and_then(|value| value.checked_mul(4))
2762        .ok_or(BridgeError::InvalidInput("RGBA row width overflow"))?;
2763    let rows =
2764        usize::try_from(height).map_err(|_| BridgeError::InvalidInput("negative RGBA height"))?;
2765    let expected = row_bytes
2766        .checked_mul(rows)
2767        .ok_or(BridgeError::InvalidInput("RGBA frame size overflow"))?;
2768    if bytes.len() != expected {
2769        return Err(BridgeError::InvalidInput("RGBA byte length mismatch"));
2770    }
2771
2772    let mut frame = AVFrame::new();
2773    frame.set_format(ffi::AV_PIX_FMT_RGBA);
2774    frame.set_width(width);
2775    frame.set_height(height);
2776    frame.get_buffer(1)?;
2777    frame.make_writable()?;
2778    let linesize = usize::try_from(frame.linesize[0])
2779        .map_err(|_| BridgeError::InvalidInput("negative RGBA linesize"))?;
2780    if frame.data[0].is_null() || linesize < row_bytes {
2781        return Err(BridgeError::InvalidInput(
2782            "RGBA destination plane is too small",
2783        ));
2784    }
2785
2786    // SAFETY: av_frame_get_buffer allocated `height` writable rows of `linesize` bytes; both slices
2787    // span one validated RGBA row.
2788    unsafe {
2789        for row in 0..rows {
2790            let destination_offset = row.checked_mul(linesize).ok_or(BridgeError::InvalidInput(
2791                "RGBA destination offset overflow",
2792            ))?;
2793            let source_offset = row
2794                .checked_mul(row_bytes)
2795                .ok_or(BridgeError::InvalidInput("RGBA source offset overflow"))?;
2796            let destination =
2797                slice::from_raw_parts_mut(frame.data[0].add(destination_offset), row_bytes);
2798            destination.copy_from_slice(&bytes[source_offset..source_offset + row_bytes]);
2799        }
2800    }
2801    Ok(frame)
2802}
2803
2804/// Copies owned planar 8-bit 4:2:0 samples into an `FFmpeg` video frame.
2805///
2806/// # Errors
2807/// Returns an error for invalid dimensions, short source planes, or an allocation failure.
2808#[allow(clippy::too_many_arguments)]
2809pub fn yuv420p_frame(
2810    y: &[u8],
2811    y_stride: u32,
2812    u: &[u8],
2813    u_stride: u32,
2814    v: &[u8],
2815    v_stride: u32,
2816    width: i32,
2817    height: i32,
2818) -> Result<AVFrame, BridgeError> {
2819    let width =
2820        u32::try_from(width).map_err(|_| BridgeError::InvalidInput("negative YUV width"))?;
2821    let height =
2822        u32::try_from(height).map_err(|_| BridgeError::InvalidInput("negative YUV height"))?;
2823    if width == 0 || height == 0 {
2824        return Err(BridgeError::InvalidInput("empty YUV frame"));
2825    }
2826    let chroma_width = width.div_ceil(2);
2827    let chroma_height = height.div_ceil(2);
2828    validate_source_plane(y, y_stride, width, height, "invalid Y source plane")?;
2829    validate_source_plane(
2830        u,
2831        u_stride,
2832        chroma_width,
2833        chroma_height,
2834        "invalid U source plane",
2835    )?;
2836    validate_source_plane(
2837        v,
2838        v_stride,
2839        chroma_width,
2840        chroma_height,
2841        "invalid V source plane",
2842    )?;
2843
2844    let mut frame = AVFrame::new();
2845    frame.set_format(ffi::AV_PIX_FMT_YUV420P);
2846    frame.set_width(i32::try_from(width).map_err(|_| BridgeError::InvalidInput("YUV width"))?);
2847    frame.set_height(i32::try_from(height).map_err(|_| BridgeError::InvalidInput("YUV height"))?);
2848    frame.get_buffer(1)?;
2849    frame.make_writable()?;
2850    copy_plane_to_frame(y, y_stride, width, height, frame.data[0], frame.linesize[0])?;
2851    copy_plane_to_frame(
2852        u,
2853        u_stride,
2854        chroma_width,
2855        chroma_height,
2856        frame.data[1],
2857        frame.linesize[1],
2858    )?;
2859    copy_plane_to_frame(
2860        v,
2861        v_stride,
2862        chroma_width,
2863        chroma_height,
2864        frame.data[2],
2865        frame.linesize[2],
2866    )?;
2867    Ok(frame)
2868}
2869
2870/// The first pixel format in `FFmpeg`'s table laid out as `layout` (`yuv420p`, not the deprecated
2871/// `yuvj420p`).
2872#[must_use]
2873pub fn yuv_pixel_format(layout: YuvPlaneLayout) -> Option<ffi::AVPixelFormat> {
2874    let mut descriptor = ptr::null();
2875    loop {
2876        // SAFETY: null starts the walk; other values are static descriptors from the previous call.
2877        descriptor = unsafe { ffi::av_pix_fmt_desc_next(descriptor) };
2878        if descriptor.is_null() {
2879            return None;
2880        }
2881        // SAFETY: a descriptor from the table names its own format.
2882        let format = unsafe { ffi::av_pix_fmt_desc_get_id(descriptor) };
2883        if yuv_layout(format) == Some(layout) {
2884            return Some(format);
2885        }
2886    }
2887}
2888
2889/// A `width` by `height` frame of `format` holding a copy of `planes` (bytes and stride each).
2890///
2891/// # Errors
2892/// For a format without a descriptor, the wrong plane count, or a plane smaller than the picture.
2893pub fn planar_frame(
2894    format: ffi::AVPixelFormat,
2895    planes: &[(&[u8], u32)],
2896    width: u32,
2897    height: u32,
2898) -> Result<AVFrame, BridgeError> {
2899    // SAFETY: `av_pix_fmt_desc_get` accepts any value and returns null or a static descriptor.
2900    let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
2901        .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
2902    // SAFETY: a pure computation over plain values.
2903    let count = unsafe { ffi::av_pix_fmt_count_planes(format) };
2904    if usize::try_from(count).ok() != Some(planes.len()) || width == 0 || height == 0 {
2905        return Err(BridgeError::InvalidInput(
2906            "planes do not match the pixel format",
2907        ));
2908    }
2909    let signed = |value: u32| {
2910        i32::try_from(value).map_err(|_| BridgeError::InvalidInput("frame size overflow"))
2911    };
2912    let mut frame = AVFrame::new();
2913    frame.set_format(format);
2914    frame.set_width(signed(width)?);
2915    frame.set_height(signed(height)?);
2916    frame.get_buffer(1)?;
2917    frame.make_writable()?;
2918    for (index, (bytes, stride)) in planes.iter().enumerate() {
2919        let plane = i32::try_from(index).unwrap_or(i32::MAX);
2920        // SAFETY: a pure computation over plain values.
2921        let row_bytes = unsafe { ffi::av_image_get_linesize(format, signed(width)?, plane) };
2922        let row_bytes = u32::try_from(row_bytes).map_err(|_| BridgeError::FfmpegCode(row_bytes))?;
2923        let rows = if index == 0 || index == 3 {
2924            height
2925        } else {
2926            height.div_ceil(1 << descriptor.log2_chroma_h)
2927        };
2928        validate_source_plane(bytes, *stride, row_bytes, rows, "invalid source plane")?;
2929        copy_plane_to_frame(
2930            bytes,
2931            *stride,
2932            row_bytes,
2933            rows,
2934            frame.data[index],
2935            frame.linesize[index],
2936        )?;
2937    }
2938    Ok(frame)
2939}
2940
2941fn validate_source_plane(
2942    bytes: &[u8],
2943    stride: u32,
2944    width: u32,
2945    height: u32,
2946    context: &'static str,
2947) -> Result<(), BridgeError> {
2948    let required = usize::try_from(stride).ok().and_then(|stride| {
2949        usize::try_from(height)
2950            .ok()
2951            .and_then(|height| stride.checked_mul(height))
2952    });
2953    if stride < width || required != Some(bytes.len()) {
2954        Err(BridgeError::InvalidInput(context))
2955    } else {
2956        Ok(())
2957    }
2958}
2959
2960fn copy_plane_to_frame(
2961    source: &[u8],
2962    source_stride: u32,
2963    width: u32,
2964    height: u32,
2965    destination: *mut u8,
2966    destination_stride: i32,
2967) -> Result<(), BridgeError> {
2968    let row_bytes =
2969        usize::try_from(width).map_err(|_| BridgeError::InvalidInput("YUV row width overflow"))?;
2970    let rows =
2971        usize::try_from(height).map_err(|_| BridgeError::InvalidInput("YUV row count overflow"))?;
2972    let source_stride = usize::try_from(source_stride)
2973        .map_err(|_| BridgeError::InvalidInput("YUV source stride overflow"))?;
2974    let destination_stride = usize::try_from(destination_stride)
2975        .map_err(|_| BridgeError::InvalidInput("negative YUV destination stride"))?;
2976    if destination.is_null() || destination_stride < row_bytes {
2977        return Err(BridgeError::InvalidInput(
2978            "YUV destination plane is too small",
2979        ));
2980    }
2981    for row in 0..rows {
2982        let source_offset = row
2983            .checked_mul(source_stride)
2984            .ok_or(BridgeError::InvalidInput("YUV source offset overflow"))?;
2985        let destination_offset = row
2986            .checked_mul(destination_stride)
2987            .ok_or(BridgeError::InvalidInput("YUV destination offset overflow"))?;
2988        // SAFETY: the destination has `height` writable rows covering `width` bytes, and the source
2989        // length was checked against its stride and row count.
2990        unsafe {
2991            ptr::copy_nonoverlapping(
2992                source.as_ptr().add(source_offset),
2993                destination.add(destination_offset),
2994                row_bytes,
2995            );
2996        }
2997    }
2998    Ok(())
2999}
3000
3001/// Copies planar `f32` samples into an audio frame of `format` (`FLTP`, `FLT` or `S16`). 16-bit
3002/// samples are clamped to [-1, 1] and rounded.
3003///
3004/// # Errors
3005/// Returns an error for mismatched channels, invalid dimensions, another sample format, or an
3006/// allocation failure.
3007pub fn audio_frame(
3008    channels: &[Vec<f32>],
3009    format: ffi::AVSampleFormat,
3010    sample_rate: i32,
3011    pts: i64,
3012) -> Result<AVFrame, BridgeError> {
3013    let Some(samples) = channels.first().map(Vec::len) else {
3014        return Err(BridgeError::InvalidInput("invalid planar audio shape"));
3015    };
3016    if sample_rate <= 0
3017        || samples == 0
3018        || channels.len() > ffi::AV_NUM_DATA_POINTERS as usize
3019        || channels.iter().any(|channel| channel.len() != samples)
3020    {
3021        return Err(BridgeError::InvalidInput(
3022            "planar audio channel lengths differ",
3023        ));
3024    }
3025    let sample_bytes = match format {
3026        ffi::AV_SAMPLE_FMT_FLTP | ffi::AV_SAMPLE_FMT_FLT => size_of::<f32>(),
3027        ffi::AV_SAMPLE_FMT_S16 => size_of::<i16>(),
3028        _ => return Err(BridgeError::InvalidInput("unsupported audio sample format")),
3029    };
3030    let planar = format == ffi::AV_SAMPLE_FMT_FLTP;
3031    let channel_count = i32::try_from(channels.len())
3032        .map_err(|_| BridgeError::InvalidInput("audio channel count overflow"))?;
3033    let sample_count = i32::try_from(samples)
3034        .map_err(|_| BridgeError::InvalidInput("audio sample count overflow"))?;
3035    let mut frame = AVFrame::new();
3036    frame.set_format(format);
3037    frame.set_ch_layout(
3038        rsmpeg::avutil::AVChannelLayout::from_nb_channels(channel_count).into_inner(),
3039    );
3040    frame.set_sample_rate(sample_rate);
3041    frame.set_nb_samples(sample_count);
3042    frame.set_pts(pts);
3043    frame.set_time_base(ffi::AVRational {
3044        num: 1,
3045        den: sample_rate,
3046    });
3047    frame.get_buffer(0)?;
3048    frame.make_writable()?;
3049    let plane_bytes = samples
3050        .checked_mul(sample_bytes)
3051        .and_then(|bytes| bytes.checked_mul(if planar { 1 } else { channels.len() }))
3052        .ok_or(BridgeError::InvalidInput("audio plane byte count overflow"))?;
3053    let plane_capacity = usize::try_from(frame.linesize[0]).unwrap_or(0);
3054    if plane_capacity < plane_bytes {
3055        return Err(BridgeError::InvalidInput(
3056            "audio plane capacity is too small",
3057        ));
3058    }
3059    let planes = if planar { channels.len() } else { 1 };
3060    if frame.data[..planes].iter().any(|plane| plane.is_null()) {
3061        return Err(BridgeError::InvalidInput("audio plane pointer is null"));
3062    }
3063    if planar {
3064        for (index, source) in channels.iter().enumerate() {
3065            // SAFETY: av_frame_get_buffer allocated one writable plane per channel of `linesize[0]`
3066            // bytes, checked above to hold the channel.
3067            unsafe {
3068                ptr::copy_nonoverlapping(
3069                    source.as_ptr().cast::<u8>(),
3070                    frame.data[index],
3071                    plane_bytes,
3072                );
3073            }
3074        }
3075        return Ok(frame);
3076    }
3077    // SAFETY: the single interleaved plane was checked to hold every sample and is unshared.
3078    let plane = unsafe { std::slice::from_raw_parts_mut(frame.data[0], plane_bytes) };
3079    let interleaved = (0..samples).flat_map(|sample| channels.iter().map(move |c| c[sample]));
3080    if format == ffi::AV_SAMPLE_FMT_FLT {
3081        for (bytes, value) in plane.as_chunks_mut::<4>().0.iter_mut().zip(interleaved) {
3082            *bytes = value.to_ne_bytes();
3083        }
3084    } else {
3085        for (bytes, value) in plane.as_chunks_mut::<2>().0.iter_mut().zip(interleaved) {
3086            // In range after the clamp, so the cast cannot truncate.
3087            #[allow(clippy::cast_possible_truncation)]
3088            let value = (value.clamp(-1.0, 1.0) * 32_767.0).round() as i16;
3089            *bytes = value.to_ne_bytes();
3090        }
3091    }
3092    Ok(frame)
3093}
3094
3095/// The `AVChannel` of each channel of `layout`, in order; empty for `AV_CHANNEL_ORDER_UNSPEC`.
3096///
3097/// Takes rsmpeg's wrapper because a bare `AVChannelLayout` can carry a forged channel map:
3098///
3099/// ```compile_fail,E0308
3100/// use rsmpeg::ffi;
3101/// let forged = ffi::AVChannelLayout {
3102///     order: ffi::AV_CHANNEL_ORDER_CUSTOM,
3103///     nb_channels: 4,
3104///     u: ffi::AVChannelLayout__bindgen_ty_1 { map: 0x10 as *mut _ },
3105///     opaque: std::ptr::null_mut(),
3106/// };
3107/// alpha2_ffmpeg_bridge::channel_layout_channels(&forged);
3108/// ```
3109#[must_use]
3110pub fn channel_layout_channels(layout: &rsmpeg::avutil::AVChannelLayout) -> Vec<ffi::AVChannel> {
3111    if layout.order == ffi::AV_CHANNEL_ORDER_UNSPEC {
3112        return Vec::new();
3113    }
3114    let channels = u32::try_from(layout.nb_channels).unwrap_or(0);
3115    (0..channels)
3116        .map(|index| {
3117            layout
3118                .channel_from_index(index)
3119                .unwrap_or(ffi::AV_CHAN_NONE)
3120        })
3121        .collect()
3122}
3123
3124/// A channel layout of `channels` in order, native when possible, else custom.
3125///
3126/// # Errors
3127/// Returns an error for no channels or when `FFmpeg` cannot allocate or retype the layout.
3128pub fn channel_layout_of(
3129    channels: &[ffi::AVChannel],
3130) -> Result<rsmpeg::avutil::AVChannelLayout, BridgeError> {
3131    let count = i32::try_from(channels.len())
3132        .ok()
3133        .filter(|count| *count > 0)
3134        .ok_or(BridgeError::InvalidInput("a channel layout needs channels"))?;
3135    let mut raw = std::mem::MaybeUninit::<ffi::AVChannelLayout>::zeroed();
3136    // SAFETY: `custom_init` gives the zeroed layout a map of `count` entries, all written below.
3137    let initialized = unsafe { ffi::av_channel_layout_custom_init(raw.as_mut_ptr(), count) };
3138    if initialized < 0 {
3139        return Err(BridgeError::FfmpegCode(initialized));
3140    }
3141    // SAFETY: initialized above; from here `layout` owns it and uninitializes it on drop.
3142    let mut layout = unsafe { rsmpeg::avutil::AVChannelLayout::new(raw.assume_init()) };
3143    for (index, channel) in channels.iter().enumerate() {
3144        // SAFETY: a custom layout's map holds `count` entries, and `index` is below it.
3145        unsafe { (*layout.u.map.add(index)).id = *channel };
3146    }
3147    let flags = i32::try_from(ffi::AV_CHANNEL_LAYOUT_RETYPE_FLAG_CANONICAL).unwrap_or(0);
3148    // SAFETY: `layout` is a valid custom layout that `retype` may rewrite in place.
3149    let retyped = unsafe {
3150        ffi::av_channel_layout_retype(layout.as_mut_ptr(), ffi::AV_CHANNEL_ORDER_UNSPEC, flags)
3151    };
3152    if retyped < 0 {
3153        return Err(BridgeError::FfmpegCode(retyped));
3154    }
3155    Ok(layout)
3156}
3157
3158/// Copies a packed `AV_SAMPLE_FMT_FLT` frame into an owned interleaved vector.
3159///
3160/// # Errors
3161/// Returns an error if the frame format, dimensions, or buffer is invalid.
3162pub fn audio_f32_interleaved(frame: &AVFrame) -> Result<Vec<f32>, BridgeError> {
3163    if frame.format != ffi::AV_SAMPLE_FMT_FLT || frame.nb_samples < 0 {
3164        return Err(BridgeError::InvalidInput(
3165            "packed audio format or sample count is invalid",
3166        ));
3167    }
3168    let channels = usize::try_from(frame.ch_layout().nb_channels)
3169        .map_err(|_| BridgeError::InvalidInput("packed audio channel count is negative"))?;
3170    let frames = usize::try_from(frame.nb_samples)
3171        .map_err(|_| BridgeError::InvalidInput("packed audio sample count is negative"))?;
3172    let samples = frames
3173        .checked_mul(channels)
3174        .ok_or(BridgeError::InvalidInput(
3175            "packed audio sample count overflow",
3176        ))?;
3177    let bytes = samples
3178        .checked_mul(size_of::<f32>())
3179        .ok_or(BridgeError::InvalidInput(
3180            "packed audio byte count overflow",
3181        ))?;
3182    if channels == 0
3183        || frame.data[0].is_null()
3184        || usize::try_from(frame.linesize[0]).unwrap_or(0) < bytes
3185    {
3186        return Err(BridgeError::InvalidInput(
3187            "packed audio plane is missing or too small",
3188        ));
3189    }
3190    let mut output = vec![0.0_f32; samples];
3191    // SAFETY: the FLT plane was checked to hold every sample, and `output` is exactly that size.
3192    unsafe {
3193        ptr::copy_nonoverlapping(frame.data[0], output.as_mut_ptr().cast::<u8>(), bytes);
3194    }
3195    Ok(output)
3196}
3197
3198/// The rotation a display matrix asks for, in `FFmpeg`'s convention.
3199#[derive(Copy, Clone, Debug, PartialEq)]
3200pub struct DisplayRotation {
3201    /// Counter-clockwise angle in degrees, in `[-180, 180]`.
3202    pub counter_clockwise_degrees: f64,
3203    /// Whether the matrix also mirrors: this rotation followed by a horizontal flip.
3204    pub flipped: bool,
3205}
3206
3207/// Reads a stream display matrix.
3208#[must_use]
3209pub fn display_rotation(parameters: &AVCodecParameters) -> Option<DisplayRotation> {
3210    let count = usize::try_from(parameters.nb_coded_side_data).ok()?;
3211    if count == 0 || count > 64 || parameters.coded_side_data.is_null() {
3212        return None;
3213    }
3214    // SAFETY: the borrowed parameters own exactly `nb_coded_side_data` entries.
3215    let entries = unsafe { slice::from_raw_parts(parameters.coded_side_data, count) };
3216    let matrix = entries.iter().find(|entry| {
3217        entry.type_ == ffi::AV_PKT_DATA_DISPLAYMATRIX
3218            && entry.size >= 9 * size_of::<i32>()
3219            && !entry.data.is_null()
3220    })?;
3221    // SAFETY: the matching side-data entry was validated to hold a complete 3x3 display matrix.
3222    unsafe { matrix_rotation(matrix.data) }
3223}
3224
3225/// Reads a frame's display matrix, such as the JPEG decoder attaches for Exif `Orientation`.
3226#[must_use]
3227pub fn frame_display_rotation(frame: &AVFrame) -> Option<DisplayRotation> {
3228    // SAFETY: `frame` is a live frame; the returned entry, if any, is owned by it for this borrow.
3229    let entry =
3230        unsafe { ffi::av_frame_get_side_data(frame.as_ptr(), ffi::AV_FRAME_DATA_DISPLAYMATRIX) };
3231    if entry.is_null() {
3232        return None;
3233    }
3234    // SAFETY: a non-null entry returned by `av_frame_get_side_data` is a valid side-data record.
3235    let entry = unsafe { &*entry };
3236    if entry.size < 9 * size_of::<i32>() || entry.data.is_null() {
3237        return None;
3238    }
3239    // SAFETY: the entry was validated to hold a complete 3x3 display matrix.
3240    unsafe { matrix_rotation(entry.data) }
3241}
3242
3243/// # Safety
3244/// `data` must point at nine readable `i32`s, aligned or not.
3245unsafe fn matrix_rotation(data: *const u8) -> Option<DisplayRotation> {
3246    let mut aligned = [0_i32; 9];
3247    // SAFETY: the caller guarantees a complete 3x3 matrix; a byte copy needs no alignment.
3248    unsafe {
3249        ptr::copy_nonoverlapping(
3250            data,
3251            aligned.as_mut_ptr().cast::<u8>(),
3252            size_of::<[i32; 9]>(),
3253        );
3254    }
3255    // `av_display_rotation_get` is meaningless for a mirroring matrix (negative 2x2 determinant),
3256    // so remove the horizontal flip first.
3257    let determinant = i64::from(aligned[0]) * i64::from(aligned[4])
3258        - i64::from(aligned[1]) * i64::from(aligned[3]);
3259    let flipped = determinant < 0;
3260    if flipped {
3261        // SAFETY: `aligned` is a complete, correctly aligned 3x3 matrix.
3262        unsafe { ffi::av_display_matrix_flip(aligned.as_mut_ptr(), 1, 0) };
3263    }
3264    // SAFETY: `aligned` is a complete, correctly aligned 3x3 display matrix.
3265    let angle = unsafe { ffi::av_display_rotation_get(aligned.as_ptr()) };
3266    angle.is_finite().then_some(DisplayRotation {
3267        counter_clockwise_degrees: angle,
3268        flipped,
3269    })
3270}
3271
3272const fn size_of<T>() -> usize {
3273    std::mem::size_of::<T>()
3274}
3275
3276/// A reusable `FFmpeg` YUV420P frame the caller writes into directly.
3277///
3278/// Avoids [`yuv420p_frame`]'s per-frame allocation and copy. [`Yuv420pFrameBuffer::begin_write`]
3279/// returns plane memory only once `FFmpeg` no longer shares the buffer; a shared buffer is left to
3280/// its holder and replaced by zeroed memory, without the old picture.
3281pub struct Yuv420pFrameBuffer {
3282    frame: AVFrame,
3283    width: usize,
3284    height: usize,
3285    /// Each plane's visible bytes per row and rows, from the pixel format descriptor.
3286    planes: Vec<(usize, usize)>,
3287}
3288
3289/// Writable plane memory for one reusable frame.
3290pub struct Yuv420pFramePlanes<'a> {
3291    /// Luma rows, `y_stride` bytes apart.
3292    pub y: &'a mut [u8],
3293    /// Distance between luma rows.
3294    pub y_stride: usize,
3295    /// Blue-difference chroma rows, `chroma_stride` bytes apart.
3296    pub u: &'a mut [u8],
3297    /// Red-difference chroma rows, `chroma_stride` bytes apart.
3298    pub v: &'a mut [u8],
3299    /// Distance between chroma rows.
3300    pub chroma_stride: usize,
3301}
3302
3303impl Yuv420pFrameBuffer {
3304    /// Allocates one reusable frame for this exact coded size.
3305    ///
3306    /// # Errors
3307    /// Returns an error for a non-positive size or a failed allocation.
3308    pub fn new(width: i32, height: i32) -> Result<Self, BridgeError> {
3309        Self::with_format(width, height, ffi::AV_PIX_FMT_YUV420P)
3310    }
3311
3312    /// Allocates one reusable frame of `format`; each plane's row bytes and rows come from the
3313    /// format's descriptor.
3314    ///
3315    /// # Errors
3316    /// Returns an error for a non-positive size, a format without planes, or a failed allocation.
3317    pub fn with_format(
3318        width: i32,
3319        height: i32,
3320        format: ffi::AVPixelFormat,
3321    ) -> Result<Self, BridgeError> {
3322        let coded_width = usize::try_from(width)
3323            .map_err(|_| BridgeError::InvalidInput("negative frame width"))?;
3324        let coded_height = usize::try_from(height)
3325            .map_err(|_| BridgeError::InvalidInput("negative frame height"))?;
3326        if coded_width == 0 || coded_height == 0 {
3327            return Err(BridgeError::InvalidInput("empty frame"));
3328        }
3329        let planes = plane_geometry(format, width, height)?;
3330        let frame = zeroed_frame(width, height, format)?;
3331        for (index, &(row_bytes, _)) in planes.iter().enumerate() {
3332            if frame.data[index].is_null()
3333                || plane_stride(frame.linesize[index], row_bytes).is_err()
3334            {
3335                return Err(BridgeError::InvalidInput(
3336                    "the frame's planes do not match its pixel format",
3337                ));
3338            }
3339        }
3340        Ok(Self {
3341            frame,
3342            width: coded_width,
3343            height: coded_height,
3344            planes,
3345        })
3346    }
3347
3348    /// Each plane's visible bytes per row and rows, in `FFmpeg`'s plane order.
3349    #[must_use]
3350    pub fn planes(&self) -> &[(usize, usize)] {
3351        &self.planes
3352    }
3353
3354    /// Each plane's memory and stride after making the frame unshared, for any format.
3355    ///
3356    /// # Errors
3357    /// As [`Self::begin_write`].
3358    pub fn begin_write_planes(&mut self) -> Result<Vec<(&mut [u8], usize)>, BridgeError> {
3359        self.make_writable()?;
3360        let mut written = Vec::with_capacity(self.planes.len());
3361        for (index, &(row_bytes, rows)) in self.planes.iter().enumerate() {
3362            let stride = plane_stride(self.frame.linesize[index], row_bytes)?;
3363            // SAFETY: `writable_plane` checks the rows lie in one of the frame's buffers, and
3364            // `make_writable` left this frame their sole owner.
3365            let plane = unsafe { writable_plane(&self.frame, index, stride, row_bytes, rows)? };
3366            written.push((plane, stride));
3367        }
3368        Ok(written)
3369    }
3370
3371    /// Whether another reference, such as an encoder's, still holds this frame's memory.
3372    ///
3373    /// # Errors
3374    /// Returns an error when `FFmpeg` cannot tell.
3375    pub fn is_shared(&self) -> Result<bool, BridgeError> {
3376        Ok(!self.frame.is_writable().map_err(BridgeError::Ffmpeg)?)
3377    }
3378
3379    fn make_writable(&mut self) -> Result<(), BridgeError> {
3380        if self.is_shared()? {
3381            let mut replacement =
3382                zeroed_frame(self.frame.width, self.frame.height, self.frame.format)?;
3383            // SAFETY: both frames are live, `replacement` unshared and `self.frame` only read.
3384            let status =
3385                unsafe { ffi::av_frame_copy_props(replacement.as_mut_ptr(), self.frame.as_ptr()) };
3386            if status < 0 {
3387                return Err(BridgeError::FfmpegCode(status));
3388            }
3389            self.frame = replacement;
3390        }
3391        Ok(())
3392    }
3393
3394    /// Luma width and height in pixels.
3395    #[must_use]
3396    pub const fn dimensions(&self) -> (usize, usize) {
3397        (self.width, self.height)
3398    }
3399
3400    /// Returns the plane memory to overwrite, after making the frame unshared.
3401    ///
3402    /// # Errors
3403    /// Returns an error when the buffer cannot be made writable or its planes changed layout.
3404    pub fn begin_write(&mut self) -> Result<Yuv420pFramePlanes<'_>, BridgeError> {
3405        if self.frame.format != ffi::AV_PIX_FMT_YUV420P {
3406            return Err(BridgeError::InvalidInput("the frame is not YUV420P"));
3407        }
3408        let mut planes = self.begin_write_planes()?.into_iter();
3409        let (Some((y, y_stride)), Some((u, u_stride)), Some((v, v_stride))) =
3410            (planes.next(), planes.next(), planes.next())
3411        else {
3412            return Err(BridgeError::InvalidInput("the frame is not YUV420P"));
3413        };
3414        if u_stride != v_stride {
3415            return Err(BridgeError::InvalidInput("mismatched chroma strides"));
3416        }
3417        Ok(Yuv420pFramePlanes {
3418            y,
3419            y_stride,
3420            u,
3421            v,
3422            chroma_stride: u_stride,
3423        })
3424    }
3425
3426    /// Stamps the presentation timestamp this frame will be encoded with.
3427    pub fn set_presentation(&mut self, pts: i64, time_base: ffi::AVRational) {
3428        self.frame.set_pts(pts);
3429        self.frame.set_time_base(time_base);
3430    }
3431
3432    /// The frame to hand to an encoder.
3433    #[must_use]
3434    pub const fn frame(&self) -> &AVFrame {
3435        &self.frame
3436    }
3437
3438    /// Bytes of the visible planes, without row padding.
3439    #[must_use]
3440    pub fn visible_bytes(&self) -> usize {
3441        if self.planes.is_empty() {
3442            let chroma = self.width.div_ceil(2) * self.height.div_ceil(2);
3443            return self.width * self.height + 2 * chroma;
3444        }
3445        self.planes
3446            .iter()
3447            .map(|&(row_bytes, rows)| row_bytes * rows)
3448            .sum()
3449    }
3450
3451    /// Coded luma dimensions this buffer was allocated for.
3452    #[must_use]
3453    pub const fn size(&self) -> (usize, usize) {
3454        (self.width, self.height)
3455    }
3456}
3457
3458/// A frame of `format` with tightly packed rows, every byte of it zero.
3459fn zeroed_frame(
3460    width: i32,
3461    height: i32,
3462    format: ffi::AVPixelFormat,
3463) -> Result<AVFrame, BridgeError> {
3464    let mut frame = AVFrame::new();
3465    frame.set_format(format);
3466    frame.set_width(width);
3467    frame.set_height(height);
3468    frame.get_buffer(1)?;
3469    for buffer in frame.buf {
3470        // SAFETY: a non-null `AVFrame::buf` entry is live, and this new frame is its only owner.
3471        if let Some(buffer) = unsafe { buffer.as_ref() } {
3472            // SAFETY: as above.
3473            unsafe { ptr::write_bytes(buffer.data, 0, buffer.size) };
3474        }
3475    }
3476    Ok(frame)
3477}
3478
3479impl fmt::Debug for Yuv420pFrameBuffer {
3480    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3481        formatter
3482            .debug_struct("Yuv420pFrameBuffer")
3483            .field("width", &self.width)
3484            .field("height", &self.height)
3485            .finish_non_exhaustive()
3486    }
3487}
3488
3489fn plane_stride(linesize: i32, width: usize) -> Result<usize, BridgeError> {
3490    let stride = usize::try_from(linesize)
3491        .map_err(|_| BridgeError::InvalidInput("negative frame linesize"))?;
3492    if stride < width {
3493        return Err(BridgeError::InvalidInput(
3494            "frame linesize is below its width",
3495        ));
3496    }
3497    Ok(stride)
3498}
3499
3500/// Plane `index` of `frame` as `rows` rows of `stride` bytes, the last one `row_bytes` long.
3501///
3502/// # Safety
3503/// The caller must solely own the frame's buffers for the slice's lifetime.
3504unsafe fn writable_plane<'a>(
3505    frame: &AVFrame,
3506    index: usize,
3507    stride: usize,
3508    row_bytes: usize,
3509    rows: usize,
3510) -> Result<&'a mut [u8], BridgeError> {
3511    let data = frame.data[index];
3512    if data.is_null() {
3513        return Err(BridgeError::InvalidInput("frame plane is null"));
3514    }
3515    let len = stride
3516        .checked_mul(rows.saturating_sub(1))
3517        .and_then(|before| before.checked_add(row_bytes))
3518        .ok_or(BridgeError::InvalidInput("frame plane size overflow"))?;
3519    if !in_frame_buffer(frame, data as usize, len) {
3520        return Err(BridgeError::InvalidInput(
3521            "frame plane extends past its buffer",
3522        ));
3523    }
3524    // SAFETY: the range lies in one of the frame's buffers; exclusivity is the caller's.
3525    Ok(unsafe { slice::from_raw_parts_mut(data, len) })
3526}
3527
3528/// Whether `len` bytes from address `start` lie inside one of `frame`'s buffers.
3529fn in_frame_buffer(frame: &AVFrame, start: usize, len: usize) -> bool {
3530    let Some(end) = start.checked_add(len) else {
3531        return false;
3532    };
3533    frame.buf.iter().any(|buffer| {
3534        // SAFETY: a non-null `AVFrame::buf` entry is a live `AVBufferRef` the frame holds.
3535        let Some(buffer) = (unsafe { buffer.as_ref() }) else {
3536            return false;
3537        };
3538        let buffer_start = buffer.data as usize;
3539        buffer_start
3540            .checked_add(buffer.size)
3541            .is_some_and(|buffer_end| buffer_start <= start && end <= buffer_end)
3542    })
3543}
3544
3545/// Visible bytes per row and rows of each plane of a `width` by `height` frame of `format`.
3546fn plane_geometry(
3547    format: ffi::AVPixelFormat,
3548    width: i32,
3549    height: i32,
3550) -> Result<Vec<(usize, usize)>, BridgeError> {
3551    // SAFETY: `av_pix_fmt_desc_get` accepts any value and returns null or a static descriptor.
3552    let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
3553        .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
3554    // SAFETY: a pure computation over plain values.
3555    let count = unsafe { ffi::av_pix_fmt_count_planes(format) };
3556    let count = usize::try_from(count)
3557        .ok()
3558        .filter(|count| (1..=4).contains(count))
3559        .ok_or(BridgeError::InvalidInput("pixel format has no planes"))?;
3560    let rows = usize::try_from(height).map_err(|_| BridgeError::InvalidInput("negative height"))?;
3561    (0..count)
3562        .map(|index| {
3563            let plane = i32::try_from(index).unwrap_or(i32::MAX);
3564            // SAFETY: a pure computation over plain values.
3565            let row_bytes = unsafe { ffi::av_image_get_linesize(format, width, plane) };
3566            let row_bytes =
3567                usize::try_from(row_bytes).map_err(|_| BridgeError::FfmpegCode(row_bytes))?;
3568            let rows = if index == 1 || index == 2 {
3569                rows.div_ceil(1 << descriptor.log2_chroma_h)
3570            } else {
3571                rows
3572            };
3573            Ok((row_bytes, rows))
3574        })
3575        .collect()
3576}
3577
3578#[cfg(all(test, target_os = "linux", feature = "hwdevice"))]
3579mod vulkan_shim_tests;
3580
3581#[cfg(all(test, target_os = "linux", feature = "hwdevice"))]
3582mod vulkan_access_tests;
3583
3584#[cfg(test)]
3585mod tests;