1
//! Shared core for the "video-ish" widgets (camera / screencap / video).
2
//!
3
//! All three are identical in architecture (RefAny dataset + AfterMount
4
//! background capture/decode thread + writeback that uploads each frame into a
5
//! stable external GL texture + recomposites). Only the *config* and the
6
//! *worker* differ. This module holds the duplicated pieces - the [`VideoFrame`]
7
//! the worker produces and [`present_frame`], the GL writeback core - so each
8
//! widget is a thin config+worker wrapper and there's a single place for GL
9
//! fixes + the real platform workers (AVFoundation / ScreenCaptureKit /
10
//! vk-video) to plug in.
11
//!
12
//! NOTE: GL code - compile-verified here; the actual texture rendering must be
13
//! verified on a machine with a window + GPU.
14

            
15
use std::sync::{
16
    atomic::{AtomicBool, Ordering},
17
    Arc,
18
};
19

            
20
use azul_core::{
21
    callbacks::Update,
22
    geom::PhysicalSizeU32,
23
    gl::{
24
        gl::{RGBA, TEXTURE_2D, UNSIGNED_BYTE},
25
        GlContextPtr, OptionU8VecRef, U8VecRef,
26
    },
27
    refany::RefAny,
28
    resources::{ImageRef, UpdateImageType},
29
    task::{OptionThreadSendMsg, ThreadId, ThreadReceiver, ThreadSendMsg},
30
    video::{ConsumerFrame, FrameConsumer, VideoFrame},
31
};
32
use azul_css::impl_option_inner; /* brought into scope for impl_widget_callback!'s
33
                                   * impl_option! */
