config and ffmpeg bootstrap

This commit is contained in:
2026-05-11 23:48:23 +03:00
parent 472aa6f9ec
commit c64ec2045e
15 changed files with 8710 additions and 68 deletions
+211 -1
View File
@@ -1 +1,211 @@
// first-run ffmpeg download, sha256 verification, extraction into ./bin/
use std::fs::{self, File};
use std::io::{self, Cursor};
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, Context, Result};
use futures_util::StreamExt;
use serde::Serialize;
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FfmpegStatus {
Ready,
Missing,
}
pub fn bin_dir(app_dir: &Path) -> PathBuf {
app_dir.join("bin")
}
pub fn ffmpeg_path(app_dir: &Path) -> PathBuf {
bin_dir(app_dir).join("ffmpeg.exe")
}
pub fn check(app_dir: &Path) -> FfmpegStatus {
if ffmpeg_path(app_dir).is_file() {
FfmpegStatus::Ready
} else {
FfmpegStatus::Missing
}
}
enum ArchiveKind {
SevenZ,
Zip,
}
struct Source {
name: &'static str,
archive_url: &'static str,
checksum_url: &'static str,
kind: ArchiveKind,
}
const SOURCES: &[Source] = &[
Source {
name: "GyanD",
archive_url: "https://github.com/GyanD/codexffmpeg/releases/download/8.1.1/ffmpeg-8.1.1-essentials_build.7z",
checksum_url: "https://github.com/GyanD/codexffmpeg/releases/download/8.1.1/ffmpeg-8.1.1-essentials_build.7z.sha256",
kind: ArchiveKind::SevenZ,
},
Source {
name: "BtbN",
archive_url: "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip",
checksum_url: "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip.sha256",
kind: ArchiveKind::Zip,
},
];
pub async fn download<F>(app_dir: &Path, mut on_progress: F) -> Result<()>
where
F: FnMut(u64, Option<u64>) + 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<anyhow::Error> = 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<F>(source: &Source, dest: &Path, on_progress: &mut F) -> Result<()>
where
F: FnMut(u64, Option<u64>),
{
let client = reqwest::Client::builder()
.user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
.build()?;
let expected = fetch_sha256(&client, source.checksum_url)
.await
.with_context(|| format!("fetching checksum from {}", source.checksum_url))?;
let archive = download_verified(&client, source.archive_url, &expected, on_progress)
.await
.with_context(|| format!("downloading archive from {}", source.archive_url))?;
match source.kind {
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?,
ArchiveKind::Zip => extract_ffmpeg_from_zip(&archive, dest)?,
}
Ok(())
}
async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> {
let body = client
.get(url)
.send()
.await?
.error_for_status()?
.text()
.await?;
let hex_str = body
.split_whitespace()
.next()
.ok_or_else(|| anyhow!("empty checksum file"))?;
let bytes = hex::decode(hex_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_verified<F>(
client: &reqwest::Client,
url: &str,
expected: &[u8; 32],
on_progress: &mut F,
) -> Result<Vec<u8>>
where
F: FnMut(u64, Option<u64>),
{
let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length();
let mut hasher = Sha256::new();
let mut buf: Vec<u8> = Vec::with_capacity(total.unwrap_or(0) as usize);
let mut downloaded = 0u64;
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
hasher.update(&chunk);
buf.extend_from_slice(&chunk);
downloaded += chunk.len() as u64;
on_progress(downloaded, total);
}
let got: [u8; 32] = hasher.finalize().into();
if &got != expected {
bail!(
"sha256 mismatch: expected {} got {}",
hex::encode(expected),
hex::encode(got)
);
}
Ok(buf)
}
fn is_ffmpeg_entry(name: &str) -> bool {
let normalized: String = name
.chars()
.map(|c| if c == '\\' { '/' } else { c })
.collect();
normalized
.rsplit('/')
.next()
.map(|leaf| leaf.eq_ignore_ascii_case("ffmpeg.exe"))
.unwrap_or(false)
}
fn extract_ffmpeg_from_7z(archive: &[u8], dest: &Path) -> Result<()> {
let reader = Cursor::new(archive);
let mut extracted = false;
let scratch = std::env::temp_dir();
sevenz_rust2::decompress_with_extract_fn(reader, scratch, |entry, src, _| {
if extracted || entry.is_directory() {
return Ok(true);
}
if is_ffmpeg_entry(entry.name()) {
let mut out = File::create(dest)?;
io::copy(src, &mut out)?;
extracted = true;
}
Ok(true)
})
.map_err(|e| anyhow!("7z extraction failed: {e}"))?;
if !extracted {
bail!("ffmpeg.exe not found inside the 7z archive");
}
Ok(())
}
fn extract_ffmpeg_from_zip(archive: &[u8], dest: &Path) -> Result<()> {
let reader = Cursor::new(archive);
let mut zip = zip::ZipArchive::new(reader).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");
}