grafton_ndi/runtime.rs
1//! Select an NDI implementation and manage its initialization lifetime.
2//!
3//! Using NDI takes two steps, and each is explicit:
4//!
5//! 1. **Select.** [`Runtime::select`] loads the NDI runtime library and pins it
6//! for the rest of the process. Nothing is started. The [`Runtime`] it
7//! returns describes the library: where it was loaded from, its edition and
8//! version ([`Runtime::info`]), what it can do ([`Runtime::capabilities`])
9//! and whether it can run on this CPU ([`Runtime::is_supported_cpu`]).
10//! 2. **Initialize.** [`Runtime::initialize`] starts NDI and returns an [`Ndi`]
11//! handle, from which every finder, sender and receiver is created. NDI
12//! stays started while any handle exists, and stops when the last one is
13//! dropped unless [`Ndi::process_lifetime`] was chosen.
14//!
15//! [`Ndi::new`] performs both steps with the default options, and
16//! [`Ndi::with_options`] with the options it is given. Nothing else in the
17//! crate selects or starts a runtime: every operation that needs NDI takes a
18//! handle, and a question such as [`Ndi::is_running`] only reports the current
19//! state.
20//!
21//! ```no_run
22//! use grafton_ndi::{Runtime, RuntimeOptions};
23//!
24//! # fn main() -> Result<(), grafton_ndi::Error> {
25//! let runtime = Runtime::select(&RuntimeOptions::default())?;
26//! println!("NDI {}", runtime.info().raw_version());
27//! if !runtime.is_supported_cpu() {
28//! eprintln!("this CPU cannot run the selected NDI runtime");
29//! }
30//! let ndi = runtime.initialize()?;
31//! # drop(ndi);
32//! # Ok(())
33//! # }
34//! ```
35//!
36//! Default builds on dynamically loaded targets need no NDI SDK. A selected shared library stays
37//! loaded for the life of the process, including after the last [`Ndi`] handle
38//! is dropped. Statically linked targets use the SDK archive linked at build
39//! time, and selecting it loads nothing.
40//!
41//! # Where the runtime is loaded from
42//!
43//! **Deployment trust boundary:** [`Ndi::new`] uses a packaging-oriented
44//! search. Every searched directory must be controlled by a trusted owner.
45//! Loading a native library executes its constructors before its symbols or
46//! edition can be checked, including libraries later rejected during fallback.
47//! For services and elevated processes, make the very first selection use an
48//! absolute path in an application-owner-controlled directory:
49//!
50//! ```no_run
51//! # fn main() -> grafton_ndi::Result<()> {
52//! use grafton_ndi::{Runtime, RuntimeOptions};
53//! let runtime = Runtime::select(&RuntimeOptions::new()
54//! .library_path("/opt/my-service/ndi/libndi.so.6"))?;
55//! println!("Selected runtime: {:?}", runtime.info().library_path());
56//! let ndi = runtime.initialize()?;
57//! # Ok(())
58//! # }
59//! ```
60//!
61//! An explicit path must be absolute and name an existing file. A relative
62//! path returns [`Error::InvalidInput`]. An absent file returns an absent-path
63//! refusal before calling the platform loader. The crate makes no
64//! executable, environment or platform search for an explicit path. A later
65//! explicit selection cannot undo code already run by an earlier load. Native
66//! dependencies still use platform loader rules and must also come from
67//! trusted locations. With the
68//! File API, explicitly select `FileApiOptions::library_path`
69//! too, or establish that its companion and other search directories are
70//! trusted; inspect the selection through `FileApi::library_path`.
71//!
72//! Unless [`RuntimeOptions::library_path`] names an exact file, the first usable
73//! library in this order is selected:
74//!
75//! 1. the directory containing the running executable;
76//! 2. the absolute directory named by `NDI_RUNTIME_DIR_V6`; relative values
77//! are recorded as refused locations and never searched;
78//! 3. platform-specific locations: on Windows, absolute `PATH` directories
79//! followed by a System32-only name lookup; on macOS, `@rpath/<name>` and
80//! absolute `DYLD_LIBRARY_PATH` directories; on Linux and Android, the
81//! native loader search (`rpath`, `LD_LIBRARY_PATH` and system locations).
82//! Explicitly configured relative or empty `LD_LIBRARY_PATH` entries can
83//! still name the working directory on Linux and Android.
84//!
85//! Windows and macOS never add the working directory to this search. Relative
86//! or empty `PATH`/`DYLD_LIBRARY_PATH` entries are recorded as refused locations.
87//! On macOS, a relative or empty entry in either `DYLD_LIBRARY_PATH` or
88//! `DYLD_FALLBACK_LIBRARY_PATH` refuses the entire default search before opening
89//! a library. The check reads the process environment at search time; dyld uses
90//! its launch-time values, so changing `DYLD_*` after launch is unsupported.
91//! On unrestricted macOS processes dyld can use `DYLD_LIBRARY_PATH` to
92//! substitute an existing explicit file. Such substitutions are refused with
93//! [`crate::LoadRefusal::ResolvedToAnotherFile`] after loading the candidate,
94//! when its initializers have already run. Configure trusted absolute
95//! `DYLD_*` entries before launching.
96//!
97//! Each location is tried for the file names of both SDK editions, for
98//! example `libndi.so.6` and `libndi_advanced.so.6` on Linux, unless
99//! [`RuntimeOptions::edition`] asks for one. A build with the `advanced`
100//! feature, or with `file-io` on a platform where the File library needs the
101//! Advanced runtime, tries the Advanced name first at each location, and other
102//! builds the Standard name; where a library is installed matters more than
103//! which edition it is. Nothing installed on the build machine changes the
104//! search.
105//!
106//! A file that is not there is skipped. A library that cannot be loaded, or
107//! that loads but is rejected because it lacks a required entry point or is
108//! not the requested edition, is recorded and the search moves on. When
109//! nothing is usable,
110//! [`Error::RuntimeLoadFailed`] carries [`crate::LoadFailure`] with every
111//! location, [`crate::LoadOrigin`] and typed [`crate::LoadRefusal`]. Its
112//! `loaded_any()` distinguishes code that loaded and was refused from locations
113//! that could not be opened; `Display` retains the diagnostic text, including
114//! the operating system's own. [`Error::RuntimeConflict`] carries a
115//! [`crate::SelectionFailure`] with a typed kind and selected, requested or
116//! foreign module paths, alongside its diagnostic text.
117//!
118//! On dynamically loaded, non-Apple ELF targets, a runtime already linked or
119//! preloaded into the process's global symbol scope must also be the selected
120//! runtime. Other candidates are refused before opening them, because that
121//! global runtime would capture their native calls. Search failures record
122//! [`crate::LoadRefusal::ForeignRuntimeInScope`]; an explicit different file
123//! returns [`crate::SelectionConflict::ForeignRuntimeInScope`]. Select the
124//! module named in the diagnostic, or stop linking or preloading it.
125//!
126//! One limit applies to a library that loads but is rejected: it stays loaded,
127//! because a native library can never be unloaded safely. If the platform
128//! loader's own search then matches the library name to that module, it
129//! returns the module again instead of looking further, so no other library
130//! of that name can be reached by name in this process. The error names the
131//! rejected file. Remove or fix that file, or name the wanted library with
132//! [`RuntimeOptions::library_path`].
133
134use std::{
135 fmt,
136 num::NonZeroUsize,
137 path::PathBuf,
138 sync::{Condvar, Mutex, MutexGuard, OnceLock},
139};
140
141use crate::{
142 capabilities::{Capabilities, RuntimeFeature, RuntimeInfo, SdkEdition},
143 sys, Error, Result,
144};
145
146/// Which NDI runtime to select; see [`Runtime::select`].
147///
148/// The default options search for the runtime library of either edition in
149/// the [documented order](crate::runtime#where-the-runtime-is-loaded-from)
150/// and accept whichever is found first.
151/// On dynamically loaded, non-Apple ELF targets, any runtime already in the
152/// process's global symbol scope must be the selected module; see
153/// [`crate::LoadRefusal::ForeignRuntimeInScope`].
154///
155/// # Examples
156///
157/// ```no_run
158/// use grafton_ndi::{Runtime, RuntimeOptions, SdkEdition};
159///
160/// # fn main() -> Result<(), grafton_ndi::Error> {
161/// let options = RuntimeOptions::default()
162/// .library_path("/opt/ndi/lib/libndi.so.6")
163/// .edition(SdkEdition::Standard);
164/// let runtime = Runtime::select(&options)?;
165/// # let _ = runtime;
166/// # Ok(())
167/// # }
168/// ```
169#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
170pub struct RuntimeOptions {
171 pub(crate) library_path: Option<PathBuf>,
172 pub(crate) edition: Option<SdkEdition>,
173}
174
175impl RuntimeOptions {
176 /// Restore the normal library search instead of an explicit path.
177 #[must_use]
178 pub fn clear_library_path(mut self) -> Self {
179 self.library_path = None;
180 self
181 }
182
183 /// Accept either SDK edition instead of requiring one.
184 #[must_use]
185 pub fn clear_edition(mut self) -> Self {
186 self.edition = None;
187 self
188 }
189
190 /// Requested exact library path, or `None` for the normal search.
191 #[must_use]
192 pub fn configured_library_path(&self) -> Option<&std::path::Path> {
193 self.library_path.as_deref()
194 }
195
196 /// Requested edition, or `None` to accept either edition.
197 #[must_use]
198 pub fn configured_edition(&self) -> Option<SdkEdition> {
199 self.edition
200 }
201
202 /// The default options: the runtime library of either edition, from the
203 /// [documented search](crate::runtime#where-the-runtime-is-loaded-from).
204 pub fn new() -> Self {
205 Self::default()
206 }
207
208 /// Load exactly this absolute shared-library path.
209 ///
210 /// A path that does not name an existing file is refused before native
211 /// loading. A failure to load the file is reported without a fallback. A statically linked target has no library to
212 /// load and rejects an absolute path with [`Error::RuntimeConflict`].
213 /// A relative path returns [`Error::InvalidInput`] on every target,
214 /// before an implementation is selected.
215 /// On dynamically loaded, non-Apple ELF targets, a different runtime
216 /// already linked or preloaded into the global symbol scope causes
217 /// [`crate::SelectionConflict::ForeignRuntimeInScope`] before this file
218 /// is opened. Aliases identifying the same loaded module are accepted.
219 #[must_use]
220 pub fn library_path(mut self, path: impl Into<PathBuf>) -> Self {
221 self.library_path = Some(path.into());
222 self
223 }
224
225 /// Search only for the runtime library of this SDK edition.
226 ///
227 /// On dynamically loaded targets, requesting [`SdkEdition::Advanced`]
228 /// requires the selected library to export the Advanced SDK entry points. Requesting
229 /// [`SdkEdition::Standard`] never rejects an implementation for exporting
230 /// more than the Standard SDK does, so an Advanced runtime found under the
231 /// Standard file name, or named by [`library_path`](Self::library_path),
232 /// meets it. Without a request, the libraries of both editions are sought.
233 ///
234 /// A statically linked target has one implementation, the archive linked
235 /// at build time. An Advanced request is met only when the build linked the
236 /// Advanced archive; a Standard request accepts either archive. See
237 /// [`SdkEdition`] for how the build chooses the archive.
238 #[must_use]
239 pub fn edition(mut self, edition: SdkEdition) -> Self {
240 self.edition = Some(edition);
241 self
242 }
243}
244
245/// The NDI implementation selected for this process.
246///
247/// A `Runtime` is a small `Copy` handle. Obtaining one loads and pins the NDI
248/// runtime library but does not start NDI, so it can be inspected first:
249/// [`info`](Self::info) for its path, edition and version,
250/// [`capabilities`](Self::capabilities) for what it supports and
251/// [`is_supported_cpu`](Self::is_supported_cpu) for whether it can run here.
252/// [`initialize`](Self::initialize) then starts NDI.
253///
254/// A process has one selected implementation. Once [`select`](Self::select)
255/// succeeds, every handle refers to it, and what the accessors return stays
256/// valid until the process exits.
257///
258/// # Examples
259///
260/// ```no_run
261/// use grafton_ndi::{Finder, FinderOptions, Runtime, RuntimeFeature, RuntimeOptions};
262///
263/// # fn main() -> Result<(), grafton_ndi::Error> {
264/// let runtime = Runtime::select(&RuntimeOptions::default())?;
265///
266/// let info = runtime.info();
267/// println!("{:?} {} from {:?}", info.edition(), info.raw_version(), info.library_path());
268/// if !runtime.capabilities().supports(RuntimeFeature::Planar444Video) {
269/// println!("this runtime predates the planar 4:4:4 formats");
270/// }
271///
272/// let ndi = runtime.initialize()?;
273/// let finder = Finder::new(&ndi, &FinderOptions::default())?;
274/// # drop(finder);
275/// # Ok(())
276/// # }
277/// ```
278#[derive(Clone, Copy)]
279pub struct Runtime {
280 selected: &'static sys::Runtime,
281}
282
283impl Runtime {
284 /// Select the NDI implementation `options` describe, without starting NDI.
285 ///
286 /// The first successful call loads the runtime library, checks that it
287 /// exports every entry point this crate requires, and pins it for the rest
288 /// of the process. Later calls return the same implementation, provided
289 /// their options are met by it. A statically linked target selects the
290 /// archive linked at build time.
291 ///
292 /// Loading a native library runs its initialization code: select only
293 /// trusted SDK files.
294 ///
295 /// # Errors
296 ///
297 /// * [`Error::RuntimeLoadFailed`] when no usable library is found. Nothing
298 /// is selected and the call can be repeated, with other options if
299 /// wanted. The [`crate::LoadFailure`] records each attempted location,
300 /// its origin, typed refusal and whether native code loaded.
301 /// * [`Error::RuntimeConflict`] when an implementation is already selected
302 /// and does not meet `options`: they name a different library file, or
303 /// ask for the Advanced SDK when the selected implementation is not one.
304 /// Also returned for an explicit path on a linked target, or when native
305 /// loading re-enters selection on the same thread before selection finishes.
306 /// On dynamically loaded, non-Apple ELF targets, an explicit file is also
307 /// refused before opening when another runtime is in the global symbol scope.
308 /// [`crate::SelectionConflict`] identifies the cause.
309 /// * [`Error::InvalidInput`] when `options` name a relative
310 /// library path.
311 ///
312 /// # Examples
313 ///
314 /// ```no_run
315 /// use grafton_ndi::{Error, Runtime, RuntimeOptions};
316 ///
317 /// match Runtime::select(&RuntimeOptions::default()) {
318 /// Ok(runtime) => println!("selected {:?}", runtime.info().library_path()),
319 /// Err(Error::RuntimeLoadFailed(failure)) if !failure.loaded_any() => {
320 /// eprintln!("no runtime could be opened: {failure}");
321 /// }
322 /// Err(error) => eprintln!("{error}"),
323 /// }
324 /// ```
325 pub fn select(options: &RuntimeOptions) -> Result<Self> {
326 sys::select(options).map(|selected| Self { selected })
327 }
328
329 /// The selected implementation's identity: the file it was loaded from,
330 /// its edition, how it is linked and the version it reports.
331 ///
332 /// # Examples
333 ///
334 /// ```no_run
335 /// # use grafton_ndi::{Runtime, RuntimeOptions};
336 /// # fn main() -> Result<(), grafton_ndi::Error> {
337 /// let runtime = Runtime::select(&RuntimeOptions::default())?;
338 /// println!("NDI version: {}", runtime.info().raw_version());
339 /// # Ok(())
340 /// # }
341 /// ```
342 pub fn info(&self) -> &'static RuntimeInfo {
343 &self.selected.info
344 }
345
346 /// What the selected implementation supports, by optional capability.
347 ///
348 /// This is evidence about the library and this build, not about hardware
349 /// or licenses.
350 ///
351 /// # Examples
352 ///
353 /// ```no_run
354 /// # use grafton_ndi::{Runtime, RuntimeFeature, RuntimeOptions};
355 /// # fn main() -> Result<(), grafton_ndi::Error> {
356 /// let runtime = Runtime::select(&RuntimeOptions::default())?;
357 /// let status = runtime.capabilities().status(RuntimeFeature::ReceiveDelay);
358 /// println!("receive delay: {status:?}");
359 /// # Ok(())
360 /// # }
361 /// ```
362 pub fn capabilities(&self) -> &'static Capabilities {
363 self.selected.gates.capabilities()
364 }
365
366 /// Check that the selected implementation provides `feature`.
367 ///
368 /// # Errors
369 ///
370 /// Returns [`Error::UnsupportedCapability`] naming the capability and why
371 /// the selected implementation or this build cannot provide it.
372 ///
373 /// # Examples
374 ///
375 /// ```no_run
376 /// # use grafton_ndi::{Runtime, RuntimeFeature, RuntimeOptions};
377 /// # fn main() -> Result<(), grafton_ndi::Error> {
378 /// let runtime = Runtime::select(&RuntimeOptions::default())?;
379 /// runtime.require_feature(RuntimeFeature::Routing)?;
380 /// # Ok(())
381 /// # }
382 /// ```
383 pub fn require_feature(&self, feature: RuntimeFeature) -> Result<()> {
384 self.selected.require(feature)
385 }
386
387 /// Whether the selected implementation can run on this CPU.
388 ///
389 /// The implementation itself answers, because the instructions it needs
390 /// depend on the SDK version and the platform. A runtime that does not
391 /// start for this reason makes [`Runtime::initialize`] report
392 /// [`Error::UnsupportedCpu`].
393 ///
394 /// # Examples
395 ///
396 /// ```no_run
397 /// # use grafton_ndi::{Runtime, RuntimeOptions};
398 /// # fn main() -> Result<(), grafton_ndi::Error> {
399 /// let runtime = Runtime::select(&RuntimeOptions::default())?;
400 /// if !runtime.is_supported_cpu() {
401 /// eprintln!("this CPU lacks instructions the NDI runtime needs");
402 /// }
403 /// # Ok(())
404 /// # }
405 /// ```
406 #[doc(alias = "NDIlib_is_supported_CPU")]
407 pub fn is_supported_cpu(&self) -> bool {
408 is_supported_cpu(&self.selected.gates.api().core)
409 }
410
411 /// Start NDI and return a handle to it.
412 ///
413 /// NDI is started by the first handle and stays started while any handle
414 /// exists; each further call, like [`Ndi::clone`], only adds a handle.
415 /// Dropping the last one stops NDI, after which this can be called again.
416 /// The call is thread-safe.
417 ///
418 /// # Errors
419 ///
420 /// * [`Error::UnsupportedCpu`] when the implementation does not start and
421 /// reports that this CPU cannot run it.
422 /// * [`Error::InitializationFailed`] when it does not start for any other
423 /// reason, or the count of handles is exhausted.
424 ///
425 /// A failed start can be retried.
426 ///
427 /// # Examples
428 ///
429 /// ```no_run
430 /// # use grafton_ndi::{Error, Runtime, RuntimeOptions};
431 /// # fn main() -> Result<(), grafton_ndi::Error> {
432 /// let runtime = Runtime::select(&RuntimeOptions::default())?;
433 /// match runtime.initialize() {
434 /// Ok(ndi) => println!("NDI is running: {ndi:?}"),
435 /// Err(Error::UnsupportedCpu) => eprintln!("NDI cannot run on this CPU"),
436 /// Err(error) => return Err(error),
437 /// }
438 /// # Ok(())
439 /// # }
440 /// ```
441 #[doc(alias = "NDIlib_initialize")]
442 pub fn initialize(&self) -> Result<Ndi> {
443 self.selected.lifecycle.acquire()?;
444 Ok(Ndi { runtime: *self })
445 }
446}
447
448impl fmt::Debug for Runtime {
449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450 f.debug_struct("Runtime")
451 .field("info", self.info())
452 .finish_non_exhaustive()
453 }
454}
455
456/// An explicit promise that the selected NDI runtime stays initialized until exit.
457///
458/// Created by [`Ndi::process_lifetime`]. The first creation retains one runtime
459/// reference permanently. Dropping this token does not reverse that choice.
460/// This is intended for native callbacks whose completion cannot be bounded by a
461/// normal sender/receiver lifetime. It does not grant an SDK license entitlement.
462#[derive(Clone, Copy)]
463pub struct ProcessLifetimeRuntime {
464 ndi: &'static Ndi,
465}
466
467impl fmt::Debug for ProcessLifetimeRuntime {
468 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469 f.debug_struct("ProcessLifetimeRuntime")
470 .field("info", self.ndi.info())
471 .finish_non_exhaustive()
472 }
473}
474
475impl ProcessLifetimeRuntime {
476 /// Borrow the permanently retained runtime handle.
477 pub fn ndi(&self) -> &Ndi {
478 self.ndi
479 }
480}
481
482static PROCESS_LIFETIME: OnceLock<Ndi> = OnceLock::new();
483
484/// Lifecycle state; only an active runtime can own live handle counts.
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486enum Phase {
487 Stopped,
488 Starting,
489 Running(NonZeroUsize),
490 Stopping,
491}
492
493/// The native calls the lifecycle needs. Tests substitute their own, so the
494/// production state machine runs without an SDK.
495pub(crate) trait RuntimeBackend {
496 /// Start NDI; `false` when it does not start.
497 fn initialize(&self) -> bool;
498 /// Whether the implementation can run on this CPU.
499 fn is_supported_cpu(&self) -> bool;
500 /// Stop NDI.
501 fn destroy(&self);
502}
503
504/// Whether the implementation behind `core` can run on this CPU.
505fn is_supported_cpu(core: &sys::Core) -> bool {
506 // SAFETY: the query takes no arguments and needs no initialization.
507 unsafe { core.NDIlib_is_supported_CPU() }
508}
509
510/// Initialization through the selected implementation's own entry points.
511pub(crate) struct SdkBackend {
512 lifecycle: sys::Lifecycle,
513 supported_cpu: unsafe extern "C" fn() -> bool,
514}
515
516impl RuntimeBackend for SdkBackend {
517 fn initialize(&self) -> bool {
518 // SAFETY: the manager serializes initialization against destruction.
519 unsafe { self.lifecycle.NDIlib_initialize() }
520 }
521
522 fn is_supported_cpu(&self) -> bool {
523 // SAFETY: this no-argument query needs no initialization.
524 unsafe { (self.supported_cpu)() }
525 }
526
527 fn destroy(&self) {
528 // SAFETY: the manager calls this only after the last handle is released,
529 // so no SDK object created through this initialization remains.
530 unsafe { self.lifecycle.NDIlib_destroy() };
531 }
532}
533
534/// Process-global runtime manager for NDI.
535///
536/// This implementation uses a `Mutex` + `Condvar` state machine that:
537/// - Allows re-initialization after teardown
538/// - Allows retry after initialization failure
539/// - Avoids spin loops by using `Condvar` waits
540/// - Maintains the invariant: `Ndi::new()` returns `Ok` only when runtime is initialized
541pub(crate) struct RuntimeManager<B = SdkBackend> {
542 state: Mutex<Phase>,
543 cv: Condvar,
544 backend: B,
545}
546
547impl<B: RuntimeBackend> RuntimeManager<B> {
548 const fn with_backend(backend: B) -> Self {
549 Self {
550 state: Mutex::new(Phase::Stopped),
551 cv: Condvar::new(),
552 backend,
553 }
554 }
555
556 /// Recover from mutex poisoning, preferring progress over panic.
557 fn recover_guard<'a>(
558 result: std::sync::LockResult<MutexGuard<'a, Phase>>,
559 ) -> MutexGuard<'a, Phase> {
560 result.unwrap_or_else(|poisoned| poisoned.into_inner())
561 }
562
563 fn acquire(&self) -> Result<()> {
564 let mut guard = Self::recover_guard(self.state.lock());
565 loop {
566 match *guard {
567 Phase::Stopped => {
568 *guard = Phase::Starting;
569 drop(guard);
570 // Native calls run outside the state lock.
571 let started = self.start();
572 guard = Self::recover_guard(self.state.lock());
573 *guard = if started.is_ok() {
574 Phase::Running(NonZeroUsize::MIN)
575 } else {
576 Phase::Stopped
577 };
578 self.cv.notify_all();
579 return started;
580 }
581 Phase::Starting | Phase::Stopping => {
582 guard = Self::recover_guard(self.cv.wait(guard));
583 }
584 Phase::Running(count) => {
585 let next = count.checked_add(1).ok_or(Error::InitializationFailed(
586 crate::InitializationFailure::HandleCountExhausted,
587 ))?;
588 *guard = Phase::Running(next);
589 return Ok(());
590 }
591 }
592 }
593 }
594
595 /// Start NDI, classifying a failure by what the implementation reports.
596 ///
597 /// The CPU is consulted only after a failed start: an implementation that
598 /// starts is the authority on whether it can run.
599 fn start(&self) -> Result<()> {
600 if self.backend.initialize() {
601 Ok(())
602 } else if self.backend.is_supported_cpu() {
603 Err(Error::InitializationFailed(
604 crate::InitializationFailure::NotStarted,
605 ))
606 } else {
607 Err(Error::UnsupportedCpu)
608 }
609 }
610
611 fn release(&self) {
612 let mut guard = Self::recover_guard(self.state.lock());
613 match *guard {
614 Phase::Running(count) => {
615 // NonZeroUsize proves the subtraction cannot underflow.
616 if let Some(remaining) = NonZeroUsize::new(count.get() - 1) {
617 *guard = Phase::Running(remaining);
618 return;
619 }
620 *guard = Phase::Stopping;
621 drop(guard);
622 // The last handle stops NDI outside the state lock.
623 self.backend.destroy();
624 let mut guard = Self::recover_guard(self.state.lock());
625 *guard = Phase::Stopped;
626 self.cv.notify_all();
627 }
628 other => {
629 debug_invariant!(false, "release() called while runtime was {other:?}");
630 }
631 }
632 }
633
634 pub(crate) fn is_running(&self) -> bool {
635 matches!(*Self::recover_guard(self.state.lock()), Phase::Running(_))
636 }
637}
638
639impl RuntimeManager {
640 pub(crate) fn new(
641 lifecycle: sys::Lifecycle,
642 supported_cpu: unsafe extern "C" fn() -> bool,
643 ) -> Self {
644 Self::with_backend(SdkBackend {
645 lifecycle,
646 supported_cpu,
647 })
648 }
649}
650
651/// A handle to the started NDI runtime.
652///
653/// Every finder, sender and receiver is created from an `Ndi` handle, and NDI
654/// stays started while any handle exists: those objects each retain one, and
655/// [`Clone::clone`] and [`Runtime::initialize`] add more. Dropping the last
656/// handle stops NDI but leaves the selected library loaded, so NDI can be
657/// started again. [`Ndi::process_lifetime`] keeps it started until the process
658/// exits.
659///
660/// [`Ndi::new`] selects the default runtime and starts it in one call. To
661/// inspect a runtime before starting it, or to choose which one is loaded, use
662/// [`Runtime::select`] and then [`Runtime::initialize`].
663///
664/// # Examples
665///
666/// ```no_run
667/// use grafton_ndi::Ndi;
668///
669/// # fn main() -> Result<(), grafton_ndi::Error> {
670/// let ndi = Ndi::new()?;
671///
672/// // NDI stays started for as long as any handle exists.
673/// let another = ndi.clone();
674/// drop(ndi);
675/// assert!(Ndi::is_running());
676///
677/// // Dropping the last handle stops it.
678/// drop(another);
679/// # Ok(())
680/// # }
681/// ```
682pub struct Ndi {
683 runtime: Runtime,
684}
685
686/// The initialized runtime already retained by a native resource.
687/// Binding an existing owner never acquires another runtime reference.
688pub(crate) trait LiveOwner {
689 fn ndi(&self) -> &Ndi;
690}
691
692impl LiveOwner for Ndi {
693 fn ndi(&self) -> &Ndi {
694 self
695 }
696}
697
698impl LiveOwner for std::sync::Arc<crate::receiver::ReceiverCore> {
699 fn ndi(&self) -> &Ndi {
700 self.as_ref().ndi()
701 }
702}
703
704/// How a native capability reaches its table through its retained owner.
705/// The core table is already in `Ndi`, so it needs no second pointer.
706/// Optional and File tables cache their gated pointer beside that owner.
707pub(crate) trait BoundTable: 'static {
708 type Storage: Copy;
709
710 fn store(table: &'static Self) -> Self::Storage;
711 fn borrow<'a>(table: &'a Self::Storage, ndi: &'a Ndi) -> &'a Self;
712}
713
714impl<T: sys::Table> BoundTable for T {
715 type Storage = &'static T;
716
717 fn store(table: &'static Self) -> Self::Storage {
718 table
719 }
720
721 fn borrow<'a>(table: &'a Self::Storage, _: &'a Ndi) -> &'a Self {
722 table
723 }
724}
725
726impl BoundTable for sys::Core {
727 type Storage = ();
728
729 fn store(_: &'static Self) {}
730
731 fn borrow<'a>(_: &'a (), ndi: &'a Ndi) -> &'a Self {
732 &ndi.api().core
733 }
734}
735
736#[cfg(feature = "file-io")]
737macro_rules! file_bound_tables {
738 ($($table:ty),+ $(,)?) => {$(
739 impl BoundTable for $table {
740 type Storage = &'static Self;
741
742 fn store(table: &'static Self) -> Self::Storage {
743 table
744 }
745
746 fn borrow<'a>(table: &'a Self::Storage, _: &'a Ndi) -> &'a Self {
747 table
748 }
749 }
750 )+};
751}
752
753#[cfg(feature = "file-io")]
754file_bound_tables!(sys::FileRuntime, sys::FilePlayback, sys::FileRecording);
755
756/// A native constructor's result and any configuration it may have retained.
757pub(crate) struct NativeCreation<I> {
758 pub(crate) call: sys::table::Called<I>,
759 #[cfg(feature = "advanced")]
760 pub(crate) config: crate::advanced::RetainedConfig,
761}
762
763impl<I> NativeCreation<I> {
764 pub(crate) fn plain(call: sys::table::Called<I>) -> Self {
765 Self {
766 call,
767 #[cfg(feature = "advanced")]
768 config: crate::advanced::RetainedConfig::default(),
769 }
770 }
771}
772
773/// Native entry points paired with the initialized runtime they require.
774/// Only runtime binding paths can construct this capability. Dereferencing it
775/// borrows the table for no longer than the retained owner.
776pub(crate) struct Bound<T: BoundTable, O: LiveOwner = Ndi> {
777 table: T::Storage,
778 owner: O,
779}
780
781impl<T: BoundTable, O: LiveOwner> Bound<T, O> {
782 pub(crate) fn ndi(&self) -> &Ndi {
783 self.owner().ndi()
784 }
785
786 pub(crate) fn owner(&self) -> &O {
787 &self.owner
788 }
789}
790
791impl<T: sys::Table, O: LiveOwner> Bound<T, O> {
792 /// Gate through an existing live owner and move its proof into the table.
793 #[allow(
794 dead_code,
795 reason = "existing-owner bindings are used by optional receiver adapters"
796 )]
797 pub(crate) fn with_owner(owner: O) -> Result<Self> {
798 let table = T::of(owner.ndi().runtime.selected)?;
799 Ok(Self {
800 table: T::store(table),
801 owner,
802 })
803 }
804}
805
806#[cfg(test)]
807impl<T: BoundTable> Bound<T> {
808 pub(crate) fn for_test(ndi: Ndi, table: &'static T) -> Self {
809 Self {
810 table: T::store(table),
811 owner: ndi,
812 }
813 }
814}
815
816#[cfg(feature = "file-io")]
817impl Bound<sys::FileRuntime> {
818 pub(crate) fn into_file_table<T: sys::FileTable>(self) -> Result<Bound<T>> {
819 let table = self.table.table::<T>()?;
820 Ok(Bound {
821 table: T::store(table),
822 owner: self.owner,
823 })
824 }
825
826 pub(crate) fn bind_file_table<T: sys::FileTable>(&self) -> Result<Bound<T>> {
827 // Gate before cloning, so an unsupported family does not acquire a handle.
828 let table = self.table.table::<T>()?;
829 Ok(Bound {
830 table: T::store(table),
831 owner: self.owner.clone(),
832 })
833 }
834}
835
836impl<T: BoundTable, O: LiveOwner> std::ops::Deref for Bound<T, O> {
837 type Target = T;
838
839 fn deref(&self) -> &T {
840 T::borrow(&self.table, self.owner.ndi())
841 }
842}
843
844impl<T: BoundTable, O: LiveOwner + Clone> Clone for Bound<T, O> {
845 fn clone(&self) -> Self {
846 Self {
847 table: self.table,
848 owner: self.owner.clone(),
849 }
850 }
851}
852
853impl fmt::Debug for Ndi {
854 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
855 f.debug_struct("Ndi")
856 .field("info", self.info())
857 .finish_non_exhaustive()
858 }
859}
860
861impl Ndi {
862 #[cfg(test)]
863 pub(crate) fn test_double(core: sys::Core) -> Self {
864 Runtime {
865 selected: sys::Runtime::test_double(core),
866 }
867 .initialize()
868 .unwrap()
869 }
870
871 /// Select the default NDI runtime and start it.
872 ///
873 /// This is [`Runtime::select`] with the default [`RuntimeOptions`]
874 /// followed by [`Runtime::initialize`]. It is thread-safe: the first
875 /// handle starts NDI and later calls add handles to the running runtime.
876 /// See the [search and trust policy](crate::runtime#where-the-runtime-is-loaded-from)
877 /// before selecting a runtime in a service or elevated process.
878 ///
879 /// # Errors
880 ///
881 /// Returns [`Error::RuntimeLoadFailed`] if no usable runtime library is
882 /// found in the [search order](crate::runtime#where-the-runtime-is-loaded-from).
883 /// Its [`crate::LoadFailure`] distinguishes code that loaded and was refused
884 /// from locations that could not be opened. Returns
885 /// [`Error::RuntimeConflict`] if native loading re-enters runtime selection
886 /// on the same thread. Returns [`Error::UnsupportedCpu`] if the runtime does not start because this
887 /// CPU cannot run it, and [`Error::InitializationFailed`] if it does not
888 /// start for another reason or the count of handles is exhausted.
889 ///
890 /// # Examples
891 ///
892 /// ```no_run
893 /// # use grafton_ndi::Ndi;
894 /// # fn main() -> Result<(), grafton_ndi::Error> {
895 /// let ndi = Ndi::new()?;
896 /// // Use NDI operations...
897 /// # Ok(())
898 /// # }
899 /// ```
900 #[doc(alias = "NDIlib_initialize")]
901 pub fn new() -> Result<Self> {
902 Self::with_options(&RuntimeOptions::default())
903 }
904
905 /// Select the NDI runtime `options` describe and start it.
906 ///
907 /// This is [`Runtime::select`] followed by [`Runtime::initialize`].
908 ///
909 /// # Errors
910 ///
911 /// Returns the errors of those two steps. A failed selection or start can
912 /// be retried; once selection has succeeded, every later call uses the
913 /// selected runtime and reports [`Error::RuntimeConflict`] for options it
914 /// does not meet, with a typed [`crate::SelectionConflict`]. A
915 /// [`crate::LoadFailure`] retains the structured attempts when loading fails.
916 ///
917 /// # Examples
918 ///
919 /// ```no_run
920 /// use grafton_ndi::{RuntimeOptions, SdkEdition, Ndi};
921 ///
922 /// # fn main() -> Result<(), grafton_ndi::Error> {
923 /// let ndi = Ndi::with_options(&RuntimeOptions::default().edition(SdkEdition::Advanced))?;
924 /// # drop(ndi);
925 /// # Ok(())
926 /// # }
927 /// ```
928 #[doc(alias = "NDIlib_initialize")]
929 pub fn with_options(options: &RuntimeOptions) -> Result<Self> {
930 Runtime::select(options)?.initialize()
931 }
932
933 /// The selected implementation this handle keeps started.
934 ///
935 /// # Examples
936 ///
937 /// ```no_run
938 /// # use grafton_ndi::Ndi;
939 /// # fn main() -> Result<(), grafton_ndi::Error> {
940 /// let ndi = Ndi::new()?;
941 /// // A second handle from the same runtime, without selecting again.
942 /// let another = ndi.runtime().initialize()?;
943 /// # drop(another);
944 /// # Ok(())
945 /// # }
946 /// ```
947 pub fn runtime(&self) -> Runtime {
948 self.runtime
949 }
950
951 /// The selected implementation's identity; see [`Runtime::info`].
952 pub fn info(&self) -> &'static RuntimeInfo {
953 self.runtime.info()
954 }
955
956 /// What the selected implementation supports; see [`Runtime::capabilities`].
957 pub fn capabilities(&self) -> &'static Capabilities {
958 self.runtime.capabilities()
959 }
960
961 #[cfg(feature = "file-io")]
962 pub(crate) fn selected(&self) -> &sys::Runtime {
963 self.runtime.selected
964 }
965
966 /// The selected implementation's entry points.
967 pub(crate) fn api(&self) -> &sys::Api {
968 self.runtime.selected.gates.api()
969 }
970
971 /// Reject an unavailable operation before passing newer inputs to the SDK.
972 ///
973 /// # Errors
974 ///
975 /// Returns [`Error::UnsupportedCapability`] naming the capability and why
976 /// the selected runtime or this build cannot provide it.
977 pub fn require_feature(&self, feature: RuntimeFeature) -> Result<()> {
978 self.runtime.require_feature(feature)
979 }
980
981 /// The entry points of an optional capability, core or Advanced, or the
982 /// error [`Self::require_feature`] reports for it.
983 ///
984 /// The table type alone selects the capability, so a table cannot be
985 /// obtained without its gate or be reported as another capability.
986 pub(crate) fn table<T: sys::Table>(&self) -> Result<&T> {
987 T::of(self.runtime.selected)
988 }
989
990 /// Check the capability and acquire its runtime before native creation.
991 pub(crate) fn bind<T: sys::Table>(&self) -> Result<Bound<T>> {
992 let table = T::of(self.runtime.selected)?;
993 Ok(Bound {
994 table: T::store(table),
995 owner: self.clone(),
996 })
997 }
998
999 pub(crate) fn bind_core(&self) -> Bound<sys::Core> {
1000 Bound {
1001 table: (),
1002 owner: self.clone(),
1003 }
1004 }
1005
1006 #[cfg(feature = "file-io")]
1007 pub(crate) fn bind_file_runtime(
1008 &self,
1009 table: &'static sys::FileRuntime,
1010 ) -> Bound<sys::FileRuntime> {
1011 Bound {
1012 table,
1013 owner: self.clone(),
1014 }
1015 }
1016
1017 pub(crate) fn evidence(&self) -> sys::Evidence<'_> {
1018 self.runtime.selected.evidence()
1019 }
1020
1021 /// The receiver color format that selects `preset`, or the error
1022 /// [`Self::require_feature`] reports for it. The preset's gate includes
1023 /// the configured receiver's, so that table is then available too.
1024 #[cfg(feature = "advanced")]
1025 pub(crate) fn passthrough_format(
1026 &self,
1027 preset: crate::advanced::PassthroughPreset,
1028 ) -> Result<sys::bindings::NDIlib_recv_color_format_e> {
1029 self.runtime.selected.evidence().passthrough_format(preset)
1030 }
1031
1032 /// Retain an initialized runtime reference until process exit.
1033 ///
1034 /// This is an irreversible, process-wide opt-in. It does not change ordinary
1035 /// reference-counted teardown unless this method is explicitly called.
1036 pub fn process_lifetime(&self) -> ProcessLifetimeRuntime {
1037 ProcessLifetimeRuntime {
1038 ndi: PROCESS_LIFETIME.get_or_init(|| self.clone()),
1039 }
1040 }
1041
1042 /// Whether NDI is started, by this or any other handle in the process.
1043 ///
1044 /// This only reads the current state: it never selects or loads a
1045 /// runtime, and is `false` before one has been selected.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```
1050 /// if grafton_ndi::Ndi::is_running() {
1051 /// println!("NDI runtime is active");
1052 /// }
1053 /// ```
1054 pub fn is_running() -> bool {
1055 sys::is_running()
1056 }
1057}
1058
1059impl Clone for Ndi {
1060 /// Acquires another reference to the active runtime.
1061 ///
1062 /// # Panics
1063 ///
1064 /// Panics if the runtime handle reference count is exhausted. The original
1065 /// handle and runtime remain valid.
1066 #[expect(
1067 clippy::expect_used,
1068 reason = "Clone cannot report handle-count exhaustion; its documented panic preserves the original handle"
1069 )]
1070 fn clone(&self) -> Self {
1071 self.runtime
1072 .selected
1073 .lifecycle
1074 .acquire()
1075 .expect("Unable to acquire another reference to the existing NDI runtime");
1076 Self {
1077 runtime: self.runtime,
1078 }
1079 }
1080}
1081
1082impl Drop for Ndi {
1083 fn drop(&mut self) {
1084 self.runtime.selected.lifecycle.release();
1085 }
1086}
1087
1088#[cfg(test)]
1089mod tests {
1090 use super::*;
1091 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1092 use std::sync::Arc;
1093 use std::thread;
1094 use std::time::Duration;
1095
1096 #[derive(Default)]
1097 struct MockBackend {
1098 init_count: AtomicUsize,
1099 destroy_count: AtomicUsize,
1100 cpu_query_count: AtomicUsize,
1101 init_should_fail: AtomicBool,
1102 cpu_unsupported: AtomicBool,
1103 init_delay_ms: AtomicUsize,
1104 destroy_delay_ms: AtomicUsize,
1105 }
1106
1107 impl RuntimeBackend for MockBackend {
1108 fn initialize(&self) -> bool {
1109 thread::sleep(Duration::from_millis(
1110 self.init_delay_ms.load(Ordering::Acquire) as u64,
1111 ));
1112 self.init_count.fetch_add(1, Ordering::AcqRel);
1113 !self.init_should_fail.load(Ordering::Acquire)
1114 }
1115
1116 fn is_supported_cpu(&self) -> bool {
1117 self.cpu_query_count.fetch_add(1, Ordering::AcqRel);
1118 !self.cpu_unsupported.load(Ordering::Acquire)
1119 }
1120
1121 fn destroy(&self) {
1122 thread::sleep(Duration::from_millis(
1123 self.destroy_delay_ms.load(Ordering::Acquire) as u64,
1124 ));
1125 self.destroy_count.fetch_add(1, Ordering::AcqRel);
1126 }
1127 }
1128
1129 impl RuntimeManager<MockBackend> {
1130 fn phase(&self) -> Phase {
1131 *Self::recover_guard(self.state.lock())
1132 }
1133
1134 fn refcount(&self) -> usize {
1135 match *Self::recover_guard(self.state.lock()) {
1136 Phase::Running(count) => count.get(),
1137 _ => 0,
1138 }
1139 }
1140 }
1141
1142 fn isolated_ndi() -> Ndi {
1143 // No native operation is invoked by these lifecycle/binding tests.
1144 let core = sys::Core::load(&sys::table::ExportsWhere(|_| true))
1145 .unwrap()
1146 .unwrap();
1147 Ndi::test_double(core)
1148 }
1149
1150 #[test]
1151 fn a_bound_table_retains_exactly_one_runtime_reference() {
1152 let ndi = isolated_ndi();
1153 let manager = &ndi.runtime.selected.lifecycle;
1154 let bound = ndi.bind_core();
1155 assert!(
1156 matches!(*manager.state.lock().unwrap(), Phase::Running(count) if count.get() == 2)
1157 );
1158 drop(ndi);
1159 assert!(manager.is_running());
1160 assert_eq!(bound.ndi().info().raw_version(), "6.4.0.2");
1161 drop(bound);
1162 assert!(matches!(*manager.state.lock().unwrap(), Phase::Stopped));
1163 assert_eq!(
1164 std::mem::size_of::<Bound<sys::Core>>(),
1165 std::mem::size_of::<Ndi>()
1166 );
1167 assert_eq!(
1168 std::mem::size_of::<Bound<sys::Routing>>(),
1169 std::mem::size_of::<Ndi>() + std::mem::size_of::<&sys::Routing>()
1170 );
1171 }
1172
1173 #[test]
1174 fn binding_an_existing_owner_needs_no_additional_runtime_handle() {
1175 struct TestTable;
1176 impl sys::Table for TestTable {
1177 fn within(_: sys::Evidence<'_>) -> Result<&Self> {
1178 static TABLE: TestTable = TestTable;
1179 Ok(&TABLE)
1180 }
1181 }
1182 struct Owner(Ndi);
1183 impl LiveOwner for std::sync::Arc<Owner> {
1184 fn ndi(&self) -> &Ndi {
1185 &self.0
1186 }
1187 }
1188
1189 let ndi = isolated_ndi();
1190 let manager = &ndi.runtime.selected.lifecycle;
1191 let owner = std::sync::Arc::new(Owner(ndi));
1192 *manager.state.lock().unwrap() = Phase::Running(NonZeroUsize::MAX);
1193 let bound = Bound::<TestTable, _>::with_owner(owner.clone()).unwrap();
1194 assert!(std::sync::Arc::ptr_eq(bound.owner(), &owner));
1195 assert!(
1196 matches!(*manager.state.lock().unwrap(), Phase::Running(count) if count == NonZeroUsize::MAX)
1197 );
1198 *manager.state.lock().unwrap() = Phase::Running(NonZeroUsize::MIN);
1199 assert_eq!(
1200 std::mem::size_of_val(&bound),
1201 std::mem::size_of_val(&owner) + std::mem::size_of::<&TestTable>()
1202 );
1203 drop(owner);
1204 assert!(manager.is_running());
1205 drop(bound);
1206 assert!(matches!(*manager.state.lock().unwrap(), Phase::Stopped));
1207 }
1208
1209 #[test]
1210 fn exhausted_binding_never_calls_native_creation() {
1211 let ndi = isolated_ndi();
1212 let manager = &ndi.runtime.selected.lifecycle;
1213 *manager.state.lock().unwrap() = Phase::Running(NonZeroUsize::MAX);
1214 let creates = AtomicUsize::new(0);
1215 let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1216 // SAFETY: no native instance is returned; an exhausted bind must
1217 // panic before this closure can observe the settings at all.
1218 let _ = unsafe {
1219 crate::Finder::create(&ndi, &crate::FinderOptions::new(), |_, _| {
1220 creates.fetch_add(1, Ordering::Relaxed);
1221 NativeCreation::plain(sys::table::for_test(
1222 std::ptr::null_mut(),
1223 c"NDIlib_find_create_v2",
1224 ))
1225 })
1226 };
1227 }));
1228 // An unavailable capability is still refused before the exhausted clone.
1229 let unavailable = ndi.bind::<sys::Routing>();
1230 *manager.state.lock().unwrap() = Phase::Running(NonZeroUsize::MIN);
1231 assert!(rejected.is_err());
1232 assert_eq!(creates.load(Ordering::Relaxed), 0);
1233 assert!(matches!(
1234 unavailable,
1235 Err(Error::UnsupportedCapability { .. })
1236 ));
1237 }
1238
1239 #[test]
1240 fn refcount_overflow_preserves_live_runtime() {
1241 let manager = RuntimeManager::with_backend(MockBackend::default());
1242 manager.acquire().unwrap();
1243 *manager.state.lock().unwrap() = Phase::Running(NonZeroUsize::MAX);
1244 assert!(manager.acquire().is_err());
1245 assert_eq!(manager.refcount(), usize::MAX);
1246 assert!(manager.is_running());
1247 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 0);
1248 // Restore the injected count so the acquired reference can be released.
1249 *manager.state.lock().unwrap() = Phase::Running(NonZeroUsize::MIN);
1250 manager.release();
1251 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 1);
1252 }
1253
1254 #[test]
1255 fn two_handles_release_the_runtime_exactly_once() {
1256 let manager = RuntimeManager::with_backend(MockBackend::default());
1257 manager.acquire().unwrap();
1258 manager.acquire().unwrap();
1259 assert_eq!(manager.refcount(), 2);
1260 manager.release();
1261 assert_eq!(manager.phase(), Phase::Running(NonZeroUsize::MIN));
1262 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 0);
1263 manager.release();
1264 assert_eq!(manager.phase(), Phase::Stopped);
1265 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 1);
1266 }
1267
1268 #[test]
1269 fn a_failed_start_is_classified_by_what_the_cpu_supports() {
1270 let manager = RuntimeManager::with_backend(MockBackend::default());
1271 manager
1272 .backend
1273 .init_should_fail
1274 .store(true, Ordering::Release);
1275
1276 // The implementation supports the CPU, so it failed for another reason.
1277 assert!(matches!(
1278 manager.acquire(),
1279 Err(Error::InitializationFailed(_))
1280 ));
1281 assert_eq!(manager.phase(), Phase::Stopped);
1282
1283 manager
1284 .backend
1285 .cpu_unsupported
1286 .store(true, Ordering::Release);
1287 assert!(matches!(manager.acquire(), Err(Error::UnsupportedCpu)));
1288 assert_eq!(manager.phase(), Phase::Stopped);
1289 assert!(!manager.is_running());
1290 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 2);
1291 assert_eq!(manager.backend.cpu_query_count.load(Ordering::Acquire), 2);
1292 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 0);
1293
1294 // Either failure leaves the runtime ready for another attempt.
1295 manager
1296 .backend
1297 .init_should_fail
1298 .store(false, Ordering::Release);
1299 manager.acquire().unwrap();
1300 assert!(manager.is_running());
1301 manager.release();
1302 }
1303
1304 #[test]
1305 fn a_runtime_that_starts_is_not_asked_about_the_cpu() {
1306 let manager = RuntimeManager::with_backend(MockBackend::default());
1307 // The start itself is the authority: a successful one is never
1308 // overruled by the separate CPU query.
1309 manager
1310 .backend
1311 .cpu_unsupported
1312 .store(true, Ordering::Release);
1313 manager.acquire().unwrap();
1314 assert!(manager.is_running());
1315 assert_eq!(manager.backend.cpu_query_count.load(Ordering::Acquire), 0);
1316 manager.release();
1317 }
1318
1319 // ========== Lifecycle Invariant Tests ==========
1320
1321 #[test]
1322 fn test_reinit_after_teardown() {
1323 // Issue requirement: create NDI, drop all, create NDI again
1324 // => init called twice, destroy called twice, both Ndi::new() return Ok
1325 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1326
1327 // First cycle
1328 manager.acquire().expect("First init should succeed");
1329 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 1);
1330 assert!(manager.is_running());
1331
1332 manager.release();
1333 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 1);
1334 assert!(!manager.is_running());
1335 assert_eq!(manager.phase(), Phase::Stopped);
1336
1337 // Second cycle - must re-initialize
1338 manager.acquire().expect("Second init should succeed");
1339 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 2);
1340 assert!(manager.is_running());
1341
1342 manager.release();
1343 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 2);
1344 assert!(!manager.is_running());
1345 }
1346
1347 #[test]
1348 fn test_init_failure_retry() {
1349 // Issue requirement: first init fails => error, next call succeeds => Ok
1350 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1351
1352 // Configure first init to fail
1353 manager
1354 .backend
1355 .init_should_fail
1356 .store(true, Ordering::Release);
1357
1358 let result = manager.acquire();
1359 assert!(result.is_err());
1360 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 1);
1361 assert_eq!(manager.phase(), Phase::Stopped);
1362 assert!(!manager.is_running());
1363
1364 // Configure next init to succeed
1365 manager
1366 .backend
1367 .init_should_fail
1368 .store(false, Ordering::Release);
1369
1370 let result = manager.acquire();
1371 assert!(result.is_ok());
1372 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 2);
1373 assert!(manager.is_running());
1374
1375 manager.release();
1376 }
1377
1378 #[test]
1379 fn test_no_ok_while_uninitialized() {
1380 // Issue requirement: cannot get Ok from acquire without init in that cycle
1381 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1382
1383 // Verify initial state
1384 assert_eq!(manager.phase(), Phase::Stopped);
1385 assert!(!manager.is_running());
1386 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 0);
1387
1388 // Acquire must call init
1389 manager.acquire().expect("Should succeed");
1390 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 1);
1391
1392 // Clone/acquire with running does NOT call init
1393 manager.acquire().expect("Clone should succeed");
1394 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 1);
1395 assert_eq!(manager.refcount(), 2);
1396
1397 // Release both
1398 manager.release();
1399 manager.release();
1400
1401 // After teardown, next acquire MUST call init
1402 assert_eq!(manager.phase(), Phase::Stopped);
1403 manager.acquire().expect("Re-init should succeed");
1404 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 2);
1405
1406 manager.release();
1407 }
1408
1409 #[test]
1410 fn test_destroy_called_exactly_once_per_cycle() {
1411 // Issue requirement: destroy called exactly once per successful init cycle
1412 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1413
1414 // First cycle with multiple refs
1415 manager.acquire().expect("Init");
1416 manager.acquire().expect("Clone 1");
1417 manager.acquire().expect("Clone 2");
1418 assert_eq!(manager.refcount(), 3);
1419 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 0);
1420
1421 manager.release();
1422 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 0);
1423 manager.release();
1424 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 0);
1425 manager.release(); // Last one
1426 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 1);
1427
1428 // Second cycle
1429 manager.acquire().expect("Re-init");
1430 manager.acquire().expect("Clone");
1431 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 1);
1432
1433 manager.release();
1434 manager.release();
1435 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 2);
1436 }
1437
1438 // ========== Concurrency Stress Tests ==========
1439
1440 #[test]
1441 fn test_concurrent_acquire_single_init() {
1442 // Issue requirement: concurrent Ndi::new() calls result in at most one init per cycle
1443 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1444
1445 // Add a small delay to init to increase chance of race
1446 manager.backend.init_delay_ms.store(5, Ordering::Release);
1447
1448 let handles: Vec<_> = (0..10)
1449 .map(|_| {
1450 let mgr = Arc::clone(&manager);
1451 thread::spawn(move || mgr.acquire())
1452 })
1453 .collect();
1454
1455 let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
1456
1457 // All should succeed
1458 for result in &results {
1459 assert!(result.is_ok());
1460 }
1461
1462 // Only one init call should have happened
1463 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 1);
1464 assert_eq!(manager.refcount(), 10);
1465
1466 // Cleanup
1467 for _ in 0..10 {
1468 manager.release();
1469 }
1470 }
1471
1472 #[test]
1473 fn test_concurrent_acquire_during_destroy() {
1474 // Issue requirement: callers block during destroy, then succeed after
1475 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1476
1477 // Initialize
1478 manager.acquire().expect("Init");
1479 assert!(manager.is_running());
1480
1481 // Add delay to destroy
1482 manager
1483 .backend
1484 .destroy_delay_ms
1485 .store(50, Ordering::Release);
1486
1487 let mgr_clone = Arc::clone(&manager);
1488
1489 // Start a thread that will try to acquire while destroy is in progress
1490 let acquirer = thread::spawn(move || {
1491 // Wait a bit to ensure destroy starts
1492 thread::sleep(Duration::from_millis(10));
1493 mgr_clone.acquire()
1494 });
1495
1496 // Trigger destroy
1497 manager.release();
1498
1499 // The acquirer should have blocked and then succeeded
1500 let result = acquirer.join().unwrap();
1501 assert!(result.is_ok());
1502
1503 // A new init cycle should have started
1504 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 2);
1505 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 1);
1506
1507 manager.release();
1508 }
1509
1510 #[test]
1511 fn test_mixed_acquire_release_concurrent() {
1512 // Stress test with mixed operations
1513 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1514 let success_count = Arc::new(AtomicUsize::new(0));
1515 let failure_count = Arc::new(AtomicUsize::new(0));
1516
1517 let handles: Vec<_> = (0..20)
1518 .map(|i| {
1519 let mgr = Arc::clone(&manager);
1520 let success = Arc::clone(&success_count);
1521 let failure = Arc::clone(&failure_count);
1522
1523 thread::spawn(move || {
1524 for _ in 0..10 {
1525 match mgr.acquire() {
1526 Ok(()) => {
1527 success.fetch_add(1, Ordering::Relaxed);
1528 // Hold for a bit
1529 if i % 3 == 0 {
1530 thread::sleep(Duration::from_micros(100));
1531 }
1532 mgr.release();
1533 }
1534 Err(_) => {
1535 failure.fetch_add(1, Ordering::Relaxed);
1536 }
1537 }
1538 }
1539 })
1540 })
1541 .collect();
1542
1543 for handle in handles {
1544 handle.join().expect("Thread panicked");
1545 }
1546
1547 // All should succeed (no failures configured)
1548 assert_eq!(success_count.load(Ordering::Relaxed), 200);
1549 assert_eq!(failure_count.load(Ordering::Relaxed), 0);
1550
1551 // Final state should be clean
1552 assert!(!manager.is_running());
1553 assert_eq!(manager.refcount(), 0);
1554 assert_eq!(manager.phase(), Phase::Stopped);
1555 }
1556
1557 #[test]
1558 fn test_concurrent_init_with_failures() {
1559 // Test that failures during concurrent init are handled correctly
1560 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1561 manager
1562 .backend
1563 .init_should_fail
1564 .store(true, Ordering::Release);
1565 manager.backend.init_delay_ms.store(5, Ordering::Release);
1566
1567 let handles: Vec<_> = (0..5)
1568 .map(|_| {
1569 let mgr = Arc::clone(&manager);
1570 thread::spawn(move || mgr.acquire())
1571 })
1572 .collect();
1573
1574 let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
1575
1576 // All should fail
1577 for result in &results {
1578 assert!(result.is_err());
1579 }
1580
1581 // State should be Failed
1582 assert_eq!(manager.phase(), Phase::Stopped);
1583 assert!(!manager.is_running());
1584
1585 // Now allow init to succeed
1586 manager
1587 .backend
1588 .init_should_fail
1589 .store(false, Ordering::Release);
1590
1591 // Retry should work
1592 manager.acquire().expect("Retry should succeed");
1593 assert!(manager.is_running());
1594
1595 manager.release();
1596 }
1597
1598 #[test]
1599 fn test_client_handles_can_be_released_and_recreated() {
1600 // Independent clients can share the runtime, release it, and start again.
1601 let manager = Arc::new(RuntimeManager::with_backend(MockBackend::default()));
1602
1603 // First client initializes the runtime.
1604 manager.acquire().expect("First client");
1605 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 1);
1606
1607 // Additional clients acquire independent references.
1608 manager.acquire().expect("Second client");
1609 manager.acquire().expect("Third client");
1610 assert_eq!(manager.refcount(), 3);
1611
1612 // All clients release their handles.
1613 manager.release();
1614 manager.release();
1615 manager.release();
1616
1617 // Runtime should be destroyed
1618 assert_eq!(manager.backend.destroy_count.load(Ordering::Acquire), 1);
1619 assert!(!manager.is_running());
1620
1621 // A later client must reinitialize the runtime.
1622 manager.acquire().expect("New client after teardown");
1623 assert_eq!(manager.backend.init_count.load(Ordering::Acquire), 2);
1624 assert!(manager.is_running());
1625
1626 manager.release();
1627 }
1628}