1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
#![allow(clippy::missing_errors_doc, clippy::must_use_candidate)]
use core::ffi::{c_char, c_void};
use core::ptr;
use std::ffi::{CStr, CString};
use std::path::Path;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use crate::asset::{Asset, Size};
use crate::error::{from_swift, AVPlayerError};
use crate::ffi;
use crate::metadata::MetadataItem;
use crate::time::Time;
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PlayerInfoPayload {
status: i32,
error_message: Option<String>,
rate: f32,
current_time: Time,
duration: Time,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PlayerItemInfoPayload {
status: i32,
error_message: Option<String>,
duration: Time,
presentation_size: Size,
metadata: Vec<MetadataItem>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PlayerItemEventPayload {
event: String,
status: Option<i32>,
error_message: Option<String>,
presentation_size: Option<Size>,
has_originating_participant: Option<bool>,
recommended_time_offset_from_live: Option<Time>,
}
/// `AVPlayerStatus`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PlayerStatus {
/// Mirrors the `AVPlayer` framework case `Unknown`.
Unknown,
/// Mirrors the `AVPlayer` framework case `ReadyToPlay`.
ReadyToPlay,
/// Mirrors the `AVPlayer` framework case `Failed`.
Failed,
}
impl PlayerStatus {
/// Mirrors the `AVPlayer` framework constant `fn`.
#[must_use]
pub const fn from_raw(raw: i32) -> Self {
match raw {
1 => Self::ReadyToPlay,
2 => Self::Failed,
_ => Self::Unknown,
}
}
}
/// `AVPlayerItemStatus`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PlayerItemStatus {
/// Mirrors the `AVPlayer` framework case `Unknown`.
Unknown,
/// Mirrors the `AVPlayer` framework case `ReadyToPlay`.
ReadyToPlay,
/// Mirrors the `AVPlayer` framework case `Failed`.
Failed,
}
impl PlayerItemStatus {
/// Mirrors the `AVPlayer` framework constant `fn`.
#[must_use]
pub const fn from_raw(raw: i32) -> Self {
match raw {
1 => Self::ReadyToPlay,
2 => Self::Failed,
_ => Self::Unknown,
}
}
}
/// Events emitted by `PlayerItemObserver`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum PlayerItemEvent {
/// Mirrors the `AVPlayer` framework case `StatusChanged`.
StatusChanged {
status: PlayerItemStatus,
error_message: Option<String>,
},
/// Mirrors the `AVPlayer` framework case `PresentationSizeChanged`.
PresentationSizeChanged(Size),
/// Mirrors the `AVPlayer` framework case `TimeJumped`.
TimeJumped {
has_originating_participant: bool,
},
/// Mirrors the `AVPlayer` framework case `DidPlayToEnd`.
DidPlayToEnd,
/// Mirrors the `AVPlayer` framework case `FailedToPlayToEnd`.
FailedToPlayToEnd {
error_message: Option<String>,
},
/// Mirrors the `AVPlayer` framework case `PlaybackStalled`.
PlaybackStalled,
/// Mirrors the `AVPlayer` framework case `NewAccessLogEntry`.
NewAccessLogEntry,
/// Mirrors the `AVPlayer` framework case `NewErrorLogEntry`.
NewErrorLogEntry,
/// Mirrors the `AVPlayer` framework case `RecommendedTimeOffsetFromLiveDidChange`.
RecommendedTimeOffsetFromLiveDidChange(Time),
/// Mirrors the `AVPlayer` framework case `MediaSelectionChanged`.
MediaSelectionChanged,
}
struct PlayerItemObserverState {
callback: Box<dyn Fn(PlayerItemEvent) + Send + 'static>,
}
struct PeriodicTimeObserverState {
callback: Box<dyn FnMut(Time) + Send + 'static>,
}
struct BoundaryTimeObserverState {
callback: Box<dyn FnMut() + Send + 'static>,
}
/// Safe wrapper around `AVPlayerItem`.
#[derive(Debug)]
pub struct PlayerItem {
pub(crate) ptr: *mut c_void,
}
impl Drop for PlayerItem {
fn drop(&mut self) {
if !self.ptr.is_null() {
// SAFETY: `self.ptr` is a valid, non-null handle returned by the corresponding
// ffi create function and has not been released.
unsafe { ffi::av_player_item_release(self.ptr) };
self.ptr = ptr::null_mut();
}
}
}
impl PlayerItem {
/// Create a player item from a file path.
pub fn from_file_path(path: impl AsRef<Path>) -> Result<Self, AVPlayerError> {
let path = path
.as_ref()
.to_str()
.ok_or_else(|| AVPlayerError::InvalidArgument("path is not valid UTF-8".into()))?;
Self::from_url_internal(path, true)
}
/// Create a player item from a remote URL.
pub fn from_remote_url(url: impl AsRef<str>) -> Result<Self, AVPlayerError> {
Self::from_url_internal(url.as_ref(), false)
}
/// Create a player item from an existing asset.
pub fn from_asset(asset: &Asset) -> Result<Self, AVPlayerError> {
let keys_json =
CString::new("[\"duration\",\"tracks\",\"metadata\"]").map_err(|error| {
AVPlayerError::InvalidArgument(format!("asset-key JSON contains NUL byte: {error}"))
})?;
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `asset.ptr` is a valid borrowed AVAsset handle, `keys_json` is a
// NUL-terminated string, and `err` points to writable storage for the bridge.
let ptr = unsafe {
ffi::av_player_item_create_with_asset(asset.ptr, keys_json.as_ptr(), &mut err)
};
if ptr.is_null() {
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::PLAYER_CREATE_FAILED, err) });
}
Ok(Self { ptr })
}
fn from_url_internal(url: &str, is_file_url: bool) -> Result<Self, AVPlayerError> {
let url = CString::new(url).map_err(|error| {
AVPlayerError::InvalidArgument(format!("URL contains NUL byte: {error}"))
})?;
let keys_json =
CString::new("[\"duration\",\"tracks\",\"metadata\"]").map_err(|error| {
AVPlayerError::InvalidArgument(format!("asset-key JSON contains NUL byte: {error}"))
})?;
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `url` and `keys_json` are NUL-terminated strings owned by this
// frame, and `err` points to writable storage for the bridge.
let ptr = unsafe {
ffi::av_player_item_create_with_url(
url.as_ptr(),
is_file_url,
keys_json.as_ptr(),
&mut err,
)
};
if ptr.is_null() {
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::PLAYER_CREATE_FAILED, err) });
}
Ok(Self { ptr })
}
fn info(&self) -> Result<PlayerItemInfoPayload, AVPlayerError> {
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `self.ptr` is a valid AVPlayerItem handle and `err` points to
// writable storage for the bridge.
let json_ptr = unsafe { ffi::av_player_item_info_json(self.ptr, &mut err) };
if json_ptr.is_null() {
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::OPERATION_FAILED, err) });
}
parse_json_and_free(json_ptr)
}
/// Calls the `AVPlayer` framework counterpart for `status`.
pub fn status(&self) -> Result<PlayerItemStatus, AVPlayerError> {
Ok(PlayerItemStatus::from_raw(self.info()?.status))
}
/// Calls the `AVPlayer` framework counterpart for `error`.
pub fn error(&self) -> Result<Option<String>, AVPlayerError> {
Ok(self.info()?.error_message)
}
/// Calls the `AVPlayer` framework counterpart for `duration`.
pub fn duration(&self) -> Result<Time, AVPlayerError> {
Ok(self.info()?.duration)
}
/// Calls the `AVPlayer` framework counterpart for `presentation_size`.
pub fn presentation_size(&self) -> Result<Size, AVPlayerError> {
Ok(self.info()?.presentation_size)
}
/// The current macOS SDK does not expose `externalMetadata`; this returns
/// the underlying asset metadata instead.
pub fn metadata(&self) -> Result<Vec<MetadataItem>, AVPlayerError> {
Ok(self.info()?.metadata)
}
/// Calls the `AVPlayer` framework counterpart for `observe`.
pub fn observe<F>(&self, callback: F) -> Result<PlayerItemObserver, AVPlayerError>
where
F: Fn(PlayerItemEvent) + Send + 'static,
{
let state = Box::new(PlayerItemObserverState {
callback: Box::new(callback),
});
let userdata = Box::into_raw(state).cast::<c_void>();
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `self.ptr` is a valid AVPlayerItem handle, `userdata` is a Box
// allocation that remains alive until the drop callback runs, and `err`
// points to writable storage for the bridge.
let token = unsafe {
ffi::av_player_item_add_observer(
self.ptr,
Some(player_item_event_trampoline),
userdata,
Some(player_item_observer_drop),
&mut err,
)
};
if token.is_null() {
// SAFETY: Observer creation failed before ownership of `userdata` was
// transferred to the bridge, so we must reclaim it locally.
unsafe { player_item_observer_drop(userdata) };
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::OBSERVER_FAILED, err) });
}
Ok(PlayerItemObserver { token })
}
}
/// KVO + notification observer for `AVPlayerItem`.
#[derive(Debug)]
pub struct PlayerItemObserver {
token: *mut c_void,
}
impl Drop for PlayerItemObserver {
fn drop(&mut self) {
if !self.token.is_null() {
// SAFETY: `self.token` is a valid observer token returned by the bridge
// and has not been released yet.
unsafe { ffi::av_player_item_observer_release(self.token) };
self.token = ptr::null_mut();
}
}
}
/// Safe wrapper around `AVPlayer`.
#[derive(Debug)]
pub struct Player {
pub(crate) ptr: *mut c_void,
}
impl Drop for Player {
fn drop(&mut self) {
if !self.ptr.is_null() {
// SAFETY: `self.ptr` is a valid, non-null handle returned by the corresponding
// ffi create function and has not been released.
unsafe { ffi::av_player_release(self.ptr) };
self.ptr = ptr::null_mut();
}
}
}
impl Player {
/// Create a player from a file path.
pub fn from_file_path(path: impl AsRef<Path>) -> Result<Self, AVPlayerError> {
let path = path
.as_ref()
.to_str()
.ok_or_else(|| AVPlayerError::InvalidArgument("path is not valid UTF-8".into()))?;
Self::from_url_internal(path, true)
}
/// Create a player from a remote URL.
pub fn from_remote_url(url: impl AsRef<str>) -> Result<Self, AVPlayerError> {
Self::from_url_internal(url.as_ref(), false)
}
/// Create a player that plays the supplied asset.
pub fn from_asset(asset: &Asset) -> Result<Self, AVPlayerError> {
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `asset.ptr` is a valid borrowed AVAsset handle and `err` points
// to writable storage for the bridge.
let ptr = unsafe { ffi::av_player_create_with_asset(asset.ptr, &mut err) };
if ptr.is_null() {
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::PLAYER_CREATE_FAILED, err) });
}
Ok(Self { ptr })
}
/// Create a player from an already-configured item.
pub fn from_item(item: &PlayerItem) -> Result<Self, AVPlayerError> {
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `item.ptr` is a valid borrowed AVPlayerItem handle and `err`
// points to writable storage for the bridge.
let ptr = unsafe { ffi::av_player_create_with_item(item.ptr, &mut err) };
if ptr.is_null() {
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::PLAYER_CREATE_FAILED, err) });
}
Ok(Self { ptr })
}
fn from_url_internal(url: &str, is_file_url: bool) -> Result<Self, AVPlayerError> {
let url = CString::new(url).map_err(|error| {
AVPlayerError::InvalidArgument(format!("URL contains NUL byte: {error}"))
})?;
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `url` is a NUL-terminated string owned by this frame and `err`
// points to writable storage for the bridge.
let ptr = unsafe { ffi::av_player_create_with_url(url.as_ptr(), is_file_url, &mut err) };
if ptr.is_null() {
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::PLAYER_CREATE_FAILED, err) });
}
Ok(Self { ptr })
}
fn info(&self) -> Result<PlayerInfoPayload, AVPlayerError> {
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `self.ptr` is a valid AVPlayer handle and `err` points to
// writable storage for the bridge.
let json_ptr = unsafe { ffi::av_player_info_json(self.ptr, &mut err) };
if json_ptr.is_null() {
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::OPERATION_FAILED, err) });
}
parse_json_and_free(json_ptr)
}
/// Calls the `AVPlayer` framework counterpart for `status`.
pub fn status(&self) -> Result<PlayerStatus, AVPlayerError> {
Ok(PlayerStatus::from_raw(self.info()?.status))
}
/// Calls the `AVPlayer` framework counterpart for `error`.
pub fn error(&self) -> Result<Option<String>, AVPlayerError> {
Ok(self.info()?.error_message)
}
/// Calls the `AVPlayer` framework counterpart for `rate`.
pub fn rate(&self) -> Result<f32, AVPlayerError> {
Ok(self.info()?.rate)
}
/// Calls the `AVPlayer` framework counterpart for `current_time`.
pub fn current_time(&self) -> Result<Time, AVPlayerError> {
Ok(self.info()?.current_time)
}
/// Calls the `AVPlayer` framework counterpart for `duration`.
pub fn duration(&self) -> Result<Time, AVPlayerError> {
Ok(self.info()?.duration)
}
/// Calls the `AVPlayer` framework counterpart for `current_item`.
pub fn current_item(&self) -> Option<PlayerItem> {
// SAFETY: `self.ptr` is a valid AVPlayer handle; the bridge returns either
// a retained current item or null when no item is set.
let ptr = unsafe { ffi::av_player_copy_current_item(self.ptr) };
if ptr.is_null() {
None
} else {
Some(PlayerItem { ptr })
}
}
/// Calls the `AVPlayer` framework counterpart for `play`.
pub fn play(&self) {
// SAFETY: `self.ptr` is a valid, non-null handle returned by the corresponding
// ffi create function and has not been released.
unsafe { ffi::av_player_play(self.ptr) };
}
/// Calls the `AVPlayer` framework counterpart for `pause`.
pub fn pause(&self) {
// SAFETY: `self.ptr` is a valid, non-null handle returned by the corresponding
// ffi create function and has not been released.
unsafe { ffi::av_player_pause(self.ptr) };
}
/// Calls the `AVPlayer` framework counterpart for `set_rate`.
pub fn set_rate(&self, rate: f32) {
// SAFETY: `self.ptr` is a valid, non-null handle returned by the corresponding
// ffi create function and has not been released.
unsafe { ffi::av_player_set_rate(self.ptr, rate) };
}
/// Calls the `AVPlayer` framework counterpart for `seek_to`.
pub fn seek_to(&self, time: Time) -> Result<(), AVPlayerError> {
let mut err: *mut c_char = ptr::null_mut();
let (value, timescale, kind) = time.to_raw();
// SAFETY: `self.ptr` is a valid AVPlayer handle and `err` points to
// writable storage for the bridge.
let status = unsafe { ffi::av_player_seek(self.ptr, value, timescale, kind, &mut err) };
if status != ffi::status::OK {
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(status, err) });
}
Ok(())
}
/// Calls the `AVPlayer` framework counterpart for `add_periodic_time_observer`.
pub fn add_periodic_time_observer<F>(
&self,
interval: Time,
queue_label: Option<&str>,
callback: F,
) -> Result<PeriodicTimeObserver, AVPlayerError>
where
F: FnMut(Time) + Send + 'static,
{
let queue_label = queue_label_cstring(queue_label)?;
let state = Box::new(PeriodicTimeObserverState {
callback: Box::new(callback),
});
let userdata = Box::into_raw(state).cast::<c_void>();
let (value, timescale, kind) = interval.to_raw();
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `self.ptr` is a valid AVPlayer handle, `userdata` is a Box
// allocation that remains alive until the drop callback runs, and `err`
// points to writable storage for the bridge.
let token = unsafe {
ffi::av_player_add_periodic_time_observer(
self.ptr,
value,
timescale,
kind,
queue_label
.as_ref()
.map_or(ptr::null(), |label| label.as_ptr()),
Some(periodic_time_observer_trampoline),
userdata,
Some(periodic_time_observer_drop),
&mut err,
)
};
if token.is_null() {
// SAFETY: Observer creation failed before ownership of `userdata` was
// transferred to the bridge, so we must reclaim it locally.
unsafe { periodic_time_observer_drop(userdata) };
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::OBSERVER_FAILED, err) });
}
Ok(PeriodicTimeObserver { token })
}
/// Calls the `AVPlayer` framework counterpart for `add_boundary_time_observer`.
pub fn add_boundary_time_observer<F>(
&self,
times: &[Time],
queue_label: Option<&str>,
callback: F,
) -> Result<BoundaryTimeObserver, AVPlayerError>
where
F: FnMut() + Send + 'static,
{
let queue_label = queue_label_cstring(queue_label)?;
let times_json = serde_json::to_string(times).map_err(|error| {
AVPlayerError::InvalidArgument(format!("failed to encode boundary times: {error}"))
})?;
let times_json = CString::new(times_json).map_err(|error| {
AVPlayerError::InvalidArgument(format!(
"boundary times JSON contains NUL byte: {error}"
))
})?;
let state = Box::new(BoundaryTimeObserverState {
callback: Box::new(callback),
});
let userdata = Box::into_raw(state).cast::<c_void>();
let mut err: *mut c_char = ptr::null_mut();
// SAFETY: `self.ptr` is a valid AVPlayer handle, `times_json` is a
// NUL-terminated string owned by this frame, `userdata` is kept alive
// until the drop callback runs, and `err` points to writable storage.
let token = unsafe {
ffi::av_player_add_boundary_time_observer(
self.ptr,
times_json.as_ptr(),
queue_label
.as_ref()
.map_or(ptr::null(), |label| label.as_ptr()),
Some(boundary_time_observer_trampoline),
userdata,
Some(boundary_time_observer_drop),
&mut err,
)
};
if token.is_null() {
// SAFETY: Observer creation failed before ownership of `userdata` was
// transferred to the bridge, so we must reclaim it locally.
unsafe { boundary_time_observer_drop(userdata) };
// SAFETY: On failure the bridge initializes `err` to an owned Swift error
// payload that `from_swift` consumes.
return Err(unsafe { from_swift(ffi::status::OBSERVER_FAILED, err) });
}
Ok(BoundaryTimeObserver { token })
}
}
/// RAII token for `addPeriodicTimeObserver`.
#[derive(Debug)]
pub struct PeriodicTimeObserver {
token: *mut c_void,
}
impl Drop for PeriodicTimeObserver {
fn drop(&mut self) {
if !self.token.is_null() {
// SAFETY: `self.token` is a valid observer token returned by the bridge
// and has not been released yet.
unsafe { ffi::av_player_time_observer_release(self.token) };
self.token = ptr::null_mut();
}
}
}
/// RAII token for `addBoundaryTimeObserver`.
#[derive(Debug)]
pub struct BoundaryTimeObserver {
token: *mut c_void,
}
impl Drop for BoundaryTimeObserver {
fn drop(&mut self) {
if !self.token.is_null() {
// SAFETY: `self.token` is a valid observer token returned by the bridge
// and has not been released yet.
unsafe { ffi::av_player_time_observer_release(self.token) };
self.token = ptr::null_mut();
}
}
}
// SAFETY: AVPlayer / AVPlayerItem ObjC handles and observer tokens are safe to
// transfer across thread boundaries; method calls are internally dispatched
// safely.
unsafe impl Send for PlayerItem {}
unsafe impl Send for PlayerItemObserver {}
unsafe impl Send for Player {}
unsafe impl Send for PeriodicTimeObserver {}
unsafe impl Send for BoundaryTimeObserver {}
unsafe extern "C" fn player_item_event_trampoline(
userdata: *mut c_void,
payload_json: *const c_char,
) {
if userdata.is_null() || payload_json.is_null() {
return;
}
// SAFETY: `userdata` is a valid `*mut PlayerItemObserverState` allocated in
// `observe()` and kept alive for the lifetime of the token; null is checked above.
let callback = unsafe { &*userdata.cast::<PlayerItemObserverState>() };
// SAFETY: `payload_json` is a non-null, NUL-terminated string owned by the
// bridge for the duration of this callback.
let Ok(payload) = unsafe { CStr::from_ptr(payload_json) }.to_str() else {
return;
};
let Ok(payload) = serde_json::from_str::<PlayerItemEventPayload>(payload) else {
return;
};
let event = match payload.event.as_str() {
"status_changed" => PlayerItemEvent::StatusChanged {
status: PlayerItemStatus::from_raw(payload.status.unwrap_or_default()),
error_message: payload.error_message,
},
"presentation_size_changed" => match payload.presentation_size {
Some(size) => PlayerItemEvent::PresentationSizeChanged(size),
None => return,
},
"time_jumped" => PlayerItemEvent::TimeJumped {
has_originating_participant: payload.has_originating_participant.unwrap_or(false),
},
"did_play_to_end" => PlayerItemEvent::DidPlayToEnd,
"failed_to_play_to_end" => PlayerItemEvent::FailedToPlayToEnd {
error_message: payload.error_message,
},
"playback_stalled" => PlayerItemEvent::PlaybackStalled,
"new_access_log_entry" => PlayerItemEvent::NewAccessLogEntry,
"new_error_log_entry" => PlayerItemEvent::NewErrorLogEntry,
"recommended_time_offset_from_live_did_change" => {
match payload.recommended_time_offset_from_live {
Some(time) => PlayerItemEvent::RecommendedTimeOffsetFromLiveDidChange(time),
None => return,
}
}
"media_selection_changed" => PlayerItemEvent::MediaSelectionChanged,
_ => return,
};
crate::util::catch_cb_panic("player_item_event_trampoline", || {
(callback.callback)(event);
});
}
unsafe extern "C" fn player_item_observer_drop(userdata: *mut c_void) {
if !userdata.is_null() {
// SAFETY: `userdata` is the unique Box pointer created in `observe()`; the
// Swift bridge calls this drop callback exactly once.
drop(unsafe { Box::from_raw(userdata.cast::<PlayerItemObserverState>()) });
}
}
unsafe extern "C" fn periodic_time_observer_trampoline(
userdata: *mut c_void,
value: i64,
timescale: i32,
kind: i32,
) {
if userdata.is_null() {
return;
}
// SAFETY: `userdata` is a valid `*mut PeriodicTimeObserverState` allocated in
// `add_periodic_time_observer()` and kept alive for the lifetime of the token;
// null is checked above.
let state = unsafe { &mut *userdata.cast::<PeriodicTimeObserverState>() };
crate::util::catch_cb_panic("periodic_time_observer_trampoline", || {
(state.callback)(Time::from_raw(value, timescale, kind));
});
}
unsafe extern "C" fn periodic_time_observer_drop(userdata: *mut c_void) {
if !userdata.is_null() {
// SAFETY: `userdata` is the unique Box pointer created in
// `add_periodic_time_observer()`; the Swift bridge calls this drop callback
// exactly once.
drop(unsafe { Box::from_raw(userdata.cast::<PeriodicTimeObserverState>()) });
}
}
unsafe extern "C" fn boundary_time_observer_trampoline(userdata: *mut c_void) {
if userdata.is_null() {
return;
}
// SAFETY: `userdata` is a valid `*mut BoundaryTimeObserverState` allocated in
// `add_boundary_time_observer()` and kept alive for the lifetime of the token;
// null is checked above.
let state = unsafe { &mut *userdata.cast::<BoundaryTimeObserverState>() };
crate::util::catch_cb_panic("boundary_time_observer_trampoline", || {
(state.callback)();
});
}
unsafe extern "C" fn boundary_time_observer_drop(userdata: *mut c_void) {
if !userdata.is_null() {
// SAFETY: `userdata` is the unique Box pointer created in
// `add_boundary_time_observer()`; the Swift bridge calls this drop callback
// exactly once.
drop(unsafe { Box::from_raw(userdata.cast::<BoundaryTimeObserverState>()) });
}
}
fn queue_label_cstring(queue_label: Option<&str>) -> Result<Option<CString>, AVPlayerError> {
queue_label
.map(|label| {
CString::new(label).map_err(|error| {
AVPlayerError::InvalidArgument(format!("queue label contains NUL byte: {error}"))
})
})
.transpose()
}
fn parse_json_and_free<T: DeserializeOwned>(json_ptr: *mut c_char) -> Result<T, AVPlayerError> {
// SAFETY: `json_ptr` is a non-null, NUL-terminated C string returned by the
// bridge; it remains valid until freed with `avp_string_free`.
let json = unsafe { CStr::from_ptr(json_ptr) }
.to_string_lossy()
.into_owned();
// SAFETY: `json_ptr` was returned by the FFI and has not been freed yet.
unsafe { ffi::avp_string_free(json_ptr) };
serde_json::from_str::<T>(&json).map_err(|error| {
AVPlayerError::OperationFailed(format!("failed to decode bridge JSON: {error}"))
})
}