cranpose-services 0.1.161

Multiplatform system services for Cranpose (HTTP, URI, and OS integrations)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! The live camera: what it is doing, the frames it is producing, and the
//! stills it takes.
//!
//! Three things about a camera are easy to get wrong and expensive to get wrong
//! twice, so the framework owns all three.
//!
//! A camera is **observable, not polled**. A viewfinder that asks "is there a
//! new frame yet?" every frame does that work whether or not one arrived, and
//! learns about a failure only by noticing that frames stopped. Here the
//! session publishes what it is doing and the frames it produces, and a screen
//! reacts.
//!
//! Frames arrive in the **format the sensor produced**. Encoding a preview
//! frame as JPEG to hand it across a language boundary and decoding it back
//! costs several milliseconds per frame, every frame, to arrive at the pixels
//! the camera already had. [`FrameFormat::Nv12`] is what a phone camera
//! actually produces, and it converts to RGBA in one pass over the bytes.
//!
//! Analysis is **bounded and latest-wins**. A detector that takes longer than a
//! frame interval must fall behind rather than accumulate: a queue of stale
//! frames costs memory to hold and produces answers about a scene that has
//! already moved.

use std::sync::{
    Arc, Mutex, OnceLock,
    atomic::{AtomicU64, Ordering},
};

use cranpose_core::{EventStream, State, rememberEventStream};

use crate::registry::ServiceRegistry;

/// How a frame's pixels are laid out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FrameFormat {
    /// Tightly packed RGBA8, row-major, no padding.
    #[default]
    Rgba8,
    /// Tightly packed RGB8, row-major, no padding.
    ///
    /// What a USB webcam decodes to. Carried as-is so a desktop viewfinder does
    /// not pay a widening copy per frame for an alpha channel a camera never
    /// has.
    Rgb8,
    /// Full-range NV12: a `width * height` luma plane followed by an
    /// interleaved `width * height / 2` chroma plane at half resolution in both
    /// directions.
    ///
    /// What a phone camera produces. Carrying it as-is is what removes the
    /// encode-and-decode round trip a JPEG preview pays on every frame.
    Nv12,
}

impl FrameFormat {
    /// How many bytes a frame of this size occupies, or `None` when the size
    /// cannot be represented — which is a frame nobody can allocate anyway.
    pub fn byte_len(self, width: u32, height: u32) -> Option<usize> {
        let pixels = (width as usize).checked_mul(height as usize)?;
        match self {
            FrameFormat::Rgba8 => pixels.checked_mul(4),
            FrameFormat::Rgb8 => pixels.checked_mul(3),
            FrameFormat::Nv12 => {
                if !width.is_multiple_of(2) || !height.is_multiple_of(2) {
                    return None;
                }
                pixels.checked_add(pixels / 2)
            }
        }
    }
}

/// One frame from the viewfinder.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CameraFrame {
    pub width: u32,
    pub height: u32,
    pub format: FrameFormat,
    /// How far the frame must be rotated clockwise to be the right way up,
    /// which is the sensor's mounting plus the device's rotation.
    pub rotation_degrees: u16,
    /// Which frame this is in the session, so a consumer can tell a repeat from
    /// a new one and count what it missed.
    pub sequence: u64,
    /// The pixels, in [`format`](Self::format).
    pub bytes: Vec<u8>,
}

impl CameraFrame {
    /// A frame, or `None` when the bytes do not match the size and format —
    /// which is a backend bug, and one that reads as corrupted video rather
    /// than as an error if it is let through.
    pub fn new(
        width: u32,
        height: u32,
        format: FrameFormat,
        rotation_degrees: u16,
        sequence: u64,
        bytes: Vec<u8>,
    ) -> Option<Self> {
        if format.byte_len(width, height)? != bytes.len() {
            return None;
        }
        Some(Self {
            width,
            height,
            format,
            rotation_degrees: rotation_degrees % 360,
            sequence,
            bytes,
        })
    }

