qaros/d3d11.rs
1//! The D3D11 render sender path (feature `d3d11`).
2//!
3//! The application creates a D3D11.1 device and immediate context on the adapter the session
4//! uses ([`crate::Session::graphics_adapter`]) and hands both to QAROS
5//! ([`D3D11StreamParams`], chained into `QarRenderSenderInit` as `QarStreamParamsD3D11`). QAROS
6//! then creates the frame's shared textures on that device and hands them out with the views
7//! laid out on them, as `QarVideoFrameD3D11`.
8//!
9//! One frame, in the order of QuaternAR's `d3d11_render_sender.c`:
10//!
11//! 1. Begin a frame ([`crate::RenderSender::begin_owned_frame`],
12//! [`crate::RenderSender::try_begin_owned_frame`], ...).
13//! 2. [`crate::OwnedFrame::d3d11_frame`]: the views ([`D3D11Frame::view_index`] finds each
14//! eye's color and depth view) and the shared textures they lie on.
15//! 3. When the sender was created with `acquire_keyed_mutex_sync` false: acquire each
16//! texture's keyed mutex with its acquire key ([`D3D11Frame::keyed_mutexes`]).
17//! 4. Render each eye into its view's rectangle with the frame's view pose and field of view.
18//! 5. With `acquire_keyed_mutex_sync` false: release each keyed mutex with its release key.
19//! 6. [`crate::OwnedFrame::show`].
20//!
21//! # Safety rules
22//!
23//! These come from the header (`QarStreamParamsD3D11`, `QarSyncFrameD3D11`,
24//! `qar_render_sender_frame_d3d11`) and the C sample; the wrapper enforces what a borrow or a
25//! reference count can express and documents the rest.
26//!
27//! Items that take or lend `windows` crate types (`D3D11StreamParams::new`,
28//! `D3D11Texture::texture`, `D3D11KeyedMutex::mutex`) exist on Windows only; macOS builds the
29//! rest against `qaros-stub`, with raw pointers.
30//!
31//! - **Device lifetime.** `D3D11StreamParams::new` takes a reference on the device and the
32//! context (`AddRef`), and the sender keeps both until it is destroyed, and its session with
33//! it when the sender held the session's last reference. A creation dropped before its
34//! callback keeps them until the callback has come. [`D3D11StreamParams::from_raw`] takes no
35//! reference; the caller then keeps both valid that long.
36//! - **The immediate context.** QAROS uses the context it is given. When and on which thread
37//! is not documented, and a D3D11 immediate context is not thread-safe. That is why sender
38//! creation is `unsafe`: use the context only on the thread that drives the sender (every
39//! `qaros` handle stays on one thread), or turn on the device's multithread protection
40//! (`ID3D11Multithread::SetMultithreadProtected`).
41//! - **Ownership of the textures.** The shared textures and their keyed mutexes are the
42//! sender's. `D3D11Texture::texture` and `D3D11KeyedMutex::mutex` lend them for the
43//! borrow of the frame, without `AddRef` or `Release`; clone the interface to keep one
44//! longer. Read the frame every cycle: the header does not say the textures stay the same.
45//! - **Writes only inside a frame cycle.** The frame record is readable from creation
46//! ([`crate::RenderSender::d3d11_frame_state`], for creating views up front); the textures
47//! may be rendered to only between a begin and its show (the header's "writable only inside
48//! a frame cycle"). The wrapper cannot see GPU work, so this rule is the caller's.
49//! - **Keyed mutexes.** With `acquire_keyed_mutex_sync` true (the header's default) the
50//! library acquires and releases them around the cycle; do not touch them. With it false
51//! the application drives the chain with the record's keys; the header gives the keys and
52//! says the entries match the textures, an empty list meaning no external synchronization.
53//! - **Device.** D3D11.1 (`ID3D11Device1`, `ID3D11DeviceContext1`), on the session's adapter:
54//! the header creates the session's devices, and with them every sender's frame textures,
55//! there.
56
57use std::ffi::c_void;
58use std::marker::PhantomData;
59
60use qaros_sys::{self as sys, defaults};
61#[cfg(windows)]
62use windows::Win32::Graphics::Direct3D11::{ID3D11Device1, ID3D11DeviceContext1, ID3D11Texture2D};
63#[cfg(windows)]
64use windows::Win32::Graphics::Dxgi::IDXGIKeyedMutex;
65#[cfg(windows)]
66use windows::core::Interface as _;
67
68use crate::render::{TextureSize, VideoFrameView};
69use crate::types::{Eye, ViewKind};
70
71/// `QarStreamParamsD3D11`: the application's D3D11.1 device and immediate context, on which
72/// QAROS creates the frame's shared textures, and how it creates and synchronizes them.
73#[derive(Clone, Debug)]
74pub struct D3D11StreamParams {
75 device: DeviceReferences,
76 /// `D3D11_BIND_FLAG` bits of the color textures; the C sample asks for
77 /// `D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE`. The header's default is 0.
78 pub color_bind_flags: u32,
79 /// `D3D11_BIND_FLAG` bits of the depth textures, for example `D3D11_BIND_DEPTH_STENCIL`.
80 /// QAROS creates them as `DXGI_FORMAT_D32_FLOAT`, a typed depth format, so
81 /// `D3D11_BIND_SHADER_RESOURCE` makes sender creation fail with `E_INVALIDARG`. The header's
82 /// default is 0.
83 pub depth_bind_flags: u32,
84 /// True (the header's default): the library acquires and releases each texture's keyed
85 /// mutex around the frame cycle. False: the application drives the keyed-mutex chain with
86 /// the keys in [`D3D11Frame::keyed_mutexes`], for example when it copies through a chain of
87 /// shared textures.
88 pub acquire_keyed_mutex_sync: bool,
89}
90
91/// The device and context pointers handed to QAROS, and on Windows the references that keep
92/// them alive while a sender may use them.
93#[derive(Clone, Debug)]
94pub(crate) struct DeviceReferences {
95 device: *mut sys::ID3D11Device1,
96 context: *mut sys::ID3D11DeviceContext1,
97 #[cfg(windows)]
98 _held: Option<(ID3D11Device1, ID3D11DeviceContext1)>,
99}
100
101impl D3D11StreamParams {
102 /// The header's defaults (`qar_stream_params_d3d11_default`: no bind flags, the library
103 /// drives the keyed mutexes) for `device` and its immediate `context`. Takes a reference
104 /// on both, which every sender created with these parameters keeps.
105 #[cfg(windows)]
106 pub fn new(device: &ID3D11Device1, context: &ID3D11DeviceContext1) -> Self {
107 Self::with_defaults(DeviceReferences {
108 device: device.as_raw().cast::<sys::ID3D11Device1>(),
109 context: context.as_raw().cast::<sys::ID3D11DeviceContext1>(),
110 _held: Some((device.clone(), context.clone())),
111 })
112 }
113
114 /// The header's defaults for a device and context given as raw pointers, from another
115 /// D3D11 binding or a test. `None` when either is null. No reference is taken.
116 ///
117 /// # Safety
118 ///
119 /// `device` is an `ID3D11Device1` and `context` its immediate `ID3D11DeviceContext1`, and
120 /// both stay valid for as long as a sender created with these parameters may use them:
121 /// until its session is dropped, and for a creation started with
122 /// [`crate::Session::start_d3d11_render_sender`] as described there.
123 pub unsafe fn from_raw(
124 device: *mut sys::ID3D11Device1,
125 context: *mut sys::ID3D11DeviceContext1,
126 ) -> Option<Self> {
127 if device.is_null() || context.is_null() {
128 return None;
129 }
130 Some(Self::with_defaults(DeviceReferences {
131 device,
132 context,
133 #[cfg(windows)]
134 _held: None,
135 }))
136 }
137
138 fn with_defaults(device: DeviceReferences) -> Self {
139 let raw = defaults::qar_stream_params_d3d11_default();
140 Self {
141 device,
142 color_bind_flags: raw.color_bind_flags,
143 depth_bind_flags: raw.depth_bind_flags,
144 acquire_keyed_mutex_sync: raw.acquire_keyed_mutex_sync,
145 }
146 }
147
148 /// The device pointer handed to QAROS.
149 pub fn device_raw(&self) -> *mut sys::ID3D11Device1 {
150 self.device.device
151 }
152
153 /// The immediate context pointer handed to QAROS.
154 pub fn context_raw(&self) -> *mut sys::ID3D11DeviceContext1 {
155 self.device.context
156 }
157
158 pub(crate) fn to_raw(&self) -> sys::QarStreamParamsD3D11 {
159 let mut raw = defaults::qar_stream_params_d3d11_default();
160 raw.d3d11_device = self.device.device;
161 raw.d3d11_context = self.device.context;
162 raw.color_bind_flags = self.color_bind_flags;
163 raw.depth_bind_flags = self.depth_bind_flags;
164 raw.acquire_keyed_mutex_sync = self.acquire_keyed_mutex_sync;
165 raw
166 }
167
168 pub(crate) fn references(&self) -> DeviceReferences {
169 self.device.clone()
170 }
171}
172
173/// One shared texture of the frame (`QarVideoTextureD3D11`), lent for the borrow of the frame.
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
175pub struct D3D11Texture<'frame> {
176 pub size: TextureSize,
177 raw: *mut c_void,
178 _frame: PhantomData<&'frame ()>,
179}
180
181impl D3D11Texture<'_> {
182 /// The `ID3D11Texture2D` pointer the record carries. The sender owns it.
183 pub fn as_raw(&self) -> *mut sys::ID3D11Texture2D {
184 self.raw.cast()
185 }
186
187 /// The texture, borrowed: no `AddRef`, no `Release`. `None` when the record carries a null
188 /// pointer.
189 #[cfg(windows)]
190 pub fn texture(&self) -> Option<&ID3D11Texture2D> {
191 // SAFETY: the record's texture is a live ID3D11Texture2D owned by the sender, which
192 // the frame borrow keeps alive.
193 unsafe { ID3D11Texture2D::from_raw_borrowed(&self.raw) }
194 }
195}
196
197/// The keyed mutex of one shared texture and the keys of its acquire and release
198/// (`QarDXGIKeyedMutexSync`), for an application that drives the chain itself.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub struct D3D11KeyedMutex<'frame> {
201 /// The key to pass to `IDXGIKeyedMutex::AcquireSync` before rendering.
202 pub acquire_key: u32,
203 /// The key to pass to `IDXGIKeyedMutex::ReleaseSync` after rendering.
204 pub release_key: u32,
205 raw: *mut c_void,
206 _frame: PhantomData<&'frame ()>,
207}
208
209impl D3D11KeyedMutex<'_> {
210 /// The `IDXGIKeyedMutex` pointer the record carries. The sender owns it.
211 pub fn as_raw(&self) -> *mut sys::IDXGIKeyedMutex {
212 self.raw.cast()
213 }
214
215 /// The keyed mutex, borrowed: no `AddRef`, no `Release`. `None` when the record carries
216 /// a null pointer.
217 #[cfg(windows)]
218 pub fn mutex(&self) -> Option<&IDXGIKeyedMutex> {
219 // SAFETY: the record's mutex is a live IDXGIKeyedMutex owned by the sender, which the
220 // frame borrow keeps alive.
221 unsafe { IDXGIKeyedMutex::from_raw_borrowed(&self.raw) }
222 }
223}
224
225/// A copy of the sender's D3D11 frame record (`qar_render_sender_frame_d3d11`): its views, its
226/// shared textures and their keyed-mutex synchronization. From
227/// [`crate::OwnedFrame::d3d11_frame`] or [`crate::Frame::d3d11_frame`] inside a frame cycle,
228/// or [`crate::RenderSender::d3d11_frame_state`] outside one. The textures it lends live as
229/// long as the borrow it was taken from.
230#[derive(Debug)]
231pub struct D3D11Frame<'borrow> {
232 record: sys::QarVideoFrameD3D11,
233 _borrow: PhantomData<&'borrow ()>,
234}
235
236impl D3D11Frame<'_> {
237 pub(crate) fn from_record(record: &sys::QarVideoFrameD3D11) -> Self {
238 Self {
239 record: *record,
240 _borrow: PhantomData,
241 }
242 }
243
244 /// The record as the library wrote it, for C helpers that take it.
245 pub fn as_raw(&self) -> &sys::QarVideoFrameD3D11 {
246 &self.record
247 }
248
249 /// The frame's views: which texture, which rectangle, which eye, color or depth.
250 pub fn views(&self) -> Vec<VideoFrameView> {
251 let count = self
252 .record
253 .texture_views_count
254 .min(self.record.texture_views.len());
255 self.record.texture_views[..count]
256 .iter()
257 .map(VideoFrameView::from_raw)
258 .collect()
259 }
260
261 /// Index of the first view showing `kind` for `eye`. The same index selects the view's
262 /// pose and field of view on the frame ([`crate::OwnedFrame::view`]).
263 pub fn view_index(&self, eye: Eye, kind: ViewKind) -> Option<usize> {
264 self.views()
265 .iter()
266 .position(|view| view.eye == eye && view.kind == kind)
267 }
268
269 /// Number of shared textures in the frame.
270 pub fn texture_count(&self) -> usize {
271 self.record.textures_count.min(self.record.textures.len())
272 }
273
274 /// The texture a view's `texture_index` names.
275 pub fn texture(&self, index: usize) -> Option<D3D11Texture<'_>> {
276 self.record.textures[..self.texture_count()]
277 .get(index)
278 .map(texture_from_raw)
279 }
280
281 /// Every shared texture of the frame, in `texture_index` order.
282 pub fn textures(&self) -> Vec<D3D11Texture<'_>> {
283 self.record.textures[..self.texture_count()]
284 .iter()
285 .map(texture_from_raw)
286 .collect()
287 }
288
289 /// One entry per texture when the application drives the keyed mutexes
290 /// (`acquire_keyed_mutex_sync` false); empty when no external synchronization is needed.
291 pub fn keyed_mutexes(&self) -> Vec<D3D11KeyedMutex<'_>> {
292 let synchronization = &self.record.synchronization;
293 let count = synchronization
294 .texture_sync_count
295 .min(synchronization.texture_sync.len());
296 synchronization.texture_sync[..count]
297 .iter()
298 .map(|sync| D3D11KeyedMutex {
299 acquire_key: sync.acquire,
300 release_key: sync.release,
301 raw: sync.mutex.cast(),
302 _frame: PhantomData,
303 })
304 .collect()
305 }
306}
307
308fn texture_from_raw<'frame>(raw: &sys::QarVideoTextureD3D11) -> D3D11Texture<'frame> {
309 D3D11Texture {
310 size: TextureSize::from_raw(&raw.size),
311 raw: raw.texture.cast(),
312 _frame: PhantomData,
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319
320 fn record_with_two_textures() -> sys::QarVideoFrameD3D11 {
321 let mut record = defaults::qar_video_frame_d3d11_default();
322 record.textures_count = 2;
323 record.textures[0].texture = 0x1000 as *mut sys::ID3D11Texture2D;
324 record.textures[0].size.width = 128;
325 record.textures[1].texture = 0x2000 as *mut sys::ID3D11Texture2D;
326 record.texture_views_count = 2;
327 record.texture_views[0].eye = sys::QarVideoFrameViewEye::QAR_VIDEO_FRAME_VIEW_EYE_LEFT;
328 record.texture_views[0].data_type =
329 sys::QarVideoFrameViewType::QAR_VIDEO_FRAME_VIEW_TYPE_DEPTH;
330 record.texture_views[0].texture_index = 1;
331 record.texture_views[1].eye = sys::QarVideoFrameViewEye::QAR_VIDEO_FRAME_VIEW_EYE_LEFT;
332 record.texture_views[1].data_type =
333 sys::QarVideoFrameViewType::QAR_VIDEO_FRAME_VIEW_TYPE_COLOR;
334 record.synchronization.texture_sync_count = 2;
335 record.synchronization.texture_sync[0].mutex = 0x3000 as *mut sys::IDXGIKeyedMutex;
336 record.synchronization.texture_sync[0].acquire = 7;
337 record.synchronization.texture_sync[0].release = 8;
338 record
339 }
340
341 #[test]
342 fn views_textures_and_keys_are_read_within_their_counts() {
343 let frame = D3D11Frame::from_record(&record_with_two_textures());
344 assert_eq!(frame.view_index(Eye::Left, ViewKind::Color), Some(1));
345 assert_eq!(frame.view_index(Eye::Right, ViewKind::Color), None);
346 let textures = frame.textures();
347 assert_eq!(textures.len(), 2);
348 assert_eq!(textures[0].as_raw() as usize, 0x1000);
349 assert_eq!(textures[0].size.width, 128);
350 assert_eq!(
351 frame.texture(1).map(|texture| texture.as_raw() as usize),
352 Some(0x2000)
353 );
354 assert_eq!(frame.texture(2), None);
355 let keyed_mutexes = frame.keyed_mutexes();
356 assert_eq!(keyed_mutexes.len(), 2);
357 assert_eq!(keyed_mutexes[0].as_raw() as usize, 0x3000);
358 assert_eq!(
359 (keyed_mutexes[0].acquire_key, keyed_mutexes[0].release_key),
360 (7, 8)
361 );
362 }
363
364 #[test]
365 fn counts_beyond_the_arrays_are_clamped() {
366 let mut record = record_with_two_textures();
367 record.textures_count = usize::MAX;
368 record.texture_views_count = usize::MAX;
369 record.synchronization.texture_sync_count = usize::MAX;
370 let frame = D3D11Frame::from_record(&record);
371 assert_eq!(frame.texture_count(), sys::QAR_MAX_FRAME_TEXTURES as usize);
372 assert_eq!(frame.views().len(), sys::QAR_MAX_FRAME_VIEWS as usize);
373 assert_eq!(
374 frame.keyed_mutexes().len(),
375 sys::QAR_MAX_FRAME_TEXTURES as usize
376 );
377 }
378
379 #[test]
380 fn stream_params_carry_the_pointers_flags_and_stamp() {
381 // SAFETY: the pointers are only copied into the record, never used.
382 let created = unsafe {
383 D3D11StreamParams::from_raw(
384 0x4000 as *mut sys::ID3D11Device1,
385 0x5000 as *mut sys::ID3D11DeviceContext1,
386 )
387 };
388 let Some(mut params) = created else {
389 unreachable!("non-null pointers are accepted");
390 };
391 assert!(params.acquire_keyed_mutex_sync);
392 assert_eq!((params.color_bind_flags, params.depth_bind_flags), (0, 0));
393 params.color_bind_flags = 0x28;
394 params.acquire_keyed_mutex_sync = false;
395 let raw = params.to_raw();
396 assert_eq!(
397 raw.header.type_,
398 sys::QarStructureType::QAR_STRUCTURE_TYPE_STREAM_D3D11_PARAMS_EXT
399 );
400 assert!(raw.header.next.is_null());
401 assert_eq!(raw.d3d11_device as usize, 0x4000);
402 assert_eq!(raw.d3d11_context as usize, 0x5000);
403 assert_eq!(raw.color_bind_flags, 0x28);
404 assert!(!raw.acquire_keyed_mutex_sync);
405 // SAFETY: null pointers are refused before anything else.
406 let refused = unsafe {
407 D3D11StreamParams::from_raw(
408 std::ptr::null_mut(),
409 0x5000 as *mut sys::ID3D11DeviceContext1,
410 )
411 };
412 assert!(refused.is_none());
413 }
414}