rosier 0.5.1

A fast picture and video viewer for large folders
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
//! Minimal binding to libmpv's client and software render API.
//!
//! rosier draws video itself inside split-view panes, so it asks mpv for BGRA
//! frames at the size it needs ("sw" render API) instead of letting mpv open
//! a window. The same path makes video thumbnails, so users do not need the
//! ffmpeg command.

use std::ffi::{CStr, CString, c_char, c_double, c_int, c_void};
use std::ptr;
use std::time::{Duration, Instant};

use anyhow::{Result, bail};

use crate::turbo::Bgra;

#[repr(C)]
struct MpvHandle {
    _p: [u8; 0],
}
#[repr(C)]
struct MpvRenderContext {
    _p: [u8; 0],
}

#[repr(C)]
struct MpvEvent {
    event_id: c_int,
    error: c_int,
    reply_userdata: u64,
    data: *mut c_void,
}

#[repr(C)]
struct MpvRenderParam {
    kind: c_int,
    data: *mut c_void,
}

const PARAM_INVALID: c_int = 0;
const PARAM_API_TYPE: c_int = 1;
const PARAM_SW_SIZE: c_int = 17;
const PARAM_SW_FORMAT: c_int = 18;
const PARAM_SW_STRIDE: c_int = 19;
const PARAM_SW_POINTER: c_int = 20;
const UPDATE_FRAME: u64 = 1;
const FORMAT_STRING: c_int = 1;
const FORMAT_FLAG: c_int = 3;
const FORMAT_INT64: c_int = 4;
const FORMAT_DOUBLE: c_int = 5;

const EVENT_SHUTDOWN: c_int = 1;
const EVENT_END_FILE: c_int = 7;
const EVENT_PLAYBACK_RESTART: c_int = 21;
/// `mpv_end_file_reason`: playback stopped because of an error.
const END_FILE_REASON_ERROR: c_int = 4;

/// The start of `mpv_event_end_file`.
#[repr(C)]
struct MpvEventEndFile {
    reason: c_int,
    _error: c_int,
}

/// What `Player::wait_event` saw.
#[derive(Debug, PartialEq, Eq)]
pub enum Event {
    /// A timeout, or an event rosier does not act on.
    Other,
    Shutdown,
    /// The file played to its end (or playback was stopped).
    Ended,
    /// The file could not be played.
    Failed,
    /// Playback (re)started after loading or seeking.
    Restarted,
}

/// libmpv's functions, loaded when first needed instead of linked at build
/// time. rosier then builds anywhere without libmpv, and the release
/// archives ship the library next to the program.
struct Api {
    _lib: libloading::Library,
    create: unsafe extern "C" fn() -> *mut MpvHandle,
    initialize: unsafe extern "C" fn(*mut MpvHandle) -> c_int,
    terminate_destroy: unsafe extern "C" fn(*mut MpvHandle),
    set_option_string: unsafe extern "C" fn(*mut MpvHandle, *const c_char, *const c_char) -> c_int,
    set_property_string: unsafe extern "C" fn(*mut MpvHandle, *const c_char, *const c_char) -> c_int,
    get_property: unsafe extern "C" fn(*mut MpvHandle, *const c_char, c_int, *mut c_void) -> c_int,
    free: unsafe extern "C" fn(*mut c_void),
    command: unsafe extern "C" fn(*mut MpvHandle, *mut *const c_char) -> c_int,
    wait_event: unsafe extern "C" fn(*mut MpvHandle, c_double) -> *mut MpvEvent,
    error_string: unsafe extern "C" fn(c_int) -> *const c_char,
    render_context_create:
        unsafe extern "C" fn(*mut *mut MpvRenderContext, *mut MpvHandle, *mut MpvRenderParam) -> c_int,
    render_context_update: unsafe extern "C" fn(*mut MpvRenderContext) -> u64,
    render_context_render: unsafe extern "C" fn(*mut MpvRenderContext, *mut MpvRenderParam) -> c_int,
    render_context_free: unsafe extern "C" fn(*mut MpvRenderContext),
}

