avplayer 0.3.5

Safe Rust bindings for Apple's AVPlayer + AVAssetReader — playback and frame-by-frame asset reading on macOS
Documentation
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
//! Async API for `avplayer` — executor-agnostic `Future` wrappers for
//! `AVFoundation`'s `async throws` and completion-handler surfaces.
//!
//! Gated behind the **`async`** cargo feature.
//!
//! ## Available types
//!
//! | Type | Description |
//! |------|-------------|
//! | [`AsyncAsset`] | Async property / track loading (`AVAsset.load(...)`) |
//! | [`AsyncPlayerItem`] | Async seek (`AVPlayerItem.seek(to:completionHandler:)`) |
//! | [`AsyncPlayer`] | Async seek + preroll (`AVPlayer.seek / preroll`) |
//!
//! ## Note on KVO / periodic observers
//!
//! KVO-based observation (`PlayerItemObserver`, `PeriodicTimeObserver`, etc.)
//! fires multiple times and therefore belongs to a Stream-based "Tier 2" async
//! pattern — **not** this module.
//!
//! ## Example
//!
//! ```rust,no_run
//! use avplayer::{UrlAsset, async_api::AsyncAsset};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     pollster::block_on(async {
//!         let asset = UrlAsset::from_remote_url("https://example.com/sample.mp4")?;
//!         let props = AsyncAsset::new(asset.as_asset()).load_properties().await?;
//!         println!("duration: {:?}  playable: {}", props.duration, props.is_playable);
//!         Ok(())
//!     })
//! }
//! ```

#![allow(clippy::missing_errors_doc, clippy::must_use_candidate)]

use std::ffi::{c_void, CStr};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use doom_fish_utils::completion::{error_from_cstr, AsyncCompletion, AsyncCompletionFuture};
use serde::Deserialize;

use crate::asset::{Asset, MediaType, Size};
use crate::error::AVPlayerError;
use crate::ffi;
use crate::metadata::MetadataItem;
use crate::player::{Player, PlayerItem};
use crate::time::Time;

// ── JSON payloads (private) ───────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AsyncAssetPropertiesPayload {
    duration: Time,
    metadata: Vec<MetadataItem>,
    is_playable: bool,
    is_exportable: bool,
    has_protected_content: bool,
    preferred_rate: f32,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TrackInfoPayload {
    track_id: i32,
    media_type: String,
    natural_size: Size,
    nominal_frame_rate: String,
    estimated_data_rate: String,
}

// ── Public result structs ─────────────────────────────────────────────────────

/// Properties loaded asynchronously from `AVAsset.load(...)`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct AssetProperties {
    /// Asset duration.
    pub duration: Time,
    /// Static metadata items.
    pub metadata: Vec<MetadataItem>,
    /// Whether the asset can be used for playback.
    pub is_playable: bool,
    /// Whether the asset can be exported.
    pub is_exportable: bool,
    /// Whether the asset contains protected (`FairPlay`) content.
    pub has_protected_content: bool,
    /// Natural playback rate encoded in the asset.
    pub preferred_rate: f32,
}

/// Track properties loaded asynchronously.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct TrackProperties {
    /// Persistent track identifier.
    pub track_id: i32,
    /// Track media type.
    pub media_type: MediaType,
    /// Natural presentation size.
    pub natural_size: Size,
    /// Nominal frame rate (for video tracks; `None` if unavailable or non-numeric).
    pub nominal_frame_rate: Option<f32>,
    /// Estimated data rate in bps (`None` if unavailable or non-numeric).
    pub estimated_data_rate: Option<f32>,
}

