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;
const END_FILE_REASON_ERROR: c_int = 4;
#[repr(C)]
struct MpvEventEndFile {
reason: c_int,
_error: c_int,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Event {
Other,
Shutdown,
Ended,
Failed,
Restarted,
}
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),
}
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)));
}
}
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() {
let lib = match unsafe { libloading::Library::new(&path) } {
Ok(lib) => lib,
Err(e) => {
last = e.to_string();
continue;
}
};
macro_rules! sym {
($name:literal) => {
*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() {
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()
}
pub struct Player {
api: &'static Api,
h: *mut MpvHandle,
rctx: *mut MpvRenderContext,
}
unsafe impl Send for Player {}
unsafe impl Sync for Player {}
impl Player {
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));
}
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)
}
pub fn wait_event(&self, timeout: Duration) -> Event {
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,
}
}
}
pub fn frame_ready(&self) -> bool {
unsafe { (self.api.render_context_update)(self.rctx) & UPDATE_FRAME != 0 }
}
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))
}
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));
}
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);
}
}
}
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))
}
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);
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")
}
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)
}
});
}
#[cfg(test)]
pub fn available() -> bool {
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());
}
}