//! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in //! the old Tauri app's `lib.rs`. use std::path::{Path, PathBuf}; use std::sync::Mutex; 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 std::time::SystemTime; use crate::daemon; /// A clip the user exported: one file in the clips folder. #[derive(Debug, Clone)] pub struct Clip { /// The file's name without `.mp4`, as the export named it: often `{recording}-clip`. pub name: String, /// The file, for playing it and for deleting it. pub path: PathBuf, /// When the export finished: the file's modified time. pub exported: Option, /// Bytes on disk. pub bytes: u64, /// The miniature cut from the video, when one is on disk and as new as the clip. pub thumb: Option, /// The recording the clip was cut from, from the file a rename leaves beside it. A clip /// still named as it was exported carries the id in its name instead. pub recording_id: Option, } /// 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 { 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 { 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 /// where a half-finished export writes too, and a clip without its pictures is no clip. pub fn list_clips() -> Vec { let Ok(entries) = std::fs::read_dir(clips_dir()) else { return Vec::new(); }; let mut clips: Vec = entries .flatten() .filter_map(|entry| { let path = entry.path(); if path.extension().and_then(|ext| ext.to_str()) != Some("mp4") { return None; } let meta = entry.metadata().ok()?; let mut clip = Clip { name: path.file_stem()?.to_string_lossy().into_owned(), path: path.clone(), exported: meta.modified().ok(), bytes: meta.len(), thumb: None, recording_id: recording_link(&path), }; clip.thumb = thumb_of(&clip); Some(clip) }) .collect(); clips.sort_by_key(|clip| std::cmp::Reverse(clip.exported)); clips } /// The file beside a clip that names the recording it was cut from. /// /// The export writes the recording's id into the clip's name, and the name is the user's to /// change. A clip renamed in the app carries this file instead, so a screen that leads back to /// the game still finds it. pub fn link_path(clip: &Path) -> PathBuf { clip.with_extension("json") } /// Name the recording beside `clip`. True when the file landed. pub fn link_recording(clip: &Path, recording_id: &str) -> bool { let text = serde_json::json!({ "recording_id": recording_id }).to_string(); std::fs::write(link_path(clip), text).is_ok() } /// The recording `clip`'s link file names, when one sits beside it. pub fn recording_link(clip: &Path) -> Option { let text = std::fs::read_to_string(link_path(clip)).ok()?; let value: serde_json::Value = serde_json::from_str(&text).ok()?; value.get("recording_id")?.as_str().map(str::to_string) } /// 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); /// 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. 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 { 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 = 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, 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) .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 { // 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| { if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') { c } else { '_' } }) .collect() } #[cfg(test)] mod tests { use super::{link_path, link_recording, recording_link}; use std::path::Path; #[test] fn a_link_file_names_the_recording_beside_its_clip() { let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&dir).unwrap(); let clip = dir.join("My Ace.mp4"); std::fs::write(&clip, b"").unwrap(); assert_eq!(link_path(&clip), Path::new(&dir).join("My Ace.json")); assert_eq!(recording_link(&clip), None); assert!(link_recording(&clip, "demo-1")); assert_eq!(recording_link(&clip).as_deref(), Some("demo-1")); let _ = std::fs::remove_dir_all(&dir); } }