/// Names to try, most specific first. A copy next to the executable (or in
/// the app bundle's Frameworks folder on macOS) wins over the system's.
fn candidates() -> Vec<std::path::PathBuf> {
    let names: &[&str] = if cfg!(windows) {
        &["libmpv-2.dll", "mpv-2.dll", "mpv-1.dll"]
    } else if cfg!(target_os = "macos") {
        &["libmpv.2.dylib", "libmpv.dylib"]
    } else {
        &["libmpv.so.2", "libmpv.so.1", "libmpv.so"]
    };
    let mut out = Vec::new();
    if let Some(dir) = std::env::current_exe().ok().and_then(|e| e.parent().map(|p| p.to_path_buf())) {
        for n in names {
            out.push(dir.join(n));
            if cfg!(target_os = "macos") {
                out.push(dir.join("../Frameworks").join(n));
            }
            // The AppImage keeps its libraries in usr/lib beside usr/bin.
            if cfg!(target_os = "linux") {
                out.push(dir.join("../lib").join(n));
            }
        }
    }
    if cfg!(target_os = "macos") {
        for prefix in ["/opt/homebrew/lib", "/usr/local/lib"] {
            out.extend(names.iter().map(|n| std::path::Path::new(prefix).join(n)));
        }
    }
    // Bare names: the system's normal library search.
    out.extend(names.iter().map(std::path::PathBuf::from));
    out
}

fn load() -> Result<Api, String> {
    let mut last = String::from("not found");
    for path in candidates() {
        // SAFETY: loading libmpv runs only its library initializers.
        let lib = match unsafe { libloading::Library::new(&path) } {
            Ok(lib) => lib,
            Err(e) => {
                last = e.to_string();
                continue;
            }
        };
        macro_rules! sym {
            ($name:literal) => {
                // SAFETY: the signature matches libmpv's client.h / render.h.
                *unsafe { lib.get(concat!($name, "\0").as_bytes()) }.map_err(|e| e.to_string())?
            };
        }
        let api = Api {
            create: sym!("mpv_create"),
            initialize: sym!("mpv_initialize"),
            terminate_destroy: sym!("mpv_terminate_destroy"),
            set_option_string: sym!("mpv_set_option_string"),
            set_property_string: sym!("mpv_set_property_string"),
            get_property: sym!("mpv_get_property"),
            free: sym!("mpv_free"),
            command: sym!("mpv_command"),
            wait_event: sym!("mpv_wait_event"),
            error_string: sym!("mpv_error_string"),
            render_context_create: sym!("mpv_render_context_create"),
            render_context_update: sym!("mpv_render_context_update"),
            render_context_render: sym!("mpv_render_context_render"),
            render_context_free: sym!("mpv_render_context_free"),
            _lib: lib,
        };
        return Ok(api);
    }
    Err(format!("libmpv could not be loaded ({last})"))
}

/// libmpv, loaded the first time anything needs it (a picture-only start
/// never pays for loading it), with its silent first player made at once.
fn api() -> Result<&'static Api> {
    use std::sync::OnceLock;
    static API: OnceLock<Result<Api, String>> = OnceLock::new();
    let api = API.get_or_init(load).as_ref().map_err(|e| anyhow::anyhow!("{e}"))?;
    quiet_logging(api);
    Ok(api)
}

fn err(code: c_int) -> String {
    match api() {
        // SAFETY: mpv_error_string returns a static C string.
        Ok(a) => unsafe { CStr::from_ptr((a.error_string)(code)) }.to_string_lossy().into_owned(),
        Err(e) => e.to_string(),
    }
}

