mpv-engine 0.1.1

Toolkit-agnostic libmpv embedding core: handle lifecycle, commands, typed events, and render seams.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! Engine tests against real libmpv, headless (`vo=null`) — no display,
//! no toolkit. Media inputs are generated with ffmpeg; tests skip
//! gracefully when it (or an mpv build) is unavailable, so a bare CI box
//! degrades to a no-op instead of a failure.

use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::Duration;

use mpv_engine::{EndReason, Engine, PlaybackEvent, PropertyFormat, PropertyValue};

fn headless_engine() -> Option<Engine> {
    // `headless()` nulls only the video output — audio stays real because
    // audio-only playback is its point. Tests must null the audio side
    // too: on a CI box with no sound server, mpv's AO probe reaches
    // PulseAudio's client lib, which hard-aborts the whole test process
    // (`pa_mainloop_prepare(): Assertion 'm->state == STATE_PASSIVE'`).
    match Engine::headless().property("ao", "null").build() {
        Ok(e) => Some(e),
        Err(e) => {
            eprintln!("skipping: mpv engine unavailable: {e}");
            None
        }
    }
}

/// A render-API (`vo=libmpv`) engine, or None when mpv is unavailable.
/// Audio is nulled for the same reason as in [`headless_engine`]: mpv's
/// AO probe hard-aborts the process on a box with no sound server.
fn video_engine() -> Option<Engine> {
    match Engine::video().property("ao", "null").build() {
        Ok(e) => Some(e),
        Err(e) => {
            eprintln!("skipping: mpv engine unavailable: {e}");
            None
        }
    }
}

/// 1 second of silence in an ogg container, or None when ffmpeg is absent.
fn generate_audio(target: &Path) -> Option<()> {
    let status = std::process::Command::new("ffmpeg")
        .args([
            "-y",
            "-f",
            "lavfi",
            "-i",
            "anullsrc=r=44100:cl=mono",
            "-t",
            "1",
        ])
        .arg(target)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();
    match status {
        Ok(s) if s.success() => Some(()),
        _ => {
            eprintln!("skipping: ffmpeg unavailable or failed");
            None
        }
    }
}

/// 1 second of 64x64 test video (rawvideo in NUT — no encoder needed),
/// or None when ffmpeg is absent.
fn generate_video(target: &Path) -> Option<()> {
    let status = std::process::Command::new("ffmpeg")
        .args([
            "-y",
            "-f",
            "lavfi",
            "-i",
            "testsrc2=size=64x64:rate=10",
            "-t",
            "1",
            "-c:v",
            "rawvideo",
            "-pix_fmt",
            "yuv420p",
            "-f",
            "nut",
        ])
        .arg(target)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();
    match status {
        Ok(s) if s.success() => Some(()),
        _ => {
            eprintln!("skipping: ffmpeg unavailable or failed");
            None
        }
    }
}

