diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 06bc04f..6c48ab5 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -80,10 +80,8 @@ fn find_fxc() -> Option { continue; } let fxc = entry.path().join("x64").join("fxc.exe"); - if fxc.is_file() { - if best.as_ref().map_or(true, |(b, _)| name.as_str() > b.as_str()) { - best = Some((name, fxc)); - } + if fxc.is_file() && best.as_ref().is_none_or(|(b, _)| name.as_str() > b.as_str()) { + best = Some((name, fxc)); } } best.map(|(_, p)| p) diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index d93bced..81356f7 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -76,9 +76,6 @@ pub struct CaptureHandler { /// D3D11 device/context from the frame). Recreated on resize. pipeline: Option, frame_count: Arc, - /// TEMP DIAG: log per-frame timing for the first 10 frames. - timing_n: u32, - timing_start: Option, } /// Persistent D3D11 state for the HDR->SDR tonemap pass. Owns the render @@ -111,7 +108,7 @@ impl TonemapPipeline { // Validated against the VS bytecode by CreateInputLayout. let input_elements = [ D3D11_INPUT_ELEMENT_DESC { - SemanticName: windows::core::PCSTR(b"POSITION\0".as_ptr()), + SemanticName: windows::core::PCSTR(c"POSITION".as_ptr().cast()), SemanticIndex: 0, Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT, InputSlot: 0, @@ -120,7 +117,7 @@ impl TonemapPipeline { InstanceDataStepRate: 0, }, D3D11_INPUT_ELEMENT_DESC { - SemanticName: windows::core::PCSTR(b"TEXCOORD\0".as_ptr()), + SemanticName: windows::core::PCSTR(c"TEXCOORD".as_ptr().cast()), SemanticIndex: 0, Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT, InputSlot: 0, @@ -167,7 +164,7 @@ impl TonemapPipeline { } let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?; - // Pixel shader: ACES tonemap + bt709 OETF. + // Pixel shader: Hable tonemap + bt709 OETF. let mut ps = None; unsafe { device.CreatePixelShader(TONEMAP_PS, None, Some(&mut ps))?; @@ -235,7 +232,7 @@ impl TonemapPipeline { } let render_target = render_target.ok_or_else(|| anyhow!("CreateTexture2D rt returned null"))?; - let rtv_desc = D3D11_RENDER_TARGET_VIEW_DESC { + let view_desc = D3D11_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT_B8G8R8A8_UNORM, ViewDimension: D3D11_RTV_DIMENSION_TEXTURE2D, Anonymous: windows::Win32::Graphics::Direct3D11::D3D11_RENDER_TARGET_VIEW_DESC_0 { @@ -244,7 +241,7 @@ impl TonemapPipeline { }; let mut rtv = None; unsafe { - device.CreateRenderTargetView(&render_target, Some(&rtv_desc), Some(&mut rtv))?; + device.CreateRenderTargetView(&render_target, Some(&view_desc), Some(&mut rtv))?; } let rtv = rtv.ok_or_else(|| anyhow!("CreateRenderTargetView returned null"))?; @@ -367,7 +364,7 @@ impl TonemapPipeline { (mapped.RowPitch as usize) * (self.height as usize), ); // RowPitch may exceed width*4 (alignment); copy row by row. - if mapped.RowPitch as u32 == row_bytes { + if mapped.RowPitch == row_bytes { out.write_all(&src_slice[..(row_bytes as usize) * (self.height as usize)]) .map_err(|e| anyhow!("writing tonemapped frame: {e}"))?; } else { @@ -465,8 +462,6 @@ impl GraphicsCaptureApiHandler for CaptureHandler { height: setup.height, pipeline: None, frame_count: setup.frame_counter.clone(), - timing_n: 0, - timing_start: None, }) } @@ -475,7 +470,6 @@ impl GraphicsCaptureApiHandler for CaptureHandler { frame: &mut Frame<'_>, _capture_control: InternalCaptureControl, ) -> Result<(), Self::Error> { - let start = std::time::Instant::now(); let Some(stdin) = self.stdin.as_mut() else { return Ok(()); }; @@ -492,13 +486,6 @@ impl GraphicsCaptureApiHandler for CaptureHandler { let pipeline = self.pipeline.as_mut().expect("just initialized"); pipeline.process(device, context, src, stdin)?; - // TEMP DIAG: per-frame timing for the first 10 frames. - if self.timing_n < 10 { - let elapsed = start.elapsed().as_millis(); - tracing::warn!("DIAG-TIMING frame {}: {}ms", self.timing_n, elapsed); - self.timing_n += 1; - } - self.frame_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed); Ok(()) } diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 479dbd8..7e110bf 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -60,24 +60,47 @@ pub struct TranscodeRequest { const MAX_CLICK_HIGHLIGHTS: usize = 50; -fn click_filters(req: &TranscodeRequest) -> Option { - if req.clicks.is_empty() { +const BOX_SIZE: i32 = 24; +const BOX_HALF: i32 = BOX_SIZE / 2; + +/// What `click_filters` needs to place the highlight boxes. +fn click_box(clip_x: i32, clip_y: i32, clip_w: u32, clip_h: u32) -> Option<(i32, i32)> { + let vw = clip_w as i32; + let vh = clip_h as i32; + // Only suppress when the point lies entirely outside the frame, so a click + // just inside an edge still gets the sliver of box that is visible. + let outside = clip_x + BOX_HALF <= 0 + || clip_y + BOX_HALF <= 0 + || clip_x - BOX_HALF >= vw + || clip_y - BOX_HALF >= vh; + if outside { + return None; + } + let x = (clip_x - BOX_HALF).clamp(0, (vw - BOX_SIZE).max(0)); + let y = (clip_y - BOX_HALF).clamp(0, (vh - BOX_SIZE).max(0)); + Some((x, y)) +} + +fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32) -> Option { + if clicks.is_empty() { return None; } - let size = 24i32; - let half = size / 2; let mut parts: Vec = Vec::new(); - let clicks_to_render = req.clicks.len().min(MAX_CLICK_HIGHLIGHTS); - if req.clicks.len() > MAX_CLICK_HIGHLIGHTS { + let clicks_to_render = clicks.len().min(MAX_CLICK_HIGHLIGHTS); + if clicks.len() > MAX_CLICK_HIGHLIGHTS { tracing::warn!( "{} click events recorded, only first {} will be highlighted", - req.clicks.len(), + clicks.len(), MAX_CLICK_HIGHLIGHTS ); } - for click in &req.clicks[..clicks_to_render] { - let x = click.x - half; - let y = click.y - half; + for click in &clicks[..clicks_to_render] { + // Clicks recorded outside the capture region (or outside the crop) land + // behind the origin. Clamping here keeps the box inside the frame; + // without it the offsets went negative and drawbox dropped the box. + 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 color = match click.button { @@ -86,7 +109,7 @@ fn click_filters(req: &TranscodeRequest) -> Option { crate::clicks::MouseButton::Middle => "green@0.6", }; parts.push(format!( - "drawbox=x={x}:y={y}:w={size}:h={size}:color={color}:t=2:enable='between(t,{t1:.3},{t2:.3})'" + "drawbox=x={x}:y={y}:w={BOX_SIZE}:h={BOX_SIZE}:color={color}:t=2:enable='between(t,{t1:.3},{t2:.3})'" )); } if parts.is_empty() { @@ -321,7 +344,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); + let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height); let combined_vf: Option = match (&crop, &clicks) { (Some(c), Some(k)) => Some(format!("{c},{k}")), (Some(c), None) => Some(c.clone()), @@ -555,7 +578,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { let mut prev_actual: Option = None; for attempt in 0..max_retries { - if req.cancel.as_ref().map_or(false, |c| c.load(Ordering::Relaxed)) { + if req.cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) { bail!("export cancelled"); } // Last resort: use minimal settings to hit the target @@ -622,19 +645,16 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { match req.gif_budget_mode { GifBudgetMode::Resolution => { - scale_width = ((scale_width as f64 * factor).round() as u32 / 2) - .max(60) - .min(1280) - * 2; + // Halve before clamping so the *2 keeps the width even. + scale_width = + ((scale_width as f64 * factor).round() as u32 / 2).clamp(60, 640) * 2; } GifBudgetMode::Framerate => { effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1); } GifBudgetMode::Balanced => { - scale_width = ((scale_width as f64 * factor).round() as u32 / 2) - .max(60) - .min(1280) - * 2; + scale_width = + ((scale_width as f64 * factor).round() as u32 / 2).clamp(60, 640) * 2; effective_fps = ((effective_fps as f64 * factor).round() as u32).max(1); } } @@ -673,7 +693,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) + let click_prefix = click_filters(&req.clicks, req.clip_width, req.clip_height) .map(|c| format!("{c},")) .unwrap_or_default(); let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices) @@ -1155,7 +1175,7 @@ fn run_impl( // 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> = stdout.map(|out| { - let tx = tx.as_ref().map(|t| t.clone()); + let tx = tx.clone(); let encode_dur_us = (progress_duration_secs * 1_000_000.0).max(1.0); let pass = progress_pass; let total_passes = progress_total_passes; @@ -1360,15 +1380,46 @@ mod tests { let clicks: Vec = (0..100) .map(|i| Click { time_secs: i as f64, x: i, y: i, button: crate::clicks::MouseButton::Left }) .collect(); - let req = TranscodeRequest { - clicks, - ..dummy_request() - }; - let filter = click_filters(&req).unwrap(); + let filter = click_filters(&clicks, 1920, 1080).unwrap(); let count = filter.matches("drawbox").count(); assert_eq!(count, MAX_CLICK_HIGHLIGHTS); } + #[test] + fn click_boxes_stay_inside_the_frame() { + let frame = (1920u32, 1080u32); + // Near each edge, and one dead-centre. + assert_eq!(click_box(2, 2, frame.0, frame.1), Some((0, 0))); + assert_eq!(click_box(1919, 1079, frame.0, frame.1), Some((1920 - BOX_SIZE, 1080 - BOX_SIZE))); + assert_eq!(click_box(960, 540, frame.0, frame.1), Some((948, 528))); + } + + #[test] + fn clicks_outside_the_capture_region_are_skipped() { + let frame = (1920u32, 1080u32); + // A click to the left of / above the crop maps to a negative offset, and + // one past the far edge lands beyond the frame. Both used to produce a + // negative drawbox offset that ffmpeg silently dropped. + assert_eq!(click_box(-620, 115, frame.0, frame.1), None); + assert_eq!(click_box(100, -40, frame.0, frame.1), None); + assert_eq!(click_box(2100, 500, frame.0, frame.1), None); + assert_eq!(click_box(500, 1200, frame.0, frame.1), None); + } + + #[test] + fn click_filters_drops_clicks_off_frame() { + let clicks = vec![ + 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(); + 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. + assert!(!filter.contains("x=-")); + assert!(!filter.contains("y=-")); + } + #[test] fn gif_shrink_factor_resolution_uses_sqrt() { // ratio 0.25 -> halving the *width* (which quarters pixels) needs sqrt(0.25)=0.5 diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index dff3521..093ee4b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -22,7 +22,7 @@ use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilte use crate::bootstrap::FfmpegStatus; use crate::config::{Config, Format, GifBudgetMode, GifDither}; -fn lock(m: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| { tracing::warn!("mutex poisoned, recovering"); e.into_inner() @@ -918,7 +918,7 @@ fn render_preview( let (w, _) = encode::gif_params(&budget, clip.width, clip.height); w } else { - clip.width.min(1280).max(160) + clip.width.clamp(160, 1280) }; let preview_path = temp_dir(&state.app_dir).join("preview.png"); @@ -1700,7 +1700,7 @@ fn read_log_tail(log_dir: &Path) -> String { } if let Ok(meta) = entry.metadata() { if let Ok(mtime) = meta.modified() { - if newest.as_ref().map_or(true, |(t, _)| mtime > *t) { + if newest.as_ref().is_none_or(|(t, _)| mtime > *t) { newest = Some((mtime, entry.path())); } }