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
2030pub 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 unsafe {
2044 (*raw).color_primaries = primaries;
2045 (*raw).color_trc = transfer;
2046 (*raw).colorspace = space;
2047 (*raw).color_range = range;
2048 }
2049}
2050
2051pub 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 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 unsafe { ptr::copy_nonoverlapping(data.as_ptr(), entry, data.len()) };
2069 Ok(())
2070}
2071
2072pub 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 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 unsafe { ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len()) };
2099 unsafe {
2102 ffi::av_freep((&raw mut (*parameters).extradata).cast());
2103 (*parameters).extradata = buffer;
2104 (*parameters).extradata_size = size;
2105 }
2106 Ok(())
2107}
2108
2109pub 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 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 unsafe { ptr::copy_nonoverlapping(data.as_ptr(), packet.data, data.len()) };
2125 }
2126 Ok(packet)
2127}
2128
2129pub 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 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 unsafe { ptr::copy_nonoverlapping(data.as_ptr(), packet.data, data.len()) };
2149 }
2150 unsafe { ffi::av_shrink_packet(packet.as_mut_ptr(), size) };
2152 Ok(())
2153}
2154
2155#[derive(Clone, Copy, Debug)]
2157pub struct VideoStreamDescription<'a> {
2158 pub codec_id: ffi::AVCodecID,
2160 pub width: i32,
2162 pub height: i32,
2164 pub pixel_format: ffi::AVPixelFormat,
2166 pub profile: i32,
2168 pub level: i32,
2170 pub color_primaries: ffi::AVColorPrimaries,
2172 pub color_trc: ffi::AVColorTransferCharacteristic,
2174 pub color_space: ffi::AVColorSpace,
2176 pub color_range: ffi::AVColorRange,
2178 pub sample_aspect_ratio: ffi::AVRational,
2180 pub frame_rate: ffi::AVRational,
2182 pub bit_rate: i64,
2184 pub extradata: &'a [u8],
2186}
2187
2188pub 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 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 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 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
2239pub 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 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 let mut context = unsafe { rsmpeg::avcodec::AVBSFContextUninit::from_raw(raw) };
2261 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
2272pub fn set_stream_codec_tag(stream: &mut rsmpeg::avformat::AVStreamMut<'_>, tag: u32) {
2274 let mut parameters = stream.codecpar_mut();
2275 unsafe { (*parameters.as_mut_ptr()).codec_tag = tag };
2277}
2278
2279pub 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 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 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 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#[must_use]
2327pub fn hardware_device_type_name(device_type: ffi::AVHWDeviceType) -> Option<String> {
2328 let name = unsafe { ffi::av_hwdevice_get_type_name(device_type) };
2330 if name.is_null() {
2331 None
2332 } else {
2333 Some(
2335 unsafe { CStr::from_ptr(name) }
2336 .to_string_lossy()
2337 .into_owned(),
2338 )
2339 }
2340}
2341
2342#[must_use]
2349pub fn yuv_layout(format: ffi::AVPixelFormat) -> Option<YuvPlaneLayout> {
2350 if format == ffi::AV_PIX_FMT_NONE {
2351 return None;
2352 }
2353 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
2417pub fn yuv_planes(frame: &AVFrame) -> Result<Option<YuvPlanes>, BridgeError> {
2426 frame_yuv_planes(frame, false)
2427}
2428
2429pub struct DecodedFrame {
2433 frame: AVFrame,
2434 written: bool,
2435}
2436
2437impl DecodedFrame {
2438 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 pub fn yuv_planes(&self) -> Result<Option<YuvPlanes>, BridgeError> {
2455 frame_yuv_planes(&self.frame, self.written)
2456 }
2457
2458 pub fn set_pts(&mut self, pts: i64) {
2460 self.frame.set_pts(pts);
2461 }
2462
2463 #[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
2491fn decoder_frames_are_initialized(decoder: &AVCodecContext) -> bool {
2496 static DEFAULT_GET_BUFFER2: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2497 let default = *DEFAULT_GET_BUFFER2.get_or_init(|| {
2499 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 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
2517fn 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 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
2580struct SharedFrame(AVFrame);
2582
2583unsafe impl Sync for SharedFrame {}
2586
2587struct PlaneView {
2589 frame: std::sync::Arc<SharedFrame>,
2590 data: *const u8,
2591 len: usize,
2592 stride: usize,
2593}
2594
2595unsafe impl Send for PlaneView {}
2598
2599impl PlaneView {
2600 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 unsafe { slice::from_raw_parts(self.data, self.len) }
2629 }
2630}
2631
2632fn 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 unsafe { copy_plane_rows(data, linesize, width, height, context) }
2648}
2649
2650fn 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 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
2679unsafe 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 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 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
2715pub 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 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#[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#[must_use]
2834pub fn yuv_pixel_format(layout: YuvPlaneLayout) -> Option<ffi::AVPixelFormat> {
2835 let mut descriptor = ptr::null();
2836 loop {
2837 descriptor = unsafe { ffi::av_pix_fmt_desc_next(descriptor) };
2839 if descriptor.is_null() {
2840 return None;
2841 }
2842 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
2850pub fn planar_frame(
2855 format: ffi::AVPixelFormat,
2856 planes: &[(&[u8], u32)],
2857 width: u32,
2858 height: u32,
2859) -> Result<AVFrame, BridgeError> {
2860 let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
2862 .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
2863 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 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 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
2962pub 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 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 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 #[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#[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
3085pub 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 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 let mut layout = unsafe { rsmpeg::avutil::AVChannelLayout::new(raw.assume_init()) };
3104 for (index, channel) in channels.iter().enumerate() {
3105 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 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
3119pub 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 unsafe {
3154 ptr::copy_nonoverlapping(frame.data[0], output.as_mut_ptr().cast::<u8>(), bytes);
3155 }
3156 Ok(output)
3157}
3158
3159#[derive(Copy, Clone, Debug, PartialEq)]
3161pub struct DisplayRotation {
3162 pub counter_clockwise_degrees: f64,
3164 pub flipped: bool,
3166}
3167
3168#[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 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 unsafe { matrix_rotation(matrix.data) }
3184}
3185
3186#[must_use]
3188pub fn frame_display_rotation(frame: &AVFrame) -> Option<DisplayRotation> {
3189 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 let entry = unsafe { &*entry };
3197 if entry.size < 9 * size_of::<i32>() || entry.data.is_null() {
3198 return None;
3199 }
3200 unsafe { matrix_rotation(entry.data) }
3202}
3203
3204unsafe fn matrix_rotation(data: *const u8) -> Option<DisplayRotation> {
3207 let mut aligned = [0_i32; 9];
3208 unsafe {
3210 ptr::copy_nonoverlapping(
3211 data,
3212 aligned.as_mut_ptr().cast::<u8>(),
3213 size_of::<[i32; 9]>(),
3214 );
3215 }
3216 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 unsafe { ffi::av_display_matrix_flip(aligned.as_mut_ptr(), 1, 0) };
3224 }
3225 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
3237pub struct Yuv420pFrameBuffer {
3243 frame: AVFrame,
3244 width: usize,
3245 height: usize,
3246 planes: Vec<(usize, usize)>,
3248}
3249
3250pub struct Yuv420pFramePlanes<'a> {
3252 pub y: &'a mut [u8],
3254 pub y_stride: usize,
3256 pub u: &'a mut [u8],
3258 pub v: &'a mut [u8],
3260 pub chroma_stride: usize,
3262}
3263
3264impl Yuv420pFrameBuffer {
3265 pub fn new(width: i32, height: i32) -> Result<Self, BridgeError> {
3270 Self::with_format(width, height, ffi::AV_PIX_FMT_YUV420P)
3271 }
3272
3273 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 #[must_use]
3311 pub fn planes(&self) -> &[(usize, usize)] {
3312 &self.planes
3313 }
3314
3315 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 let plane = unsafe { writable_plane(&self.frame, index, stride, row_bytes, rows)? };
3327 written.push((plane, stride));
3328 }
3329 Ok(written)
3330 }
3331
3332 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 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 #[must_use]
3357 pub const fn dimensions(&self) -> (usize, usize) {
3358 (self.width, self.height)
3359 }
3360
3361 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 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 #[must_use]
3395 pub const fn frame(&self) -> &AVFrame {
3396 &self.frame
3397 }
3398
3399 #[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 #[must_use]
3414 pub const fn size(&self) -> (usize, usize) {
3415 (self.width, self.height)
3416 }
3417}
3418
3419fn 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 if let Some(buffer) = unsafe { buffer.as_ref() } {
3433 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
3461unsafe 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 Ok(unsafe { slice::from_raw_parts_mut(data, len) })
3487}
3488
3489fn 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 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
3506fn plane_geometry(
3508 format: ffi::AVPixelFormat,
3509 width: i32,
3510 height: i32,
3511) -> Result<Vec<(usize, usize)>, BridgeError> {
3512 let descriptor = unsafe { ffi::av_pix_fmt_desc_get(format).as_ref() }
3514 .ok_or(BridgeError::InvalidInput("pixel format has no descriptor"))?;
3515 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 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;