click highlights via global mouse hook + ffmpeg drawbox
This commit is contained in:
@@ -142,6 +142,17 @@ pub struct CaptureSession {
|
||||
control: CaptureControl<CaptureHandler, anyhow::Error>,
|
||||
}
|
||||
|
||||
pub fn primary_monitor_dims() -> Result<(u32, u32)> {
|
||||
let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?;
|
||||
let w = monitor
|
||||
.width()
|
||||
.map_err(|e| anyhow!("monitor width: {e:?}"))?;
|
||||
let h = monitor
|
||||
.height()
|
||||
.map_err(|e| anyhow!("monitor height: {e:?}"))?;
|
||||
Ok((w & !1, h & !1))
|
||||
}
|
||||
|
||||
pub fn start(
|
||||
output_path: PathBuf,
|
||||
ffmpeg_path: PathBuf,
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
pub struct Click {
|
||||
pub time_secs: f64,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
pub struct ClickRecorder {
|
||||
running: Arc<AtomicBool>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
clicks: Arc<Mutex<Vec<Click>>>,
|
||||
}
|
||||
|
||||
pub fn start() -> ClickRecorder {
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
let clicks: Arc<Mutex<Vec<Click>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
let running_clone = running.clone();
|
||||
let clicks_clone = clicks.clone();
|
||||
|
||||
let thread = thread::spawn(move || {
|
||||
use windows::Win32::Foundation::POINT;
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
|
||||
use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
|
||||
|
||||
const VK_LBUTTON: i32 = 0x01;
|
||||
let start = Instant::now();
|
||||
let mut last_pressed = false;
|
||||
|
||||
while running_clone.load(Ordering::Relaxed) {
|
||||
let state = unsafe { GetAsyncKeyState(VK_LBUTTON) };
|
||||
let pressed = (state as u16 & 0x8000) != 0;
|
||||
if pressed && !last_pressed {
|
||||
let mut pt = POINT::default();
|
||||
if unsafe { GetCursorPos(&mut pt) }.is_ok() {
|
||||
let click = Click {
|
||||
time_secs: start.elapsed().as_secs_f64(),
|
||||
x: pt.x,
|
||||
y: pt.y,
|
||||
};
|
||||
if let Ok(mut v) = clicks_clone.lock() {
|
||||
v.push(click);
|
||||
}
|
||||
}
|
||||
}
|
||||
last_pressed = pressed;
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
});
|
||||
|
||||
ClickRecorder {
|
||||
running,
|
||||
thread: Some(thread),
|
||||
clicks,
|
||||
}
|
||||
}
|
||||
|
||||
impl ClickRecorder {
|
||||
pub fn stop(mut self) -> Vec<Click> {
|
||||
self.running.store(false, Ordering::Relaxed);
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
self.clicks
|
||||
.lock()
|
||||
.map(|v| v.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
+41
-4
@@ -5,6 +5,7 @@ use std::process::Command;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
|
||||
use crate::clicks::Click;
|
||||
use crate::config::{Format, GifDither, Mp4Codec, WebmCodec};
|
||||
use crate::CaptureRect;
|
||||
|
||||
@@ -27,6 +28,30 @@ pub struct TranscodeRequest {
|
||||
pub deleted_frame_indices: Vec<u32>,
|
||||
pub trim_start_secs: Option<f64>,
|
||||
pub trim_end_secs: Option<f64>,
|
||||
pub clicks: Vec<Click>,
|
||||
}
|
||||
|
||||
fn click_filters(req: &TranscodeRequest) -> Option<String> {
|
||||
if req.clicks.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let size = 24i32;
|
||||
let half = size / 2;
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for click in &req.clicks {
|
||||
let x = click.x - half;
|
||||
let y = click.y - half;
|
||||
let t1 = (click.time_secs - 0.05).max(0.0);
|
||||
let t2 = click.time_secs + 0.25;
|
||||
parts.push(format!(
|
||||
"drawbox=x={x}:y={y}:w={size}:h={size}:color=yellow@0.6:t=fill:enable='between(t,{t1:.3},{t2:.3})'"
|
||||
));
|
||||
}
|
||||
if parts.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(parts.join(","))
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_trim(cmd: &mut Command, req: &TranscodeRequest) {
|
||||
@@ -194,6 +219,13 @@ 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 combined_vf: Option<String> = match (&crop, &clicks) {
|
||||
(Some(c), Some(k)) => Some(format!("{c},{k}")),
|
||||
(Some(c), None) => Some(c.clone()),
|
||||
(None, Some(k)) => Some(k.clone()),
|
||||
(None, None) => None,
|
||||
};
|
||||
|
||||
let mut pass1 = Command::new(ffmpeg);
|
||||
pass1
|
||||
@@ -202,7 +234,7 @@ fn two_pass_video(
|
||||
.arg("-i")
|
||||
.arg(&req.input);
|
||||
apply_trim(&mut pass1, req);
|
||||
if let Some(c) = &crop {
|
||||
if let Some(c) = &combined_vf {
|
||||
pass1.args(["-vf", c]);
|
||||
}
|
||||
pass1
|
||||
@@ -222,7 +254,7 @@ fn two_pass_video(
|
||||
.arg("-i")
|
||||
.arg(&req.input);
|
||||
apply_trim(&mut pass2, req);
|
||||
if let Some(c) = &crop {
|
||||
if let Some(c) = &combined_vf {
|
||||
pass2.args(["-vf", c]);
|
||||
}
|
||||
pass2
|
||||
@@ -271,12 +303,16 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
let crop_prefix = crop_filter(req.crop)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let click_prefix = click_filters(req)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices)
|
||||
.map(|s| format!("{s},"))
|
||||
.unwrap_or_default();
|
||||
let palettegen_filter = format!(
|
||||
"{cprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff",
|
||||
"{cprefix}{kprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff",
|
||||
cprefix = crop_prefix,
|
||||
kprefix = click_prefix,
|
||||
sprefix = select_prefix,
|
||||
fps = req.fps,
|
||||
w = scale_width,
|
||||
@@ -298,8 +334,9 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
GifDither::None => "none",
|
||||
};
|
||||
let use_filter = format!(
|
||||
"{cprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}",
|
||||
"{cprefix}{kprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}",
|
||||
cprefix = crop_prefix,
|
||||
kprefix = click_prefix,
|
||||
sprefix = select_prefix,
|
||||
fps = req.fps,
|
||||
w = scale_width,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod audio;
|
||||
mod bootstrap;
|
||||
mod capture;
|
||||
mod clicks;
|
||||
mod config;
|
||||
mod encode;
|
||||
mod updates;
|
||||
@@ -31,6 +32,7 @@ pub struct AppState {
|
||||
pub config: Mutex<Config>,
|
||||
pub capture: Mutex<Option<capture::CaptureSession>>,
|
||||
pub audio: Mutex<Option<audio::AudioSession>>,
|
||||
pub click_recorder: Mutex<Option<clicks::ClickRecorder>>,
|
||||
pub last_clip: Mutex<Option<RecordedClip>>,
|
||||
pub session: Mutex<Option<SessionState>>,
|
||||
}
|
||||
@@ -46,6 +48,10 @@ pub struct SessionState {
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub monitor_width: u32,
|
||||
pub monitor_height: u32,
|
||||
pub clicks: Vec<clicks::Click>,
|
||||
pub segment_start_offsets: Vec<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -54,7 +60,10 @@ pub struct RecordedClip {
|
||||
pub duration_secs: f64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub monitor_width: u32,
|
||||
pub monitor_height: u32,
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub clicks: Vec<clicks::Click>,
|
||||
}
|
||||
|
||||
fn exe_dir() -> Result<PathBuf> {
|
||||
@@ -293,6 +302,9 @@ fn start_capture(
|
||||
return Err("ffmpeg.exe not found - run the encoder setup first".to_string());
|
||||
}
|
||||
|
||||
let (monitor_w, monitor_h) =
|
||||
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
let session = capture::start(
|
||||
output,
|
||||
ffmpeg.clone(),
|
||||
@@ -334,11 +346,22 @@ fn start_capture(
|
||||
crop,
|
||||
width: session.width,
|
||||
height: session.height,
|
||||
monitor_width: monitor_w,
|
||||
monitor_height: monitor_h,
|
||||
clicks: Vec::new(),
|
||||
segment_start_offsets: vec![0.0],
|
||||
};
|
||||
|
||||
let click_rec = if cfg.capture.capture_cursor {
|
||||
Some(clicks::start())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
*state.session.lock().expect("session mutex") = Some(session_state);
|
||||
*state.capture.lock().expect("capture mutex") = Some(session);
|
||||
*state.audio.lock().expect("audio mutex") = audio_session;
|
||||
*state.click_recorder.lock().expect("click mutex") = click_rec;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -360,15 +383,31 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||
.take()
|
||||
.and_then(|a| a.stop().ok());
|
||||
|
||||
let new_clicks: Vec<clicks::Click> = state
|
||||
.click_recorder
|
||||
.lock()
|
||||
.expect("click mutex")
|
||||
.take()
|
||||
.map(|r| r.stop())
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut ss = state.session.lock().expect("session mutex");
|
||||
let ss = ss
|
||||
.as_mut()
|
||||
.ok_or_else(|| "no session state".to_string())?;
|
||||
let offset = *ss.segment_start_offsets.last().unwrap_or(&0.0);
|
||||
for c in new_clicks {
|
||||
ss.clicks.push(clicks::Click {
|
||||
time_secs: offset + c.time_secs,
|
||||
..c
|
||||
});
|
||||
}
|
||||
ss.segments.push(path);
|
||||
if let Some(ap) = audio_path {
|
||||
ss.audio_segments.push(ap);
|
||||
}
|
||||
ss.total_recorded_secs += elapsed;
|
||||
ss.segment_start_offsets.push(ss.total_recorded_secs);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -415,8 +454,15 @@ fn resume_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||
None
|
||||
};
|
||||
|
||||
let click_rec = if capture_cursor {
|
||||
Some(clicks::start())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
*state.capture.lock().expect("capture mutex") = Some(session);
|
||||
*state.audio.lock().expect("audio mutex") = audio_session;
|
||||
*state.click_recorder.lock().expect("click mutex") = click_rec;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -446,6 +492,21 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
|
||||
}
|
||||
}
|
||||
|
||||
let live_clicks = state
|
||||
.click_recorder
|
||||
.lock()
|
||||
.expect("click mutex")
|
||||
.take()
|
||||
.map(|r| r.stop())
|
||||
.unwrap_or_default();
|
||||
let offset = *ss.segment_start_offsets.last().unwrap_or(&0.0);
|
||||
for c in live_clicks {
|
||||
ss.clicks.push(clicks::Click {
|
||||
time_secs: offset + c.time_secs,
|
||||
..c
|
||||
});
|
||||
}
|
||||
|
||||
if ss.segments.is_empty() {
|
||||
return Err("no recorded segments".to_string());
|
||||
}
|
||||
@@ -508,7 +569,10 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
|
||||
duration_secs: ss.total_recorded_secs,
|
||||
width: ss.width,
|
||||
height: ss.height,
|
||||
monitor_width: ss.monitor_width,
|
||||
monitor_height: ss.monitor_height,
|
||||
crop: ss.crop,
|
||||
clicks: ss.clicks.clone(),
|
||||
};
|
||||
*state.last_clip.lock().expect("clip mutex") = Some(clip.clone());
|
||||
Ok(clip)
|
||||
@@ -731,6 +795,27 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportRe
|
||||
(None, None) => clip.duration_secs,
|
||||
};
|
||||
|
||||
let (src_w, src_origin) = if let Some(c) = clip.crop {
|
||||
(c.width, (c.x, c.y))
|
||||
} else {
|
||||
(
|
||||
clip
|
||||
.monitor_width
|
||||
.max(1),
|
||||
(0, 0),
|
||||
)
|
||||
};
|
||||
let scale = clip.width as f64 / src_w as f64;
|
||||
let transformed_clicks: Vec<clicks::Click> = clip
|
||||
.clicks
|
||||
.iter()
|
||||
.map(|c| clicks::Click {
|
||||
time_secs: c.time_secs,
|
||||
x: (((c.x - src_origin.0) as f64) * scale).round() as i32,
|
||||
y: (((c.y - src_origin.1) as f64) * scale).round() as i32,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let req = encode::TranscodeRequest {
|
||||
input: clip.temp_path.clone(),
|
||||
output: out_path.clone(),
|
||||
@@ -747,6 +832,7 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportRe
|
||||
deleted_frame_indices: request.deleted_frame_indices,
|
||||
trim_start_secs: trim_start,
|
||||
trim_end_secs: trim_end,
|
||||
clicks: transformed_clicks,
|
||||
};
|
||||
|
||||
encode::transcode(&ffmpeg, &req).map_err(|e| format!("{e:#}"))?;
|
||||
@@ -780,6 +866,7 @@ pub fn run() {
|
||||
config: Mutex::new(cfg),
|
||||
capture: Mutex::new(None),
|
||||
audio: Mutex::new(None),
|
||||
click_recorder: Mutex::new(None),
|
||||
last_clip: Mutex::new(None),
|
||||
session: Mutex::new(None),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user