calibrate gif size, probe codecs, align audio with video

- sample-encode gif calibration before the retry loop
- probe ffmpeg encoders and grey out missing codecs in settings
- pad audio head with silence so it lines up with video start
- cache gif preview palette keyed on colors and sample window
- read encode progress from -progress pipe:1 instead of stderr scraping
- thread bt709 color metadata through capture, fix, and gif scale
- sweep temp on startup
- gif estimate table for the ui, interpolated locally on slider drag
This commit is contained in:
2026-06-17 23:09:53 +03:00
parent 4ca802ef71
commit f732cdda4d
7 changed files with 647 additions and 155 deletions
+149 -15
View File
@@ -66,6 +66,11 @@ pub struct SessionState {
pub monitor_height: u32,
pub clicks: Vec<clicks::Click>,
pub segment_start_offsets: Vec<f64>,
/// Wall-clock time the first video segment began. Used to align the head
/// of the audio track (which starts a little later due to WASAPI init).
pub video_started_at: Option<std::time::Instant>,
/// Wall-clock time the first audio segment began capturing.
pub audio_started_at: Option<std::time::Instant>,
}
#[derive(Debug, Clone, Serialize)]
@@ -315,6 +320,7 @@ fn clear_temp_segments(app_dir: &Path) {
if let Some(name) = entry.file_name().to_str() {
if (name.starts_with("segment-") && name.ends_with(".mp4"))
|| (name.starts_with("audio-") && name.ends_with(".pcm"))
|| (name.starts_with("preview-palette-") && name.ends_with(".png"))
{
let _ = std::fs::remove_file(entry.path());
}
@@ -357,6 +363,37 @@ fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs
Ok(())
}
/// Prepend `head_secs` of silence to a raw f32le PCM file so the audio track
/// aligns with the video start. WASAPI init adds a delay between capture
/// start and the first audio packet; this pads the gap.
fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64) -> Result<()> {
use std::io::{Read, Write};
let bytes_per_sec = sample_rate as f64 * channels as f64 * 4.0;
let pad_bytes = (head_secs * bytes_per_sec).round() as u64;
if pad_bytes == 0 {
return Ok(());
}
let mut existing = Vec::new();
{
let mut f = std::fs::File::open(path)?;
f.read_to_end(&mut existing)?;
}
let mut f = std::fs::File::create(path)?;
let zeros = vec![0u8; 64 * 1024];
let mut remaining = pad_bytes;
while remaining > 0 {
let to_write = remaining.min(zeros.len() as u64) as usize;
f.write_all(&zeros[..to_write])?;
remaining -= to_write as u64;
}
f.write_all(&existing)?;
tracing::debug!(
"padded audio head with {:.1}ms ({} bytes) of silence",
head_secs * 1000.0, pad_bytes
);
Ok(())
}
fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) {
if let Some(win) = app.get_webview_window("overlay") {
let _ = win.set_ignore_cursor_events(enabled);
@@ -453,6 +490,8 @@ fn start_capture(
monitor_height: monitor_h,
clicks: Vec::new(),
segment_start_offsets: vec![0.0],
video_started_at: Some(session.started_at),
audio_started_at: audio_session.as_ref().map(|a| a.started_at),
};
let click_rec = start_click_recorder(cfg.capture.capture_cursor);
@@ -471,11 +510,11 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
.ok_or_else(|| "no capture in progress".to_string())?;
let elapsed = session.started_at.elapsed().as_secs_f64();
let frames = session.frame_counter.load(std::sync::atomic::Ordering::Relaxed);
let pipe_fps = session.pipe_fps;
let raw_path = session.stop().map_err(|e| format!("{e:#}"))?;
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
let cap_fps = lock(&state.config).capture.default_fps;
let fixed_path = raw_path.with_extension("fixed.mp4");
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, cap_fps)
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
.map_err(|e| format!("fixing fps: {e:#}"))?;
let path = if fixed_path.exists() { fixed_path } else { raw_path };
@@ -602,11 +641,11 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
if let Some(session) = live {
let elapsed = session.started_at.elapsed().as_secs_f64();
let frames = session.frame_counter.load(std::sync::atomic::Ordering::Relaxed);
let pipe_fps = session.pipe_fps;
let raw_path = session.stop().map_err(|e| format!("{e:#}"))?;
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
let cap_fps = lock(&state.config).capture.default_fps;
let fixed_path = raw_path.with_extension("fixed.mp4");
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, cap_fps)
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
.map_err(|e| format!("fixing fps: {e:#}"))?;
let final_path = if fixed_path.exists() { fixed_path } else { raw_path };
ss.segments.push(final_path);
@@ -666,6 +705,23 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
let audio_concat = temp.join("audio-concat.pcm");
encode::concat_pcm(&ss.audio_segments, &audio_concat)
.map_err(|e| format!("audio concat: {e:#}"))?;
// Pad the head with silence so the audio track starts at the same
// wall-clock moment the video did. WASAPI init + Start adds a delay
// between the capture session start and the first audio packet.
if let (Some(video_start), Some(audio_start)) = (ss.video_started_at, ss.audio_started_at) {
if audio_start > video_start {
let head_offset_secs = audio_start.duration_since(video_start).as_secs_f64();
if head_offset_secs > 0.001 {
pad_audio_head(
&audio_concat,
ss.audio_sample_rate.unwrap(),
ss.audio_channels.unwrap(),
head_offset_secs,
)
.map_err(|e| format!("padding audio head: {e:#}"))?;
}
}
}
adjust_audio_length(
&audio_concat,
ss.audio_sample_rate.unwrap(),
@@ -821,6 +877,20 @@ pub struct GifEstimate {
pub dims_label: String,
}
#[derive(Debug, Serialize)]
pub struct GifEstimateTable {
/// Sorted ascending. Frontend interpolates between points.
pub points: Vec<GifEstimatePoint>,
}
#[derive(Debug, Serialize)]
pub struct GifEstimatePoint {
pub target_bytes: u64,
pub width: u32,
pub fps: u32,
pub height: u32,
}
#[tauri::command]
fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
let budget = encode::GifBudgetInput {
@@ -833,9 +903,44 @@ fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
let (w, fps) = encode::gif_params(&budget, request.clip_width, request.clip_height);
let height = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
let dims_label = format!("{w}x{height} @ {fps}fps");
GifEstimate { width: w, fps, height, dims_label }
}
/// Return estimates for a grid of target_bytes values so the frontend can
/// interpolate on slider drag without an IPC per debounce tick. The grid is
/// geometric from 100KB to 200MB.
#[tauri::command]
fn estimate_gif_params_table(request: PreviewRequest) -> GifEstimateTable {
let colors = request.gif_colors.unwrap_or(256);
let dur = request.duration_secs.unwrap_or(0.0).max(0.1);
let fps = request.fps;
let mode = request.gif_budget_mode;
// Geometric grid: 100KB, 200KB, 500KB, 1MB, 2MB, 5MB, 10MB, 20MB, 50MB, 100MB, 200MB
const GRID: &[u64] = &[
100_000, 200_000, 500_000,
1_048_576, 2_097_152, 5_242_880,
10_485_760, 20_971_520, 52_428_800,
104_857_600, 209_715_200,
];
let mut points = Vec::with_capacity(GRID.len());
for &target in GRID {
let budget = encode::GifBudgetInput {
gif_colors: colors,
target_bytes: target,
fps,
duration_secs: dur,
gif_budget_mode: mode,
};
let (w, f) = encode::gif_params(&budget, request.clip_width, request.clip_height);
let h = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
points.push(GifEstimatePoint { target_bytes: target, width: w, fps: f, height: h });
}
GifEstimateTable { points }
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1467,13 +1572,25 @@ fn cancel_export(state: State<'_, AppState>) {
}
#[tauri::command]
fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
let cfg = lock(&state.config).clone();
let clip = lock(&state.last_clip)
.clone()
.ok_or_else(|| "no recorded clip available".to_string())?;
fn codec_availability(state: State<'_, AppState>) -> Result<encode::CodecAvailability, String> {
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
if !ffmpeg.is_file() {
return Ok(encode::CodecAvailability::all_unknown());
}
Ok(encode::codec_availability(&ffmpeg))
}
#[tauri::command]
async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
let (cfg, clip, app_dir, export_cancel) = {
let cfg = lock(&state.config).clone();
let clip = lock(&state.last_clip)
.clone()
.ok_or_else(|| "no recorded clip available".to_string())?;
(cfg, clip, state.app_dir.clone(), state.export_cancel.clone())
};
let ffmpeg = bootstrap::ffmpeg_path(&app_dir);
if !ffmpeg.is_file() {
return Err("ffmpeg.exe not found - run the encoder setup first".to_string());
}
@@ -1481,7 +1598,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
let out_path: PathBuf = match request.output_path.as_deref() {
Some(p) if !p.trim().is_empty() => PathBuf::from(p),
_ => {
let out_dir = output_dir(&state.app_dir, &cfg);
let out_dir = output_dir(&app_dir, &cfg);
out_dir.join(format!(
"bytesize-{}.{}",
timestamp_slug(),
@@ -1539,7 +1656,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
gif_colors: request.gif_colors.unwrap_or(256),
webm_codec: cfg.export.webm_codec,
mp4_codec: cfg.export.mp4_codec,
scratch_dir: temp_dir(&state.app_dir),
scratch_dir: temp_dir(&app_dir),
crop: request.crop,
gif_budget_mode: request.gif_budget_mode,
deleted_frame_indices: request.deleted_frame_indices,
@@ -1549,7 +1666,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
clip_width: clip.width,
clip_height: clip.height,
progress_tx: None,
cancel: Some(state.export_cancel.clone()),
cancel: Some(export_cancel.clone()),
};
let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 };
@@ -1572,8 +1689,18 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
}
});
state.export_cancel.store(false, Ordering::SeqCst);
encode::transcode(&ffmpeg, &req_with_progress).map_err(|e| format!("{e:#}"))?;
export_cancel.store(false, Ordering::SeqCst);
// Run the (potentially minutes-long) ffmpeg encode on a blocking thread so
// we don't hold a Tauri async worker for the whole duration.
let ffmpeg_arc = std::sync::Arc::new(ffmpeg);
let ffmpeg_for_task = ffmpeg_arc.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
encode::transcode(&ffmpeg_for_task, &req_with_progress)
})
.await
.map_err(|e| format!("encode task panicked: {e:#}"))?;
result.map_err(|e| format!("{e:#}"))?;
let size_bytes = std::fs::metadata(&out_path)
.map(|m| m.len())
@@ -1587,6 +1714,11 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
pub fn run() {
let app_dir = exe_dir().expect("resolve exe directory");
// Sweep temp/ before anything else so a crash on the previous run does not
// leave orphaned segments, previews, or thumbs behind - the portability
// spec promises no trace, and stale temp is trace.
clear_temp_segments(&app_dir);
let log_dir = app_dir.join("logs");
let _ = std::fs::create_dir_all(&log_dir);
let file_appender = tracing_appender::rolling::daily(&log_dir, "bytesize.log");
@@ -1742,6 +1874,7 @@ pub fn run() {
render_preview,
render_raw_preview,
estimate_gif_params,
estimate_gif_params_table,
reveal_in_explorer,
open_url,
show_overlay,
@@ -1756,6 +1889,7 @@ pub fn run() {
close_window_picker,
get_overlay_rect,
cancel_export,
codec_availability,
])
.build(tauri::generate_context!())
.expect("error while building ByteSize");