Skip to main content

waft_widgets/media/
camera.rs

1//! A camera running for an app, as the app holds it, and the view that shows its preview.
2
3use std::fmt;
4use std::path::PathBuf;
5use std::rc::Rc;
6use std::sync::Arc;
7
8use waft_embedder::{
9    Camera, CameraDevice, CameraError, CameraFormat, CameraListFuture, CameraOpenFuture,
10    CameraOutputs, CaptureSession, CaptureState, CompositionLayer, MediaChangeFuture, PhotoFuture,
11    RecordingFuture, Size,
12};
13use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, Ref, Task};
14
15use super::at_size;
16use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
17use crate::widgets::basic::SizedBox;
18use crate::widgets::composition_layer_view::CompositionLayerView;
19use crate::widgets::transitions::ListenableBuilder;
20
21/// The cameras attached now, in the system's order; none where the platform has no cameras:
22/// Flutter's `availableCameras`. Listing asks the user nothing.
23pub fn available_cameras(app: &App) -> CameraListFuture {
24    match app.platform().cameras() {
25        Some(cameras) => cameras.cameras(),
26        None => Box::pin(std::future::ready(Vec::new())),
27    }
28}
29
30/// Resolves once [`available_cameras`] may answer something else than when this was called: a
31/// camera plugged in or out; `None` where the platform has no cameras.
32pub fn available_cameras_changed(app: &App) -> Option<MediaChangeFuture> {
33    Some(app.platform().cameras()?.changed())
34}
35
36/// Opens `camera`, asking the user for the cameras first where the system asks and the user has
37/// not answered; `None` where the platform has no cameras. The camera opened lists the formats it
38/// runs in, and a [`CameraSession`] starts it in one.
39pub fn open_camera(app: &App, camera: &Camera) -> Option<CameraOpenFuture> {
40    Some(app.platform().cameras()?.open(camera))
41}
42
43/// A camera running for the app in one format, feeding the outputs it started with, each the
44/// system's own: the host's session, whose listeners hear its state change.
45pub struct CameraSession {
46    change_notifier: ChangeNotifierData,
47    /// The host's session, until [`dispose`](CameraSession::dispose).
48    host: Option<Rc<dyn CaptureSession>>,
49    /// The format the camera runs in for the session.
50    format: CameraFormat,
51    /// The host's state when it last changed.
52    state: CaptureState,
53    /// The host's rotation angles, the preview's and the capture's, when they last changed.
54    rotation_angles: [u32; 2],
55    /// The layer the preview shows on, among the outputs it started with, which a
56    /// [`CameraPreview`] places.
57    preview_layer: Option<Arc<dyn CompositionLayer>>,
58}
59
60impl CameraSession {
61    /// Starts `camera` in `format`, one of its formats, feeding `outputs`, which the system
62    /// configures together, and answers the session once it runs, or is interrupted, from which
63    /// it resumes by itself; where the camera already runs for another session in a format of its
64    /// own, the session joins that one, which [`format`](CameraSession::format) says. It fails
65    /// for what can happen at any time: the camera in use, unplugged, or not allowed; and for a
66    /// format the camera does not list.
67    pub fn start(
68        app: &App,
69        camera: &dyn CameraDevice,
70        format: &CameraFormat,
71        outputs: CameraOutputs,
72    ) -> Task<Result<Ref<CameraSession>, CameraError>> {
73        let preview_layer = outputs.preview.clone();
74        let starting = camera.start(format, outputs);
75        app.spawn(async move |cx| {
76            let host = starting.await?;
77            Ok(cx.update(|app| CameraSession::of_host(app, Rc::from(host), preview_layer)))
78        })
79    }
80
81    /// The session over `host`, which started with its preview on `preview_layer`, following its
82    /// state from now on.
83    fn of_host(
84        app: &mut App,
85        host: Rc<dyn CaptureSession>,
86        preview_layer: Option<Arc<dyn CompositionLayer>>,
87    ) -> Ref<CameraSession> {
88        let changed = host.changed();
89        let session = app.create(CameraSession {
90            change_notifier: ChangeNotifierData::new(),
91            format: host.format(),
92            state: host.state(),
93            rotation_angles: rotation_angles_of(&*host),
94            host: Some(host),
95            preview_layer,
96        });
97        session.follow(app, changed);
98        session
99    }
100
101    /// The format the camera runs in: the one picked, unless the session joined another.
102    pub fn format(self: Handle<Self>, app: &App) -> &CameraFormat {
103        &app.get(self).format
104    }
105
106    /// The session's state when it last changed.
107    pub fn state(self: Handle<Self>, app: &App) -> &CaptureState {
108        &app.get(self).state
109    }
110
111    /// The turn, in degrees clockwise, that keeps the preview level, when it last changed:
112    /// [`CaptureSession::video_rotation_angle_for_horizon_level_preview`]. The system's preview is
113    /// turned so on its layer, which a [`CameraPreview`] lays out turned.
114    pub fn video_rotation_angle_for_horizon_level_preview(self: Handle<Self>, app: &App) -> u32 {
115        app.get(self).rotation_angles[0]
116    }
117
118    /// The turn that keeps what is captured level, when it last changed:
119    /// [`CaptureSession::video_rotation_angle_for_horizon_level_capture`].
120    pub fn video_rotation_angle_for_horizon_level_capture(self: Handle<Self>, app: &App) -> u32 {
121        app.get(self).rotation_angles[1]
122    }
123
124    /// The layer the preview shows on, which a [`CameraPreview`] places; `None` where the session
125    /// started without one, or once disposed.
126    pub fn preview_layer(self: Handle<Self>, app: &App) -> Option<&Arc<dyn CompositionLayer>> {
127        app.get(self).preview_layer.as_ref()
128    }
129
130    /// Takes a photo, captured, processed and encoded by the system, while the session runs with
131    /// photos among its outputs.
132    pub fn take_photo(self: Handle<Self>, app: &App) -> PhotoFuture {
133        self.host(app).take_photo()
134    }
135
136    /// Records to a new file at `path`, encoded and written by the system, while the session runs
137    /// with movies among its outputs, until [`stop_recording`](CameraSession::stop_recording).
138    pub fn start_recording(self: Handle<Self>, app: &App, path: PathBuf) -> RecordingFuture {
139        self.host(app).start_recording(path)
140    }
141
142    /// Ends the recording, whose future then answers.
143    pub fn stop_recording(self: Handle<Self>, app: &App) {
144        self.host(app).stop_recording();
145    }
146
147    /// Stops the camera for the app and lets go of the host's session: its preview leaves the
148    /// layer it was on, and its listeners hear nothing more.
149    pub fn dispose(self: Handle<Self>, app: &mut App) {
150        let session = app.get_mut(self);
151        session.host = None;
152        session.preview_layer = None;
153        ChangeNotifierData::dispose(app, self);
154    }
155
156    /// The host's session.
157    ///
158    /// # Panics
159    ///
160    /// Once disposed.
161    fn host(self: Handle<Self>, app: &App) -> &dyn CaptureSession {
162        app.get(self)
163            .host
164            .as_deref()
165            .expect("a CameraSession used after dispose")
166    }
167
168    /// Takes the host's state at each of its changes, from the one `changed` resolves at, until
169    /// the session is disposed or no longer kept.
170    fn follow(self: Handle<Self>, app: &mut App, changed: MediaChangeFuture) {
171        let _following = app.spawn(async move |cx| {
172            let mut changed = changed;
173            loop {
174                changed.await;
175                let next = cx.update(|app| {
176                    let session = self.upgrade(app)?;
177                    session.take_host_state(app)
178                });
179                match next {
180                    Some(next) => changed = next,
181                    None => return,
182                }
183            }
184        });
185    }
186
187    /// Takes the host's state and rotation angles, telling the listeners if either changed;
188    /// answers the future of the host's next change, asked before they are read so that no change
189    /// goes unheard, or `None` once the session is disposed.
190    fn take_host_state(self: Handle<Self>, app: &mut App) -> Option<MediaChangeFuture> {
191        let host = app.get(self).host.clone()?;
192        let next = host.changed();
193        let state = host.state();
194        let rotation_angles = rotation_angles_of(&*host);
195        let session = app.get_mut(self);
196        if state != session.state || rotation_angles != session.rotation_angles {
197            session.state = state;
198            session.rotation_angles = rotation_angles;
199            self.notify_listeners(app);
200        }
201        Some(next)
202    }
203}
204
205/// `host`'s rotation angles, the preview's and the capture's.
206fn rotation_angles_of(host: &dyn CaptureSession) -> [u32; 2] {
207    [
208        host.video_rotation_angle_for_horizon_level_preview(),
209        host.video_rotation_angle_for_horizon_level_capture(),
210    ]
211}
212
213impl ChangeNotifier for CameraSession {
214    fn change_notifier_data(&self) -> &ChangeNotifierData {
215        &self.change_notifier
216    }
217
218    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
219        &mut self.change_notifier
220    }
221}
222
223impl fmt::Debug for CameraSession {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        f.debug_struct("CameraSession")
226            .field("format", &self.format)
227            .field("state", &self.state)
228            .finish_non_exhaustive()
229    }
230}
231
232/// A camera session's preview, laid out at the size of the format the camera runs in, turned by
233/// the preview's rotation angle, in logical pixels, or as large as the constraints let it be at
234/// that aspect; laid out again as the angle changes. It places the layer the
235/// session started with for its preview, which the system draws into; a session started without
236/// one shows nothing there.
237#[derive(Clone)]
238pub struct CameraPreview {
239    pub key: Option<KeyRef>,
240    pub session: Ref<CameraSession>,
241}
242
243impl CameraPreview {
244    pub fn new(session: Ref<CameraSession>) -> CameraPreview {
245        CameraPreview { key: None, session }
246    }
247
248    pub fn key(mut self, key: KeyRef) -> CameraPreview {
249        self.key = Some(key);
250        self
251    }
252}
253
254impl fmt::Debug for CameraPreview {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        f.debug_struct("CameraPreview").finish_non_exhaustive()
257    }
258}
259
260impl StatelessWidget for CameraPreview {
261    fn key(&self) -> Option<&KeyRef> {
262        self.key.as_ref()
263    }
264
265    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
266        let session = self.session.clone();
267        ListenableBuilder::new(Rc::new(session.clone()), move |app, _context, _child| {
268            let size = turned(
269                session.format(app).size,
270                session.video_rotation_angle_for_horizon_level_preview(app),
271            );
272            let preview = match session.preview_layer(app) {
273                Some(layer) => CompositionLayerView::new(Arc::clone(layer)).into_widget(),
274                None => SizedBox::expand().into_widget(),
275            };
276            at_size(size, preview)
277        })
278        .into_widget()
279    }
280}
281
282/// `size` turned `angle` degrees clockwise: its sides swapped by a quarter turn.
283fn turned(size: Size, angle: u32) -> Size {
284    if angle % 180 == 90 {
285        Size::new(size.height(), size.width())
286    } else {
287        size
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use std::time::Duration;
294    use waft_foundation::Ref;
295
296    use waft_embedder::{
297        CameraFacing, CameraId, CameraInterruption, MediaError, MovieOptions, Photo, Size,
298        TargetPlatform, VideoFrameReaders,
299    };
300    use waft_foundation::{AppCell, ListenableObject, Listener};
301    use waft_test::{MockCameras, MockCompositor, MockVideoFrameReaders, TestPlatform, TestView};
302
303    use super::*;
304    use crate::testing::WidgetTester;
305
306    fn front_camera() -> Camera {
307        Camera {
308            id: CameraId("front".to_owned()),
309            name: "Front camera".to_owned(),
310            facing: CameraFacing::Front,
311        }
312    }
313
314    fn format(width: f64, height: f64) -> CameraFormat {
315        CameraFormat {
316            size: Size::new(width, height),
317            min_frame_rate: 15.0,
318            max_frame_rate: 30.0,
319            photo_sizes: vec![Size::new(width, height)],
320        }
321    }
322
323    fn cameras() -> MockCameras {
324        MockCameras::new(vec![front_camera()])
325            .with_formats(vec![format(1920.0, 1080.0), format(640.0, 480.0)])
326    }
327
328    fn app_with(cameras: &MockCameras, compositor: &MockCompositor) -> Rc<AppCell> {
329        let platform = platform_with(cameras, compositor)
330            .with_view(Rc::new(TestView::new(400.0, 800.0)) as waft_embedder::ViewRef);
331        AppCell::with_platform(Rc::new(platform))
332    }
333
334    /// An iPhone with `cameras`, compositing through `compositor`.
335    fn platform_with(cameras: &MockCameras, compositor: &MockCompositor) -> TestPlatform {
336        TestPlatform::new()
337            .on(TargetPlatform::IOS)
338            .with_cameras(Rc::new(cameras.clone()))
339            .with_compositor(Arc::new(compositor.clone()))
340    }
341
342    /// Runs `future` to its end, which the mocks answer without waiting.
343    fn now<T>(future: impl std::future::Future<Output = T>) -> T {
344        let mut future = std::pin::pin!(future);
345        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
346        match future.as_mut().poll(&mut context) {
347            std::task::Poll::Ready(output) => output,
348            std::task::Poll::Pending => panic!("the mock answers at once"),
349        }
350    }
351
352    /// Starts `camera` as an app does, running the app's tasks until the start answers.
353    fn start(
354        cell: &AppCell,
355        camera: &dyn CameraDevice,
356        format: &CameraFormat,
357        outputs: CameraOutputs,
358    ) -> Result<Ref<CameraSession>, CameraError> {
359        let starting = CameraSession::start(&cell.borrow(), camera, format, outputs);
360        cell.checkpoint();
361        now(starting)
362    }
363
364    fn opened(cell: &AppCell) -> Box<dyn CameraDevice> {
365        let opening =
366            open_camera(&cell.borrow(), &front_camera()).expect("a platform with cameras");
367        now(opening).expect("the user lets the app use the cameras")
368    }
369
370    #[test]
371    fn the_cameras_are_the_platforms_and_none_where_it_has_none() {
372        let cameras = cameras();
373        let cell = app_with(&cameras, &MockCompositor::new());
374        assert_eq!(now(available_cameras(&cell.borrow())), vec![front_camera()]);
375
376        let without = AppCell::with_platform(Rc::new(TestPlatform::new()));
377        assert!(now(available_cameras(&without.borrow())).is_empty());
378        assert!(available_cameras_changed(&without.borrow()).is_none());
379        assert!(open_camera(&without.borrow(), &front_camera()).is_none());
380    }
381
382    #[test]
383    fn the_cameras_change_as_one_comes_or_goes() {
384        let cameras = cameras();
385        let cell = app_with(&cameras, &MockCompositor::new());
386        let mut changed =
387            available_cameras_changed(&cell.borrow()).expect("a platform with cameras");
388        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
389        assert!(changed.as_mut().poll(&mut context).is_pending());
390
391        let plugged_in = Camera {
392            id: CameraId("usb".to_owned()),
393            name: "USB camera".to_owned(),
394            facing: CameraFacing::External,
395        };
396        cameras.set_cameras(vec![front_camera(), plugged_in.clone()]);
397        assert!(changed.as_mut().poll(&mut context).is_ready());
398        assert_eq!(
399            now(available_cameras(&cell.borrow())),
400            vec![front_camera(), plugged_in]
401        );
402
403        let mut changed = available_cameras_changed(&cell.borrow()).unwrap();
404        assert!(
405            changed.as_mut().poll(&mut context).is_pending(),
406            "a change before the future was asked for is not one after it"
407        );
408        cameras.set_cameras(vec![front_camera()]);
409        assert!(changed.as_mut().poll(&mut context).is_ready());
410        assert_eq!(now(available_cameras(&cell.borrow())), vec![front_camera()]);
411    }
412
413    #[test]
414    fn a_camera_the_user_does_not_allow_does_not_open() {
415        let cell = app_with(&cameras().denying(), &MockCompositor::new());
416        let opening = open_camera(&cell.borrow(), &front_camera()).unwrap();
417        assert!(matches!(now(opening), Err(CameraError::NotAllowed)));
418    }
419
420    #[test]
421    fn a_camera_starts_in_a_format_it_lists_with_its_outputs_given_whole() {
422        let cameras = cameras();
423        let cell = app_with(&cameras, &MockCompositor::new());
424        let camera = opened(&cell);
425        let formats = camera.formats();
426        assert_eq!(formats, vec![format(1920.0, 1080.0), format(640.0, 480.0)]);
427
428        let reader = MockVideoFrameReaders::new().make_reader();
429        let outputs = CameraOutputs::new()
430            .frames(Arc::clone(&reader))
431            .photos(Size::new(640.0, 480.0))
432            .movies(MovieOptions { sound: true });
433        let session = start(&cell, &*camera, &formats[1], outputs).unwrap();
434        let host = &cameras.sessions()[0];
435        assert_eq!(host.camera(), front_camera());
436        assert_eq!(*session.format(&cell.borrow()), format(640.0, 480.0));
437        assert!(Arc::ptr_eq(&host.frame_reader().unwrap(), &reader));
438        assert_eq!(host.photo_size(), Some(Size::new(640.0, 480.0)));
439        assert_eq!(host.movie_options(), Some(MovieOptions { sound: true }));
440        assert_eq!(*session.state(&cell.borrow()), CaptureState::Running);
441
442        let unlisted = format(320.0, 240.0);
443        assert!(matches!(
444            start(&cell, &*camera, &unlisted, CameraOutputs::new()),
445            Err(CameraError::Failed(_))
446        ));
447
448        session.dispose(&mut cell.borrow_mut());
449        assert!(host.is_dropped());
450    }
451
452    #[test]
453    fn a_session_on_a_camera_another_runs_joins_its_format_and_says_so() {
454        let cameras = cameras();
455        let cell = app_with(&cameras, &MockCompositor::new());
456        let camera = opened(&cell);
457        let formats = camera.formats();
458        let first = start(&cell, &*camera, &formats[0], CameraOutputs::new()).unwrap();
459        let joined = start(&cell, &*camera, &formats[1], CameraOutputs::new()).unwrap();
460        assert_eq!(cameras.sessions()[1].picked(), format(640.0, 480.0));
461        assert_eq!(*joined.format(&cell.borrow()), format(1920.0, 1080.0));
462
463        first.dispose(&mut cell.borrow_mut());
464        joined.dispose(&mut cell.borrow_mut());
465        let alone = start(&cell, &*camera, &formats[1], CameraOutputs::new()).unwrap();
466        assert_eq!(
467            *alone.format(&cell.borrow()),
468            format(640.0, 480.0),
469            "once no session runs the camera, it runs in the format picked"
470        );
471    }
472
473    #[test]
474    fn a_sessions_listeners_hear_it_interrupted_resume_and_end() {
475        let cameras = cameras();
476        let cell = app_with(&cameras, &MockCompositor::new());
477        let camera = opened(&cell);
478        let outputs = CameraOutputs::new().photos(Size::new(1920.0, 1080.0));
479        let session = start(&cell, &*camera, &camera.formats()[0], outputs).unwrap();
480        let heard = Rc::new(std::cell::Cell::new(0));
481        let hearing = Rc::clone(&heard);
482        session.add_listener(
483            &mut cell.borrow_mut(),
484            Listener::new(move |_| hearing.set(hearing.get() + 1)),
485        );
486        let host = &cameras.sessions()[0];
487        let photo = Photo {
488            bytes: vec![0xff, 0xd8],
489            mime_type: "image/jpeg".to_owned(),
490        };
491        host.answering_photo(photo.clone());
492        assert_eq!(now(session.take_photo(&cell.borrow())), Ok(photo));
493        assert!(
494            matches!(
495                now(session.start_recording(&cell.borrow(), PathBuf::from("/tmp/clip.mov"))),
496                Err(MediaError::Failed(_))
497            ),
498            "movies were not among its outputs"
499        );
500
501        let interrupted = CaptureState::Interrupted(Some(CameraInterruption::InUseByAnotherApp));
502        host.set_state(interrupted.clone());
503        cell.checkpoint();
504        assert_eq!(*session.state(&cell.borrow()), interrupted);
505        assert_eq!(
506            now(session.take_photo(&cell.borrow())),
507            Err(MediaError::NotRunning)
508        );
509
510        host.set_state(CaptureState::Running);
511        cell.checkpoint();
512        host.set_state(CaptureState::Ended(CameraError::Unplugged));
513        cell.checkpoint();
514        assert_eq!(
515            *session.state(&cell.borrow()),
516            CaptureState::Ended(CameraError::Unplugged)
517        );
518        assert_eq!(heard.get(), 3);
519    }
520
521    #[test]
522    fn a_session_records_while_it_runs_with_movies_among_its_outputs() {
523        let cameras = cameras();
524        let cell = app_with(&cameras, &MockCompositor::new());
525        let camera = opened(&cell);
526        let outputs = CameraOutputs::new().movies(MovieOptions::default());
527        let session = start(&cell, &*camera, &camera.formats()[0], outputs).unwrap();
528        let mut recording = session.start_recording(&cell.borrow(), PathBuf::from("/tmp/clip.mov"));
529        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
530        assert!(recording.as_mut().poll(&mut context).is_pending());
531        session.stop_recording(&cell.borrow());
532        assert_eq!(now(recording), Ok(()));
533        assert_eq!(
534            cameras.sessions()[0].recordings(),
535            vec![PathBuf::from("/tmp/clip.mov")]
536        );
537    }
538
539    #[test]
540    fn a_camera_preview_places_the_sessions_preview_layer_at_its_formats_size() {
541        let cameras = cameras();
542        let compositor = MockCompositor::new();
543        let tester = &mut WidgetTester::with_platform(platform_with(&cameras, &compositor));
544        tester.view().set_physical_size(Size::new(1200.0, 2400.0));
545        let camera = opened(&tester.cell);
546        let layer = tester.update(|app| {
547            app.platform()
548                .compositor()
549                .expect("a platform with a compositor")
550                .make_layer(false)
551        });
552        let outputs = CameraOutputs::new().preview(Arc::clone(&layer));
553        let session = start(&tester.cell, &*camera, &camera.formats()[0], outputs).unwrap();
554        assert!(Arc::ptr_eq(
555            &cameras.sessions()[0].preview_layer().unwrap(),
556            &layer
557        ));
558        tester.pump_widget(crate::Center::new().child(CameraPreview::new(session.clone())));
559        let scene = tester.view().last_scene().unwrap();
560        let slices = waft_embedder::slices(&scene, |_| None);
561        let (placed, placement) = slices.composition_layers().next().unwrap();
562        assert!(Arc::ptr_eq(placed, &layer));
563        assert_eq!(
564            placement.bounds().size(),
565            Size::new(1200.0, 675.0),
566            "as wide as the view lets it be, at the format's aspect, in physical pixels"
567        );
568
569        cameras.sessions()[0].set_rotation_angles(90, 90);
570        tester.cell.checkpoint();
571        assert_eq!(
572            tester.update(|app| session.video_rotation_angle_for_horizon_level_preview(app)),
573            90
574        );
575        tester.pump_by(Duration::ZERO);
576        let scene = tester.view().last_scene().unwrap();
577        let slices = waft_embedder::slices(&scene, |_| None);
578        let (_, placement) = slices.composition_layers().next().unwrap();
579        let size = placement.bounds().size();
580        assert_eq!(
581            (size.width(), (size.height() * 10.0).round() / 10.0),
582            (1200.0, 2133.3),
583            "turned a quarter as the device turns: as wide as the view, at the turned aspect"
584        );
585    }
586
587    #[test]
588    fn a_size_turned_a_quarter_swaps_its_sides() {
589        assert_eq!(turned(Size::new(16.0, 9.0), 90), Size::new(9.0, 16.0));
590        assert_eq!(turned(Size::new(16.0, 9.0), 270), Size::new(9.0, 16.0));
591        assert_eq!(turned(Size::new(16.0, 9.0), 180), Size::new(16.0, 9.0));
592    }
593}