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");
}
+145 -1
View File
@@ -1 +1,145 @@
// TOML config load/save - state lives in ./config.toml next to the exe
use std::path::{Path, PathBuf};
use anyhow::Result;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
pub export: ExportConfig,
#[serde(default)]
pub capture: CaptureConfig,
#[serde(default)]
pub hotkeys: HotkeyConfig,
#[serde(default)]
pub updates: UpdatesConfig,
#[serde(default)]
pub output_dir: Option<PathBuf>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportConfig {
pub default_format: Format,
pub gif_dither: GifDither,
pub webm_codec: WebmCodec,
pub mp4_codec: Mp4Codec,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaptureConfig {
pub default_fps: u32,
pub capture_cursor: bool,
pub capture_audio: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HotkeyConfig {
pub start: Option<String>,
pub stop: Option<String>,
pub pause: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdatesConfig {
pub check_on_launch: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Format {
Gif,
Webm,
Mp4,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GifDither {
FloydSteinberg,
Bayer,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WebmCodec {
Vp9,
Av1,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Mp4Codec {
H264,
H265,
}
impl Default for Config {
fn default() -> Self {
Self {
export: ExportConfig::default(),
capture: CaptureConfig::default(),
hotkeys: HotkeyConfig::default(),
updates: UpdatesConfig::default(),
output_dir: None,
}
}
}
impl Default for ExportConfig {
fn default() -> Self {
Self {
default_format: Format::Gif,
gif_dither: GifDither::FloydSteinberg,
webm_codec: WebmCodec::Vp9,
mp4_codec: Mp4Codec::H264,
}
}
}
impl Default for CaptureConfig {
fn default() -> Self {
Self {
default_fps: 30,
capture_cursor: true,
capture_audio: false,
}
}
}
impl Default for UpdatesConfig {
fn default() -> Self {
Self { check_on_launch: true }
}
}
impl Config {
pub fn load_or_create(path: &Path) -> Result<Self> {
if !path.exists() {
let cfg = Self::default();
cfg.save(path)?;
return Ok(cfg);
}
let raw = std::fs::read_to_string(path)?;
Ok(toml::from_str(&raw)?)
}
pub fn save(&self, path: &Path) -> Result<()> {
let serialized = toml::to_string_pretty(self)?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, serialized)?;
Ok(())
}
pub fn needs_first_run(&self) -> bool {
self.hotkeys.start.is_none()
|| self.hotkeys.stop.is_none()
|| self.hotkeys.pause.is_none()
}
}
pub fn config_path(app_dir: &Path) -> PathBuf {
app_dir.join("config.toml")
}
+91 -1
View File
@@ -3,10 +3,100 @@ mod capture;
mod config;
mod encode;
use std::path::PathBuf;
use std::sync::Mutex;
use anyhow::Result;
use serde::Serialize;
use tauri::{AppHandle, Emitter, State};
use crate::bootstrap::FfmpegStatus;
use crate::config::Config;
pub struct AppState {
pub app_dir: PathBuf,
pub config: Mutex<Config>,
}
fn exe_dir() -> Result<PathBuf> {
let exe = std::env::current_exe()?;
Ok(exe
.parent()
.ok_or_else(|| anyhow::anyhow!("exe has no parent directory"))?
.to_path_buf())
}
#[derive(Serialize)]
struct AppStatus {
ffmpeg: FfmpegStatus,
needs_first_run: bool,
}
#[tauri::command]
fn get_status(state: State<'_, AppState>) -> AppStatus {
let cfg = state.config.lock().expect("config mutex");
AppStatus {
ffmpeg: bootstrap::check(&state.app_dir),
needs_first_run: cfg.needs_first_run(),
}
}
#[tauri::command]
fn get_config(state: State<'_, AppState>) -> Config {
state.config.lock().expect("config mutex").clone()
}
#[tauri::command]
fn save_config(state: State<'_, AppState>, config: Config) -> Result<(), String> {
let path = config::config_path(&state.app_dir);
config.save(&path).map_err(|e| format!("{e:#}"))?;
*state.config.lock().expect("config mutex") = config;
Ok(())
}
#[derive(Clone, Serialize)]
struct DownloadProgress {
downloaded: u64,
total: Option<u64>,
}
#[tauri::command]
async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
let app_dir = state.app_dir.clone();
let app_handle = app.clone();
bootstrap::download(&app_dir, move |downloaded, total| {
let _ = app_handle.emit(
"ffmpeg-progress",
DownloadProgress { downloaded, total },
);
})
.await
.map_err(|e| format!("{e:#}"))
}
pub fn run() {
tracing_subscriber::fmt::init();
let app_dir = exe_dir().expect("resolve exe directory");
let cfg_path = config::config_path(&app_dir);
let cfg = Config::load_or_create(&cfg_path).expect("load or create config.toml");
tracing::info!(?app_dir, "starting ByteSize");
let state = AppState {
app_dir,
config: Mutex::new(cfg),
};
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.invoke_handler(tauri::generate_handler![])
.manage(state)
.invoke_handler(tauri::generate_handler![
get_status,
get_config,
save_config,
download_ffmpeg,
])
.run(tauri::generate_context!())
.expect("error while running ByteSize")
}