fn cstr(s: &str) -> CString {
    CString::new(s).unwrap_or_default()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrackKind {
    Audio,
    Sub,
}

/// An audio or subtitle track of the playing file.
#[derive(Debug, Clone, PartialEq)]
pub struct Track {
    pub kind: TrackKind,
    pub id: i64,
    pub lang: Option<String>,
    pub title: Option<String>,
    pub selected: bool,
}

/// One mpv player that renders into memory.
pub struct Player {
    api: &'static Api,
    h: *mut MpvHandle,
    rctx: *mut MpvRenderContext,
}

// mpv's client API is thread-safe. The render context and mpv_wait_event are
// only ever used by one thread (the thumbnail caller or a video thread);
// other threads only send commands and read or set properties.
unsafe impl Send for Player {}
unsafe impl Sync for Player {}

impl Player {
    /// Creates a player. `opts` are mpv options set before initialization.
    pub fn new(opts: &[(&str, &str)]) -> Result<Self> {
        let api = api()?;
        let h = unsafe { (api.create)() };
        if h.is_null() {
            bail!("mpv_create failed");
        }
        let mut p = Player { api, h, rctx: ptr::null_mut() };
        let base = [
            ("vo", "libmpv"),
            ("config", "no"),
            ("terminal", "no"),
            ("msg-level", "all=no"),
            ("load-scripts", "no"),
            ("ytdl", "no"),
            ("osc", "no"),
            ("input-default-bindings", "no"),
        ];
        for (k, v) in base.iter().chain(opts.iter()) {
            let (k, v) = (cstr(k), cstr(v));
            let rc = unsafe { (p.api.set_option_string)(p.h, k.as_ptr(), v.as_ptr()) };
            if rc < 0 {
                bail!("mpv option {}: {}", k.to_string_lossy(), err(rc));
            }
        }
        let rc = unsafe { (p.api.initialize)(p.h) };
        if rc < 0 {
            bail!("mpv_initialize: {}", err(rc));
        }
        // The render context must exist before a file is loaded.
        let api = cstr("sw");
        let mut params = [
            MpvRenderParam { kind: PARAM_API_TYPE, data: api.as_ptr() as *mut c_void },
            MpvRenderParam { kind: PARAM_INVALID, data: ptr::null_mut() },
        ];
        let rc = unsafe { (p.api.render_context_create)(&mut p.rctx, p.h, params.as_mut_ptr()) };
        if rc < 0 {
            bail!("mpv_render_context_create: {}", err(rc));
        }
        Ok(p)
    }

    pub fn command(&self, args: &[&str]) -> Result<()> {
        let owned: Vec<CString> = args.iter().map(|a| cstr(a)).collect();
        let mut ptrs: Vec<*const c_char> = owned.iter().map(|c| c.as_ptr()).collect();
        ptrs.push(ptr::null());
        let rc = unsafe { (self.api.command)(self.h, ptrs.as_mut_ptr()) };
        if rc < 0 {
            bail!("mpv {:?}: {}", args.first(), err(rc));
        }
        Ok(())
    }

    pub fn set(&self, name: &str, value: &str) -> Result<()> {
        let (k, v) = (cstr(name), cstr(value));
        let rc = unsafe { (self.api.set_property_string)(self.h, k.as_ptr(), v.as_ptr()) };
        if rc < 0 {
            bail!("mpv set {name}: {}", err(rc));
        }
        Ok(())
    }

    fn get_i64(&self, name: &str) -> Option<i64> {
        let k = cstr(name);
        let mut v: i64 = 0;
        let rc =
            unsafe { (self.api.get_property)(self.h, k.as_ptr(), FORMAT_INT64, &mut v as *mut i64 as *mut c_void) };
        (rc >= 0).then_some(v)
    }

    pub fn get_string(&self, name: &str) -> Option<String> {
        let k = cstr(name);
        let mut v: *mut c_char = ptr::null_mut();
        let rc = unsafe {
            (self.api.get_property)(self.h, k.as_ptr(), FORMAT_STRING, &mut v as *mut *mut c_char as *mut c_void)
        };
        if rc < 0 || v.is_null() {
            return None;
        }
        // SAFETY: mpv returned a NUL-terminated string it allocated; it is
        // copied and then handed back to mpv_free.
        let out = unsafe { CStr::from_ptr(v) }.to_string_lossy().into_owned();
        unsafe { (self.api.free)(v as *mut c_void) };
        Some(out)
    }

    /// Start times of the file's chapters, in seconds.
    pub fn chapters(&self) -> Vec<f64> {
        let n = self.get_i64("chapter-list/count").unwrap_or(0);
        (0..n).filter_map(|i| self.get_f64(&format!("chapter-list/{i}/time"))).collect()
    }

    /// The file's audio and subtitle tracks, in mpv's order.
    pub fn tracks(&self) -> Vec<Track> {
        let n = self.get_i64("track-list/count").unwrap_or(0);
        (0..n)
            .filter_map(|i| {
                let kind = match self.get_string(&format!("track-list/{i}/type"))?.as_str() {
                    "audio" => TrackKind::Audio,
                    "sub" => TrackKind::Sub,
                    _ => return None,
                };
                Some(Track {
                    kind,
                    id: self.get_i64(&format!("track-list/{i}/id"))?,
                    lang: self.get_string(&format!("track-list/{i}/lang")),
                    title: self.get_string(&format!("track-list/{i}/title")),
                    selected: self.get_flag(&format!("track-list/{i}/selected")).unwrap_or(false),
                })
            })
            .collect()
    }

    pub fn get_flag(&self, name: &str) -> Option<bool> {
        let k = cstr(name);
        let mut v: c_int = 0;
        let rc =
            unsafe { (self.api.get_property)(self.h, k.as_ptr(), FORMAT_FLAG, &mut v as *mut c_int as *mut c_void) };
        (rc >= 0).then_some(v != 0)
    }

    pub fn get_f64(&self, name: &str) -> Option<f64> {
        let k = cstr(name);
        let mut v: f64 = 0.0;
        let rc =
            unsafe { (self.api.get_property)(self.h, k.as_ptr(), FORMAT_DOUBLE, &mut v as *mut f64 as *mut c_void) };
        (rc >= 0).then_some(v)
    }

    /// Waits up to `timeout` for the next event.
    pub fn wait_event(&self, timeout: Duration) -> Event {
        // SAFETY: mpv returns a pointer valid until the next wait_event call
        // on this handle, and END_FILE events carry an mpv_event_end_file.
        unsafe {
            let ev = (self.api.wait_event)(self.h, timeout.as_secs_f64());
            if ev.is_null() {
                return Event::Other;
            }
            match (*ev).event_id {
                EVENT_SHUTDOWN => Event::Shutdown,
                EVENT_PLAYBACK_RESTART => Event::Restarted,
                EVENT_END_FILE => {
                    let end = (*ev).data as *const MpvEventEndFile;
                    if !end.is_null() && (*end).reason == END_FILE_REASON_ERROR { Event::Failed } else { Event::Ended }
                }
                _ => Event::Other,
            }
        }
    }

    /// True when mpv has a new video frame to render.
    pub fn frame_ready(&self) -> bool {
        unsafe { (self.api.render_context_update)(self.rctx) & UPDATE_FRAME != 0 }
    }

    /// Displayed video size (after rotation and aspect correction).
    pub fn video_size(&self) -> Option<(u32, u32)> {
        let w = self.get_i64("dwidth")?;
        let h = self.get_i64("dheight")?;
        (w > 0 && h > 0).then_some((w as u32, h as u32))
    }

    /// Renders the current frame scaled to `w`x`h` as opaque BGRA.
    pub fn render(&self, w: u32, h: u32) -> Result<Bgra> {
        let mut size: [c_int; 2] = [w as c_int, h as c_int];
        let fmt = cstr("bgr0");
        let mut stride: usize = w as usize * 4;
        let mut pixels = vec![0u8; stride * h as usize];
        let mut params = [
            MpvRenderParam { kind: PARAM_SW_SIZE, data: size.as_mut_ptr() as *mut c_void },
            MpvRenderParam { kind: PARAM_SW_FORMAT, data: fmt.as_ptr() as *mut c_void },
            MpvRenderParam { kind: PARAM_SW_STRIDE, data: &mut stride as *mut usize as *mut c_void },
            MpvRenderParam { kind: PARAM_SW_POINTER, data: pixels.as_mut_ptr() as *mut c_void },
            MpvRenderParam { kind: PARAM_INVALID, data: ptr::null_mut() },
        ];
        let rc = unsafe { (self.api.render_context_render)(self.rctx, params.as_mut_ptr()) };
        if rc < 0 {
            bail!("mpv render: {}", err(rc));
        }
        // "bgr0" leaves the 4th byte undefined; gpui expects opaque alpha.
        opaque(&mut pixels);
        Ok(Bgra { width: w, height: h, pixels })
    }
}

impl Drop for Player {
    fn drop(&mut self) {
        unsafe {
            if !self.rctx.is_null() {
                (self.api.render_context_free)(self.rctx);
            }
            (self.api.terminate_destroy)(self.h);
        }
    }
}

/// Sets the alpha byte of every BGRA pixel to 255, four bytes at a time so
/// the compiler vectorizes it (a quarter of the time at 4K).
fn opaque(pixels: &mut [u8]) {
    // SAFETY: any bytes are a valid u32; align_to_mut splits off the
    // unaligned ends, and then the byte loop below does the whole buffer.
    let (head, words, tail) = unsafe { pixels.align_to_mut::<u32>() };
    if head.is_empty() && tail.is_empty() {
        let alpha = u32::from_le_bytes([0, 0, 0, 255]);
        for w in words {
            *w |= alpha;
        }
        return;
    }
    for px in pixels.as_chunks_mut::<4>().0 {
        px[3] = 255;
    }
}

/// Hardware decoders that hand frames back to memory, for each platform:
/// VA-API (Linux), NVDEC, VideoToolbox (macOS) and D3D11VA (Windows). mpv
/// takes the first that works and decodes in software otherwise.
pub const HWDEC_COPY: &str = "vaapi-copy,nvdec-copy,videotoolbox-copy,d3d11va-copy";

/// HDR video (PQ or HLG) turned into SDR for an ordinary screen: the
/// software renderer converts colors but cannot tone-map, so highlights
/// above 100 nits all came out white. libplacebo (in FFmpeg) tone-maps with
/// Hable on the GPU through Vulkan: 4K60 plays every frame on 2 cores,
/// where the CPU chain below took 9 and fell to 49 fps. nv12 out: BGRA
/// made it slower (four bytes a pixel back from the GPU against 1.5).
pub const HDR_TO_SDR: &str =
    "lavfi=[libplacebo=tonemapping=hable:colorspace=bt709:color_primaries=bt709:color_trc=bt709:range=tv:format=nv12]";

/// The same on the CPU with FFmpeg's zscale and tonemap, for an FFmpeg
/// without libplacebo or a machine without Vulkan. Where FFmpeg lacks
/// these too, mpv drops the filter and the video plays as before.
pub const HDR_TO_SDR_CPU: &str = "lavfi=[zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p]";

/// Whether mpv's `video-params/gamma` names an HDR transfer.
pub fn is_hdr(gamma: &str) -> bool {
    matches!(gamma, "pq" | "hlg")
}

/// Grabs one frame from `path` (at `start`, an mpv time spec such as "10%")
/// scaled so its longer side is at most `max_long`, for a thumbnail.
pub fn grab_frame(path: &std::path::Path, start: &str, max_long: u32) -> Result<Bgra> {
    grab(path, start, max_long, false).map(|(b, _)| b)
}

/// `grab_frame`, with the full size of the picture as mpv shows it (turned
/// upright by its rotation tag). For the viewer (`viewer`), the decoder
/// uses every core; thumbnails, made many at a time, use one each.
pub fn grab(path: &std::path::Path, start: &str, max_long: u32, viewer: bool) -> Result<(Bgra, (u32, u32))> {
    // HEIC is HEVC, which GPUs decode several times faster than software
    // (4K: 0.13 s against 0.66 s). AV1 stills (AVIF) were slower on the GPU.
    let heif = path
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case("heic") || e.eq_ignore_ascii_case("heif"));
    let p = Player::new(&[
        ("pause", "yes"),
        ("audio", "no"),
        ("hwdec", if heif { HWDEC_COPY } else { "no" }),
        ("hr-seek", "no"),
        ("vd-lavc-threads", if viewer { "0" } else { "1" }),
        // Without it mpv holds the first frame of a paused file for 200 ms
        // before handing it over: every still and thumbnail paid that.
        ("video-latency-hacks", "yes"),
        // zimg splits the scaling of one frame over every core, which for a
        // single still cost more than it saved: a 12 MP HEIC to 1920 took
        // 0.37 s, on one thread 0.14 s (same scaler, same picture).
        ("zimg-threads", "1"),
        ("start", start),
    ])?;
    p.command(&["loadfile", &path.to_string_lossy()])?;
    let deadline = Instant::now() + Duration::from_secs(15);
    // Wait until the paused player has sought to `start`: a frame ready
    // before that is from the beginning of the file.
    loop {
        match p.wait_event(Duration::from_millis(200)) {
            Event::Restarted => break,
            Event::Ended | Event::Failed | Event::Shutdown => bail!("mpv could not open the file"),
            _ if Instant::now() > deadline => bail!("timed out opening the file"),
            _ => {}
        }
    }
    let (vw, vh) = p.video_size().ok_or_else(|| anyhow::anyhow!("no video track"))?;
    let (w, h) = crate::pixels::fit_size(vw, vh, max_long);
    while Instant::now() < deadline {
        if p.frame_ready() {
            return Ok((p.render(w, h)?, (vw, vh)));
        }
        p.wait_event(Duration::from_millis(5));
    }
    bail!("timed out waiting for a frame")
}