    /// The frame as tightly packed RGBA8, converting only when it has to.
    ///
    /// One pass over the bytes with no allocation beyond the result, because
    /// this runs per frame: a conversion that allocates per row shows up as
    /// dropped frames rather than as a slow function.
    pub fn to_rgba8(&self) -> Vec<u8> {
        match self.format {
            FrameFormat::Rgba8 => self.bytes.clone(),
            FrameFormat::Rgb8 => rgb8_to_rgba8(&self.bytes),
            FrameFormat::Nv12 => nv12_to_rgba8(self.width, self.height, &self.bytes),
        }
    }

    /// The frame as tightly packed RGBA8 with
    /// [`rotation_degrees`](Self::rotation_degrees) applied, so the pixels are
    /// the right way up whatever the sensor's mounting was.
    ///
    /// The turn happens in the same pass as the format conversion, because this
    /// runs on every previewed frame: converting and then turning would walk
    /// the pixels twice. A rotation that is not a quarter turn is left alone —
    /// no camera produces one.
    pub fn upright_rgba8(&self) -> UprightRgba {
        let rotation = self.rotation_degrees;
        if !matches!(rotation, 90 | 180 | 270) {
            return UprightRgba {
                width: self.width,
                height: self.height,
                rgba: self.to_rgba8(),
            };
        }
        let (width, height) = (self.width as usize, self.height as usize);
        let (out_width, out_height) = match rotation {
            90 | 270 => (self.height, self.width),
            _ => (self.width, self.height),
        };
        let mut rgba = vec![0u8; width * height * 4];
        match self.format {
            FrameFormat::Rgba8 => {
                for y in 0..height {
                    let row = &self.bytes[y * width * 4..(y + 1) * width * 4];
                    for x in 0..width {
                        let src = &row[x * 4..x * 4 + 4];
                        let dst = turned_index(rotation, width, height, x, y) * 4;
                        rgba[dst..dst + 4].copy_from_slice(src);
                    }
                }
            }
            FrameFormat::Rgb8 => {
                for y in 0..height {
                    let row = &self.bytes[y * width * 3..(y + 1) * width * 3];
                    for x in 0..width {
                        let src = &row[x * 3..x * 3 + 3];
                        let dst = turned_index(rotation, width, height, x, y) * 4;
                        rgba[dst..dst + 3].copy_from_slice(src);
                        rgba[dst + 3] = 255;
                    }
                }
            }
            FrameFormat::Nv12 => {
                let pixels = width * height;
                if self.bytes.len() < pixels + pixels / 2 || width == 0 || height == 0 {
                    return UprightRgba {
                        width: out_width,
                        height: out_height,
                        rgba,
                    };
                }
                let (luma, chroma) = self.bytes.split_at(pixels);
                for y in 0..height {
                    let luma_row = &luma[y * width..(y + 1) * width];
                    let chroma_row = &chroma[(y / 2) * width..(y / 2 + 1) * width];
                    for x in 0..width {
                        let luminance = luma_row[x] as i32;
                        let blue_difference = chroma_row[x & !1] as i32 - 128;
                        let red_difference = chroma_row[(x & !1) + 1] as i32 - 128;
                        let dst = turned_index(rotation, width, height, x, y) * 4;
                        rgba[dst] = clamp_byte(luminance + ((91881 * red_difference) >> 16));
                        rgba[dst + 1] = clamp_byte(
                            luminance - ((22554 * blue_difference + 46802 * red_difference) >> 16),
                        );
                        rgba[dst + 2] = clamp_byte(luminance + ((116130 * blue_difference) >> 16));
                        rgba[dst + 3] = 255;
                    }
                }
            }
        }
        UprightRgba {
            width: out_width,
            height: out_height,
            rgba,
        }
    }
}

/// A frame's pixels as tightly packed RGBA8, already the right way up.
///
/// `width` and `height` describe the turned image, so a 90° or 270° turn swaps
/// them relative to the frame that produced this.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UprightRgba {
    pub width: u32,
    pub height: u32,
    pub rgba: Vec<u8>,
}

#[inline]
fn turned_index(rotation: u16, width: usize, height: usize, x: usize, y: usize) -> usize {
    match rotation {
        90 => x * height + (height - 1 - y),
        180 => (height - 1 - y) * width + (width - 1 - x),
        270 => (width - 1 - x) * height + y,
        _ => y * width + x,
    }
}

