waft_embedder/media.rs
1//! Players and cameras: the system's own media stack, as a host hands it to the app. Not a
2//! dart:ui file: Flutter reaches media through its `video_player` and `camera` plugins, whose
3//! controllers come from their method channels. These follow the systems' own model instead,
4//! which they share: a player is one object made from a URL, loading by itself, which the app
5//! controls and whose state it observes (`AVPlayer`, Media3's `ExoPlayer`, Windows'
6//! `MediaPlayer`, the web's `<video>`); a camera is a session on one device with outputs, each for
7//! one use (`AVCaptureSession` with its preview layer and its photo, video data and movie file
8//! outputs, CameraX's use cases).
9//!
10//! Every system has two levels: a view that takes a player (`AVPlayerLayer(player:)`, Media3's
11//! `PlayerView.player`), which is the framework's, and a player that puts its pictures where it
12//! is given (Media3's `setVideoSurface`), which is the host's and this module's. A player's
13//! picture goes to one destination at a time, which the app makes and gives it
14//! ([`MediaPlayer::set_video_output`]): a [`CompositionLayer`], whose content becomes a layer the
15//! system draws the picture into, which is the only way protected and HDR video show at all, with
16//! no copy; or a [`VideoFrameReader`], made on its own ([`VideoFrameReaders::make_reader`]), which
17//! hands the frames to the app's GPU, as an Android app makes an `ImageReader` and an Apple app an
18//! `AVPlayerItemVideoOutput` and gives it to its player. A camera, once opened, lists the formats
19//! it runs in, and starts in one of them with its outputs given whole ([`CameraOutputs`]): a layer
20//! for its preview and a reader for its frames, made the same way, beside its photos and
21//! recordings, all of which the system configures together, as Apple configures an
22//! `AVCaptureSession` between `beginConfiguration` and `commitConfiguration` and Android binds
23//! CameraX's use cases at once. A camera's photos are encoded by the system and its recordings
24//! encoded and written to a file by the system: the app encodes nothing.
25//!
26//! Listing the cameras, opening one and starting it answer futures, as systems that answer them
27//! later do: the web's `enumerateDevices` and `getUserMedia` answer promises, and Apple's
28//! documentation of `AVCaptureSession` has a session started on a serial queue of its own, since
29//! `startRunning` blocks until the session runs or fails.
30//!
31//! Beside the player, every system reads media without playing it ([`MediaAssets`]), as a library
32//! reads its videos' lengths, titles and thumbnails: Apple's `AVAsset` and
33//! `AVAssetImageGenerator`, Android's `MediaMetadataRetriever`, Windows' `MediaClip`. An asset
34//! answers with the player's own types, its tracks, its tags and a failure's kind, and its
35//! pictures as the [`VideoFrame`]s a reader hands out, so the app draws one as it draws any frame;
36//! each answer is a future, since the system reads in the background.
37//!
38//! A player tells its media's tracks, plays one audio track and shows one text track or none, as
39//! every system's player does (Apple's media selection groups, Media3's track overrides); it tells
40//! what the media's tags say ([`MediaMetadata`]); and it hands the app the [`Cue`]s of its text
41//! track to draw, the system drawing none, as most players draw their own (Media3's
42//! `SubtitleView`, Safari over AVFoundation's legible output). A cue carries the media's own
43//! styling, and the user's caption style is a system setting beside it, which the platform's
44//! caption settings answer ([`Platform::caption_settings`](crate::Platform::caption_settings))
45//! and the app merges in as it draws, as Media3's `SubtitleView` and WebKit's cue style sheet do.
46//!
47//! A player's state tells what the system's player does, not what the app asked of it: whether
48//! it is paused, waiting or playing, and why, as Apple's `timeControlStatus` and Windows'
49//! `PlaybackState` tell it, since the system pauses a player itself (a call takes the sound,
50//! headphones are unplugged); a seek under way; what is loaded and where it can seek; the rate,
51//! volume and mute it plays with, which the system can change; and a failure with its kind, at
52//! any time. A player's position is read when the app needs it ([`MediaPlayer::position`]), as
53//! every system lets an app read it (AVPlayer's `currentTime()`, Media3's
54//! `getCurrentPosition()`, Windows' `PlaybackSession.Position`, the web's `currentTime`), and told
55//! only when it jumps (a seek landing, a loop), as the systems tell it (Apple's
56//! `AVPlayerItemTimeJumped`, Media3's `onPositionDiscontinuity`, the web's `seeked`): while it
57//! plays it moves on by itself, and an app that shows it reads it at each frame it draws.
58//!
59//! The platform answers `None` where its system has no players, no cameras or no frames. A player
60//! or a session reports its state through [`MediaPlayer::state`] and [`CaptureSession::state`],
61//! and the cameras their list through [`Cameras::cameras`], each read when the future from its
62//! `changed` resolves: the invariant a host keeps is that such a future resolves at every change
63//! of what it reads, a player's metadata and cues included, at every jump of a player's position,
64//! and when the player or session goes, so the app never waits on one for ever.
65
66use std::any::Any;
67use std::fmt;
68use std::future::Future;
69use std::path::PathBuf;
70use std::pin::Pin;
71use std::sync::Arc;
72use std::time::{Duration, Instant};
73
74use crate::image_codecs::{ImageFuture, PixelBuffer};
75use crate::{CompositionLayer, Cue, Size};
76
77/// The system's players, or `None` from [`Platform::players`](crate::Platform::players) where it
78/// has none.
79pub trait Players {
80 /// A player of the media at `url`, which loads by itself, its state saying how far it got: a
81 /// link the system fetches (`https:`, a streaming playlist), or a picked file's
82 /// [`PickedFile::url`](crate::PickedFile::url), as every system's player takes a URL. A URL
83 /// the system cannot play gives a player that failed, with the system's reason. A player of
84 /// bytes the app makes itself is for later.
85 fn open(&self, url: &str) -> Box<dyn MediaPlayer>;
86}
87
88/// One player, controlled on the app's main thread. Dropped, it stops, and its picture goes
89/// nowhere: it leaves the layer it showed on, and its reader reads nothing more.
90pub trait MediaPlayer {
91 /// Plays from where it is, at the rate last set: from the start once it has ended.
92 fn play(&self);
93
94 fn pause(&self);
95
96 /// Moves to `position`, or as near it as `tolerance` lets the system land for speed,
97 /// playing on from there if it was playing. The state tells the seek under way until it
98 /// lands; a seek outside the seekable ranges moves nothing.
99 fn seek(&self, position: Duration, tolerance: SeekTolerance);
100
101 /// How fast it plays, `1.0` the media's own speed; kept while paused, for the next play.
102 fn set_rate(&self, rate: f64);
103
104 /// How loud it plays, from `0.0`, silent, to `1.0`, the media's own volume.
105 fn set_volume(&self, volume: f64);
106
107 /// Whether its sound is off, apart from its volume.
108 fn set_muted(&self, muted: bool);
109
110 /// Whether it starts again from the beginning when it reaches the end, rather than ending.
111 fn set_looping(&self, looping: bool);
112
113 /// The player's state now.
114 fn state(&self) -> PlayerState;
115
116 /// Where it is in the media now, read from the system at each call; it moves on by itself
117 /// while the player plays, and is the target while a seek is under way, as the web's and
118 /// Media3's are.
119 fn position(&self) -> Duration;
120
121 /// Resolves once [`state`](Self::state), [`metadata`](Self::metadata) or
122 /// [`cues`](Self::cues) may answer something else than when this was called, once the
123 /// [`position`](Self::position) jumped, as a seek landing or a loop makes it, or once the
124 /// player is gone; not as the position moves on while the player plays.
125 fn changed(&self) -> MediaChangeFuture;
126
127 /// Sends the picture to `output` from now on, and nowhere it went before; `None` sends it
128 /// nowhere, as Media3's `setVideoSurface` does. The player holds the output while it sends
129 /// the picture there, as a producer holds its layer. A layer no compositor of this host made
130 /// shows nothing, and a reader no [`VideoFrameReaders`] of this host made reads nothing.
131 fn set_video_output(&self, output: Option<VideoOutput>);
132
133 /// Plays the audio track `id`, one of the state's [`tracks`](PlayerState::tracks), in place
134 /// of the one playing.
135 fn select_audio_track(&self, id: &str);
136
137 /// Shows the text track `id`, one of the state's [`tracks`](PlayerState::tracks), or none:
138 /// subtitles off. Its cues are what [`cues`](Self::cues) answers.
139 fn select_text_track(&self, id: Option<&str>);
140
141 /// What the media's tags say about it; empty until the player has read them.
142 fn metadata(&self) -> MediaMetadata;
143
144 /// The cues of the text track shown, to show now, as the media styles them: the user's
145 /// caption style is not merged in. Empty while no text track is shown.
146 fn cues(&self) -> Vec<Cue>;
147}
148
149/// Where a player sends its picture, one destination at a time.
150#[derive(Clone)]
151pub enum VideoOutput {
152 /// The system draws the picture into a layer of its own that is this layer's content.
153 Layer(Arc<dyn CompositionLayer>),
154 /// The app draws the frames this reader hands out.
155 Frames(Arc<dyn VideoFrameReader>),
156}
157
158/// What a player's media is, and what the system's player does with it.
159#[derive(Clone, Debug, PartialEq)]
160pub struct PlayerState {
161 pub status: PlayerStatus,
162 /// Whether it is paused, waiting or playing, as the system reports it.
163 pub activity: PlayerActivity,
164 /// Where a seek is taking it, until it lands; `None` while no seek is under way. A later
165 /// seek replaces the target.
166 pub seeking: Option<Duration>,
167 /// The rate it plays at while it plays, `1.0` the media's own speed, kept while paused for
168 /// the next play; as the system reports it, which can differ from the rate asked for.
169 pub rate: f64,
170 /// How loud it plays, from `0.0`, silent, to `1.0`, the media's own volume.
171 pub volume: f64,
172 /// Whether its sound is off, apart from its volume.
173 pub muted: bool,
174 /// How long the media is; `None` until it is known, and for a live stream.
175 pub duration: Option<Duration>,
176 /// The parts of the media loaded now, in order.
177 pub loaded: Vec<TimeRange>,
178 /// The parts it can seek into, in order: the whole media for a file, a moving window for a
179 /// live stream, none where it cannot seek.
180 pub seekable: Vec<TimeRange>,
181 /// The picture's size, in its own pixels, as it is presented: its aspect corrected; `None`
182 /// until it is known, and for media without a picture.
183 pub size: Option<Size>,
184 /// The media's tracks; empty until it is ready.
185 pub tracks: Vec<MediaTrack>,
186}
187
188impl PlayerState {
189 /// A player that is loading, paused as the app has not played it: nothing known yet.
190 pub fn loading() -> PlayerState {
191 PlayerState {
192 status: PlayerStatus::Loading,
193 activity: PlayerActivity::Paused(Some(PauseReason::Requested)),
194 seeking: None,
195 rate: 1.0,
196 volume: 1.0,
197 muted: false,
198 duration: None,
199 loaded: Vec::new(),
200 seekable: Vec::new(),
201 size: None,
202 tracks: Vec::new(),
203 }
204 }
205
206 /// A player that failed with `error`, and does nothing more.
207 pub fn failed(error: PlayerError) -> PlayerState {
208 PlayerState {
209 status: PlayerStatus::Failed(error),
210 activity: PlayerActivity::Paused(None),
211 ..PlayerState::loading()
212 }
213 }
214}
215
216/// How far a player got with its media.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub enum PlayerStatus {
219 Loading,
220 /// It can play.
221 Ready,
222 /// It cannot play, from the start or partway through, and does nothing more: Apple's failed
223 /// item and its failure to play to the end, Media3's player error, the web's `error`. It is
224 /// opened again to try again.
225 Failed(PlayerError),
226}
227
228/// What a player is doing: Apple's `timeControlStatus`, Windows' `PlaybackState`.
229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
230pub enum PlayerActivity {
231 /// Not playing, and not trying to; the reason is `None` where the system does not say.
232 Paused(Option<PauseReason>),
233 /// Trying to play, and waiting; the reason is `None` where the system does not say.
234 Waiting(Option<WaitReason>),
235 Playing,
236}
237
238/// Why a player is paused.
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub enum PauseReason {
241 /// The app paused it, or has not played it yet.
242 Requested,
243 /// It reached the end of media it does not loop: Apple's played-to-end, Media3's end of the
244 /// media item, the web's `ended`.
245 End,
246 /// The system took the sound for something else, a call or another app: Apple's audio
247 /// session interruption, Android's audio focus loss.
248 Interrupted,
249 /// The sound's output went, such as headphones unplugged: Android's audio becoming noisy.
250 OutputRemoved,
251 /// The app went to the background, where the system pauses its video: Apple's app
252 /// backgrounded.
253 Backgrounded,
254}
255
256/// Why a player waits to play.
257#[derive(Clone, Copy, Debug, PartialEq, Eq)]
258pub enum WaitReason {
259 /// For media data: Apple's waiting to minimize stalls, Media3's buffering, the web's
260 /// `waiting`, Windows' buffering.
261 Data,
262 /// The system judges whether data comes fast enough to play on, and Apple advises showing
263 /// no waiting yet: Apple's waiting while evaluating the buffering rate.
264 EvaluatingData,
265 /// The system holds it back for a moment: Android's playback suppressed by a short loss of
266 /// audio focus.
267 HeldBySystem,
268}
269
270/// Why a player failed.
271#[derive(Clone, Debug, PartialEq, Eq)]
272pub struct PlayerError {
273 pub kind: PlayerErrorKind,
274 /// The system's own words, for logs: not for showing as they are.
275 pub message: String,
276}
277
278/// The kind of a player's failure, which an app words for its user and acts on: the web's
279/// `MediaError` and Windows' `MediaPlayerError` share the first three, and Apple's `AVError` and
280/// Media3's error codes fall into them.
281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
282pub enum PlayerErrorKind {
283 /// Reaching the media failed: a connection, a timeout, an HTTP error, a file that is not
284 /// there.
285 Network,
286 /// The media is damaged, or decoding it failed.
287 Decode,
288 /// A format or codec the system cannot play.
289 Unsupported,
290 /// The media is protected, and the system may not play it here.
291 Protected,
292 /// The system or the host does not let the player reach the source: a sandbox's rules, a
293 /// file it may not read, a link it may not fetch.
294 Refused,
295 /// Anything else the system reports.
296 Other,
297}
298
299/// A span of a player's media, from `start` to `end`.
300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
301pub struct TimeRange {
302 pub start: Duration,
303 pub end: Duration,
304}
305
306/// How far from its target a seek may land, before and after it, for the system to land
307/// sooner: Apple's tolerances, Media3's `SeekParameters`. A system that seeks only exactly keeps
308/// any tolerance.
309#[derive(Clone, Copy, Debug, PartialEq, Eq)]
310pub struct SeekTolerance {
311 pub before: Duration,
312 pub after: Duration,
313}
314
315impl SeekTolerance {
316 /// Exactly at the target, which may take longer to decode to.
317 pub const EXACT: SeekTolerance = SeekTolerance {
318 before: Duration::ZERO,
319 after: Duration::ZERO,
320 };
321
322 /// Wherever the system lands soonest, such as the nearest keyframe.
323 pub const ANY: SeekTolerance = SeekTolerance {
324 before: Duration::MAX,
325 after: Duration::MAX,
326 };
327}
328
329/// One of a player's media's tracks.
330#[derive(Clone, Debug, PartialEq, Eq)]
331pub struct MediaTrack {
332 /// Names the track for this player's run.
333 pub id: String,
334 pub kind: MediaTrackKind,
335 /// A BCP 47 language tag; empty where the media gives none.
336 pub language: String,
337 /// Its name as the media gives it; empty where it gives none.
338 pub label: String,
339 /// Whether it plays now: one audio track at a time, and one text track or none.
340 pub selected: bool,
341}
342
343/// What a track carries.
344#[derive(Clone, Copy, Debug, PartialEq, Eq)]
345pub enum MediaTrackKind {
346 Audio,
347 Video,
348 /// Subtitles or captions.
349 Text,
350}
351
352/// What a player's media says about itself, from its tags; a field is `None` where it does not
353/// say.
354#[derive(Clone, Debug, Default, PartialEq, Eq)]
355pub struct MediaMetadata {
356 pub title: Option<String>,
357 pub artist: Option<String>,
358 pub album: Option<String>,
359 /// The cover image, encoded as the media holds it.
360 pub artwork: Option<EncodedImage>,
361}
362
363/// An image as its file format encodes it.
364#[derive(Clone, Debug, PartialEq, Eq)]
365pub struct EncodedImage {
366 /// Its format's MIME type, such as `image/jpeg`.
367 pub mime_type: String,
368 /// Shared, so that a player hands the same image out again without copying it.
369 pub data: Arc<[u8]>,
370}
371
372/// The system's reading of media without playing it, or `None` from
373/// [`Platform::media_assets`](crate::Platform::media_assets) where it has none: a library's
374/// lengths, titles and thumbnails before anything plays. Every system has this beside its player:
375/// Apple's `AVAsset` and `AVAssetImageGenerator`, Android's `MediaMetadataRetriever`, Windows'
376/// `MediaClip`.
377pub trait MediaAssets {
378 /// The media at `url`, as a player opens it ([`Players::open`]): a link the system fetches,
379 /// or a picked file's [`PickedFile::url`](crate::PickedFile::url). It reads nothing until
380 /// asked.
381 fn open(&self, url: &str) -> Box<dyn MediaAsset>;
382}
383
384/// One piece of media, read on the app's main thread. Each answer is a future of its own, which
385/// resolves once the system has read what it asks, with a player's failure where the system could
386/// not; dropping the asset leaves each future to resolve.
387pub trait MediaAsset {
388 /// How long it is; `None` for a live stream, as a player's state has none.
389 fn duration(&self) -> MediaAssetFuture<Option<Duration>>;
390
391 /// Its tracks, as a player would list them, `selected` the ones a player would play
392 /// unless asked otherwise.
393 fn tracks(&self) -> MediaAssetFuture<Vec<MediaTrack>>;
394
395 /// What its tags say about it.
396 fn metadata(&self) -> MediaAssetFuture<MediaMetadata>;
397
398 /// Its picture at `time`, or as near it as `tolerance` lets the system land for speed, as a
399 /// seek does, presented as a player presents it, its track's rotation applied, and scaled down
400 /// to fit `max_size`, in pixels, where given.
401 fn frame_at(
402 &self,
403 time: Duration,
404 tolerance: SeekTolerance,
405 max_size: Option<Size>,
406 ) -> MediaAssetFuture<Arc<dyn VideoFrame>>;
407}
408
409/// The system's cameras, or `None` from [`Platform::cameras`](crate::Platform::cameras) where it
410/// has none.
411pub trait Cameras {
412 /// The cameras attached now, in the system's order. Listing asks the user nothing.
413 fn cameras(&self) -> CameraListFuture;
414
415 /// Resolves once [`cameras`](Self::cameras) may answer something else than when this was
416 /// called: a camera plugged in or out, as Apple's discovery session, Android's
417 /// `CameraManager.AvailabilityCallback`, the web's `devicechange` event and Windows'
418 /// `DeviceWatcher` tell it.
419 fn changed(&self) -> MediaChangeFuture;
420
421 /// Opens `camera`, asking the user for the cameras first where the system asks and the user
422 /// has not answered, as an Android app opens Camera2's `CameraDevice` once it holds the
423 /// camera permission: [`CameraError::NotAllowed`] where the user or the system's policy does
424 /// not let the app use them, and [`CameraError::Unplugged`] for a camera no longer attached.
425 fn open(&self, camera: &Camera) -> CameraOpenFuture;
426}
427
428/// A camera, as the system lists it.
429#[derive(Clone, Debug, PartialEq, Eq)]
430pub struct Camera {
431 pub id: CameraId,
432 /// What the system calls it, which the user knows it by.
433 pub name: String,
434 pub facing: CameraFacing,
435}
436
437/// The system's name for a camera, kept while it stays attached.
438#[derive(Clone, Debug, PartialEq, Eq, Hash)]
439pub struct CameraId(pub String);
440
441/// Which way a camera looks.
442#[derive(Clone, Copy, Debug, PartialEq, Eq)]
443pub enum CameraFacing {
444 /// At the user: a phone's selfie camera, a laptop's.
445 Front,
446 /// Away from the user: a phone's main camera.
447 Back,
448 /// A camera the system cannot say of: one plugged in, or on another device.
449 External,
450}
451
452/// A camera the app opened, controlled on the app's main thread: Camera2's `CameraDevice`. A
453/// session started on it runs on after it is dropped.
454pub trait CameraDevice {
455 /// The formats the camera runs in, in the system's order, each with all its outputs: Apple's
456 /// `AVCaptureDevice.formats`, Android's stream configuration map.
457 fn formats(&self) -> Vec<CameraFormat>;
458
459 /// Starts the camera in `format`, one of [`formats`](Self::formats), feeding `outputs`, which
460 /// the system configures together, and answers the session once it runs, or is interrupted,
461 /// from which it resumes by itself. Where the camera already runs for another session and the
462 /// system runs a camera in one format at a time, the session joins that format instead, and
463 /// its [`format`](CaptureSession::format) says so; on Android, which gives a camera one JPEG
464 /// stream, a session that joins takes photos at the size the first session set, or none where
465 /// it set none. It fails for what can happen at any time: the camera in use, unplugged, or not
466 /// allowed; for a format the camera does not list; and, with
467 /// [`CameraError::NotSupported`], for outputs the system cannot feed, such as upright frames
468 /// on Android.
469 fn start(&self, format: &CameraFormat, outputs: CameraOutputs) -> CameraStartFuture;
470}
471
472/// One way a camera runs, with all its outputs.
473#[derive(Clone, Debug, PartialEq)]
474pub struct CameraFormat {
475 /// The size of its frames and its preview, in the camera's own pixels.
476 pub size: Size,
477 /// The slowest frame rate it keeps at that size, in frames a second.
478 pub min_frame_rate: f64,
479 /// The fastest frame rate it keeps at that size, in frames a second.
480 pub max_frame_rate: f64,
481 /// The sizes it takes photos at while it runs so, in pixels.
482 pub photo_sizes: Vec<Size>,
483}
484
485/// What a camera feeds, given whole to [`CameraDevice::start`]: each output the system's own, for
486/// one use. An output left out is not fed.
487#[derive(Clone, Default)]
488pub struct CameraOutputs {
489 /// The layer the preview shows on, drawn by the system into a layer of its own that is this
490 /// layer's content. The session holds it while it runs. A layer no compositor of this host
491 /// made shows nothing.
492 pub preview: Option<Arc<dyn CompositionLayer>>,
493 /// The reader the frames go to, for the app to draw. A reader no [`VideoFrameReaders`] of this
494 /// host made reads nothing.
495 pub frames: Option<Arc<dyn VideoFrameReader>>,
496 /// The size photos are taken at, one of the format's
497 /// [`photo_sizes`](CameraFormat::photo_sizes), each captured, processed and encoded by the
498 /// system. In a joined format that does not list it, photos come at the system's own size
499 /// for that format.
500 pub photos: Option<Size>,
501 /// Recordings, each encoded and written to a file by the system, with sound where `options`
502 /// ask for it, which asks the user for the microphone as the session starts.
503 pub movies: Option<MovieOptions>,
504 /// Whether the frames come turned and mirrored as they show, each reporting a
505 /// [`rotation`](VideoFrame::rotation) of 0 and no [`flip`](VideoFrame::flip), the system
506 /// turning every frame at a cost and keeping them turned at the session's capture angle as
507 /// the device turns: Apple's video data output connection's `videoRotationAngle` and
508 /// `isVideoMirrored`. Only the frames: photos are turned in their EXIF, and the preview by
509 /// the system, either way. A system that cannot turn them fails the start with
510 /// [`CameraError::NotSupported`], as Android's camera does.
511 pub upright_frames: bool,
512}
513
514impl CameraOutputs {
515 /// Outputs that feed nothing.
516 pub fn new() -> CameraOutputs {
517 CameraOutputs::default()
518 }
519
520 pub fn preview(mut self, layer: Arc<dyn CompositionLayer>) -> CameraOutputs {
521 self.preview = Some(layer);
522 self
523 }
524
525 pub fn frames(mut self, reader: Arc<dyn VideoFrameReader>) -> CameraOutputs {
526 self.frames = Some(reader);
527 self
528 }
529
530 pub fn photos(mut self, size: Size) -> CameraOutputs {
531 self.photos = Some(size);
532 self
533 }
534
535 pub fn movies(mut self, options: MovieOptions) -> CameraOutputs {
536 self.movies = Some(options);
537 self
538 }
539
540 pub fn upright_frames(mut self) -> CameraOutputs {
541 self.upright_frames = true;
542 self
543 }
544}
545
546/// A camera running for the app, controlled on the app's main thread. Dropped, it stops for the
547/// app: its preview leaves the layer it showed on, and its reader reads nothing more.
548pub trait CaptureSession {
549 /// The format it runs in: the one picked, unless it joined the format the camera ran in for
550 /// another session.
551 fn format(&self) -> CameraFormat;
552
553 /// The session's state now.
554 fn state(&self) -> CaptureState;
555
556 /// The turn, in degrees clockwise, 0, 90, 180 or 270, that keeps the preview level relative
557 /// to gravity: Apple's `AVCaptureDevice.RotationCoordinator`'s
558 /// `videoRotationAngleForHorizonLevelPreview`. The system's preview on a layer is turned so
559 /// already; an app lays the layer out at the turned size. On Android it is the capture angle.
560 /// WaOS's `capture-session` gives both angles as one record, and a stream of their changes.
561 fn video_rotation_angle_for_horizon_level_preview(&self) -> u32;
562
563 /// The turn, in degrees clockwise, that keeps what is captured level relative to gravity:
564 /// the coordinator's `videoRotationAngleForHorizonLevelCapture`. A photo is taken turned so,
565 /// in its EXIF, and a frame reports what of it its pixels do not carry as its
566 /// [`rotation`](VideoFrame::rotation). It differs from the preview's only while the device
567 /// turns, and on Android never: there both are the sensor's orientation against the
568 /// display's.
569 fn video_rotation_angle_for_horizon_level_capture(&self) -> u32;
570
571 /// Resolves once [`state`](Self::state) or either rotation angle may answer something else
572 /// than when this was called, or once the session is gone.
573 fn changed(&self) -> MediaChangeFuture;
574
575 /// Takes a photo while the session runs with photos among its outputs, answering it once the
576 /// system has encoded it.
577 fn take_photo(&self) -> PhotoFuture;
578
579 /// Records to a new file at `path`, as a QuickTime movie, while the session runs with movies
580 /// among its outputs, until [`stop_recording`](Self::stop_recording); answers once the file is
581 /// written whole, or why it was not.
582 fn start_recording(&self, path: PathBuf) -> RecordingFuture;
583
584 /// Ends the recording, whose future then answers.
585 fn stop_recording(&self);
586}
587
588/// What a camera session is doing.
589#[derive(Clone, Debug, PartialEq, Eq)]
590pub enum CaptureState {
591 Running,
592 /// No frames for now, for this reason where the system gives one; it resumes by itself.
593 /// macOS gives none: Apple marks the interruption's reason unavailable there.
594 Interrupted(Option<CameraInterruption>),
595 /// For good, for this reason.
596 Ended(CameraError),
597}
598
599/// Why a camera session gives no frames for now.
600#[derive(Clone, Copy, Debug, PartialEq, Eq)]
601pub enum CameraInterruption {
602 /// Another app has the camera, as a phone allows one at a time.
603 InUseByAnotherApp,
604 /// The app is in the background.
605 Background,
606 /// The system is too hot or too busy.
607 SystemPressure,
608}
609
610/// Why a camera did not open, start or run.
611#[derive(Clone, Debug, PartialEq, Eq)]
612pub enum CameraError {
613 /// The user did not let the app use the cameras, or the system's policy does not.
614 NotAllowed,
615 /// Another app has the camera, and the system does not share it.
616 InUse,
617 /// The camera is no longer attached.
618 Unplugged,
619 /// The system cannot feed an output asked for, for this reason, such as upright frames on
620 /// Android.
621 NotSupported(String),
622 /// The system failed, for its reason.
623 Failed(String),
624}
625
626impl fmt::Display for CameraError {
627 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628 match self {
629 CameraError::NotAllowed => f.write_str("the app may not use the camera"),
630 CameraError::InUse => f.write_str("another app has the camera"),
631 CameraError::Unplugged => f.write_str("the camera is no longer attached"),
632 CameraError::NotSupported(reason) => write!(f, "the system cannot: {reason}"),
633 CameraError::Failed(reason) => write!(f, "the camera failed: {reason}"),
634 }
635 }
636}
637
638impl std::error::Error for CameraError {}
639
640/// A photo, as the system encoded it.
641#[derive(Clone, Debug, PartialEq, Eq)]
642pub struct Photo {
643 pub bytes: Vec<u8>,
644 /// The encoding's MIME type: `image/jpeg`.
645 pub mime_type: String,
646}
647
648/// What a recording asks for beyond the picture.
649#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
650pub struct MovieOptions {
651 /// Whether it records sound from the system's microphone.
652 pub sound: bool,
653}
654
655/// The system's frame readers, or `None` from
656/// [`Platform::video_frame_readers`](crate::Platform::video_frame_readers) where it hands out no
657/// frames.
658pub trait VideoFrameReaders {
659 /// A reader fed by nothing yet, which reads the frames of the source it is given to: a
660 /// player's [`set_video_output`](MediaPlayer::set_video_output), a camera's outputs
661 /// ([`CameraOutputs::frames`]). The reader goes when its last handle does: the app's, and its
662 /// source's.
663 fn make_reader(&self) -> Arc<dyn VideoFrameReader>;
664}
665
666/// The pictures of the one source a reader is given to, read from any thread as they are drawn.
667/// It takes one source at a time, as Android's `ImageReader` takes one producer: given to a second
668/// while the first still feeds it, it is refused, and the second sends its frames nowhere. A
669/// reader keeps no frame for later: one not read before the next arrives is dropped.
670///
671/// A host gets its own type back from a reader it is given by downcasting through `Any`.
672pub trait VideoFrameReader: Any + Send + Sync {
673 /// The frame to show at `display_time`, the moment the picture being drawn reaches the
674 /// screen: a player's frame for that moment of the video, as a display link asks
675 /// AVFoundation's video output for each refresh's target time, and a camera's newest. `None`
676 /// when it is the frame handed out last, or none came.
677 fn frame_for(&self, display_time: Instant) -> Option<Arc<dyn VideoFrame>>;
678}
679
680/// One picture of a video as the system hands it out, as WebCodecs' `VideoFrame`: lent with its
681/// slot in the decoder's pool, which it holds until it, its hardware buffer and every texture
682/// imported of the buffer are dropped. Its memory is a [`HardwareBuffer`](crate::HardwareBuffer),
683/// GPU memory the system's compositor reaches too, which the app draws through a texture it
684/// imports ([`Platform::import_texture`](crate::Platform::import_texture)), the hardware codecs
685/// encode and a composition layer shows; memory the app holds of its own, which no pool waits for,
686/// is a buffer it allocates ([`HardwareBufferAllocator`](crate::HardwareBufferAllocator)) or an
687/// image the hardware codecs decoded.
688///
689/// Each host implements it over the frames its system hands out. Platform code reaches the
690/// system's own frame by downcasting through `Any` to the type of the host that handed it out:
691/// on Apple's systems `waft-embedder-winit`'s `CoreVideoFrame`, whose `pixel_buffer` is the
692/// `CVPixelBuffer` AVFoundation handed out.
693pub trait VideoFrame: Any + Send + Sync {
694 /// The picture's width, in its own pixels.
695 fn width(&self) -> u32;
696
697 /// The picture's height, in its own pixels.
698 fn height(&self) -> u32;
699
700 /// The frame's pixels copied into the app's memory, in the layout the frame holds them: BGRA
701 /// on Apple's systems. The one way back from GPU memory to the app's;
702 /// [`ImageErrorKind::Unsupported`](crate::image_codecs::ImageErrorKind::Unsupported) for a
703 /// frame whose pixels are in no [`PixelFormat`](crate::image_codecs::PixelFormat), as a
704 /// decoder's planes ([`HardwareBufferFormat::Nv12`](crate::HardwareBufferFormat::Nv12) and
705 /// `P010`) are.
706 fn read_pixels(&self) -> ImageFuture<PixelBuffer>;
707
708 /// The frame's memory, for sampling, which keeps the frame, and its slot in the pool, while
709 /// it and every texture imported of it are held: what the app draws through a texture it
710 /// imports, the hardware codecs encode and a composition layer shows.
711 fn hardware_buffer(&self) -> Arc<dyn crate::HardwareBuffer>;
712
713 /// The rotation applied to the frame when it is shown, in degrees clockwise: 0, 90, 180 or
714 /// 270, as WebCodecs' `VideoFrame.rotation`. It applies before [`flip`](Self::flip). The
715 /// pixels are not turned: [`width`](Self::width) and [`height`](Self::height) are the
716 /// frame's own, so a frame turned a quarter shows `height` wide. A camera's frame on a phone
717 /// is turned so, unless its session asked for upright frames.
718 fn rotation(&self) -> u32;
719
720 /// Whether the frame is flipped horizontally when it is shown, after
721 /// [`rotation`](Self::rotation), as WebCodecs' `VideoFrame.flip`: a camera that looks at its
722 /// user, shown as a mirror.
723 fn flip(&self) -> bool;
724
725 /// When the picture is shown, in nanoseconds on its stream's own timeline: for a decoder's
726 /// frame, the timestamp of the chunk it came from. `None` for a frame whose source gives
727 /// none, as a reader's, which comes for a display time.
728 fn timestamp(&self) -> Option<i64> {
729 None
730 }
731
732 /// How long the picture is shown, where its source says.
733 fn duration(&self) -> Option<Duration> {
734 None
735 }
736
737 /// The part of the frame's memory that is picture, in its own pixels and before
738 /// [`rotation`](Self::rotation). A decoder pads a picture to its blocks' size, so the memory
739 /// may be larger than the picture: 1920 by 1088 for a picture of 1920 by 1080. All of it,
740 /// for a frame whose source pads nothing.
741 fn visible_rect(&self) -> PixelRect {
742 PixelRect {
743 x: 0,
744 y: 0,
745 width: self.width(),
746 height: self.height(),
747 }
748 }
749
750 /// The shape of one pixel, width to height: 1 to 1 unless the video is anamorphic.
751 fn pixel_aspect(&self) -> PixelAspect {
752 PixelAspect {
753 width: 1,
754 height: 1,
755 }
756 }
757
758 /// What the samples mean as colour. A frame that says nothing more is red, green and blue
759 /// over its whole range, as a reader's is.
760 fn color(&self) -> VideoColor {
761 VideoColor {
762 primaries: None,
763 transfer: None,
764 matrix: Some(VideoColor::RGB_MATRIX),
765 range: Some(ColorRange::Full),
766 chroma_location: None,
767 }
768 }
769
770 /// The brightness the picture was mastered for, where its stream says: what a display needs
771 /// to show an HDR picture.
772 fn hdr_metadata(&self) -> Option<HdrMetadata> {
773 None
774 }
775}
776
777/// A rectangle of a frame's pixels, from its top-left corner.
778#[derive(Clone, Copy, Debug, PartialEq, Eq)]
779pub struct PixelRect {
780 pub x: u32,
781 pub y: u32,
782 pub width: u32,
783 pub height: u32,
784}
785
786/// The shape of one pixel: `width` to `height`.
787#[derive(Clone, Copy, Debug, PartialEq, Eq)]
788pub struct PixelAspect {
789 pub width: u32,
790 pub height: u32,
791}
792
793/// What a frame's samples mean as colour, as its stream says it: the code points of ITU-T
794/// H.273, which every codec and every system's frame carry. `None` of a value where neither the
795/// stream nor the app said.
796#[derive(Clone, Copy, Debug, PartialEq, Eq)]
797pub struct VideoColor {
798 /// Which red, green and blue: 1 is BT.709, 9 BT.2020, 12 Display P3.
799 pub primaries: Option<u8>,
800 /// How samples encode brightness: 1 is BT.709, 13 sRGB, 16 PQ, 18 HLG.
801 pub transfer: Option<u8>,
802 /// How brightness and colour mix into red, green and blue: 1 is BT.709, 6 BT.601, 9
803 /// BT.2020, 0 none.
804 pub matrix: Option<u8>,
805 pub range: Option<ColorRange>,
806 pub chroma_location: Option<ChromaLocation>,
807}
808
809impl VideoColor {
810 /// The matrix of samples that are red, green and blue already.
811 pub const RGB_MATRIX: u8 = 0;
812}
813
814/// How much of a sample's range the picture uses.
815#[derive(Clone, Copy, Debug, PartialEq, Eq)]
816pub enum ColorRange {
817 /// Video's range: 16 to 235 of 8 bits for brightness.
818 Limited,
819 /// All of it.
820 Full,
821}
822
823/// Where a half-size colour plane's samples sit against the brightness plane's.
824#[derive(Clone, Copy, Debug, PartialEq, Eq)]
825pub struct ChromaLocation {
826 pub horizontal: ChromaAlignment,
827 pub vertical: ChromaAlignment,
828}
829
830#[derive(Clone, Copy, Debug, PartialEq, Eq)]
831pub enum ChromaAlignment {
832 /// On the first of the brightness samples it covers.
833 Cosited,
834 /// Midway between them.
835 Centered,
836}
837
838/// The brightness a picture was mastered for.
839#[derive(Clone, Copy, Debug, PartialEq)]
840pub struct HdrMetadata {
841 /// The display it was mastered on (SMPTE ST 2086).
842 pub mastering_display: Option<MasteringDisplay>,
843 /// How bright its content gets (CTA-861.3).
844 pub content_light: Option<ContentLight>,
845}
846
847#[derive(Clone, Copy, Debug, PartialEq)]
848pub struct MasteringDisplay {
849 pub red: Chromaticity,
850 pub green: Chromaticity,
851 pub blue: Chromaticity,
852 pub white: Chromaticity,
853 /// In candelas a square metre.
854 pub max_luminance: f32,
855 pub min_luminance: f32,
856}
857
858/// A colour's place on the CIE 1931 diagram.
859#[derive(Clone, Copy, Debug, PartialEq)]
860pub struct Chromaticity {
861 pub x: f32,
862 pub y: f32,
863}
864
865/// In candelas a square metre.
866#[derive(Clone, Copy, Debug, PartialEq, Eq)]
867pub struct ContentLight {
868 /// The brightest sample of the whole video.
869 pub max: u32,
870 /// The brightest picture's average.
871 pub max_frame_average: u32,
872}
873
874/// Why a camera session's photo or recording answered nothing.
875#[derive(Clone, Debug, PartialEq, Eq)]
876pub enum MediaError {
877 /// The session is interrupted or ended.
878 NotRunning,
879 /// The system failed, for its reason.
880 Failed(String),
881}
882
883impl fmt::Display for MediaError {
884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885 match self {
886 MediaError::NotRunning => f.write_str("the camera session does not run"),
887 MediaError::Failed(reason) => write!(f, "the camera failed: {reason}"),
888 }
889 }
890}
891
892impl std::error::Error for MediaError {}
893
894/// What a player's, a session's, the cameras' or the caption settings' `changed` answers.
895pub type MediaChangeFuture = Pin<Box<dyn Future<Output = ()>>>;
896/// What reading a media asset answers.
897pub type MediaAssetFuture<T> = Pin<Box<dyn Future<Output = Result<T, PlayerError>>>>;
898/// What listing the cameras answers.
899pub type CameraListFuture = Pin<Box<dyn Future<Output = Vec<Camera>>>>;
900/// What opening a camera answers.
901pub type CameraOpenFuture =
902 Pin<Box<dyn Future<Output = Result<Box<dyn CameraDevice>, CameraError>>>>;
903/// What starting a camera answers.
904pub type CameraStartFuture =
905 Pin<Box<dyn Future<Output = Result<Box<dyn CaptureSession>, CameraError>>>>;
906/// What taking a photo answers.
907pub type PhotoFuture = Pin<Box<dyn Future<Output = Result<Photo, MediaError>>>>;
908/// What a recording answers once it ends.
909pub type RecordingFuture = Pin<Box<dyn Future<Output = Result<(), MediaError>>>>;