mod bootstrap; mod capture; mod config; mod encode; use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{anyhow, Result}; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, Manager, State}; use crate::bootstrap::FfmpegStatus; use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec}; #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct CaptureRect { pub x: i32, pub y: i32, pub width: u32, pub height: u32, } pub struct AppState { pub app_dir: PathBuf, pub config: Mutex, pub capture: Mutex>, pub last_clip: Mutex>, } #[derive(Debug, Clone, Serialize)] pub struct RecordedClip { pub temp_path: PathBuf, pub duration_secs: f64, pub width: u32, pub height: u32, pub crop: Option, } fn exe_dir() -> Result { let exe = std::env::current_exe()?; Ok(exe .parent() .ok_or_else(|| anyhow!("exe has no parent directory"))? .to_path_buf()) } fn temp_dir(app_dir: &Path) -> PathBuf { app_dir.join("temp") } fn output_dir(app_dir: &Path, cfg: &Config) -> PathBuf { cfg.output_dir .clone() .unwrap_or_else(|| app_dir.join("output")) } fn timestamp_slug() -> String { let now = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); let local = chrono_like(now); format!( "{:04}{:02}{:02}-{:02}{:02}{:02}", local.year, local.month, local.day, local.hour, local.minute, local.second ) } struct LocalTime { year: u32, month: u32, day: u32, hour: u32, minute: u32, second: u32, } fn chrono_like(epoch_secs: u64) -> LocalTime { let seconds_per_day = 86400u64; let days = epoch_secs / seconds_per_day; let secs_in_day = epoch_secs % seconds_per_day; let hour = (secs_in_day / 3600) as u32; let minute = ((secs_in_day % 3600) / 60) as u32; let second = (secs_in_day % 60) as u32; let mut year = 1970u32; let mut remaining = days as i64; loop { let leap = is_leap(year); let days_in_year = if leap { 366 } else { 365 }; if remaining < days_in_year { break; } remaining -= days_in_year; year += 1; } let leap = is_leap(year); let month_days: [i64; 12] = [ 31, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ]; let mut month = 1u32; for d in month_days { if remaining < d { break; } remaining -= d; month += 1; } let day = remaining as u32 + 1; LocalTime { year, month, day, hour, minute, second } } fn is_leap(year: u32) -> bool { (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 } fn ext_for(format: Format) -> &'static str { match format { Format::Gif => "gif", Format::Webm => "webm", Format::Mp4 => "mp4", } } #[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, } #[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:#}")) } #[derive(Debug, Deserialize)] pub struct StartCaptureRequest { pub crop: Option, } #[tauri::command] fn start_capture( state: State<'_, AppState>, request: Option, ) -> Result<(), String> { let mut slot = state.capture.lock().expect("capture mutex"); if slot.is_some() { return Err("a capture is already running".to_string()); } let cfg = state.config.lock().expect("config mutex").clone(); let temp = temp_dir(&state.app_dir); std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?; let output = temp.join("recording.mp4"); let _ = std::fs::remove_file(&output); let crop = request.and_then(|r| r.crop); let session = capture::start( output, cfg.capture.capture_cursor, cfg.capture.capture_audio, crop, ) .map_err(|e| format!("{e:#}"))?; *slot = Some(session); Ok(()) } #[tauri::command] fn stop_capture(state: State<'_, AppState>) -> Result { let session = state .capture .lock() .expect("capture mutex") .take() .ok_or_else(|| "no capture in progress".to_string())?; let duration_secs = session.started_at.elapsed().as_secs_f64(); let width = session.width; let height = session.height; let crop = session.crop; let temp_path = session.stop().map_err(|e| format!("{e:#}"))?; let clip = RecordedClip { temp_path, duration_secs, width, height, crop, }; *state.last_clip.lock().expect("clip mutex") = Some(clip.clone()); Ok(clip) } #[derive(Debug, Deserialize)] pub struct ExportRequest { pub format: Format, pub target_bytes: u64, pub fps: u32, pub keep_audio: bool, } #[derive(Debug, Serialize)] pub struct ExportResult { pub output_path: PathBuf, pub size_bytes: u64, } const OVERLAY_BORDER_LOGICAL_PX: f64 = 2.0; const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 22.0; #[tauri::command] fn show_overlay(app: AppHandle) -> Result<(), String> { let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; win.show().map_err(|e| e.to_string())?; win.set_focus().map_err(|e| e.to_string()) } #[tauri::command] fn hide_overlay(app: AppHandle) -> Result<(), String> { let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; win.hide().map_err(|e| e.to_string()) } #[tauri::command] fn get_overlay_rect(app: AppHandle) -> Result { let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; let pos = win.outer_position().map_err(|e| e.to_string())?; let size = win.outer_size().map_err(|e| e.to_string())?; let scale = win.scale_factor().map_err(|e| e.to_string())?; let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let inset_top = border_phys + titlebar_phys; let inset_sides = border_phys; let inset_bottom = border_phys; let width = (size.width as i32 - inset_sides * 2).max(2) as u32; let height = (size.height as i32 - inset_top - inset_bottom).max(2) as u32; let width = (width / 2) * 2; let height = (height / 2) * 2; Ok(CaptureRect { x: pos.x + inset_sides, y: pos.y + inset_top, width, height, }) } #[tauri::command] fn reveal_in_explorer(path: String) -> Result<(), String> { use std::process::Command; Command::new("explorer.exe") .arg(format!("/select,{path}")) .spawn() .map_err(|e| format!("opening explorer: {e}"))?; Ok(()) } #[tauri::command] fn export(state: State<'_, AppState>, request: ExportRequest) -> Result { let cfg = state.config.lock().expect("config mutex").clone(); let clip = state .last_clip .lock() .expect("clip mutex") .clone() .ok_or_else(|| "no recorded clip available".to_string())?; let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if !ffmpeg.is_file() { return Err("ffmpeg.exe not found - run the encoder setup first".to_string()); } let out_dir = output_dir(&state.app_dir, &cfg); std::fs::create_dir_all(&out_dir).map_err(|e| format!("creating output dir: {e}"))?; let out_path = out_dir.join(format!( "bytesize-{}.{}", timestamp_slug(), ext_for(request.format) )); let req = encode::TranscodeRequest { input: clip.temp_path.clone(), output: out_path.clone(), format: request.format, target_bytes: request.target_bytes, duration_secs: clip.duration_secs, fps: request.fps, keep_audio: request.keep_audio, gif_dither: cfg.export.gif_dither, webm_codec: cfg.export.webm_codec, mp4_codec: cfg.export.mp4_codec, scratch_dir: temp_dir(&state.app_dir), crop: clip.crop, }; encode::transcode(&ffmpeg, &req).map_err(|e| format!("{e:#}"))?; let size_bytes = std::fs::metadata(&out_path) .map(|m| m.len()) .unwrap_or(0); Ok(ExportResult { output_path: out_path, size_bytes, }) } // Suppress dead-code warnings for codec helper functions used only via config. #[allow(dead_code)] fn _codec_keepalive() -> (GifDither, WebmCodec, Mp4Codec) { (GifDither::None, WebmCodec::Vp9, Mp4Codec::H264) } 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), capture: Mutex::new(None), last_clip: Mutex::new(None), }; tauri::Builder::default() .plugin(tauri_plugin_dialog::init()) .manage(state) .invoke_handler(tauri::generate_handler![ get_status, get_config, save_config, download_ffmpeg, start_capture, stop_capture, export, reveal_in_explorer, show_overlay, hide_overlay, get_overlay_rect, ]) .run(tauri::generate_context!()) .expect("error while running ByteSize") }