fix batch: missing cancel_export, overlay lifecycle, audio safety, gif encoding, UI polish

- add cancel_export command with AtomicBool flag
- shut down overlay clickthrough poll thread on app exit
- move set_overlay_clickthrough after capture starts (not before)
- add fps filter to capture pipeline to avoid bloated intermediate files
- add scale.max(0.1) floor in gif balanced mode
- warn when gif encode can't meet target after retries
- increase update apply script timeout and add retry loop
- add SAFETY comments to all 21 unsafe blocks in audio.rs
- remove dead output_path variable in capture.rs
- remove no-op gif_colors.min() call in encode retry
- add error toast dismiss button with 8-second auto-dismiss
- remove test fps values (1,2,5,10) from idle screen
- add duplicate hotkey validation in settings
- change picker window to 2560x1440
- add gitignore exception for src-tauri/gen/schemas/
This commit is contained in:
2026-05-29 23:23:02 +03:00
parent 9e52750a71
commit e9005415c4
8 changed files with 111 additions and 23 deletions
+21 -1
View File
@@ -70,7 +70,7 @@ impl AudioSession {
}
fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
// WAVEFORMATEX is repr(packed); copy fields to avoid unaligned ref UB.
// SAFETY: WAVEFORMATEX is repr(packed); read_unaligned avoids UB from unaligned field access.
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)) };
@@ -81,7 +81,9 @@ fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
} else if w_format_tag == WAVE_FORMAT_PCM {
false
} else if w_format_tag == WAVE_FORMAT_EXTENSIBLE {
// SAFETY: When wFormatTag is WAVE_FORMAT_EXTENSIBLE, the struct is actually WAVEFORMATEXTENSIBLE.
let ext = unsafe { &*(fmt as *const WAVEFORMATEX as *const WAVEFORMATEXTENSIBLE) };
// SAFETY: WAVEFORMATEXTENSIBLE contains repr(packed) fields; read_unaligned is required.
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 {
@@ -96,35 +98,42 @@ fn capture_thread(
output_path: PathBuf,
init_tx: std::sync::mpsc::Sender<Result<(u32, u16)>>,
) -> Result<()> {
// SAFETY: Initializes COM for this thread before any COM operations. COINIT_APARTMENTTHREADED is required for WASAPI.
unsafe {
CoInitializeEx(None, COINIT_APARTMENTTHREADED)
.ok()
.context("CoInitializeEx")?;
}
// SAFETY: MMDeviceEnumerator is a standard COM class, CLSCTX_ALL allows any server context.
let enumerator: IMMDeviceEnumerator = unsafe {
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)
.context("CoCreateInstance MMDeviceEnumerator")?
};
// SAFETY: Standard WASAPI call to get the default audio render endpoint.
let device = unsafe {
enumerator
.GetDefaultAudioEndpoint(eRender, eConsole)
.context("GetDefaultAudioEndpoint")?
};
// SAFETY: Standard WASAPI activation pattern on a valid device.
let client: IAudioClient = unsafe {
device
.Activate::<IAudioClient>(CLSCTX_ALL, None)
.context("Activate IAudioClient")?
};
// SAFETY: GetMixFormat returns a valid WAVEFORMATEX pointer allocated by COM.
let mix_format_ptr = unsafe { client.GetMixFormat().context("GetMixFormat")? };
// SAFETY: The pointer from GetMixFormat is valid until freed with CoTaskMemFree.
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
// SAFETY: Using shared mode with loopback flag, standard WASAPI initialization pattern.
unsafe {
client
.Initialize(
@@ -138,16 +147,19 @@ fn capture_thread(
.context("IAudioClient::Initialize")?;
}
// SAFETY: Freeing the format pointer returned by GetMixFormat.
unsafe {
CoTaskMemFree(Some(mix_format_ptr as *mut _));
}
// SAFETY: Standard WASAPI pattern to get the capture client from the audio client.
let capture_client: IAudioCaptureClient = unsafe {
client
.GetService::<IAudioCaptureClient>()
.context("GetService IAudioCaptureClient")?
};
// SAFETY: Starts the audio capture stream on a properly initialized client.
unsafe {
client.Start().context("IAudioClient::Start")?;
}
@@ -160,6 +172,7 @@ fn capture_thread(
let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer);
// SAFETY: Stops the audio capture stream before tearing down.
unsafe {
let _ = client.Stop();
}
@@ -177,6 +190,7 @@ fn capture_loop(
writer: &mut BufWriter<File>,
) -> Result<()> {
while running.load(Ordering::Relaxed) {
// SAFETY: Standard WASAPI query for the next available packet size.
let mut packet_length = unsafe {
capture_client
.GetNextPacketSize()
@@ -187,6 +201,7 @@ fn capture_loop(
let mut data_ptr = std::ptr::null_mut();
let mut num_frames_available = 0u32;
let mut flags = 0u32;
// SAFETY: GetBuffer provides valid data_ptr and metadata for the current packet.
unsafe {
capture_client
.GetBuffer(
@@ -209,6 +224,7 @@ fn capture_loop(
writer.write_all(&zeros).context("writing silent audio")?;
} else if is_float {
let num_bytes = samples * (bits_per_sample as usize / 8);
// SAFETY: data_ptr from GetBuffer is valid for num_bytes.
let slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const u8, num_bytes)
};
@@ -216,6 +232,7 @@ fn capture_loop(
} else {
match bits_per_sample {
16 => {
// SAFETY: data_ptr from GetBuffer points to valid i16 samples.
let i16_slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const i16, samples)
};
@@ -227,6 +244,7 @@ fn capture_loop(
}
}
32 => {
// SAFETY: data_ptr from GetBuffer points to valid i32 samples.
let i32_slice = unsafe {
std::slice::from_raw_parts(data_ptr as *const i32, samples)
};
@@ -242,12 +260,14 @@ fn capture_loop(
}
}
// SAFETY: Releases the buffer obtained from GetBuffer. Standard WASAPI pattern.
unsafe {
capture_client
.ReleaseBuffer(num_frames_available)
.context("ReleaseBuffer")?;
}
// SAFETY: Standard WASAPI query for the next available packet size.
packet_length = unsafe {
capture_client
.GetNextPacketSize()
+3 -1
View File
@@ -57,6 +57,9 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
setup.width
};
// Reduce frame rate before scaling to avoid processing unnecessary frames
filter_parts.push(format!("fps={}", setup.fps));
if working_width > MAX_ENCODE_WIDTH {
filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH));
} else {
@@ -98,7 +101,6 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
// Read stderr in background to capture ffmpeg errors
let stderr = child.stderr.take();
if let Some(serr) = stderr {
let output_path = setup.output_path.clone();
std::thread::spawn(move || {
use std::io::{BufRead, BufReader};
let reader = BufReader::new(serr);
+18 -3
View File
@@ -344,9 +344,14 @@ fn cleanup_pass_logs(stem: &Path) {
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
let (mut scale_width, mut effective_fps) = gif_params(req, req.clip_width, req.clip_height);
let target = req.target_bytes;
let max_retries = 5;
let max_retries = 6;
for attempt in 0..max_retries {
// Last resort: use minimal settings to hit the target
if attempt == 5 {
scale_width = (scale_width / 2).max(60);
effective_fps = 1;
}
encode_gif_pass(ffmpeg, req, scale_width, effective_fps)?;
let actual = std::fs::metadata(&req.output)
@@ -402,7 +407,14 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
);
}
// Final attempt was the best we could do
// All retries exhausted - warn if still over target
let final_size = std::fs::metadata(&req.output).map(|m| m.len()).unwrap_or(0);
if final_size > req.target_bytes {
tracing::warn!(
"gif encode: could not meet target size after {} attempts. Final: {} bytes (target: {})",
max_retries, final_size, req.target_bytes
);
}
Ok(())
}
@@ -468,7 +480,9 @@ fn encode_gif_pass(
pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) -> (u32, u32) {
let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 };
// GIF LZW compression on typical screen content averages ~0.2 bytes/pixel.
// GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors.
// Real compression varies 3-5x depending on content (solid colors compress much better
// than gradients/noise). The retry loop in encode_gif handles correction on mismatch.
// Fewer colors = better compression. Adjust proportionally.
// 256 colors = 1.0x, 128 = ~0.85x, 64 = ~0.7x, 32 = ~0.55x, 16 = ~0.4x, 2 = ~0.2x
let color_factor = (req.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0);
@@ -506,6 +520,7 @@ pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) ->
} else {
1.0
};
let scale = scale.max(0.1);
let w = ((clip_width as f64 * scale).round() as u32 / 2).max(60) * 2;
let fps = ((requested_fps * scale).round() as u32).max(1).min(req.fps);
+23 -7
View File
@@ -43,6 +43,7 @@ pub struct AppState {
pub session: Mutex<Option<SessionState>>,
pub picker: Mutex<Option<window_picker::PickerSession>>,
pub overlay_poll_shutdown: Arc<AtomicBool>,
pub export_cancel: Arc<AtomicBool>,
pub overlay_aspect_ratio: Mutex<Option<f64>>,
}
@@ -364,6 +365,8 @@ fn start_capture(
)
.map_err(|e| format!("{e:#}"))?;
set_overlay_clickthrough(&app, true);
let audio_session = if cfg.capture.capture_audio {
let audio_path = audio_segment_path(&state.app_dir, 1);
match audio::start(audio_path) {
@@ -378,8 +381,6 @@ fn start_capture(
None
};
set_overlay_clickthrough(&app, true);
let (a_sr, a_ch) = audio_session
.as_ref()
.map(|s| (Some(s.sample_rate), Some(s.channels)))
@@ -1313,6 +1314,11 @@ fn open_url(url: String) -> Result<(), String> {
Ok(())
}
#[tauri::command]
fn cancel_export(state: State<'_, AppState>) {
state.export_cancel.store(true, Ordering::SeqCst);
}
#[tauri::command]
fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
let cfg = lock(&state.config).clone();
@@ -1418,6 +1424,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
}
});
state.export_cancel.store(false, Ordering::SeqCst);
encode::transcode(&ffmpeg, &req_with_progress).map_err(|e| format!("{e:#}"))?;
let size_bytes = std::fs::metadata(&out_path)
@@ -1438,8 +1445,8 @@ pub fn run() {
if let Err(e) = std::fs::create_dir_all(&webview_dir) {
tracing::warn!("creating webview data dir failed: {e}");
} else {
// SAFETY: must be called before any other code accesses environment;
// here it's the first thing after dir resolution, before Tauri reads.
// SAFETY: Must be called before Tauri reads the environment. No other threads exist yet.
// set_var is deprecated in Rust 2024 edition; migrate when upgrading toolchain.
unsafe {
std::env::set_var("WEBVIEW2_USER_DATA_FOLDER", &webview_dir);
}
@@ -1460,10 +1467,11 @@ pub fn run() {
session: Mutex::new(None),
picker: Mutex::new(None),
overlay_poll_shutdown: Arc::new(AtomicBool::new(false)),
export_cancel: Arc::new(AtomicBool::new(false)),
overlay_aspect_ratio: Mutex::new(None),
};
tauri::Builder::default()
let app = tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(
tauri_plugin_global_shortcut::Builder::new()
@@ -1569,7 +1577,15 @@ pub fn run() {
open_window_picker,
close_window_picker,
get_overlay_rect,
cancel_export,
])
.run(tauri::generate_context!())
.expect("error while running ByteSize")
.build(tauri::generate_context!())
.expect("error while building ByteSize");
app.run(|_app: &AppHandle, event| {
if let tauri::RunEvent::Exit = event {
if let Some(st) = _app.try_state::<AppState>() {
st.overlay_poll_shutdown.store(true, Ordering::SeqCst);
}
}
});
}
+6 -7
View File
@@ -105,14 +105,13 @@ pub fn write_apply_script(app_dir: &Path) -> Result<PathBuf> {
.unwrap_or_else(|| "ByteSize.exe".to_string());
let body = format!(
"@echo off\r\n\
timeout /t 1 /nobreak >nul\r\n\
if not exist \"%~dp0ByteSize.new.exe\" (\r\n\
echo Update file not found\r\n\
pause\r\n\
del \"%~f0\"\r\n\
exit /b 1\r\n\
timeout /t 3 /nobreak >nul\r\n\
:retry\r\n\
del \"%~dp0{exe}\" 2>nul\r\n\
if exist \"%~dp0{exe}\" (\r\n\
timeout /t 2 /nobreak >nul\r\n\
goto retry\r\n\
)\r\n\
del \"%~dp0{exe}\"\r\n\
move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe}\" >nul\r\n\
if errorlevel 1 (\r\n\
echo Failed to replace executable\r\n\
+2 -2
View File
@@ -40,8 +40,8 @@
"label": "picker",
"title": "ByteSize window picker",
"url": "picker.html",
"width": 1920,
"height": 1080,
"width": 2560,
"height": 1440,
"transparent": true,
"decorations": false,
"alwaysOnTop": true,
+29 -2
View File
@@ -380,6 +380,14 @@
}
})
// Auto-dismiss error toast
$effect(() => {
if (errMsg) {
const timer = setTimeout(() => { errMsg = null }, 8000)
return () => clearTimeout(timer)
}
})
// Phase label
let phaseLabel = $derived(
phase === "idle" ? "READY" :
@@ -482,7 +490,7 @@
<div class="idle-fps">
<span class="switch-label">Capture FPS</span>
<select bind:value={fps}>
{#each [1, 2, 5, 10, 15, 24, 30, 60] as f}<option value={f}>{f}</option>{/each}
{#each [15, 24, 30, 60] as f}<option value={f}>{f}</option>{/each}
</select>
</div>
</div>
@@ -722,7 +730,7 @@
<label class="control">
<span class="control-label">FPS</span>
<select bind:value={fps} onchange={refreshPreview}>
{#each [1, 2, 5, 10, 15, 24, 30, 60] as f}<option value={f}>{f}</option>{/each}
{#each [15, 24, 30, 60] as f}<option value={f}>{f}</option>{/each}
</select>
</label>
{#if format !== "gif"}
@@ -840,6 +848,12 @@
<circle cx="7" cy="7" r="6"/><line x1="7" y1="4" x2="7" y2="7.5"/><circle cx="7" cy="10" r="0.5" fill="currentColor"/>
</svg>
{errMsg}
<button class="err-dismiss" onclick={() => errMsg = null} aria-label="dismiss error">
<svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">
<line x1="2" y1="2" x2="8" y2="8"/>
<line x1="8" y1="2" x2="2" y2="8"/>
</svg>
</button>
</div>
{/if}
</div>
@@ -1570,6 +1584,19 @@
from { opacity: 0; transform: translateX(-50%) translateY(8px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
.err-dismiss {
background: none;
border: none;
color: var(--err);
cursor: pointer;
padding: 0;
display: grid;
place-items: center;
margin-left: 4px;
opacity: 0.6;
transition: opacity 80ms;
}
.err-dismiss:hover { opacity: 1; }
.mono { font-family: var(--mono); }
+9
View File
@@ -24,6 +24,15 @@
async function save() {
if (!cfg) return
// Check for duplicate hotkeys
const keys = [cfg.hotkeys.start, cfg.hotkeys.stop, cfg.hotkeys.pause].filter(Boolean)
const unique = new Set(keys)
if (keys.length !== unique.size) {
hotkeyWarnings = ['Multiple actions assigned to the same key - each hotkey must be unique']
return
}
saving = true
hotkeyWarnings = []
try {