fn rgb8_to_rgba8(bytes: &[u8]) -> Vec<u8> {
    let mut rgba = Vec::with_capacity(bytes.len() / 3 * 4);
    for [red, green, blue] in bytes.as_chunks::<3>().0 {
        rgba.extend_from_slice(&[*red, *green, *blue, 255]);
    }
    rgba
}

fn nv12_to_rgba8(width: u32, height: u32, bytes: &[u8]) -> Vec<u8> {
    let (width, height) = (width as usize, height as usize);
    let pixels = width * height;
    let mut rgba = vec![0u8; pixels * 4];
    if bytes.len() < pixels + pixels / 2 || width == 0 || height == 0 {
        return rgba;
    }
    let (luma, chroma) = bytes.split_at(pixels);

    for y in 0..height {
        let luma_row = &luma[y * width..(y + 1) * width];
        let chroma_row = &chroma[(y / 2) * width..(y / 2 + 1) * width];
        let out_row = &mut rgba[y * width * 4..(y + 1) * width * 4];
        for x in 0..width {
            let luminance = luma_row[x] as i32;
            let blue_difference = chroma_row[x & !1] as i32 - 128;
            let red_difference = chroma_row[(x & !1) + 1] as i32 - 128;
            let out = &mut out_row[x * 4..x * 4 + 4];
            out[0] = clamp_byte(luminance + ((91881 * red_difference) >> 16));
            out[1] =
                clamp_byte(luminance - ((22554 * blue_difference + 46802 * red_difference) >> 16));
            out[2] = clamp_byte(luminance + ((116130 * blue_difference) >> 16));
            out[3] = 255;
        }
    }
    rgba
}

fn clamp_byte(value: i32) -> u8 {
    value.clamp(0, 255) as u8
}

/// A full-resolution still photograph as an encoded image.
///
/// Unlike a viewfinder frame, a still comes through the platform's dedicated
/// photo pipeline at full sensor resolution. The bytes are an encoded JPEG
/// whose EXIF orientation tag reflects the device rotation; decode with an
/// orientation-aware decoder.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CameraStill {
    pub jpeg: Vec<u8>,
}

/// One capture device the application may pick.
///
/// `id` is the platform's own handle for the device (an `AVCaptureDevice`
/// uniqueID on iOS, a camera2 id on Android, a device index on desktop); pass
/// it back to [`Camera::use_lens`]. `name` is for a button label: "Ultra
/// wide", "Wide", "Tele".
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CameraLens {
    pub id: String,
    pub name: String,
    /// Which way the device points, so an application can offer back lenses
    /// and the front lens as different controls.
    pub facing: LensFacing,
}

/// Which way a capture device points.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LensFacing {
    /// Away from the screen: the main photography cameras on a phone.
    #[default]
    Back,
    /// At the person holding the device.
    Front,
    /// Not fixed to a screen at all: a webcam or another attached device.
    External,
}

/// The devices the application may pick between, and the one in use.
///
/// Published by the backend when a session opens and when the device changes.
/// A screen showing a lens control observes this instead of asking the
/// platform, because both phone lens lists are blocking platform calls — a
/// JNI round trip on Android, a fresh discovery session on iOS — and a
/// recomposition must not pay that.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CameraLenses {
    /// Back lenses first in field-of-view order, widest first, then the rest.
    pub lenses: Vec<CameraLens>,
    /// The id of the device the open session uses, or `None` while nothing
    /// runs.
    pub active: Option<String>,
}

/// What the light does when a still is captured.
///
/// `Auto` leaves the choice to the device's exposure metering. A backend with
/// no flash reports `false` from [`Camera::set_flash`] and the application
/// hides the control.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FlashMode {
    #[default]
    Off,
    Auto,
    On,
}

#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum CameraError {
    /// No live camera backend on this platform.
    #[error("live camera capture is not supported here")]
    Unsupported,
    /// The user denied camera access.
    #[error("camera permission denied")]
    PermissionDenied,
    /// A still was asked for while nothing was running.
    #[error("the camera is not running")]
    NotRunning,
    /// Any other failure — no device, a configuration the hardware refused.
    #[error("{0}")]
    Failed(String),
}

