Skip to main content

grafton_ndi/
time.rs

1//! Time values carried by frames and read from the selected runtime's clock.
2//!
3//! These values count 100-nanosecond ticks, the SDK's unit for time.
4
5use crate::{
6    sys::bindings::{NDIlib_recv_timestamp_undefined, NDIlib_send_timecode_synthesize},
7    Ndi, Result,
8};
9
10/// The editorial timecode a frame carries, in 100-nanosecond ticks.
11///
12/// Every sendable frame starts with [`Timecode::SYNTHESIZE`], which asks the
13/// SDK to generate a timecode when the frame is sent. Any other value,
14/// including zero, is sent unchanged. A received frame carries the timecode
15/// its sender gave it or the SDK generated.
16///
17/// # Examples
18///
19/// ```
20/// use grafton_ndi::Timecode;
21///
22/// let one_second = Timecode::from_ticks(10_000_000);
23/// assert_eq!(one_second.ticks(), 10_000_000);
24/// assert_eq!(Timecode::default(), Timecode::SYNTHESIZE);
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct Timecode(i64);
28
29impl Timecode {
30    /// The SDK's request to generate a timecode when the frame is sent
31    /// (`NDIlib_send_timecode_synthesize`, `i64::MAX` ticks).
32    pub const SYNTHESIZE: Self = Self(NDIlib_send_timecode_synthesize);
33
34    /// A timecode of `ticks` 100-nanosecond intervals.
35    #[must_use]
36    pub const fn from_ticks(ticks: i64) -> Self {
37        Self(ticks)
38    }
39
40    /// The timecode in 100-nanosecond ticks.
41    #[must_use]
42    pub const fn ticks(self) -> i64 {
43        self.0
44    }
45}
46
47impl Default for Timecode {
48    /// [`Timecode::SYNTHESIZE`].
49    fn default() -> Self {
50        Self::SYNTHESIZE
51    }
52}
53
54/// A reading of the SDK's clock, in 100-nanosecond ticks since the Unix epoch.
55///
56/// [`Ndi::timestamp`] reads the clock. Media accessors return
57/// [`ReceivedTimestamp`], whose tick origin depends on the source.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
59pub struct SdkTimestamp(i64);
60
61impl SdkTimestamp {
62    /// A timestamp of `ticks` 100-nanosecond intervals since the Unix epoch.
63    #[must_use]
64    pub const fn from_ticks(ticks: i64) -> Self {
65        Self(ticks)
66    }
67
68    /// The timestamp in 100-nanosecond ticks since the Unix epoch.
69    #[must_use]
70    pub const fn ticks(self) -> i64 {
71        self.0
72    }
73}
74
75/// A received media timestamp in signed 100-nanosecond ticks.
76///
77/// The source and capture path determine the tick origin. For example, on
78/// Linux x86-64 with NDI Advanced and the File library 6.4.0.2, seeking a
79/// single-track file produced a video frame whose timestamp matched the
80/// file-relative PTS in the player's `FirstFrame` event.
81///
82/// An undefined timestamp is represented as `None` by media accessors.
83/// FrameSync and AV-sync audio also treat zero as undefined.
84///
85/// Order these values only when they share a tick origin. Use [`Self::ticks`]
86/// and interpret the ticks for the specific source before comparing them
87/// with an [`SdkTimestamp`].
88#[repr(transparent)]
89#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
90pub struct ReceivedTimestamp(i64);
91
92impl ReceivedTimestamp {
93    /// The raw signed timestamp in 100-nanosecond ticks from the source.
94    #[must_use]
95    pub const fn ticks(self) -> i64 {
96        self.0
97    }
98
99    /// The timestamp field of a frame the SDK delivered: `None` when it holds
100    /// the SDK's undefined sentinel (`NDIlib_recv_timestamp_undefined`).
101    pub(crate) fn from_sdk(ticks: i64) -> Option<Self> {
102        (ticks != NDIlib_recv_timestamp_undefined).then_some(Self(ticks))
103    }
104
105    /// The SDK's timestamp field for `timestamp`, the inverse of
106    /// [`Self::from_sdk`].
107    pub(crate) fn to_sdk(timestamp: Option<Self>) -> i64 {
108        timestamp.map_or(NDIlib_recv_timestamp_undefined, Self::ticks)
109    }
110}
111
112impl Ndi {
113    /// Read the selected SDK's current timestamp, retaining its clock semantics.
114    ///
115    /// Requires the NDI 6.4 timestamp helper. Missing capability is an error;
116    /// this never falls back to `SystemTime` or `Instant`.
117    #[doc(alias = "NDIlib_util_get_timestamp")]
118    pub fn timestamp(&self) -> Result<SdkTimestamp> {
119        let timestamp = self.table::<crate::sys::Timestamp>()?;
120        // SAFETY: the query takes no arguments, and this handle keeps the
121        // selected runtime initialized for the duration of the call.
122        Ok(SdkTimestamp(unsafe {
123            timestamp.NDIlib_util_get_timestamp()
124        }))
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use crate::{capabilities::RuntimeFeature, Error};
132
133    #[test]
134    fn received_timestamps_map_the_undefined_sentinel_to_none() {
135        assert_eq!(
136            ReceivedTimestamp::from_sdk(NDIlib_recv_timestamp_undefined),
137            None
138        );
139        for ticks in [i64::MIN, -1, 0, 1, i64::MAX - 1] {
140            let timestamp = ReceivedTimestamp::from_sdk(ticks);
141            assert_eq!(timestamp.map(ReceivedTimestamp::ticks), Some(ticks));
142            assert_eq!(ReceivedTimestamp::to_sdk(timestamp), ticks);
143        }
144        assert_eq!(
145            ReceivedTimestamp::to_sdk(None),
146            NDIlib_recv_timestamp_undefined
147        );
148        assert_eq!(
149            std::mem::size_of::<ReceivedTimestamp>(),
150            std::mem::size_of::<SdkTimestamp>()
151        );
152    }
153
154    #[test]
155    fn editorial_timecode_defaults_to_synthesize() {
156        assert_eq!(Timecode::SYNTHESIZE.ticks(), i64::MAX);
157        assert_eq!(Timecode::default(), Timecode::SYNTHESIZE);
158    }
159
160    #[test]
161    fn native_timestamp_has_utc_100ns_units_or_reports_missing_capability() {
162        let Some(ndi) = crate::test_support::ndi() else {
163            return;
164        };
165        if ndi.require_feature(RuntimeFeature::SdkTimestamp).is_err() {
166            assert!(matches!(
167                ndi.timestamp(),
168                Err(Error::UnsupportedCapability { .. })
169            ));
170            return;
171        }
172        let clock_ticks = || {
173            std::time::SystemTime::now()
174                .duration_since(std::time::UNIX_EPOCH)
175                .unwrap()
176                .as_nanos()
177                / 100
178        };
179        let before = clock_ticks() as i128;
180        let ticks = i128::from(ndi.timestamp().unwrap().ticks());
181        let after = clock_ticks() as i128;
182        // Allow one second for native/system clock sampling differences. This
183        // catches unit or epoch mistakes without relying on subsecond equality.
184        assert!((before - 10_000_000..=after + 10_000_000).contains(&ticks));
185    }
186}