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
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ByteSize capture frame</title>
</head>
<body>
<div id="overlay"></div>
<script type="module" src="/src/overlay.ts"></script>
</body>
</html>
+3 -1
View File
@@ -2,9 +2,11 @@
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "default capabilities for ByteSize", "description": "default capabilities for ByteSize",
"windows": ["main"], "windows": ["main", "overlay"],
"permissions": [ "permissions": [
"core:default", "core:default",
"core:window:default",
"core:webview:default",
"dialog:default" "dialog:default"
] ]
} }
+10 -1
View File
@@ -5,6 +5,8 @@ use anyhow::{anyhow, Result};
use windows_capture::capture::{ use windows_capture::capture::{
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler, CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
}; };
use crate::CaptureRect;
use windows_capture::encoder::{ use windows_capture::encoder::{
AudioSettingsBuilder, ContainerSettingsBuilder, VideoEncoder, VideoSettingsBuilder, AudioSettingsBuilder, ContainerSettingsBuilder, VideoEncoder, VideoSettingsBuilder,
}; };
@@ -73,10 +75,16 @@ pub struct CaptureSession {
pub started_at: Instant, pub started_at: Instant,
pub width: u32, pub width: u32,
pub height: u32, pub height: u32,
pub crop: Option<CaptureRect>,
control: CaptureControl<CaptureHandler, anyhow::Error>, 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 monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?;
let width = monitor let width = monitor
.width() .width()
@@ -117,6 +125,7 @@ pub fn start(output_path: PathBuf, capture_cursor: bool, audio: bool) -> Result<
started_at: Instant::now(), started_at: Instant::now(),
width, width,
height, height,
crop,
control, control,
}) })
} }
+33 -4
View File
@@ -5,6 +5,7 @@ use std::process::Command;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use crate::config::{Format, GifDither, Mp4Codec, WebmCodec}; use crate::config::{Format, GifDither, Mp4Codec, WebmCodec};
use crate::CaptureRect;
const AUDIO_BITRATE_KBPS: u64 = 128; const AUDIO_BITRATE_KBPS: u64 = 128;
@@ -21,6 +22,19 @@ pub struct TranscodeRequest {
pub webm_codec: WebmCodec, pub webm_codec: WebmCodec,
pub mp4_codec: Mp4Codec, pub mp4_codec: Mp4Codec,
pub scratch_dir: PathBuf, 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<()> { 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"))?; .ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?;
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" }; let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
let crop = crop_filter(req.crop);
let mut pass1 = Command::new(ffmpeg); let mut pass1 = Command::new(ffmpeg);
pass1 pass1
.arg("-y") .arg("-y")
.arg("-hide_banner") .arg("-hide_banner")
.arg("-i") .arg("-i")
.arg(&req.input) .arg(&req.input);
if let Some(c) = &crop {
pass1.args(["-vf", c]);
}
pass1
.args(["-c:v", video_codec]) .args(["-c:v", video_codec])
.args(["-b:v", &bitrate]) .args(["-b:v", &bitrate])
.args(["-pass", "1"]) .args(["-pass", "1"])
@@ -110,7 +130,11 @@ fn two_pass_video(
.arg("-y") .arg("-y")
.arg("-hide_banner") .arg("-hide_banner")
.arg("-i") .arg("-i")
.arg(&req.input) .arg(&req.input);
if let Some(c) = &crop {
pass2.args(["-vf", c]);
}
pass2
.args(["-c:v", video_codec]) .args(["-c:v", video_codec])
.args(["-b:v", &bitrate]) .args(["-b:v", &bitrate])
.args(["-pass", "2"]) .args(["-pass", "2"])
@@ -153,8 +177,12 @@ fn cleanup_pass_logs(stem: &Path) {
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let palette_path = req.scratch_dir.join("palette.png"); let palette_path = req.scratch_dir.join("palette.png");
let scale_width = estimate_gif_scale_width(req); 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!( 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, fps = req.fps,
w = scale_width, w = scale_width,
); );
@@ -174,7 +202,8 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
GifDither::None => "none", GifDither::None => "none",
}; };
let use_filter = format!( 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, fps = req.fps,
w = scale_width, w = scale_width,
d = dither, d = dither,
+82 -4
View File
@@ -9,11 +9,19 @@ use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, State}; use tauri::{AppHandle, Emitter, Manager, State};
use crate::bootstrap::FfmpegStatus; use crate::bootstrap::FfmpegStatus;
use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec}; 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 struct AppState {
pub app_dir: PathBuf, pub app_dir: PathBuf,
pub config: Mutex<Config>, pub config: Mutex<Config>,
@@ -27,6 +35,7 @@ pub struct RecordedClip {
pub duration_secs: f64, pub duration_secs: f64,
pub width: u32, pub width: u32,
pub height: u32, pub height: u32,
pub crop: Option<CaptureRect>,
} }
fn exe_dir() -> Result<PathBuf> { fn exe_dir() -> Result<PathBuf> {
@@ -174,8 +183,16 @@ async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(
.map_err(|e| format!("{e:#}")) .map_err(|e| format!("{e:#}"))
} }
#[derive(Debug, Deserialize)]
pub struct StartCaptureRequest {
pub crop: Option<CaptureRect>,
}
#[tauri::command] #[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"); let mut slot = state.capture.lock().expect("capture mutex");
if slot.is_some() { if slot.is_some() {
return Err("a capture is already running".to_string()); 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 output = temp.join("recording.mp4");
let _ = std::fs::remove_file(&output); let _ = std::fs::remove_file(&output);
let session = capture::start(output, cfg.capture.capture_cursor, cfg.capture.capture_audio) let crop = request.and_then(|r| r.crop);
.map_err(|e| format!("{e:#}"))?; let session = capture::start(
output,
cfg.capture.capture_cursor,
cfg.capture.capture_audio,
crop,
)
.map_err(|e| format!("{e:#}"))?;
*slot = Some(session); *slot = Some(session);
Ok(()) 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 duration_secs = session.started_at.elapsed().as_secs_f64();
let width = session.width; let width = session.width;
let height = session.height; let height = session.height;
let crop = session.crop;
let temp_path = session.stop().map_err(|e| format!("{e:#}"))?; let temp_path = session.stop().map_err(|e| format!("{e:#}"))?;
let clip = RecordedClip { let clip = RecordedClip {
@@ -210,6 +234,7 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
duration_secs, duration_secs,
width, width,
height, height,
crop,
}; };
*state.last_clip.lock().expect("clip mutex") = Some(clip.clone()); *state.last_clip.lock().expect("clip mutex") = Some(clip.clone());
Ok(clip) Ok(clip)
@@ -229,6 +254,55 @@ pub struct ExportResult {
pub size_bytes: u64, 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] #[tauri::command]
fn reveal_in_explorer(path: String) -> Result<(), String> { fn reveal_in_explorer(path: String) -> Result<(), String> {
use std::process::Command; use std::process::Command;
@@ -274,6 +348,7 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportRe
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(&state.app_dir),
crop: clip.crop,
}; };
encode::transcode(&ffmpeg, &req).map_err(|e| format!("{e:#}"))?; encode::transcode(&ffmpeg, &req).map_err(|e| format!("{e:#}"))?;
@@ -321,6 +396,9 @@ pub fn run() {
stop_capture, stop_capture,
export, export,
reveal_in_explorer, reveal_in_explorer,
show_overlay,
hide_overlay,
get_overlay_rect,
]) ])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running ByteSize") .expect("error while running ByteSize")
+15
View File
@@ -20,6 +20,21 @@
"minHeight": 400, "minHeight": 400,
"resizable": true, "resizable": true,
"fullscreen": false "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": { "security": {
+43 -3
View File
@@ -25,6 +25,7 @@
let targetMB: number = $state(8) let targetMB: number = $state(8)
let exportResult: ExportResult | null = $state(null) let exportResult: ExportResult | null = $state(null)
let errMsg: string | null = $state(null) let errMsg: string | null = $state(null)
let useFrame: boolean = $state(false)
onMount(async () => { onMount(async () => {
config = await api.getConfig() config = await api.getConfig()
@@ -46,15 +47,39 @@
} }
} }
async function toggleFrame() {
useFrame = !useFrame
try {
if (useFrame) await api.showOverlay()
else await api.hideOverlay()
} catch (e) {
errMsg = String(e)
useFrame = false
}
}
async function startRec() { async function startRec() {
errMsg = null errMsg = null
elapsed = 0 elapsed = 0
let crop = null
if (useFrame) {
try {
crop = await api.getOverlayRect()
await api.hideOverlay()
} catch (e) {
errMsg = String(e)
return
}
}
try { try {
await api.startCapture() await api.startCapture({ crop })
phase = "recording" phase = "recording"
tick() tick()
} catch (e) { } catch (e) {
errMsg = String(e) errMsg = String(e)
if (useFrame) {
await api.showOverlay().catch(() => {})
}
} }
} }
@@ -127,10 +152,18 @@
{#if phase === "idle"} {#if phase === "idle"}
<section class="controls"> <section class="controls">
<button class="primary big" onclick={startRec}>start recording</button> <button class="primary big" onclick={startRec}>start recording</button>
<button class:on={useFrame} onclick={toggleFrame}>
{useFrame ? "hide capture frame" : "show capture frame"}
</button>
</section> </section>
<p class="hint"> <p class="hint">
Captures your primary monitor. Region capture and the draggable overlay {#if useFrame}
come next. Drag the green frame on screen to position the region you want to
capture. The frame hides automatically while recording.
{:else}
Captures your full primary monitor. Click "show capture frame" to draw
a region instead.
{/if}
</p> </p>
{:else if phase === "recording"} {:else if phase === "recording"}
<section class="recording"> <section class="recording">
@@ -288,6 +321,8 @@
.controls { .controls {
display: flex; display: flex;
justify-content: center; justify-content: center;
gap: 0.75rem;
flex-wrap: wrap;
margin-top: 2rem; margin-top: 2rem;
} }
.recording { .recording {
@@ -326,6 +361,11 @@
padding: 0.75rem 1.75rem; padding: 0.75rem 1.75rem;
font-size: 1rem; font-size: 1rem;
} }
button.on {
background: #1a2a24;
border-color: #4a8;
color: #4a8;
}
button.stop { button.stop {
background: #c33; background: #c33;
border-color: #c33; border-color: #c33;
+73
View File
@@ -0,0 +1,73 @@
<script lang="ts">
import { onMount } from "svelte"
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"
let width: number = $state(0)
let height: number = $state(0)
onMount(() => {
const win = getCurrentWebviewWindow()
const updateSize = async () => {
const size = await win.innerSize()
const scale = await win.scaleFactor()
width = Math.round(size.width / scale)
height = Math.round(size.height / scale)
}
updateSize()
const unlisten = win.onResized(updateSize)
return () => {
unlisten.then((fn) => fn())
}
})
</script>
<div class="frame">
<div class="titlebar" data-tauri-drag-region>
<span class="grip" data-tauri-drag-region>⠿</span>
<span class="dim" data-tauri-drag-region>{width} x {height}</span>
</div>
</div>
<style>
:global(html), :global(body), :global(#overlay) {
margin: 0;
padding: 0;
background: transparent;
height: 100vh;
width: 100vw;
overflow: hidden;
}
.frame {
box-sizing: border-box;
height: 100vh;
width: 100vw;
border: 2px solid #4a8;
display: flex;
flex-direction: column;
background: transparent;
}
.titlebar {
height: 22px;
background: rgba(74, 170, 136, 0.85);
color: #0e1a16;
display: flex;
align-items: center;
gap: 8px;
padding: 0 8px;
font: 11px ui-monospace, monospace;
cursor: grab;
flex-shrink: 0;
}
.titlebar:active {
cursor: grabbing;
}
.grip {
font-size: 14px;
opacity: 0.7;
}
.dim {
font-variant-numeric: tabular-nums;
}
</style>
+17 -1
View File
@@ -49,11 +49,23 @@ export type DownloadProgress = {
total: number | null total: number | null
} }
export type CaptureRect = {
x: number
y: number
width: number
height: number
}
export type RecordedClip = { export type RecordedClip = {
temp_path: string temp_path: string
duration_secs: number duration_secs: number
width: number width: number
height: number height: number
crop: CaptureRect | null
}
export type StartCaptureRequest = {
crop: CaptureRect | null
} }
export type ExportRequest = { export type ExportRequest = {
@@ -75,10 +87,14 @@ export const api = {
downloadFfmpeg: () => invoke<void>("download_ffmpeg"), downloadFfmpeg: () => invoke<void>("download_ffmpeg"),
onFfmpegProgress: (handler: (p: DownloadProgress) => void): Promise<UnlistenFn> => onFfmpegProgress: (handler: (p: DownloadProgress) => void): Promise<UnlistenFn> =>
listen<DownloadProgress>("ffmpeg-progress", (e) => handler(e.payload)), listen<DownloadProgress>("ffmpeg-progress", (e) => handler(e.payload)),
startCapture: () => invoke<void>("start_capture"), startCapture: (request: StartCaptureRequest) =>
invoke<void>("start_capture", { request }),
stopCapture: () => invoke<RecordedClip>("stop_capture"), stopCapture: () => invoke<RecordedClip>("stop_capture"),
export: (request: ExportRequest) => invoke<ExportResult>("export", { request }), export: (request: ExportRequest) => invoke<ExportResult>("export", { request }),
revealInExplorer: (path: string) => invoke<void>("reveal_in_explorer", { path }), revealInExplorer: (path: string) => invoke<void>("reveal_in_explorer", { path }),
showOverlay: () => invoke<void>("show_overlay"),
hideOverlay: () => invoke<void>("hide_overlay"),
getOverlayRect: () => invoke<CaptureRect>("get_overlay_rect"),
} }
export function formatBytes(n: number): string { export function formatBytes(n: number): string {
+8
View File
@@ -0,0 +1,8 @@
import { mount } from "svelte"
import Overlay from "./lib/Overlay.svelte"
const app = mount(Overlay, {
target: document.getElementById("overlay")!,
})
export default app
+9
View File
@@ -1,5 +1,6 @@
import { defineConfig } from "vite" import { defineConfig } from "vite"
import { svelte } from "@sveltejs/vite-plugin-svelte" import { svelte } from "@sveltejs/vite-plugin-svelte"
import { resolve } from "path"
const host = process.env.TAURI_DEV_HOST const host = process.env.TAURI_DEV_HOST
@@ -17,4 +18,12 @@ export default defineConfig({
ignored: ["**/src-tauri/**"], ignored: ["**/src-tauri/**"],
}, },
}, },
build: {
rollupOptions: {
input: {
main: resolve(__dirname, "index.html"),
overlay: resolve(__dirname, "overlay.html"),
},
},
},
}) })