capture, encode, export wiring
This commit is contained in:
+219
-5
@@ -3,29 +3,129 @@ mod capture;
|
||||
mod config;
|
||||
mod encode;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::Result;
|
||||
use serde::Serialize;
|
||||
use anyhow::{anyhow, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
|
||||
use crate::bootstrap::FfmpegStatus;
|
||||
use crate::config::Config;
|
||||
use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec};
|
||||
|
||||
pub struct AppState {
|
||||
pub app_dir: PathBuf,
|
||||
pub config: Mutex<Config>,
|
||||
pub capture: Mutex<Option<capture::CaptureSession>>,
|
||||
pub last_clip: Mutex<Option<RecordedClip>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RecordedClip {
|
||||
pub temp_path: PathBuf,
|
||||
pub duration_secs: f64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
fn exe_dir() -> Result<PathBuf> {
|
||||
let exe = std::env::current_exe()?;
|
||||
Ok(exe
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("exe has no parent directory"))?
|
||||
.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,
|
||||
@@ -74,6 +174,115 @@ async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(
|
||||
.map_err(|e| format!("{e:#}"))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn start_capture(state: State<'_, AppState>) -> 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 session = capture::start(output, cfg.capture.capture_cursor, cfg.capture.capture_audio)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
*slot = Some(session);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
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 temp_path = session.stop().map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
let clip = RecordedClip {
|
||||
temp_path,
|
||||
duration_secs,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
*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,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
|
||||
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),
|
||||
};
|
||||
|
||||
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();
|
||||
|
||||
@@ -86,6 +295,8 @@ pub fn run() {
|
||||
let state = AppState {
|
||||
app_dir,
|
||||
config: Mutex::new(cfg),
|
||||
capture: Mutex::new(None),
|
||||
last_clip: Mutex::new(None),
|
||||
};
|
||||
|
||||
tauri::Builder::default()
|
||||
@@ -96,6 +307,9 @@ pub fn run() {
|
||||
get_config,
|
||||
save_config,
|
||||
download_ffmpeg,
|
||||
start_capture,
|
||||
stop_capture,
|
||||
export,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running ByteSize")
|
||||
|
||||
Reference in New Issue
Block a user