current state before improvement pass

This commit is contained in:
2026-05-27 18:56:36 +03:00
parent 5eb27ab779
commit f0775b8ff0
23 changed files with 3563 additions and 1853 deletions
+1 -1
View File
@@ -18,7 +18,7 @@ tauri = { version = "2.11", features = ["protocol-asset"] }
tauri-plugin-dialog = "2"
tauri-plugin-global-shortcut = "2"
windows-capture = "2.0"
windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_Foundation", "Win32_Graphics_Dwm"] }
windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_HiDpi", "Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_System_SystemInformation", "Win32_Media_Audio", "Win32_Media_Multimedia", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Threading", "Win32_System_Variant"] }
cpal = "0.16"
tokio = { version = "1.47", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
+222 -48
View File
@@ -1,77 +1,251 @@
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use anyhow::{anyhow, Context, Result};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use anyhow::{bail, Context, Result};
use windows::Win32::Media::Audio::{
eConsole, eRender, IAudioCaptureClient, IAudioClient, IMMDeviceEnumerator,
MMDeviceEnumerator, WAVEFORMATEX, WAVEFORMATEXTENSIBLE,
};
use windows::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
};
// WASAPI constants — defined here so we don't depend on exact windows-crate naming.
const AUDCLNT_STREAMFLAGS_LOOPBACK: u32 = 0x2000_0000;
const AUDCLNT_BUFFERFLAGS_SILENT: u32 = 0x0000_0002;
const WAVE_FORMAT_PCM: u16 = 0x0001;
const WAVE_FORMAT_IEEE_FLOAT: u16 = 0x0003;
const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
pub struct AudioSession {
_stream: cpal::Stream,
pub output_path: PathBuf,
thread: Option<JoinHandle<Result<()>>>,
running: Arc<AtomicBool>,
output_path: PathBuf,
pub sample_rate: u32,
pub channels: u16,
writer: Arc<Mutex<Option<BufWriter<File>>>>,
}
pub fn start(output_path: PathBuf) -> Result<AudioSession> {
let host = cpal::default_host();
let device = host
.default_output_device()
.ok_or_else(|| anyhow!("no default output device for loopback"))?;
let supported = device
.default_output_config()
.context("default output config")?;
let sample_rate = supported.sample_rate().0;
let channels = supported.channels();
let stream_config: cpal::StreamConfig = supported.config();
let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone();
let path_clone = output_path.clone();
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent).ok();
}
let file = File::create(&output_path).context("creating audio output file")?;
let writer = Arc::new(Mutex::new(Some(BufWriter::new(file))));
let writer_clone = writer.clone();
let (init_tx, init_rx) = std::sync::mpsc::channel();
let stream = device
.build_input_stream(
&stream_config,
move |data: &[f32], _info: &cpal::InputCallbackInfo| {
if let Ok(mut guard) = writer_clone.lock() {
if let Some(w) = guard.as_mut() {
let bytes: &[u8] = bytemuck_cast(data);
let _ = w.write_all(bytes);
}
}
},
|err| tracing::warn!("audio capture error: {err}"),
None,
)
.context("building input stream")?;
stream.play().context("starting audio stream")?;
let thread = thread::spawn(move || {
let result = capture_thread(running_clone, path_clone, init_tx);
if let Err(ref e) = result {
tracing::error!("audio capture thread ended with error: {e:#}");
}
result
});
let (sample_rate, channels) = init_rx
.recv_timeout(std::time::Duration::from_secs(3))
.context("audio capture thread failed to initialize within 3 seconds")?
.context("audio capture initialization failed")?;
Ok(AudioSession {
_stream: stream,
thread: Some(thread),
running,
output_path,
sample_rate,
channels,
writer,
})
}
impl AudioSession {
pub fn stop(self) -> Result<PathBuf> {
drop(self._stream);
if let Ok(mut guard) = self.writer.lock() {
if let Some(mut w) = guard.take() {
let _ = w.flush();
}
self.running.store(false, Ordering::Relaxed);
if let Some(t) = self.thread {
let _ = t.join();
}
Ok(self.output_path)
}
}
fn bytemuck_cast(data: &[f32]) -> &[u8] {
let len_bytes = std::mem::size_of_val(data);
unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, len_bytes) }
fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
// WAVEFORMATEX is repr(packed); copy fields to avoid unaligned ref UB.
let w_format_tag = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wFormatTag)) };
let n_channels = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nChannels)) };
let n_samples_per_sec = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nSamplesPerSec)) };
let w_bits_per_sample = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wBitsPerSample)) };
let is_float = if w_format_tag == WAVE_FORMAT_IEEE_FLOAT {
true
} else if w_format_tag == WAVE_FORMAT_PCM {
false
} else if w_format_tag == WAVE_FORMAT_EXTENSIBLE {
let ext = unsafe { &*(fmt as *const WAVEFORMATEX as *const WAVEFORMATEXTENSIBLE) };
let sub_fmt = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(ext.SubFormat)) };
sub_fmt == windows::core::GUID::from_u128(0x00000003_0000_0010_8000_00aa00389b71)
} else {
bail!("unsupported WAVEFORMATEX format tag: {}", w_format_tag);
};
Ok((n_samples_per_sec, n_channels, w_bits_per_sample, is_float))
}
fn capture_thread(
running: Arc<AtomicBool>,
output_path: PathBuf,
init_tx: std::sync::mpsc::Sender<Result<(u32, u16)>>,
) -> Result<()> {
unsafe {
CoInitializeEx(None, COINIT_APARTMENTTHREADED)
.ok()
.context("CoInitializeEx")?;
}
let enumerator: IMMDeviceEnumerator = unsafe {
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)
.context("CoCreateInstance MMDeviceEnumerator")?
};
let device = unsafe {
enumerator
.GetDefaultAudioEndpoint(eRender, eConsole)
.context("GetDefaultAudioEndpoint")?
};
let client: IAudioClient = unsafe {
device
.Activate::<IAudioClient>(CLSCTX_ALL, None)
.context("Activate IAudioClient")?
};
let mix_format_ptr = unsafe { client.GetMixFormat().context("GetMixFormat")? };
let mix_format = unsafe { &*mix_format_ptr };
let (sample_rate, channels, bits_per_sample, is_float) = parse_format(mix_format)?;
let buffer_duration = 10_000_000i64; // 1 second in 100-ns units
unsafe {
client
.Initialize(
windows::Win32::Media::Audio::AUDCLNT_SHAREMODE(0), // Shared
AUDCLNT_STREAMFLAGS_LOOPBACK,
buffer_duration,
0,
mix_format_ptr,
None,
)
.context("IAudioClient::Initialize")?;
}
unsafe {
CoTaskMemFree(Some(mix_format_ptr as *mut _));
}
let capture_client: IAudioCaptureClient = unsafe {
client
.GetService::<IAudioCaptureClient>()
.context("GetService IAudioCaptureClient")?
};
unsafe {
client.Start().context("IAudioClient::Start")?;
}
let file = File::create(&output_path).context("creating audio output file")?;
let mut writer = BufWriter::new(file);
// Notify parent that init succeeded.
let _ = init_tx.send(Ok((sample_rate, channels)));
while running.load(Ordering::Relaxed) {
let mut packet_length = unsafe {
capture_client
.GetNextPacketSize()
.context("GetNextPacketSize")?
};
while packet_length > 0 {
let mut data_ptr = std::ptr::null_mut();
let mut num_frames_available = 0u32;
let mut flags = 0u32;
unsafe {
capture_client
.GetBuffer(
&mut data_ptr,
&mut num_frames_available,
&mut flags,
None,
None,
)
.context("GetBuffer")?;
}
if num_frames_available > 0 {
let is_silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0;
let samples = (num_frames_available as usize) * (channels as usize);
if is_silent {
// Write f32 zeros for silent frames.
let zero_bytes = samples * 4;
let zeros = vec![0u8; zero_bytes];
writer.write_all(&zeros).context("writing silent audio")?;
} else if is_float {
let num_bytes = samples * (bits_per_sample as usize / 8);
let slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const u8, num_bytes)
};
writer.write_all(slice).context("writing audio data")?;
} else {
// Convert integer PCM to f32 little-endian.
match bits_per_sample {
16 => {
let i16_slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const i16, samples)
};
for &sample in i16_slice {
let f = sample as f32 / 32768.0;
writer
.write_all(&f.to_le_bytes())
.context("writing f32 sample")?;
}
}
32 => {
let i32_slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const i32, samples)
};
for &sample in i32_slice {
let f = sample as f32 / 2147483648.0;
writer
.write_all(&f.to_le_bytes())
.context("writing f32 sample")?;
}
}
_ => bail!("unsupported bits per sample: {bits_per_sample}"),
}
}
}
unsafe {
capture_client
.ReleaseBuffer(num_frames_available)
.context("ReleaseBuffer")?;
}
packet_length = unsafe {
capture_client
.GetNextPacketSize()
.context("GetNextPacketSize")?
};
}
thread::sleep(std::time::Duration::from_millis(1));
}
unsafe {
let _ = client.Stop();
}
writer.flush().context("flushing audio writer")?;
Ok(())
}
+91 -28
View File
@@ -46,7 +46,7 @@ struct Source {
const SOURCES: &[Source] = &[
Source {
name: "GyanD",
release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/tags/8.1.1",
release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/tags/latest",
asset_name_suffix: "full_build.7z",
kind: ArchiveKind::SevenZ,
},
@@ -60,6 +60,7 @@ const SOURCES: &[Source] = &[
#[derive(Debug, Deserialize)]
struct GithubRelease {
tag_name: String,
assets: Vec<GithubAsset>,
}
@@ -67,8 +68,6 @@ struct GithubRelease {
struct GithubAsset {
name: String,
browser_download_url: String,
#[serde(default)]
digest: Option<String>,
}
pub async fn download<F>(app_dir: &Path, mut on_progress: F) -> Result<()>
@@ -103,14 +102,31 @@ where
.user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
.build()?;
let asset = pick_asset(&client, source).await?;
let (asset, version) = pick_asset(&client, source).await?;
let expected = parse_sha256_digest(&asset.digest)
.with_context(|| format!("parsing digest for {}", asset.name))?;
// GyanD publishes a .sha256 file alongside each release.
// BtbN does not, so we skip verification for BtbN.
let expected = if source.name == "GyanD" {
let checksum_url = format!(
"https://github.com/GyanD/codexffmpeg/releases/download/{}/{}.sha256",
version,
asset.name
);
Some(fetch_sha256(&client, &checksum_url).await?)
} else {
tracing::warn!("BtbN build: skipping SHA-256 verification (no checksum file)");
None
};
let archive = download_verified(&client, &asset.browser_download_url, &expected, on_progress)
.await
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
let archive = if let Some(ref hash) = expected {
download_verified(&client, &asset.browser_download_url, hash, on_progress)
.await
.with_context(|| format!("downloading {}", asset.browser_download_url))?
} else {
download_plain(&client, &asset.browser_download_url, on_progress)
.await
.with_context(|| format!("downloading {}", asset.browser_download_url))?
};
match source.kind {
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?,
@@ -119,7 +135,65 @@ where
Ok(())
}
async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<GithubAsset> {
/// Fetch and parse a SHA-256 checksums file from GyanD.
/// The file contains a line like:
/// abc123def456... ffmpeg-8.1.1-full_build.7z
async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> {
let resp = client.get(url).send().await?.error_for_status()?;
let text = resp.text().await?;
// Each line is: "<hex> <filename>" - find the line with our filename
let hash_str = text
.lines()
.find_map(|line| {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return None;
}
// SHA-256 hex is 64 chars, followed by spaces and the filename
if line.len() < 64 {
return None;
}
let (hash, _file) = line.split_at(64);
let remainder = _file.trim_start();
// Must be followed by two spaces and a filename
if !remainder.starts_with(" ") {
return None;
}
Some(hash)
})
.ok_or_else(|| anyhow!("SHA-256 for this build not found in checksums file"))?;
let bytes = hex::decode(hash_str).context("checksum is not valid hex")?;
if bytes.len() != 32 {
bail!("checksum length is {} bytes, expected 32", bytes.len());
}
let mut sha = [0u8; 32];
sha.copy_from_slice(&bytes);
Ok(sha)
}
async fn download_plain<F>(
client: &reqwest::Client,
url: &str,
mut on_progress: F,
) -> Result<Vec<u8>>
where
F: FnMut(u64, Option<u64>),
{
let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length();
let mut buf: Vec<u8> = Vec::with_capacity(total.unwrap_or(0) as usize);
let mut downloaded = 0u64;
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
buf.extend_from_slice(&chunk);
downloaded += chunk.len() as u64;
on_progress(downloaded, total);
}
Ok(buf)
}
async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> {
let resp = client
.get(source.release_api_url)
.header("Accept", "application/vnd.github+json")
@@ -129,7 +203,11 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<GithubA
let body = resp.text().await?;
let release: GithubRelease =
serde_json::from_str(&body).context("parsing release metadata")?;
release
let version = release
.tag_name
.trim_start_matches('v')
.to_string();
let asset = release
.assets
.into_iter()
.find(|a| a.name.ends_with(source.asset_name_suffix))
@@ -138,23 +216,8 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<GithubA
"no asset matching '*{}' in release",
source.asset_name_suffix
)
})
}
fn parse_sha256_digest(digest: &Option<String>) -> Result<[u8; 32]> {
let raw = digest
.as_deref()
.ok_or_else(|| anyhow!("release asset has no digest"))?;
let hex_str = raw
.strip_prefix("sha256:")
.ok_or_else(|| anyhow!("digest is not sha256: '{raw}'"))?;
let bytes = hex::decode(hex_str).context("digest is not valid hex")?;
if bytes.len() != 32 {
bail!("digest length is {} bytes, expected 32", bytes.len());
}
let mut sha = [0u8; 32];
sha.copy_from_slice(&bytes);
Ok(sha)
})?;
Ok((asset, version))
}
async fn download_verified<F>(
+43 -8
View File
@@ -3,7 +3,7 @@ use std::path::PathBuf;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::time::Instant;
use anyhow::{anyhow, Result};
use anyhow::{anyhow, bail, Context, Result};
use windows_capture::capture::{
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
};
@@ -114,12 +114,14 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
self.scratch.clear();
let bytes = buf.as_nopadding_buffer(&mut self.scratch);
let expected = (self.width as usize) * (self.height as usize) * 4;
let slice = if bytes.len() >= expected {
&bytes[..expected]
} else {
bytes
};
let _ = stdin.write_all(slice);
if bytes.len() < expected {
tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected);
return Ok(());
}
stdin.write_all(&bytes[..expected]).map_err(|e| {
tracing::error!("ffmpeg stdin write failed: {e} — encoder may have crashed");
anyhow!("ffmpeg encoder stopped unexpectedly: {e}")
})?;
Ok(())
}
}
@@ -153,6 +155,22 @@ pub fn primary_monitor_dims() -> Result<(u32, u32)> {
Ok((w & !1, h & !1))
}
/// Find the monitor containing the given screen point using the Win32 API.
/// Falls back to the primary monitor if no monitor is found.
fn monitor_at_point(x: i32, y: i32) -> Result<Monitor> {
use windows::Win32::Foundation::POINT;
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
let pt = POINT { x, y };
let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
if hmonitor.0.is_null() {
bail!("MonitorFromPoint returned null for ({x}, {y})");
}
// SAFETY: hmonitor is a valid monitor handle from MonitorFromPoint.
let monitor = Monitor::from_raw_hmonitor(hmonitor.0 as *mut _);
Ok(monitor)
}
pub fn start(
output_path: PathBuf,
ffmpeg_path: PathBuf,
@@ -161,7 +179,19 @@ pub fn start(
crop: Option<CaptureRect>,
fps: u32,
) -> Result<CaptureSession> {
let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?;
// Use the center of the capture region to determine which monitor to capture.
// If the region spans monitors, we pick the one containing the center.
let monitor = if let Some(ref c) = crop {
let cx = c.x.saturating_add(c.width as i32 / 2);
let cy = c.y.saturating_add(c.height as i32 / 2);
tracing::info!("capture center=({cx}, {cy}), selecting monitor");
monitor_at_point(cx, cy).unwrap_or_else(|_| {
tracing::warn!("no monitor at ({cx}, {cy}), falling back to primary");
Monitor::primary().expect("primary monitor always available")
})
} else {
Monitor::primary().expect("primary monitor always available")
};
let raw_width = monitor
.width()
.map_err(|e| anyhow!("monitor width: {e:?}"))?;
@@ -238,6 +268,11 @@ impl CaptureSession {
self.control
.stop()
.map_err(|e| anyhow!("capture stop: {e}"))?;
let meta = std::fs::metadata(&self.output_path)
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
if meta.len() == 0 {
bail!("capture output file is empty — ffmpeg may have crashed during recording");
}
Ok(self.output_path)
}
}
+81 -4
View File
@@ -3,6 +3,14 @@ use std::path::{Path, PathBuf};
use anyhow::Result;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Theme {
#[default]
Dark,
Light,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
@@ -15,6 +23,8 @@ pub struct Config {
pub updates: UpdatesConfig,
#[serde(default)]
pub output_dir: Option<PathBuf>,
#[serde(default)]
pub theme: Theme,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -44,32 +54,36 @@ pub struct UpdatesConfig {
pub check_on_launch: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Format {
#[default]
Gif,
Webm,
Mp4,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum GifDither {
#[default]
FloydSteinberg,
Bayer,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum WebmCodec {
#[default]
Vp9,
Av1,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Mp4Codec {
#[default]
H264,
H265,
}
@@ -82,6 +96,7 @@ impl Default for Config {
hotkeys: HotkeyConfig::default(),
updates: UpdatesConfig::default(),
output_dir: None,
theme: Theme::Dark,
}
}
}
@@ -143,3 +158,65 @@ impl Config {
pub fn config_path(app_dir: &Path) -> PathBuf {
app_dir.join("config.toml")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_roundtrip() {
let cfg = Config {
export: ExportConfig {
default_format: Format::Webm,
gif_dither: GifDither::Bayer,
webm_codec: WebmCodec::Av1,
mp4_codec: Mp4Codec::H265,
},
capture: CaptureConfig {
default_fps: 60,
capture_cursor: false,
capture_audio: true,
},
hotkeys: HotkeyConfig {
start: Some("F9".to_string()),
stop: Some("F10".to_string()),
pause: Some("F11".to_string()),
},
updates: UpdatesConfig { check_on_launch: false },
output_dir: Some(PathBuf::from("./custom")),
theme: Theme::Light,
};
let dir = std::env::temp_dir().join("bytesize-test-config");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("config.toml");
cfg.save(&path).unwrap();
let loaded = Config::load_or_create(&path).unwrap();
assert_eq!(loaded.export.default_format, Format::Webm);
assert_eq!(loaded.capture.default_fps, 60);
assert_eq!(loaded.hotkeys.start, Some("F9".to_string()));
assert_eq!(loaded.output_dir, Some(PathBuf::from("./custom")));
assert_eq!(loaded.theme, Theme::Light);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn needs_first_run_when_hotkeys_missing() {
let cfg = Config::default();
assert!(cfg.needs_first_run());
}
#[test]
fn no_first_run_when_hotkeys_set() {
let cfg = Config {
hotkeys: HotkeyConfig {
start: Some("F9".to_string()),
stop: Some("F10".to_string()),
pause: Some("F11".to_string()),
},
..Config::default()
};
assert!(!cfg.needs_first_run());
}
}
+251 -15
View File
@@ -2,6 +2,8 @@ use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::mpsc::Sender;
use std::thread;
use anyhow::{anyhow, bail, Context, Result};
@@ -9,7 +11,19 @@ use crate::clicks::Click;
use crate::config::{Format, GifDither, Mp4Codec, WebmCodec};
use crate::CaptureRect;
const AUDIO_BITRATE_KBPS: u64 = 128;
// Used both for bitrate budget calculation and final mux. Must be consistent.
const AUDIO_BITRATE_KBPS: u64 = 192;
/// Progress update sent during encoding.
/// pass: 1-based pass number (1 or 2 for two-pass video, 1 for GIF).
/// total_passes: total number of passes.
/// percent: 0.0 to 100.0.
#[derive(Debug, Clone, Copy, serde::Serialize)]
pub struct EncodeProgress {
pub pass: u8,
pub total_passes: u8,
pub percent: f64,
}
#[derive(Debug, Clone)]
pub struct TranscodeRequest {
@@ -29,8 +43,13 @@ pub struct TranscodeRequest {
pub trim_start_secs: Option<f64>,
pub trim_end_secs: Option<f64>,
pub clicks: Vec<Click>,
/// Optional channel to report encoding progress.
#[doc(hidden)]
pub progress_tx: Option<Sender<EncodeProgress>>,
}
const MAX_CLICK_HIGHLIGHTS: usize = 50;
fn click_filters(req: &TranscodeRequest) -> Option<String> {
if req.clicks.is_empty() {
return None;
@@ -38,7 +57,15 @@ fn click_filters(req: &TranscodeRequest) -> Option<String> {
let size = 24i32;
let half = size / 2;
let mut parts: Vec<String> = Vec::new();
for click in &req.clicks {
let clicks_to_render = req.clicks.len().min(MAX_CLICK_HIGHLIGHTS);
if req.clicks.len() > MAX_CLICK_HIGHLIGHTS {
tracing::warn!(
"{} click events recorded, only first {} will be highlighted",
req.clicks.len(),
MAX_CLICK_HIGHLIGHTS
);
}
for click in &req.clicks[..clicks_to_render] {
let x = click.x - half;
let y = click.y - half;
let t1 = (click.time_secs - 0.05).max(0.0);
@@ -206,9 +233,8 @@ fn two_pass_video(
req: &TranscodeRequest,
video_codec: &str,
audio_codec: &str,
container: &str,
_container: &str,
) -> Result<()> {
let _ = container;
let bitrate_kbps = video_bitrate_kbps(req)?;
let bitrate = format!("{bitrate_kbps}k");
@@ -245,7 +271,16 @@ fn two_pass_video(
.arg("-an")
.args(["-f", "null"])
.arg(null_target);
run(&mut pass1, "pass 1")?;
let tx = req.progress_tx.clone();
let dur = req.duration_secs;
let fps = req.fps;
run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref())?;
// Send 50% to signal pass 1 done, pass 2 starting.
if let Some(ref t) = tx {
let _ = t.send(EncodeProgress { pass: 1, total_passes: 2, percent: 100.0 });
}
let mut pass2 = Command::new(ffmpeg);
pass2
@@ -270,7 +305,7 @@ fn two_pass_video(
pass2.arg("-an");
}
pass2.arg(&req.output);
run(&mut pass2, "pass 2")?;
run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref())?;
cleanup_pass_logs(&log_stem);
Ok(())
@@ -356,7 +391,15 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
.args(["-lavfi", &use_filter])
.args(["-loop", "0"])
.arg(&req.output);
run(&mut encode, "gif encode")?;
run_with_progress(
&mut encode,
"gif encode",
1,
1,
req.duration_secs,
req.fps,
req.progress_tx.as_ref(),
)?;
let _ = std::fs::remove_file(&palette_path);
Ok(())
@@ -533,6 +576,44 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
}
fn run(cmd: &mut Command, label: &str) -> Result<()> {
let output = run_impl(cmd, label, 0, 0, 0.0, 0, None)?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, head);
}
Ok(())
}
/// Run an ffmpeg command with progress monitoring.
/// progress_tx, if provided, receives (pass, total_passes, percent) updates.
fn run_with_progress(
cmd: &mut Command,
label: &str,
pass: u8,
total_passes: u8,
duration_secs: f64,
fps: u32,
progress_tx: Option<&Sender<EncodeProgress>>,
) -> Result<()> {
let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned())?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let head: String = stderr.lines().take(12).collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, head);
}
Ok(())
}
fn run_impl(
cmd: &mut Command,
label: &str,
progress_pass: u8,
progress_total_passes: u8,
progress_duration_secs: f64,
progress_fps: u32,
progress_tx: Option<Sender<EncodeProgress>>,
) -> Result<std::process::Output> {
use std::process::Stdio;
let mut printable = OsString::from(label);
@@ -544,14 +625,169 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> {
}
tracing::debug!("{}", printable.to_string_lossy());
cmd.stdout(Stdio::null()).stderr(Stdio::piped());
let output = cmd
.output()
let mut child = cmd
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.with_context(|| format!("spawning ffmpeg for {label}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let tail: String = stderr.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, tail);
// Spawn a thread to monitor stderr and emit progress.
let stderr = child.stderr.take();
let tx = progress_tx.clone();
let handle = stderr.map(move |serr| {
// Clone the Sender if present.
let tx = tx.as_ref().map(|t| t.clone());
let encode_dur = progress_duration_secs;
let fps = progress_fps;
let pass = progress_pass;
let total_passes = progress_total_passes;
thread::spawn(move || {
use std::io::{BufRead, BufReader};
let reader = BufReader::new(serr);
for line in reader.lines().map_while(Result::ok) {
if let Some(frame) = parse_frame_from_stderr(&line) {
let total = (encode_dur * fps as f64).max(1.0);
let percent = (frame / total * 100.0).min(100.0);
if let Some(ref sender) = tx {
let _ = sender.send(EncodeProgress {
pass,
total_passes,
percent,
});
}
}
}
})
});
let output = child.wait_with_output().context("waiting for ffmpeg")?;
if let Some(h) = handle {
let _ = h.join();
}
Ok(output)
}
/// Parse a frame count from an ffmpeg stderr progress line.
/// Lines look like: "frame= 123 fps= 30 q=-0.0 size= 1024kB time=00:00:04.10 ..."
fn parse_frame_from_stderr(line: &str) -> Option<f64> {
let trimmed = line.trim();
if !trimmed.starts_with("frame=") {
return None;
}
// Find the "frame= NNN" token and extract the number after it.
let after = trimmed.strip_prefix("frame=")?.trim_start();
let end = after
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(after.len());
let frame_str = &after[..end];
frame_str.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn dummy_request() -> TranscodeRequest {
TranscodeRequest {
input: PathBuf::new(),
output: PathBuf::new(),
format: Format::Mp4,
target_bytes: 0,
duration_secs: 10.0,
fps: 30,
keep_audio: true,
gif_dither: GifDither::FloydSteinberg,
webm_codec: WebmCodec::Vp9,
mp4_codec: Mp4Codec::H264,
scratch_dir: PathBuf::new(),
crop: None,
deleted_frame_indices: vec![],
trim_start_secs: None,
trim_end_secs: None,
clicks: vec![],
progress_tx: None,
}
}
#[test]
fn bitrate_for_8mb_10s_with_audio() {
let mut req = dummy_request();
req.target_bytes = 8 * 1024 * 1024;
req.duration_secs = 10.0;
req.keep_audio = true;
let kbps = video_bitrate_kbps(&req).unwrap();
// 8 MB * 8 * 0.95 = 60.96 Mbits total
// minus 192k * 10 = 1.92 Mbits audio
// video = ~59 Mbits / 10s = ~5900 kbps
assert!(kbps > 5800 && kbps < 6200);
}
#[test]
fn bitrate_for_8mb_10s_no_audio() {
let mut req = dummy_request();
req.target_bytes = 8 * 1024 * 1024;
req.duration_secs = 10.0;
req.keep_audio = false;
let kbps = video_bitrate_kbps(&req).unwrap();
// 8 MB * 8 * 0.95 = 60.96 Mbits total, all video
// 60.96 Mbits / 10s = ~6096 kbps
assert!(kbps > 6000 && kbps < 6500);
}
#[test]
fn bitrate_rejects_too_small() {
let mut req = dummy_request();
req.target_bytes = 1000;
req.duration_secs = 10.0;
req.keep_audio = true;
assert!(video_bitrate_kbps(&req).is_err());
}
#[test]
fn bitrate_floor_at_16_kbps() {
let mut req = dummy_request();
req.target_bytes = 1024 * 1024;
req.duration_secs = 600.0;
req.keep_audio = false;
let kbps = video_bitrate_kbps(&req).unwrap();
assert_eq!(kbps, 16);
}
#[test]
fn parse_ffmpeg_stderr_frame() {
assert_eq!(
parse_frame_from_stderr("frame= 123 fps= 30 q=-0.0 size= 1024kB"),
Some(123.0)
);
assert_eq!(
parse_frame_from_stderr("frame=9999 fps=60.0"),
Some(9999.0)
);
assert_eq!(parse_frame_from_stderr("size= 1024kB"), None);
}
#[test]
fn crop_filter_output() {
let rect = CaptureRect { x: 10, y: 20, width: 100, height: 200 };
assert_eq!(
crop_filter(Some(rect)),
Some("crop=100:200:10:20".to_string())
);
assert_eq!(crop_filter(None), None);
}
#[test]
fn click_filters_capped_at_max() {
let clicks: Vec<Click> = (0..100)
.map(|i| Click { time_secs: i as f64, x: i, y: i })
.collect();
let req = TranscodeRequest {
clicks,
..dummy_request()
};
let filter = click_filters(&req).unwrap();
let count = filter.matches("drawbox").count();
assert_eq!(count, MAX_CLICK_HIGHLIGHTS);
}
Ok(())
}
+257 -113
View File
@@ -10,7 +10,6 @@ mod windows_list;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
@@ -19,7 +18,7 @@ use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
use std::str::FromStr;
use crate::bootstrap::FfmpegStatus;
use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec};
use crate::config::{Config, Format};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct CaptureRect {
@@ -88,76 +87,19 @@ fn output_dir(app_dir: &Path, cfg: &Config) -> PathBuf {
}
fn timestamp_slug() -> String {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let local = chrono_like(now);
use windows::Win32::System::SystemInformation::GetLocalTime;
let st = unsafe { GetLocalTime() };
format!(
"{:04}{:02}{:02}-{:02}{:02}{:02}",
local.year, local.month, local.day, local.hour, local.minute, local.second
st.wYear,
st.wMonth,
st.wDay,
st.wHour,
st.wMinute,
st.wSecond
)
}
struct LocalTime {
year: u32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
}
fn chrono_like(epoch_secs: u64) -> LocalTime {
let seconds_per_day = 86400u64;
let days = epoch_secs / seconds_per_day;
let secs_in_day = epoch_secs % seconds_per_day;
let hour = (secs_in_day / 3600) as u32;
let minute = ((secs_in_day % 3600) / 60) as u32;
let second = (secs_in_day % 60) as u32;
let mut year = 1970u32;
let mut remaining = days as i64;
loop {
let leap = is_leap(year);
let days_in_year = if leap { 366 } else { 365 };
if remaining < days_in_year {
break;
}
remaining -= days_in_year;
year += 1;
}
let leap = is_leap(year);
let month_days: [i64; 12] = [
31,
if leap { 29 } else { 28 },
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
let mut month = 1u32;
for d in month_days {
if remaining < d {
break;
}
remaining -= d;
month += 1;
}
let day = remaining as u32 + 1;
LocalTime { year, month, day, hour, minute, second }
}
fn is_leap(year: u32) -> bool {
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
fn ext_for(format: Format) -> &'static str {
match format {
Format::Gif => "gif",
@@ -190,37 +132,61 @@ fn parse_shortcut(s: &str) -> Option<Shortcut> {
Shortcut::from_str(s).ok()
}
fn register_hotkeys(app: &AppHandle, cfg: &Config) {
/// Result of attempting to register all hotkeys.
/// Each field is None if the hotkey was not set, or Some(true/false) for success/failure.
#[derive(Debug, Clone, Serialize)]
pub struct HotkeyRegistrationResult {
pub start_ok: Option<bool>,
pub stop_ok: Option<bool>,
pub pause_ok: Option<bool>,
}
fn register_hotkeys(app: &AppHandle, cfg: &Config) -> HotkeyRegistrationResult {
let gs = app.global_shortcut();
let _ = gs.unregister_all();
let mut registered: Vec<(Shortcut, &'static str)> = Vec::new();
if let Some(s) = cfg.hotkeys.start.as_deref().and_then(parse_shortcut) {
registered.push((s, "start"));
}
if let Some(s) = cfg.hotkeys.stop.as_deref().and_then(parse_shortcut) {
registered.push((s, "stop"));
}
if let Some(s) = cfg.hotkeys.pause.as_deref().and_then(parse_shortcut) {
registered.push((s, "pause"));
}
for (sc, _) in &registered {
if let Err(e) = gs.register(*sc) {
tracing::warn!("registering shortcut failed: {e}");
}
let start_ok = cfg
.hotkeys
.start
.as_deref()
.and_then(parse_shortcut)
.map(|sc| gs.register(sc).is_ok());
let stop_ok = cfg
.hotkeys
.stop
.as_deref()
.and_then(parse_shortcut)
.map(|sc| gs.register(sc).is_ok());
let pause_ok = cfg
.hotkeys
.pause
.as_deref()
.and_then(parse_shortcut)
.map(|sc| gs.register(sc).is_ok());
HotkeyRegistrationResult {
start_ok,
stop_ok,
pause_ok,
}
}
#[derive(Serialize)]
struct SaveConfigResult {
hotkey_result: HotkeyRegistrationResult,
}
#[tauri::command]
fn save_config(
app: AppHandle,
state: State<'_, AppState>,
config: Config,
) -> Result<(), String> {
) -> Result<SaveConfigResult, String> {
let path = config::config_path(&state.app_dir);
config.save(&path).map_err(|e| format!("{e:#}"))?;
*state.config.lock().expect("config mutex") = config.clone();
register_hotkeys(&app, &config);
Ok(())
let hotkey_result = register_hotkeys(&app, &config);
Ok(SaveConfigResult { hotkey_result })
}
#[derive(Clone, Serialize)]
@@ -320,6 +286,31 @@ fn clear_temp_segments(app_dir: &Path) {
let _ = std::fs::remove_file(temp.join("audio-concat.pcm"));
}
/// Pad or trim a raw f32le PCM file so its duration matches `target_secs`.
fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs: f64) -> Result<()> {
use std::io::Write;
let bytes_per_sec = sample_rate as f64 * channels as f64 * 4.0;
let target_bytes = (target_secs * bytes_per_sec).round() as u64;
let current_bytes = std::fs::metadata(path)?.len();
if current_bytes == target_bytes {
return Ok(());
}
if current_bytes < target_bytes {
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
let zeros = vec![0u8; 64 * 1024];
let mut remaining = target_bytes - current_bytes;
while remaining > 0 {
let to_write = remaining.min(zeros.len() as u64) as usize;
file.write_all(&zeros[..to_write])?;
remaining -= to_write as u64;
}
} else {
let file = std::fs::OpenOptions::new().write(true).open(path)?;
file.set_len(target_bytes)?;
}
Ok(())
}
fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) {
if let Some(win) = app.get_webview_window("overlay") {
let _ = win.set_ignore_cursor_events(enabled);
@@ -370,6 +361,7 @@ fn start_capture(
Ok(s) => Some(s),
Err(e) => {
tracing::warn!("audio capture failed to start: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None
}
}
@@ -461,7 +453,7 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
}
#[tauri::command]
fn resume_capture(state: State<'_, AppState>) -> Result<(), String> {
fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
{
let slot = state.capture.lock().expect("capture mutex");
if slot.is_some() {
@@ -496,6 +488,7 @@ fn resume_capture(state: State<'_, AppState>) -> Result<(), String> {
Ok(s) => Some(s),
Err(e) => {
tracing::warn!("audio resume failed: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None
}
}
@@ -590,6 +583,13 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
let audio_concat = temp.join("audio-concat.pcm");
encode::concat_pcm(&ss.audio_segments, &audio_concat)
.map_err(|e| format!("audio concat: {e:#}"))?;
adjust_audio_length(
&audio_concat,
ss.audio_sample_rate.unwrap(),
ss.audio_channels.unwrap(),
ss.total_recorded_secs,
)
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
encode::mux_with_audio(
&ffmpeg,
&video_concat,
@@ -641,6 +641,8 @@ pub struct ExportRequest {
pub trim_end_secs: Option<f64>,
#[serde(default)]
pub output_path: Option<String>,
#[serde(default)]
pub crop: Option<CaptureRect>,
}
#[tauri::command]
@@ -679,19 +681,20 @@ fn render_preview(
return Err("ffmpeg.exe not found".to_string());
}
let target_width: u32 = match request.format {
Format::Gif => {
let frames = (request.fps as f64 * clip.duration_secs).max(1.0);
let budget = (request.target_bytes as f64) / (frames * 0.5);
let aspect = if clip.height == 0 {
16.0 / 9.0
} else {
clip.width as f64 / clip.height as f64
};
let w = (budget * aspect).sqrt();
(w.clamp(120.0, clip.width as f64) as u32 / 2) * 2
}
_ => clip.width,
let target_width: u32 = if request.format == Format::Gif {
// For GIF, derive a width that fits the target byte budget.
let frames = (request.fps as f64 * clip.duration_secs).max(1.0);
let budget = (request.target_bytes as f64) / (frames * 0.5);
let aspect = if clip.height == 0 {
16.0 / 9.0
} else {
clip.width as f64 / clip.height as f64
};
let w = (budget * aspect).sqrt();
(w.clamp(120.0, clip.width as f64) as u32 / 2) * 2
} else {
// For video formats, scale to a reasonable preview size.
clip.width.min(1280).max(160)
};
let preview_path = temp_dir(&state.app_dir).join("preview.png");
@@ -727,9 +730,98 @@ pub struct ExportResult {
pub size_bytes: u64,
}
const OVERLAY_BORDER_LOGICAL_PX: f64 = 2.0;
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 22.0;
fn apply_overlay_region(_win: &tauri::WebviewWindow) -> Result<(), String> {
Ok(())
}
fn start_overlay_clickthrough_poll(app: AppHandle) {
use std::time::Duration;
use windows::Win32::Foundation::{HWND, POINT, RECT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::HiDpi::GetDpiForWindow;
use windows::Win32::UI::WindowsAndMessaging::{GetCursorPos, GetWindowRect};
std::thread::spawn(move || {
let mut last_inner: Option<bool> = None;
loop {
std::thread::sleep(Duration::from_millis(30));
let overlay = match app.get_webview_window("overlay") {
Some(w) => w,
None => continue,
};
if !overlay.is_visible().unwrap_or(false) {
last_inner = None;
continue;
}
// During recording, the overlay should always be click-through.
// start_capture already sets ignore_cursor_events(true). Skip polling
// so we don't fight it.
let state = app.state::<AppState>();
let is_recording = state.capture.lock().expect("capture mutex").is_some();
if is_recording {
last_inner = Some(true);
continue;
}
let mut pt = POINT::default();
if unsafe { GetCursorPos(&mut pt) }.is_err() {
continue;
}
let raw = match overlay.hwnd() {
Ok(h) => h,
Err(_) => continue,
};
let hwnd = HWND(raw.0 as *mut _);
let mut dwm = RECT::default();
let dwm_ok = unsafe {
DwmGetWindowAttribute(
hwnd,
DWMWA_EXTENDED_FRAME_BOUNDS,
&mut dwm as *mut RECT as *mut std::ffi::c_void,
std::mem::size_of::<RECT>() as u32,
)
}
.is_ok()
&& dwm.right > dwm.left;
let visible = if dwm_ok {
dwm
} else {
let mut outer = RECT::default();
if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() {
continue;
}
outer
};
let dpi = unsafe { GetDpiForWindow(hwnd) };
let scale = if dpi > 0 { dpi as f64 / 96.0 } else { 1.0 };
let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
let inner_left = visible.left + border;
let inner_top = visible.top + border + titlebar;
let inner_right = visible.right - border;
let inner_bottom = visible.bottom - border;
let in_inner = pt.x >= inner_left
&& pt.x < inner_right
&& pt.y >= inner_top
&& pt.y < inner_bottom;
if last_inner != Some(in_inner) {
let _ = overlay.set_ignore_cursor_events(in_inner);
last_inner = Some(in_inner);
}
}
});
}
fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(), String> {
use windows::Win32::Foundation::HWND;
use windows::Win32::UI::WindowsAndMessaging::{
@@ -751,6 +843,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
.ok_or_else(|| "overlay window not found".to_string())?;
win.show().map_err(|e| e.to_string())?;
let _ = mark_overlay_excluded_from_capture(&win);
let _ = apply_overlay_region(&win);
win.set_focus().map_err(|e| e.to_string())
}
@@ -774,7 +867,9 @@ fn set_overlay_size(app: AppHandle, width: u32, height: u32) -> Result<(), Strin
let final_h =
height as f64 + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
.map_err(|e| e.to_string())
.map_err(|e| e.to_string())?;
let _ = apply_overlay_region(&win);
Ok(())
}
#[tauri::command]
@@ -815,7 +910,7 @@ fn open_window_picker(
picker
.set_position(Position::Physical(PhysicalPosition::new(0, 0)))
.map_err(|e| e.to_string())?;
let _ = picker.set_ignore_cursor_events(true);
let _ = picker.set_ignore_cursor_events(false);
let _ = picker.set_always_on_top(true);
picker.show().map_err(|e| e.to_string())?;
if let Ok(h) = picker.hwnd() {
@@ -895,6 +990,34 @@ fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) {
)
}
/// Get the DPI scale factor for the monitor containing a given point.
fn scale_factor_at_point(x: i32, y: i32) -> f64 {
use windows::Win32::Foundation::POINT;
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MONITOR_DPI_TYPE};
let pt = POINT { x, y };
let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
if hmonitor.0.is_null() {
return 1.0;
}
let mut dpi_x = 0u32;
let mut dpi_y = 0u32;
let hr = unsafe {
GetDpiForMonitor(
hmonitor,
MONITOR_DPI_TYPE(0), // MdtEffectiveDpi
&mut dpi_x,
&mut dpi_y,
)
};
if hr.is_ok() && dpi_x > 0 {
dpi_x as f64 / 96.0
} else {
1.0
}
}
#[tauri::command]
fn set_overlay_to_window(
app: AppHandle,
@@ -906,7 +1029,11 @@ fn set_overlay_to_window(
let win = app
.get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?;
let scale = win.scale_factor().map_err(|e| e.to_string())?;
// Use the target monitor's scale factor, not the overlay's current one,
// so border/titlebar compensation is correct when snapping across monitors.
let cx = x.saturating_add(width as i32 / 2);
let cy = y.saturating_add(height as i32 / 2);
let scale = scale_factor_at_point(cx, cy);
let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
@@ -951,6 +1078,7 @@ fn set_overlay_to_window(
}
.map_err(|e| format!("SetWindowPos: {e}"))?;
let _ = apply_overlay_region(&win);
let _ = (visible_left, visible_top, visible_w, visible_h, scale, border_phys, titlebar_phys);
Ok(())
}
@@ -1051,7 +1179,7 @@ fn open_url(url: String) -> Result<(), String> {
}
#[tauri::command]
fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
let cfg = state.config.lock().expect("config mutex").clone();
let clip = state
.last_clip
@@ -1125,14 +1253,35 @@ 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: None,
crop: request.crop,
deleted_frame_indices: request.deleted_frame_indices,
trim_start_secs: trim_start,
trim_end_secs: trim_end,
clicks: transformed_clicks,
progress_tx: None,
};
encode::transcode(&ffmpeg, &req).map_err(|e| format!("{e:#}"))?;
let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 };
let (tx, rx) = std::sync::mpsc::channel();
let mut req_with_progress = req;
req_with_progress.progress_tx = Some(tx);
let app_handle = app.clone();
// Spawn a thread to forward encode progress to the frontend.
std::thread::spawn(move || {
while let Ok(progress) = rx.recv() {
let _ = app_handle.emit(
"encode-progress",
encode::EncodeProgress {
pass: progress.pass,
total_passes,
percent: progress.percent,
},
);
}
});
encode::transcode(&ffmpeg, &req_with_progress).map_err(|e| format!("{e:#}"))?;
let size_bytes = std::fs::metadata(&out_path)
.map(|m| m.len())
@@ -1143,12 +1292,6 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportRe
})
}
// Suppress dead-code warnings for codec helper functions used only via config.
#[allow(dead_code)]
fn _codec_keepalive() -> (GifDither, WebmCodec, Mp4Codec) {
(GifDither::None, WebmCodec::Vp9, Mp4Codec::H264)
}
pub fn run() {
tracing_subscriber::fmt::init();
@@ -1237,7 +1380,8 @@ pub fn run() {
let cfg = st.config.lock().expect("config mutex").clone();
(cfg.updates.check_on_launch, cfg)
};
register_hotkeys(app.handle(), &cfg);
let _ = register_hotkeys(app.handle(), &cfg);
start_overlay_clickthrough_poll(app.handle().clone());
if check_on_launch {
let handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
+42
View File
@@ -124,3 +124,45 @@ fn is_newer(latest: &str, current: &str) -> bool {
c.resize(max, 0);
l > c
}
#[cfg(test)]
mod tests {
use super::is_newer;
#[test]
fn version_major_bump() {
assert!(is_newer("2.0.0", "1.9.9"));
assert!(!is_newer("1.9.9", "2.0.0"));
}
#[test]
fn version_minor_bump() {
assert!(is_newer("1.1.0", "1.0.0"));
assert!(!is_newer("1.0.0", "1.1.0"));
}
#[test]
fn version_patch_bump() {
assert!(is_newer("1.0.1", "1.0.0"));
assert!(!is_newer("1.0.0", "1.0.1"));
}
#[test]
fn version_equal() {
assert!(!is_newer("1.0.0", "1.0.0"));
}
#[test]
fn version_different_lengths() {
assert!(is_newer("1.0.1", "1.0"));
assert!(!is_newer("1.0", "1.0.1"));
assert!(is_newer("1.1", "1.0.9"));
}
#[test]
fn version_ignores_extra_text() {
assert!(is_newer("1.0.0-beta", "0.9.0"));
// "beta" doesn't parse as u32, so it's filtered out.
// 1.0.0 vs 0.9.0 -> newer
}
}
+1 -1
View File
@@ -56,7 +56,7 @@
"csp": null,
"assetProtocol": {
"enable": true,
"scope": ["**/*"]
"scope": ["$APPDIR/**", "$TEMP/**"]
}
}
},