/// What the camera session is doing.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum CameraState {
    /// Nothing has been asked of it.
    #[default]
    Idle,
    /// A session is opening. Phones take a noticeable moment over this, which
    /// is why it is a state a screen can show rather than a gap before frames.
    Starting,
    /// Frames are being produced.
    Running {
        /// The device the session opened, for a label.
        device: String,
    },
    /// The session was stopped and the device released.
    Stopped,
    /// The session could not start, or ended on its own.
    Failed(CameraError),
}

impl CameraState {
    /// Whether frames are being produced now.
    pub fn is_running(&self) -> bool {
        matches!(self, CameraState::Running { .. })
    }

    /// Whether the session is opening or open — which is when a screen keeps
    /// the viewfinder on screen rather than showing a placeholder.
    pub fn is_active(&self) -> bool {
        matches!(self, CameraState::Starting | CameraState::Running { .. })
    }

    /// The failure, if the session ended in one.
    pub fn failure(&self) -> Option<&CameraError> {
        match self {
            CameraState::Failed(error) => Some(error),
            _ => None,
        }
    }
}

/// A platform capture session.
///
/// A backend starts and stops the device and publishes what it produces through
/// [`publish_camera_frame`] and [`publish_camera_state`]; nothing here is
/// polled, and no method blocks for the length of a capture.
pub trait Camera: Send + Sync {
    /// Opens the session.
    ///
    /// Returns as soon as the request is accepted. The session's progress
    /// arrives as [`CameraState`], because opening a camera takes long enough
    /// on a phone that a screen has to show something in the meantime.
    fn start(&self) -> Result<(), CameraError>;

    /// Stops the session and releases the device.
    fn stop(&self);

    /// Asks for a full-resolution still.
    ///
    /// The picture arrives through [`publish_camera_still`], because the device
    /// takes as long as it takes to expose and encode, and a call that blocked
    /// for it would block whatever asked.
    fn request_still(&self) -> Result<(), CameraError> {
        Err(CameraError::Unsupported)
    }

    /// Turns the torch on or off while the session runs.
    ///
    /// Scanner-style applications light a dim scene rather than analysing
    /// photon-starved frames. Returns `false` where the device has no torch;
    /// the torch dies with the session.
    fn set_torch(&self, _on: bool) -> bool {
        false
    }

    /// The devices the application may pick between, back cameras first and in
    /// field-of-view order, widest first, then the rest.
    ///
    /// An empty list means the application shows no lens control: either the
    /// platform has one camera or the backend does not list them. Backends
    /// also publish this through [`publish_camera_lenses`] when a session
    /// opens, so a screen observes [`rememberCameraLenses`] rather than paying
    /// this blocking platform call per recomposition.
    fn lenses(&self) -> Vec<CameraLens> {
        Vec::new()
    }

    /// The device the session is using, or `None` when nothing is open and the
    /// backend has no stored choice.
    fn lens(&self) -> Option<String> {
        None
    }

    /// Opens `id` instead of the current device, keeping the session running.
    /// Returns `false` when the id is unknown or the backend cannot switch.
    fn use_lens(&self, _id: &str) -> bool {
        false
    }

    /// Whether the current device has a flash for stills.
    fn has_flash(&self) -> bool {
        false
    }

    /// What the flash does on the next still. Returns `false` where the device
    /// has no flash; the mode dies with the session.
    fn set_flash(&self, _mode: FlashMode) -> bool {
        false
    }
}

/// Shared handle to the platform camera.
pub type CameraRef = Arc<dyn Camera>;

static PLATFORM_CAMERA: ServiceRegistry<dyn Camera> = ServiceRegistry::new();

/// Installs the platform camera, replacing any previous one.
pub fn set_platform_camera(camera: CameraRef) {
    PLATFORM_CAMERA.set(camera);
}

