1
//! Video-playback widget - a "dumb widget" identical in architecture to the
2
//! [`CameraWidget`](super::camera) / [`ScreenCaptureWidget`](super::screencap),
3
//! only the source differs (a video URL/file decoded via vk-video).
4
//! SUPER_PLAN_2 §4 P6, widget pivot.
5
//!
6
//! `VideoWidget::create(config).dom()` → an `<img>` a background decode thread
7
//! keeps fed; each frame goes through [`super::capture_common::present_frame`]
8
//! (GL-texture install-once / re-upload + recomposite). Shared core in
9
//! `capture_common`; this widget is its config + worker. Test-pattern worker
10
//! (scrolling SMPTE colour bars) stands in for the real vk-video decode worker.
11

            
12
use alloc::vec::Vec;
13

            
14
use azul_core::{
15
    callbacks::{Update, VirtualViewCallbackInfo, VirtualViewReturn},
16
    dom::{ComponentEventFilter, DatasetMergeCallbackType, Dom, EventFilter, OptionDom},
17
    geom::LogicalPosition,
18
    refany::{OptionRefAny, RefAny},
19
    resources::{ImageRef, RawImage, RawImageData, RawImageFormat},
20
    task::{ThreadId, ThreadReceiver, ThreadSendMsg},
21
    video::{VideoConfig, VideoFrame},
22
};
23

            
24
use super::capture_common::{
25
    invoke_on_frame, OnVideoFrame, OnVideoFrameCallback, OptionOnVideoFrame,
26
};
27
use azul_css::impl_option_inner; // for impl_widget_callback!'s impl_option!
28

            
29
use crate::{
30
    callbacks::{Callback, CallbackInfo, CallbackType},
31
    http::{HttpClient, OptionHttpClient},
32
    thread::{
33
        OptionThreadPool, Thread, ThreadCallback, ThreadPool, ThreadReceiveMsg, ThreadSender,
34
        ThreadWriteBackMsg, WriteBackCallback,
35
    },
36
};
37

            
38
/// Default decode size for the test pattern (the real decoder reports the
39
/// stream's actual size).
40
const DEFAULT_W: u32 = 1280;
41
const DEFAULT_H: u32 = 720;
42

            
43
/// Live state for one video widget, carried across relayout by
44
/// [`merge_video_state`].
45
#[derive(Debug)]
46
pub struct VideoWidgetState {
47
    /// The requested playback configuration (source + autoplay/loop).
48
    pub config: VideoConfig,
49
    /// `true` once the decode thread has been started.
50
    pub started: bool,
51
    /// The stable external GL texture id once installed.
52
    pub gl_texture_id: Option<u32>,
53
    /// Optional user hook invoked with each decoded frame (effects / save /
54
    /// send). Re-set on every fresh build (see [`merge_video_state`]).
55
    pub on_frame: OptionOnVideoFrame,
56
    /// Optional pre-decoded frames to replay (a `RefAny` holding a
57
    /// `Vec<VideoFrame>`); when set, the replay worker cycles these instead of
58
    /// the built-in test pattern. Carried forward by [`merge_video_state`].
59
    pub frames: OptionRefAny,
60
    /// The off-main-thread streaming decode worker (mirrors the map widget's
61
    /// `fetch_callback`). Installed on mount from [`register_video_decoder`]
62
    /// unless the widget replays [`VideoWidget::with_frames`]. When present,
63
    /// `AfterMount` spawns it on a background `Thread` instead of the replay /
64
    /// test-pattern workers, so the VK decode runs off the main thread.
65
    pub decode_callback: Option<ThreadCallback>,
66
    /// The latest decoded frame to display, as a CPU `ImageRef` (RGBA8). The
67
    /// `VirtualView` render callback ([`video_widget_render`]) reads this on each
68
    /// re-render; [`video_writeback`] stores it and triggers an in-place
69
    /// `VirtualView` re-render - so the frame renders on cpurender AND webrender,
70
    /// exactly like the map widget's tile cache. (Replaces the GL `present_frame`
71
    /// path for video; camera/screencap still use `present_frame`.)
72
    pub current_frame: Option<ImageRef>,
73
    /// The decode worker's `ThreadId` (set by `AfterMount`). Lets the resize callback
74
    /// message the running worker (`info.get_thread(id).sender.send(..)`) so it can
75
    /// re-target the decoder to the new physical-pixel size - a cheap image swap, no
76
    /// relayout. Carried across relayout by [`merge_video_state`].
77
    pub thread_id: Option<ThreadId>,
78
    /// Clone of the worker's main→worker `Sender` (set by `AfterMount`, carried by
79
    /// merge). Lets [`merge_video_state`] - which has no `CallbackInfo` - push a
80
    /// seek to the running worker when `config.timestamp` changes (scrubbing).
81
    pub seek_sender: Option<std::sync::mpsc::Sender<ThreadSendMsg>>,
82
    /// The user's `on_mount` hook, copied from the builder so mount can fire
83
    /// it. Carried across relayout.
84
    pub on_mount: OptionVideoMount,
85
    /// What the decode worker runs on, as the `on_mount` hook last returned it.
86
    /// Written on mount, never by a rebuild (see [`merge_video_state`]).
87
    pub setup: VideoSetup,
88
}
89

            
90
/// The runtime-installed streaming decode worker every video picks up when it
91
/// mounts. Registered once by the dll, where the worker and its decoder
92
/// dependencies live.
93
static VIDEO_DECODER: std::sync::OnceLock<ThreadCallback> = std::sync::OnceLock::new();
94

            
95
/// Install the framework-owned streaming decode worker. The first registration
96
/// wins; returns `false` when one was already installed.
97
2
pub fn register_video_decoder(cb: ThreadCallback) -> bool {
98
2
    VIDEO_DECODER.set(cb).is_ok()
99
2
}
100

            
101
/// Whether a streaming decode worker has been installed.
102
#[must_use]
103
pub fn has_video_decoder() -> bool {
104
    VIDEO_DECODER.get().is_some()
105
}
106

            
107
/// The decode worker's thread-init: what to play, and the connection pool to
108
/// download it through.
109
#[derive(Debug, Clone)]
110
pub struct VideoDecodeInit {
111
    pub config: VideoConfig,
112
    /// From the widget's [`VideoSetup`]. `None` opens a connection of its own.
113
    pub client: OptionHttpClient,
114
}
115

            
116
/// A video-playback widget. `create(config).dom()` yields an `<img>` the
117
/// decode thread keeps fed.
118
#[repr(C)]
119
#[derive(Debug)]
120
pub struct VideoWidget {
121
    /// Source URL + autoplay/loop + format.
122
    pub config: VideoConfig,
123
    /// Optional per-frame user hook (effects / save / send - azul-meet).
124
    pub on_frame: OptionOnVideoFrame,
125
    /// Optional pre-decoded frames to replay (a `RefAny` holding a
126
    /// `Vec<VideoFrame>`); set via [`with_frames`](Self::with_frames). When
127
    /// present the widget cycles these instead of the test pattern.
128
    pub frames: OptionRefAny,
129
    /// Optional hook fired when the widget is mounted, returning the
130
    /// [`VideoSetup`] its decode worker runs on.
131
    pub on_mount: OptionVideoMount,
132
}
133

            
134
impl VideoWidget {
135
    /// Create a video widget for the given config.
136
    #[must_use]
137
51
    pub const fn create(config: VideoConfig) -> Self {
138
51
        Self {
139
51
            config,
140
51
            on_frame: OptionOnVideoFrame::None,
141
51
            frames: OptionRefAny::None,
142
51
            on_mount: OptionVideoMount::None,
143
51
        }
144
51
    }
145

            
146
    /// Set a hook fired when the widget is mounted. It receives the widget's
147
    /// current [`VideoSetup`] and returns the one to use: this is where an app
148
    /// hands the decoder a shared `HttpClient` or `ThreadPool`. Without a hook
149
    /// the decoder downloads over its own connection on its own thread.
150
    ///
151
    /// The decoder runs for as long as the video plays, so a pool keeps one
152
    /// worker busy per playing video.
153
2
    pub fn set_on_mount<C: Into<VideoMountCallback>>(&mut self, data: RefAny, callback: C) {
154
2
        self.on_mount = Some(VideoMount {
155
2
            refany: data,
156
2
            callback: callback.into(),
157
2
        })
158
2
        .into();
159
2
    }
160

            
161
    /// Builder form of [`set_on_mount`](Self::set_on_mount).
162
    #[must_use]
163
2
    pub fn with_on_mount<C: Into<VideoMountCallback>>(mut self, data: RefAny, callback: C) -> Self {
164
2
        self.set_on_mount(data, callback);
165
2
        self
166
2
    }
167

            
168
    /// Set a hook invoked with every decoded frame - for live effects, saving
169
    /// frames into your data model, or sending them over the network
170
    /// (azul-meet).
171
15
    pub fn set_on_frame<C: Into<OnVideoFrameCallback>>(&mut self, data: RefAny, on_frame: C) {
172
15
        self.on_frame = Some(OnVideoFrame {
173
15
            refany: data,
174
15
            callback: on_frame.into(),
175
15
        })
176
15
        .into();
177
15
    }
178

            
179
    /// Builder form of [`set_on_frame`](Self::set_on_frame).
180
    #[must_use]
181
13
    pub fn with_on_frame<C: Into<OnVideoFrameCallback>>(
182
13
        mut self,
183
13
        data: RefAny,
184
13
        on_frame: C,
185
13
    ) -> Self {
186
13
        self.set_on_frame(data, on_frame);
187
13
        self
188
13
    }
189

            
190
    /// Replay a list of already-decoded frames instead of the built-in test
191
    /// pattern: `frames` is a [`RefAny`] holding a `Vec<VideoFrame>`. The
192
    /// background worker cycles them through the shared GL presenter (the same
193
    /// `present_frame` path the camera/screencap widgets use), so callers that
194
    /// decode a clip up front (e.g. `decode_mp4_h264_bytes`) get real pixels on
195
    /// screen. The `RefAny` must carry a `Vec<VideoFrame>`, else playback is
196
    /// skipped and the test pattern shows instead.
197
    #[must_use]
198
18
    pub fn with_frames(mut self, frames: RefAny) -> Self {
199
18
        self.frames = Some(frames).into();
200
18
        self
201
18
    }
202

            
203
    /// Build the widget's DOM: an `<img>` a background thread keeps fed.
204
    ///
205
    /// Replays pre-decoded [`with_frames`](Self::with_frames) if given. Otherwise
206
    /// the widget streams `config.source` through the decode worker the runtime
207
    /// registered ([`register_video_decoder`]), installed when the widget mounts;
208
    /// without one it shows the built-in test pattern. Pools for the decoder come
209
    /// from the `on_mount` hook, never from here: building the `Dom` only
210
    /// describes the UI.
211
    #[must_use]
212
17
    pub fn dom(self) -> Dom {
213
17
        let state = VideoWidgetState {
214
17
            config: self.config,
215
17
            started: false,
216
17
            gl_texture_id: None,
217
17
            on_frame: self.on_frame,
218
17
            frames: self.frames,
219
17
            decode_callback: None,
220
17
            current_frame: None,
221
17
            thread_id: None,
222
17
            seek_sender: None,
223
17
            on_mount: self.on_mount,
224
17
            setup: VideoSetup::new(),
225
17
        };
226
17
        let dataset = RefAny::new(state);
227
17
        let vv_data = dataset.clone();
228

            
229
        // The body is a VirtualView (exactly like the map widget): its render
230
        // callback re-reads `current_frame` from the dataset each re-render and
231
        // builds the `<img>`, so streamed frames render on BOTH cpurender and
232
        // webrender. The background decode worker is started on AfterMount and
233
        // `WriteBack`s frames into `current_frame` + triggers a VirtualView
234
        // re-render in place (no DOM rebuild) — see `video_writeback`. The caller
235
        // sizes the outer node via `.with_css(...)` on the returned Dom.
236
17
        Dom::create_div()
237
17
            .with_dataset(OptionRefAny::Some(dataset.clone()))
238
17
            .with_merge_callback(azul_core::dom::DatasetMergeCallback::from_ptr(merge_video_state))
239
17
            .with_callback(
240
17
                EventFilter::Component(ComponentEventFilter::AfterMount),
241
17
                dataset.clone(),
242
17
                Callback::from_ptr(video_on_after_mount),
243
            )
244
            // Window/layout resize → re-target the decoder to the new physical size
245
            // (a cheap image swap, no relayout). See `video_on_resize`.
246
17
            .with_callback(
247
17
                EventFilter::Component(ComponentEventFilter::NodeResized),
248
17
                dataset,
249
17
                Callback::from_ptr(video_on_resize),
250
            )
251
17
            .with_child(
252
17
                Dom::create_virtual_view(
253
17
                    vv_data,
254
17
                    azul_core::callbacks::VirtualViewCallback::create(video_widget_render),
255
                )
256
17
                .with_css("width: 100%; height: 100%; overflow: hidden;"),
257
            )
258
17
    }
259
}
260

            
261
/// `VirtualView` render callback (mirrors `map_widget_render`): build the `<img>`
262
/// for the latest decoded frame, re-read from the widget's dataset on every
263
/// re-render. The decode worker stores frames into `current_frame` and triggers
264
/// the re-render in place (see [`video_writeback`]), so this renders on both the
265
/// CPU and GPU renderers with no DOM rebuild.
266
25
extern "C" fn video_widget_render(
267
25
    mut data: RefAny,
268
25
    info: VirtualViewCallbackInfo,
269
25
) -> VirtualViewReturn {
270
25
    let bounds = info.get_bounds().get_logical_size();
271
25
    if std::env::var("AZ_VIDEO_FRAMELOG").is_ok() {
272
        eprintln!("[vrender] bounds {}x{}", bounds.width, bounds.height);
273
25
    }
274
    // Defensive (like map_widget_render): a non-finite / non-positive box (layout
275
    // not yet settled, e.g. flex-grow before the parent height resolves) would
276
    // produce a garbage `<img>` size — render nothing until it settles.
277
25
    let dom = if !bounds.width.is_finite()
278
22
        || !bounds.height.is_finite()
279
20
        || bounds.width <= 0.0
280
16
        || bounds.height <= 0.0
281
    {
282
10
        OptionDom::None
283
    } else {
284
15
        data.downcast_ref::<VideoWidgetState>()
285
15
            .map_or(OptionDom::None, |s| {
286
14
                s.current_frame.as_ref().map_or_else(
287
2
                    || {
288
                        // Poster / "no signal" placeholder. Returning None here
289
                        // rendered NOTHING, so a decoder that never produced a
290
                        // frame (missing video-native feature, non-x86_64 target,
291
                        // Vulkan init failure, network stall) was
292
                        // indistinguishable from a black video — the shipped
293
                        // azul-video "black frame" bug. A dead pipeline must be
294
                        // visibly dead.
295
2
                        OptionDom::Some(Dom::create_div().with_css(
296
2
                            "width: 100%; height: 100%; background: #2a2a30; border: 1px solid \
297
2
                             #44444c;",
298
2
                        ))
299
2
                    },
300
12
                    |img| {
301
12
                        OptionDom::Some(
302
12
                            Dom::create_image(img.clone()).with_css("width: 100%; height: 100%;"),
303
12
                        )
304
12
                    },
305
                )
306
14
            })
307
    };
308
25
    VirtualViewReturn {
309
25
        dom,
310
25
        materialized: azul_core::geom::LogicalRect::new(LogicalPosition::zero(), bounds),
311
25
        virtual_rect: azul_core::geom::LogicalRect::new(LogicalPosition::zero(), bounds),
312
25
    }
313
25
}
314

            
315
// --- User hook: on_mount (backreference DI, FFI-exposed) ---
316

            
317
/// What a video's decode worker runs on. Handed to the `on_mount` hook, which
318
/// returns the setup the widget uses from then on.
319
///
320
/// The default shares nothing: the worker downloads over its own connection on
321
/// its own thread, which is also what a widget without an `on_mount` hook does.
322
#[derive(Debug, Clone, PartialEq)]
323
#[repr(C)]
324
pub struct VideoSetup {
325
    /// Connection pool for the download. `None`: a connection of its own.
326
    pub http_client: OptionHttpClient,
327
    /// Workers to run the decoder on. `None`: a thread of its own.
328
    pub thread_pool: OptionThreadPool,
329
}
330

            
331
impl Default for VideoSetup {
332
    fn default() -> Self {
333
        Self::new()
334
    }
335
}
336

            
337
impl VideoSetup {
338
    /// A setup that shares nothing
339
    #[must_use]
340
72
    pub const fn new() -> Self {
341
72
        Self {
342
72
            http_client: OptionHttpClient::None,
343
72
            thread_pool: OptionThreadPool::None,
344
72
        }
345
72
    }
346

            
347
    /// Download the video through a shared connection pool
348
    #[must_use]
349
    pub fn with_http_client(mut self, client: HttpClient) -> Self {
350
        self.http_client = OptionHttpClient::Some(client);
351
        self
352
    }
353

            
354
    /// Run the decoder on a shared thread pool
355
    #[must_use]
356
1
    pub fn with_thread_pool(mut self, pool: ThreadPool) -> Self {
357
1
        self.thread_pool = OptionThreadPool::Some(pool);
358
1
        self
359
1
    }
360
}
361

            
362
/// User hook fired when the video widget is mounted: receives the widget's
363
/// current [`VideoSetup`] and returns the one its decode worker should use.
364
pub type VideoMountCallbackType = extern "C" fn(RefAny, CallbackInfo, VideoSetup) -> VideoSetup;
365
impl_widget_callback!(
366
    VideoMount,
367
    OptionVideoMount,
368
    VideoMountCallback,
369
    VideoMountCallbackType
370
);
371
azul_core::impl_managed_callback! {
372
    wrapper:        VideoMountCallback,
373
    info_ty:        CallbackInfo,
374
    return_ty:      VideoSetup,
375
    default_ret:    VideoSetup::new(),
376
    invoker_static: VIDEO_MOUNT_INVOKER,
377
    invoker_ty:     AzVideoMountCallbackInvoker,
378
    thunk_fn:       az_video_mount_callback_thunk,
379
    setter_fn:      AzApp_setVideoMountCallbackInvoker,
380
    from_handle_fn: AzVideoMountCallback_createFromHostHandle,
381
    extra_args:     [ setup: VideoSetup ],
382
}
383

            
384
/// Everything a video needs before its worker starts, done once it is in the
385
/// tree rather than while `layout()` describes it: the registered decode worker
386
/// (unless the widget replays frames it was given), then whatever the app's
387
/// `on_mount` hook wants the worker to run on.
388
11
fn mount_video(data: &mut RefAny, info: &CallbackInfo) {
389
10
    let (hook, setup) = {
390
11
        let Some(mut s) = data.downcast_mut::<VideoWidgetState>() else {
391
1
            return;
392
        };
393
10
        let replays = matches!(s.frames, OptionRefAny::Some(_));
394
10
        if !s.started && !replays && s.decode_callback.is_none() {
395
2
            s.decode_callback = VIDEO_DECODER.get().cloned();
396
8
        }
397
10
        (s.on_mount.clone(), s.setup.clone())
398
    };
399
10
    let OptionVideoMount::Some(hook) = hook else {
400
9
        return;
401
    };
402
    // The state is released while the hook runs: it is app code and may reach
403
    // back into this widget.
404
1
    let setup = (hook.callback.cb)(hook.refany, *info, setup);
405
1
    if let Some(mut s) = data.downcast_mut::<VideoWidgetState>() {
406
1
        s.setup = setup;
407
1
    }
408
11
}
409

            
410
/// `AfterMount`: start the background decode thread exactly once.
411
8
extern "C" fn video_on_after_mount(mut data: RefAny, mut info: CallbackInfo) -> Update {
412
8
    mount_video(&mut data, &info);
413
    // Mark started exactly once; pull out the streaming decode worker (if any),
414
    // its source, any pre-decoded replay frames, and what to run on.
415
5
    let (decode_cb, config, frames, setup) = {
416
8
        let Some(mut s) = data.downcast_mut::<VideoWidgetState>() else {
417
1
            return Update::DoNothing;
418
        };
419
7
        if s.started {
420
2
            return Update::DoNothing;
421
5
        }
422
5
        s.started = true;
423
5
        let frames = match &s.frames {
424
3
            OptionRefAny::Some(f) => Some(f.clone()),
425
2
            OptionRefAny::None => None,
426
        };
427
5
        (
428
5
            s.decode_callback.clone(),
429
5
            s.config.clone(),
430
5
            frames,
431
5
            s.setup.clone(),
432
5
        )
433
    };
434
5
    let spawn = |init: RefAny, writeback: RefAny, cb: ThreadCallback| match &setup.thread_pool {
435
        OptionThreadPool::Some(pool) => pool.create_thread(init, writeback, cb),
436
5
        OptionThreadPool::None => Thread::create(init, writeback, cb),
437
5
    };
438
    // Priority: off-main streaming decode worker > replay pre-decoded frames >
439
    // built-in test pattern. All feed the same WriteBack -> video_writeback path.
440
5
    if let Some(cb) = decode_cb {
441
        // The worker matches on `config.source` (typed — no RefAny downcast),
442
        // reads `config.timestamp`, and downloads through `client`.
443
3
        let init = RefAny::new(VideoDecodeInit {
444
3
            config,
445
3
            client: setup.http_client.clone(),
446
3
        });
447
3
        let tid = ThreadId::unique();
448
3
        let thread = spawn(init, data.clone(), cb);
449
        // Grab the main→worker sender BEFORE add_thread moves the Thread, so the
450
        // merge callback can push seeks to the worker (scrubbing).
451
3
        let seek_sender = thread.clone_sender();
452
3
        info.add_thread(tid, thread);
453
        // Remember the worker's id (resize messaging) + sender (seek messaging).
454
3
        if let Some(mut s) = data.downcast_mut::<VideoWidgetState>() {
455
3
            s.thread_id = Some(tid);
456
3
            s.seek_sender = seek_sender;
457
3
        }
458
2
    } else if let Some(frames) = frames {
459
2
        info.add_thread(
460
2
            ThreadId::unique(),
461
2
            spawn(
462
2
                frames,
463
2
                data.clone(),
464
2
                ThreadCallback::new(video_replay_worker),
465
2
            ),
466
2
        );
467
2
    } else {
468
        info.add_thread(
469
            ThreadId::unique(),
470
            spawn(
471
                RefAny::new(()),
472
                data.clone(),
473
                ThreadCallback::new(video_test_worker),
474
            ),
475
        );
476
    }
477
5
    Update::DoNothing
478
8
}
479

            
480
/// `NodeResized`: the video box changed physical size (window resize / relayout). Tell
481
/// the running decode worker the new target size via its `ThreadSender` so it scales
482
/// frames to fit OFF the main thread - the UI then does a cheap image swap with no
483
/// interpolation. This is a message, NOT a relayout: returns `DoNothing`.
484
///
485
/// The size is in DEVICE pixels (`capture_common::preview_size_for_node`):
486
/// the logical size undersized a Retina video by 2x.
487
7
extern "C" fn video_on_resize(mut data: RefAny, info: CallbackInfo) -> Update {
488
7
    let tid = match data.downcast_ref::<VideoWidgetState>() {
489
6
        Some(s) => s.thread_id,
490
1
        None => return Update::DoNothing,
491
    };
492
6
    let Some(tid) = tid else {
493
1
        return Update::DoNothing;
494
    };
495
5
    let Some(target) = super::capture_common::preview_size_for_node(&info) else {
496
5
        return Update::DoNothing;
497
    };
498
    if let Some(thread) = info.get_thread(&tid) {
499
        // Best-effort resize notification: if the decode worker has already
500
        // exited, the send fails and there is nothing to do here.
501
        let _ = thread.send_message(ThreadSendMsg::Custom(RefAny::new(target)));
502
    }
503
    Update::DoNothing
504
7
}
505

            
506
/// Background worker (test pattern): SMPTE-style colour bars scrolling
507
/// horizontally ~30x/s. Replaced by the real vk-video decode worker later.
508
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
509
7
extern "C" fn video_test_worker(_init: RefAny, mut sender: ThreadSender, _recv: ThreadReceiver) {
510
    const BARS: [[u8; 3]; 7] = [
511
        [235, 235, 235],
512
        [235, 235, 16],
513
        [16, 235, 235],
514
        [16, 235, 16],
515
        [235, 16, 235],
516
        [235, 16, 16],
517
        [16, 16, 235],
518
    ];
519
7
    let (w, h) = (DEFAULT_W as usize, DEFAULT_H as usize);
520
7
    let mut tick: u32 = 0;
521
    loop {
522
10
        let shift = (tick as usize / 4) % 7;
523
10
        let mut bytes = Vec::with_capacity(w * h * 4);
524
7200
        for _y in 0..h {
525
9216000
            for x in 0..w {
526
9216000
                let c = BARS[((x * 7 / w) + shift) % 7];
527
9216000
                bytes.extend_from_slice(&[c[0], c[1], c[2], 255]);
528
9216000
            }
529
        }
530
10
        let frame = VideoFrame {
531
10
            width: w as u32,
532
10
            height: h as u32,
533
10
            bytes: bytes.into(),
534
10
        };
535
10
        let sent = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
536
10
            WriteBackCallback::new(video_writeback),
537
10
            RefAny::new(frame),
538
10
        )));