34
use azul_css::{props::basic::ColorU, AzString};
35

            
36
use crate::{
37
    callbacks::CallbackInfo,
38
    image_scale::{self, ResampleFn, SrcImage},
39
    thread::{
40
        ThreadReceiveMsg, ThreadSender, ThreadWriteBackMsg, WriteBackCallback,
41
        WriteBackCallbackType,
42
    },
43
};
44

            
45
/// User hook fired once per captured/decoded frame - the backreference
46
/// dependency-injection pattern (see `architecture.md`).
47
///
48
/// A capture widget's
49
/// private writeback invokes it with each [`VideoFrame`], so application code
50
/// can apply effects, save the frame into its own data model, or send it over
51
/// the network (azul-meet). Returns `Update` like any callback. Wired via
52
/// `CameraWidget::with_on_frame` / `ScreenCaptureWidget::with_on_frame` /
53
/// `VideoWidget::with_on_frame`.
54
pub type OnVideoFrameCallbackType = extern "C" fn(RefAny, CallbackInfo, VideoFrame) -> Update;
55
impl_widget_callback!(
56
    OnVideoFrame,
57
    OptionOnVideoFrame,
58
    OnVideoFrameCallback,
59
    OnVideoFrameCallbackType
60
);
61

            
62
// Host-invoker plumbing for managed-FFI bindings - see core/src/host_invoker.rs.
63
azul_core::impl_managed_callback! {
64
    wrapper:        OnVideoFrameCallback,
65
    info_ty:        CallbackInfo,
66
    return_ty:      Update,
67
    default_ret:    Update::DoNothing,
68
    invoker_static: ON_VIDEO_FRAME_INVOKER,
69
    invoker_ty:     AzOnVideoFrameCallbackInvoker,
70
    thunk_fn:       az_on_video_frame_callback_thunk,
71
    setter_fn:      AzApp_setOnVideoFrameCallbackInvoker,
72
    from_handle_fn: AzOnVideoFrameCallback_createFromHostHandle,
73
    extra_args:     [ frame: VideoFrame ],
74
}
75

            
76
/// User hook fired once per CONSUMER per captured frame with that consumer's
77
/// cut ([`ConsumerFrame`]: the [`FrameConsumer`] it was cut for + the frame
78
/// at its size). Register consumers with `CameraWidget::with_consumer` /
79
/// `ScreenCaptureWidget::with_consumer`; route on `frame.consumer.id`
80
/// ("client Bob" gets his 500x200, the recorder its 1280x720, from ONE
81
/// capture). Returns `Update` like any callback.
82
pub type OnConsumerFrameCallbackType = extern "C" fn(RefAny, CallbackInfo, ConsumerFrame) -> Update;
83
impl_widget_callback!(
84
    OnConsumerFrame,
85
    OptionOnConsumerFrame,
86
    OnConsumerFrameCallback,
87
    OnConsumerFrameCallbackType
88
);
89

            
90
azul_core::impl_managed_callback! {
91
    wrapper:        OnConsumerFrameCallback,
92
    info_ty:        CallbackInfo,
93
    return_ty:      Update,
94
    default_ret:    Update::DoNothing,
95
    invoker_static: ON_CONSUMER_FRAME_INVOKER,
96
    invoker_ty:     AzOnConsumerFrameCallbackInvoker,
97
    thunk_fn:       az_on_consumer_frame_callback_thunk,
98
    setter_fn:      AzApp_setOnConsumerFrameCallbackInvoker,
99
    from_handle_fn: AzOnConsumerFrameCallback_createFromHostHandle,
100
    extra_args:     [ frame: ConsumerFrame ],
101
}
102

            
103
/// Invoke a capture widget's optional `on_consumer_frame` hook with one
104
/// consumer's cut, returning the user's `Update` (`DoNothing` when unset).
105
2
pub fn invoke_on_consumer_frame(
106
2
    hook: &OptionOnConsumerFrame,
107
2
    info: &mut CallbackInfo,
108
2
    frame: ConsumerFrame,
109
2
) -> Update {
110
2
    match hook {
111
2
        OptionOnConsumerFrame::Some(h) => (h.callback.cb)(h.refany.clone(), *info, frame),
112
        OptionOnConsumerFrame::None => Update::DoNothing,
113
    }
114
2
}
115

            
116
/// Invoke a capture widget's optional `on_frame` hook with `frame`, returning
117
/// the user's `Update` (`DoNothing` when no hook is set). Shared by all three
118
/// capture widgets' writebacks.
119
45
pub fn invoke_on_frame(
120
45
    hook: &OptionOnVideoFrame,
121
45
    info: &mut CallbackInfo,
122
45
    frame: &VideoFrame,
123
45
) -> Update {
124
45
    match hook {
125
18
        OptionOnVideoFrame::Some(h) => (h.callback.cb)(h.refany.clone(), *info, frame.clone()),
126
27
        OptionOnVideoFrame::None => Update::DoNothing,
127
    }
128
45
}
129

            
130
/// Mint a process-unique MARKER string for a capture widget's tile node.
131
///
132
/// The widget stamps it on the node (`Dom::with_marker`) *and* stores it in its
133
/// private dataset; the frame writeback later resolves it back to the node via
134
/// `CallbackInfo::get_node_id_by_marker`. One fresh string per `dom()` build,
135
/// so two widgets of the same type can never collide - the old lookup
136
/// (`get_node_id_of_root_dataset`) matched by dataset TYPE and did.
137
#[must_use]
138
30
pub fn next_capture_marker(kind: &str) -> AzString {
139
    use core::sync::atomic::AtomicU64;
140
    static NEXT: AtomicU64 = AtomicU64::new(1);
141
30
    format!("azul-{}-{:x}", kind, NEXT.fetch_add(1, Ordering::Relaxed)).into()
142
30
}
143

            
144
/// Present `frame` for a video-ish widget.
145
///
146
/// ONE path on every backend: install the frame as a raw RGBA `ImageRef` on
147
/// the widget's node via `change_node_image` → the content chokepoint
148
/// (`LayoutWindow::apply_content_change`), which patches the display list in
149
/// place and lets damage fall out of `ImageRef` identity. The widget never
150
/// branches on the renderer — that branch was the shipped bug: a CPU-rendered
151
/// window can still EXPOSE a GL context, so the widget took the GL path and
152
/// sent texture-only updates (`update_all_image_callbacks` → `ReRender`) that
153
/// the CPU rasterizer never saw; camera/screenshare tiles froze on their
154
/// placeholder. On GPU backends the `WebRender` translator re-uploads the
155
/// changed raster `ImageRef` — the backend decides texture vs raster, the
156
/// widget cannot know or care.
157
///
158
/// `current_id` is passed through unchanged (widgets store it; the GL texture
159
/// pool it used to name is gone).
160
20
pub fn present_frame(
161
20
    info: &mut CallbackInfo,
162
20
    marker: AzString,
163
20
    current_id: Option<u32>,
164
20
    frame: &VideoFrame,
165
20
) -> Option<u32> {
166
20
    present_frame_pixels(
167
20
        info,
168
20
        marker,
169
20
        current_id,
170
20
        frame.bytes.clone(),
171
20
        frame.width,
172
20
        frame.height,
173
    )
174
20
}
175

            
176
/// [`present_frame`] taking the pixels BY VALUE: the writebacks `mem::take`
177
/// them out of the frame `RefAny` (dropped right after) instead of cloning
178
/// a full frame on the main thread.
179
///
180
/// `premultiplied_alpha: true` because every
181
/// capture backend forces alpha 255, for which straight == premultiplied —
182
/// `load_rgba8` then skips its per-pixel multiply.
183
39
pub fn present_frame_pixels(
184
39
    info: &mut CallbackInfo,
185
39
    marker: AzString,
186
39
    current_id: Option<u32>,
187
39
    bytes: azul_css::U8Vec,
188
39
    width: u32,
189
39
    height: u32,
190
39
) -> Option<u32> {
191
    use azul_core::resources::{RawImage, RawImageData, RawImageFormat};
192

            
193
39
    if let Some(img) = ImageRef::new_rawimage(RawImage {
194
39
        pixels: RawImageData::U8(bytes),
195
39
        width: width as usize,
196
39
        height: height as usize,
197
39
        premultiplied_alpha: true,
198
39
        data_format: RawImageFormat::RGBA8,
199
39
        tag: b"azul-capture-frame".to_vec().into(),
200
39
    }) {
201
27
        if let Some(node) = info.get_node_id_by_marker(marker) {
202
12
            if let Some(nid) = node.node.into_crate_internal() {
203
12
                info.change_node_image(node.dom, nid, img, UpdateImageType::Content);
204
12
            }
205
15
        }
206
12
    }
207
39
    current_id
208
39
}
209

            
210
/// Upload tightly-packed RGBA8 pixels into the GL texture `texture_id`.
211
#[allow(clippy::cast_possible_wrap)] // bounded graphics/coord/counter/fixed-point cast
212
12
pub fn upload_rgba(gl: &GlContextPtr, texture_id: u32, frame: &VideoFrame) {
213
12
    gl.bind_texture(TEXTURE_2D, texture_id);
214
12
    gl.tex_image_2d(
215
        TEXTURE_2D,
216
        0,
217
12
        RGBA as i32,
218
12
        frame.width as i32,
219
12
        frame.height as i32,
220
        0,
221
        RGBA,
222
        UNSIGNED_BYTE,
223
12
        OptionU8VecRef::Some(U8VecRef::from(frame.bytes.as_ref())),
224
    );
225
12
}
226

            
227
/// What a capture backend is asked to open: the source, the size the frames
228
/// should have, the frame rate, and (screens) whether to leave the app's own
229
/// windows out of the picture.
230
///
231
/// `width` x `height` is the size the WIDGET needs — the covering size of
232
/// every consumer ([`required_capture_size`]) — not a constant. A backend
233
/// delivers the smallest size it can that covers the request (the camera's
234
/// next session preset up, the screen stream scaled down by the OS) and
235
/// reports the actual size with every frame; it never delivers less than it
236
/// can and is never asked for more than someone will look at.
237
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
238
pub struct CaptureRequest {
239
    /// Camera device index / display index (0 = default).
240
    pub index: u32,
241
    /// A specific window to capture by platform id (`0` = the whole source).
242
    /// Screens only; cameras ignore it.
243
    pub window: u64,
244
    /// Wanted frame width in px (`0` = the backend's default).
245
    pub width: u32,
246
    /// Wanted frame height in px (`0` = the backend's default).
247
    pub height: u32,
248
    /// Wanted frame rate (`0` = the backend's default, 30 on every backend
249
    /// that has one). A 300x200 tile does not need 30 fps.
250
    pub fps: u32,
251
    /// Screens: exclude this process's own windows from the capture. Without
252
    /// it a shared desktop that shows the sharing app loops: every tile
253
    /// repaint is a screen change, which emits a frame, which repaints the
254
    /// tile, ... — a steady 30 fps on an idle desktop.
255
    pub exclude_self: bool,
256
}
257

            
258
impl CaptureRequest {
259
    /// `index` at `width` x `height`, everything else default.
260
    #[must_use]
261
11
    pub const fn new(index: u32, width: u32, height: u32) -> Self {
262
11
        Self {
263
11
            index,
264
11
            window: 0,
265
11
            width,
266
11
            height,
267
11
            fps: 0,
268
11
            exclude_self: true,
269
11
        }
270
11
    }
271

            
272
    /// The same request at another size.
273
    #[must_use]
274
8
    pub const fn with_size(self, width: u32, height: u32) -> Self {
275
8
        Self {
276
8
            width,
277
8
            height,
278
8
            ..self
279
8
        }
280
8
    }
281

            
282
    /// `fps`, or the backend default when the request says 0.
283
    #[must_use]
284
    pub const fn fps_or(&self, default: u32) -> u32 {
285
        if self.fps > 0 {
286
            self.fps
287
        } else {
288
            default
289
        }
290
    }
291
}
292

            
293
/// What one blocking read of a capture source produced.
294
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
295
pub enum CaptureRead {
296
    /// A new frame: tightly-packed RGBA8 of this size is in `out`.
297
    Frame {
298
        /// Delivered width in px.
299
        width: u32,
300
        /// Delivered height in px.
301
        height: u32,
302
    },
303
    /// Nothing new within the backend's wait: an idle screen, a camera that
304
    /// stalled (sleep/wake, a Continuity camera reconnecting). NOT the end of
305
    /// the stream — the worker keeps polling, and presents nothing, so an
306
    /// unchanged picture costs no repaint.
307
    Idle,
308
    /// The source is gone (device unplugged, stream stopped, error): the
309
    /// worker closes and exits.
310
    Ended,
311
}
312

            
313
/// A platform frame-capture backend (camera / screen), registered by the dll at
314
/// startup so the cross-platform capture widgets can pull **real** frames
315
/// instead of their built-in test pattern.
316
///
317
/// The dll provides one per OS (v4l2 on
318
/// Linux, `AVFoundation` on macOS, Media Foundation on Windows, `ScreenCaptureKit` /
319
/// `PipeWire` / DXGI for screens, ...). These are plain Rust fn pointers - the dll
320
/// links azul-layout statically, so registering + calling is a Rust-to-Rust
321
/// call, no `extern "C"`/trait-object dance.
322
#[derive(Debug, Clone, Copy)]
323
pub struct CaptureVTable {
324
    /// Open the source described by the request. Returns an opaque handle,
325
    /// or `0` on failure (the worker then falls back to the test pattern).
326
    pub open: fn(request: &CaptureRequest) -> u64,
327
    /// Block (bounded, ~1 s) for the next frame, writing tightly-packed RGBA8
328
    /// into `out` (resized as needed). See [`CaptureRead`] for the three
329
    /// outcomes — a timeout is `Idle`, never `Ended`.
330
    pub read: fn(handle: u64, out: &mut Vec<u8>) -> CaptureRead,
331
    /// Close + free the source.
332
    pub close: fn(handle: u64),
333
    /// Change the delivered size / fps of a RUNNING source without a
334
    /// close + open (macOS: a live session-preset switch, an `SCStream`
335
    /// `updateConfiguration`). `None`, or a `false` return, makes the worker
336
    /// reopen instead — the universal fallback, so a backend without it is
337
    /// merely slower to follow a resize, never wrong.
338
    pub reconfigure: Option<fn(handle: u64, request: &CaptureRequest) -> bool>,
339
}
340

            
341
static CAMERA_BACKEND: std::sync::OnceLock<CaptureVTable> = std::sync::OnceLock::new();
342
static SCREEN_BACKEND: std::sync::OnceLock<CaptureVTable> = std::sync::OnceLock::new();
343
static FRAME_RESAMPLER: std::sync::OnceLock<ResampleFn> = std::sync::OnceLock::new();
344

            
345
/// Register a platform-accelerated whole-frame scaler (the dll registers
346
/// Accelerate/vImage on macOS). It must be a pure function with
347
/// [`image_scale::resample_rgba`]'s contract — same inputs, same output
348
/// within rounding — because the fan-out may run it per consumer on any
349
/// thread. First registration wins; without one the portable scaler is used.
350
pub fn register_frame_resampler(resample: ResampleFn) {
351
    let _ = FRAME_RESAMPLER.set(resample);
352
}
353

            
354
/// The whole-frame scaler the capture fan-out uses: the registered
355
/// platform one, else [`image_scale::resample_rgba`].
356
#[must_use]
357
4
pub fn frame_resampler() -> ResampleFn {
358
4
    FRAME_RESAMPLER
359
4
        .get()
360
4
        .copied()
361
4
        .unwrap_or(image_scale::resample_rgba)
362
4
}
363

            
364
/// Register the platform **camera** capture backend (called once by the dll at
365
/// startup; the first registration wins). Without it, `CameraWidget` shows its
366
/// test pattern.
367
3
pub fn register_camera_backend(vtable: CaptureVTable) {
368
3
    let _ = CAMERA_BACKEND.set(vtable);
369
3
}
370

            
371
/// Register the platform **screen** capture backend (for `ScreenCaptureWidget`).
372
1
pub fn register_screen_backend(vtable: CaptureVTable) {
373
1
    let _ = SCREEN_BACKEND.set(vtable);
374
1
}
375

            
376
/// The registered camera backend, if the dll provided one for this platform.
377
10
pub fn camera_backend() -> Option<CaptureVTable> {
378
10
    CAMERA_BACKEND.get().copied()
379
10
}
380

            
381
/// The registered screen-capture backend, if any.
382
6
pub fn screen_backend() -> Option<CaptureVTable> {
383
6
    SCREEN_BACKEND.get().copied()
384
6
}
385

            
386
/// A platform **audio**-capture backend (microphone), registered by the dll so
387
/// `MicrophoneWidget` can pull real samples instead of the test tone.
388
///
389
/// Like
390
/// [`CaptureVTable`] but yields interleaved `f32` audio rather than RGBA video.
391
#[derive(Debug, Clone, Copy)]
392
pub struct AudioCaptureVTable {
393
    /// Open the default mic at `sample_rate` x `channels`. Opaque handle, or
394
    /// `0` on failure.
395
    pub open: fn(sample_rate: u32, channels: u16) -> u64,
396
    /// Block for the next chunk, writing interleaved `f32` into `out` (resized).
397
    /// Returns the frame count (`out.len() / channels`), or `0` on error / EOF
398
    /// (the worker then stops + closes).
399
    pub read: fn(handle: u64, out: &mut Vec<f32>) -> u32,
400
    /// Close + free the source.
401
    pub close: fn(handle: u64),
402
}
403

            
404
static MIC_BACKEND: std::sync::OnceLock<AudioCaptureVTable> = std::sync::OnceLock::new();
405

            
406
/// Register the platform microphone-capture backend (called once by the dll).
407
2
pub fn register_mic_backend(vtable: AudioCaptureVTable) {
408
2
    let _ = MIC_BACKEND.set(vtable);
409
2
}
410

            
411
/// The registered mic-capture backend, if the dll provided one for this platform.
412
13
pub fn mic_backend() -> Option<AudioCaptureVTable> {
413
13
    MIC_BACKEND.get().copied()
414
13
}
415

            
416
/// Poll the main->worker channel and report whether the worker was asked to
417
/// stop.
418
///
419
/// Every capture worker (camera / screencap / microphone) sits in a
420
/// `loop { read_device(); send_frame(); }`. Before this existed, none of them
421
/// ever looked at their `ThreadReceiver`, so `ThreadSendMsg::TerminateThread`
422
/// was never observed and the only way out was `sender.send()` failing — which
423
/// does NOT happen at shutdown, because the main thread still owns the
424
/// receiving end while it waits. The result was the 2 s grace period in
425
/// `crate::thread::default_thread_destructor_fn` expiring and the worker being
426
/// DETACHED:
427
///
428
/// ```text
429
/// [azul][thread] a background thread did not acknowledge TerminateThread
430
/// within 2000ms and was DETACHED rather than joined.
431
/// ```
432
///
433
/// (Reported twice from azul-meet on macOS after using camera + screenshare —
434
/// one line per capture worker.)
435
///
436
/// `ThreadReceiver::recv` is a `try_recv` under the hood, so this never blocks.
437
/// Non-terminate messages are drained and ignored: these workers have no other
438
/// commands, and leaving them queued would hide a `TerminateThread` sent behind
439
/// them.
440
#[must_use]
441
6
pub fn terminate_requested(recv: &mut ThreadReceiver) -> bool {
442
    loop {
443
6
        match recv.recv() {
444
1
            OptionThreadSendMsg::Some(ThreadSendMsg::TerminateThread) => return true,
445
            OptionThreadSendMsg::Some(_) => {}
446
5
            OptionThreadSendMsg::None => return false,
447
        }
448
    }
449
6
}
450

            
451
// ============================================================================
452
// The shared capture loop: one capture, many consumers
453
// ============================================================================
454

            
455
/// Who wants frames of which size — the main thread's view, sent to the
456
/// worker as `ThreadSendMsg::Custom(RefAny::new(CaptureTargets))` whenever it
457
/// changes (the node was laid out / resized, the app registered a consumer).
458
#[derive(Debug, Clone, PartialEq, Eq, Default)]
459
pub struct CaptureTargets {
460
    /// The on-screen tile's size in DEVICE pixels (logical size x hidpi), once
461
    /// layout has produced one. `None` before the first layout: the captured
462
    /// frame is shown as-is.
463
    pub preview: Option<(u32, u32)>,
464
    /// Every registered consumer (see [`FrameConsumer`]).
465
    pub consumers: Vec<FrameConsumer>,
466
    /// The widget has an `on_frame` hook, which receives the frame AS
467
    /// CAPTURED — so the capture may not shrink below the configured size
468
    /// and the source frame must travel to the main thread.
469
    pub wants_source: bool,
470
}
471

            
472
/// Drain the main->worker channel into `targets`; `true` if the worker was
473
/// asked to stop. The generalisation of [`terminate_requested`] for the
474
/// video workers: a `Custom` message carrying [`CaptureTargets`] replaces the
475
/// current targets (the LAST one wins, so a burst of resizes costs one
476
/// reconfigure), a terminate is reported, anything else is ignored.
477
#[must_use]
478
79
pub fn poll_capture_control(recv: &mut ThreadReceiver, targets: &mut CaptureTargets) -> bool {
479
    loop {
480
80
        match recv.recv() {
481
2
            OptionThreadSendMsg::Some(ThreadSendMsg::TerminateThread) => return true,
482
1
            OptionThreadSendMsg::Some(ThreadSendMsg::Custom(mut payload)) => {
483
1
                if let Some(t) = payload.downcast_ref::<CaptureTargets>() {
484
1
                    *targets = t.clone();
485
1
                }
486
            }
487
            OptionThreadSendMsg::Some(ThreadSendMsg::Tick) => {}
488
77
            OptionThreadSendMsg::None => return false,
489
        }
490
    }
491
79
}
492

            
493
/// The size the device should capture at: the covering size of everything
494
/// that wants frames.
495
///
496
/// * `floor` — the configured size when the app set one explicitly, or the widget's default when an
497
///   `on_frame` hook wants the source frame (the hook sees what the config promised, so the capture
498
///   never shrinks below it);
499
/// * the preview tile (device px) and every consumer;
500
/// * `fallback` when none of the above is known yet (before the first layout, no hook, no
501
///   consumers).
502
///
503
/// "Client Bob wants 500x200, the preview is 100x200, no hook" -> 500x200.
504
/// "Only a 300x200 preview" -> 300x200: the camera is told to capture a
505
/// small frame instead of 1080p that is then thrown away.
506
#[must_use]
507
29
pub fn required_capture_size(
508
29
    floor: Option<(u32, u32)>,
509
29
    targets: &CaptureTargets,
510
29
    fallback: (u32, u32),
511
29
) -> (u32, u32) {
512
29
    let sizes = floor
513
29
        .into_iter()
514
29
        .chain(targets.preview)
515
29
        .chain(targets.consumers.iter().map(|c| (c.width, c.height)));
516
29
    image_scale::covering_size(sizes).unwrap_or(fallback)
517
29
}
518

            
519
/// Should a running source be reconfigured / reopened for `required`?
520
///
521
/// * `requested` — the size the source was last opened / reconfigured for;
522
/// * `delivered` — the size its frames actually have (backends snap up to a preset, so this is
523
///   often larger than `requested`);
524
/// * `required` — [`required_capture_size`] now.
525
///
526
/// Reopen when the consumers need MORE than the source delivers (quality), or
527
/// when they need so much less than was requested (both axes at most half)
528
/// that the device is doing 4x the work anyone looks at (cost). Comparing the
529
/// shrink case against `requested` rather than `delivered` is what makes a
530
/// 300x200 tile fed by the 640x480 minimum preset NOT reopen forever: the
531
/// request is already as small as it can be.
532
#[must_use]
533
25
pub const fn needs_reopen(
534
25
    requested: (u32, u32),
535
25
    delivered: (u32, u32),
536
25
    required: (u32, u32),
537
25
) -> bool {
538
25
    let more = (required.0 > delivered.0 || required.1 > delivered.1)
539
3
        && (required.0 > requested.0 || required.1 > requested.1);
540
25
    let much_less = required.0 * 2 <= requested.0 && required.1 * 2 <= requested.1;
541
25
    more || much_less
542
25
}
543

            
544
/// The worker's choice of preview cut: `Some(size)` when the tile's device
545
/// size is known AND differs from the captured frame (a same-size preview is
546
/// the source frame itself, shown without a copy).
547
#[must_use]
548
11
pub fn preview_cut_size(targets: &CaptureTargets, captured: (u32, u32)) -> Option<(u32, u32)> {
549
11
    targets
550
11
        .preview
551
11
        .filter(|&(w, h)| w > 0 && h > 0 && (w, h) != captured)
552
11
}
553

            
554
/// What one captured frame became after the worker's fan-out — the payload
555
/// of every capture writeback. Built off the main thread; the writeback
556
/// ([`present_captured`]) only hands things out.
557
#[derive(Debug)]
558
pub struct CapturedFrames {
559
    /// The frame as captured: present when the `on_frame` hook wants it, or
560
    /// when there is no preview cut (then it IS what goes on screen).
561
    pub source: Option<VideoFrame>,
562
    /// The on-screen tile's cut (consumer 0), at the tile's device size.
563
    pub preview: Option<VideoFrame>,
564
    /// Every registered consumer's cut.
565
    pub consumers: Vec<ConsumerFrame>,
566
    /// Back-pressure latch: set by the worker when it queues this payload,
567
    /// cleared by the writeback. While it is set the worker DROPS new frames
568
    /// instead of queueing them, so at most one frame is ever in flight — a
569
    /// busy main thread sees the newest frame late, never a growing backlog.
570
    pub in_flight: Arc<AtomicBool>,
571
}
572

            
573
/// The writeback core shared by the camera and screen widgets: release the
574
/// back-pressure latch, run the user hooks, put the preview (else the source
575
/// frame) on the widget's node. Returns the strongest `Update` a hook asked
576
/// for.
577
19
pub fn present_captured(
578
19
    info: &mut CallbackInfo,
579
19
    marker: AzString,
580
19
    on_frame: &OptionOnVideoFrame,
581
19
    on_consumer_frame: &OptionOnConsumerFrame,
582
19
    captured: &mut CapturedFrames,
583
19
) -> Update {
584
19
    captured.in_flight.store(false, Ordering::Release);
585
19
    let mut update = Update::DoNothing;
586
19
    if let Some(source) = captured.source.as_ref() {
587
18
        update.max_self(invoke_on_frame(on_frame, info, source));
588
18
    }
589
19
    for cut in core::mem::take(&mut captured.consumers) {
590
2
        update.max_self(invoke_on_consumer_frame(on_consumer_frame, info, cut));
591
2
    }
592
19
    let shown = captured.preview.take().or_else(|| captured.source.take());
593
19
    if let Some(frame) = shown {
594
19
        let _texture_id: Option<u32> =
595
19
            present_frame_pixels(info, marker, None, frame.bytes, frame.width, frame.height);
596
19
    }
597
19
    update
598
19
}
599

            
600
/// The on-screen tile's size in DEVICE pixels for the callback's hit node:
601
/// the laid-out logical size times the window's hidpi factor. `None` before
602
/// layout. Logical pixels would undersize a Retina preview by 2x.
603
#[must_use]
604
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded layout/render numeric
605
                                                                   // cast
