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/// Tags `frame` with `FFmpeg`'s colour properties, which some encoders (`ProRes`) write into each
2031/// frame header.
2032pub fn set_frame_color(
2033    frame: &mut rsmpeg::avutil::AVFrame,
2034    (primaries, transfer, space, range): (
2035        ffi::AVColorPrimaries,
2036        ffi::AVColorTransferCharacteristic,
2037        ffi::AVColorSpace,
2038        ffi::AVColorRange,
2039    ),
2040) {
2041    let raw = frame.as_mut_ptr();
2042    // SAFETY: `frame` is mutably borrowed; the fields are plain values.
2043    unsafe {
2044        (*raw).color_primaries = primaries;
2045        (*raw).color_trc = transfer;
2046        (*raw).colorspace = space;
2047        (*raw).color_range = range;
2048    }
2049}
2050
2051/// Gives `packet` side data of `kind` holding `data`, replacing any it had.
2052///
2053/// # Errors
2054/// When the side data cannot be allocated or `data` is too large.
2055pub fn set_packet_side_data(
2056    packet: &mut rsmpeg::avcodec::AVPacket,
2057    kind: ffi::AVPacketSideDataType,
2058    data: &[u8],
2059) -> Result<(), BridgeError> {
2060    let _ = take_packet_side_data(packet, kind);
2061    // SAFETY: `packet` is mutably borrowed; `av_packet_new_side_data` returns null or a padded
2062    // entry of `data.len()` bytes.
2063    let entry = unsafe { ffi::av_packet_new_side_data(packet.as_mut_ptr(), kind, data.len()) };
2064    if entry.is_null() {
2065        return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2066    }
2067    // SAFETY: the entry just made holds `data.len()` writable bytes.
2068    unsafe { ptr::copy_nonoverlapping(data.as_ptr(), entry, data.len()) };
2069    Ok(())
2070}
2071
2072/// Replaces the extradata of `output`'s stream `index` before the header is written.
2073///
2074/// rsmpeg exposes an output's streams read-only. `FFmpeg` needs padded `av_malloc` memory here, not
2075/// a Rust buffer.
2076///
2077/// # Errors
2078/// When there is no stream `index`, or `data` is too large or cannot be allocated.
2079pub fn set_output_stream_extradata(
2080    output: &mut rsmpeg::avformat::AVFormatContextOutput,
2081    index: usize,
2082    data: &[u8],
2083) -> Result<(), BridgeError> {
2084    let parameters = output
2085        .streams()
2086        .get(index)
2087        .ok_or(BridgeError::InvalidInput("the output has no such stream"))?
2088        .codecpar;
2089    let size = i32::try_from(data.len())
2090        .map_err(|_| BridgeError::InvalidInput("extradata is larger than FFmpeg holds"))?;
2091    let padding = usize::try_from(ffi::AV_INPUT_BUFFER_PADDING_SIZE).unwrap_or(64);
2092    // SAFETY: `av_mallocz` returns null or a zeroed buffer of the size asked for.
2093    let buffer = unsafe { ffi::av_mallocz(data.len() + padding) }.cast::<u8>();
2094    if buffer.is_null() {
2095        return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2096    }
2097    // SAFETY: `buffer` holds `data.len()` writable bytes and does not overlap `data`.
2098    unsafe { ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len()) };
2099    // SAFETY: the stream owns its codec parameters and the output is mutably borrowed. The old
2100    // extradata is null or `av_malloc`ed and is freed; the parameters now own `buffer`.
2101    unsafe {
2102        ffi::av_freep((&raw mut (*parameters).extradata).cast());
2103        (*parameters).extradata = buffer;
2104        (*parameters).extradata_size = size;
2105    }
2106    Ok(())
2107}
2108
2109/// A packet holding a copy of `data`, every other field at its default.
2110///
2111/// # Errors
2112/// When `data` is too large or the packet cannot be allocated.
2113pub fn packet_from_bytes(data: &[u8]) -> Result<rsmpeg::avcodec::AVPacket, BridgeError> {
2114    let size = i32::try_from(data.len())
2115        .map_err(|_| BridgeError::InvalidInput("a packet is larger than FFmpeg holds"))?;
2116    let mut packet = rsmpeg::avcodec::AVPacket::new();
2117    // SAFETY: `packet` is fresh and empty; `av_new_packet` gives it a padded buffer or fails.
2118    let status = unsafe { ffi::av_new_packet(packet.as_mut_ptr(), size) };
2119    if status < 0 {
2120        return Err(BridgeError::FfmpegCode(status));
2121    }
2122    if !data.is_empty() {
2123        // SAFETY: the packet's buffer holds `size` writable bytes and does not overlap `data`.
2124        unsafe { ptr::copy_nonoverlapping(data.as_ptr(), packet.data, data.len()) };
2125    }
2126    Ok(packet)
2127}
2128
2129/// Replaces `packet`'s payload with `data`, no longer than it, keeping timestamps and side data.
2130///
2131/// # Errors
2132/// When `data` is longer than the payload or the buffer cannot be made writable.
2133pub fn shrink_packet_to(
2134    packet: &mut rsmpeg::avcodec::AVPacket,
2135    data: &[u8],
2136) -> Result<(), BridgeError> {
2137    let size = i32::try_from(data.len())
2138        .ok()
2139        .filter(|size| *size <= packet.size)
2140        .ok_or(BridgeError::InvalidInput("a packet cannot grow in place"))?;
2141    // SAFETY: `packet` is live; `av_packet_make_writable` gives it an unshared buffer of its size.
2142    let status = unsafe { ffi::av_packet_make_writable(packet.as_mut_ptr()) };
2143    if status < 0 {
2144        return Err(BridgeError::FfmpegCode(status));
2145    }
2146    if !data.is_empty() {
2147        // SAFETY: the writable buffer holds at least `data.len()` bytes and cannot overlap `data`.
2148        unsafe { ptr::copy_nonoverlapping(data.as_ptr(), packet.data, data.len()) };
2149    }
2150    // SAFETY: `size` is not above the packet's size; FFmpeg zeroes the padding after it.
2151    unsafe { ffi::av_shrink_packet(packet.as_mut_ptr(), size) };
2152    Ok(())
2153}
2154
2155/// Codec parameters for a video stream not produced by an `FFmpeg` encoder.
2156#[derive(Clone, Copy, Debug)]
2157pub struct VideoStreamDescription<'a> {
2158    /// The codec.
2159    pub codec_id: ffi::AVCodecID,
2160    /// Coded width.
2161    pub width: i32,
2162    /// Coded height.
2163    pub height: i32,
2164    /// The pixel format the stream decodes to.
2165    pub pixel_format: ffi::AVPixelFormat,
2166    /// `AV_PROFILE_*` for the codec.
2167    pub profile: i32,
2168    /// The codec's level number.
2169    pub level: i32,
2170    /// Colour primaries tag.
2171    pub color_primaries: ffi::AVColorPrimaries,
2172    /// Transfer characteristics tag.
2173    pub color_trc: ffi::AVColorTransferCharacteristic,
2174    /// Matrix coefficients tag.
2175    pub color_space: ffi::AVColorSpace,
2176    /// Sample range.
2177    pub color_range: ffi::AVColorRange,
2178    /// Pixel aspect ratio; `0/1` when undeclared.
2179    pub sample_aspect_ratio: ffi::AVRational,
2180    /// Frames per second.
2181    pub frame_rate: ffi::AVRational,
2182    /// Average bitrate, `0` when unknown.
2183    pub bit_rate: i64,
2184    /// The sample description (`avcC` for H.264).
2185    pub extradata: &'a [u8],
2186}
2187
2188/// Codec parameters for a video stream `description` describes.
2189///
2190/// # Errors
2191/// When the extradata is larger than `FFmpeg` holds or cannot be allocated.
2192pub fn video_codec_parameters(
2193    description: &VideoStreamDescription<'_>,
2194) -> Result<rsmpeg::avcodec::AVCodecParameters, BridgeError> {
2195    let extradata_size = i32::try_from(description.extradata.len())
2196        .map_err(|_| BridgeError::InvalidInput("extradata is larger than FFmpeg holds"))?;
2197    let mut parameters = rsmpeg::avcodec::AVCodecParameters::new();
2198    let raw = parameters.as_mut_ptr();
2199    // SAFETY: `raw` is freshly allocated and uniquely owned; the fields are plain values.
2200    unsafe {
2201        (*raw).codec_type = ffi::AVMEDIA_TYPE_VIDEO;
2202        (*raw).codec_id = description.codec_id;
2203        (*raw).width = description.width;
2204        (*raw).height = description.height;
2205        (*raw).format = description.pixel_format;
2206        (*raw).profile = description.profile;
2207        (*raw).level = description.level;
2208        (*raw).color_primaries = description.color_primaries;
2209        (*raw).color_trc = description.color_trc;
2210        (*raw).color_space = description.color_space;
2211        (*raw).color_range = description.color_range;
2212        (*raw).sample_aspect_ratio = description.sample_aspect_ratio;
2213        (*raw).framerate = description.frame_rate;
2214        (*raw).bit_rate = description.bit_rate;
2215        (*raw).field_order = ffi::AV_FIELD_PROGRESSIVE;
2216    }
2217    if !description.extradata.is_empty() {
2218        let padding = usize::try_from(ffi::AV_INPUT_BUFFER_PADDING_SIZE).unwrap_or(64);
2219        // SAFETY: `av_mallocz` returns null or a zeroed buffer of the size asked for.
2220        let buffer = unsafe { ffi::av_mallocz(description.extradata.len() + padding) }.cast::<u8>();
2221        if buffer.is_null() {
2222            return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2223        }
2224        // SAFETY: `buffer` holds the extradata's length and does not overlap it. The parameters
2225        // had no extradata and now own `buffer`.
2226        unsafe {
2227            ptr::copy_nonoverlapping(
2228                description.extradata.as_ptr(),
2229                buffer,
2230                description.extradata.len(),
2231            );
2232            (*raw).extradata = buffer;
2233            (*raw).extradata_size = extradata_size;
2234        }
2235    }
2236    Ok(parameters)
2237}
2238
2239/// Opens a bitstream filter chain in `ffmpeg -bsf` list syntax for a stream described by
2240/// `parameters` with packets in `time_base`.
2241///
2242/// rsmpeg cannot parse a list or set a filter's private options.
2243///
2244/// # Errors
2245/// Returns the `FFmpeg` status when the list does not parse, names a filter or option the runtime
2246/// lacks, or a filter refuses the stream.
2247pub fn bitstream_filter_list(
2248    spec: &CStr,
2249    parameters: &AVCodecParameters,
2250    time_base: rsmpeg::avutil::AVRational,
2251) -> Result<rsmpeg::avcodec::AVBSFContext, BridgeError> {
2252    let mut raw = ptr::null_mut();
2253    // SAFETY: `spec` is NUL-terminated; on success `raw` holds a new context taken over below.
2254    let status = unsafe { ffi::av_bsf_list_parse_str(spec.as_ptr(), &raw mut raw) };
2255    if status < 0 {
2256        return Err(BridgeError::FfmpegCode(status));
2257    }
2258    let raw = ptr::NonNull::new(raw).ok_or(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)))?;
2259    // SAFETY: `raw` was just allocated and is unshared; the wrapper frees it with `av_bsf_free`.
2260    let mut context = unsafe { rsmpeg::avcodec::AVBSFContextUninit::from_raw(raw) };
2261    // rsmpeg's `set_par_in` panics when the copy cannot allocate.
2262    // SAFETY: `par_in` is the context's own parameter set and `parameters` is live;
2263    // `avcodec_parameters_copy` deep-copies into it.
2264    let status = unsafe { ffi::avcodec_parameters_copy(context.par_in, parameters.as_ptr()) };
2265    if status < 0 {
2266        return Err(BridgeError::FfmpegCode(status));
2267    }
2268    context.set_time_base_in(time_base);
2269    context.init().map_err(BridgeError::Ffmpeg)
2270}
2271
2272/// Sets a stream's codec tag (sample entry); zero lets the muxer pick its default.
2273pub fn set_stream_codec_tag(stream: &mut rsmpeg::avformat::AVStreamMut<'_>, tag: u32) {
2274    let mut parameters = stream.codecpar_mut();
2275    // SAFETY: the mutably borrowed stream owns its codec parameters; `codec_tag` is a plain field.
2276    unsafe { (*parameters.as_mut_ptr()).codec_tag = tag };
2277}
2278
2279/// Replaces a stream's display matrix (MP4's `tkhd` matrix) with `display`'s rotation and flip, as
2280/// [`display_rotation`] reads it back.
2281///
2282/// # Errors
2283/// When the side data cannot be allocated.
2284pub fn set_stream_display_matrix(
2285    stream: &mut rsmpeg::avformat::AVStreamMut<'_>,
2286    display: DisplayRotation,
2287) -> Result<(), BridgeError> {
2288    let mut parameters = stream.codecpar_mut();
2289    let parameters = parameters.as_mut_ptr();
2290    // SAFETY: the mutably borrowed stream owns its codec parameters; `av_packet_side_data_new`
2291    // keeps the array and count consistent and returns null only on allocation failure.
2292    let entry = unsafe {
2293        ffi::av_packet_side_data_new(
2294            &raw mut (*parameters).coded_side_data,
2295            &raw mut (*parameters).nb_coded_side_data,
2296            ffi::AV_PKT_DATA_DISPLAYMATRIX,
2297            size_of::<[i32; 9]>(),
2298            0,
2299        )
2300    };
2301    if entry.is_null() {
2302        return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2303    }
2304    let mut matrix = [0_i32; 9];
2305    // `av_display_rotation_set` turns clockwise, opposite to `av_display_rotation_get`.
2306    // SAFETY: `matrix` is a complete, aligned 3x3 display matrix.
2307    unsafe {
2308        ffi::av_display_rotation_set(matrix.as_mut_ptr(), -display.counter_clockwise_degrees);
2309        if display.flipped {
2310            ffi::av_display_matrix_flip(matrix.as_mut_ptr(), 1, 0);
2311        }
2312    }
2313    // SAFETY: the new entry holds `size_of::<[i32; 9]>()` writable bytes; a byte copy needs no
2314    // alignment.
2315    unsafe {
2316        ptr::copy_nonoverlapping(
2317            matrix.as_ptr().cast::<u8>(),
2318            (*entry).data,
2319            size_of::<[i32; 9]>(),
2320        );
2321    }
2322    Ok(())
2323}
2324
2325/// Returns `FFmpeg`'s stable name for a hardware device type.
2326#[must_use]
2327pub fn hardware_device_type_name(device_type: ffi::AVHWDeviceType) -> Option<String> {
2328    // SAFETY: `av_hwdevice_get_type_name` accepts any value and returns null or a static C string.
2329    let name = unsafe { ffi::av_hwdevice_get_type_name(device_type) };
2330    if name.is_null() {
2331        None
2332    } else {
2333        // SAFETY: non-null return values obey the FFmpeg string contract above.
2334        Some(
2335            unsafe { CStr::from_ptr(name) }
2336                .to_string_lossy()
2337                .into_owned(),
2338        )
2339    }
2340}
2341
2342/// The plane layout of a YCbCr format the renderer samples directly, or `None`.
2343///
2344/// Accepts three components of one depth from 8 to 16 bits, chroma subsampled by at most four per
2345/// axis, three planes or U, V interleaved in the second, native byte order, low- or (above eight
2346/// bits) high-bit aligned. Rejects RGB, alpha, gray, palette, Bayer, float, XYZ, bitstream,
2347/// hardware formats and NV21.
2348#[must_use]
2349pub fn yuv_layout(format: ffi::AVPixelFormat) -> Option<YuvPlaneLayout> {
2350    if format == ffi::AV_PIX_FMT_NONE {
2351        return None;
2352    }
2353    // SAFETY: `av_pix_fmt_desc_get` accepts any value and returns null or a static descriptor.
2354    let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }?;
2355    let foreign_endian = if cfg!(target_endian = "little") {
2356        ffi::AV_PIX_FMT_FLAG_BE
2357    } else {
2358        0
2359    };
2360    let rejected = foreign_endian
2361        | ffi::AV_PIX_FMT_FLAG_PAL
2362        | ffi::AV_PIX_FMT_FLAG_BITSTREAM
2363        | ffi::AV_PIX_FMT_FLAG_HWACCEL
2364        | ffi::AV_PIX_FMT_FLAG_RGB
2365        | ffi::AV_PIX_FMT_FLAG_ALPHA
2366        | ffi::AV_PIX_FMT_FLAG_BAYER
2367        | ffi::AV_PIX_FMT_FLAG_FLOAT
2368        | ffi::AV_PIX_FMT_FLAG_XYZ;
2369    if descriptor.flags & u64::from(rejected) != 0 || descriptor.nb_components != 3 {
2370        return None;
2371    }
2372    let [luma, u, v, _] = descriptor.comp;
2373    let depth = luma.depth;
2374    if !(8..=16).contains(&depth) || u.depth != depth || v.depth != depth {
2375        return None;
2376    }
2377    if descriptor.log2_chroma_w > 2 || descriptor.log2_chroma_h > 2 {
2378        return None;
2379    }
2380    let bytes = if depth > 8 { 2 } else { 1 };
2381    let shift = luma.shift;
2382    let msb_aligned = match shift {
2383        0 => false,
2384        _ if depth > 8 && shift == 16 - depth => true,
2385        _ => return None,
2386    };
2387    let planar = u.plane == 1
2388        && v.plane == 2
2389        && u.step == bytes
2390        && v.step == bytes
2391        && u.offset == 0
2392        && v.offset == 0;
2393    let interleaved = u.plane == 1
2394        && v.plane == 1
2395        && u.step == 2 * bytes
2396        && v.step == 2 * bytes
2397        && u.offset == 0
2398        && v.offset == bytes;
2399    if luma.plane != 0
2400        || luma.step != bytes
2401        || luma.offset != 0
2402        || u.shift != shift
2403        || v.shift != shift
2404        || !(planar || interleaved)
2405    {
2406        return None;
2407    }
2408    Some(YuvPlaneLayout {
2409        chroma_shift_x: descriptor.log2_chroma_w,
2410        chroma_shift_y: descriptor.log2_chroma_h,
2411        bit_depth: u8::try_from(depth).ok()?,
2412        interleaved_chroma: interleaved,
2413        msb_aligned,
2414    })
2415}
2416
2417/// Copies the samples of a frame whose format [`yuv_layout`] accepts into packed forward rows, or
2418/// returns `Ok(None)` for other formats. Odd dimensions round chroma up.
2419///
2420/// Row padding is never read since it may be uninitialized; [`DecodedFrame::yuv_planes`] can share
2421/// fully written frames instead.
2422///
2423/// # Errors
2424/// Returns an error for invalid dimensions, null planes, or linesizes shorter than the plane width.
2425pub fn yuv_planes(frame: &AVFrame) -> Result<Option<YuvPlanes>, BridgeError> {
2426    frame_yuv_planes(frame, false)
2427}
2428
2429/// A decoded frame, and whether every byte of its buffers, row padding included, is written.
2430///
2431/// Only this crate constructs one; frames from elsewhere go to [`yuv_planes`].
2432pub struct DecodedFrame {
2433    frame: AVFrame,
2434    written: bool,
2435}
2436
2437impl DecodedFrame {
2438    /// Takes the next frame `decoder` has ready.
2439    ///
2440    /// # Errors
2441    /// Returns what `avcodec_receive_frame` does for a drained decoder or a decode failure.
2442    pub fn receive(decoder: &mut AVCodecContext) -> Result<Self, RsmpegError> {
2443        let written = decoder_frames_are_initialized(decoder);
2444        let frame = decoder.receive_frame()?;
2445        Ok(Self { frame, written })
2446    }
2447
2448    /// Like [`yuv_planes`], but shares the frame's buffer when it is fully written. Planes with a
2449    /// negative linesize or outside the frame's buffers are still copied.
2450    ///
2451    /// # Errors
2452    /// Returns an error for invalid dimensions, null planes, or linesizes shorter than the plane
2453    /// width.
2454    pub fn yuv_planes(&self) -> Result<Option<YuvPlanes>, BridgeError> {
2455        frame_yuv_planes(&self.frame, self.written)
2456    }
2457
2458    /// Sets the frame's presentation timestamp.
2459    pub fn set_pts(&mut self, pts: i64) {
2460        self.frame.set_pts(pts);
2461    }
2462
2463    /// Takes ownership of the frame.
2464    #[must_use]
2465    pub fn into_frame(self) -> AVFrame {
2466        self.frame
2467    }
2468}
2469
2470impl std::ops::Deref for DecodedFrame {
2471    type Target = AVFrame;
2472
2473    fn deref(&self) -> &AVFrame {
2474        &self.frame
2475    }
2476}
2477
2478impl fmt::Debug for DecodedFrame {
2479    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2480        formatter
2481            .debug_struct("DecodedFrame")
2482            .field("format", &self.frame.format)
2483            .field("width", &self.frame.width)
2484            .field("height", &self.frame.height)
2485            .field("pts", &self.frame.pts)
2486            .field("written", &self.written)
2487            .finish_non_exhaustive()
2488    }
2489}
2490
2491/// Whether `decoder`'s frame buffers are fully initialized, so they may be shared.
2492///
2493/// The default `get_buffer2` uses zeroed pools. Wrapped external decoders (`wrapper_name`, such as
2494/// libdav1d) and replaced `get_buffer2` callbacks do not qualify.
2495fn decoder_frames_are_initialized(decoder: &AVCodecContext) -> bool {
2496    static DEFAULT_GET_BUFFER2: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2497    // Read the default from a new context; Rust's address of the function could be a linker stub.
2498    let default = *DEFAULT_GET_BUFFER2.get_or_init(|| {
2499        // SAFETY: a context allocated without a codec is only read and then freed.
2500        unsafe {
2501            let mut context = ffi::avcodec_alloc_context3(ptr::null());
2502            let get_buffer2 = context
2503                .as_ref()
2504                .and_then(|context| context.get_buffer2)
2505                .map_or(0, |function| function as usize);
2506            ffi::avcodec_free_context(&raw mut context);
2507            get_buffer2
2508        }
2509    });
2510    // SAFETY: a context's `codec` is null or a static, read-only description.
2511    let wrapped =
2512        unsafe { decoder.codec.as_ref() }.is_none_or(|codec| !codec.wrapper_name.is_null());
2513    let get_buffer2 = decoder.get_buffer2.map_or(0, |function| function as usize);
2514    !wrapped && default != 0 && get_buffer2 == default
2515}
2516
2517/// The planes of `frame`; `share` only for fully initialized frames.
2518fn frame_yuv_planes(frame: &AVFrame, share: bool) -> Result<Option<YuvPlanes>, BridgeError> {
2519    let Some(layout) = yuv_layout(frame.format) else {
2520        return Ok(None);
2521    };
2522    let width =
2523        u32::try_from(frame.width).map_err(|_| BridgeError::InvalidInput("negative YUV width"))?;
2524    let height = u32::try_from(frame.height)
2525        .map_err(|_| BridgeError::InvalidInput("negative YUV height"))?;
2526    if width == 0 || height == 0 {
2527        return Err(BridgeError::InvalidInput("empty YUV frame"));
2528    }
2529    let bytes = layout.bytes_per_sample();
2530    let chroma_width = width.div_ceil(1 << layout.chroma_shift_x);
2531    let chroma_height = height.div_ceil(1 << layout.chroma_shift_y);
2532    // Only a vouched-for, reference-counted frame is shared; `AVFrame::clone` adds buffer refs.
2533    let shared =
2534        (share && !frame.buf[0].is_null()).then(|| std::sync::Arc::new(SharedFrame(frame.clone())));
2535    let copy = |index: usize,
2536                samples: u32,
2537                pairs: u32,
2538                rows: u32,
2539                context: &'static str|
2540     -> Result<FramePlane, BridgeError> {
2541        let row_bytes = samples
2542            .checked_mul(bytes)
2543            .and_then(|row| row.checked_mul(pairs))
2544            .ok_or(BridgeError::InvalidInput(context))?;
2545        if let Some(view) = shared
2546            .as_ref()
2547            .and_then(|frame| PlaneView::new(frame, index, row_bytes, rows))
2548        {
2549            let stride =
2550                u32::try_from(view.stride).map_err(|_| BridgeError::InvalidInput(context))?;
2551            return Ok(FramePlane {
2552                bytes: bytes::Bytes::from_owner(view),
2553                stride,
2554                width: samples,
2555                height: rows,
2556            });
2557        }
2558        Ok(FramePlane {
2559            bytes: copy_video_plane(frame, index, row_bytes, rows, context)?.into(),
2560            stride: row_bytes,
2561            width: samples,
2562            height: rows,
2563        })
2564    };
2565    let mut planes = vec![copy(0, width, 1, height, "invalid Y plane")?];
2566    if layout.interleaved_chroma {
2567        planes.push(copy(1, chroma_width, 2, chroma_height, "invalid UV plane")?);
2568    } else {
2569        planes.push(copy(1, chroma_width, 1, chroma_height, "invalid U plane")?);
2570        planes.push(copy(2, chroma_width, 1, chroma_height, "invalid V plane")?);
2571    }
2572    Ok(Some(YuvPlanes {
2573        layout,
2574        width,
2575        height,
2576        planes,
2577    }))
2578}
2579
2580/// A decoded frame whose buffers several plane views share.
2581struct SharedFrame(AVFrame);
2582
2583// SAFETY: the wrapped frame is only read. FFmpeg never writes to a buffer with more than one
2584// reference, so nothing mutates it while shared.
2585unsafe impl Sync for SharedFrame {}
2586
2587/// `stride * rows` bytes of one plane of a fully written [`SharedFrame`], which it keeps alive.
2588struct PlaneView {
2589    frame: std::sync::Arc<SharedFrame>,
2590    data: *const u8,
2591    len: usize,
2592    stride: usize,
2593}
2594
2595// SAFETY: the view reads immutable memory in `frame`'s buffers, which it keeps alive;
2596// `SharedFrame` is `Send + Sync`.
2597unsafe impl Send for PlaneView {}
2598
2599impl PlaneView {
2600    /// `None` unless the linesize is positive, covers `row_bytes`, and all rows lie in one buffer.
2601    fn new(
2602        frame: &std::sync::Arc<SharedFrame>,
2603        index: usize,
2604        row_bytes: u32,
2605        rows: u32,
2606    ) -> Option<Self> {
2607        let inner = &frame.0;
2608        let data = inner.data[index].cast_const();
2609        let stride = usize::try_from(inner.linesize[index]).ok()?;
2610        let row_bytes = usize::try_from(row_bytes).ok()?;
2611        if data.is_null() || stride < row_bytes || rows == 0 {
2612            return None;
2613        }
2614        let len = stride.checked_mul(usize::try_from(rows).ok()?)?;
2615        in_frame_buffer(inner, data as usize, len).then(|| Self {
2616            frame: std::sync::Arc::clone(frame),
2617            data,
2618            len,
2619            stride,
2620        })
2621    }
2622}
2623
2624impl AsRef<[u8]> for PlaneView {
2625    fn as_ref(&self) -> &[u8] {
2626        let _ = &self.frame;
2627        // SAFETY: `new` checked `data..data + len` lies in a buffer of the frame `self` holds.
2628        unsafe { slice::from_raw_parts(self.data, self.len) }
2629    }
2630}
2631
2632/// Copies plane `index` of `frame`, refusing rows outside the frame's buffers when it has any.
2633fn copy_video_plane(
2634    frame: &AVFrame,
2635    index: usize,
2636    width: u32,
2637    height: u32,
2638    context: &'static str,
2639) -> Result<Vec<u8>, BridgeError> {
2640    let (data, linesize) = (frame.data[index].cast_const(), frame.linesize[index]);
2641    let has_buffers = frame.buf.iter().any(|buffer| !buffer.is_null());
2642    if has_buffers && !plane_rows_in_frame_buffer(frame, data, linesize, width, height) {
2643        return Err(BridgeError::InvalidInput(context));
2644    }
2645    // SAFETY: the rows lie in one of the frame's buffers, or a frame without buffers vouches for
2646    // its own planes.
2647    unsafe { copy_plane_rows(data, linesize, width, height, context) }
2648}
2649
2650/// Whether `height` rows of `width` bytes at the signed `linesize` from `data` lie in one buffer.
2651fn plane_rows_in_frame_buffer(
2652    frame: &AVFrame,
2653    data: *const u8,
2654    linesize: i32,
2655    width: u32,
2656    height: u32,
2657) -> bool {
2658    let (Ok(row_bytes), Ok(rows)) = (usize::try_from(width), usize::try_from(height)) else {
2659        return false;
2660    };
2661    let Ok(stride) = usize::try_from(linesize.unsigned_abs()) else {
2662        return false;
2663    };
2664    let Some(span) = stride
2665        .checked_mul(rows.saturating_sub(1))
2666        .and_then(|before| before.checked_add(row_bytes))
2667    else {
2668        return false;
2669    };
2670    // A negative linesize walks back from the first row, so the lowest address is the last row.
2671    let start = if linesize < 0 {
2672        (data as usize).checked_sub(span - row_bytes)
2673    } else {
2674        Some(data as usize)
2675    };
2676    !data.is_null() && rows > 0 && start.is_some_and(|start| in_frame_buffer(frame, start, span))
2677}
2678
2679/// # Safety
2680/// A non-null `data` must have `height` rows at the signed `linesize`, each `width` bytes long.
2681unsafe fn copy_plane_rows(
2682    data: *const u8,
2683    linesize: i32,
2684    width: u32,
2685    height: u32,
2686    context: &'static str,
2687) -> Result<Vec<u8>, BridgeError> {
2688    let row_bytes = usize::try_from(width).map_err(|_| BridgeError::InvalidInput(context))?;
2689    let rows = usize::try_from(height).map_err(|_| BridgeError::InvalidInput(context))?;
2690    let stride =
2691        usize::try_from(linesize.unsigned_abs()).map_err(|_| BridgeError::InvalidInput(context))?;
2692    if data.is_null() || linesize == 0 || stride < row_bytes {
2693        return Err(BridgeError::InvalidInput(context));
2694    }
2695    let byte_len = row_bytes
2696        .checked_mul(rows)
2697        .ok_or(BridgeError::InvalidInput(context))?;
2698    // Append row by row to avoid an extra zeroing pass over the buffer.
2699    let mut output = Vec::with_capacity(byte_len);
2700    let signed_stride =
2701        isize::try_from(linesize).map_err(|_| BridgeError::InvalidInput(context))?;
2702    for row in 0..rows {
2703        let row = isize::try_from(row).map_err(|_| BridgeError::InvalidInput(context))?;
2704        let offset = row
2705            .checked_mul(signed_stride)
2706            .ok_or(BridgeError::InvalidInput(context))?;
2707        // SAFETY: delegated to this function's contract; the linesize covers `row_bytes`.
2708        let source = unsafe { slice::from_raw_parts(data.offset(offset), row_bytes) };
2709        output.extend_from_slice(source);
2710    }
2711    debug_assert_eq!(output.len(), byte_len);
2712    Ok(output)
2713}
2714
2715/// Copies tightly packed RGBA bytes into an owned `FFmpeg` frame.
2716///
2717/// # Errors
2718/// Returns an `FFmpeg` error when its frame buffer cannot be allocated.
2719pub fn rgba_frame(bytes: &[u8], width: i32, height: i32) -> Result<AVFrame, BridgeError> {
2720    let row_bytes = usize::try_from(width)
2721        .ok()
2722        .and_then(|value| value.checked_mul(4))
2723        .ok_or(BridgeError::InvalidInput("RGBA row width overflow"))?;
2724    let rows =
2725        usize::try_from(height).map_err(|_| BridgeError::InvalidInput("negative RGBA height"))?;
2726    let expected = row_bytes
2727        .checked_mul(rows)
2728        .ok_or(BridgeError::InvalidInput("RGBA frame size overflow"))?;
2729    if bytes.len() != expected {
2730        return Err(BridgeError::InvalidInput("RGBA byte length mismatch"));
2731    }
2732
2733    let mut frame = AVFrame::new();
2734    frame.set_format(ffi::AV_PIX_FMT_RGBA);
2735    frame.set_width(width);
2736    frame.set_height(height);
2737    frame.get_buffer(1)?;
2738    frame.make_writable()?;
2739    let linesize = usize::try_from(frame.linesize[0])
2740        .map_err(|_| BridgeError::InvalidInput("negative RGBA linesize"))?;
2741    if frame.data[0].is_null() || linesize < row_bytes {
2742        return Err(BridgeError::InvalidInput(
2743            "RGBA destination plane is too small",
2744        ));
2745    }
2746
2747    // SAFETY: av_frame_get_buffer allocated `height` writable rows of `linesize` bytes; both slices
2748    // span one validated RGBA row.
2749    unsafe {
2750        for row in 0..rows {
2751            let destination_offset = row.checked_mul(linesize).ok_or(BridgeError::InvalidInput(
2752                "RGBA destination offset overflow",
2753            ))?;
2754            let source_offset = row
2755                .checked_mul(row_bytes)
2756                .ok_or(BridgeError::InvalidInput("RGBA source offset overflow"))?;
2757            let destination =
2758                slice::from_raw_parts_mut(frame.data[0].add(destination_offset), row_bytes);
2759            destination.copy_from_slice(&bytes[source_offset..source_offset + row_bytes]);
2760        }
2761    }
2762    Ok(frame)
2763}
2764
2765/// Copies owned planar 8-bit 4:2:0 samples into an `FFmpeg` video frame.
2766///
2767/// # Errors
2768/// Returns an error for invalid dimensions, short source planes, or an allocation failure.
2769#[allow(clippy::too_many_arguments)]
2770pub fn yuv420p_frame(
2771    y: &[u8],
2772    y_stride: u32,
2773    u: &[u8],
2774    u_stride: u32,
2775    v: &[u8],
2776    v_stride: u32,
2777    width: i32,
2778    height: i32,
2779) -> Result<AVFrame, BridgeError> {
2780    let width =
2781        u32::try_from(width).map_err(|_| BridgeError::InvalidInput("negative YUV width"))?;
2782    let height =
2783        u32::try_from(height).map_err(|_| BridgeError::InvalidInput("negative YUV height"))?;
2784    if width == 0 || height == 0 {
2785        return Err(BridgeError::InvalidInput("empty YUV frame"));
2786    }
2787    let chroma_width = width.div_ceil(2);
2788    let chroma_height = height.div_ceil(2);
2789    validate_source_plane(y, y_stride, width, height, "invalid Y source plane")?;
2790    validate_source_plane(
2791        u,
2792        u_stride,
2793        chroma_width,
2794        chroma_height,
2795        "invalid U source plane",
2796    )?;
2797    validate_source_plane(
2798        v,
2799        v_stride,
2800        chroma_width,
2801        chroma_height,
2802        "invalid V source plane",
2803    )?;
2804
2805    let mut frame = AVFrame::new();
2806    frame.set_format(ffi::AV_PIX_FMT_YUV420P);
2807    frame.set_width(i32::try_from(width).map_err(|_| BridgeError::InvalidInput("YUV width"))?);
2808    frame.set_height(i32::try_from(height).map_err(|_| BridgeError::InvalidInput("YUV height"))?);
2809    frame.get_buffer(1)?;
2810    frame.make_writable()?;
2811    copy_plane_to_frame(y, y_stride, width, height, frame.data[0], frame.linesize[0])?;
2812    copy_plane_to_frame(
2813        u,
2814        u_stride,
2815        chroma_width,
2816        chroma_height,
2817        frame.data[1],
2818        frame.linesize[1],
2819    )?;
2820    copy_plane_to_frame(
2821        v,
2822        v_stride,
2823        chroma_width,
2824        chroma_height,
2825        frame.data[2],
2826        frame.linesize[2],
2827    )?;
2828    Ok(frame)
2829}
2830
2831/// The first pixel format in `FFmpeg`'s table laid out as `layout` (`yuv420p`, not the deprecated
2832/// `yuvj420p`).
2833#[must_use]
2834pub fn yuv_pixel_format(layout: YuvPlaneLayout) -> Option<ffi::AVPixelFormat> {
2835    let mut descriptor = ptr::null();
2836    loop {
2837        // SAFETY: null starts the walk; other values are static descriptors from the previous call.
2838        descriptor = unsafe { ffi::av_pix_fmt_desc_next(descriptor) };
2839        if descriptor.is_null() {
2840            return None;
2841        }
2842        // SAFETY: a descriptor from the table names its own format.
2843        let format = unsafe { ffi::av_pix_fmt_desc_get_id(descriptor) };
2844        if yuv_layout(format) == Some(layout) {
2845            return Some(format);
2846        }
2847    }
2848}
2849
2850/// A `width` by `height` frame of `format` holding a copy of `planes` (bytes and stride each).
2851///
2852/// # Errors
2853/// For a format without a descriptor, the wrong plane count, or a plane smaller than the picture.
2854pub fn planar_frame(
2855    format: ffi::AVPixelFormat,
2856    planes: &[(&[u8], u32)],
2857    width: u32,
2858    height: u32,
2859) -> Result<AVFrame, BridgeError> {
2860    // SAFETY: `av_pix_fmt_desc_get` accepts any value and returns null or a static descriptor.
2861    let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
2862        .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
2863    // SAFETY: a pure computation over plain values.
2864    let count = unsafe { ffi::av_pix_fmt_count_planes(format) };
2865    if usize::try_from(count).ok() != Some(planes.len()) || width == 0 || height == 0 {
2866        return Err(BridgeError::InvalidInput(
2867            "planes do not match the pixel format",
2868        ));
2869    }
2870    let signed = |value: u32| {
2871        i32::try_from(value).map_err(|_| BridgeError::InvalidInput("frame size overflow"))
2872    };
2873    let mut frame = AVFrame::new();
2874    frame.set_format(format);
2875    frame.set_width(signed(width)?);
2876    frame.set_height(signed(height)?);
2877    frame.get_buffer(1)?;
2878    frame.make_writable()?;
2879    for (index, (bytes, stride)) in planes.iter().enumerate() {
2880        let plane = i32::try_from(index).unwrap_or(i32::MAX);
2881        // SAFETY: a pure computation over plain values.
2882        let row_bytes = unsafe { ffi::av_image_get_linesize(format, signed(width)?, plane) };
2883        let row_bytes = u32::try_from(row_bytes).map_err(|_| BridgeError::FfmpegCode(row_bytes))?;
2884        let rows = if index == 0 || index == 3 {
2885            height
2886        } else {
2887            height.div_ceil(1 << descriptor.log2_chroma_h)
2888        };
2889        validate_source_plane(bytes, *stride, row_bytes, rows, "invalid source plane")?;
2890        copy_plane_to_frame(
2891            bytes,
2892            *stride,
2893            row_bytes,
2894            rows,
2895            frame.data[index],
2896            frame.linesize[index],
2897        )?;
2898    }
2899    Ok(frame)
2900}
2901
2902fn validate_source_plane(
2903    bytes: &[u8],
2904    stride: u32,
2905    width: u32,
2906    height: u32,
2907    context: &'static str,
2908) -> Result<(), BridgeError> {
2909    let required = usize::try_from(stride).ok().and_then(|stride| {
2910        usize::try_from(height)
2911            .ok()
2912            .and_then(|height| stride.checked_mul(height))
2913    });
2914    if stride < width || required != Some(bytes.len()) {
2915        Err(BridgeError::InvalidInput(context))
2916    } else {
2917        Ok(())
2918    }
2919}
2920
2921fn copy_plane_to_frame(
2922    source: &[u8],
2923    source_stride: u32,
2924    width: u32,
2925    height: u32,
2926    destination: *mut u8,
2927    destination_stride: i32,
2928) -> Result<(), BridgeError> {
2929    let row_bytes =
2930        usize::try_from(width).map_err(|_| BridgeError::InvalidInput("YUV row width overflow"))?;
2931    let rows =
2932        usize::try_from(height).map_err(|_| BridgeError::InvalidInput("YUV row count overflow"))?;
2933    let source_stride = usize::try_from(source_stride)
2934        .map_err(|_| BridgeError::InvalidInput("YUV source stride overflow"))?;
2935    let destination_stride = usize::try_from(destination_stride)
2936        .map_err(|_| BridgeError::InvalidInput("negative YUV destination stride"))?;
2937    if destination.is_null() || destination_stride < row_bytes {
2938        return Err(BridgeError::InvalidInput(
2939            "YUV destination plane is too small",
2940        ));
2941    }
2942    for row in 0..rows {
2943        let source_offset = row
2944            .checked_mul(source_stride)
2945            .ok_or(BridgeError::InvalidInput("YUV source offset overflow"))?;
2946        let destination_offset = row
2947            .checked_mul(destination_stride)
2948            .ok_or(BridgeError::InvalidInput("YUV destination offset overflow"))?;
2949        // SAFETY: the destination has `height` writable rows covering `width` bytes, and the source
2950        // length was checked against its stride and row count.
2951        unsafe {
2952            ptr::copy_nonoverlapping(
2953                source.as_ptr().add(source_offset),
2954                destination.add(destination_offset),
2955                row_bytes,
2956            );
2957        }
2958    }
2959    Ok(())
2960}
2961
2962/// Copies planar `f32` samples into an audio frame of `format` (`FLTP`, `FLT` or `S16`). 16-bit
2963/// samples are clamped to [-1, 1] and rounded.
2964///
2965/// # Errors
2966/// Returns an error for mismatched channels, invalid dimensions, another sample format, or an
2967/// allocation failure.
2968pub fn audio_frame(
2969    channels: &[Vec<f32>],
2970    format: ffi::AVSampleFormat,
2971    sample_rate: i32,
2972    pts: i64,
2973) -> Result<AVFrame, BridgeError> {
2974    let Some(samples) = channels.first().map(Vec::len) else {
2975        return Err(BridgeError::InvalidInput("invalid planar audio shape"));
2976    };
2977    if sample_rate <= 0
2978        || samples == 0
2979        || channels.len() > ffi::AV_NUM_DATA_POINTERS as usize
2980        || channels.iter().any(|channel| channel.len() != samples)
2981    {
2982        return Err(BridgeError::InvalidInput(
2983            "planar audio channel lengths differ",
2984        ));
2985    }
2986    let sample_bytes = match format {
2987        ffi::AV_SAMPLE_FMT_FLTP | ffi::AV_SAMPLE_FMT_FLT => size_of::<f32>(),
2988        ffi::AV_SAMPLE_FMT_S16 => size_of::<i16>(),
2989        _ => return Err(BridgeError::InvalidInput("unsupported audio sample format")),
2990    };
2991    let planar = format == ffi::AV_SAMPLE_FMT_FLTP;
2992    let channel_count = i32::try_from(channels.len())
2993        .map_err(|_| BridgeError::InvalidInput("audio channel count overflow"))?;
2994    let sample_count = i32::try_from(samples)
2995        .map_err(|_| BridgeError::InvalidInput("audio sample count overflow"))?;
2996    let mut frame = AVFrame::new();
2997    frame.set_format(format);
2998    frame.set_ch_layout(
2999        rsmpeg::avutil::AVChannelLayout::from_nb_channels(channel_count).into_inner(),
3000    );
3001    frame.set_sample_rate(sample_rate);
3002    frame.set_nb_samples(sample_count);
3003    frame.set_pts(pts);
3004    frame.set_time_base(ffi::AVRational {
3005        num: 1,
3006        den: sample_rate,
3007    });
3008    frame.get_buffer(0)?;
3009    frame.make_writable()?;
3010    let plane_bytes = samples
3011        .checked_mul(sample_bytes)
3012        .and_then(|bytes| bytes.checked_mul(if planar { 1 } else { channels.len() }))
3013        .ok_or(BridgeError::InvalidInput("audio plane byte count overflow"))?;
3014    let plane_capacity = usize::try_from(frame.linesize[0]).unwrap_or(0);
3015    if plane_capacity < plane_bytes {
3016        return Err(BridgeError::InvalidInput(
3017            "audio plane capacity is too small",
3018        ));
3019    }
3020    let planes = if planar { channels.len() } else { 1 };
3021    if frame.data[..planes].iter().any(|plane| plane.is_null()) {
3022        return Err(BridgeError::InvalidInput("audio plane pointer is null"));
3023    }
3024    if planar {
3025        for (index, source) in channels.iter().enumerate() {
3026            // SAFETY: av_frame_get_buffer allocated one writable plane per channel of `linesize[0]`
3027            // bytes, checked above to hold the channel.
3028            unsafe {
3029                ptr::copy_nonoverlapping(
3030                    source.as_ptr().cast::<u8>(),
3031                    frame.data[index],
3032                    plane_bytes,
3033                );
3034            }
3035        }
3036        return Ok(frame);
3037    }
3038    // SAFETY: the single interleaved plane was checked to hold every sample and is unshared.
3039    let plane = unsafe { std::slice::from_raw_parts_mut(frame.data[0], plane_bytes) };
3040    let interleaved = (0..samples).flat_map(|sample| channels.iter().map(move |c| c[sample]));
3041    if format == ffi::AV_SAMPLE_FMT_FLT {
3042        for (bytes, value) in plane.as_chunks_mut::<4>().0.iter_mut().zip(interleaved) {
3043            *bytes = value.to_ne_bytes();
3044        }
3045    } else {
3046        for (bytes, value) in plane.as_chunks_mut::<2>().0.iter_mut().zip(interleaved) {
3047            // In range after the clamp, so the cast cannot truncate.
3048            #[allow(clippy::cast_possible_truncation)]
3049            let value = (value.clamp(-1.0, 1.0) * 32_767.0).round() as i16;
3050            *bytes = value.to_ne_bytes();
3051        }
3052    }
3053    Ok(frame)
3054}
3055
3056/// The `AVChannel` of each channel of `layout`, in order; empty for `AV_CHANNEL_ORDER_UNSPEC`.
3057///
3058/// Takes rsmpeg's wrapper because a bare `AVChannelLayout` can carry a forged channel map:
3059///
3060/// ```compile_fail,E0308
3061/// use rsmpeg::ffi;
3062/// let forged = ffi::AVChannelLayout {
3063///     order: ffi::AV_CHANNEL_ORDER_CUSTOM,
3064///     nb_channels: 4,
3065///     u: ffi::AVChannelLayout__bindgen_ty_1 { map: 0x10 as *mut _ },
3066///     opaque: std::ptr::null_mut(),
3067/// };
3068/// alpha2_ffmpeg_bridge::channel_layout_channels(&forged);
3069/// ```
3070#[must_use]
3071pub fn channel_layout_channels(layout: &rsmpeg::avutil::AVChannelLayout) -> Vec<ffi::AVChannel> {
3072    if layout.order == ffi::AV_CHANNEL_ORDER_UNSPEC {
3073        return Vec::new();
3074    }
3075    let channels = u32::try_from(layout.nb_channels).unwrap_or(0);
3076    (0..channels)
3077        .map(|index| {
3078            layout
3079                .channel_from_index(index)
3080                .unwrap_or(ffi::AV_CHAN_NONE)
3081        })
3082        .collect()
3083}
3084
3085/// A channel layout of `channels` in order, native when possible, else custom.
3086///
3087/// # Errors
3088/// Returns an error for no channels or when `FFmpeg` cannot allocate or retype the layout.
3089pub fn channel_layout_of(
3090    channels: &[ffi::AVChannel],
3091) -> Result<rsmpeg::avutil::AVChannelLayout, BridgeError> {
3092    let count = i32::try_from(channels.len())
3093        .ok()
3094        .filter(|count| *count > 0)
3095        .ok_or(BridgeError::InvalidInput("a channel layout needs channels"))?;
3096    let mut raw = std::mem::MaybeUninit::<ffi::AVChannelLayout>::zeroed();
3097    // SAFETY: `custom_init` gives the zeroed layout a map of `count` entries, all written below.
3098    let initialized = unsafe { ffi::av_channel_layout_custom_init(raw.as_mut_ptr(), count) };
3099    if initialized < 0 {
3100        return Err(BridgeError::FfmpegCode(initialized));
3101    }
3102    // SAFETY: initialized above; from here `layout` owns it and uninitializes it on drop.
3103    let mut layout = unsafe { rsmpeg::avutil::AVChannelLayout::new(raw.assume_init()) };
3104    for (index, channel) in channels.iter().enumerate() {
3105        // SAFETY: a custom layout's map holds `count` entries, and `index` is below it.
3106        unsafe { (*layout.u.map.add(index)).id = *channel };
3107    }
3108    let flags = i32::try_from(ffi::AV_CHANNEL_LAYOUT_RETYPE_FLAG_CANONICAL).unwrap_or(0);
3109    // SAFETY: `layout` is a valid custom layout that `retype` may rewrite in place.
3110    let retyped = unsafe {
3111        ffi::av_channel_layout_retype(layout.as_mut_ptr(), ffi::AV_CHANNEL_ORDER_UNSPEC, flags)
3112    };
3113    if retyped < 0 {
3114        return Err(BridgeError::FfmpegCode(retyped));
3115    }
3116    Ok(layout)
3117}
3118
3119/// Copies a packed `AV_SAMPLE_FMT_FLT` frame into an owned interleaved vector.
3120///
3121/// # Errors
3122/// Returns an error if the frame format, dimensions, or buffer is invalid.
3123pub fn audio_f32_interleaved(frame: &AVFrame) -> Result<Vec<f32>, BridgeError> {
3124    if frame.format != ffi::AV_SAMPLE_FMT_FLT || frame.nb_samples < 0 {
3125        return Err(BridgeError::InvalidInput(
3126            "packed audio format or sample count is invalid",
3127        ));
3128    }
3129    let channels = usize::try_from(frame.ch_layout().nb_channels)
3130        .map_err(|_| BridgeError::InvalidInput("packed audio channel count is negative"))?;
3131    let frames = usize::try_from(frame.nb_samples)
3132        .map_err(|_| BridgeError::InvalidInput("packed audio sample count is negative"))?;
3133    let samples = frames
3134        .checked_mul(channels)
3135        .ok_or(BridgeError::InvalidInput(
3136            "packed audio sample count overflow",
3137        ))?;
3138    let bytes = samples
3139        .checked_mul(size_of::<f32>())
3140        .ok_or(BridgeError::InvalidInput(
3141            "packed audio byte count overflow",
3142        ))?;
3143    if channels == 0
3144        || frame.data[0].is_null()
3145        || usize::try_from(frame.linesize[0]).unwrap_or(0) < bytes
3146    {
3147        return Err(BridgeError::InvalidInput(
3148            "packed audio plane is missing or too small",
3149        ));
3150    }
3151    let mut output = vec![0.0_f32; samples];
3152    // SAFETY: the FLT plane was checked to hold every sample, and `output` is exactly that size.
3153    unsafe {
3154        ptr::copy_nonoverlapping(frame.data[0], output.as_mut_ptr().cast::<u8>(), bytes);
3155    }
3156    Ok(output)
3157}
3158
3159/// The rotation a display matrix asks for, in `FFmpeg`'s convention.
3160#[derive(Copy, Clone, Debug, PartialEq)]
3161pub struct DisplayRotation {
3162    /// Counter-clockwise angle in degrees, in `[-180, 180]`.
3163    pub counter_clockwise_degrees: f64,
3164    /// Whether the matrix also mirrors: this rotation followed by a horizontal flip.
3165    pub flipped: bool,
3166}
3167
3168/// Reads a stream display matrix.
3169#[must_use]
3170pub fn display_rotation(parameters: &AVCodecParameters) -> Option<DisplayRotation> {
3171    let count = usize::try_from(parameters.nb_coded_side_data).ok()?;
3172    if count == 0 || count > 64 || parameters.coded_side_data.is_null() {
3173        return None;
3174    }
3175    // SAFETY: the borrowed parameters own exactly `nb_coded_side_data` entries.
3176    let entries = unsafe { slice::from_raw_parts(parameters.coded_side_data, count) };
3177    let matrix = entries.iter().find(|entry| {
3178        entry.type_ == ffi::AV_PKT_DATA_DISPLAYMATRIX
3179            && entry.size >= 9 * size_of::<i32>()
3180            && !entry.data.is_null()
3181    })?;
3182    // SAFETY: the matching side-data entry was validated to hold a complete 3x3 display matrix.
3183    unsafe { matrix_rotation(matrix.data) }
3184}
3185
3186/// Reads a frame's display matrix, such as the JPEG decoder attaches for Exif `Orientation`.
3187#[must_use]
3188pub fn frame_display_rotation(frame: &AVFrame) -> Option<DisplayRotation> {
3189    // SAFETY: `frame` is a live frame; the returned entry, if any, is owned by it for this borrow.
3190    let entry =
3191        unsafe { ffi::av_frame_get_side_data(frame.as_ptr(), ffi::AV_FRAME_DATA_DISPLAYMATRIX) };
3192    if entry.is_null() {
3193        return None;
3194    }
3195    // SAFETY: a non-null entry returned by `av_frame_get_side_data` is a valid side-data record.
3196    let entry = unsafe { &*entry };
3197    if entry.size < 9 * size_of::<i32>() || entry.data.is_null() {
3198        return None;
3199    }
3200    // SAFETY: the entry was validated to hold a complete 3x3 display matrix.
3201    unsafe { matrix_rotation(entry.data) }
3202}
3203
3204/// # Safety
3205/// `data` must point at nine readable `i32`s, aligned or not.
3206unsafe fn matrix_rotation(data: *const u8) -> Option<DisplayRotation> {
3207    let mut aligned = [0_i32; 9];
3208    // SAFETY: the caller guarantees a complete 3x3 matrix; a byte copy needs no alignment.
3209    unsafe {
3210        ptr::copy_nonoverlapping(
3211            data,
3212            aligned.as_mut_ptr().cast::<u8>(),
3213            size_of::<[i32; 9]>(),
3214        );
3215    }
3216    // `av_display_rotation_get` is meaningless for a mirroring matrix (negative 2x2 determinant),
3217    // so remove the horizontal flip first.
3218    let determinant = i64::from(aligned[0]) * i64::from(aligned[4])
3219        - i64::from(aligned[1]) * i64::from(aligned[3]);
3220    let flipped = determinant < 0;
3221    if flipped {
3222        // SAFETY: `aligned` is a complete, correctly aligned 3x3 matrix.
3223        unsafe { ffi::av_display_matrix_flip(aligned.as_mut_ptr(), 1, 0) };
3224    }
3225    // SAFETY: `aligned` is a complete, correctly aligned 3x3 display matrix.
3226    let angle = unsafe { ffi::av_display_rotation_get(aligned.as_ptr()) };
3227    angle.is_finite().then_some(DisplayRotation {
3228        counter_clockwise_degrees: angle,
3229        flipped,
3230    })
3231}
3232
3233const fn size_of<T>() -> usize {
3234    std::mem::size_of::<T>()
3235}
3236
3237/// A reusable `FFmpeg` YUV420P frame the caller writes into directly.
3238///
3239/// Avoids [`yuv420p_frame`]'s per-frame allocation and copy. [`Yuv420pFrameBuffer::begin_write`]
3240/// returns plane memory only once `FFmpeg` no longer shares the buffer; a shared buffer is left to
3241/// its holder and replaced by zeroed memory, without the old picture.
3242pub struct Yuv420pFrameBuffer {
3243    frame: AVFrame,
3244    width: usize,
3245    height: usize,
3246    /// Each plane's visible bytes per row and rows, from the pixel format descriptor.
3247    planes: Vec<(usize, usize)>,
3248}
3249
3250/// Writable plane memory for one reusable frame.
3251pub struct Yuv420pFramePlanes<'a> {
3252    /// Luma rows, `y_stride` bytes apart.
3253    pub y: &'a mut [u8],
3254    /// Distance between luma rows.
3255    pub y_stride: usize,
3256    /// Blue-difference chroma rows, `chroma_stride` bytes apart.
3257    pub u: &'a mut [u8],
3258    /// Red-difference chroma rows, `chroma_stride` bytes apart.
3259    pub v: &'a mut [u8],
3260    /// Distance between chroma rows.
3261    pub chroma_stride: usize,
3262}
3263
3264impl Yuv420pFrameBuffer {
3265    /// Allocates one reusable frame for this exact coded size.
3266    ///
3267    /// # Errors
3268    /// Returns an error for a non-positive size or a failed allocation.
3269    pub fn new(width: i32, height: i32) -> Result<Self, BridgeError> {
3270        Self::with_format(width, height, ffi::AV_PIX_FMT_YUV420P)
3271    }
3272
3273    /// Allocates one reusable frame of `format`; each plane's row bytes and rows come from the
3274    /// format's descriptor.
3275    ///
3276    /// # Errors
3277    /// Returns an error for a non-positive size, a format without planes, or a failed allocation.
3278    pub fn with_format(
3279        width: i32,
3280        height: i32,
3281        format: ffi::AVPixelFormat,
3282    ) -> Result<Self, BridgeError> {
3283        let coded_width = usize::try_from(width)
3284            .map_err(|_| BridgeError::InvalidInput("negative frame width"))?;
3285        let coded_height = usize::try_from(height)
3286            .map_err(|_| BridgeError::InvalidInput("negative frame height"))?;
3287        if coded_width == 0 || coded_height == 0 {
3288            return Err(BridgeError::InvalidInput("empty frame"));
3289        }
3290        let planes = plane_geometry(format, width, height)?;
3291        let frame = zeroed_frame(width, height, format)?;
3292        for (index, &(row_bytes, _)) in planes.iter().enumerate() {
3293            if frame.data[index].is_null()
3294                || plane_stride(frame.linesize[index], row_bytes).is_err()
3295            {
3296                return Err(BridgeError::InvalidInput(
3297                    "the frame's planes do not match its pixel format",
3298                ));
3299            }
3300        }
3301        Ok(Self {
3302            frame,
3303            width: coded_width,
3304            height: coded_height,
3305            planes,
3306        })
3307    }
3308
3309    /// Each plane's visible bytes per row and rows, in `FFmpeg`'s plane order.
3310    #[must_use]
3311    pub fn planes(&self) -> &[(usize, usize)] {
3312        &self.planes
3313    }
3314
3315    /// Each plane's memory and stride after making the frame unshared, for any format.
3316    ///
3317    /// # Errors
3318    /// As [`Self::begin_write`].
3319    pub fn begin_write_planes(&mut self) -> Result<Vec<(&mut [u8], usize)>, BridgeError> {
3320        self.make_writable()?;
3321        let mut written = Vec::with_capacity(self.planes.len());
3322        for (index, &(row_bytes, rows)) in self.planes.iter().enumerate() {
3323            let stride = plane_stride(self.frame.linesize[index], row_bytes)?;
3324            // SAFETY: `writable_plane` checks the rows lie in one of the frame's buffers, and
3325            // `make_writable` left this frame their sole owner.
3326            let plane = unsafe { writable_plane(&self.frame, index, stride, row_bytes, rows)? };
3327            written.push((plane, stride));
3328        }
3329        Ok(written)
3330    }
3331
3332    /// Whether another reference, such as an encoder's, still holds this frame's memory.
3333    ///
3334    /// # Errors
3335    /// Returns an error when `FFmpeg` cannot tell.
3336    pub fn is_shared(&self) -> Result<bool, BridgeError> {
3337        Ok(!self.frame.is_writable().map_err(BridgeError::Ffmpeg)?)
3338    }
3339
3340    fn make_writable(&mut self) -> Result<(), BridgeError> {
3341        if self.is_shared()? {
3342            let mut replacement =
3343                zeroed_frame(self.frame.width, self.frame.height, self.frame.format)?;
3344            // SAFETY: both frames are live, `replacement` unshared and `self.frame` only read.
3345            let status =
3346                unsafe { ffi::av_frame_copy_props(replacement.as_mut_ptr(), self.frame.as_ptr()) };
3347            if status < 0 {
3348                return Err(BridgeError::FfmpegCode(status));
3349            }
3350            self.frame = replacement;
3351        }
3352        Ok(())
3353    }
3354
3355    /// Luma width and height in pixels.
3356    #[must_use]
3357    pub const fn dimensions(&self) -> (usize, usize) {
3358        (self.width, self.height)
3359    }
3360
3361    /// Returns the plane memory to overwrite, after making the frame unshared.
3362    ///
3363    /// # Errors
3364    /// Returns an error when the buffer cannot be made writable or its planes changed layout.
3365    pub fn begin_write(&mut self) -> Result<Yuv420pFramePlanes<'_>, BridgeError> {
3366        if self.frame.format != ffi::AV_PIX_FMT_YUV420P {
3367            return Err(BridgeError::InvalidInput("the frame is not YUV420P"));
3368        }
3369        let mut planes = self.begin_write_planes()?.into_iter();
3370        let (Some((y, y_stride)), Some((u, u_stride)), Some((v, v_stride))) =
3371            (planes.next(), planes.next(), planes.next())
3372        else {
3373            return Err(BridgeError::InvalidInput("the frame is not YUV420P"));
3374        };
3375        if u_stride != v_stride {
3376            return Err(BridgeError::InvalidInput("mismatched chroma strides"));
3377        }
3378        Ok(Yuv420pFramePlanes {
3379            y,
3380            y_stride,
3381            u,
3382            v,
3383            chroma_stride: u_stride,
3384        })
3385    }
3386
3387    /// Stamps the presentation timestamp this frame will be encoded with.
3388    pub fn set_presentation(&mut self, pts: i64, time_base: ffi::AVRational) {
3389        self.frame.set_pts(pts);
3390        self.frame.set_time_base(time_base);
3391    }
3392
3393    /// The frame to hand to an encoder.
3394    #[must_use]
3395    pub const fn frame(&self) -> &AVFrame {
3396        &self.frame
3397    }
3398
3399    /// Bytes of the visible planes, without row padding.
3400    #[must_use]
3401    pub fn visible_bytes(&self) -> usize {
3402        if self.planes.is_empty() {
3403            let chroma = self.width.div_ceil(2) * self.height.div_ceil(2);
3404            return self.width * self.height + 2 * chroma;
3405        }
3406        self.planes
3407            .iter()
3408            .map(|&(row_bytes, rows)| row_bytes * rows)
3409            .sum()
3410    }
3411
3412    /// Coded luma dimensions this buffer was allocated for.
3413    #[must_use]
3414    pub const fn size(&self) -> (usize, usize) {
3415        (self.width, self.height)
3416    }
3417}
3418
3419/// A frame of `format` with tightly packed rows, every byte of it zero.
3420fn zeroed_frame(
3421    width: i32,
3422    height: i32,
3423    format: ffi::AVPixelFormat,
3424) -> Result<AVFrame, BridgeError> {
3425    let mut frame = AVFrame::new();
3426    frame.set_format(format);
3427    frame.set_width(width);
3428    frame.set_height(height);
3429    frame.get_buffer(1)?;
3430    for buffer in frame.buf {
3431        // SAFETY: a non-null `AVFrame::buf` entry is live, and this new frame is its only owner.
3432        if let Some(buffer) = unsafe { buffer.as_ref() } {
3433            // SAFETY: as above.
3434            unsafe { ptr::write_bytes(buffer.data, 0, buffer.size) };
3435        }
3436    }
3437    Ok(frame)
3438}
3439
3440impl fmt::Debug for Yuv420pFrameBuffer {
3441    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3442        formatter
3443            .debug_struct("Yuv420pFrameBuffer")
3444            .field("width", &self.width)
3445            .field("height", &self.height)
3446            .finish_non_exhaustive()
3447    }
3448}
3449
3450fn plane_stride(linesize: i32, width: usize) -> Result<usize, BridgeError> {
3451    let stride = usize::try_from(linesize)
3452        .map_err(|_| BridgeError::InvalidInput("negative frame linesize"))?;
3453    if stride < width {
3454        return Err(BridgeError::InvalidInput(
3455            "frame linesize is below its width",
3456        ));
3457    }
3458    Ok(stride)
3459}
3460
3461/// Plane `index` of `frame` as `rows` rows of `stride` bytes, the last one `row_bytes` long.
3462///
3463/// # Safety
3464/// The caller must solely own the frame's buffers for the slice's lifetime.
3465unsafe fn writable_plane<'a>(
3466    frame: &AVFrame,
3467    index: usize,
3468    stride: usize,
3469    row_bytes: usize,
3470    rows: usize,
3471) -> Result<&'a mut [u8], BridgeError> {
3472    let data = frame.data[index];
3473    if data.is_null() {
3474        return Err(BridgeError::InvalidInput("frame plane is null"));
3475    }
3476    let len = stride
3477        .checked_mul(rows.saturating_sub(1))
3478        .and_then(|before| before.checked_add(row_bytes))
3479        .ok_or(BridgeError::InvalidInput("frame plane size overflow"))?;
3480    if !in_frame_buffer(frame, data as usize, len) {
3481        return Err(BridgeError::InvalidInput(
3482            "frame plane extends past its buffer",
3483        ));
3484    }
3485    // SAFETY: the range lies in one of the frame's buffers; exclusivity is the caller's.
3486    Ok(unsafe { slice::from_raw_parts_mut(data, len) })
3487}
3488
3489/// Whether `len` bytes from address `start` lie inside one of `frame`'s buffers.
3490fn in_frame_buffer(frame: &AVFrame, start: usize, len: usize) -> bool {
3491    let Some(end) = start.checked_add(len) else {
3492        return false;
3493    };
3494    frame.buf.iter().any(|buffer| {
3495        // SAFETY: a non-null `AVFrame::buf` entry is a live `AVBufferRef` the frame holds.
3496        let Some(buffer) = (unsafe { buffer.as_ref() }) else {
3497            return false;
3498        };
3499        let buffer_start = buffer.data as usize;
3500        buffer_start
3501            .checked_add(buffer.size)
3502            .is_some_and(|buffer_end| buffer_start <= start && end <= buffer_end)
3503    })
3504}
3505
3506/// Visible bytes per row and rows of each plane of a `width` by `height` frame of `format`.
3507fn plane_geometry(
3508    format: ffi::AVPixelFormat,
3509    width: i32,
3510    height: i32,
3511) -> Result<Vec<(usize, usize)>, BridgeError> {
3512    // SAFETY: `av_pix_fmt_desc_get` accepts any value and returns null or a static descriptor.
3513    let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
3514        .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
3515    // SAFETY: a pure computation over plain values.
3516    let count = unsafe { ffi::av_pix_fmt_count_planes(format) };
3517    let count = usize::try_from(count)
3518        .ok()
3519        .filter(|count| (1..=4).contains(count))
3520        .ok_or(BridgeError::InvalidInput("pixel format has no planes"))?;
3521    let rows = usize::try_from(height).map_err(|_| BridgeError::InvalidInput("negative height"))?;
3522    (0..count)
3523        .map(|index| {
3524            let plane = i32::try_from(index).unwrap_or(i32::MAX);
3525            // SAFETY: a pure computation over plain values.
3526            let row_bytes = unsafe { ffi::av_image_get_linesize(format, width, plane) };
3527            let row_bytes =
3528                usize::try_from(row_bytes).map_err(|_| BridgeError::FfmpegCode(row_bytes))?;
3529            let rows = if index == 1 || index == 2 {
3530                rows.div_ceil(1 << descriptor.log2_chroma_h)
3531            } else {
3532                rows
3533            };
3534            Ok((row_bytes, rows))
3535        })
3536        .collect()
3537}
3538
3539#[cfg(all(test, target_os = "linux", feature = "hwdevice"))]
3540mod vulkan_shim_tests;
3541
3542#[cfg(all(test, target_os = "linux", feature = "hwdevice"))]
3543mod vulkan_access_tests;
3544
3545#[cfg(test)]
3546mod tests;