Skip to main content

grafton_ndi/file/
types.rs

1//! Owned configuration, event and format values for the File API.
2
3use std::{
4    borrow::Cow,
5    ffi::{c_char, CString},
6    path::{Path, PathBuf},
7    time::Duration,
8};
9
10use crate::{
11    finder::SourceName,
12    sys::{self, bindings::*},
13    Error, FourCc, FrameRate, MediaTypes, PictureAspectRatio, Result, ScanType, SdkResultDefect,
14    StreamTier, Timecode,
15};
16
17/// Why an operation is not permitted in the current state, carried by
18/// [`Error::InvalidState`].
19///
20/// Its `Display` text describes the state for diagnostics; match on the
21/// variant rather than the text.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
23#[non_exhaustive]
24pub enum StateConflict {
25    /// A session is recording or stopping, or a known file awaits closure
26    /// under complete tracking. Finish or poll it before starting another.
27    #[error("finish the previous session before starting another")]
28    PreviousSessionOpen,
29    /// The session ended with incomplete file tracking after native event
30    /// loss, unreadable lifecycle evidence or a tracking limit. Even after
31    /// every known file closes, unknown files may still be open and cleanup
32    /// uses the remaining [`FileRecorderOptions::drop_wait`] budget. Later
33    /// events do not change the indeterminate report. Start another session
34    /// only after a successful [`FileRecorder::reset`](super::FileRecorder::reset)
35    /// replaces the recorder. A failed reset preserves the recorder and its
36    /// cleanup obligation. Eviction from the async application event queue
37    /// does not affect native file tracking.
38    #[error("file tracking is incomplete; reset the recorder before starting another session")]
39    IncompleteFileTracking,
40    /// Events from an earlier session kept arriving, so a new session was not
41    /// started.
42    #[error("the recorder keeps producing events from an earlier session")]
43    EarlierSessionEvents,
44    /// Waiting for a session to end needs a session that has been asked to
45    /// stop, or that the SDK is ending.
46    #[error("request a stop before waiting for the session to end")]
47    StopNotRequested,
48    /// The session is stopping.
49    #[error("the session is stopping")]
50    Stopping,
51    /// The operation needs a session that is recording.
52    #[error("the operation needs a session that is recording")]
53    NotRecording,
54    /// The recorder names its files exactly, so it cannot switch to a new file
55    /// during a session: the next file would have the same name. Use a
56    /// filename pattern with `{index}`.
57    #[error("a recorder with an exact file name cannot switch to a new file during a session")]
58    ExactFileName,
59    /// Another event future is already waiting on the async handle, which
60    /// delivers each event to one waiter. A close never reports this: closes
61    /// made while one is awaited complete with it.
62    #[error("another File event waiter is already pending")]
63    WaiterPending,
64    /// The async handle's object has been closed, or its thread stopped
65    /// normally before it carried out the operation. A thread that failed
66    /// reports [`OwnerFailed`](Self::OwnerFailed) instead.
67    /// Also returned by an in-flight async finish or wait when a concurrent
68    /// close's remaining finalization budget ends without a settled outcome.
69    #[error("File owner has closed")]
70    Closed,
71    /// The async handle's thread failed, for example by panicking. The
72    /// operation it was running, every command queued behind it, every later
73    /// command, every event wait and the close report this, not
74    /// [`Closed`](Self::Closed).
75    #[error("File owner thread failed")]
76    OwnerFailed,
77}
78
79impl StateConflict {
80    /// Whether the same call can succeed later without anything else changing
81    /// on this handle: true only for [`WaiterPending`](Self::WaiterPending),
82    /// once the other waiter has finished. A full command queue, which can
83    /// also succeed later, is [`Error::QueueFull`](crate::Error::QueueFull).
84    ///
85    /// The other states change only through another call, such as finishing a
86    /// session, or never, for a handle that is closed.
87    pub fn is_retryable(self) -> bool {
88        matches!(self, Self::WaiterPending)
89    }
90}
91
92/// UTF-8 text whose only NUL is its final byte, proven at construction.
93#[derive(Clone, PartialEq, Eq, Hash)]
94pub(super) struct FileText(Box<str>);
95
96impl FileText {
97    fn new(value: &str, what: &'static str) -> Result<Self> {
98        if value.is_empty() {
99            return Err(Error::InvalidInput(crate::InputDefect::Empty { what }));
100        }
101        let bytes = CString::new(value)?.into_bytes_with_nul();
102        // SAFETY: CString preserves the bytes of the UTF-8 input, adding only
103        // its ASCII NUL terminator.
104        Ok(Self(
105            unsafe { String::from_utf8_unchecked(bytes) }.into_boxed_str(),
106        ))
107    }
108
109    // Only constructors that proved the text nonempty and NUL-free call this.
110    fn from_checked(value: &str) -> Self {
111        let mut text = String::with_capacity(value.len() + 1);
112        text.push_str(value);
113        text.push('\0');
114        Self(text.into_boxed_str())
115    }
116
117    pub(super) fn as_str(&self) -> &str {
118        &self.0[..self.0.len() - 1]
119    }
120
121    pub(super) fn as_ptr(&self) -> *const c_char {
122        self.0.as_ptr().cast()
123    }
124}
125
126impl std::fmt::Debug for FileText {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        self.as_str().fmt(f)
129    }
130}
131
132/// An owned source name or direct URL used by a recorder.
133///
134/// Name and URL constructors are separate because the SDK gives a nonempty name
135/// precedence over a URL. Converting a discovered [`crate::Source`] pins its
136/// supplied endpoint, falling back to its name only when no address is present.
137/// Endpoint pinning can become stale; [`Self::new`] deliberately selects by name
138/// so the SDK can rediscover an endpoint after it changes. Neither policy silently
139/// falls back to the other after a connection failure. No discovery or SDK call
140/// occurs while constructing this value; constructors allocate one C string.
141#[derive(Debug, Clone, PartialEq, Eq, Hash)]
142pub struct SourceSpec {
143    selection: SourceSelection,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq, Hash)]
147enum SourceSelection {
148    Name(FileText),
149    Url(FileText),
150}
151
152impl SourceSpec {
153    /// Select a source by its NDI name, for example `"MACHINE (Camera 1)"`.
154    ///
155    /// # Errors
156    ///
157    /// [`Error::InvalidInput`] when the name is empty, and
158    /// [`Error::InvalidCString`] when it contains a NUL. For this error,
159    /// [`NulError::into_vec`](std::ffi::NulError::into_vec) returns the bytes
160    /// through the first NUL.
161    pub fn new(name: impl AsRef<str>) -> Result<Self> {
162        let name = SourceName::checked(name.as_ref())?;
163        Ok(Self {
164            selection: SourceSelection::Name(FileText::from_checked(name.as_str())),
165        })
166    }
167
168    /// Select a source by its address, for example `"192.168.1.20:5961"`,
169    /// without discovering it by name.
170    ///
171    /// # Errors
172    ///
173    /// [`Error::InvalidInput`] when the address is empty, and
174    /// [`Error::InvalidCString`] when it contains a NUL.
175    pub fn from_url(url: impl AsRef<str>) -> Result<Self> {
176        Ok(Self {
177            selection: SourceSelection::Url(FileText::new(url.as_ref(), "source URL")?),
178        })
179    }
180
181    /// The requested display name, when selecting by name.
182    pub fn name(&self) -> Option<&str> {
183        match &self.selection {
184            SourceSelection::Name(name) => Some(name.as_str()),
185            SourceSelection::Url(_) => None,
186        }
187    }
188
189    /// The requested URL/address, when selecting directly.
190    pub fn url(&self) -> Option<&str> {
191        match &self.selection {
192            SourceSelection::Name(_) => None,
193            SourceSelection::Url(url) => Some(url.as_str()),
194        }
195    }
196
197    /// The native descriptor borrows the selected C string from `self`.
198    pub(super) fn raw_source(&self) -> NDIlib_file_recorder_source_t {
199        let (name, url) = match &self.selection {
200            SourceSelection::Name(name) => (name.as_ptr(), std::ptr::null()),
201            SourceSelection::Url(url) => (std::ptr::null(), url.as_ptr()),
202        };
203        NDIlib_file_recorder_source_t {
204            p_ndi_name: name,
205            p_url_address: url,
206        }
207    }
208}
209
210impl TryFrom<&crate::Source> for SourceSpec {
211    type Error = Error;
212
213    fn try_from(source: &crate::Source) -> Result<Self> {
214        match source.address() {
215            Some(address) => Self::from_url(address.as_str()),
216            None => Self::new(source.name()),
217        }
218    }
219}
220
221/// How a player advertises its NDI source. Creating this value advertises
222/// nothing.
223///
224/// The options are checked when a player is created from them, by
225/// [`FilePlayer::new`](super::FilePlayer::new) or
226/// [`AsyncFilePlayer::create`](super::AsyncFilePlayer::create): the name must
227/// not be empty or contain a NUL. Each group must be nonempty and contain
228/// neither a comma nor a NUL.
229#[derive(Debug, Clone, PartialEq, Eq, Hash)]
230pub struct FilePlayerOptions {
231    pub(super) name: String,
232    groups: Option<Vec<String>>,
233}
234
235impl FilePlayerOptions {
236    /// Replace the advertised player name, preserving every other setting.
237    #[must_use]
238    pub fn name(mut self, name: impl Into<String>) -> Self {
239        self.name = name.into();
240        self
241    }
242
243    /// Inherit discovery groups from the NDI configuration.
244    #[must_use]
245    pub fn clear_groups(mut self) -> Self {
246        self.groups = None;
247        self
248    }
249
250    /// Requested advertised player name.
251    #[must_use]
252    pub fn configured_name(&self) -> &str {
253        &self.name
254    }
255
256    /// Requested discovery groups, or `None` to inherit the NDI configuration.
257    #[must_use]
258    pub fn configured_groups(&self) -> Option<&[String]> {
259        self.groups.as_deref()
260    }
261
262    /// A player that advertises its source as `name`, in the groups of the
263    /// NDI configuration.
264    pub fn new(name: impl Into<String>) -> Self {
265        Self {
266            name: name.into(),
267            groups: None,
268        }
269    }
270
271    /// Set a non-empty list of NDI groups the player's source is advertised in,
272    /// replacing the NDI configuration. Use [`Self::clear_groups`] to inherit
273    /// the configuration.
274    /// Each group is checked when the player is created: it must be nonempty
275    /// and contain neither a comma nor a NUL.
276    #[must_use]
277    pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
278        self.groups = Some(groups.into_iter().map(Into::into).collect());
279        self
280    }
281
282    /// Check the options and convert their strings for the SDK.
283    ///
284    /// # Errors
285    ///
286    /// [`Error::InvalidInput`] when the name or group list is empty, or a group
287    /// is empty or contains a comma or NUL. [`Error::InvalidCString`] when the name
288    /// contains a NUL.
289    pub(super) fn resolve(&self) -> Result<ResolvedPlayerOptions> {
290        Ok(ResolvedPlayerOptions {
291            name: FileText::new(&self.name, "player name")?,
292            groups: crate::list_setting::list_cstring(self.groups.as_deref(), "player groups")?,
293        })
294    }
295}
296
297/// A player's options, checked and converted for the SDK.
298#[derive(Debug)]
299pub(super) struct ResolvedPlayerOptions {
300    pub(super) name: FileText,
301    pub(super) groups: Option<CString>,
302}
303
304/// How a recorder names the files of a session from its [`RecordingTarget`].
305///
306/// The directory the name leads to must exist and be writable. See
307/// [`Self::Exact`] for the tested exclusive-open behavior and the limits of
308/// preflight.
309///
310/// The expanded filename must be absolute. It must fit exactly in the
311/// recorder's event field, at most 4094 UTF-8 bytes with the current SDK.
312/// Preflight counts the spelling the SDK will use, including redundant
313/// separators and `.` components, and reserves at least 20 digits for each
314/// index token to cover future rollovers. Start and rollover refuse relative
315/// or oversized filenames with [`Error::InvalidInput`].
316///
317/// Preflight checks the exact filename or the first indexed candidate against
318/// the destination filesystem. If later indexes can add digits, it also checks
319/// a candidate with the maximum index width. Start and rollover return
320/// [`Error::Io`] if the widest basename exceeds a filesystem limit, even
321/// when the first candidate fits. Shorten the basename prefix or remove a
322/// repeated index token to fit the limit.
323#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
324#[non_exhaustive]
325pub enum FileNaming {
326    /// Name each file exactly as its [`RecordingTarget`] says, with no index.
327    ///
328    /// [`FileRecorder::start`] and [`FileRecorder::rollover`] refuse a target
329    /// that already exists with an [`Error::Io`] of kind
330    /// [`AlreadyExists`](std::io::ErrorKind::AlreadyExists), before the SDK is
331    /// called.
332    /// This preflight does not reserve the path. A collision created after
333    /// the check is handled by the native library; a rollover may return
334    /// success before its later open fails and stops the session. Linux File
335    /// SDK 6.4.0.2 uses exclusive creation and preserves existing files,
336    /// including symlinks, in this race. Other platforms and SDK releases
337    /// have not been verified. Use a recorder-controlled output directory
338    /// when uninterrupted recording or destination containment matters;
339    /// mutable parent directories are not pinned by this API.
340    ///
341    /// One target names one file, so a session cannot move to a new file by
342    /// itself:
343    ///
344    /// * a format change of the source closes the file and ends the session,
345    ///   which [`RecordingReport::stopped_by_sdk`] then reports; see
346    ///   [`FileRecorderOptions::format_change_rollover`];
347    /// * format-change rollover switched on, or a nonzero
348    ///   [`FileRecorderOptions::rollover_size`], is refused with
349    ///   [`Error::InvalidInput`] when the recorder is created;
350    /// * [`FileRecorder::set_source`] is refused during a session with
351    ///   [`StateConflict::ExactFileName`].
352    ///
353    /// [`FileRecorder::rollover`] to a new target still works. Use
354    /// [`Indexed`](Self::Indexed), or a [`Pattern`](Self::Pattern) with
355    /// `{index}`, for recordings that must survive these changes.
356    ///
357    /// [`FileRecorder::start`]: super::FileRecorder::start
358    /// [`FileRecorder::rollover`]: super::FileRecorder::rollover
359    /// [`FileRecorder::set_source`]: super::FileRecorder::set_source
360    /// [`RecordingReport::stopped_by_sdk`]: super::RecordingReport::stopped_by_sdk
361    Exact,
362    /// The SDK's indexed `{prefix}_{index:03}.mkv`: the target `take` becomes
363    /// `take_001.mkv`, and each new file of the session takes the lowest
364    /// unused index.
365    #[default]
366    Indexed,
367    /// A filename pattern using `{prefix}`, `{index}` and `{index:N}` tokens.
368    ///
369    /// `{prefix}` is replaced by the [`RecordingTarget`], and `{index:N}` pads
370    /// the index with zeros to `N` digits, from 1 through 1024. The pattern
371    /// may name a directory, for example `{prefix}/{index:03}.mkv`; that
372    /// directory must exist. Index tokens must be in the file name: directories
373    /// may come only from literal text and `{prefix}`. A pattern placing an
374    /// index in a directory is refused when the recorder is created.
375    ///
376    /// Use `{prefix}{index}.mkv` with `RecordingTarget::new("take")` to
377    /// write `take1.mkv` in the directory in effect when the target is built.
378    /// A pattern may also contain a literal absolute path.
379    ///
380    /// A pattern without `{index}` or `{index:N}` names its file exactly,
381    /// with every rule of [`Exact`](Self::Exact).
382    ///
383    /// A pattern that is empty, or has an unknown token or unbalanced braces,
384    /// is refused with [`Error::InvalidInput`] when the recorder is created,
385    /// and one that contains a NUL with [`Error::InvalidCString`].
386    Pattern(String),
387}
388
389/// Recorder configuration fixed when its native instance is created.
390///
391/// Nothing is checked until a recorder is created from the options, by
392/// [`FileRecorder::new`](super::FileRecorder::new),
393/// [`FileRecorder::reset`](super::FileRecorder::reset) or
394/// [`AsyncFileRecorder::create`](super::AsyncFileRecorder::create). The
395/// options are then checked against each other, so the order of the setter
396/// calls does not matter.
397#[derive(Debug, Clone, PartialEq, Eq, Hash)]
398pub struct FileRecorderOptions {
399    pub(super) source: SourceSpec,
400    pub(super) tracks: MediaTypes,
401    pub(super) planar_audio: bool,
402    /// `None` until set: on for indexed file names, off for exact ones.
403    format_change_rollover: Option<bool>,
404    naming: FileNaming,
405    pub(super) proxy: bool,
406    pub(super) rollover_size: u64,
407    pub(super) drop_wait: Duration,
408}
409
410impl FileRecorderOptions {
411    /// Replace the recording source, preserving every other setting.
412    #[must_use]
413    pub fn source(mut self, source: SourceSpec) -> Self {
414        self.source = source;
415        self
416    }
417
418    /// Derive format-change rollover from the final naming policy again.
419    #[must_use]
420    pub fn clear_format_change_rollover(mut self) -> Self {
421        self.format_change_rollover = None;
422        self
423    }
424
425    /// Requested source descriptor, before any live source change.
426    #[must_use]
427    pub fn configured_source(&self) -> &SourceSpec {
428        &self.source
429    }
430
431    /// Requested track types.
432    #[must_use]
433    pub fn configured_tracks(&self) -> MediaTypes {
434        self.tracks
435    }
436
437    /// Whether planar audio storage was requested.
438    #[must_use]
439    pub fn configured_planar_audio(&self) -> bool {
440        self.planar_audio
441    }
442
443    /// Explicit rollover choice, or `None` to derive it from the final naming policy at creation.
444    #[must_use]
445    pub fn configured_format_change_rollover(&self) -> Option<bool> {
446        self.format_change_rollover
447    }
448
449    /// Requested file naming policy.
450    #[must_use]
451    pub fn configured_naming(&self) -> &FileNaming {
452        &self.naming
453    }
454
455    /// Whether recording the proxy was requested.
456    #[must_use]
457    pub fn configured_proxy(&self) -> bool {
458        self.proxy
459    }
460
461    /// Requested soft rollover threshold in bytes; zero disables it.
462    #[must_use]
463    pub fn configured_rollover_size(&self) -> u64 {
464        self.rollover_size
465    }
466
467    /// Requested cleanup budget from drop or async close submission, including
468    /// the native stop.
469    #[must_use]
470    pub fn configured_drop_wait(&self) -> Duration {
471        self.drop_wait
472    }
473
474    /// Record every track of `source`, including its proxy when it has one,
475    /// in [`FileNaming::Indexed`] files.
476    pub fn new(source: SourceSpec) -> Self {
477        Self {
478            source,
479            tracks: MediaTypes::ALL,
480            planar_audio: false,
481            format_change_rollover: None,
482            naming: FileNaming::Indexed,
483            proxy: true,
484            rollover_size: 0,
485            drop_wait: Self::DEFAULT_DROP_WAIT,
486        }
487    }
488
489    /// Default cleanup budget from drop or async close submission, including
490    /// the native stop; [`drop_wait`](Self::drop_wait) overrides it.
491    pub const DEFAULT_DROP_WAIT: Duration = Duration::from_secs(5);
492
493    /// Set how long dropping the recorder waits for an unfinished session.
494    ///
495    /// The SDK finalizes a file between the stop request and its file-closed
496    /// event; destroying the recorder sooner may leave a truncated file. A
497    /// recorder dropped with a session still open requests the stop and waits
498    /// for closure within one `wait` budget, measured from drop or an async
499    /// close's submission and including the native stop. The native stop can
500    /// itself outlast that budget; only the remaining time is available for
501    /// closure events after it returns. Synchronous
502    /// [`FileRecorder::finish`](super::FileRecorder::finish) instead starts its
503    /// wait after the stop returns, giving closure its full requested wait.
504    /// Async close shares its budget with any finish or wait already submitted.
505    /// Cleanup can end early once there are no known files left to finalize,
506    /// subject to [`StateConflict::IncompleteFileTracking`]. `Duration::ZERO`
507    /// waits for no future events:
508    /// the stop is requested and a bounded nonblocking drain takes queued
509    /// events before destruction. [`FileRecorder::abandon`](super::FileRecorder::abandon)
510    /// takes no events.
511    ///
512    /// A wait longer than [`crate::MAX_TIMEOUT`] is refused with
513    /// [`Error::InvalidInput`] when the recorder is created.
514    #[must_use]
515    pub fn drop_wait(mut self, wait: Duration) -> Self {
516        self.drop_wait = wait;
517        self
518    }
519
520    /// Select which track types to record: all three unless this says
521    /// otherwise.
522    ///
523    /// An empty selection is refused with [`Error::InvalidInput`] when the
524    /// recorder is created, rather than meaning all tracks as it does to the
525    /// SDK.
526    #[must_use]
527    pub fn tracks(mut self, tracks: MediaTypes) -> Self {
528        self.tracks = tracks;
529        self
530    }
531
532    /// Store uncompressed float audio as native planar data when true.
533    ///
534    /// The default interleaved layout is more widely playable by third parties.
535    #[must_use]
536    pub fn planar_audio(mut self, planar: bool) -> Self {
537        self.planar_audio = planar;
538        self
539    }
540
541    /// Whether a change of the source's format closes the current file and
542    /// continues the session in a new one.
543    ///
544    /// Left unset, a format change rolls over to a new file when files are
545    /// indexed, and closes the file and ends the session when the file name
546    /// is exact, because a second file cannot take the same name. With
547    /// `false` a format change always ends the session. A session that ends
548    /// this way is reported by [`RecordingReport::stopped_by_sdk`].
549    ///
550    /// `true` cannot be combined with an exact file name
551    /// ([`FileNaming::Exact`], or a [`FileNaming::Pattern`] without
552    /// `{index}`): creating the recorder then fails with
553    /// [`Error::InvalidInput`].
554    /// Index tokens must remain in the file name, as [`FileNaming::Pattern`]
555    /// requires, so every rollover uses the directory checked at preflight.
556    ///
557    /// [`RecordingReport::stopped_by_sdk`]: super::RecordingReport::stopped_by_sdk
558    #[must_use]
559    pub fn format_change_rollover(mut self, enabled: bool) -> Self {
560        self.format_change_rollover = Some(enabled);
561        self
562    }
563
564    /// Whether to record the source's proxy alongside its full-quality video.
565    #[must_use]
566    pub fn proxy(mut self, enabled: bool) -> Self {
567        self.proxy = enabled;
568        self
569    }
570
571    /// Set a soft size threshold, in bytes, for keyframe-aligned rollover;
572    /// zero disables it.
573    ///
574    /// A nonzero size cannot be combined with an exact file name
575    /// ([`FileNaming::Exact`], or a [`FileNaming::Pattern`] without
576    /// `{index}`), because the next file would have the same name: creating
577    /// the recorder then fails with [`Error::InvalidInput`].
578    /// Index tokens must remain in the file name, as [`FileNaming::Pattern`]
579    /// requires, so every rollover uses the directory checked at preflight.
580    #[must_use]
581    pub fn rollover_size(mut self, bytes: u64) -> Self {
582        self.rollover_size = bytes;
583        self
584    }
585
586    /// Set how the recorder names its files: [`FileNaming::Indexed`] unless
587    /// this says otherwise.
588    #[must_use]
589    pub fn naming(mut self, naming: FileNaming) -> Self {
590        self.naming = naming;
591        self
592    }
593
594    /// Check the options and settle what they leave open.
595    ///
596    /// Done when a recorder is created rather than in the setters, so that
597    /// the order of those calls does not matter.
598    ///
599    /// # Errors
600    ///
601    /// [`Error::InvalidInput`] when the drop wait exceeds
602    /// [`crate::MAX_TIMEOUT`], the track selection is empty, the filename
603    /// pattern is malformed, or an exact file name is combined with a
604    /// rollover, and [`Error::InvalidCString`] when the filename pattern
605    /// contains a NUL.
606    pub(super) fn check(&self) -> Result<CheckedRecorderOptions> {
607        let drop_wait = crate::timeout::Timeout::new(self.drop_wait)?;
608        if self.tracks.is_empty() {
609            return Err(Error::InvalidInput(
610                crate::InputDefect::EmptyRecordingTracks,
611            ));
612        }
613        // The SDK is given no pattern for its own indexed default.
614        let naming = NamePattern::new(match &self.naming {
615            FileNaming::Exact => Some(EXACT_PATTERN),
616            FileNaming::Indexed => None,
617            FileNaming::Pattern(pattern) => Some(pattern.as_str()),
618        })?;
619        if naming.is_exact() {
620            if self.format_change_rollover == Some(true) {
621                return Err(Error::InvalidInput(
622                    crate::InputDefect::ExactNameFormatRollover,
623                ));
624            }
625            if self.rollover_size > 0 {
626                return Err(Error::InvalidInput(
627                    crate::InputDefect::ExactNameSizeRollover,
628                ));
629            }
630        }
631        Ok(CheckedRecorderOptions {
632            source: self.source.clone(),
633            tracks: self.tracks,
634            planar_audio: self.planar_audio,
635            proxy: self.proxy,
636            rollover_size: self.rollover_size,
637            drop_wait,
638            format_change_rollover: self.format_change_rollover.unwrap_or(!naming.is_exact()),
639            naming,
640        })
641    }
642}
643
644/// Every option needed for creation, retaining the validated naming pattern.
645#[derive(Debug)]
646pub(super) struct CheckedRecorderOptions {
647    pub(super) source: SourceSpec,
648    pub(super) tracks: MediaTypes,
649    pub(super) planar_audio: bool,
650    pub(super) proxy: bool,
651    pub(super) rollover_size: u64,
652    pub(super) drop_wait: crate::timeout::Timeout,
653    pub(super) naming: NamePattern,
654    pub(super) format_change_rollover: bool,
655}
656
657/// The SDK's filename pattern when none is set.
658const DEFAULT_PATTERN: &str = "{prefix}_{index:03}.mkv";
659
660/// The pattern that names each file exactly as its target says.
661const EXACT_PATTERN: &str = "{prefix}";
662
663// A terminated string filling the event field could have been truncated.
664const RECORDER_PATH_LIMIT: usize = NDIlib_file_recorder_event_path_max_size as usize - 2;
665const INDEX_DIGITS: usize = u64::MAX.ilog10() as usize + 1;
666const MAX_INDEX_WIDTH: usize = 1024;
667const FIRST_INDEX: &str = index_text(&padded_index(1));
668const MAX_INDEX: &str = index_text(&padded_index(u64::MAX));
669
670const fn padded_index(mut index: u64) -> [u8; MAX_INDEX_WIDTH] {
671    let mut digits = [b'0'; MAX_INDEX_WIDTH];
672    let mut offset = MAX_INDEX_WIDTH;
673    while index != 0 {
674        offset -= 1;
675        digits[offset] += (index % 10) as u8;
676        index /= 10;
677    }
678    digits
679}
680
681#[expect(clippy::panic, reason = "the const callers supply only ASCII digits")]
682const fn index_text(digits: &[u8; MAX_INDEX_WIDTH]) -> &str {
683    match std::str::from_utf8(digits) {
684        Ok(text) => text,
685        Err(_) => panic!("index padding must be ASCII"),
686    }
687}
688
689#[derive(Clone, Copy)]
690enum IndexSample {
691    First,
692    Maximum,
693}
694
695impl IndexSample {
696    fn with_width(self, width: usize) -> &'static str {
697        match self {
698            Self::First => &FIRST_INDEX[MAX_INDEX_WIDTH - width.max(1)..],
699            Self::Maximum => &MAX_INDEX[MAX_INDEX_WIDTH - width.max(INDEX_DIGITS)..],
700        }
701    }
702}
703
704/// One part of a filename pattern.
705#[derive(Debug, Clone, PartialEq, Eq)]
706enum PatternPart {
707    Text(std::ops::Range<usize>),
708    Prefix,
709    /// `{index}`, with no padding, or `{index:N}`, padded to `N` digits.
710    Index(usize),
711}
712
713/// The literal text and tokens of a filename pattern, in order.
714fn pattern_parts(pattern: &str) -> Result<Vec<PatternPart>> {
715    let unmatched = || Error::InvalidInput(crate::InputDefect::FilenamePatternBrace);
716    let mut parts = Vec::new();
717    let mut rest = pattern;
718    while let Some(start) = rest.find(['{', '}']) {
719        if rest.as_bytes()[start] == b'}' {
720            return Err(unmatched());
721        }
722        if start > 0 {
723            let offset = pattern.len() - rest.len();
724            parts.push(PatternPart::Text(offset..offset + start));
725        }
726        let after = &rest[start + 1..];
727        let end = after.find('}').ok_or_else(unmatched)?;
728        let token = &after[..end];
729        let width = |width: &str| {
730            (!width.is_empty() && width.bytes().all(|b| b.is_ascii_digit()))
731                .then(|| width.parse::<u16>().ok())
732                .flatten()
733                .filter(|&n| (1..=MAX_INDEX_WIDTH).contains(&usize::from(n)))
734        };
735        parts.push(match token {
736            "prefix" => PatternPart::Prefix,
737            "index" => PatternPart::Index(0),
738            _ => match token.strip_prefix("index:").and_then(width) {
739                Some(width) => PatternPart::Index(usize::from(width)),
740                None => {
741                    return Err(Error::InvalidInput(
742                        crate::InputDefect::FilenamePatternToken {
743                            token: token.into(),
744                        },
745                    ))
746                }
747            },
748        });
749        rest = &after[end + 1..];
750    }
751    if !rest.is_empty() {
752        parts.push(PatternPart::Text(pattern.len() - rest.len()..pattern.len()));
753    }
754    Ok(parts)
755}
756
757/// The filename pattern a recorder names its files with.
758#[derive(Debug, Clone)]
759pub(super) struct NamePattern {
760    /// None selects the SDK default and passes a null pointer.
761    pattern: Option<FileText>,
762    parts: Vec<PatternPart>,
763    /// The pattern has no index, so each target names exactly one file.
764    exact: bool,
765    /// Extra digits beyond index 1, reserving the full range of a u64 index.
766    index_digits_reserved: usize,
767}
768
769impl NamePattern {
770    /// Parse `pattern`, failing with [`Error::InvalidInput`] when it is
771    /// malformed.
772    fn new(explicit: Option<&str>) -> Result<Self> {
773        let pattern = explicit.unwrap_or(DEFAULT_PATTERN);
774        let parts = pattern_parts(pattern)?;
775        let mut indexed = false;
776        for part in &parts {
777            let directory_after_index = match part {
778                PatternPart::Index(_) => {
779                    indexed = true;
780                    false
781                }
782                PatternPart::Text(range) => {
783                    indexed && pattern[range.clone()].chars().any(std::path::is_separator)
784                }
785                // A RecordingTarget is absolute, so its expansion always
786                // contains a directory separator even if no literal follows.
787                PatternPart::Prefix => indexed,
788            };
789            if directory_after_index {
790                return Err(Error::InvalidInput(
791                    crate::InputDefect::FilenamePatternIndexInDirectory,
792                ));
793            }
794        }
795        let exact = !parts
796            .iter()
797            .any(|part| matches!(part, PatternPart::Index(_)));
798        let index_digits_reserved = parts
799            .iter()
800            .filter_map(|part| match part {
801                PatternPart::Index(width) => Some(INDEX_DIGITS.saturating_sub((*width).max(1))),
802                _ => None,
803            })
804            .fold(0usize, usize::saturating_add);
805        Ok(Self {
806            pattern: explicit
807                .map(|value| FileText::new(value, "filename pattern"))
808                .transpose()?,
809            parts,
810            exact,
811            index_digits_reserved,
812        })
813    }
814
815    pub(super) fn as_sdk_ptr(&self) -> *const c_char {
816        self.pattern
817            .as_ref()
818            .map_or(std::ptr::null(), FileText::as_ptr)
819    }
820
821    /// Whether each target names exactly one file.
822    pub(super) fn is_exact(&self) -> bool {
823        self.exact
824    }
825
826    fn file_pieces<'a>(
827        &'a self,
828        target: &'a RecordingTarget,
829        index: IndexSample,
830    ) -> impl Iterator<Item = &'a str> + Clone {
831        let pattern = self
832            .pattern
833            .as_ref()
834            .map_or(DEFAULT_PATTERN, FileText::as_str);
835        self.parts.iter().map(move |part| match part {
836            PatternPart::Text(range) => &pattern[range.clone()],
837            PatternPart::Prefix => target.prefix.as_str(),
838            PatternPart::Index(width) => index.with_width(*width),
839        })
840    }
841
842    fn render_name<'a>(pieces: impl Iterator<Item = &'a str>, bytes: usize) -> String {
843        let mut name = String::with_capacity(bytes);
844        pieces.for_each(|piece| name.push_str(piece));
845        name
846    }
847
848    /// Expand the exact filename or the one with index 1. Check its raw byte
849    /// length and the reserve for later indexes before allocating it.
850    fn first_file(&self, target: &RecordingTarget) -> Result<PathBuf> {
851        let pieces = self.file_pieces(target, IndexSample::First);
852        let bytes = pieces
853            .clone()
854            .fold(0usize, |total, piece| total.saturating_add(piece.len()));
855        let longest_bytes = bytes.saturating_add(self.index_digits_reserved);
856        if longest_bytes > RECORDER_PATH_LIMIT {
857            return Err(Error::InvalidInput(
858                crate::InputDefect::RecordingPathTooLong {
859                    maximum_bytes: RECORDER_PATH_LIMIT,
860                    longest_bytes,
861                    index_digits_reserved: self.index_digits_reserved,
862                },
863            ));
864        }
865
866        let name = Self::render_name(pieces, bytes);
867        let path = Path::new(&name);
868        if !path.is_absolute() {
869            return Err(Error::InvalidInput(
870                crate::InputDefect::RecordingPathNotAbsolute,
871            ));
872        }
873        // Path::file_name skips terminal separators and ".", so also check
874        // the original spelling. The component check catches bare Windows
875        // UNC shares, which can have no terminal separator or file name.
876        let last = name.rsplit(std::path::is_separator).next();
877        if matches!(last, Some("" | "." | "..")) || path.file_name().is_none() {
878            return Err(Error::InvalidInput(
879                crate::InputDefect::RecordingPathMissingFilename,
880            ));
881        }
882        Ok(PathBuf::from(name))
883    }
884
885    /// Confirm that the SDK can create the file this pattern gives `target`:
886    /// that its longest path can be reported exactly, its directory exists
887    /// and can be written to, and the filesystem accepts the candidate name
888    /// even at its full index width. An existing candidate is allowed only
889    /// for indexed naming.
890    ///
891    /// The SDK accepts a rollover to a file it cannot create and then ends
892    /// the whole session, so the mistake is caught here, while the session
893    /// can still go on. Nothing is created.
894    pub(super) fn check(&self, target: &RecordingTarget) -> Result<()> {
895        self.check_with_metadata(target, |path| std::fs::symlink_metadata(path))
896    }
897
898    fn check_with_metadata(
899        &self,
900        target: &RecordingTarget,
901        mut metadata: impl FnMut(&Path) -> std::io::Result<std::fs::Metadata>,
902    ) -> Result<()> {
903        let file = self.first_file(target)?;
904        check_directory(file.parent().unwrap_or(&file))?;
905        self.check_candidate(&file, metadata(&file))?;
906        if self.index_digits_reserved > 0 {
907            drop(file);
908            // first_file already bounded the longest spelling. The directory
909            // stays the same because every index is in the basename.
910            let pieces = self.file_pieces(target, IndexSample::Maximum);
911            let bytes = pieces.clone().map(str::len).sum();
912            let name = Self::render_name(pieces, bytes);
913            let widest = Path::new(&name);
914            self.check_candidate(widest, metadata(widest))?;
915        }
916        Ok(())
917    }
918
919    fn check_candidate(
920        &self,
921        file: &Path,
922        metadata: std::io::Result<std::fs::Metadata>,
923    ) -> Result<()> {
924        match metadata {
925            Ok(_) if self.exact => Err(Error::Io(std::io::Error::new(
926                std::io::ErrorKind::AlreadyExists,
927                format!(
928                    "the recording file {} already exists at preflight",
929                    file.display()
930                ),
931            ))),
932            Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(Error::Io(error)),
933            _ => Ok(()),
934        }
935    }
936}
937
938/// Confirm that `directory` exists and can be written to.
939fn check_directory(directory: &Path) -> Result<()> {
940    let refuse = |kind, problem: &str| {
941        Error::Io(std::io::Error::new(
942            kind,
943            format!("the recording directory {} {problem}", directory.display()),
944        ))
945    };
946    match std::fs::metadata(directory) {
947        Err(error) => return Err(refuse(error.kind(), "cannot be used")),
948        Ok(found) if !found.is_dir() => {
949            return Err(refuse(
950                std::io::ErrorKind::NotADirectory,
951                "is not a directory",
952            ))
953        }
954        Ok(_) => {}
955    }
956    #[cfg(unix)]
957    {
958        use std::os::unix::ffi::OsStrExt;
959        let path = CString::new(directory.as_os_str().as_bytes())?;
960        // Check as the effective identity the SDK uses to open the file.
961        // Android has no AT_EACCESS; application real and effective IDs agree.
962        // SAFETY: `path` is a NUL-terminated string that outlives either call.
963        #[cfg(not(target_os = "android"))]
964        let access = unsafe {
965            libc::faccessat(
966                libc::AT_FDCWD,
967                path.as_ptr(),
968                libc::W_OK | libc::X_OK,
969                libc::AT_EACCESS,
970            )
971        };
972        #[cfg(target_os = "android")]
973        let access = unsafe { libc::access(path.as_ptr(), libc::W_OK | libc::X_OK) };
974        if access != 0 {
975            return Err(refuse(
976                std::io::ErrorKind::PermissionDenied,
977                "cannot be written to",
978            ));
979        }
980    }
981    #[cfg(windows)]
982    {
983        if !super::windows_permissions::check_directory(directory)? {
984            return Err(refuse(
985                std::io::ErrorKind::PermissionDenied,
986                "cannot be written to",
987            ));
988        }
989    }
990    Ok(())
991}
992
993/// An owned absolute output prefix/path interpreted by the recorder's naming policy.
994///
995/// Construction freezes the current directory for relative paths and preserves
996/// the prefix text used in naming, including trailing separators and `.`
997/// components. It neither creates directories nor creates/removes/overwrites a
998/// file. The SDK requires losslessly representable UTF-8 paths.
999#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1000pub struct RecordingTarget {
1001    pub(super) prefix: FileText,
1002}
1003
1004impl RecordingTarget {
1005    /// Take an output prefix or exact path, making a relative one absolute.
1006    ///
1007    /// # Errors
1008    ///
1009    /// [`Error::InvalidInput`] when the path is empty or is not UTF-8,
1010    /// [`Error::InvalidCString`] when it contains a NUL, and [`Error::Io`]
1011    /// when the operating system cannot resolve a relative path.
1012    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
1013        let prefix = resolve_path(path.as_ref(), "recording target", absolute_recording_prefix)?;
1014        Ok(Self { prefix })
1015    }
1016
1017    /// The frozen absolute path/prefix, without filesystem canonicalization.
1018    pub fn path(&self) -> &Path {
1019        Path::new(self.prefix.as_str())
1020    }
1021}
1022
1023fn absolute_recording_prefix(text: &str) -> std::io::Result<PathBuf> {
1024    #[cfg(windows)]
1025    let (mut anchor, suffix) = {
1026        use std::path::{Component, Prefix};
1027        match Path::new(text).components().next() {
1028            Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::Disk(_)) => {
1029                // `C:.` resolves the current directory for drive C, even if
1030                // the process is working on another drive.
1031                let drive = Path::new(prefix.as_os_str());
1032                let anchor = std::path::absolute(drive.join("."))?;
1033                (anchor, &text[prefix.as_os_str().len()..])
1034            }
1035            Some(Component::Prefix(_)) => return std::path::absolute(text),
1036            Some(Component::RootDir) => (std::path::absolute(r"\")?, &text[1..]),
1037            _ => (std::env::current_dir()?, text),
1038        }
1039    };
1040    #[cfg(not(windows))]
1041    let (mut anchor, suffix) = (std::env::current_dir()?, text);
1042
1043    // Append text without PathBuf::push, which can normalize components on
1044    // a verbatim Windows anchor. The naming pattern may complete a filename.
1045    let prefix = anchor.as_mut_os_string();
1046    if !prefix
1047        .as_encoded_bytes()
1048        .last()
1049        .is_some_and(|&byte| std::path::is_separator(char::from(byte)))
1050    {
1051        prefix.push(std::path::MAIN_SEPARATOR_STR);
1052    }
1053    prefix.push(suffix);
1054    Ok(anchor)
1055}
1056
1057/// Make `path` absolute against the current directory and convert it for the
1058/// SDK. `what` names the path in the errors: a recording target and a file to
1059/// play are different things to the caller.
1060///
1061/// # Errors
1062///
1063/// [`Error::InvalidInput`] naming `what` when the path is empty or is not
1064/// UTF-8, [`Error::InvalidCString`] when it contains a NUL, and
1065/// [`Error::Io`] when the operating system cannot resolve a relative path.
1066fn resolve_path(
1067    path: &Path,
1068    what: &'static str,
1069    absolutize: impl FnOnce(&str) -> std::io::Result<PathBuf>,
1070) -> Result<FileText> {
1071    if path.as_os_str().is_empty() {
1072        return Err(Error::InvalidInput(crate::InputDefect::Empty { what }));
1073    }
1074    let text = path
1075        .to_str()
1076        .ok_or(Error::InvalidInput(crate::InputDefect::PathNotUtf8 {
1077            what,
1078        }))?;
1079    // Validate before resolving. Windows reports a relative path containing
1080    // NUL as an I/O error, while the File API reports the original NUL index.
1081    let checked = FileText::new(text, what)?;
1082    if path.is_absolute() {
1083        return Ok(checked);
1084    }
1085    let absolute = absolutize(text)?;
1086    let text = absolute
1087        .to_str()
1088        .ok_or(Error::InvalidInput(crate::InputDefect::PathNotUtf8 {
1089            what,
1090        }))?;
1091    // Resolving the checked path against the OS directory cannot add a NUL.
1092    Ok(FileText::from_checked(text))
1093}
1094
1095/// A path to play or probe, as the SDK takes it.
1096pub(super) fn path_string(path: &Path) -> Result<FileText> {
1097    resolve_path(path, "file path", |text| std::path::absolute(text))
1098}
1099
1100/// Original SDK event bytes, retaining invalid UTF-8 and truncation evidence.
1101#[derive(Clone, PartialEq, Eq, Hash)]
1102pub struct EventText {
1103    bytes: Vec<u8>,
1104    terminated: bool,
1105    possibly_truncated: bool,
1106}
1107
1108impl std::fmt::Debug for EventText {
1109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1110        let mut summary = f.debug_struct("EventText");
1111        summary.field("text", &self.to_string_lossy());
1112        if !self.terminated {
1113            summary.field("terminated", &false);
1114        }
1115        if self.possibly_truncated {
1116            summary.field("possibly_truncated", &true);
1117        }
1118        summary.finish()
1119    }
1120}
1121
1122impl Default for EventText {
1123    fn default() -> Self {
1124        Self {
1125            bytes: Vec::new(),
1126            terminated: true,
1127            possibly_truncated: false,
1128        }
1129    }
1130}
1131
1132impl EventText {
1133    /// Bytes owned by the event text, including spare capacity.
1134    pub(super) fn retained_bytes(&self) -> usize {
1135        self.bytes.capacity()
1136    }
1137
1138    pub(super) fn from_buffer(buffer: &[c_char]) -> Self {
1139        EventTextRef::from_buffer(buffer).into_owned()
1140    }
1141
1142    #[cfg(test)]
1143    pub(super) fn as_ref(&self) -> EventTextRef<'_> {
1144        EventTextRef {
1145            bytes: &self.bytes,
1146            terminated: self.terminated,
1147            possibly_truncated: self.possibly_truncated,
1148        }
1149    }
1150
1151    /// Original bytes up to a bounded NUL search, excluding the terminator.
1152    pub fn as_bytes(&self) -> &[u8] {
1153        &self.bytes
1154    }
1155
1156    /// Strict text decoding; failure does not discard the original event bytes.
1157    pub fn to_str(&self) -> std::result::Result<&str, std::str::Utf8Error> {
1158        std::str::from_utf8(&self.bytes)
1159    }
1160
1161    /// Text suitable for diagnostics, replacing malformed UTF-8 explicitly.
1162    pub fn to_string_lossy(&self) -> Cow<'_, str> {
1163        String::from_utf8_lossy(&self.bytes)
1164    }
1165
1166    /// Whether the native fixed-size buffer contained a NUL terminator.
1167    pub fn is_terminated(&self) -> bool {
1168        self.terminated
1169    }
1170
1171    /// Whether the string filled the available payload and might be truncated.
1172    pub fn is_possibly_truncated(&self) -> bool {
1173        self.possibly_truncated
1174    }
1175}
1176
1177/// The bounded text of one event while its native buffer is still available.
1178#[derive(Clone, Copy)]
1179pub(super) struct EventTextRef<'a> {
1180    bytes: &'a [u8],
1181    terminated: bool,
1182    possibly_truncated: bool,
1183}
1184
1185impl<'a> EventTextRef<'a> {
1186    pub(super) fn from_buffer(buffer: &'a [c_char]) -> Self {
1187        let end = buffer.iter().position(|&b| b == 0);
1188        let used = end.unwrap_or(buffer.len());
1189        // SAFETY: c_char and u8 are both one byte with alignment one. Every
1190        // initialized c_char bit pattern is a u8, and used is within buffer.
1191        let bytes = unsafe { std::slice::from_raw_parts(buffer.as_ptr().cast::<u8>(), used) };
1192        Self {
1193            bytes,
1194            terminated: end.is_some(),
1195            possibly_truncated: !buffer.is_empty() && used >= buffer.len() - 1,
1196        }
1197    }
1198
1199    pub(super) fn as_bytes(self) -> &'a [u8] {
1200        self.bytes
1201    }
1202
1203    pub(super) fn is_exact_nonempty(self) -> bool {
1204        !self.bytes.is_empty() && self.terminated && !self.possibly_truncated
1205    }
1206
1207    pub(super) fn into_owned(self) -> EventText {
1208        EventText {
1209            bytes: self.bytes.to_vec(),
1210            terminated: self.terminated,
1211            possibly_truncated: self.possibly_truncated,
1212        }
1213    }
1214}
1215
1216/// Unsigned file-relative time in 100ns units, distinct from the editorial
1217/// [`Timecode`] that frames carry.
1218#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
1219pub struct FilePosition(pub(super) u64);
1220
1221impl FilePosition {
1222    /// Preserve native 100ns ticks.
1223    pub const fn from_ticks(ticks: u64) -> Self {
1224        Self(ticks)
1225    }
1226
1227    /// The position `duration` after the start of the file, rounded down to a
1228    /// 100 ns tick.
1229    ///
1230    /// # Errors
1231    ///
1232    /// [`Error::InvalidInput`] when the duration exceeds 64 bits of ticks.
1233    pub fn from_duration(duration: Duration) -> Result<Self> {
1234        let ticks = duration.as_nanos() / 100;
1235        u64::try_from(ticks)
1236            .map(Self)
1237            .map_err(|_| Error::InvalidInput(crate::InputDefect::FilePositionOverflow))
1238    }
1239
1240    /// Native 100ns ticks.
1241    pub const fn ticks(self) -> u64 {
1242        self.0
1243    }
1244
1245    /// Exact duration represented by these ticks.
1246    pub fn duration(self) -> Duration {
1247        Duration::new(self.0 / 10_000_000, ((self.0 % 10_000_000) * 100) as u32)
1248    }
1249}
1250
1251/// An explicit editorial timecode from which a recording session can advance.
1252///
1253/// The send-only [`Timecode::SYNTHESIZE`] sentinel is not a recording start.
1254/// Choose a value such as zero when the source has no meaningful timecode.
1255///
1256/// ```
1257/// use grafton_ndi::{file::{RecordingTimecode, SessionTimecode}, Timecode};
1258///
1259/// let start = SessionTimecode::new(Timecode::from_ticks(0))?;
1260/// let policy = RecordingTimecode::GenerateFrom(start);
1261/// assert_eq!(start.timecode(), Timecode::from_ticks(0));
1262/// assert!(SessionTimecode::new(Timecode::SYNTHESIZE).is_err());
1263/// # Ok::<(), grafton_ndi::Error>(())
1264/// ```
1265#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1266pub struct SessionTimecode(Timecode);
1267
1268impl SessionTimecode {
1269    /// Validate an explicit recording start without changing its ticks.
1270    ///
1271    /// Negative values and every value except the send sentinel are accepted.
1272    ///
1273    /// # Errors
1274    ///
1275    /// [`Error::InvalidInput`] for [`Timecode::SYNTHESIZE`], including the
1276    /// default `Timecode`. Use an explicit start such as zero instead.
1277    pub fn new(timecode: Timecode) -> Result<Self> {
1278        if timecode == Timecode::SYNTHESIZE {
1279            return Err(Error::InvalidInput(
1280                crate::InputDefect::SynthesizeRecordingStart,
1281            ));
1282        }
1283        Ok(Self(timecode))
1284    }
1285
1286    /// The validated editorial timecode.
1287    pub const fn timecode(self) -> Timecode {
1288        self.0
1289    }
1290
1291    /// The explicit start in 100-nanosecond ticks.
1292    pub const fn ticks(self) -> i64 {
1293        self.0.ticks()
1294    }
1295}
1296
1297/// Timecode policy applied when a recording session starts.
1298#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1299#[non_exhaustive]
1300pub enum RecordingTimecode {
1301    /// Preserve the source's original editorial timecode.
1302    #[default]
1303    Preserve,
1304    /// Generate the session's timecode, starting at this value and advancing
1305    /// with the content, in place of the source's own. Use it when the source
1306    /// provides no meaningful timecode. Construct the explicit start with
1307    /// [`SessionTimecode::new`]; the send-only synthesize sentinel is refused.
1308    GenerateFrom(SessionTimecode),
1309}
1310
1311/// A current duration that may still be growing.
1312#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1313pub struct FileDuration {
1314    pub(super) position: FilePosition,
1315    pub(super) is_final: bool,
1316}
1317
1318impl FileDuration {
1319    /// The duration in 100ns units.
1320    pub fn value(self) -> FilePosition {
1321        self.position
1322    }
1323
1324    /// Whether the SDK says this duration is finalized.
1325    pub fn is_final(self) -> bool {
1326        self.is_final
1327    }
1328}
1329
1330/// An owned description of one video track, not a decoded pixel layout.
1331///
1332/// A recorder's events describe the source's declared format, and a probe the
1333/// track header of the file. A value the SDK does not know yet is zero or
1334/// `None`.
1335#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1336pub struct VideoTrack {
1337    tier: StreamTier,
1338    width: u32,
1339    height: u32,
1340    frame_rate: Option<FrameRate>,
1341    fourcc: FourCc,
1342    scan_type: Option<ScanType>,
1343    picture_aspect_ratio: Option<PictureAspectRatio>,
1344}
1345
1346impl VideoTrack {
1347    /// Which of the source's streams the track recorded: the full-quality
1348    /// program stream or the low-bandwidth preview (proxy) stream.
1349    pub fn tier(&self) -> StreamTier {
1350        self.tier
1351    }
1352
1353    /// The width in pixels, or zero while it is not known.
1354    pub fn width(&self) -> u32 {
1355        self.width
1356    }
1357
1358    /// The height in pixels, or zero while it is not known.
1359    pub fn height(&self) -> u32 {
1360        self.height
1361    }
1362
1363    /// The frame rate, or `None` while it is not known.
1364    pub fn frame_rate(&self) -> Option<FrameRate> {
1365        self.frame_rate
1366    }
1367
1368    /// The codec or packing identifier, including one this crate does not
1369    /// know.
1370    pub fn fourcc(&self) -> FourCc {
1371        self.fourcc
1372    }
1373
1374    /// The scan type, or `None` for a value this crate does not know.
1375    ///
1376    /// A file recorded before the SDK stored the scan type reports
1377    /// [`ScanType::Interlaced`], the SDK's zero value.
1378    pub fn scan_type(&self) -> Option<ScanType> {
1379        self.scan_type
1380    }
1381
1382    /// The display aspect ratio of the full frame, such as 16/9, or `None`
1383    /// when it is not known, in which case the pixels are square.
1384    pub fn picture_aspect_ratio(&self) -> Option<PictureAspectRatio> {
1385        self.picture_aspect_ratio
1386    }
1387}
1388
1389/// An owned layout snapshot containing no borrowed native memory.
1390///
1391/// A value the SDK does not know, or that does not apply, such as the audio
1392/// of a source without audio, is zero.
1393#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1394pub struct SourceFormat {
1395    video_tracks: Vec<VideoTrack>,
1396    audio_sample_rate: u32,
1397    audio_num_channels: u32,
1398    audio_num_samples: u32,
1399    audio_bit_depth: u32,
1400    audio_fourcc: FourCc,
1401}
1402
1403impl SourceFormat {
1404    /// The populated video tracks: the program track first, then the
1405    /// preview (proxy) track when there is one.
1406    pub fn video_tracks(&self) -> &[VideoTrack] {
1407        &self.video_tracks
1408    }
1409
1410    /// The audio sample rate in Hz.
1411    pub fn audio_sample_rate(&self) -> u32 {
1412        self.audio_sample_rate
1413    }
1414
1415    /// The number of audio channels.
1416    pub fn audio_num_channels(&self) -> u32 {
1417        self.audio_num_channels
1418    }
1419
1420    /// The number of audio samples per channel in each packet.
1421    pub fn audio_num_samples(&self) -> u32 {
1422        self.audio_num_samples
1423    }
1424
1425    /// The audio bit depth.
1426    pub fn audio_bit_depth(&self) -> u32 {
1427        self.audio_bit_depth
1428    }
1429
1430    /// The audio codec or packing identifier.
1431    pub fn audio_fourcc(&self) -> FourCc {
1432        self.audio_fourcc
1433    }
1434}
1435
1436/// A non-advertising file probe result.
1437#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1438pub struct FileInfo {
1439    pub(super) duration: FileDuration,
1440    pub(super) track_count: u32,
1441    pub(super) video_track_count: u32,
1442    pub(super) audio_track_count: u32,
1443    pub(super) metadata_track_count: u32,
1444    pub(super) source_format: std::result::Result<SourceFormat, SdkResultDefect>,
1445}
1446
1447impl FileInfo {
1448    /// Best-known duration and its finalized status.
1449    pub fn duration(&self) -> FileDuration {
1450        self.duration
1451    }
1452    /// Total reported track count.
1453    pub fn track_count(&self) -> u32 {
1454        self.track_count
1455    }
1456    /// Reported video track count.
1457    pub fn video_track_count(&self) -> u32 {
1458        self.video_track_count
1459    }
1460    /// Reported audio track count.
1461    pub fn audio_track_count(&self) -> u32 {
1462        self.audio_track_count
1463    }
1464    /// Reported metadata track count.
1465    pub fn metadata_track_count(&self) -> u32 {
1466        self.metadata_track_count
1467    }
1468    /// Owned codec/layout information.
1469    /// An unreadable format is withheld with its cause; the remaining event
1470    /// or probe fields are still delivered.
1471    ///
1472    /// # Errors
1473    ///
1474    /// The typed SDK-result defect that prevented decoding the format.
1475    pub fn source_format(&self) -> std::result::Result<&SourceFormat, SdkResultDefect> {
1476        self.source_format.as_ref().map_err(|cause| *cause)
1477    }
1478}
1479
1480/// Playback event kind; unknown native values remain observable.
1481#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1482#[non_exhaustive]
1483pub enum PlayerEventKind {
1484    /// Natural end of file.
1485    Ended,
1486    /// Unrecoverable playback error.
1487    Error,
1488    /// File was opened.
1489    FileOpened,
1490    /// First displayed packet after start, seek or loop.
1491    FirstFrame,
1492    /// A playback session closed.
1493    FileClosed,
1494    /// Playback looped to its beginning.
1495    Looped,
1496    /// An unrecognized native event identifier.
1497    Unknown(u32),
1498}
1499
1500impl PlayerEventKind {
1501    pub(super) fn from_raw(value: u32) -> Self {
1502        match value {
1503            sys::bindings::NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_ended => Self::Ended,
1504            sys::bindings::NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_error => Self::Error,
1505            sys::bindings::NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_file_opened => {
1506                Self::FileOpened
1507            }
1508            sys::bindings::NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_first_frame => {
1509                Self::FirstFrame
1510            }
1511            sys::bindings::NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_file_closed => {
1512                Self::FileClosed
1513            }
1514            sys::bindings::NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_looped => Self::Looped,
1515            value => Self::Unknown(value),
1516        }
1517    }
1518}
1519
1520/// An owned player event. Inline SDK strings are copied within their bounds.
1521#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1522pub struct PlayerEvent {
1523    pub(super) kind: PlayerEventKind,
1524    pub(super) path: EventText,
1525    pub(super) message: EventText,
1526    pub(super) first_pts: FilePosition,
1527    pub(super) last_pts: FilePosition,
1528    pub(super) source_timecode: Option<Timecode>,
1529    pub(super) source_format: std::result::Result<SourceFormat, SdkResultDefect>,
1530}
1531
1532impl PlayerEvent {
1533    /// Event kind.
1534    pub fn kind(&self) -> PlayerEventKind {
1535        self.kind
1536    }
1537    /// Reported path, potentially truncated.
1538    pub fn path(&self) -> &EventText {
1539        &self.path
1540    }
1541    /// Diagnostic/causality text.
1542    pub fn message(&self) -> &EventText {
1543        &self.message
1544    }
1545    /// First packet timestamp where applicable; otherwise native zero.
1546    pub fn first_pts(&self) -> FilePosition {
1547        self.first_pts
1548    }
1549    /// Last packet timestamp where applicable; otherwise native zero.
1550    pub fn last_pts(&self) -> FilePosition {
1551        self.last_pts
1552    }
1553    /// The source's original editorial timecode, recorded with the frame,
1554    /// when the SDK knows it. Unlike the file position it need not increase.
1555    pub fn source_timecode(&self) -> Option<Timecode> {
1556        self.source_timecode
1557    }
1558    /// Source format snapshot; zero/empty fields may mean inapplicable.
1559    /// An unreadable format is withheld with its cause; the remaining event
1560    /// or probe fields are still delivered.
1561    ///
1562    /// # Errors
1563    ///
1564    /// The typed SDK-result defect that prevented decoding the format.
1565    pub fn source_format(&self) -> std::result::Result<&SourceFormat, SdkResultDefect> {
1566        self.source_format.as_ref().map_err(|cause| *cause)
1567    }
1568}
1569
1570/// Recorder event kind; a write failure is not necessarily fatal.
1571#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1572#[non_exhaustive]
1573pub enum RecorderEventKind {
1574    /// First output file opened.
1575    Started,
1576    /// A new rollover file opened.
1577    Rollover,
1578    /// Output open failed.
1579    OpenFailed,
1580    /// Packet write failure, either fatal I/O or nonfatal missing track.
1581    WriteFailed,
1582    /// Unrecoverable writer error.
1583    Error,
1584    /// Source format changed.
1585    FormatChanged,
1586    /// First audio/video packet was written; absent for metadata-only recording.
1587    FirstFrame,
1588    /// Source disconnected while recording remains active.
1589    SourceLost,
1590    /// Source resumed delivering packets.
1591    SourceConnected,
1592    /// Current file finalized and closed.
1593    FileClosed,
1594    /// Expected proxy was unavailable.
1595    ProxyMissing,
1596    /// An unrecognized native event identifier.
1597    /// Its lifecycle effect cannot be established, so file tracking becomes
1598    /// incomplete while the event and its original identifier remain available.
1599    Unknown(u32),
1600}
1601
1602impl RecorderEventKind {
1603    pub(super) fn from_raw(value: u32) -> Self {
1604        match value {
1605            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_started => {
1606                Self::Started
1607            }
1608            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_rollover => {
1609                Self::Rollover
1610            }
1611            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_open_failed => {
1612                Self::OpenFailed
1613            }
1614            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_write_failed => {
1615                Self::WriteFailed
1616            }
1617            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_error => Self::Error,
1618            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_format_changed => {
1619                Self::FormatChanged
1620            }
1621            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_first_frame => {
1622                Self::FirstFrame
1623            }
1624            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_source_lost => {
1625                Self::SourceLost
1626            }
1627            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_source_connected => {
1628                Self::SourceConnected
1629            }
1630            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_file_closed => {
1631                Self::FileClosed
1632            }
1633            sys::bindings::NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_proxy_missing => {
1634                Self::ProxyMissing
1635            }
1636            value => Self::Unknown(value),
1637        }
1638    }
1639}
1640
1641/// An owned recorder event, including original bounded diagnostic text.
1642#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1643pub struct RecorderEvent {
1644    pub(super) kind: RecorderEventKind,
1645    pub(super) path: EventText,
1646    pub(super) message: EventText,
1647    pub(super) tracks: MediaTypes,
1648    pub(super) dropped_packet_count: u64,
1649    pub(super) first_pts: FilePosition,
1650    pub(super) last_pts: FilePosition,
1651    pub(super) format_text: EventText,
1652    pub(super) source_format: std::result::Result<SourceFormat, SdkResultDefect>,
1653}
1654
1655impl RecorderEvent {
1656    /// Event kind.
1657    pub fn kind(&self) -> RecorderEventKind {
1658        self.kind
1659    }
1660    /// Reported file path, potentially truncated.
1661    pub fn path(&self) -> &EventText {
1662        &self.path
1663    }
1664    /// Diagnostic/causality text.
1665    pub fn message(&self) -> &EventText {
1666        &self.message
1667    }
1668    /// The track a [`WriteFailed`](RecorderEventKind::WriteFailed) event
1669    /// concerns; empty for every other event.
1670    pub fn tracks(&self) -> MediaTypes {
1671        self.tracks
1672    }
1673    /// Packet count attached to this particular event, not all session drops.
1674    pub fn dropped_packet_count(&self) -> u64 {
1675        self.dropped_packet_count
1676    }
1677    /// First packet timestamp where applicable.
1678    pub fn first_pts(&self) -> FilePosition {
1679        self.first_pts
1680    }
1681    /// Last packet timestamp where applicable.
1682    pub fn last_pts(&self) -> FilePosition {
1683        self.last_pts
1684    }
1685    /// Legacy textual format description.
1686    pub fn format_text(&self) -> &EventText {
1687        &self.format_text
1688    }
1689    /// Structured format description.
1690    /// An unreadable format is withheld with its cause; the remaining event
1691    /// or probe fields are still delivered.
1692    ///
1693    /// # Errors
1694    ///
1695    /// The typed SDK-result defect that prevented decoding the format.
1696    pub fn source_format(&self) -> std::result::Result<&SourceFormat, SdkResultDefect> {
1697        self.source_format.as_ref().map_err(|cause| *cause)
1698    }
1699}
1700
1701/// Owned playback counters for the current or most recent file session.
1702#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1703pub struct PlayerStats {
1704    pub(super) program_video_frames: u64,
1705    pub(super) preview_video_frames: u64,
1706    pub(super) audio_frames: u64,
1707    pub(super) metadata_frames: u64,
1708    pub(super) wallclock: FilePosition,
1709}
1710
1711impl PlayerStats {
1712    /// Sent video frames for the program or preview stream.
1713    pub fn video_frames_sent(&self, tier: StreamTier) -> u64 {
1714        match tier {
1715            StreamTier::Program => self.program_video_frames,
1716            StreamTier::Preview => self.preview_video_frames,
1717        }
1718    }
1719    /// Sent audio packet count.
1720    pub fn audio_frames_sent(&self) -> u64 {
1721        self.audio_frames
1722    }
1723    /// Sent metadata packet count.
1724    pub fn metadata_frames_sent(&self) -> u64 {
1725        self.metadata_frames
1726    }
1727    /// Playback wall-clock duration reported by the SDK.
1728    pub fn wallclock(&self) -> FilePosition {
1729        self.wallclock
1730    }
1731}
1732
1733/// Owned recorder telemetry. Counts refer to packets rather than decoded samples.
1734#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1735pub struct RecorderStats {
1736    pub(super) bytes_written: u64,
1737    pub(super) video_frames: u64,
1738    pub(super) audio_frames: u64,
1739    pub(super) metadata_frames: u64,
1740    pub(super) video_frames_dropped_by_receiver: u64,
1741    pub(super) audio_frames_dropped_by_receiver: u64,
1742    pub(super) metadata_frames_dropped_by_receiver: u64,
1743    pub(super) video_frames_dropped_by_pipeline: u64,
1744    pub(super) audio_frames_dropped_by_pipeline: u64,
1745    pub(super) metadata_frames_dropped_by_pipeline: u64,
1746    pub(super) writer_dropped: u64,
1747    pub(super) rollover_count: u64,
1748    pub(super) recording_time: FilePosition,
1749    pub(super) last_video_pts: FilePosition,
1750    pub(super) last_audio_pts: FilePosition,
1751    pub(super) last_metadata_pts: FilePosition,
1752}
1753
1754impl RecorderStats {
1755    /// Bytes written.
1756    pub fn bytes_written(&self) -> u64 {
1757        self.bytes_written
1758    }
1759    /// Muxed video packet count.
1760    pub fn video_frames_written(&self) -> u64 {
1761        self.video_frames
1762    }
1763    /// Muxed audio packet count.
1764    pub fn audio_frames_written(&self) -> u64 {
1765        self.audio_frames
1766    }
1767    /// Muxed metadata packet count.
1768    pub fn metadata_frames_written(&self) -> u64 {
1769        self.metadata_frames
1770    }
1771    /// Video packets dropped by the receiver.
1772    pub fn video_frames_dropped_by_receiver(&self) -> u64 {
1773        self.video_frames_dropped_by_receiver
1774    }
1775    /// Audio packets dropped by the receiver.
1776    pub fn audio_frames_dropped_by_receiver(&self) -> u64 {
1777        self.audio_frames_dropped_by_receiver
1778    }
1779    /// Metadata packets dropped by the receiver.
1780    pub fn metadata_frames_dropped_by_receiver(&self) -> u64 {
1781        self.metadata_frames_dropped_by_receiver
1782    }
1783    /// Video packets dropped by the pipeline.
1784    pub fn video_frames_dropped_by_pipeline(&self) -> u64 {
1785        self.video_frames_dropped_by_pipeline
1786    }
1787    /// Audio packets dropped by the pipeline.
1788    pub fn audio_frames_dropped_by_pipeline(&self) -> u64 {
1789        self.audio_frames_dropped_by_pipeline
1790    }
1791    /// Metadata packets dropped by the pipeline.
1792    pub fn metadata_frames_dropped_by_pipeline(&self) -> u64 {
1793        self.metadata_frames_dropped_by_pipeline
1794    }
1795    /// Writer-stage drops across all tracks.
1796    pub fn frames_dropped_by_writer(&self) -> u64 {
1797        self.writer_dropped
1798    }
1799    /// Completed rollover count.
1800    pub fn rollover_count(&self) -> u64 {
1801        self.rollover_count
1802    }
1803    /// Recorded duration reported by the SDK.
1804    pub fn recording_time(&self) -> FilePosition {
1805        self.recording_time
1806    }
1807    /// Last muxed video timestamp.
1808    pub fn last_video_pts(&self) -> FilePosition {
1809        self.last_video_pts
1810    }
1811    /// Last muxed audio timestamp.
1812    pub fn last_audio_pts(&self) -> FilePosition {
1813        self.last_audio_pts
1814    }
1815    /// Last muxed metadata timestamp.
1816    pub fn last_metadata_pts(&self) -> FilePosition {
1817        self.last_metadata_pts
1818    }
1819}
1820
1821/// A quantity the SDK reports as a signed integer, which must not be negative.
1822fn non_negative(value: i32, what: &'static str) -> std::result::Result<u32, SdkResultDefect> {
1823    u32::try_from(value).map_err(|_| SdkResultDefect::NegativeFormatCount { what, value })
1824}
1825
1826/// The scan type a File SDK frame format names, if it names one.
1827fn scan_type(format: NDIlib_file_video_frame_format_e) -> Option<ScanType> {
1828    match format {
1829        sys::bindings::NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_interleaved => {
1830            Some(ScanType::Interlaced)
1831        }
1832        sys::bindings::NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_progressive => {
1833            Some(ScanType::Progressive)
1834        }
1835        sys::bindings::NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_field_0 => {
1836            Some(ScanType::Field0)
1837        }
1838        sys::bindings::NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_field_1 => {
1839            Some(ScanType::Field1)
1840        }
1841        _ => None,
1842    }
1843}
1844
1845/// Each media type and the SDK's recorder track flag for it.
1846const TRACK_FLAGS: [(MediaTypes, NDIlib_file_recorder_track_flags_e); 3] = [
1847    (
1848        MediaTypes::VIDEO,
1849        NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_video,
1850    ),
1851    (
1852        MediaTypes::AUDIO,
1853        NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_audio,
1854    ),
1855    (
1856        MediaTypes::METADATA,
1857        NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_metadata,
1858    ),
1859];
1860
1861/// The SDK's recorder track flags for `tracks`.
1862pub(super) fn track_flags(tracks: MediaTypes) -> NDIlib_file_recorder_track_flags_e {
1863    TRACK_FLAGS
1864        .into_iter()
1865        .filter(|&(kind, _)| tracks.contains(kind))
1866        .fold(0, |flags, (_, flag)| flags | flag)
1867}
1868
1869/// The media types the SDK's recorder track flags name. A flag this crate
1870/// does not know is left out.
1871fn tracks(flags: NDIlib_file_recorder_track_flags_e) -> MediaTypes {
1872    TRACK_FLAGS
1873        .into_iter()
1874        .filter(|&(_, flag)| flags & flag == flag)
1875        .fold(MediaTypes::NONE, |tracks, (kind, _)| tracks | kind)
1876}
1877
1878impl VideoTrack {
1879    /// The track the SDK's `raw` describes.
1880    pub(super) fn from_sdk(
1881        raw: &NDIlib_file_video_track_format_t,
1882    ) -> std::result::Result<Self, SdkResultDefect> {
1883        let ratio = raw.picture_aspect_ratio;
1884        Ok(Self {
1885            tier: if raw.is_high_quality {
1886                StreamTier::Program
1887            } else {
1888                StreamTier::Preview
1889            },
1890            width: non_negative(raw.xres, "width")?,
1891            height: non_negative(raw.yres, "height")?,
1892            // Both parts are at most i32::MAX, so only a zero part, which
1893            // the SDK reports while the rate is unknown, has no frame rate.
1894            frame_rate: FrameRate::new(
1895                non_negative(raw.frame_rate_n, "frame-rate numerator")?,
1896                non_negative(raw.frame_rate_d, "frame-rate denominator")?,
1897            )
1898            .ok(),
1899            fourcc: FourCc::from_raw(raw.fourcc),
1900            scan_type: scan_type(raw.frame_format_type),
1901            picture_aspect_ratio: if ratio > 0.0 {
1902                PictureAspectRatio::new(ratio).ok()
1903            } else {
1904                None
1905            },
1906        })
1907    }
1908}
1909
1910impl SourceFormat {
1911    /// The format the SDK's `raw` describes.
1912    pub(super) fn from_sdk(
1913        raw: &NDIlib_file_source_format_t,
1914    ) -> std::result::Result<Self, SdkResultDefect> {
1915        // Lossless: the SDK count is u32 and supported targets have >=32-bit usize.
1916        let count = raw.video_track_count as usize;
1917        let tracks = raw.video_tracks.get(..count).ok_or({
1918            SdkResultDefect::FileTrackCount {
1919                count: raw.video_track_count,
1920                capacity: raw.video_tracks.len(),
1921            }
1922        })?;
1923        Ok(Self {
1924            video_tracks: tracks
1925                .iter()
1926                .map(VideoTrack::from_sdk)
1927                .collect::<std::result::Result<_, _>>()?,
1928            audio_sample_rate: non_negative(raw.audio_sample_rate, "audio sample rate")?,
1929            audio_num_channels: non_negative(raw.audio_no_channels, "audio channel count")?,
1930            audio_num_samples: non_negative(raw.audio_no_samples, "audio sample count")?,
1931            audio_bit_depth: raw.audio_bit_depth,
1932            audio_fourcc: FourCc::from_raw(raw.audio_fourcc),
1933        })
1934    }
1935}
1936
1937impl FileInfo {
1938    /// The information the SDK's `raw` reports.
1939    pub(super) fn from_sdk(raw: &NDIlib_file_player_file_info_t) -> Self {
1940        Self {
1941            duration: FileDuration {
1942                position: FilePosition::from_ticks(raw.duration_100ns),
1943                is_final: raw.duration_is_final,
1944            },
1945            track_count: raw.track_count,
1946            video_track_count: raw.video_track_count,
1947            audio_track_count: raw.audio_track_count,
1948            metadata_track_count: raw.metadata_track_count,
1949            source_format: SourceFormat::from_sdk(&raw.source_format),
1950        }
1951    }
1952}
1953
1954impl PlayerEvent {
1955    /// The event the SDK's `raw` reports.
1956    pub(super) fn from_sdk(raw: &NDIlib_file_player_event_t) -> Self {
1957        Self {
1958            kind: PlayerEventKind::from_raw(raw.type_),
1959            path: EventText::from_buffer(&raw.p_path),
1960            message: EventText::from_buffer(&raw.p_message),
1961            first_pts: FilePosition::from_ticks(raw.first_pts_100ns),
1962            last_pts: FilePosition::from_ticks(raw.last_pts_100ns),
1963            source_timecode: raw
1964                .has_source_timecode
1965                .then(|| Timecode::from_ticks(raw.source_timecode_100ns)),
1966            source_format: SourceFormat::from_sdk(&raw.source_format),
1967        }
1968    }
1969}
1970
1971impl RecorderEvent {
1972    /// The event the SDK's `raw` reports.
1973    pub(super) fn from_sdk(
1974        raw: &NDIlib_file_recorder_event_t,
1975        kind: RecorderEventKind,
1976        path: EventTextRef<'_>,
1977    ) -> Self {
1978        Self {
1979            kind,
1980            path: path.into_owned(),
1981            message: EventText::from_buffer(&raw.p_message),
1982            tracks: tracks(raw.track_flags),
1983            dropped_packet_count: raw.dropped_packet_count,
1984            first_pts: FilePosition::from_ticks(raw.first_pts_100ns),
1985            last_pts: FilePosition::from_ticks(raw.last_pts_100ns),
1986            format_text: EventText::from_buffer(&raw.source_format),
1987            source_format: SourceFormat::from_sdk(&raw.source_format_payload),
1988        }
1989    }
1990}
1991
1992impl PlayerStats {
1993    /// The statistics the SDK's `raw` reports.
1994    pub(super) fn from_sdk(raw: &NDIlib_file_player_stats_t) -> Self {
1995        Self {
1996            program_video_frames: raw.video_frames_sent[0],
1997            preview_video_frames: raw.video_frames_sent[1],
1998            audio_frames: raw.audio_frames_sent,
1999            metadata_frames: raw.metadata_frames_sent,
2000            wallclock: FilePosition::from_ticks(raw.playback_wallclock_100ns),
2001        }
2002    }
2003}
2004
2005impl RecorderStats {
2006    /// The statistics the SDK's `raw` reports.
2007    pub(super) fn from_sdk(raw: &NDIlib_file_recorder_stats_t) -> Self {
2008        Self {
2009            bytes_written: raw.bytes_written,
2010            video_frames: raw.video_frames,
2011            audio_frames: raw.audio_frames,
2012            metadata_frames: raw.metadata_frames,
2013            video_frames_dropped_by_receiver: raw.receiver_dropped_video_frames,
2014            audio_frames_dropped_by_receiver: raw.receiver_dropped_audio_frames,
2015            metadata_frames_dropped_by_receiver: raw.receiver_dropped_metadata_frames,
2016            video_frames_dropped_by_pipeline: raw.pipeline_dropped_video_frames,
2017            audio_frames_dropped_by_pipeline: raw.pipeline_dropped_audio_frames,
2018            metadata_frames_dropped_by_pipeline: raw.pipeline_dropped_metadata_frames,
2019            writer_dropped: raw.writer_dropped_frames,
2020            rollover_count: raw.rollover_count,
2021            recording_time: FilePosition::from_ticks(raw.recording_time_100ns),
2022            last_video_pts: FilePosition::from_ticks(raw.last_video_pts_100ns),
2023            last_audio_pts: FilePosition::from_ticks(raw.last_audio_pts_100ns),
2024            last_metadata_pts: FilePosition::from_ticks(raw.last_metadata_pts_100ns),
2025        }
2026    }
2027}
2028
2029#[cfg(test)]
2030mod tests {
2031    use super::*;
2032
2033    fn decode_recorder_event(raw: &NDIlib_file_recorder_event_t) -> RecorderEvent {
2034        RecorderEvent::from_sdk(
2035            raw,
2036            RecorderEventKind::from_raw(raw.type_),
2037            EventTextRef::from_buffer(&raw.p_path),
2038        )
2039    }
2040
2041    #[test]
2042    fn event_text_debug_prints_text_and_only_nondefault_evidence() {
2043        let text = |bytes: &[u8]| {
2044            EventText::from_buffer(&bytes.iter().map(|&byte| byte as c_char).collect::<Vec<_>>())
2045        };
2046        assert_eq!(
2047            format!("{:?}", text(b"take.mkv\0\0")),
2048            "EventText { text: \"take.mkv\" }"
2049        );
2050        assert_eq!(
2051            format!("{:?}", text(b"take")),
2052            "EventText { text: \"take\", terminated: false, possibly_truncated: true }"
2053        );
2054        assert_eq!(
2055            format!("{:?}", text(b"\xff\0\0")),
2056            "EventText { text: \"�\" }"
2057        );
2058        assert_eq!(
2059            format!("{:?}", text(b"x\0")),
2060            "EventText { text: \"x\", possibly_truncated: true }"
2061        );
2062    }
2063
2064    #[test]
2065    fn session_timecodes_refuse_only_the_send_sentinel() {
2066        for timecode in [Timecode::SYNTHESIZE, Timecode::default()] {
2067            let error = SessionTimecode::new(timecode).unwrap_err();
2068            assert!(matches!(
2069                error,
2070                Error::InvalidInput(crate::InputDefect::SynthesizeRecordingStart)
2071            ));
2072        }
2073        for ticks in [i64::MIN, -1, 0, 360_000_000_000, i64::MAX - 1] {
2074            let timecode = Timecode::from_ticks(ticks);
2075            let start = SessionTimecode::new(timecode).unwrap();
2076            assert_eq!(start.timecode(), timecode);
2077            assert_eq!(start.ticks(), ticks);
2078        }
2079    }
2080
2081    #[test]
2082    fn file_statistics_preserve_each_native_media_and_stream_counter() {
2083        let playback = PlayerStats::from_sdk(&NDIlib_file_player_stats_t {
2084            video_frames_sent: [11, 22],
2085            audio_frames_sent: 33,
2086            metadata_frames_sent: u64::MAX,
2087            playback_wallclock_100ns: 55,
2088        });
2089        assert_eq!(playback.video_frames_sent(StreamTier::Program), 11);
2090        assert_eq!(playback.video_frames_sent(StreamTier::Preview), 22);
2091        assert_eq!(playback.audio_frames_sent(), 33);
2092        assert_eq!(playback.metadata_frames_sent(), u64::MAX);
2093        assert_eq!(playback.wallclock().ticks(), 55);
2094
2095        let recording = RecorderStats::from_sdk(&NDIlib_file_recorder_stats_t {
2096            bytes_written: u64::MAX,
2097            video_frames: 1,
2098            audio_frames: 2,
2099            metadata_frames: 3,
2100            receiver_dropped_video_frames: 4,
2101            receiver_dropped_audio_frames: 5,
2102            receiver_dropped_metadata_frames: 6,
2103            pipeline_dropped_video_frames: 7,
2104            pipeline_dropped_audio_frames: 8,
2105            pipeline_dropped_metadata_frames: 9,
2106            writer_dropped_frames: 10,
2107            rollover_count: 11,
2108            recording_time_100ns: 12,
2109            last_video_pts_100ns: 13,
2110            last_audio_pts_100ns: 14,
2111            last_metadata_pts_100ns: 15,
2112        });
2113        assert_eq!(recording.bytes_written(), u64::MAX);
2114        assert_eq!(recording.video_frames_written(), 1);
2115        assert_eq!(recording.audio_frames_written(), 2);
2116        assert_eq!(recording.metadata_frames_written(), 3);
2117        assert_eq!(recording.video_frames_dropped_by_receiver(), 4);
2118        assert_eq!(recording.audio_frames_dropped_by_receiver(), 5);
2119        assert_eq!(recording.metadata_frames_dropped_by_receiver(), 6);
2120        assert_eq!(recording.video_frames_dropped_by_pipeline(), 7);
2121        assert_eq!(recording.audio_frames_dropped_by_pipeline(), 8);
2122        assert_eq!(recording.metadata_frames_dropped_by_pipeline(), 9);
2123        assert_eq!(recording.frames_dropped_by_writer(), 10);
2124        assert_eq!(recording.rollover_count(), 11);
2125        assert_eq!(recording.recording_time().ticks(), 12);
2126        assert_eq!(recording.last_video_pts().ticks(), 13);
2127        assert_eq!(recording.last_audio_pts().ticks(), 14);
2128        assert_eq!(recording.last_metadata_pts().ticks(), 15);
2129    }
2130
2131    fn invalid_cause<T: std::fmt::Debug>(result: Result<T>) -> crate::InputDefect {
2132        match result {
2133            Err(Error::InvalidInput(text)) => text,
2134            other => panic!("expected InvalidInput, got {other:?}"),
2135        }
2136    }
2137
2138    /// Where the NUL that `result` was refused for is, in bytes.
2139    fn nul_position<T: std::fmt::Debug>(result: Result<T>) -> usize {
2140        match result {
2141            Err(Error::InvalidCString(error)) => error.nul_position(),
2142            other => panic!("expected InvalidCString, got {other:?}"),
2143        }
2144    }
2145
2146    #[test]
2147    fn path_errors_name_what_the_path_is() {
2148        let empty = Path::new("");
2149        assert_eq!(
2150            invalid_cause(path_string(empty)),
2151            crate::InputDefect::Empty { what: "file path" }
2152        );
2153        assert_eq!(
2154            invalid_cause(RecordingTarget::new(empty)),
2155            crate::InputDefect::Empty {
2156                what: "recording target"
2157            }
2158        );
2159    }
2160
2161    #[test]
2162    fn a_nul_in_paths_or_scalar_strings_is_the_crates_c_string_error() {
2163        // An absolute path on every platform: `/take` is not one on Windows, where
2164        // it would be resolved against the current drive and the NUL would sit
2165        // after that prefix. The path is used as it is, so the NUL stays where
2166        // `str::find` puts it in the text.
2167        let nul = std::env::current_dir().unwrap().join("take\0.mkv");
2168        assert!(nul.is_absolute());
2169        let at = nul.to_str().unwrap().find('\0').unwrap();
2170        assert_eq!(nul_position(path_string(&nul)), at);
2171        assert_eq!(nul_position(RecordingTarget::new(&nul)), at);
2172        assert_eq!(nul_position(SourceSpec::new("cam\0era")), 3);
2173        assert_eq!(nul_position(SourceSpec::from_url("url\0tail")), 3);
2174        assert_eq!(
2175            nul_position(FilePlayerOptions::new("Re\0play").resolve()),
2176            2
2177        );
2178        let pattern = FileNaming::Pattern("{prefix}\0_{index}.mkv".into());
2179        assert_eq!(
2180            nul_position(
2181                FileRecorderOptions::new(SourceSpec::new("camera").unwrap())
2182                    .naming(pattern)
2183                    .check()
2184            ),
2185            8
2186        );
2187    }
2188
2189    #[cfg(unix)]
2190    #[test]
2191    fn non_utf8_paths_are_named_by_their_use() {
2192        use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
2193        let path = Path::new(OsStr::from_bytes(b"/take-\xff.mkv"));
2194        assert_eq!(
2195            invalid_cause(path_string(path)),
2196            crate::InputDefect::PathNotUtf8 { what: "file path" }
2197        );
2198        assert_eq!(
2199            invalid_cause(RecordingTarget::new(path)),
2200            crate::InputDefect::PathNotUtf8 {
2201                what: "recording target"
2202            }
2203        );
2204    }
2205
2206    #[test]
2207    fn relative_paths_are_made_absolute_once() {
2208        let text = path_string(Path::new("take.mkv")).unwrap();
2209        let absolute = Path::new(text.as_str());
2210        assert!(absolute.is_absolute());
2211        assert_eq!(RecordingTarget::new("take.mkv").unwrap().path(), absolute);
2212        assert_eq!(path_string(absolute).unwrap(), text);
2213    }
2214
2215    #[test]
2216    fn relative_paths_reject_nul_as_a_c_string_error() {
2217        let path = Path::new("take\0.mkv");
2218        assert_eq!(nul_position(path_string(path)), 4);
2219        assert_eq!(nul_position(RecordingTarget::new(path)), 4);
2220    }
2221
2222    #[cfg(windows)]
2223    #[test]
2224    fn windows_drive_relative_paths_are_made_absolute() {
2225        for path in [r"C:take.mkv", r"C:folder\take.mkv", r"\take.mkv"] {
2226            let text = path_string(Path::new(path)).unwrap();
2227            let absolute = Path::new(text.as_str());
2228            assert!(absolute.is_absolute(), "{absolute:?}");
2229            assert!(absolute.ends_with("take.mkv"));
2230            assert_eq!(path_string(Path::new(path)).unwrap(), text);
2231            assert_eq!(RecordingTarget::new(path).unwrap().path(), absolute);
2232        }
2233    }
2234
2235    #[cfg(windows)]
2236    #[test]
2237    fn windows_recording_prefixes_preserve_the_suffix_after_the_drive_or_root() {
2238        let drive = std::path::absolute("C:.").unwrap();
2239        let root = std::path::absolute(r"\").unwrap();
2240        let exact = NamePattern::new(Some(EXACT_PATTERN)).unwrap();
2241        let hidden = NamePattern::new(Some("{prefix}hidden.mkv")).unwrap();
2242        for (input, anchor, suffix) in [
2243            (r"C:folder\.", &drive, r"folder\."),
2244            (r"\folder\.", &root, r"folder\."),
2245            ("C:", &drive, ""),
2246            (r"\", &root, ""),
2247        ] {
2248            let target = RecordingTarget::new(input).unwrap();
2249            let anchor = anchor
2250                .to_str()
2251                .unwrap()
2252                .trim_end_matches(std::path::is_separator);
2253            let absolute = format!("{anchor}\\{suffix}");
2254            assert_eq!(target.path().to_str().unwrap(), absolute);
2255            assert_eq!(
2256                invalid_cause(exact.check(&target)),
2257                crate::InputDefect::RecordingPathMissingFilename
2258            );
2259            assert_eq!(
2260                hidden.first_file(&target).unwrap().to_str().unwrap(),
2261                format!("{absolute}hidden.mkv")
2262            );
2263        }
2264    }
2265
2266    #[cfg(windows)]
2267    #[test]
2268    fn windows_recording_patterns_require_a_rooted_drive_or_unc_path() {
2269        let target = RecordingTarget::new("take").unwrap();
2270        for pattern in [
2271            r"C:take_{index:03}.mkv",
2272            r"C:folder\take_{index:03}.mkv",
2273            r"\take_{index:03}.mkv",
2274            "/take_{index:03}.mkv",
2275        ] {
2276            let naming = NamePattern::new(Some(pattern)).unwrap();
2277            assert_eq!(
2278                invalid_cause(naming.first_file(&target)),
2279                crate::InputDefect::RecordingPathNotAbsolute,
2280                "{pattern}"
2281            );
2282        }
2283        for (pattern, expected) in [
2284            (
2285                r"C:\recordings\.\take{index}.mkv",
2286                r"C:\recordings\.\take1.mkv",
2287            ),
2288            (
2289                "C://recordings/./take{index}.mkv",
2290                "C://recordings/./take1.mkv",
2291            ),
2292            (r"\\host\share\take{index}.mkv", r"\\host\share\take1.mkv"),
2293        ] {
2294            let naming = NamePattern::new(Some(pattern)).unwrap();
2295            assert_eq!(naming.first_file(&target).unwrap().to_str(), Some(expected));
2296        }
2297    }
2298
2299    #[cfg(unix)]
2300    #[test]
2301    fn unix_recording_patterns_preserve_literal_absolute_paths() {
2302        let target = RecordingTarget::new("take").unwrap();
2303        let naming = NamePattern::new(Some("//recordings/./take{index}.mkv")).unwrap();
2304        assert_eq!(
2305            naming.first_file(&target).unwrap().to_str(),
2306            Some("//recordings/./take1.mkv")
2307        );
2308    }
2309
2310    #[test]
2311    fn source_selection_is_explicit_and_rejects_nul() {
2312        assert!(SourceSpec::new("").is_err());
2313        assert!(SourceSpec::from_url("").is_err());
2314        assert!(SourceSpec::from_url("url\0tail").is_err());
2315        let source = SourceSpec::from_url("ndi://camera").unwrap();
2316        assert_eq!(source.name(), None);
2317        assert_eq!(source.url(), Some("ndi://camera"));
2318    }
2319
2320    #[test]
2321    fn file_text_retains_utf8_termination_identity_and_allocation_budgets() {
2322        use std::hash::{Hash, Hasher};
2323        fn hash<T: Hash>(value: &T) -> u64 {
2324            let mut state = std::hash::DefaultHasher::new();
2325            value.hash(&mut state);
2326            state.finish()
2327        }
2328        let (source, allocations) =
2329            crate::test_alloc::allocation_count(|| SourceSpec::new("Caméra").unwrap());
2330        assert_eq!(allocations, 1);
2331        let (address, allocations) =
2332            crate::test_alloc::allocation_count(|| SourceSpec::from_url("Caméra").unwrap());
2333        assert_eq!(allocations, 1);
2334        let (_, allocations) = crate::test_alloc::allocation_count(|| {
2335            for _ in 0..100 {
2336                assert_eq!(source.name(), Some("Caméra"));
2337                assert_eq!(source.url(), None);
2338                assert_eq!(address.name(), None);
2339                assert_eq!(address.url(), Some("Caméra"));
2340            }
2341        });
2342        assert_eq!(allocations, 0);
2343        let same = SourceSpec::new("Caméra").unwrap();
2344        assert_eq!(source, same);
2345        assert_eq!(hash(&source), hash(&same));
2346        let same = SourceSpec::from_url("Caméra").unwrap();
2347        assert_eq!(address, same);
2348        assert_eq!(hash(&address), hash(&same));
2349        assert_ne!(source, address);
2350        assert_ne!(source, SourceSpec::new("Other camera").unwrap());
2351        let raw = source.raw_source();
2352        assert!(!raw.p_ndi_name.is_null());
2353        // SAFETY: FileText owns its only trailing NUL and the bytes stay live.
2354        assert_eq!(
2355            unsafe { std::ffi::CStr::from_ptr(raw.p_ndi_name) }.to_bytes(),
2356            "Caméra".as_bytes()
2357        );
2358
2359        let target = RecordingTarget::new("take-é").unwrap();
2360        let same = RecordingTarget::new(target.path()).unwrap();
2361        assert_eq!(target, same);
2362        assert_eq!(hash(&target), hash(&same));
2363        assert_ne!(target, RecordingTarget::new("take-other").unwrap());
2364        assert_eq!(target.prefix.as_str(), target.path().to_str().unwrap());
2365    }
2366
2367    #[test]
2368    fn recorder_option_check_keeps_one_copy_of_the_explicit_pattern() {
2369        let options = FileRecorderOptions::new(SourceSpec::new("camera").unwrap())
2370            .naming(FileNaming::Pattern("{prefix}_{index}.mkv".into()));
2371        let (checked, allocations) =
2372            crate::test_alloc::allocation_count(|| options.check().unwrap());
2373        // The source name, the filename pattern, and the four compiled parts.
2374        assert_eq!(allocations, 3);
2375        let pattern = checked.naming.pattern.as_ref().unwrap();
2376        assert_eq!(pattern.as_str(), "{prefix}_{index}.mkv");
2377        assert_eq!(checked.naming.as_sdk_ptr(), pattern.as_ptr());
2378    }
2379
2380    #[test]
2381    fn cached_pattern_parts_avoid_preflight_parse_allocation() {
2382        let target = RecordingTarget::new("take").unwrap();
2383        let pattern = NamePattern::new(Some(DEFAULT_PATTERN)).unwrap();
2384        let (file, allocations) =
2385            crate::test_alloc::allocation_count(|| pattern.first_file(&target).unwrap());
2386        assert!(file.ends_with("take_001.mkv"));
2387        assert!(allocations <= 3, "preflight made {allocations} allocations");
2388    }
2389
2390    #[test]
2391    fn filename_indexes_cannot_change_the_preflight_directory() {
2392        for pattern in [
2393            "{prefix}/{index:03}/clip.mkv",
2394            "{index}/{prefix}.mkv",
2395            "{prefix}_{index}/clip.mkv",
2396            "{index}{prefix}.mkv",
2397            "{prefix}_{index}{prefix}.mkv",
2398            "{prefix}/{index}_{index}/clip.mkv",
2399        ] {
2400            assert_eq!(
2401                invalid_cause(NamePattern::new(Some(pattern))),
2402                crate::InputDefect::FilenamePatternIndexInDirectory,
2403                "{pattern}"
2404            );
2405        }
2406        for pattern in [
2407            DEFAULT_PATTERN,
2408            EXACT_PATTERN,
2409            "{prefix}/{index:03}.mkv",
2410            "{prefix}_{index:03}.mkv",
2411            "{prefix}_{index}_{index:03}.mkv",
2412            "{prefix}{prefix}_{index}.mkv",
2413        ] {
2414            assert!(NamePattern::new(Some(pattern)).is_ok(), "{pattern}");
2415        }
2416        #[cfg(windows)]
2417        assert_eq!(
2418            invalid_cause(NamePattern::new(Some(r"{prefix}\{index}\clip.mkv"))),
2419            crate::InputDefect::FilenamePatternIndexInDirectory
2420        );
2421        #[cfg(unix)]
2422        assert!(NamePattern::new(Some(r"{prefix}_{index}\clip.mkv")).is_ok());
2423    }
2424
2425    #[test]
2426    fn discovered_sources_pin_the_complete_endpoint_without_name_precedence() {
2427        use crate::{Source, SourceAddress};
2428        for address in [
2429            SourceAddress::new("192.0.2.10:5962").unwrap(),
2430            SourceAddress::new("ndi://user@camera.local:5962/path?opaque=1").unwrap(),
2431        ] {
2432            let text = address.as_str();
2433            for name in ["STUDIO (Camera 2)", ""] {
2434                let selected = Source::new(name).unwrap().with_address(address.clone());
2435                let spec = SourceSpec::try_from(&selected).unwrap();
2436                assert_eq!(spec.name(), None, "name must not override an endpoint");
2437                assert_eq!(spec.url(), Some(text));
2438                assert_eq!(spec.clone(), spec);
2439            }
2440        }
2441        let named = Source::new("STUDIO (Camera 2)").unwrap();
2442        let spec = SourceSpec::try_from(&named).unwrap();
2443        assert_eq!(spec.name(), Some(named.name()));
2444        assert_eq!(spec.url(), None);
2445        let addressed = named
2446            .clone()
2447            .with_address(SourceAddress::new("192.0.2.10:5962").unwrap());
2448        let logical = SourceSpec::new(addressed.name()).unwrap();
2449        assert_eq!(logical.name(), Some(addressed.name()));
2450        assert_eq!(logical.url(), None);
2451        let selected = named.clone().with_address(SourceAddress::new("").unwrap());
2452        assert!(
2453            SourceSpec::try_from(&selected).is_err(),
2454            "invalid endpoint must not fall back to name"
2455        );
2456        assert!(SourceSpec::try_from(&Source::new("").unwrap()).is_err());
2457        assert!(matches!(
2458            Source::new("bad\0name"),
2459            Err(Error::InvalidCString(_))
2460        ));
2461        assert!(matches!(
2462            SourceAddress::new("bad\0endpoint"),
2463            Err(Error::InvalidCString(_))
2464        ));
2465    }
2466
2467    #[test]
2468    fn player_group_lists_round_trip_and_reject_ambiguous_elements() {
2469        let options = FilePlayerOptions::new("Replay").groups(["Public", "Studio"]);
2470        assert_eq!(
2471            options.configured_groups(),
2472            Some(&["Public".to_owned(), "Studio".to_owned()][..])
2473        );
2474        assert_eq!(options.clone(), options);
2475        assert_eq!(
2476            options.resolve().unwrap().groups.unwrap().as_bytes(),
2477            b"Public,Studio"
2478        );
2479        for value in ["", "Public,Studio", "bad\0group"] {
2480            assert_eq!(
2481                invalid_cause(
2482                    FilePlayerOptions::new("Replay")
2483                        .groups(["valid", value])
2484                        .resolve()
2485                ),
2486                crate::InputDefect::ListElement {
2487                    setting: "player groups",
2488                    index: 1
2489                },
2490            );
2491        }
2492    }
2493
2494    #[test]
2495    fn player_options_are_checked_when_they_are_resolved() {
2496        assert_eq!(
2497            invalid_cause(
2498                FilePlayerOptions::new("Replay")
2499                    .groups([] as [&str; 0])
2500                    .resolve()
2501            ),
2502            crate::InputDefect::Empty {
2503                what: "player groups"
2504            }
2505        );
2506        assert!(FilePlayerOptions::new("Replay")
2507            .resolve()
2508            .unwrap()
2509            .groups
2510            .is_none());
2511        assert_eq!(
2512            invalid_cause(FilePlayerOptions::new("").resolve()),
2513            crate::InputDefect::Empty {
2514                what: "player name"
2515            }
2516        );
2517    }
2518
2519    #[test]
2520    fn a_drop_wait_beyond_the_largest_timeout_is_refused_when_resolved() {
2521        let options = FileRecorderOptions::new(SourceSpec::new("camera").unwrap());
2522        assert_eq!(options.drop_wait, FileRecorderOptions::DEFAULT_DROP_WAIT);
2523        options
2524            .clone()
2525            .drop_wait(crate::MAX_TIMEOUT)
2526            .check()
2527            .unwrap();
2528        let requested = crate::MAX_TIMEOUT + Duration::from_millis(1);
2529        assert_eq!(
2530            invalid_cause(options.drop_wait(requested).check()),
2531            crate::InputDefect::TimeoutTooLong {
2532                requested: requested.into()
2533            }
2534        );
2535    }
2536
2537    #[test]
2538    fn tracks_do_not_silently_map_empty_to_all() {
2539        let options = FileRecorderOptions::new(SourceSpec::new("camera").unwrap());
2540        assert_eq!(options.tracks, MediaTypes::ALL);
2541        assert!(options.check().is_ok());
2542        let empty = options.clone().tracks(MediaTypes::NONE);
2543        assert_eq!(
2544            invalid_cause(empty.check()),
2545            crate::InputDefect::EmptyRecordingTracks
2546        );
2547        let some = options.tracks(MediaTypes::AUDIO | MediaTypes::METADATA);
2548        assert_eq!(some.tracks, MediaTypes::AUDIO | MediaTypes::METADATA);
2549        assert!(some.check().is_ok());
2550    }
2551
2552    /// The pattern the SDK is given for `naming`.
2553    fn sdk_pattern(naming: FileNaming) -> Result<Option<String>> {
2554        let options = FileRecorderOptions::new(SourceSpec::new("camera").unwrap()).naming(naming);
2555        Ok(options
2556            .check()?
2557            .naming
2558            .pattern
2559            .map(|pattern| pattern.as_str().to_owned()))
2560    }
2561
2562    #[test]
2563    fn filename_patterns_are_validated_without_filesystem_mutation() {
2564        assert_eq!(sdk_pattern(FileNaming::default()).unwrap(), None);
2565        assert_eq!(sdk_pattern(FileNaming::Indexed).unwrap(), None);
2566        assert_eq!(
2567            sdk_pattern(FileNaming::Exact).unwrap().as_deref(),
2568            Some("{prefix}")
2569        );
2570        assert_eq!(
2571            sdk_pattern(FileNaming::Pattern("{prefix}_{index:03}.mkv".into()))
2572                .unwrap()
2573                .as_deref(),
2574            Some("{prefix}_{index:03}.mkv")
2575        );
2576        for (pattern, cause) in [
2577            (
2578                "",
2579                crate::InputDefect::Empty {
2580                    what: "filename pattern",
2581                },
2582            ),
2583            ("{prefix", crate::InputDefect::FilenamePatternBrace),
2584            ("prefix}", crate::InputDefect::FilenamePatternBrace),
2585            (
2586                "{unknown}",
2587                crate::InputDefect::FilenamePatternToken {
2588                    token: "unknown".into(),
2589                },
2590            ),
2591            (
2592                "{index:0}",
2593                crate::InputDefect::FilenamePatternToken {
2594                    token: "index:0".into(),
2595                },
2596            ),
2597            (
2598                "{index:2000}",
2599                crate::InputDefect::FilenamePatternToken {
2600                    token: "index:2000".into(),
2601                },
2602            ),
2603        ] {
2604            assert_eq!(
2605                invalid_cause(sdk_pattern(FileNaming::Pattern(pattern.into()))),
2606                cause,
2607                "{pattern:?}"
2608            );
2609        }
2610        let target = RecordingTarget::new("nonexistent-parent/take").unwrap();
2611        assert!(target.path().is_absolute());
2612        assert!(target.path().ends_with("nonexistent-parent/take"));
2613    }
2614
2615    #[test]
2616    fn only_a_pending_waiter_is_retryable() {
2617        use StateConflict::*;
2618        for (state, retryable) in [
2619            (PreviousSessionOpen, false),
2620            (IncompleteFileTracking, false),
2621            (EarlierSessionEvents, false),
2622            (StopNotRequested, false),
2623            (Stopping, false),
2624            (NotRecording, false),
2625            (ExactFileName, false),
2626            (WaiterPending, true),
2627            (Closed, false),
2628            (OwnerFailed, false),
2629        ] {
2630            assert_eq!(state.is_retryable(), retryable, "{state:?}");
2631        }
2632    }
2633
2634    #[test]
2635    fn state_errors_keep_their_messages() {
2636        assert_eq!(
2637            StateConflict::PreviousSessionOpen.to_string(),
2638            "finish the previous session before starting another"
2639        );
2640        assert_eq!(
2641            StateConflict::IncompleteFileTracking.to_string(),
2642            "file tracking is incomplete; reset the recorder before starting another session"
2643        );
2644        assert_eq!(
2645            Error::InvalidState(StateConflict::Stopping).to_string(),
2646            "Invalid File API state: the session is stopping"
2647        );
2648    }
2649
2650    fn options() -> FileRecorderOptions {
2651        FileRecorderOptions::new(SourceSpec::new("camera").unwrap())
2652    }
2653
2654    fn refused(options: FileRecorderOptions) -> crate::InputDefect {
2655        match options.check() {
2656            Err(Error::InvalidInput(reason)) => reason,
2657            Err(other) => panic!("expected the options to be refused as input: {other}"),
2658            Ok(_) => panic!("expected the options to be refused"),
2659        }
2660    }
2661
2662    #[test]
2663    fn a_pattern_is_exact_when_it_has_no_index() {
2664        for (pattern, exact) in [
2665            (DEFAULT_PATTERN, false),
2666            (EXACT_PATTERN, true),
2667            ("{prefix}.mkv", true),
2668            ("{prefix}_{index}.mkv", false),
2669            ("{prefix}/{index:03}.mkv", false),
2670        ] {
2671            assert_eq!(
2672                NamePattern::new(Some(pattern)).unwrap().is_exact(),
2673                exact,
2674                "{pattern:?}"
2675            );
2676        }
2677        let exact = |options: FileRecorderOptions| options.check().unwrap().naming.is_exact();
2678        assert!(!exact(options()));
2679        assert!(exact(options().naming(FileNaming::Exact)));
2680        assert!(exact(
2681            options().naming(FileNaming::Pattern("{prefix}.mkv".into()))
2682        ));
2683        assert!(!exact(
2684            options()
2685                .naming(FileNaming::Exact)
2686                .naming(FileNaming::Indexed)
2687        ));
2688    }
2689
2690    #[test]
2691    fn format_change_rollover_follows_the_naming_unless_set() {
2692        let rolls = |options: FileRecorderOptions| options.check().unwrap().format_change_rollover;
2693        assert!(rolls(options()));
2694        assert!(!rolls(options().naming(FileNaming::Exact)));
2695        assert!(!rolls(options().format_change_rollover(false)));
2696        assert!(!rolls(
2697            options()
2698                .naming(FileNaming::Exact)
2699                .format_change_rollover(false)
2700        ));
2701        assert!(rolls(
2702            options()
2703                .naming(FileNaming::Pattern("{prefix}-{index:2}.mkv".into()))
2704                .format_change_rollover(true)
2705        ));
2706    }
2707
2708    #[test]
2709    fn clearing_rollover_override_recomputes_the_policy_for_the_final_template() {
2710        let template = options().format_change_rollover(true);
2711        assert!(template.clone().naming(FileNaming::Exact).check().is_err());
2712        let exact = template
2713            .clone()
2714            .naming(FileNaming::Exact)
2715            .clear_format_change_rollover()
2716            .check()
2717            .unwrap();
2718        assert!(!exact.format_change_rollover);
2719        let indexed = template
2720            .format_change_rollover(false)
2721            .clear_format_change_rollover()
2722            .check()
2723            .unwrap();
2724        assert!(indexed.format_change_rollover);
2725    }
2726
2727    #[test]
2728    fn player_template_clear_groups_restores_the_native_null_default() {
2729        let template = FilePlayerOptions::new("Replay A").groups([] as [&str; 0]);
2730        assert_eq!(
2731            invalid_cause(template.resolve()),
2732            crate::InputDefect::Empty {
2733                what: "player groups"
2734            }
2735        );
2736        let inherited = template.name("Replay B").clear_groups().resolve().unwrap();
2737        assert_eq!(inherited.name.as_str(), "Replay B");
2738        assert!(inherited.groups.is_none());
2739    }
2740
2741    #[test]
2742    fn an_exact_name_that_would_roll_over_is_refused_whatever_the_call_order() {
2743        for options in [
2744            options()
2745                .naming(FileNaming::Exact)
2746                .format_change_rollover(true),
2747            options()
2748                .format_change_rollover(true)
2749                .naming(FileNaming::Exact),
2750            options()
2751                .format_change_rollover(true)
2752                .naming(FileNaming::Pattern("{prefix}.mkv".into())),
2753        ] {
2754            assert_eq!(
2755                refused(options),
2756                crate::InputDefect::ExactNameFormatRollover
2757            );
2758        }
2759        for options in [
2760            options().naming(FileNaming::Exact).rollover_size(1 << 20),
2761            options().rollover_size(1 << 20).naming(FileNaming::Exact),
2762        ] {
2763            assert_eq!(refused(options), crate::InputDefect::ExactNameSizeRollover);
2764        }
2765        // Indexed names may roll over either way.
2766        options()
2767            .rollover_size(1 << 20)
2768            .format_change_rollover(true)
2769            .check()
2770            .unwrap();
2771    }
2772
2773    fn io_kind(result: Result<()>) -> std::io::ErrorKind {
2774        match result {
2775            Err(Error::Io(error)) => error.kind(),
2776            other => panic!("expected a filesystem error: {other:?}"),
2777        }
2778    }
2779
2780    #[test]
2781    fn recording_preflight_requires_an_expanded_filename() {
2782        let directory = crate::test_support::FixtureDir::create("filename-ending");
2783        let check = |pattern, prefix| {
2784            let target = RecordingTarget::new(directory.join(prefix)).unwrap();
2785            NamePattern::new(Some(pattern)).unwrap().check(&target)
2786        };
2787        for (pattern, prefix) in [
2788            (EXACT_PATTERN, "missing/"),
2789            (EXACT_PATTERN, "missing/."),
2790            (EXACT_PATTERN, "missing/.."),
2791            ("{prefix}/", "missing"),
2792            ("{prefix}.", "missing/"),
2793            ("{prefix}.", "missing/."),
2794            #[cfg(windows)]
2795            (EXACT_PATTERN, r"missing\"),
2796            #[cfg(windows)]
2797            ("{prefix}.", r"missing\."),
2798        ] {
2799            assert_eq!(
2800                invalid_cause(check(pattern, prefix)),
2801                crate::InputDefect::RecordingPathMissingFilename,
2802                "{pattern:?} with prefix {prefix:?}"
2803            );
2804        }
2805
2806        std::fs::create_dir(directory.join("folder")).unwrap();
2807        for (pattern, prefix) in [
2808            (EXACT_PATTERN, ".hidden"),
2809            ("{prefix}hidden", "folder/."),
2810            ("{prefix}take.mkv", "folder/"),
2811            #[cfg(unix)]
2812            (EXACT_PATTERN, r"trailing\"),
2813        ] {
2814            check(pattern, prefix).unwrap();
2815        }
2816    }
2817
2818    #[test]
2819    fn relative_recording_prefixes_keep_their_spelling_after_the_directory_changes() {
2820        use crate::file::{mock, FileRecorder, RecorderState};
2821
2822        const CHANGED_DIRECTORY: &str = "GRAFTON_NDI_TEST_RECORDING_PREFIX_CHANGED_DIRECTORY";
2823        let Some(changed) = std::env::var_os(CHANGED_DIRECTORY) else {
2824            let scratch = crate::test_support::FixtureDir::create("relative-recording-prefixes");
2825            let original = scratch.join("original");
2826            let changed = scratch.join("changed");
2827            std::fs::create_dir_all(original.join("folder")).unwrap();
2828            std::fs::create_dir(&changed).unwrap();
2829            let output = crate::test_support::TestChild::new(
2830                "file::types::tests::relative_recording_prefixes_keep_their_spelling_after_the_directory_changes",
2831            )
2832            .current_dir(original)
2833            .env(CHANGED_DIRECTORY, changed)
2834            .run();
2835            assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
2836            return;
2837        };
2838        let original = std::env::current_dir().unwrap();
2839        let targets = |prefix| {
2840            let relative = RecordingTarget::new(prefix).unwrap();
2841            let absolute = RecordingTarget::new(original.join(prefix)).unwrap();
2842            assert_eq!(relative.path().as_os_str(), absolute.path().as_os_str());
2843            [relative, absolute]
2844        };
2845        let directory_only = [".", "..", "missing/", "missing/.", "missing/.."].map(targets);
2846        let files = [
2847            (EXACT_PATTERN, ".hidden.mkv", ".hidden.mkv"),
2848            ("{prefix}hidden.mkv", "folder/.", "folder/.hidden.mkv"),
2849            ("{prefix}hidden.mkv", "folder/..", "folder/..hidden.mkv"),
2850            ("{prefix}take.mkv", "folder/", "folder/take.mkv"),
2851            ("{prefix}{index:03}.mkv", "folder/.", "folder/.001.mkv"),
2852            ("{prefix}{index:03}.mkv", "folder/", "folder/001.mkv"),
2853        ]
2854        .map(|(pattern, prefix, expected)| (pattern, targets(prefix), original.join(expected)));
2855        std::env::set_current_dir(changed).unwrap();
2856
2857        let device = mock::Recorder::new(mock::Closing::AtStop);
2858        device.install();
2859        let options = FileRecorderOptions::new(SourceSpec::new("mock source").unwrap())
2860            .naming(FileNaming::Exact);
2861        let mut recorder = FileRecorder::new(&mock::recorder_api(), &options).unwrap();
2862        for target in directory_only.iter().flatten() {
2863            assert_eq!(
2864                invalid_cause(recorder.start(target, RecordingTimecode::Preserve)),
2865                crate::InputDefect::RecordingPathMissingFilename,
2866                "{target:?}"
2867            );
2868        }
2869        assert_eq!(recorder.state(), RecorderState::Idle);
2870        let valid = RecordingTarget::new(original.join("valid.mkv")).unwrap();
2871        recorder.start(&valid, RecordingTimecode::Preserve).unwrap();
2872        for target in directory_only.iter().flatten() {
2873            assert_eq!(
2874                invalid_cause(recorder.rollover(target)),
2875                crate::InputDefect::RecordingPathMissingFilename,
2876                "{target:?}"
2877            );
2878        }
2879        assert_eq!(recorder.state(), RecorderState::Recording);
2880        for (pattern, targets, expected) in files {
2881            let pattern = NamePattern::new(Some(pattern)).unwrap();
2882            for target in targets {
2883                assert_eq!(
2884                    pattern.first_file(&target).unwrap().as_os_str(),
2885                    expected.as_os_str()
2886                );
2887                pattern.check(&target).unwrap();
2888            }
2889        }
2890    }
2891
2892    #[test]
2893    #[cfg(windows)]
2894    fn recording_preflight_refuses_a_bare_unc_share() {
2895        let root = RecordingTarget::new(r"\\grafton-ndi-invalid-host\share").unwrap();
2896        let exact = NamePattern::new(Some(EXACT_PATTERN)).unwrap();
2897        assert_eq!(
2898            invalid_cause(exact.check(&root)),
2899            crate::InputDefect::RecordingPathMissingFilename,
2900        );
2901    }
2902
2903    #[test]
2904    fn the_file_a_pattern_names_is_where_it_is_checked() {
2905        let directory = crate::test_support::FixtureDir::create("check");
2906        let target = RecordingTarget::new(directory.join("take")).unwrap();
2907        let first = |pattern: &str| {
2908            NamePattern::new(Some(pattern))
2909                .unwrap()
2910                .first_file(&target)
2911                .unwrap()
2912        };
2913        assert_eq!(first(DEFAULT_PATTERN), directory.join("take_001.mkv"));
2914        assert_eq!(first(EXACT_PATTERN), directory.join("take"));
2915        assert_eq!(
2916            first("{prefix}/{index:03}.mkv"),
2917            directory.join("take/001.mkv")
2918        );
2919
2920        // The default pattern checks the target's own directory.
2921        let indexed = NamePattern::new(Some(DEFAULT_PATTERN)).unwrap();
2922        indexed.check(&target).unwrap();
2923        let missing = RecordingTarget::new(directory.join("absent/take")).unwrap();
2924        assert_eq!(
2925            io_kind(indexed.check(&missing)),
2926            std::io::ErrorKind::NotFound
2927        );
2928        // A pattern that names a directory of its own checks that one.
2929        let nested = NamePattern::new(Some("{prefix}/{index:03}.mkv")).unwrap();
2930        assert_eq!(io_kind(nested.check(&target)), std::io::ErrorKind::NotFound);
2931        std::fs::create_dir(directory.join("take")).unwrap();
2932        nested.check(&target).unwrap();
2933
2934        // An exact name refuses a file that exists, and an indexed one does not.
2935        let exact = NamePattern::new(Some("{prefix}.mkv")).unwrap();
2936        exact.check(&target).unwrap();
2937        std::fs::write(directory.join("take.mkv"), b"kept").unwrap();
2938        assert_eq!(
2939            io_kind(exact.check(&target)),
2940            std::io::ErrorKind::AlreadyExists
2941        );
2942        std::fs::write(directory.join("take_001.mkv"), b"kept").unwrap();
2943        indexed.check(&target).unwrap();
2944        assert_eq!(std::fs::read(directory.join("take.mkv")).unwrap(), b"kept");
2945    }
2946
2947    #[test]
2948    fn indexed_preflight_checks_the_maximum_basename_width() {
2949        use std::io::{Error as IoError, ErrorKind};
2950
2951        let directory = crate::test_support::FixtureDir::create("basename-width");
2952        let max = u64::MAX.to_string();
2953        for (pattern, first, widest) in [
2954            ("{prefix}.mkv", String::from(".mkv"), String::from(".mkv")),
2955            (
2956                "{prefix}{index}.mkv",
2957                String::from("1.mkv"),
2958                format!("{max}.mkv"),
2959            ),
2960            (
2961                "{prefix}{index}-{index:03}-{index:23}.mkv",
2962                format!("1-001-{:023}.mkv", 1),
2963                format!("{max}-{max}-000{max}.mkv"),
2964            ),
2965            (
2966                "{prefix}{index:20}-{index:23}.mkv",
2967                format!("{:020}-{:023}.mkv", 1, 1),
2968                format!("{max}-000{max}.mkv"),
2969            ),
2970        ] {
2971            let naming = NamePattern::new(Some(pattern)).unwrap();
2972            let max_prefix = 255 - widest.len();
2973            for (prefix_bytes, fits) in [(max_prefix, true), (max_prefix + 1, false)] {
2974                let prefix = "x".repeat(prefix_bytes);
2975                let target = RecordingTarget::new(directory.join(&prefix)).unwrap();
2976                let mut probes = Vec::new();
2977                let result = naming.check_with_metadata(&target, |path| {
2978                    let basename = path.file_name().unwrap().to_str().unwrap();
2979                    probes.push(basename.to_owned());
2980                    let kind = if basename.len() <= 255 {
2981                        ErrorKind::NotFound
2982                    } else {
2983                        ErrorKind::InvalidInput
2984                    };
2985                    Err(IoError::from(kind))
2986                });
2987                let mut expected = vec![format!("{prefix}{first}")];
2988                if first.len() != widest.len() {
2989                    expected.push(format!("{prefix}{widest}"));
2990                }
2991                assert_eq!(probes, expected, "{pattern}");
2992                if fits {
2993                    result.unwrap();
2994                } else {
2995                    assert_eq!(io_kind(result), ErrorKind::InvalidInput, "{pattern}");
2996                }
2997            }
2998        }
2999    }
3000
3001    #[test]
3002    fn indexed_preflight_probe_count_is_independent_of_occupied_indices() {
3003        let directory = crate::test_support::FixtureDir::create("indexed-probes");
3004        let target = RecordingTarget::new(directory.join("take")).unwrap();
3005        let naming = NamePattern::new(Some("{prefix}{index}.mkv")).unwrap();
3006        let metadata = std::fs::metadata(directory.path()).unwrap();
3007        for occupied in [0, 1, 9, 1_000, u64::MAX] {
3008            let mut indices = Vec::new();
3009            naming
3010                .check_with_metadata(&target, |path| {
3011                    let name = path.file_stem().unwrap().to_str().unwrap();
3012                    let index: u64 = name.strip_prefix("take").unwrap().parse().unwrap();
3013                    indices.push(index);
3014                    if index <= occupied {
3015                        Ok(metadata.clone())
3016                    } else {
3017                        Err(std::io::ErrorKind::NotFound.into())
3018                    }
3019                })
3020                .unwrap();
3021            assert_eq!(indices, [1, u64::MAX], "{occupied} occupied indices");
3022        }
3023    }
3024
3025    #[test]
3026    fn recording_path_preflight_reserves_every_indexs_full_width() {
3027        let target_at_length = |length: usize| {
3028            let directory = std::env::temp_dir().join("grafton-ndi-absent-path-limit");
3029            let directory = directory.to_str().unwrap();
3030            RecordingTarget::new(format!(
3031                "{directory}/{}",
3032                "x".repeat(length - directory.len() - 1)
3033            ))
3034            .unwrap()
3035        };
3036        let exact = NamePattern::new(Some(EXACT_PATTERN)).unwrap();
3037        assert!(matches!(
3038            exact.check(&target_at_length(RECORDER_PATH_LIMIT)),
3039            Err(Error::Io(_))
3040        ));
3041        assert!(matches!(
3042            exact.check(&target_at_length(RECORDER_PATH_LIMIT + 1)),
3043            Err(Error::InvalidInput(_))
3044        ));
3045
3046        let indexed = NamePattern::new(Some(DEFAULT_PATTERN)).unwrap();
3047        let first_suffix = "_001.mkv".len();
3048        assert_eq!(indexed.index_digits_reserved, 17);
3049        assert!(matches!(
3050            indexed.check(&target_at_length(4077 - first_suffix)),
3051            Err(Error::Io(_))
3052        ));
3053        assert!(matches!(
3054            indexed.check(&target_at_length(4078 - first_suffix)),
3055            Err(Error::InvalidInput(_))
3056        ));
3057
3058        // Every index token counts; padding wider than u64 needs no growth.
3059        let multiple = NamePattern::new(Some("{prefix}_{index}_{index:03}_{index:24}")).unwrap();
3060        assert_eq!(multiple.index_digits_reserved, 19 + 17);
3061        let suffix = "_1_001_000000000000000000000001".len();
3062        let boundary = RECORDER_PATH_LIMIT - multiple.index_digits_reserved - suffix;
3063        assert!(matches!(
3064            multiple.check(&target_at_length(boundary)),
3065            Err(Error::Io(_))
3066        ));
3067        assert!(matches!(
3068            multiple.check(&target_at_length(boundary + 1)),
3069            Err(Error::InvalidInput(_))
3070        ));
3071    }
3072
3073    #[test]
3074    fn recording_path_limit_counts_utf8_bytes() {
3075        let directory = std::env::temp_dir().join("grafton-ndi-absent-utf8-path-limit");
3076        let base = directory.to_str().unwrap().len() + 1;
3077        let remaining = RECORDER_PATH_LIMIT - base;
3078        let name = format!("{}{}", "é".repeat(remaining / 2), "x".repeat(remaining % 2));
3079        let exact = NamePattern::new(Some(EXACT_PATTERN)).unwrap();
3080        assert!(matches!(
3081            exact.check(&RecordingTarget::new(directory.join(&name)).unwrap()),
3082            Err(Error::Io(_))
3083        ));
3084        assert!(matches!(
3085            exact.check(&RecordingTarget::new(directory.join(format!("{name}x"))).unwrap()),
3086            Err(Error::InvalidInput(_))
3087        ));
3088    }
3089
3090    #[test]
3091    fn oversized_recording_patterns_do_not_allocate_their_expansion() {
3092        let directory = crate::test_support::FixtureDir::create("pattern-expansion");
3093        let target = RecordingTarget::new(directory.join("caméra")).unwrap();
3094        let prefix_bytes = target.path().to_str().unwrap().len();
3095        for tokens in [5, 32, 128] {
3096            let pattern = format!("{{prefix}}_{{index}}{}", "{index:1024}".repeat(tokens));
3097            let pattern = NamePattern::new(Some(&pattern)).unwrap();
3098            let (result, peak) = crate::test_alloc::peak_bytes(|| pattern.check(&target));
3099            assert_eq!(
3100                invalid_cause(result),
3101                crate::InputDefect::RecordingPathTooLong {
3102                    maximum_bytes: RECORDER_PATH_LIMIT,
3103                    longest_bytes: prefix_bytes + 1 + 20 + tokens * 1024,
3104                    index_digits_reserved: 19,
3105                }
3106            );
3107            assert!(
3108                peak <= RECORDER_PATH_LIMIT,
3109                "{tokens} tokens used {peak} bytes"
3110            );
3111        }
3112
3113        let repeated = "{prefix}".repeat(RECORDER_PATH_LIMIT / prefix_bytes + 1);
3114        let pattern = NamePattern::new(Some(&repeated)).unwrap();
3115        let (result, peak) = crate::test_alloc::peak_bytes(|| pattern.check(&target));
3116        assert_eq!(
3117            invalid_cause(result),
3118            crate::InputDefect::RecordingPathTooLong {
3119                maximum_bytes: RECORDER_PATH_LIMIT,
3120                longest_bytes: prefix_bytes * (RECORDER_PATH_LIMIT / prefix_bytes + 1),
3121                index_digits_reserved: 0,
3122            }
3123        );
3124        assert!(
3125            peak <= RECORDER_PATH_LIMIT,
3126            "repeated prefixes used {peak} bytes"
3127        );
3128    }
3129
3130    #[test]
3131    fn only_the_expanded_recording_pattern_determines_absoluteness() {
3132        let target = RecordingTarget::new("take").unwrap();
3133        for pattern in ["take{index}.mkv", "./take.mkv", "relative/{prefix}.mkv"] {
3134            let naming = NamePattern::new(Some(pattern)).unwrap();
3135            assert_eq!(
3136                invalid_cause(naming.check(&target)),
3137                crate::InputDefect::RecordingPathNotAbsolute,
3138                "{pattern}"
3139            );
3140        }
3141
3142        let naming = NamePattern::new(Some("{prefix}//./caméra{index:03}.mkv")).unwrap();
3143        let expected = format!("{}//./caméra001.mkv", target.path().to_str().unwrap());
3144        assert_eq!(
3145            naming.first_file(&target).unwrap().to_str(),
3146            Some(expected.as_str())
3147        );
3148    }
3149
3150    #[test]
3151    fn recording_path_limit_counts_the_raw_expanded_spelling() {
3152        let target = RecordingTarget::new("take").unwrap();
3153        let prefix = target.path().to_str().unwrap();
3154        let remaining = RECORDER_PATH_LIMIT - prefix.len() - 1 - ".mkv".len();
3155        let dots = "./".repeat((remaining - 1) / 2);
3156        let basename = "x".repeat(remaining - dots.len());
3157        let suffix = format!("{dots}{basename}.mkv");
3158        let full = format!("{prefix}/{suffix}");
3159        assert_eq!(full.len(), RECORDER_PATH_LIMIT);
3160        let literal = format!("{{prefix}}/{suffix}");
3161        let naming = NamePattern::new(Some(&literal)).unwrap();
3162        assert_eq!(
3163            naming.first_file(&target).unwrap().to_str(),
3164            Some(full.as_str())
3165        );
3166
3167        let oversized = crate::InputDefect::RecordingPathTooLong {
3168            maximum_bytes: RECORDER_PATH_LIMIT,
3169            longest_bytes: RECORDER_PATH_LIMIT + 1,
3170            index_digits_reserved: 0,
3171        };
3172        let relative_dots = "./".repeat((RECORDER_PATH_LIMIT + 1 - "x.mkv".len()) / 2);
3173        for pattern in [format!("{literal}x"), format!("{relative_dots}x.mkv")] {
3174            let naming = NamePattern::new(Some(&pattern)).unwrap();
3175            let (result, allocations) =
3176                crate::test_alloc::allocation_count(|| naming.first_file(&target));
3177            assert_eq!(invalid_cause(result), oversized);
3178            assert_eq!(allocations, 0);
3179        }
3180    }
3181
3182    #[test]
3183    fn recorder_path_limit_matches_the_events_exact_text_capacity() {
3184        let mut buffer = NDIlib_file_recorder_event_t::default().p_path;
3185        assert_eq!(
3186            buffer.len(),
3187            NDIlib_file_recorder_event_path_max_size as usize
3188        );
3189        buffer[..RECORDER_PATH_LIMIT].fill(b'x' as c_char);
3190        let exact = EventText::from_buffer(&buffer);
3191        assert_eq!(exact.as_bytes().len(), RECORDER_PATH_LIMIT);
3192        assert!(exact.is_terminated());
3193        assert!(!exact.is_possibly_truncated());
3194        buffer[RECORDER_PATH_LIMIT] = b'x' as c_char;
3195        let ambiguous = EventText::from_buffer(&buffer);
3196        assert_eq!(ambiguous.as_bytes().len(), RECORDER_PATH_LIMIT + 1);
3197        assert!(ambiguous.is_terminated());
3198        assert!(ambiguous.is_possibly_truncated());
3199    }
3200
3201    #[test]
3202    fn bounded_event_text_preserves_bad_utf8_and_missing_terminator() {
3203        let text = EventText::from_buffer(&[0xff_u8 as c_char, b'x' as c_char]);
3204        assert_eq!(text.as_bytes(), &[0xff, b'x']);
3205        assert!(!text.is_terminated());
3206        assert!(text.is_possibly_truncated());
3207        assert!(text.to_str().is_err());
3208        let short = EventText::from_buffer(&[b'a' as c_char, 0, 42, 42]);
3209        assert_eq!(short.as_bytes(), b"a");
3210        assert!(short.is_terminated());
3211        assert!(!short.is_possibly_truncated());
3212    }
3213
3214    #[test]
3215    fn time_conversion_retains_large_values_and_checks_overflow() {
3216        let max = FilePosition::from_ticks(u64::MAX);
3217        assert_eq!(FilePosition::from_duration(max.duration()).unwrap(), max);
3218        assert!(FilePosition::from_duration(Duration::MAX).is_err());
3219        assert_eq!(
3220            FilePosition::from_duration(Duration::from_nanos(199))
3221                .unwrap()
3222                .ticks(),
3223            1
3224        );
3225    }
3226
3227    #[test]
3228    fn future_event_values_are_preserved() {
3229        assert_eq!(
3230            PlayerEventKind::from_raw(1234),
3231            PlayerEventKind::Unknown(1234)
3232        );
3233        assert_eq!(
3234            RecorderEventKind::from_raw(4321),
3235            RecorderEventKind::Unknown(4321)
3236        );
3237        assert_eq!(scan_type(99), None);
3238    }
3239
3240    #[test]
3241    fn every_file_frame_format_names_its_scan_type() {
3242        for (format, scan) in [
3243            (
3244                NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_interleaved,
3245                ScanType::Interlaced,
3246            ),
3247            (
3248                NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_progressive,
3249                ScanType::Progressive,
3250            ),
3251            (
3252                NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_field_0,
3253                ScanType::Field0,
3254            ),
3255            (
3256                NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_field_1,
3257                ScanType::Field1,
3258            ),
3259        ] {
3260            assert_eq!(scan_type(format), Some(scan));
3261        }
3262    }
3263
3264    #[test]
3265    fn track_selections_map_to_exactly_the_sdk_flags_and_back() {
3266        assert_eq!(
3267            track_flags(MediaTypes::ALL),
3268            NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_all
3269        );
3270        assert_eq!(
3271            track_flags(MediaTypes::VIDEO),
3272            NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_video
3273        );
3274        assert_eq!(
3275            track_flags(MediaTypes::AUDIO | MediaTypes::METADATA),
3276            NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_audio
3277                | NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_metadata
3278        );
3279        // The SDK reads no flags as all of them; creation refuses that first.
3280        assert_eq!(track_flags(MediaTypes::NONE), 0);
3281        for selection in [
3282            MediaTypes::NONE,
3283            MediaTypes::VIDEO,
3284            MediaTypes::AUDIO,
3285            MediaTypes::METADATA,
3286            MediaTypes::VIDEO | MediaTypes::METADATA,
3287            MediaTypes::ALL,
3288        ] {
3289            assert_eq!(tracks(track_flags(selection)), selection);
3290        }
3291        // A flag from a later SDK is left out rather than misread.
3292        assert_eq!(
3293            tracks(
3294                1 << 8 | NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_audio
3295            ),
3296            MediaTypes::AUDIO
3297        );
3298    }
3299
3300    #[test]
3301    fn a_write_failure_names_its_track() {
3302        let raw = NDIlib_file_recorder_event_t {
3303            type_: NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_write_failed,
3304            track_flags: NDIlib_file_recorder_track_flags_e_NDIlib_file_recorder_track_flags_audio,
3305            ..Default::default()
3306        };
3307        assert_eq!(decode_recorder_event(&raw).tracks(), MediaTypes::AUDIO);
3308        let other = NDIlib_file_recorder_event_t {
3309            type_: NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_started,
3310            ..Default::default()
3311        };
3312        assert!(decode_recorder_event(&other).tracks().is_empty());
3313    }
3314
3315    #[test]
3316    fn a_player_event_keeps_the_source_timecode_only_when_the_sdk_has_one() {
3317        let mut raw = NDIlib_file_player_event_t {
3318            type_: NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_first_frame,
3319            source_timecode_100ns: -100,
3320            ..Default::default()
3321        };
3322        assert_eq!(PlayerEvent::from_sdk(&raw).source_timecode(), None);
3323        raw.has_source_timecode = true;
3324        assert_eq!(
3325            PlayerEvent::from_sdk(&raw).source_timecode(),
3326            Some(Timecode::from_ticks(-100))
3327        );
3328    }
3329
3330    #[test]
3331    fn raw_track_count_is_bounded_before_slicing() {
3332        let mut raw = NDIlib_file_source_format_t {
3333            video_track_count: 3,
3334            ..Default::default()
3335        };
3336        assert!(matches!(
3337            SourceFormat::from_sdk(&raw),
3338            Err(crate::SdkResultDefect::FileTrackCount {
3339                count: 3,
3340                capacity: 2
3341            })
3342        ));
3343        raw.video_track_count = 2;
3344        raw.video_tracks[0].is_high_quality = true;
3345        raw.video_tracks[1].fourcc = u32::MAX;
3346        let snapshot = SourceFormat::from_sdk(&raw).unwrap();
3347        assert_eq!(snapshot.video_tracks().len(), 2);
3348        assert_eq!(snapshot.video_tracks()[0].tier(), StreamTier::Program);
3349        assert_eq!(snapshot.video_tracks()[1].tier(), StreamTier::Preview);
3350        assert_eq!(snapshot.video_tracks()[1].fourcc().raw(), u32::MAX);
3351        assert_eq!(snapshot.video_tracks()[0].picture_aspect_ratio(), None);
3352    }
3353
3354    #[test]
3355    fn a_track_reports_what_the_sdk_knows_and_nothing_it_does_not() {
3356        let mut raw = NDIlib_file_video_track_format_t {
3357            is_high_quality: true,
3358            xres: 1920,
3359            yres: 1080,
3360            frame_rate_n: 30_000,
3361            frame_rate_d: 1_001,
3362            fourcc: u32::from_le_bytes(*b"H264"),
3363            frame_format_type:
3364                NDIlib_file_video_frame_format_e_NDIlib_file_video_frame_format_progressive,
3365            picture_aspect_ratio: 16.0 / 9.0,
3366        };
3367        let track = VideoTrack::from_sdk(&raw).unwrap();
3368        assert_eq!(track.tier(), StreamTier::Program);
3369        assert_eq!((track.width(), track.height()), (1920, 1080));
3370        assert_eq!(
3371            track.frame_rate(),
3372            Some(FrameRate::new(30_000, 1_001).unwrap())
3373        );
3374        assert_eq!(track.fourcc().raw().to_le_bytes(), *b"H264");
3375        assert_eq!(track.scan_type(), Some(ScanType::Progressive));
3376        assert_eq!(
3377            track.picture_aspect_ratio(),
3378            Some(PictureAspectRatio::new(16.0 / 9.0).unwrap())
3379        );
3380
3381        // Zero is what the SDK reports for what it does not know yet.
3382        let unknown = VideoTrack::from_sdk(&NDIlib_file_video_track_format_t {
3383            frame_rate_n: 30,
3384            ..Default::default()
3385        })
3386        .unwrap();
3387        assert_eq!((unknown.width(), unknown.height()), (0, 0));
3388        assert_eq!(unknown.frame_rate(), None);
3389        assert_eq!(unknown.picture_aspect_ratio(), None);
3390        raw.frame_format_type = 99;
3391        raw.picture_aspect_ratio = f32::NAN;
3392        let future = VideoTrack::from_sdk(&raw).unwrap();
3393        assert_eq!(future.scan_type(), None);
3394        assert_eq!(future.picture_aspect_ratio(), None);
3395    }
3396
3397    #[test]
3398    fn a_negative_quantity_breaks_the_sdk_contract() {
3399        let track = NDIlib_file_video_track_format_t {
3400            xres: 1920,
3401            yres: 1080,
3402            frame_rate_n: 30,
3403            frame_rate_d: 1,
3404            ..Default::default()
3405        };
3406        for (broken, what, value) in [
3407            (
3408                NDIlib_file_video_track_format_t { xres: -1, ..track },
3409                "width",
3410                -1,
3411            ),
3412            (
3413                NDIlib_file_video_track_format_t { yres: -1, ..track },
3414                "height",
3415                -1,
3416            ),
3417            (
3418                NDIlib_file_video_track_format_t {
3419                    frame_rate_n: -30,
3420                    ..track
3421                },
3422                "frame-rate numerator",
3423                -30,
3424            ),
3425            (
3426                NDIlib_file_video_track_format_t {
3427                    frame_rate_d: -1,
3428                    ..track
3429                },
3430                "frame-rate denominator",
3431                -1,
3432            ),
3433        ] {
3434            let Err(cause) = VideoTrack::from_sdk(&broken) else {
3435                panic!("the negative {what} was not refused");
3436            };
3437            assert_eq!(
3438                cause,
3439                crate::SdkResultDefect::NegativeFormatCount { what, value }
3440            );
3441        }
3442        let format = NDIlib_file_source_format_t {
3443            audio_sample_rate: 48_000,
3444            audio_no_channels: 2,
3445            audio_no_samples: 1_600,
3446            audio_bit_depth: 32,
3447            ..Default::default()
3448        };
3449        let audio = SourceFormat::from_sdk(&format).unwrap();
3450        assert_eq!(
3451            (
3452                audio.audio_sample_rate(),
3453                audio.audio_num_channels(),
3454                audio.audio_num_samples(),
3455                audio.audio_bit_depth()
3456            ),
3457            (48_000, 2, 1_600, 32)
3458        );
3459        for (broken, what) in [
3460            (
3461                NDIlib_file_source_format_t {
3462                    audio_sample_rate: -1,
3463                    ..format
3464                },
3465                "audio sample rate",
3466            ),
3467            (
3468                NDIlib_file_source_format_t {
3469                    audio_no_channels: -1,
3470                    ..format
3471                },
3472                "audio channel count",
3473            ),
3474            (
3475                NDIlib_file_source_format_t {
3476                    audio_no_samples: -1,
3477                    ..format
3478                },
3479                "audio sample count",
3480            ),
3481        ] {
3482            let Err(cause) = SourceFormat::from_sdk(&broken) else {
3483                panic!("the negative {what} was not refused");
3484            };
3485            assert_eq!(
3486                cause,
3487                crate::SdkResultDefect::NegativeFormatCount { what, value: -1 }
3488            );
3489        }
3490    }
3491
3492    #[test]
3493    fn unreadable_formats_preserve_every_other_event_and_probe_field() {
3494        let mut format = NDIlib_file_source_format_t {
3495            video_track_count: 1,
3496            audio_sample_rate: 48_000,
3497            audio_no_channels: 2,
3498            audio_no_samples: 1_600,
3499            ..Default::default()
3500        };
3501        format.video_tracks[0] = NDIlib_file_video_track_format_t {
3502            xres: 1920,
3503            yres: 1080,
3504            frame_rate_n: 30,
3505            frame_rate_d: 1,
3506            ..Default::default()
3507        };
3508        let info = NDIlib_file_player_file_info_t {
3509            duration_100ns: 123,
3510            duration_is_final: true,
3511            track_count: 4,
3512            video_track_count: 1,
3513            audio_track_count: 2,
3514            metadata_track_count: 1,
3515            source_format: format,
3516        };
3517        let mut player = NDIlib_file_player_event_t {
3518            type_: NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_ended,
3519            first_pts_100ns: 17,
3520            last_pts_100ns: 19,
3521            has_source_timecode: true,
3522            source_timecode_100ns: -13,
3523            source_format: format,
3524            ..Default::default()
3525        };
3526        player.p_path[0] = b'p' as c_char;
3527        player.p_message[0] = b'm' as c_char;
3528        let mut recorder = NDIlib_file_recorder_event_t {
3529            type_: NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_file_closed,
3530            dropped_packet_count: 23,
3531            first_pts_100ns: 29,
3532            last_pts_100ns: 31,
3533            source_format_payload: format,
3534            ..Default::default()
3535        };
3536        recorder.p_path[0] = b'r' as c_char;
3537        recorder.p_message[0] = b'd' as c_char;
3538        recorder.source_format[0] = b'f' as c_char;
3539        let expected_info = FileInfo::from_sdk(&info);
3540        let expected_player = PlayerEvent::from_sdk(&player);
3541        let expected_recorder = decode_recorder_event(&recorder);
3542        assert_eq!(
3543            expected_info.source_format().unwrap().audio_num_channels(),
3544            2
3545        );
3546        let mut broken = Vec::new();
3547        for (index, what) in [
3548            "width",
3549            "height",
3550            "frame-rate numerator",
3551            "frame-rate denominator",
3552            "audio sample rate",
3553            "audio channel count",
3554            "audio sample count",
3555        ]
3556        .into_iter()
3557        .enumerate()
3558        {
3559            let mut raw = format;
3560            match index {
3561                0 => raw.video_tracks[0].xres = -1,
3562                1 => raw.video_tracks[0].yres = -1,
3563                2 => raw.video_tracks[0].frame_rate_n = -1,
3564                3 => raw.video_tracks[0].frame_rate_d = -1,
3565                4 => raw.audio_sample_rate = -1,
3566                5 => raw.audio_no_channels = -1,
3567                _ => raw.audio_no_samples = -1,
3568            }
3569            broken.push((
3570                raw,
3571                SdkResultDefect::NegativeFormatCount { what, value: -1 },
3572            ));
3573        }
3574        broken.push((
3575            NDIlib_file_source_format_t {
3576                video_track_count: 3,
3577                ..format
3578            },
3579            SdkResultDefect::FileTrackCount {
3580                count: 3,
3581                capacity: 2,
3582            },
3583        ));
3584        for (format, defect) in broken {
3585            let mut decoded_info = FileInfo::from_sdk(&NDIlib_file_player_file_info_t {
3586                source_format: format,
3587                ..info
3588            });
3589            let mut decoded_player = PlayerEvent::from_sdk(&NDIlib_file_player_event_t {
3590                source_format: format,
3591                ..player
3592            });
3593            let mut decoded_recorder = decode_recorder_event(&NDIlib_file_recorder_event_t {
3594                source_format_payload: format,
3595                ..recorder
3596            });
3597            for result in [
3598                decoded_info.source_format(),
3599                decoded_player.source_format(),
3600                decoded_recorder.source_format(),
3601            ] {
3602                assert_eq!(result, Err(defect));
3603            }
3604            decoded_info.source_format = expected_info.source_format.clone();
3605            decoded_player.source_format = expected_player.source_format.clone();
3606            decoded_recorder.source_format = expected_recorder.source_format.clone();
3607            assert_eq!(decoded_info, expected_info);
3608            assert_eq!(decoded_player, expected_player);
3609            assert_eq!(decoded_recorder, expected_recorder);
3610        }
3611    }
3612
3613    #[test]
3614    fn withholding_a_format_adds_no_decode_allocation() {
3615        let good = NDIlib_file_player_event_t::default();
3616        let mut bad = good;
3617        bad.source_format.video_track_count = 3;
3618        let (_, good_allocations) =
3619            crate::test_alloc::allocation_count(|| PlayerEvent::from_sdk(&good));
3620        let (event, bad_allocations) =
3621            crate::test_alloc::allocation_count(|| PlayerEvent::from_sdk(&bad));
3622        assert!(event.source_format().is_err());
3623        assert!(bad_allocations <= good_allocations);
3624    }
3625
3626    #[test]
3627    fn malformed_event_text_does_not_hide_file_closed() {
3628        let mut raw = NDIlib_file_recorder_event_t {
3629            type_: NDIlib_file_recorder_event_type_e_NDIlib_file_recorder_event_type_file_closed,
3630            ..Default::default()
3631        };
3632        raw.p_path.fill(0xff_u8 as c_char);
3633        let event = decode_recorder_event(&raw);
3634        assert_eq!(event.kind(), RecorderEventKind::FileClosed);
3635        assert!(!event.path().is_terminated());
3636        assert!(event.path().to_str().is_err());
3637    }
3638
3639    #[cfg(unix)]
3640    #[test]
3641    fn non_utf8_native_paths_are_rejected_without_lossy_conversion() {
3642        use std::os::unix::ffi::OsStrExt;
3643        assert!(RecordingTarget::new(Path::new(std::ffi::OsStr::from_bytes(b"bad\xff"))).is_err());
3644    }
3645}