use std::fs::{self, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use anyhow::{anyhow, bail, Context, Result}; use futures_util::StreamExt; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub(crate) enum FfmpegStatus { Ready, Missing, } pub(crate) fn bin_dir(app_dir: &Path) -> PathBuf { app_dir.join("bin") } pub(crate) fn ffmpeg_path(app_dir: &Path) -> PathBuf { bin_dir(app_dir).join("ffmpeg.exe") } pub(crate) fn check(app_dir: &Path) -> FfmpegStatus { if ffmpeg_path(app_dir).is_file() { FfmpegStatus::Ready } else { FfmpegStatus::Missing } } #[derive(Clone, Copy)] enum ArchiveKind { SevenZ, Zip, } struct Source { name: &'static str, release_api_url: &'static str, asset_name_suffix: &'static str, kind: ArchiveKind, /// Release download directory, used to fetch the sibling `.sha256`. None /// when the project publishes no checksums at all. download_base: Option<&'static str>, } // `releases/latest` rather than `releases/tags/latest` for both: the latter // only resolves for a repo that happens to have a tag literally named "latest", // which GyanD does not - its tag is the version, so that URL 404s. // // BtbN is first because its zip is the path that actually installs today; the // 7z branch below is the fallback. const SOURCES: &[Source] = &[ Source { name: "BtbN", release_api_url: "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/latest", asset_name_suffix: "win64-gpl.zip", kind: ArchiveKind::Zip, download_base: None, }, Source { name: "GyanD", release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/latest", asset_name_suffix: "full_build.7z", kind: ArchiveKind::SevenZ, download_base: Some("https://github.com/GyanD/codexffmpeg/releases/download"), }, ]; #[derive(Debug, Deserialize)] struct GithubRelease { tag_name: String, assets: Vec, } #[derive(Debug, Deserialize)] struct GithubAsset { name: String, browser_download_url: String, } pub(crate) async fn download(app_dir: &Path, mut on_progress: F) -> Result<()> where F: FnMut(u64, Option) + Send, { let bin = bin_dir(app_dir); fs::create_dir_all(&bin).context("creating ./bin/")?; let dest = bin.join("ffmpeg.exe"); let mut last_err: Option = None; for source in SOURCES { match try_source(source, &dest, &mut on_progress).await { Ok(()) => { tracing::info!("ffmpeg installed via {}", source.name); return Ok(()); } Err(e) => { tracing::warn!("source {} failed: {e:#}", source.name); last_err = Some(e); } } } Err(last_err.unwrap_or_else(|| anyhow!("no ffmpeg source succeeded"))) } async fn try_source(source: &Source, dest: &Path, on_progress: &mut F) -> Result<()> where F: FnMut(u64, Option), { let client = reqwest::Client::builder() .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .build()?; let (asset, version) = pick_asset(&client, source).await?; // Verify against the published checksum when there is one. GyanD used to // ship a .sha256 next to each asset and no longer does, so a missing // checksum downgrades to a logged warning rather than failing the source - // aborting on it would just push the user onto the unverified build anyway. let expected = if let Some(base) = source.download_base { let checksum_url = format!("{base}/{version}/{}.sha256", asset.name); match fetch_sha256(&client, &checksum_url).await { Ok(hash) => Some(hash), Err(e) => { tracing::warn!( "{} publishes no usable checksum for {} ({e:#}), continuing unverified", source.name, asset.name ); None } } } else { tracing::warn!( "{} publishes no checksums, downloading {} unverified", source.name, asset.name ); None }; let app_dir = dest .parent() .and_then(|p| p.parent()) .context("invalid dest path for temp archive")?; let scratch_dir = app_dir.join("temp"); fs::create_dir_all(&scratch_dir).context("creating temp dir for archive")?; let archive_path = scratch_dir.join(format!( "ffmpeg-archive-{}.tmp", source.name.to_lowercase() )); if let Some(ref hash) = expected { download_verified( &client, &asset.browser_download_url, hash, &archive_path, on_progress, ) .await .with_context(|| format!("downloading {}", asset.browser_download_url))?; } else { download_plain(&client, &asset.browser_download_url, &archive_path, on_progress) .await .with_context(|| format!("downloading {}", asset.browser_download_url))?; } let result = match source.kind { ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive_path, dest), ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive_path, dest), }; drop(fs::remove_file(&archive_path)); result } /// Fetch and parse a SHA-256 checksums file from `GyanD`. /// The file contains a line like: /// abc123def456... ffmpeg-8.1.1-full_build.7z async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> { let resp = client.get(url).send().await?.error_for_status()?; let text = resp.text().await?; // Each line is: " " - find the line with our filename let hash_str = text .lines() .find_map(|line| { let line = line.trim(); if line.is_empty() || line.starts_with('#') { return None; } // SHA-256 hex is 64 chars, followed by spaces and the filename if line.len() < 64 { return None; } let (hash, file) = line.split_at(64); let remainder = file.trim_start(); // Must be followed by two spaces and a filename if !remainder.starts_with(" ") { return None; } Some(hash) }) .ok_or_else(|| anyhow!("SHA-256 for this build not found in checksums file"))?; let bytes = hex::decode(hash_str).context("checksum is not valid hex")?; if bytes.len() != 32 { bail!("checksum length is {} bytes, expected 32", bytes.len()); } let mut sha = [0u8; 32]; sha.copy_from_slice(&bytes); Ok(sha) } async fn download_plain( client: &reqwest::Client, url: &str, dest: &Path, mut on_progress: F, ) -> Result<()> where F: FnMut(u64, Option), { let resp = client.get(url).send().await?.error_for_status()?; let total = resp.content_length(); let mut file = File::create(dest).context("creating archive temp file")?; let mut downloaded = 0u64; let mut stream = resp.bytes_stream(); while let Some(chunk) = stream.next().await { let chunk = chunk?; file.write_all(&chunk)?; downloaded += chunk.len() as u64; on_progress(downloaded, total); } file.flush()?; Ok(()) } async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> { let resp = client .get(source.release_api_url) .header("Accept", "application/vnd.github+json") .send() .await? .error_for_status()?; let body = resp.text().await?; let release: GithubRelease = serde_json::from_str(&body).context("parsing release metadata")?; let version = release .tag_name .trim_start_matches('v') .to_string(); let asset = release .assets .into_iter() .find(|a| a.name.ends_with(source.asset_name_suffix)) .ok_or_else(|| { anyhow!( "no asset matching '*{}' in release", source.asset_name_suffix ) })?; Ok((asset, version)) } async fn download_verified( client: &reqwest::Client, url: &str, expected: &[u8; 32], dest: &Path, on_progress: &mut F, ) -> Result<()> where F: FnMut(u64, Option), { let resp = client.get(url).send().await?.error_for_status()?; let total = resp.content_length(); let mut hasher = Sha256::new(); let mut file = File::create(dest).context("creating archive temp file")?; let mut downloaded = 0u64; let mut stream = resp.bytes_stream(); while let Some(chunk) = stream.next().await { let chunk = chunk?; hasher.update(&chunk); file.write_all(&chunk)?; downloaded += chunk.len() as u64; on_progress(downloaded, total); } file.flush()?; let got: [u8; 32] = hasher.finalize().into(); if &got != expected { drop(fs::remove_file(dest)); bail!( "sha256 mismatch: expected {} got {}", hex::encode(expected), hex::encode(got) ); } Ok(()) } fn is_ffmpeg_entry(name: &str) -> bool { let normalized: String = name .chars() .map(|c| if c == '\\' { '/' } else { c }) .collect(); normalized .rsplit('/') .next() .is_some_and(|leaf| leaf.eq_ignore_ascii_case("ffmpeg.exe")) } /// Removes a scratch directory on drop so extraction failures don't leave an /// unpacked ffmpeg build sitting in temp/. struct DirGuard(PathBuf); impl Drop for DirGuard { fn drop(&mut self) { drop(fs::remove_dir_all(&self.0)); } } fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> { let app_dir = dest .parent() .and_then(|p| p.parent()) .context("invalid dest path")?; let scratch = app_dir.join("temp").join("ffmpeg-extract"); drop(fs::remove_dir_all(&scratch)); fs::create_dir_all(&scratch).context("create 7z scratch dir")?; // Removes the extracted tree on every exit path, including the extraction // failure below - the older unconditional remove sat before the `?`, so a // failed extract left the whole unpacked build behind in temp/. let _guard = DirGuard(scratch.clone()); let file = File::open(archive_path).context("opening 7z archive")?; let extract_result = sevenz_rust2::decompress_with_extract_fn(file, &scratch, |_, _, _| Ok(true)) .map_err(|e| anyhow!("7z extraction failed: {e}")); let found = find_ffmpeg_in(&scratch); extract_result?; let Some(src) = found else { bail!("ffmpeg.exe not found inside the 7z archive"); }; fs::copy(&src, dest).context("write ffmpeg.exe from 7z")?; Ok(()) } fn find_ffmpeg_in(dir: &Path) -> Option { let entries = fs::read_dir(dir).ok()?; for e in entries.flatten() { let p = e.path(); if p.is_dir() { if let Some(found) = find_ffmpeg_in(&p) { return Some(found); } } else if let Some(name) = p.file_name() { if is_ffmpeg_entry(&name.to_string_lossy()) { return Some(p); } } else { // Neither a directory nor a named file, so nothing to look inside. } } None } fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> { let file = File::open(archive_path).context("opening zip archive")?; let mut zip = zip::ZipArchive::new(file).context("open zip archive")?; for i in 0..zip.len() { let mut entry = zip.by_index(i)?; if entry.is_dir() { continue; } let name = entry.name().to_string(); if is_ffmpeg_entry(&name) { let mut out = File::create(dest).context("create ffmpeg.exe")?; io::copy(&mut entry, &mut out).context("write ffmpeg.exe from zip")?; return Ok(()); } } bail!("ffmpeg.exe not found inside the zip archive"); } #[cfg(test)] mod tests { use super::*; /// Stands in for the body of extract_ffmpeg_from_7z: it builds a scratch /// directory, arms the guard, then leaves through the `?` the way a failed /// extraction does. fn fails_with_guard_alive(scratch: &Path) -> Result<()> { fs::create_dir_all(scratch).context("create scratch")?; let _guard = DirGuard(scratch.to_path_buf()); fs::write(scratch.join("ffmpeg.exe"), b"x").context("write payload")?; bail!("deliberate extraction failure") } /// The scratch tree used to be removed only on the success path, so a failed /// bootstrap left the whole unpacked ffmpeg build sitting in temp/. #[test] fn dir_guard_removes_scratch_even_on_early_exit() { let dir = std::env::temp_dir().join(format!("bytesize-guard-test-{}", std::process::id())); let scratch = dir.join("temp").join("ffmpeg-extract"); drop(fs::remove_dir_all(&dir)); assert!(fails_with_guard_alive(&scratch).is_err()); assert!( !scratch.exists(), "scratch dir should be gone after the error return" ); drop(fs::remove_dir_all(&dir)); } }