The triangle sat ~14 px right of the shape's centre. Online videos now list the heights yt-dlp found and switch quality in place, keeping the position. Co-Authored-By: Claude Opus 5.5 <[email protected]>
831 lines
31 KiB
Rust
831 lines
31 KiB
Rust
//! mpv: one libmpv handle, its OpenGL render context, and the properties the UI shows.
|
||
//!
|
||
//! The video is rendered into our own framebuffer texture (libmpv's render API) and drawn by egui like any image, so
|
||
//! every control can sit on top of it. Property changes arrive as events; `pump` drains them into `State` each frame.
|
||
|
||
use libmpv2::{Format, Mpv, events::Event, events::PropertyData};
|
||
use libmpv2_sys as sys;
|
||
use serde::Deserialize;
|
||
use std::ffi::{CStr, CString, c_char, c_void};
|
||
use std::sync::Arc;
|
||
|
||
pub type GetProc = Arc<dyn Fn(&CStr) -> *const c_void + Send + Sync>;
|
||
|
||
/// What mpv is starting with; most can change while it runs.
|
||
#[derive(Clone, Debug)]
|
||
pub struct Init {
|
||
pub use_mpv_conf: bool,
|
||
pub hwdec: bool,
|
||
pub resume: bool,
|
||
pub ytdl_format: String,
|
||
pub alang: String,
|
||
pub slang: String,
|
||
pub screenshot_dir: String,
|
||
pub volume: f64,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Deserialize)]
|
||
pub struct Track {
|
||
pub id: i64,
|
||
#[serde(rename = "type")]
|
||
pub kind: String,
|
||
#[serde(default)]
|
||
pub title: Option<String>,
|
||
#[serde(default)]
|
||
pub lang: Option<String>,
|
||
#[serde(default)]
|
||
pub codec: Option<String>,
|
||
#[serde(default)]
|
||
pub selected: bool,
|
||
#[serde(default)]
|
||
pub external: bool,
|
||
#[serde(default, rename = "default")]
|
||
pub is_default: bool,
|
||
#[serde(default, rename = "demux-channel-count")]
|
||
pub channels: Option<i64>,
|
||
#[serde(default, rename = "demux-w")]
|
||
pub w: Option<i64>,
|
||
#[serde(default, rename = "demux-h")]
|
||
pub h: Option<i64>,
|
||
#[serde(default, rename = "demux-fps")]
|
||
pub fps: Option<f64>,
|
||
#[serde(default, rename = "demux-samplerate")]
|
||
pub samplerate: Option<i64>,
|
||
}
|
||
|
||
impl Track {
|
||
/// "English · AAC 5.1" style name for menus.
|
||
pub fn label(&self) -> String {
|
||
let mut parts = vec![];
|
||
if let Some(t) = self.title.as_deref().filter(|t| !t.is_empty()) {
|
||
parts.push(t.to_string());
|
||
}
|
||
if let Some(l) = self.lang.as_deref() {
|
||
let name = lang_name(l);
|
||
if !parts.iter().any(|p| p.eq_ignore_ascii_case(&name)) {
|
||
parts.push(name);
|
||
}
|
||
}
|
||
if parts.is_empty() {
|
||
parts.push(format!("Track {}", self.id));
|
||
}
|
||
parts.join(" · ")
|
||
}
|
||
|
||
pub fn detail(&self) -> String {
|
||
let mut d = vec![];
|
||
if let Some(c) = &self.codec {
|
||
d.push(c.to_uppercase());
|
||
}
|
||
match self.kind.as_str() {
|
||
"video" => {
|
||
if let (Some(w), Some(h)) = (self.w, self.h) {
|
||
d.push(format!("{w}×{h}"));
|
||
}
|
||
if let Some(f) = self.fps {
|
||
d.push(format!("{} fps", trim_num(f, 3)));
|
||
}
|
||
}
|
||
"audio" => {
|
||
if let Some(c) = self.channels {
|
||
d.push(match c {
|
||
1 => "mono".into(),
|
||
2 => "stereo".into(),
|
||
6 => "5.1".into(),
|
||
8 => "7.1".into(),
|
||
n => format!("{n} ch"),
|
||
});
|
||
}
|
||
if let Some(s) = self.samplerate {
|
||
d.push(format!("{} kHz", trim_num(s as f64 / 1000.0, 1)));
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
if self.external {
|
||
d.push("external".into());
|
||
}
|
||
if self.is_default {
|
||
d.push("default".into());
|
||
}
|
||
d.join(" · ")
|
||
}
|
||
}
|
||
|
||
pub fn trim_num(v: f64, places: usize) -> String {
|
||
let s = format!("{v:.places$}");
|
||
if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s }
|
||
}
|
||
|
||
fn lang_name(code: &str) -> String {
|
||
let n = match code.to_ascii_lowercase().as_str() {
|
||
"en" | "eng" => "English",
|
||
"ja" | "jpn" => "Japanese",
|
||
"de" | "ger" | "deu" => "German",
|
||
"fr" | "fre" | "fra" => "French",
|
||
"es" | "spa" => "Spanish",
|
||
"it" | "ita" => "Italian",
|
||
"pt" | "por" => "Portuguese",
|
||
"ru" | "rus" => "Russian",
|
||
"zh" | "chi" | "zho" => "Chinese",
|
||
"ko" | "kor" => "Korean",
|
||
"nl" | "dut" | "nld" => "Dutch",
|
||
"sv" | "swe" => "Swedish",
|
||
"pl" | "pol" => "Polish",
|
||
"ar" | "ara" => "Arabic",
|
||
"hi" | "hin" => "Hindi",
|
||
"tr" | "tur" => "Turkish",
|
||
"und" => "Unknown language",
|
||
_ => return code.to_string(),
|
||
};
|
||
n.into()
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Deserialize)]
|
||
pub struct Chapter {
|
||
#[serde(default)]
|
||
pub title: Option<String>,
|
||
pub time: f64,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Deserialize)]
|
||
pub struct Entry {
|
||
pub filename: String,
|
||
#[serde(default)]
|
||
pub title: Option<String>,
|
||
#[serde(default)]
|
||
pub current: bool,
|
||
#[serde(default)]
|
||
pub id: i64,
|
||
}
|
||
|
||
impl Entry {
|
||
pub fn name(&self) -> String {
|
||
if let Some(t) = self.title.as_deref().filter(|t| !t.is_empty()) {
|
||
return t.to_string();
|
||
}
|
||
display_name(&self.filename)
|
||
}
|
||
}
|
||
|
||
/// The video heights in mpv's copy of yt-dlp's answer (`{"stdout": "<yt-dlp json>", ...}`), tallest first.
|
||
pub fn stream_heights(result: &str) -> Vec<u32> {
|
||
let Ok(outer) = serde_json::from_str::<serde_json::Value>(result) else { return vec![] };
|
||
let Some(Ok(info)) = outer["stdout"].as_str().map(serde_json::from_str::<serde_json::Value>) else { return vec![] };
|
||
let mut v: Vec<u32> = info["formats"]
|
||
.as_array()
|
||
.into_iter()
|
||
.flatten()
|
||
.filter(|f| f["vcodec"].as_str().is_some_and(|c| c != "none"))
|
||
.filter_map(|f| f["height"].as_u64())
|
||
.map(|h| h as u32)
|
||
.filter(|&h| h >= 144)
|
||
.collect();
|
||
v.sort_unstable_by(|a, b| b.cmp(a));
|
||
v.dedup();
|
||
v
|
||
}
|
||
|
||
/// The file name of a path or URL, without the folder.
|
||
pub fn display_name(path: &str) -> String {
|
||
if path.contains("://") {
|
||
let p = path.split(['?', '#']).next().unwrap_or(path);
|
||
let last = p.trim_end_matches('/').rsplit('/').next().unwrap_or(p);
|
||
let last = urlencoding::decode(last).map(|s| s.into_owned()).unwrap_or_else(|_| last.to_string());
|
||
return if last.is_empty() || last.contains(':') { path.to_string() } else { last };
|
||
}
|
||
std::path::Path::new(path).file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string())
|
||
}
|
||
|
||
/// What the UI shows, as mpv last said it.
|
||
#[derive(Clone, Debug, Default)]
|
||
pub struct State {
|
||
pub idle: bool,
|
||
pub pause: bool,
|
||
pub time: f64,
|
||
pub duration: f64,
|
||
pub volume: f64,
|
||
pub mute: bool,
|
||
pub speed: f64,
|
||
pub title: String,
|
||
pub path: String,
|
||
pub tracks: Vec<Track>,
|
||
pub chapters: Vec<Chapter>,
|
||
pub chapter: i64,
|
||
pub playlist: Vec<Entry>,
|
||
pub playlist_pos: i64,
|
||
pub cache_time: f64,
|
||
pub buffering: bool,
|
||
pub seeking: bool,
|
||
pub eof: bool,
|
||
pub loop_file: bool,
|
||
pub loop_playlist: bool,
|
||
pub ab_a: Option<f64>,
|
||
pub ab_b: Option<f64>,
|
||
pub sub_delay: f64,
|
||
pub audio_delay: f64,
|
||
pub sub_scale: f64,
|
||
pub sub_pos: f64,
|
||
pub sub_visible: bool,
|
||
pub sub_ass_override: String,
|
||
pub secondary_sid: String,
|
||
pub vid: String,
|
||
pub aid: String,
|
||
pub sid: String,
|
||
pub width: i64,
|
||
pub height: i64,
|
||
pub hwdec_current: String,
|
||
pub hwdec: String,
|
||
pub aspect_override: String,
|
||
pub rotate: i64,
|
||
pub zoom: f64,
|
||
pub brightness: f64,
|
||
pub contrast: f64,
|
||
pub saturation: f64,
|
||
pub gamma: f64,
|
||
pub hue: f64,
|
||
pub deinterlace: bool,
|
||
pub audio_pitch_correction: bool,
|
||
pub audio_device: String,
|
||
pub af: String,
|
||
pub vf: String,
|
||
pub shuffle: bool,
|
||
pub file_format: String,
|
||
pub video_codec: String,
|
||
pub audio_codec: String,
|
||
pub fps: f64,
|
||
pub panscan: f64,
|
||
pub devices: Vec<Device>,
|
||
pub audio_channels: String,
|
||
/// Picture heights an online video offers (from yt-dlp), tallest first; empty for local files.
|
||
pub stream_heights: Vec<u32>,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Deserialize)]
|
||
pub struct Device {
|
||
pub name: String,
|
||
#[serde(default)]
|
||
pub description: String,
|
||
}
|
||
|
||
impl State {
|
||
pub fn tracks_of(&self, kind: &str) -> impl Iterator<Item = &Track> {
|
||
self.tracks.iter().filter(move |t| t.kind == kind)
|
||
}
|
||
|
||
pub fn has_video(&self) -> bool {
|
||
self.width > 0 && self.height > 0
|
||
}
|
||
|
||
pub fn loaded(&self) -> bool {
|
||
!self.idle && !self.path.is_empty()
|
||
}
|
||
}
|
||
|
||
/// Things that happened, for the app to react to.
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub enum Happened {
|
||
FileLoaded,
|
||
StartFile,
|
||
EndFile,
|
||
/// A command or a file failed; the app knows which from what it was doing.
|
||
Error(String),
|
||
VideoReconfig,
|
||
PlaybackRestart,
|
||
Shutdown,
|
||
}
|
||
|
||
const PROPS: &[(&str, Format)] = &[
|
||
("idle-active", Format::Flag),
|
||
("pause", Format::Flag),
|
||
("time-pos", Format::Double),
|
||
("duration", Format::Double),
|
||
("volume", Format::Double),
|
||
("mute", Format::Flag),
|
||
("speed", Format::Double),
|
||
("media-title", Format::String),
|
||
("path", Format::String),
|
||
("track-list", Format::String),
|
||
("chapter-list", Format::String),
|
||
("chapter", Format::Int64),
|
||
("playlist", Format::String),
|
||
("playlist-pos", Format::Int64),
|
||
("demuxer-cache-time", Format::Double),
|
||
("paused-for-cache", Format::Flag),
|
||
("seeking", Format::Flag),
|
||
("eof-reached", Format::Flag),
|
||
("loop-file", Format::String),
|
||
("loop-playlist", Format::String),
|
||
("ab-loop-a", Format::String),
|
||
("ab-loop-b", Format::String),
|
||
("sub-delay", Format::Double),
|
||
("audio-delay", Format::Double),
|
||
("sub-scale", Format::Double),
|
||
("sub-pos", Format::Double),
|
||
("sub-visibility", Format::Flag),
|
||
("sub-ass-override", Format::String),
|
||
("secondary-sid", Format::String),
|
||
("vid", Format::String),
|
||
("aid", Format::String),
|
||
("sid", Format::String),
|
||
("dwidth", Format::Int64),
|
||
("dheight", Format::Int64),
|
||
("hwdec-current", Format::String),
|
||
("hwdec", Format::String),
|
||
("video-aspect-override", Format::String),
|
||
("video-rotate", Format::Int64),
|
||
("video-zoom", Format::Double),
|
||
("brightness", Format::Double),
|
||
("contrast", Format::Double),
|
||
("saturation", Format::Double),
|
||
("gamma", Format::Double),
|
||
("hue", Format::Double),
|
||
("deinterlace", Format::Flag),
|
||
("audio-pitch-correction", Format::Flag),
|
||
("audio-device", Format::String),
|
||
("af", Format::String),
|
||
("vf", Format::String),
|
||
("shuffle", Format::Flag),
|
||
("file-format", Format::String),
|
||
("video-codec", Format::String),
|
||
("audio-codec-name", Format::String),
|
||
("container-fps", Format::Double),
|
||
("panscan", Format::Double),
|
||
("audio-device-list", Format::String),
|
||
("audio-channels", Format::String),
|
||
];
|
||
|
||
fn json<T: for<'de> Deserialize<'de> + Default>(s: &str) -> T {
|
||
serde_json::from_str(s).unwrap_or_default()
|
||
}
|
||
|
||
fn opt_time(s: &str) -> Option<f64> {
|
||
s.parse::<f64>().ok()
|
||
}
|
||
|
||
pub struct Player {
|
||
pub mpv: Mpv,
|
||
pub state: State,
|
||
render: *mut sys::mpv_render_context,
|
||
_get_proc: Box<GetProc>,
|
||
fbo: Option<Target>,
|
||
dirty: bool,
|
||
}
|
||
|
||
struct Target {
|
||
fbo: glow::Framebuffer,
|
||
tex: glow::Texture,
|
||
w: i32,
|
||
h: i32,
|
||
id: Option<eframe::egui::TextureId>,
|
||
}
|
||
|
||
unsafe extern "C" fn get_proc_cb(ctx: *mut c_void, name: *const c_char) -> *mut c_void {
|
||
let f = unsafe { &*(ctx as *const GetProc) };
|
||
f(unsafe { CStr::from_ptr(name) }) as *mut c_void
|
||
}
|
||
|
||
fn ctx_free(_id: eframe::egui::TextureId) {
|
||
// native textures are only a name for our GL texture; deleting the texture below is enough
|
||
}
|
||
|
||
unsafe extern "C" fn on_update(ctx: *mut c_void) {
|
||
let wake = unsafe { &*(ctx as *const Waker) };
|
||
wake.wake();
|
||
}
|
||
|
||
/// mpv calls back from its own threads, sometimes while holding its core lock. Asking egui for a repaint there
|
||
/// could wait on egui's lock while the UI thread, inside egui, waits on mpv. So callbacks only post a note and
|
||
/// a small thread of ours does the asking.
|
||
#[derive(Clone)]
|
||
struct Waker(std::sync::mpsc::SyncSender<()>);
|
||
|
||
impl Waker {
|
||
fn new(egui: eframe::egui::Context) -> Waker {
|
||
let (tx, rx) = std::sync::mpsc::sync_channel::<()>(1);
|
||
let _ = std::thread::Builder::new().name("mpv-wake".into()).spawn(move || {
|
||
while rx.recv().is_ok() {
|
||
egui.request_repaint();
|
||
}
|
||
});
|
||
Waker(tx)
|
||
}
|
||
|
||
fn wake(&self) {
|
||
let _ = self.0.try_send(());
|
||
}
|
||
}
|
||
|
||
/// Display pointers mpv needs for hardware decoding interop.
|
||
pub enum Display {
|
||
Wayland(*mut c_void),
|
||
X11(*mut c_void),
|
||
None,
|
||
}
|
||
|
||
impl Player {
|
||
pub fn new(init: &Init, get_proc_address: GetProc, display: Display, egui: eframe::egui::Context) -> Result<Player, String> {
|
||
let config_dir = dirs::config_dir().unwrap_or_default().join("mpv");
|
||
let watch_later = dirs::state_dir().unwrap_or_else(std::env::temp_dir).join("quince/watch_later");
|
||
let _ = std::fs::create_dir_all(&watch_later);
|
||
let log = dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join("quince/mpv.log");
|
||
let _ = std::fs::create_dir_all(log.parent().unwrap());
|
||
let init = init.clone();
|
||
let mut mpv = Mpv::with_initializer(move |i| {
|
||
i.set_property("vo", "libmpv")?;
|
||
i.set_property("config", if init.use_mpv_conf { "yes" } else { "no" })?;
|
||
i.set_property("config-dir", config_dir.to_string_lossy().as_ref())?;
|
||
i.set_property("input-default-bindings", "yes")?;
|
||
i.set_property("input-vo-keyboard", "no")?;
|
||
i.set_property("osc", "no")?;
|
||
i.set_property("osd-bar", "no")?;
|
||
i.set_property("idle", "yes")?;
|
||
i.set_property("keep-open", "yes")?;
|
||
i.set_property("force-window", "no")?;
|
||
i.set_property("terminal", "no")?;
|
||
i.set_property("log-file", log.to_string_lossy().as_ref())?;
|
||
i.set_property("msg-level", "all=info")?;
|
||
i.set_property("audio-client-name", "quince")?;
|
||
i.set_property("volume-max", "150")?;
|
||
i.set_property("volume", init.volume)?;
|
||
i.set_property("hwdec", if init.hwdec { "auto-safe" } else { "no" })?;
|
||
i.set_property("ytdl", "yes")?;
|
||
if !init.ytdl_format.is_empty() {
|
||
i.set_property("ytdl-format", init.ytdl_format.as_str())?;
|
||
}
|
||
i.set_property("sub-auto", "fuzzy")?;
|
||
if !init.alang.is_empty() {
|
||
i.set_property("alang", init.alang.as_str())?;
|
||
}
|
||
if !init.slang.is_empty() {
|
||
i.set_property("slang", init.slang.as_str())?;
|
||
}
|
||
i.set_property("save-position-on-quit", init.resume)?;
|
||
i.set_property("watch-later-directory", watch_later.to_string_lossy().as_ref())?;
|
||
i.set_property("screenshot-directory", init.screenshot_dir.as_str())?;
|
||
i.set_property("screenshot-template", "Quince %F %wH-%wM-%wS")?;
|
||
i.set_property("screenshot-format", "png")?;
|
||
i.set_property("cache", "auto")?;
|
||
Ok(())
|
||
})
|
||
.map_err(|e| format!("Couldn't start mpv: {e}"))?;
|
||
// mpv.conf may name another video output; ours must stay.
|
||
let _ = mpv.set_property("vo", "libmpv");
|
||
let _ = mpv.disable_deprecated_events();
|
||
for (n, (name, fmt)) in PROPS.iter().enumerate() {
|
||
let _ = mpv.observe_property(name, *fmt, n as u64);
|
||
}
|
||
let waker = Waker::new(egui);
|
||
let wake = waker.clone();
|
||
mpv.set_wakeup_callback(move || wake.wake());
|
||
|
||
let get_proc = Box::new(get_proc_address);
|
||
let mut init_params = sys::mpv_opengl_init_params {
|
||
get_proc_address: Some(get_proc_cb),
|
||
get_proc_address_ctx: &*get_proc as *const GetProc as *mut c_void,
|
||
};
|
||
let mut params = vec![
|
||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_API_TYPE, data: sys::MPV_RENDER_API_TYPE_OPENGL.as_ptr() as *mut c_void },
|
||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, data: &mut init_params as *mut _ as *mut c_void },
|
||
];
|
||
match display {
|
||
Display::Wayland(p) => params.push(sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_WL_DISPLAY, data: p }),
|
||
Display::X11(p) => params.push(sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_X11_DISPLAY, data: p }),
|
||
Display::None => {}
|
||
}
|
||
params.push(sys::mpv_render_param { type_: 0, data: std::ptr::null_mut() });
|
||
let mut render: *mut sys::mpv_render_context = std::ptr::null_mut();
|
||
let err = unsafe { sys::mpv_render_context_create(&mut render, mpv.ctx.as_ptr(), params.as_mut_ptr()) };
|
||
if err < 0 {
|
||
return Err(format!("Couldn't set up video output: {}", sys::mpv_error_str(err)));
|
||
}
|
||
// The waker lives as long as the app (we leak one clone of it on purpose).
|
||
let ctx_ptr = Box::into_raw(Box::new(waker)) as *mut c_void;
|
||
unsafe { sys::mpv_render_context_set_update_callback(render, Some(on_update), ctx_ptr) };
|
||
Ok(Player { mpv, state: State { idle: true, speed: 1.0, volume: 100.0, sub_visible: true, sub_scale: 1.0, sub_pos: 100.0, zoom: 0.0, ..State::default() }, render, _get_proc: get_proc, fbo: None, dirty: true })
|
||
}
|
||
|
||
/// Runs a command without waiting for it.
|
||
pub fn cmd(&self, args: &[&str]) {
|
||
let owned: Vec<CString> = args.iter().map(|a| CString::new(*a).unwrap_or_default()).collect();
|
||
let mut ptrs: Vec<*const c_char> = owned.iter().map(|c| c.as_ptr()).collect();
|
||
ptrs.push(std::ptr::null());
|
||
unsafe { sys::mpv_command_async(self.mpv.ctx.as_ptr(), 0, ptrs.as_mut_ptr()) };
|
||
}
|
||
|
||
pub fn set<T: libmpv2::SetData>(&self, name: &str, v: T) {
|
||
let _ = self.mpv.set_property(name, v);
|
||
}
|
||
|
||
pub fn get_str(&self, name: &str) -> Option<String> {
|
||
self.mpv.get_property::<String>(name).ok()
|
||
}
|
||
|
||
pub fn get_f64(&self, name: &str) -> Option<f64> {
|
||
self.mpv.get_property::<f64>(name).ok()
|
||
}
|
||
|
||
/// Drains mpv's events into `state` and returns what happened.
|
||
pub fn pump(&mut self) -> Vec<Happened> {
|
||
let mut out = vec![];
|
||
while let Some(ev) = self.mpv.wait_event(0.0) {
|
||
match ev {
|
||
Ok(Event::PropertyChange { name, change, .. }) => apply(&mut self.state, name, change),
|
||
Ok(Event::FileLoaded) => {
|
||
self.state.stream_heights = if self.state.path.contains("://") {
|
||
self.get_str("user-data/mpv/ytdl/json-subprocess-result").map(|j| stream_heights(&j)).unwrap_or_default()
|
||
} else {
|
||
vec![]
|
||
};
|
||
out.push(Happened::FileLoaded)
|
||
}
|
||
Ok(Event::StartFile) => out.push(Happened::StartFile),
|
||
Ok(Event::EndFile(_)) => out.push(Happened::EndFile),
|
||
Err(e) => out.push(Happened::Error(err_words(&e))),
|
||
Ok(Event::VideoReconfig) => out.push(Happened::VideoReconfig),
|
||
Ok(Event::PlaybackRestart) => out.push(Happened::PlaybackRestart),
|
||
Ok(Event::Shutdown) => out.push(Happened::Shutdown),
|
||
Ok(_) => {}
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
/// Renders the newest video frame into our texture, `w`×`h` physical pixels, if mpv has one or the size changed.
|
||
/// Returns the texture to draw.
|
||
pub fn render(&mut self, gl: &glow::Context, frame: &mut eframe::Frame, w: i32, h: i32) -> Option<eframe::egui::TextureId> {
|
||
use glow::HasContext;
|
||
let (w, h) = (w.max(1), h.max(1));
|
||
if self.render.is_null() {
|
||
return None;
|
||
}
|
||
let flags = unsafe { sys::mpv_render_context_update(self.render) };
|
||
if flags & sys::mpv_render_update_flag_MPV_RENDER_UPDATE_FRAME as u64 != 0 {
|
||
self.dirty = true;
|
||
}
|
||
let resized = self.fbo.as_ref().is_none_or(|t| t.w != w || t.h != h);
|
||
unsafe {
|
||
if resized {
|
||
if let Some(old) = self.fbo.take() {
|
||
if let Some(id) = old.id {
|
||
let _ = frame;
|
||
ctx_free(id);
|
||
}
|
||
gl.delete_framebuffer(old.fbo);
|
||
gl.delete_texture(old.tex);
|
||
}
|
||
let tex = gl.create_texture().ok()?;
|
||
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
|
||
gl.tex_image_2d(glow::TEXTURE_2D, 0, glow::RGBA8 as i32, w, h, 0, glow::RGBA, glow::UNSIGNED_BYTE, glow::PixelUnpackData::Slice(None));
|
||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR as i32);
|
||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32);
|
||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
|
||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
|
||
gl.bind_texture(glow::TEXTURE_2D, None);
|
||
let fbo = gl.create_framebuffer().ok()?;
|
||
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo));
|
||
gl.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(tex), 0);
|
||
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
|
||
let id = frame.register_native_glow_texture(tex);
|
||
self.fbo = Some(Target { fbo, tex, w, h, id: Some(id) });
|
||
self.dirty = true;
|
||
}
|
||
let t = self.fbo.as_ref()?;
|
||
if self.dirty {
|
||
self.dirty = false;
|
||
let mut fbo = sys::mpv_opengl_fbo { fbo: t.fbo.0.get() as i32, w, h, internal_format: 0 };
|
||
let mut flip: i32 = 0;
|
||
let mut block: i32 = 0;
|
||
let mut params = [
|
||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_OPENGL_FBO, data: &mut fbo as *mut _ as *mut c_void },
|
||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_FLIP_Y, data: &mut flip as *mut _ as *mut c_void },
|
||
sys::mpv_render_param { type_: sys::mpv_render_param_type_MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME, data: &mut block as *mut _ as *mut c_void },
|
||
sys::mpv_render_param { type_: 0, data: std::ptr::null_mut() },
|
||
];
|
||
sys::mpv_render_context_render(self.render, params.as_mut_ptr());
|
||
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
|
||
gl.bind_texture(glow::TEXTURE_2D, None);
|
||
gl.use_program(None);
|
||
sys::mpv_render_context_report_swap(self.render);
|
||
}
|
||
t.id
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
impl Player {
|
||
/// Frees the render context and our GL objects; must run while the GL context is current.
|
||
pub fn shutdown(&mut self, gl: Option<&glow::Context>) {
|
||
use glow::HasContext;
|
||
if !self.render.is_null() {
|
||
unsafe { sys::mpv_render_context_free(self.render) };
|
||
self.render = std::ptr::null_mut();
|
||
}
|
||
if let (Some(gl), Some(t)) = (gl, self.fbo.take()) {
|
||
unsafe {
|
||
gl.delete_framebuffer(t.fbo);
|
||
gl.delete_texture(t.tex);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
impl Drop for Player {
|
||
fn drop(&mut self) {
|
||
// libmpv2 frees our wakeup closure before destroying mpv, which may still call it in between.
|
||
// Unsetting it here waits for a call in flight (mpv holds the same lock) and stops later ones.
|
||
unsafe { sys::mpv_set_wakeup_callback(self.mpv.ctx.as_ptr(), None, std::ptr::null_mut()) };
|
||
if !self.render.is_null() {
|
||
unsafe { sys::mpv_render_context_free(self.render) };
|
||
}
|
||
}
|
||
}
|
||
|
||
/// mpv's error, in words a person can use.
|
||
fn err_words(e: &libmpv2::Error) -> String {
|
||
let raw = match e {
|
||
libmpv2::Error::Raw(code) => sys::mpv_error_str(*code).to_string(),
|
||
other => format!("{other}"),
|
||
};
|
||
match raw.as_str() {
|
||
"loading failed" => "the file couldn't be read".into(),
|
||
"unrecognized file format" => "it isn't a format mpv can play".into(),
|
||
"no audio or video data played" => "it has no sound or picture mpv can play".into(),
|
||
"error running command" => "mpv couldn't do that".into(),
|
||
"property unavailable" => "that isn't available for this file".into(),
|
||
r => r.to_string(),
|
||
}
|
||
}
|
||
|
||
fn apply(s: &mut State, name: &str, v: PropertyData) {
|
||
let f = |v: &PropertyData| match v {
|
||
PropertyData::Double(d) => *d,
|
||
PropertyData::Int64(i) => *i as f64,
|
||
_ => 0.0,
|
||
};
|
||
let b = |v: &PropertyData| matches!(v, PropertyData::Flag(true));
|
||
let st = |v: &PropertyData| match v {
|
||
PropertyData::Str(s) | PropertyData::OsdStr(s) => s.to_string(),
|
||
_ => String::new(),
|
||
};
|
||
let i = |v: &PropertyData| match v {
|
||
PropertyData::Int64(i) => *i,
|
||
PropertyData::Double(d) => *d as i64,
|
||
_ => 0,
|
||
};
|
||
match name {
|
||
"idle-active" => s.idle = b(&v),
|
||
"pause" => s.pause = b(&v),
|
||
"time-pos" => s.time = f(&v),
|
||
"duration" => s.duration = f(&v),
|
||
"volume" => s.volume = f(&v),
|
||
"mute" => s.mute = b(&v),
|
||
"speed" => s.speed = f(&v),
|
||
"media-title" => s.title = st(&v),
|
||
"path" => s.path = st(&v),
|
||
"track-list" => s.tracks = json(&st(&v)),
|
||
"chapter-list" => s.chapters = json(&st(&v)),
|
||
"chapter" => s.chapter = i(&v),
|
||
"playlist" => s.playlist = json(&st(&v)),
|
||
"playlist-pos" => s.playlist_pos = i(&v),
|
||
"demuxer-cache-time" => s.cache_time = f(&v),
|
||
"paused-for-cache" => s.buffering = b(&v),
|
||
"seeking" => s.seeking = b(&v),
|
||
"eof-reached" => s.eof = b(&v),
|
||
"loop-file" => s.loop_file = st(&v) != "no",
|
||
"loop-playlist" => s.loop_playlist = st(&v) != "no",
|
||
"ab-loop-a" => s.ab_a = opt_time(&st(&v)),
|
||
"ab-loop-b" => s.ab_b = opt_time(&st(&v)),
|
||
"sub-delay" => s.sub_delay = f(&v),
|
||
"audio-delay" => s.audio_delay = f(&v),
|
||
"sub-scale" => s.sub_scale = f(&v),
|
||
"sub-pos" => s.sub_pos = f(&v),
|
||
"sub-visibility" => s.sub_visible = b(&v),
|
||
"sub-ass-override" => s.sub_ass_override = st(&v),
|
||
"secondary-sid" => s.secondary_sid = st(&v),
|
||
"vid" => s.vid = st(&v),
|
||
"aid" => s.aid = st(&v),
|
||
"sid" => s.sid = st(&v),
|
||
"dwidth" => s.width = i(&v),
|
||
"dheight" => s.height = i(&v),
|
||
"hwdec-current" => s.hwdec_current = st(&v),
|
||
"hwdec" => s.hwdec = st(&v),
|
||
"video-aspect-override" => {
|
||
let a = st(&v);
|
||
s.aspect_override = if a.parse::<f64>().is_ok_and(|x| x <= 0.0) || a == "no" { "-1".into() } else { a };
|
||
}
|
||
"video-rotate" => s.rotate = i(&v),
|
||
"video-zoom" => s.zoom = f(&v),
|
||
"brightness" => s.brightness = f(&v),
|
||
"contrast" => s.contrast = f(&v),
|
||
"saturation" => s.saturation = f(&v),
|
||
"gamma" => s.gamma = f(&v),
|
||
"hue" => s.hue = f(&v),
|
||
"deinterlace" => s.deinterlace = b(&v),
|
||
"audio-pitch-correction" => s.audio_pitch_correction = b(&v),
|
||
"audio-device" => s.audio_device = st(&v),
|
||
"af" => s.af = st(&v),
|
||
"vf" => s.vf = st(&v),
|
||
"shuffle" => s.shuffle = b(&v),
|
||
"file-format" => s.file_format = st(&v),
|
||
"video-codec" => s.video_codec = st(&v),
|
||
"audio-codec-name" => s.audio_codec = st(&v),
|
||
"container-fps" => s.fps = f(&v),
|
||
"panscan" => s.panscan = f(&v),
|
||
"audio-device-list" => s.devices = json(&st(&v)),
|
||
"audio-channels" => s.audio_channels = st(&v),
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
/// mpv's name for an egui key, for passing keys the app doesn't use on to mpv (input.conf, scripts, the console).
|
||
pub fn key_name(key: eframe::egui::Key, m: eframe::egui::Modifiers) -> Option<String> {
|
||
use eframe::egui::Key as K;
|
||
let base = match key {
|
||
K::ArrowDown => "DOWN".into(),
|
||
K::ArrowLeft => "LEFT".into(),
|
||
K::ArrowRight => "RIGHT".into(),
|
||
K::ArrowUp => "UP".into(),
|
||
K::Escape => "ESC".into(),
|
||
K::Tab => "TAB".into(),
|
||
K::Backspace => "BS".into(),
|
||
K::Enter => "ENTER".into(),
|
||
K::Space => "SPACE".into(),
|
||
K::Insert => "INS".into(),
|
||
K::Delete => "DEL".into(),
|
||
K::Home => "HOME".into(),
|
||
K::End => "END".into(),
|
||
K::PageUp => "PGUP".into(),
|
||
K::PageDown => "PGDWN".into(),
|
||
K::F1 => "F1".into(),
|
||
K::F2 => "F2".into(),
|
||
K::F3 => "F3".into(),
|
||
K::F4 => "F4".into(),
|
||
K::F5 => "F5".into(),
|
||
K::F6 => "F6".into(),
|
||
K::F7 => "F7".into(),
|
||
K::F8 => "F8".into(),
|
||
K::F9 => "F9".into(),
|
||
K::F10 => "F10".into(),
|
||
K::F11 => "F11".into(),
|
||
K::F12 => "F12".into(),
|
||
_ => {
|
||
let s = key.symbol_or_name();
|
||
if s.chars().count() != 1 {
|
||
return None;
|
||
}
|
||
let c = s.chars().next()?;
|
||
if c.is_ascii_alphabetic() {
|
||
// mpv tells letters apart by case, not by Shift.
|
||
let c = if m.shift { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() };
|
||
let mut out = String::new();
|
||
if m.ctrl {
|
||
out.push_str("Ctrl+");
|
||
}
|
||
if m.alt {
|
||
out.push_str("Alt+");
|
||
}
|
||
out.push(c);
|
||
return Some(out);
|
||
}
|
||
s.to_string()
|
||
}
|
||
};
|
||
let mut out = String::new();
|
||
if m.ctrl {
|
||
out.push_str("Ctrl+");
|
||
}
|
||
if m.alt {
|
||
out.push_str("Alt+");
|
||
}
|
||
if m.shift {
|
||
out.push_str("Shift+");
|
||
}
|
||
out.push_str(&base);
|
||
Some(out)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn names_and_tracks_read_well() {
|
||
assert_eq!(display_name("/home/a/Films/The Film (2020).mkv"), "The Film (2020).mkv");
|
||
assert_eq!(display_name("https://example.com/v/My%20clip.mp4?x=1"), "My clip.mp4");
|
||
}
|
||
|
||
#[test]
|
||
fn heights_from_ytdl() {
|
||
let inner = r#"{"formats":[{"height":1080,"vcodec":"vp9"},{"height":720,"vcodec":"avc1"},{"height":1080,"vcodec":"av01"},{"vcodec":"none","acodec":"opus"},{"height":90,"vcodec":"none"},{"height":27,"vcodec":"images"}]}"#;
|
||
let outer = serde_json::json!({ "stdout": inner, "status": 0 }).to_string();
|
||
assert_eq!(stream_heights(&outer), vec![1080, 720]);
|
||
assert!(stream_heights("{}").is_empty());
|
||
assert_eq!(trim_num(23.976, 3), "23.976");
|
||
assert_eq!(trim_num(48.0, 1), "48");
|
||
let t: Vec<Track> = json(r#"[{"id":1,"type":"audio","lang":"jpn","codec":"aac","demux-channel-count":6,"demux-samplerate":48000,"selected":true}]"#);
|
||
assert_eq!(t[0].label(), "Japanese");
|
||
assert_eq!(t[0].detail(), "AAC · 5.1 · 48 kHz");
|
||
}
|
||
}
|