/// The length of the video at `path` in seconds, read without decoding.
pub fn probe_duration(path: &std::path::Path) -> Result<f64> {
    let p =
        Player::new(&[("pause", "yes"), ("audio", "no"), ("sid", "no"), ("hwdec", "no"), ("vd-lavc-threads", "1")])?;
    p.command(&["loadfile", &path.to_string_lossy()])?;
    let deadline = Instant::now() + Duration::from_secs(10);
    while Instant::now() < deadline {
        if let Some(d) = p.get_f64("duration").filter(|d| *d > 0.0) {
            return Ok(d);
        }
        if matches!(p.wait_event(Duration::from_millis(50)), Event::Ended | Event::Failed | Event::Shutdown) {
            bail!("mpv could not open the file");
        }
    }
    bail!("timed out reading the duration")
}

/// Keeps one silent mpv instance alive for the whole process.
///
/// libmpv routes FFmpeg's log output through the first mpv instance. Once
/// that instance is destroyed while others still run (as happens when many
/// thumbnail players come and go), FFmpeg's debug lines leak to stderr. A
/// long-lived instance with all messages off keeps them quiet.
fn quiet_logging(api: &'static Api) {
    use std::sync::OnceLock;
    struct Keep(#[allow(dead_code)] *mut MpvHandle);
    unsafe impl Send for Keep {}
    unsafe impl Sync for Keep {}
    static KEEP: OnceLock<Keep> = OnceLock::new();
    KEEP.get_or_init(|| unsafe {
        let h = (api.create)();
        if !h.is_null() {
            for (k, v) in [("config", "no"), ("terminal", "no"), ("msg-level", "all=no")] {
                let (k, v) = (cstr(k), cstr(v));
                (api.set_option_string)(h, k.as_ptr(), v.as_ptr());
            }
            (api.initialize)(h);
        }
        Keep(h)
    });
}

/// Whether libmpv can be loaded here.
pub fn can_load() -> bool {
    api().is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    pub fn clip() -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/clip.webm")
    }

    #[test]
    fn hdr_video_is_tone_mapped_to_sdr() {
        if !can_load() {
            eprintln!("libmpv not found: skipped");
            return;
        }
        // A PQ ramp from black to 10000 nits: without tone mapping everything
        // above 100 nits (half of it) is white; with it, only the very top.
        let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hdr_ramp.mkv");
        let (video, rx) = crate::video::Video::start(&clip, true, true, 0.0, 1.0, 0.0).unwrap();
        video.set_target(256, 16);
        // The filter goes in once mpv has read the transfer, a few frames
        // in; the fewest white pixels any frame had is what counts.
        let mut fewest = (usize::MAX, Vec::new());
        let deadline = Instant::now() + Duration::from_secs(5);
        while Instant::now() < deadline {
            if let Ok(crate::video::Msg::Frame(b, _)) = rx.recv_blocking() {
                let row: Vec<u8> = (0..b.width).map(|x| b.pixels[(8 * b.width + x) as usize * 4 + 1]).collect();
                let white = row.iter().filter(|&&v| v >= 250).count();
                if white < fewest.0 {
                    fewest = (white, row);
                }
            }
        }
        drop(video);
        let (white, row) = fewest;
        assert!(white * 100 < row.len() * 35, "{white} of {} white: {row:?}", row.len());
    }

    #[test]
    fn opaque_sets_only_alpha() {
        let mut px = vec![1, 2, 3, 0, 4, 5, 6, 7];
        opaque(&mut px);
        assert_eq!(px, vec![1, 2, 3, 255, 4, 5, 6, 255]);
        // Unaligned: the byte path does the same.
        let mut buf = [0u8; 9];
        opaque(&mut buf[1..]);
        assert_eq!(&buf[1..], &[0, 0, 0, 255, 0, 0, 0, 255]);
    }

    #[test]
    fn grabs_a_scaled_frame() {
        if !can_load() {
            eprintln!("libmpv not found: skipped");
            return;
        }
        let b = grab_frame(&clip(), "10%", 48).unwrap();
        assert_eq!((b.width, b.height), (48, 32));
        assert_eq!(b.pixels.len(), 48 * 32 * 4);
        assert!(grab_frame(std::path::Path::new("/no/such/clip.mp4"), "0", 48).is_err());
    }

    #[test]
    fn subtitle_files_beside_a_video_are_tracks() {
        if !can_load() {
            eprintln!("libmpv not found: skipped");
            return;
        }
        let dir = std::env::temp_dir().join(format!("rosier-subs-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let video = dir.join("film.webm");
        std::fs::copy(clip(), &video).unwrap();
        std::fs::write(dir.join("film.srt"), "1\n00:00:00,000 --> 00:00:01,000\nhi\n").unwrap();
        let p = Player::new(&[("pause", "yes"), ("audio", "no")]).unwrap();
        p.command(&["loadfile", &video.to_string_lossy()]).unwrap();
        let deadline = Instant::now() + Duration::from_secs(10);
        let mut subs = 0;
        while Instant::now() < deadline && subs == 0 {
            p.wait_event(Duration::from_millis(50));
            subs = p.tracks().iter().filter(|t| t.kind == TrackKind::Sub).count();
        }
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(subs, 1);
    }

    #[test]
    fn probes_the_duration() {
        if !can_load() {
            eprintln!("libmpv not found: skipped");
            return;
        }
        let d = probe_duration(&clip()).unwrap();
        assert!((d - 1.0).abs() < 0.1, "{d}");
        assert!(probe_duration(std::path::Path::new("/no/such/clip.mp4")).is_err());
    }
}