539
10
        if !sent {
540
7
            break;
541
3
        }
542
3
        std::thread::sleep(std::time::Duration::from_millis(33));
543
3
        tick = tick.wrapping_add(2);
544
    }
545
7
}
546

            
547
/// Background worker (replay): cycle a caller-supplied `Vec<VideoFrame>` (e.g. a
548
/// clip decoded up front via `decode_mp4_h264_bytes`) ~30x/s through the same
549
/// `WriteBack` -> [`video_writeback`] -> [`super::capture_common::present_frame`]
550
/// path as the test pattern, so real decoded pixels land in the shared GL
551
/// texture. `init` is the `RefAny` handed to
552
/// [`VideoWidget::with_frames`](VideoWidget::with_frames); if it doesn't hold a
553
/// non-empty `Vec<VideoFrame>` the worker just returns.
554
10
extern "C" fn video_replay_worker(
555
10
    mut init: RefAny,
556
10
    mut sender: ThreadSender,
557
10
    _recv: ThreadReceiver,
558
10
) {
559
10
    let frames: Vec<VideoFrame> = match init.downcast_ref::<Vec<VideoFrame>>() {
560
5
        Some(f) => f.clone(),
561
5
        None => return,
562
    };
563
5
    if frames.is_empty() {
564
2
        return;
565
3
    }
566
3
    let mut idx: usize = 0;
567
    loop {
568
12
        let frame = frames[idx % frames.len()].clone();
569
12
        let sent = sender.send(ThreadReceiveMsg::WriteBack(ThreadWriteBackMsg::new(
570
12
            WriteBackCallback::new(video_writeback),
571
12
            RefAny::new(frame),
572
12
        )));
573
12
        if !sent {
574
3
            break;
575
9
        }
576
9
        std::thread::sleep(std::time::Duration::from_millis(33));
577
9
        idx = idx.wrapping_add(1);
578
    }
579
10
}
580

            
581
#[must_use]
582
/// Writeback (main thread): store the decoded frame as the widget's
583
/// `current_frame` (a CPU `ImageRef`) and re-render the `VirtualView` in place so it
584
/// re-reads it - exactly like `map_tile_writeback`.
585
///
586
/// Renders on cpurender AND
587
/// webrender (no GL `present_frame`, no DOM rebuild).
588
16
pub extern "C" fn video_writeback(
589
16
    mut writeback_data: RefAny,
590
16
    mut frame_data: RefAny,
591
16
    mut info: CallbackInfo,
592
16
) -> Update {
593
16
    let hook = writeback_data
594
16
        .downcast_ref::<VideoWidgetState>()
595
16
        .map_or_else(|| OptionOnVideoFrame::None, |s| s.on_frame.clone());
596
16
    let mut user_update = Update::DoNothing;
597
16
    match frame_data.downcast_ref::<VideoFrame>() {
598
15
        Some(frame) => {
599
            // Guard against dimensions whose RGBA byte count overflows `usize`
600
            // before `ImageRef::new_rawimage` validates it against the buffer:
601
            // `width * height * 4` wraps in release (e.g. 2^31 x 2^31 -> 0) so an
602
            // empty buffer would spuriously "match" and store a bogus frame. A
603
            // `checked_mul` that overflows drops the frame — the hook is still
604
            // notified below, exactly as for a byte-count mismatch.
605
15
            let fits = (frame.width as usize)
606
15
                .checked_mul(frame.height as usize)
607
15
                .and_then(|px| px.checked_mul(4))
608
15
                .is_some();
609
15
            if fits {
610
14
                if let Some(img) = ImageRef::new_rawimage(RawImage {
611
14
                    pixels: RawImageData::U8(frame.bytes.clone()),
612
14
                    width: frame.width as usize,
613
14
                    height: frame.height as usize,
614
14
                    premultiplied_alpha: false,
615
14
                    data_format: RawImageFormat::RGBA8,
616
14
                    tag: b"azul-video-frame".to_vec().into(),
617
14
                }) {
618
7
                    if let Some(mut s) = writeback_data.downcast_mut::<VideoWidgetState>() {
619
6
                        s.current_frame = Some(img);
620
6
                    }
621
7
                }
622
1
            }
623
15
            user_update = invoke_on_frame(&hook, &mut info, &frame);
624
        }
625
1
        None => return Update::DoNothing,
626
    }
627
    // Re-render the VirtualView(s) in place so the content callback re-reads the
628
    // freshly-stored `current_frame` (NOT RefreshDom — that would rebuild the DOM
629
    // and orphan the worker's dataset clone). Same trick as `map_tile_writeback`.
630
15
    info.trigger_all_virtual_view_rerender();
631
15
    user_update
632
16
}
633

            
634
/// Carry live state forward across relayout.
635
#[allow(clippy::float_cmp)] // intentional exact compare: change-detection / identity fast-path /
636
                            // cache-key match
