//! Video playback: one long-lived libmpv instance whose output is composed //! beneath the (transparent) web view, so the interface draws its controls //! directly over the video. How the video reaches the screen is platform //! specific; see `platform::VideoSurface`. use std::sync::Arc; use std::time::{Duration, Instant}; use parking_lot::Mutex; use serde::Deserialize; use serde_json::{json, Value}; use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow}; use crate::mpv::{self, Event, Mpv}; use crate::platform::VideoSurface; /// Both locks are taken by commands on background threads, and some window /// calls made while holding them (Tauri's getters, such as `hwnd()`) wait for /// the UI thread to answer. So the UI thread must never wait on these locks: /// window events hand their work to a background thread (lib.rs). #[derive(Default)] pub struct PlayerState { mpv: Mutex>>, surface: Mutex>, } /// Properties streamed to the interface as they change. const OBSERVED: &[&str] = &[ "time-pos", "duration", "pause", "paused-for-cache", "cache-buffering-state", "demuxer-cache-time", "eof-reached", "idle-active", "track-list", "volume", "mute", "speed", "sub-delay", "audio-delay", "video-params", "hwdec-current", "chapter-list", "seeking", ]; #[derive(Deserialize, Default)] #[serde(rename_all = "camelCase")] pub struct InitOptions { #[serde(default)] pub hwdec: Option, #[serde(default)] pub hdr: Option, #[serde(default)] pub extra: Vec<(String, String)>, } fn emit(app: &AppHandle, payload: Value) { let _ = app.emit("mpv", payload); } fn create_player(app: &AppHandle, window: &WebviewWindow, opts: &InitOptions) -> Result, String> { let resource_dir = app.path().resource_dir().ok(); let mpv = Mpv::load(&mpv::library_candidates(resource_dir))?; // libmpv's runtime may install its own crash filter as it loads; ours goes back on top. crate::platform::install_crash_handler(); let surface = VideoSurface::create(window)?; let render_options = surface.mpv_options(); *app.state::().surface.lock() = Some(surface); let set = |k: &str, v: &str| mpv.set_option(k, v); for (k, v) in &render_options { set(k, v)?; } set("hwdec", opts.hwdec.as_deref().unwrap_or("auto-safe"))?; set("keep-open", "yes")?; set("idle", "yes")?; if !render_options.iter().any(|(k, _)| *k == "force-window") { set("force-window", "yes")?; } set("osc", "no")?; set("osd-level", "0")?; set("input-default-bindings", "no")?; set("input-vo-keyboard", "no")?; set("input-cursor", "no")?; set("cursor-autohide", "no")?; set("terminal", "no")?; set("ytdl", "no")?; set("sub-auto", "no")?; set("audio-client-name", "Kaleido")?; set("title", "Kaleido")?; set("cache", "yes")?; set("demuxer-max-bytes", "300MiB")?; set("demuxer-max-back-bytes", "100MiB")?; set("demuxer-readahead-secs", "30")?; set("network-timeout", "30")?; set("hr-seek", "yes")?; set("background-color", "#000000")?; set("user-agent", "Kaleido")?; // Keep compiled shaders between runs: translating the larger upscaling // shaders for Direct3D can take seconds, and should only happen once. if let Ok(dir) = app.path().app_cache_dir() { let dir = dir.join("shader-cache"); if std::fs::create_dir_all(&dir).is_ok() { let _ = set("gpu-shader-cache-dir", &dir.to_string_lossy()); } } if opts.hdr.unwrap_or(true) { let _ = set("target-colorspace-hint", "yes"); } for (k, v) in &opts.extra { let _ = set(k, v); } mpv.request_log_messages("warn"); mpv.initialize()?; if let Some(surface) = app.state::().surface.lock().as_mut() { surface.start(&mpv)?; } for (i, name) in OBSERVED.iter().chain(crate::platform::SURFACE_PROPERTIES).enumerate() { mpv.observe(i as u64 + 1, name); } let events = mpv.clone(); let app = app.clone(); std::thread::Builder::new() .name("mpv-events".into()) .spawn(move || event_loop(app, events)) .map_err(|e| e.to_string())?; Ok(mpv) } fn event_loop(app: AppHandle, mpv: Arc) { let mut last_time = Instant::now() - Duration::from_secs(1); let mut last_pos = -1.0f64; loop { let Some(event) = mpv.wait_event(1.0) else { continue }; match event { Event::Shutdown => break, Event::StartFile => emit(&app, json!({"type": "start-file"})), Event::FileLoaded => emit(&app, json!({"type": "file-loaded"})), Event::PlaybackRestart => emit(&app, json!({"type": "playback-restart"})), Event::Seek => emit(&app, json!({"type": "seek"})), Event::EndFile { reason, error } => emit(&app, json!({"type": "end-file", "reason": reason, "error": error})), Event::Property { name, value } => { if crate::platform::SURFACE_PROPERTIES.contains(&name.as_str()) { let state = app.state::(); let mut surface = state.surface.lock(); if let Some(surface) = surface.as_mut() { surface.on_property(&name, &value); } continue; } if name == "time-pos" { // Positions change every frame; a few updates a second suffice. let pos = value.as_f64().unwrap_or(-1.0); let now = Instant::now(); if now.duration_since(last_time) < Duration::from_millis(200) && (pos - last_pos).abs() < 1.5 { continue; } last_time = now; last_pos = pos; } emit(&app, json!({"type": "property", "name": name, "value": value})); } Event::Log { level, prefix, text } => { eprintln!("[mpv {level}] {prefix}: {text}"); emit(&app, json!({"type": "log", "level": level, "prefix": prefix, "text": text})); } Event::Other => {} } } } fn player(app: &AppHandle) -> Result, String> { app.state::().mpv.lock().clone().ok_or_else(|| "The player has not started.".to_string()) } #[tauri::command] pub async fn player_init(app: AppHandle, window: WebviewWindow, options: Option) -> Result<(), String> { let state = app.state::(); { let mut guard = state.mpv.lock(); if guard.is_none() { *guard = Some(create_player(&app, &window, &options.unwrap_or_default())?); } } // Outside the lock: creating a window waits on the UI thread. crate::mini::prepare(&app); Ok(()) } /// Moves the video into another window (the miniplayer's, mini.rs) or back to /// the main one. Off the UI thread only (it takes the player's locks). pub fn set_video_host(app: &AppHandle, host: Option) -> Result<(), String> { let state = app.state::(); let mpv = state.mpv.lock().clone(); let mut surface = state.surface.lock(); match surface.as_mut() { Some(surface) => surface.set_host(host, mpv.as_deref()), None => Ok(()), } } #[tauri::command] pub async fn player_show(app: AppHandle, window: WebviewWindow, visible: bool) -> Result<(), String> { let state = app.state::(); let mpv = state.mpv.lock().clone(); let mut surface = state.surface.lock(); if let Some(surface) = surface.as_mut() { surface.fit(&window, mpv.as_deref()); surface.show(&window, visible); } Ok(()) } #[derive(Deserialize)] pub struct VideoRect { x: f64, y: f64, width: f64, height: f64, } /// Draws the video in a rectangle of the window (physical pixels), for the /// miniplayer; `None` fills the window again. #[tauri::command] pub async fn player_rect(app: AppHandle, window: WebviewWindow, rect: Option) -> Result<(), String> { let state = app.state::(); let mpv = state.mpv.lock().clone(); let mut surface = state.surface.lock(); if let Some(surface) = surface.as_mut() { let rect = rect.map(|r| (r.x.round() as i32, r.y.round() as i32, r.width.round() as i32, r.height.round() as i32)); surface.set_rect(&window, mpv.as_deref(), rect); } Ok(()) } #[tauri::command] pub async fn player_command(app: AppHandle, args: Vec) -> Result<(), String> { player(&app)?.command(&args) } #[tauri::command] pub async fn player_set(app: AppHandle, name: String, value: Value) -> Result<(), String> { player(&app)?.set_property(&name, &value) } #[tauri::command] pub async fn player_get(app: AppHandle, name: String) -> Result { player(&app)?.get_property(&name) } /// Shows or hides the native window buttons where the OS draws them (the /// macOS traffic lights fade with the player's controls). #[tauri::command] pub fn window_buttons(window: WebviewWindow, visible: bool) { crate::platform::set_window_buttons(&window, visible); } /// Keeps the video surface matched to the window's client area. pub fn on_resize(window: &WebviewWindow) { let app = window.app_handle(); let state = app.state::(); let mpv = state.mpv.lock().clone(); let mut surface = state.surface.lock(); if let Some(surface) = surface.as_mut() { surface.fit(window, mpv.as_deref()); } }