Files
leaguerecorder/app/src/export.rs
T
vhaudiquet 297118cfc1
record-daemon / Build, check and test (push) Failing after 1m15s
app: download ffmpeg on the first run, not the first export
Clip export needs ffmpeg, and the app fetched it when an export was
asked for: a minute of nothing at the worst moment, with the export
sitting behind it. The run that follows an install now fetches it in
the background and narrates the download in the notice banner; the
notice is updated in place and leaves another notice alone. A hidden
start (the login item) skips the fetch and leaves it to the export.

Only ffmpeg.exe is unpacked. The archive also carries ffplay and
ffprobe, which the export paths never call: unpacking all three put
370 MB beside the exe instead of 105 MB.

An export asked for while the download runs says so instead of
starting a second download over the same directory, and --fetch-ffmpeg
runs the same fetch from a shell, printing progress.

Checked on this machine: --fetch-ffmpeg downloaded in about 20 s,
unpacked, and answered "ready"; a second run returned at once.
2026-11-19 22:23:08 +01:00

282 lines
8.9 KiB
Rust

//! 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::sync::atomic::{AtomicBool, Ordering};
use ffmpeg_sidecar::command::{FfmpegCommand, ffmpeg_is_installed};
use ffmpeg_sidecar::download::{
FfmpegDownloadProgressEvent, download_ffmpeg_package_with_progress, ffmpeg_download_url,
unpack_ffmpeg_without_extras,
};
use ffmpeg_sidecar::event::{FfmpegEvent, LogLevel};
use ffmpeg_sidecar::paths::{sidecar_dir, sidecar_path};
use crate::daemon;
/// The clips folder beside the recordings.
pub fn clips_dir() -> PathBuf {
let dir = daemon::recordings_dir().join("clips");
let _ = std::fs::create_dir_all(&dir);
dir
}
/// Set while `fetch` runs, so an export during the download does not start a second one that
/// unpacks over the first.
static FETCHING: AtomicBool = AtomicBool::new(false);
/// What `fetch` reports while it runs.
pub enum FetchEvent {
/// Bytes of the download so far, of the total the server announced.
Bytes { done: u64, total: u64 },
/// The archive is complete and being unpacked beside the exe.
Unpacking,
/// The work is over, with its outcome.
Finished(Result<(), String>),
}
/// Whether ffmpeg still has to be downloaded: it lives beside the exe. The presence of the file
/// is enough here; `ffmpeg -version` is left to the export that needs it.
pub fn missing() -> bool {
sidecar_path().map(|path| !path.exists()).unwrap_or(true)
}
/// Whether a download is running right now.
pub fn fetching() -> bool {
FETCHING.load(Ordering::SeqCst)
}
/// Download ffmpeg beside the exe, reporting progress. Blocks: call it on a thread.
///
/// Only `ffmpeg.exe` is unpacked. The archive carries `ffplay` and `ffprobe` too, and the
/// export paths call neither; unpacking all three would add 200 MB to every install.
pub fn fetch(report: impl Fn(FetchEvent)) -> Result<(), String> {
if ffmpeg_is_installed() {
return Ok(());
}
FETCHING.store(true, Ordering::SeqCst);
let result = download(&report);
FETCHING.store(false, Ordering::SeqCst);
report(FetchEvent::Finished(result.clone()));
result
}
fn download(report: &impl Fn(FetchEvent)) -> Result<(), String> {
let url = ffmpeg_download_url().map_err(|e| format!("cannot find a build to download: {e}"))?;
let dir = sidecar_dir().map_err(|e| format!("cannot find where to put ffmpeg: {e}"))?;
let archive = download_ffmpeg_package_with_progress(url, &dir, |event| {
if let FfmpegDownloadProgressEvent::Downloading {
total_bytes,
downloaded_bytes,
} = event
{
report(FetchEvent::Bytes {
done: downloaded_bytes,
total: total_bytes,
});
}
})
.map_err(|e| format!("cannot download ffmpeg: {e}"))?;
report(FetchEvent::Unpacking);
unpack_ffmpeg_without_extras(&archive, &dir)
.map_err(|e| format!("cannot unpack ffmpeg: {e}"))?;
if !ffmpeg_is_installed() {
return Err("ffmpeg did not end up beside the app".to_string());
}
Ok(())
}
/// Download the ffmpeg sidecar on first use.
pub fn ensure_ffmpeg() -> Result<(), String> {
if ffmpeg_is_installed() {
return Ok(());
}
if fetching() {
return Err("ffmpeg is still downloading; try the export again in a moment".to_string());
}
fetch(|_| {})
}
/// Export `start..end` of `video`. Stream copy is fast and keyframe-aligned; `precise` re-encodes
/// with x264 for exact cuts. `audio` names the audio streams the clip keeps, empty for all of
/// them as they are.
pub fn export_clip(
video: &str,
start: f64,
end: f64,
output_name: &str,
precise: bool,
quality: &str,
audio: &[usize],
) -> Result<String, String> {
ensure_ffmpeg()?;
if !PathBuf::from(video).exists() {
return Err(format!("video file not found: {video}"));
}
let output = clips_dir().join(format!("{}.mp4", sanitize(output_name)));
let duration = (end - start).max(0.0);
if duration <= 0.0 {
return Err("the clip has no length".into());
}
let mut command = FfmpegCommand::new();
command
.arg("-y")
.arg("-ss")
.arg(format!("{start:.3}"))
.arg("-i")
.arg(video)
.arg("-t")
.arg(format!("{duration:.3}"));
// Which tracks the clip keeps. One track is mapped whole; several are mixed into a single
// stereo track, because a clip is meant to be played, not to carry a track picker.
let kept: Vec<String> = audio
.iter()
.map(|stream| format!("[0:a:{stream}]"))
.collect();
if kept.len() > 1 {
command
.arg("-filter_complex")
.arg(format!(
"{}amix=inputs={}:normalize=0[out]",
kept.concat(),
kept.len()
))
.arg("-map")
.arg("0:v")
.arg("-map")
.arg("[out]")
.arg("-c:a")
.arg("aac")
.arg("-b:a")
.arg("160k");
} else if let Some(stream) = audio.first() {
command
.arg("-map")
.arg("0:v")
.arg("-map")
.arg(format!("0:a:{stream}"));
}
if precise || kept.len() > 1 {
let crf = match quality {
"low" => "28",
"high" => "18",
_ => "23",
};
command
.arg("-c:v")
.arg("libx264")
.arg("-crf")
.arg(crf)
.arg("-preset")
.arg("fast")
.arg("-c:a")
.arg("aac")
.arg("-b:a")
.arg("128k");
} else {
command
.arg("-c")
.arg("copy")
.arg("-avoid_negative_ts")
.arg("make_zero");
}
let iter = command
.arg(output.to_string_lossy().to_string())
.spawn()
.map_err(|e| format!("cannot start ffmpeg: {e}"))?
.iter()
.map_err(|e| format!("cannot read ffmpeg output: {e}"))?;
let mut errors = Vec::new();
for event in iter {
match event {
FfmpegEvent::Error(e) => errors.push(e),
FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg),
_ => {}
}
}
let size = std::fs::metadata(&output).map(|m| m.len()).unwrap_or(0);
if size == 0 {
return Err(if errors.is_empty() {
"ffmpeg produced no output".to_string()
} else {
errors.join("; ")
});
}
Ok(output.display().to_string())
}
/// Copy each audio track of `video` into a file of its own, so a player can be opened per
/// 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> {
ensure_ffmpeg()?;
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)
.and_then(|m| m.modified())
.map_err(|e| format!("cannot read {video}: {e}"))?;
let mut paths = Vec::new();
for track in 0..count {
let path = dir.join(format!("track-{track}.m4a"));
let fresh = std::fs::metadata(&path)
.and_then(|m| m.modified())
.map(|time| time >= 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("; ")
});
}
}
paths.push(path);
}
Ok(paths)
}
fn sanitize(name: &str) -> String {
name.chars()
.map(|c| {
if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'_'
}
})
.collect()
}