region capture overlay window

This commit is contained in:
2026-05-12 00:06:31 +03:00
parent 03af276a1d
commit 14d02cdad4
11 changed files with 305 additions and 14 deletions
+3 -1
View File
@@ -2,9 +2,11 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "default capabilities for ByteSize",
"windows": ["main"],
"windows": ["main", "overlay"],
"permissions": [
"core:default",
"core:window:default",
"core:webview:default",
"dialog:default"
]
}
+10 -1
View File
@@ -5,6 +5,8 @@ use anyhow::{anyhow, Result};
use windows_capture::capture::{
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
};
use crate::CaptureRect;
use windows_capture::encoder::{
AudioSettingsBuilder, ContainerSettingsBuilder, VideoEncoder, VideoSettingsBuilder,
};
@@ -73,10 +75,16 @@ pub struct CaptureSession {
pub started_at: Instant,
pub width: u32,
pub height: u32,
pub crop: Option<CaptureRect>,
control: CaptureControl<CaptureHandler, anyhow::Error>,
}
pub fn start(output_path: PathBuf, capture_cursor: bool, audio: bool) -> Result<CaptureSession> {
pub fn start(
output_path: PathBuf,
capture_cursor: bool,
audio: bool,
crop: Option<CaptureRect>,
) -> Result<CaptureSession> {
let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?;
let width = monitor
.width()
@@ -117,6 +125,7 @@ pub fn start(output_path: PathBuf, capture_cursor: bool, audio: bool) -> Result<
started_at: Instant::now(),
width,
height,
crop,
control,
})
}
+33 -4
View File
@@ -5,6 +5,7 @@ use std::process::Command;
use anyhow::{anyhow, bail, Context, Result};
use crate::config::{Format, GifDither, Mp4Codec, WebmCodec};
use crate::CaptureRect;
const AUDIO_BITRATE_KBPS: u64 = 128;
@@ -21,6 +22,19 @@ pub struct TranscodeRequest {
pub webm_codec: WebmCodec,
pub mp4_codec: Mp4Codec,
pub scratch_dir: PathBuf,
pub crop: Option<CaptureRect>,
}
fn crop_filter(crop: Option<CaptureRect>) -> Option<String> {
crop.map(|c| {
format!(
"crop={w}:{h}:{x}:{y}",
w = c.width,
h = c.height,
x = c.x.max(0),
y = c.y.max(0)
)
})
}
pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
@@ -90,12 +104,18 @@ fn two_pass_video(
.ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?;
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
let crop = crop_filter(req.crop);
let mut pass1 = Command::new(ffmpeg);
pass1
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input)
.arg(&req.input);
if let Some(c) = &crop {
pass1.args(["-vf", c]);
}
pass1
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "1"])
@@ -110,7 +130,11 @@ fn two_pass_video(
.arg("-y")
.arg("-hide_banner")
.arg("-i")
.arg(&req.input)
.arg(&req.input);
if let Some(c) = &crop {
pass2.args(["-vf", c]);
}
pass2
.args(["-c:v", video_codec])
.args(["-b:v", &bitrate])
.args(["-pass", "2"])
@@ -153,8 +177,12 @@ fn cleanup_pass_logs(stem: &Path) {
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let palette_path = req.scratch_dir.join("palette.png");
let scale_width = estimate_gif_scale_width(req);
let crop_prefix = crop_filter(req.crop)
.map(|c| format!("{c},"))
.unwrap_or_default();
let palettegen_filter = format!(
"fps={fps},scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff",
"{prefix}fps={fps},scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff",
prefix = crop_prefix,
fps = req.fps,
w = scale_width,
);
@@ -174,7 +202,8 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
GifDither::None => "none",
};
let use_filter = format!(
"fps={fps},scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}",
"{prefix}fps={fps},scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}",
prefix = crop_prefix,
fps = req.fps,
w = scale_width,
d = dither,
+82 -4
View File
@@ -9,11 +9,19 @@ use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, State};
use tauri::{AppHandle, Emitter, Manager, State};
use crate::bootstrap::FfmpegStatus;
use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct CaptureRect {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
}
pub struct AppState {
pub app_dir: PathBuf,
pub config: Mutex<Config>,
@@ -27,6 +35,7 @@ pub struct RecordedClip {
pub duration_secs: f64,
pub width: u32,
pub height: u32,
pub crop: Option<CaptureRect>,
}
fn exe_dir() -> Result<PathBuf> {
@@ -174,8 +183,16 @@ async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(
.map_err(|e| format!("{e:#}"))
}
#[derive(Debug, Deserialize)]
pub struct StartCaptureRequest {
pub crop: Option<CaptureRect>,
}
#[tauri::command]
fn start_capture(state: State<'_, AppState>) -> Result<(), String> {
fn start_capture(
state: State<'_, AppState>,
request: Option<StartCaptureRequest>,
) -> Result<(), String> {
let mut slot = state.capture.lock().expect("capture mutex");
if slot.is_some() {
return Err("a capture is already running".to_string());
@@ -186,8 +203,14 @@ fn start_capture(state: State<'_, AppState>) -> Result<(), String> {
let output = temp.join("recording.mp4");
let _ = std::fs::remove_file(&output);
let session = capture::start(output, cfg.capture.capture_cursor, cfg.capture.capture_audio)
.map_err(|e| format!("{e:#}"))?;
let crop = request.and_then(|r| r.crop);
let session = capture::start(
output,
cfg.capture.capture_cursor,
cfg.capture.capture_audio,
crop,
)
.map_err(|e| format!("{e:#}"))?;
*slot = Some(session);
Ok(())
}
@@ -203,6 +226,7 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
let duration_secs = session.started_at.elapsed().as_secs_f64();
let width = session.width;
let height = session.height;
let crop = session.crop;
let temp_path = session.stop().map_err(|e| format!("{e:#}"))?;
let clip = RecordedClip {
@@ -210,6 +234,7 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
duration_secs,
width,
height,
crop,
};
*state.last_clip.lock().expect("clip mutex") = Some(clip.clone());
Ok(clip)
@@ -229,6 +254,55 @@ pub struct ExportResult {
pub size_bytes: u64,
}
const OVERLAY_BORDER_LOGICAL_PX: f64 = 2.0;
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 22.0;
#[tauri::command]
fn show_overlay(app: AppHandle) -> Result<(), String> {
let win = app
.get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?;
win.show().map_err(|e| e.to_string())?;
win.set_focus().map_err(|e| e.to_string())
}
#[tauri::command]
fn hide_overlay(app: AppHandle) -> Result<(), String> {
let win = app
.get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?;
win.hide().map_err(|e| e.to_string())
}
#[tauri::command]
fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
let win = app
.get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?;
let pos = win.outer_position().map_err(|e| e.to_string())?;
let size = win.outer_size().map_err(|e| e.to_string())?;
let scale = win.scale_factor().map_err(|e| e.to_string())?;
let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
let inset_top = border_phys + titlebar_phys;
let inset_sides = border_phys;
let inset_bottom = border_phys;
let width = (size.width as i32 - inset_sides * 2).max(2) as u32;
let height = (size.height as i32 - inset_top - inset_bottom).max(2) as u32;
let width = (width / 2) * 2;
let height = (height / 2) * 2;
Ok(CaptureRect {
x: pos.x + inset_sides,
y: pos.y + inset_top,
width,
height,
})
}
#[tauri::command]
fn reveal_in_explorer(path: String) -> Result<(), String> {
use std::process::Command;
@@ -274,6 +348,7 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportRe
webm_codec: cfg.export.webm_codec,
mp4_codec: cfg.export.mp4_codec,
scratch_dir: temp_dir(&state.app_dir),
crop: clip.crop,
};
encode::transcode(&ffmpeg, &req).map_err(|e| format!("{e:#}"))?;
@@ -321,6 +396,9 @@ pub fn run() {
stop_capture,
export,
reveal_in_explorer,
show_overlay,
hide_overlay,
get_overlay_rect,
])
.run(tauri::generate_context!())
.expect("error while running ByteSize")
+15
View File
@@ -20,6 +20,21 @@
"minHeight": 400,
"resizable": true,
"fullscreen": false
},
{
"label": "overlay",
"title": "ByteSize capture frame",
"url": "overlay.html",
"width": 640,
"height": 360,
"minWidth": 160,
"minHeight": 90,
"transparent": true,
"decorations": false,
"alwaysOnTop": true,
"skipTaskbar": true,
"resizable": true,
"visible": false
}
],
"security": {