use crate::{archive, model::*, playback, reports}; use anyhow::{Context, Result}; use std::{ collections::BTreeSet, fs::{self, File}, path::{Path, PathBuf}, process::{Command, Stdio}, sync::atomic::{AtomicBool, Ordering}, time::{Duration, Instant}, }; #[derive(Clone, Debug)] pub struct Event { pub message: String, pub done: usize, pub total: usize, pub warning: bool, pub path: Option, } impl Event { pub fn step(message: impl Into, done: usize, total: usize) -> Self { Self { message: message.into(), done, total, warning: false, path: None, } } } #[derive(Default, Debug)] pub struct Outcome { pub report: Option, pub paths: Vec, pub output: PathBuf, } pub fn cancelled(cancel: &AtomicBool) -> Result<()> { anyhow::ensure!(!cancel.load(Ordering::Relaxed), "Cancelled."); Ok(()) } pub fn find_ffprobe(override_path: Option<&Path>) -> Result { if let Some(path) = override_path { anyhow::ensure!(path.is_file(), "FFprobe not found: {}", path.display()); return Ok(path.to_owned()); } let name = if cfg!(windows) { "ffprobe.exe" } else { "ffprobe" }; let mut dirs = vec![]; if let Ok(exe) = std::env::current_exe() && let Some(dir) = exe.parent() { dirs.extend([dir.to_owned(), dir.join("bin")]); } if let Some(path) = std::env::var_os("PATH") { dirs.extend(std::env::split_paths(&path)); } dirs.into_iter().map(|d| d.join(name)).find(|p| p.is_file()) .context("FFprobe is required for timings. Put ffprobe.exe beside this app on Windows, install FFmpeg, or choose extraction only.") } pub fn probe_json(bytes: &[u8]) -> (Option, String, String) { let unknown = (None, "Unknown".into(), "Unknown".into()); let Ok(v) = serde_json::from_slice::(bytes) else { return unknown; }; let duration = v["format"]["duration"] .as_str() .and_then(|s| s.parse::().ok()) .or_else(|| v["format"]["duration"].as_f64()) .filter(|d| d.is_finite() && *d >= 0.0); let stream = v["streams"] .as_array() .and_then(|a| a.iter().find(|s| s["codec_type"] == "video")); let resolution = stream .and_then(|s| Some((s["width"].as_u64()?, s["height"].as_u64()?))) .filter(|(w, h)| *w > 0 && *h > 0) .map(|(w, h)| format!("{w}×{h}")) .unwrap_or("Unknown".into()); ( duration, resolution, stream .and_then(|s| s["codec_name"].as_str()) .unwrap_or("Unknown") .into(), ) } pub fn probe( exe: &Path, path: &Path, cancel: &AtomicBool, ) -> Result<(Option, String, String)> { let output = tempfile::NamedTempFile::new()?; let mut command = Command::new(exe); command .args([ "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height,codec_name", "-of", "json", ]) .arg(path) .stdout(Stdio::from(output.reopen()?)) .stderr(Stdio::null()); #[cfg(windows)] { use std::os::windows::process::CommandExt; command.creation_flags(0x08000000); // CREATE_NO_WINDOW } let Ok(mut child) = command.spawn() else { return Ok(probe_json(b"")); }; let start = Instant::now(); loop { if cancel.load(Ordering::Relaxed) || start.elapsed() > Duration::from_secs(120) { let _ = child.kill(); let _ = child.wait(); cancelled(cancel)?; return Ok(probe_json(b"")); } if let Some(exit) = child.try_wait()? { return Ok(if exit.success() { probe_json(&fs::read(output.path())?) } else { probe_json(b"") }); } std::thread::sleep(Duration::from_millis(50)); } } pub fn assemble(source: &Path, mut videos: Vec