//! Seek-bar previews: a small frame at the hovered time, cut by ffmpeg on a worker thread, cached per file and per few //! seconds. Local files only; nothing runs while the pointer isn't over the bar. use eframe::egui::{self, ColorImage, TextureHandle, TextureOptions}; use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender, channel}; pub const HEIGHT: u32 = 90; pub struct Thumbs { path: String, step: f64, cache: HashMap>, asked: Option, busy: bool, tx: Sender<(String, u64, Option)>, rx: Receiver<(String, u64, Option)>, pub available: bool, } impl Thumbs { pub fn new() -> Thumbs { let (tx, rx) = channel(); let available = std::process::Command::new("ffmpeg").arg("-version").stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().is_ok(); Thumbs { path: String::new(), step: 5.0, cache: HashMap::new(), asked: None, busy: false, tx, rx, available } } /// A preview near `time` of `path`, if one is ready; asks for it otherwise. pub fn get(&mut self, ctx: &egui::Context, path: &str, duration: f64, time: f64) -> Option { if !self.available || path.is_empty() || path.contains("://") || duration <= 0.0 { return None; } if path != self.path { self.path = path.to_string(); self.cache.clear(); self.step = (duration / 200.0).clamp(2.0, 30.0); } while let Ok((p, k, img)) = self.rx.try_recv() { self.busy = false; if p == self.path { let tex = img.map(|i| ctx.load_texture(format!("thumb-{k}"), i, TextureOptions::LINEAR)); self.cache.insert(k, tex); } } let key = (time / self.step).floor() as u64; if let Some(t) = self.cache.get(&key) { return t.clone(); } if !self.busy && self.asked != Some(key) { self.asked = Some(key); self.busy = true; let (tx, path, at, ctx) = (self.tx.clone(), self.path.clone(), key as f64 * self.step + self.step / 2.0, ctx.clone()); std::thread::spawn(move || { let img = grab(&path, at.min(duration - 0.5).max(0.0)); let _ = tx.send((path, key, img)); ctx.request_repaint(); }); } // the nearest one we have stands in while the right one is cut (0..6u64).find_map(|d| self.cache.get(&key.saturating_sub(d)).cloned().flatten()) } } fn grab(path: &str, at: f64) -> Option { let out = std::process::Command::new("nice") .args(["-n", "10", "ffmpeg", "-v", "error", "-nostdin", "-ss", &format!("{at:.2}"), "-i", path, "-frames:v", "1", "-an", "-sn"]) .args(["-vf", &format!("scale=-2:{HEIGHT}"), "-f", "image2pipe", "-vcodec", "png", "-"]) .output() .ok()?; let img = image::load_from_memory(&out.stdout).ok()?.to_rgba8(); Some(ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.as_raw())) }