Skip to main content

grafton_ndi/file/
recorder.rs

1//! Recording an NDI source to disk, with explicit finalization.
2
3use std::{
4    cell::{Cell, LazyCell},
5    time::{Duration, Instant},
6};
7
8use super::{
9    types::{CheckedRecorderOptions, EventTextRef, NamePattern},
10    EventText, FileApi, FileBound, FileRecorderOptions, RecorderEvent, RecorderEventKind,
11    RecorderStats, RecordingTarget, RecordingTimecode, SourceFormat, SourceSpec, StateConflict,
12};
13#[cfg(doc)]
14use super::{FileFamily, FileNaming};
15use crate::{
16    sys,
17    timeout::{Deadline, Timeout},
18    Error, MediaTypes, MetadataSource, Result,
19};
20
21mod ledger;
22mod native;
23mod settle;
24mod tracker;
25use ledger::Ledger;
26pub use ledger::RecordingReport;
27use native::NativeRecorder;
28use settle::{DrainBudget, LateDrain, LocalFinish, Pumped, SessionId};
29pub(super) use settle::{FinishReply, FinishWaiters, Settlement, WaitOutcome};
30use tracker::FileTracker;
31
32/// The longest single wait for an event while finalization is pending. Short
33/// enough that a caller's interruption is noticed promptly.
34const FINISH_POLL: Duration = Duration::from_millis(25);
35
36/// The wait for a further event once every file is reported closed: long
37/// enough not to spin while the SDK finishes stopping.
38const SETTLE_POLL: Duration = Duration::from_millis(1);
39
40/// How many stale events [`FileRecorder::start`] discards before giving up on
41/// finding the queue empty, and how many queued events a wait takes after its
42/// deadline before it reports a timeout.
43pub(super) const STALE_EVENT_LIMIT: usize = 256;
44
45/// Where a recorder is in its session.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47#[non_exhaustive]
48pub enum RecorderState {
49    /// No session has been started.
50    Idle,
51    /// A session is recording, or waiting for its source.
52    Recording,
53    /// The session is stopping and its last file is not yet reported closed.
54    Stopping,
55    /// The session ended and every file it opened was reported closed.
56    Closed,
57    /// The session ended without [`RecordingReport::closure_confirmed`].
58    /// Events were lost, unreadable or inconsistent, or the session ended
59    /// before reporting any file. Incomplete tracking requires
60    /// [`FileRecorder::reset`] before starting another session; see
61    /// [`StateConflict::IncompleteFileTracking`].
62    Indeterminate,
63}
64
65/// What [`FileRecorder::request_stop`] did.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67#[non_exhaustive]
68pub enum StopRequest {
69    /// This call asked the SDK to stop.
70    Requested,
71    /// The session was already stopping.
72    AlreadyStopping,
73    /// No session has been started.
74    NotStarted,
75    /// The session had already ended with every file closed.
76    AlreadyClosed,
77    /// The session had already ended without confirmation that every file
78    /// was closed.
79    AlreadyEnded,
80}
81
82/// The outcome of finishing a recording session.
83///
84/// [`FileRecorder::finish`] and [`AsyncFileRecorder::finish`](super::AsyncFileRecorder::finish)
85/// retain a report even when their completion budget expires. The corresponding
86/// `wait_for_finish` methods return `None` on timeout and `Some` for a closed or
87/// indeterminate session.
88///
89/// A synchronous recorder stays usable whatever the outcome, but incomplete
90/// file tracking requires [`FileRecorder::reset`] before another session can
91/// start. An async recorder can be closed by another clone while the operation
92/// is running.
93#[derive(Clone, Debug, PartialEq, Eq, Hash)]
94#[non_exhaustive]
95pub enum FinishStatus {
96    /// The session ended within the completion budget.
97    Ended(SessionEnd),
98    /// `finish`'s completion budget expired before the session ended.
99    /// Call [`FileRecorder::wait_for_finish`] to keep waiting, or inspect the
100    /// recorder's current report.
101    /// An async operation interrupted by a close reports [`StateConflict::Closed`]
102    /// instead when closure cannot be established in its remaining budget.
103    TimedOut(RecordingReport),
104}
105
106/// The final outcome of a recording session.
107#[derive(Clone, Debug, PartialEq, Eq, Hash)]
108#[non_exhaustive]
109pub enum SessionEnd {
110    /// Every file the session opened is finalized. The report still records
111    /// any errors during the session, and
112    /// [`stopped_by_sdk`](RecordingReport::stopped_by_sdk) says whether the
113    /// recording ran until it was asked to stop or the SDK ended it sooner.
114    Closed(RecordingReport),
115    /// The session ended without [`RecordingReport::closure_confirmed`].
116    /// Incomplete file tracking requires [`FileRecorder::reset`] before
117    /// another session starts. See [`StateConflict::IncompleteFileTracking`].
118    Indeterminate(RecordingReport),
119}
120
121/// A file the recorder's events reported open.
122struct OpenFile {
123    path: EventText,
124    /// The SDK reported the first audio or video packet written to it.
125    has_media: bool,
126    /// Opening order is independent of the tracker's path-sorted storage.
127    order: u64,
128}
129
130/// What initiated the owner's cleanup. Abandon can replace an earlier close
131/// while that close is draining; synchronous drop never requests that change.
132#[derive(Clone, Copy)]
133pub(super) enum CleanupRequest {
134    Drop,
135    Close,
136    Abandon,
137}
138
139/// An absent sink still observes every event in the ledger.
140pub(super) type RecorderEventSink<'a> = Option<&'a dyn Fn(Result<RecorderEvent>)>;
141
142/// A recorder that writes one NDI source to disk.
143///
144/// The recorder subscribes to the source named in its options and stores the
145/// compressed essence as it arrives; it takes no frames from Rust. A session
146/// runs from [`start`](Self::start) until its last file is closed, and may
147/// span several files through [`rollover`](Self::rollover),
148/// [`set_source`](Self::set_source) and the SDK's own rollovers.
149///
150/// # Finishing
151///
152/// [`finish`](Self::finish) requests a stop and waits for closure events. Check
153/// [`RecordingReport::closure_confirmed`] and the report's error counters.
154/// Drop follows [`FileRecorderOptions::drop_wait`]; [`abandon`](Self::abandon)
155/// skips that wait. See [`StateConflict::IncompleteFileTracking`] for recovery.
156///
157/// # What a closed file means
158///
159/// A report of closure repeats what the SDK said: that it finalized the file.
160/// A closed file is not proof its data was written. Inspect the report and
161/// read back recordings whose completeness matters. See
162/// [the module's limits](super#limits-of-the-ndi-64-file-library).
163///
164/// # Events
165///
166/// Events are taken with [`next_event`](Self::next_event), and
167/// [`finish`](Self::finish) takes them itself while it waits; their effect on
168/// the session is kept in the [`report`](Self::report) either way. The SDK
169/// discards events that are not taken promptly, and a session that lost
170/// events can no longer be confirmed closed, so poll throughout a recording.
171/// File bookkeeping retains at most 16,384 entries and 16 MiB, accounting for
172/// entry storage and path capacity. Exceeding either private limit or failing
173/// to reserve storage makes tracking incomplete without dropping delivered
174/// events or changing the native dropped-event count.
175///
176/// A recorder belongs to the thread that created it, so it is neither
177/// [`Send`] nor [`Sync`]: the File API documents no thread on which a
178/// recorder may be used or destroyed, nor whether two calls on one recorder
179/// may overlap. Methods that call into the SDK may block; cached state and
180/// report snapshots do not call it.
181/// [`AsyncFileRecorder`](super::AsyncFileRecorder) offers the same operations
182/// as futures.
183pub struct FileRecorder {
184    native: NativeRecorder,
185    /// The configured tracks, used when starting each new session.
186    tracks: MediaTypes,
187    /// The source in effect, when the last change of source was accepted.
188    accepted_source: Option<SourceSpec>,
189    /// How the recorder names its files.
190    naming: NamePattern,
191    ledger: Ledger,
192    generation: u64,
193    cleanup: Option<Timeout>,
194}
195
196/// Rust-only creation state: its validation and family check require no
197/// native object, so this value can move to an owner thread before creation.
198pub(super) struct PreparedRecorder {
199    recording: FileBound<sys::FileRecording>,
200    options: CheckedRecorderOptions,
201}
202
203impl PreparedRecorder {
204    pub(super) fn create(self) -> Result<FileRecorder> {
205        let Self { recording, options } = self;
206        let native = NativeRecorder::create(recording, &options)?;
207        Ok(FileRecorder {
208            native,
209            tracks: options.tracks,
210            cleanup: Some(options.drop_wait),
211            accepted_source: Some(options.source),
212            naming: options.naming,
213            ledger: Ledger::idle(),
214            generation: 0,
215        })
216    }
217}
218
219impl std::fmt::Debug for FileRecorder {
220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221        f.debug_struct("FileRecorder")
222            .field("state", &self.ledger.state())
223            .field("session", &self.ledger.session_number())
224            .finish_non_exhaustive()
225    }
226}
227
228impl FileRecorder {
229    /// Create a recorder for the source named in `options`.
230    ///
231    /// Nothing is written until [`FileRecorder::start`]. The options are only
232    /// read, so they stay with the caller whatever the outcome; the recorder
233    /// keeps its own copy of the source they name.
234    ///
235    /// # Errors
236    ///
237    /// [`Error::InvalidInput`] when the options are malformed or conflict:
238    /// an empty track selection, a drop wait beyond [`crate::MAX_TIMEOUT`], a
239    /// malformed [`FileNaming::Pattern`], or an exact file name
240    /// ([`FileNaming::Exact`], or a pattern without `{index}`) with
241    /// format-change rollover switched on or a nonzero rollover size.
242    /// [`Error::InvalidCString`] when the filename pattern contains a NUL.
243    /// [`Error::NativeOperationFailed`] when the SDK cannot create the
244    /// recorder and [`Error::UnsupportedCapability`] when the library does not
245    /// provide [`FileFamily::Recording`].
246    #[doc(alias = "NDIlib_file_recorder_create")]
247    pub fn new(api: &FileApi, options: &FileRecorderOptions) -> Result<Self> {
248        Self::prepare(api.clone(), options)?.create()
249    }
250
251    pub(super) fn prepare(api: FileApi, options: &FileRecorderOptions) -> Result<PreparedRecorder> {
252        let recording = api.into_table::<sys::FileRecording>()?;
253        let options = options.check()?;
254        Ok(PreparedRecorder { recording, options })
255    }
256
257    /// Where the recorder is in its session.
258    ///
259    /// The state follows the events taken so far. A source that disconnects
260    /// leaves a session [`RecorderState::Recording`]; recording resumes when
261    /// it returns.
262    pub fn state(&self) -> RecorderState {
263        self.ledger.state()
264    }
265
266    /// What the events taken so far have shown about the current session.
267    pub fn report(&self) -> RecordingReport {
268        self.ledger.report()
269    }
270
271    fn session_id(&self) -> SessionId {
272        SessionId {
273            recorder: self.generation,
274            session: self.ledger.session_number(),
275        }
276    }
277
278    /// Start a session writing to `target`, and return its number.
279    ///
280    /// The recorder's [`FileNaming`](super::FileNaming) turns the target into
281    /// file names. With the default indexed names the lowest unused index is
282    /// chosen; with an exact file name a file that already exists is refused.
283    /// The directory the naming leads to must exist. The check does not
284    /// reserve the file: a collision created afterwards reaches the SDK and
285    /// can cause a native open failure. Linux File SDK 6.4.0.2 uses exclusive
286    /// creation and preserves the colliding file; other platforms and SDK
287    /// releases have not been verified. Use a recorder-controlled directory
288    /// for uninterrupted recording and destination containment. Parent
289    /// directories are not pinned against replacement.
290    ///
291    /// Queued events from an earlier session, including unreadable events,
292    /// are consumed and discarded before the native start. Poll them before
293    /// starting if their contents are needed. The asynchronous recorder instead
294    /// forwards these events through its `next_event` operation.
295    /// A restart checks for SDK event loss after draining the queue. A loss
296    /// visible at this check can require a reset without changing the previous
297    /// session's final report. If the restart succeeds, the new session
298    /// accounts for loss after this check.
299    ///
300    /// The target is only read, so it stays with the caller whatever the
301    /// outcome, for example to start again once a missing directory exists.
302    /// [`RecordingTimecode::GenerateFrom`] takes a validated
303    /// [`SessionTimecode`](super::SessionTimecode), so the native start always
304    /// receives an explicit timecode rather than the send synthesize sentinel.
305    ///
306    /// # Errors
307    ///
308    /// * [`Error::InvalidState`] with [`StateConflict::PreviousSessionOpen`]
309    ///   while an earlier session is recording, stopping, awaiting a known
310    ///   file's closure under complete tracking; finish or poll it first.
311    ///   [`StateConflict::IncompleteFileTracking`] after a session ends with
312    ///   incomplete tracking. [`StateConflict::EarlierSessionEvents`]
313    ///   when the SDK keeps reporting events of an earlier session.
314    /// * [`Error::InvalidInput`] when the expanded output path is relative,
315    ///   has no file name, or its longest form exceeds the recorder event's
316    ///   exact path limit (4094 UTF-8 bytes with the current SDK), reserving
317    ///   at least 20 digits per index token. The SDK is not called.
318    /// * [`Error::Io`] when the directory of the file the pattern names
319    ///   does not exist or cannot be written to, the filesystem rejects the
320    ///   candidate path, or an exact file name exists (kind
321    ///   [`AlreadyExists`](std::io::ErrorKind::AlreadyExists)). The SDK is not called.
322    ///   On Windows, also reports security queries that could not be completed.
323    /// * [`Error::NativeOperationFailed`] when the SDK cannot start the source
324    ///   or open the first file. `Processing.NDI.Lib.File.Recorder.h` specifies
325    ///   an open-failed event for an output-file open failure; source-start
326    ///   failure need not queue one. [`next_event`](Self::next_event) can return
327    ///   that event, counted in no session's report. Retrying `start` discards
328    ///   queued events before asking the SDK to start again.
329    #[doc(alias = "NDIlib_file_recorder_start")]
330    #[doc(alias = "NDIlib_file_recorder_start_with_timecode")]
331    pub fn start(&mut self, target: &RecordingTarget, timecode: RecordingTimecode) -> Result<u64> {
332        self.start_with_sink(target, timecode, None)
333    }
334
335    pub(super) fn start_with_sink(
336        &mut self,
337        target: &RecordingTarget,
338        timecode: RecordingTimecode,
339        sink: RecorderEventSink<'_>,
340    ) -> Result<u64> {
341        self.ledger.admit_start()?;
342        self.naming.check(target)?;
343        // Events left over from an earlier session must not be counted in this one.
344        self.discard_stale_events(sink)?;
345        // Both sessions share this boundary so a counter increase cannot
346        // fall between the prior ledger's check and the new ledger's baseline.
347        let dropped_at_boundary = self.dropped_event_count();
348        self.ledger.dropped(dropped_at_boundary);
349        self.ledger.admit_start()?;
350        let session = self
351            .ledger
352            .session_number()
353            .checked_add(1)
354            .ok_or(Error::InvalidInput(
355                crate::InputDefect::SessionCounterExhausted,
356            ))?;
357        self.native.start(target, timecode)?;
358        self.ledger = Ledger::session(
359            session,
360            dropped_at_boundary,
361            self.tracks.contains(MediaTypes::VIDEO) || self.tracks.contains(MediaTypes::AUDIO),
362        );
363        Ok(session)
364    }
365
366    /// Take events until the queue is empty, so that none from an earlier
367    /// session is attributed to the next one.
368    fn discard_stale_events(&mut self, sink: RecorderEventSink<'_>) -> Result<()> {
369        let mut budget = DrainBudget::late();
370        loop {
371            match self.pump(&mut budget, Duration::ZERO, sink) {
372                Pumped::Empty { .. } => return Ok(()),
373                Pumped::Exhausted => {
374                    return Err(Error::InvalidState(StateConflict::EarlierSessionEvents));
375                }
376                Pumped::Took { .. } => {}
377            }
378        }
379    }
380
381    /// Ask the SDK to stop the session. Idempotent.
382    ///
383    /// The SDK then finalizes the open file and reports it closed; this call
384    /// alone does not show that it has. Use [`finish`](Self::finish) or
385    /// [`wait_for_finish`](Self::wait_for_finish) to find out.
386    #[doc(alias = "NDIlib_file_recorder_stop")]
387    pub fn request_stop(&mut self) -> StopRequest {
388        match self.state() {
389            RecorderState::Idle => StopRequest::NotStarted,
390            RecorderState::Closed => StopRequest::AlreadyClosed,
391            RecorderState::Indeterminate => StopRequest::AlreadyEnded,
392            RecorderState::Stopping => StopRequest::AlreadyStopping,
393            RecorderState::Recording => {
394                let still_recording = self.is_recording();
395                self.native
396                    .apply(self.ledger.stop_requested(still_recording));
397                StopRequest::Requested
398            }
399        }
400    }
401
402    /// Take the next queued event, waiting up to `timeout` for one, or
403    /// `None` when none arrives in time.
404    ///
405    /// The event's effect on the session is recorded before it is returned,
406    /// including when the event itself is malformed.
407    ///
408    /// # Errors
409    ///
410    /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`],
411    /// and [`Error::UnexpectedSdkResult`] when the SDK's event does not match
412    /// this crate's structure layout or its returned event type. An unreadable
413    /// format is withheld through [`RecorderEvent::source_format`] while the
414    /// rest of the event is delivered.
415    #[doc(alias = "NDIlib_file_recorder_capture_event")]
416    pub fn next_event(&mut self, timeout: Duration) -> Result<Option<RecorderEvent>> {
417        let captured = Cell::new(None);
418        self.poll_event_ms(
419            crate::to_ms_checked(timeout)?,
420            Some(&|event| captured.set(Some(event))),
421        );
422        captured.into_inner().transpose()
423    }
424
425    /// Observe one native capture. Return true only if the queue was empty.
426    fn poll_event_ms(&mut self, wait_ms: u32, sink: RecorderEventSink<'_>) -> bool {
427        let event = self.native.capture(wait_ms);
428        if self.ledger.cleanup_pending()
429            || (self.ledger.tracker().is_some() && !matches!(&event, Ok(None)))
430        {
431            self.ledger.dropped(self.dropped_event_count());
432        }
433        let event = match event {
434            Ok(Some(ref event)) => event,
435            Ok(None) => {
436                // Query recording only when the closed or incomplete file set
437                // can end the session. This relies on open-before-close rollover
438                // events, pinned by `rollovers_open_the_next_file_before_closing_the_previous_file`.
439                let transition = self.ledger.drained(|| self.native.is_recording());
440                self.native.apply(transition);
441                return true;
442            }
443            Err(error) => {
444                self.ledger.mark_uncertain();
445                if let Some(sink) = sink {
446                    sink(Err(error));
447                }
448                return false;
449            }
450        };
451        let kind = RecorderEventKind::from_raw(event.type_);
452        let path = LazyCell::new(|| EventTextRef::from_buffer(&event.p_path));
453        self.native
454            .apply(self.ledger.observe_with_path(kind, || *path));
455        // Decode after updating the ledger, so that a malformed format
456        // cannot hide the event that closes a file.
457        if let Some(sink) = sink {
458            sink(Ok(RecorderEvent::from_sdk(event, kind, *path)));
459        }
460        false
461    }
462
463    /// Stop the session and wait up to `timeout` for its last file to be
464    /// closed.
465    ///
466    /// Events that arrive during the wait are consumed; their effect is in
467    /// the returned report. A malformed event is consumed too: what it showed
468    /// about the session is recorded as [`next_event`](Self::next_event)
469    /// records it, and the wait goes on. One that could not be read at all
470    /// makes the outcome [`SessionEnd::Indeterminate`] rather than an error.
471    ///
472    /// The wait starts once the stop has returned, and covers taking the
473    /// closure's event, not the stop itself, which the SDK may carry out
474    /// before it returns. Events already queued are taken even when the wait
475    /// is over, so `finish(Duration::ZERO)` reports [`SessionEnd::Closed`]
476    /// when the SDK finalized the file during the stop.
477    ///
478    /// # Errors
479    ///
480    /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`],
481    /// without requesting the stop, and [`Error::InvalidState`] with
482    /// [`StateConflict::StopNotRequested`] when no session was started. Neither
483    /// is returned once the wait has begun: whatever the SDK's events hold,
484    /// the outcome is a [`FinishStatus`].
485    #[doc(alias = "NDIlib_file_recorder_stop")]
486    #[doc(alias = "NDIlib_file_recorder_capture_event")]
487    pub fn finish(&mut self, timeout: Duration) -> Result<FinishStatus> {
488        // Checked here, so that a timeout out of range leaves the session
489        // recording; the wait driver's budget starts only after the stop.
490        let timeout = Timeout::new(timeout)?;
491        self.request_stop();
492        // Synchronous finish's documented event-wait budget begins after
493        // the native stop returns. The checked duration survives that call.
494        self.wait_until(Deadline::starting(Instant::now(), timeout)?)
495    }
496
497    /// Wait up to `timeout` for a stopping session to end.
498    ///
499    /// Returns `None` when the timeout expires, and `Some` with
500    /// [`SessionEnd::Closed`] or [`SessionEnd::Indeterminate`] when the
501    /// session ends. A timeout retains the session's report in
502    /// [`report`](Self::report), and another wait can continue observing it.
503    ///
504    /// Use this to keep waiting after `finish` returns [`FinishStatus::TimedOut`].
505    /// Events already queued are taken even when `timeout` is over, so a closure
506    /// that has been reported is never missed. Malformed events are taken and
507    /// recorded as [`finish`](Self::finish) describes, without ending the
508    /// wait.
509    ///
510    /// # Errors
511    ///
512    /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`],
513    /// and [`Error::InvalidState`] with
514    /// [`StateConflict::StopNotRequested`] when no session was started or the
515    /// session has not been asked to stop. Neither is returned once the wait
516    /// has begun.
517    #[doc(alias = "NDIlib_file_recorder_capture_event")]
518    pub fn wait_for_finish(&mut self, timeout: Duration) -> Result<Option<SessionEnd>> {
519        self.settle_until(Deadline::after(timeout)?)
520            .map(WaitOutcome::into_end)
521    }
522
523    pub(super) fn wait_until(&mut self, deadline: Deadline) -> Result<FinishStatus> {
524        self.settle_until(deadline).map(WaitOutcome::into_finish)
525    }
526
527    fn settle_until(&mut self, deadline: Deadline) -> Result<WaitOutcome> {
528        self.check_wait()?;
529        let result = std::cell::RefCell::new(None);
530        let mut waiters = FinishWaiters::new();
531        waiters.register(self, deadline, LocalFinish(&result));
532        let mut budget = DrainBudget::new(deadline);
533        loop {
534            // A synchronous caller already has this final ledger. Preserve
535            // its queued events for next_event rather than draining again.
536            if let Some(outcome) = self.settle_wait(None) {
537                return Ok(outcome);
538            }
539            waiters.settle_at(
540                self,
541                Settlement {
542                    cleanup_expired: false,
543                    at: Instant::now(),
544                },
545                None,
546                || false,
547                Some(&mut budget),
548            );
549            if let Some(result) = result.borrow_mut().take() {
550                return result;
551            }
552            let step = if self.ledger.all_closed() {
553                SETTLE_POLL
554            } else {
555                FINISH_POLL
556            };
557            self.pump(&mut budget, step, None);
558        }
559    }
560
561    pub(super) fn check_wait(&self) -> Result<()> {
562        if matches!(self.state(), RecorderState::Idle | RecorderState::Recording) {
563            Err(Error::InvalidState(StateConflict::StopNotRequested))
564        } else {
565            Ok(())
566        }
567    }
568
569    fn settle_wait(&self, late: Option<&LateDrain>) -> Option<WaitOutcome> {
570        self.ledger.settle(late)
571    }
572
573    /// Share abandon's cleanup policy with the async owner's shutdown driver.
574    pub(super) fn skip_cleanup(&mut self) {
575        self.cleanup = None;
576    }
577
578    /// Start cleanup once, retaining an async close's original submission time.
579    fn begin_cleanup(&mut self, requested: Instant) -> DrainBudget {
580        DrainBudget::cleanup(self.cleanup.take(), requested)
581    }
582
583    pub(super) fn cleanup_pending(&self) -> bool {
584        self.ledger.cleanup_pending()
585    }
586
587    /// Poll once through the shared deadline/drain rule and publish its event.
588    fn pump(
589        &mut self,
590        budget: &mut DrainBudget,
591        step: Duration,
592        sink: RecorderEventSink<'_>,
593    ) -> Pumped {
594        budget.poll(step, |wait| self.poll_event_ms(wait, sink))
595    }
596
597    /// Drop and async close share the same cleanup driver, including the
598    /// waiters' polls: a final drain spends this recorder's budget only once.
599    pub(super) fn drain_cleanup<R: FinishReply>(
600        &mut self,
601        requested: Instant,
602        waiters: &mut FinishWaiters<R>,
603        queued: impl IntoIterator<Item = (Deadline, R)>,
604        tick: Duration,
605        sink: RecorderEventSink<'_>,
606        closing: impl Fn() -> CleanupRequest,
607    ) {
608        if matches!(closing(), CleanupRequest::Abandon) {
609            self.skip_cleanup();
610        }
611        let mut budget = self.begin_cleanup(requested);
612        self.request_stop();
613        for (deadline, reply) in queued {
614            waiters.register(self, deadline, reply);
615        }
616        waiters.retain();
617        while self.cleanup_pending() || !waiters.is_empty() {
618            if matches!(closing(), CleanupRequest::Abandon) {
619                // A close may already be draining when abandon is submitted.
620                // Stop spending its remaining budget before the next native
621                // poll. An in-progress native call itself is not interruptible.
622                budget = DrainBudget::Spent;
623            }
624            let polled = self.pump(&mut budget, waiters.wait_timeout(tick), sink);
625            waiters.settle_at(
626                self,
627                Settlement {
628                    cleanup_expired: polled.expired(),
629                    at: Instant::now(),
630                },
631                sink,
632                || !matches!(closing(), CleanupRequest::Drop),
633                Some(&mut budget),
634            );
635            if matches!(budget, DrainBudget::Spent) {
636                break;
637            }
638        }
639        debug_invariant!(waiters.is_empty(), "a completed drain settles every waiter");
640    }
641
642    /// Stop and destroy the recorder at once, without waiting for the SDK to
643    /// finalize an open file, and return what was known about the session.
644    ///
645    /// The file of a session that had not ended may be left truncated.
646    #[doc(alias = "NDIlib_file_recorder_destroy")]
647    pub fn abandon(mut self) -> RecordingReport {
648        self.skip_cleanup();
649        self.report()
650    }
651
652    /// Abandon this native recorder and replace it with a new idle recorder.
653    ///
654    /// Use this after a finalization timeout when the SDK stopped producing
655    /// events, or to recover from [`StateConflict::IncompleteFileTracking`].
656    /// The returned report preserves what was known about the old session.
657    /// An unfinished file can be left truncated.
658    /// The replacement has its own event queue, so delayed events from the old
659    /// session cannot affect a new recording. The last report is retained and
660    /// session numbers continue increasing across resets.
661    ///
662    /// The replacement is created first. If creation fails, this recorder and
663    /// its report are kept and can still be polled or finalized. The options
664    /// are only read, as by [`FileRecorder::new`].
665    ///
666    /// # Errors
667    ///
668    /// The errors of [`FileRecorder::new`].
669    #[doc(alias = "NDIlib_file_recorder_destroy")]
670    #[doc(alias = "NDIlib_file_recorder_create")]
671    pub fn reset(&mut self, options: &FileRecorderOptions) -> Result<RecordingReport> {
672        self.reset_with(|recorder| {
673            PreparedRecorder {
674                recording: recorder.native.recording(),
675                options: options.check()?,
676            }
677            .create()
678        })
679    }
680
681    pub(super) fn reset_checked(
682        &mut self,
683        options: CheckedRecorderOptions,
684    ) -> Result<RecordingReport> {
685        self.reset_with(|recorder| {
686            PreparedRecorder {
687                recording: recorder.native.recording(),
688                options,
689            }
690            .create()
691        })
692    }
693
694    fn reset_with(
695        &mut self,
696        create: impl FnOnce(&Self) -> Result<Self>,
697    ) -> Result<RecordingReport> {
698        let generation = self.generation.checked_add(1).ok_or(Error::InvalidInput(
699            crate::InputDefect::RecorderGenerationExhausted,
700        ))?;
701        let mut replacement = create(self)?;
702        replacement.generation = generation;
703        replacement.ledger = Ledger::inheriting(self.report());
704        Ok(std::mem::replace(self, replacement).abandon())
705    }
706
707    /// Whether the SDK is recording or waiting for frames. False once a stop
708    /// has taken effect; this alone does not show that a file was finalized.
709    #[doc(alias = "NDIlib_file_recorder_is_recording")]
710    pub fn is_recording(&self) -> bool {
711        self.native.is_recording()
712    }
713
714    /// How many events the SDK has discarded since the recorder was created
715    /// because they were not taken in time.
716    #[doc(alias = "NDIlib_file_recorder_get_dropped_event_count")]
717    pub fn dropped_event_count(&self) -> u64 {
718        self.native.dropped_event_count()
719    }
720
721    /// Switch to recording another source.
722    ///
723    /// During a session the SDK starts the new source at once and rolls over
724    /// to a new file, named from the session's current target. Before a
725    /// session, the source is used by the next [`start`](Self::start).
726    ///
727    /// A recorder with an exact file name
728    /// ([`FileNaming::Exact`](super::FileNaming::Exact), or a
729    /// [`FileNaming::Pattern`](super::FileNaming::Pattern) without `{index}`)
730    /// cannot roll over to a file of the same name, and the SDK would end the
731    /// session instead, so it refuses a change of source during a session
732    /// and the session goes on. Before a session the change works as for any
733    /// recorder.
734    ///
735    /// The source stays with the caller; the recorder keeps a copy of it
736    /// when the SDK accepts it, for
737    /// [`last_accepted_source`](Self::last_accepted_source).
738    ///
739    /// # Errors
740    ///
741    /// * [`Error::InvalidState`] with [`StateConflict::ExactFileName`]
742    ///   during a session, recording or stopping, of a recorder with an exact
743    ///   file name, and with [`StateConflict::Stopping`] while any other
744    ///   recorder's session is stopping. The SDK is not called.
745    /// * [`Error::NativeOperationFailed`] when the SDK cannot start the source. The
746    ///   SDK does not say which source is then in effect, so
747    ///   [`last_accepted_source`](Self::last_accepted_source) returns `None`
748    ///   until a later change succeeds.
749    #[doc(alias = "NDIlib_file_recorder_set_source")]
750    pub fn set_source(&mut self, source: &SourceSpec) -> Result<()> {
751        if self.naming.is_exact() && self.ledger.session_open() {
752            return Err(Error::InvalidState(StateConflict::ExactFileName));
753        }
754        if self.state() == RecorderState::Stopping {
755            return Err(Error::InvalidState(StateConflict::Stopping));
756        }
757        let accepted = self.native.set_source(source);
758        // Kept only once accepted: the copy is what the recorder retains.
759        self.accepted_source = accepted.is_ok().then(|| source.clone());
760        accepted
761    }
762
763    /// The source the SDK accepted last: the one given at creation, or by the
764    /// last successful [`set_source`](Self::set_source).
765    ///
766    /// `None` after a rejected change, because the SDK does not say which
767    /// source is then in effect. This is what was requested, not a statement
768    /// that the source is connected.
769    pub fn last_accepted_source(&self) -> Option<&SourceSpec> {
770        self.accepted_source.as_ref()
771    }
772
773    /// The most recently opened file still retained in the file tracker.
774    ///
775    /// The path is as the SDK gave it, and can lag events not yet taken. Once
776    /// tracking is incomplete, later opens are not retained; consume
777    /// [`next_event`](Self::next_event) for their paths. `None` does not prove
778    /// that no files remain open.
779    pub fn reported_current_file(&self) -> Option<&EventText> {
780        self.ledger.tracker().and_then(FileTracker::current)
781    }
782
783    /// Close the current file and continue the session in a new one named
784    /// from `target`.
785    ///
786    /// For compressed video the SDK makes the cut at the next keyframe, so the
787    /// new file starts decodable. A rollover that has not happened by the time
788    /// the session stops is dropped.
789    ///
790    /// The SDK accepts a rollover it then cannot carry out, and ends the
791    /// session when the new file cannot be opened: it reports open-failed,
792    /// closes the old file and reports an error. The file the pattern names
793    /// for the target is therefore checked first. Its directory must exist
794    /// and be writable, the filesystem must accept the candidate path, and
795    /// an exact file name must be available.
796    /// The usual mistakes then leave the session running, and the target,
797    /// which is only read, stays with the caller to correct and try again.
798    /// The preflight is not a reservation: a path created after it can make
799    /// the later native open fail and end the session even after this method
800    /// returns `Ok(())`. Observe open-failed/error events and the final
801    /// [`RecordingReport`]. The exclusive-creation behavior tested on Linux
802    /// File SDK 6.4.0.2 preserves colliding regular files and symlinks; other
803    /// platforms and SDK releases have not been verified. A
804    /// recorder-controlled output directory avoids this race with other writers.
805    ///
806    /// # Errors
807    ///
808    /// * [`Error::InvalidState`] with [`StateConflict::NotRecording`] unless
809    ///   a session is recording.
810    /// * [`Error::InvalidInput`] when the expanded output path is relative,
811    ///   has no file name, or its longest form exceeds the recorder event's
812    ///   exact path limit (4094 UTF-8 bytes with the current SDK), reserving
813    ///   at least 20 digits per index token. The SDK is not called and the
814    ///   session goes on.
815    /// * [`Error::Io`] when the directory of the file the pattern names
816    ///   does not exist or cannot be written to, the filesystem rejects the
817    ///   candidate path, or an exact file name exists (kind
818    ///   [`AlreadyExists`](std::io::ErrorKind::AlreadyExists)).
819    ///   The SDK is not called and the session goes on.
820    ///   On Windows, also reports security queries that could not be completed.
821    /// * [`Error::NativeOperationFailed`] when the SDK refuses the target.
822    #[doc(alias = "NDIlib_file_recorder_rollover")]
823    pub fn rollover(&mut self, target: &RecordingTarget) -> Result<()> {
824        if self.state() != RecorderState::Recording {
825            return Err(Error::InvalidState(StateConflict::NotRecording));
826        }
827        self.naming.check(target)?;
828        self.native.rollover(target)
829    }
830
831    /// Write a metadata frame into the recording at its current position.
832    ///
833    /// The frame's timecode is stored and re-published on playback; it does
834    /// not move the frame on the file's timeline. The frame's text is handed
835    /// to the SDK as it is, without a wrapper copy. Owned and captured
836    /// metadata are accepted, and need only outlive this synchronous call.
837    ///
838    /// # Errors
839    ///
840    /// [`Error::InvalidState`] with [`StateConflict::NotRecording`] unless a
841    /// session is recording, and [`Error::NativeOperationFailed`] when the
842    /// SDK refuses it, for example because the metadata track is not being
843    /// recorded.
844    #[doc(alias = "NDIlib_file_recorder_inject_metadata")]
845    pub fn inject_metadata<S: MetadataSource + ?Sized>(&mut self, metadata: &S) -> Result<()> {
846        if self.state() != RecorderState::Recording {
847            return Err(Error::InvalidState(StateConflict::NotRecording));
848        }
849        self.native.inject_metadata(metadata)
850    }
851
852    /// The recorder's running counters, when the SDK has any.
853    /// Interpret these with the recorder session state and events; they do
854    /// not use receiver drop-percentage semantics.
855    ///
856    /// # Errors
857    ///
858    /// [`Error::UnexpectedSdkResult`] when the SDK's structure does not match this
859    /// crate's layout.
860    #[doc(alias = "NDIlib_file_recorder_get_stats")]
861    pub fn stats(&self) -> Result<Option<RecorderStats>> {
862        self.native.stats()
863    }
864
865    /// The format of the source, once the recorder has seen audio or video.
866    ///
867    /// # Errors
868    ///
869    /// [`Error::UnexpectedSdkResult`] when the SDK's structure is malformed.
870    #[doc(alias = "NDIlib_file_recorder_get_source_format")]
871    pub fn source_format(&self) -> Result<Option<SourceFormat>> {
872        self.native.source_format()
873    }
874}
875
876impl Drop for FileRecorder {
877    fn drop(&mut self) {
878        // The SDK finalizes a file between the stop request and the
879        // file-closed event; destroying sooner may truncate it.
880        if self.ledger.cleanup_pending() {
881            self.drain_cleanup(
882                Instant::now(),
883                &mut FinishWaiters::<LocalFinish<'_>>::new(),
884                std::iter::empty(),
885                FINISH_POLL,
886                None,
887                || CleanupRequest::Drop,
888            );
889        }
890    }
891}
892
893#[cfg(test)]
894#[path = "drain_budget_tests.rs"]
895mod drain_budget_tests;
896
897#[cfg(ndi_test_file_late_drain)]
898#[path = "../../tests/ui/internal/file_late_drain.rs"]
899mod late_drain_contract;
900
901#[cfg(any(ndi_test_file_proofs, ndi_test_file_proofs_discarded))]
902#[path = "../../tests/ui/internal/file_proofs.rs"]
903mod file_proof_contract;