diff --git a/docs/implementation-status.md b/docs/implementation-status.md index 2d8d1e6..ac53cb1 100644 --- a/docs/implementation-status.md +++ b/docs/implementation-status.md @@ -42,9 +42,13 @@ - Panic reporting writes crash reports with stack traces to the logs folder (`library/logs`), prunes old entries, and the Settings screen can open the logs folder. - Native Windows Graphics Capture now downscales the captured window/monitor to the configured resolution cap (e.g. 720p) with even dimensions while preserving aspect ratio; covered by unit tests. - Capture quality and storage settings are exposed: the Settings screen can change resolution, FPS, bitrate, buffer storage cap, excluded window titles, and the separate-audio-tracks toggle via the `set_capture_settings` command, and current values are shown in DesktopStatus. +- Per-game capture quality overrides can be set from the Recording screen per detected game title, saved in settings, and applied automatically by the recorder when that game is active. - The configured storage cap is enforced by a backend worker that prunes the oldest rolling buffer segments once the buffer exceeds `storage_limit_gb`. - SQLite schema uses versioned migrations tracked via `PRAGMA user_version`; legacy databases (missing tables or the `title` column) are repaired and upgraded in place, with migration tests. +- Valve GSI event mapping enriches CS2 round, bomb, and match-start events with round number, map scores, and plant-region metadata; these events are unit tested against realistic JSON payloads. +- A GitHub Actions release workflow (`.github/workflows/release.yml`) builds MSI and NSIS installers on tag push or manual dispatch and publishes them to a GitHub Release, ready for the auto-updater to pick up. - Auto-update checks the GitHub repo releases (`Alvin-Zilverstand/clipforge-game-clipper`) for the latest MSI/NSIS installer, compares it against the running version, downloads it to temp, launches the installer, and exits the app to finish; version comparison, asset selection, and parsing are unit tested plus one ignored live test against the GitHub API. +- A GitHub Actions release workflow publishes MSI/NSIS assets on tag push; auto-update will pick up newer releases automatically once the repo ships a tag newer than the running app version. - The Settings screen shows the current version, checks for updates, and offers a Download & install button when a newer release exists. - Vite TypeScript UI builds and has interactive Library, Recording, Auto Clip, Uploads, and Settings views. - Library search, event/upload filters, and grid/list switching are functional in the UI. @@ -54,9 +58,8 @@ - Native Windows Graphics Capture and FFmpeg capture finalization have not yet been manually QA-tested on real NVIDIA/AMD/Intel gaming systems. - Native WASAPI audio is mixed into a single AAC track for MVP clips; separate audio tracks and per-process audio capture are still future work (the separate-audio-tracks setting is stored but not yet honored by the encoder). -- Valve GSI receiver is a lightweight MVP receiver; config templates can be generated from the Auto Clip screen, but richer event mapping per game is still needed. +- Valve GSI receiver is a lightweight MVP receiver; config templates can be generated from the Auto Clip screen. CS2 event mapping is now enriched with round, bomb, and match-start metadata, but full per-game mapping for Dota 2 and other Source titles is still needed. - Auto start/stop is conservative but live: when auto-record is enabled, supported detected games can start recording and stop when the game disappears. -- Per-game capture quality overrides are still incomplete. - Recorder service still runs inside the Tauri process instead of a separate background service process. - Installer onboarding is still not implemented. - 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). @@ -64,8 +67,7 @@ ## Next Engineering Steps 1. Honor the separate-audio-tracks setting by encoding system and mic audio to distinct tracks, and consider per-process loopback capture. -2. Expand CS2/Dota GSI event mapping beyond the current MVP event parser. -3. Add per-game capture quality overrides. -4. Add installer/onboarding screens for privacy, capture source, storage, and hotkeys. -5. Automate building and publishing GitHub releases (e.g. a GitHub Action that runs Tauri + uploads MSI/NSIS assets) so the updater has fresh assets to install. -6. Run manual QA on Windows gaming hardware and tune CPU/GPU overhead. +2. Add full per-game Valve GSI event mapping for Dota 2 and other Source titles beyond the current CS2 enrichment. +3. Add installer/onboarding screens for privacy, capture source, storage, and hotkeys. +4. Exercise the GitHub Actions release workflow with a real tag push and verify the published assets appear in a GitHub Release. +5. Run manual QA on Windows gaming hardware and tune CPU/GPU overhead. diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index fae8a54..95ffa79 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -129,9 +129,21 @@ struct DesktopStatus { storage_limit_gb: u64, excluded_window_titles: Vec, separate_audio_tracks: bool, + game_quality_overrides: Vec, + effective_quality_applied: bool, app_version: String, } +#[derive(Debug, Clone, Serialize)] +struct GameQualityOverrideDto { + game_id: String, + name: String, + width: u32, + height: u32, + fps: u32, + bitrate_kbps: u32, +} + #[derive(Debug, Serialize)] struct ClipDto { id: String, @@ -663,6 +675,11 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result { } recorder.toggle_session_recording(); + let game_id = recorder.state.detected_game_id.clone().unwrap_or_default(); + let quality = recorder + .settings + .effective_quality_for(&game_id) + .clone(); let session_id = recorder .state .active_session_id @@ -698,10 +715,10 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result { let config = CaptureConfig { source, method, - width: recorder.settings.quality.width, - height: recorder.settings.quality.height, - fps: recorder.settings.quality.fps, - bitrate_kbps: recorder.settings.quality.bitrate_kbps, + width: quality.width, + height: quality.height, + fps: quality.fps, + bitrate_kbps: quality.bitrate_kbps, encoder: EncoderPreference::HardwareH264, system_audio_enabled, mic_enabled: recorder.settings.privacy.mic_enabled, @@ -1573,6 +1590,8 @@ fn main() { reveal_screenshot, reveal_crash_logs, list_crash_logs, + set_game_quality_override, + clear_game_quality_override, check_for_updates, download_and_apply_update, set_hotkeys @@ -1778,6 +1797,8 @@ fn enforce_storage_cap(runtime: &AppRuntime) -> Result<(), String> { } fn status_from_recorder(recorder: &RecorderService, capture: Option<&ActiveCapture>) -> DesktopStatus { + let game_id = recorder.state.detected_game_id.clone().unwrap_or_default(); + let quality = recorder.settings.effective_quality_for(&game_id).clone(); DesktopStatus { recording_state: recording_status_name(&recorder.state.status).to_string(), detected_game: recorder.state.detected_game_id.clone(), @@ -1820,19 +1841,82 @@ fn status_from_recorder(recorder: &RecorderService, capture: Option<&ActiveCaptu 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(), - capture_fps: recorder.settings.quality.fps, - capture_bitrate_kbps: recorder.settings.quality.bitrate_kbps, - capture_resolution: format!( - "{}x{}", - recorder.settings.quality.width, recorder.settings.quality.height - ), + 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, 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), + effective_quality_applied: game_override_is_active(&recorder.settings, &game_id), app_version: env!("CARGO_PKG_VERSION").to_string(), } } +fn quality_override_dtos(settings: &AppSettings) -> Vec { + settings + .quality_overrides_by_game + .iter() + .map(|(game_id, preset)| GameQualityOverrideDto { + game_id: game_id.clone(), + name: preset.name.clone(), + width: preset.width, + height: preset.height, + fps: preset.fps, + bitrate_kbps: preset.bitrate_kbps, + }) + .collect() +} + +fn game_override_is_active(settings: &AppSettings, game_id: &str) -> bool { + settings.quality_overrides_by_game.contains_key(game_id) +} + +#[tauri::command] +fn set_game_quality_override( + game_id: String, + name: String, + width: u32, + height: u32, + fps: u32, + bitrate_kbps: u32, + runtime: State<'_, AppRuntime>, +) -> Result { + let mut recorder = runtime.recorder.lock().map_err(|error| error.to_string())?; + let capture = runtime.capture.lock().map_err(|error| error.to_string())?; + let preset = clipforge::settings::QualityPreset { + name: if name.trim().is_empty() { + "Custom".to_string() + } else { + name.trim().to_string() + }, + width: even_between(width, 640, 7680), + height: even_between(height, 360, 4320), + fps: fps.clamp(15, 240), + bitrate_kbps: bitrate_kbps.clamp(500, 50_000), + }; + recorder + .settings + .quality_overrides_by_game + .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())) +} + +#[tauri::command] +fn clear_game_quality_override( + game_id: String, + runtime: State<'_, AppRuntime>, +) -> Result { + 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.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())) +} + fn clip_to_dto(clip: &Clip) -> ClipDto { ClipDto { id: clip.id.clone(), diff --git a/src/integrations.rs b/src/integrations.rs index 4628df5..ceb97a4 100644 --- a/src/integrations.rs +++ b/src/integrations.rs @@ -194,6 +194,10 @@ pub fn valve_gsi_raw_events( let mut events = Vec::new(); // Round events + let round_number = value + .pointer("/map/round") + .and_then(Value::as_u64) + .unwrap_or_default(); if let Some(round_phase) = value .pointer("/round/phase") .and_then(Value::as_str) @@ -206,7 +210,19 @@ pub fn valve_gsi_raw_events( name: "round_win".to_string(), timestamp: now, player: None, - metadata: [("win_team".to_string(), win_team.to_string())].into(), + metadata: [ + ("win_team".to_string(), win_team.to_string()), + ("round".to_string(), round_number.to_string()), + ( + "ct_score".to_string(), + map_stat_string(&value, "/map/team_ct/score"), + ), + ( + "t_score".to_string(), + map_stat_string(&value, "/map/team_t/score"), + ), + ] + .into(), }); } } @@ -216,11 +232,33 @@ pub fn valve_gsi_raw_events( name: "round_start".to_string(), timestamp: now, player: None, - metadata: BTreeMap::new(), + metadata: [("round".to_string(), round_number.to_string())].into(), }); } "live" => { - // Round is live, could track bomb events + // Round is live, could track bomb events. A fresh match is live on round 1. + if round_number == 1 { + events.push(RawGameEvent { + event_id: format!("match_start:{}", millis(now)), + name: "match_start".to_string(), + timestamp: now, + player: value + .pointer("/player/name") + .and_then(Value::as_str) + .map(ToString::to_string), + metadata: [ + ( + "map".to_string(), + map_stat_string(&value, "/map/name"), + ), + ( + "mode".to_string(), + map_stat_string(&value, "/map/mode"), + ), + ] + .into(), + }); + } } _ => {} } @@ -228,6 +266,15 @@ pub fn valve_gsi_raw_events( // Bomb events (CS2) if let Some(bomb_state) = value.pointer("/round/bomb").and_then(Value::as_str) { + let bomb_region = map_stat_string(&value, "/map/region"); + let bomb_metadata = |region: String| { + let mut metadata = BTreeMap::new(); + metadata.insert("round".to_string(), round_number.to_string()); + if !region.is_empty() { + metadata.insert("region".to_string(), region); + } + metadata + }; match bomb_state { "planted" => { events.push(RawGameEvent { @@ -238,7 +285,7 @@ pub fn valve_gsi_raw_events( .pointer("/player/name") .and_then(Value::as_str) .map(ToString::to_string), - metadata: BTreeMap::new(), + metadata: bomb_metadata(bomb_region), }); } "defused" => { @@ -250,7 +297,7 @@ pub fn valve_gsi_raw_events( .pointer("/player/name") .and_then(Value::as_str) .map(ToString::to_string), - metadata: BTreeMap::new(), + metadata: bomb_metadata(bomb_region), }); } "exploded" => { @@ -259,7 +306,7 @@ pub fn valve_gsi_raw_events( name: "bomb_exploded".to_string(), timestamp: now, player: None, - metadata: BTreeMap::new(), + metadata: bomb_metadata(bomb_region), }); } _ => {} @@ -432,6 +479,18 @@ fn millis(time: SystemTime) -> u128 { .as_millis() } +fn map_stat_string(value: &Value, pointer: &str) -> String { + match value.pointer(pointer) { + Some(inner) => inner + .as_str() + .map(ToString::to_string) + .or_else(|| inner.as_u64().map(|n| n.to_string())) + .or_else(|| inner.as_i64().map(|n| n.to_string())) + .unwrap_or_default(), + None => String::new(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -486,4 +545,84 @@ mod tests { assert_eq!(events[0].name, "triple_kill"); assert_eq!(events[0].player.as_deref(), Some("Alvin")); } + + #[test] + fn parses_valve_gsi_round_metadata_and_match_start() { + let body = r#"{ + "round": {"phase": "over", "win_team": "CT"}, + "map": { + "round": 5, + "phase": "live", + "name": "de_mirage", + "mode": "competitive", + "team_ct": {"score": 3}, + "team_t": {"score": 2} + } + }"#; + + let events = valve_gsi_raw_events(body, SystemTime::UNIX_EPOCH).expect("events"); + + let round_win = events + .iter() + .find(|event| event.name == "round_win") + .expect("round win event"); + assert_eq!(round_win.metadata.get("win_team").map(String::as_str), Some("CT")); + assert_eq!(round_win.metadata.get("round").map(String::as_str), Some("5")); + assert_eq!( + round_win.metadata.get("ct_score").map(String::as_str), + Some("3") + ); + assert_eq!( + round_win.metadata.get("t_score").map(String::as_str), + Some("2") + ); + assert!(!events.iter().any(|event| event.name == "match_start")); + } + + #[test] + fn parses_valve_gsi_match_start_on_fresh_live_round() { + let body = r#"{ + "round": {"phase": "live"}, + "map": {"round": 1, "phase": "live", "name": "de_inferno", "mode": "casual"}, + "player": {"name": "Alvin"} + }"#; + + let events = valve_gsi_raw_events(body, SystemTime::UNIX_EPOCH).expect("events"); + + let match_start = events + .iter() + .find(|event| event.name == "match_start") + .expect("match start event"); + assert_eq!(match_start.player.as_deref(), Some("Alvin")); + assert_eq!( + match_start.metadata.get("map").map(String::as_str), + Some("de_inferno") + ); + assert_eq!( + match_start.metadata.get("mode").map(String::as_str), + Some("casual") + ); + } + + #[test] + fn parses_valve_gsi_bomb_plant_region() { + let body = r#"{ + "round": {"phase": "live", "bomb": "planted"}, + "map": {"round": 2, "region": "b"}, + "player": {"name": "Alvin"} + }"#; + + let events = valve_gsi_raw_events(body, SystemTime::UNIX_EPOCH).expect("events"); + + let bomb = events + .iter() + .find(|event| event.name == "bomb_planted") + .expect("bomb planted event"); + assert_eq!(bomb.player.as_deref(), Some("Alvin")); + assert_eq!( + bomb.metadata.get("region").map(String::as_str), + Some("b") + ); + assert_eq!(bomb.metadata.get("round").map(String::as_str), Some("2")); + } } diff --git a/src/settings.rs b/src/settings.rs index 370103d..0b15704 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -89,6 +89,8 @@ pub struct AppSettings { pub auto_clip: AutoClipSettings, #[serde(default)] pub upload: UploadSettings, + #[serde(default)] + pub quality_overrides_by_game: BTreeMap, } impl AppSettings { @@ -134,9 +136,16 @@ impl AppSettings { enabled_events_by_game: BTreeMap::new(), }, upload: UploadSettings::default(), + quality_overrides_by_game: BTreeMap::new(), } } + pub fn effective_quality_for(&self, game_id: &str) -> &QualityPreset { + self.quality_overrides_by_game + .get(game_id) + .unwrap_or(&self.quality) + } + pub fn clamp_replay_buffer(&mut self) { self.replay_buffer = self .replay_buffer @@ -219,6 +228,36 @@ mod tests { let _ = fs::remove_dir_all(root); } + #[test] + fn quality_overrides_round_trip_and_apply_per_game() { + let root = std::env::temp_dir().join(format!( + "clipforge-settings-overrides-{}", + SystemTimeCompat::millis() + )); + let mut settings = AppSettings::default_for_root(&root); + settings.quality_overrides_by_game.insert( + "counter-strike-2".to_string(), + QualityPreset { + name: "Competitive 1080p60".to_string(), + width: 1920, + height: 1080, + fps: 60, + bitrate_kbps: 12_000, + }, + ); + + save_settings(&root, &settings).expect("save"); + let loaded = load_or_create_settings(&root).expect("load"); + + let override_quality = loaded + .effective_quality_for("counter-strike-2"); + assert_eq!(override_quality.width, 1920); + assert_eq!(override_quality.fps, 60); + assert_eq!(loaded.effective_quality_for("league-of-leagues").width, 1280); + assert!(loaded.quality_overrides_by_game.contains_key("counter-strike-2")); + let _ = fs::remove_dir_all(root); + } + #[test] fn legacy_settings_migrate_upload_defaults() { let root = std::env::temp_dir().join(format!( diff --git a/ui/src/main.ts b/ui/src/main.ts index a714632..cd6e121 100644 --- a/ui/src/main.ts +++ b/ui/src/main.ts @@ -81,6 +81,8 @@ type DesktopStatus = { storage_limit_gb: number; excluded_window_titles: string[]; separate_audio_tracks: boolean; + game_quality_overrides: GameQualityOverrideDto[]; + effective_quality_applied: boolean; app_version: string; }; @@ -129,6 +131,15 @@ type UpdateInfo = { applying: boolean; }; +type GameQualityOverrideDto = { + game_id: string; + name: string; + width: number; + height: number; + fps: number; + bitrate_kbps: number; +}; + type AppState = { activeView: "Library" | "Recording" | "Auto Clip" | "Uploads" | "Settings"; recordingState: RecordingState; @@ -177,6 +188,8 @@ type AppState = { excludedWindowText: string; separateAudioTracks: boolean; appVersion: string; + gameQualityOverrides: GameQualityOverrideDto[]; + effectiveQualityApplied: boolean; update: UpdateInfo; }; @@ -262,6 +275,8 @@ const state: AppState = { excludedWindowText: "", separateAudioTracks: false, appVersion: "0.1.0", + gameQualityOverrides: [], + effectiveQualityApplied: false, update: { checked: false, updateAvailable: false, @@ -522,6 +537,16 @@ function renderClipDetails(clip: Clip | undefined) { } function renderRecordingView() { + const override = state.gameQualityOverrides.find((candidate) => candidate.game_id === state.detectedGame) ?? null; + const baseResolution = state.captureResolution || "1280x720"; + const overrideResolution = override ? `${override.width}x${override.height}` : baseResolution; + const presetOptions = ["1280x720", "1920x1080", "2560x1440", "3840x2160"]; + const resolutionOptions = presetOptions.includes(overrideResolution) + ? presetOptions + : [overrideResolution, ...presetOptions]; + const fpsOptions = [30, 60, 120]; + const overrideFps = override?.fps ?? state.captureFps; + const overrideBitrate = override?.bitrate_kbps ?? state.captureBitrateKbps; return `
@@ -531,7 +556,8 @@ function renderRecordingView() {

Capture

-

720p30 Performance

+

${escapeHtml(state.captureResolution)} @ ${state.captureFps} fps

+

${state.effectiveQualityApplied ? `A quality override is active for ${escapeHtml(state.detectedGame)}.` : "Using the global quality settings."}

Lightweight desktop capture uses bundled FFmpeg when system FFmpeg is missing.

${state.desktopDuplicationAvailable ? "Desktop Duplication capture available" : "Using GDI capture fallback"}

${state.captureBackend ? `Active backend: ${state.captureBackend}` : "Active backend: idle"}

@@ -539,6 +565,30 @@ function renderRecordingView() {

${state.capturePath ? `Writing ${state.capturePath}` : "No active capture file"}

${state.freeDiskGb > 0 ? `${state.freeDiskGb.toFixed(1)} GB free on recording drive` : "Disk space unknown"}

+
+

Quality override

+

Per-game capture settings

+ ${state.detectedGame === "Waiting for game" ? ` +

Start a supported game and you can give it its own resolution, FPS, and bitrate here.

+ ` : ` +

Override quality for ${escapeHtml(state.detectedGame)}${override ? ` (currently ${override.width}x${override.height} @ ${override.fps} fps)` : ""}.

+
+ + +
+ + + + `} +

Audio

${state.systemAudioAvailable ? "System audio ready" : "System audio unavailable"}

@@ -948,6 +998,14 @@ function bindEvents() { void checkForUpdates(); }); + appRoot.querySelector("[data-action='save-override']")?.addEventListener("click", () => { + void saveGameQualityOverride(); + }); + + appRoot.querySelector("[data-action='clear-override']")?.addEventListener("click", () => { + void clearGameQualityOverride(); + }); + appRoot.querySelector("[data-action='download-update']")?.addEventListener("click", () => { void downloadUpdate(); }); @@ -1240,8 +1298,10 @@ function applyDesktopStatus(status: DesktopStatus) { state.storageLimitGb = status.storage_limit_gb; state.excludedWindowTitles = status.excluded_window_titles ?? []; state.excludedWindowText = (status.excluded_window_titles ?? []).join(", "); - state.separateAudioTracks = status.separate_audio_tracks ?? false; +state.separateAudioTracks = status.separate_audio_tracks ?? false; state.appVersion = status.app_version ?? state.appVersion; + state.gameQualityOverrides = status.game_quality_overrides ?? []; + state.effectiveQualityApplied = status.effective_quality_applied ?? false; } async function trimSelectedClip() { @@ -1641,6 +1701,59 @@ function parseResolution(value: string): [number, number] { ]; } +async function saveGameQualityOverride() { + if (!tauriInvoke) { + return; + } + if (state.detectedGame === "Waiting for game") { + return; + } + + const preset = + appRoot.querySelector("[data-action='override-preset']")?.value ?? "1280x720"; + const fps = Number(appRoot.querySelector("[data-action='override-fps']")?.value ?? 30); + const bitrate = Number(appRoot.querySelector("[data-action='override-bitrate']")?.value ?? 6000); + const [width, height] = parseResolution(preset); + + try { + const status = await tauriInvoke("set_game_quality_override", { + gameId: state.detectedGame, + name: `${preset} ${fps}fps`, + width, + height, + fps, + bitrateKbps: bitrate, + }); + applyDesktopStatus(status); + showNotice(`Quality override saved for ${state.detectedGame}.`); + render(); + } catch (error) { + console.warn("Could not save quality override", error); + showNotice(`Could not save quality override: ${String(error)}`); + } +} + +async function clearGameQualityOverride() { + if (!tauriInvoke) { + return; + } + if (state.detectedGame === "Waiting for game") { + return; + } + + try { + const status = await tauriInvoke("clear_game_quality_override", { + gameId: state.detectedGame, + }); + applyDesktopStatus(status); + showNotice(`Quality override cleared for ${state.detectedGame}.`); + render(); + } catch (error) { + console.warn("Could not clear quality override", error); + showNotice(`Could not clear quality override: ${String(error)}`); + } +} + async function checkForUpdates() { if (!tauriInvoke) { return;