1
//! Camera-preview widget - a "dumb widget" (like [`MapWidget`](super::map))
2
//! that owns a background capture thread + a GL-texture `ImageRef`, with **no**
3
//! camera-specific logic in the core framework (SUPER_PLAN_2 ยง4 P6, widget
4
//! pivot - see the MASTER PLAN in `MOBILE_SESSION_LOG.md`).
5
//!
6
//! `CameraWidget::create(config).dom()` -> a static `<img>` whose pixels a
7
//! background thread keeps fed. On `AfterMount` the capture thread starts
8
//! (`CallbackInfo::add_thread`); each frame goes through
9
//! [`super::capture_common::present_frame`], which uploads it into a stable
10
//! external GL texture + recomposites - no relayout, no display-list rebuild.
11
//! The shared thread/writeback/GL core lives in `capture_common`; this widget
12
//! is just its config + worker.
13
//!
14
//! ONE CAPTURE, MANY CONSUMERS. The camera is opened at the smallest size
15
//! that covers everyone who wants frames โ€” the on-screen tile (its device
16
//! size, reported by layout through `NodeResized`), every
17
//! [`FrameConsumer`] registered with [`CameraWidget::with_consumer`] ("client
18
//! Bob wants 500x200"), and the configured size when an `on_frame` hook
19
//! wants the frame as captured. Each captured frame is cut to every
20
//! consumer's size OFF the main thread (`capture_common::run_capture_loop`
21
//! + `image_scale::fan_out`) and delivered through
22
//! [`CameraWidget::with_on_consumer_frame`]; the tile gets a frame at
23
//! exactly its own size. Without a platform backend a colour-cycle test
24
//! pattern runs through the same loop.
25

            
26
use alloc::vec::Vec;
27

            
28
use azul_core::{
29
    callbacks::Update,
30
    camera::CameraConfig,
31
    dom::{ComponentEventFilter, DatasetMergeCallbackType, Dom, EventFilter},
32
    refany::{OptionRefAny, RefAny},
33
    resources::{ImageRef, RawImageFormat},
34
    task::{ThreadId, ThreadReceiver, ThreadSendMsg},
35
    video::{FrameConsumer, FrameConsumerVec},
36
};
37
use azul_css::AzString;
38

            
39
use super::capture_common::{
40
    camera_backend, frame_resampler, present_captured, preview_size_for_node, run_capture_loop,
41
    send_capture_targets, test_pattern_vtable, CaptureRequest, CaptureSession, CaptureTargets,
42
    CapturedFrames, OnConsumerFrame, OnConsumerFrameCallback, OnVideoFrame, OnVideoFrameCallback,
43
    OptionOnConsumerFrame, OptionOnVideoFrame, TestPattern, REOPEN_COOLDOWN_MS,
44
};
45
use crate::{
46
    callbacks::{Callback, CallbackInfo, CallbackType},
47
    thread::{Thread, ThreadCallback, ThreadSender},
48
};
49

            
50
/// Init data handed to the capture worker thread.
51
struct CameraThreadInit {
52
    /// Camera device index.
53
    index: u32,
54
    /// Requested frame rate (0 = backend default).
55
    fps: u32,
56
    /// The size to capture when nothing else is known (`frame_dims`).
57
    width: u32,
58
    /// See `width`.
59
    height: u32,
60
    /// The size the capture never drops below (see [`capture_floor`]).
61
    floor: Option<(u32, u32)>,
62
    /// Who wants frames at mount time (the tile's size if already laid out,
63
    /// the registered consumers, whether the `on_frame` hook is set).
64
    targets: CaptureTargets,
65
}
66

            
67
impl CameraThreadInit {
68
    /// An init with only a size (the test pattern's size without a backend).
69
3
    const fn sized(width: u32, height: u32) -> Self {
70
3
        Self {
71
3
            index: 0,
72
3
            fps: 0,
73
3
            width,
74
3
            height,
75
3
            floor: None,
76
3
            targets: CaptureTargets {
77
3
                preview: None,
78
3
                consumers: Vec::new(),
79
3
                wants_source: false,
80
3
            },
81
3
        }
82
3
    }
83
}
84

            
85
/// Live state for one camera widget, carried across relayout by
86
/// [`merge_camera_state`].
87
#[derive(Debug)]
88
pub struct CameraWidgetState {
89
    /// The requested capture configuration (the control POD).
90
    pub config: CameraConfig,
91
    /// `true` once the capture thread has been started.
92
    pub started: bool,
93
    /// The stable external GL texture id once the first frame installed it.
94
    pub gl_texture_id: Option<u32>,
95
    /// Optional user hook invoked with each captured frame (effects / save /
96
    /// send). Re-set on every fresh build (see [`merge_camera_state`]).
97
    pub on_frame: OptionOnVideoFrame,
98
    /// Every registered consumer (see [`FrameConsumer`]). Re-set on every
99
    /// fresh build; a change is pushed to the running worker.
100
    pub consumers: FrameConsumerVec,
101
    /// Optional hook receiving every consumer's cut of every frame.
102
    pub on_consumer_frame: OptionOnConsumerFrame,
103
    /// The MARKER stamped on the tile node (`Dom::with_marker`); the frame
104
    /// writeback resolves it back to the node via
105
    /// `CallbackInfo::get_node_id_by_marker`. Adopted forward on merge so the
106
    /// persistent allocation always names the CURRENT build's node.
107
    pub marker: AzString,
108
    /// The capture worker, once started (`NodeResized` messages it).
109
    pub thread_id: Option<ThreadId>,
110
    /// The main->worker sender, cloned at mount so the merge callback (which
111
    /// has no `CallbackInfo`) can push a changed consumer list.
112
    pub control: Option<std::sync::mpsc::Sender<ThreadSendMsg>>,
113
    /// The tile's last reported device size (so a resize that does not change
114
    /// it sends nothing).
115
    pub preview: Option<(u32, u32)>,
116
}
117

            
118
impl CameraWidgetState {
119
    /// The worker's view of who wants frames, from this state.
120
    #[must_use]
121
3
    pub fn targets(&self) -> CaptureTargets {
122
3
        CaptureTargets {
123
3
            preview: self.preview,
124
3
            consumers: self.consumers.as_ref().to_vec(),
125
3
            wants_source: self.on_frame.is_some(),
126
3
        }
127
3
    }
128
}
129

            
130
/// A camera-preview widget. `create(config).dom()` yields an `<img>` the
131
/// capture thread keeps fed.
132
#[repr(C)]
133
#[derive(Debug)]
134
pub struct CameraWidget {
135
    /// Requested capture config (camera facing, resolution, fps, format).
136
    pub config: CameraConfig,
137
    /// Optional per-frame user hook (effects / save / send - azul-meet).
138
    pub on_frame: OptionOnVideoFrame,
139
    /// Consumers of the captured frames beyond the on-screen tile: each gets
140
    /// its own cut of every frame at its requested size.
141
    pub consumers: FrameConsumerVec,
142
    /// Optional hook receiving each consumer's cut (see `consumers`).
143
    pub on_consumer_frame: OptionOnConsumerFrame,
144
}
145

            
146
impl CameraWidget {
147
    /// Create a camera widget for the given capture config.
148
    #[must_use]
149
19
    pub const fn create(config: CameraConfig) -> Self {
150
19
        Self {
151
19
            config,
152
19
            on_frame: OptionOnVideoFrame::None,
153
19
            consumers: FrameConsumerVec::from_const_slice(&[]),
154
19
            on_consumer_frame: OptionOnConsumerFrame::None,
155
19
        }
156
19
    }
157

            
158
    /// Register a consumer of the captured frames: every frame is cut to
159
    /// `consumer`'s size (off the main thread) and handed to the
160
    /// `on_consumer_frame` hook with `consumer.id`. The camera is opened at
161
    /// the smallest size covering every consumer and the tile, so "client
162
    /// Bob wants 500x200 while the local preview is 100x200" captures ONE
163
    /// 500x200 frame and samples it twice - nothing larger is captured, and
164
    /// nothing larger than asked is sent. A consumer with a zero size or the
165
    /// reserved preview id 0 is ignored.
166
5
    pub fn add_consumer(&mut self, consumer: FrameConsumer) {
167
5
        let mut all: Vec<FrameConsumer> = self.consumers.as_ref().to_vec();
168
5
        all.retain(|c| c.id != consumer.id);
169
5
        all.push(consumer);
170
5
        self.consumers = all.into();
171
5
    }
172

            
173
    /// Builder form of [`add_consumer`](Self::add_consumer).
174
    #[must_use]
175
5
    pub fn with_consumer(mut self, consumer: FrameConsumer) -> Self {
176
5
        self.add_consumer(consumer);
177
5
        self
178
5
    }
179

            
180
    /// Set the hook that receives every consumer's cut of every captured
181
    /// frame (route on `frame.consumer.id`; send Bob his, record the other).
182
1
    pub fn set_on_consumer_frame<C: Into<OnConsumerFrameCallback>>(
183
1
        &mut self,
184
1
        data: RefAny,
185
1
        on_consumer_frame: C,
186
1
    ) {
187
1
        self.on_consumer_frame = Some(OnConsumerFrame {
188
1
            refany: data,
189
1
            callback: on_consumer_frame.into(),
190
1
        })
191
1
        .into();
192
1
    }
193

            
194
    /// Builder form of [`set_on_consumer_frame`](Self::set_on_consumer_frame).
195
    #[must_use]
196
1
    pub fn with_on_consumer_frame<C: Into<OnConsumerFrameCallback>>(
197
1
        mut self,
198
1
        data: RefAny,
199
1
        on_consumer_frame: C,
200
1
    ) -> Self {
201
1
        self.set_on_consumer_frame(data, on_consumer_frame);
202
1
        self
203
1
    }
204

            
205
    /// Set a hook invoked with every captured frame - for live effects, saving
206
    /// frames into your data model, or sending them over the network
207
    /// (azul-meet).
208
4
    pub fn set_on_frame<C: Into<OnVideoFrameCallback>>(&mut self, data: RefAny, on_frame: C) {
209
4
        self.on_frame = Some(OnVideoFrame {
210
4
            refany: data,
211
4
            callback: on_frame.into(),
212
4
        })
213
4
        .into();
214
4
    }
215

            
216
    /// Builder form of [`set_on_frame`](Self::set_on_frame).
217
    #[must_use]
218
2
    pub fn with_on_frame<C: Into<OnVideoFrameCallback>>(
219
2
        mut self,
220
2
        data: RefAny,
221
2
        on_frame: C,
222
2
    ) -> Self {
223
2
        self.set_on_frame(data, on_frame);
224
2
        self
225
2
    }
226

            
227
    /// Build the widget's DOM: a single `<img>` node, fed by a background
228
    /// capture thread started on mount.
229
    #[must_use]
230
8
    pub fn dom(self) -> Dom {
231
8
        let marker = super::capture_common::next_capture_marker("camera");
232
8
        let state = CameraWidgetState {
233
8
            config: self.config,
234
8
            started: false,
235
8
            gl_texture_id: None,
236
8
            on_frame: self.on_frame,
237
8
            consumers: self.consumers,
238
8
            on_consumer_frame: self.on_consumer_frame,
239
8
            marker: marker.clone(),
240
8
            thread_id: None,
241
8
            control: None,
242
8
            preview: None,
243
8
        };
244
8
        let dataset = RefAny::new(state);
245

            
246
8
        let (w, h) = frame_dims(&self.config);
247
8
        let placeholder = ImageRef::null_image(
248
8
            w as usize,
249
8
            h as usize,
250
8
            RawImageFormat::BGRA8,
251
8
            b"azul-camera-placeholder".to_vec(),
252
        );
253

            
254
8
        Dom::create_image(placeholder)
255
8
            .with_dataset(OptionRefAny::Some(dataset.clone()))
256
8
            .with_marker(Some(marker).into())
257
8
            .with_merge_callback(azul_core::dom::DatasetMergeCallback::from_ptr(merge_camera_state))
258
8
            .with_callback(
259
8
                EventFilter::Component(ComponentEventFilter::AfterMount),
260
8
                dataset.clone(),
261
8
                Callback::from_ptr(camera_on_after_mount),
262
            )
263
            // The tile's device size feeds the capture size + the preview
264
            // cut โ€” see `camera_on_resize`.
265
8
            .with_callback(
266
8
                EventFilter::Component(ComponentEventFilter::NodeResized),
267
8
                dataset,
268
8
                Callback::from_ptr(camera_on_resize),
269
            )
270
8
    }
271
}
272

            
273
/// Frame dimensions for a config (0 -> a sane default).
274
27
const fn frame_dims(config: &CameraConfig) -> (u32, u32) {
275
27
    let w = if config.width > 0 { config.width } else { 640 };
276
27
    let h = if config.height > 0 {
277
9
        config.height
278
    } else {
279
18
        480
280
    };
281
27
    (w, h)
282
27
}
283

            
284
/// The size the capture never drops below: the configured size when the app
285
/// set one explicitly (either axis), or the default when an `on_frame` hook
286
/// expects frames as the config promised. `None` otherwise โ€” then the tile
287
/// and the consumers alone decide, and a 300x200 tile captures 300x200.
288
4
const fn capture_floor(config: &CameraConfig, wants_source: bool) -> Option<(u32, u32)> {
289
4
    if config.width > 0 || config.height > 0 || wants_source {
290
3
        Some(frame_dims(config))
291
    } else {
292
1
        None
293
    }
294
4
}
295

            
296
/// `AfterMount`: start the background capture thread exactly once, telling
297
/// it who wants frames (the tile's size if layout already produced one).
298
2
extern "C" fn camera_on_after_mount(mut data: RefAny, mut info: CallbackInfo) -> Update {
299
2
    let preview = preview_size_for_node(&info);
300
    let init = {
301
2
        let Some(mut s) = data.downcast_mut::<CameraWidgetState>() else {
302
1
            return Update::DoNothing;
303
        };
304
1
        if s.started {
305
1
            return Update::DoNothing;
306
        }
307
        s.started = true;
308
        s.preview = preview;
309
        let (width, height) = frame_dims(&s.config);
310
        CameraThreadInit {
311
            index: 0,
312
            fps: s.config.fps,
313
            width,
314
            height,
315
            floor: capture_floor(&s.config, s.on_frame.is_some()),
316
            targets: s.targets(),
317
        }
318
    };
319

            
320
    let tid = ThreadId::unique();
321
    let thread = Thread::create(
322
        RefAny::new(init),
323
        data.clone(),
324
        ThreadCallback::new(camera_worker),
325
    );
326
    // Grab the main->worker sender BEFORE add_thread moves the Thread, so the
327
    // merge callback can push a changed consumer list without a CallbackInfo.
328
    let control = thread.clone_sender();
329
    info.add_thread(tid, thread);
330
    if let Some(mut s) = data.downcast_mut::<CameraWidgetState>() {
331
        s.thread_id = Some(tid);
332
        s.control = control;
333
    }
334
    Update::DoNothing
335
2
}
336

            
337
/// `NodeResized`: the tile's device size changed โ€” tell the worker, which
338
/// cuts the preview at the new size and reopens the camera smaller/larger
339
/// when that pays (see `capture_common::needs_reopen`). A message, not a
340
/// relayout: returns `DoNothing`.
341
1
extern "C" fn camera_on_resize(mut data: RefAny, info: CallbackInfo) -> Update {
342
1
    let Some(preview) = preview_size_for_node(&info) else {
343
1
        return Update::DoNothing;
344
    };
345
    let (tid, targets) = {
346
        let Some(mut s) = data.downcast_mut::<CameraWidgetState>() else {
347
            return Update::DoNothing;
348
        };
349
        if s.preview == Some(preview) {
350
            return Update::DoNothing;
351
        }
352
        s.preview = Some(preview);
353
        (s.thread_id, s.targets())
354
    };
355
    if let Some(tid) = tid {
356
        // Best effort: a worker that already exited has nothing to resize.
357
        send_capture_targets(&info, tid, targets);
358
    }
359
    Update::DoNothing
360
1
}
361

            
362
/// Background worker: the shared capture loop over the registered camera
363
/// backend (v4l2 / `AVFoundation` / Media Foundation / Camera2), else the
364
/// colour-cycle test pattern โ€” see `capture_common::run_capture_loop`.
365
3
extern "C" fn camera_worker(mut init: RefAny, mut sender: ThreadSender, mut recv: ThreadReceiver) {
366
3
    let (targets, session) = match init.downcast_ref::<CameraThreadInit>() {
367
2
        Some(i) => (
368
2
            i.targets.clone(),
369
2
            camera_session(i.index, i.fps, (i.width, i.height), i.floor),
370
2
        ),
371
1
        None => (
372
1
            CaptureTargets::default(),
373
1
            camera_session(0, 0, (640, 480), None),
374
1
        ),
375
    };
376
3
    run_capture_loop(session, targets, &mut sender, &mut recv);
377
3
}
378

            
379
/// The camera's capture session: platform backend + colour-cycle fallback.
380
3
fn camera_session(
381
3
    index: u32,
382
3
    fps: u32,
383
3
    fallback: (u32, u32),
384
3
    floor: Option<(u32, u32)>,
385
3
) -> CaptureSession {
386
3
    CaptureSession {
387
3
        backend: camera_backend(),
388
3
        test_pattern: test_pattern_vtable(TestPattern::ColourCycle),
389
3
        request: CaptureRequest {
390
3
            index,
391
3
            window: 0,
392
3
            width: 0,
393
3
            height: 0,
394
3
            fps,
395
3
            exclude_self: false,
396
3
        },
397
3
        floor,
398
3
        fallback,
399
3
        writeback: camera_writeback,
400
3
        resample: frame_resampler(),
401
3
        reopen_cooldown_ms: REOPEN_COOLDOWN_MS,
402
3
    }
403
3
}
404

            
405
/// Writeback (main thread): run the hooks and put the preview cut (else the
406
/// captured frame) on the node โ€” `capture_common::present_captured`.
407
6
extern "C" fn camera_writeback(
408
6
    mut writeback_data: RefAny,
409
6
    mut frame_data: RefAny,
410
6
    mut info: CallbackInfo,
411
6
) -> Update {
412
6
    let (on_frame, on_consumer_frame, marker) = writeback_data
413
6
        .downcast_ref::<CameraWidgetState>()
414
6
        .map_or_else(
415
1
            || {
416
1
                (
417
1
                    OptionOnVideoFrame::None,
418
1
                    OptionOnConsumerFrame::None,
419
1
                    AzString::from_const_str(""),
420
1
                )
421
1
            },
422
5
            |s| {
423
5
                (
424
5
                    s.on_frame.clone(),
425
5
                    s.on_consumer_frame.clone(),
426
5
                    s.marker.clone(),
427
5
                )
428
5
            },
429
        );
430
6
    let Some(mut captured) = frame_data.downcast_mut::<CapturedFrames>() else {
431
1
        return Update::DoNothing;
432
    };
433
5
    present_captured(
434
5
        &mut info,
435
5
        marker,
436
5
        &on_frame,
437
5
        &on_consumer_frame,
438
5
        &mut captured,
439
    )
440
6
}
441

            
442
/// Carry live state forward across relayout (config from the fresh build,
443
/// thread / texture from the previous frame).
444
6
extern "C" fn merge_camera_state(mut new_data: RefAny, mut old_data: RefAny) -> RefAny {
445
    // Return the OLD allocation (the one live capture backends may hold a
446
    // clone of), adopting config forward โ€” the merge_map_tile_cache rule.
447
    // Returning new_data would re-point the DOM at a fresh allocation the
448
    // running worker's writeback clone never sees.
449
6
    let merged_into_old = {
450
6
        let new_guard = new_data.downcast_ref::<CameraWidgetState>();
451
6
        let old_guard = old_data.downcast_mut::<CameraWidgetState>();
452
6
        if let (Some(new_g), Some(mut old_g)) = (new_guard, old_guard) {
453
3
            let worker_cares = old_g.consumers != new_g.consumers
454
2
                || old_g.on_frame.is_some() != new_g.on_frame.is_some();
455
3
            old_g.config = new_g.config;
456
3
            old_g.on_frame = new_g.on_frame.clone();
457
3
            old_g.consumers = new_g.consumers.clone();
458
3
            old_g.on_consumer_frame = new_g.on_consumer_frame.clone();
459
            // The reconciled NODE carries the NEW build's marker string, so
460
            // the surviving allocation must resolve by that string too.
461
3
            old_g.marker = new_g.marker.clone();
462
            // A changed consumer list / hook presence reaches the RUNNING
463
            // worker now (it reopens or refans as needed) โ€” there is no
464
            // CallbackInfo here, hence the cloned sender.
465
3
            if worker_cares {
466
2
                let targets = old_g.targets();
467
2
                if let Some(snd) = old_g.control.as_ref() {
468
1
                    drop(snd.send(ThreadSendMsg::Custom(RefAny::new(targets))));
469
1
                }
470
1
            }
471
3
            true
472
        } else {
473
            // Foreign / mismatched payloads (one side is not this widget's
474
            // state): hand back the NEW payload untouched โ€” there is no
475
            // persistent allocation to preserve, and returning a
476
            // wrong-typed old dataset would poison the node.
477
3
            false
478
        }
479
    };
480
6
    if merged_into_old {
481
3
        old_data
482
    } else {
483
3
        new_data
484
    }
485
6
}
486

            
487
// ============================================================================
488
// Generated adversarial tests
489
// ============================================================================
490

            
491
#[cfg(test)]
492
#[allow(clippy::too_many_lines, clippy::cast_possible_truncation)]
493
mod autotest_generated {
494
    use std::{
495
        collections::BTreeMap,
496
        sync::{
497
            mpsc::{channel, Receiver, Sender},
498
            Arc, Mutex,
499
        },
500
    };
501

            
502
    use azul_core::{
503
        camera::CameraFacing,
504
        dom::{DomId, DomNodeId, NodeType},
505
        geom::OptionLogicalPosition,
506
        gl::OptionGlContextPtr,
507
        hit_test::ScrollPosition,
508
        resources::{DecodedImage, RendererResources},
509
        styled_dom::NodeHierarchyItemId,
510
        task::{
511
            OptionThreadSendMsg, ThreadReceiverDestructorCallback, ThreadReceiverInner,
512
            ThreadRecvCallback, ThreadSendMsg,
513
        },
514
        video::{ConsumerFrame, VideoFrame},
515
        window::{MonitorVec, RawWindowHandle},
516
    };
517
    use azul_css::system::SystemStyle;
518
    use rust_fontconfig::FcFontCache;
519

            
520
    use super::*;
521
    #[cfg(feature = "icu")]
522
    use crate::icu::IcuLocalizerHandle;
523
    use crate::{
524
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
525
        thread::{
526
            ThreadReceiveMsg, ThreadSendCallback, ThreadSenderDestructorCallback, ThreadSenderInner,
527
        },
528
        widgets::capture_common::{OnConsumerFrameCallbackType, OnVideoFrameCallbackType},
529
        window::LayoutWindow,
530
        window_state::FullWindowState,
531
    };
532

            
533
    // ------------------------------------------------------------------
534
    // Helpers
535
    // ------------------------------------------------------------------
536

            
537
    const ALL_FACINGS: [CameraFacing; 3] = [
538
        CameraFacing::Front,
539
        CameraFacing::Back,
540
        CameraFacing::External,
541
    ];
542

            
543
    /// A config with explicit dimensions (everything else fixed).
544
    fn cfg(width: u32, height: u32) -> CameraConfig {
545
        CameraConfig {
546
            facing: CameraFacing::Front,
547
            width,
548
            height,
549
            fps: 30,
550
            output_format: RawImageFormat::BGRA8,
551
        }
552
    }
553

            
554
    /// A `CameraWidgetState` payload with no `on_frame` hook.
555
    fn state(config: CameraConfig, started: bool, gl_texture_id: Option<u32>) -> RefAny {
556
        RefAny::new(CameraWidgetState {
557
            config,
558
            started,
559
            gl_texture_id,
560
            on_frame: OptionOnVideoFrame::None,
561
            consumers: FrameConsumerVec::from_const_slice(&[]),
562
            on_consumer_frame: OptionOnConsumerFrame::None,
563
            marker: "azul-camera-test".into(),
564
            thread_id: None,
565
            control: None,
566
            preview: None,
567
        })
568
    }
569

            
570
    /// The writeback payload the worker queues for one captured `frame`
571
    /// (no preview cut, no consumers) โ€” what `run_capture_loop` sends when
572
    /// the tile's size is unknown.
573
    fn captured(frame: VideoFrame) -> RefAny {
574
        RefAny::new(CapturedFrames {
575
            source: Some(frame),
576
            preview: None,
577
            consumers: Vec::new(),
578
            in_flight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
579
        })
580
    }
581

            
582
    /// `(config, started, gl_texture_id, has_hook)` of a `CameraWidgetState` payload.
583
    fn read_state(data: &mut RefAny) -> (CameraConfig, bool, Option<u32>, bool) {
584
        let s = data
585
            .downcast_ref::<CameraWidgetState>()
586
            .expect("payload must still be a CameraWidgetState");
587
        (
588
            s.config,
589
            s.started,
590
            s.gl_texture_id,
591
            matches!(s.on_frame, OptionOnVideoFrame::Some(_)),
592
        )
593
    }
594

            
595
    /// The placeholder image behind an `<img>` `Dom` root: `(width, height, format, tag)`.
596
    fn placeholder_of(dom: &Dom) -> (usize, usize, RawImageFormat, Vec<u8>) {
597
        let NodeType::Image(image) = dom.root.get_node_type() else {
598
            panic!("CameraWidget::dom must build an image node");
599
        };
600
        match image.get_data() {
601
            DecodedImage::NullImage {
602
                width,
603
                height,
604
                format,
605
                tag,
606
            } => (*width, *height, *format, tag.clone()),
607
            _ => panic!("the placeholder must be a NullImage (no decode, no allocation)"),
608
        }
609
    }
610

            
611
    // ---- frame hook -------------------------------------------------------
612

            
613
    /// Records every frame a widget's `on_frame` hook is handed.
614
    struct FrameLog {
615
        seen: Vec<(u32, u32, usize)>,
616
    }
617

            
618
    extern "C" fn record_frame(mut data: RefAny, _: CallbackInfo, frame: VideoFrame) -> Update {
619
        if let Some(mut log) = data.downcast_mut::<FrameLog>() {
620
            log.seen
621
                .push((frame.width, frame.height, frame.bytes.as_ref().len()));
622
        }
623
        Update::RefreshDom
624
    }
625

            
626
    extern "C" fn frame_do_nothing(_: RefAny, _: CallbackInfo, _: VideoFrame) -> Update {
627
        Update::DoNothing
628
    }
629

            
630
    /// The frames recorded by a `FrameLog` payload.
631
    fn logged_frames(data: &mut RefAny) -> Vec<(u32, u32, usize)> {
632
        data.downcast_ref::<FrameLog>()
633
            .expect("payload must still be a FrameLog")
634
            .seen
635
            .clone()
636
    }
637

            
638
    /// A `CameraWidgetState` whose `on_frame` hook writes into `log`.
639
    fn state_with_hook(config: CameraConfig, log: &RefAny) -> RefAny {
640
        RefAny::new(CameraWidgetState {
641
            config,
642
            started: true,
643
            gl_texture_id: None,
644
            on_frame: Some(OnVideoFrame {
645
                refany: log.clone(),
646
                callback: (record_frame as OnVideoFrameCallbackType).into(),
647
            })
648
            .into(),
649
            consumers: FrameConsumerVec::from_const_slice(&[]),
650
            on_consumer_frame: OptionOnConsumerFrame::None,
651
            marker: "azul-camera-test".into(),
652
            thread_id: None,
653
            control: None,
654
            preview: None,
655
        })
656
    }
657

            
658
    /// A tightly-packed RGBA frame (`width * height * 4` bytes).
659
    fn frame(width: u32, height: u32) -> VideoFrame {
660
        let px = (width as usize) * (height as usize);
661
        VideoFrame {
662
            width,
663
            height,
664
            bytes: vec![7u8; px * 4].into(),
665
        }
666
    }
667

            
668
    // ---- CallbackInfo harness --------------------------------------------
669

            
670
    /// Runs `f` against a real `CallbackInfo` over an empty `LayoutWindow` (no GL
671
    /// context -> the widgets' CPU present path). Returns `f`'s value plus every
672
    /// `CallbackChange` the callback recorded.
673
    fn with_callback_info<R>(f: impl FnOnce(CallbackInfo) -> R) -> (R, Vec<CallbackChange>) {
674
        let layout_window =
675
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
676
        let renderer_resources = RendererResources::default();
677
        let previous_window_state: Option<FullWindowState> = None;
678
        let current_window_state = FullWindowState::default();
679
        let gl_context = OptionGlContextPtr::None;
680
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
681
            BTreeMap::new();
682
        let window_handle = RawWindowHandle::Unsupported;
683
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
684

            
685
        let ref_data = CallbackInfoRefData {
686
            layout_window: &layout_window,
687
            renderer_resources: &renderer_resources,
688
            previous_window_state: &previous_window_state,
689
            current_window_state: &current_window_state,
690
            gl_context: &gl_context,
691
            current_scroll_manager: &scroll_states,
692
            current_window_handle: &window_handle,
693
            system_callbacks: &system_callbacks,
694
            system_style: Arc::new(SystemStyle::default()),
695
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
696
            #[cfg(feature = "icu")]
697
            icu_localizer: IcuLocalizerHandle::default(),
698
            ctx: OptionRefAny::None,
699
        };
700

            
701
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
702

            
703
        let info = CallbackInfo::new(
704
            &ref_data,
705
            &changes,
706
            DomNodeId {
707
                dom: DomId::ROOT_ID,
708
                node: NodeHierarchyItemId::NONE,
709
            },
710
            OptionLogicalPosition::None,
711
            OptionLogicalPosition::None,
712
        );
713

            
714
        let out = f(info);
715
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
716
        (out, recorded)
717
    }
718

            
719
    // ---- camera_worker harness -------------------------------------------
720

            
721
    /// Every frame `camera_worker` pushed: `(width, height, bytes, all pixels are the
722
    /// tick-0 colour)`. Guarded by `WORKER_GATE` - the worker's send callback is a
723
    /// plain C fn pointer, so it has nowhere else to put its result.
724
    static WORKER_LOG: Mutex<Vec<(u32, u32, usize, bool)>> = Mutex::new(Vec::new());
725
    static WORKER_GATE: Mutex<()> = Mutex::new(());
726

            
727
    /// Records the frame, then reports the send as *failed* - i.e. "the main thread is
728
    /// gone", the only signal `camera_worker` has to stop. A worker that ignores it
729
    /// would hang this test forever.
730
    extern "C" fn record_and_stop(
731
        _sender: *const core::ffi::c_void,
732
        msg: ThreadReceiveMsg,
733
    ) -> bool {
734
        if let ThreadReceiveMsg::WriteBack(mut wb) = msg {
735
            if let Some(c) = wb.refany.downcast_ref::<CapturedFrames>() {
736
                let Some(f) = c.preview.as_ref().or(c.source.as_ref()) else {
737
                    return false;
738
                };
739
                let bytes = f.bytes.as_ref();
740
                let tick0 = bytes.chunks_exact(4).all(|px| px == &[0u8, 0, 0, 255][..]);
741
                WORKER_LOG
742
                    .lock()
743
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
744
                    .push((f.width, f.height, bytes.len(), tick0));
745
            }
746
        }
747
        false
748
    }
749

            
750
    extern "C" fn sender_drop_noop(_: *mut ThreadSenderInner) {}
751
    extern "C" fn receiver_drop_noop(_: *mut ThreadReceiverInner) {}
752
    extern "C" fn recv_nothing(_: *const core::ffi::c_void) -> OptionThreadSendMsg {
753
        OptionThreadSendMsg::None
754
    }
755

            
756
    /// A `ThreadSender` whose every `send` is recorded and then rejected.
757
    fn stopped_sender() -> (Receiver<ThreadReceiveMsg>, ThreadSender) {
758
        let (tx, rx) = channel::<ThreadReceiveMsg>();
759
        let sender = ThreadSender::new(ThreadSenderInner {
760
            ptr: Box::new(tx),
761
            send_fn: ThreadSendCallback {
762
                cb: record_and_stop,
763
            },
764
            destructor: ThreadSenderDestructorCallback {
765
                cb: sender_drop_noop,
766
            },
767
        });
768
        (rx, sender)
769
    }
770

            
771
    /// A `ThreadReceiver` that never delivers anything (`camera_worker` ignores it).
772
    fn silent_receiver() -> (Sender<ThreadSendMsg>, ThreadReceiver) {
773
        let (tx, rx) = channel::<ThreadSendMsg>();
774
        let receiver = ThreadReceiver::new(ThreadReceiverInner {
775
            ptr: Box::new(rx),
776
            recv_fn: ThreadRecvCallback { cb: recv_nothing },
777
            destructor: ThreadReceiverDestructorCallback {
778
                cb: receiver_drop_noop,
779
            },
780
        });
781
        (tx, receiver)
782
    }
783

            
784
    /// Runs `camera_worker` with `init` against a sender that rejects the first frame,
785
    /// and returns everything the worker managed to send. `None` when a real platform
786
    /// backend is registered in this process (then the worker is not the test pattern
787
    /// these assertions describe).
788
    fn run_worker(init: RefAny) -> Option<Vec<(u32, u32, usize, bool)>> {
789
        let _gate = WORKER_GATE
790
            .lock()
791
            .unwrap_or_else(std::sync::PoisonError::into_inner);
792
        if camera_backend().is_some() {
793
            return None;
794
        }
795
        WORKER_LOG
796
            .lock()
797
            .unwrap_or_else(std::sync::PoisonError::into_inner)
798
            .clear();
799

            
800
        let (_rx, sender) = stopped_sender();
801
        let (_tx, receiver) = silent_receiver();
802
        camera_worker(init, sender, receiver);
803

            
804
        let sent = WORKER_LOG
805
            .lock()
806
            .unwrap_or_else(std::sync::PoisonError::into_inner)
807
            .clone();
808
        Some(sent)
809
    }
810

            
811
    // ------------------------------------------------------------------
812
    // frame_dims  (numeric / boundary)
813
    // ------------------------------------------------------------------
814

            
815
    #[test]
816
    fn frame_dims_substitutes_the_default_for_a_zero_dimension() {
817
        assert_eq!(frame_dims(&cfg(0, 0)), (640, 480));
818
        assert_eq!(frame_dims(&cfg(0, 720)), (640, 720), "only width defaults");
819
        assert_eq!(
820
            frame_dims(&cfg(1280, 0)),
821
            (1280, 480),
822
            "only height defaults"
823
        );
824
        assert_eq!(frame_dims(&CameraConfig::default()), (640, 480));
825
    }
826

            
827
    #[test]
828
    fn frame_dims_passes_nonzero_dimensions_through_unclamped() {
829
        assert_eq!(frame_dims(&cfg(1, 1)), (1, 1), "1px is not 'unset'");
830
        assert_eq!(frame_dims(&cfg(u32::MAX, u32::MAX)), (u32::MAX, u32::MAX));
831
        assert_eq!(frame_dims(&cfg(u32::MAX, 0)), (u32::MAX, 480));
832
    }
833

            
834
    #[test]
835
    fn frame_dims_ignores_facing_fps_and_format() {
836
        for facing in ALL_FACINGS {
837
            for fps in [0, 1, u32::MAX] {
838
                let config = CameraConfig {
839
                    facing,
840
                    width: 0,
841
                    height: 0,
842
                    fps,
843
                    output_format: RawImageFormat::R8,
844
                };
845
                assert_eq!(frame_dims(&config), (640, 480));
846
            }
847
        }
848
    }
849

            
850
    #[test]
851
    fn frame_dims_is_usable_in_const_context() {
852
        const CONFIG: CameraConfig = CameraConfig {
853
            facing: CameraFacing::Back,
854
            width: 0,
855
            height: 4096,
856
            fps: 0,
857
            output_format: RawImageFormat::BGRA8,
858
        };
859
        const DIMS: (u32, u32) = frame_dims(&CONFIG);
860
        assert_eq!(DIMS, (640, 4096));
861
    }
862

            
863
    // ------------------------------------------------------------------
864
    // CameraWidget::create / set_on_frame / with_on_frame
865
    // ------------------------------------------------------------------
866

            
867
    #[test]
868
    fn create_stores_the_config_verbatim_and_leaves_the_hook_unset() {
869
        for facing in ALL_FACINGS {
870
            for (w, h, fps) in [(0, 0, 0), (1, 1, 1), (u32::MAX, u32::MAX, u32::MAX)] {
871
                let config = CameraConfig {
872
                    facing,
873
                    width: w,
874
                    height: h,
875
                    fps,
876
                    output_format: RawImageFormat::RGBA8,
877
                };
878
                let widget = CameraWidget::create(config);
879
                assert_eq!(
880
                    widget.config, config,
881
                    "create must not normalise the config"
882
                );
883
                assert!(
884
                    matches!(widget.on_frame, OptionOnVideoFrame::None),
885
                    "a fresh widget has no frame hook"
886
                );
887
            }
888
        }
889
    }
890

            
891
    #[test]
892
    fn with_on_frame_installs_the_hook_and_keeps_the_config() {
893
        let config = cfg(320, 240);
894
        let widget = CameraWidget::create(config).with_on_frame(
895
            RefAny::new(FrameLog { seen: Vec::new() }),
896
            record_frame as OnVideoFrameCallbackType,
897
        );
898

            
899
        assert_eq!(
900
            widget.config, config,
901
            "the builder must not touch the config"
902
        );
903
        let OptionOnVideoFrame::Some(hook) = &widget.on_frame else {
904
            panic!("with_on_frame must install a hook");
905
        };
906
        assert_eq!(
907
            hook.callback.cb as usize,
908
            record_frame as OnVideoFrameCallbackType as usize
909
        );
910
    }
911

            
912
    #[test]
913
    fn set_on_frame_twice_keeps_only_the_last_hook() {
914
        let mut widget = CameraWidget::create(cfg(2, 2));
915
        widget.set_on_frame(
916
            RefAny::new(0_usize),
917
            record_frame as OnVideoFrameCallbackType,
918
        );
919
        widget.set_on_frame(
920
            RefAny::new(1_usize),
921
            frame_do_nothing as OnVideoFrameCallbackType,
922
        );
923

            
924
        let OptionOnVideoFrame::Some(hook) = &widget.on_frame else {
925
            panic!("hook must still be set");
926
        };
927
        assert_eq!(
928
            hook.callback.cb as usize, frame_do_nothing as OnVideoFrameCallbackType as usize,
929
            "the second set_on_frame must replace the first"
930
        );
931
    }
932

            
933
    // ------------------------------------------------------------------
934
    // CameraWidget::dom
935
    // ------------------------------------------------------------------
936

            
937
    #[test]
938
    fn dom_placeholder_uses_the_defaulted_dims_and_is_always_bgra8() {
939
        let (w, h, format, tag) = placeholder_of(&CameraWidget::create(cfg(0, 0)).dom());
940
        assert_eq!((w, h), (640, 480), "a 0-sized config falls back to 640x480");
941
        assert_eq!(format, RawImageFormat::BGRA8);
942
        assert_eq!(tag, b"azul-camera-placeholder".to_vec());
943

            
944
        // The requested output format is a *capture* request - the placeholder is
945
        // BGRA8 regardless.
946
        let config = CameraConfig {
947
            output_format: RawImageFormat::R8,
948
            ..cfg(320, 240)
949
        };
950
        let (w, h, format, _) = placeholder_of(&CameraWidget::create(config).dom());
951
        assert_eq!((w, h), (320, 240));
952
        assert_eq!(format, RawImageFormat::BGRA8);
953
    }
954

            
955
    #[test]
956
    fn dom_with_extreme_dims_builds_a_null_image_without_allocating() {
957
        // u32::MAX x u32::MAX pixels is ~7e19 bytes - a NullImage reserves no memory,
958
        // so this must stay a cheap, panic-free descriptor.
959
        let (w, h, format, _) =
960
            placeholder_of(&CameraWidget::create(cfg(u32::MAX, u32::MAX)).dom());
961
        assert_eq!((w, h), (u32::MAX as usize, u32::MAX as usize));
962
        assert_eq!(format, RawImageFormat::BGRA8);
963
    }
964

            
965
    #[test]
966
    fn dom_wires_exactly_one_after_mount_callback_a_dataset_and_a_merge_callback() {
967
        let dom = CameraWidget::create(cfg(64, 48)).dom();
968

            
969
        assert_eq!(
970
            dom.children.as_ref().len(),
971
            0,
972
            "the widget is a single node"
973
        );
974

            
975
        let callbacks = dom.root.get_callbacks();
976
        assert_eq!(
977
            callbacks.as_ref().len(),
978
            2,
979
            "two callbacks: the AfterMount capture-thread starter + the NodeResized re-targeter"
980
        );
981
        assert_eq!(
982
            callbacks.as_ref()[0].event,
983
            EventFilter::Component(ComponentEventFilter::AfterMount)
984
        );
985
        assert!(
986
            dom.root.get_merge_callback().is_some(),
987
            "state must survive relayout"
988
        );
989

            
990
        let mut dataset = dom
991
            .root
992
            .get_dataset()
993
            .cloned()
994
            .expect("the node must carry its CameraWidgetState");
995
        let (config, started, texture, has_hook) = read_state(&mut dataset);
996
        assert_eq!(config, cfg(64, 48));
997
        assert!(!started, "the thread only starts on AfterMount");
998
        assert_eq!(texture, None);
999
        assert!(!has_hook);
    }
    #[test]
    fn dom_moves_the_on_frame_hook_into_the_dataset() {
        let dom = CameraWidget::create(cfg(8, 8))
            .with_on_frame(
                RefAny::new(FrameLog { seen: Vec::new() }),
                record_frame as OnVideoFrameCallbackType,
            )
            .dom();
        let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
        let (_, _, _, has_hook) = read_state(&mut dataset);
        assert!(has_hook, "dom() must carry the user hook into the state");
    }
    // ------------------------------------------------------------------
    // camera_on_after_mount
    //
    // NOTE: the *first* mount is deliberately not exercised - it spawns a real
    // capture thread whose `Thread` destructor joins a worker that never reads its
    // receiver, which would hang the test binary (see the report). Only the guard
    // paths below can be driven safely.
    // ------------------------------------------------------------------
    #[test]
    fn after_mount_ignores_a_dataset_that_is_not_a_camera_state() {
        let (update, changes) =
            with_callback_info(|info| camera_on_after_mount(RefAny::new(0_u32), info));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign dataset must not start a capture thread"
        );
    }
    #[test]
    fn after_mount_is_a_no_op_once_the_thread_has_started() {
        let mut data = state(cfg(0, 0), true, Some(3));
        let (update, changes) =
            with_callback_info(|info| camera_on_after_mount(data.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "AfterMount must start the capture thread at most once"
        );
        let (_, started, texture, _) = read_state(&mut data);
        assert!(started);
        assert_eq!(texture, Some(3), "a re-mount must not drop the texture");
    }
    // ------------------------------------------------------------------
    // camera_worker
    // ------------------------------------------------------------------
    #[test]
    fn worker_stops_as_soon_as_the_main_thread_stops_receiving() {
        let Some(sent) = run_worker(RefAny::new(CameraThreadInit::sized(2, 3))) else {
            return; // a platform backend is registered: not the test pattern
        };
        assert_eq!(
            sent.len(),
            1,
            "the worker must stop after the first rejected send, not spin"
        );
        assert_eq!(
            sent[0],
            (2, 3, 2 * 3 * 4, true),
            "the first test-pattern frame is w*h*4 opaque-black RGBA bytes"
        );
    }
    #[test]
    fn worker_with_a_foreign_init_falls_back_to_640x480() {
        let Some(sent) = run_worker(RefAny::new("not a CameraThreadInit")) else {
            return;
        };
        assert_eq!(sent.len(), 1);
        let (w, h, bytes, _) = sent[0];
        assert_eq!(
            (w, h),
            (640, 480),
            "a bad init must not panic - it defaults"
        );
        assert_eq!(bytes, 640 * 480 * 4);
    }
    #[test]
    fn worker_with_zero_dims_terminates_without_a_frame_instead_of_hanging() {
        // camera_on_after_mount always routes through frame_dims, but the worker itself
        // does not - a 0x0 init must still terminate. A zero-sized frame is not a
        // frame: the test pattern refuses to open and the loop returns.
        let Some(sent) = run_worker(RefAny::new(CameraThreadInit::sized(0, 0))) else {
            return;
        };
        assert!(sent.is_empty(), "nothing to capture at 0x0: {sent:?}");
    }
    // ------------------------------------------------------------------
    // One capture, many consumers (widget side)
    // ------------------------------------------------------------------
    extern "C" fn record_consumer_frame(
        mut data: RefAny,
        _: CallbackInfo,
        cut: ConsumerFrame,
    ) -> Update {
        if let Some(mut log) = data.downcast_mut::<FrameLog>() {
            log.seen.push((
                cut.consumer.id,
                cut.frame.width,
                cut.frame.bytes.as_ref().len(),
            ));
        }
        Update::RefreshDom
    }
    #[test]
    fn consumers_and_their_hook_reach_the_dataset_and_the_worker_targets() {
        let log = RefAny::new(FrameLog { seen: Vec::new() });
        let dom = CameraWidget::create(cfg(0, 0))
            .with_consumer(FrameConsumer::new(7, 500, 200)) // client Bob
            .with_consumer(FrameConsumer::new(7, 640, 360)) // Bob changed his mind: replaces
            .with_consumer(FrameConsumer::new(8, 1280, 720)) // the recorder
            .with_on_consumer_frame(log, record_consumer_frame as OnConsumerFrameCallbackType)
            .dom();
        let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
        let s = dataset
            .downcast_ref::<CameraWidgetState>()
            .expect("camera state");
        assert_eq!(
            s.consumers.as_ref(),
            &[
                FrameConsumer::new(7, 640, 360),
                FrameConsumer::new(8, 1280, 720)
            ],
            "a same-id consumer replaces the earlier one"
        );
        assert!(s.on_consumer_frame.is_some());
        let t = s.targets();
        assert_eq!(t.consumers.len(), 2);
        assert!(
            !t.wants_source,
            "no on_frame hook: the captured frame stays on the worker"
        );
        assert_eq!(t.preview, None, "not laid out yet");
    }
    #[test]
    fn the_capture_floor_is_the_config_size_only_when_set_or_when_a_hook_wants_the_source() {
        // No explicit size, no hook: the tile and the consumers decide โ€” a
        // 300x200 tile captures 300x200, not the 640x480 default.
        assert_eq!(capture_floor(&cfg(0, 0), false), None);
        // A hook sees frames "as configured": the default is the floor.
        assert_eq!(capture_floor(&cfg(0, 0), true), Some((640, 480)));
        // An explicit size is a floor on its own.
        assert_eq!(capture_floor(&cfg(1280, 720), false), Some((1280, 720)));
        assert_eq!(capture_floor(&cfg(0, 720), false), Some((640, 720)));
    }
    #[test]
    fn writeback_routes_each_consumer_cut_to_the_consumer_hook_and_shows_the_preview() {
        let mut log = RefAny::new(FrameLog { seen: Vec::new() });
        let mut data = state(cfg(0, 0), true, None);
        if let Some(mut s) = data.downcast_mut::<CameraWidgetState>() {
            s.on_consumer_frame = Some(OnConsumerFrame {
                refany: log.clone(),
                callback: (record_consumer_frame as OnConsumerFrameCallbackType).into(),
            })
            .into();
        }
        let latch = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
        let payload = RefAny::new(CapturedFrames {
            source: None,
            preview: Some(frame(4, 3)),
            consumers: vec![
                ConsumerFrame::new(FrameConsumer::new(7, 2, 1), frame(2, 1)),
                ConsumerFrame::new(FrameConsumer::new(8, 3, 3), frame(3, 3)),
            ],
            in_flight: latch.clone(),
        });
        let (update, changes) =
            with_callback_info(|info| camera_writeback(data.clone(), payload.clone(), info));
        assert_eq!(
            update,
            Update::RefreshDom,
            "the consumer hook's Update wins"
        );
        assert_eq!(
            logged_frames(&mut log),
            vec![(7, 2, 2 * 4), (8, 3, 3 * 3 * 4)],
            "one hook call per consumer, each with ITS cut"
        );
        assert!(
            !latch.load(std::sync::atomic::Ordering::Acquire),
            "the writeback releases the back-pressure latch"
        );
        // The harness has no DOM, so present_frame_pixels finds no node to
        // install the preview on; the image change itself is exercised by
        // the headless capture-tile test.
        let _ = changes;
    }
    #[test]
    fn resize_without_a_laid_out_node_sends_nothing_and_stores_nothing() {
        let mut data = state(cfg(0, 0), true, None);
        let (update, changes) = with_callback_info(|info| camera_on_resize(data.clone(), info));
        assert_eq!(
            update,
            Update::DoNothing,
            "a resize is a message, never a relayout"
        );
        assert!(changes.is_empty());
        let s = data.downcast_ref::<CameraWidgetState>().expect("state");
        assert_eq!(s.preview, None, "no node size -> no preview size");
    }
    #[test]
    fn merge_carries_consumers_forward_and_pushes_them_to_the_running_worker() {
        let (tx, rx) = std::sync::mpsc::channel::<ThreadSendMsg>();
        let mut old_data = state(cfg(0, 0), true, Some(9));
        if let Some(mut s) = old_data.downcast_mut::<CameraWidgetState>() {
            s.control = Some(tx);
            s.thread_id = Some(ThreadId::unique());
        }
        let new_data = CameraWidget::create(cfg(0, 0))
            .with_consumer(FrameConsumer::new(7, 500, 200))
            .dom()
            .root
            .get_dataset()
            .cloned()
            .expect("dataset");
        let mut merged = merge_camera_state(new_data, old_data);
        let s = merged.downcast_ref::<CameraWidgetState>().expect("state");
        assert_eq!(s.consumers.as_ref(), &[FrameConsumer::new(7, 500, 200)]);
        assert!(
            s.started && s.gl_texture_id == Some(9),
            "thread state carries forward"
        );
        drop(s);
        let msg = rx.try_recv().expect("the running worker is told about Bob");
        let ThreadSendMsg::Custom(mut payload) = msg else {
            panic!("a consumer change is a Custom(CaptureTargets) message");
        };
        let t = payload
            .downcast_ref::<CaptureTargets>()
            .expect("CaptureTargets");
        assert_eq!(t.consumers, vec![FrameConsumer::new(7, 500, 200)]);
        // An unchanged rebuild sends nothing (hundreds of relayouts must not
        // spam the worker).
        let same = CameraWidget::create(cfg(0, 0))
            .with_consumer(FrameConsumer::new(7, 500, 200))
            .dom()
            .root
            .get_dataset()
            .cloned()
            .expect("dataset");
        let _ = merge_camera_state(same, merged);
        assert!(rx.try_recv().is_err(), "no change, no message");
    }
    // ------------------------------------------------------------------
    // camera_writeback
    // ------------------------------------------------------------------
    #[test]
    fn writeback_invokes_the_hook_with_the_frame_and_returns_its_update() {
        let mut log = RefAny::new(FrameLog { seen: Vec::new() });
        let mut data = state_with_hook(cfg(2, 2), &log);
        let frame_data = captured(frame(2, 2));
        let (update, _) =
            with_callback_info(|info| camera_writeback(data.clone(), frame_data.clone(), info));
        assert_eq!(update, Update::RefreshDom, "the hook's Update must win");
        assert_eq!(logged_frames(&mut log), vec![(2, 2, 16)]);
        let (_, _, texture, _) = read_state(&mut data);
        assert_eq!(
            texture, None,
            "without a GL context no texture id is ever installed"
        );
    }
    #[test]
    fn writeback_ignores_frame_data_of_the_wrong_type() {
        let mut log = RefAny::new(FrameLog { seen: Vec::new() });
        let mut data = state_with_hook(cfg(2, 2), &log);
        let (update, changes) =
            with_callback_info(|info| camera_writeback(data.clone(), RefAny::new(0_u32), info));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty(), "no frame -> no image change");
        assert!(
            logged_frames(&mut log).is_empty(),
            "the user hook must not fire without a frame"
        );
    }
    #[test]
    fn writeback_survives_a_writeback_dataset_that_is_not_a_camera_state() {
        let (update, _) = with_callback_info(|info| {
            camera_writeback(RefAny::new(0_u32), captured(frame(1, 1)), info)
        });
        assert_eq!(
            update,
            Update::DoNothing,
            "a foreign dataset means no hook and no texture - but no panic either"
        );
    }
    #[test]
    fn writeback_keeps_a_preexisting_texture_id_on_the_cpu_path() {
        let mut data = state(cfg(2, 2), true, Some(42));
        let frame_data = captured(frame(2, 2));
        let (update, _) =
            with_callback_info(|info| camera_writeback(data.clone(), frame_data.clone(), info));
        assert_eq!(update, Update::DoNothing, "no hook -> no user update");
        let (_, _, texture, _) = read_state(&mut data);
        assert_eq!(texture, Some(42), "the texture id must stay stable");
    }
    #[test]
    fn writeback_rejects_a_frame_whose_bytes_do_not_match_its_dimensions() {
        // A malformed/hostile frame (huge dims, no pixels): the image upload must fail
        // cleanly instead of indexing out of bounds or allocating.
        let mut data = state(cfg(2, 2), true, None);
        let bogus = captured(VideoFrame {
            width: u32::MAX,
            height: 1,
            bytes: Vec::<u8>::new().into(),
        });
        let (update, changes) =
            with_callback_info(|info| camera_writeback(data.clone(), bogus.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a rejected frame must not touch the DOM"
        );
        let (_, _, texture, _) = read_state(&mut data);
        assert_eq!(texture, None);
    }
    // ------------------------------------------------------------------
    // merge_camera_state
    // ------------------------------------------------------------------
    #[test]
    fn merge_takes_the_thread_state_from_old_and_everything_else_from_new() {
        let log = RefAny::new(FrameLog { seen: Vec::new() });
        let new_data = state_with_hook(cfg(1920, 1080), &log);
        let old_data = state(cfg(320, 240), true, Some(9));
        let mut merged = merge_camera_state(new_data, old_data);
        let (config, started, texture, has_hook) = read_state(&mut merged);
        assert_eq!(config, cfg(1920, 1080), "the fresh build's config wins");
        assert!(has_hook, "the fresh build's hook wins");
        assert!(started, "'thread already running' must carry forward");
        assert_eq!(texture, Some(9), "the stable texture id must carry forward");
    }
    #[test]
    fn merge_leaves_the_new_state_alone_when_the_old_one_is_foreign() {
        let new_data = state(cfg(640, 480), false, None);
        let mut merged = merge_camera_state(new_data, RefAny::new(0_u32));
        let (config, started, texture, _) = read_state(&mut merged);
        assert_eq!(config, cfg(640, 480));
        assert!(!started, "nothing to carry forward from a foreign payload");
        assert_eq!(texture, None);
    }
    #[test]
    fn merge_returns_a_foreign_new_dataset_untouched() {
        let old_data = state(cfg(640, 480), true, Some(1));
        let mut merged = merge_camera_state(RefAny::new(77_u32), old_data);
        assert_eq!(
            merged.downcast_ref::<u32>().map(|v| *v),
            Some(77),
            "merge must hand back exactly the payload it was given"
        );
    }
    #[test]
    fn merge_of_a_dataset_with_itself_does_not_panic() {
        // The same RefAny on both sides: the mutable + shared borrow overlap, so the
        // merge is skipped rather than aliasing. Either way the state must survive.
        let mut data = state(cfg(800, 600), true, Some(5));
        let mut merged = merge_camera_state(data.clone(), data.clone());
        let (config, started, texture, _) = read_state(&mut merged);
        assert_eq!(config, cfg(800, 600));
        assert!(started);
        assert_eq!(texture, Some(5));
        assert_eq!(read_state(&mut data), (cfg(800, 600), true, Some(5), false));
    }
    /// REGRESSION (B3): a capture worker must ACKNOWLEDGE `TerminateThread`.
    ///
    /// Reported from azul-meet on macOS after using camera + screenshare โ€” the
    /// framework printed, twice (once per capture worker):
    ///
    /// ```text
    /// [azul][thread] a background thread did not acknowledge TerminateThread
    /// within 2000ms and was DETACHED rather than joined.
    /// ```
    ///
    /// Root cause: the worker took its receiver as `_recv` and never polled it,
    /// so the terminate message was never observed. The only exit was
    /// `sender.send()` returning false, which does NOT happen at shutdown
    /// because the main thread still owns the receiving end while it waits out
    /// the grace period. Fixed by `capture_common::terminate_requested`.
    ///
    /// The budget here is the framework's own:
    /// `THREAD_TERMINATE_GRACE_STEPS (200) * 10ms = 2000ms`.
    #[test]
    fn camera_worker_acknowledges_terminate_within_the_grace_budget() {
        use crate::thread::{Thread, ThreadCallback};
        let t = Thread::create(
            RefAny::new(CameraThreadInit::sized(8, 8)),
            RefAny::new(0_usize),
            ThreadCallback::new(camera_worker),
        );
        assert!(
            t.send_message(ThreadSendMsg::TerminateThread),
            "the worker holds its receiver alive, so the send must succeed"
        );
        let finished = || {
            t.ptr
                .lock()
                .expect("thread mutex must not be poisoned")
                .is_finished()
        };
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(2_000);
        while !finished() && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert!(
            finished(),
            "camera_worker did not acknowledge TerminateThread within 2000ms โ€” at shutdown it \
             would be DETACHED rather than joined"
        );
    }
}