fn pump_until(engine: &Engine, mut stop: impl FnMut(&PlaybackEvent) -> bool) -> bool {
    for _ in 0..100 {
        for ev in engine.pump_events() {
            if stop(&ev) {
                return true;
            }
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    false
}

/// Poll `pred` at [`pump_until`]'s cadence (50ms interval, ~5s deadline)
/// until it holds — the one home for the wait/timeout policy, so a
/// flakiness fix lands everywhere at once.
fn wait_until(mut pred: impl FnMut() -> bool) -> bool {
    (0..100).any(|_| {
        std::thread::sleep(Duration::from_millis(50));
        pred()
    })
}

/// [`pump_until`]'s negative-check twin: drain events for roughly `dur`
/// at the same cadence and return everything seen — for asserting what
/// must NOT arrive inside a window.
fn pump_for(engine: &Engine, dur: Duration) -> Vec<PlaybackEvent> {
    let mut out = Vec::new();
    for _ in 0..dur.as_millis().div_ceil(50) {
        std::thread::sleep(Duration::from_millis(50));
        out.extend(engine.pump_events());
    }
    out
}

/// The spaced-path regression that motivated the array-args command layer:
/// a file whose name carries spaces, quotes, and parens must reach
/// `Loaded`. (Under a string-joined command layer this failed with
/// `MPV_ERROR_INVALID_PARAMETER`.)
#[test]
fn loadfile_handles_awkward_filenames() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("Riley Cyriis_test \"q\" (copy).ogg");
    if generate_audio(&source).is_none() {
        return;
    }
    let Some(engine) = headless_engine() else {
        return;
    };
    engine.load(source.to_str().unwrap()).unwrap();

    let loaded = pump_until(&engine, |ev| match ev {
        PlaybackEvent::Loaded => true,
        PlaybackEvent::Failed { message, .. } => {
            panic!("loadfile failed on awkward path: {message}")
        }
        _ => false,
    });
    assert!(loaded, "awkward-path file never reached Loaded");
}

/// An empty/invalid file must surface a typed `Failed` event rather than
/// being swallowed. A 0-byte file is rejected at demux, before any
/// audio-output init, so this doesn't need a sound device either.
#[test]
fn empty_file_surfaces_failed_event() {
    let Some(engine) = headless_engine() else {
        return;
    };
    let dir = tempfile::tempdir().unwrap();
    let bad = dir.path().join("empty.mkv");
    std::fs::File::create(&bad).unwrap();
    engine.load(bad.to_str().unwrap()).unwrap();

    let failed = pump_until(&engine, |ev| match ev {
        PlaybackEvent::Failed { code, .. } => {
            // mpv error codes are negative by contract — integrators rely
            // on the raw code to map to their own error copy.
            assert!(*code < 0, "Failed event must carry a negative mpv code");
            true
        }
        _ => false,
    });
    assert!(failed, "empty file must produce a Failed playback event");
}

/// `load_paused` really holds playback: after `Loaded`, the engine reports
/// paused and position does not advance until unpaused.
#[test]
fn load_paused_holds_until_unpaused() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("tone.ogg");
    if generate_audio(&source).is_none() {
        return;
    }
    let Some(engine) = headless_engine() else {
        return;
    };
    engine.load_paused(source.to_str().unwrap()).unwrap();
    assert!(pump_until(&engine, |ev| matches!(
        ev,
        PlaybackEvent::Loaded
    )));
    assert!(engine.is_paused(), "engine must come up paused");

    // Even while paused, time-pos appears a beat after `Loaded` and can
    // shift once more as the initial playback restart settles. Wait for
    // two consecutive equal samples 200ms apart — that pair *is* the
    // hold check: a genuinely advancing position never stabilizes.
    let mut held = None;
    let settled = (0..25).any(|_| {
        let a = engine.position();
        std::thread::sleep(Duration::from_millis(200));
        if a.is_some() && a == engine.position() {
            held = a;
            true
        } else {
            false
        }
    });
    assert!(settled, "position must settle and hold while paused");

    engine.set_paused(false).unwrap();
    assert!(!engine.is_paused());
    let advanced = wait_until(|| engine.position() > held);
    assert!(advanced, "position must advance after unpausing");
}

/// On an engine whose `vo` never touches the render API, no attach is
/// coming — `load_when_ready` must degrade to a plain playing `load`
/// instead of a deferred start that would hold paused forever.
#[test]
fn load_when_ready_plays_immediately_without_render_api() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("tone.ogg");
    if generate_audio(&source).is_none() {
        return;
    }
    let Some(engine) = headless_engine() else {
        return;
    };
    engine.load_when_ready(source.to_str().unwrap()).unwrap();
    assert!(pump_until(&engine, |ev| matches!(
        ev,
        PlaybackEvent::Loaded
    )));
    assert!(
        !engine.is_paused(),
        "no render attach is coming — playback must start immediately"
    );
}

