qaros/vulkan.rs
1//! The Vulkan render sender path (feature `vulkan`).
2//!
3//! The application creates its own `VkInstance` and `VkDevice` on the
4//! adapter the session uses ([`crate::GraphicsAdapter`]) and hands both to
5//! QAROS ([`VulkanStreamParams`], chained into `QarRenderSenderInit`). QAROS
6//! then owns the frame images: it creates them on that device and reports,
7//! per frame, each image's handle, memory, size, format features, current
8//! layout and queue family, plus a binary semaphore to signal.
9//!
10//! One frame, in the order of QuaternAR's `vulkan_cube` example:
11//!
12//! 1. Begin a frame ([`crate::RenderSender::begin_owned_frame`],
13//! [`crate::RenderSender::try_begin_owned_frame`], ...).
14//! 2. [`crate::OwnedFrame::vulkan_frame`]: find each eye's color and depth
15//! view ([`VulkanFrameState::view_index`]) and read the image records.
16//! 3. Record a barrier per image from its reported `layout` and
17//! `queue_family_index` to the attachment layout on the application's
18//! queue family (no ownership transfer when the reported family is
19//! `VK_QUEUE_FAMILY_IGNORED` or already the application's).
20//! 4. Render each eye with the frame's view pose and field of view.
21//! 5. Record a barrier per image to [`SHOWN_LAYOUT`]
22//! (`VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL`) that releases ownership to
23//! `VK_QUEUE_FAMILY_EXTERNAL`.
24//! 6. Submit, signalling [`VulkanFrameState::semaphore`].
25//! 7. Write the new state back: [`VulkanFrame::release_to_external`] (or
26//! [`VulkanFrame::set_image_state`] per image) and
27//! [`VulkanFrame::set_fence`] with a null fence.
28//! 8. [`crate::OwnedFrame::show`].
29//!
30//! A frame that is begun but not rendered must still signal the semaphore
31//! (an empty submission will do) before it is dropped, so that QAROS can
32//! consume it.
33//!
34//! # Safety rules
35//!
36//! These come from the header (`qar_render_sender_frame_vulkan`,
37//! `QarStreamParamsVulkan`) and the cube example; the wrapper enforces what a
38//! borrow can express and documents the rest.
39//!
40//! - **Ownership.** QAROS owns the images, their memory and the semaphore.
41//! Never destroy, free or re-bind them. They live at most as long as the
42//! render sender; the handles may change between frames (after a layout
43//! change, for example), so read the records every frame and rebuild image
44//! views when a handle changes.
45//! - **Frame pointer validity.** The library's frame record stays valid until
46//! the next `qar_render_sender_frame_vulkan` call or sender destruction.
47//! [`VulkanFrameState`] and [`VulkanFrame`] borrow the sender or the open
48//! frame mutably, which rules out both while they live. Handles copied out
49//! of them stay valid after the borrow ends, as long as the sender lives.
50//! - **Writes only inside a frame cycle.** Only [`VulkanFrame`], from an open
51//! frame, can write back; [`VulkanFrameState`] (from the sender, outside a
52//! cycle) is read-only.
53//! - **Order.** Submit the work that signals the semaphore, then write back,
54//! then show. The write-back cannot outlive the frame (the borrow ends
55//! before `show` consumes it), but the wrapper cannot see the GPU
56//! submission: a binary semaphore wait needs its signal submitted first,
57//! so showing before submitting is invalid Vulkan usage on the QAROS side.
58//! - **Device.** The device must be created from the physical device on the
59//! session's adapter, enable [`required_device_extensions`], and outlive
60//! every render sender created with it. Queue submissions and the
61//! images' layouts are the application's responsibility; QAROS reads the
62//! written-back records to know them.
63
64use std::ffi::CStr;
65use std::marker::PhantomData;
66use std::ops::Deref;
67use std::ptr::NonNull;
68
69use ash::vk::{self, Handle};
70use qaros_sys::{self as sys, defaults};
71
72use crate::error::{Error, Result};
73use crate::render::{TextureSize, VideoFrameView};
74use crate::types::{Eye, PixelFormat, ViewKind};
75
76/// The layout every image is left in, and written back as, before
77/// `show_frame` (the cube's final transition).
78pub const SHOWN_LAYOUT: vk::ImageLayout = vk::ImageLayout::TRANSFER_SRC_OPTIMAL;
79
80/// Device extensions QAROS needs on the application's device, as the C Vulkan
81/// cube enables them: Win32 external memory and semaphores on Windows, file
82/// descriptor external memory on Linux (the cube also enables
83/// `VK_KHR_external_semaphore_fd` where the device has it). None elsewhere,
84/// where no QAROS runtime exists and the stub works with plain images.
85pub fn required_device_extensions() -> &'static [&'static CStr] {
86 if cfg!(target_os = "windows") {
87 &[
88 ash::khr::external_memory_win32::NAME,
89 ash::khr::external_semaphore_win32::NAME,
90 ]
91 } else if cfg!(target_os = "linux") {
92 &[ash::khr::external_memory_fd::NAME]
93 } else {
94 &[]
95 }
96}
97
98/// The `VkFormat` assumed for a QAROS pixel format. The header reports only
99/// the [`PixelFormat`], not the image's `VkFormat`; these are the UNORM and
100/// SFLOAT formats `qaros-stub` creates, and the depth-stencil formats by their
101/// Vulkan names (`D32FloatS8X24Uint` is `D32_SFLOAT_S8_UINT`). Whether QAROS
102/// uses the sRGB variants for 8-bit color is not documented.
103pub fn assumed_vk_format(format: PixelFormat) -> Option<vk::Format> {
104 match format {
105 PixelFormat::R8G8B8A8 => Some(vk::Format::R8G8B8A8_UNORM),
106 PixelFormat::B8G8R8A8 | PixelFormat::B8G8R8X8 => Some(vk::Format::B8G8R8A8_UNORM),
107 PixelFormat::R16G16B16A16 => Some(vk::Format::R16G16B16A16_SFLOAT),
108 PixelFormat::R32Float => Some(vk::Format::R32_SFLOAT),
109 PixelFormat::D16Unorm => Some(vk::Format::D16_UNORM),
110 PixelFormat::D32Float => Some(vk::Format::D32_SFLOAT),
111 PixelFormat::D24UnormS8Uint => Some(vk::Format::D24_UNORM_S8_UINT),
112 PixelFormat::D32FloatS8X24Uint => Some(vk::Format::D32_SFLOAT_S8_UINT),
113 PixelFormat::Other(_) => None,
114 }
115}
116
117/// `QarStreamParamsVulkan`: the application's physical device and device,
118/// on which QAROS creates the frame images.
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub struct VulkanStreamParams {
121 pub physical_device: vk::PhysicalDevice,
122 pub device: vk::Device,
123}
124
125impl VulkanStreamParams {
126 pub(crate) fn to_raw(self) -> sys::QarStreamParamsVulkan {
127 let mut raw = defaults::qar_stream_params_vulkan_default();
128 raw.physical_device = dispatchable_pointer(self.physical_device.as_raw());
129 raw.device = dispatchable_pointer(self.device.as_raw());
130 raw
131 }
132}
133
134/// Dispatchable Vulkan handles are pointers; `ash` stores them as `u64`
135/// through `Handle::as_raw`.
136fn dispatchable_pointer<Target>(raw_handle: u64) -> *mut Target {
137 usize::try_from(raw_handle).map_or(std::ptr::null_mut(), |address| address as *mut Target)
138}
139
140/// One sender-owned image of the frame (`QarVideoTextureVulkan`), copied out
141/// of the library's record.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub struct VulkanImage {
144 pub size: TextureSize,
145 pub image: vk::Image,
146 pub memory: vk::DeviceMemory,
147 /// Format features of the image's format, as QAROS reports them. The
148 /// image's usage flags are not reported.
149 pub format_features: vk::FormatFeatureFlags,
150 /// The layout the image is in now: transition from it.
151 pub layout: vk::ImageLayout,
152 /// The queue family that owns the image now; `VK_QUEUE_FAMILY_IGNORED`
153 /// means no ownership transfer is needed.
154 pub queue_family_index: u32,
155}
156
157impl VulkanImage {
158 fn from_raw(raw: &sys::QarVideoTextureVulkan) -> Self {
159 Self {
160 size: TextureSize::from_raw(&raw.size),
161 image: vk::Image::from_raw(raw.image),
162 memory: vk::DeviceMemory::from_raw(raw.image_memory),
163 format_features: vk::FormatFeatureFlags::from_raw(raw.format_features),
164 layout: vk::ImageLayout::from_raw(raw.layout),
165 queue_family_index: raw.queue_family_index,
166 }
167 }
168}
169
170/// Read access to the sender-owned Vulkan frame record. From
171/// [`crate::RenderSender::vulkan_frame_state`] outside a frame cycle, or
172/// through [`VulkanFrame`] inside one.
173#[derive(Debug)]
174pub struct VulkanFrameState<'borrow> {
175 raw: NonNull<sys::QarVideoFrameVulkan>,
176 _borrow: PhantomData<&'borrow mut sys::QarVideoFrameVulkan>,
177}
178
179impl VulkanFrameState<'_> {
180 /// # Safety
181 ///
182 /// `raw` points to the library's frame record and stays valid, and is not
183 /// accessed through another path, for the chosen lifetime.
184 pub(crate) unsafe fn from_raw(raw: NonNull<sys::QarVideoFrameVulkan>) -> Self {
185 Self {
186 raw,
187 _borrow: PhantomData,
188 }
189 }
190
191 fn record(&self) -> &sys::QarVideoFrameVulkan {
192 // SAFETY: valid and unaliased for the borrow (from_raw's contract).
193 unsafe { self.raw.as_ref() }
194 }
195
196 /// The frame's views: which image, which rectangle, which eye, color or
197 /// depth. QuaternAR's cube finds views by eye and kind rather than by the
198 /// order they were declared in; [`Self::view_index`] does that.
199 pub fn views(&self) -> Vec<VideoFrameView> {
200 let record = self.record();
201 let count = record.texture_views_count.min(record.texture_views.len());
202 record.texture_views[..count]
203 .iter()
204 .map(VideoFrameView::from_raw)
205 .collect()
206 }
207
208 /// Index of the first view showing `kind` for `eye`, the cube's
209 /// `FindFrameView`. The same index selects the view's pose and field of
210 /// view on the frame ([`crate::OwnedFrame::view`]).
211 pub fn view_index(&self, eye: Eye, kind: ViewKind) -> Option<usize> {
212 self.views()
213 .iter()
214 .position(|view| view.eye == eye && view.kind == kind)
215 }
216
217 /// Number of sender-owned images in the frame.
218 pub fn image_count(&self) -> usize {
219 let record = self.record();
220 record.textures_count.min(record.textures.len())
221 }
222
223 /// The image a view's `texture_index` names.
224 pub fn image(&self, index: usize) -> Option<VulkanImage> {
225 let record = self.record();
226 record.textures[..self.image_count()]
227 .get(index)
228 .map(VulkanImage::from_raw)
229 }
230
231 /// Every image of the frame, in `texture_index` order.
232 pub fn images(&self) -> Vec<VulkanImage> {
233 self.record().textures[..self.image_count()]
234 .iter()
235 .map(VulkanImage::from_raw)
236 .collect()
237 }
238
239 /// The binary semaphore the frame's last submission must signal. Owned by
240 /// QAROS; `VK_NULL_HANDLE` when the frame has none.
241 pub fn semaphore(&self) -> vk::Semaphore {
242 vk::Semaphore::from_raw(self.record().synchronization.semaphore)
243 }
244
245 /// The fence currently in the frame record. The cube writes null before
246 /// showing; what QAROS does with a non-null fence is not documented.
247 pub fn fence(&self) -> vk::Fence {
248 vk::Fence::from_raw(self.record().synchronization.fence)
249 }
250}
251
252/// The Vulkan frame of an open frame cycle, with write access to the state
253/// QAROS reads at `show_frame`. From [`crate::OwnedFrame::vulkan_frame`] or
254/// [`crate::Frame::vulkan_frame`]. Dereferences to [`VulkanFrameState`].
255#[derive(Debug)]
256pub struct VulkanFrame<'frame> {
257 state: VulkanFrameState<'frame>,
258}
259
260impl<'frame> VulkanFrame<'frame> {
261 pub(crate) fn new(state: VulkanFrameState<'frame>) -> Self {
262 Self { state }
263 }
264
265 /// The library's `QarVideoFrameVulkan` record of this frame, for C helpers
266 /// that take it (QuaternAR's test extension writes textures and the
267 /// write-back through it). Valid, and not to be used through another
268 /// path, while this `VulkanFrame` is borrowed.
269 pub fn as_raw_mut(&mut self) -> *mut sys::QarVideoFrameVulkan {
270 self.state.raw.as_ptr()
271 }
272
273 fn record_mut(&mut self) -> &mut sys::QarVideoFrameVulkan {
274 // SAFETY: valid and unaliased for the borrow (from_raw's contract),
275 // and this frame is inside a cycle, where the header allows writes.
276 unsafe { self.state.raw.as_mut() }
277 }
278
279 /// Records the layout and owning queue family image `index` is left in
280 /// by the work just submitted.
281 pub fn set_image_state(
282 &mut self,
283 index: usize,
284 layout: vk::ImageLayout,
285 queue_family_index: u32,
286 ) -> Result<()> {
287 let count = self.state.image_count();
288 let Some(texture) = self.record_mut().textures[..count].get_mut(index) else {
289 return Err(Error::InvalidArgument(format!(
290 "image {index} does not exist; the frame has {count}"
291 )));
292 };
293 texture.layout = layout.as_raw();
294 texture.queue_family_index = queue_family_index;
295 Ok(())
296 }
297
298 /// Records every image as left in `layout` and released to
299 /// `VK_QUEUE_FAMILY_EXTERNAL`, the cube's write-back with
300 /// [`SHOWN_LAYOUT`].
301 pub fn release_to_external(&mut self, layout: vk::ImageLayout) {
302 let count = self.state.image_count();
303 for texture in &mut self.record_mut().textures[..count] {
304 texture.layout = layout.as_raw();
305 texture.queue_family_index = vk::QUEUE_FAMILY_EXTERNAL;
306 }
307 }
308
309 /// Writes the frame's fence; the cube writes `vk::Fence::null()`.
310 pub fn set_fence(&mut self, fence: vk::Fence) {
311 self.record_mut().synchronization.fence = fence.as_raw();
312 }
313}
314
315impl<'frame> Deref for VulkanFrame<'frame> {
316 type Target = VulkanFrameState<'frame>;
317
318 fn deref(&self) -> &Self::Target {
319 &self.state
320 }
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
326
327 fn record_with_two_images() -> sys::QarVideoFrameVulkan {
328 let mut record = defaults::qar_video_frame_vulkan_default();
329 record.textures_count = 2;
330 record.textures[0].image = 11;
331 record.textures[0].layout = vk::ImageLayout::UNDEFINED.as_raw();
332 record.textures[0].queue_family_index = vk::QUEUE_FAMILY_IGNORED;
333 record.textures[1].image = 12;
334 record.texture_views_count = 2;
335 record.texture_views[0].eye = sys::QarVideoFrameViewEye::QAR_VIDEO_FRAME_VIEW_EYE_LEFT;
336 record.texture_views[0].data_type =
337 sys::QarVideoFrameViewType::QAR_VIDEO_FRAME_VIEW_TYPE_DEPTH;
338 record.texture_views[1].eye = sys::QarVideoFrameViewEye::QAR_VIDEO_FRAME_VIEW_EYE_LEFT;
339 record.texture_views[1].data_type =
340 sys::QarVideoFrameViewType::QAR_VIDEO_FRAME_VIEW_TYPE_COLOR;
341 record.texture_views[1].texture_index = 1;
342 record.synchronization.semaphore = 99;
343 record.synchronization.fence = 98;
344 record
345 }
346
347 #[test]
348 fn views_are_found_by_eye_and_kind_and_images_read_back() {
349 let mut record = record_with_two_images();
350 // SAFETY: the record lives on this stack frame for the whole test.
351 let state = unsafe { VulkanFrameState::from_raw(NonNull::from(&mut record)) };
352 assert_eq!(state.view_index(Eye::Left, ViewKind::Color), Some(1));
353 assert_eq!(state.view_index(Eye::Right, ViewKind::Color), None);
354 let images = state.images();
355 assert_eq!(images.len(), 2);
356 assert_eq!(images[1].image, vk::Image::from_raw(12));
357 assert_eq!(images[0].queue_family_index, vk::QUEUE_FAMILY_IGNORED);
358 assert_eq!(state.semaphore(), vk::Semaphore::from_raw(99));
359 assert_eq!(state.image(2), None);
360 }
361
362 #[test]
363 fn the_write_back_lands_in_the_library_record() {
364 let mut record = record_with_two_images();
365 {
366 // SAFETY: as above.
367 let state = unsafe { VulkanFrameState::from_raw(NonNull::from(&mut record)) };
368 let mut frame = VulkanFrame::new(state);
369 frame.release_to_external(SHOWN_LAYOUT);
370 frame.set_fence(vk::Fence::null());
371 let refused = frame.set_image_state(2, SHOWN_LAYOUT, 0);
372 assert!(refused.is_err());
373 }
374 for texture in &record.textures[..2] {
375 assert_eq!(texture.layout, SHOWN_LAYOUT.as_raw());
376 assert_eq!(texture.queue_family_index, vk::QUEUE_FAMILY_EXTERNAL);
377 }
378 assert_eq!(record.textures[2].layout, 0);
379 assert_eq!(record.synchronization.fence, 0);
380 }
381
382 #[test]
383 fn stream_params_carry_the_dispatchable_handles_as_pointers() {
384 let params = VulkanStreamParams {
385 physical_device: vk::PhysicalDevice::from_raw(0x1000),
386 device: vk::Device::from_raw(0x2000),
387 };
388 let raw = params.to_raw();
389 assert_eq!(
390 raw.header.type_,
391 sys::QarStructureType::QAR_STRUCTURE_TYPE_STREAM_VULKAN_PARAMS_EXT
392 );
393 assert_eq!(raw.physical_device as usize, 0x1000);
394 assert_eq!(raw.device as usize, 0x2000);
395 }
396}