1use 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#[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
51const _: () = {
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#[cfg(all(
79 any(target_os = "linux", target_os = "macos", target_os = "windows"),
80 feature = "hwdevice"
81))]
82#[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 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 zero_row_padding(&mut software, written.0, written.1)?;
103 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#[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 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 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 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 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 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#[cfg(all(target_os = "windows", feature = "hwdevice"))]
203pub const DXGI_FORMAT_NV12: u32 = 103;
204
205#[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 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
232pub struct D3D12FrameInfo {
233 pub resource: u64,
235 pub fence: u64,
237 pub fence_value: u64,
239 pub device: u64,
241 pub dxgi_format: u32,
243 pub width: i32,
245 pub height: i32,
247 pub software_format: i32,
249 pub surface_width: u32,
251 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#[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 #[must_use]
295 pub fn new(frame: AVFrame) -> Self {
296 Self {
297 frame: Mutex::new(frame),
298 }
299 }
300
301 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 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#[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 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#[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#[cfg(all(target_os = "windows", feature = "hwdevice"))]
370pub fn d3d12_frame_info(frame: &AVFrame) -> Result<D3D12FrameInfo, BridgeError> {
371 let mut descriptor = D3D12FrameDescriptor::default();
372 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#[cfg(all(target_os = "windows", feature = "hwdevice"))]
385pub fn d3d12_frame_fence_value(frame: &AVFrame) -> Result<u64, BridgeError> {
386 let mut value = 0;
387 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#[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 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 #[must_use]
429 pub const fn info(&self) -> &D3D12FrameInfo {
430 &self.info
431 }
432
433 pub fn retain_frame(&self) -> Result<AVFrame, BridgeError> {
438 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 Ok(unsafe { AVFrame::from_raw(raw) })
444 }
445
446 pub fn commit(&mut self, fence_value: u64) -> Result<(), BridgeError> {
451 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#[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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
483pub struct VideoToolboxFrameInfo {
484 pub pixel_buffer: u64,
486 pub width: i32,
488 pub height: i32,
490 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#[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 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#[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 #[must_use]
543 pub fn new(frame: AVFrame) -> Self {
544 Self {
545 frame: Mutex::new(frame),
546 }
547 }
548
549 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 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#[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#[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#[cfg(all(target_os = "linux", feature = "hwdevice"))]
596pub const MAX_VULKAN_PLANES: usize = interop::ALPHA2_MAX_VULKAN_PLANES as usize;
597
598#[cfg(all(target_os = "linux", feature = "hwdevice"))]
600#[derive(Clone, Debug)]
601pub struct VulkanDeviceInfo {
602 pub instance: u64,
604 pub physical_device: u64,
606 pub device: u64,
608 pub graphics_queue_family: u32,
610 pub graphics_queue_count: u32,
612 pub decode_queue_family: u32,
614 pub decode_queue_count: u32,
616 pub decode_video_caps: u32,
618 pub encode_queue_family: u32,
620 pub encode_queue_count: u32,
622 pub encode_video_caps: u32,
624 pub core_features: [u32; 4],
626 pub timeline_semaphore: u32,
628 pub synchronization2: u32,
630 pub sampler_ycbcr_conversion: u32,
632 pub video_maintenance1: u32,
634 pub video_decode_vp9: u32,
636 pub instance_extensions: Vec<String>,
638 pub device_extensions: Vec<String>,
640}
641
642#[cfg(all(target_os = "linux", feature = "hwdevice"))]
643use interop::Alpha2VulkanDeviceInfo as VulkanDeviceDescriptor;
644
645#[cfg(all(target_os = "linux", feature = "hwdevice"))]
650pub struct VulkanQueueLock {
651 device: AVHWDeviceContext,
652 queue_family: u32,
653}
654
655#[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 #[allow(clippy::cast_ptr_alignment)]
678 pub fn new(device: AVHWDeviceContext, queue_family: u32) -> Result<Self, BridgeError> {
679 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 #[must_use]
700 pub fn lock(&self) -> VulkanQueueGuard<'_> {
701 unsafe { self.raw_lock() };
703 VulkanQueueGuard {
704 lock: self,
705 _owning_thread: std::marker::PhantomData,
706 }
707 }
708
709 #[allow(clippy::cast_ptr_alignment)]
715 pub unsafe fn raw_lock(&self) {
716 unsafe {
719 alpha2_vulkan_queue_lock(
720 self.device.data.cast::<ffi::AVHWDeviceContext>(),
721 self.queue_family,
722 );
723 }
724 }
725
726 #[allow(clippy::cast_ptr_alignment)]
732 pub unsafe fn raw_unlock(&self) {
733 unsafe {
735 alpha2_vulkan_queue_unlock(
736 self.device.data.cast::<ffi::AVHWDeviceContext>(),
737 self.queue_family,
738 );
739 }
740 }
741}
742
743#[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 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#[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 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#[cfg(all(target_os = "linux", feature = "hwdevice"))]
846#[derive(Clone, Debug, Eq, PartialEq)]
847pub struct VulkanFrameInfo {
848 pub hardware_format: i32,
850 pub software_format: i32,
852 pub width: i32,
854 pub height: i32,
856 pub coded_width: i32,
858 pub coded_height: i32,
860 pub plane_count: u32,
862 pub sampled: bool,
864 pub instance: u64,
866 pub physical_device: u64,
868 pub device: u64,
870 pub images: [u64; MAX_VULKAN_PLANES],
872 pub formats: [u32; MAX_VULKAN_PLANES],
874 pub layouts: [u32; MAX_VULKAN_PLANES],
876 pub access: [u32; MAX_VULKAN_PLANES],
878 pub semaphores: [u64; MAX_VULKAN_PLANES],
880 pub semaphore_values: [u64; MAX_VULKAN_PLANES],
882 pub queue_families: [u32; MAX_VULKAN_PLANES],
884}
885
886#[cfg(all(target_os = "linux", feature = "hwdevice"))]
888pub type VulkanFrameDescriptor = interop::Alpha2VulkanFrameInfo;
889
890#[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 #[must_use]
903 pub const fn frame(&self) -> &VulkanFrameDescriptor {
904 &self.0.frame
905 }
906
907 pub const fn frame_mut(&mut self) -> &mut VulkanFrameDescriptor {
909 &mut self.0.frame
910 }
911
912 #[must_use]
914 pub const fn allocator(&self) -> u64 {
915 self.0.allocator
916 }
917
918 #[must_use]
920 pub const fn queue_family(&self) -> u32 {
921 self.0.queue_family
922 }
923
924 #[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#[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#[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 #[must_use]
985 pub fn new(frame: AVFrame) -> Self {
986 Self {
987 frame: Mutex::new(frame),
988 }
989 }
990
991 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 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 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 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#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1056pub struct VulkanFrameAccessGuard<'a> {
1057 _frame: MutexGuard<'a, AVFrame>,
1058 begun: interop::Alpha2VulkanFrameAccess,
1060 access: VulkanFrameAccess,
1061 committed: bool,
1062}
1063
1064#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1065impl VulkanFrameAccessGuard<'_> {
1066 #[must_use]
1068 pub const fn access(&self) -> &VulkanFrameAccess {
1069 &self.access
1070 }
1071
1072 #[must_use]
1079 pub const unsafe fn access_mut(&mut self) -> &mut VulkanFrameAccess {
1080 &mut self.access
1081 }
1082
1083 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 unsafe { alpha2_vulkan_frame_access_end(&raw const self.begun, updated) };
1100 }
1101}
1102
1103#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1108pub struct VulkanEncodeFrameAccess<'a> {
1109 frame: &'a mut AVFrame,
1110 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 pub fn retain_frame(&self) -> Result<AVFrame, BridgeError> {
1124 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 Ok(unsafe { AVFrame::from_raw(raw) })
1130 }
1131
1132 pub fn begin(frame: &'a mut AVFrame) -> Result<Self, BridgeError> {
1137 let mut access = VulkanFrameAccess::default();
1138 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 #[must_use]
1155 pub const fn access(&self) -> &VulkanFrameAccess {
1156 &self.access
1157 }
1158
1159 #[must_use]
1165 pub const unsafe fn access_mut(&mut self) -> &mut VulkanFrameAccess {
1166 &mut self.access
1167 }
1168
1169 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 unsafe { alpha2_vulkan_frame_access_end(&raw const self.begun, updated) };
1186 }
1187}
1188
1189#[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#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1204pub fn vulkan_frame_info(frame: &AVFrame) -> Result<VulkanFrameInfo, BridgeError> {
1205 let mut raw = VulkanFrameDescriptor::default();
1206 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#[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 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#[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#[derive(Debug)]
1265#[non_exhaustive]
1266pub enum BridgeError {
1267 InvalidInput(&'static str),
1269 Ffmpeg(RsmpegError),
1271 FfmpegCode(i32),
1274 NativeGpu(NativeGpuFailure),
1276 MissingHwDevice(&'static str),
1278 RuntimeMismatch(&'static str),
1281 UnsupportedSurface(String),
1283}
1284
1285#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1287pub struct YuvPlaneLayout {
1288 pub chroma_shift_x: u8,
1290 pub chroma_shift_y: u8,
1292 pub bit_depth: u8,
1294 pub interleaved_chroma: bool,
1296 pub msb_aligned: bool,
1298}
1299
1300impl YuvPlaneLayout {
1301 #[must_use]
1303 pub const fn bytes_per_sample(self) -> u32 {
1304 if self.bit_depth > 8 { 2 } else { 1 }
1305 }
1306}
1307
1308#[derive(Clone, Debug, Eq, PartialEq)]
1310pub struct FramePlane {
1311 pub bytes: bytes::Bytes,
1313 pub stride: u32,
1315 pub width: u32,
1317 pub height: u32,
1319}
1320
1321#[derive(Clone, Debug, Eq, PartialEq)]
1323pub struct YuvPlanes {
1324 pub layout: YuvPlaneLayout,
1326 pub width: u32,
1328 pub height: u32,
1330 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
1352fn 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 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
1384const SCALER_DESTINATION_ALIGN: i32 = 64;
1386
1387pub 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 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 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 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 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 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 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
1531fn 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 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
1553fn 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 if let Some(buffer) = unsafe { buffer.as_ref() } {
1567 unsafe { ptr::write_bytes(buffer.data, 0, buffer.size) };
1569 }
1570 }
1571 Ok(frame)
1572}
1573
1574fn scale_into(
1577 context: &mut SwsContext,
1578 source: &AVFrame,
1579 destination: &mut AVFrame,
1580 height: i32,
1581) -> Result<(), BridgeError> {
1582 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 #[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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1622pub enum NativeGpuBackend {
1623 Vulkan,
1625 D3D12,
1627 Metal,
1629}
1630
1631impl NativeGpuBackend {
1632 #[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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1647pub struct NativeGpuFailure {
1648 pub backend: NativeGpuBackend,
1650 pub operation: &'static str,
1652 pub step: &'static str,
1654 pub status: i32,
1656 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 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#[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 let compiled = unsafe { alpha2_ffmpeg_shim_avutil_version() };
1713 let loaded = unsafe { ffi::avutil_version() };
1715 interop_version_refusal(compiled, loaded)
1716 })
1717 .as_deref()
1718}
1719
1720fn 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
1733pub fn check_hardware_interop() -> Result<(), BridgeError> {
1738 hardware_interop_refusal().map_or(Ok(()), |reason| Err(BridgeError::RuntimeMismatch(reason)))
1739}
1740
1741#[must_use]
1743pub fn runtime_version() -> String {
1744 unsafe { CStr::from_ptr(ffi::av_version_info()) }
1746 .to_string_lossy()
1747 .into_owned()
1748}
1749
1750#[must_use]
1752pub fn runtime_configuration() -> String {
1753 unsafe { CStr::from_ptr(ffi::avcodec_configuration()) }
1755 .to_string_lossy()
1756 .into_owned()
1757}
1758
1759#[must_use]
1761pub fn muxer_accepts_codec(format: &CStr, codec: ffi::AVCodecID) -> Option<bool> {
1762 let muxer = unsafe { ffi::av_guess_format(format.as_ptr(), ptr::null(), ptr::null()) };
1765 if muxer.is_null() {
1766 return None;
1767 }
1768 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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1781pub struct SampleProfile {
1782 pub is_yuv_420: bool,
1784 pub bit_depth: u8,
1786 pub has_alpha: bool,
1788 pub is_rgb: bool,
1790}
1791
1792#[must_use]
1796pub fn sample_profile(format: ffi::AVPixelFormat) -> Option<SampleProfile> {
1797 if format == ffi::AV_PIX_FMT_NONE {
1798 return None;
1799 }
1800 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#[must_use]
1821pub fn pixel_format_name(format: ffi::AVPixelFormat) -> Option<String> {
1822 let name = unsafe { ffi::av_get_pix_fmt_name(format) };
1824 if name.is_null() {
1825 None
1826 } else {
1827 Some(
1829 unsafe { CStr::from_ptr(name) }
1830 .to_string_lossy()
1831 .into_owned(),
1832 )
1833 }
1834}
1835
1836pub 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 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 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
1868fn 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 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
1887pub 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#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1926pub const VULKAN_ENCODE_INPUT_USAGE: u32 = 0x0000_0001 | 0x0000_0002 | 0x0000_0004 | 0x0000_4000;
1927
1928#[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 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#[cfg(all(target_os = "linux", feature = "hwdevice"))]
1952#[must_use]
1953pub fn vulkan_frames_usage(frames: &rsmpeg::avutil::AVHWFramesContext) -> u32 {
1954 unsafe { alpha2_vulkan_frames_usage(frames.as_ptr()) }
1956}
1957
1958#[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 unsafe { slice::from_raw_parts(packet.data.cast_const(), size) }.to_vec()
1967}
1968
1969#[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 unsafe { slice::from_raw_parts(parameters.extradata.cast_const(), size) }.to_vec()
1987}
1988
1989#[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 !unsafe { ffi::av_packet_get_side_data(packet.as_ptr(), kind, &raw mut size) }.is_null()
1998}
1999
2000#[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 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 let bytes = unsafe { slice::from_raw_parts(data, size) }.to_vec();
2017 let packet = packet.as_mut_ptr();
2018 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#[must_use]
2033pub fn packet_block_addition(packet: &rsmpeg::avcodec::AVPacket, id: u64) -> Option<&[u8]> {
2034 let count = usize::try_from(packet.side_data_elems).ok()?;
2035 if count == 0 || packet.side_data.is_null() {
2036 return None;
2037 }
2038 let entries = unsafe { slice::from_raw_parts(packet.side_data, count) };
2040 entries
2041 .iter()
2042 .filter(|entry| {
2043 entry.type_ == ffi::AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL
2044 && !entry.data.is_null()
2045 && entry.size >= 8
2046 })
2047 .map(|entry| unsafe { slice::from_raw_parts(entry.data, entry.size) })
2049 .find(|data| data[..8] == id.to_be_bytes())
2050 .map(|data| &data[8..])
2051}
2052
2053#[must_use]
2056pub fn vp9_frame_is_keyframe(data: &[u8]) -> bool {
2057 let Some(&header) = data.first() else {
2058 return false;
2059 };
2060 let bit = |index: u32| (header >> (7 - index)) & 1 == 1;
2061 if header >> 6 != 0b10 {
2062 return false;
2063 }
2064 let profile = u8::from(bit(2)) | (u8::from(bit(3)) << 1);
2065 let next = if profile == 3 { 5 } else { 4 };
2066 !bit(next) && !bit(next + 1)
2067}
2068
2069pub fn set_frame_color(
2072 frame: &mut rsmpeg::avutil::AVFrame,
2073 (primaries, transfer, space, range): (
2074 ffi::AVColorPrimaries,
2075 ffi::AVColorTransferCharacteristic,
2076 ffi::AVColorSpace,
2077 ffi::AVColorRange,
2078 ),
2079) {
2080 let raw = frame.as_mut_ptr();
2081 unsafe {
2083 (*raw).color_primaries = primaries;
2084 (*raw).color_trc = transfer;
2085 (*raw).colorspace = space;
2086 (*raw).color_range = range;
2087 }
2088}
2089
2090pub fn set_packet_side_data(
2095 packet: &mut rsmpeg::avcodec::AVPacket,
2096 kind: ffi::AVPacketSideDataType,
2097 data: &[u8],
2098) -> Result<(), BridgeError> {
2099 let _ = take_packet_side_data(packet, kind);
2100 let entry = unsafe { ffi::av_packet_new_side_data(packet.as_mut_ptr(), kind, data.len()) };
2103 if entry.is_null() {
2104 return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2105 }
2106 unsafe { ptr::copy_nonoverlapping(data.as_ptr(), entry, data.len()) };
2108 Ok(())
2109}
2110
2111pub fn set_output_stream_extradata(
2119 output: &mut rsmpeg::avformat::AVFormatContextOutput,
2120 index: usize,
2121 data: &[u8],
2122) -> Result<(), BridgeError> {
2123 let parameters = output
2124 .streams()
2125 .get(index)
2126 .ok_or(BridgeError::InvalidInput("the output has no such stream"))?
2127 .codecpar;
2128 let size = i32::try_from(data.len())
2129 .map_err(|_| BridgeError::InvalidInput("extradata is larger than FFmpeg holds"))?;
2130 let padding = usize::try_from(ffi::AV_INPUT_BUFFER_PADDING_SIZE).unwrap_or(64);
2131 let buffer = unsafe { ffi::av_mallocz(data.len() + padding) }.cast::<u8>();
2133 if buffer.is_null() {
2134 return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2135 }
2136 unsafe { ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len()) };
2138 unsafe {
2141 ffi::av_freep((&raw mut (*parameters).extradata).cast());
2142 (*parameters).extradata = buffer;
2143 (*parameters).extradata_size = size;
2144 }
2145 Ok(())
2146}
2147
2148pub fn packet_from_bytes(data: &[u8]) -> Result<rsmpeg::avcodec::AVPacket, BridgeError> {
2153 let size = i32::try_from(data.len())
2154 .map_err(|_| BridgeError::InvalidInput("a packet is larger than FFmpeg holds"))?;
2155 let mut packet = rsmpeg::avcodec::AVPacket::new();
2156 let status = unsafe { ffi::av_new_packet(packet.as_mut_ptr(), size) };
2158 if status < 0 {
2159 return Err(BridgeError::FfmpegCode(status));
2160 }
2161 if !data.is_empty() {
2162 unsafe { ptr::copy_nonoverlapping(data.as_ptr(), packet.data, data.len()) };
2164 }
2165 Ok(packet)
2166}
2167
2168pub fn shrink_packet_to(
2173 packet: &mut rsmpeg::avcodec::AVPacket,
2174 data: &[u8],
2175) -> Result<(), BridgeError> {
2176 let size = i32::try_from(data.len())
2177 .ok()
2178 .filter(|size| *size <= packet.size)
2179 .ok_or(BridgeError::InvalidInput("a packet cannot grow in place"))?;
2180 let status = unsafe { ffi::av_packet_make_writable(packet.as_mut_ptr()) };
2182 if status < 0 {
2183 return Err(BridgeError::FfmpegCode(status));
2184 }
2185 if !data.is_empty() {
2186 unsafe { ptr::copy_nonoverlapping(data.as_ptr(), packet.data, data.len()) };
2188 }
2189 unsafe { ffi::av_shrink_packet(packet.as_mut_ptr(), size) };
2191 Ok(())
2192}
2193
2194#[derive(Clone, Copy, Debug)]
2196pub struct VideoStreamDescription<'a> {
2197 pub codec_id: ffi::AVCodecID,
2199 pub width: i32,
2201 pub height: i32,
2203 pub pixel_format: ffi::AVPixelFormat,
2205 pub profile: i32,
2207 pub level: i32,
2209 pub color_primaries: ffi::AVColorPrimaries,
2211 pub color_trc: ffi::AVColorTransferCharacteristic,
2213 pub color_space: ffi::AVColorSpace,
2215 pub color_range: ffi::AVColorRange,
2217 pub sample_aspect_ratio: ffi::AVRational,
2219 pub frame_rate: ffi::AVRational,
2221 pub bit_rate: i64,
2223 pub extradata: &'a [u8],
2225}
2226
2227pub fn video_codec_parameters(
2232 description: &VideoStreamDescription<'_>,
2233) -> Result<rsmpeg::avcodec::AVCodecParameters, BridgeError> {
2234 let extradata_size = i32::try_from(description.extradata.len())
2235 .map_err(|_| BridgeError::InvalidInput("extradata is larger than FFmpeg holds"))?;
2236 let mut parameters = rsmpeg::avcodec::AVCodecParameters::new();
2237 let raw = parameters.as_mut_ptr();
2238 unsafe {
2240 (*raw).codec_type = ffi::AVMEDIA_TYPE_VIDEO;
2241 (*raw).codec_id = description.codec_id;
2242 (*raw).width = description.width;
2243 (*raw).height = description.height;
2244 (*raw).format = description.pixel_format;
2245 (*raw).profile = description.profile;
2246 (*raw).level = description.level;
2247 (*raw).color_primaries = description.color_primaries;
2248 (*raw).color_trc = description.color_trc;
2249 (*raw).color_space = description.color_space;
2250 (*raw).color_range = description.color_range;
2251 (*raw).sample_aspect_ratio = description.sample_aspect_ratio;
2252 (*raw).framerate = description.frame_rate;
2253 (*raw).bit_rate = description.bit_rate;
2254 (*raw).field_order = ffi::AV_FIELD_PROGRESSIVE;
2255 }
2256 if !description.extradata.is_empty() {
2257 let padding = usize::try_from(ffi::AV_INPUT_BUFFER_PADDING_SIZE).unwrap_or(64);
2258 let buffer = unsafe { ffi::av_mallocz(description.extradata.len() + padding) }.cast::<u8>();
2260 if buffer.is_null() {
2261 return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2262 }
2263 unsafe {
2266 ptr::copy_nonoverlapping(
2267 description.extradata.as_ptr(),
2268 buffer,
2269 description.extradata.len(),
2270 );
2271 (*raw).extradata = buffer;
2272 (*raw).extradata_size = extradata_size;
2273 }
2274 }
2275 Ok(parameters)
2276}
2277
2278pub fn bitstream_filter_list(
2287 spec: &CStr,
2288 parameters: &AVCodecParameters,
2289 time_base: rsmpeg::avutil::AVRational,
2290) -> Result<rsmpeg::avcodec::AVBSFContext, BridgeError> {
2291 let mut raw = ptr::null_mut();
2292 let status = unsafe { ffi::av_bsf_list_parse_str(spec.as_ptr(), &raw mut raw) };
2294 if status < 0 {
2295 return Err(BridgeError::FfmpegCode(status));
2296 }
2297 let raw = ptr::NonNull::new(raw).ok_or(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)))?;
2298 let mut context = unsafe { rsmpeg::avcodec::AVBSFContextUninit::from_raw(raw) };
2300 let status = unsafe { ffi::avcodec_parameters_copy(context.par_in, parameters.as_ptr()) };
2304 if status < 0 {
2305 return Err(BridgeError::FfmpegCode(status));
2306 }
2307 context.set_time_base_in(time_base);
2308 context.init().map_err(BridgeError::Ffmpeg)
2309}
2310
2311pub fn set_stream_codec_tag(stream: &mut rsmpeg::avformat::AVStreamMut<'_>, tag: u32) {
2313 let mut parameters = stream.codecpar_mut();
2314 unsafe { (*parameters.as_mut_ptr()).codec_tag = tag };
2316}
2317
2318pub fn set_stream_display_matrix(
2324 stream: &mut rsmpeg::avformat::AVStreamMut<'_>,
2325 display: DisplayRotation,
2326) -> Result<(), BridgeError> {
2327 let mut parameters = stream.codecpar_mut();
2328 let parameters = parameters.as_mut_ptr();
2329 let entry = unsafe {
2332 ffi::av_packet_side_data_new(
2333 &raw mut (*parameters).coded_side_data,
2334 &raw mut (*parameters).nb_coded_side_data,
2335 ffi::AV_PKT_DATA_DISPLAYMATRIX,
2336 size_of::<[i32; 9]>(),
2337 0,
2338 )
2339 };
2340 if entry.is_null() {
2341 return Err(BridgeError::FfmpegCode(ffi::AVERROR(ffi::ENOMEM)));
2342 }
2343 let mut matrix = [0_i32; 9];
2344 unsafe {
2347 ffi::av_display_rotation_set(matrix.as_mut_ptr(), -display.counter_clockwise_degrees);
2348 if display.flipped {
2349 ffi::av_display_matrix_flip(matrix.as_mut_ptr(), 1, 0);
2350 }
2351 }
2352 unsafe {
2355 ptr::copy_nonoverlapping(
2356 matrix.as_ptr().cast::<u8>(),
2357 (*entry).data,
2358 size_of::<[i32; 9]>(),
2359 );
2360 }
2361 Ok(())
2362}
2363
2364#[must_use]
2366pub fn hardware_device_type_name(device_type: ffi::AVHWDeviceType) -> Option<String> {
2367 let name = unsafe { ffi::av_hwdevice_get_type_name(device_type) };
2369 if name.is_null() {
2370 None
2371 } else {
2372 Some(
2374 unsafe { CStr::from_ptr(name) }
2375 .to_string_lossy()
2376 .into_owned(),
2377 )
2378 }
2379}
2380
2381#[must_use]
2388pub fn yuv_layout(format: ffi::AVPixelFormat) -> Option<YuvPlaneLayout> {
2389 if format == ffi::AV_PIX_FMT_NONE {
2390 return None;
2391 }
2392 let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }?;
2394 let foreign_endian = if cfg!(target_endian = "little") {
2395 ffi::AV_PIX_FMT_FLAG_BE
2396 } else {
2397 0
2398 };
2399 let rejected = foreign_endian
2400 | ffi::AV_PIX_FMT_FLAG_PAL
2401 | ffi::AV_PIX_FMT_FLAG_BITSTREAM
2402 | ffi::AV_PIX_FMT_FLAG_HWACCEL
2403 | ffi::AV_PIX_FMT_FLAG_RGB
2404 | ffi::AV_PIX_FMT_FLAG_ALPHA
2405 | ffi::AV_PIX_FMT_FLAG_BAYER
2406 | ffi::AV_PIX_FMT_FLAG_FLOAT
2407 | ffi::AV_PIX_FMT_FLAG_XYZ;
2408 if descriptor.flags & u64::from(rejected) != 0 || descriptor.nb_components != 3 {
2409 return None;
2410 }
2411 let [luma, u, v, _] = descriptor.comp;
2412 let depth = luma.depth;
2413 if !(8..=16).contains(&depth) || u.depth != depth || v.depth != depth {
2414 return None;
2415 }
2416 if descriptor.log2_chroma_w > 2 || descriptor.log2_chroma_h > 2 {
2417 return None;
2418 }
2419 let bytes = if depth > 8 { 2 } else { 1 };
2420 let shift = luma.shift;
2421 let msb_aligned = match shift {
2422 0 => false,
2423 _ if depth > 8 && shift == 16 - depth => true,
2424 _ => return None,
2425 };
2426 let planar = u.plane == 1
2427 && v.plane == 2
2428 && u.step == bytes
2429 && v.step == bytes
2430 && u.offset == 0
2431 && v.offset == 0;
2432 let interleaved = u.plane == 1
2433 && v.plane == 1
2434 && u.step == 2 * bytes
2435 && v.step == 2 * bytes
2436 && u.offset == 0
2437 && v.offset == bytes;
2438 if luma.plane != 0
2439 || luma.step != bytes
2440 || luma.offset != 0
2441 || u.shift != shift
2442 || v.shift != shift
2443 || !(planar || interleaved)
2444 {
2445 return None;
2446 }
2447 Some(YuvPlaneLayout {
2448 chroma_shift_x: descriptor.log2_chroma_w,
2449 chroma_shift_y: descriptor.log2_chroma_h,
2450 bit_depth: u8::try_from(depth).ok()?,
2451 interleaved_chroma: interleaved,
2452 msb_aligned,
2453 })
2454}
2455
2456pub fn yuv_planes(frame: &AVFrame) -> Result<Option<YuvPlanes>, BridgeError> {
2465 frame_yuv_planes(frame, false)
2466}
2467
2468pub struct DecodedFrame {
2472 frame: AVFrame,
2473 written: bool,
2474}
2475
2476impl DecodedFrame {
2477 pub fn receive(decoder: &mut AVCodecContext) -> Result<Self, RsmpegError> {
2482 let written = decoder_frames_are_initialized(decoder);
2483 let frame = decoder.receive_frame()?;
2484 Ok(Self { frame, written })
2485 }
2486
2487 pub fn yuv_planes(&self) -> Result<Option<YuvPlanes>, BridgeError> {
2494 frame_yuv_planes(&self.frame, self.written)
2495 }
2496
2497 pub fn set_pts(&mut self, pts: i64) {
2499 self.frame.set_pts(pts);
2500 }
2501
2502 #[must_use]
2504 pub fn into_frame(self) -> AVFrame {
2505 self.frame
2506 }
2507}
2508
2509impl std::ops::Deref for DecodedFrame {
2510 type Target = AVFrame;
2511
2512 fn deref(&self) -> &AVFrame {
2513 &self.frame
2514 }
2515}
2516
2517impl fmt::Debug for DecodedFrame {
2518 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2519 formatter
2520 .debug_struct("DecodedFrame")
2521 .field("format", &self.frame.format)
2522 .field("width", &self.frame.width)
2523 .field("height", &self.frame.height)
2524 .field("pts", &self.frame.pts)
2525 .field("written", &self.written)
2526 .finish_non_exhaustive()
2527 }
2528}
2529
2530fn decoder_frames_are_initialized(decoder: &AVCodecContext) -> bool {
2535 static DEFAULT_GET_BUFFER2: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2536 let default = *DEFAULT_GET_BUFFER2.get_or_init(|| {
2538 unsafe {
2540 let mut context = ffi::avcodec_alloc_context3(ptr::null());
2541 let get_buffer2 = context
2542 .as_ref()
2543 .and_then(|context| context.get_buffer2)
2544 .map_or(0, |function| function as usize);
2545 ffi::avcodec_free_context(&raw mut context);
2546 get_buffer2
2547 }
2548 });
2549 let wrapped =
2551 unsafe { decoder.codec.as_ref() }.is_none_or(|codec| !codec.wrapper_name.is_null());
2552 let get_buffer2 = decoder.get_buffer2.map_or(0, |function| function as usize);
2553 !wrapped && default != 0 && get_buffer2 == default
2554}
2555
2556fn frame_yuv_planes(frame: &AVFrame, share: bool) -> Result<Option<YuvPlanes>, BridgeError> {
2558 let Some(layout) = yuv_layout(frame.format) else {
2559 return Ok(None);
2560 };
2561 let width =
2562 u32::try_from(frame.width).map_err(|_| BridgeError::InvalidInput("negative YUV width"))?;
2563 let height = u32::try_from(frame.height)
2564 .map_err(|_| BridgeError::InvalidInput("negative YUV height"))?;
2565 if width == 0 || height == 0 {
2566 return Err(BridgeError::InvalidInput("empty YUV frame"));
2567 }
2568 let bytes = layout.bytes_per_sample();
2569 let chroma_width = width.div_ceil(1 << layout.chroma_shift_x);
2570 let chroma_height = height.div_ceil(1 << layout.chroma_shift_y);
2571 let shared =
2573 (share && !frame.buf[0].is_null()).then(|| std::sync::Arc::new(SharedFrame(frame.clone())));
2574 let copy = |index: usize,
2575 samples: u32,
2576 pairs: u32,
2577 rows: u32,
2578 context: &'static str|
2579 -> Result<FramePlane, BridgeError> {
2580 let row_bytes = samples
2581 .checked_mul(bytes)
2582 .and_then(|row| row.checked_mul(pairs))
2583 .ok_or(BridgeError::InvalidInput(context))?;
2584 if let Some(view) = shared
2585 .as_ref()
2586 .and_then(|frame| PlaneView::new(frame, index, row_bytes, rows))
2587 {
2588 let stride =
2589 u32::try_from(view.stride).map_err(|_| BridgeError::InvalidInput(context))?;
2590 return Ok(FramePlane {
2591 bytes: bytes::Bytes::from_owner(view),
2592 stride,
2593 width: samples,
2594 height: rows,
2595 });
2596 }
2597 Ok(FramePlane {
2598 bytes: copy_video_plane(frame, index, row_bytes, rows, context)?.into(),
2599 stride: row_bytes,
2600 width: samples,
2601 height: rows,
2602 })
2603 };
2604 let mut planes = vec![copy(0, width, 1, height, "invalid Y plane")?];
2605 if layout.interleaved_chroma {
2606 planes.push(copy(1, chroma_width, 2, chroma_height, "invalid UV plane")?);
2607 } else {
2608 planes.push(copy(1, chroma_width, 1, chroma_height, "invalid U plane")?);
2609 planes.push(copy(2, chroma_width, 1, chroma_height, "invalid V plane")?);
2610 }
2611 Ok(Some(YuvPlanes {
2612 layout,
2613 width,
2614 height,
2615 planes,
2616 }))
2617}
2618
2619struct SharedFrame(AVFrame);
2621
2622unsafe impl Sync for SharedFrame {}
2625
2626struct PlaneView {
2628 frame: std::sync::Arc<SharedFrame>,
2629 data: *const u8,
2630 len: usize,
2631 stride: usize,
2632}
2633
2634unsafe impl Send for PlaneView {}
2637
2638impl PlaneView {
2639 fn new(
2641 frame: &std::sync::Arc<SharedFrame>,
2642 index: usize,
2643 row_bytes: u32,
2644 rows: u32,
2645 ) -> Option<Self> {
2646 let inner = &frame.0;
2647 let data = inner.data[index].cast_const();
2648 let stride = usize::try_from(inner.linesize[index]).ok()?;
2649 let row_bytes = usize::try_from(row_bytes).ok()?;
2650 if data.is_null() || stride < row_bytes || rows == 0 {
2651 return None;
2652 }
2653 let len = stride.checked_mul(usize::try_from(rows).ok()?)?;
2654 in_frame_buffer(inner, data as usize, len).then(|| Self {
2655 frame: std::sync::Arc::clone(frame),
2656 data,
2657 len,
2658 stride,
2659 })
2660 }
2661}
2662
2663impl AsRef<[u8]> for PlaneView {
2664 fn as_ref(&self) -> &[u8] {
2665 let _ = &self.frame;
2666 unsafe { slice::from_raw_parts(self.data, self.len) }
2668 }
2669}
2670
2671fn copy_video_plane(
2673 frame: &AVFrame,
2674 index: usize,
2675 width: u32,
2676 height: u32,
2677 context: &'static str,
2678) -> Result<Vec<u8>, BridgeError> {
2679 let (data, linesize) = (frame.data[index].cast_const(), frame.linesize[index]);
2680 let has_buffers = frame.buf.iter().any(|buffer| !buffer.is_null());
2681 if has_buffers && !plane_rows_in_frame_buffer(frame, data, linesize, width, height) {
2682 return Err(BridgeError::InvalidInput(context));
2683 }
2684 unsafe { copy_plane_rows(data, linesize, width, height, context) }
2687}
2688
2689fn plane_rows_in_frame_buffer(
2691 frame: &AVFrame,
2692 data: *const u8,
2693 linesize: i32,
2694 width: u32,
2695 height: u32,
2696) -> bool {
2697 let (Ok(row_bytes), Ok(rows)) = (usize::try_from(width), usize::try_from(height)) else {
2698 return false;
2699 };
2700 let Ok(stride) = usize::try_from(linesize.unsigned_abs()) else {
2701 return false;
2702 };
2703 let Some(span) = stride
2704 .checked_mul(rows.saturating_sub(1))
2705 .and_then(|before| before.checked_add(row_bytes))
2706 else {
2707 return false;
2708 };
2709 let start = if linesize < 0 {
2711 (data as usize).checked_sub(span - row_bytes)
2712 } else {
2713 Some(data as usize)
2714 };
2715 !data.is_null() && rows > 0 && start.is_some_and(|start| in_frame_buffer(frame, start, span))
2716}
2717
2718unsafe fn copy_plane_rows(
2721 data: *const u8,
2722 linesize: i32,
2723 width: u32,
2724 height: u32,
2725 context: &'static str,
2726) -> Result<Vec<u8>, BridgeError> {
2727 let row_bytes = usize::try_from(width).map_err(|_| BridgeError::InvalidInput(context))?;
2728 let rows = usize::try_from(height).map_err(|_| BridgeError::InvalidInput(context))?;
2729 let stride =
2730 usize::try_from(linesize.unsigned_abs()).map_err(|_| BridgeError::InvalidInput(context))?;
2731 if data.is_null() || linesize == 0 || stride < row_bytes {
2732 return Err(BridgeError::InvalidInput(context));
2733 }
2734 let byte_len = row_bytes
2735 .checked_mul(rows)
2736 .ok_or(BridgeError::InvalidInput(context))?;
2737 let mut output = Vec::with_capacity(byte_len);
2739 let signed_stride =
2740 isize::try_from(linesize).map_err(|_| BridgeError::InvalidInput(context))?;
2741 for row in 0..rows {
2742 let row = isize::try_from(row).map_err(|_| BridgeError::InvalidInput(context))?;
2743 let offset = row
2744 .checked_mul(signed_stride)
2745 .ok_or(BridgeError::InvalidInput(context))?;
2746 let source = unsafe { slice::from_raw_parts(data.offset(offset), row_bytes) };
2748 output.extend_from_slice(source);
2749 }
2750 debug_assert_eq!(output.len(), byte_len);
2751 Ok(output)
2752}
2753
2754pub fn rgba_frame(bytes: &[u8], width: i32, height: i32) -> Result<AVFrame, BridgeError> {
2759 let row_bytes = usize::try_from(width)
2760 .ok()
2761 .and_then(|value| value.checked_mul(4))
2762 .ok_or(BridgeError::InvalidInput("RGBA row width overflow"))?;
2763 let rows =
2764 usize::try_from(height).map_err(|_| BridgeError::InvalidInput("negative RGBA height"))?;
2765 let expected = row_bytes
2766 .checked_mul(rows)
2767 .ok_or(BridgeError::InvalidInput("RGBA frame size overflow"))?;
2768 if bytes.len() != expected {
2769 return Err(BridgeError::InvalidInput("RGBA byte length mismatch"));
2770 }
2771
2772 let mut frame = AVFrame::new();
2773 frame.set_format(ffi::AV_PIX_FMT_RGBA);
2774 frame.set_width(width);
2775 frame.set_height(height);
2776 frame.get_buffer(1)?;
2777 frame.make_writable()?;
2778 let linesize = usize::try_from(frame.linesize[0])
2779 .map_err(|_| BridgeError::InvalidInput("negative RGBA linesize"))?;
2780 if frame.data[0].is_null() || linesize < row_bytes {
2781 return Err(BridgeError::InvalidInput(
2782 "RGBA destination plane is too small",
2783 ));
2784 }
2785
2786 unsafe {
2789 for row in 0..rows {
2790 let destination_offset = row.checked_mul(linesize).ok_or(BridgeError::InvalidInput(
2791 "RGBA destination offset overflow",
2792 ))?;
2793 let source_offset = row
2794 .checked_mul(row_bytes)
2795 .ok_or(BridgeError::InvalidInput("RGBA source offset overflow"))?;
2796 let destination =
2797 slice::from_raw_parts_mut(frame.data[0].add(destination_offset), row_bytes);
2798 destination.copy_from_slice(&bytes[source_offset..source_offset + row_bytes]);
2799 }
2800 }
2801 Ok(frame)
2802}
2803
2804#[allow(clippy::too_many_arguments)]
2809pub fn yuv420p_frame(
2810 y: &[u8],
2811 y_stride: u32,
2812 u: &[u8],
2813 u_stride: u32,
2814 v: &[u8],
2815 v_stride: u32,
2816 width: i32,
2817 height: i32,
2818) -> Result<AVFrame, BridgeError> {
2819 let width =
2820 u32::try_from(width).map_err(|_| BridgeError::InvalidInput("negative YUV width"))?;
2821 let height =
2822 u32::try_from(height).map_err(|_| BridgeError::InvalidInput("negative YUV height"))?;
2823 if width == 0 || height == 0 {
2824 return Err(BridgeError::InvalidInput("empty YUV frame"));
2825 }
2826 let chroma_width = width.div_ceil(2);
2827 let chroma_height = height.div_ceil(2);
2828 validate_source_plane(y, y_stride, width, height, "invalid Y source plane")?;
2829 validate_source_plane(
2830 u,
2831 u_stride,
2832 chroma_width,
2833 chroma_height,
2834 "invalid U source plane",
2835 )?;
2836 validate_source_plane(
2837 v,
2838 v_stride,
2839 chroma_width,
2840 chroma_height,
2841 "invalid V source plane",
2842 )?;
2843
2844 let mut frame = AVFrame::new();
2845 frame.set_format(ffi::AV_PIX_FMT_YUV420P);
2846 frame.set_width(i32::try_from(width).map_err(|_| BridgeError::InvalidInput("YUV width"))?);
2847 frame.set_height(i32::try_from(height).map_err(|_| BridgeError::InvalidInput("YUV height"))?);
2848 frame.get_buffer(1)?;
2849 frame.make_writable()?;
2850 copy_plane_to_frame(y, y_stride, width, height, frame.data[0], frame.linesize[0])?;
2851 copy_plane_to_frame(
2852 u,
2853 u_stride,
2854 chroma_width,
2855 chroma_height,
2856 frame.data[1],
2857 frame.linesize[1],
2858 )?;
2859 copy_plane_to_frame(
2860 v,
2861 v_stride,
2862 chroma_width,
2863 chroma_height,
2864 frame.data[2],
2865 frame.linesize[2],
2866 )?;
2867 Ok(frame)
2868}
2869
2870#[must_use]
2873pub fn yuv_pixel_format(layout: YuvPlaneLayout) -> Option<ffi::AVPixelFormat> {
2874 let mut descriptor = ptr::null();
2875 loop {
2876 descriptor = unsafe { ffi::av_pix_fmt_desc_next(descriptor) };
2878 if descriptor.is_null() {
2879 return None;
2880 }
2881 let format = unsafe { ffi::av_pix_fmt_desc_get_id(descriptor) };
2883 if yuv_layout(format) == Some(layout) {
2884 return Some(format);
2885 }
2886 }
2887}
2888
2889pub fn planar_frame(
2894 format: ffi::AVPixelFormat,
2895 planes: &[(&[u8], u32)],
2896 width: u32,
2897 height: u32,
2898) -> Result<AVFrame, BridgeError> {
2899 let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
2901 .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
2902 let count = unsafe { ffi::av_pix_fmt_count_planes(format) };
2904 if usize::try_from(count).ok() != Some(planes.len()) || width == 0 || height == 0 {
2905 return Err(BridgeError::InvalidInput(
2906 "planes do not match the pixel format",
2907 ));
2908 }
2909 let signed = |value: u32| {
2910 i32::try_from(value).map_err(|_| BridgeError::InvalidInput("frame size overflow"))
2911 };
2912 let mut frame = AVFrame::new();
2913 frame.set_format(format);
2914 frame.set_width(signed(width)?);
2915 frame.set_height(signed(height)?);
2916 frame.get_buffer(1)?;
2917 frame.make_writable()?;
2918 for (index, (bytes, stride)) in planes.iter().enumerate() {
2919 let plane = i32::try_from(index).unwrap_or(i32::MAX);
2920 let row_bytes = unsafe { ffi::av_image_get_linesize(format, signed(width)?, plane) };
2922 let row_bytes = u32::try_from(row_bytes).map_err(|_| BridgeError::FfmpegCode(row_bytes))?;
2923 let rows = if index == 0 || index == 3 {
2924 height
2925 } else {
2926 height.div_ceil(1 << descriptor.log2_chroma_h)
2927 };
2928 validate_source_plane(bytes, *stride, row_bytes, rows, "invalid source plane")?;
2929 copy_plane_to_frame(
2930 bytes,
2931 *stride,
2932 row_bytes,
2933 rows,
2934 frame.data[index],
2935 frame.linesize[index],
2936 )?;
2937 }
2938 Ok(frame)
2939}
2940
2941fn validate_source_plane(
2942 bytes: &[u8],
2943 stride: u32,
2944 width: u32,
2945 height: u32,
2946 context: &'static str,
2947) -> Result<(), BridgeError> {
2948 let required = usize::try_from(stride).ok().and_then(|stride| {
2949 usize::try_from(height)
2950 .ok()
2951 .and_then(|height| stride.checked_mul(height))
2952 });
2953 if stride < width || required != Some(bytes.len()) {
2954 Err(BridgeError::InvalidInput(context))
2955 } else {
2956 Ok(())
2957 }
2958}
2959
2960fn copy_plane_to_frame(
2961 source: &[u8],
2962 source_stride: u32,
2963 width: u32,
2964 height: u32,
2965 destination: *mut u8,
2966 destination_stride: i32,
2967) -> Result<(), BridgeError> {
2968 let row_bytes =
2969 usize::try_from(width).map_err(|_| BridgeError::InvalidInput("YUV row width overflow"))?;
2970 let rows =
2971 usize::try_from(height).map_err(|_| BridgeError::InvalidInput("YUV row count overflow"))?;
2972 let source_stride = usize::try_from(source_stride)
2973 .map_err(|_| BridgeError::InvalidInput("YUV source stride overflow"))?;
2974 let destination_stride = usize::try_from(destination_stride)
2975 .map_err(|_| BridgeError::InvalidInput("negative YUV destination stride"))?;
2976 if destination.is_null() || destination_stride < row_bytes {
2977 return Err(BridgeError::InvalidInput(
2978 "YUV destination plane is too small",
2979 ));
2980 }
2981 for row in 0..rows {
2982 let source_offset = row
2983 .checked_mul(source_stride)
2984 .ok_or(BridgeError::InvalidInput("YUV source offset overflow"))?;
2985 let destination_offset = row
2986 .checked_mul(destination_stride)
2987 .ok_or(BridgeError::InvalidInput("YUV destination offset overflow"))?;
2988 unsafe {
2991 ptr::copy_nonoverlapping(
2992 source.as_ptr().add(source_offset),
2993 destination.add(destination_offset),
2994 row_bytes,
2995 );
2996 }
2997 }
2998 Ok(())
2999}
3000
3001pub fn audio_frame(
3008 channels: &[Vec<f32>],
3009 format: ffi::AVSampleFormat,
3010 sample_rate: i32,
3011 pts: i64,
3012) -> Result<AVFrame, BridgeError> {
3013 let Some(samples) = channels.first().map(Vec::len) else {
3014 return Err(BridgeError::InvalidInput("invalid planar audio shape"));
3015 };
3016 if sample_rate <= 0
3017 || samples == 0
3018 || channels.len() > ffi::AV_NUM_DATA_POINTERS as usize
3019 || channels.iter().any(|channel| channel.len() != samples)
3020 {
3021 return Err(BridgeError::InvalidInput(
3022 "planar audio channel lengths differ",
3023 ));
3024 }
3025 let sample_bytes = match format {
3026 ffi::AV_SAMPLE_FMT_FLTP | ffi::AV_SAMPLE_FMT_FLT => size_of::<f32>(),
3027 ffi::AV_SAMPLE_FMT_S16 => size_of::<i16>(),
3028 _ => return Err(BridgeError::InvalidInput("unsupported audio sample format")),
3029 };
3030 let planar = format == ffi::AV_SAMPLE_FMT_FLTP;
3031 let channel_count = i32::try_from(channels.len())
3032 .map_err(|_| BridgeError::InvalidInput("audio channel count overflow"))?;
3033 let sample_count = i32::try_from(samples)
3034 .map_err(|_| BridgeError::InvalidInput("audio sample count overflow"))?;
3035 let mut frame = AVFrame::new();
3036 frame.set_format(format);
3037 frame.set_ch_layout(
3038 rsmpeg::avutil::AVChannelLayout::from_nb_channels(channel_count).into_inner(),
3039 );
3040 frame.set_sample_rate(sample_rate);
3041 frame.set_nb_samples(sample_count);
3042 frame.set_pts(pts);
3043 frame.set_time_base(ffi::AVRational {
3044 num: 1,
3045 den: sample_rate,
3046 });
3047 frame.get_buffer(0)?;
3048 frame.make_writable()?;
3049 let plane_bytes = samples
3050 .checked_mul(sample_bytes)
3051 .and_then(|bytes| bytes.checked_mul(if planar { 1 } else { channels.len() }))
3052 .ok_or(BridgeError::InvalidInput("audio plane byte count overflow"))?;
3053 let plane_capacity = usize::try_from(frame.linesize[0]).unwrap_or(0);
3054 if plane_capacity < plane_bytes {
3055 return Err(BridgeError::InvalidInput(
3056 "audio plane capacity is too small",
3057 ));
3058 }
3059 let planes = if planar { channels.len() } else { 1 };
3060 if frame.data[..planes].iter().any(|plane| plane.is_null()) {
3061 return Err(BridgeError::InvalidInput("audio plane pointer is null"));
3062 }
3063 if planar {
3064 for (index, source) in channels.iter().enumerate() {
3065 unsafe {
3068 ptr::copy_nonoverlapping(
3069 source.as_ptr().cast::<u8>(),
3070 frame.data[index],
3071 plane_bytes,
3072 );
3073 }
3074 }
3075 return Ok(frame);
3076 }
3077 let plane = unsafe { std::slice::from_raw_parts_mut(frame.data[0], plane_bytes) };
3079 let interleaved = (0..samples).flat_map(|sample| channels.iter().map(move |c| c[sample]));
3080 if format == ffi::AV_SAMPLE_FMT_FLT {
3081 for (bytes, value) in plane.as_chunks_mut::<4>().0.iter_mut().zip(interleaved) {
3082 *bytes = value.to_ne_bytes();
3083 }
3084 } else {
3085 for (bytes, value) in plane.as_chunks_mut::<2>().0.iter_mut().zip(interleaved) {
3086 #[allow(clippy::cast_possible_truncation)]
3088 let value = (value.clamp(-1.0, 1.0) * 32_767.0).round() as i16;
3089 *bytes = value.to_ne_bytes();
3090 }
3091 }
3092 Ok(frame)
3093}
3094
3095#[must_use]
3110pub fn channel_layout_channels(layout: &rsmpeg::avutil::AVChannelLayout) -> Vec<ffi::AVChannel> {
3111 if layout.order == ffi::AV_CHANNEL_ORDER_UNSPEC {
3112 return Vec::new();
3113 }
3114 let channels = u32::try_from(layout.nb_channels).unwrap_or(0);
3115 (0..channels)
3116 .map(|index| {
3117 layout
3118 .channel_from_index(index)
3119 .unwrap_or(ffi::AV_CHAN_NONE)
3120 })
3121 .collect()
3122}
3123
3124pub fn channel_layout_of(
3129 channels: &[ffi::AVChannel],
3130) -> Result<rsmpeg::avutil::AVChannelLayout, BridgeError> {
3131 let count = i32::try_from(channels.len())
3132 .ok()
3133 .filter(|count| *count > 0)
3134 .ok_or(BridgeError::InvalidInput("a channel layout needs channels"))?;
3135 let mut raw = std::mem::MaybeUninit::<ffi::AVChannelLayout>::zeroed();
3136 let initialized = unsafe { ffi::av_channel_layout_custom_init(raw.as_mut_ptr(), count) };
3138 if initialized < 0 {
3139 return Err(BridgeError::FfmpegCode(initialized));
3140 }
3141 let mut layout = unsafe { rsmpeg::avutil::AVChannelLayout::new(raw.assume_init()) };
3143 for (index, channel) in channels.iter().enumerate() {
3144 unsafe { (*layout.u.map.add(index)).id = *channel };
3146 }
3147 let flags = i32::try_from(ffi::AV_CHANNEL_LAYOUT_RETYPE_FLAG_CANONICAL).unwrap_or(0);
3148 let retyped = unsafe {
3150 ffi::av_channel_layout_retype(layout.as_mut_ptr(), ffi::AV_CHANNEL_ORDER_UNSPEC, flags)
3151 };
3152 if retyped < 0 {
3153 return Err(BridgeError::FfmpegCode(retyped));
3154 }
3155 Ok(layout)
3156}
3157
3158pub fn audio_f32_interleaved(frame: &AVFrame) -> Result<Vec<f32>, BridgeError> {
3163 if frame.format != ffi::AV_SAMPLE_FMT_FLT || frame.nb_samples < 0 {
3164 return Err(BridgeError::InvalidInput(
3165 "packed audio format or sample count is invalid",
3166 ));
3167 }
3168 let channels = usize::try_from(frame.ch_layout().nb_channels)
3169 .map_err(|_| BridgeError::InvalidInput("packed audio channel count is negative"))?;
3170 let frames = usize::try_from(frame.nb_samples)
3171 .map_err(|_| BridgeError::InvalidInput("packed audio sample count is negative"))?;
3172 let samples = frames
3173 .checked_mul(channels)
3174 .ok_or(BridgeError::InvalidInput(
3175 "packed audio sample count overflow",
3176 ))?;
3177 let bytes = samples
3178 .checked_mul(size_of::<f32>())
3179 .ok_or(BridgeError::InvalidInput(
3180 "packed audio byte count overflow",
3181 ))?;
3182 if channels == 0
3183 || frame.data[0].is_null()
3184 || usize::try_from(frame.linesize[0]).unwrap_or(0) < bytes
3185 {
3186 return Err(BridgeError::InvalidInput(
3187 "packed audio plane is missing or too small",
3188 ));
3189 }
3190 let mut output = vec![0.0_f32; samples];
3191 unsafe {
3193 ptr::copy_nonoverlapping(frame.data[0], output.as_mut_ptr().cast::<u8>(), bytes);
3194 }
3195 Ok(output)
3196}
3197
3198#[derive(Copy, Clone, Debug, PartialEq)]
3200pub struct DisplayRotation {
3201 pub counter_clockwise_degrees: f64,
3203 pub flipped: bool,
3205}
3206
3207#[must_use]
3209pub fn display_rotation(parameters: &AVCodecParameters) -> Option<DisplayRotation> {
3210 let count = usize::try_from(parameters.nb_coded_side_data).ok()?;
3211 if count == 0 || count > 64 || parameters.coded_side_data.is_null() {
3212 return None;
3213 }
3214 let entries = unsafe { slice::from_raw_parts(parameters.coded_side_data, count) };
3216 let matrix = entries.iter().find(|entry| {
3217 entry.type_ == ffi::AV_PKT_DATA_DISPLAYMATRIX
3218 && entry.size >= 9 * size_of::<i32>()
3219 && !entry.data.is_null()
3220 })?;
3221 unsafe { matrix_rotation(matrix.data) }
3223}
3224
3225#[must_use]
3227pub fn frame_display_rotation(frame: &AVFrame) -> Option<DisplayRotation> {
3228 let entry =
3230 unsafe { ffi::av_frame_get_side_data(frame.as_ptr(), ffi::AV_FRAME_DATA_DISPLAYMATRIX) };
3231 if entry.is_null() {
3232 return None;
3233 }
3234 let entry = unsafe { &*entry };
3236 if entry.size < 9 * size_of::<i32>() || entry.data.is_null() {
3237 return None;
3238 }
3239 unsafe { matrix_rotation(entry.data) }
3241}
3242
3243unsafe fn matrix_rotation(data: *const u8) -> Option<DisplayRotation> {
3246 let mut aligned = [0_i32; 9];
3247 unsafe {
3249 ptr::copy_nonoverlapping(
3250 data,
3251 aligned.as_mut_ptr().cast::<u8>(),
3252 size_of::<[i32; 9]>(),
3253 );
3254 }
3255 let determinant = i64::from(aligned[0]) * i64::from(aligned[4])
3258 - i64::from(aligned[1]) * i64::from(aligned[3]);
3259 let flipped = determinant < 0;
3260 if flipped {
3261 unsafe { ffi::av_display_matrix_flip(aligned.as_mut_ptr(), 1, 0) };
3263 }
3264 let angle = unsafe { ffi::av_display_rotation_get(aligned.as_ptr()) };
3266 angle.is_finite().then_some(DisplayRotation {
3267 counter_clockwise_degrees: angle,
3268 flipped,
3269 })
3270}
3271
3272const fn size_of<T>() -> usize {
3273 std::mem::size_of::<T>()
3274}
3275
3276pub struct Yuv420pFrameBuffer {
3282 frame: AVFrame,
3283 width: usize,
3284 height: usize,
3285 planes: Vec<(usize, usize)>,
3287}
3288
3289pub struct Yuv420pFramePlanes<'a> {
3291 pub y: &'a mut [u8],
3293 pub y_stride: usize,
3295 pub u: &'a mut [u8],
3297 pub v: &'a mut [u8],
3299 pub chroma_stride: usize,
3301}
3302
3303impl Yuv420pFrameBuffer {
3304 pub fn new(width: i32, height: i32) -> Result<Self, BridgeError> {
3309 Self::with_format(width, height, ffi::AV_PIX_FMT_YUV420P)
3310 }
3311
3312 pub fn with_format(
3318 width: i32,
3319 height: i32,
3320 format: ffi::AVPixelFormat,
3321 ) -> Result<Self, BridgeError> {
3322 let coded_width = usize::try_from(width)
3323 .map_err(|_| BridgeError::InvalidInput("negative frame width"))?;
3324 let coded_height = usize::try_from(height)
3325 .map_err(|_| BridgeError::InvalidInput("negative frame height"))?;
3326 if coded_width == 0 || coded_height == 0 {
3327 return Err(BridgeError::InvalidInput("empty frame"));
3328 }
3329 let planes = plane_geometry(format, width, height)?;
3330 let frame = zeroed_frame(width, height, format)?;
3331 for (index, &(row_bytes, _)) in planes.iter().enumerate() {
3332 if frame.data[index].is_null()
3333 || plane_stride(frame.linesize[index], row_bytes).is_err()
3334 {
3335 return Err(BridgeError::InvalidInput(
3336 "the frame's planes do not match its pixel format",
3337 ));
3338 }
3339 }
3340 Ok(Self {
3341 frame,
3342 width: coded_width,
3343 height: coded_height,
3344 planes,
3345 })
3346 }
3347
3348 #[must_use]
3350 pub fn planes(&self) -> &[(usize, usize)] {
3351 &self.planes
3352 }
3353
3354 pub fn begin_write_planes(&mut self) -> Result<Vec<(&mut [u8], usize)>, BridgeError> {
3359 self.make_writable()?;
3360 let mut written = Vec::with_capacity(self.planes.len());
3361 for (index, &(row_bytes, rows)) in self.planes.iter().enumerate() {
3362 let stride = plane_stride(self.frame.linesize[index], row_bytes)?;
3363 let plane = unsafe { writable_plane(&self.frame, index, stride, row_bytes, rows)? };
3366 written.push((plane, stride));
3367 }
3368 Ok(written)
3369 }
3370
3371 pub fn is_shared(&self) -> Result<bool, BridgeError> {
3376 Ok(!self.frame.is_writable().map_err(BridgeError::Ffmpeg)?)
3377 }
3378
3379 fn make_writable(&mut self) -> Result<(), BridgeError> {
3380 if self.is_shared()? {
3381 let mut replacement =
3382 zeroed_frame(self.frame.width, self.frame.height, self.frame.format)?;
3383 let status =
3385 unsafe { ffi::av_frame_copy_props(replacement.as_mut_ptr(), self.frame.as_ptr()) };
3386 if status < 0 {
3387 return Err(BridgeError::FfmpegCode(status));
3388 }
3389 self.frame = replacement;
3390 }
3391 Ok(())
3392 }
3393
3394 #[must_use]
3396 pub const fn dimensions(&self) -> (usize, usize) {
3397 (self.width, self.height)
3398 }
3399
3400 pub fn begin_write(&mut self) -> Result<Yuv420pFramePlanes<'_>, BridgeError> {
3405 if self.frame.format != ffi::AV_PIX_FMT_YUV420P {
3406 return Err(BridgeError::InvalidInput("the frame is not YUV420P"));
3407 }
3408 let mut planes = self.begin_write_planes()?.into_iter();
3409 let (Some((y, y_stride)), Some((u, u_stride)), Some((v, v_stride))) =
3410 (planes.next(), planes.next(), planes.next())
3411 else {
3412 return Err(BridgeError::InvalidInput("the frame is not YUV420P"));
3413 };
3414 if u_stride != v_stride {
3415 return Err(BridgeError::InvalidInput("mismatched chroma strides"));
3416 }
3417 Ok(Yuv420pFramePlanes {
3418 y,
3419 y_stride,
3420 u,
3421 v,
3422 chroma_stride: u_stride,
3423 })
3424 }
3425
3426 pub fn set_presentation(&mut self, pts: i64, time_base: ffi::AVRational) {
3428 self.frame.set_pts(pts);
3429 self.frame.set_time_base(time_base);
3430 }
3431
3432 #[must_use]
3434 pub const fn frame(&self) -> &AVFrame {
3435 &self.frame
3436 }
3437
3438 #[must_use]
3440 pub fn visible_bytes(&self) -> usize {
3441 if self.planes.is_empty() {
3442 let chroma = self.width.div_ceil(2) * self.height.div_ceil(2);
3443 return self.width * self.height + 2 * chroma;
3444 }
3445 self.planes
3446 .iter()
3447 .map(|&(row_bytes, rows)| row_bytes * rows)
3448 .sum()
3449 }
3450
3451 #[must_use]
3453 pub const fn size(&self) -> (usize, usize) {
3454 (self.width, self.height)
3455 }
3456}
3457
3458fn zeroed_frame(
3460 width: i32,
3461 height: i32,
3462 format: ffi::AVPixelFormat,
3463) -> Result<AVFrame, BridgeError> {
3464 let mut frame = AVFrame::new();
3465 frame.set_format(format);
3466 frame.set_width(width);
3467 frame.set_height(height);
3468 frame.get_buffer(1)?;
3469 for buffer in frame.buf {
3470 if let Some(buffer) = unsafe { buffer.as_ref() } {
3472 unsafe { ptr::write_bytes(buffer.data, 0, buffer.size) };
3474 }
3475 }
3476 Ok(frame)
3477}
3478
3479impl fmt::Debug for Yuv420pFrameBuffer {
3480 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3481 formatter
3482 .debug_struct("Yuv420pFrameBuffer")
3483 .field("width", &self.width)
3484 .field("height", &self.height)
3485 .finish_non_exhaustive()
3486 }
3487}
3488
3489fn plane_stride(linesize: i32, width: usize) -> Result<usize, BridgeError> {
3490 let stride = usize::try_from(linesize)
3491 .map_err(|_| BridgeError::InvalidInput("negative frame linesize"))?;
3492 if stride < width {
3493 return Err(BridgeError::InvalidInput(
3494 "frame linesize is below its width",
3495 ));
3496 }
3497 Ok(stride)
3498}
3499
3500unsafe fn writable_plane<'a>(
3505 frame: &AVFrame,
3506 index: usize,
3507 stride: usize,
3508 row_bytes: usize,
3509 rows: usize,
3510) -> Result<&'a mut [u8], BridgeError> {
3511 let data = frame.data[index];
3512 if data.is_null() {
3513 return Err(BridgeError::InvalidInput("frame plane is null"));
3514 }
3515 let len = stride
3516 .checked_mul(rows.saturating_sub(1))
3517 .and_then(|before| before.checked_add(row_bytes))
3518 .ok_or(BridgeError::InvalidInput("frame plane size overflow"))?;
3519 if !in_frame_buffer(frame, data as usize, len) {
3520 return Err(BridgeError::InvalidInput(
3521 "frame plane extends past its buffer",
3522 ));
3523 }
3524 Ok(unsafe { slice::from_raw_parts_mut(data, len) })
3526}
3527
3528fn in_frame_buffer(frame: &AVFrame, start: usize, len: usize) -> bool {
3530 let Some(end) = start.checked_add(len) else {
3531 return false;
3532 };
3533 frame.buf.iter().any(|buffer| {
3534 let Some(buffer) = (unsafe { buffer.as_ref() }) else {
3536 return false;
3537 };
3538 let buffer_start = buffer.data as usize;
3539 buffer_start
3540 .checked_add(buffer.size)
3541 .is_some_and(|buffer_end| buffer_start <= start && end <= buffer_end)
3542 })
3543}
3544
3545fn plane_geometry(
3547 format: ffi::AVPixelFormat,
3548 width: i32,
3549 height: i32,
3550) -> Result<Vec<(usize, usize)>, BridgeError> {
3551 let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
3553 .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
3554 let count = unsafe { ffi::av_pix_fmt_count_planes(format) };
3556 let count = usize::try_from(count)
3557 .ok()
3558 .filter(|count| (1..=4).contains(count))
3559 .ok_or(BridgeError::InvalidInput("pixel format has no planes"))?;
3560 let rows = usize::try_from(height).map_err(|_| BridgeError::InvalidInput("negative height"))?;
3561 (0..count)
3562 .map(|index| {
3563 let plane = i32::try_from(index).unwrap_or(i32::MAX);
3564 let row_bytes = unsafe { ffi::av_image_get_linesize(format, width, plane) };
3566 let row_bytes =
3567 usize::try_from(row_bytes).map_err(|_| BridgeError::FfmpegCode(row_bytes))?;
3568 let rows = if index == 1 || index == 2 {
3569 rows.div_ceil(1 << descriptor.log2_chroma_h)
3570 } else {
3571 rows
3572 };
3573 Ok((row_bytes, rows))
3574 })
3575 .collect()
3576}
3577
3578#[cfg(all(test, target_os = "linux", feature = "hwdevice"))]
3579mod vulkan_shim_tests;
3580
3581#[cfg(all(test, target_os = "linux", feature = "hwdevice"))]
3582mod vulkan_access_tests;
3583
3584#[cfg(test)]
3585mod tests;