637
19
extern "C" fn merge_video_state(mut new_data: RefAny, mut old_data: RefAny) -> RefAny {
638
    // Return the OLD allocation, adopting config forward — the same rule
639
    // `merge_map_tile_cache` documents. The decode worker holds a clone of
640
    // the OLD RefAny (handed over at spawn) and writes every decoded frame
641
    // into it; returning `new_data` re-pointed the DOM at a fresh allocation
642
    // nobody wrote to, so the picture froze on whatever frame existed at
643
    // merge time — the AzVideo demo hit it on the FIRST timeline click
644
    // (its callback returns RefreshDom).
645
19
    let merged_into_old = {
646
19
        let new_guard = new_data.downcast_ref::<VideoWidgetState>();
647
19
        let old_guard = old_data.downcast_mut::<VideoWidgetState>();
648
19
        if let (Some(new_g), Some(mut old_g)) = (new_guard, old_guard) {
649
            // Scrubbing: a changed `config.timestamp` across this relayout → tell the
650
            // worker to seek. Cheap wall-clock reposition (the worker already has the
651
            // decoded frames), result comes back as an image swap — no re-decode here.
652
16
            if old_g.config.timestamp != new_g.config.timestamp {
653
5
                if let Some(snd) = old_g.seek_sender.as_ref() {
654
4
                    drop(snd.send(ThreadSendMsg::Custom(RefAny::new(new_g.config.timestamp))));
655
4
                }
656
11
            }
657
            // Input-source change → tell the worker to re-init the decode (it
658
            // re-resolves/demuxes/decodes the new source); the frame swaps in when ready.
659
16
            if old_g.config.source != new_g.config.source {
660
5
                if let Some(snd) = old_g.seek_sender.as_ref() {
661
5
                    drop(snd.send(ThreadSendMsg::Custom(RefAny::new(
662
5
                        new_g.config.source.clone(),
663
5
                    ))));
664
5
                }
665
11
            }
666
            // Adopt the app-driven config; keep every worker-facing field
667
            // (frames, current_frame, thread_id, seek_sender, started) in the
668
            // allocation the worker actually writes to.
669
16
            old_g.config = new_g.config.clone();
670
16
            old_g.on_frame = new_g.on_frame.clone();
671
            // The hook is adopted; `setup` and the decode worker were installed on
672
            // mount and belong to the running widget, so they stay.
673
16
            old_g.on_mount = new_g.on_mount.clone();
674
16
            true
675
        } else {
676
            // Foreign / mismatched payloads (one side is not this widget's
677
            // state): hand back the NEW payload untouched — there is no
678
            // persistent allocation to preserve, and returning a
679
            // wrong-typed old dataset would poison the node.
680
3
            false
681
        }
682
    };
683
19
    if merged_into_old {
684
16
        old_data
685
    } else {
686
3
        new_data
687
    }
688
19
}
689

            
690
// ============================================================================
691
// Generated adversarial tests
692
// ============================================================================
693

            
694
#[cfg(test)]
695
#[allow(
696
    clippy::too_many_lines,
697
    clippy::cast_possible_truncation,
698
    clippy::float_cmp,
699
    clippy::items_after_statements,
700
    clippy::let_and_return