/// The deferred-load policy end-to-end on a render-API engine: the
/// `loadfile` itself waits for the attach. Loading before the context
/// exists isn't survivable — mpv can't init the VO, drops the video
/// track, and a video-only file dies with `MPV_ERROR_NOTHING_TO_PLAY`
/// (-16) — so the pre-attach window must stay silent (no Failed), and
/// the attach call must issue the load and reach `Loaded` playing.
#[test]
fn load_when_ready_loads_on_attach() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("test.nut");
    if generate_video(&source).is_none() {
        return;
    }
    let Some(engine) = video_engine() else {
        return;
    };
    engine.load_when_ready(source.to_str().unwrap()).unwrap();

    // The failure this API exists to prevent lands within ~100ms of an
    // eager load; 200ms of silence proves nothing was loaded eagerly.
    for ev in pump_for(&engine, Duration::from_millis(200)) {
        match ev {
            PlaybackEvent::Failed { message, .. } => {
                panic!("deferred load must not fail pre-attach: {message}")
            }
            PlaybackEvent::Loaded => panic!("load must wait for the attach"),
            _ => {}
        }
    }

    engine.attach_sw_render(|| {}).unwrap();
    let loaded = pump_until(&engine, |ev| match ev {
        PlaybackEvent::Loaded => true,
        PlaybackEvent::Failed { message, .. } => {
            panic!("deferred load failed after attach: {message}")
        }
        _ => false,
    });
    assert!(loaded, "attach must issue the deferred load");
    assert!(!engine.is_paused(), "deferred load must come up playing");
}

/// Pause intent set between `load_when_ready` and the attach carries
/// into the deferred load: the `pause` property persists across
/// `loadfile`, so the queued file comes up paused — no policy flag
/// second-guesses the user.
#[test]
fn pause_before_attach_loads_deferred_file_paused() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("test.nut");
    if generate_video(&source).is_none() {
        return;
    }
    let Some(engine) = video_engine() else {
        return;
    };
    engine.load_when_ready(source.to_str().unwrap()).unwrap();
    engine.set_paused(true).unwrap();

    engine.attach_sw_render(|| {}).unwrap();
    assert!(pump_until(&engine, |ev| matches!(
        ev,
        PlaybackEvent::Loaded
    )));
    assert!(
        engine.is_paused(),
        "pause set before attach must hold through the deferred load"
    );
}

/// The defer-or-load decision reads the *current* `vo`, not a build-time
/// snapshot: a render-API engine switched to `vo=null` at runtime (an
/// audio-only mode) gets a plain playing load — not a source parked in
/// the queue waiting for an attach that will never come.
#[test]
fn load_when_ready_follows_runtime_vo_change() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("test.nut");
    if generate_video(&source).is_none() {
        return;
    }
    let Some(engine) = video_engine() else {
        return;
    };
    engine.set_property("vo", "null").unwrap();
    engine.load_when_ready(source.to_str().unwrap()).unwrap();
    assert!(
        pump_until(&engine, |ev| matches!(ev, PlaybackEvent::Loaded)),
        "with vo switched off the render API, the load must not defer"
    );
    assert!(!engine.is_paused(), "playback must start immediately");
}

/// Transport commands issued through the `command` escape hatch obey the
/// same "newest call decides what plays" rule as the typed methods: a
/// `stop` between `load_when_ready` and the attach discards the queued
/// source — the attach must not resurrect it.
#[test]
fn command_stop_discards_deferred_load() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("test.nut");
    if generate_video(&source).is_none() {
        return;
    }
    let Some(engine) = video_engine() else {
        return;
    };
    engine.load_when_ready(source.to_str().unwrap()).unwrap();
    engine.command("stop", &[]).unwrap();
    engine.attach_sw_render(|| {}).unwrap();
    // A wrongly issued load surfaces well within this window (see the
    // pre-attach check in load_when_ready_loads_on_attach).
    for ev in pump_for(&engine, Duration::from_millis(200)) {
        assert!(
            !matches!(ev, PlaybackEvent::Loaded),
            "stop before attach must discard the deferred load"
        );
    }
    assert!(engine.is_idle(), "nothing may be loaded after the stop");
}

