//! 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 { 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 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() }