701
)]
702
mod autotest_generated {
703
    use std::{
704
        collections::BTreeMap,
705
        panic::{catch_unwind, AssertUnwindSafe},
706
        sync::{
707
            atomic::{AtomicUsize, Ordering},
708
            mpsc::{channel, Receiver, Sender},
709
            Arc, Mutex, PoisonError,
710
        },
711
    };
712

            
713
    use azul_core::{
714
        callbacks::{HidpiAdjustedBounds, VirtualViewCallbackReason},
715
        dom::{DomId, DomNodeId, NodeType},
716
        geom::{LogicalSize, OptionLogicalPosition},
717
        gl::OptionGlContextPtr,
718
        hit_test::ScrollPosition,
719
        resources::{DecodedImage, DpiScaleFactor, ImageCache, RendererResources},
720
        styled_dom::NodeHierarchyItemId,
721
        task::{
722
            OptionThreadSendMsg, ThreadReceiverDestructorCallback, ThreadReceiverInner,
723
            ThreadRecvCallback,
724
        },
725
        video::VideoSource,
726
        window::{MonitorVec, RawWindowHandle, WindowTheme},
727
    };
728
    use azul_css::{system::SystemStyle, AzString};
729
    use rust_fontconfig::FcFontCache;
730

            
731
    use super::*;
732
    #[cfg(feature = "icu")]
733
    use crate::icu::IcuLocalizerHandle;
734
    use crate::{
735
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
736
        thread::{
737
            ThreadCallbackType, ThreadSendCallback, ThreadSenderDestructorCallback,
738
            ThreadSenderInner,
739
        },
740
        widgets::capture_common::OnVideoFrameCallbackType,
741
        window::LayoutWindow,
742
        window_state::FullWindowState,
743
    };
744

            
745
    // ==================================================================
746
    // Config fixtures
747
    // ==================================================================
748

            
749
    /// A config with an explicit source + scrub position (everything else
750
    /// pinned so a test only varies what it names).
751
    fn config(source: VideoSource, timestamp: f32) -> VideoConfig {
752
        VideoConfig {
753
            source,
754
            timestamp,
755
            autoplay: true,
756
            looping: false,
757
            output_format: RawImageFormat::BGRA8,
758
        }
759
    }
760

            
761
    fn url_source(host: &str, path: &str) -> VideoSource {
762
        VideoSource::Url(azul_core::url::Url::from_parts("https", host, 443, path))
763
    }
764

            
765
    fn file_source(path: &'static str) -> VideoSource {
766
        VideoSource::File(AzString::from_const_str(path))
767
    }
768

            
769
    fn bytes_source(bytes: Vec<u8>) -> VideoSource {
770
        VideoSource::Bytes(bytes.into())
771
    }
772

            
773
    /// Representative + hostile configs: every `VideoSource` variant (empty and
774
    /// large payloads), a non-ASCII path, and every f32 boundary a scrub
775
    /// position can take (NaN / ±inf / ±0 / MIN / MAX).
776
    fn all_configs() -> Vec<VideoConfig> {
777
        vec![
778
            VideoConfig::default(),
779
            config(url_source("example.com", "/clip.mp4"), 0.0),
780
            config(url_source("", ""), f32::MAX),
781
            config(file_source("/tmp/clip.mp4"), -1.0),
782
            // unicode: emoji + CJK + RTL + a combining mark in the path.
783
            config(
784
                file_source(
785
                    "/tmp/\u{1F3AC}-\u{5F71}\u{7247}-\u{0631}\u{0645}\u{0632}-e\u{0301}.mp4",
786
                ),
787
                f32::NAN,
788
            ),
789
            config(bytes_source(Vec::new()), f32::INFINITY),
790
            config(bytes_source(vec![0xFF; 8192]), f32::NEG_INFINITY),
791
            config(bytes_source(vec![0x00]), f32::MIN),
792
            VideoConfig {
793
                source: file_source("x"),
794
                timestamp: -0.0,
795
                autoplay: false,
796
                looping: true,
797
                output_format: RawImageFormat::R8,
798
            },
799
        ]
800
    }
801

            
802
    /// `VideoConfig` is only `PartialEq`, so a NaN scrub position never compares
803
    /// equal to itself - compare the timestamp bit-exactly instead.
804
    fn assert_same_config(actual: &VideoConfig, expected: &VideoConfig) {
805
        assert_eq!(actual.source, expected.source, "source must round-trip");
806
        assert_eq!(
807
            actual.timestamp.to_bits(),
808
            expected.timestamp.to_bits(),
809
            "timestamp must survive bit-exactly (NaN included)"
810
        );
811
        assert_eq!(actual.autoplay, expected.autoplay);
812
        assert_eq!(actual.looping, expected.looping);
813
        assert_eq!(actual.output_format, expected.output_format);
814
    }
815

            
816
    const CONST_CONFIG: VideoConfig = VideoConfig {
817
        source: VideoSource::File(AzString::from_const_str("/tmp/const-clip.mp4")),
818
        timestamp: 2.5,
819
        autoplay: false,
820
        looping: true,
821
        output_format: RawImageFormat::RGBA8,
822
    };
823

            
824
    /// Compile-time proof that `create` really is a `const fn` - the `const`
825
    /// qualifier is part of the public API, so a non-const `create` must break
826
    /// this file.
827
    const CONST_WIDGET: VideoWidget = VideoWidget::create(CONST_CONFIG);
828

            
829
    // ==================================================================
830
    // State fixtures
831
    // ==================================================================
832

            
833
    /// A freshly-built widget state (exactly what `dom` stores).
834
    fn base_state(config: VideoConfig) -> VideoWidgetState {
835
        VideoWidgetState {
836
            config,
837
            started: false,
838
            gl_texture_id: None,
839
            on_frame: OptionOnVideoFrame::None,
840
            frames: OptionRefAny::None,
841
            decode_callback: None,
842
            current_frame: None,
843
            thread_id: None,
844
            seek_sender: None,
845
            on_mount: OptionVideoMount::None,
846
            setup: VideoSetup::new(),
847
        }
848
    }
849

            
850
    fn state(config: VideoConfig) -> RefAny {
851
        RefAny::new(base_state(config))
852
    }
853

            
854
    /// Everything a test needs to know about a `VideoWidgetState`, read out in
855
    /// one borrow (`downcast_ref` takes `&mut self`, so overlapping reads would
856
    /// otherwise have to nest).
857
    #[derive(Debug, Clone, PartialEq)]
858
    struct StateSummary {
859
        started: bool,
860
        gl_texture_id: Option<u32>,
861
        has_hook: bool,
862
        has_frames: bool,
863
        decode_cb: Option<usize>,
864
        current_frame_id: Option<u64>,
865
        thread_id: Option<ThreadId>,
866
        has_seek_sender: bool,
867
    }
868

            
869
    fn read_state(data: &mut RefAny) -> StateSummary {
870
        let s = data
871
            .downcast_ref::<VideoWidgetState>()
872
            .expect("payload must still be a VideoWidgetState");
873
        StateSummary {
874
            started: s.started,
875
            gl_texture_id: s.gl_texture_id,
876
            has_hook: matches!(s.on_frame, OptionOnVideoFrame::Some(_)),
877
            has_frames: matches!(s.frames, OptionRefAny::Some(_)),
878
            decode_cb: s.decode_callback.as_ref().map(|c| c.cb as usize),
879
            current_frame_id: s.current_frame.as_ref().map(|i| i.id),
880
            thread_id: s.thread_id,
881
            has_seek_sender: s.seek_sender.is_some(),
882
        }
883
    }
884

            
885
    fn read_config(data: &mut RefAny) -> VideoConfig {
886
        data.downcast_ref::<VideoWidgetState>()
887
            .expect("payload must still be a VideoWidgetState")
888
            .config
889
            .clone()
890
    }
891

            
892
    /// The `(width, height)` of every frame in the state's replay list, or
893
    /// `None` when there is no list / it does not hold a `Vec<VideoFrame>`.
894
    fn state_frames(data: &mut RefAny) -> Option<Vec<(u32, u32)>> {
895
        let inner = {
896
            let s = data.downcast_ref::<VideoWidgetState>()?;
897
            match &s.frames {
898
                OptionRefAny::Some(f) => Some(f.clone()),
899
                OptionRefAny::None => None,
900
            }
901
        };
902
        let mut inner = inner?;
903
        let v = inner.downcast_ref::<Vec<VideoFrame>>()?;
904
        Some(v.iter().map(|f| (f.width, f.height)).collect())
905
    }
906

            
907
    /// The `(width, height)` of a widget's `frames` `RefAny` (same shape as
908
    /// `state_frames`, but for the builder-side `VideoWidget`).
909
    fn widget_frames(widget: &VideoWidget) -> Option<Vec<(u32, u32)>> {
910
        let OptionRefAny::Some(f) = &widget.frames else {
911
            return None;
912
        };
913
        let mut f = f.clone();
914
        let v = f.downcast_ref::<Vec<VideoFrame>>()?;
915
        Some(v.iter().map(|fr| (fr.width, fr.height)).collect())
916
    }
917

            
918
    // ---- frames / images --------------------------------------------------
919

            
920
    /// A tightly-packed RGBA frame (`width * height * 4` bytes).
921
    fn frame(width: u32, height: u32) -> VideoFrame {
922
        let px = (width as usize) * (height as usize);
923
        VideoFrame {
924
            width,
925
            height,
926
            bytes: vec![7u8; px * 4].into(),
927
        }
928
    }
929

            
930
    /// A frame whose declared dimensions need NOT match its byte count.
931
    fn frame_raw(width: u32, height: u32, bytes: Vec<u8>) -> VideoFrame {
932
        VideoFrame {
933
            width,
934
            height,
935
            bytes: bytes.into(),
936
        }
937
    }
938

            
939
    /// A zero-allocation stand-in for an already-decoded frame.
940
    fn placeholder_image(tag: &[u8]) -> ImageRef {
941
        ImageRef::null_image(4, 4, RawImageFormat::BGRA8, tag.to_vec())
942
    }
943

            
944
    /// `(width, height)` of the raw CPU image a writeback stored, or `None` if
945
    /// the stored image is not a raw one.
946
    fn raw_dims(img: &ImageRef) -> Option<(usize, usize)> {
947
        match img.get_data() {
948
            DecodedImage::Raw((descriptor, _)) => Some((descriptor.width, descriptor.height)),
949
            _ => None,
950
        }
951
    }
952

            
953
    fn current_frame_dims(data: &mut RefAny) -> Option<(usize, usize)> {
954
        let s = data.downcast_ref::<VideoWidgetState>()?;
955
        raw_dims(s.current_frame.as_ref()?)
956
    }
957

            
958
    // ---- frame hook -------------------------------------------------------
959

            
960
    /// Records every frame the widget's `on_frame` hook is handed, and answers
961
    /// with a caller-chosen `Update`.
962
    struct FrameLog {
963
        seen: Vec<(u32, u32, usize)>,
964
        reply: Update,
965
    }
966

            
967
    extern "C" fn record_frame(mut data: RefAny, _: CallbackInfo, frame: VideoFrame) -> Update {
968
        let mut reply = Update::DoNothing;
969
        if let Some(mut log) = data.downcast_mut::<FrameLog>() {
970
            log.seen
971
                .push((frame.width, frame.height, frame.bytes.as_ref().len()));
972
            reply = log.reply;
973
        }
974
        reply
975
    }
976

            
977
    extern "C" fn frame_do_nothing(_: RefAny, _: CallbackInfo, _: VideoFrame) -> Update {
978
        // A distinct body so the linker cannot fold this onto `record_frame`
979
        // and make the fn-pointer identity assertions vacuous.
980
        core::hint::black_box(Update::DoNothing)
981
    }
982

            
983
    fn frame_log(reply: Update) -> RefAny {
984
        RefAny::new(FrameLog {
985
            seen: Vec::new(),
986
            reply,
987
        })
988
    }
989

            
990
    fn logged_frames(data: &mut RefAny) -> Vec<(u32, u32, usize)> {
991
        data.downcast_ref::<FrameLog>()
992
            .expect("payload must still be a FrameLog")
993
            .seen
994
            .clone()
995
    }
996

            
997
    fn hook_into(log: &RefAny) -> OptionOnVideoFrame {
998
        Some(OnVideoFrame {
999
            refany: log.clone(),
            callback: (record_frame as OnVideoFrameCallbackType).into(),
        })
        .into()
    }
    // ---- thread workers ---------------------------------------------------
    /// A decode worker that returns immediately. Used wherever a test must let
    /// `AfterMount` really spawn a `Thread`: the framework's thread destructor
    /// *joins*, so only a worker that returns on its own can be joined safely.
    extern "C" fn noop_decode_worker(_: RefAny, _: ThreadSender, _: ThreadReceiver) {}
    extern "C" fn other_noop_worker(_: RefAny, _: ThreadSender, _: ThreadReceiver) {
        core::hint::black_box(());
    }
    // ==================================================================
    // CallbackInfo harness
    // ==================================================================
    /// Runs `f` against a real `CallbackInfo` over an empty `LayoutWindow` (no
    /// GL context, no laid-out nodes). Returns `f`'s value plus every
    /// `CallbackChange` the callback recorded.
    fn with_callback_info<R>(f: impl FnOnce(CallbackInfo) -> R) -> (R, Vec<CallbackChange>) {
        let layout_window =
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
        let renderer_resources = RendererResources::default();
        let previous_window_state: Option<FullWindowState> = None;
        let current_window_state = FullWindowState::default();
        let gl_context = OptionGlContextPtr::None;
        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 info = CallbackInfo::new(
            &ref_data,
            &changes,
            DomNodeId {
                dom: DomId::ROOT_ID,
                node: NodeHierarchyItemId::NONE,
            },
            OptionLogicalPosition::None,
            OptionLogicalPosition::None,
        );
        let out = f(info);
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
        (out, recorded)
    }
    fn count_virtual_view_rerenders(changes: &[CallbackChange]) -> usize {
        changes
            .iter()
            .filter(|c| matches!(c, CallbackChange::UpdateAllVirtualViews))
            .count()
    }
    /// The `ThreadId` of the single `AddThread` change, or `None`.
    fn added_thread_id(changes: &[CallbackChange]) -> Option<ThreadId> {
        changes.iter().find_map(|c| match c {
            CallbackChange::AddThread { thread_id, .. } => Some(*thread_id),
            _ => None,
        })
    }
    // ==================================================================
    // VirtualViewCallbackInfo harness
    // ==================================================================
    /// Runs `f` against a `VirtualViewCallbackInfo` reporting `w x h` bounds.
    fn with_virtual_view_info<R>(
        w: f32,
        h: f32,
        f: impl FnOnce(VirtualViewCallbackInfo) -> R,
    ) -> R {
        let fonts = FcFontCache::default();
        let images = ImageCache::default();
        let size = LogicalSize::new(w, h);
        let info = VirtualViewCallbackInfo::new(
            VirtualViewCallbackReason::InitialRender,
            &fonts,
            &images,
            WindowTheme::LightMode,
            azul_core::window::WindowFrame::Normal,
            HidpiAdjustedBounds {
                logical_size: size,
                hidpi_factor: DpiScaleFactor::new(1.0),
            },
            azul_core::geom::LogicalRect::new(LogicalPosition::zero(), size),
            azul_core::geom::LogicalRect::new(LogicalPosition::zero(), size),
            LogicalPosition::zero(),
        );
        f(info)
    }
    /// The `ImageRef` id of the `<img>` a render pass emitted, or `None` when it
    /// emitted no DOM at all.
    fn rendered_image_id(ret: &VirtualViewReturn) -> Option<u64> {
        let OptionDom::Some(dom) = &ret.dom else {
            return None;
        };
        match dom.root.get_node_type() {
            NodeType::Image(img) => Some(img.id),
            other => panic!("the video VirtualView must render an <img>, got {other:?}"),
        }
    }
    fn rendered_nothing(ret: &VirtualViewReturn) -> bool {
        matches!(ret.dom, OptionDom::None)
    }
    // ==================================================================
    // Worker harness
    // ==================================================================
    /// One frame a worker pushed, summarised so the (multi-megabyte) pixel
    /// buffer never has to be cloned into the log.
    #[derive(Debug, Clone, PartialEq, Eq)]
    struct SentFrame {
        width: u32,
        height: u32,
        len: usize,
        /// Distinct RGBA pixels in the first scanline, in first-seen order
        /// (capped, so a pathological frame cannot blow up the log).
        row0_palette: Vec<[u8; 4]>,
        /// Every scanline is byte-identical to the first.
        rows_identical: bool,
        /// The whole pixel buffer - captured only for frames small enough to
        /// compare byte-for-byte (the replay fixtures).
        small_bytes: Option<Vec<u8>>,
    }
    fn summarise(f: &VideoFrame) -> SentFrame {
        let bytes = f.bytes.as_ref();
        let row_len = (f.width as usize).saturating_mul(4);
        let mut row0_palette: Vec<[u8; 4]> = Vec::new();
        if row_len > 0 && bytes.len() >= row_len {
            for px in bytes[..row_len].chunks_exact(4) {
                let px = [px[0], px[1], px[2], px[3]];
                if row0_palette.len() < 32 && !row0_palette.contains(&px) {
                    row0_palette.push(px);
                }
            }
        }
        let rows_identical = row_len == 0
            || bytes.len() < row_len
            || bytes
                .chunks_exact(row_len)
                .all(|row| row == &bytes[..row_len]);
        SentFrame {
            width: f.width,
            height: f.height,
            len: bytes.len(),
            row0_palette,
            rows_identical,
            small_bytes: (bytes.len() <= 4096).then(|| bytes.to_vec()),
        }
    }
    /// Guarded by `WORKER_GATE`: a worker's send callback is a plain C fn
    /// pointer, so it has nowhere but a static to put its result.
    static WORKER_LOG: Mutex<Vec<SentFrame>> = Mutex::new(Vec::new());
    static WORKER_GATE: Mutex<()> = Mutex::new(());
    /// How many more sends are accepted before the harness reports "the main
    /// thread is gone" - the only signal these workers ever stop on.
    static ACCEPT_BUDGET: AtomicUsize = AtomicUsize::new(0);
    extern "C" fn record_then_maybe_stop(
        _sender: *const core::ffi::c_void,
        msg: ThreadReceiveMsg,
    ) -> bool {
        let ThreadReceiveMsg::WriteBack(mut wb) = msg else {
            return false;
        };
        if let Some(f) = wb.refany.downcast_ref::<VideoFrame>() {
            WORKER_LOG
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .push(summarise(&f));
        }
        let left = ACCEPT_BUDGET.load(Ordering::SeqCst);
        if left == 0 {
            return false;
        }
        ACCEPT_BUDGET.store(left - 1, Ordering::SeqCst);
        true
    }
    extern "C" fn sender_drop_noop(_: *mut ThreadSenderInner) {}
    extern "C" fn receiver_drop_noop(_: *mut ThreadReceiverInner) {}
    extern "C" fn recv_nothing(_: *const core::ffi::c_void) -> OptionThreadSendMsg {
        OptionThreadSendMsg::None
    }
    /// A receiver that answers *every* poll with "terminate now".
    extern "C" fn recv_terminate(_: *const core::ffi::c_void) -> OptionThreadSendMsg {
        OptionThreadSendMsg::Some(ThreadSendMsg::TerminateThread)
    }
    fn logging_sender() -> (Receiver<ThreadReceiveMsg>, ThreadSender) {
        let (tx, rx) = channel::<ThreadReceiveMsg>();
        let sender = ThreadSender::new(ThreadSenderInner {
            ptr: Box::new(tx),
            send_fn: ThreadSendCallback {
                cb: record_then_maybe_stop,
            },
            destructor: ThreadSenderDestructorCallback {
                cb: sender_drop_noop,
            },
        });
        (rx, sender)
    }
    fn receiver(terminate: bool) -> (Sender<ThreadSendMsg>, ThreadReceiver) {
        let (tx, rx) = channel::<ThreadSendMsg>();
        let cb: extern "C" fn(*const core::ffi::c_void) -> OptionThreadSendMsg = if terminate {
            recv_terminate
        } else {
            recv_nothing
        };
        let receiver = ThreadReceiver::new(ThreadReceiverInner {
            ptr: Box::new(rx),
            recv_fn: ThreadRecvCallback { cb },
            destructor: ThreadReceiverDestructorCallback {
                cb: receiver_drop_noop,
            },
        });
        (tx, receiver)
    }
    /// Runs `worker` in-process against a sender that accepts `accept` frames
    /// and then reports failure, and returns everything it managed to send.
    /// `terminate` decides whether its receiver answers every poll with
    /// `TerminateThread`.
    fn run_worker(
        worker: ThreadCallbackType,
        init: RefAny,
        accept: usize,
        terminate: bool,
    ) -> Vec<SentFrame> {
        let _gate = WORKER_GATE.lock().unwrap_or_else(PoisonError::into_inner);
        WORKER_LOG
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clear();
        ACCEPT_BUDGET.store(accept, Ordering::SeqCst);
        let (_rx, sender) = logging_sender();
        let (_tx, recv) = receiver(terminate);
        worker(init, sender, recv);
        WORKER_LOG
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }
    /// The SMPTE bars `video_test_worker` hard-codes (duplicated here on
    /// purpose: the palette is observable output, so a silent change to it must
    /// break a test).
    const EXPECTED_BARS: [[u8; 4]; 7] = [
        [235, 235, 235, 255],
        [235, 235, 16, 255],
        [16, 235, 235, 255],
        [16, 235, 16, 255],
        [235, 16, 235, 255],
        [235, 16, 16, 255],
        [16, 16, 235, 255],
    ];
    // ==================================================================
    // Seek-channel helpers (merge_video_state)
    // ==================================================================
    fn custom_f32(msg: &ThreadSendMsg) -> Option<f32> {
        let ThreadSendMsg::Custom(r) = msg else {
            return None;
        };
        let mut r = r.clone();
        let out = r.downcast_ref::<f32>().map(|v| *v);
        out
    }
    fn custom_source(msg: &ThreadSendMsg) -> Option<VideoSource> {
        let ThreadSendMsg::Custom(r) = msg else {
            return None;
        };
        let mut r = r.clone();
        let out = r.downcast_ref::<VideoSource>().map(|v| (*v).clone());
        out
    }
    // ==================================================================
    // VideoWidget::create  (constructor)
    // ==================================================================
    #[test]
    fn create_stores_the_config_verbatim_and_leaves_every_hook_unset() {
        for cfg in all_configs() {
            let widget = VideoWidget::create(cfg.clone());
            assert_same_config(&widget.config, &cfg);
            assert!(
                matches!(widget.on_frame, OptionOnVideoFrame::None),
                "a fresh widget has no frame hook"
            );
            assert!(
                matches!(widget.frames, OptionRefAny::None),
                "a fresh widget has no replay list"
            );
        }
    }
    #[test]
    fn create_is_usable_in_a_const_context() {
        let widget = CONST_WIDGET;
        assert_same_config(&widget.config, &CONST_CONFIG);
        assert!(matches!(widget.on_frame, OptionOnVideoFrame::None));
        assert!(matches!(widget.frames, OptionRefAny::None));
    }
    // ==================================================================
    // VideoWidget::set_on_frame / with_on_frame  (constructor)
    // ==================================================================
    #[test]
    fn with_on_frame_installs_the_hook_and_keeps_the_config() {
        for cfg in all_configs() {
            let widget = VideoWidget::create(cfg.clone()).with_on_frame(
                frame_log(Update::DoNothing),
                record_frame as OnVideoFrameCallbackType,
            );
            assert_same_config(&widget.config, &cfg);
            let OptionOnVideoFrame::Some(hook) = &widget.on_frame else {
                panic!("with_on_frame must install a hook");
            };
            assert_eq!(
                hook.callback.cb as usize, record_frame as OnVideoFrameCallbackType as usize,
                "the installed hook must be exactly the one handed in"
            );
            assert!(
                matches!(widget.frames, OptionRefAny::None),
                "with_on_frame must not invent a replay list"
            );
        }
    }
    #[test]
    fn set_on_frame_twice_keeps_only_the_last_hook() {
        let mut widget = VideoWidget::create(VideoConfig::default());
        widget.set_on_frame(
            RefAny::new(0_usize),
            record_frame as OnVideoFrameCallbackType,
        );
        widget.set_on_frame(
            RefAny::new(1_usize),
            frame_do_nothing as OnVideoFrameCallbackType,
        );
        let OptionOnVideoFrame::Some(hook) = &widget.on_frame else {
            panic!("hook must still be set");
        };
        assert_eq!(
            hook.callback.cb as usize, frame_do_nothing as OnVideoFrameCallbackType as usize,
            "the second set_on_frame must replace the first"
        );
        let mut data = hook.refany.clone();
        assert_eq!(
            data.downcast_ref::<usize>().map(|v| *v),
            Some(1),
            "the second hook's data must replace the first hook's, not merge with it"
        );
    }
    #[test]
    fn set_on_frame_accepts_a_refany_that_is_also_the_widgets_replay_list() {
        // Aliasing the same RefAny into two slots must not panic or deadlock -
        // both are plain shared handles.
        let shared = RefAny::new(vec![frame(1, 1)]);
        let widget = VideoWidget::create(VideoConfig::default())
            .with_frames(shared.clone())
            .with_on_frame(shared, record_frame as OnVideoFrameCallbackType);
        assert!(matches!(widget.on_frame, OptionOnVideoFrame::Some(_)));
        assert_eq!(widget_frames(&widget), Some(vec![(1, 1)]));
    }
    // ==================================================================
    // VideoWidget::with_frames  (constructor)
    // ==================================================================
    #[test]
    fn with_frames_stores_the_list_and_keeps_everything_else() {
        for cfg in all_configs() {
            let widget = VideoWidget::create(cfg.clone())
                .with_frames(RefAny::new(vec![frame(2, 3), frame(4, 5)]));
            assert_same_config(&widget.config, &cfg);
            assert_eq!(widget_frames(&widget), Some(vec![(2, 3), (4, 5)]));
            assert!(
                matches!(widget.on_frame, OptionOnVideoFrame::None),
                "with_frames must not invent a hook"
            );
        }
    }
    #[test]
    fn with_frames_twice_keeps_only_the_last_list() {
        let widget = VideoWidget::create(VideoConfig::default())
            .with_frames(RefAny::new(vec![frame(1, 1)]))
            .with_frames(RefAny::new(vec![frame(9, 9), frame(8, 8)]));
        assert_eq!(widget_frames(&widget), Some(vec![(9, 9), (8, 8)]));
    }
    #[test]
    fn with_frames_accepts_an_empty_and_a_wrong_typed_payload_without_complaint() {
        // Documented: a `RefAny` that does not carry a `Vec<VideoFrame>` is
        // accepted here and only *skipped* later, by the replay worker.
        let empty = VideoWidget::create(VideoConfig::default())
            .with_frames(RefAny::new(Vec::<VideoFrame>::new()));
        assert_eq!(widget_frames(&empty), Some(Vec::new()));
        let foreign = VideoWidget::create(VideoConfig::default()).with_frames(RefAny::new(0_u32));
        assert!(
            matches!(foreign.frames, OptionRefAny::Some(_)),
            "the builder stores whatever it is given"
        );
        assert_eq!(
            widget_frames(&foreign),
            None,
            "...but it is not a frame list"
        );
    }
    #[test]
    fn builder_order_does_not_matter() {
        let a = VideoWidget::create(config(file_source("/a.mp4"), 1.0))
            .with_frames(RefAny::new(vec![frame(3, 3)]))
            .with_on_frame(
                frame_log(Update::DoNothing),
                record_frame as OnVideoFrameCallbackType,
            );
        let b = VideoWidget::create(config(file_source("/a.mp4"), 1.0))
            .with_on_frame(
                frame_log(Update::DoNothing),
                record_frame as OnVideoFrameCallbackType,
            )
            .with_frames(RefAny::new(vec![frame(3, 3)]));
        assert_same_config(&a.config, &b.config);
        assert_eq!(widget_frames(&a), widget_frames(&b));
        assert!(matches!(a.on_frame, OptionOnVideoFrame::Some(_)));
        assert!(matches!(b.on_frame, OptionOnVideoFrame::Some(_)));
    }
    // ==================================================================
    // VideoWidget::dom / mount
    // ==================================================================
    #[test]
    fn dom_builds_a_div_with_one_virtual_view_child() {
        let dom = VideoWidget::create(VideoConfig::default()).dom();
        assert!(
            matches!(dom.root.get_node_type(), NodeType::Div),
            "the widget root is a plain div (the <img> lives in the VirtualView)"
        );
        assert_eq!(dom.children.as_slice().len(), 1, "one VirtualView child");
        assert!(
            matches!(
                dom.children.as_slice()[0].root.get_node_type(),
                NodeType::VirtualView
            ),
            "the child must be the VirtualView the decode worker re-renders"
        );
    }
    #[test]
    fn dom_wires_after_mount_node_resized_a_dataset_and_a_merge_callback() {
        let dom = VideoWidget::create(VideoConfig::default()).dom();
        let events: Vec<EventFilter> = dom
            .root
            .get_callbacks()
            .as_ref()
            .iter()
            .map(|c| c.event)
            .collect();
        assert_eq!(events.len(), 2, "exactly two component callbacks");
        assert!(events.contains(&EventFilter::Component(ComponentEventFilter::AfterMount)));
        assert!(events.contains(&EventFilter::Component(ComponentEventFilter::NodeResized)));
        assert!(
            dom.root.get_merge_callback().is_some(),
            "live state must survive relayout"
        );
        assert!(
            dom.root.get_dataset().is_some(),
            "the widget div must carry its VideoWidgetState"
        );
    }
    #[test]
    fn dom_stores_a_pristine_state_for_every_config() {
        for cfg in all_configs() {
            let dom = VideoWidget::create(cfg.clone()).dom();
            let mut dataset = dom
                .root
                .get_dataset()
                .cloned()
                .expect("the node must carry its VideoWidgetState");
            assert_same_config(&read_config(&mut dataset), &cfg);
            assert_eq!(
                read_state(&mut dataset),
                StateSummary {
                    started: false,
                    gl_texture_id: None,
                    has_hook: false,
                    has_frames: false,
                    decode_cb: None,
                    current_frame_id: None,
                    thread_id: None,
                    has_seek_sender: false,
                },
                "dom() must not start anything - AfterMount does that"
            );
        }
    }
    #[test]
    fn dom_moves_the_hook_and_the_replay_list_into_the_state() {
        let dom = VideoWidget::create(VideoConfig::default())
            .with_frames(RefAny::new(vec![frame(6, 7)]))
            .with_on_frame(
                frame_log(Update::DoNothing),
                record_frame as OnVideoFrameCallbackType,
            )
            .dom();
        let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
        let summary = read_state(&mut dataset);
        assert!(summary.has_hook, "dom() must carry the user hook forward");
        assert!(summary.has_frames);
        assert_eq!(state_frames(&mut dataset), Some(vec![(6, 7)]));
    }
    #[test]
    fn mounting_installs_the_registered_decoder_and_building_the_dom_never_does() {
        // The decoder is a process-wide registration (first one wins), so the
        // test accepts whichever worker is installed.
        let _ = register_video_decoder(ThreadCallback::new(noop_decode_worker));
        let registered = VIDEO_DECODER.get().expect("registered").cb as usize;
        let dom = VideoWidget::create(VideoConfig::default()).dom();
        let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
        assert_eq!(
            read_state(&mut dataset).decode_cb,
            None,
            "building the Dom only describes the UI"
        );
        with_callback_info(|info| mount_video(&mut dataset, &info));
        assert_eq!(read_state(&mut dataset).decode_cb, Some(registered));
        let setup = dataset
            .downcast_ref::<VideoWidgetState>()
            .map(|s| s.setup.clone());
        assert_eq!(
            setup,
            Some(VideoSetup::new()),
            "without a hook nothing is shared"
        );
    }
    #[test]
    fn a_widget_that_replays_frames_is_not_given_the_decoder() {
        let _ = register_video_decoder(ThreadCallback::new(noop_decode_worker));
        let dom = VideoWidget::create(VideoConfig::default())
            .with_frames(RefAny::new(vec![frame(2, 2)]))
            .dom();
        let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
        with_callback_info(|info| mount_video(&mut dataset, &info));
        assert_eq!(
            read_state(&mut dataset).decode_cb,
            None,
            "with_frames asked for a replay, so the replay worker must run"
        );
    }
    extern "C" fn pooled_video_setup(_: RefAny, _: CallbackInfo, setup: VideoSetup) -> VideoSetup {
        setup.with_thread_pool(ThreadPool::create(1))
    }
    #[test]
    fn the_video_mount_hook_decides_the_setup_and_a_rebuild_keeps_it() {
        let build = || {
            VideoWidget::create(VideoConfig::default())
                .with_on_mount(
                    RefAny::new(()),
                    pooled_video_setup as VideoMountCallbackType,
                )
                .dom()
        };
        let mut mounted = build().root.get_dataset().cloned().expect("dataset");
        with_callback_info(|info| mount_video(&mut mounted, &info));
        let pool = match mounted
            .downcast_ref::<VideoWidgetState>()
            .map(|s| s.setup.thread_pool.clone())
        {
            Some(OptionThreadPool::Some(pool)) => pool,
            _ => panic!("the hook's pool must be installed"),
        };
        let rebuilt = build().root.get_dataset().cloned().expect("dataset");
        let mut kept = merge_video_state(rebuilt, mounted);
        let kept_pool = kept
            .downcast_ref::<VideoWidgetState>()
            .map(|s| s.setup.thread_pool.clone());
        assert_eq!(
            kept_pool,
            Some(OptionThreadPool::Some(pool)),
            "the same pool, not a new one"
        );
    }
    #[test]
    fn dom_survives_a_huge_in_memory_source_without_copying_it_into_the_tree() {
        // 4 MiB of "MP4 bytes": the widget must move them into the state, not
        // choke on them.
        let widget = VideoWidget::create(config(bytes_source(vec![0xAB; 4 * 1024 * 1024]), 0.0));
        let dom = widget.dom();
        let mut dataset = dom.root.get_dataset().cloned().expect("dataset");
        match read_config(&mut dataset).source {
            VideoSource::Bytes(b) => assert_eq!(b.as_ref().len(), 4 * 1024 * 1024),
            other => panic!("the source must survive verbatim, got {other:?}"),
        }
    }
    // ==================================================================
    // video_widget_render  (VirtualView callback)
    // ==================================================================
    #[test]
    fn render_with_non_finite_or_empty_bounds_emits_no_dom() {
        let mut s = base_state(VideoConfig::default());
        s.current_frame = Some(placeholder_image(b"ready"));
        let dataset = RefAny::new(s);
        for (w, h) in [
            (0.0_f32, 0.0_f32),
            (0.0, 600.0),
            (800.0, 0.0),
            (-800.0, -600.0),
            (-1.0, 600.0),
            (f32::NAN, 600.0),
            (800.0, f32::NAN),
            (f32::INFINITY, 600.0),
            (800.0, f32::NEG_INFINITY),
        ] {
            let ret =
                with_virtual_view_info(w, h, |info| video_widget_render(dataset.clone(), info));
            assert!(
                rendered_nothing(&ret),
                "bounds {w}x{h} must render nothing until layout settles - even with a frame ready"
            );
        }
    }
    #[test]
    fn render_with_a_wrong_typed_dataset_emits_no_dom() {
        let dataset = RefAny::new(0_u32);
        let ret = with_virtual_view_info(800.0, 600.0, |info| {
            video_widget_render(dataset.clone(), info)
        });
        assert!(rendered_nothing(&ret));
    }
    #[test]
    fn render_before_the_first_frame_emits_the_no_signal_poster() {
        // PIN FLIPPED (2026-07-31, deliberately): rendering NOTHING before
        // the first frame made a dead decode pipeline (missing feature,
        // unsupported target, Vulkan init failure, network stall)
        // indistinguishable from a black video — the shipped azul-video
        // "black frame" bug. A decoder that has produced no frame must be
        // VISIBLY "no signal".
        let dataset = state(VideoConfig::default());
        let ret = with_virtual_view_info(800.0, 600.0, |info| {
            video_widget_render(dataset.clone(), info)
        });
        assert!(
            !rendered_nothing(&ret),
            "no decoded frame yet -> a visible no-signal poster, NOT an invisible tile"
        );
    }
    #[test]
    fn render_emits_the_stored_frame_as_an_image() {
        let img = placeholder_image(b"azul-video-frame");
        let expected_id = img.id;
        let mut s = base_state(VideoConfig::default());
        s.current_frame = Some(img);
        let dataset = RefAny::new(s);
        let ret = with_virtual_view_info(800.0, 600.0, |info| {
            video_widget_render(dataset.clone(), info)
        });
        assert_eq!(
            rendered_image_id(&ret),
            Some(expected_id),
            "the <img> must show exactly the frame the writeback stored"
        );
    }
    #[test]
    fn render_reports_the_bounds_back_as_the_scroll_size() {
        let dataset = state(VideoConfig::default());
        let ret = with_virtual_view_info(640.0, 480.0, |info| {
            video_widget_render(dataset.clone(), info)
        });
        assert_eq!(ret.materialized.size.width, 640.0);
        assert_eq!(ret.materialized.size.height, 480.0);
        assert_eq!(ret.virtual_rect.size.width, 640.0);
        assert_eq!(ret.virtual_rect.size.height, 480.0);
        assert_eq!(
            (ret.materialized.origin.x, ret.materialized.origin.y),
            (0.0, 0.0)
        );
        assert_eq!(
            (ret.virtual_rect.origin.x, ret.virtual_rect.origin.y),
            (0.0, 0.0)
        );
    }
    #[test]
    fn render_echoes_even_a_nan_bound_into_the_scroll_size() {
        // The early-out only suppresses the DOM: the reported scroll size is
        // still whatever layout handed in, NaN included.
        let dataset = state(VideoConfig::default());
        let ret = with_virtual_view_info(f32::NAN, 480.0, |info| {
            video_widget_render(dataset.clone(), info)
        });
        assert!(rendered_nothing(&ret));
        assert!(ret.materialized.size.width.is_nan());
        assert_eq!(ret.materialized.size.height, 480.0);
    }
    #[test]
    fn render_is_pure_and_repeatable() {
        let img = placeholder_image(b"stable");
        let expected_id = img.id;
        let mut s = base_state(VideoConfig::default());
        s.current_frame = Some(img);
        s.started = true;
        let mut dataset = RefAny::new(s);
        for _ in 0..8 {
            let ret = with_virtual_view_info(320.0, 240.0, |info| {
                video_widget_render(dataset.clone(), info)
            });
            assert_eq!(rendered_image_id(&ret), Some(expected_id));
        }
        let summary = read_state(&mut dataset);
        assert!(summary.started, "render must not touch the live state");
        assert_eq!(summary.current_frame_id, Some(expected_id));
    }
    #[test]
    fn render_with_the_smallest_positive_bounds_still_emits_the_image() {
        let img = placeholder_image(b"tiny");
        let expected_id = img.id;
        let mut s = base_state(VideoConfig::default());
        s.current_frame = Some(img);
        let dataset = RefAny::new(s);
        for (w, h) in [
            (f32::MIN_POSITIVE, f32::MIN_POSITIVE),
            (1.0, 1.0),
            (f32::MAX, f32::MAX),
        ] {
            let ret =
                with_virtual_view_info(w, h, |info| video_widget_render(dataset.clone(), info));
            assert_eq!(
                rendered_image_id(&ret),
                Some(expected_id),
                "{w}x{h} is finite and positive, so the frame must render"
            );
        }
    }
    // ==================================================================
    // video_on_after_mount
    //
    // NOTE: the default (test-pattern) mount path is deliberately NOT driven
    // here. `video_test_worker` never reads its receiver, so it ignores
    // `ThreadSendMsg::TerminateThread`; the framework's thread destructor
    // *joins* that worker and would hang the test binary forever (see the
    // report). Only workers that return on their own are mounted below.
    // ==================================================================
    #[test]
    fn after_mount_ignores_a_dataset_that_is_not_a_video_state() {
        let (update, changes) =
            with_callback_info(|info| video_on_after_mount(RefAny::new(0_u32), info));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign dataset must not start a decode thread"
        );
    }
    #[test]
    fn after_mount_is_a_no_op_once_the_decode_thread_has_started() {
        let mut s = base_state(VideoConfig::default());
        s.started = true;
        s.thread_id = Some(ThreadId::unique());
        s.current_frame = Some(placeholder_image(b"kept"));
        let mut data = RefAny::new(s);
        let before = read_state(&mut data);
        let (update, changes) = with_callback_info(|info| video_on_after_mount(data.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "AfterMount must start the decode thread at most once"
        );
        assert_eq!(
            read_state(&mut data),
            before,
            "a re-mount must not disturb the running state"
        );
    }
    #[test]
    fn after_mount_spawns_the_streaming_decoder_and_remembers_its_id_and_sender() {
        let mut s = base_state(config(file_source("/tmp/clip.mp4"), 12.5));
        s.decode_callback = Some(ThreadCallback::new(noop_decode_worker));
        let mut data = RefAny::new(s);
        let (update, changes) = with_callback_info(|info| video_on_after_mount(data.clone(), info));
        assert_eq!(
            update,
            Update::DoNothing,
            "mounting never triggers relayout"
        );
        assert_eq!(changes.len(), 1, "exactly one thread is spawned");
        let tid = added_thread_id(&changes).expect("the decode worker must be added as a Thread");
        let summary = read_state(&mut data);
        assert!(summary.started);
        assert_eq!(
            summary.thread_id,
            Some(tid),
            "the state must remember the very thread id it registered (resize messaging)"
        );
        assert!(
            summary.has_seek_sender,
            "the merge callback needs the worker's sender to push seeks"
        );
    }
    #[test]
    fn after_mount_only_ever_spawns_one_decode_thread() {
        let mut s = base_state(VideoConfig::default());
        s.decode_callback = Some(ThreadCallback::new(noop_decode_worker));
        let mut data = RefAny::new(s);
        let (_, first) = with_callback_info(|info| video_on_after_mount(data.clone(), info));
        let first_id = read_state(&mut data).thread_id;
        let (_, second) = with_callback_info(|info| video_on_after_mount(data.clone(), info));
        assert_eq!(first.len(), 1);
        assert!(second.is_empty(), "the second AfterMount must be a no-op");
        assert_eq!(
            read_state(&mut data).thread_id,
            first_id,
            "the recorded thread id must not be re-rolled"
        );
    }
    #[test]
    fn after_mount_replay_path_spawns_a_worker_but_records_no_id_or_sender() {
        // ADVERSARIAL: the replay path spawns a `Thread` like the streaming path
        // does, but stores neither its `ThreadId` nor its sender - so resize
        // re-targeting and scrub/seek messaging are silently dead for replayed
        // clips (see the report). An EMPTY frame list is used so the worker
        // returns immediately and can be joined.
        let mut s = base_state(VideoConfig::default());
        s.frames = OptionRefAny::Some(RefAny::new(Vec::<VideoFrame>::new()));
        let mut data = RefAny::new(s);
        let (update, changes) = with_callback_info(|info| video_on_after_mount(data.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert_eq!(changes.len(), 1, "the replay worker is still spawned");
        let summary = read_state(&mut data);
        assert!(summary.started);
        assert_eq!(summary.thread_id, None);
        assert!(!summary.has_seek_sender);
    }
    #[test]
    fn after_mount_replay_path_accepts_a_wrong_typed_frame_list() {
        // A `RefAny` that is not a `Vec<VideoFrame>` must not panic the mount -
        // the worker just returns.
        let mut s = base_state(VideoConfig::default());
        s.frames = OptionRefAny::Some(RefAny::new("not a frame list"));
        let mut data = RefAny::new(s);
        let (update, changes) = with_callback_info(|info| video_on_after_mount(data.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert_eq!(changes.len(), 1);
        assert!(read_state(&mut data).started);
    }
    #[test]
    fn after_mount_prefers_the_streaming_decoder_over_a_replay_list() {
        // Documented priority: decode worker > replay frames > test pattern.
        // A NON-empty replay list is safe here precisely because it must NOT be
        // used (the replay worker would otherwise loop forever).
        let mut s = base_state(VideoConfig::default());
        s.decode_callback = Some(ThreadCallback::new(noop_decode_worker));
        s.frames = OptionRefAny::Some(RefAny::new(vec![frame(2, 2), frame(2, 2)]));
        let mut data = RefAny::new(s);
        let (_, changes) = with_callback_info(|info| video_on_after_mount(data.clone(), info));
        assert_eq!(changes.len(), 1);
        let summary = read_state(&mut data);
        assert!(
            summary.thread_id.is_some() && summary.has_seek_sender,
            "only the streaming path records an id + sender, so it is the one that ran"
        );
        assert!(summary.has_frames, "the replay list is kept, just unused");
    }
    // ==================================================================
    // video_on_resize
    // ==================================================================
    #[test]
    fn resize_ignores_a_dataset_that_is_not_a_video_state() {
        let (update, changes) =
            with_callback_info(|info| video_on_resize(RefAny::new(0_u32), info));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
    }
    #[test]
    fn resize_before_the_worker_started_is_a_no_op() {
        let mut data = state(VideoConfig::default());
        let before = read_state(&mut data);
        let (update, changes) = with_callback_info(|info| video_on_resize(data.clone(), info));
        assert_eq!(
            update,
            Update::DoNothing,
            "resize is a message, never a relayout"
        );
        assert!(changes.is_empty(), "no worker -> nothing to tell");
        assert_eq!(read_state(&mut data), before);
    }
    #[test]
    fn resize_with_an_unknown_node_is_a_no_op() {
        // The state knows a thread id, but the hit node has no laid-out size in
        // this (empty) window: the callback must bail instead of messaging a
        // bogus target size.
        let mut s = base_state(VideoConfig::default());
        s.started = true;
        s.thread_id = Some(ThreadId::unique());
        let mut data = RefAny::new(s);
        let before = read_state(&mut data);
        let (update, changes) = with_callback_info(|info| video_on_resize(data.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(read_state(&mut data), before);
    }
    #[test]
    fn resize_with_a_thread_id_that_no_longer_exists_is_a_no_op() {
        // A worker that already exited: `get_thread` returns None and the
        // best-effort send is simply skipped.
        let mut s = base_state(VideoConfig::default());
        s.thread_id = Some(ThreadId::unique());
        s.started = true;
        let data = RefAny::new(s);
        for _ in 0..4 {
            let (update, changes) = with_callback_info(|info| video_on_resize(data.clone(), info));
            assert_eq!(update, Update::DoNothing);
            assert!(changes.is_empty());
        }
    }
    // ==================================================================
    // video_test_worker
    // ==================================================================
    #[test]
    fn test_worker_stops_as_soon_as_the_main_thread_stops_receiving() {
        let sent = run_worker(video_test_worker, RefAny::new(()), 0, false);
        assert_eq!(
            sent.len(),
            1,
            "the worker must stop after the first rejected send, not spin"
        );
        assert_eq!((sent[0].width, sent[0].height), (1280, 720));
        assert_eq!(
            sent[0].len,
            1280 * 720 * 4,
            "a frame is exactly width * height * 4 tightly-packed RGBA bytes"
        );
    }
    #[test]
    fn test_worker_emits_seven_opaque_smpte_bars_in_order() {
        let sent = run_worker(video_test_worker, RefAny::new(()), 0, false);
        let f = &sent[0];
        assert!(
            f.rows_identical,
            "the bars scroll horizontally only - every scanline must be identical"
        );
        assert_eq!(
            f.row0_palette,
            EXPECTED_BARS.to_vec(),
            "tick 0 must emit the seven SMPTE bars left-to-right, all fully opaque"
        );
    }
    #[test]
    fn test_worker_ignores_terminate_and_scrolls_the_pattern() {
        // ADVERSARIAL: the worker never polls its receiver, so `TerminateThread`
        // - the message the framework's thread destructor sends before joining -
        // is ignored outright. The only thing that stops it is a failed send.
        let sent = run_worker(video_test_worker, RefAny::new(()), 3, true);
        assert_eq!(
            sent.len(),
            4,
            "3 accepted + 1 rejected: TerminateThread did not stop the worker"
        );
        for f in &sent {
            assert_eq!(f.len, 1280 * 720 * 4);
            assert!(f.rows_identical);
        }
        // tick advances by 2 per frame and the shift is `tick / 4`, so frames
        // 0+1 share a phase and frame 2 is rotated by exactly one bar.
        assert_eq!(sent[0].row0_palette, sent[1].row0_palette);
        assert_eq!(sent[2].row0_palette, sent[3].row0_palette);
        assert_ne!(
            sent[1].row0_palette, sent[2].row0_palette,
            "the pattern must actually scroll"
        );
        assert_eq!(
            sent[2].row0_palette[0], EXPECTED_BARS[1],
            "one tick of scroll rotates the palette by one bar"
        );
    }
    #[test]
    fn test_worker_ignores_its_init_payload_entirely() {
        // The test pattern is fixed-size: no init data can change it (or crash it).
        for init in [
            RefAny::new(()),
            RefAny::new(0_u32),
            RefAny::new(VideoConfig::default()),
            RefAny::new(vec![frame(1, 1)]),
        ] {
            let sent = run_worker(video_test_worker, init, 0, false);
            assert_eq!(sent.len(), 1);
            assert_eq!((sent[0].width, sent[0].height), (1280, 720));
        }
    }
    // ==================================================================
    // video_replay_worker
    // ==================================================================
    #[test]
    fn replay_worker_returns_immediately_for_a_wrong_typed_init() {
        for init in [
            RefAny::new(0_u32),
            RefAny::new("not a frame list"),
            RefAny::new(VideoConfig::default()),
            RefAny::new(frame(1, 1)),
        ] {
            let sent = run_worker(video_replay_worker, init, 8, false);
            assert!(
                sent.is_empty(),
                "a payload that is not a Vec<VideoFrame> must be skipped, not guessed at"
            );
        }
    }
    #[test]
    fn replay_worker_returns_immediately_for_an_empty_frame_list() {
        // Boundary: an empty list would make `idx % frames.len()` divide by
        // zero - the worker must bail first.
        let sent = run_worker(
            video_replay_worker,
            RefAny::new(Vec::<VideoFrame>::new()),
            8,
            false,
        );
        assert!(sent.is_empty());
    }
    #[test]
    fn replay_worker_sends_the_caller_frames_byte_for_byte() {
        let frames = vec![
            frame_raw(2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]),
            frame_raw(1, 2, vec![9, 10, 11, 12, 13, 14, 15, 16]),
        ];
        let sent = run_worker(video_replay_worker, RefAny::new(frames.clone()), 2, false);
        assert_eq!(sent.len(), 3, "2 accepted + 1 rejected");
        for (i, s) in sent.iter().enumerate() {
            let expected = &frames[i % frames.len()];
            assert_eq!((s.width, s.height), (expected.width, expected.height));
            assert_eq!(
                s.small_bytes.as_deref(),
                Some(expected.bytes.as_ref()),
                "frame {i} must be replayed verbatim - no re-encoding"
            );
        }
    }
    #[test]
    fn replay_worker_cycles_the_list_and_never_indexes_out_of_bounds() {
        let frames = vec![frame_raw(1, 1, vec![0; 4]), frame_raw(2, 2, vec![1; 16])];
        let sent = run_worker(video_replay_worker, RefAny::new(frames), 5, false);
        assert_eq!(sent.len(), 6);
        let widths: Vec<u32> = sent.iter().map(|s| s.width).collect();
        assert_eq!(widths, vec![1, 2, 1, 2, 1, 2], "the list must wrap around");
    }
    #[test]
    fn replay_worker_forwards_degenerate_frames_unchanged() {
        // A decoder can hand back a 0x0 frame or one whose byte count does not
        // match its dimensions; the replay worker is a pipe, not a validator -
        // it must not panic, truncate, or drop them.
        let frames = vec![
            frame_raw(0, 0, Vec::new()),
            frame_raw(u32::MAX, u32::MAX, Vec::new()),
            frame_raw(1, 1, vec![0xAB; 3]),
        ];
        let sent = run_worker(video_replay_worker, RefAny::new(frames), 2, false);
        assert_eq!(sent.len(), 3);
        assert_eq!((sent[0].width, sent[0].height, sent[0].len), (0, 0, 0));
        assert_eq!(
            (sent[1].width, sent[1].height, sent[1].len),
            (u32::MAX, u32::MAX, 0)
        );
        assert_eq!(
            sent[2].small_bytes.as_deref(),
            Some(&[0xAB, 0xAB, 0xAB][..])
        );
    }
    // ==================================================================
    // video_writeback
    // ==================================================================
    #[test]
    fn writeback_stores_the_frame_and_rerenders_the_virtual_view() {
        let mut data = state(VideoConfig::default());
        let frame_data = RefAny::new(frame(4, 3));
        let (update, changes) =
            with_callback_info(|info| video_writeback(data.clone(), frame_data.clone(), info));
        assert_eq!(update, Update::DoNothing, "no hook -> no user update");
        assert_eq!(
            count_virtual_view_rerenders(&changes),
            1,
            "the VirtualView must be re-rendered in place (never RefreshDom)"
        );
        assert_eq!(
            current_frame_dims(&mut data),
            Some((4, 3)),
            "the decoded frame becomes the widget's current CPU image"
        );
    }
    #[test]
    fn writeback_invokes_the_hook_with_the_exact_frame_and_returns_its_update() {
        let mut log = frame_log(Update::RefreshDom);
        let mut s = base_state(VideoConfig::default());
        s.on_frame = hook_into(&log);
        let mut data = RefAny::new(s);
        let frame_data = RefAny::new(frame(2, 2));
        let (update, changes) =
            with_callback_info(|info| video_writeback(data.clone(), frame_data.clone(), info));
        assert_eq!(update, Update::RefreshDom, "the hook's Update must win");
        assert_eq!(logged_frames(&mut log), vec![(2, 2, 16)]);
        assert_eq!(count_virtual_view_rerenders(&changes), 1);
        assert_eq!(current_frame_dims(&mut data), Some((2, 2)));
    }
    #[test]
    fn writeback_ignores_frame_data_of_the_wrong_type() {
        let mut log = frame_log(Update::RefreshDom);
        let mut s = base_state(VideoConfig::default());
        s.on_frame = hook_into(&log);
        let mut data = RefAny::new(s);
        let (update, changes) =
            with_callback_info(|info| video_writeback(data.clone(), RefAny::new(0_u32), info));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "no frame -> no re-render is scheduled at all"
        );
        assert!(
            logged_frames(&mut log).is_empty(),
            "the user hook must not fire without a frame"
        );
        assert_eq!(read_state(&mut data).current_frame_id, None);
    }
    #[test]
    fn writeback_survives_a_writeback_dataset_that_is_not_a_video_state() {
        let (update, changes) = with_callback_info(|info| {
            video_writeback(RefAny::new(0_u32), RefAny::new(frame(1, 1)), info)
        });
        assert_eq!(
            update,
            Update::DoNothing,
            "a foreign dataset means no hook and nowhere to store - but no panic"
        );
        assert_eq!(
            count_virtual_view_rerenders(&changes),
            1,
            "the re-render is still scheduled (documented cost of a stale dataset)"
        );
    }
    #[test]
    fn writeback_rejects_a_frame_whose_bytes_do_not_match_its_dimensions() {
        // A malformed/hostile frame: the image build must fail cleanly instead
        // of indexing out of bounds or allocating.
        let mut data = state(VideoConfig::default());
        for bogus in [
            frame_raw(u32::MAX, 1, Vec::new()),
            frame_raw(4, 4, vec![0; 4 * 4 * 4 - 1]),
            frame_raw(4, 4, vec![0; 4 * 4 * 4 + 1]),
            frame_raw(1, 1, Vec::new()),
            frame_raw(0, 0, vec![0; 4]),
        ] {
            let payload = RefAny::new(bogus);
            let (update, changes) =
                with_callback_info(|info| video_writeback(data.clone(), payload.clone(), info));
            assert_eq!(update, Update::DoNothing);
            assert_eq!(
                count_virtual_view_rerenders(&changes),
                1,
                "a rejected frame still costs a re-render"
            );
            assert_eq!(
                read_state(&mut data).current_frame_id,
                None,
                "a rejected frame must never become the displayed image"
            );
        }
    }
    #[test]
    fn writeback_accepts_an_empty_zero_by_zero_frame() {
        // Boundary: 0x0 with 0 bytes is internally consistent, so it is accepted
        // as a (degenerate) image rather than rejected.
        let mut data = state(VideoConfig::default());
        let empty = RefAny::new(frame_raw(0, 0, Vec::new()));
        let (update, _) =
            with_callback_info(|info| video_writeback(data.clone(), empty.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert_eq!(current_frame_dims(&mut data), Some((0, 0)));
    }
    #[test]
    fn writeback_replaces_the_previous_frame_every_time() {
        let mut s = base_state(VideoConfig::default());
        s.current_frame = Some(placeholder_image(b"old"));
        let mut data = RefAny::new(s);
        let old_id = read_state(&mut data).current_frame_id.expect("seeded");
        let f1 = RefAny::new(frame(2, 2));
        let (_, _) = with_callback_info(|info| video_writeback(data.clone(), f1.clone(), info));
        let id1 = read_state(&mut data).current_frame_id.expect("stored");
        assert_ne!(id1, old_id, "the stale placeholder must be replaced");
        let f2 = RefAny::new(frame(3, 3));
        let (_, _) = with_callback_info(|info| video_writeback(data.clone(), f2.clone(), info));
        let id2 = read_state(&mut data).current_frame_id.expect("stored");
        assert_ne!(id2, id1, "every frame installs a fresh image");
        assert_eq!(current_frame_dims(&mut data), Some((3, 3)));
    }
    #[test]
    fn writeback_keeps_the_last_good_frame_when_a_later_one_is_malformed() {
        let mut data = state(VideoConfig::default());
        let good = RefAny::new(frame(2, 2));
        let (_, _) = with_callback_info(|info| video_writeback(data.clone(), good.clone(), info));
        let good_id = read_state(&mut data).current_frame_id.expect("stored");
        let bad = RefAny::new(frame_raw(1024, 1024, vec![0; 16]));
        let (update, _) =
            with_callback_info(|info| video_writeback(data.clone(), bad.clone(), info));
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            read_state(&mut data).current_frame_id,
            Some(good_id),
            "a corrupt frame must not blank the picture"
        );
    }
    #[test]
    fn writeback_still_notifies_the_hook_for_a_frame_it_cannot_display() {
        // The hook is the user's data path (save / send), so it fires even when
        // the frame is unusable as an image - documented here so a change is
        // deliberate.
        let mut log = frame_log(Update::RefreshDom);
        let mut s = base_state(VideoConfig::default());
        s.on_frame = hook_into(&log);
        let mut data = RefAny::new(s);
        let bogus = RefAny::new(frame_raw(64, 64, vec![0; 3]));
        let (update, _) =
            with_callback_info(|info| video_writeback(data.clone(), bogus.clone(), info));
        assert_eq!(update, Update::RefreshDom);
        assert_eq!(logged_frames(&mut log), vec![(64, 64, 3)]);
        assert_eq!(read_state(&mut data).current_frame_id, None);
    }
    #[test]
    fn writeback_survives_dimensions_whose_byte_count_overflows_usize() {
        // ADVERSARIAL: a decoder reporting 2^31 x 2^31 makes the raw-image path
        // compute `width * height * 4` in usize -> 2^64, which overflows. In a
        // debug build that is an arithmetic-overflow panic; in release it wraps
        // and the empty buffer may be *accepted*. Neither is a graceful
        // rejection (see the report) - what must hold in both modes is that the
        // widget never ends up displaying a bogus image.
        let mut data = state(VideoConfig::default());
        let huge = RefAny::new(frame_raw(1_u32 << 31, 1_u32 << 31, Vec::new()));
        let (result, _) = with_callback_info(|info| {
            catch_unwind(AssertUnwindSafe(|| {
                video_writeback(data.clone(), huge.clone(), info)
            }))
        });
        match result {
            Ok(update) => {
                assert_eq!(update, Update::DoNothing);
                assert_eq!(
                    read_state(&mut data).current_frame_id,
                    None,
                    "an overflowing frame must not become the displayed image"
                );
            }
            Err(_) => eprintln!(
                "NOTE: video_writeback panicked (usize overflow of width*height*4) for a 2^31 x \
                 2^31 frame - see the autotest report"
            ),
        }
    }
    // ==================================================================
    // merge_video_state
    // ==================================================================
    /// An `(old, new)` pair plus the seek channel `old` hands forward.
    fn merge_pair(
        old_cfg: VideoConfig,
        new_cfg: VideoConfig,
    ) -> (RefAny, RefAny, Receiver<ThreadSendMsg>) {
        let (tx, rx) = channel::<ThreadSendMsg>();
        let mut old = base_state(old_cfg);
        old.started = true;
        old.thread_id = Some(ThreadId::unique());
        old.seek_sender = Some(tx);
        (RefAny::new(base_state(new_cfg)), RefAny::new(old), rx)
    }
    #[test]
    fn merge_takes_the_live_state_from_old_and_the_config_from_new() {
        let log = frame_log(Update::DoNothing);
        let tid = ThreadId::unique();
        let (tx, _rx) = channel::<ThreadSendMsg>();
        let mut new = base_state(config(file_source("/new.mp4"), 3.0));
        new.on_frame = hook_into(&log);
        new.frames = OptionRefAny::Some(RefAny::new(vec![frame(1, 1)]));
        let mut old = base_state(config(file_source("/old.mp4"), 3.0));
        old.started = true;
        old.gl_texture_id = Some(9);
        old.frames = OptionRefAny::Some(RefAny::new(vec![frame(7, 7), frame(8, 8)]));
        old.decode_callback = Some(ThreadCallback::new(noop_decode_worker));
        old.current_frame = Some(placeholder_image(b"live"));
        old.thread_id = Some(tid);
        old.seek_sender = Some(tx);
        let old_frame_id = old.current_frame.as_ref().map(|i| i.id);
        let mut merged = merge_video_state(RefAny::new(new), RefAny::new(old));
        assert_same_config(
            &read_config(&mut merged),
            &config(file_source("/new.mp4"), 3.0),
        );
        let summary = read_state(&mut merged);
        assert!(summary.has_hook, "the fresh build's hook wins");
        assert!(summary.started, "'already running' must carry forward");
        assert_eq!(summary.gl_texture_id, Some(9));
        assert_eq!(
            summary.decode_cb,
            Some(noop_decode_worker as ThreadCallbackType as usize)
        );
        assert_eq!(summary.current_frame_id, old_frame_id, "no visible flicker");
        assert_eq!(summary.thread_id, Some(tid));
        assert!(summary.has_seek_sender);
        assert_eq!(
            state_frames(&mut merged),
            Some(vec![(7, 7), (8, 8)]),
            "the OLD replay list wins - a fresh build cannot swap the clip"
        );
    }
    #[test]
    fn merge_leaves_the_new_state_alone_when_the_old_one_is_foreign() {
        let mut new = base_state(config(file_source("/new.mp4"), 1.0));
        new.frames = OptionRefAny::Some(RefAny::new(vec![frame(5, 5)]));
        let mut merged = merge_video_state(RefAny::new(new), RefAny::new(0_u32));
        let summary = read_state(&mut merged);
        assert!(!summary.started, "nothing to carry forward");
        assert_eq!(summary.thread_id, None);
        assert_eq!(
            state_frames(&mut merged),
            Some(vec![(5, 5)]),
            "with no old state the new build's own list survives"
        );
    }
    #[test]
    fn merge_returns_a_foreign_new_dataset_untouched() {
        let old = state(VideoConfig::default());
        let mut merged = merge_video_state(RefAny::new(77_u32), old);
        assert_eq!(
            merged.downcast_ref::<u32>().map(|v| *v),
            Some(77),
            "merge must hand back exactly the payload it was given"
        );
    }
    #[test]
    fn merge_of_a_dataset_with_itself_does_not_panic() {
        // The same RefAny on both sides: the mutable + shared borrows overlap,
        // so the merge is skipped rather than aliasing. Either way the state
        // must survive intact.
        let mut s = base_state(config(file_source("/self.mp4"), 4.0));
        s.started = true;
        s.gl_texture_id = Some(5);
        let mut data = RefAny::new(s);
        let before = read_state(&mut data);
        let mut merged = merge_video_state(data.clone(), data.clone());
        assert_eq!(read_state(&mut merged), before);
        assert_eq!(read_state(&mut data), before);
    }
    #[test]
    fn merge_pushes_a_seek_when_the_scrub_position_changed() {
        let (new, old, rx) = merge_pair(
            config(file_source("/clip.mp4"), 0.0),
            config(file_source("/clip.mp4"), 42.25),
        );
        let _merged = merge_video_state(new, old);
        let msgs: Vec<ThreadSendMsg> = rx.try_iter().collect();
        assert_eq!(msgs.len(), 1, "one seek, no source re-init");
        assert_eq!(
            custom_f32(&msgs[0]),
            Some(42.25),
            "the worker must be told the NEW timestamp"
        );
    }
    #[test]
    fn merge_stays_quiet_when_nothing_changed() {
        let (new, old, rx) = merge_pair(
            config(file_source("/clip.mp4"), 7.5),
            config(file_source("/clip.mp4"), 7.5),
        );
        let _merged = merge_video_state(new, old);
        assert!(
            rx.try_iter().next().is_none(),
            "an unchanged config must not wake the decode worker"
        );
    }
    #[test]
    fn merge_treats_negative_zero_and_zero_as_the_same_position() {
        let (new, old, rx) = merge_pair(
            config(file_source("/clip.mp4"), -0.0),
            config(file_source("/clip.mp4"), 0.0),
        );
        let _merged = merge_video_state(new, old);
        assert!(
            rx.try_iter().next().is_none(),
            "-0.0 == 0.0 is the same scrub position"
        );
    }
    #[test]
    fn merge_seeks_on_every_relayout_while_the_timestamp_is_nan() {
        // ADVERSARIAL: `NaN != NaN`, so an unchanged NaN scrub position looks
        // like a change on every single relayout and floods the worker with
        // seeks (see the report). Pinned here as the current behaviour.
        let (new, old, rx) = merge_pair(
            config(file_source("/clip.mp4"), f32::NAN),
            config(file_source("/clip.mp4"), f32::NAN),
        );
        let _merged = merge_video_state(new, old);
        let msgs: Vec<ThreadSendMsg> = rx.try_iter().collect();
        assert_eq!(msgs.len(), 1);
        assert!(
            custom_f32(&msgs[0]).is_some_and(f32::is_nan),
            "the spurious seek carries the NaN straight through to the worker"
        );
    }
    #[test]
    fn merge_pushes_the_new_source_when_the_input_changed() {
        let (new, old, rx) = merge_pair(
            config(file_source("/old.mp4"), 1.0),
            config(url_source("cdn.example", "/new.mp4"), 1.0),
        );
        let _merged = merge_video_state(new, old);
        let msgs: Vec<ThreadSendMsg> = rx.try_iter().collect();
        assert_eq!(msgs.len(), 1, "one re-init, no seek");
        assert_eq!(
            custom_source(&msgs[0]),
            Some(url_source("cdn.example", "/new.mp4"))
        );
    }
    #[test]
    fn merge_sends_the_seek_before_the_source_when_both_changed() {
        let (new, old, rx) = merge_pair(
            config(file_source("/old.mp4"), 0.0),
            config(bytes_source(vec![1, 2, 3]), 9.0),
        );
        let _merged = merge_video_state(new, old);
        let msgs: Vec<ThreadSendMsg> = rx.try_iter().collect();
        assert_eq!(msgs.len(), 2);
        assert_eq!(custom_f32(&msgs[0]), Some(9.0));
        assert_eq!(custom_source(&msgs[1]), Some(bytes_source(vec![1, 2, 3])));
    }
    #[test]
    fn merge_notices_a_source_change_that_only_differs_in_unicode() {
        let (new, old, rx) = merge_pair(
            config(file_source("/tmp/\u{1F3AC}.mp4"), 0.0),
            config(file_source("/tmp/\u{1F3AB}.mp4"), 0.0),
        );
        let _merged = merge_video_state(new, old);
        let msgs: Vec<ThreadSendMsg> = rx.try_iter().collect();
        assert_eq!(msgs.len(), 1, "distinct emoji are distinct sources");
        assert_eq!(
            custom_source(&msgs[0]),
            Some(file_source("/tmp/\u{1F3AB}.mp4"))
        );
    }
    #[test]
    fn merge_without_a_seek_sender_drops_the_seek_silently() {
        // Nothing to send to (replay / test-pattern mounts never record a
        // sender): the merge must still carry the state, not panic.
        let new = RefAny::new(base_state(config(file_source("/clip.mp4"), 5.0)));
        let mut old_state = base_state(config(file_source("/clip.mp4"), 0.0));
        old_state.started = true;
        let mut merged = merge_video_state(new, RefAny::new(old_state));
        let summary = read_state(&mut merged);
        assert!(summary.started);
        assert!(!summary.has_seek_sender);
        assert_eq!(read_config(&mut merged).timestamp, 5.0);
    }
    #[test]
    fn merge_survives_a_worker_whose_channel_is_already_closed() {
        let (new, old, rx) = merge_pair(
            config(file_source("/a.mp4"), 0.0),
            config(file_source("/b.mp4"), 1.0),
        );
        drop(rx); // the worker exited and its receiver is gone
        let mut merged = merge_video_state(new, old);
        let summary = read_state(&mut merged);
        assert!(
            summary.has_seek_sender,
            "a dead sender is still carried forward - the send just fails"
        );
        assert!(summary.started);
    }
    #[test]
    fn merge_is_idempotent_across_repeated_relayouts() {
        let (tx, rx) = channel::<ThreadSendMsg>();
        let tid = ThreadId::unique();
        let mut live = base_state(config(file_source("/clip.mp4"), 2.0));
        live.started = true;
        live.gl_texture_id = Some(3);
        live.thread_id = Some(tid);
        live.seek_sender = Some(tx);
        live.current_frame = Some(placeholder_image(b"live"));
        let mut carried = RefAny::new(live);
        for _ in 0..5 {
            let fresh = RefAny::new(base_state(config(file_source("/clip.mp4"), 2.0)));
            carried = merge_video_state(fresh, carried);
        }
        let summary = read_state(&mut carried);
        assert!(summary.started);
        assert_eq!(summary.gl_texture_id, Some(3));
        assert_eq!(summary.thread_id, Some(tid));
        assert!(
            summary.current_frame_id.is_some(),
            "the picture never blanks"
        );
        assert!(
            rx.try_iter().next().is_none(),
            "a stable config must never seek, however many relayouts happen"
        );
    }
}