//! Game review: the recorded clip, a scrubber with event markers, highlights and export. use std::sync::mpsc::{Receiver, TryRecvError, channel}; use rune::tok::{radius, space, type_}; use rune::{El, Player, SurfaceFit, Tx, col, el, row, text}; use crate::app::{App, Screen}; use crate::format; use crate::highlight::{self, Highlight}; use crate::history::{self, Outcome, Timeline}; use crate::icons; use crate::ui::{self, Paint, body, heading}; pub struct Review { /// The opened recording, once its file has been read. pub game: Option, /// Set while that file is on its way to the screen. pub loading: bool, pub player: Option, /// The clip's audio tracks, one player each, so the channels are heard apart. pub sounds: Vec, /// Tracks being cut out of the clip on a thread. `tick` opens their players when they land, /// so a long clip does not hold the frame while ffmpeg reads it. pub sound_rx: Option, String>>>, /// Whether the soundtrack has been asked for, so a failed cut is not retried every frame. pub sound_tried: bool, /// The picture time the soundtrack was last put back to, to spot a window that stopped drawing. steady_at: f64, pub time: f64, pub duration: f64, pub scrubber_width: f32, /// Where the scrubber starts in the window, in points, so an arrow drag can read the /// pointer against the track. pub scrubber_x: f32, /// Where playback began, while it runs. A selection preview stops at its end only when the /// play head started before it; played from the end, there is nothing left to preview. pub play_from: Option, /// The stretch the scrubber shows, held still while an end is dragged so the track does not /// move under the pointer. pub frozen_window: Option<(f64, f64)>, pub show_details: bool, pub highlights: Vec, /// The clip being chosen on the scrubber, once the Clip button is pressed. pub clip: Option, pub export: Option>>, pub export_note: Option, /// Soundtrack gain, 0 to 1; the transport bar sets it. pub volume: f32, pub muted: bool, pub error: Option, /// Why the channels could not be opened, when the clip has more than one. pub channel_error: Option, } impl Review { /// The video player only draws; the audio players carry the gain and the mute. fn mute_video(player: &Player) { player.set_muted(true); } /// Set the gain from the transport bar. Sliding off zero is also how a viewer unmutes. pub fn set_volume(&mut self, volume: f32) { self.volume = volume.clamp(0.0, 1.0); if self.volume > 0.0 { self.muted = false; } for channel in &self.sounds { channel.sound.set_volume(self.volume); channel.sound.set_muted(!channel.heard(self.muted)); } } pub fn toggle_muted(&mut self) { self.muted = !self.muted; for channel in &self.sounds { channel.sound.set_muted(!channel.heard(self.muted)); } } /// Turn one track on or off, and make the change audible now rather than at the next seek. pub fn toggle_channel(&mut self, index: usize) { let Some(channel) = self.sounds.get_mut(index) else { return; }; channel.on = !channel.on; channel.sound.set_muted(!channel.heard(self.muted)); } /// The audio streams a clip or highlight keeps: the tracks the viewer left on. pub fn kept_tracks(&self) -> Vec { self.sounds .iter() .filter(|channel| channel.on) .map(|channel| channel.stream) .collect() } /// Start the soundtrack's players, at the place the viewer is watching. Blocks while /// ffmpeg cuts the tracks; a screen that keeps drawing calls [`request_sound`] instead. /// /// [`request_sound`]: Self::request_sound pub fn open_sound(&mut self, path: &str) { self.sound_tried = true; self.sounds.clear(); self.channel_error = None; let labels = self.track_labels(); if labels.len() < 2 { // One track, or a recording made before the recorder split them: the file's own // sound is the whole mix, and an audio player reads it as it is. let label = labels .first() .cloned() .unwrap_or_else(|| "All audio".to_string()); let channel = self.channel(0, label, path); self.sounds.push(channel); return; } let stem = self.stem(path); match crate::export::extract_tracks(path, &stem, labels.len()) { Ok(files) => self.open_tracks(&labels, &files), Err(e) => self.channel_error = Some(e), } } /// Ask for the soundtrack's players without waiting. ffmpeg reads the whole clip once per /// track it cuts, so a five-track recording of an hour takes a minute. That work runs on a /// thread, and `tick` opens the players (see `settle_sound`) when the files land. pub fn request_sound(&mut self, path: &str) { if self.sound_tried { return; } self.sound_tried = true; let labels = self.track_labels(); if labels.len() < 2 { self.open_sound(path); return; } self.channel_error = None; let path = path.to_string(); let stem = self.stem(&path); let count = labels.len(); let (tx, rx) = channel(); std::thread::spawn(move || { let _ = tx.send(crate::export::extract_tracks(&path, &stem, count)); }); self.sound_rx = Some(rx); } /// The cut tracks have landed: open a player for each at the place the viewer is now. pub fn settle_sound(&mut self) { let Some(rx) = &self.sound_rx else { return; }; let files = match rx.try_recv() { Ok(files) => files, Err(TryRecvError::Empty) => return, Err(TryRecvError::Disconnected) => Err("the audio tracks could not be cut".to_string()), }; self.sound_rx = None; match files { Ok(files) => { let labels = self.track_labels(); self.open_tracks(&labels, &files); } Err(e) => self.channel_error = Some(e), } } /// What each track of the clip carries, in file order. fn track_labels(&self) -> Vec { self.game .as_ref() .map(|game| game.audio_tracks.clone()) .unwrap_or_default() } /// The name of the cache folder the clip's track files go in. fn stem(&self, path: &str) -> String { let stem = self .game .as_ref() .and_then(|game| game.video_file.clone()) .or_else(|| { std::path::Path::new(path) .file_name() .map(|name| name.to_string_lossy().to_string()) }) .unwrap_or_default(); stem.rsplit_once('.') .map(|(name, _)| name) .unwrap_or(&stem) .to_string() } /// Open one player per track file. A track no source fed is silent in the clip and has no /// label, so it gets no toggle. fn open_tracks(&mut self, labels: &[String], files: &[std::path::PathBuf]) { for (stream, file) in files.iter().enumerate() { let Some(label) = labels.get(stream).filter(|label| !label.trim().is_empty()) else { continue; }; let channel = self.channel(stream, label.clone(), &file.to_string_lossy()); self.sounds.push(channel); } } fn channel(&self, stream: usize, label: String, path: &str) -> Channel { let sound = Player::audio(path.to_string()); sound.set_looping(false); sound.set_volume(self.volume); sound.set_muted(self.muted); let playing = self.player.as_ref().is_some_and(Player::is_playing); let from = self.time.max(0.0); if from > 0.0 { sound.seek(from); } if playing { sound.play(); } Channel { label, stream, sound, on: true, } } fn playback(&mut self) { let playing = self.player.as_ref().is_some_and(Player::is_playing); if let Some(player) = &self.player { if playing { player.pause(); } else { player.play(); } } for channel in &self.sounds { if playing { channel.sound.pause(); } else { channel.sound.play(); } } } /// The Clip button: start a selection at the viewer's place, or drop the one on screen. pub fn toggle_clip(&mut self) { self.clip = match self.clip { Some(_) => None, None => { let start = self.time.clamp(0.0, (self.duration - 1.0).max(0.0)); let end = (start + 30.0).min(self.duration.max(start + 1.0)); Some(Clip { start, end }) } }; } /// The stretch of the recording the scrubber lays out: the whole file, unless a clip is /// being chosen, when it zooms to a window around the selection so its ends can be placed /// to the pixel. A drag freezes it; the window follows once the drag is over. pub fn shown(&self) -> (f64, f64) { let duration = self.duration.max(0.0); if let Some(window) = self.frozen_window { return window; } let Some(clip) = self.clip else { return (0.0, duration); }; let half = (clip.end - clip.start).max(1.0) * 0.5; let mut from = clip.start - half; let mut to = clip.end + half; if from < 0.0 { to -= from; from = 0.0; } if to > duration { from = (from - (to - duration)).max(0.0); to = duration; } (from, to) } /// Move one end of the selection to `at`, a second away from the other end at least, and /// show the picture there. Only the arrows on the scrubber call this. pub fn drag_clip_end(&mut self, start: bool, at: f64) { let duration = self.duration.max(0.0); let Some(clip) = &mut self.clip else { return; }; let at = at.clamp(0.0, duration); let place = if start { clip.start = at.min(clip.end - 1.0).max(0.0); clip.start } else { clip.end = at.max(clip.start + 1.0).min(duration); clip.end }; self.seek(place); } fn seek(&mut self, seconds: f64) { let at = seconds.clamp(0.0, self.duration.max(0.0)); if let Some(player) = &self.player { player.seek(at); self.time = at; } for channel in &self.sounds { channel.sound.seek(at); } } } /// One audio track of the clip, copied to a file of its own and played on its own, so the /// channels are heard apart and can be kept apart. /// Rune's video player asks Media Foundation for pictures and sound from one reader, and that /// reader stamps the sound from its own clock instead of the clip's, so the sound never lines /// up with the clock and plays silent. Audio-only players read one track each and need no /// video, so their sound starts at zero. pub struct Channel { /// What the track carries, as the recorder named it. pub label: String, /// The stream this track is, in the file. pub stream: usize, pub sound: Player, /// Off means the viewer does not hear it, and a clip or highlight does not keep it. pub on: bool, } impl Channel { /// Whether this track goes into the current mix, given the master mute. fn heard(&self, muted: bool) -> bool { self.on && !muted } } /// A clip being chosen on the scrubber: where it starts and where it ends. #[derive(Clone, Copy)] pub struct Clip { pub start: f64, pub end: f64, } impl Clip { pub fn length(&self) -> f64 { (self.end - self.start).max(0.0) } } impl Default for Review { fn default() -> Self { Self { game: None, loading: false, player: None, sounds: Vec::new(), sound_rx: None, sound_tried: false, steady_at: 0.0, time: 0.0, duration: 0.0, scrubber_width: 0.0, scrubber_x: 0.0, play_from: None, frozen_window: None, highlights: Vec::new(), clip: None, show_details: false, export: None, export_note: None, error: None, // Rune plays a video muted, so the review has to unmute. Eight tenths leaves // headroom, and the transport bar can change it. volume: 0.8, muted: false, channel_error: None, } } } /// Open a recording in the review screen. /// /// Only the id travels here: the timeline with its events and raw responses is a large file /// and stays on disk until a row is opened. It is read on a thread, and `poll` hands it to /// [`show`] when it arrives. pub fn open(app: &mut App, recording_id: &str) { leave(app); app.screen = Screen::Review; app.review.loading = true; let id = recording_id.to_string(); let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { let _ = tx.send(history::load(&id)); }); app.review_rx = Some(rx); } /// Fill the review screen with a timeline that has been read, and load its clip. pub fn show(app: &mut App, game: Timeline) { let path = game.video_path(); let highlights = highlight::compute( &game, game.summoner().as_deref(), highlight::Options::default(), ); app.review.highlights = highlights; app.review.duration = game.duration_secs.max(0) as f64; let video_file = game.video_file.clone(); app.review.game = Some(game); let Some(path) = path else { app.review.error = Some(format!( "No video file found for this recording ({}).", video_file.as_deref().unwrap_or("unnamed") )); return; }; let player = Player::file(&path); player.set_looping(false); if let Some(waker) = &app.waker { player.set_waker(waker.clone()); } app.review.player = Some(player); app.review.sounds.clear(); app.review.sound_rx = None; app.review.sound_tried = false; app.review.channel_error = None; app.review.steady_at = 0.0; Review::mute_video(app.review.player.as_ref().expect("just set")); // The timeline names several tracks, and cutting them is the slow part of opening a // recording. Start it on a thread now, while the first picture decodes. let many_tracks = app .review .game .as_ref() .is_some_and(|game| game.audio_tracks.len() >= 2); if many_tracks { app.review.request_sound(&path.to_string_lossy()); } } /// The soundtrack player follows the video player: it starts once the file is known to have /// sound, and from then on keeps the same place, the same playing state and the same gain. fn follow_sound(app: &mut App) { let Some(player) = &app.review.player else { return; }; if app.review.sound_tried || player.has_sound() != Some(true) { return; } let Some(path) = app .review .game .as_ref() .and_then(history::Timeline::video_path) else { return; }; app.review.request_sound(&path.to_string_lossy()); } /// Leave the review screen and stop playback. pub fn leave(app: &mut App) { app.review_rx = None; app.review.loading = false; app.review.play_from = None; app.review.frozen_window = None; app.review.player = None; app.review.sounds.clear(); app.review.sound_rx = None; app.review.sound_tried = false; app.review.channel_error = None; app.review.game = None; app.review.highlights.clear(); app.review.time = 0.0; app.review.duration = 0.0; app.review.error = None; app.review.export_note = None; app.review.export = None; } /// Called from `poll` while the review screen is up. /// Sound from a second player drifts from the pictures by a few milliseconds a minute. Past a /// quarter second it is worth a seek, and short of that a seek would be audible. fn keep_in_step(app: &mut App) { let (Some(player), Some(sound)) = ( &app.review.player, app.review.sounds.first().map(|channel| &channel.sound), ) else { return; }; if !player.is_playing() { return; } let watching = app.review.time; // A window that stops drawing stops pulling the clip, so the pictures stand still while the // soundtrack plays on. Pulling the sound back to that standing place every wake is what // repeats one second forever: only correct when the pictures have moved since the last // correction. if (watching - app.review.steady_at).abs() < 0.05 { return; } let hearing = sound.time(); if (hearing - watching).abs() > 0.25 { sound.seek(watching); app.review.steady_at = watching; } } pub fn tick(app: &mut App, tx: &mut Tx) -> bool { let mut changed = false; if let Some(player) = &app.review.player { // Rune reads a layered clip's place from the compositor clock, and that clock stops with // playback, so the first pause can read zero and send the scrubber to the start. While // the clip is paused the place is ours: only a seek moves it. if player.is_playing() { let time = player.time(); if (time - app.review.time).abs() > 0.001 { app.review.time = time; changed = true; } } if let Some(duration) = player.duration() && duration > 0.0 && (duration - app.review.duration).abs() > 0.05 { app.review.duration = duration; changed = true; } if app.review.error.is_none() && let rune::PlayerState::Failed(message) = player.state() { app.review.error = Some(message); changed = true; } if player.is_playing() { tx.wake_after(std::time::Duration::from_millis(33)); } } follow_sound(app); app.review.settle_sound(); keep_in_step(app); // A clip preview stops where the clip does: the selection is what is being watched. A play // that started at or past the end previews nothing, so it runs on rather than freezing. if playing(app) { let from = *app.review.play_from.get_or_insert(app.review.time); if let Some(clip) = app.review.clip && from < clip.end && app.review.time >= clip.end { app.review.playback(); changed = true; } } else { app.review.play_from = None; } if let Some(rx) = &app.review.export { match rx.try_recv() { Ok(Ok(path)) => { app.review.export_note = Some(format!("Clip saved to {path}")); app.review.export = None; changed = true; // The clips grid lists the folder this clip just joined. if app.screen == crate::app::Screen::Clips { app.refresh_clips(); } } Ok(Err(e)) => { app.review.export_note = Some(format!("Export failed: {e}")); app.review.export = None; changed = true; } Err(_) => {} } } changed } pub fn view(app: &App, p: Paint) -> El { let Some(game) = app.reviewed() else { let message = if app.review.loading { "Opening the recording…" } else { "No game selected." }; return col() .key("review") .padding(space::S6) .child(text(message).font(body(13.0)).color(p.muted())); }; let outcome = game.outcome(); let ink = match outcome { Outcome::Victory => p.success, Outcome::Defeat => p.danger, Outcome::Terminated => p.muted(), }; let header = row() .key("review-header") .w_full() .center_y() .justify_between() .child( row() .key("review-title") .gap(10.0) .center_y() .child(ui::champion_portrait( app, p, game.champion().as_deref(), 26.0, )) .child( text(game.champion().unwrap_or_else(|| "Unknown champion".into())) .key("champion") .font(heading(20.0)) .color(p.t.text), ) .child( text(outcome.label()) .key("outcome") .font(type_::LABEL) .color(ink), ) .child( text(format!( "{} · {}", game.queue_label(), format::duration(app.review.duration) )) .key("meta") .font(body(12.0)) .color(p.muted()), ), ) .child( text(format::game_start(game.start_time)) .key("started") .font(body(11.5)) .color(p.muted()), ); // The player takes the window: the clip is why the screen exists. The details column // opens beside it on demand, so a closed panel leaves the clip the whole width. let body = row() .key("review-body") .w_full() .grow(1.0) .min_h(0.0) .gap(space::S3) .child( col() .key("player") .grow(1.0) .min_w(0.0) .min_h(0.0) .gap(space::S2) .child(video_stage(app, p)) .child(transport(app, p)) .child(scrubber(app, p, game)), ); let body = if app.review.show_details { body.child( col() .key("details") .w(380.0) .min_w(320.0) .h_full() .min_h(0.0) .gap(space::S2) .child(highlights(app, p, game)) .child(events(app, p, game)), ) } else { body }; col() .key("review") .w_full() .h_full() .padding(space::S6) .gap(space::S3) .child(header) .child(body) } /// The clip itself: the largest 16:9 box that fits, on black, with a message when there is no /// file to play. fn video_stage(app: &App, p: Paint) -> El { let stage = el() .key("stage") .w_full() .grow(1.0) .min_h(0.0) .fill(rune::Color::BLACK) .radius(radius::LG) .clip_soft(radius::LG) .center(); match &app.review.player { Some(player) => stage.child( el().key("video") .aspect_fit(16.0 / 9.0) .video(player, SurfaceFit::Fill), ), None => stage.child( col().key("stage-empty").center().gap(6.0).child( text( app.review .error .clone() .unwrap_or_else(|| "Loading the clip…".into()), ) .key("stage-message") .font(body(13.0)) .color(p.muted()), ), ), } } /// Mute and gain. Rune plays a video muted until told otherwise, so these are the only way to /// hear a recording; the settings carry over to the next one opened. fn volume(app: &App, p: Paint) -> El { let percent = (app.review.volume * 100.0).round() as u32; let muted = app.review.muted || percent == 0; row() .key("volume") .center_y() .gap(space::S2) .child(ui::button( p, "mute", if muted { "Unmute" } else { "Mute" }, false, |app: &mut App| app.review.toggle_muted(), )) .child(ui::slider_width( p, "volume", "Volume", 110.0, percent, |app, value| app.review.set_volume(value as f32 / 100.0), )) } /// Play/pause, the ten-second steps and the clock, with the highlights toggle on the other /// side: the list is one press away, not a column that always takes the clip's width. /// Transport: back ten seconds, play or pause, forward ten seconds, then the clock and the /// gain. The highlights toggle sits at the far end, one press away, and the Clip button opens /// the selection row under the bar. fn transport(app: &App, p: Paint) -> El { let count = app.review.highlights.len(); let mut bar = row() .key("transport") .w_full() .center_y() .gap(space::S2) .child(ui::media_button( p, "rewind", &icons::BACK, "Back 10 seconds", false, |app: &mut App| { let at = app.review.time - 10.0; app.review.seek(at); }, )) .child(ui::media_button( p, "play-pause", if playing(app) { &icons::PAUSE } else { &icons::PLAY }, if playing(app) { "Pause" } else { "Play" }, true, |app: &mut App| { app.review.playback(); }, )) .child(ui::media_button( p, "advance", &icons::FORWARD, "Forward 10 seconds", false, |app: &mut App| { let at = app.review.time + 10.0; app.review.seek(at); }, )) .child( text(format!( "{} / {}", format::clock(app.review.time), format::clock(app.review.duration) )) .key("time") .font(type_::MONO_CAPTION) .color(p.muted()), ) .child(volume(app, p)) .child(el().grow(1.0)); if let Some(note) = &app.review.export_note { bar = bar.child( text(note.clone()) .key("export-note") .font(body(11.5)) .color(p.muted()), ); } let bar = bar .child(ui::button( p, "clip", "Clip", app.review.clip.is_some(), |app: &mut App| app.review.toggle_clip(), )) .child(ui::button( p, "toggle-details", &if app.review.show_details { "Hide details".to_string() } else { format!("Highlights · {count}") }, false, |app: &mut App| { app.review.show_details = !app.review.show_details; }, )); let mut column = col() .key("transport-bar") .w_full() .gap(space::S2) .child(bar); if let Some(line) = channels(app, p) { column = column.child(line); } if let Some(clip) = app.review.clip { column = column.child(clip_row(app, p, clip)); } column } /// One toggle per audio track, shown once the clip carries more than one. A track that is off /// is neither heard nor kept in an export. fn channels(app: &App, p: Paint) -> Option { if app.review.sounds.len() < 2 { return None; } let mut line = row().key("channels").center_y().gap(space::S2).child( text("Audio") .key("channels-label") .font(body(11.5)) .color(p.muted()), ); for (index, channel) in app.review.sounds.iter().enumerate() { let label = channel.label.clone(); let on = channel.on; line = line.child( el().key(format!("channel-{index}")) .role("switch") .label(label.clone()) .checked(on) .focusable(true) .h(24.0) .px(10.0) .center() .radius(radius::MD) .fill(if on { p.accent } else { p.t.control_off }) .hover(p.t.hover) .press(p.t.press) .on_press(move |app: &mut App| app.review.toggle_channel(index)) .child( text(label) .key("label") .font(type_::LABEL) .color(if on { p.accent_ink } else { p.muted() }) .a11y_hidden(), ), ); } if let Some(error) = &app.review.channel_error { line = line.child( text(error.clone()) .key("channels-error") .font(body(11.5)) .color(p.warning), ); } Some(line) } /// The row under the transport while a clip is being chosen: the two ends, its length, and the /// two things to do with it. fn clip_row(app: &App, p: Paint, clip: Clip) -> El { let video = app .reviewed() .and_then(|game| game.video_path()) .map(|path| path.display().to_string()); let name = app .reviewed() .map(|game| format!("{}-clip", game.recording_id)) .unwrap_or_default(); let mut actions = row() .key("clip-actions") .center_y() .gap(space::S2) .child( text(format!( "Clip {} to {} · {}", format::clock(clip.start), format::clock(clip.end), format::clock(clip.length()) )) .key("clip-range") .font(type_::MONO_CAPTION) .color(p.muted()), ) .child(el().grow(1.0)); if let Some(video) = video { actions = actions.child(ui::button( p, "export-clip", "Export clip", true, move |app: &mut App| { let (tx, rx) = channel(); let video = video.clone(); let name = name.clone(); let (start, end) = match app.review.clip { Some(clip) => (clip.start, clip.end), None => return, }; let audio = app.review.kept_tracks(); std::thread::spawn(move || { let result = crate::export::export_clip(&video, start, end, &name, true, "high", &audio); let _ = tx.send(result); }); app.review.export = Some(rx); app.review.export_note = Some("Exporting clip…".into()); }, )); } actions.child(ui::button( p, "clip-done", "Done", false, |app: &mut App| app.review.clip = None, )) } fn playing(app: &App) -> bool { app.review.player.as_ref().is_some_and(Player::is_playing) } /// Where `x`, in points across the track, falls in time within the stretch the scrubber shows. /// `x` may lie past either end: a drag that leaves the bar keeps counting, so an end can be /// pulled beyond the window rather than stopping at its edge. fn time_at(x: f32, width: f32, (from, to): (f64, f64)) -> f64 { from + (x / width.max(1.0)) as f64 * (to - from) } fn scrubber(app: &App, p: Paint, game: &Timeline) -> El { let width = if app.review.scrubber_width > 0.0 { app.review.scrubber_width } else { 800.0 }; let (shown_from, shown_to) = app.review.shown(); let shown = (shown_to - shown_from).max(0.001); let shown_x = |at: f64| ((at - shown_from) / shown).clamp(0.0, 1.0) as f32; let progress = shown_x(app.review.time); let knob = 14.0; let player = game.summoner(); let mut bar = el() .key("scrubber") .role("slider") .label("Playback position") .range_value(app.review.time, shown_from, shown_to) .w_full() .h(34.0) .on_layout(|app: &mut App, [x, _, w, _]| { app.review.scrubber_x = x; app.review.scrubber_width = w; }) .on_step(|app: &mut App, steps, _| { let at = app.review.time + steps as f64 * 5.0; app.review.seek(at); }) .on_drag(move |app: &mut App, d: &mut rune::Drag, tx| { let w = app.review.scrubber_width.max(1.0); let at = time_at(d.x, w, app.review.shown()); app.review.seek(at); tx.instant(); }) .child( el().key("track") .w_full() .h(6.0) .absolute(0.0, 12.0) .radius(3.0) .fill(p.t.control_off) .a11y_hidden(), ); // Each highlight as a band on the track, so the clip it exports is visible at a glance. for (index, clip) in app.review.highlights.iter().enumerate() { if clip.end < shown_from || clip.start > shown_to { continue; } let x = shown_x(clip.start) * width; let end = shown_x(clip.end) * width; let ink = match clip.kind { highlight::Kind::Death => p.danger, highlight::Kind::Assist => p.muted(), _ => p.success, }; bar = bar.child( el().key(format!("clip-{index}")) .w((end - x).max(4.0)) .h(6.0) .absolute(x, 12.0) .radius(3.0) .fill(ink.alpha(0.32)) .a11y_hidden(), ); } // The played part of the track. In clip mode it goes neutral: gold there marks the // selection and nothing else. let played = if app.review.clip.is_some() { p.muted().alpha(0.4) } else { p.accent.alpha(0.55) }; bar = bar.child( el().key("played") .w((width * progress).max(2.0)) .h(6.0) .absolute(0.0, 12.0) .radius(3.0) .fill(played) .a11y_hidden(), ); // The clip being chosen: only its span is gold. The two ends are drawn after the knob, so // their arrows stay visible over it. let bounds = app .review .clip .map(|clip| (shown_x(clip.start) * width, shown_x(clip.end) * width)); if let Some((from, to)) = bounds { bar = bar.child( el().key("clip-span") .w((to - from).max(2.0)) .h(6.0) .absolute(from, 12.0) .radius(3.0) .fill(p.accent) .a11y_hidden(), ); } // One tick per timeline event, below the track: every kill, objective and change the // recording has, not only the player's own. for (index, event) in game.events.iter().enumerate() { let at = event.time(); if !at.is_finite() || at < shown_from || at > shown_to { continue; } let x = ((at - shown_from) / shown) as f32 * (width - 2.0); let involvement = player .as_deref() .and_then(|name| highlight::involvement(event, name)); let ink = match event.event_type.as_str() { "kill" => match involvement { Some(highlight::Kind::Death) => p.danger, Some(_) => p.success, None => p.muted().alpha(0.75), }, "objective" | "lp_change" => p.accent, "game_start" | "game_end" => p.muted(), _ => p.muted().alpha(0.5), }; let label = match involvement { Some(kind) => kind.label().to_string(), None if event.description.is_empty() => event.event_type.clone(), None => event.description.clone(), }; bar = bar.child( el().key(format!("event-tick-{index}")) .role("button") .label(format!("{label} at {}", format::clock(at))) .w(2.0) .h(9.0) .absolute(x, 21.0) .fill(ink) .on_press(move |app: &mut App| app.review.seek(at)) .a11y_hidden(), ); } // The knob is centred on the play head, so an arrow at the same second sits on it. let knob_x = (progress * width - knob / 2.0).clamp(0.0, width - knob); bar = bar.child( el().key("knob") .size(knob, knob) .absolute(knob_x, 8.0) .radius(knob / 2.0) .fill(p.t.knob) .shadow(1.0, 3.0, p.t.knob_shadow) .shadow(0.0, 0.5, p.t.edge) .a11y_hidden(), ); // The two ends of the selection, over the knob: an arrow each, and a drag that starts on // one of them moves that end. A drag anywhere else still scrubs the video. if let Some((from, to)) = bounds { bar = bar .child(clip_end( p, "clip-start-arrow", &icons::CHEVRON_LEFT, true, from, )) .child(clip_end( p, "clip-end-arrow", &icons::CHEVRON_RIGHT, false, to, )); } bar } /// One end of the clip: a round gold arrow on the track, wide enough to take hold of. A drag /// that starts on it moves that end and shows the picture there. fn clip_end(p: Paint, key: &str, icon: &'static rune::Icon, start: bool, x: f32) -> El { const SIZE: f32 = 18.0; el().key(key) .w(SIZE) .h(SIZE) .absolute(x - SIZE / 2.0, 15.0 - SIZE / 2.0) .center() .radius(SIZE / 2.0) .fill(p.accent) .border(1.0, p.t.bg) .shadow(0.0, 1.0, p.t.edge) .on_drag(move |app: &mut App, d: &mut rune::Drag, tx| { // The window holds still for the drag: zooming as the end moves would slide the // track under the pointer. if d.phase == rune::Phase::Down { app.review.frozen_window = Some(app.review.shown()); } let w = app.review.scrubber_width.max(1.0); let x = d.window_point()[0] - app.review.scrubber_x; app.review .drag_clip_end(start, time_at(x, w, app.review.shown())); if d.phase == rune::Phase::Up { app.review.frozen_window = None; } tx.instant(); }) .child(rune::icon(icon, 12.0).color(p.accent_ink).a11y_hidden()) .a11y_hidden() } fn highlights(app: &App, p: Paint, game: &Timeline) -> El { let mut list = col().key("highlight-rows").w_full().gap(4.0); if app.review.highlights.is_empty() { list = list.child( text(if game.events.is_empty() { "No timeline was saved for this recording." } else { "No kills or deaths in this recording." }) .key("no-highlights") .font(body(12.0)) .color(p.muted()) .padding(space::S2), ); } for (index, clip) in app.review.highlights.iter().enumerate() { let start = clip.start; let end = clip.end; let video = game.video_path().map(|path| path.display().to_string()); let name = format!("{}-highlight-{}", game.recording_id, index); let kind_ink = match clip.kind { highlight::Kind::Death => p.danger, highlight::Kind::Assist => p.muted(), highlight::Kind::MultiKill | highlight::Kind::TradeKill => p.accent, highlight::Kind::Kill => p.success, }; let mut actions = row().key("actions").gap(6.0).center_y().child(ui::button( p, &format!("play-{index}"), "Play", false, move |app: &mut App| { app.review.seek(start); if let Some(player) = &app.review.player { player.play(); } }, )); if video.is_some() { actions = actions.child(ui::button( p, &format!("export-{index}"), "Export", false, move |app: &mut App| { let (tx, rx) = channel(); let Some(video) = video.clone() else { return }; let name = name.clone(); let audio = app.review.kept_tracks(); std::thread::spawn(move || { let result = crate::export::export_clip( &video, start, end, &name, true, "high", &audio, ); let _ = tx.send(result); }); app.review.export = Some(rx); app.review.export_note = Some("Exporting clip…".into()); }, )); } list = list.child( row() .key(format!("highlight-{index}")) .w_full() .h(44.0) .px(space::S3) .center_y() .justify_between() .radius(radius::MD) .hover(p.t.hover) .on_press({ let start = clip.start; move |app: &mut App| app.review.seek(start) }) .child( col() .key("labels") .gap(1.0) .child( row() .key("title-row") .gap(6.0) .center_y() .child(ui::dot(kind_ink)) .child( text(clip.title.clone()) .key("title") .font(type_::LABEL) .color(p.t.text), ) .child( text(format!( "{} to {}", format::clock(start), format::clock(end) )) .key("range") .font(type_::MONO_CAPTION) .color(p.muted()), ), ) .child( text(clip.subtitle.clone()) .key("subtitle") .font(body(11.0)) .color(p.muted()), ), ) .child(actions), ); } col() .key("highlights-panel") .w_full() .grow(1.0) .min_h(0.0) .gap(space::S2) .child( text("Highlights") .key("header") .font(type_::SECTION) .color(p.muted()), ) .child( app.highlights_scroll.follow( "highlight-scroller", col() .w_full() .grow(1.0) .min_h(0.0) .scroll(rune::ScrollSpec { stick_bottom: false, }) .child(list.pr(14.0)), ), ) } fn events(_app: &App, p: Paint, game: &Timeline) -> El { let interesting = |kind: &str| { matches!( kind, "kill" | "death" | "objective" | "game_start" | "game_end" | "lp_change" ) }; let mut list = col().key("event-rows").w_full().gap(1.0); let mut shown = 0; for event in game.events.iter().filter(|e| interesting(&e.event_type)) { let at = event.time(); let label = match event.event_type.as_str() { "kill" => "Kill", "death" => "Death", "objective" => "Objective", "game_start" => "Game start", "game_end" => "Game end", "lp_change" => "LP change", other => other, }; let detail = if event.description.is_empty() { label.to_string() } else { event.description.clone() }; list = list.child( row() .key(format!("event-{shown}")) .w_full() .h(30.0) .px(space::S2) .center_y() .gap(space::S2) .radius(radius::SM) .hover(p.t.hover) .on_press(move |app: &mut App| app.review.seek(at)) .child( text(format::clock(at)) .key("time") .font(type_::MONO_CAPTION) .color(p.muted()), ) .child( text(detail) .key("detail") .font(body(11.5)) .color(p.t.text) .grow(1.0) .shrink() .truncate(), ), ); shown += 1; } if shown == 0 { list = list.child( text("No timeline events.") .key("no-events") .font(body(12.0)) .color(p.muted()), ); } col() .key("events-panel") .w_full() .grow(1.5) .min_h(0.0) .gap(space::S2) .child( text("Timeline") .key("header") .font(type_::SECTION) .color(p.muted()), ) .child( _app.events_scroll.follow( "event-scroller", col() .w_full() .grow(1.0) .min_h(0.0) .scroll(rune::ScrollSpec { stick_bottom: false, }) .child(list.pr(14.0)), ), ) } #[cfg(test)] mod tests { use super::*; #[test] fn the_scrubber_shows_the_whole_file_without_a_clip() { let mut review = review(10.0, 20.0); review.clip = None; assert_eq!(review.shown(), (0.0, 100.0)); } #[test] fn a_clip_zooms_the_scrubber_around_it() { let review = review(40.0, 60.0); assert_eq!(review.shown(), (30.0, 70.0)); } #[test] fn the_window_stays_inside_the_recording() { assert_eq!(review(0.0, 20.0).shown(), (0.0, 40.0)); assert_eq!(review(80.0, 100.0).shown(), (60.0, 100.0)); for (start, end) in [(0.0, 20.0), (80.0, 100.0), (40.0, 60.0)] { let window = review(start, end).shown(); assert!( window.0 <= start && window.1 >= end, "{window:?} misses the clip" ); } } #[test] fn a_drag_past_the_bar_keeps_counting() { assert_eq!(time_at(0.0, 100.0, (10.0, 20.0)), 10.0); assert_eq!(time_at(50.0, 100.0, (10.0, 20.0)), 15.0); assert_eq!(time_at(150.0, 100.0, (10.0, 20.0)), 25.0); assert_eq!(time_at(-50.0, 100.0, (10.0, 20.0)), 5.0); } #[test] fn a_drag_holds_the_window_still() { let mut review = review(40.0, 60.0); review.frozen_window = Some((0.0, 100.0)); assert_eq!(review.shown(), (0.0, 100.0)); } fn review(start: f64, end: f64) -> Review { Review { duration: 100.0, clip: Some(Clip { start, end }), ..Review::default() } } #[test] fn an_arrow_moves_its_own_end() { let mut review = review(10.0, 20.0); review.drag_clip_end(true, 4.0); assert_eq!(review.clip.unwrap().start, 4.0); review.drag_clip_end(false, 30.0); assert_eq!(review.clip.unwrap().end, 30.0); } #[test] fn the_ends_keep_a_second_apart() { let mut review = review(10.0, 20.0); review.drag_clip_end(true, 50.0); assert_eq!(review.clip.unwrap().start, 19.0); review.drag_clip_end(false, 0.0); assert_eq!(review.clip.unwrap().end, 20.0); } #[test] fn the_end_stops_at_the_recording_end() { let mut review = review(10.0, 20.0); review.drag_clip_end(false, 500.0); assert_eq!(review.clip.unwrap().end, 100.0); review.drag_clip_end(true, 0.0); assert_eq!(review.clip.unwrap().start, 0.0); } }