Skip to main content
QAROS Rust API Dev (main) · versions: Dev (main) · Developer Guide

qaros/
render.rs

1use std::cell::{Cell, RefCell};
2use std::ffi::c_void;
3use std::marker::PhantomData;
4use std::ptr::{self, NonNull};
5use std::rc::Rc;
6use std::time::Duration;
7
8use qaros_sys::{self as sys, QarApi, defaults};
9
10use crate::callbacks::BlockingOptions;
11use crate::error::{Error, Result, check};
12use crate::library::require_handle;
13use crate::pending::{self, AbandonedCall, CallSpec, PendingCall, RawOutcome};
14use crate::session::SessionInner;
15use crate::types::{
16    AppVolumeId, Eye, Fov, FrameLayout, PeerId, PixelFormat, Pose, StreamId, ViewKind,
17};
18
19const FRAME_ALREADY_OPEN: &str =
20    "a frame is already open on this render sender; show or drop it first";
21const BEGIN_FRAME_ASYNC: &str = "qar_render_sender_begin_frame_async";
22
23/// A begin-frame in flight from [`RenderSender::start_owned_frame`], delivering an
24/// [`OwnedFrame`].
25pub type PendingFrame = PendingCall<OwnedFrame>;
26
27/// A render stream request from a peer that wants this application's
28/// frames, read inside the callback.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct RenderRequest {
31    /// Pass as [`RenderSenderConfig::target_peer`].
32    pub target_peer: PeerId,
33    pub stream_id: StreamId,
34}
35
36pub(crate) fn read_render_request(
37    api: &QarApi,
38    request: *mut sys::QarRenderStreamRequest,
39) -> Result<RenderRequest> {
40    let mut target_peer = defaults::qar_peer_id_default();
41    // SAFETY: the request is live for the callback; valid out-pointer.
42    let result =
43        unsafe { (api.qar_impl_render_request_get_target_peer_id)(request, &raw mut target_peer) };
44    check(api, "qar_render_request_get_target_peer_id", result)?;
45    let mut stream_id = defaults::qar_stream_id_default();
46    // SAFETY: as above.
47    let result =
48        unsafe { (api.qar_impl_render_request_get_stream_id)(request, &raw mut stream_id) };
49    check(api, "qar_render_request_get_stream_id", result)?;
50    Ok(RenderRequest {
51        target_peer: PeerId::from_raw(target_peer),
52        stream_id: StreamId::from_raw(stream_id),
53    })
54}
55
56/// One view inside the video frame, as declared at sender creation.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub struct FrameViewSpec {
59    pub kind: ViewKind,
60    pub eye: Eye,
61    pub texture_index: u32,
62}
63
64/// What a render sender's colour alpha means (`QarColorAlphaMode`), declared
65/// through `QarRenderSenderAlphaModeExt`. The stream publishes it and a
66/// receiver composites by it.
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
68pub enum ColorAlphaMode {
69    /// Not declared: a receiver keeps its own default. The sender chains no
70    /// extension.
71    #[default]
72    Unspecified,
73    /// The alpha channel means nothing; every pixel is fully covered. The
74    /// declaration for a `B8G8R8X8` colour, if any.
75    Opaque,
76    /// The colour is premultiplied by the alpha, which is the pixel's
77    /// coverage: what drawing over a transparent-black clear with ordinary
78    /// alpha blending produces.
79    Premultiplied,
80    /// The colour is not multiplied by the alpha. The sender premultiplies it
81    /// before the frame leaves the application, at one shader pass per frame,
82    /// and the stream publishes [`Self::Premultiplied`].
83    Straight,
84}
85
86/// What the numbers in a render sender's colour texture mean
87/// (`QarColorEncoding`), declared through `QarRenderSenderColorEncodingExt`.
88/// Whatever is declared, the stream carries sRGB-encoded colour.
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
90pub enum ColorEncoding {
91    /// sRGB-encoded, as a display shows it; nothing is converted. The sender
92    /// chains no extension.
93    #[default]
94    Srgb,
95    /// Linear light, as stored in a plain UNORM render target. The sender
96    /// encodes it at one GPU pass per frame; 8-bit linear colour bands
97    /// slightly in the darks, which [`PixelFormat::R16G16B16A16`] avoids.
98    Linear,
99}
100
101/// When a render sender's application renders its frames (`QarRenderLoop`),
102/// declared through `QarRenderSenderRenderLoopExt`.
103#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
104pub enum RenderLoop {
105    /// The application renders a frame when the receiver asks: begin-frame
106    /// waits for the receiver's render request and renders for the display
107    /// time it names. The sender chains no extension.
108    #[default]
109    RequestDriven,
110    /// The application renders from a loop of its own, at its own rate, and
111    /// polls [`RenderSender::try_begin_owned_frame`]: begin-frame waits only
112    /// for the receiver to have a destination ready, and the view poses are
113    /// predicted from the newest head pose for when the frame will be shown.
114    FreeRunning,
115}
116
117impl ColorAlphaMode {
118    fn to_raw(self) -> sys::QarColorAlphaMode {
119        match self {
120            Self::Unspecified => sys::QarColorAlphaMode::QAR_COLOR_ALPHA_MODE_UNSPECIFIED,
121            Self::Opaque => sys::QarColorAlphaMode::QAR_COLOR_ALPHA_MODE_OPAQUE,
122            Self::Premultiplied => sys::QarColorAlphaMode::QAR_COLOR_ALPHA_MODE_PREMULTIPLIED,
123            Self::Straight => sys::QarColorAlphaMode::QAR_COLOR_ALPHA_MODE_STRAIGHT,
124        }
125    }
126}
127
128impl ColorEncoding {
129    fn to_raw(self) -> sys::QarColorEncoding {
130        match self {
131            Self::Srgb => sys::QarColorEncoding::QAR_COLOR_ENCODING_SRGB,
132            Self::Linear => sys::QarColorEncoding::QAR_COLOR_ENCODING_LINEAR,
133        }
134    }
135}
136
137impl RenderLoop {
138    fn to_raw(self) -> sys::QarRenderLoop {
139        match self {
140            Self::RequestDriven => sys::QarRenderLoop::QAR_RENDER_LOOP_REQUEST_DRIVEN,
141            Self::FreeRunning => sys::QarRenderLoop::QAR_RENDER_LOOP_FREE_RUNNING,
142        }
143    }
144}
145
146/// Options for `qar_render_sender_create` on the CPU path.
147#[derive(Clone, Debug)]
148pub struct RenderSenderConfig {
149    /// The requesting peer, from [`RenderRequest::target_peer`].
150    pub target_peer: PeerId,
151    pub auto_reconnect: bool,
152    pub layout: FrameLayout,
153    /// At most `QAR_MAX_FRAME_VIEWS` (8). The docs do not specify which view
154    /// set a given layout expects; query [`RenderSender::layout`] after
155    /// creation and write pixels where the frame's views say.
156    pub views: Vec<FrameViewSpec>,
157    /// Composites the stream inside this app volume.
158    pub app_volume: Option<AppVolumeId>,
159    pub color_format: PixelFormat,
160    /// [`PixelFormat::D16Unorm`] on every graphics API;
161    /// [`PixelFormat::D24UnormS8Uint`] and [`PixelFormat::D32FloatS8X24Uint`]
162    /// on Vulkan only. A format the graphics API cannot take is refused with
163    /// [`crate::StatusCode::RENDERING_DEPTH_FORMAT_NOT_SUPPORTED`].
164    pub depth_format: PixelFormat,
165    /// Chains `QarRenderSenderAlphaModeExt` unless
166    /// [`ColorAlphaMode::Unspecified`].
167    pub alpha_mode: ColorAlphaMode,
168    /// Chains `QarRenderSenderColorEncodingExt` unless
169    /// [`ColorEncoding::Srgb`].
170    pub color_encoding: ColorEncoding,
171    /// Chains `QarRenderSenderRenderLoopExt` unless
172    /// [`RenderLoop::RequestDriven`].
173    pub render_loop: RenderLoop,
174}
175
176impl RenderSenderConfig {
177    /// The values of `qar_render_sender_init_default()`: auto-reconnect,
178    /// side-by-side, no views, BGRA8 color, D32 depth; no colour or render
179    /// loop extension, so the alpha mode is unspecified, the colour sRGB and
180    /// the loop request-driven.
181    pub fn new(target_peer: PeerId) -> Self {
182        Self {
183            target_peer,
184            auto_reconnect: true,
185            layout: FrameLayout::SideBySide,
186            views: Vec::new(),
187            app_volume: None,
188            color_format: PixelFormat::B8G8R8A8,
189            depth_format: PixelFormat::D32Float,
190            alpha_mode: ColorAlphaMode::Unspecified,
191            color_encoding: ColorEncoding::Srgb,
192            render_loop: RenderLoop::RequestDriven,
193        }
194    }
195}
196
197/// Per-view pose and field of view to render with, from `begin_frame`.
198#[derive(Clone, Copy, Debug, PartialEq)]
199pub struct ViewPose {
200    pub pose: Pose,
201    pub fov: Fov,
202}
203
204/// What `show_frame` reports about the frame just rendered. The default is
205/// `qar_render_frame_show_default()`: near 0.1, far 100, depth scale 1.
206#[derive(Clone, Copy, Debug, PartialEq)]
207pub struct ShowParams {
208    /// The near plane actually used.
209    pub near: f32,
210    /// The far plane actually used.
211    pub far: f32,
212    pub depth_scale: f32,
213}
214
215impl Default for ShowParams {
216    fn default() -> Self {
217        let raw = defaults::qar_render_frame_show_default();
218        Self {
219            near: raw.rendered_near_far.near_plane,
220            far: raw.rendered_near_far.far_plane,
221            depth_scale: raw.depth_scale,
222        }
223    }
224}
225
226/// A view rectangle inside one of the frame's textures. End coordinates are
227/// exclusive and may be smaller than the start (flips).
228#[derive(Clone, Copy, Debug, PartialEq, Eq)]
229pub struct VideoFrameView {
230    pub start_x: u32,
231    pub start_y: u32,
232    pub end_x: u32,
233    pub end_y: u32,
234    pub texture_index: u32,
235    pub array_layer_index: u32,
236    pub format: PixelFormat,
237    pub kind: ViewKind,
238    pub eye: Eye,
239}
240
241impl VideoFrameView {
242    pub(crate) fn from_raw(raw: &sys::QarVideoFrameView) -> Self {
243        Self {
244            start_x: raw.start_x,
245            start_y: raw.start_y,
246            end_x: raw.end_x,
247            end_y: raw.end_y,
248            texture_index: raw.texture_index,
249            array_layer_index: raw.array_layer_index,
250            format: PixelFormat::from_raw(raw.texture_format),
251            kind: ViewKind::from_raw(raw.data_type),
252            eye: Eye::from_raw(raw.eye),
253        }
254    }
255}
256
257/// Format and size of one texture of the frame layout (`QarTextureSize`).
258#[derive(Clone, Copy, Debug, PartialEq, Eq)]
259pub struct TextureSize {
260    pub format: PixelFormat,
261    pub width: u32,
262    pub height: u32,
263    pub array_layers: u32,
264}
265
266impl TextureSize {
267    pub(crate) fn from_raw(raw: &sys::QarTextureSize) -> Self {
268        Self {
269            format: PixelFormat::from_raw(raw.format),
270            width: raw.width,
271            height: raw.height,
272            array_layers: raw.array_layers,
273        }
274    }
275}
276
277/// The negotiated layout (`qar_render_sender_layout`).
278#[derive(Clone, Debug, PartialEq, Eq)]
279pub struct VideoFrameLayout {
280    pub views: Vec<VideoFrameView>,
281    pub textures: Vec<TextureSize>,
282}
283
284/// A CPU texture of the current frame, writable until the frame is shown.
285#[derive(Debug)]
286pub struct CpuTexture<'frame> {
287    pub size: TextureSize,
288    /// Bytes per row.
289    pub pitch: u32,
290    pub data: &'frame mut [u8],
291}
292
293/// The frame's CPU textures and the views mapping eyes and color/depth onto
294/// them (`qar_render_sender_frame_cpu`).
295#[derive(Debug)]
296pub struct CpuFrame<'frame> {
297    pub views: Vec<VideoFrameView>,
298    pub textures: Vec<CpuTexture<'frame>>,
299}
300
301/// A CPU render stream sender. Keeps its session alive; destroyed with
302/// `qar_render_stream_handle_destroy` after the last open frame.
303#[derive(Debug)]
304pub struct RenderSender {
305    inner: Rc<RenderSenderInner>,
306}
307
308// Fields drop in declaration order after `drop` destroyed the handle: the session (destroyed
309// here when this sender held its last reference) goes before the graphics references, so a
310// D3D11 device outlives the session as well as the sender.
311#[derive(Debug)]
312struct RenderSenderInner {
313    handle: NonNull<sys::QarRenderSender>,
314    session: Rc<SessionInner>,
315    /// A frame is open, or a begin-frame is in flight (pending or abandoned).
316    frame_open: Cell<bool>,
317    /// An async begin-frame whose [`PendingFrame`] was dropped before the callback; the frame
318    /// stays "open" until it is settled.
319    abandoned_frame: RefCell<Option<AbandonedCall>>,
320    // Read only by the Vulkan and D3D11 frame access, to refuse a sender of another API.
321    #[cfg_attr(not(any(feature = "vulkan", qaros_d3d11)), expect(dead_code))]
322    graphics_api: sys::QarGraphicsAPI,
323    _graphics: GraphicsReferences,
324}
325
326/// The graphics path a render sender is created for.
327#[derive(Clone, Debug)]
328pub(crate) enum SenderGraphics {
329    Cpu,
330    /// The caller vouches for the device handles (see
331    /// `Session::create_vulkan_render_sender`).
332    #[cfg(feature = "vulkan")]
333    Vulkan(crate::vulkan::VulkanStreamParams),
334    /// The parameters hold references on the device and context, or the caller vouches for
335    /// them (see `Session::create_d3d11_render_sender`).
336    #[cfg(qaros_d3d11)]
337    D3D11(crate::d3d11::D3D11StreamParams),
338}
339
340impl SenderGraphics {
341    /// What the sender has to keep alive for as long as the library may use it.
342    pub(crate) fn references(&self) -> GraphicsReferences {
343        match self {
344            #[cfg(qaros_d3d11)]
345            Self::D3D11(params) => GraphicsReferences {
346                _d3d11: Some(params.references()),
347            },
348            _ => GraphicsReferences::default(),
349        }
350    }
351}
352
353/// Graphics objects the library may use while a sender lives: the D3D11 device and context
354/// references of `D3D11StreamParams::new`. Empty for the CPU and Vulkan paths, whose handles
355/// carry no reference count.
356#[derive(Debug, Default)]
357pub(crate) struct GraphicsReferences {
358    #[cfg(qaros_d3d11)]
359    _d3d11: Option<crate::d3d11::DeviceReferences>,
360}
361
362/// A `QarRenderSenderInit` together with the app volume id and the
363/// extensions it points to, so that one allocation keeps all of it valid for
364/// as long as the library may read it.
365pub(crate) struct RenderSenderInitStorage {
366    init: sys::QarRenderSenderInit,
367    app_volume: Option<sys::QarAppVolumeId>,
368    vulkan_params: Option<sys::QarStreamParamsVulkan>,
369    #[cfg(qaros_d3d11)]
370    d3d11_params: Option<sys::QarStreamParamsD3D11>,
371    alpha_mode: Option<sys::QarRenderSenderAlphaModeExt>,
372    color_encoding: Option<sys::QarRenderSenderColorEncodingExt>,
373    render_loop: Option<sys::QarRenderSenderRenderLoopExt>,
374}
375
376impl RenderSenderInitStorage {
377    pub(crate) fn new(config: &RenderSenderConfig, graphics: &SenderGraphics) -> Result<Box<Self>> {
378        let maximum_views = sys::QAR_MAX_FRAME_VIEWS as usize;
379        if config.views.len() > maximum_views {
380            return Err(Error::InvalidArgument(format!(
381                "{} frame views requested, the C API holds at most {maximum_views}",
382                config.views.len()
383            )));
384        }
385
386        let mut init = defaults::qar_render_sender_init_default();
387        init.peer_id = config.target_peer.to_raw();
388        init.enable_auto_reconnects = config.auto_reconnect;
389        init.texture_layout = config.layout.to_raw();
390        for (slot, view) in init.frame_views.iter_mut().zip(&config.views) {
391            slot.data_type = view.kind.to_raw();
392            slot.eye = view.eye.to_raw();
393            slot.texture_index = view.texture_index;
394        }
395        init.frame_views_count = config.views.len();
396        init.color_format = config.color_format.to_raw();
397        init.depth_format = config.depth_format.to_raw();
398        let mut storage = Box::new(Self {
399            init,
400            app_volume: config.app_volume.map(AppVolumeId::to_raw),
401            vulkan_params: None,
402            #[cfg(qaros_d3d11)]
403            d3d11_params: None,
404            alpha_mode: alpha_mode_extension(config.alpha_mode),
405            color_encoding: color_encoding_extension(config.color_encoding),
406            render_loop: render_loop_extension(config.render_loop),
407        });
408        match graphics {
409            SenderGraphics::Cpu => {
410                storage.init.graphics_api = sys::QarGraphicsAPI::QAR_GRAPHICS_API_CPU;
411            }
412            #[cfg(feature = "vulkan")]
413            SenderGraphics::Vulkan(params) => {
414                storage.init.graphics_api = sys::QarGraphicsAPI::QAR_GRAPHICS_API_VULKAN;
415                storage.vulkan_params = Some(params.to_raw());
416            }
417            #[cfg(qaros_d3d11)]
418            SenderGraphics::D3D11(params) => {
419                storage.init.graphics_api = sys::QarGraphicsAPI::QAR_GRAPHICS_API_D3D11;
420                storage.d3d11_params = Some(params.to_raw());
421            }
422        }
423        Ok(storage)
424    }
425
426    pub(crate) fn graphics_api(&self) -> sys::QarGraphicsAPI {
427        self.init.graphics_api
428    }
429
430    /// Points the init at the app volume id and the extensions stored beside
431    /// it, chained as alpha mode, colour encoding, render loop, graphics
432    /// extension (the header allows any order). The returned pointer, and those inside it,
433    /// stay valid while the storage is neither moved nor accessed in any other
434    /// way.
435    pub(crate) fn wired_init(&mut self) -> *mut sys::QarRenderSenderInit {
436        self.init.app_volume_id = self.app_volume.as_ref().map_or(ptr::null(), ptr::from_ref);
437        let vulkan_extension = self
438            .vulkan_params
439            .as_mut()
440            .map(|params| ptr::from_mut(&mut params.header).cast::<c_void>());
441        #[cfg(qaros_d3d11)]
442        let d3d11_extension = self
443            .d3d11_params
444            .as_mut()
445            .map(|params| ptr::from_mut(&mut params.header).cast::<c_void>());
446        #[cfg(not(qaros_d3d11))]
447        let d3d11_extension = None;
448        let graphics_extension = vulkan_extension
449            .or(d3d11_extension)
450            .unwrap_or(ptr::null_mut());
451        let render_loop_extension = self.chain_render_loop_extension_before(graphics_extension);
452        self.init.header.next = self.chain_color_extensions_before(render_loop_extension);
453        &raw mut self.init
454    }
455
456    /// Chains the render loop extension, if set, in front of `next` and
457    /// returns the start of the chain.
458    fn chain_render_loop_extension_before(&mut self, next: *mut c_void) -> *mut c_void {
459        let Some(extension) = self.render_loop.as_mut() else {
460            return next;
461        };
462        extension.header.next = next;
463        ptr::from_mut(&mut extension.header).cast::<c_void>()
464    }
465
466    /// Chains the colour extensions that are set in front of `next` and
467    /// returns the start of the chain.
468    fn chain_color_extensions_before(&mut self, mut next: *mut c_void) -> *mut c_void {
469        if let Some(extension) = self.color_encoding.as_mut() {
470            extension.header.next = next;
471            next = ptr::from_mut(&mut extension.header).cast::<c_void>();
472        }
473        if let Some(extension) = self.alpha_mode.as_mut() {
474            extension.header.next = next;
475            next = ptr::from_mut(&mut extension.header).cast::<c_void>();
476        }
477        next
478    }
479}
480
481fn alpha_mode_extension(alpha_mode: ColorAlphaMode) -> Option<sys::QarRenderSenderAlphaModeExt> {
482    (alpha_mode != ColorAlphaMode::Unspecified).then(|| {
483        let mut extension = defaults::qar_render_sender_alpha_mode_ext_default();
484        extension.alpha_mode = alpha_mode.to_raw();
485        extension
486    })
487}
488
489fn color_encoding_extension(
490    color_encoding: ColorEncoding,
491) -> Option<sys::QarRenderSenderColorEncodingExt> {
492    (color_encoding != ColorEncoding::Srgb).then(|| {
493        let mut extension = defaults::qar_render_sender_color_encoding_ext_default();
494        extension.color_encoding = color_encoding.to_raw();
495        extension
496    })
497}
498
499fn render_loop_extension(render_loop: RenderLoop) -> Option<sys::QarRenderSenderRenderLoopExt> {
500    (render_loop != RenderLoop::RequestDriven).then(|| {
501        let mut extension = defaults::qar_render_sender_render_loop_ext_default();
502        extension.render_loop = render_loop.to_raw();
503        extension
504    })
505}
506
507impl RenderSender {
508    pub(crate) fn create(
509        session: &Rc<SessionInner>,
510        config: &RenderSenderConfig,
511        graphics: &SenderGraphics,
512        options: &BlockingOptions<'_>,
513    ) -> Result<Self> {
514        let mut storage = RenderSenderInitStorage::new(config, graphics)?;
515        let graphics_api = storage.graphics_api();
516        let init = storage.wired_init();
517        let api = session.api();
518        let mut handle: *mut sys::QarRenderSender = ptr::null_mut();
519        // SAFETY: live session; the storage behind init lives until the
520        // blocking call returns; valid out-pointer.
521        let result = unsafe {
522            (api.qar_impl_render_sender_create)(
523                session.handle.as_ptr(),
524                init,
525                options.cancel_pointer(),
526                &raw mut handle,
527            )
528        };
529        check(api, "qar_render_sender_create", result)?;
530        let handle = require_handle(handle, "qar_render_sender_create")?;
531        Ok(Self::from_created_handle(
532            session,
533            handle,
534            graphics_api,
535            graphics.references(),
536        ))
537    }
538
539    /// Takes ownership of a sender the library created on `session`, with the graphics
540    /// references it keeps until it is destroyed.
541    pub(crate) fn from_created_handle(
542        session: &Rc<SessionInner>,
543        handle: NonNull<sys::QarRenderSender>,
544        graphics_api: sys::QarGraphicsAPI,
545        graphics: GraphicsReferences,
546    ) -> Self {
547        Self {
548            inner: Rc::new(RenderSenderInner {
549                handle,
550                session: Rc::clone(session),
551                frame_open: Cell::new(false),
552                abandoned_frame: RefCell::new(None),
553                graphics_api,
554                _graphics: graphics,
555            }),
556        }
557    }
558
559    /// The sender's D3D11 frame record outside a frame cycle (`qar_render_sender_frame_d3d11`),
560    /// readable from creation: create views on the shared textures here, before the first
561    /// frame, but render into them only inside a cycle. Fails while a frame is open on this
562    /// sender; inside a cycle use [`Frame::d3d11_frame`] or [`OwnedFrame::d3d11_frame`]. Fails
563    /// for a sender not created for D3D11.
564    #[cfg(qaros_d3d11)]
565    pub fn d3d11_frame_state(&self) -> Result<crate::d3d11::D3D11Frame<'_>> {
566        self.inner.refuse_if_frame_open(
567            "a frame is open on this render sender; read its D3D11 frame through the frame",
568        )?;
569        let record = self.inner.fetch_d3d11_frame()?;
570        Ok(crate::d3d11::D3D11Frame::from_record(&record))
571    }
572
573    /// The sender-owned Vulkan frame outside a frame cycle
574    /// (`qar_render_sender_frame_vulkan`), readable from creation: create
575    /// image views and framebuffers against the real images here, before the
576    /// first frame. Fails while a frame is open on this sender;
577    /// inside a cycle use [`Frame::vulkan_frame`] or
578    /// [`OwnedFrame::vulkan_frame`], which also allow the write-back.
579    #[cfg(feature = "vulkan")]
580    pub fn vulkan_frame_state(&mut self) -> Result<crate::vulkan::VulkanFrameState<'_>> {
581        self.inner.refuse_if_frame_open(
582            "a frame is open on this render sender; read its Vulkan frame through the frame",
583        )?;
584        self.inner.fetch_vulkan_frame()
585    }
586
587    /// The `QarRenderSender` handle, for the functions only the raw table of
588    /// [`crate::Library::raw_api`] reaches, such as `qar_render_sender_last_hands`,
589    /// `qar_render_sender_stream_id` and `qar_render_sender_change_layout`.
590    ///
591    /// Taking the pointer is safe; using it is `unsafe`, under the rules of
592    /// [`crate::Session::as_raw`] for a sender: valid while this `RenderSender` lives, never
593    /// destroyed by the caller, used on the thread that drives this sender. The frame cycle stays
594    /// with the safe API: never begin or show a frame through the raw table.
595    pub fn as_raw(&self) -> *mut sys::QarRenderSender {
596        self.inner.handle.as_ptr()
597    }
598
599    /// The layout negotiated with the receiver (`qar_render_sender_layout`).
600    pub fn layout(&self) -> Result<VideoFrameLayout> {
601        let api = self.inner.session.api();
602        let mut layout = defaults::qar_video_frame_layout_default();
603        // SAFETY: live sender; valid out-pointer.
604        let result = unsafe {
605            (api.qar_impl_render_sender_layout)(self.inner.handle.as_ptr(), &raw mut layout)
606        };
607        check(api, "qar_render_sender_layout", result)?;
608        let view_count = layout.views_count.min(layout.views.len());
609        let texture_count = layout.textures_count.min(layout.textures.len());
610        Ok(VideoFrameLayout {
611            views: layout.views[..view_count]
612                .iter()
613                .map(VideoFrameView::from_raw)
614                .collect(),
615            textures: layout.textures[..texture_count]
616                .iter()
617                .map(TextureSize::from_raw)
618                .collect(),
619        })
620    }
621
622    /// For a sender created with [`RenderLoop::FreeRunning`]: the poses and
623    /// fields of view to render the next frame with, taken before begin-frame
624    /// (`qar_render_sender_next_render_pose`). Predicted now from the newest
625    /// head pose for when the frame is shown, in the same app content space as
626    /// a frame's views. The next begin-frame opens its frame with exactly these
627    /// poses: render into your own target, then begin the frame, copy into it
628    /// and show it. A second call before that begin-frame replaces the poses.
629    ///
630    /// `view_count` is at most the number of views the sender was created
631    /// with; the result is in the frame's view order, as [`OwnedFrame::view`]
632    /// indexes it. Fails with [`crate::StatusCode::RENDERING_MISSING_POSE_DATA`]
633    /// before the viewer's first head pose,
634    /// [`crate::StatusCode::RENDERING_APP_VOLUME_UNRESOLVED`] while the app volume
635    /// does not resolve, and [`crate::StatusCode::LOGIC_ERROR`] for a
636    /// request-driven sender or too many views.
637    pub fn next_render_pose(&self, view_count: usize) -> Result<Vec<ViewPose>> {
638        let api = self.inner.session.api();
639        let mut poses = vec![defaults::qar_pose_default(); view_count];
640        let mut fovs = vec![defaults::qar_fov_default(); view_count];
641        // SAFETY: live sender; both out-arrays hold `view_count` elements.
642        let result = unsafe {
643            (api.qar_impl_render_sender_next_render_pose)(
644                self.inner.handle.as_ptr(),
645                view_count,
646                poses.as_mut_ptr(),
647                fovs.as_mut_ptr(),
648            )
649        };
650        check(api, "qar_render_sender_next_render_pose", result)?;
651        Ok(poses
652            .into_iter()
653            .zip(fovs)
654            .map(|(pose, fov)| ViewPose {
655                pose: Pose::from_raw(pose),
656                fov: Fov::from_raw(fov),
657            })
658            .collect())
659    }
660
661    /// For a sender created with [`RenderLoop::FreeRunning`]: whether a frame
662    /// rendered now can be sent without waiting
663    /// (`qar_render_sender_is_ready_for_next_frame`). Never blocks.
664    ///
665    /// True once the receiver has handed back the previous frame's
666    /// destination: it is then reserved for this sender's next frame, and the
667    /// next begin-frame takes it without waiting. False while it is still out,
668    /// and while the stream is paused, reconnecting or has no receiver yet. A
669    /// loop serving several senders checks each one first and takes
670    /// [`Self::next_render_pose`], renders and begins only for those that are
671    /// ready, so a slower receiver or a reconnecting stream holds back no
672    /// other. Fails with [`crate::StatusCode::RENDERING_STREAM_IS_CLOSED`] once
673    /// the stream closed, and with [`crate::StatusCode::LOGIC_ERROR`] for a
674    /// request-driven sender or while a begin-frame is waiting.
675    pub fn is_ready_for_next_frame(&self) -> Result<bool> {
676        let api = self.inner.session.api();
677        let mut ready = false;
678        // SAFETY: live sender; `ready` outlives the call.
679        let result = unsafe {
680            (api.qar_impl_render_sender_is_ready_for_next_frame)(
681                self.inner.handle.as_ptr(),
682                &raw mut ready,
683            )
684        };
685        check(api, "qar_render_sender_is_ready_for_next_frame", result)?;
686        Ok(ready)
687    }
688
689    /// Begins a frame (`qar_render_sender_begin_frame`). Render with the
690    /// returned views' poses and fields of view, then [`Frame::show`].
691    pub fn begin_frame(&mut self, options: &BlockingOptions<'_>) -> Result<Frame<'_>> {
692        Ok(Frame {
693            owned: self.begin_owned_frame(options)?,
694            _sender: PhantomData,
695        })
696    }
697
698    /// Like [`RenderSender::begin_frame`], for a frame that stays open while
699    /// the caller does other work, for example across several UI frames
700    /// until a GPU readback arrives. The frame keeps the sender alive. One
701    /// frame is open per sender at a time; a second call before the first
702    /// frame is shown or dropped fails without calling the library.
703    pub fn begin_owned_frame(&mut self, options: &BlockingOptions<'_>) -> Result<OwnedFrame> {
704        self.inner.refuse_if_frame_open(FRAME_ALREADY_OPEN)?;
705        let api = self.inner.session.api();
706        let mut info: *mut sys::QarRenderFrameInfo = ptr::null_mut();
707        // SAFETY: live sender; valid out-pointer.
708        let result = unsafe {
709            (api.qar_impl_render_sender_begin_frame)(
710                self.inner.handle.as_ptr(),
711                options.cancel_pointer(),
712                &raw mut info,
713            )
714        };
715        check(api, "qar_render_sender_begin_frame", result)?;
716        let info = require_handle(info, "qar_render_sender_begin_frame")?;
717        self.inner.frame_open.set(true);
718        Ok(OwnedFrame {
719            info,
720            sender: Rc::clone(&self.inner),
721        })
722    }
723
724    /// Starts a frame without blocking (`qar_render_sender_begin_frame_async`) and returns at
725    /// once; [`PendingCall::poll`] or [`PendingCall::wait`] picks up the [`OwnedFrame`], which
726    /// behaves like one from [`RenderSender::begin_owned_frame`] (CPU, Vulkan and D3D11 access
727    /// alike). Same poses, failures and wait through a paused stream as the blocking begin.
728    ///
729    /// The frame counts as open from the start: another begin on this sender fails without a
730    /// library call until the pending frame is taken and shown or dropped. `timeout` cancels
731    /// the call through its token, after which the library calls back with
732    /// [`crate::StatusCode::TIMEOUT`]. `wake` runs on a library thread right after the result
733    /// arrived.
734    ///
735    /// Dropping the pending frame cancels it and returns at once. The next begin on this sender
736    /// first waits for its callback and destroys a frame info it delivered; destroying the sender
737    /// cancels it and waits for its callback. The
738    /// frame info the callback hands over is owned by the caller, as the runtime's tests use it;
739    /// the header does not say so.
740    pub fn start_owned_frame(
741        &mut self,
742        timeout: Option<Duration>,
743        wake: impl Fn() + Send + Sync + 'static,
744    ) -> Result<PendingFrame> {
745        self.inner.refuse_if_frame_open(FRAME_ALREADY_OPEN)?;
746        let finish_sender = Rc::clone(&self.inner);
747        let abandon_sender = Rc::clone(&self.inner);
748        let poll_sender = Rc::clone(&self.inner);
749        let spec = CallSpec {
750            function: BEGIN_FRAME_ASYNC,
751            progress: None,
752            timeout,
753            wake: Box::new(wake),
754            keep: None,
755            finish: Box::new(move |outcome: RawOutcome| {
756                let api = finish_sender.session.api();
757                let delivered = check(api, BEGIN_FRAME_ASYNC, outcome.result).and_then(|()| {
758                    require_handle(
759                        outcome.handle as *mut sys::QarRenderFrameInfo,
760                        BEGIN_FRAME_ASYNC,
761                    )
762                });
763                match delivered {
764                    Ok(info) => Ok(OwnedFrame {
765                        info,
766                        sender: finish_sender,
767                    }),
768                    Err(error) => {
769                        release_frame_info(api, outcome.handle);
770                        finish_sender.frame_open.set(false);
771                        Err(error)
772                    }
773                }
774            }),
775            abandon: Box::new(move |call| {
776                *abandon_sender.abandoned_frame.borrow_mut() = Some(call);
777            }),
778            before_poll: Box::new(move || {
779                poll_sender.session.release_delivered_abandoned_calls();
780            }),
781            destroy: Some(release_frame_info),
782        };
783        let sender = self.inner.handle.as_ptr();
784        let api = self.inner.session.api();
785        let pending = pending::start(
786            self.inner.session.library(),
787            spec,
788            |user_state, _progress, token| {
789                // SAFETY: live sender; the token outlives the call (the pending frame or the
790                // sender keeps it).
791                unsafe {
792                    (api.qar_impl_render_sender_begin_frame_async)(
793                        sender,
794                        Some(pending::handle_result_trampoline::<sys::QarRenderFrameInfo>),
795                        user_state,
796                        token,
797                    )
798                }
799            },
800        )?;
801        self.inner.frame_open.set(true);
802        Ok(pending)
803    }
804
805    /// Polls for a frame without blocking (`qar_render_sender_try_begin_frame`,
806    /// the call QuaternAR's Vulkan cube uses). The first call starts the
807    /// library's begin-frame wait; `Ok(None)` means not ready yet, poll again
808    /// later on the same sender. A frame it returns behaves like one from
809    /// [`RenderSender::begin_owned_frame`]. Fails without calling the library
810    /// while a frame is open on this sender.
811    pub fn try_begin_owned_frame(&mut self) -> Result<Option<OwnedFrame>> {
812        self.inner.refuse_if_frame_open(FRAME_ALREADY_OPEN)?;
813        let api = self.inner.session.api();
814        let mut info: *mut sys::QarRenderFrameInfo = ptr::null_mut();
815        let mut ready = false;
816        // SAFETY: live sender; valid out-pointers.
817        let result = unsafe {
818            (api.qar_impl_render_sender_try_begin_frame)(
819                self.inner.handle.as_ptr(),
820                &raw mut info,
821                &raw mut ready,
822            )
823        };
824        check(api, "qar_render_sender_try_begin_frame", result)?;
825        if !ready {
826            return Ok(None);
827        }
828        let info = require_handle(info, "qar_render_sender_try_begin_frame")?;
829        self.inner.frame_open.set(true);
830        Ok(Some(OwnedFrame {
831            info,
832            sender: Rc::clone(&self.inner),
833        }))
834    }
835}
836
837impl RenderSenderInner {
838    fn refuse_if_frame_open(&self, message: &str) -> Result<()> {
839        self.settle_abandoned_frame();
840        if self.frame_open.get() {
841            return Err(Error::InvalidArgument(message.to_string()));
842        }
843        Ok(())
844    }
845
846    /// Ends a dropped async begin-frame: waits for its callback, which the cancel brings
847    /// promptly and the header guarantees, then destroys a frame info it delivered and closes the
848    /// frame. A cancel arriving as the begin finishes may still deliver a frame, so a new begin
849    /// must not start before this.
850    fn settle_abandoned_frame(&self) {
851        if let Some(call) = self.abandoned_frame.borrow_mut().take() {
852            call.settle(self.session.api());
853            self.frame_open.set(false);
854        }
855    }
856
857    #[cfg(feature = "vulkan")]
858    fn fetch_vulkan_frame<'borrow>(&self) -> Result<crate::vulkan::VulkanFrameState<'borrow>> {
859        if self.graphics_api != sys::QarGraphicsAPI::QAR_GRAPHICS_API_VULKAN {
860            return Err(Error::InvalidArgument(
861                "this render sender was not created for Vulkan".to_string(),
862            ));
863        }
864        let api = self.session.api();
865        let mut frame: *mut sys::QarVideoFrameVulkan = ptr::null_mut();
866        // SAFETY: live sender; valid out-pointer.
867        let result = unsafe {
868            (api.qar_impl_render_sender_frame_vulkan)(self.handle.as_ptr(), &raw mut frame)
869        };
870        check(api, "qar_render_sender_frame_vulkan", result)?;
871        let frame = require_handle(frame, "qar_render_sender_frame_vulkan")?;
872        // SAFETY: the library keeps the frame valid until the next
873        // frame_vulkan call or sender destruction; callers tie 'borrow to a
874        // mutable borrow that rules out both (see the call sites).
875        Ok(unsafe { crate::vulkan::VulkanFrameState::from_raw(frame) })
876    }
877
878    /// A copy of the D3D11 frame record. The pointers in it name the sender's own textures
879    /// and keyed mutexes; callers lend them for a borrow of the sender or the open frame.
880    #[cfg(qaros_d3d11)]
881    fn fetch_d3d11_frame(&self) -> Result<sys::QarVideoFrameD3D11> {
882        if self.graphics_api != sys::QarGraphicsAPI::QAR_GRAPHICS_API_D3D11 {
883            return Err(Error::InvalidArgument(
884                "this render sender was not created for D3D11".to_string(),
885            ));
886        }
887        let api = self.session.api();
888        let mut frame = defaults::qar_video_frame_d3d11_default();
889        // SAFETY: live sender; valid out-pointer to a record the library fills.
890        let result = unsafe {
891            (api.qar_impl_render_sender_frame_d3d11)(self.handle.as_ptr(), &raw mut frame)
892        };
893        check(api, "qar_render_sender_frame_d3d11", result)?;
894        Ok(frame)
895    }
896}
897
898impl Drop for RenderSenderInner {
899    fn drop(&mut self) {
900        let api = self.session.api();
901        let abandoned = self.abandoned_frame.get_mut().take();
902        if let Some(call) = &abandoned {
903            call.release_if_delivered(api);
904        }
905        // SAFETY: open frames and pending begin-frames hold an Rc to this value, so none is
906        // alive. Per the header, the destroy cancels an abandoned begin-frame still running and
907        // returns only after its callback has returned.
908        unsafe { (api.qar_impl_render_stream_handle_destroy)(self.handle.as_ptr()) };
909        if let Some(call) = abandoned {
910            call.leak_late_delivery();
911        }
912    }
913}
914
915/// Destroys a frame info an async begin-frame delivered that nobody takes.
916fn release_frame_info(api: &QarApi, info: usize) {
917    if info != 0 {
918        // SAFETY: delivered to us, used by nobody, and its sender is alive.
919        unsafe {
920            (api.qar_impl_render_frame_info_handle_destroy)(info as *mut sys::QarRenderFrameInfo);
921        };
922    }
923}
924
925/// A frame between `begin_frame` and `show_frame`, borrowing its sender.
926/// Dropping it without [`Frame::show`] releases the frame info without
927/// presenting.
928#[derive(Debug)]
929pub struct Frame<'sender> {
930    owned: OwnedFrame,
931    _sender: PhantomData<&'sender mut RenderSender>,
932}
933
934impl Frame<'_> {
935    /// Pose and field of view for view `view_index`. The C API offers no
936    /// view count; use the number of views the sender was created with.
937    pub fn view(&self, view_index: usize) -> Result<ViewPose> {
938        self.owned.view(view_index)
939    }
940
941    /// The CPU textures to write this frame's pixels into
942    /// (`qar_render_sender_frame_cpu`).
943    pub fn cpu_frame(&mut self) -> Result<CpuFrame<'_>> {
944        self.owned.cpu_frame()
945    }
946
947    /// The sender-owned Vulkan images of this frame, with the write-back of
948    /// layouts, queue family and fence; see [`OwnedFrame::vulkan_frame`].
949    #[cfg(feature = "vulkan")]
950    pub fn vulkan_frame(&mut self) -> Result<crate::vulkan::VulkanFrame<'_>> {
951        self.owned.vulkan_frame()
952    }
953
954    /// The shared D3D11 textures of this frame and the views on them; see
955    /// [`OwnedFrame::d3d11_frame`].
956    #[cfg(qaros_d3d11)]
957    pub fn d3d11_frame(&self) -> Result<crate::d3d11::D3D11Frame<'_>> {
958        self.owned.d3d11_frame()
959    }
960
961    /// Presents the frame (`qar_render_sender_show_frame`) with the near and
962    /// far planes actually used.
963    pub fn show(self, params: &ShowParams) -> Result<()> {
964        self.owned.show(params)
965    }
966}
967
968/// A frame between `begin_frame` and `show_frame` that owns a reference to
969/// its sender, from [`RenderSender::begin_owned_frame`]. Dropping it without
970/// [`OwnedFrame::show`] releases the frame info without presenting.
971#[derive(Debug)]
972pub struct OwnedFrame {
973    info: NonNull<sys::QarRenderFrameInfo>,
974    sender: Rc<RenderSenderInner>,
975}
976
977impl OwnedFrame {
978    /// Pose and field of view for view `view_index`. The C API offers no
979    /// view count; use the number of views the sender was created with.
980    pub fn view(&self, view_index: usize) -> Result<ViewPose> {
981        let api = self.sender.session.api();
982        let mut pose = defaults::qar_pose_default();
983        // SAFETY: live frame info; valid out-pointer.
984        let result = unsafe {
985            (api.qar_impl_render_frame_info_get_view_pose)(
986                self.info.as_ptr(),
987                view_index,
988                &raw mut pose,
989            )
990        };
991        check(api, "qar_render_frame_info_get_view_pose", result)?;
992        let mut fov = defaults::qar_fov_default();
993        // SAFETY: as above.
994        let result = unsafe {
995            (api.qar_impl_render_frame_info_get_view_fov)(
996                self.info.as_ptr(),
997                view_index,
998                &raw mut fov,
999            )
1000        };
1001        check(api, "qar_render_frame_info_get_view_fov", result)?;
1002        Ok(ViewPose {
1003            pose: Pose::from_raw(pose),
1004            fov: Fov::from_raw(fov),
1005        })
1006    }
1007
1008    /// The CPU textures to write this frame's pixels into
1009    /// (`qar_render_sender_frame_cpu`).
1010    pub fn cpu_frame(&mut self) -> Result<CpuFrame<'_>> {
1011        let api = self.sender.session.api();
1012        let mut frame = defaults::qar_video_frame_cpu_default();
1013        // SAFETY: live sender; valid out-pointer.
1014        let result = unsafe {
1015            (api.qar_impl_render_sender_frame_cpu)(self.sender.handle.as_ptr(), &raw mut frame)
1016        };
1017        check(api, "qar_render_sender_frame_cpu", result)?;
1018
1019        let view_count = frame.texture_views_count.min(frame.texture_views.len());
1020        let texture_count = frame.textures_count.min(frame.textures.len());
1021        let views = frame.texture_views[..view_count]
1022            .iter()
1023            .map(VideoFrameView::from_raw)
1024            .collect();
1025        let raw_textures = &frame.textures[..texture_count];
1026        reject_overlapping_textures(raw_textures)?;
1027        let textures = raw_textures
1028            .iter()
1029            .map(|texture| CpuTexture {
1030                size: TextureSize::from_raw(&texture.size),
1031                pitch: texture.pitch,
1032                // SAFETY: the library hands out texture_data_size writable
1033                // bytes that stay valid until show_frame; the returned slice
1034                // borrows this frame mutably, so it cannot outlive show, and
1035                // only one frame is open per sender.
1036                data: unsafe { texture_bytes(texture.texture_data, texture.texture_data_size) },
1037            })
1038            .collect();
1039        Ok(CpuFrame { views, textures })
1040    }
1041
1042    /// The sender-owned Vulkan images of this frame
1043    /// (`qar_render_sender_frame_vulkan`): views, image records and the
1044    /// semaphore to signal, plus the write-back that must happen before
1045    /// [`OwnedFrame::show`]. The borrow keeps the library's frame pointer
1046    /// valid: no other `frame_vulkan` call can happen on this sender while it
1047    /// lives. Image records are snapshots; re-read them every frame.
1048    #[cfg(feature = "vulkan")]
1049    pub fn vulkan_frame(&mut self) -> Result<crate::vulkan::VulkanFrame<'_>> {
1050        self.sender
1051            .fetch_vulkan_frame()
1052            .map(crate::vulkan::VulkanFrame::new)
1053    }
1054
1055    /// The shared D3D11 textures of this frame, the views laid out on them and, when the
1056    /// sender was created with `acquire_keyed_mutex_sync` false, their keyed mutexes and keys
1057    /// (`qar_render_sender_frame_d3d11`). Render into each view's rectangle before
1058    /// [`OwnedFrame::show`]; the borrow ends before `show` can consume the frame, so the
1059    /// textures it lends cannot be used past the cycle. Read it every frame. Fails for a
1060    /// sender not created for D3D11.
1061    #[cfg(qaros_d3d11)]
1062    pub fn d3d11_frame(&self) -> Result<crate::d3d11::D3D11Frame<'_>> {
1063        let record = self.sender.fetch_d3d11_frame()?;
1064        Ok(crate::d3d11::D3D11Frame::from_record(&record))
1065    }
1066
1067    /// Presents the frame (`qar_render_sender_show_frame`) with the near and
1068    /// far planes actually used.
1069    pub fn show(self, params: &ShowParams) -> Result<()> {
1070        let api = self.sender.session.api();
1071        let mut show = defaults::qar_render_frame_show_default();
1072        show.rendered_near_far.near_plane = params.near;
1073        show.rendered_near_far.far_plane = params.far;
1074        show.depth_scale = params.depth_scale;
1075        // SAFETY: live sender; show is stamped and lives for the call.
1076        let result = unsafe {
1077            (api.qar_impl_render_sender_show_frame)(self.sender.handle.as_ptr(), &raw const show)
1078        };
1079        check(api, "qar_render_sender_show_frame", result)
1080    }
1081}
1082
1083impl Drop for OwnedFrame {
1084    fn drop(&mut self) {
1085        let destroy_frame_info = self
1086            .sender
1087            .session
1088            .api()
1089            .qar_impl_render_frame_info_handle_destroy;
1090        // SAFETY: the info handle is owned by this frame and destroyed once,
1091        // after show_frame when the frame was shown (the C sample's order).
1092        unsafe { destroy_frame_info(self.info.as_ptr()) };
1093        self.sender.frame_open.set(false);
1094    }
1095}
1096
1097/// Two `&mut` slices over the same bytes would be undefined behaviour, so
1098/// texture buffers reported by the library must be disjoint.
1099fn reject_overlapping_textures(textures: &[sys::QarVideoTextureCpu]) -> Result<()> {
1100    let mut ranges: Vec<(usize, usize)> = textures
1101        .iter()
1102        .filter(|texture| !texture.texture_data.is_null() && texture.texture_data_size > 0)
1103        .map(|texture| {
1104            let start = texture.texture_data as usize;
1105            (start, start.saturating_add(texture.texture_data_size))
1106        })
1107        .collect();
1108    ranges.sort_unstable();
1109    if ranges.windows(2).any(|pair| pair[1].0 < pair[0].1) {
1110        return Err(Error::Api {
1111            function: "qar_render_sender_frame_cpu",
1112            code: crate::error::StatusCode::UNCLASSIFIED,
1113            message: "the frame's CPU textures share memory; this wrapper needs disjoint buffers"
1114                .to_string(),
1115            causes: Vec::new(),
1116        });
1117    }
1118    Ok(())
1119}
1120
1121/// # Safety
1122///
1123/// `data` must be null or point to `size` writable bytes valid for `'frame`.
1124unsafe fn texture_bytes<'frame>(data: *mut u8, size: usize) -> &'frame mut [u8] {
1125    if data.is_null() || size == 0 {
1126        return &mut [];
1127    }
1128    // SAFETY: forwarded to the caller.
1129    unsafe { std::slice::from_raw_parts_mut(data, size) }
1130}