/// An attach `Err` means "no context was attached" — nothing else. A
/// deferred source that cannot play must not fail the attach: the
/// context goes live, and the failure arrives as a `Failed` event.
#[test]
fn attach_survives_failing_deferred_load() {
    let Some(engine) = video_engine() else {
        return;
    };
    engine.load_when_ready("/nonexistent/deferred.nut").unwrap();
    engine
        .attach_sw_render(|| {})
        .expect("a failing deferred load must not fail the attach");
    assert!(engine.has_render(), "the render context must be live");
    assert!(
        pump_until(&engine, |ev| matches!(ev, PlaybackEvent::Failed { .. })),
        "the deferred load's failure must surface as a Failed event"
    );
}

/// `stop()` surfaces as `Ended { reason: Stop }` — the distinction
/// playlist logic needs (user stop must not auto-advance, EOF should).
#[test]
fn stop_reports_stop_reason() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("tone.ogg");
    if generate_audio(&source).is_none() {
        return;
    }
    let Some(engine) = headless_engine() else {
        return;
    };
    engine.load_paused(source.to_str().unwrap()).unwrap();
    assert!(pump_until(&engine, |ev| matches!(
        ev,
        PlaybackEvent::Loaded
    )));

    engine.stop().unwrap();
    let ended = pump_until(&engine, |ev| match ev {
        PlaybackEvent::Ended { reason } => {
            assert_eq!(*reason, EndReason::Stop, "stop must not look like EOF");
            true
        }
        _ => false,
    });
    assert!(ended, "stop must produce an Ended event");
}

/// Observation delivers the current value immediately, then pushes
/// changes: no polling needed for UI state like volume sliders.
#[test]
fn observe_pushes_initial_value_and_changes() {
    let Some(engine) = headless_engine() else {
        return;
    };
    let observe_id = engine.observe("volume", PropertyFormat::Double).unwrap();

    // mpv sends the current value right after observe registration, and
    // the event's id must round-trip so multiple observations of one
    // property stay distinguishable.
    let initial = pump_until(&engine, |ev| {
        matches!(
            ev,
            PlaybackEvent::PropertyChanged { id, name, .. }
                if name == "volume" && *id == observe_id
        )
    });
    assert!(initial, "observe must push the initial value with its id");

    engine.set_volume(55.0).unwrap();
    let changed = pump_until(&engine, |ev| {
        matches!(
            ev,
            PlaybackEvent::PropertyChanged { name, value: PropertyValue::Double(v), .. }
                if name == "volume" && *v == 55.0
        )
    });
    assert!(changed, "volume change must arrive as PropertyChanged");
}

/// The software render path end-to-end, no GL and no display: attach,
/// load real video, wait for a frame signal, render, and pin the
/// opaque-alpha guarantee plus the backend-mismatch error.
#[test]
fn sw_render_produces_opaque_rgba_frames() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("test.nut");
    if generate_video(&source).is_none() {
        return;
    }
    let Some(engine) = video_engine() else {
        return;
    };

    // With no backend attached, update processing is a `false` no-op.
    assert!(!engine.render_update());

    let frame_ready = Arc::new(AtomicBool::new(false));
    let flag = frame_ready.clone();
    engine
        .attach_sw_render(move || flag.store(true, Ordering::SeqCst))
        .unwrap();
    // The registration itself signals once synchronously; clear that so
    // the flag below means "a real frame wants drawing".
    frame_ready.store(false, Ordering::SeqCst);

    engine.load(source.to_str().unwrap()).unwrap();
    assert!(pump_until(&engine, |ev| matches!(
        ev,
        PlaybackEvent::Loaded
    )));
    let ready = wait_until(|| frame_ready.load(Ordering::SeqCst));
    assert!(ready, "update callback must signal a frame");

    // The signaled frame must also be visible through the pull side of
    // the seam: `render_update` reports a frame wants drawing.
    let update_frame = wait_until(|| engine.render_update());
    assert!(update_frame, "render_update must report the pending frame");

    let mut buf = Vec::new();
    engine.render_sw(64, 64, &mut buf).unwrap();
    assert_eq!(buf.len(), 64 * 64 * 4);
    assert!(
        buf.chunks_exact(4).all(|px| px[3] == 0xFF),
        "every pixel's alpha must be forced opaque"
    );
    assert!(
        buf.chunks_exact(4)
            .any(|px| px[..3].iter().any(|&b| b != 0)),
        "a rendered test-pattern frame must contain non-black pixels"
    );

    // A GL draw against the software backend is a wiring bug and must
    // surface as an error, not a silent no-op.
    assert!(engine.render_gl(0, 64, 64, false).is_err());

    engine.detach_render();
    assert!(!engine.has_render());
}