impl TrackProperties {
    fn from_payload(p: &TrackInfoPayload) -> Self {
        Self {
            track_id: p.track_id,
            media_type: MediaType::from_raw(&p.media_type),
            natural_size: p.natural_size,
            nominal_frame_rate: p.nominal_frame_rate.parse().ok(),
            estimated_data_rate: p.estimated_data_rate.parse().ok(),
        }
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Map a `String` (error message from completion) to `AVPlayerError::LoadFailed`.
const fn bridge_err(msg: String) -> AVPlayerError {
    AVPlayerError::LoadFailed(msg)
}

// ── AssetProperties future ────────────────────────────────────────────────────

extern "C" fn asset_properties_cb(result: *const c_void, error: *const i8, ctx: *mut c_void) {
    if !error.is_null() {
        // SAFETY: `error` is a non-null, NUL-terminated error string provided by
        // the bridge for the duration of this callback.
        let msg = unsafe { error_from_cstr(error) };
        // SAFETY: `ctx` is the raw context pointer vended by
        // `AsyncCompletion::create()` and has not been consumed yet; Swift fires
        // this callback exactly once.
        unsafe { AsyncCompletion::<String>::complete_err(ctx, msg) };
    } else if !result.is_null() {
        // SAFETY: `result` is a non-null, NUL-terminated C string returned by the
        // bridge; it remains valid until freed with `avp_string_free`.
        let s = unsafe { CStr::from_ptr(result.cast()).to_string_lossy().into_owned() };
        // SAFETY: `result` was returned by the FFI and has not been freed yet.
        unsafe { ffi::avp_string_free(result as *mut _) };
        // SAFETY: `ctx` is the raw context pointer vended by
        // `AsyncCompletion::create()` and has not been consumed yet; Swift fires
        // this callback exactly once.
        unsafe { AsyncCompletion::complete_ok(ctx, s) };
    } else {
        // SAFETY: `ctx` is the raw context pointer vended by
        // `AsyncCompletion::create()` and has not been consumed yet; Swift fires
        // this callback exactly once.
        unsafe {
            AsyncCompletion::<String>::complete_err(ctx, "bridge returned null result".into());
        };
    }
}

/// Future returned by [`AsyncAsset::load_properties`].
pub struct AssetPropertiesFuture {
    inner: AsyncCompletionFuture<String>,
}

impl std::fmt::Debug for AssetPropertiesFuture {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AssetPropertiesFuture")
            .finish_non_exhaustive()
    }
}

impl Future for AssetPropertiesFuture {
    type Output = Result<AssetProperties, AVPlayerError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.inner).poll(cx).map(|r| {
            let json = r.map_err(bridge_err)?;
            let p = serde_json::from_str::<AsyncAssetPropertiesPayload>(&json).map_err(|e| {
                AVPlayerError::OperationFailed(format!("async bridge JSON decode failed: {e}"))
            })?;
            Ok(AssetProperties {
                duration: p.duration,
                metadata: p.metadata,
                is_playable: p.is_playable,
                is_exportable: p.is_exportable,
                has_protected_content: p.has_protected_content,
                preferred_rate: p.preferred_rate,
            })
        })
    }
}

// ── Tracks future ─────────────────────────────────────────────────────────────

extern "C" fn asset_tracks_cb(result: *const c_void, error: *const i8, ctx: *mut c_void) {
    asset_properties_cb(result, error, ctx); // same JSON-string pattern
}

/// Future returned by [`AsyncAsset::load_tracks`] and [`AsyncAsset::load_tracks_with_media_type`].
pub struct AssetTracksFuture {
    inner: AsyncCompletionFuture<String>,
}

impl std::fmt::Debug for AssetTracksFuture {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AssetTracksFuture").finish_non_exhaustive()
    }
}

impl Future for AssetTracksFuture {
    type Output = Result<Vec<TrackProperties>, AVPlayerError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.inner).poll(cx).map(|r| {
            let json = r.map_err(bridge_err)?;
            let payloads = serde_json::from_str::<Vec<TrackInfoPayload>>(&json).map_err(|e| {
                AVPlayerError::OperationFailed(format!("async bridge JSON decode failed: {e}"))
            })?;
            Ok(payloads
                .into_iter()
                .map(|p| TrackProperties::from_payload(&p))
                .collect())
        })
    }
}

// ── TrackById future ──────────────────────────────────────────────────────────

extern "C" fn asset_track_by_id_cb(result: *const c_void, error: *const i8, ctx: *mut c_void) {
    asset_properties_cb(result, error, ctx); // same JSON-string pattern
}

/// Future returned by [`AsyncAsset::load_track_with_id`].
pub struct AssetTrackByIdFuture {
    inner: AsyncCompletionFuture<String>,
}

impl std::fmt::Debug for AssetTrackByIdFuture {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AssetTrackByIdFuture")
            .finish_non_exhaustive()
    }
}

impl Future for AssetTrackByIdFuture {
    type Output = Result<Option<TrackProperties>, AVPlayerError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.inner).poll(cx).map(|r| {
            let json = r.map_err(bridge_err)?;
            if json.trim() == "null" {
                return Ok(None);
            }
            let payload = serde_json::from_str::<TrackInfoPayload>(&json).map_err(|e| {
                AVPlayerError::OperationFailed(format!("async bridge JSON decode failed: {e}"))
            })?;
            Ok(Some(TrackProperties::from_payload(&payload)))
        })
    }
}

// ── Bool (seek / preroll) future ──────────────────────────────────────────────