606
13
pub fn preview_size_for_node(info: &CallbackInfo) -> Option<(u32, u32)> {
607
13
    let size = info.get_node_size(info.get_hit_node())?;
608
    let dpi = info
609
        .get_current_window_state()
610
        .size
611
        .get_hidpi_factor()
612
        .inner
613
        .get()
614
        .max(0.5);
615
    let w = (size.width * dpi).round().max(1.0) as u32;
616
    let h = (size.height * dpi).round().max(1.0) as u32;
617
    Some((w, h))
618
13
}
619

            
620
/// Send `targets` to the capture worker `thread_id`. Best effort: a worker
621
/// that already exited has nothing to resize, and a merge that changes the
622
/// consumer list resends through the state's cloned sender.
623
pub fn send_capture_targets(info: &CallbackInfo, thread_id: ThreadId, targets: CaptureTargets) {
624
    if let Some(thread) = info.get_thread(&thread_id) {
625
        let _delivered: bool = thread.send_message(ThreadSendMsg::Custom(RefAny::new(targets)));
626
    }
627
}
628

            
629
/// Everything a widget's worker needs to run [`run_capture_loop`].
630
#[derive(Debug, Clone, Copy)]
631
pub struct CaptureSession {
632
    /// The platform backend, if the dll registered one.
633
    pub backend: Option<CaptureVTable>,
634
    /// The built-in generator shown when there is no backend or it fails to
635
    /// open (so a widget is never blank).
636
    pub test_pattern: CaptureVTable,
637
    /// Source / fps / exclusion; the size is filled in per reopen.
638
    pub request: CaptureRequest,
639
    /// See [`required_capture_size`].
640
    pub floor: Option<(u32, u32)>,
641
    /// See [`required_capture_size`].
642
    pub fallback: (u32, u32),
643
    /// The widget's writeback (its `extern "C"` wrapper around
644
    /// [`present_captured`]).
645
    pub writeback: WriteBackCallbackType,
646
    /// The scaler for the fan-out ([`frame_resampler`]).
647
    pub resample: ResampleFn,
648
    /// Minimum milliseconds between two reopens ([`REOPEN_COOLDOWN_MS`] for
649
    /// the widgets; tests set zero).
650
    pub reopen_cooldown_ms: u64,
651
}
652

            
653
/// How long (ms) the worker waits for layout to report a preview size before
654
/// it opens the device at the fallback size. Layout runs right after mount,
655
/// so this is normally a few ms; it bounds the wait when a tile is never
656
/// laid out (display: none).
657
const PREVIEW_SIZE_GRACE_MS: u64 = 150;
658
/// Minimum milliseconds between two reopens, so a window-edge drag (hundreds
659
/// of `NodeResized`s) costs at most one device restart per second.
660
pub const REOPEN_COOLDOWN_MS: u64 = 1000;
661

            
662
/// Milliseconds since `since` on the engine clock (`azul_core::task::Instant`
663
/// — never `std::time::Instant`, which panics on wasm).
664
64
fn millis_since(since: &azul_core::task::Instant) -> u64 {
665
64
    azul_core::task::Instant::now()
666
64
        .duration_since(since)
667
64
        .as_millis_u64()
668
64
}
669

            
670
/// THE capture worker: one loop for the camera and the screen widgets.
671
///
672
/// 1. Learn the targets (wait briefly for the first preview size so the device is opened at the
673
///    size the tile needs, not at a default that is reopened a frame later).
674
/// 2. Open the backend at [`required_capture_size`]; on failure the test pattern.
675
/// 3. Per frame: poll the control channel (new targets / terminate), reconfigure or reopen when
676
///    [`needs_reopen`] says so (rate-limited), read a frame, drop it if the previous one is still
677
///    in flight, else cut the preview and every consumer from it OFF the main thread
678
///    ([`image_scale::fan_out`]) and queue one [`CapturedFrames`] writeback.
679
/// 4. `Ended` / a dead main thread / terminate -> close + return.
680
#[allow(clippy::too_many_lines)] // one loop, documented step by step above
681
9
pub fn run_capture_loop(
682
9
    session: CaptureSession,
683
9
    mut targets: CaptureTargets,
684
9
    sender: &mut ThreadSender,
685
9
    recv: &mut ThreadReceiver,
686
9
) {
687
    // 1. Wait (briefly) for the preview size if we do not have one.
688
9
    if targets.preview.is_none() {
689
4
        let started = azul_core::task::Instant::now();
690
63
        while targets.preview.is_none() && millis_since(&started) < PREVIEW_SIZE_GRACE_MS {
691
61
            if poll_capture_control(recv, &mut targets) {
692
2
                return;
693
59
            }
694
59
            std::thread::sleep(std::time::Duration::from_millis(5));
695
        }
696
5
    }
697

            
698
    // 2. Open.
699
7
    let mut required = required_capture_size(session.floor, &targets, session.fallback);
700
7
    let mut request = session.request.with_size(required.0, required.1);
701
7
    let (mut backend, mut handle) = open_with_fallback(&session, &request);
702
7
    if handle == 0 {
703
        return;
704
7
    }
705
7
    let mut requested = required;
706
7
    let mut delivered: Option<(u32, u32)> = None;
707
7
    let mut last_open = azul_core::task::Instant::now();
708
7
    let in_flight = Arc::new(AtomicBool::new(false));
709
7
    let mut buf: Vec<u8> = Vec::new();
710

            
711
    // 3. Frames.
712
    loop {
713
18
        if poll_capture_control(recv, &mut targets) {
714
            break;
715
18
        }
716
18
        required = required_capture_size(session.floor, &targets, session.fallback);
717
18
        if needs_reopen(requested, delivered.unwrap_or(requested), required)
718
1
            && millis_since(&last_open) >= session.reopen_cooldown_ms
719
        {
720
1
            request = request.with_size(required.0, required.1);
721
1
            let reconfigured = backend
722
1
                .reconfigure
723
1
                .is_some_and(|reconfigure| reconfigure(handle, &request));
724
1
            if !reconfigured {
725
1
                (backend.close)(handle);
726
1
                let (b, h) = open_with_fallback(&session, &request);
727
1
                if h == 0 {
728
                    return;
729
1
                }
730
1
                backend = b;
731
1
                handle = h;
732
            }
733
1
            requested = required;
734
1
            delivered = None;
735
1
            last_open = azul_core::task::Instant::now();
736
17
        }
737

            
738
18
        let (fw, fh) = match (backend.read)(handle, &mut buf) {
739
13
            CaptureRead::Frame { width, height } if width > 0 && height > 0 => (width, height),
740
5
            CaptureRead::Frame { .. } | CaptureRead::Ended => break,
741
            CaptureRead::Idle => continue,
742
        };
743
13
        delivered = Some((fw, fh));
744
13
        if in_flight.load(Ordering::Acquire) {
745
            // The main thread has not presented the previous frame yet: drop
746
            // this one (the next read brings a newer one) rather than queue it.
747
6
            continue;
748
7
        }
749
7
        let captured = cut_frame(&targets, &mut buf, fw, fh, session.resample, &in_flight);
750
7
        in_flight.store(true, Ordering::Release);
751
7
        let sent = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
752
7
            WriteBackCallback::new(session.writeback),
753
7
            RefAny::new(captured),
754
7
        )));
755
7
        if !sent {
756
2
            break;
757
5
        }
758
    }
759

            
760
    // 4. Done.
761
7
    (backend.close)(handle);
