Skip to main content

waft_test/
media.rs

1//! A compositor, frame readers, players, media assets and cameras in memory, as a host shows
2//! nothing: each keeps what the app asked of it or gave it, and reports the state the test gives
3//! it, a player its position, metadata and cues too, an asset what it reads, and the cameras their
4//! list.
5
6use std::cell::{Cell, RefCell};
7use std::future::Future;
8use std::path::PathBuf;
9use std::pin::Pin;
10use std::rc::Rc;
11use std::sync::atomic::{AtomicUsize, Ordering};
12use std::sync::{Arc, Mutex};
13use std::task::{Context, Poll, Waker};
14use std::time::Duration;
15
16use waft_embedder::image_codecs::{
17    ImageError, ImageErrorKind, ImageFuture, PixelBuffer, PixelFormat,
18};
19use waft_embedder::{
20    AcceptedBuffers, Camera, CameraDevice, CameraError, CameraFormat, CameraListFuture,
21    CameraOpenFuture, CameraOutputs, CameraStartFuture, Cameras, CaptureSession, CaptureState,
22    CompositionLayer, Compositor, Cue, HardwareBuffer, HardwareBufferFormat, LayerPicture,
23    MediaAsset, MediaAssetFuture, MediaAssets, MediaChangeFuture, MediaError, MediaMetadata,
24    MediaPlayer, MediaTrack, MovieOptions, Photo, PhotoFuture, Placement, PlayerError, PlayerState,
25    Players, RecordingFuture, SeekTolerance, Size, VideoFrame, VideoFrameReader, VideoFrameReaders,
26    VideoOutput,
27};
28
29use crate::MockHardwareBuffer;
30use crate::hardware_buffers::SYSTEM_GIVEN;
31use crate::image_codecs::pixels_of;
32
33/// A compositor whose layers show nowhere and keep what they show now ([`MockLayer`]), kept in
34/// the order made. It accepts the buffers the test gives it, none unless told. Every clone is the
35/// same compositor.
36#[derive(Clone, Default)]
37pub struct MockCompositor {
38    made: Arc<Mutex<Vec<Arc<MockLayer>>>>,
39    accepted: AcceptedBuffers,
40}
41
42impl MockCompositor {
43    pub fn new() -> MockCompositor {
44        MockCompositor::default()
45    }
46
47    /// A compositor that answers `accepted` for the buffers it shows.
48    pub fn accepting(accepted: AcceptedBuffers) -> MockCompositor {
49        MockCompositor {
50            accepted,
51            ..MockCompositor::default()
52        }
53    }
54
55    /// The layers the app made, in order.
56    pub fn made(&self) -> Vec<Arc<MockLayer>> {
57        self.made.lock().expect("never held across a panic").clone()
58    }
59}
60
61impl Compositor for MockCompositor {
62    fn make_layer(&self, opaque: bool) -> Arc<dyn CompositionLayer> {
63        let layer = Arc::new(MockLayer::new(opaque));
64        self.made
65            .lock()
66            .expect("never held across a panic")
67            .push(Arc::clone(&layer));
68        layer
69    }
70
71    fn accepted_buffers(&self) -> AcceptedBuffers {
72        self.accepted.clone()
73    }
74}
75
76/// A layer that shows nothing, and keeps what it shows now: the buffer presented last, as its
77/// [`current_picture`](CompositionLayer::current_picture), and the layers placed under it then;
78/// and how many pictures it was handed. Presents release their buffers at once.
79pub struct MockLayer {
80    opaque: bool,
81    shown: Mutex<Option<Shown>>,
82    presents: AtomicUsize,
83}
84
85/// What a layer shows: its buffer, and the layers under it, each where it is placed.
86type Shown = (
87    Arc<dyn HardwareBuffer>,
88    Vec<(Arc<dyn CompositionLayer>, Placement)>,
89);
90
91impl MockLayer {
92    /// A layer that has shown nothing yet.
93    pub fn new(opaque: bool) -> MockLayer {
94        MockLayer {
95            opaque,
96            shown: Mutex::default(),
97            presents: AtomicUsize::new(0),
98        }
99    }
100
101    /// Whether the layer was made opaque.
102    pub fn opaque(&self) -> bool {
103        self.opaque
104    }
105
106    /// The layers placed under the picture the layer shows now, the bottom-most first, each where
107    /// it is placed; none before its first picture.
108    pub fn children(&self) -> Vec<(Arc<dyn CompositionLayer>, Placement)> {
109        self.shown
110            .lock()
111            .expect("never held across a panic")
112            .as_ref()
113            .map(|(_, children)| children.clone())
114            .unwrap_or_default()
115    }
116
117    /// How many pictures the layer was handed.
118    pub fn presents(&self) -> usize {
119        self.presents.load(Ordering::SeqCst)
120    }
121
122    /// The [`MockLayer`] a layer [`MockCompositor`] made is.
123    pub fn of(layer: &dyn CompositionLayer) -> Option<&MockLayer> {
124        (layer as &dyn std::any::Any).downcast_ref::<MockLayer>()
125    }
126}
127
128impl CompositionLayer for MockLayer {
129    fn present(
130        &self,
131        buffer: Arc<dyn HardwareBuffer>,
132        children: Vec<(Arc<dyn CompositionLayer>, Placement)>,
133        released: Box<dyn FnOnce() + Send + Sync>,
134    ) {
135        *self.shown.lock().expect("never held across a panic") = Some((buffer, children));
136        self.presents.fetch_add(1, Ordering::SeqCst);
137        released();
138    }
139
140    fn current_picture(&self) -> Option<LayerPicture> {
141        self.shown
142            .lock()
143            .expect("never held across a panic")
144            .as_ref()
145            .map(|(buffer, _)| LayerPicture::Buffer(Arc::clone(buffer)))
146    }
147}
148
149/// Frame readers that never have a frame, and which keep each reader made. Every clone is the
150/// same readers.
151#[derive(Clone, Default)]
152pub struct MockVideoFrameReaders(Rc<RefCell<Vec<Arc<dyn VideoFrameReader>>>>);
153
154impl MockVideoFrameReaders {
155    pub fn new() -> MockVideoFrameReaders {
156        MockVideoFrameReaders::default()
157    }
158
159    /// The readers made, in order.
160    pub fn made(&self) -> Vec<Arc<dyn VideoFrameReader>> {
161        self.0.borrow().clone()
162    }
163}
164
165impl VideoFrameReaders for MockVideoFrameReaders {
166    fn make_reader(&self) -> Arc<dyn VideoFrameReader> {
167        let reader: Arc<dyn VideoFrameReader> = Arc::new(NoFrames);
168        self.0.borrow_mut().push(Arc::clone(&reader));
169        reader
170    }
171}
172
173/// Players that keep each player opened, which reports the state, position, metadata and cues
174/// the test gives it. Every clone is the same players.
175#[derive(Clone, Default)]
176pub struct MockPlayers(Rc<RefCell<Vec<MockPlayer>>>);
177
178impl MockPlayers {
179    pub fn new() -> MockPlayers {
180        MockPlayers::default()
181    }
182
183    /// The players opened, in order.
184    pub fn opened(&self) -> Vec<MockPlayer> {
185        self.0.borrow().clone()
186    }
187}
188
189impl Players for MockPlayers {
190    fn open(&self, url: &str) -> Box<dyn MediaPlayer> {
191        let player = MockPlayer(Rc::new(PlayerShared {
192            url: url.to_owned(),
193            state: RefCell::new(PlayerState::loading()),
194            position: Cell::new(Duration::ZERO),
195            metadata: RefCell::default(),
196            cues: RefCell::default(),
197            calls: RefCell::default(),
198            video_output: RefCell::default(),
199            changes: Changes::default(),
200            dropped: Cell::new(false),
201        }));
202        self.0.borrow_mut().push(player.clone());
203        Box::new(OpenedPlayer(player))
204    }
205}
206
207/// What a player was asked to do.
208#[derive(Clone, Debug, PartialEq)]
209pub enum PlayerCall {
210    Play,
211    Pause,
212    Seek(Duration, SeekTolerance),
213    SetRate(f64),
214    SetVolume(f64),
215    SetMuted(bool),
216    SetLooping(bool),
217    /// What kind of output was given, or none.
218    SetVideoOutput(Option<VideoOutputKind>),
219    SelectAudioTrack(String),
220    SelectTextTrack(Option<String>),
221}
222
223/// The kind of a [`VideoOutput`], which a [`PlayerCall`] records.
224#[derive(Clone, Copy, Debug, PartialEq, Eq)]
225pub enum VideoOutputKind {
226    Layer,
227    Frames,
228}
229
230impl VideoOutputKind {
231    fn of(output: &VideoOutput) -> VideoOutputKind {
232        match output {
233            VideoOutput::Layer(_) => VideoOutputKind::Layer,
234            VideoOutput::Frames(_) => VideoOutputKind::Frames,
235        }
236    }
237}
238
239/// A player the app opened, as the test sees it. Every clone is the same player.
240#[derive(Clone)]
241pub struct MockPlayer(Rc<PlayerShared>);
242
243struct PlayerShared {
244    url: String,
245    state: RefCell<PlayerState>,
246    position: Cell<Duration>,
247    metadata: RefCell<MediaMetadata>,
248    cues: RefCell<Vec<Cue>>,
249    calls: RefCell<Vec<PlayerCall>>,
250    video_output: RefCell<Option<VideoOutput>>,
251    changes: Changes,
252    dropped: Cell<bool>,
253}
254
255impl MockPlayer {
256    /// The URL the player was opened from.
257    pub fn url(&self) -> String {
258        self.0.url.clone()
259    }
260
261    /// What the player was asked, in order.
262    pub fn calls(&self) -> Vec<PlayerCall> {
263        self.0.calls.borrow().clone()
264    }
265
266    /// The layer the player's picture is on; `None` once it is sent nowhere, or to a frame
267    /// reader.
268    pub fn video_layer(&self) -> Option<Arc<dyn CompositionLayer>> {
269        match &*self.0.video_output.borrow() {
270            Some(VideoOutput::Layer(layer)) => Some(Arc::clone(layer)),
271            _ => None,
272        }
273    }
274
275    /// The reader the player's frames go to; `None` once its picture is sent nowhere, or to a
276    /// layer.
277    pub fn frame_reader(&self) -> Option<Arc<dyn VideoFrameReader>> {
278        match &*self.0.video_output.borrow() {
279            Some(VideoOutput::Frames(reader)) => Some(Arc::clone(reader)),
280            _ => None,
281        }
282    }
283
284    /// Whether the app let go of the player.
285    pub fn is_dropped(&self) -> bool {
286        self.0.dropped.get()
287    }
288
289    /// Reports `state` from now on, as the system would have changed it.
290    pub fn set_state(&self, state: PlayerState) {
291        *self.0.state.borrow_mut() = state;
292        self.0.changes.notify();
293    }
294
295    /// Answers `position` from now on, telling the app nothing, as a playing player moves on.
296    pub fn move_to(&self, position: Duration) {
297        self.0.position.set(position);
298    }
299
300    /// Answers `position` from now on, telling the app it jumped, as a seek landing or a loop
301    /// does.
302    pub fn jump_to(&self, position: Duration) {
303        self.0.position.set(position);
304        self.0.changes.notify();
305    }
306
307    /// Reports `metadata` from now on, as the system would have read it from the media.
308    pub fn set_metadata(&self, metadata: MediaMetadata) {
309        *self.0.metadata.borrow_mut() = metadata;
310        self.0.changes.notify();
311    }
312
313    /// Reports `cues` from now on, as the system would have reached them in the text track.
314    pub fn set_cues(&self, cues: Vec<Cue>) {
315        *self.0.cues.borrow_mut() = cues;
316        self.0.changes.notify();
317    }
318
319    fn call(&self, call: PlayerCall) {
320        self.0.calls.borrow_mut().push(call);
321    }
322}
323
324/// The player the app holds; dropping it ends the player's changes.
325struct OpenedPlayer(MockPlayer);
326
327impl MediaPlayer for OpenedPlayer {
328    fn play(&self) {
329        self.0.call(PlayerCall::Play);
330    }
331
332    fn pause(&self) {
333        self.0.call(PlayerCall::Pause);
334    }
335
336    fn seek(&self, position: Duration, tolerance: SeekTolerance) {
337        self.0.call(PlayerCall::Seek(position, tolerance));
338    }
339
340    fn set_rate(&self, rate: f64) {
341        self.0.call(PlayerCall::SetRate(rate));
342    }
343
344    fn set_volume(&self, volume: f64) {
345        self.0.call(PlayerCall::SetVolume(volume));
346    }
347
348    fn set_muted(&self, muted: bool) {
349        self.0.call(PlayerCall::SetMuted(muted));
350    }
351
352    fn set_looping(&self, looping: bool) {
353        self.0.call(PlayerCall::SetLooping(looping));
354    }
355
356    fn state(&self) -> PlayerState {
357        self.0.0.state.borrow().clone()
358    }
359
360    fn position(&self) -> Duration {
361        self.0.0.position.get()
362    }
363
364    fn changed(&self) -> MediaChangeFuture {
365        self.0.0.changes.next()
366    }
367
368    fn set_video_output(&self, output: Option<VideoOutput>) {
369        self.0.call(PlayerCall::SetVideoOutput(
370            output.as_ref().map(VideoOutputKind::of),
371        ));
372        *self.0.0.video_output.borrow_mut() = output;
373    }
374
375    fn select_audio_track(&self, id: &str) {
376        self.0.call(PlayerCall::SelectAudioTrack(id.to_owned()));
377    }
378
379    fn select_text_track(&self, id: Option<&str>) {
380        self.0
381            .call(PlayerCall::SelectTextTrack(id.map(str::to_owned)));
382    }
383
384    fn metadata(&self) -> MediaMetadata {
385        self.0.0.metadata.borrow().clone()
386    }
387
388    fn cues(&self) -> Vec<Cue> {
389        self.0.0.cues.borrow().clone()
390    }
391}
392
393impl Drop for OpenedPlayer {
394    fn drop(&mut self) {
395        self.0.0.dropped.set(true);
396        self.0.0.changes.end();
397    }
398}
399
400/// Media assets that each answer what the test set, at once, and keep each asset opened with the
401/// pictures asked of it. Every clone is the same assets.
402#[derive(Clone)]
403pub struct MockMediaAssets(Rc<AssetsShared>);
404
405struct AssetsShared {
406    answers: RefCell<AssetAnswers>,
407    opened: RefCell<Vec<MockMediaAsset>>,
408}
409
410/// What every asset answers: its length, `None` for a live stream, its tracks, its tags, and the
411/// size of its pictures, each or a failure.
412#[derive(Clone, Debug, PartialEq)]
413pub struct AssetAnswers {
414    pub duration: Result<Option<Duration>, PlayerError>,
415    pub tracks: Result<Vec<MediaTrack>, PlayerError>,
416    pub metadata: Result<MediaMetadata, PlayerError>,
417    /// The size of each picture, which answers a [`MockVideoFrame`] of it.
418    pub frame_size: Result<Size, PlayerError>,
419}
420
421impl MockMediaAssets {
422    /// Assets that each answer `answers`.
423    pub fn new(answers: AssetAnswers) -> MockMediaAssets {
424        MockMediaAssets(Rc::new(AssetsShared {
425            answers: RefCell::new(answers),
426            opened: RefCell::default(),
427        }))
428    }
429
430    /// Each asset answers `answers` from now on.
431    pub fn set_answers(&self, answers: AssetAnswers) {
432        *self.0.answers.borrow_mut() = answers;
433    }
434
435    /// The assets opened, in order.
436    pub fn opened(&self) -> Vec<MockMediaAsset> {
437        self.0.opened.borrow().clone()
438    }
439}
440
441impl MediaAssets for MockMediaAssets {
442    fn open(&self, url: &str) -> Box<dyn MediaAsset> {
443        let asset = MockMediaAsset(Rc::new(AssetShared {
444            url: url.to_owned(),
445            frames_asked: RefCell::default(),
446            dropped: Cell::new(false),
447        }));
448        self.0.opened.borrow_mut().push(asset.clone());
449        Box::new(OpenedAsset {
450            assets: self.clone(),
451            asset,
452        })
453    }
454}
455
456/// An asset the app opened, as the test sees it. Every clone is the same asset.
457#[derive(Clone)]
458pub struct MockMediaAsset(Rc<AssetShared>);
459
460struct AssetShared {
461    url: String,
462    frames_asked: RefCell<Vec<FrameAsked>>,
463    dropped: Cell<bool>,
464}
465
466/// A picture the app asked an asset for.
467#[derive(Clone, Copy, Debug, PartialEq)]
468pub struct FrameAsked {
469    pub time: Duration,
470    pub tolerance: SeekTolerance,
471    pub max_size: Option<Size>,
472}
473
474impl MockMediaAsset {
475    /// The URL the asset was opened from.
476    pub fn url(&self) -> String {
477        self.0.url.clone()
478    }
479
480    /// The pictures asked of it, in order.
481    pub fn frames_asked(&self) -> Vec<FrameAsked> {
482        self.0.frames_asked.borrow().clone()
483    }
484
485    /// Whether the app let go of the asset.
486    pub fn is_dropped(&self) -> bool {
487        self.0.dropped.get()
488    }
489}
490
491/// The asset the app holds.
492struct OpenedAsset {
493    assets: MockMediaAssets,
494    asset: MockMediaAsset,
495}
496
497impl OpenedAsset {
498    fn answers(&self) -> AssetAnswers {
499        self.assets.0.answers.borrow().clone()
500    }
501}
502
503impl MediaAsset for OpenedAsset {
504    fn duration(&self) -> MediaAssetFuture<Option<Duration>> {
505        Box::pin(std::future::ready(self.answers().duration))
506    }
507
508    fn tracks(&self) -> MediaAssetFuture<Vec<MediaTrack>> {
509        Box::pin(std::future::ready(self.answers().tracks))
510    }
511
512    fn metadata(&self) -> MediaAssetFuture<MediaMetadata> {
513        Box::pin(std::future::ready(self.answers().metadata))
514    }
515
516    fn frame_at(
517        &self,
518        time: Duration,
519        tolerance: SeekTolerance,
520        max_size: Option<Size>,
521    ) -> MediaAssetFuture<Arc<dyn VideoFrame>> {
522        self.asset.0.frames_asked.borrow_mut().push(FrameAsked {
523            time,
524            tolerance,
525            max_size,
526        });
527        let frame = self.answers().frame_size.map(|size| {
528            Arc::new(MockVideoFrame {
529                width: size.width() as u32,
530                height: size.height() as u32,
531                rotation: 0,
532                flip: false,
533            }) as Arc<dyn VideoFrame>
534        });
535        Box::pin(std::future::ready(frame))
536    }
537}
538
539impl Drop for OpenedAsset {
540    fn drop(&mut self) {
541        self.asset.0.dropped.set(true);
542    }
543}
544
545/// A picture of a size, with no pixels on any GPU: its buffer is imported as no texture, as a
546/// frame a device cannot take, which a drawing skips, and its pixels read back opaque black, in
547/// BGRA as Apple's frames are.
548#[derive(Clone, Copy, Debug, PartialEq, Eq)]
549pub struct MockVideoFrame {
550    pub width: u32,
551    pub height: u32,
552    /// What it reports as its `rotation` and `flip`.
553    pub rotation: u32,
554    pub flip: bool,
555}
556
557impl VideoFrame for MockVideoFrame {
558    fn width(&self) -> u32 {
559        self.width
560    }
561
562    fn height(&self) -> u32 {
563        self.height
564    }
565
566    fn read_pixels(&self) -> ImageFuture<PixelBuffer> {
567        let read = if self.width == 0 || self.height == 0 {
568            Err(ImageError::new(
569                ImageErrorKind::Other,
570                "a frame with no pixels",
571            ))
572        } else {
573            Ok(pixels_of(
574                [self.width, self.height],
575                [0, 0, 0, 255],
576                PixelFormat::Bgra8,
577            ))
578        };
579        Box::pin(std::future::ready(read))
580    }
581
582    fn rotation(&self) -> u32 {
583        self.rotation
584    }
585
586    fn flip(&self) -> bool {
587        self.flip
588    }
589
590    /// A [`MockHardwareBuffer`] of its size, for what a frame's is ([`SYSTEM_GIVEN`]).
591    fn hardware_buffer(&self) -> Arc<dyn HardwareBuffer> {
592        Arc::new(MockHardwareBuffer {
593            width: self.width,
594            height: self.height,
595            format: HardwareBufferFormat::Bgra8,
596            usage: SYSTEM_GIVEN,
597        })
598    }
599}
600
601/// Cameras that list what the test gave, telling the app each time the test changes the list,
602/// each running in the formats the test gave, and keep each session started, which reports the
603/// state the test gives it. A session started on a camera another session still runs joins that
604/// one's format, as a system that runs a camera in one format at a time does. Every clone is the
605/// same cameras.
606#[derive(Clone, Default)]
607pub struct MockCameras(Rc<CamerasShared>);
608
609#[derive(Default)]
610struct CamerasShared {
611    cameras: RefCell<Vec<Camera>>,
612    changes: Changes,
613    formats: RefCell<Vec<CameraFormat>>,
614    /// Whether the user does not let the app use the cameras.
615    denied: Cell<bool>,
616    sessions: RefCell<Vec<MockCaptureSession>>,
617}
618
619impl MockCameras {
620    /// Cameras listing `cameras`, which run in no format until [`with_formats`](Self::with_formats).
621    pub fn new(cameras: Vec<Camera>) -> MockCameras {
622        MockCameras(Rc::new(CamerasShared {
623            cameras: RefCell::new(cameras),
624            ..CamerasShared::default()
625        }))
626    }
627
628    /// Lists `cameras` from now on, as the system would once a camera was plugged in or out.
629    pub fn set_cameras(&self, cameras: Vec<Camera>) {
630        *self.0.cameras.borrow_mut() = cameras;
631        self.0.changes.notify();
632    }
633
634    /// Each camera runs in `formats`.
635    pub fn with_formats(self, formats: Vec<CameraFormat>) -> MockCameras {
636        *self.0.formats.borrow_mut() = formats;
637        self
638    }
639
640    /// The user does not let the app use the cameras: opening one fails.
641    pub fn denying(self) -> MockCameras {
642        self.0.denied.set(true);
643        self
644    }
645
646    /// The sessions started, in order.
647    pub fn sessions(&self) -> Vec<MockCaptureSession> {
648        self.0.sessions.borrow().clone()
649    }
650
651    /// The format a session still running `camera` runs it in.
652    fn running_format(&self, camera: &Camera) -> Option<CameraFormat> {
653        self.0
654            .sessions
655            .borrow()
656            .iter()
657            .find(|session| session.camera() == *camera && !session.is_dropped())
658            .map(MockCaptureSession::format)
659    }
660}
661
662impl Cameras for MockCameras {
663    fn cameras(&self) -> CameraListFuture {
664        Box::pin(std::future::ready(self.0.cameras.borrow().clone()))
665    }
666
667    fn changed(&self) -> MediaChangeFuture {
668        self.0.changes.next()
669    }
670
671    fn open(&self, camera: &Camera) -> CameraOpenFuture {
672        let opened: Result<Box<dyn CameraDevice>, CameraError> = if self.0.denied.get() {
673            Err(CameraError::NotAllowed)
674        } else {
675            Ok(Box::new(OpenedCamera {
676                cameras: self.clone(),
677                camera: camera.clone(),
678            }))
679        };
680        Box::pin(std::future::ready(opened))
681    }
682}
683
684/// A camera the app opened.
685struct OpenedCamera {
686    cameras: MockCameras,
687    camera: Camera,
688}
689
690impl CameraDevice for OpenedCamera {
691    fn formats(&self) -> Vec<CameraFormat> {
692        self.cameras.0.formats.borrow().clone()
693    }
694
695    /// Answers at once: the session runs as it starts.
696    fn start(&self, format: &CameraFormat, outputs: CameraOutputs) -> CameraStartFuture {
697        Box::pin(std::future::ready(self.started(format, outputs)))
698    }
699}
700
701impl OpenedCamera {
702    fn started(
703        &self,
704        format: &CameraFormat,
705        outputs: CameraOutputs,
706    ) -> Result<Box<dyn CaptureSession>, CameraError> {
707        if !self.cameras.0.formats.borrow().contains(format) {
708            return Err(CameraError::Failed(
709                "the camera does not list this format".to_owned(),
710            ));
711        }
712        let running = self.cameras.running_format(&self.camera);
713        let session = MockCaptureSession(Rc::new(SessionShared {
714            camera: self.camera.clone(),
715            picked: format.clone(),
716            format: running.unwrap_or_else(|| format.clone()),
717            outputs,
718            state: RefCell::new(CaptureState::Running),
719            angles: Cell::new([0, 0]),
720            photo: RefCell::default(),
721            recordings: RefCell::default(),
722            recording: RefCell::default(),
723            changes: Changes::default(),
724            dropped: Cell::new(false),
725        }));
726        self.cameras.0.sessions.borrow_mut().push(session.clone());
727        Ok(Box::new(StartedSession(session)))
728    }
729}
730
731/// A camera session the app started, as the test sees it. Its photos answer what the test gave,
732/// or that the session does not run; its recordings answer when they are stopped, writing
733/// nothing. Every clone is the same session.
734#[derive(Clone)]
735pub struct MockCaptureSession(Rc<SessionShared>);
736
737struct SessionShared {
738    camera: Camera,
739    picked: CameraFormat,
740    format: CameraFormat,
741    outputs: CameraOutputs,
742    state: RefCell<CaptureState>,
743    /// The preview's and the capture's rotation angles, 0 until the test sets them.
744    angles: Cell<[u32; 2]>,
745    photo: RefCell<Option<Photo>>,
746    /// The paths recorded to, in order.
747    recordings: RefCell<Vec<PathBuf>>,
748    /// The recording under way, which answers when stopped.
749    recording: RefCell<Option<Rc<Recording>>>,
750    changes: Changes,
751    dropped: Cell<bool>,
752}
753
754impl MockCaptureSession {
755    pub fn camera(&self) -> Camera {
756        self.0.camera.clone()
757    }
758
759    /// The format the app picked.
760    pub fn picked(&self) -> CameraFormat {
761        self.0.picked.clone()
762    }
763
764    /// The format it runs in: the one picked, or the one of the session it joined.
765    pub fn format(&self) -> CameraFormat {
766        self.0.format.clone()
767    }
768
769    /// The layer the preview shows on, among the outputs given.
770    pub fn preview_layer(&self) -> Option<Arc<dyn CompositionLayer>> {
771        self.0.outputs.preview.clone()
772    }
773
774    /// The reader the frames go to, among the outputs given.
775    pub fn frame_reader(&self) -> Option<Arc<dyn VideoFrameReader>> {
776        self.0.outputs.frames.clone()
777    }
778
779    /// The size photos are taken at, among the outputs given.
780    pub fn photo_size(&self) -> Option<Size> {
781        self.0.outputs.photos
782    }
783
784    /// What recordings ask for, among the outputs given.
785    pub fn movie_options(&self) -> Option<MovieOptions> {
786        self.0.outputs.movies
787    }
788
789    /// The paths the app recorded to, in order.
790    pub fn recordings(&self) -> Vec<PathBuf> {
791        self.0.recordings.borrow().clone()
792    }
793
794    pub fn is_dropped(&self) -> bool {
795        self.0.dropped.get()
796    }
797
798    /// Reports `preview` and `capture` as its rotation angles from now on, as the system would
799    /// have turned them with the device.
800    pub fn set_rotation_angles(&self, preview: u32, capture: u32) {
801        self.0.angles.set([preview, capture]);
802        self.0.changes.notify();
803    }
804
805    /// Answers each photo with `photo` from now on, while the session runs.
806    pub fn answering_photo(&self, photo: Photo) {
807        *self.0.photo.borrow_mut() = Some(photo);
808    }
809
810    /// Reports `state` from now on, as the system would have changed it.
811    pub fn set_state(&self, state: CaptureState) {
812        *self.0.state.borrow_mut() = state;
813        self.0.changes.notify();
814    }
815
816    fn runs(&self) -> bool {
817        *self.0.state.borrow() == CaptureState::Running
818    }
819}
820
821/// The session the app holds; dropping it ends the session's changes.
822struct StartedSession(MockCaptureSession);
823
824impl CaptureSession for StartedSession {
825    fn format(&self) -> CameraFormat {
826        self.0.format()
827    }
828
829    fn state(&self) -> CaptureState {
830        self.0.0.state.borrow().clone()
831    }
832
833    fn video_rotation_angle_for_horizon_level_preview(&self) -> u32 {
834        self.0.0.angles.get()[0]
835    }
836
837    fn video_rotation_angle_for_horizon_level_capture(&self) -> u32 {
838        self.0.0.angles.get()[1]
839    }
840
841    fn changed(&self) -> MediaChangeFuture {
842        self.0.0.changes.next()
843    }
844
845    fn take_photo(&self) -> PhotoFuture {
846        let session = &self.0;
847        let answer = if session.photo_size().is_none() {
848            Err(MediaError::Failed(
849                "photos were not among the outputs".to_owned(),
850            ))
851        } else if !session.runs() {
852            Err(MediaError::NotRunning)
853        } else {
854            session
855                .0
856                .photo
857                .borrow()
858                .clone()
859                .ok_or_else(|| MediaError::Failed("the test gave no photo".to_owned()))
860        };
861        Box::pin(std::future::ready(answer))
862    }
863
864    fn start_recording(&self, path: PathBuf) -> RecordingFuture {
865        let session = &self.0;
866        if session.movie_options().is_none() {
867            let reason = "movies were not among the outputs".to_owned();
868            return Box::pin(std::future::ready(Err(MediaError::Failed(reason))));
869        }
870        if !session.runs() {
871            return Box::pin(std::future::ready(Err(MediaError::NotRunning)));
872        }
873        session.0.recordings.borrow_mut().push(path);
874        let recording = Rc::new(Recording::default());
875        *session.0.recording.borrow_mut() = Some(Rc::clone(&recording));
876        Box::pin(RecordingEnd(recording))
877    }
878
879    fn stop_recording(&self) {
880        if let Some(recording) = self.0.0.recording.borrow_mut().take() {
881            recording.stopped.set(true);
882            if let Some(waker) = recording.waker.borrow_mut().take() {
883                waker.wake();
884            }
885        }
886    }
887}
888
889impl Drop for StartedSession {
890    fn drop(&mut self) {
891        self.0.0.dropped.set(true);
892        self.0.0.changes.end();
893    }
894}
895
896/// A recording under way, which answers once stopped.
897#[derive(Default)]
898struct Recording {
899    stopped: Cell<bool>,
900    waker: RefCell<Option<Waker>>,
901}
902
903struct RecordingEnd(Rc<Recording>);
904
905impl Future for RecordingEnd {
906    type Output = Result<(), MediaError>;
907
908    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
909        if self.0.stopped.get() {
910            return Poll::Ready(Ok(()));
911        }
912        *self.0.waker.borrow_mut() = Some(cx.waker().clone());
913        Poll::Pending
914    }
915}
916
917/// A frame reader that never has a picture.
918struct NoFrames;
919
920impl VideoFrameReader for NoFrames {
921    fn frame_for(&self, _display_time: std::time::Instant) -> Option<Arc<dyn VideoFrame>> {
922        None
923    }
924}
925
926/// Each `next` future resolves at the next change, or once the changes end.
927#[derive(Default)]
928pub(crate) struct Changes(Rc<ChangesShared>);
929
930#[derive(Default)]
931struct ChangesShared {
932    count: Cell<u64>,
933    ended: Cell<bool>,
934    wakers: RefCell<Vec<Waker>>,
935}
936
937impl Changes {
938    pub(crate) fn next(&self) -> MediaChangeFuture {
939        Box::pin(NextChange {
940            changes: Rc::clone(&self.0),
941            seen: self.0.count.get(),
942        })
943    }
944
945    pub(crate) fn notify(&self) {
946        self.0.count.set(self.0.count.get() + 1);
947        self.wake();
948    }
949
950    fn end(&self) {
951        self.0.ended.set(true);
952        self.wake();
953    }
954
955    fn wake(&self) {
956        for waker in self.0.wakers.take() {
957            waker.wake();
958        }
959    }
960}
961
962struct NextChange {
963    changes: Rc<ChangesShared>,
964    seen: u64,
965}
966
967impl Future for NextChange {
968    type Output = ();
969
970    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
971        if self.changes.ended.get() || self.changes.count.get() != self.seen {
972            return Poll::Ready(());
973        }
974        self.changes.wakers.borrow_mut().push(cx.waker().clone());
975        Poll::Pending
976    }
977}
978
979#[cfg(test)]
980mod tests {
981    use std::future::Future;
982    use std::task::{Context, Poll, Waker};
983
984    use waft_embedder::{MediaTrackKind, PlayerErrorKind};
985
986    use super::*;
987
988    fn now<T>(future: impl Future<Output = T>) -> T {
989        let mut future = std::pin::pin!(future);
990        match future
991            .as_mut()
992            .poll(&mut Context::from_waker(Waker::noop()))
993        {
994            Poll::Ready(output) => output,
995            Poll::Pending => panic!("answers at once"),
996        }
997    }
998
999    fn answers() -> AssetAnswers {
1000        AssetAnswers {
1001            duration: Ok(Some(Duration::from_secs(90))),
1002            tracks: Ok(vec![MediaTrack {
1003                id: "track:1".to_owned(),
1004                kind: MediaTrackKind::Video,
1005                language: String::new(),
1006                label: String::new(),
1007                selected: true,
1008            }]),
1009            metadata: Ok(MediaMetadata {
1010                title: Some("Bip Bop".to_owned()),
1011                ..MediaMetadata::default()
1012            }),
1013            frame_size: Ok(Size::new(320.0, 180.0)),
1014        }
1015    }
1016
1017    #[test]
1018    fn an_asset_answers_what_the_test_set_and_keeps_the_pictures_asked() {
1019        let assets = MockMediaAssets::new(answers());
1020        let asset = assets.open("file:///data/clip.mp4");
1021        assert_eq!(now(asset.duration()), Ok(Some(Duration::from_secs(90))));
1022        assert_eq!(now(asset.tracks()).unwrap()[0].id, "track:1");
1023        assert_eq!(
1024            now(asset.metadata()).unwrap().title.as_deref(),
1025            Some("Bip Bop")
1026        );
1027        let asked = FrameAsked {
1028            time: Duration::from_secs(9),
1029            tolerance: SeekTolerance::ANY,
1030            max_size: Some(Size::new(320.0, 320.0)),
1031        };
1032        let frame = now(asset.frame_at(asked.time, asked.tolerance, asked.max_size)).unwrap();
1033        assert_eq!([frame.width(), frame.height()], [320, 180]);
1034        let opened = &assets.opened()[0];
1035        assert_eq!(opened.url(), "file:///data/clip.mp4");
1036        assert_eq!(opened.frames_asked(), [asked]);
1037
1038        let refused = PlayerError {
1039            kind: PlayerErrorKind::Refused,
1040            message: "no".to_owned(),
1041        };
1042        assets.set_answers(AssetAnswers {
1043            duration: Err(refused.clone()),
1044            ..answers()
1045        });
1046        assert_eq!(now(asset.duration()), Err(refused));
1047        drop(asset);
1048        assert!(opened.is_dropped());
1049    }
1050
1051    #[test]
1052    fn a_mock_layer_keeps_what_it_shows_now_and_how_many_pictures_it_was_handed() {
1053        use waft_embedder::{HardwareBufferUsage, Rect};
1054
1055        let compositor = MockCompositor::new();
1056        let parent = compositor.make_layer(false);
1057        let child = compositor.make_layer(true);
1058        let made = compositor.made();
1059        assert_eq!(made.len(), 2);
1060        assert!(!made[0].opaque());
1061        assert!(made[1].opaque());
1062        assert!(parent.current_picture().is_none());
1063        assert_eq!(made[0].presents(), 0);
1064
1065        let buffer = |width, height| -> Arc<dyn HardwareBuffer> {
1066            Arc::new(MockHardwareBuffer {
1067                width,
1068                height,
1069                format: HardwareBufferFormat::Bgra8,
1070                usage: HardwareBufferUsage::GPU_SAMPLED,
1071            })
1072        };
1073        let released = Arc::new(AtomicUsize::new(0));
1074        let release = || -> Box<dyn FnOnce() + Send + Sync> {
1075            let bump = Arc::clone(&released);
1076            Box::new(move || {
1077                bump.fetch_add(1, Ordering::SeqCst);
1078            })
1079        };
1080        let placement = Placement {
1081            rect: Rect::from_ltwh(10.0, 20.0, 50.0, 40.0),
1082            mutators: Vec::new(),
1083        };
1084        let shown = |layer: &dyn CompositionLayer| match layer.current_picture() {
1085            Some(LayerPicture::Buffer(buffer)) => (buffer.width(), buffer.height()),
1086            _ => panic!("a buffer shown"),
1087        };
1088
1089        parent.present(
1090            buffer(100, 80),
1091            vec![(Arc::clone(&child), placement.clone())],
1092            release(),
1093        );
1094        assert_eq!(shown(&*parent), (100, 80));
1095        let children = made[0].children();
1096        assert_eq!(children.len(), 1);
1097        assert!(Arc::ptr_eq(&children[0].0, &child));
1098        assert_eq!(children[0].1, placement);
1099
1100        parent.present(buffer(200, 160), Vec::new(), release());
1101        assert_eq!(shown(&*parent), (200, 160));
1102        assert!(made[0].children().is_empty(), "what it shows now");
1103        assert_eq!(made[0].presents(), 2);
1104        assert_eq!(released.load(Ordering::SeqCst), 2, "each released at once");
1105        assert!(MockLayer::of(&*parent).is_some_and(|layer| std::ptr::eq(layer, &*made[0])));
1106    }
1107}