diff --git a/Cargo.lock b/Cargo.lock index 8e5b98d1..41e90f6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -150,7 +150,7 @@ version = "0.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" dependencies = [ - "bitflags", + "bitflags 2.13.1", "cexpr", "clang-sys", "itertools 0.13.0", @@ -170,6 +170,12 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.1" @@ -277,7 +283,7 @@ name = "cros-libva" version = "0.0.13" dependencies = [ "bindgen", - "bitflags", + "bitflags 2.13.1", "crc32fast", "log", "pkg-config", @@ -1293,7 +1299,7 @@ version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" dependencies = [ - "bitflags", + "bitflags 2.13.1", "crc32fast", "fdeflate", "flate2", @@ -1506,7 +1512,7 @@ version = "11.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" dependencies = [ - "bitflags", + "bitflags 2.13.1", ] [[package]] @@ -1876,6 +1882,32 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vk-video-ffi" +version = "0.1.0" +dependencies = [ + "vulkanalia", +] + +[[package]] +name = "vulkanalia" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebd71d6c64383bbdf1c260efa22e81e1a2a7dd832a3831af34495f47d7551d7b" +dependencies = [ + "libloading", + "vulkanalia-sys", +] + +[[package]] +name = "vulkanalia-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d4da5d5e0c7377cea24358fa238b3b22a1913a7890f65dbd8ff9aa371a493a" +dependencies = [ + "bitflags 1.3.2", +] + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" diff --git a/shims/vk-video-ffi/Cargo.toml b/shims/vk-video-ffi/Cargo.toml new file mode 100644 index 00000000..8f87214a --- /dev/null +++ b/shims/vk-video-ffi/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "vk-video-ffi" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +vulkanalia = { version = "0.35", features = ["libloading"] } diff --git a/shims/vk-video-ffi/examples/caps.rs b/shims/vk-video-ffi/examples/caps.rs new file mode 100644 index 00000000..aae4a8db --- /dev/null +++ b/shims/vk-video-ffi/examples/caps.rs @@ -0,0 +1,18 @@ +use vk_video_ffi::Gpu; + +fn main() { + let gpu = match Gpu::open() { + Ok(gpu) => gpu, + Err(e) => { + eprintln!("{e}"); + std::process::exit(1); + } + }; + println!("{}", gpu.device_name()); + for c in gpu.caps() { + println!( + "{:?} {:?} max {}x{} dpb {} refs {}", + c.codec, c.direction, c.max_width, c.max_height, c.max_dpb_slots, c.max_active_refs + ); + } +} diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs new file mode 100644 index 00000000..434e8dd6 --- /dev/null +++ b/shims/vk-video-ffi/src/lib.rs @@ -0,0 +1,413 @@ +//! Safe capability probe for Vulkan Video over vulkanalia. +#![deny(missing_docs)] + +use std::collections::BTreeSet; +use std::ffi::c_char; +use std::fmt; + +use vk::KhrVideoQueueExtensionInstanceCommands; +use vulkanalia::loader::LibloadingLoader; +use vulkanalia::prelude::v1_3::*; + +const WANTED: [vk::Extension; 14] = [ + vk::KHR_VIDEO_QUEUE_EXTENSION, + vk::KHR_VIDEO_ENCODE_QUEUE_EXTENSION, + vk::KHR_VIDEO_DECODE_QUEUE_EXTENSION, + vk::KHR_VIDEO_ENCODE_H264_EXTENSION, + vk::KHR_VIDEO_ENCODE_H265_EXTENSION, + vk::KHR_VIDEO_ENCODE_AV1_EXTENSION, + vk::KHR_VIDEO_DECODE_H264_EXTENSION, + vk::KHR_VIDEO_DECODE_H265_EXTENSION, + vk::KHR_VIDEO_DECODE_AV1_EXTENSION, + vk::KHR_VIDEO_DECODE_VP9_EXTENSION, + vk::KHR_VIDEO_MAINTENANCE1_EXTENSION, + vk::EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION, + vk::KHR_EXTERNAL_MEMORY_FD_EXTENSION, + vk::EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION, +]; + +/// Errors from opening a GPU or probing it. +#[derive(Debug)] +pub enum Error { + /// The Vulkan loader library could not be loaded. + NoLoader(String), + /// No physical device has a usable video queue family. + NoDevice, + /// A Vulkan call failed: VkResult code and call name. + Vk(i32, &'static str), + /// The requested codec or direction is not supported. + Unsupported(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::NoLoader(e) => write!(f, "no Vulkan loader: {e}"), + Error::NoDevice => write!(f, "no Vulkan Video device"), + Error::Vk(code, call) => write!(f, "{call} failed: VkResult {code}"), + Error::Unsupported(what) => write!(f, "unsupported: {what}"), + } + } +} + +impl std::error::Error for Error {} + +/// Video codec. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Codec { + /// H.264 / AVC. + H264, + /// H.265 / HEVC. + H265, + /// AV1. + Av1, + /// VP9. + Vp9, +} + +/// Video direction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + /// Encode. + Encode, + /// Decode. + Decode, +} + +/// Capabilities of one codec and direction, 4:2:0 8-bit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CodecCaps { + /// Codec. + pub codec: Codec, + /// Direction. + pub direction: Direction, + /// Maximum coded width. + pub max_width: u32, + /// Maximum coded height. + pub max_height: u32, + /// Maximum DPB slots. + pub max_dpb_slots: u32, + /// Maximum active reference pictures. + pub max_active_refs: u32, +} + +/// An opened Vulkan device with video queues. +pub struct Gpu { + device: Device, + instance: Instance, + physical: vk::PhysicalDevice, + name: String, + _entry: Entry, +} + +struct Families { + encode: Option, + decode: Option, + graphics: Option, +} + +fn queue_families(instance: &Instance, physical: vk::PhysicalDevice) -> Families { + let flags: Vec = + unsafe { instance.get_physical_device_queue_family_properties(physical) } + .iter() + .map(|p| p.queue_flags) + .collect(); + let find = |pred: &dyn Fn(vk::QueueFlags) -> bool| { + flags.iter().position(|&f| pred(f)).map(|i| i as u32) + }; + Families { + encode: find(&|f| f.contains(vk::QueueFlags::VIDEO_ENCODE_KHR)), + decode: find(&|f| f.contains(vk::QueueFlags::VIDEO_DECODE_KHR)), + graphics: find(&|f| { + f.contains(vk::QueueFlags::GRAPHICS) || f.contains(vk::QueueFlags::COMPUTE) + }), + } +} + +fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String), Error> { + let devices = unsafe { instance.enumerate_physical_devices() } + .map_err(|c| Error::Vk(c.as_raw(), "vkEnumeratePhysicalDevices"))?; + let (physical, families) = devices + .into_iter() + .find_map(|pd| { + let f = queue_families(instance, pd); + (f.encode.is_some() || f.decode.is_some()).then_some((pd, f)) + }) + .ok_or(Error::NoDevice)?; + let graphics = families.graphics.ok_or(Error::NoDevice)?; + + let mut indices = BTreeSet::from([graphics]); + indices.extend(families.encode); + indices.extend(families.decode); + let priority = [1.0f32]; + let queues: Vec = indices + .iter() + .map(|&index| { + vk::DeviceQueueCreateInfo::builder() + .queue_family_index(index) + .queue_priorities(&priority) + .build() + }) + .collect(); + + let available: Vec = + unsafe { instance.enumerate_device_extension_properties(physical, None) } + .map_err(|c| Error::Vk(c.as_raw(), "vkEnumerateDeviceExtensionProperties"))? + .iter() + .map(|e| e.extension_name) + .collect(); + let enabled: Vec = WANTED + .iter() + .map(|e| e.name) + .filter(|n| available.contains(n)) + .collect(); + let names: Vec<*const c_char> = enabled.iter().map(|n| n.as_cstr().as_ptr()).collect(); + + let mut sync2 = vk::PhysicalDeviceSynchronization2Features::builder(); + let mut ycbcr = vk::PhysicalDeviceSamplerYcbcrConversionFeatures::builder(); + let mut maint = vk::PhysicalDeviceVideoMaintenance1FeaturesKHR::builder(); + let mut features = vk::PhysicalDeviceFeatures2::builder() + .push_next(&mut sync2) + .push_next(&mut ycbcr); + if enabled.contains(&vk::KHR_VIDEO_MAINTENANCE1_EXTENSION.name) { + features = features.push_next(&mut maint); + } + unsafe { instance.get_physical_device_features2(physical, &mut features) }; + + let info = vk::DeviceCreateInfo::builder() + .queue_create_infos(&queues) + .enabled_extension_names(&names) + .push_next(&mut features); + let device = unsafe { instance.create_device(physical, &info, None) } + .map_err(|c| Error::Vk(c.as_raw(), "vkCreateDevice"))?; + + let name = unsafe { instance.get_physical_device_properties(physical) } + .device_name + .to_string_lossy() + .into_owned(); + Ok((physical, device, name)) +} + +impl Gpu { + /// Loads Vulkan and opens the first device with a video queue family. + pub fn open() -> Result { + let library = if cfg!(windows) { + "vulkan-1.dll" + } else { + "libvulkan.so.1" + }; + let loader = unsafe { LibloadingLoader::new(library) } + .map_err(|e| Error::NoLoader(e.to_string()))?; + let entry = unsafe { Entry::new(loader) }.map_err(|e| Error::NoLoader(e.to_string()))?; + let app = vk::ApplicationInfo::builder().api_version(vk::make_version(1, 3, 0)); + let info = vk::InstanceCreateInfo::builder().application_info(&app); + let instance = unsafe { entry.create_instance(&info, None) } + .map_err(|c| Error::Vk(c.as_raw(), "vkCreateInstance"))?; + match setup(&instance) { + Ok((physical, device, name)) => Ok(Gpu { + device, + instance, + physical, + name, + _entry: entry, + }), + Err(e) => { + unsafe { instance.destroy_instance(None) }; + Err(e) + } + } + } + + /// Device name as reported by the driver. + pub fn device_name(&self) -> String { + self.name.clone() + } + + /// Capabilities of every codec and direction the device supports. + pub fn caps(&self) -> Vec { + [ + (Codec::H264, Direction::Encode), + (Codec::H264, Direction::Decode), + (Codec::H265, Direction::Encode), + (Codec::H265, Direction::Decode), + (Codec::Av1, Direction::Encode), + (Codec::Av1, Direction::Decode), + (Codec::Vp9, Direction::Decode), + ] + .into_iter() + .filter_map(|(codec, direction)| self.codec_caps(codec, direction).ok()) + .collect() + } + + fn codec_caps(&self, codec: Codec, direction: Direction) -> Result { + let (operation, extension) = match (codec, direction) { + (Codec::H264, Direction::Encode) => ( + vk::VideoCodecOperationFlagsKHR::ENCODE_H264, + vk::KHR_VIDEO_ENCODE_H264_EXTENSION, + ), + (Codec::H264, Direction::Decode) => ( + vk::VideoCodecOperationFlagsKHR::DECODE_H264, + vk::KHR_VIDEO_DECODE_H264_EXTENSION, + ), + (Codec::H265, Direction::Encode) => ( + vk::VideoCodecOperationFlagsKHR::ENCODE_H265, + vk::KHR_VIDEO_ENCODE_H265_EXTENSION, + ), + (Codec::H265, Direction::Decode) => ( + vk::VideoCodecOperationFlagsKHR::DECODE_H265, + vk::KHR_VIDEO_DECODE_H265_EXTENSION, + ), + (Codec::Av1, Direction::Encode) => ( + vk::VideoCodecOperationFlagsKHR::ENCODE_AV1, + vk::KHR_VIDEO_ENCODE_AV1_EXTENSION, + ), + (Codec::Av1, Direction::Decode) => ( + vk::VideoCodecOperationFlagsKHR::DECODE_AV1, + vk::KHR_VIDEO_DECODE_AV1_EXTENSION, + ), + (Codec::Vp9, Direction::Decode) => ( + vk::VideoCodecOperationFlagsKHR::DECODE_VP9, + vk::KHR_VIDEO_DECODE_VP9_EXTENSION, + ), + (Codec::Vp9, Direction::Encode) => { + return Err(Error::Unsupported("VP9 encode".into())); + } + }; + if !self.device.extensions().contains(&extension.name) { + return Err(Error::Unsupported(format!("{codec:?} {direction:?}"))); + } + let profile = |operation| { + vk::VideoProfileInfoKHR::builder() + .video_codec_operation(operation) + .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) + .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + }; + match (codec, direction) { + (Codec::H264, Direction::Encode) => { + let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder() + .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH); + let p = profile(operation).push_next(&mut h); + self.query( + codec, + direction, + &p, + &mut vk::VideoEncodeH264CapabilitiesKHR::builder(), + ) + } + (Codec::H264, Direction::Decode) => { + let mut h = vk::VideoDecodeH264ProfileInfoKHR::builder() + .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH) + .picture_layout(vk::VideoDecodeH264PictureLayoutFlagsKHR::PROGRESSIVE); + let p = profile(operation).push_next(&mut h); + self.query( + codec, + direction, + &p, + &mut vk::VideoDecodeH264CapabilitiesKHR::builder(), + ) + } + (Codec::H265, Direction::Encode) => { + let mut h = vk::VideoEncodeH265ProfileInfoKHR::builder() + .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN); + let p = profile(operation).push_next(&mut h); + self.query( + codec, + direction, + &p, + &mut vk::VideoEncodeH265CapabilitiesKHR::builder(), + ) + } + (Codec::H265, Direction::Decode) => { + let mut h = vk::VideoDecodeH265ProfileInfoKHR::builder() + .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN); + let p = profile(operation).push_next(&mut h); + self.query( + codec, + direction, + &p, + &mut vk::VideoDecodeH265CapabilitiesKHR::builder(), + ) + } + (Codec::Av1, Direction::Encode) => { + let mut h = vk::VideoEncodeAV1ProfileInfoKHR::builder() + .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN); + let p = profile(operation).push_next(&mut h); + self.query( + codec, + direction, + &p, + &mut vk::VideoEncodeAV1CapabilitiesKHR::builder(), + ) + } + (Codec::Av1, Direction::Decode) => { + let mut h = vk::VideoDecodeAV1ProfileInfoKHR::builder() + .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN); + let p = profile(operation).push_next(&mut h); + self.query( + codec, + direction, + &p, + &mut vk::VideoDecodeAV1CapabilitiesKHR::builder(), + ) + } + (Codec::Vp9, _) => { + let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder() + .std_profile(vk::video::STD_VIDEO_VP9_PROFILE_0); + let p = profile(operation).push_next(&mut h); + self.query( + codec, + direction, + &p, + &mut vk::VideoDecodeVP9CapabilitiesKHR::builder(), + ) + } + } + } + + fn query( + &self, + codec: Codec, + direction: Direction, + profile: &vk::VideoProfileInfoKHR, + codec_caps: &mut C, + ) -> Result + where + C: vk::Cast, + C::Target: vk::ExtendsVideoCapabilitiesKHR, + { + let mut decode = vk::VideoDecodeCapabilitiesKHR::builder(); + let mut encode = vk::VideoEncodeCapabilitiesKHR::builder(); + let mut caps = vk::VideoCapabilitiesKHR::builder().push_next(codec_caps); + match direction { + Direction::Decode => caps = caps.push_next(&mut decode), + Direction::Encode => caps = caps.push_next(&mut encode), + } + unsafe { + self.instance.get_physical_device_video_capabilities_khr( + self.physical, + profile, + &mut caps, + ) + } + .map_err(|c| Error::Vk(c.as_raw(), "vkGetPhysicalDeviceVideoCapabilitiesKHR"))?; + Ok(CodecCaps { + codec, + direction, + max_width: caps.max_coded_extent.width, + max_height: caps.max_coded_extent.height, + max_dpb_slots: caps.max_dpb_slots, + max_active_refs: caps.max_active_reference_pictures, + }) + } +} + +impl Drop for Gpu { + fn drop(&mut self) { + unsafe { + let _ = self.device.device_wait_idle(); + self.device.destroy_device(None); + self.instance.destroy_instance(None); + } + } +}