grafton_ndi/file/player.rs
1//! Playing recordings back as an NDI source.
2
3use std::{marker::PhantomData, path::Path, ptr::NonNull, rc::Rc, time::Duration};
4
5#[cfg(doc)]
6use super::FileFamily;
7use super::{
8 out_param, types, FileApi, FileBound, FileDuration, FileInfo, FilePlayerOptions, FilePosition,
9 PlayerEvent, PlayerStats, SourceFormat,
10};
11use crate::{
12 sys::{self, bindings::*},
13 Error, Result, Source, Timecode,
14};
15
16/// An NDI source that plays recordings.
17///
18/// The source is advertised from creation until the player is dropped, whether
19/// or not a file is playing; [`stop`](Self::stop) ends the current file only,
20/// so receivers stay connected between files. Dropping the player stops
21/// playback and removes the source.
22///
23/// A player belongs to the thread that created it, so it is neither [`Send`]
24/// nor [`Sync`]: the File API documents no thread on which a player may be
25/// used or destroyed, nor whether two calls on one player may overlap. Every
26/// method calls into the SDK and may block.
27/// [`AsyncFilePlayer`](super::AsyncFilePlayer) offers the same operations as
28/// futures.
29pub struct FilePlayer {
30 playback: FileBound<sys::FilePlayback>,
31 handle: NonNull<NDIlib_file_player_instance_type>,
32 // Strings passed to the SDK are needed only for the call that receives
33 // them; see the note in `recorder/native.rs`. The name is kept for `Debug`.
34 name: types::FileText,
35 // Neither the NDI File Format API documentation nor
36 // Processing.NDI.Lib.File.Player.h says on which threads a player may be
37 // created, used and destroyed, or whether calls on one player may
38 // overlap; their only mention of threads is the player's own playback
39 // thread. Without that contract a player stays on its creating thread,
40 // and AsyncFilePlayer creates, uses and destroys one on a thread of its
41 // own.
42 _thread: PhantomData<Rc<()>>,
43}
44
45/// Checked Rust data and its native family; no native player exists yet.
46pub(super) struct PreparedPlayer {
47 playback: FileBound<sys::FilePlayback>,
48 resolved: types::ResolvedPlayerOptions,
49}
50
51impl PreparedPlayer {
52 pub(super) fn create(self) -> Result<FilePlayer> {
53 let Self { playback, resolved } = self;
54 let settings = NDIlib_file_player_create_t {
55 p_ndi_send_name: resolved.name.as_ptr(),
56 p_groups: resolved
57 .groups
58 .as_ref()
59 .map_or(std::ptr::null(), |groups| groups.as_ptr()),
60 };
61 // SAFETY: `settings` and the strings it points to are valid for the call.
62 let handle = unsafe { playback.named().NDIlib_file_player_create(&settings) }.created()?;
63 Ok(FilePlayer {
64 playback,
65 handle,
66 name: resolved.name,
67 _thread: PhantomData,
68 })
69 }
70}
71
72impl std::fmt::Debug for FilePlayer {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 f.debug_struct("FilePlayer")
75 .field("name", &self.name)
76 .finish_non_exhaustive()
77 }
78}
79
80impl FilePlayer {
81 /// Create a player and advertise its NDI source.
82 ///
83 /// The source is advertised from this call until the player is dropped,
84 /// whether or not a file is playing. The options are only read, so they
85 /// stay with the caller whatever the outcome.
86 ///
87 /// # Errors
88 ///
89 /// [`Error::InvalidInput`] when the player's name or group list is empty,
90 /// or a group is empty or contains a comma or NUL. [`Error::InvalidCString`] when
91 /// the player's name contains a NUL.
92 /// [`Error::NativeOperationFailed`] when the SDK cannot create the player
93 /// and [`Error::UnsupportedCapability`] when the library does not provide
94 /// [`FileFamily::Playback`].
95 #[doc(alias = "NDIlib_file_player_create")]
96 pub fn new(api: &FileApi, options: &FilePlayerOptions) -> Result<Self> {
97 Self::prepare(api.clone(), options)?.create()
98 }
99
100 pub(super) fn prepare(api: FileApi, options: &FilePlayerOptions) -> Result<PreparedPlayer> {
101 let playback = api.into_table::<sys::FilePlayback>()?;
102 let resolved = options.resolve()?;
103 Ok(PreparedPlayer { playback, resolved })
104 }
105
106 /// Read a recording's duration and track layout.
107 ///
108 /// Nothing is played and no NDI source is advertised.
109 /// An unreadable format payload does not discard the other information;
110 /// [`FileInfo::source_format`] reports the typed cause instead.
111 ///
112 /// # Errors
113 ///
114 /// [`Error::NativeOperationFailed`] when the SDK cannot read the file,
115 /// [`Error::InvalidInput`] when the path is empty or is not UTF-8,
116 /// [`Error::InvalidCString`] when it contains a NUL, [`Error::Io`] when a
117 /// relative path cannot be resolved because the current directory is
118 /// unavailable, and [`Error::UnsupportedCapability`] when the library
119 /// does not provide [`FileFamily::Playback`].
120 /// [`Error::UnexpectedSdkResult`] when the library's file information
121 /// does not match this crate's structure layout.
122 #[doc(alias = "NDIlib_file_player_probe_file")]
123 pub fn probe(api: &FileApi, path: impl AsRef<Path>) -> Result<FileInfo> {
124 let playback = api.table::<sys::FilePlayback>()?;
125 let path = types::path_string(path.as_ref())?;
126 Self::probe_checked(playback, &path)
127 }
128
129 /// Probe with the family and path already proved at submission.
130 pub(super) fn probe_checked(
131 playback: &sys::FilePlayback,
132 path: &types::FileText,
133 ) -> Result<FileInfo> {
134 let info = out_param::required_fill(|info| {
135 // SAFETY: `path` is a NUL-terminated string that outlives the
136 // call; the helper keeps guarded info storage writable through it.
137 unsafe {
138 playback
139 .named()
140 .NDIlib_file_player_probe_file(path.as_ptr(), info)
141 }
142 })?;
143 Ok(FileInfo::from_sdk(&info))
144 }
145
146 /// Play a file through the advertised source.
147 ///
148 /// A file already playing is closed first. Playback always begins unpaused
149 /// and uses the player's looping setting. As specified by
150 /// `Processing.NDI.Lib.File.Player.h`, only the player's first start may
151 /// wait up to about half a second, and only for a GOP-compressed file with
152 /// a receiver that has just connected, so it gets the opening keyframe.
153 /// There is no wait without a connected receiver, and later starts on the
154 /// same player never wait.
155 ///
156 /// # Errors
157 ///
158 /// [`Error::NativeOperationFailed`] when the SDK cannot open the file,
159 /// [`Error::InvalidInput`] when the path is empty or is not UTF-8,
160 /// [`Error::InvalidCString`] when it contains a NUL, and [`Error::Io`] when
161 /// a relative path cannot be resolved because the current directory is
162 /// unavailable.
163 #[doc(alias = "NDIlib_file_player_start")]
164 pub fn start(&mut self, path: impl AsRef<Path>) -> Result<()> {
165 let path = types::path_string(path.as_ref())?;
166 self.start_checked(&path)
167 }
168
169 /// Start with the path already resolved and validated at submission.
170 pub(super) fn start_checked(&mut self, path: &types::FileText) -> Result<()> {
171 // SAFETY: the player is live and `path` is a NUL-terminated string
172 // that outlives the call.
173 let started = unsafe {
174 self.playback
175 .named()
176 .NDIlib_file_player_start(self.handle.as_ptr(), path.as_ptr())
177 };
178 started.performed()
179 }
180
181 /// Stop the current file. The source stays advertised.
182 #[doc(alias = "NDIlib_file_player_stop")]
183 pub fn stop(&mut self) {
184 // SAFETY: the player is live for this borrow.
185 unsafe { self.playback.NDIlib_file_player_stop(self.handle.as_ptr()) };
186 }
187
188 /// Whether a file is playing. False after [`stop`](Self::stop) and once
189 /// playback reaches the end of a file that does not loop.
190 #[doc(alias = "NDIlib_file_player_is_running")]
191 pub fn is_running(&self) -> bool {
192 // SAFETY: the player is live for this borrow.
193 unsafe {
194 self.playback
195 .NDIlib_file_player_is_running(self.handle.as_ptr())
196 }
197 }
198
199 /// Take the next queued event, waiting up to `timeout` for one, or
200 /// `None` when none arrives in time.
201 /// An unreadable format is withheld through [`PlayerEvent::source_format`]
202 /// while the rest of the event is delivered.
203 ///
204 /// # Errors
205 ///
206 /// [`Error::InvalidInput`] when `timeout` exceeds [`crate::MAX_TIMEOUT`],
207 /// and [`Error::UnexpectedSdkResult`] when the SDK's event does not match
208 /// this crate's structure layout or its returned event type.
209 #[doc(alias = "NDIlib_file_player_capture_event")]
210 pub fn next_event(&mut self, timeout: Duration) -> Result<Option<PlayerEvent>> {
211 let timeout = crate::to_ms_checked(timeout)?;
212 out_param::capture_event(
213 |event| {
214 // SAFETY: the player is live and the helper keeps guarded
215 // event storage writable through the call.
216 unsafe {
217 self.playback.NDIlib_file_player_capture_event(
218 self.handle.as_ptr(),
219 event,
220 timeout,
221 )
222 }
223 },
224 |event| event.type_,
225 NDIlib_file_player_event_type_e_NDIlib_file_player_event_type_none,
226 "the player returned one event type and stored another",
227 )
228 .map(|event| event.map(|event| PlayerEvent::from_sdk(&event)))
229 }
230
231 /// How many events the SDK has discarded since the player was created
232 /// because they were not taken in time.
233 #[doc(alias = "NDIlib_file_player_get_dropped_event_count")]
234 pub fn dropped_event_count(&self) -> u64 {
235 // SAFETY: the player is live for this borrow.
236 unsafe {
237 self.playback
238 .NDIlib_file_player_get_dropped_event_count(self.handle.as_ptr())
239 }
240 }
241
242 /// Counters for the current or most recent file, when the SDK has any.
243 /// Interpret them alongside playback session state and events, rather
244 /// than as receiver-media progress.
245 ///
246 /// # Errors
247 ///
248 /// [`Error::UnexpectedSdkResult`] when the SDK's structure does not match this
249 /// crate's layout.
250 #[doc(alias = "NDIlib_file_player_get_stats")]
251 pub fn stats(&self) -> Result<Option<PlayerStats>> {
252 out_param::checked_fill(|stats| {
253 // SAFETY: the player is live and the helper keeps guarded stats
254 // storage writable through the call.
255 unsafe {
256 self.playback
257 .NDIlib_file_player_get_stats(self.handle.as_ptr(), stats)
258 }
259 })
260 .map(|stats| stats.map(|stats| PlayerStats::from_sdk(&stats)))
261 }
262
263 /// Seek to a position on the file's timeline, where zero is its first frame.
264 ///
265 /// GOP-compressed video resumes at the keyframe at or before the position;
266 /// intra-only video resumes at the first frame at or after it.
267 ///
268 /// # Errors
269 ///
270 /// [`Error::NativeOperationFailed`] when the SDK refuses the seek.
271 #[doc(alias = "NDIlib_file_player_seek_to_time")]
272 pub fn seek(&mut self, position: FilePosition) -> Result<()> {
273 // SAFETY: the player is live for this borrow.
274 let sought = unsafe {
275 self.playback
276 .named()
277 .NDIlib_file_player_seek_to_time(self.handle.as_ptr(), position.ticks())
278 };
279 sought.performed()
280 }
281
282 /// Seek to a frame index.
283 ///
284 /// The SDK converts the index to a time through the video frame rate, so
285 /// the result is approximate for fractional rates.
286 ///
287 /// # Errors
288 ///
289 /// [`Error::NativeOperationFailed`] when the SDK refuses the seek.
290 #[doc(alias = "NDIlib_file_player_seek_to_frame")]
291 pub fn seek_frame_approximate(&mut self, frame: u64) -> Result<()> {
292 // SAFETY: the player is live for this borrow.
293 let sought = unsafe {
294 self.playback
295 .named()
296 .NDIlib_file_player_seek_to_frame(self.handle.as_ptr(), frame)
297 };
298 sought.performed()
299 }
300
301 /// Pause or resume the current file. Has no effect when no file is open.
302 #[doc(alias = "NDIlib_file_player_set_paused")]
303 pub fn set_paused(&mut self, paused: bool) {
304 // SAFETY: the player is live for this borrow.
305 unsafe {
306 self.playback
307 .NDIlib_file_player_set_paused(self.handle.as_ptr(), paused)
308 };
309 }
310
311 /// Whether the current file is paused. Every [`start`](Self::start) resets
312 /// this to false.
313 #[doc(alias = "NDIlib_file_player_get_paused")]
314 pub fn is_paused(&self) -> bool {
315 // SAFETY: the player is live for this borrow.
316 unsafe {
317 self.playback
318 .NDIlib_file_player_get_paused(self.handle.as_ptr())
319 }
320 }
321
322 /// Set whether playback restarts at the end of a file.
323 ///
324 /// Looping belongs to the player, not the file: it is kept across
325 /// [`start`](Self::start) and [`stop`](Self::stop). A looping file never
326 /// raises [`PlayerEventKind::Ended`](super::PlayerEventKind::Ended).
327 #[doc(alias = "NDIlib_file_player_set_loop")]
328 pub fn set_looping(&mut self, looping: bool) {
329 // SAFETY: the player is live for this borrow.
330 unsafe {
331 self.playback
332 .NDIlib_file_player_set_loop(self.handle.as_ptr(), looping)
333 };
334 }
335
336 /// Whether playback restarts at the end of a file.
337 #[doc(alias = "NDIlib_file_player_get_loop")]
338 pub fn is_looping(&self) -> bool {
339 // SAFETY: the player is live for this borrow.
340 unsafe {
341 self.playback
342 .NDIlib_file_player_get_loop(self.handle.as_ptr())
343 }
344 }
345
346 /// The current file's best-known duration, and whether it is final.
347 ///
348 /// A file that is still being recorded reports a provisional duration.
349 #[doc(alias = "NDIlib_file_player_get_current_duration")]
350 pub fn duration(&self) -> Option<FileDuration> {
351 let (mut ticks, mut is_final) = (0, false);
352 // SAFETY: the player is live and both pointers are writable.
353 unsafe {
354 self.playback.NDIlib_file_player_get_current_duration(
355 self.handle.as_ptr(),
356 &mut ticks,
357 &mut is_final,
358 )
359 }
360 .then_some(FileDuration {
361 position: FilePosition::from_ticks(ticks),
362 is_final,
363 })
364 }
365
366 /// The position of the frame sent last: the main video track's, or the
367 /// audio track's in a file without video.
368 #[doc(alias = "NDIlib_file_player_get_current_position")]
369 pub fn position(&self) -> Option<FilePosition> {
370 let mut ticks = 0;
371 // SAFETY: the player is live and the pointer is writable.
372 unsafe {
373 self.playback
374 .NDIlib_file_player_get_current_position(self.handle.as_ptr(), &mut ticks)
375 }
376 .then_some(FilePosition::from_ticks(ticks))
377 }
378
379 /// The recorded source timecode of the frame sent last. Unlike the
380 /// position it is editorial and need not increase.
381 #[doc(alias = "NDIlib_file_player_get_current_source_timecode")]
382 pub fn source_timecode(&self) -> Option<Timecode> {
383 let mut ticks = 0;
384 // SAFETY: the player is live and the pointer is writable.
385 unsafe {
386 self.playback
387 .NDIlib_file_player_get_current_source_timecode(self.handle.as_ptr(), &mut ticks)
388 }
389 .then_some(Timecode::from_ticks(ticks))
390 }
391
392 /// The track layout of the current file, once one with audio or video is open.
393 /// A known layout alone does not establish current playback progress;
394 /// inspect the player state and events as well.
395 ///
396 /// # Errors
397 ///
398 /// [`Error::UnexpectedSdkResult`] when the SDK's structure is malformed.
399 #[doc(alias = "NDIlib_file_player_get_source_format")]
400 pub fn source_format(&self) -> Result<Option<SourceFormat>> {
401 out_param::checked_fill(|format| {
402 // SAFETY: the player is live and the helper keeps guarded format
403 // storage writable through the call.
404 unsafe {
405 self.playback
406 .NDIlib_file_player_get_source_format(self.handle.as_ptr(), format)
407 }
408 })?
409 .map(|format| SourceFormat::from_sdk(&format).map_err(Error::UnexpectedSdkResult))
410 .transpose()
411 }
412
413 /// The NDI source this player advertises, for example to connect a
414 /// [`Receiver`](crate::Receiver) to it.
415 ///
416 /// # Errors
417 ///
418 /// [`Error::NativeOperationFailed`] when the SDK returns no source, or one
419 /// that names neither a source nor an address, and
420 /// [`Error::UnexpectedSdkResult`] when its name or address is longer than
421 /// the 4 MiB available for one SDK string, including its terminator.
422 /// [`Error::InvalidUtf8`] reports an invalid name or address.
423 /// [`Error::AllocationFailed`] reports a failed text buffer reservation.
424 /// See [`crate::Finder::current_sources`] for allocation behavior of
425 /// shared source owners.
426 #[doc(alias = "NDIlib_file_player_get_advertised_source")]
427 pub fn advertised_source(&self) -> Result<Source> {
428 // SAFETY: the player is live. The descriptor the SDK returns, and its
429 // strings, stay valid until the player is destroyed, which this borrow
430 // rules out while they are copied.
431 unsafe {
432 Source::try_from_raw(
433 self.playback
434 .named()
435 .NDIlib_file_player_get_advertised_source(self.handle.as_ptr()),
436 )
437 }
438 }
439
440 /// Stop playback and remove the advertised source.
441 ///
442 /// Equivalent to dropping the player; provided so the intent is visible at
443 /// the call site.
444 #[doc(alias = "NDIlib_file_player_destroy")]
445 pub fn close(self) {
446 drop(self);
447 }
448}
449
450impl Drop for FilePlayer {
451 fn drop(&mut self) {
452 // SAFETY: the player is live and is destroyed exactly once, on the
453 // thread that created it.
454 unsafe {
455 self.playback.NDIlib_file_player_stop(self.handle.as_ptr());
456 self.playback
457 .NDIlib_file_player_destroy(self.handle.as_ptr());
458 }
459 }
460}