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

qaros/
device.rs

1//! The device an application describes itself as (`QarPeerDeviceIdentity`), and the presence,
2//! role and device identity read back from a peer ([`PeerIdentity`]).
3
4use std::ffi::CString;
5
6use qaros_sys::{self as sys, defaults};
7
8use crate::error::Result;
9use crate::strings;
10
11/// The device categories an application may declare (`QarDeviceCategory`). An application
12/// always joins as a source; the C API refuses every other category with
13/// `QAR_STATUS_PEER_DEVICE_CATEGORY_NOT_ALLOWED`, so this enum has none of them.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
15pub enum SourceDeviceCategory {
16    /// A desktop or laptop PC (`QAR_DEVICE_CATEGORY_DESKTOP_PC`), every source app's default.
17    #[default]
18    DesktopPc,
19    /// A server machine (`QAR_DEVICE_CATEGORY_SERVER`).
20    Server,
21    /// A camera of any model, its capture process (`QAR_DEVICE_CATEGORY_CAMERA`).
22    Camera,
23}
24
25impl SourceDeviceCategory {
26    pub(crate) fn to_raw(self) -> sys::QarDeviceCategory {
27        match self {
28            Self::DesktopPc => sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_DESKTOP_PC,
29            Self::Server => sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_SERVER,
30            Self::Camera => sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_CAMERA,
31        }
32    }
33}
34
35/// The device an application describes itself as (`QarPeerDeviceIdentity`). Without one it
36/// joins as a desktop PC with the fixed id of the host OS (`DesktopWindows` / `DesktopLinux`).
37///
38/// Ids and families are open UTF-8 strings (`"Zed2i"`, `"Zed"`), matched by viewers against the
39/// hub's device catalog. An id the catalog does not know is fine: viewers fall back to the family,
40/// then to the category, and show `device_name`.
41#[derive(Clone, Debug, Default, PartialEq, Eq)]
42pub struct DeviceIdentity {
43    pub category: SourceDeviceCategory,
44    /// Required and non-empty, e.g. `"LuxonisOakD"`; an empty id fails with
45    /// [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`].
46    pub device_id: String,
47    /// Optional, e.g. `"Luxonis"`.
48    pub device_family: Option<String>,
49    /// Optional, e.g. `"OAK-D"`.
50    pub device_name: Option<String>,
51}
52
53/// A [`DeviceIdentity`] as C strings and its stamped structure, which borrows them. The owner
54/// keeps it at a stable address (inside a `Box`) while the library may read it.
55#[derive(Debug)]
56pub(crate) struct DeviceIdentityStorage {
57    pub(crate) raw: sys::QarPeerDeviceIdentity,
58    _device_id: CString,
59    _device_family: Option<CString>,
60    _device_name: Option<CString>,
61}
62
63impl DeviceIdentityStorage {
64    pub(crate) fn new(identity: &DeviceIdentity) -> Result<Self> {
65        let device_id = strings::to_c_string(&identity.device_id, "device id")?;
66        let device_family =
67            strings::optional_c_string(identity.device_family.as_deref(), "device family")?;
68        let device_name =
69            strings::optional_c_string(identity.device_name.as_deref(), "device name")?;
70        let mut raw = defaults::qar_peer_device_identity_default();
71        raw.category = identity.category.to_raw();
72        // The CStrings' buffers are on the heap: moving them keeps these pointers valid.
73        raw.device_id = device_id.as_ptr();
74        raw.device_family = strings::pointer_or_null(device_family.as_ref());
75        raw.device_name = strings::pointer_or_null(device_name.as_ref());
76        Ok(Self {
77            raw,
78            _device_id: device_id,
79            _device_family: device_family,
80            _device_name: device_name,
81        })
82    }
83}
84
85/// Where a peer is (`QarPeerPresence`). Render for [`PeerPresence::Online`] peers and
86/// [`PeerPresence::Unknown`] ones; stop at the others. A value the header does not name reads as
87/// [`PeerPresence::Unknown`], as the header says to treat it.
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
89pub enum PeerPresence {
90    /// The hub has not reconciled the peer yet; nothing says it is gone: treat it like online.
91    #[default]
92    Unknown,
93    /// The hub sees the peer in the session.
94    Online,
95    /// The hub no longer sees it (a crash, a kill, a network drop); it reads online once back.
96    Offline,
97    /// The peer announced its leave; it may come back under the same id.
98    Leaving,
99    /// The peer left for good and never comes back under its id.
100    Retired,
101}
102
103/// What a peer is in the streaming graph (`QarPeerRole`). A source renders for the
104/// [`PeerRole::Target`] peers. A value the header does not name is [`PeerRole::Other`].
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub enum PeerRole {
107    /// QAROS pipeline infrastructure the hub launched itself.
108    Internal,
109    /// A source application or a camera capture process (every application using this API).
110    Source,
111    /// Shows content: a headset's serving app, a Visualizer receiver, a camera's receiver slot.
112    Target,
113    /// A QAROS runtime (hub) process.
114    Runtime,
115    /// The operator's Visualizer control session.
116    Control,
117    /// A value the header does not name.
118    Other(i64),
119}
120
121/// What kind of device a peer is (`QarDeviceCategory`): the fallback when a viewer does not know
122/// the peer's device id or family. A value the header does not name reads as
123/// [`DeviceCategory::Unknown`], as the header says to treat it.
124#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
125pub enum DeviceCategory {
126    /// Infrastructure, runtime, control, test targets and unrecognised devices.
127    #[default]
128    Unknown,
129    DesktopPc,
130    Server,
131    /// A headset or glasses of any model.
132    Headset,
133    /// A Visualizer receiver showing streams on the PC.
134    Visualizer,
135    /// A camera of any model, its capture process.
136    Camera,
137    /// A target app that sees the scene through a camera.
138    Observer,
139}
140
141/// A peer's presence, role and device identity (`qar_peer_spec_get_presence`, `_get_role`,
142/// `_get_category`, `_get_device_id`, `_get_device_family`, `_get_device_name`), read with the
143/// rest of [`crate::PeerInfo`]. The device id and name can change while the peer runs (a serving
144/// app refines them once the device reports its model): re-read them in a peer update.
145#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct PeerIdentity {
147    pub presence: PeerPresence,
148    pub role: PeerRole,
149    pub category: DeviceCategory,
150    /// An open UTF-8 id of the exact device or app (`"MetaQuest3"`, `"DesktopWindows"`).
151    pub device_id: String,
152    /// The device family (`"MetaQuest"`), the fallback for an unknown id; empty for none.
153    pub device_family: String,
154    /// The device's human name (`"Meta Quest 3"`); empty when nothing better than the id is
155    /// known.
156    pub device_name: String,
157}
158
159impl PeerPresence {
160    pub(crate) fn from_raw(raw: sys::QarPeerPresence) -> Self {
161        match raw {
162            sys::QarPeerPresence::QAR_PEER_PRESENCE_ONLINE => Self::Online,
163            sys::QarPeerPresence::QAR_PEER_PRESENCE_OFFLINE => Self::Offline,
164            sys::QarPeerPresence::QAR_PEER_PRESENCE_LEAVING => Self::Leaving,
165            sys::QarPeerPresence::QAR_PEER_PRESENCE_RETIRED => Self::Retired,
166            _ => Self::Unknown,
167        }
168    }
169}
170
171impl PeerRole {
172    pub(crate) fn from_raw(raw: sys::QarPeerRole) -> Self {
173        match raw {
174            sys::QarPeerRole::QAR_PEER_ROLE_INTERNAL => Self::Internal,
175            sys::QarPeerRole::QAR_PEER_ROLE_SOURCE => Self::Source,
176            sys::QarPeerRole::QAR_PEER_ROLE_TARGET => Self::Target,
177            sys::QarPeerRole::QAR_PEER_ROLE_RUNTIME => Self::Runtime,
178            sys::QarPeerRole::QAR_PEER_ROLE_CONTROL => Self::Control,
179            other => Self::Other(i64::from(other.0)),
180        }
181    }
182}
183
184impl DeviceCategory {
185    pub(crate) fn from_raw(raw: sys::QarDeviceCategory) -> Self {
186        match raw {
187            sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_DESKTOP_PC => Self::DesktopPc,
188            sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_SERVER => Self::Server,
189            sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_HEADSET => Self::Headset,
190            sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_VISUALIZER => Self::Visualizer,
191            sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_CAMERA => Self::Camera,
192            sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_OBSERVER => Self::Observer,
193            _ => Self::Unknown,
194        }
195    }
196}
197
198/// Reads a peer spec's identity.
199///
200/// # Safety
201///
202/// `handle` is a live peer spec handle (owned, or borrowed for a callback).
203pub(crate) unsafe fn read_peer_identity(
204    api: &sys::QarApi,
205    handle: *mut sys::QarPeerSpec,
206) -> Result<PeerIdentity> {
207    use crate::error::check;
208
209    let mut presence = sys::QarPeerPresence::QAR_PEER_PRESENCE_UNKNOWN;
210    // SAFETY: forwarded to the caller; valid out-pointer.
211    let result = unsafe { (api.qar_impl_peer_spec_get_presence)(handle, &raw mut presence) };
212    check(api, "qar_peer_spec_get_presence", result)?;
213    let mut role = sys::QarPeerRole::QAR_PEER_ROLE_INTERNAL;
214    // SAFETY: as above.
215    let result = unsafe { (api.qar_impl_peer_spec_get_role)(handle, &raw mut role) };
216    check(api, "qar_peer_spec_get_role", result)?;
217    let mut category = sys::QarDeviceCategory::QAR_DEVICE_CATEGORY_UNKNOWN;
218    // SAFETY: as above.
219    let result = unsafe { (api.qar_impl_peer_spec_get_category)(handle, &raw mut category) };
220    check(api, "qar_peer_spec_get_category", result)?;
221    let read_text = |getter: unsafe extern "C" fn(
222        *mut sys::QarPeerSpec,
223        *mut std::ffi::c_char,
224        usize,
225    ) -> sys::QarResult,
226                     function: &'static str| {
227        strings::read_string(|buffer, size| {
228            // SAFETY: handle is live; the buffer is writable for size bytes.
229            let result = unsafe { getter(handle, buffer, size) };
230            check(api, function, result)
231        })
232    };
233    Ok(PeerIdentity {
234        presence: PeerPresence::from_raw(presence),
235        role: PeerRole::from_raw(role),
236        category: DeviceCategory::from_raw(category),
237        device_id: read_text(
238            api.qar_impl_peer_spec_get_device_id,
239            "qar_peer_spec_get_device_id",
240        )?,
241        device_family: read_text(
242            api.qar_impl_peer_spec_get_device_family,
243            "qar_peer_spec_get_device_family",
244        )?,
245        device_name: read_text(
246            api.qar_impl_peer_spec_get_device_name,
247            "qar_peer_spec_get_device_name",
248        )?,
249    })
250}