use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
use std::time::{Duration, Instant};
use anyhow::Result;
use crate::mpv::{Event, Player, Track, TrackKind};
use crate::turbo::Bgra;
pub enum Msg {
Frame(Bgra, Option<Bgra>),
Ended,
Failed,
}
pub struct Video {
player: Arc<Player>,
stop: Arc<AtomicBool>,
target: Arc<AtomicU64>,
glass: Arc<AtomicBool>,
}
impl Video {
pub fn start(
path: &Path,
muted: bool,
looping: bool,
volume: f64,
speed: f64,
start: f64,
) -> Result<(Self, async_channel::Receiver<Msg>)> {
let player = Arc::new(Player::new(&[
("hwdec", crate::mpv::HWDEC_COPY),
("mute", if muted { "yes" } else { "no" }),
("loop-file", if looping { "inf" } else { "no" }),
("keep-open", "no"),
("volume", &format!("{:.0}", volume)),
("speed", &format!("{speed}")),
("start", &format!("{start:.1}")),
("framedrop", "no"),
("video-latency-hacks", "yes"),
])?);
player.command(&["loadfile", &path.to_string_lossy()])?;
let stop = Arc::new(AtomicBool::new(false));
let target = Arc::new(AtomicU64::new((640u64 << 32) | 360));
let glass = Arc::new(AtomicBool::new(true));
let (tx, rx) = async_channel::bounded(2);
{
let (player, stop, target, glass) = (player.clone(), stop.clone(), target.clone(), glass.clone());
std::thread::Builder::new()
.name("rosier-video".into())
.spawn(move || run(&player, &stop, &target, &glass, &tx))?;
}
Ok((Video { player, stop, target, glass }, rx))
}
pub fn want_glass(&self, on: bool) {
self.glass.store(on, Relaxed);
}
pub fn set_target(&self, w: u32, h: u32) {
self.target.store(((w.max(1) as u64) << 32) | h.max(1) as u64, Relaxed);
}
pub fn set_muted(&self, muted: bool) {
let _ = self.player.set("mute", if muted { "yes" } else { "no" });
}
pub fn set_paused(&self, paused: bool) {
let _ = self.player.set("pause", if paused { "yes" } else { "no" });
}
pub fn keep_playing(&self) {
if self.player.get_flag("pause") == Some(true) {
self.set_paused(false);
}
}
pub fn chapters(&self) -> Vec<f64> {
self.player.chapters()
}
pub fn step_chapter(&self, dir: i32) {
let _ = self.player.command(&["add", "chapter", &dir.to_string()]);
}
pub fn tracks(&self) -> Vec<Track> {
self.player.tracks()
}
pub fn set_track(&self, kind: TrackKind, id: Option<i64>) {
let name = match kind {
TrackKind::Audio => "aid",
TrackKind::Sub => "sid",
};
let _ = self.player.set(name, &id.map_or("no".to_string(), |i| i.to_string()));
}
pub fn cycle_track(&self, kind: TrackKind) {
let _ = self.player.command(&["cycle", if kind == TrackKind::Audio { "audio" } else { "sub" }]);
}
pub fn set_looping(&self, looping: bool) {
let _ = self.player.set("loop-file", if looping { "inf" } else { "no" });
}
pub fn set_volume(&self, volume: f64) {
let _ = self.player.set("volume", &format!("{:.0}", volume.clamp(0.0, 100.0)));
}
pub fn set_speed(&self, speed: f64) {
let _ = self.player.set("speed", &format!("{speed}"));
}
pub fn frame_step(&self, forward: bool) {
let _ = self.player.command(&[if forward { "frame-step" } else { "frame-back-step" }]);
}
pub fn status(&self) -> (f64, f64, f64) {
(
self.player.get_f64("time-pos").unwrap_or(0.0),
self.player.get_f64("duration").unwrap_or(0.0),
self.player.get_f64("volume").unwrap_or(100.0),
)
}
pub fn seek_to(&self, secs: f64) {
let _ = self.player.command(&["seek", &format!("{secs:.2}"), "absolute"]);
}
pub fn seek(&self, secs: f64) {
let _ = self.player.command(&["seek", &format!("{secs}"), "relative"]);
}
}
impl Drop for Video {
fn drop(&mut self) {
self.stop.store(true, Relaxed);
}
}
#[derive(Clone, Copy)]
enum Hdr {
Unchecked,
TryingGpu(Instant),
Settled,
}
const GPU_TONE_MAP_WAIT: Duration = Duration::from_millis(1500);
impl Hdr {
fn step(self, player: &Player, gpu: &str) -> Self {
match self {
Hdr::Unchecked => match player.get_string("video-params/gamma") {
None => self,
Some(gamma) if crate::mpv::is_hdr(&gamma) => {
let _ = player.set("vf", gpu);
Hdr::TryingGpu(Instant::now())
}
Some(_) => Hdr::Settled,
},
Hdr::TryingGpu(since) => {
let out = player.get_string("video-out-params/gamma");
if out.is_some_and(|g| !crate::mpv::is_hdr(&g)) {
Hdr::Settled
} else if since.elapsed() > GPU_TONE_MAP_WAIT {
let _ = player.set("vf", crate::mpv::HDR_TO_SDR_CPU);
Hdr::Settled
} else {
self
}
}
Hdr::Settled => self,
}
}
}
fn run(player: &Player, stop: &AtomicBool, target: &AtomicU64, glass: &AtomicBool, tx: &async_channel::Sender<Msg>) {
let mut hdr = Hdr::Unchecked;
while !stop.load(Relaxed) {
match player.wait_event(Duration::from_millis(4)) {
Event::Ended => {
let _ = tx.force_send(Msg::Ended);
return;
}
Event::Failed => {
let _ = tx.force_send(Msg::Failed);
return;
}
Event::Shutdown => return,
Event::Other | Event::Restarted => {}
}
hdr = hdr.step(player, crate::mpv::HDR_TO_SDR);
if player.frame_ready() {
let Some((vw, vh)) = player.video_size() else { continue };
let t = target.load(Relaxed);
let (tw, th) = ((t >> 32) as u32, (t & 0xffff_ffff) as u32);
let scale = (tw as f64 / vw as f64).min(th as f64 / vh as f64);
let (w, h) = (((vw as f64 * scale).round() as u32).max(2), ((vh as f64 * scale).round() as u32).max(2));
match player.render(w, h) {
Ok(frame) => {
let strip = glass.load(Relaxed).then(|| crate::glass::strip(&frame));
_ = tx.force_send(Msg::Frame(frame, strip));
}
Err(_) => {
let _ = tx.force_send(Msg::Failed);
return;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hdr_falls_back_to_the_cpu_filter() {
if !crate::mpv::available() {
eprintln!("libmpv not found: skipped");
return;
}
let clip = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hdr_ramp.mkv");
let player = Player::new(&[("loop-file", "inf"), ("mute", "yes")]).unwrap();
player.command(&["loadfile", &clip.to_string_lossy()]).unwrap();
let mut hdr = Hdr::Unchecked;
let deadline = Instant::now() + GPU_TONE_MAP_WAIT + Duration::from_secs(5);
let mut out = None;
while Instant::now() < deadline {
let _ = player.wait_event(Duration::from_millis(20));
hdr = hdr.step(&player, "lavfi=[nosuchfilter]");
if matches!(hdr, Hdr::Settled) {
out = player.get_string("video-out-params/gamma");
if out.as_deref().is_some_and(|g| !crate::mpv::is_hdr(g)) {
break;
}
}
}
assert_eq!(out.as_deref(), Some("bt.1886"));
}
}