rosier 0.4.0

A fast picture and video viewer for large folders
//! Video playback inside a pane.
//!
//! Each playing video owns a thread that drives one mpv player: it waits for
//! decoded frames, has mpv scale them to the pane's pixel size, and hands
//! BGRA buffers to the UI through a channel that keeps only the newest frame.

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 {
    /// A frame, and the blurred strip for the glass controls over it while
    /// they are shown.
    Frame(Bgra, Option<Bgra>),
    Ended,
    Failed,
}

/// A running video. Dropping it stops playback and frees the player.
pub struct Video {
    player: Arc<Player>,
    stop: Arc<AtomicBool>,
    /// Target size packed as (w << 32 | h), in physical pixels.
    target: Arc<AtomicU64>,
    /// Whether the controls are up, so each frame needs its blurred strip.
    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}")),
            // mpv guesses the display's timing, wrongly with nothing on
            // screen of its own, and then drops 10-20% of 4K60 frames as
            // late. Every frame is drawn instead.
            ("framedrop", "no"),
            // The first frame comes as soon as it is decoded, not 200 ms
            // later (mpv waits that long for a display it does not have).
            ("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))
    }

    /// Whether frames come with the blurred strip for the controls: only
    /// while they are shown (it costs 1.5 ms a frame at 4K).
    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" });
    }

    /// A frame step pauses mpv when its frame is shown, which can be after
    /// the user has already resumed. Called each tick with what the pane
    /// wants, it resumes playback such a late step paused.
    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()
    }

    /// Jumps to the next chapter (`dir` 1) or back one (-1); mpv goes to the
    /// start of the current chapter first when it is a few seconds in.
    pub fn step_chapter(&self, dir: i32) {
        let _ = self.player.command(&["add", "chapter", &dir.to_string()]);
    }

    /// The file's audio and subtitle tracks.
    pub fn tracks(&self) -> Vec<Track> {
        self.player.tracks()
    }

    /// Picks audio or subtitle track `id`, or none (subtitles off).
    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()));
    }

    /// The next audio track, or the next subtitles (then off again).
    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)));
    }

    /// Playback speed, 1 being normal. The pitch stays as it is.
    pub fn set_speed(&self, speed: f64) {
        let _ = self.player.set("speed", &format!("{speed}"));
    }

    /// Shows the next (or previous) frame and pauses there.
    pub fn frame_step(&self, forward: bool) {
        let _ = self.player.command(&[if forward { "frame-step" } else { "frame-back-step" }]);
    }

    /// Playback position, duration, and volume, for the controls.
    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"]);
    }

    /// Seeks by `secs` relative to the current position.
    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);
    }
}

/// Where tone mapping an HDR video stands.
#[derive(Clone, Copy)]
enum Hdr {
    /// mpv has not read the video's transfer yet.
    Unchecked,
    /// libplacebo was asked for at this time and has not shown up yet.
    TryingGpu(Instant),
    /// SDR, tone-mapped, or nothing left to try.
    Settled,
}

/// How long libplacebo gets to start (its Vulkan setup takes about 0.2 s)
/// before the CPU filter replaces it. mpv takes any filter graph without
/// complaint and drops one it cannot build, so the sign it works is the
/// filtered video coming out as SDR.
const GPU_TONE_MAP_WAIT: Duration = Duration::from_millis(1500);

impl Hdr {
    /// Moves on from what mpv now says, `gpu` being the filter tried first.
    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) {
        // With loop-file the file restarts without ending, so these only
        // come when playback really finished or failed.
        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) {
                // force_send drops the oldest frame if the UI is behind.
                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::*;

    /// Where libplacebo cannot run (no Vulkan, or an FFmpeg without it),
    /// mpv drops the filter and the CPU one takes over.
    #[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"));
    }
}