extern "C" fn bool_completion_cb(result: *const c_void, error: *const i8, ctx: *mut c_void) {
    if error.is_null() {
        // result is UnsafeRawPointer(bitPattern: 1) for true, nil for false
        let finished = !result.is_null();
        // SAFETY: `ctx` is the raw context pointer vended by
        // `AsyncCompletion::create()` and has not been consumed yet; Swift fires
        // this callback exactly once.
        unsafe { AsyncCompletion::complete_ok(ctx, finished) };
    } else {
        // SAFETY: `error` is a non-null, NUL-terminated error string provided by
        // the bridge for the duration of this callback.
        let msg = unsafe { error_from_cstr(error) };
        // SAFETY: `ctx` is the raw context pointer vended by
        // `AsyncCompletion::create()` and has not been consumed yet; Swift fires
        // this callback exactly once.
        unsafe { AsyncCompletion::<bool>::complete_err(ctx, msg) };
    }
}

/// Future returned by [`AsyncPlayerItem::seek`].
pub struct PlayerItemSeekFuture {
    inner: AsyncCompletionFuture<bool>,
}

impl std::fmt::Debug for PlayerItemSeekFuture {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PlayerItemSeekFuture")
            .finish_non_exhaustive()
    }
}

impl Future for PlayerItemSeekFuture {
    type Output = Result<bool, AVPlayerError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.inner)
            .poll(cx)
            .map(|r| r.map_err(bridge_err))
    }
}

/// Future returned by [`AsyncPlayer::seek`].
pub struct PlayerSeekFuture {
    inner: AsyncCompletionFuture<bool>,
}

impl std::fmt::Debug for PlayerSeekFuture {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PlayerSeekFuture").finish_non_exhaustive()
    }
}

impl Future for PlayerSeekFuture {
    type Output = Result<bool, AVPlayerError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.inner)
            .poll(cx)
            .map(|r| r.map_err(bridge_err))
    }
}

/// Future returned by [`AsyncPlayer::preroll`].
pub struct PlayerPrerollFuture {
    inner: AsyncCompletionFuture<bool>,
}

impl std::fmt::Debug for PlayerPrerollFuture {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PlayerPrerollFuture")
            .finish_non_exhaustive()
    }
}

impl Future for PlayerPrerollFuture {
    type Output = Result<bool, AVPlayerError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.inner)
            .poll(cx)
            .map(|r| r.map_err(bridge_err))
    }
}

// ── Async wrappers ────────────────────────────────────────────────────────────

/// Async accessor for [`Asset`].
///
/// Wraps the `AVAsset.load(...)` `async throws` family and the modern
/// `AVAsset.loadTracks` / `loadTrack(withTrackID:)` helpers (macOS 12+).
///
/// KVO-based observation belongs to the Tier 2 stream pattern and is **not**
/// included here.
pub struct AsyncAsset<'a> {
    asset: &'a Asset,
}

impl std::fmt::Debug for AsyncAsset<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncAsset").finish_non_exhaustive()
    }
}

impl<'a> AsyncAsset<'a> {
    /// Wrap a borrowed [`Asset`].
    pub const fn new(asset: &'a Asset) -> Self {
        Self { asset }
    }

    /// Load `duration`, `metadata`, `isPlayable`, `isExportable`,
    /// `hasProtectedContent`, and `preferredRate` concurrently via
    /// `AVAsset.load(...)`.
    pub fn load_properties(&self) -> AssetPropertiesFuture {
        let (future, ctx) = AsyncCompletion::create();
        // SAFETY: `self.asset.ptr` is a valid borrowed AVAsset handle and `ctx` is
        // the raw completion context returned by `AsyncCompletion::create()`.
        unsafe { ffi::avp_asset_load_properties_async(self.asset.ptr, asset_properties_cb, ctx) };
        AssetPropertiesFuture { inner: future }
    }

    /// Load all tracks via `AVAsset.load(.tracks)`.
    pub fn load_tracks(&self) -> AssetTracksFuture {
        let (future, ctx) = AsyncCompletion::create();
        // SAFETY: `self.asset.ptr` is a valid borrowed AVAsset handle and `ctx` is
        // the raw completion context returned by `AsyncCompletion::create()`.
        unsafe { ffi::avp_asset_load_tracks_async(self.asset.ptr, asset_tracks_cb, ctx) };
        AssetTracksFuture { inner: future }
    }

    /// Load tracks filtered by media type via `AVAsset.loadTracks(withMediaType:)`.
    ///
    /// `media_type` should be one of `"audio"`, `"video"`, `"text"`, etc.
    pub fn load_tracks_with_media_type(&self, media_type: &str) -> AssetTracksFuture {
        use std::ffi::CString;
        let mt = CString::new(media_type).unwrap_or_default();
        let (future, ctx) = AsyncCompletion::create();
        // SAFETY: `self.asset.ptr` is a valid borrowed AVAsset handle, `mt` is a
        // NUL-terminated string owned by this frame, and `ctx` is the raw
        // completion context returned by `AsyncCompletion::create()`.
        unsafe {
            ffi::avp_asset_load_tracks_with_media_type_async(
                self.asset.ptr,
                mt.as_ptr(),
                asset_tracks_cb,
                ctx,
            );
        };
        AssetTracksFuture { inner: future }
    }