/// Removes the platform camera and forgets everything the last session
/// published.
pub fn clear_platform_camera() {
    PLATFORM_CAMERA.clear();
    if let Ok(mut observers) = frame_observers().lock() {
        observers.clear();
    }
    if let Ok(mut observers) = state_observers().lock() {
        observers.clear();
    }
    if let Ok(mut observers) = still_observers().lock() {
        observers.clear();
    }
    if let Ok(mut observers) = lens_observers().lock() {
        observers.clear();
    }
    if let Ok(mut latest) = latest_frame_slot().lock() {
        *latest = None;
    }
    if let Ok(mut state) = state_slot().lock() {
        *state = CameraState::Idle;
    }
    if let Ok(mut lenses) = lenses_slot().lock() {
        *lenses = CameraLenses::default();
    }
    DROPPED_FRAMES.store(0, Ordering::Release);
}

/// The installed camera, or `None` where live capture is unsupported — which is
/// when an application falls back to the image picker.
pub fn camera() -> Option<CameraRef> {
    PLATFORM_CAMERA.get()
}

/// Whether this platform has a live camera at all.
pub fn camera_supported() -> bool {
    PLATFORM_CAMERA.get().is_some()
}

fn state_slot() -> &'static Mutex<CameraState> {
    static SLOT: OnceLock<Mutex<CameraState>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(CameraState::Idle))
}

fn latest_frame_slot() -> &'static Mutex<Option<CameraFrame>> {
    static SLOT: OnceLock<Mutex<Option<CameraFrame>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(None))
}

fn lenses_slot() -> &'static Mutex<CameraLenses> {
    static SLOT: OnceLock<Mutex<CameraLenses>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(CameraLenses::default()))
}

static DROPPED_FRAMES: AtomicU64 = AtomicU64::new(0);

type FrameObserver = Arc<dyn Fn(CameraFrame) + Send + Sync>;
type StateObserver = Arc<dyn Fn(CameraState) + Send + Sync>;
type StillObserver = Arc<dyn Fn(Result<CameraStill, CameraError>) + Send + Sync>;
type LensObserver = Arc<dyn Fn(CameraLenses) + Send + Sync>;

fn frame_observers() -> &'static Mutex<Vec<(u64, FrameObserver)>> {
    static SLOT: OnceLock<Mutex<Vec<(u64, FrameObserver)>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(Vec::new()))
}

fn state_observers() -> &'static Mutex<Vec<(u64, StateObserver)>> {
    static SLOT: OnceLock<Mutex<Vec<(u64, StateObserver)>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(Vec::new()))
}

fn still_observers() -> &'static Mutex<Vec<(u64, StillObserver)>> {
    static SLOT: OnceLock<Mutex<Vec<(u64, StillObserver)>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(Vec::new()))
}

fn lens_observers() -> &'static Mutex<Vec<(u64, LensObserver)>> {
    static SLOT: OnceLock<Mutex<Vec<(u64, LensObserver)>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(Vec::new()))
}

static NEXT_OBSERVER: AtomicU64 = AtomicU64::new(1);

/// Keeps a camera observer registered until it is dropped.
pub struct CameraObserver {
    id: u64,
    kind: ObserverKind,
}

#[derive(Clone, Copy)]
enum ObserverKind {
    Frame,
    State,
    Still,
    Lenses,
}

impl Drop for CameraObserver {
    fn drop(&mut self) {
        match self.kind {
            ObserverKind::Frame => retain_without(frame_observers(), self.id),
            ObserverKind::State => retain_without(state_observers(), self.id),
            ObserverKind::Still => retain_without(still_observers(), self.id),
            ObserverKind::Lenses => retain_without(lens_observers(), self.id),
        }
    }
}

fn retain_without<T>(slot: &'static Mutex<Vec<(u64, T)>>, id: u64) {
    if let Ok(mut observers) = slot.lock() {
        observers.retain(|(observer, _)| *observer != id);
    }
}

fn snapshot<T: Clone>(slot: &'static Mutex<Vec<(u64, T)>>) -> Vec<T> {
    slot.lock()
        .map(|observers| {
            observers
                .iter()
                .map(|(_, observer)| observer.clone())
                .collect()
        })
        .unwrap_or_default()
}

/// The last frame the session produced, or `None` before the first one.
///
/// Read outside composition — during draw — so a viewfinder shows the newest
/// frame without a recomposition per frame.
pub fn latest_camera_frame() -> Option<CameraFrame> {
    latest_frame_slot()
        .lock()
        .map_or(None, |frame| frame.clone())
}

