forge
Explore
Log in

Don't you dare go Hollow

vk-video-ffi: Vulkan Video shim core (the one crate with unsafe): loader, instance, device with video encode/decode/compute queues, codec caps; caps example

Browse files at this commit

d305564edc661f73d42c4ff6095d669c969c6295Ahmet Kaan GümüşParent: 24666c0
Cargo.lockmodified+36 -4
@@ -150,7 +150,7 @@ version = "0.70.1"
150150 source = "registry+https://github.com/rust-lang/crates.io-index"
151151 checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
152152 dependencies = [
153- "bitflags",
153+ "bitflags 2.13.1",
154154 "cexpr",
155155 "clang-sys",
156156 "itertools 0.13.0",
@@ -170,6 +170,12 @@ version = "0.10.3"
170170 source = "registry+https://github.com/rust-lang/crates.io-index"
171171 checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6"
172172
173+[[package]]
174+name = "bitflags"
175+version = "1.3.2"
176+source = "registry+https://github.com/rust-lang/crates.io-index"
177+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
178+
173179 [[package]]
174180 name = "bitflags"
175181 version = "2.13.1"
@@ -277,7 +283,7 @@ name = "cros-libva"
277283 version = "0.0.13"
278284 dependencies = [
279285 "bindgen",
280- "bitflags",
286+ "bitflags 2.13.1",
281287 "crc32fast",
282288 "log",
283289 "pkg-config",
@@ -1293,7 +1299,7 @@ version = "0.18.1"
12931299 source = "registry+https://github.com/rust-lang/crates.io-index"
12941300 checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
12951301 dependencies = [
1296- "bitflags",
1302+ "bitflags 2.13.1",
12971303 "crc32fast",
12981304 "fdeflate",
12991305 "flate2",
@@ -1506,7 +1512,7 @@ version = "11.6.0"
15061512 source = "registry+https://github.com/rust-lang/crates.io-index"
15071513 checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"
15081514 dependencies = [
1509- "bitflags",
1515+ "bitflags 2.13.1",
15101516 ]
15111517
15121518 [[package]]
@@ -1876,6 +1882,32 @@ version = "0.9.5"
18761882 source = "registry+https://github.com/rust-lang/crates.io-index"
18771883 checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
18781884
1885+[[package]]
1886+name = "vk-video-ffi"
1887+version = "0.1.0"
1888+dependencies = [
1889+ "vulkanalia",
1890+]
1891+
1892+[[package]]
1893+name = "vulkanalia"
1894+version = "0.35.0"
1895+source = "registry+https://github.com/rust-lang/crates.io-index"
1896+checksum = "ebd71d6c64383bbdf1c260efa22e81e1a2a7dd832a3831af34495f47d7551d7b"
1897+dependencies = [
1898+ "libloading",
1899+ "vulkanalia-sys",
1900+]
1901+
1902+[[package]]
1903+name = "vulkanalia-sys"
1904+version = "0.35.0"
1905+source = "registry+https://github.com/rust-lang/crates.io-index"
1906+checksum = "08d4da5d5e0c7377cea24358fa238b3b22a1913a7890f65dbd8ff9aa371a493a"
1907+dependencies = [
1908+ "bitflags 1.3.2",
1909+]
1910+
18791911 [[package]]
18801912 name = "wasip2"
18811913 version = "1.0.4+wasi-0.2.12"
shims/vk-video-ffi/Cargo.tomladded+9 -0
@@ -0,0 +1,9 @@
1+[package]
2+name = "vk-video-ffi"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+authors.workspace = true
7+
8+[dependencies]
9+vulkanalia = { version = "0.35", features = ["libloading"] }
shims/vk-video-ffi/examples/caps.rsadded+18 -0
@@ -0,0 +1,18 @@
1+use vk_video_ffi::Gpu;
2+
3+fn main() {
4+ let gpu = match Gpu::open() {
5+ Ok(gpu) => gpu,
6+ Err(e) => {
7+ eprintln!("{e}");
8+ std::process::exit(1);
9+ }
10+ };
11+ println!("{}", gpu.device_name());
12+ for c in gpu.caps() {
13+ println!(
14+ "{:?} {:?} max {}x{} dpb {} refs {}",
15+ c.codec, c.direction, c.max_width, c.max_height, c.max_dpb_slots, c.max_active_refs
16+ );
17+ }
18+}
shims/vk-video-ffi/src/lib.rsadded+413 -0
@@ -0,0 +1,413 @@
1+//! Safe capability probe for Vulkan Video over vulkanalia.
2+#![deny(missing_docs)]
3+
4+use std::collections::BTreeSet;
5+use std::ffi::c_char;
6+use std::fmt;
7+
8+use vk::KhrVideoQueueExtensionInstanceCommands;
9+use vulkanalia::loader::LibloadingLoader;
10+use vulkanalia::prelude::v1_3::*;
11+
12+const WANTED: [vk::Extension; 14] = [
13+ vk::KHR_VIDEO_QUEUE_EXTENSION,
14+ vk::KHR_VIDEO_ENCODE_QUEUE_EXTENSION,
15+ vk::KHR_VIDEO_DECODE_QUEUE_EXTENSION,
16+ vk::KHR_VIDEO_ENCODE_H264_EXTENSION,
17+ vk::KHR_VIDEO_ENCODE_H265_EXTENSION,
18+ vk::KHR_VIDEO_ENCODE_AV1_EXTENSION,
19+ vk::KHR_VIDEO_DECODE_H264_EXTENSION,
20+ vk::KHR_VIDEO_DECODE_H265_EXTENSION,
21+ vk::KHR_VIDEO_DECODE_AV1_EXTENSION,
22+ vk::KHR_VIDEO_DECODE_VP9_EXTENSION,
23+ vk::KHR_VIDEO_MAINTENANCE1_EXTENSION,
24+ vk::EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION,
25+ vk::KHR_EXTERNAL_MEMORY_FD_EXTENSION,
26+ vk::EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION,
27+];
28+
29+/// Errors from opening a GPU or probing it.
30+#[derive(Debug)]
31+pub enum Error {
32+ /// The Vulkan loader library could not be loaded.
33+ NoLoader(String),
34+ /// No physical device has a usable video queue family.
35+ NoDevice,
36+ /// A Vulkan call failed: VkResult code and call name.
37+ Vk(i32, &'static str),
38+ /// The requested codec or direction is not supported.
39+ Unsupported(String),
40+}
41+
42+impl fmt::Display for Error {
43+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44+ match self {
45+ Error::NoLoader(e) => write!(f, "no Vulkan loader: {e}"),
46+ Error::NoDevice => write!(f, "no Vulkan Video device"),
47+ Error::Vk(code, call) => write!(f, "{call} failed: VkResult {code}"),
48+ Error::Unsupported(what) => write!(f, "unsupported: {what}"),
49+ }
50+ }
51+}
52+
53+impl std::error::Error for Error {}
54+
55+/// Video codec.
56+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57+pub enum Codec {
58+ /// H.264 / AVC.
59+ H264,
60+ /// H.265 / HEVC.
61+ H265,
62+ /// AV1.
63+ Av1,
64+ /// VP9.
65+ Vp9,
66+}
67+
68+/// Video direction.
69+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70+pub enum Direction {
71+ /// Encode.
72+ Encode,
73+ /// Decode.
74+ Decode,
75+}
76+
77+/// Capabilities of one codec and direction, 4:2:0 8-bit.
78+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79+pub struct CodecCaps {
80+ /// Codec.
81+ pub codec: Codec,
82+ /// Direction.
83+ pub direction: Direction,
84+ /// Maximum coded width.
85+ pub max_width: u32,
86+ /// Maximum coded height.
87+ pub max_height: u32,
88+ /// Maximum DPB slots.
89+ pub max_dpb_slots: u32,
90+ /// Maximum active reference pictures.
91+ pub max_active_refs: u32,
92+}
93+
94+/// An opened Vulkan device with video queues.
95+pub struct Gpu {
96+ device: Device,
97+ instance: Instance,
98+ physical: vk::PhysicalDevice,
99+ name: String,
100+ _entry: Entry,
101+}
102+
103+struct Families {
104+ encode: Option<u32>,
105+ decode: Option<u32>,
106+ graphics: Option<u32>,
107+}
108+
109+fn queue_families(instance: &Instance, physical: vk::PhysicalDevice) -> Families {
110+ let flags: Vec<vk::QueueFlags> =
111+ unsafe { instance.get_physical_device_queue_family_properties(physical) }
112+ .iter()
113+ .map(|p| p.queue_flags)
114+ .collect();
115+ let find = |pred: &dyn Fn(vk::QueueFlags) -> bool| {
116+ flags.iter().position(|&f| pred(f)).map(|i| i as u32)
117+ };
118+ Families {
119+ encode: find(&|f| f.contains(vk::QueueFlags::VIDEO_ENCODE_KHR)),
120+ decode: find(&|f| f.contains(vk::QueueFlags::VIDEO_DECODE_KHR)),
121+ graphics: find(&|f| {
122+ f.contains(vk::QueueFlags::GRAPHICS) || f.contains(vk::QueueFlags::COMPUTE)
123+ }),
124+ }
125+}
126+
127+fn setup(instance: &Instance) -> Result<(vk::PhysicalDevice, Device, String), Error> {
128+ let devices = unsafe { instance.enumerate_physical_devices() }
129+ .map_err(|c| Error::Vk(c.as_raw(), "vkEnumeratePhysicalDevices"))?;
130+ let (physical, families) = devices
131+ .into_iter()
132+ .find_map(|pd| {
133+ let f = queue_families(instance, pd);
134+ (f.encode.is_some() || f.decode.is_some()).then_some((pd, f))
135+ })
136+ .ok_or(Error::NoDevice)?;
137+ let graphics = families.graphics.ok_or(Error::NoDevice)?;
138+
139+ let mut indices = BTreeSet::from([graphics]);
140+ indices.extend(families.encode);
141+ indices.extend(families.decode);
142+ let priority = [1.0f32];
143+ let queues: Vec<vk::DeviceQueueCreateInfo> = indices
144+ .iter()
145+ .map(|&index| {
146+ vk::DeviceQueueCreateInfo::builder()
147+ .queue_family_index(index)
148+ .queue_priorities(&priority)
149+ .build()
150+ })
151+ .collect();
152+
153+ let available: Vec<vk::ExtensionName> =
154+ unsafe { instance.enumerate_device_extension_properties(physical, None) }
155+ .map_err(|c| Error::Vk(c.as_raw(), "vkEnumerateDeviceExtensionProperties"))?
156+ .iter()
157+ .map(|e| e.extension_name)
158+ .collect();
159+ let enabled: Vec<vk::ExtensionName> = WANTED
160+ .iter()
161+ .map(|e| e.name)
162+ .filter(|n| available.contains(n))
163+ .collect();
164+ let names: Vec<*const c_char> = enabled.iter().map(|n| n.as_cstr().as_ptr()).collect();
165+
166+ let mut sync2 = vk::PhysicalDeviceSynchronization2Features::builder();
167+ let mut ycbcr = vk::PhysicalDeviceSamplerYcbcrConversionFeatures::builder();
168+ let mut maint = vk::PhysicalDeviceVideoMaintenance1FeaturesKHR::builder();
169+ let mut features = vk::PhysicalDeviceFeatures2::builder()
170+ .push_next(&mut sync2)
171+ .push_next(&mut ycbcr);
172+ if enabled.contains(&vk::KHR_VIDEO_MAINTENANCE1_EXTENSION.name) {
173+ features = features.push_next(&mut maint);
174+ }
175+ unsafe { instance.get_physical_device_features2(physical, &mut features) };
176+
177+ let info = vk::DeviceCreateInfo::builder()
178+ .queue_create_infos(&queues)
179+ .enabled_extension_names(&names)
180+ .push_next(&mut features);
181+ let device = unsafe { instance.create_device(physical, &info, None) }
182+ .map_err(|c| Error::Vk(c.as_raw(), "vkCreateDevice"))?;
183+
184+ let name = unsafe { instance.get_physical_device_properties(physical) }
185+ .device_name
186+ .to_string_lossy()
187+ .into_owned();
188+ Ok((physical, device, name))
189+}
190+
191+impl Gpu {
192+ /// Loads Vulkan and opens the first device with a video queue family.
193+ pub fn open() -> Result<Gpu, Error> {
194+ let library = if cfg!(windows) {
195+ "vulkan-1.dll"
196+ } else {
197+ "libvulkan.so.1"
198+ };
199+ let loader = unsafe { LibloadingLoader::new(library) }
200+ .map_err(|e| Error::NoLoader(e.to_string()))?;
201+ let entry = unsafe { Entry::new(loader) }.map_err(|e| Error::NoLoader(e.to_string()))?;
202+ let app = vk::ApplicationInfo::builder().api_version(vk::make_version(1, 3, 0));
203+ let info = vk::InstanceCreateInfo::builder().application_info(&app);
204+ let instance = unsafe { entry.create_instance(&info, None) }
205+ .map_err(|c| Error::Vk(c.as_raw(), "vkCreateInstance"))?;
206+ match setup(&instance) {
207+ Ok((physical, device, name)) => Ok(Gpu {
208+ device,
209+ instance,
210+ physical,
211+ name,
212+ _entry: entry,
213+ }),
214+ Err(e) => {
215+ unsafe { instance.destroy_instance(None) };
216+ Err(e)
217+ }
218+ }
219+ }
220+
221+ /// Device name as reported by the driver.
222+ pub fn device_name(&self) -> String {
223+ self.name.clone()
224+ }
225+
226+ /// Capabilities of every codec and direction the device supports.
227+ pub fn caps(&self) -> Vec<CodecCaps> {
228+ [
229+ (Codec::H264, Direction::Encode),
230+ (Codec::H264, Direction::Decode),
231+ (Codec::H265, Direction::Encode),
232+ (Codec::H265, Direction::Decode),
233+ (Codec::Av1, Direction::Encode),
234+ (Codec::Av1, Direction::Decode),
235+ (Codec::Vp9, Direction::Decode),
236+ ]
237+ .into_iter()
238+ .filter_map(|(codec, direction)| self.codec_caps(codec, direction).ok())
239+ .collect()
240+ }
241+
242+ fn codec_caps(&self, codec: Codec, direction: Direction) -> Result<CodecCaps, Error> {
243+ let (operation, extension) = match (codec, direction) {
244+ (Codec::H264, Direction::Encode) => (
245+ vk::VideoCodecOperationFlagsKHR::ENCODE_H264,
246+ vk::KHR_VIDEO_ENCODE_H264_EXTENSION,
247+ ),
248+ (Codec::H264, Direction::Decode) => (
249+ vk::VideoCodecOperationFlagsKHR::DECODE_H264,
250+ vk::KHR_VIDEO_DECODE_H264_EXTENSION,
251+ ),
252+ (Codec::H265, Direction::Encode) => (
253+ vk::VideoCodecOperationFlagsKHR::ENCODE_H265,
254+ vk::KHR_VIDEO_ENCODE_H265_EXTENSION,
255+ ),
256+ (Codec::H265, Direction::Decode) => (
257+ vk::VideoCodecOperationFlagsKHR::DECODE_H265,
258+ vk::KHR_VIDEO_DECODE_H265_EXTENSION,
259+ ),
260+ (Codec::Av1, Direction::Encode) => (
261+ vk::VideoCodecOperationFlagsKHR::ENCODE_AV1,
262+ vk::KHR_VIDEO_ENCODE_AV1_EXTENSION,
263+ ),
264+ (Codec::Av1, Direction::Decode) => (
265+ vk::VideoCodecOperationFlagsKHR::DECODE_AV1,
266+ vk::KHR_VIDEO_DECODE_AV1_EXTENSION,
267+ ),
268+ (Codec::Vp9, Direction::Decode) => (
269+ vk::VideoCodecOperationFlagsKHR::DECODE_VP9,
270+ vk::KHR_VIDEO_DECODE_VP9_EXTENSION,
271+ ),
272+ (Codec::Vp9, Direction::Encode) => {
273+ return Err(Error::Unsupported("VP9 encode".into()));
274+ }
275+ };
276+ if !self.device.extensions().contains(&extension.name) {
277+ return Err(Error::Unsupported(format!("{codec:?} {direction:?}")));
278+ }
279+ let profile = |operation| {
280+ vk::VideoProfileInfoKHR::builder()
281+ .video_codec_operation(operation)
282+ .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
283+ .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
284+ .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
285+ };
286+ match (codec, direction) {
287+ (Codec::H264, Direction::Encode) => {
288+ let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder()
289+ .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH);
290+ let p = profile(operation).push_next(&mut h);
291+ self.query(
292+ codec,
293+ direction,
294+ &p,
295+ &mut vk::VideoEncodeH264CapabilitiesKHR::builder(),
296+ )
297+ }
298+ (Codec::H264, Direction::Decode) => {
299+ let mut h = vk::VideoDecodeH264ProfileInfoKHR::builder()
300+ .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH)
301+ .picture_layout(vk::VideoDecodeH264PictureLayoutFlagsKHR::PROGRESSIVE);
302+ let p = profile(operation).push_next(&mut h);
303+ self.query(
304+ codec,
305+ direction,
306+ &p,
307+ &mut vk::VideoDecodeH264CapabilitiesKHR::builder(),
308+ )
309+ }
310+ (Codec::H265, Direction::Encode) => {
311+ let mut h = vk::VideoEncodeH265ProfileInfoKHR::builder()
312+ .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN);
313+ let p = profile(operation).push_next(&mut h);
314+ self.query(
315+ codec,
316+ direction,
317+ &p,
318+ &mut vk::VideoEncodeH265CapabilitiesKHR::builder(),
319+ )
320+ }
321+ (Codec::H265, Direction::Decode) => {
322+ let mut h = vk::VideoDecodeH265ProfileInfoKHR::builder()
323+ .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN);
324+ let p = profile(operation).push_next(&mut h);
325+ self.query(
326+ codec,
327+ direction,
328+ &p,
329+ &mut vk::VideoDecodeH265CapabilitiesKHR::builder(),
330+ )
331+ }
332+ (Codec::Av1, Direction::Encode) => {
333+ let mut h = vk::VideoEncodeAV1ProfileInfoKHR::builder()
334+ .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN);
335+ let p = profile(operation).push_next(&mut h);
336+ self.query(
337+ codec,
338+ direction,
339+ &p,
340+ &mut vk::VideoEncodeAV1CapabilitiesKHR::builder(),
341+ )
342+ }
343+ (Codec::Av1, Direction::Decode) => {
344+ let mut h = vk::VideoDecodeAV1ProfileInfoKHR::builder()
345+ .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN);
346+ let p = profile(operation).push_next(&mut h);
347+ self.query(
348+ codec,
349+ direction,
350+ &p,
351+ &mut vk::VideoDecodeAV1CapabilitiesKHR::builder(),
352+ )
353+ }
354+ (Codec::Vp9, _) => {
355+ let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder()
356+ .std_profile(vk::video::STD_VIDEO_VP9_PROFILE_0);
357+ let p = profile(operation).push_next(&mut h);
358+ self.query(
359+ codec,
360+ direction,
361+ &p,
362+ &mut vk::VideoDecodeVP9CapabilitiesKHR::builder(),
363+ )
364+ }
365+ }
366+ }
367+
368+ fn query<C>(
369+ &self,
370+ codec: Codec,
371+ direction: Direction,
372+ profile: &vk::VideoProfileInfoKHR,
373+ codec_caps: &mut C,
374+ ) -> Result<CodecCaps, Error>
375+ where
376+ C: vk::Cast,
377+ C::Target: vk::ExtendsVideoCapabilitiesKHR,
378+ {
379+ let mut decode = vk::VideoDecodeCapabilitiesKHR::builder();
380+ let mut encode = vk::VideoEncodeCapabilitiesKHR::builder();
381+ let mut caps = vk::VideoCapabilitiesKHR::builder().push_next(codec_caps);
382+ match direction {
383+ Direction::Decode => caps = caps.push_next(&mut decode),
384+ Direction::Encode => caps = caps.push_next(&mut encode),
385+ }
386+ unsafe {
387+ self.instance.get_physical_device_video_capabilities_khr(
388+ self.physical,
389+ profile,
390+ &mut caps,
391+ )
392+ }
393+ .map_err(|c| Error::Vk(c.as_raw(), "vkGetPhysicalDeviceVideoCapabilitiesKHR"))?;
394+ Ok(CodecCaps {
395+ codec,
396+ direction,
397+ max_width: caps.max_coded_extent.width,
398+ max_height: caps.max_coded_extent.height,
399+ max_dpb_slots: caps.max_dpb_slots,
400+ max_active_refs: caps.max_active_reference_pictures,
401+ })
402+ }
403+}
404+
405+impl Drop for Gpu {
406+ fn drop(&mut self) {
407+ unsafe {
408+ let _ = self.device.device_wait_idle();
409+ self.device.destroy_device(None);
410+ self.instance.destroy_instance(None);
411+ }
412+ }
413+}