rosier 0.3.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, Track, TrackKind};
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,
        speed: f64,
        start: 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)),
            ("speed", &format!("{speed}")),
            ("start", &format!("{start:.1}")),
        ])?);
        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" });
    }

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

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