/// The wakeup callback pushes a signal when events queue — no polling
/// timer needed to learn about `Loaded`.
#[test]
fn wakeup_callback_fires_on_events() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("tone.ogg");
    if generate_audio(&source).is_none() {
        return;
    }
    let Some(engine) = headless_engine() else {
        return;
    };

    let woke = Arc::new(AtomicBool::new(false));
    let flag = woke.clone();
    engine.set_wakeup_callback(move || flag.store(true, Ordering::SeqCst));
    // Registration fires the callback once synchronously (and mpv may
    // wake spuriously); clear so the flag below means "events queued
    // after load", not the registration echo.
    woke.store(false, Ordering::SeqCst);

    engine.load(source.to_str().unwrap()).unwrap();
    let signaled = wait_until(|| woke.load(Ordering::SeqCst));
    assert!(signaled, "wakeup must fire when events queue");
    assert!(
        pump_until(&engine, |ev| matches!(ev, PlaybackEvent::Loaded)),
        "the signaled events must include Loaded"
    );
}

/// `GlRenderOptions` must be constructible from outside the crate: it is
/// `#[non_exhaustive]`, which forbids struct expressions here (E0639 —
/// functional record update gets no exemption), so the chainable setters
/// are the consumer path and this file being an external crate makes the
/// compile itself the probe. Pure construction — no mpv needed.
#[test]
fn gl_render_options_build_externally() {
    let opts = mpv_engine::GlRenderOptions::default()
        .block_for_target_time(false)
        .advanced_control(true);
    assert!(!opts.block_for_target_time);
    assert!(opts.advanced_control);
}

/// Engines drop cleanly without a render context ever attached (the
/// explicit Drop-order path with an empty render slot).
#[test]
fn engine_drops_cleanly_without_render() {
    let Some(engine) = headless_engine() else {
        return;
    };
    assert!(!engine.has_render());
    drop(engine);
}

/// `attached_render` answers "which backend?", not just "any backend?":
/// `None` before attach, the kind while attached, `None` again after
/// detach. (Only the software kind is reachable headless; the GL arm of
/// the mapping is a two-variant match pinned at the type level.)
#[test]
fn attached_render_reports_backend_kind() {
    let Some(engine) = video_engine() else {
        return;
    };
    assert_eq!(engine.attached_render(), None);

    engine.attach_sw_render(|| {}).unwrap();
    assert_eq!(
        engine.attached_render(),
        Some(mpv_engine::RenderKind::Software)
    );

    engine.detach_render();
    assert_eq!(engine.attached_render(), None);
}

/// Registering a render-update callback with no context attached is a
/// wiring bug (it could never fire) and must error loudly, not drop the
/// closure silently — before the first attach and after detach alike.
#[test]
fn render_update_callback_requires_attach() {
    let Some(engine) = video_engine() else {
        return;
    };
    assert!(matches!(
        engine.set_render_update_callback(|| {}),
        Err(mpv_engine::Error::NotAttached)
    ));

    engine.attach_sw_render(|| {}).unwrap();
    engine.set_render_update_callback(|| {}).unwrap();

    engine.detach_render();
    assert!(matches!(
        engine.set_render_update_callback(|| {}),
        Err(mpv_engine::Error::NotAttached)
    ));
}

