app: cut miniatures for the clips grid

Each card's stage shows a frame of the clip now, cut once with ffmpeg
into a thumbs folder beside the clips and reused from there. The pass
runs one clip at a time on a thread, skips what is already on disk and
as new as its clip, and poll drops each finished picture into its card
as it lands. Deleting a clip takes its miniature with it.

The frame is the clip's first: an export starts on the moment the clip
was cut for, so the picture shows the action without a seek. A clip
re-exported over the same name keeps its old picture until restart,
because the image cache keys a file by its path alone.
This commit is contained in:
vhaudiquet committed 2026-11-22 18:52:57 +01:00
1 parent 3f82f87a81
commit 83ca4071d4
5 files changed
+196 -25

No files matched your search

+1 -1
View File
@@ -66,7 +66,7 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti
| `src/history.rs` | Timelines from disk and the values the cards show | | `src/history.rs` | Timelines from disk and the values the cards show |
| `src/portraits.rs` | Champion portraits: the Data Dragon cache and its downloads | | `src/portraits.rs` | Champion portraits: the Data Dragon cache and its downloads |
| `src/highlight.rs` | Highlight clips from kill events | | `src/highlight.rs` | Highlight clips from kill events |
| `src/export.rs` | ffmpeg clip export, and the clips folder it fills | | `src/export.rs` | ffmpeg clip export, the clips folder it fills and its miniatures |
| `src/os.rs` | Run key, toasts, tray icon and menu | | `src/os.rs` | Run key, toasts, tray icon and menu |
| `src/ui.rs` | Colours, cards, switches, sliders, buttons | | `src/ui.rs` | Colours, cards, switches, sliders, buttons |
| `src/screens/` | Settings, match history, clips, game review | | `src/screens/` | Settings, match history, clips, game review |
+57
View File
@@ -142,6 +142,10 @@ pub struct App {
/// Every clip the user exported, newest first. Read when the screen opens. /// Every clip the user exported, newest first. Read when the screen opens.
pub clips: Vec<Clip>, pub clips: Vec<Clip>,
pub clips_loaded: bool, pub clips_loaded: bool,
/// The clips' miniatures, decoded off the render path and cached by file.
pub thumbs: Option<rune::ImageCache>,
/// A miniature on its way: the clip's name and the file that holds it.
pub thumbs_rx: Option<Receiver<(String, PathBuf)>>,
/// The clip card whose actions menu is open, if any: its position, like the history's. /// The clip card whose actions menu is open, if any: its position, like the history's.
pub clips_menu_open: Option<usize>, pub clips_menu_open: Option<usize>,
/// The clip the delete dialog is about, by its `id@start` key. /// The clip the delete dialog is about, by its `id@start` key.
@@ -201,6 +205,8 @@ impl App {
menu_open: None, menu_open: None,
clips: Vec::new(), clips: Vec::new(),
clips_loaded: false, clips_loaded: false,
thumbs: None,
thumbs_rx: None,
clips_menu_open: None, clips_menu_open: None,
confirm_clip_delete: None, confirm_clip_delete: None,
review: screens::review::Review::default(), review: screens::review::Review::default(),
@@ -250,6 +256,7 @@ impl App {
Clip { Clip {
name, name,
path: PathBuf::new(), path: PathBuf::new(),
thumb: None,
exported: Some( exported: Some(
std::time::SystemTime::now() std::time::SystemTime::now()
- chrono::Duration::hours(hours_ago) - chrono::Duration::hours(hours_ago)
@@ -475,9 +482,38 @@ impl App {
} }
/// Read the clips folder into the grid. A directory read, quick enough for the UI thread. /// Read the clips folder into the grid. A directory read, quick enough for the UI thread.
/// The miniatures are ffmpeg work, so their pass runs on a thread of its own and `poll`
/// picks each one up as it lands.
pub fn refresh_clips(&mut self) { pub fn refresh_clips(&mut self) {
self.clips = export::list_clips(); self.clips = export::list_clips();
self.clips_loaded = true; self.clips_loaded = true;
self.spawn_thumbs();
}
/// Cut every missing miniature, one clip at a time, on a thread of its own; `poll` picks
/// each one up as it lands. One pass at a time: the next refresh starts another.
pub fn spawn_thumbs(&mut self) {
if self.thumbs_rx.is_some() {
return;
}
let clips = self.clips.clone();
let (tx, rx) = channel();
std::thread::spawn(move || {
for clip in &clips {
if export::thumb_of(clip).is_some() {
continue;
}
let Some(source) = export::source_of(clip) else {
continue;
};
let thumb = export::thumb_path(clip);
let cut = export::make_thumb(&source, &thumb);
if cut && tx.send((clip.name.clone(), thumb)).is_err() {
break;
}
}
});
self.thumbs_rx = Some(rx);
} }
/// Read the next page of rows, if the list has one and none is already on its way. /// Read the next page of rows, if the list has one and none is already on its way.
@@ -568,6 +604,7 @@ pub fn setup(app: &mut App, waker: rune::Waker) {
app.waker = Some(waker.clone()); app.waker = Some(waker.clone());
app.portraits = Some(portraits::Portraits::new(waker.clone())); app.portraits = Some(portraits::Portraits::new(waker.clone()));
app.icons = Some(rune::ImageCache::new(waker.clone())); app.icons = Some(rune::ImageCache::new(waker.clone()));
app.thumbs = Some(rune::ImageCache::new(waker.clone()));
app.daemon.set_waker(waker.clone()); app.daemon.set_waker(waker.clone());
app.refresh_settings(); app.refresh_settings();
app.refresh_games(); app.refresh_games();
@@ -754,6 +791,26 @@ impl App {
} }
} }
if let Some(rx) = &self.thumbs_rx {
let mut landed = false;
loop {
match rx.try_recv() {
Ok((name, thumb)) => {
if let Some(clip) = self.clips.iter_mut().find(|clip| clip.name == name) {
clip.thumb = Some(thumb);
landed = true;
}
}
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => {
self.thumbs_rx = None;
break;
}
}
}
changed |= landed;
}
// The clips grid reads the clips folder, so it loads once it is on screen, not at launch. // The clips grid reads the clips folder, so it loads once it is on screen, not at launch.
if self.screen == Screen::Clips && !self.clips_loaded { if self.screen == Screen::Clips && !self.clips_loaded {
self.refresh_clips(); self.refresh_clips();
+101 -2
View File
@@ -28,6 +28,102 @@ pub struct Clip {
pub exported: Option<SystemTime>, pub exported: Option<SystemTime>,
/// Bytes on disk. /// Bytes on disk.
pub bytes: u64, pub bytes: u64,
/// The miniature cut from the video, when one is on disk and as new as the clip.
pub thumb: Option<PathBuf>,
}
/// Where the clips' miniatures live, beside the clips.
pub fn thumbs_dir() -> PathBuf {
let dir = clips_dir().join("thumbs");
let _ = std::fs::create_dir_all(&dir);
dir
}
/// Where `clip`'s miniature lives. A clip that names no file is demo data: its miniature
/// stays in the temp folder, so the clips folder keeps only what the user exported.
pub fn thumb_path(clip: &Clip) -> PathBuf {
if clip.path.as_os_str().is_empty() {
std::env::temp_dir()
.join("leaguerecorder-demo")
.join("thumbs")
.join(format!("{}.jpg", clip.name))
} else {
thumbs_dir().join(format!("{}.jpg", clip.name))
}
}
/// The miniature when it is on disk and as new as the clip: a stale one reads as none, so
/// the thumbnail pass cuts it again. The texture under an old path is cached by path alone,
/// so a clip re-exported over the same name keeps its old picture until the app restarts.
pub fn thumb_of(clip: &Clip) -> Option<PathBuf> {
let thumb = thumb_path(clip);
let at = std::fs::metadata(&thumb).ok()?.modified().ok()?;
let clip_at = clip.exported?;
(at >= clip_at).then_some(thumb)
}
/// The video a miniature is cut from. A clip that names no file is demo data: its video is
/// synthesized once into the temp folder, so a snapshot has something to show.
pub fn source_of(clip: &Clip) -> Option<PathBuf> {
if !clip.path.as_os_str().is_empty() {
return clip.path.is_file().then(|| clip.path.clone());
}
let demo = std::env::temp_dir()
.join("leaguerecorder-demo")
.join(format!("{}.mp4", clip.name));
if demo.is_file() {
return Some(demo);
}
let _ = std::fs::create_dir_all(demo.parent()?);
let Ok(child) = FfmpegCommand::new()
.arg("-y")
.arg("-f")
.arg("lavfi")
.arg("-i")
.arg("testsrc2=size=640x360:rate=30:duration=2")
.arg("-c:v")
.arg("libx264")
.arg("-preset")
.arg("ultrafast")
.arg("-pix_fmt")
.arg("yuv420p")
.arg(demo.to_string_lossy().to_string())
.spawn()
else {
return None;
};
let mut child = child;
child.wait().ok()?.success().then_some(demo)
}
/// Cut the first frame of `video` into `thumb`, at card size. True when the file is there
/// after: the frame lands beside a `.part.jpg` file that only a good cut renames on.
pub fn make_thumb(video: &Path, thumb: &Path) -> bool {
if let Some(parent) = thumb.parent() {
let _ = std::fs::create_dir_all(parent);
}
if ffmpeg_is_installed() {
let part = thumb.with_extension("part.jpg");
let cut = FfmpegCommand::new()
.arg("-y")
.arg("-i")
.arg(video.to_string_lossy().to_string())
.arg("-frames:v")
.arg("1")
.arg("-vf")
.arg("scale=640:-2")
.arg("-q:v")
.arg("4")
.arg(part.to_string_lossy().to_string())
.spawn()
.and_then(|mut child| child.wait());
let ok = cut.map(|status| status.success()).unwrap_or(false) && part.is_file();
if ok && std::fs::rename(&part, thumb).is_ok() {
return true;
}
let _ = std::fs::remove_file(&part);
}
false
} }
/// Every clip in the clips folder, newest export first. Only `.mp4` counts: the folder is /// Every clip in the clips folder, newest export first. Only `.mp4` counts: the folder is
@@ -44,12 +140,15 @@ pub fn list_clips() -> Vec<Clip> {
return None; return None;
} }
let meta = entry.metadata().ok()?; let meta = entry.metadata().ok()?;
Some(Clip { let mut clip = Clip {
name: path.file_stem()?.to_string_lossy().into_owned(), name: path.file_stem()?.to_string_lossy().into_owned(),
path: path.clone(), path: path.clone(),
exported: meta.modified().ok(), exported: meta.modified().ok(),
bytes: meta.len(), bytes: meta.len(),
}) thumb: None,
};
clip.thumb = thumb_of(&clip);
Some(clip)
}) })
.collect(); .collect();
clips.sort_by_key(|clip| std::cmp::Reverse(clip.exported)); clips.sort_by_key(|clip| std::cmp::Reverse(clip.exported));
+3
View File
@@ -118,9 +118,11 @@ fn main() {
("clips", |app| { ("clips", |app| {
app.screen = app::Screen::Clips; app.screen = app::Screen::Clips;
app.clips_menu_open = None; app.clips_menu_open = None;
app.spawn_thumbs();
}), }),
("clips-many", |app| { ("clips-many", |app| {
app.screen = app::Screen::Clips; app.screen = app::Screen::Clips;
app.spawn_thumbs();
app.clips = (0..12) app.clips = (0..12)
.flat_map(|page| { .flat_map(|page| {
[ [
@@ -134,6 +136,7 @@ fn main() {
}), }),
("clips-delete", |app| { ("clips-delete", |app| {
app.screen = app::Screen::Clips; app.screen = app::Screen::Clips;
app.spawn_thumbs();
app.confirm_clip_delete = app.clips.first().map(|clip| clip.name.clone()); app.confirm_clip_delete = app.clips.first().map(|clip| clip.name.clone());
}), }),
("many", |app| { ("many", |app| {
+34 -22
View File
@@ -173,39 +173,50 @@ fn clip_card(app: &App, p: Paint, k: &Kit, layer: &mut Vec<El>, clip: &Clip, ind
col() col()
.key("card") .key("card")
.w_full() .w_full()
.child(stage(p, clip)) .child(stage(app, p, clip))
.child(footer(app, p, k, layer, clip, &card)), .child(footer(app, p, k, layer, clip, &card)),
) )
} }
/// The clip itself: the 16:9 box the card gives, on black, with the play mark over it. The /// The clip itself: the 16:9 box the card gives. The miniature the thumbnail pass cuts fills
/// clip's own pictures land here later; the layout of the card is the same with or without. /// it once it has landed, and the play mark rides over it either way.
fn stage(_p: Paint, _clip: &Clip) -> El { fn stage(app: &App, p: Paint, clip: &Clip) -> El {
col() let mut stage = col()
.key("stage") .key("stage")
.aspect_ratio(16.0 / 9.0) .aspect_ratio(16.0 / 9.0)
.w_full() .w_full()
.fill(Color::BLACK) .fill(Color::BLACK);
.child( if let (Some(path), Some(thumbs)) = (&clip.thumb, &app.thumbs) {
el().key("play-overlay") let image = thumbs.file(path, 360.0, p.scale);
stage = stage.child(
el().key("thumb")
.absolute(0.0, 0.0) .absolute(0.0, 0.0)
.w_full() .w_full()
.h_full() .h_full()
.center()
.a11y_hidden() .a11y_hidden()
.child( .pixels(image.pixels()),
el().key("play") );
.size(40.0, 40.0) }
.radius(20.0) stage.child(
.center() el().key("play-overlay")
.fill(Color::WHITE.alpha(0.16)) .absolute(0.0, 0.0)
.child( .w_full()
rune::icon(&icons::PLAY, 18.0) .h_full()
.color(Color::WHITE.alpha(0.9)) .center()
.a11y_hidden(), .a11y_hidden()
), .child(
), el().key("play")
) .size(40.0, 40.0)
.radius(20.0)
.center()
.fill(Color::WHITE.alpha(0.16))
.child(
rune::icon(&icons::PLAY, 18.0)
.color(Color::WHITE.alpha(0.9))
.a11y_hidden(),
),
),
)
} }
/// Who the clip stars and what game it came from, with share and the actions menu beside. /// Who the clip stars and what game it came from, with share and the actions menu beside.
@@ -364,6 +375,7 @@ fn delete_confirmed(app: &mut App) {
return; return;
}; };
let clip = app.clips.remove(index); let clip = app.clips.remove(index);
let _ = std::fs::remove_file(crate::export::thumb_path(&clip));
match std::fs::remove_file(&clip.path) { match std::fs::remove_file(&clip.path) {
Ok(()) => app.notify("Clip deleted"), Ok(()) => app.notify("Clip deleted"),
Err(error) => { Err(error) => {