762
9
}
763

            
764
/// Open the platform backend, else the test pattern. `(vtable, handle)`;
765
/// handle `0` if even the test pattern refuses (a zero-sized request).
766
8
fn open_with_fallback(session: &CaptureSession, request: &CaptureRequest) -> (CaptureVTable, u64) {
767
8
    if let Some(backend) = session.backend {
768
6
        let handle = (backend.open)(request);
769
6
        if handle != 0 {
770
6
            return (backend, handle);
771
        }
772
2
    }
773
2
    let pattern = session.test_pattern;
774
2
    let handle = (pattern.open)(request);
775
2
    (pattern, handle)
776
8
}
777

            
778
/// Cut the preview and every consumer from the captured frame in `buf`
779
/// (RGBA8 `fw` x `fh`), moving the pixels out only when the source frame
780
/// itself must travel (hook wants it, or no preview cut).
781
7
fn cut_frame(
782
7
    targets: &CaptureTargets,
783
7
    buf: &mut Vec<u8>,
784
7
    fw: u32,
785
7
    fh: u32,
786
7
    resample: ResampleFn,
787
7
    in_flight: &Arc<AtomicBool>,
788
7
) -> CapturedFrames {
789
7
    let src = SrcImage {
790
7
        bytes: buf.as_slice(),
791
7
        format: azul_core::resources::RawImageFormat::RGBA8,
792
7
        width: fw,
793
7
        height: fh,
794
7
    };
795
7
    let preview = preview_cut_size(targets, (fw, fh)).and_then(|(pw, ph)| {
796
2
        let rgba = image_scale::cut(&src, pw, ph, resample);
797
2
        (!rgba.is_empty()).then(|| VideoFrame::new(pw, ph, rgba.into()))
798
2
    });
799
7
    let consumers = image_scale::fan_out(&src, &targets.consumers, resample);
800
7
    let source = (targets.wants_source || preview.is_none())
801
7
        .then(|| VideoFrame::new(fw, fh, core::mem::take(buf).into()));
802
7
    CapturedFrames {
803
7
        source,
804
7
        preview,
805
7
        consumers,
806
7
        in_flight: in_flight.clone(),
807
7
    }
808
7
}
809

            
810
// ----------------------------------------------------------------------------
811
// Test patterns: the built-in generators behind the same vtable, so the
812
// worker has ONE loop whether or not a platform backend exists.
813
// ----------------------------------------------------------------------------
814

            
815
/// Which built-in pattern a capture widget shows without a backend.
816
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
817
pub enum TestPattern {
818
    /// A solid frame whose colour cycles per frame (the camera widget's).
819
    ColourCycle,
820
    /// A light band scrolling down a dark frame (the screen widget's).
821
    MovingBand,
822
}
823

            
824
struct TestPatternState {
825
    kind: TestPattern,
826
    width: u32,
827
    height: u32,
828
    tick: u32,
829
}
830

            
831
/// Interval between two test-pattern frames (~30 fps).
832
const TEST_PATTERN_FRAME: std::time::Duration = std::time::Duration::from_millis(33);
833

            
834
5
fn test_pattern_open(request: &CaptureRequest, kind: TestPattern) -> u64 {
835
5
    if request.width == 0 || request.height == 0 {
836
1
        return 0;
837
4
    }
838
4
    Box::into_raw(Box::new(TestPatternState {
839
4
        kind,
840
4
        width: request.width,
841
4
        height: request.height,
842
4
        tick: 0,
843
4
    })) as u64
844
5
}
845

            
846
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/counter/fixed-point cast
847
4
fn test_pattern_read(handle: u64, out: &mut Vec<u8>) -> CaptureRead {
848
    // SAFETY: `handle` is a `Box<TestPatternState>` from `test_pattern_open`,
849
    // alive until `test_pattern_close`; the worker never reads after close.
850
4
    let Some(state) = (unsafe { (handle as *mut TestPatternState).as_mut() }) else {
851
        return CaptureRead::Ended;
852
    };
853
4
    if state.tick > 0 {
854
        std::thread::sleep(TEST_PATTERN_FRAME);
855
4
    }
856
4
    let (w, h) = (state.width as usize, state.height as usize);
857
4
    out.clear();
858
4
    out.reserve(w * h * 4);
859
4
    match state.kind {
860
        TestPattern::ColourCycle => {
861
3
            let tick = state.tick;
862
3
            let color = [
863
3
                (tick % 256) as u8,
864
3
                (tick.wrapping_mul(2) % 256) as u8,
865
3
                (tick.wrapping_mul(3) % 256) as u8,
866
3
                255u8,
867
3
            ];
868
307212
            for _ in 0..w * h {
869
307212
                out.extend_from_slice(&color);
870
307212
            }
871
3
            state.tick = state.tick.wrapping_add(8);
872
        }
873
        TestPattern::MovingBand => {
874
1
            let band = (state.tick as usize) % h.max(1);
875
20
            for y in 0..h {
876
20
                let v = if y.abs_diff(band) < 8 { 235u8 } else { 28u8 };
877
60
                for _ in 0..w {
878
60
                    out.extend_from_slice(&[v, v, v, 255]);
879
60
                }
880
            }
881
1
            state.tick = state.tick.wrapping_add(12);
882
        }
883
    }
884
4
    CaptureRead::Frame {
885
4
        width: state.width,
886
4
        height: state.height,
887
4
    }
888
4
}
889

            
890
4
fn test_pattern_close(handle: u64) {
891
4
    if handle != 0 {
892
4
        // SAFETY: the handle came from `Box::into_raw` in `test_pattern_open`
893
4
        // and is closed exactly once by the worker.
894
4
        drop(unsafe { Box::from_raw(handle as *mut TestPatternState) });
895
4
    }
896
4
}
897

            
898
4
fn colour_cycle_open(request: &CaptureRequest) -> u64 {
899
4
    test_pattern_open(request, TestPattern::ColourCycle)
900
4
}
901
1
fn moving_band_open(request: &CaptureRequest) -> u64 {
902
1
    test_pattern_open(request, TestPattern::MovingBand)
903
1
}
904

            
905
/// The vtable of a built-in test pattern.
906
#[must_use]
907
11
pub const fn test_pattern_vtable(kind: TestPattern) -> CaptureVTable {
908
    CaptureVTable {
909
11
        open: match kind {
910
9
            TestPattern::ColourCycle => colour_cycle_open,
911
2
            TestPattern::MovingBand => moving_band_open,
912
        },
913
11
        read: test_pattern_read,
914
11
        close: test_pattern_close,
915
11
        reconfigure: None,
916
    }
917
11
}
918

            
919
#[cfg(test)]
920
#[allow(clippy::too_many_lines)] // table-driven cases; splitting them hides the case list
921
mod autotest_generated {
922
    use std::{
923
        collections::{BTreeMap, HashMap},
924
        panic::{catch_unwind, AssertUnwindSafe},
925
        rc::Rc,
926
        sync::{Arc, Mutex, PoisonError},
927
    };
928

            
929
    use azul_core::{
930
        dom::{Dom, DomId, DomNodeId, NodeId, NodeType},
931
        geom::{LogicalRect, OptionLogicalPosition},
932
        gl::{GLvoid, GenericGlContext, OptionGlContextPtr},
933
        hit_test::ScrollPosition,
934
        refany::OptionRefAny,
935
        resources::{DecodedImage, RendererResources},
936
        styled_dom::{NodeHierarchyItemId, StyledDom},
937
        window::{MonitorVec, RawWindowHandle, RendererType},
938
    };
939
    use azul_css::system::SystemStyle;
940
    use rust_fontconfig::FcFontCache;
941

            
942
    use super::*;
943
    #[cfg(feature = "icu")]
944
    use crate::icu::IcuLocalizerHandle;
945
    use crate::{
946
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
947
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
948
        window::{DomLayoutResult, LayoutWindow},
949
        window_state::FullWindowState,
950
    };
951

            
952
    // ------------------------------------------------------------------
953
    // Fake GL drivers
954
    //
955
    // Every field of `GenericGlContext` is a `*mut c_void` entry point, and
956
    // gl-context-loader null-checks each one before transmuting + calling it
957
    // (returning a default instead). So an all-zero context is a SAFE no-op
958
    // "driver never loaded" GL, and a context with only the three entry points
959
    // this module actually uses filled in is a safe *recording* driver: we can
960
    // observe exactly which GL calls `upload_rgba` / `present_frame` emit, with
961
    // which arguments, entirely off-GPU.
962
    // ------------------------------------------------------------------
963

            
964
    /// The texture name the recording driver hands out from `glGenTextures`.
965
    const RECORDED_TEXTURE_ID: u32 = 42;
966

            
967
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
968
    enum GlCall {
969
        GenTextures {
970
            n: i32,
971
        },
972
        BindTexture {
973
            target: u32,
974
            texture: u32,
975
        },
976
        TexImage2d {
977
            target: u32,
978
            level: i32,
979
            internal_format: i32,
980
            width: i32,
981
            height: i32,
982
            border: i32,
983
            format: u32,
984
            ty: u32,
985
            /// `false` = the `NULL` pixel pointer `Texture::allocate_rgba8` uses,
986
            /// `true` = a real pixel upload (what `upload_rgba` does).
987
            has_pixels: bool,
988
        },
989
    }
990

            
991
    static GL_LOG: Mutex<Vec<GlCall>> = Mutex::new(Vec::new());
992
    /// Serializes the tests that use the (process-global) recording driver.
993
    static GL_SERIAL: Mutex<()> = Mutex::new(());
994

            
995
    fn gl_log_push(call: GlCall) {
996
        GL_LOG
997
            .lock()
998
            .unwrap_or_else(PoisonError::into_inner)
999
            .push(call);
    }
    extern "system" fn rec_gen_textures(n: i32, out: *mut u32) {
        gl_log_push(GlCall::GenTextures { n });
        // The caller (gl-context-loader) always passes a `Vec<GLuint>` of len `n`.
        for i in 0..n.max(0) {
            // SAFETY: `out` addresses `n` writable `GLuint`s (a `vec![0; n]`).
            unsafe { out.add(i as usize).write(RECORDED_TEXTURE_ID + i as u32) };
        }
    }
    extern "system" fn rec_bind_texture(target: u32, texture: u32) {
        gl_log_push(GlCall::BindTexture { target, texture });
    }
    #[allow(clippy::too_many_arguments)] // must mirror glTexImage2D exactly
    extern "system" fn rec_tex_image_2d(
        target: u32,
        level: i32,
        internal_format: i32,
        width: i32,
        height: i32,
        border: i32,
        format: u32,
        ty: u32,
        pixels: *const GLvoid,
    ) {
        gl_log_push(GlCall::TexImage2d {
            target,
            level,
            internal_format,
            width,
            height,
            border,
            format,
            ty,
            has_pixels: !pixels.is_null(),
        });
    }
    /// A GL context whose entry points are all `NULL` (driver never loaded).
    fn null_gl_context() -> GlContextPtr {
        // SAFETY: every field of `GenericGlContext` is a raw pointer, for which
        // the all-zero (NULL) bit pattern is valid.
        let ctx: GenericGlContext = unsafe { core::mem::zeroed() };
        GlContextPtr::new(RendererType::Software, Rc::new(ctx))
    }
    /// A GL context that records the calls this module makes (and nothing else:
    /// `glTexParameteri` / `glGetIntegerv` / `glDeleteTextures` stay NULL, i.e.
    /// safe no-ops).
    fn recording_gl_context() -> GlContextPtr {
        // SAFETY: as above — NULL is a valid value for every field; the three we
        // overwrite get fn pointers with exactly the signatures gl-context-loader
        // transmutes them back to.
        let mut ctx: GenericGlContext = unsafe { core::mem::zeroed() };
        ctx.glGenTextures = rec_gen_textures as *const () as *mut azul_core::gl::c_void;
        ctx.glBindTexture = rec_bind_texture as *const () as *mut azul_core::gl::c_void;
        ctx.glTexImage2D = rec_tex_image_2d as *const () as *mut azul_core::gl::c_void;
        GlContextPtr::new(RendererType::Software, Rc::new(ctx))
    }
    /// Runs `f` against the recording driver and returns the GL calls it made.
    fn with_recorded_gl<R>(f: impl FnOnce(GlContextPtr) -> R) -> (R, Vec<GlCall>) {
        let _serial = GL_SERIAL.lock().unwrap_or_else(PoisonError::into_inner);
        GL_LOG
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clear();
        let out = f(recording_gl_context());
        let log = GL_LOG
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        (out, log)
    }
    // ------------------------------------------------------------------
    // CallbackInfo harness (mirrors the other widget test modules)
    // ------------------------------------------------------------------
    /// A `DomLayoutResult` with an *empty* layout tree: the code under test only
    /// walks `styled_dom.node_data`, so no real layout (and no font) is needed.
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
        DomLayoutResult {
            styled_dom,
            layout_tree: LayoutTree {
                nodes: Vec::new(),
                warm: Vec::new(),
                cold: Vec::new(),
                root: 0,
                dom_to_layout: BTreeMap::new(),
                children_arena: Vec::new(),
                children_offsets: Vec::new(),
                subtree_needs_intrinsic: Vec::new(),
            },
            calculated_positions: Vec::new(),
            viewport: LogicalRect::zero(),
            display_list: Arc::new(DisplayList::default()),
            scroll_ids: HashMap::new(),
            scroll_id_to_node_id: HashMap::new(),
        }
    }
    /// Invokes `f` with a `CallbackInfo` over a window holding `styled` (or no
    /// layout results at all, when `styled` is `None`) and the given GL context.
    /// Returns `f`'s value plus every `CallbackChange` the callback recorded.
    fn with_callback_info<R>(
        styled: Option<StyledDom>,
        gl_context: OptionGlContextPtr,
        f: impl FnOnce(&mut CallbackInfo) -> R,
    ) -> (R, Vec<CallbackChange>) {
        let mut layout_window =
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
        if let Some(sd) = styled {
            layout_window
                .layout_results
                .insert(DomId::ROOT_ID, layout_result(sd));
        }
        let renderer_resources = RendererResources::default();
        let previous_window_state: Option<FullWindowState> = None;
        let current_window_state = FullWindowState::default();
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
            BTreeMap::new();
        let window_handle = RawWindowHandle::Unsupported;
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
        let ref_data = CallbackInfoRefData {
            layout_window: &layout_window,
            renderer_resources: &renderer_resources,
            previous_window_state: &previous_window_state,
            current_window_state: &current_window_state,
            gl_context: &gl_context,
            current_scroll_manager: &scroll_states,
            current_window_handle: &window_handle,
            system_callbacks: &system_callbacks,
            system_style: Arc::new(SystemStyle::default()),
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
            #[cfg(feature = "icu")]
            icu_localizer: IcuLocalizerHandle::default(),
            ctx: OptionRefAny::None,
        };
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
        let mut info = CallbackInfo::new(
            &ref_data,
            &changes,
            DomNodeId {
                dom: DomId::ROOT_ID,
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0))),
            },
            OptionLogicalPosition::None,
            OptionLogicalPosition::None,
        );
        let out = f(&mut info);
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
        (out, recorded)
    }
    // ------------------------------------------------------------------
    // Fixtures
    // ------------------------------------------------------------------
    /// The MARKER a capture widget stamps on its tile node (and stores in its
    /// dataset) so the writeback can resolve the node again.
    const CAM_MARKER: &str = "azul-camera-test";
    /// A *different* marker, to prove the lookup is exact-string-scoped.
    const OTHER_MARKER: &str = "azul-other-test";
    /// A `div`, carrying `marker` when there is one.
    fn div_with(marker: Option<&str>) -> Dom {
        let d = Dom::create_node(NodeType::Div);
        match marker {
            Some(m) => d.with_marker(Some(AzString::from(m)).into()),
            None => d,
        }
    }
    /// `body(0) -> div(1) -> div(2)`, where a `Some(marker)` stamps that div.
    fn dom_with_markers(first: Option<&str>, second: Option<&str>) -> StyledDom {
        let dom = Dom::create_node(NodeType::Body)
            .with_child(div_with(first))
            .with_child(div_with(second));
        let styled = StyledDom::create_from_dom(dom);
        assert_eq!(
            styled.node_hierarchy.as_ref().len(),
            3,
            "fixture must flatten to exactly body + 2 divs"
        );
        styled
    }
    /// A `width` x `height` RGBA8 frame with a deterministic (tightly-packed) ramp.
    /// Only ever called with tiny dimensions — `width * height * 4` is allocated.
    fn frame(width: u32, height: u32) -> VideoFrame {
        let len = (width as usize) * (height as usize) * 4;
        let bytes: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
        VideoFrame::new(width, height, bytes.into())
    }
    /// A frame whose *declared* dimensions need not match its byte count.
    fn frame_raw(width: u32, height: u32, bytes: Vec<u8>) -> VideoFrame {
        VideoFrame::new(width, height, bytes.into())
    }
    /// Every image installed on a node, as `(dom, node index, image, update type)`.
    fn image_installs(
        changes: &[CallbackChange],
    ) -> Vec<(DomId, usize, &ImageRef, UpdateImageType)> {
        changes
            .iter()
            .filter_map(|c| match c {
                CallbackChange::ChangeNodeImage {
                    dom_id,
                    node_id,
                    image,
                    update_type,
                } => Some((*dom_id, node_id.index(), image, *update_type)),
                _ => None,
            })
            .collect()
    }
    /// How many "recomposite, don't relayout" requests the callback made.
    fn recomposites(changes: &[CallbackChange]) -> usize {
        changes
            .iter()
            .filter(|c| matches!(c, CallbackChange::UpdateAllImageCallbacks))
            .count()
    }
    // ==================================================================
    // invoke_on_frame
    // ==================================================================
    /// Payload of the `on_frame` hook: records every frame it is handed.
    #[derive(Debug)]
    struct HookLog {
        seen: Vec<(u32, u32, usize, Option<u8>)>,
        reply: Update,
    }
    extern "C" fn hook_record(mut data: RefAny, _: CallbackInfo, frame: VideoFrame) -> Update {
        let mut reply = Update::DoNothing;
        if let Some(mut log) = data.downcast_mut::<HookLog>() {
            let bytes = frame.bytes.as_ref();
            log.seen.push((
                frame.width,
                frame.height,
                bytes.len(),
                bytes.first().copied(),
            ));
            reply = log.reply;
        }
        reply
    }
    /// A hook that writes through the `CallbackInfo` it was handed (by value).
    extern "C" fn hook_recomposite(_: RefAny, mut info: CallbackInfo, _: VideoFrame) -> Update {
        info.update_all_image_callbacks();
        Update::RefreshDomAllWindows
    }
    fn hook(cb: OnVideoFrameCallbackType, data: RefAny) -> OptionOnVideoFrame {
        OptionOnVideoFrame::Some(OnVideoFrame {
            refany: data,
            callback: cb.into(),
        })
    }
    fn hook_seen(data: &mut RefAny) -> Vec<(u32, u32, usize, Option<u8>)> {
        data.downcast_ref::<HookLog>()
            .expect("payload must still be a HookLog")
            .seen
            .clone()
    }
    #[test]
    fn invoke_on_frame_without_a_hook_is_do_nothing_and_touches_nothing() {
        let (update, changes) = with_callback_info(None, OptionGlContextPtr::None, |info| {
            invoke_on_frame(&OptionOnVideoFrame::None, info, &frame(2, 2))
        });
        assert_eq!(
            update,
            Update::DoNothing,
            "an unset on_frame hook must be a no-op"
        );
        assert!(
            changes.is_empty(),
            "an unset hook must not record any change, got {changes:?}"
        );
    }
    #[test]
    fn invoke_on_frame_returns_the_hooks_update_verbatim() {
        for reply in [
            Update::DoNothing,
            Update::RefreshDom,
            Update::RefreshDomAllWindows,
        ] {
            let data = RefAny::new(HookLog {
                seen: Vec::new(),
                reply,
            });
            let h = hook(hook_record, data);
            let (update, _) = with_callback_info(None, OptionGlContextPtr::None, |info| {
                invoke_on_frame(&h, info, &frame(1, 1))
            });
            assert_eq!(
                update, reply,
                "invoke_on_frame must return the user's Update unchanged"
            );
        }
    }
    #[test]
    fn invoke_on_frame_forwards_every_frame_into_the_hooks_shared_refany() {
        let mut data = RefAny::new(HookLog {
            seen: Vec::new(),
            reply: Update::RefreshDom,
        });
        let h = hook(hook_record, data.clone());
        // The hook is handed a *clone* of its RefAny on every invocation — the
        // backreference DI pattern only works if that clone shares the payload.
        with_callback_info(None, OptionGlContextPtr::None, |info| {
            for (w, hgt) in [(1_u32, 1_u32), (2, 3), (4, 4)] {
                invoke_on_frame(&h, info, &frame(w, hgt));
            }
        });
        assert_eq!(
            hook_seen(&mut data),
            vec![(1, 1, 4, Some(0)), (2, 3, 24, Some(0)), (4, 4, 64, Some(0)),],
            "every frame must reach the hook, in order, with its bytes intact"
        );
    }
    #[test]
    fn invoke_on_frame_forwards_degenerate_frames_unvalidated_and_without_panicking() {
        let mut data = RefAny::new(HookLog {
            seen: Vec::new(),
            reply: Update::DoNothing,
        });
        let h = hook(hook_record, data.clone());
        with_callback_info(None, OptionGlContextPtr::None, |info| {
            // 0x0, dimensions that disagree with the byte count, and dimensions
            // whose tight-packing size (w*h*4) overflows usize. `invoke_on_frame`
            // must hand all of them to the hook as-is: it is a pure forwarder and
            // must never multiply the dimensions out.
            invoke_on_frame(&h, info, &frame_raw(0, 0, Vec::new()));
            invoke_on_frame(&h, info, &frame_raw(9, 9, vec![7, 8, 9]));
            invoke_on_frame(&h, info, &frame_raw(u32::MAX, u32::MAX, Vec::new()));
            invoke_on_frame(&h, info, &frame_raw(u32::MAX, 1, vec![255]));
        });
        assert_eq!(
            hook_seen(&mut data),
            vec![
                (0, 0, 0, None),
                (9, 9, 3, Some(7)),
                (u32::MAX, u32::MAX, 0, None),
                (u32::MAX, 1, 1, Some(255)),
            ],
            "invoke_on_frame must forward frames verbatim, without validating them"
        );
    }
    #[test]
    fn invoke_on_frame_hook_writes_through_the_shared_callback_info() {
        // `invoke_on_frame` passes `*info` (CallbackInfo is Copy) — the copy must
        // still write into the *caller's* transaction container.
        let h = hook(hook_recomposite, RefAny::new(0_u8));
        let (update, changes) = with_callback_info(None, OptionGlContextPtr::None, |info| {
            invoke_on_frame(&h, info, &frame(1, 1))
        });
        assert_eq!(update, Update::RefreshDomAllWindows);
        assert_eq!(
            recomposites(&changes),
            1,
            "a change made by the hook must be visible to the widget's writeback"
        );
    }
    // ==================================================================
    // upload_rgba
    // ==================================================================
    #[test]
    fn upload_rgba_forwards_the_texture_id_and_the_rgba8_constants() {
        for id in [0_u32, 1, 7, u32::MAX] {
            let ((), log) = with_recorded_gl(|gl| upload_rgba(&gl, id, &frame(2, 2)));
            assert_eq!(
                log,
                vec![
                    GlCall::BindTexture {
                        target: TEXTURE_2D,
                        texture: id,
                    },
                    GlCall::TexImage2d {
                        target: TEXTURE_2D,
                        level: 0,
                        internal_format: RGBA as i32,
                        width: 2,
                        height: 2,
                        border: 0,
                        format: RGBA,
                        ty: UNSIGNED_BYTE,
                        has_pixels: true,
                    },
                ],
                "upload_rgba must bind exactly texture {id} and upload tightly-packed RGBA8"
            );
        }
    }
    #[test]
    fn upload_rgba_zero_sized_frame_is_forwarded_as_a_0x0_upload() {
        let ((), log) = with_recorded_gl(|gl| upload_rgba(&gl, 3, &frame_raw(0, 0, Vec::new())));
        assert_eq!(
            log,
            vec![
                GlCall::BindTexture {
                    target: TEXTURE_2D,
                    texture: 3,
                },
                GlCall::TexImage2d {
                    target: TEXTURE_2D,
                    level: 0,
                    internal_format: RGBA as i32,
                    width: 0,
                    height: 0,
                    border: 0,
                    format: RGBA,
                    ty: UNSIGNED_BYTE,
                    has_pixels: true,
                },
            ],
            "a 0x0 frame must still be a well-formed (if empty) glTexImage2D, not a panic"
        );
    }
    #[test]
    fn upload_rgba_dimensions_above_i32_max_wrap_to_negative_glsizei() {
        // glTexImage2D takes GLsizei (= i32), so a u32 dimension > i32::MAX is a
        // lossy cast. Assert the *exact* wrapped value: GL then rejects the call
        // with GL_INVALID_VALUE (the frame is dropped) — the cast must never be a
        // debug-mode overflow panic or UB.
        let cases: [(u32, u32, i32, i32); 4] = [
            (i32::MAX as u32, 1, i32::MAX, 1),
            (i32::MAX as u32 + 1, 1, i32::MIN, 1),
            (u32::MAX, u32::MAX, -1, -1),
            (u32::MAX - 1, 2, -2, 2),
        ];
        for (w, h, want_w, want_h) in cases {
            // Empty byte buffer: the huge dimensions must never be multiplied out
            // (that would be a several-exabyte allocation), only cast.
            let ((), log) =
                with_recorded_gl(|gl| upload_rgba(&gl, 1, &frame_raw(w, h, Vec::new())));
            let tex = log
                .iter()
                .find_map(|c| match c {
                    GlCall::TexImage2d { width, height, .. } => Some((*width, *height)),
                    _ => None,
                })
                .expect("upload_rgba must always call glTexImage2D");
            assert_eq!(
                tex,
                (want_w, want_h),
                "{w}x{h} must cast to GLsizei {want_w}x{want_h}"
            );
        }
    }
    #[test]
    fn upload_rgba_against_an_unloaded_driver_is_a_silent_no_op() {
        // is_gl_usable() == false (all entry points NULL): the loader must swallow
        // every call rather than jumping through a NULL function pointer.
        let gl = null_gl_context();
        upload_rgba(&gl, 0, &frame(2, 2));
        upload_rgba(&gl, u32::MAX, &frame_raw(u32::MAX, u32::MAX, Vec::new()));
        upload_rgba(&gl, 1, &frame_raw(0, 0, Vec::new()));
    }
    // ==================================================================
    // present_frame — CPU (no GL context)
    // ==================================================================
    #[test]
    fn present_frame_without_gl_installs_a_raw_image_on_the_marked_node() {
        let styled = dom_with_markers(Some(CAM_MARKER), None);
        let (id, changes) = with_callback_info(Some(styled), OptionGlContextPtr::None, |info| {
            present_frame(info, CAM_MARKER.into(), None, &frame(4, 4))
        });
        // The CPU path never allocates a GL texture, so it must hand back the id it
        // was given (None) rather than inventing one.
        assert_eq!(id, None, "the cpurender path must not invent a texture id");
        let installs = image_installs(&changes);
        assert_eq!(installs.len(), 1, "exactly one image install per frame");
        let (dom_id, node_idx, image, update_type) = installs[0];
        assert_eq!(dom_id, DomId::ROOT_ID);
        assert_eq!(node_idx, 1, "the image must land on the MARKED node");
        assert_eq!(update_type, UpdateImageType::Content);
        match image.get_data() {
            DecodedImage::Raw((descriptor, _)) => {
                assert_eq!(
                    (descriptor.width, descriptor.height),
                    (4, 4),
                    "the installed image must keep the frame's dimensions"
                );
            }
            other => panic!("cpurender must install a raw image, got {other:?}"),
        }
        assert_eq!(
            recomposites(&changes),
            0,
            "the CPU path swaps the node's image instead of recompositing a texture"
        );
    }
    #[test]
    fn present_frame_without_gl_returns_the_current_id_verbatim() {
        for current in [None, Some(0_u32), Some(1), Some(u32::MAX)] {
            let styled = dom_with_markers(Some(CAM_MARKER), None);
            let (id, changes) =
                with_callback_info(Some(styled), OptionGlContextPtr::None, |info| {
                    present_frame(info, CAM_MARKER.into(), current, &frame(2, 2))
                });
            assert_eq!(
                id, current,
                "the cpurender path must round-trip current_id ({current:?}) untouched"
            );
            assert_eq!(
                image_installs(&changes).len(),
                1,
                "the CPU path re-installs the image on *every* frame"
            );
        }
    }
    #[test]
    fn present_frame_without_gl_and_without_a_matching_marker_installs_nothing() {
        // Node carries OTHER_MARKER, the widget looks for CAM_MARKER.
        let styled = dom_with_markers(Some(OTHER_MARKER), None);
        let (id, changes) = with_callback_info(Some(styled), OptionGlContextPtr::None, |info| {
            present_frame(info, CAM_MARKER.into(), Some(9), &frame(2, 2))
        });
        assert_eq!(id, Some(9), "a failed node lookup must not lose the id");
        assert!(
            changes.is_empty(),
            "no node carries the marker, so nothing may be installed: {changes:?}"
        );
    }
    #[test]
    fn present_frame_without_gl_and_without_any_layout_result_installs_nothing() {
        let (id, changes) = with_callback_info(None, OptionGlContextPtr::None, |info| {
            present_frame(info, CAM_MARKER.into(), Some(3), &frame(2, 2))
        });
        assert_eq!(id, Some(3));
        assert!(
            changes.is_empty(),
            "an empty window must not be written to: {changes:?}"
        );
    }
    #[test]
    fn present_frame_without_gl_rejects_a_frame_whose_byte_count_disagrees_with_its_size() {
        // A backend that lies about the frame size (or a short read) must not be
        // able to install a bogus image — RawImage validates len == w*h*4.
        for (w, h, bytes) in [
            (4_u32, 4_u32, vec![0_u8; 3]), // far too short
            (4, 4, vec![0_u8; 63]),        // one byte short
            (4, 4, vec![0_u8; 65]),        // one byte long
            (2, 2, Vec::new()),            // no pixels at all
        ] {
            let styled = dom_with_markers(Some(CAM_MARKER), None);
            let (id, changes) =
                with_callback_info(Some(styled), OptionGlContextPtr::None, |info| {
                    present_frame(
                        info,
                        CAM_MARKER.into(),
                        Some(5),
                        &frame_raw(w, h, bytes.clone()),
                    )
                });
            assert_eq!(id, Some(5), "a rejected frame must not disturb the id");
            assert!(
                changes.is_empty(),
                "a {w}x{h} frame with {} bytes must be rejected, not installed: {changes:?}",
                bytes.len()
            );
        }
    }
    #[test]
    fn present_frame_without_gl_installs_a_degenerate_image_for_a_0x0_frame() {
        // 0*0*4 == 0 == len(bytes), so a 0x0 frame passes RawImage's length check
        // and IS installed (as a 0x0 image). Pin the behaviour: it must at least
        // not panic and must not corrupt the returned id.
        let styled = dom_with_markers(Some(CAM_MARKER), None);
        let (id, changes) = with_callback_info(Some(styled), OptionGlContextPtr::None, |info| {
            present_frame(
                info,
                CAM_MARKER.into(),
                Some(2),
                &frame_raw(0, 0, Vec::new()),
            )
        });
        assert_eq!(id, Some(2));
        let installs = image_installs(&changes);
        assert_eq!(installs.len(), 1);
        match installs[0].2.get_data() {
            DecodedImage::Raw((descriptor, _)) => {
                assert_eq!((descriptor.width, descriptor.height), (0, 0));
            }
            other => panic!("expected a raw image, got {other:?}"),
        }
    }
    #[test]
    fn present_frame_without_gl_survives_dimensions_whose_byte_count_overflows_usize() {
        // ADVERSARIAL: a backend reporting 2^31 x 2^31 makes the CPU path compute
        // `width * height * 4` in usize inside `RawImage::into_loaded_image_source`
        // -> 2^64, which overflows.
        //
        // Today that is an arithmetic-overflow PANIC in a debug build (and a
        // silent wrap to 0 in release, which then *accepts* the empty byte buffer
        // as a valid 2^31 x 2^31 image). Neither is a graceful rejection — see the
        // autotest report. What must hold in *both* modes is the one invariant we
        // can still assert: the caller's texture id is never corrupted, and no GL
        // work is attempted.
        let styled = dom_with_markers(Some(CAM_MARKER), None);
        let (result, _changes) =
            with_callback_info(Some(styled), OptionGlContextPtr::None, |info| {
                catch_unwind(AssertUnwindSafe(|| {
                    present_frame(
                        info,
                        CAM_MARKER.into(),
                        Some(11),
                        &frame_raw(1_u32 << 31, 1_u32 << 31, Vec::new()),
                    )
                }))
            });
        match result {
            Ok(id) => assert_eq!(
                id,
                Some(11),
                "the cpurender path must always hand back current_id"
            ),
            Err(_) => eprintln!(
                "NOTE: present_frame panicked (usize overflow of width*height*4) for a 2^31 x \
                 2^31 frame — a malformed capture backend can take the process down"
            ),
        }
    }
    #[test]
    fn present_frame_targets_exactly_the_node_whose_marker_matches() {
        // Two capture widgets of the same type in one DOM: with per-build
        // markers each writeback resolves ITS OWN node - the old
        // lookup-by-dataset-TYPE ambiguity ("which of the two wins is an
        // internal detail") is gone by construction.
        let second = "azul-camera-test-2";
        let styled = dom_with_markers(Some(CAM_MARKER), Some(second));
        let (id, changes) = with_callback_info(Some(styled), OptionGlContextPtr::None, |info| {
            present_frame(info, second.into(), Some(4), &frame(2, 2))
        });
        assert_eq!(id, Some(4));
        let installs = image_installs(&changes);
        assert_eq!(
            installs.len(),
            1,
            "a frame must never be installed on two nodes at once: {changes:?}"
        );
        assert_eq!(
            installs[0].1, 2,
            "the frame must land on the node carrying ITS marker, not the first capture node in \
             document order"
        );
    }
    #[test]
    fn present_frame_matches_markers_by_string_equality_not_identity() {
        // A marker is a plain string: any `AzString` with the same characters
        // resolves the node, no matter where it was allocated. (What makes two
        // widgets not collide is that `next_capture_marker` never mints the
        // same string twice - not any pointer identity.)
        let styled = dom_with_markers(Some(CAM_MARKER), None);
        let same_chars: AzString = String::from(CAM_MARKER).into(); // a different allocation
        let (id, changes) = with_callback_info(Some(styled), OptionGlContextPtr::None, |info| {
            present_frame(info, same_chars.clone(), None, &frame(2, 2))
        });
        assert_eq!(id, None);
        assert_eq!(
            image_installs(&changes).len(),
            1,
            "an equal-content AzString from a different allocation must resolve the node"
        );
    }
    // ==================================================================
    // present_frame — with a GL context PRESENT (the trap case)
    //
    // A CPU-rendered window can still EXPOSE a GL context. The old code
    // branched on it inside the WIDGET and sent texture-only updates the CPU
    // rasterizer never saw (frozen camera tiles). The contract now: ONE path,
    // no GL calls, always a raw-image ChangeNodeImage through the chokepoint.
    // ==================================================================
    #[test]
    fn present_frame_with_gl_still_installs_a_raw_image_and_touches_no_gl() {
        let styled = dom_with_markers(Some(CAM_MARKER), None);
        let ((id, changes), log) = with_recorded_gl(|gl| {
            with_callback_info(Some(styled), OptionGlContextPtr::Some(gl), |info| {
                present_frame(info, CAM_MARKER.into(), None, &frame(4, 4))
            })
        });
        assert_eq!(
            id, None,
            "current_id passes through unchanged (no texture pool)"
        );
        assert!(
            log.is_empty(),
            "the widget must not branch on the GL context — no GL call is ever made: {log:?}"
        );
        let installs = image_installs(&changes);
        assert_eq!(installs.len(), 1, "exactly one ChangeNodeImage per frame");
        assert_eq!(installs[0].1, 1);
        assert_eq!(installs[0].3, UpdateImageType::Content);
        match installs[0].2.get_data() {
            DecodedImage::Raw((descriptor, _)) => {
                assert_eq!(
                    (descriptor.width, descriptor.height),
                    (4, 4),
                    "the installed raw image must be sized like the frame"
                );
            }
            other => panic!("a RAW image must be installed on every backend, got {other:?}"),
        }
        assert_eq!(
            recomposites(&changes),
            0,
            "no texture-only recomposite: the chokepoint's paint tier drives the repaint"
        );
    }
    #[test]
    fn present_frame_with_gl_steady_state_reinstalls_the_frame_not_a_texture() {
        // Re-installing per frame is CORRECT now: the chokepoint patches the
        // display list in place (no rebuild), and the ImageRef identity change
        // is exactly what makes the CPU diff damage the tile.
        let styled = dom_with_markers(Some(CAM_MARKER), None);
        let ((id, changes), log) = with_recorded_gl(|gl| {
            with_callback_info(Some(styled), OptionGlContextPtr::Some(gl), |info| {
                present_frame(
                    info,
                    CAM_MARKER.into(),
                    Some(RECORDED_TEXTURE_ID),
                    &frame(4, 4),
                )
            })
        });
        assert_eq!(
            id,
            Some(RECORDED_TEXTURE_ID),
            "a stored id must survive the writeback unchanged"
        );
        assert!(
            log.is_empty(),
            "steady state makes no GL calls either: {log:?}"
        );
        assert_eq!(image_installs(&changes).len(), 1);
        assert_eq!(recomposites(&changes), 0);
    }
    #[test]
    fn present_frame_with_gl_round_trips_extreme_texture_ids() {
        for current in [Some(0_u32), Some(u32::MAX)] {
            let styled = dom_with_markers(Some(CAM_MARKER), None);
            let ((id, changes), log) = with_recorded_gl(|gl| {
                with_callback_info(Some(styled), OptionGlContextPtr::Some(gl), |info| {
                    present_frame(info, CAM_MARKER.into(), current, &frame(1, 1))
                })
            });
            assert_eq!(
                id, current,
                "a stored texture id must survive the writeback unchanged"
            );
            assert!(log.is_empty(), "no GL call for id {current:?}: {log:?}");
            assert_eq!(image_installs(&changes).len(), 1);
        }
    }
    #[test]
    fn present_frame_with_gl_without_a_matching_node_installs_nothing() {
        // The node lookup fails (no node carries the marker): nothing is
        // installed, nothing is allocated, and the id still passes through.
        let styled = dom_with_markers(Some(OTHER_MARKER), None);
        let ((id, changes), log) = with_recorded_gl(|gl| {
            with_callback_info(Some(styled), OptionGlContextPtr::Some(gl), |info| {
                present_frame(info, CAM_MARKER.into(), None, &frame(2, 2))
            })
        });
        assert_eq!(id, None);
        assert!(
            changes.is_empty(),
            "nothing may be installed when no node carries the marker: {changes:?}"
        );
        assert!(log.is_empty(), "and no GL resource may leak: {log:?}");
    }
    // ==================================================================
    // One capture, many consumers: the policy functions
    // ==================================================================
    fn targets(
        preview: Option<(u32, u32)>,
        consumers: &[(u32, u32, u32)],
        wants_source: bool,
    ) -> CaptureTargets {
        CaptureTargets {
            preview,
            consumers: consumers
                .iter()
                .map(|&(id, w, h)| FrameConsumer::new(id, w, h))
                .collect(),
            wants_source,
        }
    }
    #[test]
    fn the_required_capture_size_covers_the_preview_every_consumer_and_the_floor() {
        // "client Bob wants 500x200, the local preview is 100x200" -> 500x200
        let t = targets(Some((100, 200)), &[(7, 500, 200)], false);
        assert_eq!(required_capture_size(None, &t, (640, 480)), (500, 200));
        // an explicit config size is a floor the capture never drops below
        assert_eq!(
            required_capture_size(Some((640, 480)), &t, (1, 1)),
            (640, 480)
        );
        // only a small preview -> capture SMALL (not the 1080p default)
        let t = targets(Some((300, 200)), &[], false);
        assert_eq!(required_capture_size(None, &t, (1920, 1080)), (300, 200));
        // nothing known yet -> the fallback
        assert_eq!(
            required_capture_size(None, &CaptureTargets::default(), (640, 480)),
            (640, 480)
        );
    }
    #[test]
    fn needs_reopen_follows_quality_and_cost_but_never_loops_on_a_preset_snap() {
        // Steady state: a 300x200 tile fed by the 640x480 minimum preset.
        // The request is as small as it gets — this must NOT reopen forever.
        assert!(!needs_reopen((300, 200), (640, 480), (300, 200)));
        // A consumer that fits inside what is delivered needs nothing.
        assert!(!needs_reopen((300, 200), (640, 480), (500, 200)));
        // More than delivered AND more than requested -> reopen (quality).
        assert!(needs_reopen((300, 200), (640, 480), (800, 200)));
        assert!(needs_reopen((300, 200), (640, 480), (300, 600)));
        // Far less than requested on BOTH axes -> reopen (cost).
        assert!(needs_reopen((1280, 720), (1280, 720), (300, 200)));
        // A modest shrink is hysteresis, not a reopen.
        assert!(!needs_reopen((640, 480), (640, 480), (400, 300)));
        assert!(
            !needs_reopen((640, 480), (640, 480), (320, 300)),
            "one axis halved is not enough"
        );
    }
    #[test]
    fn the_preview_is_cut_only_when_its_size_differs_from_the_captured_frame() {
        let same = targets(Some((640, 480)), &[], false);
        assert_eq!(
            preview_cut_size(&same, (640, 480)),
            None,
            "same size = show the source, no copy"
        );
        let smaller = targets(Some((320, 240)), &[], false);
        assert_eq!(preview_cut_size(&smaller, (640, 480)), Some((320, 240)));
        assert_eq!(
            preview_cut_size(&targets(Some((0, 240)), &[], false), (640, 480)),
            None
        );
        assert_eq!(
            preview_cut_size(&targets(None, &[], false), (640, 480)),
            None
        );
    }
    // ==================================================================
    // The shared capture loop over a FAKE backend (no device, no display):
    // the covering size reaches `open`, one frame is fanned out per
    // consumer, back-pressure drops frames, a bigger consumer reopens.
    // ==================================================================
    use std::sync::mpsc::{channel, Receiver, Sender};
    use azul_core::task::{
        ThreadReceiverDestructorCallback, ThreadReceiverInner, ThreadRecvCallback,
    };
    use crate::thread::{ThreadSendCallback, ThreadSenderDestructorCallback, ThreadSenderInner};
    /// The fake backend's diary: every `open` request size, the close count,
    /// and how many frames to deliver before `Ended`. One loop test at a time
    /// (`LOOP_GATE`), because the vtable fns are plain fn pointers with
    /// nowhere else to keep state.
    struct FakeBackend {
        opens: Vec<(u32, u32)>,
        closes: u32,
        frames_left: u32,
        /// Sent into the worker's control channel by the Nth read (1-based).
        inject_on_read: Option<(u32, CaptureTargets)>,
        reads: u32,
        control_tx: Option<Sender<ThreadSendMsg>>,
    }
    static FAKE: Mutex<Option<FakeBackend>> = Mutex::new(None);
    static LOOP_GATE: Mutex<()> = Mutex::new(());
    fn fake_open(r: &CaptureRequest) -> u64 {
        let mut g = FAKE.lock().unwrap_or_else(PoisonError::into_inner);
        let fake = g.as_mut().expect("fake backend installed");
        fake.opens.push((r.width, r.height));
        u64::from(fake.opens.len() as u32) // never 0
    }
    fn fake_read(handle: u64, out: &mut Vec<u8>) -> CaptureRead {
        let mut g = FAKE.lock().unwrap_or_else(PoisonError::into_inner);
        let fake = g.as_mut().expect("fake backend installed");
        fake.reads += 1;
        if let Some((n, t)) = fake.inject_on_read.as_ref() {
            if *n == fake.reads {
                if let Some(tx) = fake.control_tx.as_ref() {
                    drop(tx.send(ThreadSendMsg::Custom(RefAny::new(t.clone()))));
                }
            }
        }
        if fake.frames_left == 0 {
            return CaptureRead::Ended;
        }
        fake.frames_left -= 1;
        // The backend "snaps" to what was last opened: deliver that size,
        // solid blue.
        let (w, h) = fake.opens.last().copied().unwrap_or((1, 1));
        let _ = handle;
        out.clear();
        out.extend((0..w * h).flat_map(|_| [10u8, 20, 200, 255]));
        CaptureRead::Frame {
            width: w,
            height: h,
        }
    }
    fn fake_close(_handle: u64) {
        let mut g = FAKE.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(fake) = g.as_mut() {
            fake.closes += 1;
        }
    }
    const FAKE_VTABLE: CaptureVTable = CaptureVTable {
        open: fake_open,
        read: fake_read,
        close: fake_close,
        reconfigure: None,
    };
    extern "C" fn loop_writeback(_: RefAny, _: RefAny, _: CallbackInfo) -> Update {
        Update::DoNothing
    }
    // Real channels behind the FFI sender/receiver (the framework's own
    // default callbacks are private; these are their bodies).
    extern "C" fn chan_send(sender: *const core::ffi::c_void, msg: ThreadReceiveMsg) -> bool {
        unsafe { &*sender.cast::<Sender<ThreadReceiveMsg>>() }
            .send(msg)
            .is_ok()
    }
    extern "C" fn chan_recv(receiver: *const core::ffi::c_void) -> OptionThreadSendMsg {
        unsafe { &*receiver.cast::<Receiver<ThreadSendMsg>>() }
            .try_recv()
            .ok()
            .into()
    }
    extern "C" fn sender_noop_drop(_: *mut ThreadSenderInner) {}
    extern "C" fn receiver_noop_drop(_: *mut ThreadReceiverInner) {}
    /// One queued writeback, summarised: `(preview size, source size,
    /// consumer cuts as (id, w, h))`.
    type QueuedSummary = (Option<(u32, u32)>, Option<(u32, u32)>, Vec<(u32, u32, u32)>);
    /// Run the shared loop over the fake backend. Returns every payload the
    /// worker queued plus the backend diary `(opens, closes)`.
    fn run_fake_loop(
        initial: CaptureTargets,
        frames: u32,
        inject_on_read: Option<(u32, CaptureTargets)>,
        floor: Option<(u32, u32)>,
    ) -> (Vec<QueuedSummary>, Vec<(u32, u32)>, u32) {
        let _gate = LOOP_GATE.lock().unwrap_or_else(PoisonError::into_inner);
        let (wb_tx, wb_rx) = channel::<ThreadReceiveMsg>();
        let (ctl_tx, ctl_rx) = channel::<ThreadSendMsg>();
        *FAKE.lock().unwrap_or_else(PoisonError::into_inner) = Some(FakeBackend {
            opens: Vec::new(),
            closes: 0,
            frames_left: frames,
            inject_on_read,
            reads: 0,
            control_tx: Some(ctl_tx.clone()),
        });
        let mut sender = ThreadSender::new(ThreadSenderInner {
            ptr: Box::new(wb_tx),
            send_fn: ThreadSendCallback { cb: chan_send },
            destructor: ThreadSenderDestructorCallback {
                cb: sender_noop_drop,
            },
        });
        let mut receiver = ThreadReceiver::new(ThreadReceiverInner {
            ptr: Box::new(ctl_rx),
            recv_fn: ThreadRecvCallback { cb: chan_recv },
            destructor: ThreadReceiverDestructorCallback {
                cb: receiver_noop_drop,
            },
        });
        let session = CaptureSession {
            backend: Some(FAKE_VTABLE),
            test_pattern: test_pattern_vtable(TestPattern::ColourCycle),
            request: CaptureRequest::new(0, 0, 0),
            floor,
            fallback: (640, 480),
            writeback: loop_writeback,
            resample: image_scale::resample_rgba,
            reopen_cooldown_ms: 0,
        };
        run_capture_loop(session, initial, &mut sender, &mut receiver);
        let mut queued = Vec::new();
        while let Ok(ThreadReceiveMsg::WriteBack(mut wb)) = wb_rx.try_recv() {
            let Some(mut c) = wb.refany.downcast_mut::<CapturedFrames>() else {
                panic!("every capture writeback carries CapturedFrames");
            };
            let preview = c.preview.as_ref().map(|f| (f.width, f.height));
            let source = c.source.as_ref().map(|f| (f.width, f.height));
            let cuts = c
                .consumers
                .iter()
                .map(|x| (x.consumer.id, x.frame.width, x.frame.height))
                .collect();
            // Release the latch the way the real writeback does — the NEXT
            // test's loop must not see a stale `true`.
            c.in_flight.store(false, Ordering::Release);
            queued.push((preview, source, cuts));
        }
        let fake = FAKE
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
            .expect("fake backend still installed");
        drop(ctl_tx);
        (queued, fake.opens, fake.closes)
    }
    #[test]
    fn the_loop_opens_at_the_covering_size_and_fans_one_frame_out_per_consumer() {
        // Preview 4x3 + Bob 2x3 -> the device is opened at 4x3 (not 640x480),
        // and the ONE frame read becomes: a preview at 4x3 (= the captured
        // size -> shown as the source, no cut), Bob's 2x3 cut, no separate
        // source (no on_frame hook).
        let initial = targets(Some((4, 3)), &[(7, 2, 3)], false);
        let (queued, opens, closes) = run_fake_loop(initial, 1, None, None);
        assert_eq!(
            opens,
            vec![(4, 3)],
            "opened ONCE at the covering size of every consumer"
        );
        assert_eq!(closes, 1, "closed exactly once on Ended");
        assert_eq!(queued.len(), 1);
        let (preview, source, cuts) = &queued[0];
        assert_eq!(
            *preview, None,
            "a same-size preview is the source frame itself"
        );
        assert_eq!(*source, Some((4, 3)), "…so the source travels to be shown");
        assert_eq!(
            cuts,
            &vec![(7, 2, 3)],
            "Bob gets his 2x3 from the same frame"
        );
    }
    #[test]
    fn the_loop_cuts_a_smaller_preview_and_keeps_the_source_only_for_the_hook() {
        // A 1280x720 floor (an on_frame hook wants the configured frame) with
        // a 160x90 tile: the device is opened at the floor, the preview is a
        // CUT, and the source travels for the hook.
        let initial = targets(Some((160, 90)), &[], true);
        let (queued, opens, _) = run_fake_loop(initial, 1, None, Some((1280, 720)));
        assert_eq!(opens, vec![(1280, 720)]);
        let (preview, source, cuts) = &queued[0];
        assert_eq!(
            *preview,
            Some((160, 90)),
            "the tile gets a frame at ITS device size"
        );
        assert_eq!(
            *source,
            Some((1280, 720)),
            "the hook gets the frame as captured"
        );
        assert!(cuts.is_empty());
        // Without the hook the source stays on the worker side.
        let initial = targets(Some((160, 90)), &[], false);
        let (queued, _, _) = run_fake_loop(initial, 1, None, Some((1280, 720)));
        let (preview, source, _) = &queued[0];
        assert_eq!(*preview, Some((160, 90)));
        assert_eq!(
            *source, None,
            "no hook, a preview cut -> the 3.7 MB source never crosses threads"
        );
    }
    #[test]
    fn back_pressure_keeps_at_most_one_frame_in_flight() {
        // Nothing presents the frames in this test (no main thread), so the
        // latch stays set after the first send: 5 frames are read, ONE is
        // queued, the rest are dropped instead of piling up in the channel.
        let initial = targets(Some((4, 3)), &[], false);
        let (queued, _, closes) = run_fake_loop(initial, 5, None, None);
        assert_eq!(
            queued.len(),
            1,
            "frames read while one is in flight are dropped, not queued"
        );
        assert_eq!(closes, 1);
    }
    #[test]
    fn a_bigger_consumer_reopens_the_source_at_the_new_covering_size() {
        // Opened for a 4x3 preview; the 2nd read injects "Bob wants 16x12":
        // the next iteration reopens at 16x12 (more than delivered AND more
        // than requested) — exactly one close + open.
        let initial = targets(Some((4, 3)), &[], false);
        let bigger = targets(Some((4, 3)), &[(7, 16, 12)], false);
        let (_, opens, closes) = run_fake_loop(initial, 3, Some((2, bigger)), None);
        assert_eq!(
            opens,
            vec![(4, 3), (16, 12)],
            "reopened once, at the new covering size"
        );
        assert_eq!(
            closes, 2,
            "the first source was closed before the reopen, the second on Ended"
        );
    }
    #[test]
    fn a_test_pattern_refuses_a_zero_size_and_cycles_its_colour() {
        let vt = test_pattern_vtable(TestPattern::ColourCycle);
        assert_eq!(
            (vt.open)(&CaptureRequest::new(0, 0, 0)),
            0,
            "a zero-sized pattern is not a frame"
        );
        let h = (vt.open)(&CaptureRequest::new(0, 2, 3));
        assert_ne!(h, 0);
        let mut out = Vec::new();
        assert_eq!(
            (vt.read)(h, &mut out),
            CaptureRead::Frame {
                width: 2,
                height: 3
            }
        );
        assert_eq!(out.len(), 2 * 3 * 4);
        assert!(
            out.chunks_exact(4).all(|px| px == [0, 0, 0, 255]),
            "tick 0 is opaque black"
        );
        (vt.close)(h);
        let vt = test_pattern_vtable(TestPattern::MovingBand);
        let h = (vt.open)(&CaptureRequest::new(0, 3, 20));
        assert_eq!(
            (vt.read)(h, &mut out),
            CaptureRead::Frame {
                width: 3,
                height: 20
            }
        );
        assert_eq!(out.len(), 3 * 20 * 4);
        (vt.close)(h);
    }
    // ==================================================================
    // Backend registries (CaptureVTable / AudioCaptureVTable)
    //
    // The three registries are process-global `OnceLock`s, so each is exercised
    // by exactly ONE test (registering from two tests would race). Each backend
    // fn body is deliberately distinct so the linker cannot fold them onto one
    // address and make the identity assertions vacuous.
    // ==================================================================
    fn open_a(r: &CaptureRequest) -> u64 {
        u64::from(r.index) + u64::from(r.width) * 3 + u64::from(r.height)
    }
    fn read_a(handle: u64, out: &mut Vec<u8>) -> CaptureRead {
        out.clear();
        out.extend_from_slice(&[1, 2, 3, 4]);
        CaptureRead::Frame {
            width: handle as u32,
            height: 1,
        }
    }
    fn close_a(_handle: u64) {}
    fn open_b(r: &CaptureRequest) -> u64 {
        u64::from(r.index) * 7 + u64::from(r.width) + u64::from(r.height) * 11
    }
    fn read_b(_handle: u64, out: &mut Vec<u8>) -> CaptureRead {
        out.push(9);
        CaptureRead::Ended
    }
    fn close_b(_handle: u64) {
        // distinct body: the linker must not fold this onto close_a
        let _ = core::hint::black_box(1_u8);
    }
    fn vtable_a() -> CaptureVTable {
        CaptureVTable {
            open: open_a,
            read: read_a,
            close: close_a,
            reconfigure: None,
        }
    }
    fn vtable_b() -> CaptureVTable {
        CaptureVTable {
            open: open_b,
            read: read_b,
            close: close_b,
            reconfigure: None,
        }
    }
    fn same_vtable(a: CaptureVTable, b: CaptureVTable) -> bool {
        a.open as usize == b.open as usize
            && a.read as usize == b.read as usize
            && a.close as usize == b.close as usize
    }
    #[test]
    fn register_camera_backend_is_first_wins_and_never_overwritten() {
        let before = camera_backend();
        register_camera_backend(vtable_a());
        let first = camera_backend().expect("a backend is registered after the first call");
        // A second registration must be silently ignored, not panic and not swap
        // the vtable out from under a running capture worker.
        register_camera_backend(vtable_b());
        register_camera_backend(vtable_b());
        let after = camera_backend().expect("the backend must still be there");
        assert!(
            same_vtable(first, after),
            "the first registration must win; a later one must not replace it"
        );
        if let Some(pre) = before {
            assert!(
                same_vtable(pre, after),
                "a backend registered before this test must not have been replaced"
            );
        } else {
            assert!(
                same_vtable(vtable_a(), after),
                "camera_backend() must hand back exactly the vtable that was registered"
            );
            // The registered fn pointers must actually be callable through the vtable.
            let r = CaptureRequest::new(1, 2, 3);
            assert_eq!((after.open)(&r), open_a(&r));
            let r = CaptureRequest::new(u32::MAX, u32::MAX, u32::MAX);
            assert_eq!((after.open)(&r), open_a(&r));
            let mut buf = vec![0_u8; 8];
            assert_eq!(
                (after.read)(u64::from(u32::MAX), &mut buf),
                CaptureRead::Frame {
                    width: u32::MAX,
                    height: 1
                }
            );
            assert_eq!(buf, vec![1, 2, 3, 4], "read must be able to resize `out`");
            (after.close)(0);
            (after.close)(u64::MAX);
        }
    }
    #[test]
    fn register_screen_backend_is_independent_of_the_camera_backend() {
        let before = screen_backend();
        register_screen_backend(vtable_b());
        let after = screen_backend().expect("a screen backend is registered");
        if let Some(pre) = before {
            assert!(same_vtable(pre, after), "first registration wins");
        } else {
            assert!(
                same_vtable(vtable_b(), after),
                "the screen registry must hand back the screen vtable"
            );
            // Registering into the screen slot must not have leaked into the
            // camera slot (they are separate OnceLocks).
            if let Some(cam) = camera_backend() {
                assert!(
                    !same_vtable(cam, vtable_b()),
                    "the camera registry must not pick up the screen vtable"
                );
            }
            // `Ended` is the documented end-of-stream signal.
            let mut buf = Vec::new();
            assert_eq!((after.read)(0, &mut buf), CaptureRead::Ended);
        }
    }
    fn mic_open(sample_rate: u32, channels: u16) -> u64 {
        u64::from(sample_rate) * 2 + u64::from(channels)
    }
    fn mic_read(handle: u64, out: &mut Vec<f32>) -> u32 {
        out.clear();
        // NaN / inf / subnormal samples must survive the vtable boundary untouched.
        out.extend_from_slice(&[f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.0]);
        (handle % 3) as u32
    }
    fn mic_close(_handle: u64) {}
    fn mic_open_other(sample_rate: u32, channels: u16) -> u64 {
        u64::from(sample_rate) ^ u64::from(channels)
    }
    fn mic_read_other(_handle: u64, out: &mut Vec<f32>) -> u32 {
        out.push(1.0);
        0
    }
    fn mic_close_other(_handle: u64) {
        let _ = core::hint::black_box(2_u8);
    }
    #[test]
    fn register_mic_backend_is_first_wins_and_passes_f32_samples_through() {
        let before = mic_backend();
        register_mic_backend(AudioCaptureVTable {
            open: mic_open,
            read: mic_read,
            close: mic_close,
        });
        register_mic_backend(AudioCaptureVTable {
            open: mic_open_other,
            read: mic_read_other,
            close: mic_close_other,
        });
        let vt = mic_backend().expect("a mic backend is registered");
        if before.is_none() {
            assert_eq!(
                vt.open as usize, mic_open as usize,
                "the first mic registration must win"
            );
            // Boundary sample rates / channel counts must go through untouched.
            assert_eq!((vt.open)(0, 0), 0);
            assert_eq!((vt.open)(u32::MAX, u16::MAX), mic_open(u32::MAX, u16::MAX));
            let mut samples = Vec::new();
            let frames = (vt.read)(4, &mut samples);
            assert_eq!(frames, 1, "the frame count must be the vtable's, verbatim");
            assert_eq!(samples.len(), 4);
            assert!(samples[0].is_nan(), "a NaN sample must not be normalised");
            assert_eq!(samples[1], f32::INFINITY);
            assert_eq!(samples[2], f32::NEG_INFINITY);
            assert!(
                samples[3] == 0.0 && samples[3].is_sign_negative(),
                "-0.0 must keep its sign bit"
            );
            // `0` is the documented EOF/error return.
            assert_eq!((vt.read)(3, &mut samples), 0);
            (vt.close)(u64::MAX);
        }
    }
}