    /// Load a single track by persistent track ID via
    /// `AVAsset.loadTrack(withTrackID:)`.
    ///
    /// Returns `Ok(None)` when no track with the given ID exists.
    pub fn load_track_with_id(&self, track_id: i32) -> AssetTrackByIdFuture {
        let (future, ctx) = AsyncCompletion::create();
        // SAFETY: `self.asset.ptr` is a valid borrowed AVAsset handle and `ctx` is
        // the raw completion context returned by `AsyncCompletion::create()`.
        unsafe {
            ffi::avp_asset_load_track_with_id_async(
                self.asset.ptr,
                track_id,
                asset_track_by_id_cb,
                ctx,
            );
        };
        AssetTrackByIdFuture { inner: future }
    }
}

/// Async accessor for [`PlayerItem`].
///
/// Wraps `AVPlayerItem.seek(to:completionHandler:)`.
pub struct AsyncPlayerItem<'a> {
    item: &'a PlayerItem,
}

impl std::fmt::Debug for AsyncPlayerItem<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncPlayerItem").finish_non_exhaustive()
    }
}

impl<'a> AsyncPlayerItem<'a> {
    /// Wrap a borrowed [`PlayerItem`].
    pub const fn new(item: &'a PlayerItem) -> Self {
        Self { item }
    }

    /// Seek the player item to `time`.
    ///
    /// Returns `Ok(true)` when the seek completed to the requested time,
    /// `Ok(false)` when it was interrupted by another seek.
    pub fn seek(&self, time: Time) -> PlayerItemSeekFuture {
        let (future, ctx) = AsyncCompletion::create();
        let (value, timescale, kind) = time.to_raw();
        // SAFETY: `self.item.ptr` is a valid borrowed AVPlayerItem handle and
        // `ctx` is the raw completion context returned by `AsyncCompletion::create()`.
        unsafe {
            ffi::avp_player_item_seek_async(
                self.item.ptr,
                value,
                timescale,
                kind,
                bool_completion_cb,
                ctx,
            );
        };
        PlayerItemSeekFuture { inner: future }
    }
}

/// Async accessor for [`Player`].
///
/// Wraps:
/// * `AVPlayer.seek(to:completionHandler:)`
/// * `AVPlayer.preroll(atRate:completionHandler:)` (deprecated API, still functional)
pub struct AsyncPlayer<'a> {
    player: &'a Player,
}

impl std::fmt::Debug for AsyncPlayer<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncPlayer").finish_non_exhaustive()
    }
}

impl<'a> AsyncPlayer<'a> {
    /// Wrap a borrowed [`Player`].
    pub const fn new(player: &'a Player) -> Self {
        Self { player }
    }

    /// Seek the player to `time`.
    ///
    /// Returns `Ok(true)` when the seek completed to the requested time,
    /// `Ok(false)` when it was interrupted by another seek.
    pub fn seek(&self, time: Time) -> PlayerSeekFuture {
        let (future, ctx) = AsyncCompletion::create();
        let (value, timescale, kind) = time.to_raw();
        // SAFETY: `self.player.ptr` is a valid borrowed AVPlayer handle and `ctx`
        // is the raw completion context returned by `AsyncCompletion::create()`.
        unsafe {
            ffi::avp_player_seek_async(
                self.player.ptr,
                value,
                timescale,
                kind,
                bool_completion_cb,
                ctx,
            );
        };
        PlayerSeekFuture { inner: future }
    }

    /// Preroll the player at `rate`.
    ///
    /// Returns `Ok(true)` when the preroll succeeded, `Ok(false)` when it was
    /// cancelled (e.g. by a rate change or item replacement).
    ///
    /// Note: `AVPlayer.preroll(atRate:completionHandler:)` is deprecated in
    /// macOS 26+ but remains functional on all supported platforms.
    pub fn preroll(&self, rate: f32) -> PlayerPrerollFuture {
        let (future, ctx) = AsyncCompletion::create();
        // SAFETY: `self.player.ptr` is a valid borrowed AVPlayer handle and `ctx`
        // is the raw completion context returned by `AsyncCompletion::create()`.
        unsafe {
            ffi::avp_player_preroll_async(self.player.ptr, rate, bool_completion_cb, ctx);
        };
        PlayerPrerollFuture { inner: future }
    }
}