fix the behaviour bugs in capture, encode and the overlay poller
This commit is contained in:
+24
-13
@@ -524,15 +524,19 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
// the HDR->SDR tonemap happens on the GPU before this pipe, so ffmpeg
|
||||
// receives plain SDR BGRA8 already in bt709/tv range.
|
||||
let mut filter_parts: Vec<String> = Vec::new();
|
||||
// The scale decision has to be taken on the width that survives the crop.
|
||||
// Testing the monitor width here used to upscale a narrow crop on a wide
|
||||
// monitor all the way to the encode limit, while the session reported the
|
||||
// crop's own width - so the recorded clip's dimensions were a lie and the
|
||||
// click overlays were scaled against the wrong frame.
|
||||
let (crop_w, crop_h) = cropped_dims(setup.width, setup.height, setup.crop);
|
||||
if let Some(c) = setup.crop {
|
||||
let x = c.x.max(0);
|
||||
let y = c.y.max(0);
|
||||
let w = c.width.min(setup.width.saturating_sub(x.cast_unsigned()));
|
||||
let h = c.height.min(setup.height.saturating_sub(y.cast_unsigned()));
|
||||
filter_parts.push(format!("crop={w}:{h}:{x}:{y}"));
|
||||
filter_parts.push(format!("crop={crop_w}:{crop_h}:{x}:{y}"));
|
||||
}
|
||||
let limit = setup.encode_width_limit;
|
||||
if setup.width > limit {
|
||||
if crop_w > limit {
|
||||
filter_parts.push(format!("scale={limit}:-2"));
|
||||
} else {
|
||||
filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string());
|
||||
@@ -794,7 +798,22 @@ fn compute_output_dims(
|
||||
crop: Option<CaptureRect>,
|
||||
width_limit: u32,
|
||||
) -> (u32, u32) {
|
||||
let (raw_w, raw_h) = match crop {
|
||||
let (raw_w, raw_h) = cropped_dims(monitor_w, monitor_h, crop);
|
||||
let cap = width_limit;
|
||||
if raw_w > cap {
|
||||
let scale = f64::from(cap) / f64::from(raw_w);
|
||||
let nh = crate::encode::round_u32(f64::from(raw_h) * scale);
|
||||
(cap, (nh / 2) * 2)
|
||||
} else {
|
||||
((raw_w / 2) * 2, (raw_h / 2) * 2)
|
||||
}
|
||||
}
|
||||
|
||||
/// The dimensions left after the crop, clamped so the rect cannot hang off the
|
||||
/// monitor. Shared by the ffmpeg filter and the reported clip size so the two
|
||||
/// cannot disagree about how wide the frame ends up.
|
||||
fn cropped_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>) -> (u32, u32) {
|
||||
match crop {
|
||||
Some(c) => {
|
||||
let x = c.x.max(0).cast_unsigned();
|
||||
let y = c.y.max(0).cast_unsigned();
|
||||
@@ -804,14 +823,6 @@ fn compute_output_dims(
|
||||
)
|
||||
}
|
||||
None => (monitor_w, monitor_h),
|
||||
};
|
||||
let cap = width_limit;
|
||||
if raw_w > cap {
|
||||
let scale = f64::from(cap) / f64::from(raw_w);
|
||||
let nh = crate::encode::round_u32(f64::from(raw_h) * scale);
|
||||
(cap, (nh / 2) * 2)
|
||||
} else {
|
||||
((raw_w / 2) * 2, (raw_h / 2) * 2)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+50
-10
@@ -139,7 +139,20 @@ fn click_box(clip_x: i32, clip_y: i32, clip_w: u32, clip_h: u32) -> Option<(i32,
|
||||
Some((x, y))
|
||||
}
|
||||
|
||||
fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32) -> Option<String> {
|
||||
/// The time `apply_trim` cuts off the head of the clip. A seek rebases the
|
||||
/// filter graph's timestamps to zero, so anything recorded against clip time -
|
||||
/// the click highlights - has to be shifted by the same amount or it lands late
|
||||
/// by the length of the trim.
|
||||
fn trim_offset(req: &TranscodeRequest) -> f64 {
|
||||
req.trim_start_secs.filter(|s| *s > 0.001).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
fn click_filters(
|
||||
clicks: &[Click],
|
||||
clip_w: u32,
|
||||
clip_h: u32,
|
||||
time_offset: f64,
|
||||
) -> Option<String> {
|
||||
if clicks.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -161,8 +174,12 @@ fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32) -> Option<String> {
|
||||
let Some((x, y)) = click_box(click.x, click.y, clip_w, clip_h) else {
|
||||
continue;
|
||||
};
|
||||
let t1 = (click.time_secs - 0.05).max(0.0);
|
||||
let t2 = click.time_secs + 0.25;
|
||||
let t = click.time_secs - time_offset;
|
||||
if t + 0.25 < 0.0 {
|
||||
continue;
|
||||
}
|
||||
let t1 = (t - 0.05).max(0.0);
|
||||
let t2 = t + 0.25;
|
||||
let color = match click.button {
|
||||
crate::clicks::MouseButton::Left => "yellow@0.6",
|
||||
crate::clicks::MouseButton::Right => "blue@0.6",
|
||||
@@ -410,7 +427,7 @@ fn two_pass_video(
|
||||
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
||||
|
||||
let crop = crop_filter(req.crop);
|
||||
let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height);
|
||||
let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height, trim_offset(req));
|
||||
let combined_vf: Option<String> = match (&crop, &clicks) {
|
||||
(Some(c), Some(k)) => Some(format!("{c},{k}")),
|
||||
(Some(c), None) => Some(c.clone()),
|
||||
@@ -756,7 +773,7 @@ fn encode_gif_pass(
|
||||
let crop_prefix = crop_filter(req.crop)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let click_prefix = click_filters(&req.clicks, req.clip_width, req.clip_height)
|
||||
let click_prefix = click_filters(&req.clicks, req.clip_width, req.clip_height, trim_offset(req))
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices)
|
||||
@@ -990,9 +1007,12 @@ pub(crate) fn render_gif_preview(
|
||||
.args(["-lavfi", &use_filter])
|
||||
.args(["-frames:v", "1"])
|
||||
.arg(out_path);
|
||||
let result = run(&mut encode, "gif preview encode");
|
||||
drop(std::fs::remove_file(&palette_path));
|
||||
result
|
||||
// The palette is deliberately left in place: the cache key above exists so a
|
||||
// render with the same inputs can skip palettegen entirely, and deleting it
|
||||
// here meant every render regenerated it. clear_temp_segments sweeps
|
||||
// preview-palette-*.png between recordings, and clean_stale_palettes drops
|
||||
// the keys that no longer apply.
|
||||
run(&mut encode, "gif preview encode")
|
||||
}
|
||||
|
||||
/// Build a stable cache key for a GIF preview palette from the inputs that
|
||||
@@ -1485,7 +1505,7 @@ mod tests {
|
||||
let clicks: Vec<Click> = (0..100)
|
||||
.map(|i| Click { time_secs: f64::from(i), x: i, y: i, button: crate::clicks::MouseButton::Left })
|
||||
.collect();
|
||||
let filter = click_filters(&clicks, 1920, 1080).unwrap();
|
||||
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||
let count = filter.matches("drawbox").count();
|
||||
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
|
||||
}
|
||||
@@ -1517,7 +1537,7 @@ mod tests {
|
||||
Click { time_secs: 0.5, x: -620, y: 115, button: crate::clicks::MouseButton::Left },
|
||||
Click { time_secs: 0.9, x: 500, y: 400, button: crate::clicks::MouseButton::Left },
|
||||
];
|
||||
let filter = click_filters(&clicks, 1920, 1080).unwrap();
|
||||
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||
assert_eq!(filter.matches("drawbox").count(), 1);
|
||||
assert!(filter.contains("x=488:y=388"));
|
||||
// Every emitted box must be non-negative, or drawbox throws it away.
|
||||
@@ -1525,6 +1545,26 @@ mod tests {
|
||||
assert!(!filter.contains("y=-"));
|
||||
}
|
||||
|
||||
/// A trim seeks past the head of the clip, which rebases the filter timeline
|
||||
/// to zero, so a click recorded against clip time has to move back by the
|
||||
/// same amount or it fires late by the length of the trim.
|
||||
#[test]
|
||||
fn click_times_are_rebased_by_the_trim() {
|
||||
let clicks = vec![Click { time_secs: 6.0, x: 500, y: 400, button: crate::clicks::MouseButton::Left }];
|
||||
let untrimmed = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||
assert!(untrimmed.contains("between(t,5.950,6.250)"));
|
||||
let trimmed = click_filters(&clicks, 1920, 1080, 5.0).unwrap();
|
||||
assert!(trimmed.contains("between(t,0.950,1.250)"));
|
||||
assert!(!trimmed.contains("6.250"));
|
||||
}
|
||||
|
||||
/// A click that happened before the trimmed window has nothing left to draw.
|
||||
#[test]
|
||||
fn clicks_before_the_trim_are_dropped() {
|
||||
let clicks = vec![Click { time_secs: 1.0, x: 500, y: 400, button: crate::clicks::MouseButton::Left }];
|
||||
assert!(click_filters(&clicks, 1920, 1080, 5.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_shrink_factor_resolution_uses_sqrt() {
|
||||
// ratio 0.25 -> halving the *width* (which quarters pixels) needs sqrt(0.25)=0.5
|
||||
|
||||
+97
-65
@@ -64,6 +64,10 @@ pub struct AppState {
|
||||
pub picker: Mutex<Option<window_picker::PickerSession>>,
|
||||
pub overlay_poll_shutdown: Arc<AtomicBool>,
|
||||
pub export_cancel: Arc<AtomicBool>,
|
||||
/// Held for the duration of an export. Without it a second export could
|
||||
/// start while the first was still encoding, and its reset of the shared
|
||||
/// cancel flag would revive the run the user had just cancelled.
|
||||
pub exporting: Arc<AtomicBool>,
|
||||
pub overlay_aspect_ratio: Mutex<Option<f64>>,
|
||||
/// (active flag, condvar) so the overlay click-through poll thread can park
|
||||
/// itself when no overlay is on screen instead of waking every 80ms.
|
||||
@@ -466,12 +470,6 @@ fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) {
|
||||
if let Some(win) = app.get_webview_window("overlay") {
|
||||
drop(win.set_ignore_cursor_events(enabled));
|
||||
}
|
||||
}
|
||||
|
||||
fn try_start_audio(
|
||||
app: &AppHandle,
|
||||
enabled: bool,
|
||||
@@ -524,9 +522,18 @@ fn watch_audio_death(app: AppHandle, died: Arc<AtomicBool>) {
|
||||
}
|
||||
};
|
||||
if let Some(session) = take {
|
||||
// Drain the dead thread so its handle doesn't leak. The pcm
|
||||
// it already wrote stays in place for stop_capture to mux.
|
||||
drop(session.stop());
|
||||
// Drain the dead thread so its handle doesn't leak, and keep the
|
||||
// pcm it already wrote: stop_capture muxes whatever is in
|
||||
// audio_segments, so discarding the path here threw away
|
||||
// everything captured before the device went away.
|
||||
let path = session.stop();
|
||||
{
|
||||
let st = app.state::<AppState>();
|
||||
let mut slot = lock(&st.session);
|
||||
if let Some(ss) = slot.as_mut() {
|
||||
ss.audio_segments.push(path);
|
||||
}
|
||||
}
|
||||
drop(app.emit(
|
||||
"audio-failed",
|
||||
"audio device lost - endpoint changed or was unplugged".to_string(),
|
||||
@@ -577,8 +584,6 @@ fn start_capture(
|
||||
)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
set_overlay_clickthrough(&app, true);
|
||||
|
||||
let audio_path = audio_segment_path(&state.app_dir, 1);
|
||||
let audio_session = try_start_audio(&app, cfg.capture.capture_audio, audio_path);
|
||||
|
||||
@@ -756,9 +761,7 @@ fn restart_audio_capture(
|
||||
reason = "one recording-finalisation transaction; the steps share session state and temp paths"
|
||||
)]
|
||||
#[tauri::command]
|
||||
fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
set_overlay_clickthrough(&app, false);
|
||||
|
||||
fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
let mut ss = lock(&state.session)
|
||||
.take()
|
||||
.ok_or_else(|| "no session to stop".to_string())?;
|
||||
@@ -1245,18 +1248,66 @@ fn cleanup_temp_on_exit(app: &AppHandle) {
|
||||
clear_temp_segments(&st.app_dir, false);
|
||||
}
|
||||
|
||||
/// Whether the overlay should currently ignore the cursor. `None` means there is
|
||||
/// nothing to decide: no overlay window, it is hidden, or a query failed.
|
||||
///
|
||||
/// This is the only writer of the overlay's click-through state. `start_capture`
|
||||
/// and `stop_capture` used to flip the same property directly, which desynced it
|
||||
/// from the value tracked in the poll loop: after a recording stopped, the poller
|
||||
/// believed the frame was already click-through and never put it back.
|
||||
fn overlay_should_ignore_cursor(app: &AppHandle) -> Option<bool> {
|
||||
use windows::Win32::Foundation::{HWND, POINT};
|
||||
use windows::Win32::UI::HiDpi::GetDpiForWindow;
|
||||
use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
|
||||
|
||||
let overlay = app.get_webview_window("overlay")?;
|
||||
if !overlay.is_visible().unwrap_or(false) {
|
||||
return None;
|
||||
}
|
||||
let state = app.state::<AppState>();
|
||||
if lock(&state.capture).is_some() {
|
||||
// Mid-recording the frame is inert, so clicks reach the app below it.
|
||||
return Some(true);
|
||||
}
|
||||
|
||||
let mut pt = POINT::default();
|
||||
// SAFETY: `pt` is a live local that GetCursorPos writes through.
|
||||
if unsafe { GetCursorPos(&raw mut pt) }.is_err() {
|
||||
return None;
|
||||
}
|
||||
let raw = overlay.hwnd().ok()?;
|
||||
let (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize)?;
|
||||
|
||||
// SAFETY: `raw` is the overlay's own live HWND from Tauri.
|
||||
let dpi = unsafe { GetDpiForWindow(HWND(raw.0.cast::<std::ffi::c_void>())) };
|
||||
let scale = if dpi > 0 { f64::from(dpi) / 96.0 } else { 1.0 };
|
||||
let border = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale);
|
||||
let titlebar = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
||||
|
||||
// The border and titlebar stay interactive so the frame can still be dragged
|
||||
// and resized; only the capture area itself passes clicks through.
|
||||
let inner_left = vl + border;
|
||||
let inner_top = vt + border + titlebar;
|
||||
let inner_right = vr - border;
|
||||
let inner_bottom = vb - border;
|
||||
|
||||
Some(
|
||||
pt.x >= inner_left
|
||||
&& pt.x < inner_right
|
||||
&& pt.y >= inner_top
|
||||
&& pt.y < inner_bottom,
|
||||
)
|
||||
}
|
||||
|
||||
fn start_overlay_clickthrough_poll(
|
||||
app: AppHandle,
|
||||
shutdown: Arc<AtomicBool>,
|
||||
live: Arc<(Mutex<bool>, std::sync::Condvar)>,
|
||||
) {
|
||||
use std::time::Duration;
|
||||
use windows::Win32::Foundation::{HWND, POINT};
|
||||
use windows::Win32::UI::HiDpi::GetDpiForWindow;
|
||||
use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let mut last_inner: Option<bool> = None;
|
||||
let mut last: Option<bool> = None;
|
||||
while !shutdown.load(Ordering::Relaxed) {
|
||||
// Park until the overlay is shown. Without this the poller woke
|
||||
// every 80ms for the whole process lifetime just to re-check
|
||||
@@ -1273,52 +1324,18 @@ fn start_overlay_clickthrough_poll(
|
||||
}
|
||||
}
|
||||
|
||||
let Some(overlay) = app.get_webview_window("overlay") else {
|
||||
continue;
|
||||
};
|
||||
if !overlay.is_visible().unwrap_or(false) {
|
||||
last_inner = None;
|
||||
continue;
|
||||
let target = overlay_should_ignore_cursor(&app);
|
||||
if target != last {
|
||||
if let (Some(overlay), Some(value)) = (app.get_webview_window("overlay"), target)
|
||||
{
|
||||
drop(overlay.set_ignore_cursor_events(value));
|
||||
}
|
||||
last = target;
|
||||
}
|
||||
|
||||
let state = app.state::<AppState>();
|
||||
let is_recording = lock(&state.capture).is_some();
|
||||
if is_recording {
|
||||
last_inner = Some(true);
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut pt = POINT::default();
|
||||
// SAFETY: `pt` is a live local that GetCursorPos writes through.
|
||||
if unsafe { GetCursorPos(&raw mut pt) }.is_err() {
|
||||
continue;
|
||||
}
|
||||
let Ok(raw) = overlay.hwnd() else { continue };
|
||||
|
||||
let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// SAFETY: `raw` is the overlay's own live HWND from Tauri.
|
||||
let dpi = unsafe { GetDpiForWindow(HWND(raw.0.cast::<std::ffi::c_void>())) };
|
||||
let scale = if dpi > 0 { f64::from(dpi) / 96.0 } else { 1.0 };
|
||||
let border = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale);
|
||||
let titlebar = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
||||
|
||||
let inner_left = vl + border;
|
||||
let inner_top = vt + border + titlebar;
|
||||
let inner_right = vr - border;
|
||||
let inner_bottom = vb - border;
|
||||
|
||||
let in_inner = pt.x >= inner_left
|
||||
&& pt.x < inner_right
|
||||
&& pt.y >= inner_top
|
||||
&& pt.y < inner_bottom;
|
||||
|
||||
if last_inner != Some(in_inner) {
|
||||
drop(overlay.set_ignore_cursor_events(in_inner));
|
||||
last_inner = Some(in_inner);
|
||||
}
|
||||
// The only sleep in the loop, and deliberately unconditional: every
|
||||
// branch above has to pace itself, or the thread spins at full speed
|
||||
// for the whole recording.
|
||||
std::thread::sleep(Duration::from_millis(80));
|
||||
}
|
||||
});
|
||||
@@ -1404,9 +1421,9 @@ fn hide_overlay(app: AppHandle) -> Result<(), String> {
|
||||
let win = app
|
||||
.get_webview_window("overlay")
|
||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||
// Reset click-through so the next show starts from a known state, and park
|
||||
// the poll thread until show_overlay wakes it again.
|
||||
drop(win.set_ignore_cursor_events(false));
|
||||
// Leave the click-through state alone - it is the poll thread's to own, and
|
||||
// it stays consistent with the window because nothing else writes it. Just
|
||||
// park the poller until show_overlay wakes it again.
|
||||
{
|
||||
let st = app.state::<AppState>();
|
||||
let (lock, cvar) = &*st.overlay_poll_live;
|
||||
@@ -1934,6 +1951,15 @@ fn codec_availability(state: State<'_, AppState>) -> Result<encode::CodecAvailab
|
||||
Ok(encode::codec_availability(&ffmpeg))
|
||||
}
|
||||
|
||||
/// Clears the export flag on every exit path, including the `?` returns below.
|
||||
struct ExportGuard(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for ExportGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
// One export is one transaction: resolve the output path, translate the trim
|
||||
// and crop into encoder terms, run the encode, and report the size. Splitting
|
||||
// it would mean threading the same resolved state through the pieces.
|
||||
@@ -1943,6 +1969,11 @@ fn codec_availability(state: State<'_, AppState>) -> Result<encode::CodecAvailab
|
||||
)]
|
||||
#[tauri::command]
|
||||
async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
|
||||
if state.exporting.swap(true, Ordering::SeqCst) {
|
||||
return Err("an export is already running".to_string());
|
||||
}
|
||||
let _export = ExportGuard(state.exporting.clone());
|
||||
|
||||
let (cfg, clip, app_dir, export_cancel) = {
|
||||
let cfg = lock(&state.config).clone();
|
||||
let clip = lock(&state.last_clip)
|
||||
@@ -2148,6 +2179,7 @@ pub fn run() {
|
||||
picker: Mutex::new(None),
|
||||
overlay_poll_shutdown: Arc::new(AtomicBool::new(false)),
|
||||
export_cancel: Arc::new(AtomicBool::new(false)),
|
||||
exporting: Arc::new(AtomicBool::new(false)),
|
||||
overlay_aspect_ratio: Mutex::new(None),
|
||||
overlay_poll_live: Arc::new((Mutex::new(false), std::sync::Condvar::new())),
|
||||
};
|
||||
|
||||
+4
-2
@@ -409,11 +409,13 @@
|
||||
// preview so one debounced render fires per change-burst - previously the
|
||||
// debounced effect here and TrimPanel's synchronous onAfterChange could
|
||||
// both trigger a render for the same change.
|
||||
//
|
||||
// Trim and crop are deliberately not inputs: render_preview samples the middle
|
||||
// of the whole clip and ignores both, so depending on them bought an extra
|
||||
// ffmpeg run per drag that could not change a pixel.
|
||||
$effect(() => {
|
||||
void phase; void format; void fps; void targetMB
|
||||
void gifBudgetMode; void gifDither; void gifColors
|
||||
void trimStart; void trimEnd
|
||||
void cropEnabled; void cropX; void cropY; void cropW; void cropH
|
||||
if (phase === "editing" && format) {
|
||||
const timer = window.setTimeout(() => { void refreshPreview() }, 300)
|
||||
return () => { clearTimeout(timer) }
|
||||
|
||||
Reference in New Issue
Block a user