1 Commits
Author SHA1 Message Date
Alvin-Zilverstand 32e258dee7 feat: v0.1.1 update stability, storage, buffer, events, and branding
Build Windows Release / Rust tests (push) Canceled after 0s
Build Windows Release / Windows installer (push) Canceled after 0s
- Bump all versions to 0.1.1 and harden the auto-updater so a newer
  release is only offered when an installer asset actually exists.
- Add clip-folder relocation, an auto-prune toggle, cached free-disk
  checks, and a 512 MB RAM clip buffer that reduces I/O for manual,
  auto, and hotkey clips.
- Move clip-related UI actions off the main thread, add optimistic
  toggling, and switch to event-driven library and screenshot refresh.
- Add a modal clip viewer with a fallback path/reveal UI when the
  local MP4 cannot load, plus a bitrate preset dropdown, an auto-clip
  rule grid, and per-game enable/disable controls.
- Replace placeholder icons with an SVG source and regenerate raster
  assets from a 1024x1024 render of the new ClipForge logo.
- Update the implementation-status notes for v0.1.1.
2026-09-14 16:24:01 +02:00
69 changed files with 1563 additions and 131 deletions

No files matched your search

Generated
+1 -1
View File
@@ -85,7 +85,7 @@ dependencies = [
[[package]]
name = "clipforge"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"dirs",
"reqwest",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "clipforge"
version = "0.1.0"
version = "0.1.1"
edition = "2021"
description = "Windows-first local game clipping app scaffold with replay buffer and event auto-clipping core."
license = "MIT"
+18 -3
View File
@@ -59,6 +59,19 @@
- An opt-in "Minimize to tray" setting keeps ClipForge running in the system tray when the main window is closed; closing the window hides it, and the tray menu offers "Open ClipForge" to restore it or "Quit ClipForge" to exit fully. The toggle is under Settings > Tray and defaults to off.
- Library search, event/upload filters, and grid/list switching are functional in the UI.
- User-visible notices are shown for major actions and failures instead of relying only on console output.
- Versions are bumped to `0.1.1` across root `Cargo.toml`, `src-tauri/Cargo.toml`, `tauri.conf.json`, `package.json`, and the frontend `appVersion` constant.
- The updater now requires both a newer release and a published installer asset before offering a download; the UI always shows "Check for updates" and only shows a Download button when an installer is available.
- The clip folder can be changed at runtime via `set_clip_directory`; the library root and asset-protocol scope are rebuilt without restarting the app.
- An optional auto-prune toggle deletes the oldest non-manual clips once the saved library exceeds the configured storage limit.
- Free disk space and storage-limit status are cached for 10 seconds, reducing repeated FS calls from the background and UI polls.
- A RAM-backed clip buffer (512 MB cap) keeps recent segments in memory and merges them with disk segments when manual, auto, or hotkey clips are saved; this lowers disk I/O and lets clips span RAM-only material.
- Clip-related commands (`save_manual_clip`, `start_capture`, `stop_capture`, `trim_clip`, `upload_clip`, `take_screenshot`) now run as async Tauri commands so they execute off the main thread.
- The recording toggle flips optimistically in the UI and rolls back on error.
- The backend emits `clip-saved`, `clip-deleted`, `screenshots-changed`, and `storage-cleanup` events; the UI listens for them and refreshes clips and screenshots on demand.
- A modal viewer opens for clips and screenshots; when a clip's MP4 cannot load, the modal shows the file path and a Reveal-in-Explorer button instead of a broken `<video>` element.
- Bitrate settings now offer a preset dropdown (Low / Medium / Stream-ready / High / Ultra) plus a custom numeric input.
- Auto Clip rules are displayed per game with an Enable / Disable toggle per game, plus Enable all / Disable all / Restore defaults buttons.
- The app icon source is now a checked-in SVG (`src-tauri/icons/icon.svg`); all platform raster icons and `icon.ico` are regenerated from a 1024×1024 PNG rendered from that SVG.
## Not Fully Working Yet
@@ -68,11 +81,13 @@
- Auto start/stop is conservative but live: when auto-record is enabled, supported detected games can start recording and stop when the game disappears.
- Recorder service still runs inside the Tauri process instead of a separate background service process.
- Auto-update requires a GitHub release whose tag is newer than the running app version and that ships MSI/NSIS assets (the existing `v0.0.1` release carries 0.1.0 assets, so it correctly reports up to date).
- RAM-backed clipping reduces disk churn but cannot eliminate it entirely; FFmpeg still writes final clips to disk, and very large segment histories may briefly exceed the RAM cap before pruning.
- SVG icon rasterization depends on the sharp-based tooling used during development; the generated `icon.ico` and PNGs are checked in so normal builds do not require it.
## Next Engineering Steps
1. Add per-process loopback capture so individual application audio can be captured independently of the system mix.
2. Add per-player kill/death/objective event detection for Dota 2 and other Source titles beyond the current match-level transitions.
3. Exercise the GitHub Actions release workflow with a real tag push and verify the published assets appear in a GitHub Release.
4. Split the recorder service into a separate background process so capture survives app restarts.
5. Run manual QA on Windows gaming hardware and tune CPU/GPU overhead.
3. Split the recorder service into a separate background process so capture survives app restarts.
4. Run manual QA on Windows gaming hardware and tune CPU/GPU overhead.
5. Exercise the GitHub Actions release workflow with the `v0.1.1` tag push and verify the published assets appear in a GitHub Release.
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "clipforge",
"version": "0.1.0",
"name": "clipforge",
"version": "0.1.1",
"private": true,
"packageManager": "pnpm@11.19.0",
"type": "module",
+2 -2
View File
@@ -358,7 +358,7 @@ dependencies = [
[[package]]
name = "clipforge"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"dirs 5.0.1",
"reqwest 0.12.28",
@@ -372,7 +372,7 @@ dependencies = [
[[package]]
name = "clipforge-desktop"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"clipforge",
"serde",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "clipforge-desktop"
version = "0.1.0"
version = "0.1.1"
edition = "2021"
description = "Tauri desktop shell for ClipForge."
license = "MIT"
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
</resources>
Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#2b6cff"/>
<stop offset="100%" stop-color="#8b5cf6"/>
</linearGradient>
</defs>
<rect width="1024" height="1024" rx="224" fill="url(#bg)"/>
<text x="512" y="718" font-family="Arial, Helvetica, sans-serif" font-size="560" font-weight="800" text-anchor="middle" fill="#ffffff">CF</text>
<circle cx="766" cy="264" r="66" fill="#34d399"/>
<circle cx="766" cy="264" r="28" fill="#191d26"/>
</svg>

After

Width:  |  Height:  |  Size: 605 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 925 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

+489 -83
View File
@@ -16,8 +16,7 @@ use clipforge::integrations::{
LeagueLiveClientPoller, RawGameEvent, ValveGsiIntegration,
};
use clipforge::media::{
collect_segments, concat_segments, generate_thumbnail, prune_old_segments, recent_segments,
trim_clip as ffmpeg_trim_clip,
concat_segments, generate_thumbnail, trim_clip as ffmpeg_trim_clip,
};
use clipforge::models::{Clip, ClipSource, GameEvent, RecordingStatus};
use clipforge::native_audio::{
@@ -26,6 +25,10 @@ use clipforge::native_audio::{
};
use clipforge::native_wgc::NativeWgcReplayCaptureBackend;
use clipforge::proc::hidden_command;
use clipforge::ram_buffer::{
collect_disk_segments, merged_segments, spool_merged, RamReplayBuffer,
DEFAULT_RAM_CAP_BYTES,
};
use clipforge::recorder::{RecorderAction, RecorderService};
use clipforge::settings::{load_or_create_settings, save_settings, AppSettings};
use clipforge::storage::{clip_path, is_inside_root, resolve_library_root, LibraryPaths};
@@ -37,7 +40,7 @@ use serde::Serialize;
use std::fs;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
@@ -45,7 +48,7 @@ use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tauri::menu::{Menu, MenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::{Manager, State};
use tauri::{Emitter, Manager, State};
struct AppRuntime {
library_root: PathBuf,
@@ -56,10 +59,22 @@ struct AppRuntime {
valve_events: Mutex<Vec<RawGameEvent>>,
hotkey_shortcuts: Mutex<Option<HotkeyShortcuts>>,
app_handle: Mutex<Option<tauri::AppHandle>>,
metrics: Mutex<MetricCache>,
ram_buffer: Mutex<RamReplayBuffer>,
ram_staging_dir: PathBuf,
capture_capabilities: OnceLock<CaptureCapabilities>,
quitting: AtomicBool,
}
/// Coarse caches so the frequent status poll never re-scans the disk or
/// refreshes sysinfo on the UI thread. Values expire after `METRIC_CACHE_TTL`.
struct MetricCache {
free_disk_gb: Option<(std::time::Instant, f64)>,
storage_limit_exceeded: Option<(std::time::Instant, bool)>,
}
const METRIC_CACHE_TTL: Duration = Duration::from_secs(10);
#[derive(Clone)]
struct CaptureCapabilities {
ffmpeg_path: Option<PathBuf>,
@@ -156,6 +171,7 @@ struct DesktopStatus {
system_audio_available: bool,
desktop_duplication_available: bool,
auto_clip_enabled_events: Vec<AutoClipEventDto>,
auto_clip_disabled_games: Vec<String>,
hotkey_clip_last_60s: String,
hotkey_clip_last_30s: String,
hotkey_toggle_session_recording: String,
@@ -165,6 +181,9 @@ struct DesktopStatus {
capture_bitrate_kbps: u32,
capture_resolution: String,
storage_limit_gb: u64,
clip_directory: String,
storage_limit_exceeded: bool,
auto_prune_old_clips: bool,
excluded_window_titles: Vec<String>,
separate_audio_tracks: bool,
game_quality_overrides: Vec<GameQualityOverrideDto>,
@@ -234,7 +253,7 @@ struct AutoClipEventDto {
fn get_status(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -273,7 +292,7 @@ fn refresh_detected_game_inner(runtime: &AppRuntime) -> Result<DesktopStatus, St
if !should_auto_start {
if !should_auto_stop {
return Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities));
return Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()));
}
}
}
@@ -299,7 +318,7 @@ fn set_replay_buffer(seconds: u64, runtime: State<'_, AppRuntime>) -> Result<Des
recorder.settings.clamp_replay_buffer();
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -309,7 +328,7 @@ fn set_mic_enabled(enabled: bool, runtime: State<'_, AppRuntime>) -> Result<Desk
recorder.settings.privacy.mic_enabled = enabled;
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -322,7 +341,7 @@ fn set_system_audio_enabled(
recorder.settings.privacy.system_audio_enabled = enabled;
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -368,7 +387,7 @@ fn set_mic_device(
recorder.settings.privacy.mic_device = device.filter(|value| !value.trim().is_empty());
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -381,7 +400,7 @@ fn set_auto_record_enabled(
recorder.settings.privacy.desktop_capture_requires_confirmation = !enabled;
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -394,7 +413,7 @@ fn set_minimize_to_tray_enabled(
recorder.settings.minimize_to_tray_enabled = enabled;
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -426,7 +445,7 @@ fn set_upload_settings(
recorder.settings.upload.custom_headers = parse_header_lines(&custom_headers.join("\n"));
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save upload settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -439,20 +458,89 @@ fn set_auto_clip_event_enabled(
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
let defaults = default_auto_clip_events_for_game(&game_id);
let events = recorder
.settings
.auto_clip
.enabled_events_by_game
.entry(game_id)
.or_insert_with(|| defaults.iter().map(|event| (*event).to_string()).collect());
{
let events = recorder
.settings
.auto_clip
.enabled_events_by_game
.entry(game_id.clone())
.or_insert_with(|| defaults.iter().map(|event| (*event).to_string()).collect());
if enabled {
events.insert(event_type);
} else {
events.remove(&event_type);
}
}
if enabled {
events.insert(event_type);
} else {
events.remove(&event_type);
recorder.settings.auto_clip.disabled_games.remove(&game_id);
}
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save auto-clip setting: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
fn set_game_auto_clip_enabled(
game_id: String,
enabled: bool,
runtime: State<'_, AppRuntime>,
) -> Result<DesktopStatus, String> {
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
if enabled {
recorder.settings.auto_clip.disabled_games.remove(&game_id);
} else {
recorder.settings.auto_clip.disabled_games.insert(game_id);
}
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save auto-clip setting: {error}"))?;
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
fn known_auto_clip_game_ids() -> Vec<&'static str> {
["league-of-legends", "counter-strike-2", "dota-2"].to_vec()
}
#[tauri::command]
fn enable_all_auto_clips(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
recorder.settings.auto_clip.disabled_games.clear();
for game_id in known_auto_clip_game_ids() {
let defaults = default_auto_clip_events_for_game(game_id);
recorder
.settings
.auto_clip
.enabled_events_by_game
.entry(game_id.to_string())
.or_insert_with(|| defaults.iter().map(|event| (*event).to_string()).collect());
}
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save auto-clip setting: {error}"))?;
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
fn disable_all_auto_clips(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
for game_id in known_auto_clip_game_ids() {
recorder.settings.auto_clip.disabled_games.insert(game_id.to_string());
}
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save auto-clip setting: {error}"))?;
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
fn restore_default_auto_clips(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
recorder.settings.auto_clip.disabled_games.clear();
recorder.settings.auto_clip.enabled_events_by_game.clear();
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save auto-clip setting: {error}"))?;
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -478,7 +566,56 @@ fn set_capture_settings(
recorder.settings.privacy.separate_audio_tracks = separate_audio_tracks;
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save capture settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
fn set_clip_directory(
clip_dir: String,
app: tauri::AppHandle,
runtime: State<'_, AppRuntime>,
) -> Result<DesktopStatus, String> {
let clean = clip_dir.trim();
if clean.is_empty() {
return Err("Clip folder cannot be empty.".to_string());
}
let new_dir = Path::new(clean);
if !new_dir.is_absolute() {
return Err("Clip folder must be an absolute path.".to_string());
}
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
if capture.is_some() {
return Err("Stop recording before changing the clip folder.".to_string());
}
recorder.paths = LibraryPaths::with_clip_root(
PathBuf::from(&runtime.library_root),
new_dir.to_path_buf(),
);
recorder
.paths
.ensure()
.map_err(|error| format!("Could not create clip folder: {error}"))?;
recorder.settings.clip_root = new_dir.to_path_buf();
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
// The custom folder must remain servable by the asset protocol even when
// it lives outside the default library directory.
let _ = app.asset_protocol_scope().allow_directory(new_dir, true);
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
fn set_auto_prune_enabled(
enabled: bool,
runtime: State<'_, AppRuntime>,
) -> Result<DesktopStatus, String> {
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
recorder.settings.auto_prune_old_clips = enabled;
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save settings: {error}"))?;
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -515,7 +652,7 @@ fn finish_onboarding(
recorder.settings.onboarding_complete = true;
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save onboarding settings: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
fn even_between(value: u32, min: u32, max: u32) -> u32 {
@@ -604,11 +741,14 @@ fn poll_auto_clip_events_inner(runtime: &AppRuntime) -> Result<Vec<ClipDto>, Str
}
}
}
if !created.is_empty() {
emit_event(runtime, "clip-saved", created.len());
}
Ok(created)
}
#[tauri::command]
fn save_manual_clip(seconds: u64, runtime: State<'_, AppRuntime>) -> Result<ClipDto, String> {
async fn save_manual_clip(seconds: u64, runtime: State<'_, AppRuntime>) -> Result<ClipDto, String> {
save_manual_clip_inner(seconds, runtime.inner())
}
@@ -621,17 +761,6 @@ fn save_manual_clip_inner(seconds: u64, runtime: &AppRuntime) -> Result<ClipDto,
let ffmpeg = find_ffmpeg_executable()
.ok_or_else(|| "FFmpeg was not found on PATH or in the bundled sidecar.".to_string())?;
let now = SystemTime::now();
let segment_paths = recent_segments(
&active.buffer_dir,
Duration::from_secs(seconds),
active.segment_duration,
now,
)
.map_err(|error| error.to_string())?;
if segment_paths.is_empty() {
return Err("The replay buffer has not produced any segments yet.".to_string());
}
let action = recorder
.save_manual_clip(Duration::from_secs(seconds), now)
.ok_or_else(|| "No active recording session is available.".to_string())?;
@@ -648,26 +777,29 @@ fn save_manual_clip_inner(seconds: u64, runtime: &AppRuntime) -> Result<ClipDto,
.cloned()
.ok_or_else(|| "Created clip was not found in the library.".to_string())?;
if let Err(error) = concat_segments(&ffmpeg, &segment_paths, &clip.path) {
if concat_union_segments(
runtime,
active,
&ffmpeg,
Some(Duration::from_secs(seconds)),
&clip.path,
)? == 0
{
recorder.library.remove_clip(&clip.id);
if let Ok(database) = runtime.database.lock() {
let _ = database.delete_clip(&clip.id);
}
return Err(error.to_string());
return Err("The replay buffer has not produced any segments yet.".to_string());
}
if let Some(thumbnail_path) = &clip.thumbnail_path {
let _ = generate_thumbnail(&ffmpeg, &clip.path, thumbnail_path);
}
let _ = prune_old_segments(
&active.buffer_dir,
recorder.settings.replay_buffer,
active.segment_duration,
);
let mut clip = clip;
maybe_auto_upload_clip(runtime, &mut recorder, &mut clip);
recorder.library.add_clip(clip.clone());
persist_clip(runtime, &clip)?;
save_manifest(&recorder)?;
emit_event(runtime, "clip-saved", clip.id.clone());
Ok(clip_to_dto(&clip))
}
@@ -683,16 +815,6 @@ fn handle_auto_event_inner(
let ffmpeg = find_ffmpeg_executable()
.ok_or_else(|| "FFmpeg was not found on PATH or in the bundled sidecar.".to_string())?;
let clip_window = recorder.settings.auto_clip.pre_roll + recorder.settings.auto_clip.post_roll;
let segment_paths = recent_segments(
&active.buffer_dir,
clip_window,
active.segment_duration,
SystemTime::now(),
)
.map_err(|error| error.to_string())?;
if segment_paths.is_empty() {
return Ok(None);
}
if !auto_clip_event_enabled(&recorder.settings, &event.game_id, &event.event_type.to_string()) {
return Ok(None);
@@ -710,13 +832,13 @@ fn handle_auto_event_inner(
.cloned()
.ok_or_else(|| "Created auto clip was not found in the library.".to_string())?;
if let Err(error) = concat_segments(&ffmpeg, &segment_paths, &clip.path) {
if concat_union_segments(runtime, active, &ffmpeg, Some(clip_window), &clip.path)? == 0 {
recorder.library.remove_clip(&clip.id);
let _ = runtime
.database
.lock()
.map(|database| database.delete_clip(&clip.id));
return Err(error.to_string());
return Ok(None);
}
if let Some(thumbnail_path) = &clip.thumbnail_path {
let _ = generate_thumbnail(&ffmpeg, &clip.path, thumbnail_path);
@@ -730,7 +852,7 @@ fn handle_auto_event_inner(
}
#[tauri::command]
fn start_capture(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
async fn start_capture(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
start_capture_inner(runtime.inner())
}
@@ -739,9 +861,18 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
let mut capture = runtime.capture.lock().map_err(|error| error.to_string())?;
if capture.is_some() {
return Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities));
return Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()));
}
// A fresh capture session starts with an empty in-memory replay buffer, in
// case a previous session was interrupted before `stop_capture` drained it.
runtime
.ram_buffer
.lock()
.map_err(|error| error.to_string())?
.clear();
let _ = fs::remove_dir_all(&runtime.ram_staging_dir);
let storage = clipforge::storage::check_storage_space(&recorder.paths.buffer_root);
if let clipforge::storage::StorageLevel::Critical = storage.level {
return Err(format!(
@@ -833,11 +964,11 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
backend,
});
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
fn stop_capture(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
async fn stop_capture(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
stop_capture_inner(runtime.inner())
}
@@ -849,14 +980,14 @@ fn stop_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
active.backend.stop().map_err(|error| error.to_string())?;
let ffmpeg = find_ffmpeg_executable()
.ok_or_else(|| "FFmpeg was not found on PATH or in the bundled sidecar.".to_string())?;
let segments = collect_segments(&active.buffer_dir)
.map_err(|error| error.to_string())?
.into_iter()
.map(|segment| segment.path)
.collect::<Vec<_>>();
if !segments.is_empty() {
concat_segments(&ffmpeg, &segments, &active.session_output_path)
.map_err(|error| error.to_string())?;
let finalized = concat_union_segments(
runtime,
&active,
&ffmpeg,
None,
&active.session_output_path,
)?;
if finalized > 0 {
let clip = add_session_clip(
&mut recorder,
active.session_output_path,
@@ -873,10 +1004,17 @@ fn stop_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
}
}
runtime
.ram_buffer
.lock()
.map_err(|error| error.to_string())?
.clear();
let _ = fs::remove_dir_all(&runtime.ram_staging_dir);
if matches!(recorder.state.status, RecordingStatus::RecordingSession) {
recorder.toggle_session_recording();
}
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -900,6 +1038,7 @@ fn delete_clip(clip_id: String, runtime: State<'_, AppRuntime>) -> Result<Vec<Cl
delete_clip_record(runtime.inner(), &clip_id)?;
save_manifest(&recorder)?;
emit_event(runtime.inner(), "clip-deleted", clip_id);
Ok(recorder.library.all().iter().map(clip_to_dto).collect())
}
@@ -925,7 +1064,7 @@ fn reveal_clip(clip_id: String, runtime: State<'_, AppRuntime>) -> Result<(), St
}
#[tauri::command]
fn trim_clip(
async fn trim_clip(
clip_id: String,
start_seconds: f64,
end_seconds: f64,
@@ -1006,7 +1145,7 @@ fn trim_clip(
}
#[tauri::command]
fn upload_clip(
async fn upload_clip(
clip_id: String,
provider: Option<String>,
custom_endpoint: Option<String>,
@@ -1151,11 +1290,12 @@ fn export_clip_copy(clip_id: String, runtime: State<'_, AppRuntime>) -> Result<S
}
#[tauri::command]
fn take_screenshot(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
async fn take_screenshot(runtime: State<'_, AppRuntime>) -> Result<DesktopStatus, String> {
handle_screenshot()?;
emit_simple_event(&runtime, "screenshots-changed");
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
let capture = runtime.capture.lock().map_err(|error| error.to_string())?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -1407,7 +1547,7 @@ fn default_auto_clip_events_for_game(game_id: &str) -> Vec<&'static str> {
}
fn auto_clip_event_enabled(settings: &AppSettings, game_id: &str, event_type: &str) -> bool {
if !settings.auto_clip.enabled {
if !settings.auto_clip.enabled || settings.auto_clip.disabled_games.contains(game_id) {
return false;
}
settings
@@ -1607,7 +1747,7 @@ fn set_hotkeys(
register_hotkeys(&app_handle, runtime.inner())?;
}
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
fn main() {
@@ -1616,6 +1756,8 @@ fn main() {
clipforge::crashlog::install_panic_hook(library_root.join("logs"));
let ram_staging_dir = library_root.join(".ram-staging");
tauri::Builder::default()
.manage(AppRuntime {
library_root,
@@ -1626,6 +1768,12 @@ fn main() {
valve_events: Mutex::new(Vec::new()),
hotkey_shortcuts: Mutex::new(None),
app_handle: Mutex::new(None),
metrics: Mutex::new(MetricCache {
free_disk_gb: None,
storage_limit_exceeded: None,
}),
ram_buffer: Mutex::new(RamReplayBuffer::default()),
ram_staging_dir,
capture_capabilities: OnceLock::new(),
quitting: AtomicBool::new(false),
})
@@ -1712,7 +1860,13 @@ fn main() {
set_minimize_to_tray_enabled,
set_upload_settings,
set_auto_clip_event_enabled,
set_game_auto_clip_enabled,
enable_all_auto_clips,
disable_all_auto_clips,
restore_default_auto_clips,
set_capture_settings,
set_clip_directory,
set_auto_prune_enabled,
finish_onboarding,
write_gsi_configs,
poll_auto_clip_events,
@@ -1752,7 +1906,7 @@ fn create_runtime() -> Result<(PathBuf, RecorderService, ClipDatabase), String>
let root = resolution.root;
let settings = load_or_create_settings(&root)
.map_err(|error| format!("Could not load settings: {error}"))?;
let paths = LibraryPaths::new(&root);
let paths = LibraryPaths::with_clip_root(&root, absolutize(&root, &settings.clip_root));
paths.ensure().map_err(|error| error.to_string())?;
let database = ClipDatabase::open(root.join("library.sqlite"))
.map_err(|error| format!("Could not open clip database: {error}"))?;
@@ -1910,6 +2064,7 @@ fn start_backend_workers(app: tauri::AppHandle) {
.name("clipforge-backend-workers".to_string())
.spawn(move || loop {
let runtime = app.state::<AppRuntime>();
ingest_ram_buffer(runtime.inner());
let _ = refresh_detected_game_inner(runtime.inner());
let _ = poll_auto_clip_events_inner(runtime.inner());
let _ = stop_capture_on_critical_storage(runtime.inner());
@@ -1946,9 +2101,13 @@ fn stop_capture_on_critical_storage(runtime: &AppRuntime) -> Result<(), String>
}
fn enforce_storage_cap(runtime: &AppRuntime) -> Result<(), String> {
let (buffer_root, limit_gb) = {
let (buffer_root, limit_gb, auto_prune) = {
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
(recorder.paths.buffer_root.clone(), recorder.settings.storage_limit_gb)
(
recorder.paths.buffer_root.clone(),
recorder.settings.storage_limit_gb,
recorder.settings.auto_prune_old_clips,
)
};
if limit_gb == 0 {
return Ok(());
@@ -1964,15 +2123,198 @@ fn enforce_storage_cap(runtime: &AppRuntime) -> Result<(), String> {
report.deleted_bytes / (1024 * 1024)
);
}
if auto_prune {
prune_saved_clips_over_limit(runtime, max_bytes)?;
}
Ok(())
}
/// Deletes the oldest non-manual clips (and their thumbnails) until the saved
/// library fits back under the storage limit. Only automatic/event/session
/// clips are eligible so a manually saved highlight is never silently removed.
fn prune_saved_clips_over_limit(runtime: &AppRuntime, max_bytes: u64) -> Result<(), String> {
let mut removed = 0usize;
loop {
let (thumbs_root, candidate) = {
let recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
if library_usage_bytes(&recorder) <= max_bytes {
break;
}
(
recorder.paths.thumbs_root.clone(),
recorder
.library
.all()
.iter()
.filter(|clip| !matches!(clip.source, ClipSource::ManualHotkey))
.min_by_key(|clip| clip.created_at)
.cloned(),
)
};
let Some(clip) = candidate else {
break;
};
let _ = fs::remove_file(&clip.path);
if let Some(thumbnail) = &clip.thumbnail_path {
let _ = remove_if_inside(&thumbs_root, thumbnail);
}
{
let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?;
recorder.library.remove_clip(&clip.id);
}
let _ = delete_clip_record(runtime, &clip.id);
removed += 1;
}
if removed > 0 {
eprintln!(
"ClipForge storage cap: auto-pruned {removed} old clip(s) to stay under the storage limit."
);
emit_event(runtime, "storage-cleanup", removed);
}
Ok(())
}
fn emit_event(runtime: &AppRuntime, name: &str, payload: impl serde::Serialize + Clone) {
if let Ok(guard) = runtime.app_handle.lock() {
if let Some(handle) = guard.as_ref() {
let _ = handle.emit(name, payload);
}
}
}
fn emit_simple_event(state: &State<'_, AppRuntime>, name: &str) {
if let Ok(guard) = state.app_handle.lock() {
if let Some(handle) = guard.as_ref() {
let _ = handle.emit(name, ());
}
}
}
fn absolutize(root: &Path, value: &Path) -> PathBuf {
if value.is_absolute() {
value.to_path_buf()
} else {
root.join(value)
}
}
fn remove_if_inside(root: &Path, path: &Path) -> std::io::Result<()> {
if clipforge::storage::is_inside_root(root, path) && path.exists() {
fs::remove_file(path)
} else {
Ok(())
}
}
/// Merges the on-disk + in-RAM replay buffer and concatenates it into
/// `output`. RAM-held segments are materialized into a per-call staging
/// folder so FFmpeg sees real files; the folder is deleted afterwards.
/// Returns the number of segments that were stitched together (0 when the
/// buffer was empty, which leaves `output` untouched).
fn concat_union_segments(
runtime: &AppRuntime,
active: &ActiveCapture,
ffmpeg: &Path,
window: Option<Duration>,
output: &Path,
) -> Result<usize, String> {
let now = SystemTime::now();
let key = format!("clip-{}", unix_millis(now));
let staging = runtime.ram_staging_dir.join(&key);
let (paths, count) = {
let ram = runtime.ram_buffer.lock().map_err(|error| error.to_string())?;
let merged = merged_segments(
&ram,
&active.buffer_dir,
window,
active.segment_duration,
now,
)
.map_err(|error| error.to_string())?;
let paths = spool_merged(&staging, &key, &merged).map_err(|error| error.to_string())?;
(paths, merged.len())
};
if count == 0 || paths.is_empty() {
let _ = fs::remove_dir_all(&staging);
return Ok(0);
}
concat_segments(ffmpeg, &paths, output).map_err(|error| error.to_string())?;
let _ = fs::remove_dir_all(&staging);
Ok(count)
}
/// Moves completed replay segments from disk into the in-memory ring buffer,
/// then prunes the buffer to stay within the configured replay window and a
/// hard byte ceiling. The newest `.mp4` in the active session directory is
/// always skipped because the encoder may still be writing it.
fn ingest_ram_buffer(runtime: &AppRuntime) {
let (buffer_dir, replay_window, segment_duration) = {
let recorder = match runtime.recorder.lock() {
Ok(recorder) => recorder,
Err(_) => return,
};
let capture = match runtime.capture.lock() {
Ok(capture) => capture,
Err(_) => return,
};
let Some(active) = capture.as_ref() else {
drop(capture);
drop(recorder);
runtime
.ram_buffer
.lock()
.unwrap_or_else(|poison| poison.into_inner())
.clear();
return;
};
(
active.buffer_dir.clone(),
recorder.settings.replay_buffer,
active.segment_duration,
)
};
let disk_segments = match collect_disk_segments(&buffer_dir) {
Ok(disk_segments) => disk_segments,
Err(_) => return,
};
if disk_segments.is_empty() {
return;
}
let mut ram = runtime
.ram_buffer
.lock()
.unwrap_or_else(|poison| poison.into_inner());
// Skip the newest file — it is either the live segment still being written
// or, if not yet finalized, a segment that will complete before the next
// ingest cycle and will then be ingested safely.
let ingestible = disk_segments.len().saturating_sub(1);
for segment in &disk_segments[..ingestible] {
if ram.contains(&segment.file_name) {
continue;
}
let data = match fs::read(&segment.path) {
Ok(data) => data,
Err(_) => continue,
};
ram.insert(segment.file_name.clone(), segment.modified_at, data);
let _ = fs::remove_file(&segment.path);
}
let now = SystemTime::now();
ram.prune_to_window(replay_window, segment_duration, now);
ram.cap_bytes(DEFAULT_RAM_CAP_BYTES);
}
fn status_from_recorder(
runtime: &AppRuntime,
recorder: &RecorderService,
capture: Option<&ActiveCapture>,
capabilities: &OnceLock<CaptureCapabilities>,
) -> DesktopStatus {
let capabilities = capabilities.get().unwrap_or(&DEFAULT_CAPS);
let capabilities = runtime
.capture_capabilities
.get()
.unwrap_or(&DEFAULT_CAPS);
let game_id = recorder.state.detected_game_id.clone().unwrap_or_default();
let quality = recorder.settings.effective_quality_for(&game_id).clone();
DesktopStatus {
@@ -2010,15 +2352,19 @@ fn status_from_recorder(
system_audio_available: capabilities.system_audio_available,
desktop_duplication_available: capabilities.desktop_duplication_available,
auto_clip_enabled_events: auto_clip_event_dtos(&recorder.settings),
auto_clip_disabled_games: recorder.settings.auto_clip.disabled_games.iter().cloned().collect(),
hotkey_clip_last_60s: recorder.settings.hotkeys.clip_last_60s.clone(),
hotkey_clip_last_30s: recorder.settings.hotkeys.clip_last_30s.clone(),
hotkey_toggle_session_recording: recorder.settings.hotkeys.toggle_session_recording.clone(),
hotkey_screenshot: recorder.settings.hotkeys.screenshot.clone(),
free_disk_gb: clipforge::storage::check_storage_space(&recorder.paths.buffer_root).free_gb(),
free_disk_gb: cached_free_disk(runtime, &recorder.paths),
capture_fps: quality.fps,
capture_bitrate_kbps: quality.bitrate_kbps,
capture_resolution: format!("{}x{}", quality.width, quality.height),
storage_limit_gb: recorder.settings.storage_limit_gb,
clip_directory: recorder.paths.clip_root.display().to_string(),
storage_limit_exceeded: cached_limit_exceeded(runtime, recorder),
auto_prune_old_clips: recorder.settings.auto_prune_old_clips,
excluded_window_titles: recorder.settings.privacy.excluded_window_titles.clone(),
separate_audio_tracks: recorder.settings.privacy.separate_audio_tracks,
game_quality_overrides: quality_override_dtos(&recorder.settings),
@@ -2029,6 +2375,66 @@ fn status_from_recorder(
}
}
fn cached_free_disk(runtime: &AppRuntime, paths: &LibraryPaths) -> f64 {
let mut metrics = runtime.metrics.lock().unwrap_or_else(|poison| poison.into_inner());
if let Some((at, value)) = metrics.free_disk_gb {
if at.elapsed() < METRIC_CACHE_TTL {
return value;
}
}
let value = clipforge::storage::check_storage_space(&paths.buffer_root).free_gb();
metrics.free_disk_gb = Some((std::time::Instant::now(), value));
value
}
fn cached_limit_exceeded(runtime: &AppRuntime, recorder: &RecorderService) -> bool {
let limit = recorder.settings.storage_limit_gb;
if limit == 0 {
return false;
}
let mut metrics = runtime.metrics.lock().unwrap_or_else(|poison| poison.into_inner());
if let Some((at, value)) = metrics.storage_limit_exceeded {
if at.elapsed() < METRIC_CACHE_TTL {
return value;
}
}
let value = library_usage_bytes(recorder) > limit.saturating_mul(1024 * 1024 * 1024);
metrics.storage_limit_exceeded = Some((std::time::Instant::now(), value));
value
}
fn library_usage_bytes(recorder: &RecorderService) -> u64 {
let mut total = 0u64;
for dir in [&recorder.paths.clip_root, &recorder.paths.thumbs_root] {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() {
total = total.saturating_add(dir_bytes(&entry_path));
} else if let Ok(meta) = entry.metadata() {
total = total.saturating_add(meta.len());
}
}
}
}
total
}
fn dir_bytes(path: &std::path::Path) -> u64 {
let mut total = 0u64;
if let Ok(entries) = fs::read_dir(path) {
for entry in entries.flatten() {
let entry_path = entry.path();
if entry_path.is_dir() {
total = total.saturating_add(dir_bytes(&entry_path));
} else if let Ok(meta) = entry.metadata() {
total = total.saturating_add(meta.len());
}
}
}
total
}
fn quality_override_dtos(settings: &AppSettings) -> Vec<GameQualityOverrideDto> {
settings
.quality_overrides_by_game
@@ -2077,7 +2483,7 @@ fn set_game_quality_override(
.insert(game_id, preset);
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save quality override: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
#[tauri::command]
@@ -2090,7 +2496,7 @@ fn clear_game_quality_override(
recorder.settings.quality_overrides_by_game.remove(&game_id);
save_settings(&runtime.library_root, &recorder.settings)
.map_err(|error| format!("Could not save quality override: {error}"))?;
Ok(status_from_recorder(&recorder, capture.as_ref(), &runtime.capture_capabilities))
Ok(status_from_recorder(&runtime, &recorder, capture.as_ref()))
}
fn clip_to_dto(clip: &Clip) -> ClipDto {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "ClipForge",
"version": "0.1.0",
"version": "0.1.1",
"identifier": "app.clipforge.desktop",
"build": {
"beforeDevCommand": "pnpm run dev",
+1
View File
@@ -4,6 +4,7 @@ pub mod capture;
pub mod crashlog;
pub mod database;
pub mod game_detection;
pub mod ram_buffer;
pub mod game_watcher;
pub mod gsi_config;
pub mod hotkeys;
+325
View File
@@ -0,0 +1,325 @@
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
/// One finished replay segment held entirely in memory. Encoders write to a
/// file path, so a background worker moves each completed segment from disk
/// into RAM (and removes the on-disk copy) right after it is finalized.
#[derive(Debug, Clone)]
pub struct RamSegment {
pub file_name: String,
pub modified_at: SystemTime,
pub data: Vec<u8>,
}
#[derive(Default)]
pub struct RamReplayBuffer {
segments: Vec<RamSegment>,
}
/// Hard ceiling so the in-memory replay buffer can never exhaust the
/// machine's RAM, even if the replay window grows well beyond the default.
pub const DEFAULT_RAM_CAP_BYTES: usize = 512 * 1024 * 1024;
impl RamReplayBuffer {
pub fn insert(&mut self, file_name: String, modified_at: SystemTime, data: Vec<u8>) {
self.segments.retain(|segment| segment.file_name != file_name);
self.segments.push(RamSegment {
file_name,
modified_at,
data,
});
self.segments
.sort_by(|left, right| left.modified_at.cmp(&right.modified_at));
}
pub fn contains(&self, file_name: &str) -> bool {
self.segments
.iter()
.any(|segment| segment.file_name == file_name)
}
/// Keeps only segments younger than the replay window plus one segment of
/// slack, mirroring the disk-side policy in `prune_old_segments`.
pub fn prune_to_window(
&mut self,
window: Duration,
segment_duration: Duration,
now: SystemTime,
) {
let cutoff = now
.checked_sub(window + segment_duration)
.unwrap_or(SystemTime::UNIX_EPOCH);
self.segments.retain(|segment| segment.modified_at >= cutoff);
}
/// Safety net: drops the oldest segments until the retained bytes fit
/// under `cap`. Independent of the configured replay window.
pub fn cap_bytes(&mut self, cap: usize) {
let mut total: usize = self.segments.iter().map(|segment| segment.data.len()).sum();
while total > cap {
let Some(oldest) = self.segments.first() else {
break;
};
total = total.saturating_sub(oldest.data.len());
self.segments.remove(0);
}
}
pub fn clear(&mut self) {
self.segments.clear();
}
pub fn is_empty(&self) -> bool {
self.segments.is_empty()
}
pub fn buffered_bytes(&self) -> usize {
self.segments.iter().map(|segment| segment.data.len()).sum()
}
}
/// A save candidate that may live either on disk (not yet ingested into RAM)
/// or strictly in RAM.
#[derive(Debug)]
pub struct MergedSegment {
pub modified_at: SystemTime,
pub file_name: String,
pub on_disk: Option<PathBuf>,
pub in_ram: Option<RamSegment>,
}
/// Merges the rolling segments for a save operation: everything still on disk
/// plus everything held in RAM, deduplicated by file name (a segment is either
/// on disk or already ingested), and sorted oldest-first. When `window` is
/// provided only segments inside the window are kept; `None` selects the whole
/// buffer (used when finishing a session recording).
pub fn merged_segments(
ram: &RamReplayBuffer,
buffer_dir: &Path,
window: Option<Duration>,
segment_duration: Duration,
now: SystemTime,
) -> io::Result<Vec<MergedSegment>> {
let cutoff = match window {
Some(window) => now
.checked_sub(window + segment_duration)
.unwrap_or(SystemTime::UNIX_EPOCH),
None => SystemTime::UNIX_EPOCH,
};
let mut merged: Vec<MergedSegment> = collect_disk_segments(buffer_dir)?
.into_iter()
.filter(|segment| segment.modified_at >= cutoff)
.map(|segment| MergedSegment {
modified_at: segment.modified_at,
file_name: segment.file_name,
on_disk: Some(segment.path),
in_ram: None,
})
.collect();
for ram_segment in ram
.segments
.iter()
.filter(|segment| segment.modified_at >= cutoff)
{
if let Some(disk) = merged
.iter_mut()
.find(|candidate| candidate.file_name == ram_segment.file_name)
{
disk.in_ram = Some(ram_segment.clone());
} else {
merged.push(MergedSegment {
modified_at: ram_segment.modified_at,
file_name: ram_segment.file_name.clone(),
on_disk: None,
in_ram: Some(ram_segment.clone()),
});
}
}
merged.sort_by(|left, right| left.modified_at.cmp(&right.modified_at));
Ok(merged)
}
/// Materializes RAM-held segments into real files inside `staging_dir` so that
/// FFmpeg can concatenate them, and returns the ordered list of paths covering
/// the whole merge (disk files are used in place, never copied).
pub fn spool_merged(
staging_dir: &Path,
prefix: &str,
merged: &[MergedSegment],
) -> io::Result<Vec<PathBuf>> {
if merged.is_empty() {
return Ok(Vec::new());
}
fs::create_dir_all(staging_dir)?;
let mut paths = Vec::with_capacity(merged.len());
for (index, segment) in merged.iter().enumerate() {
if let Some(path) = &segment.on_disk {
paths.push(path.clone());
} else if let Some(segment) = &segment.in_ram {
let staged = staging_dir.join(format!(
"{prefix}-{index:04}-{}",
sanitize_file_name(&segment.file_name)
));
fs::write(&staged, &segment.data)?;
paths.push(staged);
}
}
Ok(paths)
}
fn sanitize_file_name(name: &str) -> String {
name.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') {
character
} else {
'_'
}
})
.collect()
}
/// Lists `.mp4` files directly inside a buffer directory (current session only).
pub fn collect_disk_segments(buffer_dir: &Path) -> io::Result<Vec<DiskSegmentFile>> {
let mut segments = Vec::new();
if !buffer_dir.exists() {
return Ok(segments);
}
for entry in fs::read_dir(buffer_dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|value| value.to_str()) != Some("mp4") {
continue;
}
let file_name = entry.file_name().to_string_lossy().into_owned();
let modified_at = entry.metadata()?.modified().unwrap_or(SystemTime::UNIX_EPOCH);
segments.push(DiskSegmentFile {
file_name,
path,
modified_at,
});
}
segments.sort_by(|left, right| left.modified_at.cmp(&right.modified_at));
Ok(segments)
}
#[derive(Debug, Clone)]
pub struct DiskSegmentFile {
pub file_name: String,
pub path: PathBuf,
pub modified_at: SystemTime,
}
#[cfg(test)]
mod tests {
use super::*;
fn segment(file_name: &str, age: u64, now: SystemTime) -> RamSegment {
RamSegment {
file_name: file_name.to_string(),
modified_at: now - Duration::from_secs(age),
data: file_name.as_bytes().to_vec(),
}
}
#[test]
fn window_prune_drops_only_stale_segments() {
let now = SystemTime::now();
let mut ram = RamReplayBuffer::default();
ram.insert("a.mp4".to_string(), now - Duration::from_secs(60), vec![1]);
ram.insert("b.mp4".to_string(), now - Duration::from_secs(20), vec![2]);
ram.insert("c.mp4".to_string(), now - Duration::from_secs(2), vec![3]);
ram.prune_to_window(Duration::from_secs(30), Duration::from_secs(5), now);
let remaining: Vec<&str> = ram
.segments
.iter()
.map(|segment| segment.file_name.as_str())
.collect();
assert_eq!(remaining, vec!["b.mp4", "c.mp4"]);
}
#[test]
fn byte_cap_frees_oldest_first() {
let now = SystemTime::now();
let mut ram = RamReplayBuffer::default();
ram.insert("a.mp4".to_string(), now - Duration::from_secs(30), vec![0; 100]);
ram.insert("b.mp4".to_string(), now - Duration::from_secs(20), vec![0; 100]);
ram.insert("c.mp4".to_string(), now - Duration::from_secs(10), vec![0; 100]);
ram.cap_bytes(250);
let first = ram.segments.first().map(|segment| segment.file_name.as_str());
assert_eq!(first, Some("b.mp4"));
assert_eq!(ram.buffered_bytes(), 200);
}
#[test]
fn merge_prefers_disk_copy_and_is_sorted() {
let root = std::env::temp_dir().join(format!(
"clipforge-ram-{}",
crate::media::timestamp_millis(SystemTime::now())
));
fs::create_dir_all(&root).expect("test root");
let now = SystemTime::now();
fs::write(root.join("disk.mp4"), b"disk").expect("disk file");
// The disk file's real mtime is essentially "now", so it sorts after
// the RAM-held segment that claims to be 6 seconds old.
let disk_modified_at = fs::metadata(root.join("disk.mp4"))
.expect("disk metadata")
.modified()
.expect("disk modified");
let mut ram = RamReplayBuffer::default();
ram.insert(
"disk.mp4".to_string(),
now - Duration::from_secs(10),
b"ram-copy".to_vec(),
);
ram.insert(
"ram-only.mp4".to_string(),
now - Duration::from_secs(6),
b"ram-only".to_vec(),
);
ram.insert(
"old.mp4".to_string(),
now - Duration::from_secs(120),
b"old".to_vec(),
);
let merged = merged_segments(
&ram,
&root,
Some(Duration::from_secs(60)),
Duration::from_secs(5),
now,
)
.expect("merge");
let file_names: Vec<String> = merged
.iter()
.map(|segment| segment.file_name.clone())
.collect();
// Sorted oldest-first: ram-only (6s old) before the just-written disk.mp4.
assert_eq!(file_names, vec!["ram-only.mp4", "disk.mp4"]);
// The disk file wins over the identical RAM copy.
let disk_merge = &merged[1];
assert!(disk_merge.on_disk.is_some());
assert_eq!(
disk_merge.on_disk.as_ref().unwrap().file_name().unwrap().to_str(),
Some("disk.mp4")
);
assert!(disk_merge.modified_at >= disk_modified_at);
let spool = root.join("staging");
let paths = spool_merged(&spool, "clip", &merged).expect("spool");
assert_eq!(paths.len(), 2);
let _ = fs::remove_dir_all(root);
}
}
+7
View File
@@ -47,7 +47,10 @@ pub struct AutoClipSettings {
pub pre_roll: Duration,
pub post_roll: Duration,
pub merge_window: Duration,
#[serde(default)]
pub enabled_events_by_game: BTreeMap<String, BTreeSet<String>>,
#[serde(default)]
pub disabled_games: BTreeSet<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -95,6 +98,8 @@ pub struct AppSettings {
pub onboarding_complete: bool,
#[serde(default)]
pub minimize_to_tray_enabled: bool,
#[serde(default)]
pub auto_prune_old_clips: bool,
}
impl AppSettings {
@@ -138,11 +143,13 @@ impl AppSettings {
post_roll: Duration::from_secs(8),
merge_window: Duration::from_secs(12),
enabled_events_by_game: BTreeMap::new(),
disabled_games: BTreeSet::new(),
},
upload: UploadSettings::default(),
quality_overrides_by_game: BTreeMap::new(),
onboarding_complete: false,
minimize_to_tray_enabled: false,
auto_prune_old_clips: false,
}
}
+12
View File
@@ -23,6 +23,18 @@ impl LibraryPaths {
}
}
/// Builds paths while honoring a user-selected clip directory. Thumbs,
/// sessions, and the rolling buffer stay under the library root.
pub fn with_clip_root(root: impl Into<PathBuf>, clip_root: impl Into<PathBuf>) -> Self {
let root = root.into();
Self {
clip_root: clip_root.into(),
thumbs_root: root.join("thumbs"),
sessions_root: root.join("sessions"),
buffer_root: root.join("buffer"),
}
}
pub fn ensure(&self) -> io::Result<()> {
fs::create_dir_all(&self.clip_root)?;
fs::create_dir_all(&self.thumbs_root)?;
+85 -4
View File
@@ -112,10 +112,20 @@ pub fn build_update_check(
release: &GitHubRelease,
) -> Result<UpdateCheck, UpdateCheckError> {
let latest_version = normalize_version(&release.tag_name);
let update_available = compare_versions(current_version, &latest_version) == Ordering::Less;
let newer_release_exists = compare_versions(current_version, &latest_version) == Ordering::Less;
let installer = select_installer_asset(&release.assets);
let message = if update_available {
// A newer tag without a published installer is not something the user can
// download, so never claim the app is installable in that state.
let update_available = newer_release_exists && installer.is_some();
let message = if !newer_release_exists {
"You are on the latest version.".to_string()
} else if installer.is_none() {
format!(
"A newer version ({latest_version}) exists, but no installer has been published for it yet."
)
} else {
let file = installer
.as_ref()
.map(|asset| asset.name.as_str())
@@ -123,8 +133,6 @@ pub fn build_update_check(
format!(
"A newer version ({latest_version}) is available — {file}, ready to download."
)
} else {
"You are on the latest version.".to_string()
};
Ok(UpdateCheck {
@@ -217,6 +225,79 @@ mod tests {
assert_eq!(compare_versions("0.3.0", "0.3.0"), Ordering::Equal);
}
#[test]
fn installed_040_detects_published_050_as_available_update() {
let release = GitHubRelease {
tag_name: "v0.0.5".to_string(),
published_at: Some("2026-09-08T00:00:00Z".to_string()),
body: None,
assets: vec![GitHubAsset {
name: "ClipForge_0.1.1_x64_en-US.msi".to_string(),
size: Some(1_000_000),
browser_download_url: "https://example.test/ClipForge_0.1.1.msi".to_string(),
}],
};
let check = build_update_check("0.0.4", &release).expect("check");
assert!(check.update_available, "v0.0.4 must see v0.0.5 as an update");
assert_eq!(check.latest_version, "0.0.5");
assert_eq!(
check.installer_file.as_deref(),
Some("ClipForge_0.1.1_x64_en-US.msi")
);
}
#[test]
fn same_version_is_reported_as_up_to_date() {
let release = GitHubRelease {
tag_name: "v0.1.1".to_string(),
published_at: None,
body: None,
assets: vec![GitHubAsset {
name: "ClipForge_0.1.1_x64-setup.exe".to_string(),
size: None,
browser_download_url: "https://example.test/setup.exe".to_string(),
}],
};
let check = build_update_check("0.1.1", &release).expect("check");
assert!(!check.update_available);
assert_eq!(check.message, "You are on the latest version.");
}
#[test]
fn newer_tag_without_installer_is_not_offered_for_download() {
let release = GitHubRelease {
tag_name: "v0.9.0".to_string(),
published_at: Some("2026-09-09T00:00:00Z".to_string()),
body: Some("notes".to_string()),
assets: vec![GitHubAsset {
name: "checksums.txt".to_string(),
size: Some(128),
browser_download_url: "https://example.test/checksums.txt".to_string(),
}],
};
let check = build_update_check("0.1.1", &release).expect("check");
assert!(!check.update_available);
assert!(check.download_url.is_none());
assert!(check.message.contains("no installer has been published"));
}
#[test]
fn patch_versions_compare_numerically_not_lexically() {
assert_eq!(compare_versions("0.0.9", "0.0.10"), Ordering::Less);
assert_eq!(compare_versions("0.0.10", "0.0.10"), Ordering::Equal);
assert_eq!(compare_versions("0.0.11", "0.0.10"), Ordering::Greater);
assert_eq!(compare_versions("0.1.0", "0.1.1"), Ordering::Less);
}
#[test]
fn older_tag_backports_do_not_mask_newer_release() {
assert_eq!(compare_versions("0.2.0", "0.1.1"), Ordering::Greater);
assert_eq!(compare_versions("0.1.1", "0.2.0"), Ordering::Less);
}
#[test]
fn leading_v_and_prerelease_tags_are_ignored() {
assert_eq!(compare_versions("v0.1.0", "v0.2.0"), Ordering::Less);
+454 -32
View File
@@ -70,6 +70,7 @@ type DesktopStatus = {
system_audio_available: boolean;
desktop_duplication_available: boolean;
auto_clip_enabled_events: AutoClipEventDto[];
auto_clip_disabled_games: string[];
hotkey_clip_last_60s: string;
hotkey_clip_last_30s: string;
hotkey_toggle_session_recording: string;
@@ -79,6 +80,9 @@ type DesktopStatus = {
capture_bitrate_kbps: number;
capture_resolution: string;
storage_limit_gb: number;
clip_directory: string;
storage_limit_exceeded: boolean;
auto_prune_old_clips: boolean;
excluded_window_titles: string[];
separate_audio_tracks: boolean;
game_quality_overrides: GameQualityOverrideDto[];
@@ -177,6 +181,7 @@ type AppState = {
screenshots: string[];
uploadHistory: UploadHistoryEntry[];
autoEvents: AutoEvent[];
disabledGames: string[];
hotkeyClipLast60s: string;
hotkeyClipLast30s: string;
hotkeyToggleRecording: string;
@@ -186,6 +191,9 @@ type AppState = {
captureBitrateKbps: number;
captureResolution: string;
storageLimitGb: number;
clipDirectory: string;
storageLimitExceeded: boolean;
autoPruneOldClips: boolean;
excludedWindowTitles: string[];
excludedWindowText: string;
separateAudioTracks: boolean;
@@ -196,12 +204,23 @@ type AppState = {
gameQualityOverrides: GameQualityOverrideDto[];
effectiveQualityApplied: boolean;
update: UpdateInfo;
modal: {
open: boolean;
kind: "clip" | "screenshot";
clipId: string;
screenshotPath: string;
videoFailed: boolean;
videoError: string;
};
};
type TauriGlobal = {
core?: {
invoke?: <T>(command: string, args?: Record<string, unknown>) => Promise<T>;
};
event?: {
listen?: <T>(eventName: string, handler: (event: { payload: T }) => void) => Promise<() => void>;
};
};
declare global {
@@ -267,6 +286,7 @@ const state: AppState = {
{ id: "dota-multi", gameId: "dota-2", eventType: "multi_kill", game: "Dota 2", event: "Multi-kill", enabled: true },
{ id: "dota-mvp", gameId: "dota-2", eventType: "mvp", game: "Dota 2", event: "MVP", enabled: true },
],
disabledGames: [],
hotkeyClipLast60s: "F8",
hotkeyClipLast30s: "Shift+F8",
hotkeyToggleRecording: "Alt+F7",
@@ -276,10 +296,21 @@ const state: AppState = {
captureBitrateKbps: 6000,
captureResolution: "1280x720",
storageLimitGb: 50,
clipDirectory: "",
storageLimitExceeded: false,
autoPruneOldClips: false,
excludedWindowTitles: [],
excludedWindowText: "",
separateAudioTracks: false,
appVersion: "0.1.0",
appVersion: "0.1.1",
modal: {
open: false,
kind: "clip",
clipId: "",
screenshotPath: "",
videoFailed: false,
videoError: "",
},
onboardingComplete: true,
minimizeToTray: false,
onboardingStep: 0,
@@ -336,10 +367,105 @@ function render() {
${renderActiveView(selectedClip)}
</section>
</main>
${renderModal()}
`;
bindEvents();
}
function openClipModal(clipId: string) {
state.selectedClipId = clipId;
state.modal.open = true;
state.modal.kind = "clip";
state.modal.clipId = clipId;
state.modal.videoFailed = false;
state.modal.videoError = "";
render();
}
function openScreenshotModal(path: string) {
state.modal.open = true;
state.modal.kind = "screenshot";
state.modal.screenshotPath = path;
state.modal.videoFailed = false;
state.modal.videoError = "";
render();
}
function closeModal() {
state.modal.open = false;
render();
}
function renderModal() {
if (!state.modal.open) {
return "";
}
if (state.modal.kind === "screenshot") {
const path = state.modal.screenshotPath;
return `
<div class="modal-overlay" data-action="modal-backdrop">
<div class="modal" role="dialog" aria-modal="true" aria-label="Screenshot preview">
<div class="modal-header">
<h2>Screenshot preview</h2>
<button class="modal-close" data-action="modal-close" aria-label="Close">&times;</button>
</div>
<div class="modal-body">
<img src="${convertFileSrc(path)}" alt="Screenshot preview" />
<p class="muted file-path">${escapeHtml(path)}</p>
<div class="actions">
<button data-action="reveal-screenshot" data-screenshot-path="${escapeHtml(path)}">Open in Explorer</button>
</div>
</div>
</div>
</div>
`;
}
const clip = state.clips.find((candidate) => candidate.id === state.modal.clipId);
if (!clip) {
return "";
}
const durationDisplay = formatDuration(parseTimestamp(clip.duration));
const canPlay = Boolean(clip.videoUrl) && !state.modal.videoFailed;
return `
<div class="modal-overlay" data-action="modal-backdrop">
<div class="modal" role="dialog" aria-modal="true" aria-label="Clip preview">
<div class="modal-header">
<h2>${escapeHtml(clip.title)}</h2>
<button class="modal-close" data-action="modal-close" aria-label="Close">&times;</button>
</div>
<div class="modal-body">
${
canPlay
? `<video controls preload="metadata" autoplay src="${clip.videoUrl}" poster="${clip.thumbnailUrl ?? ""}" id="modal-video"></video>`
: `
<div class="video-error">
<h3>Preview could not load</h3>
<p class="muted">${escapeHtml(state.modal.videoError || "No preview is available for this clip.")}</p>
<p class="muted file-path">${escapeHtml(clip.path || "No file path on record.")}</p>
<div class="actions">
<button data-action="modal-reveal">Reveal in Explorer</button>
<button data-action="modal-retry">Try loading again</button>
</div>
</div>
`
}
<p class="muted">${escapeHtml(clip.game)} · ${escapeHtml(clip.event)} · ${escapeHtml(clip.createdAt)} · ${escapeHtml(clip.uploadState)}</p>
<label>Trim start <input value="00:00" data-action="modal-trim-start" /></label>
<label>Trim end <input value="${escapeHtml(durationDisplay)}" data-action="modal-trim-end" /></label>
<div class="actions">
<button data-action="modal-trim">Trim</button>
<button data-action="modal-upload">Upload</button>
<button data-action="modal-reveal">Reveal</button>
<button data-action="modal-delete">Delete</button>
</div>
</div>
</div>
</div>
`;
}
function renderOnboardingWizard() {
const step = state.onboardingStep;
const steps = ["Privacy", "Capture source", "Storage", "Hotkeys"];
@@ -543,6 +669,7 @@ function renderScreenshotCard(path: string) {
<h3>${escapeHtml(filename)}</h3>
<p class="muted">${escapeHtml(path)}</p>
<div class="actions">
<button data-action="open-modal-screenshot" data-screenshot-path="${escapeHtml(path)}">Preview</button>
<button data-action="reveal-screenshot" data-screenshot-path="${escapeHtml(path)}">Open</button>
</div>
</article>
@@ -576,6 +703,9 @@ function renderClipCard(clip: Clip) {
</div>
<h3>${escapeHtml(clip.title)}</h3>
<p>${escapeHtml(clip.game)} · ${escapeHtml(clip.source)} · ${escapeHtml(clip.duration)}</p>
<div class="actions">
<button data-action="open-modal-clip" data-clip-id="${clip.id}">Preview</button>
</div>
</article>
`;
}
@@ -719,6 +849,12 @@ function renderRecordingView() {
}
function renderAutoClipView() {
const games: Array<{ gameId: string; game: string }> = [];
for (const event of state.autoEvents) {
if (!games.some((game) => game.gameId === event.gameId)) {
games.push({ gameId: event.gameId, game: event.game });
}
}
return `
<section class="table-panel">
<div class="section-heading">
@@ -728,18 +864,40 @@ function renderAutoClipView() {
</div>
<div class="status-pill">Local APIs only</div>
</div>
<div class="event-list">
${state.autoEvents
.map(
(event) => `
<label class="event-row">
<span><strong>${escapeHtml(event.game)}</strong><small>${escapeHtml(event.event)}</small></span>
<input type="checkbox" ${event.enabled ? "checked" : ""} data-event-id="${event.id}" />
</label>
`,
)
.join("")}
<div class="actions auto-clip-global-actions">
<button data-action="auto-clip-enable-all">Enable all games</button>
<button data-action="auto-clip-disable-all">Disable all games</button>
<button data-action="auto-clip-restore">Restore defaults</button>
</div>
${games
.map((game) => {
const gameEvents = state.autoEvents.filter((event) => event.gameId === game.gameId);
const gameEnabled = !state.disabledGames.includes(game.gameId);
return `
<section class="auto-clip-group ${gameEnabled ? "" : "disabled"}">
<div class="auto-clip-group-head">
<label class="toggle">
<input type="checkbox" ${gameEnabled ? "checked" : ""} data-game-id="${escapeHtml(game.gameId)}" data-action="toggle-game-clips" />
<strong>${escapeHtml(game.game)}</strong>
</label>
<span class="status-pill">${gameEnabled ? "Clipping enabled" : "Clipping disabled"}</span>
</div>
<div class="event-list">
${gameEvents
.map(
(event) => `
<label class="event-row">
<span><strong>${escapeHtml(event.event)}</strong></span>
<input type="checkbox" ${event.enabled ? "checked" : ""} data-event-id="${event.id}" ${gameEnabled ? "" : "disabled"} />
</label>
`,
)
.join("")}
</div>
</section>
`;
})
.join("")}
<div class="actions">
<button data-action="write-gsi-configs">Write GSI Configs</button>
</div>
@@ -858,7 +1016,17 @@ function renderSettingsView() {
</select>
</label>
</div>
<label>Video bitrate (kbps) <input type="number" min="500" max="50000" step="500" value="${state.captureBitrateKbps}" data-action="capture-bitrate" /></label>
<label>Video bitrate preset
<select data-action="capture-bitrate-preset" aria-label="Bitrate preset">
<option value="2500" ${state.captureBitrateKbps <= 3500 ? "selected" : ""}>Low (2500)</option>
<option value="4500" ${state.captureBitrateKbps > 3500 && state.captureBitrateKbps <= 5500 ? "selected" : ""}>Medium (4500)</option>
<option value="6000" ${state.captureBitrateKbps > 5500 && state.captureBitrateKbps <= 8000 ? "selected" : ""}>Stream-ready (6000)</option>
<option value="10000" ${state.captureBitrateKbps > 8000 && state.captureBitrateKbps <= 12000 ? "selected" : ""}>High (10000)</option>
<option value="14000" ${state.captureBitrateKbps > 12000 ? "selected" : ""}>Ultra (14000)</option>
<option value="custom" ${state.captureBitrateKbps < 2500 || state.captureBitrateKbps > 14000 ? "selected" : ""}>Custom…</option>
</select>
</label>
<label>Custom bitrate (kbps) <input type="number" min="500" max="50000" step="500" value="${state.captureBitrateKbps}" data-action="capture-bitrate" /></label>
<label>Buffer storage cap (GB) <input type="number" min="5" max="5000" step="1" value="${state.storageLimitGb}" data-action="capture-storage-gb" /></label>
<label>Excluded window titles
<textarea rows="2" placeholder="comma separated, e.g. Brave, Discord - Settings" data-action="excluded-windows">${escapeHtml(state.excludedWindowText)}</textarea>
@@ -868,8 +1036,15 @@ function renderSettingsView() {
</article>
<article class="settings-panel">
<p class="eyebrow">Storage</p>
<h2>${state.storageLimitGb} GB buffer cap</h2>
<p class="muted">Old temporary buffer segments are removed automatically once the buffer reaches the cap; saved clips are kept.</p>
<h2>Clips & replay buffer</h2>
<label>Clip folder
<input value="${escapeHtml(state.clipDirectory)}" data-action="clip-directory" spellcheck="false" placeholder="C:\\Users\\You\\Videos\\Clips" />
</label>
<button data-action="change-clip-dir">Apply Clip Folder</button>
${state.storageLimitExceeded ? `<p class="warn">The saved library is currently above the ${state.storageLimitGb} GB limit.</p>` : ""}
<label class="toggle"><input type="checkbox" ${state.autoPruneOldClips ? "checked" : ""} data-action="toggle-auto-prune" /> Auto-delete oldest clips when the library exceeds the ${state.storageLimitGb} GB limit</label>
<p class="muted">${state.autoPruneOldClips ? "When the limit is exceeded, the oldest automatic/event/session clips are deleted (oldest first) until you are back under it. Clips you saved manually are never auto-deleted." : "Up to the limit, the rolling replay buffer is always pruned automatically to keep it from growing. Saved clips are kept. Enable auto-cleanup above to also trim oldest clips when the limit is exceeded."}</p>
<p class="muted">This limit is set in Capture Settings (buffer storage cap).</p>
</article>
<article class="settings-panel">
<p class="eyebrow">Tray</p>
@@ -883,9 +1058,8 @@ function renderSettingsView() {
<p class="muted">${escapeHtml(state.update.message)}</p>
${state.update.updateAvailable ? `
<button data-action="download-update" ${state.update.applying ? "disabled" : ""}>Download & install v${escapeHtml(state.update.latestVersion)}</button>
` : `
<button data-action="check-updates" ${state.update.applying ? "disabled" : ""}>Check for updates</button>
`}
` : ""}
<button data-action="check-updates" ${state.update.applying ? "disabled" : ""}>${state.update.checked ? "Check for updates again" : "Check for updates"}</button>
<button data-action="reveal-crash-logs">Reveal Crash Logs</button>
</article>
<article class="settings-panel">
@@ -1068,6 +1242,30 @@ function bindEvents() {
});
});
appRoot.querySelectorAll<HTMLInputElement>("[data-action='toggle-game-clips']").forEach((input) => {
input.addEventListener("change", () => {
const gameId = input.dataset.gameId;
if (gameId) {
state.disabledGames = input.checked
? state.disabledGames.filter((game) => game !== gameId)
: [...state.disabledGames, gameId];
void invokeSetGameAutoClipEnabled(gameId, input.checked);
}
});
});
appRoot.querySelector<HTMLButtonElement>("[data-action='auto-clip-enable-all']")?.addEventListener("click", () => {
void invokeAutoClipBulk("enable_all_auto_clips");
});
appRoot.querySelector<HTMLButtonElement>("[data-action='auto-clip-disable-all']")?.addEventListener("click", () => {
void invokeAutoClipBulk("disable_all_auto_clips");
});
appRoot.querySelector<HTMLButtonElement>("[data-action='auto-clip-restore']")?.addEventListener("click", () => {
void invokeAutoClipBulk("restore_default_auto_clips");
});
appRoot.querySelector<HTMLInputElement>("[data-action='hotkey-clip-60s']")?.addEventListener("change", (event) => {
state.hotkeyClipLast60s = (event.target as HTMLInputElement).value;
});
@@ -1093,7 +1291,19 @@ function bindEvents() {
});
appRoot.querySelector<HTMLInputElement>("[data-action='capture-bitrate']")?.addEventListener("input", (event) => {
state.captureBitrateKbps = Number((event.target as HTMLInputElement).value);
state.captureBitrateKbps = Number((event.target as HTMLInputElement).value);
});
appRoot.querySelector<HTMLSelectElement>("[data-action='capture-bitrate-preset']")?.addEventListener("change", (event) => {
const preset = (event.target as HTMLSelectElement).value;
if (preset !== "custom") {
const value = Number(preset);
state.captureBitrateKbps = value;
const input = appRoot.querySelector<HTMLInputElement>("[data-action='capture-bitrate']");
if (input) {
input.value = String(value);
}
}
});
appRoot.querySelector<HTMLInputElement>("[data-action='capture-storage-gb']")?.addEventListener("input", (event) => {
@@ -1116,6 +1326,18 @@ function bindEvents() {
void checkForUpdates();
});
appRoot.querySelector<HTMLInputElement>("[data-action='clip-directory']")?.addEventListener("input", (event) => {
state.clipDirectory = (event.target as HTMLInputElement).value;
});
appRoot.querySelector<HTMLButtonElement>("[data-action='change-clip-dir']")?.addEventListener("click", () => {
void changeClipDirectory();
});
appRoot.querySelector<HTMLInputElement>("[data-action='toggle-auto-prune']")?.addEventListener("change", (event) => {
void setAutoPruneEnabled((event.target as HTMLInputElement).checked);
});
appRoot.querySelector<HTMLButtonElement>("[data-action='save-override']")?.addEventListener("click", () => {
void saveGameQualityOverride();
});
@@ -1150,6 +1372,63 @@ function bindEvents() {
void revealCrashLogs();
});
appRoot.querySelectorAll<HTMLButtonElement>("[data-action='open-modal-clip']").forEach((button) => {
button.addEventListener("click", () => {
const clipId = button.dataset.clipId;
if (clipId) {
openClipModal(clipId);
}
});
});
appRoot.querySelectorAll<HTMLButtonElement>("[data-action='open-modal-screenshot']").forEach((button) => {
button.addEventListener("click", () => {
const path = button.dataset.screenshotPath;
if (path) {
openScreenshotModal(path);
}
});
});
appRoot.querySelector<HTMLButtonElement>("[data-action='modal-close']")?.addEventListener("click", closeModal);
appRoot.querySelector<HTMLElement>("[data-action='modal-backdrop']")?.addEventListener("click", (event) => {
if (event.target === event.currentTarget) {
closeModal();
}
});
appRoot.querySelector<HTMLButtonElement>("[data-action='modal-trim']")?.addEventListener("click", () => {
void trimClipFromModal();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='modal-upload']")?.addEventListener("click", () => {
state.selectedClipId = state.modal.clipId;
void uploadSelectedClip();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='modal-reveal']")?.addEventListener("click", () => {
state.selectedClipId = state.modal.clipId;
void revealSelectedClip();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='modal-delete']")?.addEventListener("click", () => {
state.selectedClipId = state.modal.clipId;
void deleteSelectedClip();
});
appRoot.querySelector<HTMLButtonElement>("[data-action='modal-retry']")?.addEventListener("click", () => {
state.modal.videoFailed = false;
state.modal.videoError = "";
render();
});
appRoot.querySelector<HTMLVideoElement>("#modal-video")?.addEventListener("error", () => {
state.modal.videoFailed = true;
state.modal.videoError = "The clip file could not be loaded as a preview. It may have been moved or deleted, or the media table of contents is unreadable.";
render();
});
appRoot.querySelectorAll<HTMLButtonElement>("[data-action='reveal-screenshot']").forEach((button) => {
button.addEventListener("click", () => {
const path = button.dataset.screenshotPath;
@@ -1373,17 +1652,27 @@ async function saveClip() {
}
async function toggleRecording() {
const wasActive = state.captureActive;
// Optimistically flip the button so the UI reacts instantly; the real status
// returned by the backend reconciles it (or it is rolled back on error).
state.captureActive = !wasActive;
state.recordingState = state.captureActive ? "RecordingSession" : "Buffering";
render();
if (tauriInvoke) {
try {
const status = await tauriInvoke<DesktopStatus>(state.captureActive ? "stop_capture" : "start_capture");
const status = await tauriInvoke<DesktopStatus>(wasActive ? "stop_capture" : "start_capture");
applyDesktopStatus(status);
await refreshClips();
showNotice(state.captureActive ? "Recording started" : "Recording stopped");
render();
return;
} catch (error) {
state.captureActive = wasActive;
state.recordingState = wasActive ? "RecordingSession" : "Buffering";
console.error("Could not toggle desktop recording", error);
showNotice(`Could not toggle recording: ${String(error)}`);
render();
}
}
@@ -1415,6 +1704,7 @@ function applyDesktopStatus(status: DesktopStatus) {
state.ffmpegPath = status.ffmpeg_path;
state.systemAudioAvailable = status.system_audio_available;
state.desktopDuplicationAvailable = status.desktop_duplication_available;
state.disabledGames = status.auto_clip_disabled_games ?? [];
for (const event of state.autoEvents) {
const enabled = status.auto_clip_enabled_events.find(
(candidate) => candidate.game_id === event.gameId && candidate.event_type === event.eventType,
@@ -1432,6 +1722,11 @@ function applyDesktopStatus(status: DesktopStatus) {
state.captureBitrateKbps = status.capture_bitrate_kbps;
state.captureResolution = status.capture_resolution;
state.storageLimitGb = status.storage_limit_gb;
state.clipDirectory = status.clip_directory ?? state.clipDirectory;
state.storageLimitExceeded = status.storage_limit_exceeded ?? false;
if (typeof status.auto_prune_old_clips === "boolean") {
state.autoPruneOldClips = status.auto_prune_old_clips;
}
state.excludedWindowTitles = status.excluded_window_titles ?? [];
state.excludedWindowText = (status.excluded_window_titles ?? []).join(", ");
state.separateAudioTracks = status.separate_audio_tracks ?? false;
@@ -1479,6 +1774,39 @@ async function trimSelectedClip() {
}
}
async function trimClipFromModal() {
if (!tauriInvoke) {
return;
}
const clip = state.clips.find((candidate) => candidate.id === state.modal.clipId);
if (!clip) {
return;
}
const startInput = appRoot.querySelector<HTMLInputElement>("[data-action='modal-trim-start']");
const endInput = appRoot.querySelector<HTMLInputElement>("[data-action='modal-trim-end']");
const startSeconds = parseTimestamp(startInput?.value ?? "0");
const endSeconds = parseTimestamp(endInput?.value ?? clip.duration);
try {
const dto = await tauriInvoke<ClipDto>("trim_clip", {
clipId: clip.id,
startSeconds,
endSeconds,
});
const trimmed = clipFromDto(dto);
state.clips.unshift(trimmed);
state.selectedClipId = trimmed.id;
await refreshClips();
showNotice("Trimmed clip created");
closeModal();
} catch (error) {
console.error("Could not trim clip", error);
showNotice(`Could not trim clip: ${String(error)}`);
}
}
async function saveSelectedClipMetadata() {
if (!tauriInvoke || !state.selectedClipId) {
return;
@@ -1731,23 +2059,36 @@ async function refreshAudioDevices() {
}
}
async function pollAutoClips() {
if (!tauriInvoke || !state.captureActive || !state.onboardingComplete) {
async function onClipSaved() {
if (!tauriInvoke || !state.onboardingComplete) {
return;
}
try {
const clips = await tauriInvoke<ClipDto[]>("poll_auto_clip_events");
if (clips.length === 0) {
return;
await refreshClips();
const newest = state.clips[0];
if (newest) {
state.selectedClipId = newest.id;
state.activeView = "Library";
render();
} else {
render();
}
const created = clips.map(clipFromDto);
state.clips = [...created, ...state.clips.filter((clip) => !created.some((fresh) => fresh.id === clip.id))];
state.selectedClipId = created[0].id;
state.activeView = "Library";
} catch (error) {
console.warn("Could not refresh clips after save event", error);
}
}
async function onClipDeleted() {
if (!tauriInvoke) {
return;
}
try {
await refreshClips();
render();
} catch (error) {
console.warn("Could not poll auto clips", error);
console.warn("Could not refresh clips after delete event", error);
}
}
@@ -1798,6 +2139,36 @@ async function saveAutoClipEventSetting(eventRule: AutoEvent) {
}
}
async function invokeSetGameAutoClipEnabled(gameId: string, enabled: boolean) {
if (!tauriInvoke) {
return;
}
try {
const status = await tauriInvoke<DesktopStatus>("set_game_auto_clip_enabled", { gameId, enabled });
applyDesktopStatus(status);
showNotice(enabled ? "Auto-clipping enabled for game" : "Auto-clipping disabled for game");
render();
} catch (error) {
console.warn("Could not update per-game auto-clip setting", error);
showNotice(`Could not update per-game auto-clip setting: ${String(error)}`);
}
}
async function invokeAutoClipBulk(command: "enable_all_auto_clips" | "disable_all_auto_clips" | "restore_default_auto_clips") {
if (!tauriInvoke) {
return;
}
try {
const status = await tauriInvoke<DesktopStatus>(command);
applyDesktopStatus(status);
showNotice("Auto-clip rules updated");
render();
} catch (error) {
console.warn("Could not update auto-clip rules", error);
showNotice(`Could not update auto-clip rules: ${String(error)}`);
}
}
async function saveHotkeys() {
if (!tauriInvoke) {
return;
@@ -1849,6 +2220,37 @@ async function saveCaptureSettings() {
}
}
async function changeClipDirectory() {
if (!tauriInvoke) {
return;
}
try {
const status = await tauriInvoke<DesktopStatus>("set_clip_directory", {
clipDir: state.clipDirectory.trim(),
});
applyDesktopStatus(status);
showNotice("Clip folder applied.");
render();
} catch (error) {
console.warn("Could not set clip folder", error);
showNotice(`Could not set clip folder: ${String(error)}`);
}
}
async function setAutoPruneEnabled(enabled: boolean) {
if (!tauriInvoke) {
return;
}
try {
const status = await tauriInvoke<DesktopStatus>("set_auto_prune_enabled", { enabled });
applyDesktopStatus(status);
render();
} catch (error) {
console.warn("Could not update auto-cleanup setting", error);
showNotice(`Could not update auto-cleanup setting: ${String(error)}`);
}
}
function parseResolution(value: string): [number, number] {
const [width, height] = value.split("x").map((part) => Number(part));
return [
@@ -2175,9 +2577,29 @@ async function loadDesktopBridge() {
window.setInterval(() => {
void refreshStatus();
}, 3_000);
// Hotkey screenshots are taken behind Tauri's back, so keep a light poll to
// pick up new ones; clip/library changes arrive via backend events instead.
window.setInterval(() => {
void pollAutoClips();
}, 2_000);
void refreshScreenshots();
}, 5_000);
const listen = window.__TAURI__?.event?.listen;
if (listen) {
void listen("clip-saved", () => {
void onClipSaved();
});
void listen("clip-deleted", () => {
void onClipDeleted();
});
void listen("screenshots-changed", () => {
void refreshScreenshots();
});
}
window.addEventListener("keydown", (event) => {
if (event.key === "Escape" && state.modal.open) {
closeModal();
}
});
} catch (error) {
console.warn("Tauri bridge unavailable", error);
}
+143 -1
View File
@@ -280,6 +280,14 @@ h3 {
color: #9ba7b8;
}
.settings-panel .warn {
color: #e6b116;
background: rgba(230, 177, 22, 0.08);
border-left: 3px solid #e6b116;
padding: 8px 10px;
border-radius: 4px;
}
.file-path {
overflow-wrap: anywhere;
}
@@ -471,7 +479,44 @@ textarea {
.event-list {
display: grid;
gap: 8px;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 10px;
}
.auto-clip-group {
margin-top: 18px;
padding: 14px;
border: 1px solid #2c3140;
border-radius: 10px;
background: #12161d;
}
.auto-clip-group.disabled {
opacity: 0.55;
}
.auto-clip-group-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.auto-clip-group-head .toggle {
display: flex;
align-items: center;
gap: 10px;
margin: 0;
font-size: 15px;
}
.auto-clip-group .event-list {
margin-top: 0;
}
.auto-clip-global-actions {
margin-top: 14px;
}
.event-row {
@@ -680,3 +725,100 @@ textarea {
font-size: 12px;
color: #f5f7fb;
}
.modal-overlay {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
background: rgba(10, 12, 16, 0.75);
padding: 24px;
}
.modal {
width: min(880px, 100%);
max-height: 92vh;
overflow-y: auto;
background: #191d26;
border: 1px solid #2c3442;
border-radius: 12px;
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.5);
}
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 14px 18px;
border-bottom: 1px solid #2c3442;
position: sticky;
top: 0;
background: #191d26;
}
.modal-header h2 {
margin: 0;
font-size: 16px;
overflow-wrap: anywhere;
}
.modal-close {
background: #2c3442;
border: 1px solid #3a4556;
border-radius: 8px;
color: #e7edfb;
font-size: 18px;
line-height: 1;
padding: 6px 12px;
cursor: pointer;
flex: none;
}
.modal-close:hover {
background: #38445a;
}
.modal-body {
padding: 18px;
display: grid;
gap: 14px;
}
.modal-body video {
width: 100%;
max-height: 56vh;
background: #000;
border-radius: 8px;
}
.modal-body img {
max-width: 100%;
max-height: 56vh;
border-radius: 8px;
}
.modal-body label,
.modal-body input {
margin: 0;
}
.video-error {
border: 1px dashed rgba(231, 237, 251, 0.25);
border-radius: 8px;
padding: 18px;
background: #141821;
display: grid;
gap: 10px;
}
.video-error h3 {
margin: 0;
color: #f87171;
font-size: 14px;
}
.video-error-detail {
color: #9ba7b8;
}