/// `set_render_update_callback` hands mpv's update signal to the new
/// closure: the replacement is raised at registration, frame updates
/// land on it once video flows, and the attach-time closure never fires
/// again — the construct-share-register flow shells need when their
/// real callback can only capture state built after the engine.
#[test]
fn render_update_callback_replaces_attach_registration() {
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("test.nut");
    if generate_video(&source).is_none() {
        return;
    }
    let Some(engine) = video_engine() else {
        return;
    };

    let attach_fires = Arc::new(AtomicU32::new(0));
    let attach_counter = attach_fires.clone();
    engine
        .attach_sw_render(move || {
            attach_counter.fetch_add(1, Ordering::SeqCst);
        })
        .unwrap();
    assert!(
        attach_fires.load(Ordering::SeqCst) >= 1,
        "attach must raise its on_update synchronously"
    );

    let replacement_fires = Arc::new(AtomicU32::new(0));
    let replacement_counter = replacement_fires.clone();
    engine
        .set_render_update_callback(move || {
            replacement_counter.fetch_add(1, Ordering::SeqCst);
        })
        .unwrap();
    // The registration fire is synchronous — inside the call, like the
    // attach-time fire asserted above. A poll here would keep passing if
    // that guarantee regressed to "eventually"; a plain assert pins it.
    assert!(
        replacement_fires.load(Ordering::SeqCst) >= 1,
        "registration must raise the replacement callback synchronously"
    );
    // No async dispatch source exists before load() — nothing else can
    // move the attach counter from here on.
    let attach_count_after_swap = attach_fires.load(Ordering::SeqCst);

    engine.load(source.to_str().unwrap()).unwrap();
    let before_frames = replacement_fires.load(Ordering::SeqCst);
    let frames_signaled = wait_until(|| replacement_fires.load(Ordering::SeqCst) > before_frames);
    assert!(
        frames_signaled,
        "frame updates must land on the replacement callback"
    );
    assert_eq!(
        attach_fires.load(Ordering::SeqCst),
        attach_count_after_swap,
        "the replaced attach-time callback must not fire after the swap"
    );
}

/// The swap's synchronous fire runs outside every engine lock: a
/// replacement callback that queries the engine must not deadlock — the
/// regression shape for the fire-under-the-render-lock bug. (A regressed
/// engine hangs here, which is the loudest failure a deadlock can give.)
#[test]
fn render_update_callback_sync_fire_holds_no_engine_lock() {
    let Some(engine) = video_engine() else {
        return;
    };
    engine.attach_sw_render(|| {}).unwrap();
    let engine = Arc::new(engine);
    let probe = Arc::downgrade(&engine);
    let saw_context = Arc::new(AtomicBool::new(false));
    let saw = saw_context.clone();
    engine
        .set_render_update_callback(move || {
            if let Some(e) = probe.upgrade() {
                saw.store(e.has_render(), Ordering::SeqCst);
            }
        })
        .unwrap();
    assert!(
        saw_context.load(Ordering::SeqCst),
        "the sync fire must see the live context, without deadlocking"
    );
}

/// A `quit` through the command escape hatch must surface as a
/// `Shutdown` event — the shell's only direct signal that the core is
/// gone (an `Ended { reason: Quit }` only accompanies it when a file was
/// playing).
#[test]
fn quit_surfaces_shutdown_event() {
    let Some(engine) = headless_engine() else {
        return;
    };
    engine.command("quit", &[]).unwrap();
    assert!(pump_until(&engine, |ev| matches!(
        ev,
        PlaybackEvent::Shutdown
    )));
}