Skip to main content

grafton_ndi/file/
mod.rs

1//! Recording NDI sources to disk and playing recordings back, through the NDI
2//! File library.
3//!
4//! # Supported targets
5//!
6//! Enabled by `file-io`, independently of the `advanced` Cargo feature. The
7//! File ABI is included, so desktop and Android builds need no Advanced
8//! headers or `libclang`. On Linux, macOS and Android, the 6.4.0.2 File
9//! library imports the Advanced runtime's entry points and is refused before
10//! loading beside a Standard runtime. Select the runtime through
11//! [`RuntimeOptions::edition`](crate::RuntimeOptions::edition). The Windows
12//! File library ships for 64-bit Windows and supports either runtime edition.
13//! Apple mobile targets link the File archive at build time.
14//!
15//! The File library is a separate native library that accompanies the NDI
16//! runtime. [`FileApi::new`] finds it when it is first needed; nothing else in
17//! this crate depends on it, so its absence never affects sending or receiving.
18//!
19//! * [`FilePlayer::probe`] reads a recording's duration and track layout without
20//!   advertising anything on the network.
21//! * [`FilePlayer::new`] advertises an NDI source and plays recordings
22//!   through it; see [`FilePlayer`].
23//! * [`FileRecorder::new`] records a source's compressed essence exactly
24//!   as it arrives; see [`FileRecorder`]. The recorder is source-driven: it
25//!   subscribes to an NDI source and does not accept frames from Rust.
26//!
27//! # Where the File library is loaded from
28//!
29//! An explicit [`FileApiOptions::library_path`] selects a single file. The default
30//! search tries the selected NDI runtime's directory first, followed by the
31//! executable's directory, the absolute `NDI_RUNTIME_DIR_V6` and the platform
32//! loader locations, in that order.
33//!
34//! The [runtime search policy](crate::runtime#where-the-runtime-is-loaded-from)
35//! also governs File library paths, platform locations, relative environment
36//! entries and dyld behavior. Use trusted libraries and dependencies.
37//!
38//! When nothing is usable, [`Error::RuntimeLoadFailed`] carries a
39//! [`crate::LoadFailure`] for [`crate::LibraryKind::File`], with each attempted
40//! location, origin and typed refusal. `loaded_any()` reports whether any
41//! native code loaded before being refused. `Display` retains the diagnostic
42//! text for each attempt, including the operating system's reason. Like the NDI runtime, a
43//! loaded File library stays selected and loaded for the life of the process.
44//!
45//! A library that loads but cannot be used stays loaded. If the platform
46//! loader's own search then matches the library name to that module, it returns
47//! it again instead of looking further; the error names the file, and the remedy
48//! is to remove or fix it or to pass [`FileApiOptions::library_path`].
49//!
50//! The native borrowed source/path getters are deliberately not called: their
51//! strings can be invalidated by the SDK's recording thread. Use
52//! [`FileRecorder::last_accepted_source`] for the last accepted source request
53//! and [`FileRecorder::reported_current_file`] for the owned event view of the
54//! file. These can lag or differ from the native state as their docs describe.
55//!
56//! # What the File library provides
57//!
58//! Its entry points come in [`FileFamily`] groups: playback, which also
59//! probes recordings, and recording. A library is selected when it provides
60//! at least one family completely. [`FileApi::status`] reports each family,
61//! and an operation that needs a family the selected library lacks fails with
62//! [`Error::UnsupportedCapability`], naming the family and the first entry
63//! point the library does not export.
64//!
65//! # Finishing a recording
66//!
67//! [`FileRecorder::finish`] requests a stop and waits for closure events. See
68//! [`RecordingReport::closure_confirmed`] for what the SDK confirms and check
69//! the report's error counters. Drop and async close follow
70//! [`FileRecorderOptions::drop_wait`]. When file tracking becomes incomplete,
71//! follow [`StateConflict::IncompleteFileTracking`] before restarting.
72//!
73//! # Limits of the NDI 6.4 File library
74//!
75//! These limits apply to the versions and platforms named below. They lie
76//! inside the library and this crate cannot correct them.
77//!
78//! * **On Linux with the NDI 6.4 File library, a file reported closed is not
79//!   proof that its data was written.** A
80//!   session's report repeats what the library said: that it finalized each
81//!   file. When the disk fills while a session is being stopped, a write comes
82//!   up short, the library extends the file all the same and reports it closed
83//!   without an error, and [`FilePlayer::probe`] then reports a final duration
84//!   for a file whose data is not there. [`SessionEnd::Closed`] with no
85//!   errors therefore means that the container was finalized, not that every
86//!   frame reached the disk. A recording that must be complete has to be
87//!   checked by reading it back.
88//! * **On Linux with the NDI 6.4 File library, the process does not survive a
89//!   full disk during recording.** When a
90//!   write fails while a session is recording, the library queues a
91//!   write-failed and an error event and then crashes in its own writer
92//!   thread, which ends the process. Nothing this crate does can prevent it.
93//!   Record only where enough space is certain.
94//! * **On Linux with the NDI 6.4 File library, a file can be closed with
95//!   nothing in it.** The library opens a file as
96//!   soon as a session or a rollover starts, and reports it closed even if no
97//!   frame arrived: after a stop before the source delivered anything, a
98//!   switch to a source that is not there, or a rollover while the source is
99//!   lost. [`RecordingReport::empty_files`] counts confirmed empty files:
100//!   exactly under confirmed closure, and as a lower bound after incomplete
101//!   tracking.
102//! * **On Linux with the NDI 6.4 File library, a rollover the library cannot
103//!   carry out ends the session.** It accepts
104//!   the request, fails to open the new file, closes the old one and stops.
105//!   [`FileRecorder::rollover`] preflights the destination so a missing output
106//!   directory, a directory-only path, an existing exact name or an indexed
107//!   name that outgrows the filesystem limit can be refused while the session
108//!   continues. See [`FileNaming`] for the naming rules.
109//! * **On every platform with the NDI 6.4 File library, recording paths must
110//!   be absolute and reportable exactly.** Start and rollover preflight the
111//!   expanded path sent to the SDK. It must fit in 4094 UTF-8 bytes with the
112//!   current SDK, reserving at least 20 digits per index token. This keeps
113//!   closure events unambiguous.
114//!
115//! # Threads
116//!
117//! [`FilePlayer`] and [`FileRecorder`] are neither `Send` nor `Sync`: the SDK
118//! documents no threading contract for them, so each stays on the thread that
119//! created it. Every native call can block, including destruction; timeouts
120//! bound event waits only. The values they return are owned and can be sent
121//! anywhere. [`AsyncFilePlayer`] and [`AsyncFileRecorder`] keep each native
122//! object on a dedicated thread and expose futures that work with any executor.
123//! Those futures submit work on their first poll; [`FileOperation::submit`]
124//! explicitly submits immediately. Submitted stop, finish, close and abandon operations
125//! survive cancellation of their futures. Dropping the last async handle can
126//! block; await its `close()` operation before dropping it on an executor.
127//!
128//! # Examples
129//!
130//! ```no_run
131//! use std::time::{Duration, Instant};
132//!
133//! use grafton_ndi::{
134//!     file::{
135//!         FileApi, FileApiOptions, FileRecorder, FileRecorderOptions, FinishStatus,
136//!         RecordingTarget, RecordingTimecode, SessionEnd, SourceSpec,
137//!     },
138//!     Ndi,
139//! };
140//!
141//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
142//! let ndi = Ndi::new()?;
143//! let file = FileApi::new(&ndi, &FileApiOptions::default())?;
144//!
145//! let options = FileRecorderOptions::new(SourceSpec::new("STUDIO (Camera 1)")?);
146//! let mut recorder = FileRecorder::new(&file, &options)?;
147//! recorder.start(&RecordingTarget::new("take")?, RecordingTimecode::Preserve)?;
148//! let duration = Duration::from_secs(10);
149//! let start = Instant::now();
150//! while start.elapsed() < duration {
151//!     let wait = duration.saturating_sub(start.elapsed()).min(Duration::from_millis(250));
152//!     if let Some(event) = recorder.next_event(wait)? {
153//!         println!("{:?}", event.kind());
154//!     }
155//! }
156//!
157//! match recorder.finish(Duration::from_secs(5))? {
158//!     FinishStatus::Ended(SessionEnd::Closed(report)) => {
159//!         if report.error_events() != 0 || report.write_failures() != 0
160//!             || report.empty_files() != 0 || report.stopped_by_sdk()
161//!         {
162//!             return Err(format!("recording incomplete: {report:?}").into());
163//!         }
164//!         println!("closed {} file(s)", report.closed_files());
165//!     }
166//!     other => return Err(format!("closure unconfirmed: {other:?}").into()),
167//! }
168//! # Ok(())
169//! # }
170//! ```
171//!
172//! See [file_record.rs](https://github.com/GrantSparks/grafton-ndi/blob/main/examples/file_record.rs)
173//! for the complete recording workflow.
174
175#![warn(missing_docs)]
176
177mod asynchronous;
178mod out_param;
179mod player;
180mod recorder;
181mod types;
182#[cfg(windows)]
183mod windows_permissions;
184
185pub use asynchronous::{
186    AsyncFileOptions, AsyncFilePlayer, AsyncFileRecorder, FileEventFuture, FileOperation,
187};
188pub use player::FilePlayer;
189pub use recorder::{
190    FileRecorder, FinishStatus, RecorderState, RecordingReport, SessionEnd, StopRequest,
191};
192pub use types::*;
193
194use std::path::{Path, PathBuf};
195
196#[cfg(any(test, doc))]
197use crate::Error;
198use crate::{capabilities::CapabilityStatus, sys, Ndi, Result};
199#[cfg(test)]
200use out_param::OutParam;
201
202/// A family of the NDI File library's entry points, which a library provides
203/// completely or not at all.
204///
205/// [`FileApi::status`] reports whether the selected library provides one, and
206/// an operation that needs a family the library lacks fails with
207/// [`Error::UnsupportedCapability`], naming that family and its first missing
208/// entry point.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
210#[non_exhaustive]
211pub enum FileFamily {
212    /// Probing recordings ([`FilePlayer::probe`]) and playing them back as an
213    /// NDI source ([`FilePlayer`], [`AsyncFilePlayer`]).
214    Playback,
215    /// Recording NDI sources to disk ([`FileRecorder`], [`AsyncFileRecorder`]).
216    Recording,
217}
218
219impl FileFamily {
220    /// Every family.
221    #[cfg(test)]
222    pub(crate) const ALL: [Self; 2] = [Self::Playback, Self::Recording];
223
224    /// The name the family is reported under.
225    pub(crate) const fn name(self) -> &'static str {
226        match self {
227            Self::Playback => "file playback",
228            Self::Recording => "file recording",
229        }
230    }
231}
232
233impl std::fmt::Display for FileFamily {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        f.write_str(self.name())
236    }
237}
238
239/// How the File library is located. Creating this value loads nothing.
240#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
241pub struct FileApiOptions {
242    library_path: Option<PathBuf>,
243}
244
245impl FileApiOptions {
246    /// Restore the normal File library search instead of an explicit path.
247    #[must_use]
248    pub fn clear_library_path(mut self) -> Self {
249        self.library_path = None;
250        self
251    }
252
253    /// Requested exact File library path, or `None` for the normal search.
254    #[must_use]
255    pub fn configured_library_path(&self) -> Option<&Path> {
256        self.library_path.as_deref()
257    }
258
259    /// The default options: the first usable File library from the
260    /// [documented search](crate::file#where-the-file-library-is-loaded-from).
261    pub fn new() -> Self {
262        Self::default()
263    }
264
265    /// Load exactly this absolute File library path.
266    ///
267    /// A path that does not name an existing file is refused before native
268    /// loading. A failure to load the file is reported without a fallback.
269    /// A relative path is rejected by
270    /// [`FileApi::new`] with [`Error::InvalidInput`] on every target, before
271    /// selection. A target that links the SDK statically refuses an absolute
272    /// path with [`Error::RuntimeConflict`].
273    #[must_use]
274    pub fn library_path(mut self, path: impl Into<PathBuf>) -> Self {
275        self.library_path = Some(path.into());
276        self
277    }
278}
279
280/// The File library selected for this process.
281///
282/// Cloning is cheap. Every clone, and every player and recorder created from
283/// one, keeps the NDI runtime initialized.
284#[derive(Clone)]
285pub struct FileApi {
286    runtime: FileBound<sys::FileRuntime>,
287}
288
289/// A native File capability retains its initialized core runtime. Synthetic
290/// test capabilities explicitly reach no runtime and need no initialization.
291/// File owners keep the same field type in production and unit-test builds.
292enum FileBound<T: crate::runtime::BoundTable> {
293    Native(crate::runtime::Bound<T>),
294    #[cfg(test)]
295    Synthetic(&'static T),
296}
297
298impl<T: crate::runtime::BoundTable> Clone for FileBound<T> {
299    fn clone(&self) -> Self {
300        match self {
301            Self::Native(bound) => Self::Native(bound.clone()),
302            #[cfg(test)]
303            Self::Synthetic(table) => Self::Synthetic(table),
304        }
305    }
306}
307
308impl<T: crate::runtime::BoundTable> std::ops::Deref for FileBound<T> {
309    type Target = T;
310
311    fn deref(&self) -> &T {
312        match self {
313            Self::Native(bound) => bound,
314            #[cfg(test)]
315            Self::Synthetic(table) => table,
316        }
317    }
318}
319
320impl FileBound<sys::FileRuntime> {
321    /// Transfer the existing lease to the gated family before native creation.
322    fn into_table<T: sys::FileTable>(self) -> Result<FileBound<T>> {
323        match self {
324            Self::Native(bound) => bound.into_file_table().map(FileBound::Native),
325            #[cfg(test)]
326            Self::Synthetic(runtime) => runtime.table().map(FileBound::Synthetic),
327        }
328    }
329
330    fn bind_table<T: sys::FileTable>(&self) -> Result<FileBound<T>> {
331        match self {
332            Self::Native(bound) => bound.bind_file_table().map(FileBound::Native),
333            #[cfg(test)]
334            Self::Synthetic(runtime) => runtime.table().map(FileBound::Synthetic),
335        }
336    }
337}
338
339impl std::fmt::Debug for FileApi {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        f.debug_struct("FileApi")
342            .field("library_path", &self.library_path())
343            .field("playback", &self.status(FileFamily::Playback))
344            .field("recording", &self.status(FileFamily::Recording))
345            .finish_non_exhaustive()
346    }
347}
348
349impl FileApi {
350    /// Find and load the File library that accompanies `ndi`'s runtime.
351    ///
352    /// The first successful call selects the library for the process; later
353    /// calls return the same one. No player or recorder is created and nothing
354    /// is advertised.
355    ///
356    /// # Errors
357    ///
358    /// * [`Error::RuntimeLoadFailed`] when no usable File library can be
359    ///   loaded. Its [`crate::LoadFailure`] records typed attempts and whether
360    ///   any native code loaded before being refused. This is retryable, and
361    ///   the rest of the crate keeps working.
362    /// * [`Error::RuntimeConflict`] when the selected NDI runtime is not one
363    ///   the File library can accompany, `options` names a library other than
364    ///   the one already selected, or native loading re-enters File library
365    ///   selection on the same thread. [`crate::SelectionFailure::kind`] names
366    ///   the [`crate::SelectionConflict`]; its `Display` gives the diagnostic text.
367    /// * [`Error::InvalidInput`] when `options` names a relative path.
368    pub fn new(ndi: &Ndi, options: &FileApiOptions) -> Result<Self> {
369        let runtime = sys::select_file(ndi.selected(), options.library_path.as_deref())?;
370        Ok(Self {
371            runtime: FileBound::Native(ndi.bind_file_runtime(runtime)),
372        })
373    }
374
375    /// Canonical loaded file, with links resolved, or `None` for a linked SDK.
376    /// Uses the platform's ordinary path form; Windows extended syntax is kept
377    /// only when needed to express the same file.
378    pub fn library_path(&self) -> Option<&Path> {
379        self.runtime.path()
380    }
381
382    /// Whether the selected library provides `family`.
383    ///
384    /// [`CapabilityStatus::Unavailable`] with
385    /// [`SymbolUnavailable`](crate::capabilities::CapabilityRefusal::SymbolUnavailable)
386    /// when it does not export one of the family's entry points. Every
387    /// operation that needs the family then fails with
388    /// [`Error::UnsupportedCapability`], and keeps failing: the library stays
389    /// selected for the life of the process.
390    pub fn status(&self, family: FileFamily) -> CapabilityStatus {
391        self.runtime.status(family)
392    }
393
394    /// Whether the selected library provides `family`; see
395    /// [`status`](Self::status).
396    pub fn supports(&self, family: FileFamily) -> bool {
397        self.status(family) == CapabilityStatus::Available
398    }
399
400    /// Require the complete native entry-point family.
401    ///
402    /// Returns [`Error::UnsupportedCapability`] with the missing symbol when
403    /// the selected File library does not provide `family`.
404    pub fn require_family(&self, family: FileFamily) -> Result<()> {
405        self.runtime.require(family)
406    }
407
408    /// The table of a family, or the error for the first of its entry points
409    /// the library does not export. A player, recorder or probe takes its
410    /// table here, before it calls anything, so none runs without its family.
411    fn table<T: sys::FileTable>(&self) -> Result<&T> {
412        self.runtime.table()
413    }
414
415    fn into_table<T: sys::FileTable>(self) -> Result<FileBound<T>> {
416        self.runtime.into_table()
417    }
418
419    fn bind_table<T: sys::FileTable>(&self) -> Result<FileBound<T>> {
420        self.runtime.bind_table()
421    }
422}
423
424#[cfg(test)]
425impl FileApi {
426    /// An API whose entry points are the given test doubles.
427    fn with_tables(playback: sys::FilePlayback, recording: sys::FileRecording) -> Self {
428        Self::with_runtime(sys::FileRuntime::test_double(Ok(playback), Ok(recording)))
429    }
430
431    /// An API for a library of test doubles, which needs no runtime.
432    fn with_runtime(runtime: &'static sys::FileRuntime) -> Self {
433        Self {
434            runtime: FileBound::Synthetic(runtime),
435        }
436    }
437}
438
439#[cfg(test)]
440mod mock;
441
442#[cfg(test)]
443mod lifecycle_tests;
444
445#[cfg(test)]
446mod sdk_tests;