/// What the session is doing.
pub fn camera_state() -> CameraState {
    state_slot()
        .lock()
        .map(|state| state.clone())
        .unwrap_or_default()
}

/// How many frames were produced while every observer was still busy.
pub fn dropped_camera_frames() -> u64 {
    DROPPED_FRAMES.load(Ordering::Acquire)
}

/// Publishes a frame. Backends call this from whichever thread the platform
/// delivers frames on.
///
/// The newest frame always replaces the stored one, so a viewfinder never draws
/// a stale frame; observers that are keeping up see every frame, and one that
/// is not is counted in [`dropped_camera_frames`] rather than queued behind.
pub fn publish_camera_frame(frame: CameraFrame) {
    if let Ok(mut latest) = latest_frame_slot().lock() {
        *latest = Some(frame.clone());
    }
    let observers = snapshot(frame_observers());
    if observers.is_empty() {
        return;
    }
    for observer in observers {
        observer(frame.clone());
    }
}

/// Records that the platform produced a frame nobody could take.
///
/// A backend running a bounded analysis queue calls this when it drops one, so
/// the count reflects what the device produced rather than what got through.
pub fn record_dropped_camera_frame() {
    DROPPED_FRAMES.fetch_add(1, Ordering::AcqRel);
}

/// Publishes what the session is doing.
pub fn publish_camera_state(state: CameraState) {
    {
        let Ok(mut current) = state_slot().lock() else {
            return;
        };
        if *current == state {
            return;
        }
        *current = state.clone();
    }
    if matches!(state, CameraState::Idle | CameraState::Starting) {
        DROPPED_FRAMES.store(0, Ordering::Release);
        if let Ok(mut latest) = latest_frame_slot().lock() {
            *latest = None;
        }
    }
    for observer in snapshot(state_observers()) {
        observer(state.clone());
    }
}

/// Publishes the answer to a still request.
pub fn publish_camera_still(still: Result<CameraStill, CameraError>) {
    for observer in snapshot(still_observers()) {
        observer(still.clone());
    }
}

/// Publishes the lens list and the device in use. Backends call this when a
/// session opens and when the device changes.
pub fn publish_camera_lenses(lenses: CameraLenses) {
    {
        let Ok(mut current) = lenses_slot().lock() else {
            return;
        };
        if *current == lenses {
            return;
        }
        *current = lenses.clone();
    }
    for observer in snapshot(lens_observers()) {
        observer(lenses.clone());
    }
}

/// The devices the application may pick between, as the backend last published
/// them.
pub fn camera_lenses() -> CameraLenses {
    lenses_slot()
        .lock()
        .map(|lenses| lenses.clone())
        .unwrap_or_default()
}

/// Registers `observer` for frames. Applications collect
/// [`rememberCameraFrames`] instead of calling this.
pub fn observe_camera_frames(
    observer: impl Fn(CameraFrame) + Send + Sync + 'static,
) -> CameraObserver {
    let id = NEXT_OBSERVER.fetch_add(1, Ordering::Relaxed);
    if let Ok(mut observers) = frame_observers().lock() {
        observers.push((id, Arc::new(observer)));
    }
    CameraObserver {
        id,
        kind: ObserverKind::Frame,
    }
}

/// Registers `observer` for session state. The current state is delivered at
/// once, so a screen composed mid-session shows what is happening rather than
/// waiting for the next change.
pub fn observe_camera_state(
    observer: impl Fn(CameraState) + Send + Sync + 'static,
) -> CameraObserver {
    let id = NEXT_OBSERVER.fetch_add(1, Ordering::Relaxed);
    let observer: StateObserver = Arc::new(observer);
    if let Ok(mut observers) = state_observers().lock() {
        observers.push((id, Arc::clone(&observer)));
    }
    observer(camera_state());
    CameraObserver {
        id,
        kind: ObserverKind::State,
    }
}

/// Registers `observer` for stills.
pub fn observe_camera_stills(
    observer: impl Fn(Result<CameraStill, CameraError>) + Send + Sync + 'static,
) -> CameraObserver {
    let id = NEXT_OBSERVER.fetch_add(1, Ordering::Relaxed);
    if let Ok(mut observers) = still_observers().lock() {
        observers.push((id, Arc::new(observer)));
    }
    CameraObserver {
        id,
        kind: ObserverKind::Still,
    }
}

