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:
+11
-4
@@ -14,7 +14,7 @@ use windows::Win32::System::Com::{
|
|||||||
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
|
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
|
||||||
};
|
};
|
||||||
|
|
||||||
// WASAPI constants — defined here so we don't depend on exact windows-crate naming.
|
// WASAPI constants - defined here so we don't depend on exact windows-crate naming.
|
||||||
const AUDCLNT_STREAMFLAGS_LOOPBACK: u32 = 0x2000_0000;
|
const AUDCLNT_STREAMFLAGS_LOOPBACK: u32 = 0x2000_0000;
|
||||||
const AUDCLNT_BUFFERFLAGS_SILENT: u32 = 0x0000_0002;
|
const AUDCLNT_BUFFERFLAGS_SILENT: u32 = 0x0000_0002;
|
||||||
|
|
||||||
@@ -28,6 +28,7 @@ pub struct AudioSession {
|
|||||||
output_path: PathBuf,
|
output_path: PathBuf,
|
||||||
pub sample_rate: u32,
|
pub sample_rate: u32,
|
||||||
pub channels: u16,
|
pub channels: u16,
|
||||||
|
pub started_at: std::time::Instant,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start(output_path: PathBuf) -> Result<AudioSession> {
|
pub fn start(output_path: PathBuf) -> Result<AudioSession> {
|
||||||
@@ -45,7 +46,7 @@ pub fn start(output_path: PathBuf) -> Result<AudioSession> {
|
|||||||
result
|
result
|
||||||
});
|
});
|
||||||
|
|
||||||
let (sample_rate, channels) = init_rx
|
let (sample_rate, channels, started_at) = init_rx
|
||||||
.recv_timeout(std::time::Duration::from_secs(3))
|
.recv_timeout(std::time::Duration::from_secs(3))
|
||||||
.context("audio capture thread failed to initialize within 3 seconds")?
|
.context("audio capture thread failed to initialize within 3 seconds")?
|
||||||
.context("audio capture initialization failed")?;
|
.context("audio capture initialization failed")?;
|
||||||
@@ -56,6 +57,7 @@ pub fn start(output_path: PathBuf) -> Result<AudioSession> {
|
|||||||
output_path,
|
output_path,
|
||||||
sample_rate,
|
sample_rate,
|
||||||
channels,
|
channels,
|
||||||
|
started_at,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,7 +98,7 @@ fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
|
|||||||
fn capture_thread(
|
fn capture_thread(
|
||||||
running: Arc<AtomicBool>,
|
running: Arc<AtomicBool>,
|
||||||
output_path: PathBuf,
|
output_path: PathBuf,
|
||||||
init_tx: std::sync::mpsc::Sender<Result<(u32, u16)>>,
|
init_tx: std::sync::mpsc::Sender<Result<(u32, u16, std::time::Instant)>>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
// SAFETY: Initializes COM for this thread before any COM operations. COINIT_APARTMENTTHREADED is required for WASAPI.
|
// SAFETY: Initializes COM for this thread before any COM operations. COINIT_APARTMENTTHREADED is required for WASAPI.
|
||||||
unsafe {
|
unsafe {
|
||||||
@@ -167,8 +169,13 @@ fn capture_thread(
|
|||||||
let file = File::create(&output_path).context("creating audio output file")?;
|
let file = File::create(&output_path).context("creating audio output file")?;
|
||||||
let mut writer = BufWriter::new(file);
|
let mut writer = BufWriter::new(file);
|
||||||
|
|
||||||
|
// Stamp the moment audio capture actually begins so stop_capture can pad
|
||||||
|
// the head of the PCM to align with video start (WASAPI init + Start adds
|
||||||
|
// a small delay relative to the video capture start).
|
||||||
|
let started_at = std::time::Instant::now();
|
||||||
|
|
||||||
// Notify parent that init succeeded.
|
// Notify parent that init succeeded.
|
||||||
let _ = init_tx.send(Ok((sample_rate, channels)));
|
let _ = init_tx.send(Ok((sample_rate, channels, started_at)));
|
||||||
|
|
||||||
let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer);
|
let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer);
|
||||||
|
|
||||||
|
|||||||
+120
-43
@@ -19,6 +19,7 @@ use windows_capture::settings::{
|
|||||||
use crate::CaptureRect;
|
use crate::CaptureRect;
|
||||||
|
|
||||||
const MAX_ENCODE_WIDTH: u32 = 1920;
|
const MAX_ENCODE_WIDTH: u32 = 1920;
|
||||||
|
const FALLBACK_REFRESH_HZ: u32 = 60;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct CaptureSetup {
|
pub struct CaptureSetup {
|
||||||
@@ -26,9 +27,8 @@ pub struct CaptureSetup {
|
|||||||
pub ffmpeg_path: PathBuf,
|
pub ffmpeg_path: PathBuf,
|
||||||
pub width: u32,
|
pub width: u32,
|
||||||
pub height: u32,
|
pub height: u32,
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fps: u32,
|
|
||||||
pub crop: Option<CaptureRect>,
|
pub crop: Option<CaptureRect>,
|
||||||
|
pub pipe_fps: u32,
|
||||||
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,10 +60,6 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
setup.width
|
setup.width
|
||||||
};
|
};
|
||||||
|
|
||||||
// Capture at declared rate, apply fps filter to normalize timestamps.
|
|
||||||
// fix_intermediate_fps re-encodes with measured actual rate after.
|
|
||||||
filter_parts.push(format!("fps={}", setup.fps));
|
|
||||||
|
|
||||||
if working_width > MAX_ENCODE_WIDTH {
|
if working_width > MAX_ENCODE_WIDTH {
|
||||||
filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH));
|
filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH));
|
||||||
} else {
|
} else {
|
||||||
@@ -74,13 +70,14 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
// The capture API delivers frames at the monitor's refresh rate, not the
|
// The capture API delivers frames at the monitor's refresh rate, not the
|
||||||
// user's chosen FPS. We must tell ffmpeg the actual rate so timestamps are
|
// user's chosen FPS. We must tell ffmpeg the actual rate so timestamps are
|
||||||
// correct. The fps filter in the export pipeline handles the conversion.
|
// correct. The fps filter in the export pipeline handles the conversion.
|
||||||
tracing::info!("capture: size={}x{}", setup.width, setup.height);
|
tracing::info!(
|
||||||
|
"capture: size={}x{} pipe_fps={}",
|
||||||
// Declare a high-ish framerate so ffmpeg accepts all frames from the pipe.
|
setup.width, setup.height, setup.pipe_fps
|
||||||
// The actual delivery rate varies; fix_intermediate_fps re-encodes with
|
);
|
||||||
// the measured rate after capture.
|
|
||||||
let capture_fps = 120u32;
|
|
||||||
|
|
||||||
|
// Declare the detected refresh rate so ffmpeg accepts all frames from the
|
||||||
|
// pipe. The actual delivery rate varies; fix_intermediate_fps re-encodes
|
||||||
|
// with the measured rate after capture.
|
||||||
let mut cmd = Command::new(&setup.ffmpeg_path);
|
let mut cmd = Command::new(&setup.ffmpeg_path);
|
||||||
cmd.arg("-y")
|
cmd.arg("-y")
|
||||||
.arg("-hide_banner")
|
.arg("-hide_banner")
|
||||||
@@ -88,12 +85,15 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
.args(["-f", "rawvideo"])
|
.args(["-f", "rawvideo"])
|
||||||
.args(["-pixel_format", "bgra"])
|
.args(["-pixel_format", "bgra"])
|
||||||
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
|
.args(["-video_size", &format!("{}x{}", setup.width, setup.height)])
|
||||||
.args(["-framerate", &capture_fps.to_string()])
|
.args(["-framerate", &setup.pipe_fps.to_string()])
|
||||||
.args(["-i", "-"])
|
.args(["-i", "-"])
|
||||||
.args(["-vf", &filter])
|
.args(["-vf", &filter])
|
||||||
.args(["-c:v", "libx264"])
|
.args(["-c:v", "libx264"])
|
||||||
.args(["-preset", "ultrafast"])
|
.args(["-preset", "ultrafast"])
|
||||||
.args(["-tune", "zerolatency"])
|
.args(["-tune", "zerolatency"])
|
||||||
|
.args(["-color_primaries", "bt709"])
|
||||||
|
.args(["-color_trc", "bt709"])
|
||||||
|
.args(["-colorspace", "bt709"])
|
||||||
.args(["-pix_fmt", "yuv420p"])
|
.args(["-pix_fmt", "yuv420p"])
|
||||||
.args(["-movflags", "+faststart"])
|
.args(["-movflags", "+faststart"])
|
||||||
.arg(&setup.output_path)
|
.arg(&setup.output_path)
|
||||||
@@ -118,13 +118,13 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let frame_size = (setup.width as usize) * (setup.height as usize) * 4;
|
let pixels = (setup.width as usize) * (setup.height as usize);
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
stdin: Some(stdin),
|
stdin: Some(stdin),
|
||||||
child: Some(child),
|
child: Some(child),
|
||||||
width: setup.width,
|
width: setup.width,
|
||||||
height: setup.height,
|
height: setup.height,
|
||||||
scratch: Vec::with_capacity(frame_size),
|
scratch: Vec::with_capacity(pixels * 4),
|
||||||
frame_count: setup.frame_counter.clone(),
|
frame_count: setup.frame_counter.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -141,9 +141,15 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
let buf = frame
|
let buf = frame
|
||||||
.buffer()
|
.buffer()
|
||||||
.map_err(|e| anyhow!("frame buffer: {e:?}"))?;
|
.map_err(|e| anyhow!("frame buffer: {e:?}"))?;
|
||||||
self.scratch.clear();
|
|
||||||
let bytes = buf.as_nopadding_buffer(&mut self.scratch);
|
|
||||||
let expected = (self.width as usize) * (self.height as usize) * 4;
|
let expected = (self.width as usize) * (self.height as usize) * 4;
|
||||||
|
if buf.has_padding() {
|
||||||
|
// windows-capture copies padded rows into the provided Vec, but only
|
||||||
|
// grows it when capacity is too small. Keep len valid.
|
||||||
|
self.scratch.resize(expected, 0);
|
||||||
|
} else {
|
||||||
|
self.scratch.clear();
|
||||||
|
}
|
||||||
|
let bytes = buf.as_nopadding_buffer(&mut self.scratch);
|
||||||
if bytes.len() < expected {
|
if bytes.len() < expected {
|
||||||
tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected);
|
tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -172,6 +178,7 @@ pub struct CaptureSession {
|
|||||||
pub width: u32,
|
pub width: u32,
|
||||||
pub height: u32,
|
pub height: u32,
|
||||||
pub crop: Option<CaptureRect>,
|
pub crop: Option<CaptureRect>,
|
||||||
|
pub pipe_fps: u32,
|
||||||
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
pub frame_counter: Arc<std::sync::atomic::AtomicU64>,
|
||||||
control: CaptureControl<CaptureHandler, anyhow::Error>,
|
control: CaptureControl<CaptureHandler, anyhow::Error>,
|
||||||
}
|
}
|
||||||
@@ -187,23 +194,36 @@ pub fn primary_monitor_dims() -> Result<(u32, u32)> {
|
|||||||
Ok((w & !1, h & !1))
|
Ok((w & !1, h & !1))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
/// Detect the monitor's refresh rate (Hz) via `Monitor::refresh_rate`, which
|
||||||
/// Detect the primary monitor's refresh rate in Hz.
|
/// resolves the device name through `GetMonitorInfoW` and queries its current
|
||||||
/// Falls back to 60 if detection fails.
|
/// settings with `EnumDisplaySettingsW`. Falls back to [`FALLBACK_REFRESH_HZ`]
|
||||||
fn detect_monitor_refresh_rate() -> u32 {
|
/// on any failure.
|
||||||
use windows::Win32::Graphics::Gdi::{DEVMODEW, ENUM_CURRENT_SETTINGS, EnumDisplaySettingsW};
|
fn monitor_refresh_rate(monitor: &Monitor) -> u32 {
|
||||||
unsafe {
|
match monitor.refresh_rate() {
|
||||||
let mut devmode: DEVMODEW = std::mem::zeroed();
|
Ok(0) => {
|
||||||
devmode.dmSize = std::mem::size_of::<DEVMODEW>() as u16;
|
tracing::warn!("monitor reported 0 Hz refresh, using fallback");
|
||||||
if EnumDisplaySettingsW(None, ENUM_CURRENT_SETTINGS, &mut devmode).as_bool() && devmode.dmDisplayFrequency > 0 {
|
FALLBACK_REFRESH_HZ
|
||||||
return devmode.dmDisplayFrequency as u32;
|
}
|
||||||
|
Ok(hz) => hz,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("refresh rate detection failed ({e:?}), using fallback");
|
||||||
|
FALLBACK_REFRESH_HZ
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
60 // fallback
|
}
|
||||||
|
|
||||||
|
/// Pick the pipe framerate ffmpeg should declare for raw input from the
|
||||||
|
/// capture API. WGC delivers frames roughly at the monitor's refresh rate;
|
||||||
|
/// declaring that rate (instead of a fixed high constant) keeps the raw
|
||||||
|
/// timestamps close to real time so `fix_intermediate_fps` only nudges.
|
||||||
|
fn detect_pipe_framerate(monitor: &Monitor) -> u32 {
|
||||||
|
monitor_refresh_rate(monitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Find the monitor containing the given screen point using the Win32 API.
|
/// Find the monitor containing the given screen point using the Win32 API.
|
||||||
/// Falls back to the primary monitor if no monitor is found.
|
/// Falls back to the primary monitor if no monitor is found.
|
||||||
|
/// Resolve the monitor containing the given screen point, falling back to the
|
||||||
|
/// primary monitor on failure.
|
||||||
fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
|
fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
|
||||||
use windows::Win32::Foundation::POINT;
|
use windows::Win32::Foundation::POINT;
|
||||||
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
|
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
|
||||||
@@ -214,8 +234,7 @@ fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
|
|||||||
bail!("MonitorFromPoint returned null for ({x}, {y})");
|
bail!("MonitorFromPoint returned null for ({x}, {y})");
|
||||||
}
|
}
|
||||||
// SAFETY: hmonitor is a valid monitor handle from MonitorFromPoint.
|
// SAFETY: hmonitor is a valid monitor handle from MonitorFromPoint.
|
||||||
let monitor = Monitor::from_raw_hmonitor(hmonitor.0 as *mut _);
|
Ok(Monitor::from_raw_hmonitor(hmonitor.0))
|
||||||
Ok(monitor)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn start(
|
pub fn start(
|
||||||
@@ -224,7 +243,7 @@ pub fn start(
|
|||||||
capture_cursor: bool,
|
capture_cursor: bool,
|
||||||
_audio: bool,
|
_audio: bool,
|
||||||
crop: Option<CaptureRect>,
|
crop: Option<CaptureRect>,
|
||||||
fps: u32,
|
_fps: u32,
|
||||||
) -> Result<CaptureSession> {
|
) -> Result<CaptureSession> {
|
||||||
// Use the center of the capture region to determine which monitor to capture.
|
// Use the center of the capture region to determine which monitor to capture.
|
||||||
// If the region spans monitors, we pick the one containing the center.
|
// If the region spans monitors, we pick the one containing the center.
|
||||||
@@ -252,13 +271,15 @@ pub fn start(
|
|||||||
|
|
||||||
let frame_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
let frame_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||||
|
|
||||||
|
let pipe_fps = detect_pipe_framerate(&monitor);
|
||||||
|
|
||||||
let setup = CaptureSetup {
|
let setup = CaptureSetup {
|
||||||
output_path: output_path.clone(),
|
output_path: output_path.clone(),
|
||||||
ffmpeg_path,
|
ffmpeg_path,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
fps,
|
|
||||||
crop,
|
crop,
|
||||||
|
pipe_fps,
|
||||||
frame_counter: frame_counter.clone(),
|
frame_counter: frame_counter.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -288,6 +309,7 @@ pub fn start(
|
|||||||
width: out_w,
|
width: out_w,
|
||||||
height: out_h,
|
height: out_h,
|
||||||
crop,
|
crop,
|
||||||
|
pipe_fps,
|
||||||
frame_counter,
|
frame_counter,
|
||||||
control,
|
control,
|
||||||
})
|
})
|
||||||
@@ -327,8 +349,8 @@ impl CaptureSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Re-encode the intermediate file with correct timestamps.
|
/// Re-encode the intermediate file with correct timestamps.
|
||||||
/// The capture declares -framerate N and applies fps=M filter.
|
/// The capture declares a fixed pipe framerate and later scales PTS to match
|
||||||
/// This scales PTS to match real-time duration.
|
/// real-time duration from the measured frame count.
|
||||||
///
|
///
|
||||||
/// Idempotent: if `input` has already been consumed (e.g. a previous
|
/// Idempotent: if `input` has already been consumed (e.g. a previous
|
||||||
/// pause/resume cycle ran this to completion and removed it), and
|
/// pause/resume cycle ran this to completion and removed it), and
|
||||||
@@ -339,7 +361,7 @@ pub fn fix_intermediate_fps(
|
|||||||
output: &std::path::Path,
|
output: &std::path::Path,
|
||||||
elapsed_secs: f64,
|
elapsed_secs: f64,
|
||||||
frame_count: u64,
|
frame_count: u64,
|
||||||
capture_fps: u32,
|
pipe_fps: u32,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
@@ -350,17 +372,31 @@ pub fn fix_intermediate_fps(
|
|||||||
|
|
||||||
if frame_count == 0 || elapsed_secs <= 0.0 {
|
if frame_count == 0 || elapsed_secs <= 0.0 {
|
||||||
tracing::warn!("capture fix: no frames counted, keeping original");
|
tracing::warn!("capture fix: no frames counted, keeping original");
|
||||||
let _ = std::fs::rename(input, output);
|
return rename_or_copy(input, output);
|
||||||
return Ok(());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let actual_fps = frame_count as f64 / elapsed_secs;
|
let (actual_fps, pts_scale) = capture_timing(frame_count, elapsed_secs, pipe_fps)
|
||||||
let pts_scale = capture_fps as f64 / actual_fps;
|
.expect("frame_count and elapsed_secs were checked above");
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps (declared {capture_fps}), pts_scale={pts_scale:.2}"
|
"capture fix: {frame_count} frames in {elapsed_secs:.1}s = {actual_fps:.1}fps (declared {pipe_fps}), pts_scale={pts_scale:.4}"
|
||||||
);
|
);
|
||||||
|
|
||||||
// Re-encode with scaled PTS to fix timing
|
// If the measured rate already matches the declared pipe rate within 2%,
|
||||||
|
// the timestamps are already correct - the capture API's clock and the
|
||||||
|
// ffmpeg input clock agree. Skip the lossy re-encode and just rename.
|
||||||
|
// This is the common case now that pipe_fps tracks the monitor's refresh
|
||||||
|
// rate instead of a fixed high constant.
|
||||||
|
if (pts_scale - 1.0).abs() <= 0.02 {
|
||||||
|
tracing::debug!(
|
||||||
|
"capture fix: pts_scale={pts_scale:.4} within no-op tolerance, renaming without re-encode"
|
||||||
|
);
|
||||||
|
return rename_or_copy(input, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-encode with scaled PTS to fix timing.
|
||||||
|
// CRF 18 is visually lossless and avoids a second generation of H264
|
||||||
|
// quantization on top of the segment encode. The preset stays fast so the
|
||||||
|
// re-encode does not stall stop/pause/resume.
|
||||||
let status = Command::new(ffmpeg)
|
let status = Command::new(ffmpeg)
|
||||||
.arg("-y")
|
.arg("-y")
|
||||||
.arg("-hide_banner")
|
.arg("-hide_banner")
|
||||||
@@ -368,7 +404,11 @@ pub fn fix_intermediate_fps(
|
|||||||
.args(["-i", &input.to_string_lossy()])
|
.args(["-i", &input.to_string_lossy()])
|
||||||
.args(["-vf", &format!("setpts=PTS*{:.4}", pts_scale)])
|
.args(["-vf", &format!("setpts=PTS*{:.4}", pts_scale)])
|
||||||
.args(["-c:v", "libx264"])
|
.args(["-c:v", "libx264"])
|
||||||
.args(["-preset", "ultrafast"])
|
.args(["-preset", "veryfast"])
|
||||||
|
.args(["-crf", "18"])
|
||||||
|
.args(["-color_primaries", "bt709"])
|
||||||
|
.args(["-color_trc", "bt709"])
|
||||||
|
.args(["-colorspace", "bt709"])
|
||||||
.args(["-pix_fmt", "yuv420p"])
|
.args(["-pix_fmt", "yuv420p"])
|
||||||
.arg(output)
|
.arg(output)
|
||||||
.status()
|
.status()
|
||||||
@@ -378,7 +418,44 @@ pub fn fix_intermediate_fps(
|
|||||||
let _ = std::fs::remove_file(input);
|
let _ = std::fs::remove_file(input);
|
||||||
} else {
|
} else {
|
||||||
tracing::warn!("capture fix: re-encode failed, keeping original");
|
tracing::warn!("capture fix: re-encode failed, keeping original");
|
||||||
let _ = std::fs::rename(input, output);
|
let _ = rename_or_copy(input, output);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Move `input` to `output`, falling back to a copy if the rename fails
|
||||||
|
/// (e.g. cross-volume or a handle still holds the file on Windows).
|
||||||
|
fn rename_or_copy(input: &std::path::Path, output: &std::path::Path) -> Result<()> {
|
||||||
|
std::fs::rename(input, output)
|
||||||
|
.or_else(|_| std::fs::copy(input, output).map(|_| ()))
|
||||||
|
.with_context(|| format!("moving {} to {}", input.display(), output.display()))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture_timing(frame_count: u64, elapsed_secs: f64, pipe_fps: u32) -> Option<(f64, f64)> {
|
||||||
|
if frame_count == 0 || elapsed_secs <= 0.0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let actual_fps = frame_count as f64 / elapsed_secs;
|
||||||
|
Some((actual_fps, pipe_fps as f64 / actual_fps))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn timing_scale_uses_declared_pipe_rate() {
|
||||||
|
let (actual_fps, pts_scale) = capture_timing(600, 10.0, 60).unwrap();
|
||||||
|
assert_eq!(actual_fps, 60.0);
|
||||||
|
assert_eq!(pts_scale, 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn timing_scale_for_high_pipe_rate() {
|
||||||
|
// 600 frames in 10s = 60 actual; pipe declared 120 -> pts scale 2.0
|
||||||
|
let (actual_fps, pts_scale) = capture_timing(600, 10.0, 120).unwrap();
|
||||||
|
assert_eq!(actual_fps, 60.0);
|
||||||
|
assert_eq!(pts_scale, 2.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+262
-69
@@ -228,6 +228,40 @@ fn webm_video_codec(c: WebmCodec) -> &'static str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Per-codec availability for the installed ffmpeg, surfaced to the frontend
|
||||||
|
/// so Settings can grey out codecs that would fail at export time. H264 and
|
||||||
|
/// VP9 are assumed always present (they are the defaults) - only the optional
|
||||||
|
/// codecs (H265, AV1) are reported because those are the ones users pick to
|
||||||
|
/// save size and only learn at minute 5 that their build lacks them.
|
||||||
|
#[derive(Debug, Clone, serde::Serialize)]
|
||||||
|
pub struct CodecAvailability {
|
||||||
|
pub h264: bool,
|
||||||
|
pub h265: bool,
|
||||||
|
pub vp9: bool,
|
||||||
|
pub av1: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CodecAvailability {
|
||||||
|
/// Returns all-true when ffmpeg is not installed yet (the bootstrap screen
|
||||||
|
/// is still up). Settings will re-query after the user installs ffmpeg.
|
||||||
|
pub fn all_unknown() -> Self {
|
||||||
|
Self { h264: true, h265: true, vp9: true, av1: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn codec_availability(ffmpeg: &Path) -> CodecAvailability {
|
||||||
|
let encoders = match list_encoders(ffmpeg) {
|
||||||
|
Ok(set) => set,
|
||||||
|
Err(_) => return CodecAvailability::all_unknown(),
|
||||||
|
};
|
||||||
|
CodecAvailability {
|
||||||
|
h264: encoders.contains(mp4_video_codec(Mp4Codec::H264)),
|
||||||
|
h265: encoders.contains(mp4_video_codec(Mp4Codec::H265)),
|
||||||
|
vp9: encoders.contains(webm_video_codec(WebmCodec::Vp9)),
|
||||||
|
av1: encoders.contains(webm_video_codec(WebmCodec::Av1)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
|
fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
|
||||||
let target_bits = (req.target_bytes as f64) * 8.0 * 0.95;
|
let target_bits = (req.target_bytes as f64) * 8.0 * 0.95;
|
||||||
let audio_bits = if req.keep_audio {
|
let audio_bits = if req.keep_audio {
|
||||||
@@ -376,6 +410,68 @@ fn cleanup_pass_logs(stem: &Path) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Encode a short sample of the clip at the given settings and measure the
|
||||||
|
/// actual bytes-per-pixel to calibrate the retry loop's starting estimate.
|
||||||
|
/// Returns corrected (width, fps) if the sample revealed a meaningful gap
|
||||||
|
/// between the assumed 0.2 bytes/pixel constant and reality.
|
||||||
|
fn calibrate_via_sample(
|
||||||
|
ffmpeg: &Path,
|
||||||
|
req: &TranscodeRequest,
|
||||||
|
est_width: u32,
|
||||||
|
est_fps: u32,
|
||||||
|
) -> Option<(u32, u32)> {
|
||||||
|
let sample_path = req.scratch_dir.join("gif-calib-sample.gif");
|
||||||
|
let sample_dur = 2.0_f64.min(req.duration_secs);
|
||||||
|
let sample_start = (req.duration_secs / 2.0 - sample_dur / 2.0).max(0.0);
|
||||||
|
|
||||||
|
// Build a throwaway request scoped to the sample window.
|
||||||
|
let mut sample_req = req.clone();
|
||||||
|
sample_req.output = sample_path.clone();
|
||||||
|
sample_req.trim_start_secs = Some(sample_start);
|
||||||
|
sample_req.trim_end_secs = Some(sample_start + sample_dur);
|
||||||
|
sample_req.deleted_frame_indices.clear();
|
||||||
|
sample_req.clicks.clear();
|
||||||
|
sample_req.progress_tx = None;
|
||||||
|
|
||||||
|
let result = encode_gif_pass(ffmpeg, &sample_req, est_width, est_fps);
|
||||||
|
let _ = std::fs::remove_file(&sample_path);
|
||||||
|
if result.is_err() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let sample_bytes = match std::fs::metadata(&sample_path) {
|
||||||
|
Ok(m) => m.len(),
|
||||||
|
Err(_) => return None,
|
||||||
|
};
|
||||||
|
if sample_bytes == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back-compute the effective bytes/pixel from the sample. LZW on a short
|
||||||
|
// clip overstates per-frame cost slightly (less inter-frame reuse) so we
|
||||||
|
// apply a small correction factor toward the conservative side.
|
||||||
|
let aspect = aspect_ratio(req.clip_width, req.clip_height);
|
||||||
|
let sample_h = (est_width as f64 / aspect).round() as u32;
|
||||||
|
let frames = (est_fps as f64 * sample_dur).max(1.0);
|
||||||
|
let measured_bpp = sample_bytes as f64 / (est_width as f64 * sample_h as f64 * frames);
|
||||||
|
// Blend toward the assumed 0.2 constant - don't over-trust a 2s sample.
|
||||||
|
let blended_bpp = measured_bpp * 0.7 + 0.2 * 0.3;
|
||||||
|
|
||||||
|
let color_factor = (req.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0);
|
||||||
|
let assumed_bpp = 0.2 * color_factor;
|
||||||
|
let ratio = assumed_bpp / blended_bpp;
|
||||||
|
// Only recalibrate if the gap is meaningful (>15%). Small gaps aren't
|
||||||
|
// worth the risk of overshooting on a noisy 2s sample.
|
||||||
|
if (ratio - 1.0).abs() < 0.15 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recompute target params with the corrected constant. Scale resolution
|
||||||
|
// by the sqrt of the ratio so file size scales roughly linearly.
|
||||||
|
let new_width = ((est_width as f64 * ratio.sqrt()).round() as u32 / 2).max(60) * 2;
|
||||||
|
let new_fps = ((est_fps as f64 * ratio.sqrt()).round() as u32).max(1).min(est_fps);
|
||||||
|
Some((new_width.min(1280), new_fps))
|
||||||
|
}
|
||||||
|
|
||||||
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||||
let budget_input = GifBudgetInput {
|
let budget_input = GifBudgetInput {
|
||||||
gif_colors: req.gif_colors,
|
gif_colors: req.gif_colors,
|
||||||
@@ -385,6 +481,21 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
gif_budget_mode: req.gif_budget_mode,
|
gif_budget_mode: req.gif_budget_mode,
|
||||||
};
|
};
|
||||||
let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height);
|
let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height);
|
||||||
|
|
||||||
|
// Calibrate the bytes/pixel constant by encoding a short sample first.
|
||||||
|
// The default 0.2 bytes/pixel assumption varies 3-5x by content; measuring
|
||||||
|
// it on this specific clip gives the retry loop a much better starting
|
||||||
|
// point and typically cuts retry count from 4-8 down to 1-2.
|
||||||
|
if req.duration_secs > 4.0 {
|
||||||
|
if let Some((calibrated_w, calibrated_fps)) = calibrate_via_sample(ffmpeg, req, scale_width, effective_fps) {
|
||||||
|
tracing::info!(
|
||||||
|
"gif calibration: sample suggested {calibrated_w}x @ {calibrated_fps}fps (initial was {scale_width}x @ {effective_fps}fps)"
|
||||||
|
);
|
||||||
|
scale_width = calibrated_w;
|
||||||
|
effective_fps = calibrated_fps;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let target = req.target_bytes;
|
let target = req.target_bytes;
|
||||||
// Retry budget scales with the input. A 5s clip rarely needs more than 3-4
|
// Retry budget scales with the input. A 5s clip rarely needs more than 3-4
|
||||||
// attempts; a 60s clip with tight target and high colors can take 8-10.
|
// attempts; a 60s clip with tight target and high colors can take 8-10.
|
||||||
@@ -529,13 +640,14 @@ fn encode_gif_pass(
|
|||||||
|
|
||||||
// Single-pass approach: split the stream, generate palette from one copy,
|
// Single-pass approach: split the stream, generate palette from one copy,
|
||||||
// apply palette to the other. The fps filter handles frame rate conversion.
|
// apply palette to the other. The fps filter handles frame rate conversion.
|
||||||
|
let scale = gif_rgb_scale_filter(scale_width);
|
||||||
let filter_complex = format!(
|
let filter_complex = format!(
|
||||||
"{cprefix}{kprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos,split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors={colors}[p];[s1][p]paletteuse=dither={d}",
|
"{cprefix}{kprefix}fps={fps},{sprefix}{scale},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors={colors}[p];[s1][p]paletteuse=dither={d}",
|
||||||
cprefix = crop_prefix,
|
cprefix = crop_prefix,
|
||||||
kprefix = click_prefix,
|
kprefix = click_prefix,
|
||||||
sprefix = select_prefix,
|
sprefix = select_prefix,
|
||||||
fps = effective_fps,
|
fps = effective_fps,
|
||||||
w = scale_width,
|
scale = scale,
|
||||||
colors = req.gif_colors,
|
colors = req.gif_colors,
|
||||||
d = dither,
|
d = dither,
|
||||||
);
|
);
|
||||||
@@ -567,6 +679,12 @@ fn encode_gif_pass(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn gif_rgb_scale_filter(width: u32) -> String {
|
||||||
|
format!(
|
||||||
|
"scale={width}:-1:flags=lanczos:in_color_matrix=bt709:in_range=tv:in_primaries=bt709:in_transfer=bt709:out_primaries=bt709:out_transfer=srgb:out_range=pc,format=rgb24"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct GifBudgetInput {
|
pub struct GifBudgetInput {
|
||||||
pub gif_colors: u16,
|
pub gif_colors: u16,
|
||||||
@@ -682,29 +800,39 @@ pub fn render_gif_preview(
|
|||||||
if let Some(parent) = out_path.parent() {
|
if let Some(parent) = out_path.parent() {
|
||||||
std::fs::create_dir_all(parent).context("creating preview parent")?;
|
std::fs::create_dir_all(parent).context("creating preview parent")?;
|
||||||
}
|
}
|
||||||
// Generate palette from a sample of the clip (middle 2 seconds or full clip)
|
// The palette depends only on gif_colors and the sampled frame range, not
|
||||||
let palette_path = out_path.parent().unwrap_or(input.parent().unwrap()).join("preview-palette.png");
|
// on target_bytes or dither. Cache it keyed on those inputs so slider
|
||||||
|
// drags (which change target_bytes) skip the expensive palettegen pass.
|
||||||
let sample_start = (midpoint_secs - 1.0).max(0.0);
|
let sample_start = (midpoint_secs - 1.0).max(0.0);
|
||||||
let sample_dur = duration_secs.min(2.0);
|
let sample_dur = duration_secs.min(2.0);
|
||||||
let palette_filter = format!(
|
let palette_key = palette_cache_key(gif_colors, target_width, sample_start, sample_dur);
|
||||||
"scale={}:-2:flags=lanczos,palettegen=stats_mode=diff:max_colors={}",
|
let palette_path = out_path.parent().unwrap_or(input.parent().unwrap())
|
||||||
target_width, gif_colors
|
.join(format!("preview-palette-{palette_key}.png"));
|
||||||
);
|
|
||||||
let mut gen = Command::new(ffmpeg);
|
let need_regen = !palette_path.is_file();
|
||||||
gen.arg("-y")
|
if need_regen {
|
||||||
.arg("-hide_banner")
|
// Drop any stale palettes from previous inputs so temp doesn't grow.
|
||||||
.args(["-ss", &format!("{sample_start}")])
|
clean_stale_palettes(palette_path.parent().unwrap_or(Path::new(".")));
|
||||||
.args(["-t", &format!("{sample_dur}")])
|
let palette_filter = format!(
|
||||||
.arg("-i")
|
"{},palettegen=stats_mode=diff:max_colors={}",
|
||||||
.arg(input)
|
gif_rgb_scale_filter(target_width), gif_colors
|
||||||
.args(["-vf", &palette_filter])
|
);
|
||||||
.arg(&palette_path);
|
let mut gen = Command::new(ffmpeg);
|
||||||
run(&mut gen, "gif preview palette")?;
|
gen.arg("-y")
|
||||||
|
.arg("-hide_banner")
|
||||||
|
.args(["-ss", &format!("{sample_start}")])
|
||||||
|
.args(["-t", &format!("{sample_dur}")])
|
||||||
|
.arg("-i")
|
||||||
|
.arg(input)
|
||||||
|
.args(["-vf", &palette_filter])
|
||||||
|
.arg(&palette_path);
|
||||||
|
run(&mut gen, "gif preview palette")?;
|
||||||
|
}
|
||||||
|
|
||||||
// Apply palette to the target frame
|
// Apply palette to the target frame
|
||||||
let use_filter = format!(
|
let use_filter = format!(
|
||||||
"scale={}:-2:flags=lanczos[x];[x][1:v]paletteuse=dither={}",
|
"{}[x];[x][1:v]paletteuse=dither={}",
|
||||||
target_width, gif_dither
|
gif_rgb_scale_filter(target_width), gif_dither
|
||||||
);
|
);
|
||||||
let mut encode = Command::new(ffmpeg);
|
let mut encode = Command::new(ffmpeg);
|
||||||
encode.arg("-y")
|
encode.arg("-y")
|
||||||
@@ -722,6 +850,28 @@ pub fn render_gif_preview(
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Build a stable cache key for a GIF preview palette from the inputs that
|
||||||
|
/// actually affect palettegen output. Same inputs -> same palette.
|
||||||
|
fn palette_cache_key(gif_colors: u16, target_width: u32, sample_start: f64, sample_dur: f64) -> String {
|
||||||
|
format!(
|
||||||
|
"c{gif_colors}-w{target_width}-s{:.3}-d{:.3}",
|
||||||
|
sample_start, sample_dur
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove old `preview-palette-*.png` files so only the current key remains.
|
||||||
|
fn clean_stale_palettes(dir: &Path) {
|
||||||
|
if let Ok(entries) = std::fs::read_dir(dir) {
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
if let Some(name) = entry.file_name().to_str() {
|
||||||
|
if name.starts_with("preview-palette-") && name.ends_with(".png") {
|
||||||
|
let _ = std::fs::remove_file(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn extract_thumbnails(
|
pub fn extract_thumbnails(
|
||||||
ffmpeg: &Path,
|
ffmpeg: &Path,
|
||||||
input: &Path,
|
input: &Path,
|
||||||
@@ -858,15 +1008,17 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
||||||
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?;
|
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None, false)?;
|
||||||
if !output.status.success() {
|
if !output.status.success() {
|
||||||
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
|
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Run an ffmpeg command with progress monitoring.
|
/// Run an ffmpeg command with progress monitoring via `-progress pipe:1`.
|
||||||
/// progress_tx, if provided, receives (pass, total_passes, percent) updates.
|
/// progress_tx, if provided, receives (pass, total_passes, percent) updates
|
||||||
|
/// driven by ffmpeg's stable key=value output (`out_time_us`) rather than
|
||||||
|
/// fragile stderr line parsing.
|
||||||
fn run_with_progress(
|
fn run_with_progress(
|
||||||
cmd: &mut Command,
|
cmd: &mut Command,
|
||||||
label: &str,
|
label: &str,
|
||||||
@@ -877,7 +1029,13 @@ fn run_with_progress(
|
|||||||
progress_tx: Option<&Sender<EncodeProgress>>,
|
progress_tx: Option<&Sender<EncodeProgress>>,
|
||||||
cancel: Option<&Arc<AtomicBool>>,
|
cancel: Option<&Arc<AtomicBool>>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?;
|
// Ask ffmpeg to emit machine-readable progress on stdout. The output is
|
||||||
|
// "key=value" lines terminated by "progress=continue" / "progress=end".
|
||||||
|
cmd.arg("-progress").arg("pipe:1");
|
||||||
|
let output = run_impl(
|
||||||
|
cmd, label, pass, total_passes, duration_secs, fps,
|
||||||
|
progress_tx.cloned(), cancel.cloned(), true,
|
||||||
|
)?;
|
||||||
if !output.status.success() {
|
if !output.status.success() {
|
||||||
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
|
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
|
||||||
}
|
}
|
||||||
@@ -915,9 +1073,10 @@ fn run_impl(
|
|||||||
progress_pass: u8,
|
progress_pass: u8,
|
||||||
progress_total_passes: u8,
|
progress_total_passes: u8,
|
||||||
progress_duration_secs: f64,
|
progress_duration_secs: f64,
|
||||||
progress_fps: u32,
|
_progress_fps: u32,
|
||||||
progress_tx: Option<Sender<EncodeProgress>>,
|
progress_tx: Option<Sender<EncodeProgress>>,
|
||||||
cancel: Option<Arc<AtomicBool>>,
|
cancel: Option<Arc<AtomicBool>>,
|
||||||
|
read_stdout: bool,
|
||||||
) -> Result<std::process::Output> {
|
) -> Result<std::process::Output> {
|
||||||
use std::process::Stdio;
|
use std::process::Stdio;
|
||||||
|
|
||||||
@@ -930,40 +1089,57 @@ fn run_impl(
|
|||||||
}
|
}
|
||||||
tracing::debug!("{}", printable.to_string_lossy());
|
tracing::debug!("{}", printable.to_string_lossy());
|
||||||
|
|
||||||
|
// When we asked ffmpeg for `-progress pipe:1`, stdout carries the stable
|
||||||
|
// key=value stream; stderr still carries errors. Otherwise null stdout.
|
||||||
|
let stdout_cfg = if read_stdout { Stdio::piped() } else { Stdio::null() };
|
||||||
let mut child = cmd
|
let mut child = cmd
|
||||||
.stdout(Stdio::null())
|
.stdout(stdout_cfg)
|
||||||
.stderr(Stdio::piped())
|
.stderr(Stdio::piped())
|
||||||
.spawn()
|
.spawn()
|
||||||
.with_context(|| format!("spawning ffmpeg for {label}"))?;
|
.with_context(|| format!("spawning ffmpeg for {label}"))?;
|
||||||
|
|
||||||
let stderr = child.stderr.take();
|
let stderr = child.stderr.take();
|
||||||
|
let stdout = if read_stdout { child.stdout.take() } else { None };
|
||||||
let tx = progress_tx.clone();
|
let tx = progress_tx.clone();
|
||||||
|
|
||||||
let mut stderr_handle: Option<thread::JoinHandle<Vec<u8>>> = stderr.map(move |serr| {
|
// Progress reader: parse the key=value stream from stdout. Each update
|
||||||
|
// block ends with "progress=continue" or "progress=end". We track the
|
||||||
|
// latest out_time_us and emit a percent when progress= is seen.
|
||||||
|
let mut stdout_handle: Option<thread::JoinHandle<()>> = stdout.map(|out| {
|
||||||
let tx = tx.as_ref().map(|t| t.clone());
|
let tx = tx.as_ref().map(|t| t.clone());
|
||||||
let encode_dur = progress_duration_secs;
|
let encode_dur_us = (progress_duration_secs * 1_000_000.0).max(1.0);
|
||||||
let fps = progress_fps;
|
|
||||||
let pass = progress_pass;
|
let pass = progress_pass;
|
||||||
let total_passes = progress_total_passes;
|
let total_passes = progress_total_passes;
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
use std::io::{BufRead, BufReader};
|
use std::io::{BufRead, BufReader};
|
||||||
let mut collected = Vec::new();
|
let reader = BufReader::new(out);
|
||||||
let reader = BufReader::new(serr);
|
let mut last_out_time_us: f64 = 0.0;
|
||||||
for line in reader.lines().map_while(Result::ok) {
|
for line in reader.lines().map_while(Result::ok) {
|
||||||
collected.extend_from_slice(line.as_bytes());
|
if let Some((key, value)) = parse_progress_kv(&line) {
|
||||||
collected.push(b'\n');
|
if key == "out_time_us" {
|
||||||
if let Some(frame) = parse_frame_from_stderr(&line) {
|
last_out_time_us = value;
|
||||||
let total = (encode_dur * fps as f64).max(1.0);
|
} else if key == "progress" {
|
||||||
let percent = (frame / total * 100.0).min(100.0);
|
let percent = (last_out_time_us / encode_dur_us * 100.0).clamp(0.0, 100.0);
|
||||||
if let Some(ref sender) = tx {
|
if let Some(ref sender) = tx {
|
||||||
let _ = sender.send(EncodeProgress {
|
let _ = sender.send(EncodeProgress {
|
||||||
pass,
|
pass,
|
||||||
total_passes,
|
total_passes,
|
||||||
percent,
|
percent,
|
||||||
});
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
// Stderr reader: collect bytes for diagnostics. No more frame regex.
|
||||||
|
let mut stderr_handle: Option<thread::JoinHandle<Vec<u8>>> = stderr.map(move |serr| {
|
||||||
|
thread::spawn(move || {
|
||||||
|
let mut collected = Vec::new();
|
||||||
|
use std::io::Read;
|
||||||
|
let mut s = serr;
|
||||||
|
let _ = s.read_to_end(&mut collected);
|
||||||
collected
|
collected
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@@ -973,14 +1149,14 @@ fn run_impl(
|
|||||||
if c.load(Ordering::Relaxed) {
|
if c.load(Ordering::Relaxed) {
|
||||||
let _ = child.kill();
|
let _ = child.kill();
|
||||||
let _ = child.wait();
|
let _ = child.wait();
|
||||||
if let Some(h) = stderr_handle.take() {
|
if let Some(h) = stdout_handle.take() { let _ = h.join(); }
|
||||||
let _ = h.join();
|
if let Some(h) = stderr_handle.take() { let _ = h.join(); }
|
||||||
}
|
|
||||||
bail!("export cancelled");
|
bail!("export cancelled");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
match child.try_wait() {
|
match child.try_wait() {
|
||||||
Ok(Some(status)) => {
|
Ok(Some(status)) => {
|
||||||
|
if let Some(h) = stdout_handle.take() { let _ = h.join(); }
|
||||||
let stderr_bytes = stderr_handle.take()
|
let stderr_bytes = stderr_handle.take()
|
||||||
.and_then(|h| h.join().ok())
|
.and_then(|h| h.join().ok())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
@@ -998,20 +1174,15 @@ fn run_impl(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parse a frame count from an ffmpeg stderr progress line.
|
/// Parse one line of ffmpeg `-progress` output into (key, numeric value).
|
||||||
/// Lines look like: "frame= 123 fps= 30 q=-0.0 size= 1024kB time=00:00:04.10 ..."
|
/// Lines are `key=value`. For `out_time_us` the value is integer microseconds;
|
||||||
fn parse_frame_from_stderr(line: &str) -> Option<f64> {
|
/// for `progress` the value is non-numeric ("continue"/"end") so we return 0.0
|
||||||
let trimmed = line.trim();
|
/// and the caller discriminates on the key.
|
||||||
if !trimmed.starts_with("frame=") {
|
fn parse_progress_kv(line: &str) -> Option<(&str, f64)> {
|
||||||
return None;
|
let line = line.trim();
|
||||||
}
|
let (key, value) = line.split_once('=')?;
|
||||||
// Find the "frame= NNN" token and extract the number after it.
|
let num = value.trim().parse::<f64>().unwrap_or(0.0);
|
||||||
let after = trimmed.strip_prefix("frame=")?.trim_start();
|
Some((key, num))
|
||||||
let end = after
|
|
||||||
.find(|c: char| !c.is_ascii_digit())
|
|
||||||
.unwrap_or(after.len());
|
|
||||||
let frame_str = &after[..end];
|
|
||||||
frame_str.parse().ok()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -1091,16 +1262,38 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parse_ffmpeg_stderr_frame() {
|
fn parse_progress_kv_out_time_us() {
|
||||||
assert_eq!(
|
assert_eq!(parse_progress_kv("out_time_us=5000000"), Some(("out_time_us", 5_000_000.0)));
|
||||||
parse_frame_from_stderr("frame= 123 fps= 30 q=-0.0 size= 1024kB"),
|
}
|
||||||
Some(123.0)
|
|
||||||
);
|
#[test]
|
||||||
assert_eq!(
|
fn parse_progress_kv_progress_continue_returns_zero() {
|
||||||
parse_frame_from_stderr("frame=9999 fps=60.0"),
|
// "continue" is non-numeric, so value parses to 0.0; the key is what matters.
|
||||||
Some(9999.0)
|
assert_eq!(parse_progress_kv("progress=continue"), Some(("progress", 0.0)));
|
||||||
);
|
assert_eq!(parse_progress_kv("progress=end"), Some(("progress", 0.0)));
|
||||||
assert_eq!(parse_frame_from_stderr("size= 1024kB"), None);
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_progress_kv_ignores_non_kv() {
|
||||||
|
assert_eq!(parse_progress_kv("not a kv line"), None);
|
||||||
|
assert_eq!(parse_progress_kv("no_equals_here"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_progress_kv_handles_other_keys() {
|
||||||
|
assert_eq!(parse_progress_kv("frame=123"), Some(("frame", 123.0)));
|
||||||
|
assert_eq!(parse_progress_kv("fps=30.0"), Some(("fps", 30.0)));
|
||||||
|
assert_eq!(parse_progress_kv("bitrate=N/A"), Some(("bitrate", 0.0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gif_scale_forces_bt709_rgb() {
|
||||||
|
let filter = gif_rgb_scale_filter(640);
|
||||||
|
assert!(filter.contains("in_color_matrix=bt709"));
|
||||||
|
assert!(filter.contains("in_range=tv"));
|
||||||
|
assert!(filter.contains("in_transfer=bt709"));
|
||||||
|
assert!(filter.contains("out_transfer=srgb"));
|
||||||
|
assert!(filter.contains("format=rgb24"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
+149
-15
@@ -66,6 +66,11 @@ pub struct SessionState {
|
|||||||
pub monitor_height: u32,
|
pub monitor_height: u32,
|
||||||
pub clicks: Vec<clicks::Click>,
|
pub clicks: Vec<clicks::Click>,
|
||||||
pub segment_start_offsets: Vec<f64>,
|
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)]
|
#[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 let Some(name) = entry.file_name().to_str() {
|
||||||
if (name.starts_with("segment-") && name.ends_with(".mp4"))
|
if (name.starts_with("segment-") && name.ends_with(".mp4"))
|
||||||
|| (name.starts_with("audio-") && name.ends_with(".pcm"))
|
|| (name.starts_with("audio-") && name.ends_with(".pcm"))
|
||||||
|
|| (name.starts_with("preview-palette-") && name.ends_with(".png"))
|
||||||
{
|
{
|
||||||
let _ = std::fs::remove_file(entry.path());
|
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(())
|
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) {
|
fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) {
|
||||||
if let Some(win) = app.get_webview_window("overlay") {
|
if let Some(win) = app.get_webview_window("overlay") {
|
||||||
let _ = win.set_ignore_cursor_events(enabled);
|
let _ = win.set_ignore_cursor_events(enabled);
|
||||||
@@ -453,6 +490,8 @@ fn start_capture(
|
|||||||
monitor_height: monitor_h,
|
monitor_height: monitor_h,
|
||||||
clicks: Vec::new(),
|
clicks: Vec::new(),
|
||||||
segment_start_offsets: vec![0.0],
|
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);
|
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())?;
|
.ok_or_else(|| "no capture in progress".to_string())?;
|
||||||
let elapsed = session.started_at.elapsed().as_secs_f64();
|
let elapsed = session.started_at.elapsed().as_secs_f64();
|
||||||
let frames = session.frame_counter.load(std::sync::atomic::Ordering::Relaxed);
|
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 raw_path = session.stop().map_err(|e| format!("{e:#}"))?;
|
||||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
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");
|
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:#}"))?;
|
.map_err(|e| format!("fixing fps: {e:#}"))?;
|
||||||
let path = if fixed_path.exists() { fixed_path } else { raw_path };
|
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 {
|
if let Some(session) = live {
|
||||||
let elapsed = session.started_at.elapsed().as_secs_f64();
|
let elapsed = session.started_at.elapsed().as_secs_f64();
|
||||||
let frames = session.frame_counter.load(std::sync::atomic::Ordering::Relaxed);
|
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 raw_path = session.stop().map_err(|e| format!("{e:#}"))?;
|
||||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
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");
|
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:#}"))?;
|
.map_err(|e| format!("fixing fps: {e:#}"))?;
|
||||||
let final_path = if fixed_path.exists() { fixed_path } else { raw_path };
|
let final_path = if fixed_path.exists() { fixed_path } else { raw_path };
|
||||||
ss.segments.push(final_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");
|
let audio_concat = temp.join("audio-concat.pcm");
|
||||||
encode::concat_pcm(&ss.audio_segments, &audio_concat)
|
encode::concat_pcm(&ss.audio_segments, &audio_concat)
|
||||||
.map_err(|e| format!("audio concat: {e:#}"))?;
|
.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(
|
adjust_audio_length(
|
||||||
&audio_concat,
|
&audio_concat,
|
||||||
ss.audio_sample_rate.unwrap(),
|
ss.audio_sample_rate.unwrap(),
|
||||||
@@ -821,6 +877,20 @@ pub struct GifEstimate {
|
|||||||
pub dims_label: String,
|
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]
|
#[tauri::command]
|
||||||
fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
|
fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
|
||||||
let budget = encode::GifBudgetInput {
|
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 (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 height = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
|
||||||
let dims_label = format!("{w}x{height} @ {fps}fps");
|
let dims_label = format!("{w}x{height} @ {fps}fps");
|
||||||
|
|
||||||
GifEstimate { width: w, fps, height, dims_label }
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -1467,13 +1572,25 @@ fn cancel_export(state: State<'_, AppState>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
|
fn codec_availability(state: State<'_, AppState>) -> Result<encode::CodecAvailability, String> {
|
||||||
let cfg = lock(&state.config).clone();
|
|
||||||
let clip = lock(&state.last_clip)
|
|
||||||
.clone()
|
|
||||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
|
||||||
|
|
||||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
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() {
|
if !ffmpeg.is_file() {
|
||||||
return Err("ffmpeg.exe not found - run the encoder setup first".to_string());
|
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() {
|
let out_path: PathBuf = match request.output_path.as_deref() {
|
||||||
Some(p) if !p.trim().is_empty() => PathBuf::from(p),
|
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!(
|
out_dir.join(format!(
|
||||||
"bytesize-{}.{}",
|
"bytesize-{}.{}",
|
||||||
timestamp_slug(),
|
timestamp_slug(),
|
||||||
@@ -1539,7 +1656,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
|
|||||||
gif_colors: request.gif_colors.unwrap_or(256),
|
gif_colors: request.gif_colors.unwrap_or(256),
|
||||||
webm_codec: cfg.export.webm_codec,
|
webm_codec: cfg.export.webm_codec,
|
||||||
mp4_codec: cfg.export.mp4_codec,
|
mp4_codec: cfg.export.mp4_codec,
|
||||||
scratch_dir: temp_dir(&state.app_dir),
|
scratch_dir: temp_dir(&app_dir),
|
||||||
crop: request.crop,
|
crop: request.crop,
|
||||||
gif_budget_mode: request.gif_budget_mode,
|
gif_budget_mode: request.gif_budget_mode,
|
||||||
deleted_frame_indices: request.deleted_frame_indices,
|
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_width: clip.width,
|
||||||
clip_height: clip.height,
|
clip_height: clip.height,
|
||||||
progress_tx: None,
|
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 };
|
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);
|
export_cancel.store(false, Ordering::SeqCst);
|
||||||
encode::transcode(&ffmpeg, &req_with_progress).map_err(|e| format!("{e:#}"))?;
|
|
||||||
|
// 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)
|
let size_bytes = std::fs::metadata(&out_path)
|
||||||
.map(|m| m.len())
|
.map(|m| m.len())
|
||||||
@@ -1587,6 +1714,11 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
|
|||||||
pub fn run() {
|
pub fn run() {
|
||||||
let app_dir = exe_dir().expect("resolve exe directory");
|
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 log_dir = app_dir.join("logs");
|
||||||
let _ = std::fs::create_dir_all(&log_dir);
|
let _ = std::fs::create_dir_all(&log_dir);
|
||||||
let file_appender = tracing_appender::rolling::daily(&log_dir, "bytesize.log");
|
let file_appender = tracing_appender::rolling::daily(&log_dir, "bytesize.log");
|
||||||
@@ -1742,6 +1874,7 @@ pub fn run() {
|
|||||||
render_preview,
|
render_preview,
|
||||||
render_raw_preview,
|
render_raw_preview,
|
||||||
estimate_gif_params,
|
estimate_gif_params,
|
||||||
|
estimate_gif_params_table,
|
||||||
reveal_in_explorer,
|
reveal_in_explorer,
|
||||||
open_url,
|
open_url,
|
||||||
show_overlay,
|
show_overlay,
|
||||||
@@ -1756,6 +1889,7 @@ pub fn run() {
|
|||||||
close_window_picker,
|
close_window_picker,
|
||||||
get_overlay_rect,
|
get_overlay_rect,
|
||||||
cancel_export,
|
cancel_export,
|
||||||
|
codec_availability,
|
||||||
])
|
])
|
||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while building ByteSize");
|
.expect("error while building ByteSize");
|
||||||
|
|||||||
+54
-18
@@ -74,17 +74,21 @@
|
|||||||
// Derived
|
// Derived
|
||||||
let trimmedDuration = $derived(Math.max(0.1, trimEnd - trimStart))
|
let trimmedDuration = $derived(Math.max(0.1, trimEnd - trimStart))
|
||||||
// GIF size/dimensions estimate - computed by the Rust backend so the
|
// GIF size/dimensions estimate - computed by the Rust backend so the
|
||||||
// math stays in lockstep with encode.rs::gif_params.
|
// math stays in lockstep with encode.rs::gif_params. We fetch a table of
|
||||||
|
// estimates across a target-bytes grid once per parameter set (fps, dims,
|
||||||
|
// duration, mode, colors) and interpolate on slider drag locally to avoid
|
||||||
|
// one IPC per debounce tick.
|
||||||
let gifEstimate: { width: number; fps: number; height: number; dims_label: string } | null = $state(null)
|
let gifEstimate: { width: number; fps: number; height: number; dims_label: string } | null = $state(null)
|
||||||
let gifEstimateTimer: number | null = null
|
let gifEstimateTimer: number | null = null
|
||||||
|
let gifTable: { key: string; points: { target_bytes: number; width: number; fps: number; height: number }[] } | null = $state(null)
|
||||||
|
|
||||||
async function refreshGifEstimate() {
|
async function refreshGifTable() {
|
||||||
if (!clip || format !== "gif") { gifEstimate = null; return }
|
if (!clip || format !== "gif") { gifTable = null; return }
|
||||||
|
const key = `${fps}|${gifBudgetMode}|${gifColors}|${clip.width}x${clip.height}|${trimmedDuration}`
|
||||||
try {
|
try {
|
||||||
gifEstimate = await api.estimateGifParams({
|
const table = await api.estimateGifParamsTable({
|
||||||
format: "gif",
|
format: "gif",
|
||||||
fps,
|
fps,
|
||||||
target_bytes: Math.round(targetMB * 1_048_576),
|
|
||||||
gif_budget_mode: gifBudgetMode,
|
gif_budget_mode: gifBudgetMode,
|
||||||
gif_dither: gifDither,
|
gif_dither: gifDither,
|
||||||
gif_colors: gifColors,
|
gif_colors: gifColors,
|
||||||
@@ -92,26 +96,50 @@
|
|||||||
clip_height: clip.height,
|
clip_height: clip.height,
|
||||||
duration_secs: trimmedDuration,
|
duration_secs: trimmedDuration,
|
||||||
})
|
})
|
||||||
|
gifTable = { key, points: table.points }
|
||||||
} catch {
|
} catch {
|
||||||
gifEstimate = null
|
gifTable = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Debounced reactive estimate: any change to the inputs re-estimates
|
// Interpolate the cached table for the current target_bytes. GIF width/fps
|
||||||
// ~150 ms after the last change. Cancels in-flight when inputs change again.
|
// are step functions of budget, so we find the bracketing grid points and
|
||||||
|
// pick the lower one (slightly conservative on dims).
|
||||||
|
function interpolateTable(): { width: number; fps: number; height: number; dims_label: string } | null {
|
||||||
|
if (!gifTable || gifTable.points.length === 0) return null
|
||||||
|
const target = Math.round(targetMB * 1_048_576)
|
||||||
|
const pts = gifTable.points
|
||||||
|
let chosen = pts[0]
|
||||||
|
for (const p of pts) {
|
||||||
|
if (p.target_bytes <= target) chosen = p
|
||||||
|
else break
|
||||||
|
}
|
||||||
|
const { width, fps, height } = chosen
|
||||||
|
return { width, fps, height, dims_label: `${width}x${height} @ ${fps}fps` }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debounced: re-fetch the table when any non-target parameter changes;
|
||||||
|
// re-interpolate when targetMB changes (local, no IPC).
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
// Touch every input so the effect re-runs on any of them changing.
|
void phase; void clip; void format
|
||||||
void phase; void clip; void format; void fps; void targetMB
|
if (phase !== "editing" || !clip || format !== "gif") { gifTable = null; gifEstimate = null; return }
|
||||||
void gifBudgetMode; void gifDither; void gifColors
|
const key = `${fps}|${gifBudgetMode}|${gifColors}|${clip.width}x${clip.height}|${trimmedDuration}`
|
||||||
void trimStart; void trimEnd
|
if (!gifTable || gifTable.key !== key) {
|
||||||
if (phase !== "editing" || !clip) return
|
if (gifEstimateTimer !== null) clearTimeout(gifEstimateTimer)
|
||||||
if (gifEstimateTimer !== null) clearTimeout(gifEstimateTimer)
|
gifEstimateTimer = window.setTimeout(() => { void refreshGifTable() }, 150)
|
||||||
gifEstimateTimer = window.setTimeout(() => { void refreshGifEstimate() }, 150)
|
}
|
||||||
return () => {
|
return () => {
|
||||||
if (gifEstimateTimer !== null) { clearTimeout(gifEstimateTimer); gifEstimateTimer = null }
|
if (gifEstimateTimer !== null) { clearTimeout(gifEstimateTimer); gifEstimateTimer = null }
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Local interpolation on targetMB changes - no IPC.
|
||||||
|
$effect(() => {
|
||||||
|
void targetMB
|
||||||
|
if (phase !== "editing" || !clip || format !== "gif") { gifEstimate = null; return }
|
||||||
|
gifEstimate = interpolateTable()
|
||||||
|
})
|
||||||
|
|
||||||
let previewDims = $derived.by(() => {
|
let previewDims = $derived.by(() => {
|
||||||
if (!clip) return ""
|
if (!clip) return ""
|
||||||
if (format === "gif") {
|
if (format === "gif") {
|
||||||
@@ -267,14 +295,22 @@
|
|||||||
if (format !== "gif") { thumbnails = []; return }
|
if (format !== "gif") { thumbnails = []; return }
|
||||||
const cacheKey = `${format}-${fps}`
|
const cacheKey = `${format}-${fps}`
|
||||||
const cached = thumbCache.get(cacheKey)
|
const cached = thumbCache.get(cacheKey)
|
||||||
if (cached) { thumbnails = cached; deletedFrames = new Set(); return }
|
if (cached) {
|
||||||
|
// Promote to most-recently-used so eviction is LRU, not FIFO.
|
||||||
|
// Map iteration is insertion-order; delete + re-set moves the key to the end.
|
||||||
|
thumbCache.delete(cacheKey)
|
||||||
|
thumbCache.set(cacheKey, cached)
|
||||||
|
thumbnails = cached
|
||||||
|
deletedFrames = new Set()
|
||||||
|
return
|
||||||
|
}
|
||||||
loadingThumbs = true
|
loadingThumbs = true
|
||||||
try {
|
try {
|
||||||
const thumbs = await api.extractThumbnails(fps)
|
const thumbs = await api.extractThumbnails(fps)
|
||||||
thumbCache.set(cacheKey, thumbs)
|
thumbCache.set(cacheKey, thumbs)
|
||||||
if (thumbCache.size > 5) {
|
if (thumbCache.size > 5) {
|
||||||
const firstKey = thumbCache.keys().next().value
|
const oldestKey = thumbCache.keys().next().value
|
||||||
if (firstKey) thumbCache.delete(firstKey)
|
if (oldestKey) thumbCache.delete(oldestKey)
|
||||||
}
|
}
|
||||||
thumbnails = thumbs
|
thumbnails = thumbs
|
||||||
deletedFrames = new Set()
|
deletedFrames = new Set()
|
||||||
|
|||||||
+20
-6
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from "svelte"
|
import { onMount } from "svelte"
|
||||||
import { api, type Config } from "./api"
|
import { api, type Config, type CodecAvailability } from "./api"
|
||||||
import HotkeyInput from "./HotkeyInput.svelte"
|
import HotkeyInput from "./HotkeyInput.svelte"
|
||||||
import { open } from "@tauri-apps/plugin-dialog"
|
import { open } from "@tauri-apps/plugin-dialog"
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
let showAdvanced: boolean = $state(false)
|
let showAdvanced: boolean = $state(false)
|
||||||
let activeTab: string = $state("capture")
|
let activeTab: string = $state("capture")
|
||||||
let initialCfg: Config | null = $state(null)
|
let initialCfg: Config | null = $state(null)
|
||||||
|
let codecs: CodecAvailability | null = $state(null)
|
||||||
|
|
||||||
let dirty = $derived.by(() => {
|
let dirty = $derived.by(() => {
|
||||||
if (!cfg || !initialCfg) return false
|
if (!cfg || !initialCfg) return false
|
||||||
@@ -38,7 +39,11 @@
|
|||||||
{ id: "system", label: "System" },
|
{ id: "system", label: "System" },
|
||||||
]
|
]
|
||||||
|
|
||||||
onMount(async () => { cfg = await api.getConfig(); initialCfg = structuredClone(cfg) })
|
onMount(async () => {
|
||||||
|
cfg = await api.getConfig()
|
||||||
|
initialCfg = structuredClone(cfg)
|
||||||
|
try { codecs = await api.codecAvailability() } catch { codecs = null }
|
||||||
|
})
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (cfg) document.documentElement.setAttribute("data-theme", cfg.theme)
|
if (cfg) document.documentElement.setAttribute("data-theme", cfg.theme)
|
||||||
@@ -165,17 +170,20 @@
|
|||||||
<label class="field">
|
<label class="field">
|
||||||
<span class="field-label">WebM codec</span>
|
<span class="field-label">WebM codec</span>
|
||||||
<select bind:value={cfg.export.webm_codec}>
|
<select bind:value={cfg.export.webm_codec}>
|
||||||
<option value="vp9">VP9 (default)</option>
|
<option value="vp9" disabled={codecs ? !codecs.vp9 : false}>VP9 (default){codecs && !codecs.vp9 ? " - unavailable" : ""}</option>
|
||||||
<option value="av1">AV1 (smaller, slower)</option>
|
<option value="av1" disabled={codecs ? !codecs.av1 : false}>AV1 (smaller, slower){codecs && !codecs.av1 ? " - unavailable" : ""}</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label class="field">
|
<label class="field">
|
||||||
<span class="field-label">MP4 codec</span>
|
<span class="field-label">MP4 codec</span>
|
||||||
<select bind:value={cfg.export.mp4_codec}>
|
<select bind:value={cfg.export.mp4_codec}>
|
||||||
<option value="h264">H.264 (default)</option>
|
<option value="h264" disabled={codecs ? !codecs.h264 : false}>H.264 (default){codecs && !codecs.h264 ? " - unavailable" : ""}</option>
|
||||||
<option value="h265">H.265 (smaller, less universal)</option>
|
<option value="h265" disabled={codecs ? !codecs.h265 : false}>H.265 (smaller, less universal){codecs && !codecs.h265 ? " - unavailable" : ""}</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
|
{#if codecs && (!codecs.av1 || !codecs.h265)}
|
||||||
|
<p class="codec-note">Some codecs are unavailable in your ffmpeg build and disabled above.</p>
|
||||||
|
{/if}
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -442,6 +450,12 @@
|
|||||||
.advanced-toggle svg { transition: transform 150ms; }
|
.advanced-toggle svg { transition: transform 150ms; }
|
||||||
.advanced-toggle svg.rotated { transform: rotate(180deg); }
|
.advanced-toggle svg.rotated { transform: rotate(180deg); }
|
||||||
|
|
||||||
|
.codec-note {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
.path-row { display: flex; gap: 6px; }
|
.path-row { display: flex; gap: 6px; }
|
||||||
.path-input { flex: 1; font-family: var(--mono); font-size: 12px; }
|
.path-input { flex: 1; font-family: var(--mono); font-size: 12px; }
|
||||||
|
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ export type ClickEvent = {
|
|||||||
time_secs: number
|
time_secs: number
|
||||||
x: number
|
x: number
|
||||||
y: number
|
y: number
|
||||||
|
button: "Left" | "Right" | "Middle"
|
||||||
}
|
}
|
||||||
|
|
||||||
export type RecordedClip = {
|
export type RecordedClip = {
|
||||||
@@ -148,6 +149,24 @@ export type GifEstimate = {
|
|||||||
dims_label: string
|
dims_label: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type GifEstimatePoint = {
|
||||||
|
target_bytes: number
|
||||||
|
width: number
|
||||||
|
fps: number
|
||||||
|
height: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GifEstimateTable = {
|
||||||
|
points: GifEstimatePoint[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CodecAvailability = {
|
||||||
|
h264: boolean
|
||||||
|
h265: boolean
|
||||||
|
vp9: boolean
|
||||||
|
av1: boolean
|
||||||
|
}
|
||||||
|
|
||||||
export type AudioFailed = string
|
export type AudioFailed = string
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
@@ -191,6 +210,17 @@ export const api = {
|
|||||||
duration_secs: number
|
duration_secs: number
|
||||||
}) =>
|
}) =>
|
||||||
invoke<GifEstimate>("estimate_gif_params", { request: input }),
|
invoke<GifEstimate>("estimate_gif_params", { request: input }),
|
||||||
|
estimateGifParamsTable: (input: {
|
||||||
|
format: Format
|
||||||
|
fps: number
|
||||||
|
gif_budget_mode?: GifBudgetMode
|
||||||
|
gif_dither?: GifDither
|
||||||
|
gif_colors?: number
|
||||||
|
clip_width: number
|
||||||
|
clip_height: number
|
||||||
|
duration_secs: number
|
||||||
|
}) =>
|
||||||
|
invoke<GifEstimateTable>("estimate_gif_params_table", { request: input }),
|
||||||
renderRawPreview: (timestamp: number) =>
|
renderRawPreview: (timestamp: number) =>
|
||||||
invoke<string>("render_raw_preview", { timestamp }),
|
invoke<string>("render_raw_preview", { timestamp }),
|
||||||
defaultOutputPath: (format: Format) =>
|
defaultOutputPath: (format: Format) =>
|
||||||
@@ -214,6 +244,7 @@ export const api = {
|
|||||||
onAudioFailed: (handler: (msg: string) => void): Promise<UnlistenFn> =>
|
onAudioFailed: (handler: (msg: string) => void): Promise<UnlistenFn> =>
|
||||||
listen<string>("audio-failed", (e) => handler(e.payload)),
|
listen<string>("audio-failed", (e) => handler(e.payload)),
|
||||||
cancelExport: () => invoke<void>("cancel_export"),
|
cancelExport: () => invoke<void>("cancel_export"),
|
||||||
|
codecAvailability: () => invoke<CodecAvailability>("codec_availability"),
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatBytes(n: number): string {
|
export function formatBytes(n: number): string {
|
||||||
|
|||||||
Reference in New Issue
Block a user