rosier 0.2.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;

use anyhow::Result;

use crate::mpv::{Event, Player};
use crate::turbo::Bgra;

pub enum Msg {
    /// A frame, and the blurred strip for the glass controls over it.
    Frame(Bgra, 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>,
}

impl Video {
    pub fn start(path: &Path, muted: bool, looping: bool, volume: f64) -> Result<(Self, async_channel::Receiver<Msg>)> {
        let player = Arc::new(Player::new(&[
            ("hwdec", "vaapi-copy,nvdec-copy"),
            ("mute", if muted { "yes" } else { "no" }),
            ("loop-file", if looping { "inf" } else { "no" }),
            ("keep-open", "no"),
            ("volume", &format!("{:.0}", volume)),
        ])?);
        player.command(&["loadfile", &path.to_string_lossy()])?;
        let stop = Arc::new(AtomicBool::new(false));
        let target = Arc::new(AtomicU64::new((640u64 << 32) | 360));
        let (tx, rx) = async_channel::bounded(2);
        {
            let (player, stop, target) = (player.clone(), stop.clone(), target.clone());
            std::thread::Builder::new().name("rosier-video".into()).spawn(move || run(&player, &stop, &target, &tx))?;
        }
        Ok((Video { player, stop, target }, rx))
    }

    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 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 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);
    }
}

fn run(player: &Player, stop: &AtomicBool, target: &AtomicU64, tx: &async_channel::Sender<Msg>) {
    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 => {}
        }
        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 = crate::glass::strip(&frame);
                    _ = tx.force_send(Msg::Frame(frame, strip));
                }
                Err(_) => {
                    let _ = tx.force_send(Msg::Failed);
                    return;
                }
            }
        }
    }
}