diff --git a/overlay.html b/overlay.html new file mode 100644 index 0000000..6a82892 --- /dev/null +++ b/overlay.html @@ -0,0 +1,12 @@ + + + + + + ByteSize capture frame + + +
+ + + diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index ebaa4a8..cb3cd2b 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -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" ] } diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 18e23d7..7d6ed40 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -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, control: CaptureControl, } -pub fn start(output_path: PathBuf, capture_cursor: bool, audio: bool) -> Result { +pub fn start( + output_path: PathBuf, + capture_cursor: bool, + audio: bool, + crop: Option, +) -> Result { 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, }) } diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index bf15434..04d4590 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -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, +} + +fn crop_filter(crop: Option) -> Option { + 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, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b561d64..24b1a71 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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, @@ -27,6 +35,7 @@ pub struct RecordedClip { pub duration_secs: f64, pub width: u32, pub height: u32, + pub crop: Option, } fn exe_dir() -> Result { @@ -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, +} + #[tauri::command] -fn start_capture(state: State<'_, AppState>) -> Result<(), String> { +fn start_capture( + state: State<'_, AppState>, + request: Option, +) -> 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 { 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 { 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 { + 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 { 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() { errMsg = null elapsed = 0 + let crop = null + if (useFrame) { + try { + crop = await api.getOverlayRect() + await api.hideOverlay() + } catch (e) { + errMsg = String(e) + return + } + } try { - await api.startCapture() + await api.startCapture({ crop }) phase = "recording" tick() } catch (e) { errMsg = String(e) + if (useFrame) { + await api.showOverlay().catch(() => {}) + } } } @@ -127,10 +152,18 @@ {#if phase === "idle"}
+

- Captures your primary monitor. Region capture and the draggable overlay - come next. + {#if useFrame} + 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}

{:else if phase === "recording"}
@@ -288,6 +321,8 @@ .controls { display: flex; justify-content: center; + gap: 0.75rem; + flex-wrap: wrap; margin-top: 2rem; } .recording { @@ -326,6 +361,11 @@ padding: 0.75rem 1.75rem; font-size: 1rem; } + button.on { + background: #1a2a24; + border-color: #4a8; + color: #4a8; + } button.stop { background: #c33; border-color: #c33; diff --git a/src/lib/Overlay.svelte b/src/lib/Overlay.svelte new file mode 100644 index 0000000..e51f610 --- /dev/null +++ b/src/lib/Overlay.svelte @@ -0,0 +1,73 @@ + + +
+
+ ⠿ + {width} x {height} +
+
+ + diff --git a/src/lib/api.ts b/src/lib/api.ts index 7020495..58f38ab 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -49,11 +49,23 @@ export type DownloadProgress = { total: number | null } +export type CaptureRect = { + x: number + y: number + width: number + height: number +} + export type RecordedClip = { temp_path: string duration_secs: number width: number height: number + crop: CaptureRect | null +} + +export type StartCaptureRequest = { + crop: CaptureRect | null } export type ExportRequest = { @@ -75,10 +87,14 @@ export const api = { downloadFfmpeg: () => invoke("download_ffmpeg"), onFfmpegProgress: (handler: (p: DownloadProgress) => void): Promise => listen("ffmpeg-progress", (e) => handler(e.payload)), - startCapture: () => invoke("start_capture"), + startCapture: (request: StartCaptureRequest) => + invoke("start_capture", { request }), stopCapture: () => invoke("stop_capture"), export: (request: ExportRequest) => invoke("export", { request }), revealInExplorer: (path: string) => invoke("reveal_in_explorer", { path }), + showOverlay: () => invoke("show_overlay"), + hideOverlay: () => invoke("hide_overlay"), + getOverlayRect: () => invoke("get_overlay_rect"), } export function formatBytes(n: number): string { diff --git a/src/overlay.ts b/src/overlay.ts new file mode 100644 index 0000000..b2bc8d3 --- /dev/null +++ b/src/overlay.ts @@ -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 diff --git a/vite.config.ts b/vite.config.ts index 107b1cd..ea56c40 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,5 +1,6 @@ import { defineConfig } from "vite" import { svelte } from "@sveltejs/vite-plugin-svelte" +import { resolve } from "path" const host = process.env.TAURI_DEV_HOST @@ -17,4 +18,12 @@ export default defineConfig({ ignored: ["**/src-tauri/**"], }, }, + build: { + rollupOptions: { + input: { + main: resolve(__dirname, "index.html"), + overlay: resolve(__dirname, "overlay.html"), + }, + }, + }, })