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.
This commit is contained in:
1 parent
9f6a047867
commit
1d7f87f71d
2 files changed
+156
-53
No files matched your search
+53
-35
@@ -1,7 +1,8 @@
|
|||||||
//! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in
|
//! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in
|
||||||
//! `tauri-app/src-tauri/src/lib.rs`.
|
//! `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 std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
use ffmpeg_sidecar::command::{FfmpegCommand, ffmpeg_is_installed};
|
use ffmpeg_sidecar::command::{FfmpegCommand, ffmpeg_is_installed};
|
||||||
@@ -25,6 +26,10 @@ pub fn clips_dir() -> PathBuf {
|
|||||||
/// unpacks over the first.
|
/// unpacks over the first.
|
||||||
static FETCHING: AtomicBool = AtomicBool::new(false);
|
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.
|
/// What `fetch` reports while it runs.
|
||||||
pub enum FetchEvent {
|
pub enum FetchEvent {
|
||||||
/// Bytes of the download so far, of the total the server announced.
|
/// 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.
|
/// 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<Vec<PathBuf>, String> {
|
pub fn extract_tracks(video: &str, stem: &str, count: usize) -> Result<Vec<PathBuf>, String> {
|
||||||
ensure_ffmpeg()?;
|
ensure_ffmpeg()?;
|
||||||
|
let _cutting = CUTTING.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
let dir = crate::daemon::audio_cache_dir().join(sanitize(stem));
|
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()))?;
|
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||||
let clip_time = std::fs::metadata(video)
|
let clip_time = std::fs::metadata(video)
|
||||||
@@ -228,46 +234,58 @@ pub fn extract_tracks(video: &str, stem: &str, count: usize) -> Result<Vec<PathB
|
|||||||
.map(|time| time >= clip_time)
|
.map(|time| time >= clip_time)
|
||||||
.unwrap_or(false);
|
.unwrap_or(false);
|
||||||
if !fresh {
|
if !fresh {
|
||||||
let mut command = FfmpegCommand::new();
|
// The stream copy takes seconds where re-encoding takes minutes; a track whose
|
||||||
command
|
// codec an m4a cannot hold is cut again as AAC.
|
||||||
.arg("-y")
|
cut_track(video, track, &path, true)
|
||||||
.arg("-i")
|
.or_else(|_| cut_track(video, track, &path, false))?;
|
||||||
.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("; ")
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
paths.push(path);
|
paths.push(path);
|
||||||
}
|
}
|
||||||
Ok(paths)
|
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 {
|
fn sanitize(name: &str) -> String {
|
||||||
name.chars()
|
name.chars()
|
||||||
.map(|c| {
|
.map(|c| {
|
||||||
|
|||||||
+103
-18
@@ -1,6 +1,6 @@
|
|||||||
//! Game review: the recorded clip, a scrubber with event markers, highlights and export.
|
//! 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::tok::{radius, space, type_};
|
||||||
use rune::{El, Player, SurfaceFit, Tx, col, el, row, text};
|
use rune::{El, Player, SurfaceFit, Tx, col, el, row, text};
|
||||||
@@ -20,6 +20,11 @@ pub struct Review {
|
|||||||
pub player: Option<Player>,
|
pub player: Option<Player>,
|
||||||
/// The clip's audio tracks, one player each, so the channels are heard apart.
|
/// The clip's audio tracks, one player each, so the channels are heard apart.
|
||||||
pub sounds: Vec<Channel>,
|
pub sounds: Vec<Channel>,
|
||||||
|
/// 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<Receiver<Result<Vec<std::path::PathBuf>, 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.
|
/// The picture time the soundtrack was last put back to, to spot a window that stopped drawing.
|
||||||
steady_at: f64,
|
steady_at: f64,
|
||||||
pub time: f64,
|
pub time: f64,
|
||||||
@@ -91,15 +96,15 @@ impl Review {
|
|||||||
.collect()
|
.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) {
|
pub fn open_sound(&mut self, path: &str) {
|
||||||
|
self.sound_tried = true;
|
||||||
self.sounds.clear();
|
self.sounds.clear();
|
||||||
self.channel_error = None;
|
self.channel_error = None;
|
||||||
let labels = self
|
let labels = self.track_labels();
|
||||||
.game
|
|
||||||
.as_ref()
|
|
||||||
.map(|game| game.audio_tracks.clone())
|
|
||||||
.unwrap_or_default();
|
|
||||||
if labels.len() < 2 {
|
if labels.len() < 2 {
|
||||||
// One track, or a recording made before the recorder split them: the file's own
|
// 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.
|
// sound is the whole mix, and an audio player reads it as it is.
|
||||||
@@ -111,6 +116,67 @@ impl Review {
|
|||||||
self.sounds.push(channel);
|
self.sounds.push(channel);
|
||||||
return;
|
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<String> {
|
||||||
|
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
|
let stem = self
|
||||||
.game
|
.game
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -121,16 +187,16 @@ impl Review {
|
|||||||
.map(|name| name.to_string_lossy().to_string())
|
.map(|name| name.to_string_lossy().to_string())
|
||||||
})
|
})
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let stem = stem.rsplit_once('.').map(|(name, _)| name).unwrap_or(&stem);
|
stem.rsplit_once('.')
|
||||||
let files = match crate::export::extract_tracks(path, stem, labels.len()) {
|
.map(|(name, _)| name)
|
||||||
Ok(files) => files,
|
.unwrap_or(&stem)
|
||||||
Err(e) => {
|
.to_string()
|
||||||
self.channel_error = Some(e);
|
}
|
||||||
return;
|
|
||||||
}
|
/// 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() {
|
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 {
|
let Some(label) = labels.get(stream).filter(|label| !label.trim().is_empty()) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -286,6 +352,8 @@ impl Default for Review {
|
|||||||
loading: false,
|
loading: false,
|
||||||
player: None,
|
player: None,
|
||||||
sounds: Vec::new(),
|
sounds: Vec::new(),
|
||||||
|
sound_rx: None,
|
||||||
|
sound_tried: false,
|
||||||
steady_at: 0.0,
|
steady_at: 0.0,
|
||||||
time: 0.0,
|
time: 0.0,
|
||||||
duration: 0.0,
|
duration: 0.0,
|
||||||
@@ -353,8 +421,21 @@ pub fn show(app: &mut App, game: Timeline) {
|
|||||||
}
|
}
|
||||||
app.review.player = Some(player);
|
app.review.player = Some(player);
|
||||||
app.review.sounds.clear();
|
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;
|
app.review.steady_at = 0.0;
|
||||||
Review::mute_video(app.review.player.as_ref().expect("just set"));
|
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
|
/// 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 {
|
let Some(player) = &app.review.player else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
if !app.review.sounds.is_empty() || player.has_sound() != Some(true) {
|
if app.review.sound_tried || player.has_sound() != Some(true) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let Some(path) = app
|
let Some(path) = app
|
||||||
@@ -374,7 +455,7 @@ fn follow_sound(app: &mut App) {
|
|||||||
else {
|
else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
app.review.open_sound(&path.to_string_lossy());
|
app.review.request_sound(&path.to_string_lossy());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Leave the review screen and stop playback.
|
/// Leave the review screen and stop playback.
|
||||||
@@ -385,6 +466,9 @@ pub fn leave(app: &mut App) {
|
|||||||
app.review.frozen_window = None;
|
app.review.frozen_window = None;
|
||||||
app.review.player = None;
|
app.review.player = None;
|
||||||
app.review.sounds.clear();
|
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.game = None;
|
||||||
app.review.highlights.clear();
|
app.review.highlights.clear();
|
||||||
app.review.time = 0.0;
|
app.review.time = 0.0;
|
||||||
@@ -451,6 +535,7 @@ pub fn tick(app: &mut App, tx: &mut Tx) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
follow_sound(app);
|
follow_sound(app);
|
||||||
|
app.review.settle_sound();
|
||||||
keep_in_step(app);
|
keep_in_step(app);
|
||||||
// A clip preview stops where the clip does: the selection is what is being watched. A play
|
// 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.
|
// that started at or past the end previews nothing, so it runs on rather than freezing.
|
||||||
|
|||||||
Reference in new issue
Block a user