rosier 0.2.0

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
//! 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_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,
    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));
            }
        }
    }
    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"),
            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})"))
}

fn api() -> Result<&'static Api> {
    use std::sync::OnceLock;
    static API: OnceLock<Result<Api, String>> = OnceLock::new();
    API.get_or_init(load).as_ref().map_err(|e| anyhow::anyhow!("{e}"))
}

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()
}

/// 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(())
    }

    pub 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_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.
        for px in pixels.as_chunks_mut::<4>().0 {
            px[3] = 255;
        }
        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);
        }
    }
}

/// Fits (w, h) inside a `max_long` square, keeping the aspect ratio.
pub fn fit_size(w: u32, h: u32, max_long: u32) -> (u32, u32) {
    let long = w.max(h);
    if long <= max_long {
        return (w, h);
    }
    let s = max_long as f64 / long as f64;
    (((w as f64 * s).round() as u32).max(1), ((h as f64 * s).round() as u32).max(1))
}

/// Grabs one frame from `path` (at `start`, an mpv time spec such as "10%")
/// scaled so its longer side is at most `max_long`.
pub fn grab_frame(path: &std::path::Path, start: &str, max_long: u32) -> Result<Bgra> {
    let p = Player::new(&[
        ("pause", "yes"),
        ("audio", "no"),
        ("hwdec", "no"),
        ("hr-seek", "no"),
        ("vd-lavc-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 decoded the frame at `start`.
    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 video"),
            _ => {}
        }
    }
    let (vw, vh) = p.video_size().ok_or_else(|| anyhow::anyhow!("no video track"))?;
    let (w, h) = fit_size(vw, vh, max_long);
    while Instant::now() < deadline {
        if p.frame_ready() {
            return p.render(w, h);
        }
        p.wait_event(Duration::from_millis(5));
    }
    bail!("timed out waiting for a frame")
}

/// 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.
pub fn init_quiet_logging() {
    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(|| {
        let Ok(api) = api() else { return Keep(ptr::null_mut()) };
        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. Tests that play video skip without it.
#[cfg(test)]
pub fn available() -> bool {
    // As in main: one silent player first, so FFmpeg's log hook never
    // outlives the player it points to.
    init_quiet_logging();
    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 sizes_fit_within_the_long_side() {
        assert_eq!(fit_size(1920, 1080, 960), (960, 540));
        assert_eq!(fit_size(100, 50, 960), (100, 50));
        assert_eq!(fit_size(10_000, 1, 100), (100, 1));
    }

    #[test]
    fn grabs_a_scaled_frame() {
        if !available() {
            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());
    }
}