qaros/library.rs
1use std::mem::ManuallyDrop;
2use std::path::{Path, PathBuf};
3use std::ptr::NonNull;
4use std::rc::Rc;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::time::Duration;
7
8use qaros_sys::{QarApi, defaults};
9
10use crate::cancel::CancelToken;
11use crate::error::{Error, Result, check};
12use crate::invite::OnboardingInvite;
13use crate::runtime::{Runtime, RuntimeConfig};
14use crate::strings;
15use crate::types::LogSeverity;
16
17static LIBRARY_INITIALIZED: AtomicBool = AtomicBool::new(false);
18
19/// Options for `qar_library_init`; the default matches
20/// `qar_library_init_default()`.
21#[derive(Clone, Debug)]
22pub struct LibraryConfig {
23 pub console_logging: bool,
24 pub log_directory: Option<PathBuf>,
25 pub log_severity: LogSeverity,
26}
27
28impl Default for LibraryConfig {
29 fn default() -> Self {
30 Self {
31 console_logging: true,
32 log_directory: None,
33 log_severity: LogSeverity::Info,
34 }
35 }
36}
37
38/// What the loaded `qar-streaming-c` reports about itself
39/// (`qar_runtime_info`).
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct RuntimeInfo {
42 /// Product version, e.g. `0.9.0` or `0.9.0-rc.2`.
43 pub version: String,
44 /// `release` or `demo`.
45 pub flavor: String,
46 /// C API generation, `v0`.
47 pub c_api: String,
48}
49
50/// The device kind a target-app connection string names
51/// ([`Library::target_app_connection_string`]).
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub enum TargetDevice {
54 /// `"hololens:<host>"`.
55 HoloLens,
56 /// `"quest:<host>"`. An Android headset is never invited: use it with
57 /// [`crate::Session::find_render_target`]; [`crate::Session::invite_target_app`] fails with
58 /// [`crate::StatusCode::HUB_TARGET_APP_DEVICE_NOT_INVITABLE`].
59 Quest,
60 /// `"android:<host>"`. Like [`TargetDevice::Quest`], for finding a joined headset only.
61 Android,
62}
63
64/// The loaded and initialized C API library.
65///
66/// Process-wide: at most one may be alive at a time. Cloning shares the same
67/// library. Runtimes, sessions and every other handle keep it alive, so it is
68/// destroyed (`qar_library_destroy`) only after them, whatever order the Rust
69/// values are dropped in.
70///
71/// The DLL is never unloaded: it stays mapped for the rest of the process.
72/// Freeing it after `qar_library_destroy` runs its detach
73/// code and unmaps code that its threads may still reach, which has crashed
74/// processes at exit. After a drop whose `qar_library_destroy`
75/// succeeded, a second [`Library::load`] re-initializes the mapped library.
76/// After one whose `qar_library_destroy` failed, the process slot stays
77/// reserved and every later load returns [`Error::LibraryAlreadyLoaded`].
78///
79/// Not `Send`: the SDK is designed for single-threaded use per runtime.
80#[derive(Clone, Debug)]
81pub struct Library {
82 pub(crate) inner: Rc<LibraryInner>,
83}
84
85#[derive(Debug)]
86pub(crate) struct LibraryInner {
87 /// Never dropped: the table owns the opened DLL, which stays mapped for
88 /// the rest of the process (see [`Library`]).
89 pub(crate) api: ManuallyDrop<QarApi>,
90}
91
92impl Library {
93 /// Finds `qar-streaming-c` with the default lookup every QAROS binding follows and runs
94 /// `qar_library_init`. This is the normal way to load the runtime: a distributed application
95 /// runs against the QAROS installed on the PC and ships no copy of the runtime.
96 ///
97 /// The first match wins: a runtime already loaded in the process; one beside the executable
98 /// (or library) this binding is compiled into; on Windows, when `QAR_INSTANCE` names a QAROS
99 /// instance, that instance's runtime folder (`default` is the installed QAROS, any other name
100 /// the `RuntimeFolder` its hub records under `HKCU\SOFTWARE\Quaternar\QAROS\Instances`); the
101 /// installed QAROS (`<InstallFolder>\bin` from `HKLM\SOFTWARE\Quaternar\QAROS`); each
102 /// folder on `PATH`. A set `QAR_INSTANCE` naming an invalid or unknown instance, and an
103 /// instance or installed QAROS whose runtime is missing or fails to load, is an error, never
104 /// a reason to load another runtime. Nothing found is
105 /// [`Error::Load`] with [`qaros_sys::LoadError::NotFound`], naming every place looked at.
106 /// See [`QarApi::load_default`] for the details; [`Library::library_path`] tells which file
107 /// was loaded.
108 ///
109 /// # Safety
110 ///
111 /// The runtime found must be a `qar-streaming-c` build matching these bindings; see
112 /// [`QarApi::load`].
113 pub unsafe fn load_default(config: &LibraryConfig) -> Result<Self> {
114 // SAFETY: forwarded to the caller.
115 Self::load_with(config, || unsafe { QarApi::load_default() })
116 }
117
118 /// Loads `qar-streaming-c` from the library file at `path` and runs `qar_library_init`.
119 /// Only that file is tried. Explicit paths are for development builds of QAROS;
120 /// a distributed application uses [`Library::load_default`], and `QAR_INSTANCE` points a run
121 /// at another QAROS instance's runtime without code.
122 ///
123 /// # Safety
124 ///
125 /// `path` must name a `qar-streaming-c` build matching these bindings; see
126 /// [`QarApi::load`].
127 pub unsafe fn load(path: impl AsRef<Path>, config: &LibraryConfig) -> Result<Self> {
128 // SAFETY: forwarded to the caller.
129 Self::load_with(config, || unsafe { QarApi::load(path.as_ref()) })
130 }
131
132 fn load_with(
133 config: &LibraryConfig,
134 load_table: impl FnOnce() -> std::result::Result<QarApi, qaros_sys::LoadError>,
135 ) -> Result<Self> {
136 Self::reserve_process_slot()?;
137 match load_table() {
138 Ok(api) => Self::initialize(api, config),
139 Err(load_error) => {
140 LIBRARY_INITIALIZED.store(false, Ordering::Release);
141 Err(Error::Load(load_error))
142 }
143 }
144 }
145
146 /// Uses the import-library symbols (feature `link`) and runs
147 /// `qar_library_init`.
148 #[cfg(feature = "link")]
149 pub fn linked(config: &LibraryConfig) -> Result<Self> {
150 Self::reserve_process_slot()?;
151 Self::initialize(QarApi::linked(), config)
152 }
153
154 fn reserve_process_slot() -> Result<()> {
155 if LIBRARY_INITIALIZED.swap(true, Ordering::AcqRel) {
156 Err(Error::LibraryAlreadyLoaded)
157 } else {
158 Ok(())
159 }
160 }
161
162 fn initialize(api: QarApi, config: &LibraryConfig) -> Result<Self> {
163 let initialized = Self::call_library_init(&api, config);
164 if let Err(error) = initialized {
165 LIBRARY_INITIALIZED.store(false, Ordering::Release);
166 return Err(error);
167 }
168 Ok(Self {
169 inner: Rc::new(LibraryInner {
170 api: ManuallyDrop::new(api),
171 }),
172 })
173 }
174
175 fn call_library_init(api: &QarApi, config: &LibraryConfig) -> Result<()> {
176 let log_directory = config
177 .log_directory
178 .as_deref()
179 .map(|directory| strings::path_to_c_string(directory, "log directory"))
180 .transpose()?;
181 let mut init = defaults::qar_library_init_default();
182 init.enable_console_logging = config.console_logging;
183 init.log_folder_path = strings::pointer_or_null(log_directory.as_ref());
184 init.log_severity = config.log_severity.to_raw();
185 // SAFETY: init is stamped by its default and its strings outlive the call.
186 let result = unsafe { (api.qar_impl_library_init)(&raw const init) };
187 check(api, "qar_library_init", result)
188 }
189
190 /// `qar_runtime_create`.
191 pub fn create_runtime(&self, config: &RuntimeConfig) -> Result<Runtime> {
192 Runtime::create(&self.inner, config)
193 }
194
195 /// Creates a cancellation token, optionally cancelling itself after
196 /// `timeout`.
197 pub fn create_cancel_token(&self, timeout: Option<Duration>) -> Result<CancelToken> {
198 CancelToken::create(&self.inner, timeout)
199 }
200
201 /// The connection string for a target app on `host`, a hostname or IP address
202 /// (`qar_target_app_connection_string_hololens`, `_quest`, `_android`), for
203 /// [`crate::Session::invite_target_app`] (HoloLens only) or
204 /// [`crate::Session::find_render_target`]. An empty host fails in the library.
205 pub fn target_app_connection_string(&self, device: TargetDevice, host: &str) -> Result<String> {
206 let api = &self.inner.api;
207 let (builder, function) = match device {
208 TargetDevice::HoloLens => (
209 api.qar_impl_target_app_connection_string_hololens,
210 "qar_target_app_connection_string_hololens",
211 ),
212 TargetDevice::Quest => (
213 api.qar_impl_target_app_connection_string_quest,
214 "qar_target_app_connection_string_quest",
215 ),
216 TargetDevice::Android => (
217 api.qar_impl_target_app_connection_string_android,
218 "qar_target_app_connection_string_android",
219 ),
220 };
221 let host = crate::strings::to_c_string(host, "host")?;
222 crate::strings::read_string(|buffer, size| {
223 // SAFETY: host is a C string; the buffer is writable for size bytes.
224 let result = unsafe { builder(host.as_ptr(), buffer, size) };
225 check(api, function, result)
226 })
227 }
228
229 /// Parses an invite serialized by [`OnboardingInvite::serialize`].
230 pub fn deserialize_invite(&self, wire_bytes: &[u8]) -> Result<OnboardingInvite> {
231 OnboardingInvite::deserialize(&self.inner, wire_bytes)
232 }
233
234 /// Version, flavor and C API generation of the loaded runtime
235 /// (`qar_runtime_info`), for diagnostics.
236 pub fn runtime_info(&self) -> Result<RuntimeInfo> {
237 let api = &self.inner.api;
238 let mut raw_info = qaros_sys::QarRuntimeInfo {
239 version: std::ptr::null(),
240 flavor: std::ptr::null(),
241 c_api: std::ptr::null(),
242 };
243 // SAFETY: raw_info is a valid out-pointer for the whole call.
244 let result = unsafe { (api.qar_impl_runtime_info)(&raw mut raw_info) };
245 check(api, "qar_runtime_info", result)?;
246 // SAFETY: the runtime fills null or static NUL-terminated strings
247 // that stay valid while the library is loaded, which `self` keeps.
248 unsafe {
249 Ok(RuntimeInfo {
250 version: strings::from_returned_pointer(
251 raw_info.version,
252 "qar_runtime_info",
253 "a version",
254 )?,
255 flavor: strings::from_returned_pointer(
256 raw_info.flavor,
257 "qar_runtime_info",
258 "a flavor",
259 )?,
260 c_api: strings::from_returned_pointer(
261 raw_info.c_api,
262 "qar_runtime_info",
263 "a C API generation",
264 )?,
265 })
266 }
267 }
268
269 /// The library's UUID text form, for persisting ids.
270 pub fn uuid_to_string(&self, bytes: &[u8; 16]) -> Result<String> {
271 let api = &self.inner.api;
272 strings::read_string(|buffer, size| {
273 // SAFETY: bytes holds 16 bytes; the buffer is writable for size bytes.
274 let result = unsafe { (api.qar_impl_uuid_to_string)(bytes.as_ptr(), buffer, size) };
275 check(api, "qar_uuid_to_string", result)
276 })
277 }
278
279 /// Parses the library's UUID text form.
280 pub fn uuid_from_string(&self, text: &str) -> Result<[u8; 16]> {
281 let api = &self.inner.api;
282 let text = strings::to_c_string(text.trim(), "UUID text")?;
283 let mut bytes = [0_u8; 16];
284 // SAFETY: text is NUL-terminated; bytes is writable for 16 bytes.
285 let result = unsafe { (api.qar_impl_uuid_from_string)(text.as_ptr(), bytes.as_mut_ptr()) };
286 check(api, "qar_uuid_from_string", result)?;
287 Ok(bytes)
288 }
289
290 /// The file `qar-streaming-c` was loaded from, for diagnostics. `None` for the
291 /// import-linked library or when the operating system does not name the module.
292 pub fn library_path(&self) -> Option<&Path> {
293 self.inner.api.library_path()
294 }
295
296 /// The step of the default lookup that found the runtime, for diagnostics; `None` after
297 /// [`Library::load`] or for the import-linked library.
298 pub fn lookup_step(&self) -> Option<qaros_sys::LookupStep> {
299 self.inner.api.lookup_step()
300 }
301
302 /// The raw function table, for the parts this crate leaves to `qaros-sys`: hands, gestures,
303 /// world anchors, video senders, target apps, the peer presence, role, category and device
304 /// identity, and the other areas the README's coverage table lists as raw only. Call them
305 /// with the `as_raw()` handle of a safe value ([`crate::Session::as_raw`] and the others).
306 /// Valid while this `Library` (or any handle derived from it) is alive.
307 pub fn raw_api(&self) -> &QarApi {
308 &self.inner.api
309 }
310}
311
312impl Drop for LibraryInner {
313 fn drop(&mut self) {
314 // SAFETY: every runtime, session and handle holds an Rc to this
315 // value, so none is alive any more.
316 let result = unsafe { (self.api.qar_impl_library_destroy)() };
317 // The table in `api` is left undropped, so the DLL is never unloaded:
318 // freeing it after `qar_library_destroy` crashes the process at exit.
319 match check(&self.api, "qar_library_destroy", result) {
320 Ok(()) => LIBRARY_INITIALIZED.store(false, Ordering::Release),
321 Err(error) => log::error!(
322 "{error}; the library's global state may still be initialized, so no new Library can be loaded in this process"
323 ),
324 }
325 }
326}
327
328/// Converts an owned C handle out-parameter to `NonNull`, treating a null
329/// handle after a success result as an API error.
330pub(crate) fn require_handle<T>(handle: *mut T, function: &'static str) -> Result<NonNull<T>> {
331 NonNull::new(handle).ok_or_else(|| Error::Api {
332 function,
333 code: crate::error::StatusCode::UNCLASSIFIED,
334 message: "returned success without a handle".to_string(),
335 causes: Vec::new(),
336 })
337}