/// Registers `observer` for the lens list. The current list is delivered at
/// once, so a screen composed mid-session shows the devices rather than
/// waiting for the next change.
pub fn observe_camera_lenses(
    observer: impl Fn(CameraLenses) + Send + Sync + 'static,
) -> CameraObserver {
    let id = NEXT_OBSERVER.fetch_add(1, Ordering::Relaxed);
    let observer: LensObserver = Arc::new(observer);
    if let Ok(mut observers) = lens_observers().lock() {
        observers.push((id, Arc::clone(&observer)));
    }
    observer(camera_lenses());
    CameraObserver {
        id,
        kind: ObserverKind::Lenses,
    }
}

/// What the camera session is doing, observed for as long as this call stays in
/// the composition.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberCameraState() -> State<CameraState> {
    let updates = rememberEventStream((), |sender| {
        observe_camera_state(move |state| sender.send(state))
    });
    cranpose_core::collectAsState(updates, (), camera_state())
}

/// The frames the session produces, as a stream this composition collects.
///
/// This is the analysis path: a detector collects it, and one that cannot keep
/// up falls behind by frames rather than by memory — see
/// [`dropped_camera_frames`]. A viewfinder draws [`latest_camera_frame`]
/// instead, which costs no recomposition at all.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberCameraFrames() -> EventStream<CameraFrame> {
    rememberEventStream((), |sender| {
        observe_camera_frames(move |frame| sender.send(frame))
    })
}

/// The stills the session produces, as a stream this composition collects.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberCameraStills() -> EventStream<Result<CameraStill, CameraError>> {
    rememberEventStream((), |sender| {
        observe_camera_stills(move |still| sender.send(still))
    })
}

/// The lens list and the device in use, observed for as long as this call
/// stays in the composition.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberCameraLenses() -> State<CameraLenses> {
    let updates = rememberEventStream((), |sender| {
        observe_camera_lenses(move |lenses| sender.send(lenses))
    });
    cranpose_core::collectAsState(updates, (), camera_lenses())
}

/// Starts the camera, publishing [`CameraState::Starting`] before the backend
/// is asked so a screen shows the wait rather than a gap.
pub fn start_camera() -> Result<(), CameraError> {
    let Some(camera) = camera() else {
        publish_camera_state(CameraState::Failed(CameraError::Unsupported));
        return Err(CameraError::Unsupported);
    };
    publish_camera_state(CameraState::Starting);
    camera.start().inspect_err(|error| {
        publish_camera_state(CameraState::Failed(error.clone()));
    })
}

/// Stops the camera and releases the device.
pub fn stop_camera() {
    if let Some(camera) = camera() {
        camera.stop();
    }
    publish_camera_state(CameraState::Stopped);
}

/// Asks for a full-resolution still, which arrives through
/// [`rememberCameraStills`].
pub fn request_camera_still() -> Result<(), CameraError> {
    let Some(camera) = camera() else {
        return Err(CameraError::Unsupported);
    };
    if !camera_state().is_running() {
        return Err(CameraError::NotRunning);
    }
    camera.request_still()
}

/// Takes one full-resolution still and resolves with it.
///
/// [`request_camera_still`] asks and [`observe_camera_stills`] answers, which is
/// the right shape for a screen that keeps a shutter open. A caller that wants
/// one photograph wants the two joined, and joining them by hand means holding
/// an observer alive across an await in every application that takes a picture.
///
/// The observer is dropped as soon as a still arrives, so a second capture is a
/// second call rather than a subscription to unregister.
pub async fn capture_camera_still() -> Result<CameraStill, CameraError> {
    let signal = crate::async_io::Signal::new();
    let deliver = signal.clone();
    let observer = observe_camera_stills(move |result| deliver.set(result));
    request_camera_still()?;
    let arrived = signal.wait().await;
    drop(observer);
    arrived.unwrap_or(Err(CameraError::NotRunning))
}

#[cfg(test)]
#[path = "tests/camera_tests.rs"]
mod tests;