From 1d7f87f71de481d2c7466e67a7d4be56801e66ca Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Thu, 19 Nov 2026 23:20:17 +0100 Subject: [PATCH] app: cut a recording's audio tracks off the UI thread The first open of a multi-track recording re-encoded every track on the main thread, so the channels could be muted apart. On a 27 minute clip that is 12.8 s per track, about a minute of a window Windows marks as not responding, which is what made a game look ready to crash the first time it was opened. The files are cached, so only that first open paid it. The cut now runs on a thread, and `tick` opens the channel players when the files land, at the playhead's time and playing state. Each track is copied instead of re-encoded, which takes 0.4 s on the same clip, and the AAC encode stays as a fallback for a codec an m4a cannot hold. A mutex keeps two cuts from writing the same cache file when a row is reopened while its first cut is still running. --- app/src/export.rs | 88 ++++++++++++++++----------- app/src/screens/review.rs | 121 ++++++++++++++++++++++++++++++++------ 2 files changed, 156 insertions(+), 53 deletions(-) diff --git a/app/src/export.rs b/app/src/export.rs index b93cdec..6aa000e 100644 --- a/app/src/export.rs +++ b/app/src/export.rs @@ -1,7 +1,8 @@ //! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in //! `tauri-app/src-tauri/src/lib.rs`. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; use ffmpeg_sidecar::command::{FfmpegCommand, ffmpeg_is_installed}; @@ -25,6 +26,10 @@ pub fn clips_dir() -> PathBuf { /// unpacks over the first. static FETCHING: AtomicBool = AtomicBool::new(false); +/// One cut at a time. Reopening a row while its tracks are still being cut would otherwise +/// have two ffmpeg processes writing the same cache file. +static CUTTING: Mutex<()> = Mutex::new(()); + /// What `fetch` reports while it runs. pub enum FetchEvent { /// Bytes of the download so far, of the total the server announced. @@ -214,6 +219,7 @@ pub fn export_clip( /// track. Files are kept between sessions; a track older than the clip is cut again. pub fn extract_tracks(video: &str, stem: &str, count: usize) -> Result, String> { ensure_ffmpeg()?; + let _cutting = CUTTING.lock().unwrap_or_else(|e| e.into_inner()); let dir = crate::daemon::audio_cache_dir().join(sanitize(stem)); std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; let clip_time = std::fs::metadata(video) @@ -228,46 +234,58 @@ pub fn extract_tracks(video: &str, stem: &str, count: usize) -> Result= clip_time) .unwrap_or(false); if !fresh { - let mut command = FfmpegCommand::new(); - command - .arg("-y") - .arg("-i") - .arg(video) - .arg("-map") - .arg(format!("0:a:{track}")) - .arg("-vn") - .arg("-c:a") - .arg("aac") - .arg("-b:a") - .arg("160k") - .arg(path.to_string_lossy().to_string()); - let mut errors = Vec::new(); - for event in command - .spawn() - .map_err(|e| format!("cannot start ffmpeg: {e}"))? - .iter() - .map_err(|e| format!("cannot read ffmpeg output: {e}"))? - { - match event { - FfmpegEvent::Error(e) => errors.push(e), - FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg), - _ => {} - } - } - let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); - if size == 0 { - return Err(if errors.is_empty() { - format!("audio track {track} came out empty") - } else { - errors.join("; ") - }); - } + // The stream copy takes seconds where re-encoding takes minutes; a track whose + // codec an m4a cannot hold is cut again as AAC. + cut_track(video, track, &path, true) + .or_else(|_| cut_track(video, track, &path, false))?; } paths.push(path); } Ok(paths) } +/// Cut `track` out of `video` into `path`, keeping the stream as it is (`copy`) or re-encoding +/// it as AAC. +fn cut_track(video: &str, track: usize, path: &Path, copy: bool) -> Result<(), String> { + let mut command = FfmpegCommand::new(); + command + .arg("-y") + .arg("-i") + .arg(video) + .arg("-map") + .arg(format!("0:a:{track}")) + .arg("-vn"); + if copy { + command.arg("-c:a").arg("copy"); + } else { + command.arg("-c:a").arg("aac").arg("-b:a").arg("160k"); + } + command.arg(path.to_string_lossy().to_string()); + + let mut errors = Vec::new(); + for event in command + .spawn() + .map_err(|e| format!("cannot start ffmpeg: {e}"))? + .iter() + .map_err(|e| format!("cannot read ffmpeg output: {e}"))? + { + match event { + FfmpegEvent::Error(e) => errors.push(e), + FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg), + _ => {} + } + } + let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0); + if size == 0 { + return Err(if errors.is_empty() { + format!("audio track {track} came out empty") + } else { + errors.join("; ") + }); + } + Ok(()) +} + fn sanitize(name: &str) -> String { name.chars() .map(|c| { diff --git a/app/src/screens/review.rs b/app/src/screens/review.rs index 9fcbed5..360b1c2 100644 --- a/app/src/screens/review.rs +++ b/app/src/screens/review.rs @@ -1,6 +1,6 @@ //! Game review: the recorded clip, a scrubber with event markers, highlights and export. -use std::sync::mpsc::{Receiver, channel}; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; use rune::tok::{radius, space, type_}; use rune::{El, Player, SurfaceFit, Tx, col, el, row, text}; @@ -20,6 +20,11 @@ pub struct Review { 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, @@ -91,15 +96,15 @@ impl Review { .collect() } - /// Start the soundtrack's players, at the place the viewer is watching. + /// 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 - .game - .as_ref() - .map(|game| game.audio_tracks.clone()) - .unwrap_or_default(); + 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. @@ -111,6 +116,67 @@ impl Review { 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() @@ -121,16 +187,16 @@ impl Review { .map(|name| name.to_string_lossy().to_string()) }) .unwrap_or_default(); - let stem = stem.rsplit_once('.').map(|(name, _)| name).unwrap_or(&stem); - let files = match crate::export::extract_tracks(path, stem, labels.len()) { - Ok(files) => files, - Err(e) => { - self.channel_error = Some(e); - return; - } - }; + 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() { - // A track no source fed is silent in the file; it gets no toggle. let Some(label) = labels.get(stream).filter(|label| !label.trim().is_empty()) else { continue; }; @@ -286,6 +352,8 @@ impl Default for Review { loading: false, player: None, sounds: Vec::new(), + sound_rx: None, + sound_tried: false, steady_at: 0.0, time: 0.0, duration: 0.0, @@ -353,8 +421,21 @@ pub fn show(app: &mut App, game: Timeline) { } 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 @@ -363,7 +444,7 @@ fn follow_sound(app: &mut App) { let Some(player) = &app.review.player else { return; }; - if !app.review.sounds.is_empty() || player.has_sound() != Some(true) { + if app.review.sound_tried || player.has_sound() != Some(true) { return; } let Some(path) = app @@ -374,7 +455,7 @@ fn follow_sound(app: &mut App) { else { return; }; - app.review.open_sound(&path.to_string_lossy()); + app.review.request_sound(&path.to_string_lossy()); } /// Leave the review screen and stop playback. @@ -385,6 +466,9 @@ pub fn leave(app: &mut App) { 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; @@ -451,6 +535,7 @@ pub fn tick(app: &mut App, tx: &mut Tx) -> bool { } } 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.