Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

Adapt subtitle cache and game passthrough with configurable hotkeys

Veyra Goal Agentffc00be34a82
diff --git a/AGENTS.md b/AGENTS.md
index 7403c935..13ce0a71 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> **2026-10-16 粉丝字幕/鼠标穿透适配授权**:用户要求适配所附2.0.8补丁、设置中自定义鼠标穿透快捷键,完成后汇报再关机。按docs/FAN_SUBTITLE_PASSTHROUGH_PLAN_2026-10-16.md从main b571a44隔离codex/fan-subtitle-passthrough-20261016,允许必要字幕缓存/游戏模式/桥接/QML/翻译/构建测试接点,覆盖这些旧冻结。先存档81旧树/93分支/509脏文件和附件,保持其它任务及独立NR修复。产物全E盘,UI33ms/250ms与增强调度保持,不派Agent/造压/改驱动或专有运行库/真实配置;构建≤900秒、测试≤300秒。无merge/push/Release/新用户包授权。完成源码与证据保存并汇报后正常关机,不强制丢弃用户未保存内容。
+
> **2026-10-16 PR44授权**:用户要求研究合并HDR显示页PR44。基于main8d8eb09,在codex/pr44-hdr-display-20261016保留PR44 head3ee17b6并按docs/PR44_HDR_DISPLAY_PLAN_2026-10-16.md适配HDR显示/曲线/记忆/元数据/低频GPU统计及必要shader/构建回归,覆盖这些接点旧冻结。正常播放不回读像素、只读GPU归约统计且面板隐藏无采样;不提高33ms/250ms频率。78旧树/509脏文件和上一轮issues分支保持;产物全E盘,测试≤300秒/构建≤900秒。不派Agent、不改专有运行库/模型/驱动/真实配置。检查通过允许PR44合main及普通GitHub同步;无Release/用户包/评论/代发/关机授权。
> **2026-10-15 2.0.8 正式发布授权**:用户实测当前两个2.0.8测试包正常,明确要求仅改外部文件名直接发布2.0.8,不重编译、不重打包。按docs/RELEASE_2.0.8_PLAN_2026-10-15.md,汇总Claude与Codex自2.0.7以来全部最终保留内容,重点为延迟链路、窗口/显示器捕获游戏模式、可变刷新、采集卡画面与手柄转发以及搭配第三方远程软件的电脑游戏使用方式;公开说明不叙述用户要求省略的旧显示同步设定。允许本地main文档合入、普通推送nrvideo/main及v2.0.8/v2.0.8-sources标签、GitHub正式Release,主下载区只放NVIDIA/AMD两包,源材料另放非latest归档并引用已有依赖/FFmpeg源。保留六群/赞助二维码各width220、Discord、Ko-fi、知识库。77旧树/509脏文件及五个原归档保护;所有产物E盘,不改产品/运行库/模型/配置,不派Agent、不代发、不关机。内部2.0.8-test及manifest标签原样保留并明示,实测/模拟/未验证边界如实说明。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index dedf9284..3daff7c9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1081,6 +1081,14 @@ if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)
target_link_libraries(veyra_qml_ui PRIVATE veyra_qml_bridge veyra_engine Qt6::CorePrivate dbghelp ole32)
add_executable(veyra_qml_data_tests tests/unit/QmlDataDirectoryTests.cpp src/ui/QmlDataDirectory.cpp)
+ add_executable(veyra_game_passthrough_tests tests/integration/GamePassthroughTests.cpp)
+ target_compile_features(veyra_game_passthrough_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_game_passthrough_tests PRIVATE /utf-8)
+ target_link_libraries(veyra_game_passthrough_tests PRIVATE veyra_qml_bridge)
+ add_executable(veyra_subtitle_cache_tests tests/integration/SubtitleCacheTests.cpp)
+ target_compile_features(veyra_subtitle_cache_tests PRIVATE cxx_std_20)
+ target_compile_options(veyra_subtitle_cache_tests PRIVATE /utf-8)
+ target_link_libraries(veyra_subtitle_cache_tests PRIVATE veyra_engine)
target_compile_features(veyra_qml_data_tests PRIVATE cxx_std_20)
target_include_directories(veyra_qml_data_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 74541b4c..2b38f9f1 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -876,3 +876,22 @@ through RTX Video HDR, resolves metadata from the actual output curve, and
repairs persistence, failure reporting, translation and custom-preset states.
The source contribution adds no SDK, model or runtime binary. Implementation
and local validation details are in `docs/PR44_HDR_DISPLAY_REPORT_2026-10-16.md`.
+
+## User-provided fan contribution — subtitles / game passthrough (2026-10-16)
+
+The user supplied `veyra-2.0.8-local-changes.patch` (16,129 bytes, SHA256
+`f0c74f69c37c82f3efeb4e7d89d972352fad12258328dc01d0e09237e7612b1c`)
+and `Veyra-2.0.8-源码改动说明.md` (SHA256
+`a06ee46d6df240b2380ee08283b23088577c0ac28f4d313e236c0166aca53c16`),
+based on Veyra `33b22b9138a00ffc9a5e5077215d997ce328a2d1` (GPL-3.0).
+The supplied files contain no author name; none is invented here. Originals and
+identities are retained in the task archive. No binary accompanies this adaptation.
+
+`SubtitleCacheBudget.h` / `Subtitles.cpp` adapt the raised on-demand cache limit
+with strict parsing and 64-bit arithmetic. `GameHotkeys.h` / `GamePassthrough.h`
+adapt the low-level-hook approach with a dedicated message thread, queued UI
+actions, paired releases and configurable bindings. The global top-left-video
+change is replaced by native window/monitor alignment only in game mode, using
+actual screen bounds and Qt DPI conversion; ordinary movie layout is preserved.
+See `docs/FAN_SUBTITLE_PASSTHROUGH_PLAN_2026-10-16.md` and the task report for
+scope, provenance and actual tests. Veyra's GPL-3.0 source license is unchanged.
diff --git a/apps/veyra-qml/main.cpp b/apps/veyra-qml/main.cpp
index 09bddfe1..16f1ef10 100644
--- a/apps/veyra-qml/main.cpp
+++ b/apps/veyra-qml/main.cpp
@@ -165,10 +165,12 @@ bool syncVideoGeometry(QQuickWindow* window, QQuickItem* host) {
// spans the window must use its actual physical client extent: Qt rounds
// the HWND at fractional DPI, whereas flooring width*dpr can leave a
// one-pixel strip outside the video (for example 642 DIP at 125%).
- const int x = int(std::floor(topLeft.x() * dpr));
- const int y = int(std::floor(topLeft.y() * dpr));
- int w = std::max(1, int(std::floor(host->width() * dpr)));
- int h = std::max(1, int(std::floor(host->height() * dpr)));
+ const bool aligned = window->property("gameAligned").toBool();
+ const auto physical = [aligned](qreal value) { return int(aligned ? std::round(value) : std::floor(value)); };
+ const int x = physical(topLeft.x() * dpr);
+ const int y = physical(topLeft.y() * dpr);
+ int w = std::max(1, physical(host->width() * dpr));
+ int h = std::max(1, physical(host->height() * dpr));
RECT parentClient{};
if (GetClientRect(reinterpret_cast<HWND>(window->winId()), &parentClient)) {
if (std::abs(topLeft.x()) < 0.001 && std::abs(host->width() - window->width()) < 0.001)
diff --git a/docs/FAN_SUBTITLE_PASSTHROUGH_PLAN_2026-10-16.md b/docs/FAN_SUBTITLE_PASSTHROUGH_PLAN_2026-10-16.md
new file mode 100644
index 00000000..df8dd059
--- /dev/null
+++ b/docs/FAN_SUBTITLE_PASSTHROUGH_PLAN_2026-10-16.md
@@ -0,0 +1,13 @@
+# 粉丝字幕与游戏模式补丁适配
+
+用户要求适配所附三文件补丁,主要为字幕、屏幕捕获鼠标穿透,并在设置中自定义快捷键;完成后先汇报再关机。此范围覆盖字幕/游戏模式/桥接/QML/必要构建测试的历史冻结。基于 main b571a44,在 codex/fan-subtitle-passthrough-20261016 隔离施工;不混入上一轮独立 NR 同步修复,不合 main、不推送或发布、不打用户包、不改驱动、专有运行库或真实用户设置,不派 Agent,不造压。UI33ms/250ms、算法/帧队列保持。
+
+已先存档 81 旧树、93 原分支、509 未提交文件及附件原件,checkpoint/pre-fan-subtitle-passthrough-20261016,source-before.bundle verify 通过;回执在 E:/项目/Veyra/archives/fan-subtitle-passthrough-20261016/archive-receipt.json。所有产物 E盘任务目录,构建≤900秒、每测试≤300秒。
+
+1. 保留粉丝发现的64MiB截断修复,将字幕压缩缓存预算提高为4GiB上限(按实际内容增长,不预分配),环境变量严格验证1–65536MiB及64位乘法;补预算日志/有限的超限诊断和真实超过64MiB后段字幕回归,不取消坏文件/矩形/条目保护。
+2. 不采用全局视频左上对齐:原始鼠标坐标只有在未缩放且位置对齐时才匹配。仅游戏模式将视频宿主贴合被捕获窗口的实际屏幕区域,显示器捕获按监视器区域,处理屏幕偏移/DPI与移动;普通电影/专业模式保持。沿用250ms心跳刷新几何缓存,不增加绘制或采样频率。
+3. 采用粉丝建议的低层键盘钩子方向,但不在钩子内执行Qt/窗口转换:独立消息线程只做组合键状态、长按防重复和投递事件;支持左右修饰键、按下/抬起配对、离开模式卸载及旧事件失效。保持游戏前台才接管面板键,退出键始终在模式内有效;钩子安装失败拒绝穿透。
+4. 复用现有快捷键页与保存格式,面板/退出两项默认Home/Ctrl+Alt+Home,支持自定义、冲突/无效组合拒绝、还原和重启沿用;移除游戏模式里QML与钩子双触发。
+5. 构建、字幕实际解码/长缓存、Win32真实输入与穿透/面板/退出/窗口移动、普通布局、设置保存及语言回归。未测真实独占游戏/反作弊/多屏硬件的项如实报告。源/证据/报告完成并保存后,按当前请求正常关机,不强制丢弃未保存内容。
+
+附件只作为来源和待审代码,说明中“Raw Input必然绕过RegisterHotKey”“左上角就等于坐标一一对应”不当作已证事实;接口行为以Microsoft文档和本机实测为准。来源标注SHA和适配差异。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 098d6534..734c8a85 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -9590,3 +9590,8 @@ PR44最终产品输入26db779;37目标构建通过(命令python -X utf8 -B -
实际python .../checks.py --retry、ui-cards.py、ui-hdr.py与scripts/i18n/extract.py --check:HDR/链/预设/事务/颜色/几何/数据迁移通过,Qt Quick 76/76;2401翻译缺译/占位符0。真实HDR10/scRGB曲线/黑帧/统计/resize/metadata/符号RGB/强度0恒等通过,D3D12 ERROR/CORRUPTION0;另--video-hdr真实SDR→已核验TrueHDR→显示曲线sourceHdr0/videoHdrActive1通过。英日繁中五卡窄窗及OBS软件渲染、非法参数不变、A/B影片记忆37恢复、关闭清除后0条、19/60/900重开保持通过。最新完整命令/输入SHA/EXE SHA/截图在E:/项目/Veyra/{logs,reports,tests}/pr44-hdr-display-20261016;build.json/checks.json/ui.json/cards.json为指针。首轮统计描述符/ClearUAV6项GPU错误与黑帧夹具未恢复灰阶2项失败已修后重测,漏传测试目录/未建截图目录的环境失败也已修后重跑,旧失败证据保留。未测实体投影仪/AMD/Intel/跨屏/光学延迟,不宣称无开销或性能百分比。
来源及边界详见THIRD_PARTY_NOTICES与PR44_HDR_DISPLAY_REPORT_2026-10-16.md。按用户授权检查后正常推进main/nrvideo并核对PR状态,使用final-audit.py --stage pre/post保护78原树/90原分支/509脏文件(只允许main推进),复核产品输入与验收EXE一致,增量bundle/远端回执写E盘archives/reports/...;最终实际SHA、PR合并状态和保护结果以final.json为准。上一轮issues41–45分支与其它旧树原样保留,本轮无Release/打用户包/代发/子Agent/关机。
+
+
+## 2026-10-16 粉丝字幕与鼠标穿透适配开工
+
+用户要求适配所附2.0.8粉丝补丁及自定义鼠标穿透快捷键,完成汇报后关机。先运行tmp/fan-subtitle-passthrough-20261016/archive.py,81旧树/93分支/509未提交文件与两附件独立保护,pre标签main b571a44,source-before.bundle 74957056字节verify通过。新隔离分支codex/fan-subtitle-passthrough-20261016;方案FAN_SUBTITLE_PASSTHROUGH_PLAN_2026-10-16.md。不混入NR独立修复,不合main/push/Release/用户包,不派Agent/造压/改驱动或真实配置,产物全E盘;源码先实现再真实回归,后续记录失败和结果。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index c89e96b2..46740ce8 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -16808,6 +16808,69 @@
"zh-TW": ";預設“即時”,同時執行遊戲或其他重負載程式變慢時可改為“高”或“普通”",
"en": "; Realtime by default. If a game or other heavy program running alongside slows down, choose High or Normal",
"ja": ";既定は「リアルタイム」。同時に動かすゲームや重い処理が遅くなる場合は「高」か「通常」に変更してください"
+ },
+ {
+ "zh": "游戏模式键盘监听启动失败,未开启鼠标穿透;请退出全屏后重试",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "遊戲模式鍵盤監聽啟動失敗,未開啟滑鼠穿透;請退出全螢幕後重試",
+ "en": "Game mode keyboard listener could not start. Mouse passthrough is off; leave fullscreen and try again.",
+ "ja": "ゲームモードのキー監視を開始できません。マウス透過はオフです。全画面を解除して再試行してください。"
+ },
+ {
+ "zh": "游戏模式:调整画面",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "遊戲模式:調整畫面",
+ "en": "Game mode: adjust picture",
+ "ja": "ゲームモード:画面調整"
+ },
+ {
+ "zh": "仅在游戏模式中接管按键;支持 Ctrl、Alt、Shift 组合",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "僅在遊戲模式中接管按鍵;支援 Ctrl、Alt、Shift 組合",
+ "en": "Keys are captured only in game mode; Ctrl, Alt and Shift combinations are supported",
+ "ja": "ゲームモード中のみキーを使用します。Ctrl、Alt、Shift の組み合わせに対応"
+ },
+ {
+ "zh": "游戏模式:退出鼠标穿透",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "遊戲模式:退出滑鼠穿透",
+ "en": "Game mode: exit mouse passthrough",
+ "ja": "ゲームモード:マウス透過を解除"
+ },
+ {
+ "zh": "退出全屏,恢复普通窗口操作",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "退出全螢幕,恢復一般視窗操作",
+ "en": "Leave fullscreen and restore normal window controls",
+ "ja": "全画面を解除して通常のウィンドウ操作に戻る"
+ },
+ {
+ "zh": "开始后 Veyra 在这块屏幕上全屏,键鼠和手柄直接操作屏幕上的程序;%1 调整画面,%2 退出",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "開始後 Veyra 在此螢幕全螢幕顯示,鍵鼠與手把直接操作螢幕上的程式;%1 調整畫面,%2 退出",
+ "en": "Veyra opens fullscreen on this display. Keyboard, mouse and controller operate its programs; %1 adjusts the picture and %2 exits.",
+ "ja": "この画面で全画面表示し、キーボード・マウス・コントローラーで背後のアプリを操作します。%1 で画面調整、%2 で解除。"
+ },
+ {
+ "zh": "画面贴合游戏窗口的位置,键鼠和手柄照常操作游戏;%1 调整画面,%2 退出。独占全屏请改为无边框窗口",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "畫面貼合遊戲視窗位置,鍵鼠與手把照常操作遊戲;%1 調整畫面,%2 退出。獨佔全螢幕請改為無邊框視窗",
+ "en": "The picture follows the game window position. Use the keyboard, mouse and controller normally; %1 adjusts the picture and %2 exits. Use borderless mode instead of exclusive fullscreen.",
+ "ja": "ゲームウィンドウの位置に画面を合わせます。通常どおり操作し、%1 で画面調整、%2 で解除。排他全画面ではなくボーダーレスにしてください。"
+ },
+ {
+ "zh": "全屏(双击画面 / F11)· 全屏后按 %1 打开快速调节",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "全螢幕(雙擊畫面 / F11)· 全螢幕後按 %1 開啟快速調整",
+ "en": "Fullscreen (double-click / F11) · Press %1 for quick adjustments",
+ "ja": "全画面(ダブルクリック / F11)· %1 でクイック調整"
+ },
+ {
+ "zh": "%1 关闭",
+ "src": "fan-subtitle-passthrough-20261016",
+ "zh-TW": "%1 關閉",
+ "en": "%1 to close",
+ "ja": "%1 で閉じる"
}
]
}
diff --git a/include/veyra/engine/SubtitleCacheBudget.h b/include/veyra/engine/SubtitleCacheBudget.h
new file mode 100644
index 00000000..b7378dea
--- /dev/null
+++ b/include/veyra/engine/SubtitleCacheBudget.h
@@ -0,0 +1,18 @@
+#pragma once
+#include <charconv>
+#include <cstdint>
+#include <string_view>
+
+namespace veyra::engine {
+// User-supplied fan patch, 2026-10-16 (provenance in THIRD_PARTY_NOTICES).
+// A ceiling on compressed cue storage, not an allocation/reservation of 4 GiB.
+inline constexpr uint64_t kDefaultSubtitleCacheBytes = 4096ull * 1024ull * 1024ull;
+inline uint64_t subtitleCacheBudgetBytes(std::string_view mib) {
+ if (mib.empty()) return kDefaultSubtitleCacheBytes;
+ uint64_t value = 0;
+ const auto parsed = std::from_chars(mib.data(), mib.data() + mib.size(), value);
+ if (parsed.ec != std::errc{} || parsed.ptr != mib.data() + mib.size() || value < 1 || value > 65536)
+ return kDefaultSubtitleCacheBytes;
+ return value * 1024ull * 1024ull;
+}
+}
diff --git a/include/veyra/ui/GameHotkeys.h b/include/veyra/ui/GameHotkeys.h
new file mode 100644
index 00000000..73e9f36c
--- /dev/null
+++ b/include/veyra/ui/GameHotkeys.h
@@ -0,0 +1,134 @@
+#pragma once
+// Low-level hook direction from the user's fan patch (2026-10-16).
+// Veyra adaptation: a dedicated message thread, bounded callback work, queued UI
+// events, paired releases and autorepeat suppression. No input injection into games.
+#include <windows.h>
+#include <QKeySequence>
+#include <array>
+#include <atomic>
+#include <future>
+#include <thread>
+
+namespace veyra::ui {
+struct GameKey {
+ unsigned vk = 0, mods = 0; // Ctrl=1, Alt=2, Shift=4 (Win reserved)
+ bool operator==(const GameKey&) const = default;
+};
+inline GameKey gameKey(const QKeySequence& sequence) {
+ if (sequence.isEmpty() || sequence.count() != 1) return {};
+ const auto c = sequence[0]; const int k = c.key(); const auto m = c.keyboardModifiers();
+ if (m & ~(Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier)) return {};
+ unsigned vk = 0;
+ if ((k >= 'A' && k <= 'Z') || (k >= '0' && k <= '9')) vk = unsigned(k);
+ else if (k >= Qt::Key_F1 && k <= Qt::Key_F24) vk = VK_F1 + unsigned(k - Qt::Key_F1);
+ else switch (k) {
+ case Qt::Key_Home: vk = VK_HOME; break; case Qt::Key_End: vk = VK_END; break;
+ case Qt::Key_PageUp: vk = VK_PRIOR; break; case Qt::Key_PageDown: vk = VK_NEXT; break;
+ case Qt::Key_Insert: vk = VK_INSERT; break; case Qt::Key_Delete: vk = VK_DELETE; break;
+ case Qt::Key_Space: vk = VK_SPACE; break; case Qt::Key_Tab: vk = VK_TAB; break;
+ case Qt::Key_Backspace: vk = VK_BACK; break; case Qt::Key_Return: case Qt::Key_Enter: vk = VK_RETURN; break;
+ default: break;
+ }
+ return {vk, unsigned((m & Qt::ControlModifier ? 1 : 0) | (m & Qt::AltModifier ? 2 : 0) | (m & Qt::ShiftModifier ? 4 : 0))};
+}
+
+class GameKeyState {
+public:
+ struct Result { bool consume = false; int action = -1; };
+ void seed(unsigned vk, bool down) { if (vk < keys_.size()) keys_[vk] = down; }
+ Result input(unsigned vk, bool down, GameKey panel, GameKey exit, bool panelOwned) {
+ if (vk >= keys_.size()) return {};
+ const bool repeat = keys_[vk];
+ const bool claimed = claimed_[vk];
+ // Remember modifiers and hotkey trigger state only, never other typed keys.
+ const bool modifier = vk == VK_CONTROL || vk == VK_LCONTROL || vk == VK_RCONTROL ||
+ vk == VK_MENU || vk == VK_LMENU || vk == VK_RMENU || vk == VK_SHIFT || vk == VK_LSHIFT || vk == VK_RSHIFT ||
+ vk == VK_LWIN || vk == VK_RWIN;
+ if (modifier || vk == panel.vk || vk == exit.vk || claimed || repeat) keys_[vk] = down;
+ if (!down) { claimed_[vk] = false; return {claimed, -1}; }
+ if (claimed) return {true, -1};
+ if (repeat || modifier) return {};
+ const unsigned mods = ((keys_[VK_CONTROL] || keys_[VK_LCONTROL] || keys_[VK_RCONTROL]) ? 1 : 0) |
+ ((keys_[VK_MENU] || keys_[VK_LMENU] || keys_[VK_RMENU]) ? 2 : 0) |
+ ((keys_[VK_SHIFT] || keys_[VK_LSHIFT] || keys_[VK_RSHIFT]) ? 4 : 0) |
+ ((keys_[VK_LWIN] || keys_[VK_RWIN]) ? 8 : 0);
+ const GameKey pressed{vk, mods};
+ const int action = pressed == exit ? 1 : panelOwned && pressed == panel ? 0 : -1;
+ if (action < 0) return {};
+ claimed_[vk] = true;
+ return {true, action};
+ }
+private:
+ std::array<bool, 256> keys_{}, claimed_{};
+};
+
+class GameHotkeyListener {
+public:
+ static constexpr UINT message = WM_APP + 0x347;
+ ~GameHotkeyListener() { stop(); }
+ void bindings(GameKey panel, GameKey exit) {
+ config_.store(uint64_t(panel.vk) | (uint64_t(panel.mods) << 8) | (uint64_t(exit.vk) << 16) | (uint64_t(exit.mods) << 24));
+ ++epoch_;
+ }
+ void panelOwned(bool on) { panelOwned_.store(on); }
+ bool running() const { return running_.load(); }
+ bool current(LPARAM epoch) const { return running() && uint64_t(epoch) == epoch_.load(); }
+ bool start(HWND target) {
+ if (running()) return true;
+ stop(); target_ = target;
+ stopEvent_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+ if (!stopEvent_) return false;
+ std::promise<bool> ready; auto initialized = ready.get_future();
+ try {
+ thread_ = std::thread([this, ready = std::move(ready)]() mutable {
+ self_ = this; state_ = {};
+ for (unsigned k : {VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU, VK_LSHIFT, VK_RSHIFT, VK_LWIN, VK_RWIN})
+ state_.seed(k, (GetAsyncKeyState(int(k)) & 0x8000) != 0);
+ const HHOOK hook = SetWindowsHookExW(WH_KEYBOARD_LL, callback, GetModuleHandleW(nullptr), 0);
+ running_.store(hook != nullptr); ready.set_value(hook != nullptr);
+ if (hook) {
+ while (MsgWaitForMultipleObjects(1, &stopEvent_, FALSE, INFINITE, QS_ALLINPUT) == WAIT_OBJECT_0 + 1) {
+ MSG msg; while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); }
+ }
+ UnhookWindowsHookEx(hook);
+ }
+ running_.store(false); self_ = nullptr;
+ });
+ } catch (...) { CloseHandle(stopEvent_); stopEvent_ = nullptr; return false; }
+ const bool ok = initialized.get();
+ if (!ok) stop();
+ return ok;
+ }
+ void stop() {
+ running_.store(false); ++epoch_;
+ if (stopEvent_) SetEvent(stopEvent_);
+ if (thread_.joinable()) thread_.join();
+ if (stopEvent_) { CloseHandle(stopEvent_); stopEvent_ = nullptr; }
+ panelOwned_.store(false);
+ }
+private:
+ HWND target_ = nullptr;
+ HANDLE stopEvent_ = nullptr;
+ std::thread thread_;
+ std::atomic<bool> running_{false}, panelOwned_{false};
+ std::atomic<uint64_t> config_{uint64_t(VK_HOME) | (uint64_t(VK_HOME) << 16) | (3ull << 24)}, epoch_{0};
+ GameKeyState state_;
+ static inline thread_local GameHotkeyListener* self_ = nullptr;
+ static LRESULT CALLBACK callback(int code, WPARAM wp, LPARAM lp) {
+ if (code == HC_ACTION && self_ && self_->running()) {
+ const auto* key = reinterpret_cast<const KBDLLHOOKSTRUCT*>(lp);
+ const bool down = wp == WM_KEYDOWN || wp == WM_SYSKEYDOWN;
+ const bool up = wp == WM_KEYUP || wp == WM_SYSKEYUP;
+ if (key && (down || up)) {
+ auto& self = *self_; const auto epoch = self.epoch_.load(); const auto config = self.config_.load();
+ const GameKey panel{unsigned(config & 255), unsigned((config >> 8) & 15)};
+ const GameKey exit{unsigned((config >> 16) & 255), unsigned((config >> 24) & 15)};
+ const auto result = self.state_.input(key->vkCode, down, panel, exit, self.panelOwned_.load());
+ if (result.action >= 0 && epoch == self.epoch_.load()) PostMessageW(self.target_, message, WPARAM(result.action), LPARAM(epoch));
+ if (result.consume) return 1;
+ }
+ }
+ return CallNextHookEx(nullptr, code, wp, lp);
+ }
+};
+}
diff --git a/include/veyra/ui/GamePassthrough.h b/include/veyra/ui/GamePassthrough.h
index f1c05c63..26563496 100644
--- a/include/veyra/ui/GamePassthrough.h
+++ b/include/veyra/ui/GamePassthrough.h
@@ -10,10 +10,10 @@
// software interface it drops a layered bit set behind its back. Qt does not set
// WS_EX_NOACTIVATE on it, so this class adds that bit, makes the window topmost,
// hands the foreground over, owns the hotkeys and the watchdog, and makes any other
-// visible Veyra window click-through too. Home, a system hotkey while the picture is
+// visible Veyra window click-through too. The configurable panel key while the picture is
// in front, opens the adjust panel and takes the input back; closing the panel hands
-// it to the program again. Ctrl+Alt+Home leaves. RegisterHotKey, not a low-level
-// keyboard hook: nothing else is listened to, and there is no hook thread.
+// it to the program again. The configurable exit key leaves. The keyboard hook has
+// a dedicated message thread and only posts recognized actions to the GUI thread.
//
// Everything is in-process on the GUI thread, so a crash takes the windows with it
// and no click-through window can be left behind. A GUI thread that stops answering
@@ -36,6 +36,7 @@
#include <vector>
#include "veyra/Log.h"
#include "veyra/source/ScreenCaptureSource.h"
+#include "veyra/ui/GameHotkeys.h"
namespace veyra::ui {
@@ -44,13 +45,14 @@ public:
// Off: a normal window. Panel: on top and interactive (Home panel open).
// Through: on top, click-through, the captured program has the foreground.
enum class Mode { Off, Panel, Through };
- enum class Event { PanelHotkey, ExitHotkey, HomeUnavailable, ExitUnavailable, HangReleased };
+ enum class Event { PanelHotkey, ExitHotkey, ExitUnavailable, HangReleased };
std::function<void(Event)> onEvent;
GamePassthrough() { s_instance = this; }
~GamePassthrough() override {
stopWatchdog();
apply(Mode::Off);
+ keys_.stop();
if (s_instance == this) s_instance = nullptr;
}
GamePassthrough(const GamePassthrough&) = delete;
@@ -64,17 +66,35 @@ public:
}
Mode mode() const { return mode_; }
- // Entering from Off: the exit hotkey must exist before anything may become
- // click-through. False (and ExitUnavailable) when another program owns it.
+ void setHotkeys(GameKey panel, GameKey exit) { keys_.bindings(panel, exit); }
+ // WGC captures the visible window frame, not an enlarged movie viewport.
+ // Coordinates are physical pixels in the fullscreen host's client space.
+ RECT pictureBounds() const {
+ RECT r{}; POINT origin{};
+ if (!main_ || !ClientToScreen(main_, &origin)) return {};
+ if (monitorCapture_) {
+ MONITORINFO m{}; m.cbSize = sizeof(m);
+ if (!GetMonitorInfoW(monitor_, &m)) return {};
+ r = m.rcMonitor;
+ } else {
+ if (!target_ || !IsWindow(target_) || IsIconic(target_)) return {};
+ if (FAILED(DwmGetWindowAttribute(target_, DWMWA_EXTENDED_FRAME_BOUNDS, &r, sizeof(r))) &&
+ !GetWindowRect(target_, &r)) return {};
+ }
+ OffsetRect(&r, -origin.x, -origin.y);
+ return r;
+ }
+
+ // The listener must exist before anything may become click-through.
bool arm() {
if (!main_) return false;
- if (exitRegistered_) return true;
- exitRegistered_ = RegisterHotKey(main_, kExitId, MOD_CONTROL | MOD_ALT | MOD_NOREPEAT, VK_HOME) != 0;
- if (!exitRegistered_) {
- veyra::log::warn("game-mode", std::format("Ctrl+Alt+Home unavailable err={}; click-through refused", GetLastError()));
+ if (keys_.running()) return true;
+ if (!keys_.start(main_)) {
+ veyra::log::warn("game-mode", "keyboard listener unavailable; click-through refused");
if (onEvent) onEvent(Event::ExitUnavailable);
return false;
}
+ veyra::log::info("game-mode", "keyboard hook installed on dedicated message thread");
return true;
}
// The caller publishes the new mode first, so Qt has applied (or removed) the
@@ -88,7 +108,7 @@ public:
sunk_ = false;
topmost(false);
setPanelHotkey(false);
- if (exitRegistered_) { UnregisterHotKey(main_, kExitId); exitRegistered_ = false; }
+ keys_.stop();
if (hook_) { UnhookWinEvent(hook_); hook_ = nullptr; }
armed_.store(false);
mode_ = Mode::Off;
@@ -101,7 +121,6 @@ public:
if (!arm()) return;
topmostBefore_ = (GetWindowLongPtrW(main_, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
hook_ = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, &GamePassthrough::winEvent, 0, 0, WINEVENT_OUTOFCONTEXT);
- panelWarned_ = false;
startWatchdog();
}
mode_ = next;
@@ -139,9 +158,10 @@ public:
if (type != "windows_generic_MSG") return false;
const auto* msg = static_cast<const MSG*>(message);
switch (msg->message) {
- case WM_HOTKEY:
- if (msg->wParam != kPanelId && msg->wParam != kExitId) return false;
- if (onEvent) onEvent(msg->wParam == kPanelId ? Event::PanelHotkey : Event::ExitHotkey);
+ case GameHotkeyListener::message:
+ if (!keys_.current(msg->lParam) || mode_ == Mode::Off || msg->wParam > 1 ||
+ (msg->wParam == 0 && !panelOwned_)) return false;
+ if (onEvent) onEvent(msg->wParam == 0 ? Event::PanelHotkey : Event::ExitHotkey);
if (result) *result = 0;
return true;
case WM_SHOWWINDOW:
@@ -158,8 +178,6 @@ public:
}
private:
- static constexpr int kPanelId = 0x5647; // "VG"
- static constexpr int kExitId = 0x5658; // "VX"
static constexpr ULONGLONG kHangMs = 3000;
static inline GamePassthrough* s_instance = nullptr;
@@ -167,7 +185,8 @@ private:
HMONITOR monitor_ = nullptr;
bool monitorCapture_ = false;
Mode mode_ = Mode::Off;
- bool exitRegistered_ = false, panelRegistered_ = false, panelWarned_ = false;
+ bool panelOwned_ = false;
+ GameHotkeyListener keys_;
bool topmostBefore_ = false, sunk_ = false;
HWINEVENTHOOK hook_ = nullptr;
std::vector<std::pair<HWND, LONG_PTR>> changed_; // windows made click-through, with their original style
@@ -181,8 +200,8 @@ private:
void log(const char* what) {
const LONG_PTR ex = main_ ? GetWindowLongPtrW(main_, GWL_EXSTYLE) : 0;
- veyra::log::info("game-mode", std::format("{} monitorCapture={} target=0x{:X} exstyle=0x{:X} windows={} panelHotkey={} exitHotkey={}",
- what, monitorCapture_, uint64_t(uintptr_t(target_)), uint64_t(ex), changed_.size(), panelRegistered_, exitRegistered_));
+ veyra::log::info("game-mode", std::format("{} monitorCapture={} target=0x{:X} exstyle=0x{:X} windows={} panelOwned={} exitHook={}",
+ what, monitorCapture_, uint64_t(uintptr_t(target_)), uint64_t(ex), changed_.size(), panelOwned_, keys_.running()));
}
static bool ours(HWND w) {
DWORD pid = 0;
@@ -291,14 +310,9 @@ private:
veyra::log::info("game-mode", std::format("focus -> {} 0x{:X} ok={}", what, uint64_t(uintptr_t(w)), ok));
}
void setPanelHotkey(bool on) {
- if (on == panelRegistered_) return;
- if (!on) { UnregisterHotKey(main_, kPanelId); panelRegistered_ = false; return; }
- panelRegistered_ = RegisterHotKey(main_, kPanelId, MOD_NOREPEAT, VK_HOME) != 0;
- if (!panelRegistered_ && !panelWarned_) {
- panelWarned_ = true;
- veyra::log::warn("game-mode", std::format("Home unavailable err={}", GetLastError()));
- if (onEvent) onEvent(Event::HomeUnavailable);
- }
+ if (on == panelOwned_) return;
+ panelOwned_ = on;
+ keys_.panelOwned(on);
}
// Home belongs to Veyra while the user is "inside" the picture: the captured
// program (window capture) or anything on that monitor (monitor capture). In
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index 4b1698a5..d2302d8d 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -167,6 +167,7 @@ class QmlPlayerBridge : public QObject {
// fullscreen picture is click-through and the captured program has the input.
Q_PROPERTY(bool gameMode READ gameMode NOTIFY gameModeChanged)
Q_PROPERTY(bool passthroughActive READ passthroughActive NOTIFY gameModeChanged)
+ Q_PROPERTY(QRectF gameVideoRect READ gameVideoRect NOTIFY gameModeChanged)
// Subtitles (P4-c): the engine's SubtitleLoader reads the embedded tracks and
// the same-name external file; the old shell's SubtitleOverlay draws them as a
@@ -689,6 +690,7 @@ public:
Q_INVOKABLE bool startScreenCapture();
bool gameMode() const;
bool passthroughActive() const;
+ QRectF gameVideoRect() const;
// The Home panel is open: the picture stays on top but takes the input back.
Q_INVOKABLE void setGamePanelOpen(bool open);
// Index into Qt.application.screens of the monitor 游戏模式 covers, or -1.
@@ -1308,7 +1310,7 @@ signals:
// The UI moves to a page by name when a command implies it.
void navigate(const QString& page);
void gameModeChanged();
- // 游戏模式 hotkeys: 0 = Home (adjust panel), 1 = Ctrl+Alt+Home (leave).
+ // Configurable game hotkeys: 0 = adjust panel, 1 = leave.
void gameHotkey(int which);
// The game-mode capture ended or failed, or the GUI hung, while the picture was in
// front: the UI leaves fullscreen and shows the reason.
@@ -1320,6 +1322,7 @@ private:
// Value edit of one group; a change of the chain's validity notifies everything.
void emitParameterChanged(void (QmlPlayerBridge::*group)(), bool wasValid);
void updateGameMode();
+ void updateGameGeometry();
// 抖音直播伴侣 running (gfx/PresentationHooks.h): Realtime GPU priority is capped at
// High while it runs and restored when it exits; 监控软件兼容 "off" leaves it alone.
void updateLiveCompanionCompat();
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index b5483691..ceab5aa3 100644
--- a/qml/Veyra/DialogHost.qml
+++ b/qml/Veyra/DialogHost.qml
@@ -1334,8 +1334,8 @@ Item {
VRow {
label: qsTr("游戏模式")
hint: screenDialog.o.kind === 1
- ? qsTr("开始后 Veyra 在这块屏幕上全屏,键鼠和手柄直接操作屏幕上的任何程序,就像直接用电脑;Home 调整画面,Ctrl+Alt+Home 退出")
- : qsTr("开始后 Veyra 在游戏所在的屏幕上全屏盖住游戏,键鼠和手柄照常操作游戏;Home 调整画面,Ctrl+Alt+Home 退出。游戏请设为无边框全屏")
+ ? qsTr("开始后 Veyra 在这块屏幕上全屏,键鼠和手柄直接操作屏幕上的程序;%1 调整画面,%2 退出").arg(veyra.shortcuts.gamePanel).arg(veyra.shortcuts.gameExit)
+ : qsTr("画面贴合游戏窗口的位置,键鼠和手柄照常操作游戏;%1 调整画面,%2 退出。独占全屏请改为无边框窗口").arg(veyra.shortcuts.gamePanel).arg(veyra.shortcuts.gameExit)
VSwitch {
objectName: "screen-game-mode"
checked: screenDialog.o.passthrough === true
diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qml
index 23b89a92..b0e8ca7b 100644
--- a/qml/Veyra/Main.qml
+++ b/qml/Veyra/Main.qml
@@ -66,6 +66,7 @@ Window {
// 16:9 until a source reports its own shape: a PS5 / capture session has no
// aspect while it connects, and 2.39 then left a thin black strip.
property real filmAspect: 16 / 9
+ readonly property bool gameAligned: fullscreen && veyra.gameMode
readonly property real reportedAspect: veyra.previewAspect
onReportedAspectChanged: if (reportedAspect < 0.2) fitToFilm(16 / 9)
property string lastPage: "home"
@@ -216,6 +217,9 @@ Window {
// numbers rather than read from a laid-out child. A child reports 0x0 on the
// frame the user opens a file, and that once produced a 1x1 swapchain.
function videoRect() {
+ if (fullscreen && veyra.gameMode &&
+ veyra.gameVideoRect.width > 0 && veyra.gameVideoRect.height > 0)
+ return veyra.gameVideoRect
// Fullscreen is a video-only viewport (AppShell): the picture is the screen
// and the controls float above it in their own window (FullscreenBar).
if ((fullscreen || (maximized && page === "min")) && page !== "home" && page !== "set")
@@ -446,6 +450,7 @@ Window {
toast.show(reason, true)
}
function onGameModeChanged() {
+ videoHost.syncRect()
if (veyra.passthroughActive && playlistWindow.visible) playlistWindow.hide()
}
}
@@ -686,7 +691,7 @@ Window {
Shortcut {
sequence: "Home"
enabled: root.fullscreen && !root.fullLocked && dialogs.dialog === "" &&
- (root.page === "min" || root.page === "pro" || root.page === "node")
+ !veyra.gameMode && (root.page === "min" || root.page === "pro" || root.page === "node")
onActivated: root.toggleQuickPanel()
}
// 5 s steps (field request 2026-10-02).
diff --git a/qml/Veyra/NodePage.qml b/qml/Veyra/NodePage.qml
index d5c9c54a..1d859fa9 100644
--- a/qml/Veyra/NodePage.qml
+++ b/qml/Veyra/NodePage.qml
@@ -589,7 +589,7 @@ VPage {
anchors.right: parent.right
anchors.top: parent.top
anchors.margins: 12
- text: qsTr("Home 关闭")
+ text: qsTr("%1 关闭").arg(veyra.gameMode ? veyra.shortcuts.gamePanel : "Home")
color: Theme.t3
font.family: Theme.fontUi
font.pixelSize: 11
diff --git a/qml/Veyra/ProPage.qml b/qml/Veyra/ProPage.qml
index 6d22a7e0..b648ec45 100644
--- a/qml/Veyra/ProPage.qml
+++ b/qml/Veyra/ProPage.qml
@@ -734,7 +734,7 @@ VPage {
HoverHandler { id: fullHover; cursorShape: Qt.PointingHandCursor }
TapHandler { onTapped: root.requestFullscreen() }
ToolTip.visible: fullHover.hovered
- ToolTip.text: qsTr("全屏(双击画面 / F11)· 全屏后按 Home 打开快速调节")
+ ToolTip.text: qsTr("全屏(双击画面 / F11)· 全屏后按 %1 打开快速调节").arg(veyra.gameMode ? veyra.shortcuts.gamePanel : "Home")
}
}
}
@@ -1118,7 +1118,7 @@ VPage {
spacing: 12
PerfOrbs { size: 46; spacing: 10 }
Text {
- text: qsTr("Home 关闭")
+ text: qsTr("%1 关闭").arg(veyra.gameMode ? veyra.shortcuts.gamePanel : "Home")
color: Theme.t3
font.family: Theme.fontUi
font.pixelSize: 11
diff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qml
index ecc0f715..7b5d2924 100644
--- a/qml/Veyra/SettingsPage.qml
+++ b/qml/Veyra/SettingsPage.qml
@@ -826,7 +826,9 @@ VPage {
{ id: "lock", a: qsTr("锁定全屏控制条") },
{ id: "hold", a: qsTr("按住查看原画") },
{ id: "screenshot", a: qsTr("截图") },
- { id: "toggleMode", a: qsTr("切换极简 / 专业") }
+ { id: "toggleMode", a: qsTr("切换极简 / 专业") },
+ { id: "gamePanel", a: qsTr("游戏模式:调整画面"), note: qsTr("仅在游戏模式中接管按键;支持 Ctrl、Alt、Shift 组合") },
+ { id: "gameExit", a: qsTr("游戏模式:退出鼠标穿透"), note: qsTr("退出全屏,恢复普通窗口操作") }
]
delegate: VRow {
id: keyRow
@@ -869,7 +871,6 @@ VPage {
{ a: qsTr("打开文件 / 导出页"), k: "Ctrl+O / Ctrl+E" },
{ a: qsTr("字幕开关 / 主轨 / 副轨"), k: "B / T / Y" },
{ a: qsTr("字幕延时 50 ms(Shift = 1 s)"), k: "Z / X" },
- { a: qsTr("游戏模式:调整画面 / 退出"), k: "Home / Ctrl+Alt+Home" }
]
delegate: VRow {
required property var modelData
diff --git a/scripts/tests/make-subtitle-cache-fixture.py b/scripts/tests/make-subtitle-cache-fixture.py
new file mode 100644
index 00000000..2e9426c2
--- /dev/null
+++ b/scripts/tests/make-subtitle-cache-fixture.py
@@ -0,0 +1,45 @@
+"""Five real PGS tracks whose decoded cue runs cross the historical 64 MiB cap.
+
+75 MiB bounded compressed-cue representation, no video/GPU pressure. Independently
+authored Matroska and PGS bytes are decoded by the product FFmpeg. Explicit output.
+"""
+from pathlib import Path
+import struct, sys, zlib
+
+def e(tag, data):
+ if isinstance(data, str): data = data.encode('utf8')
+ if isinstance(data, int): data = data.to_bytes(max(1, (data.bit_length()+7)//8), 'big')
+ n = next(n for n in range(1, 9) if len(data) < (1 << (7*n))-1)
+ return tag.to_bytes((tag.bit_length()+7)//8, 'big') + ((1 << (7*n)) | len(data)).to_bytes(n, 'big') + data
+
+def segment(kind, payload):
+ return struct.pack('>BH', kind, len(payload)) + payload
+
+def display(seq):
+ pcs = struct.pack('>HHBHBBBB',3840,2160,0x10,seq,0x80,0,0,1) + struct.pack('>HBBHH',0,0,0,200,1900)
+ out = segment(0x16,pcs) + segment(0x17,struct.pack('>BBHHHH',1,0,0,0,3840,2160))
+ out += segment(0x14,bytes([0,seq,0,16,128,128,0,1,235,128,128,255,2,16,128,128,255]))
+ pixels = (bytes([1,2])*256 + b'\0\0')*192
+ first = struct.pack('>HBB',0,seq,0x80) + (len(pixels)+4).to_bytes(3,'big') + struct.pack('>HH',512,192)
+ out += segment(0x15,first+pixels[:65000])
+ out += segment(0x15,struct.pack('>HBB',0,seq,0x40)+pixels[65000:])
+ return out + segment(0x80,b'')
+
+ebml = e(0x1A45DFA3,b''.join(e(t,v) for t,v in [(0x4286,1),(0x42F7,1),(0x42F2,4),(0x42F3,8),(0x4282,'matroska'),(0x4287,4),(0x4285,2)]))
+info = e(0x1549A966,e(0x2AD7B1,1000000)+e(0x4489,struct.pack('>d',121000))+e(0x4D80,'Veyra cache regression')+e(0x5741,'Veyra cache regression'))
+tracks = b''
+for i in range(1,6):
+ entry = b''.join(e(t,v) for t,v in [(0xD7,i),(0x73C5,i),(0x83,17),(0x86,'S_HDMV/PGS'),(0x536E,f'PGS cache {i}')])
+ entry += e(0x6D80,e(0x6240,e(0x5031,0)+e(0x5032,1)+e(0x5033,0)+e(0x5034,e(0x4254,0))))
+ tracks += e(0xAE,entry)
+clusters = []
+for seq in range(40):
+ block_time = 1000 + seq*3000
+ cluster = e(0xE7,block_time)
+ for i in range(1,6):
+ block = bytes([0x80|i])+struct.pack('>hB',0,0)+zlib.compress(display(seq))
+ cluster += e(0xA0,e(0xA1,block)+e(0x9B,2000))
+ clusters.append(e(0x1F43B675,cluster))
+target = Path(sys.argv[1]); target.parent.mkdir(parents=True,exist_ok=True)
+target.write_bytes(ebml+e(0x18538067,info+e(0x1654AE6B,tracks)+b''.join(clusters)))
+print(target, target.stat().st_size)
diff --git a/src/engine/Subtitles.cpp b/src/engine/Subtitles.cpp
index b8a92582..5ea097fb 100644
--- a/src/engine/Subtitles.cpp
+++ b/src/engine/Subtitles.cpp
@@ -1,4 +1,6 @@
#include "veyra/engine/Subtitles.h"
+#include "veyra/engine/SubtitleCacheBudget.h"
+#include <cstdlib>
#include "veyra/Log.h"
#include <windows.h>
@@ -504,9 +506,11 @@ static std::vector<SubtitleTrack> loadDemuxedSubtitleTracks(const std::wstring&
if(std::none_of(decoders.begin(),decoders.end(),[](const auto& decoder){return bool(decoder);}))return tracks;
AVPacket* packet=av_packet_alloc();
struct PacketCleanup {AVPacket*& packet;~PacketCleanup(){av_packet_free(&packet);}} packetCleanup{packet};
- constexpr size_t maxCacheBytes=64u*1024u*1024u;
+ const char* cacheSetting=std::getenv("VEYRA_SUBTITLE_CACHE_MB");
+ const size_t maxCacheBytes=size_t(subtitleCacheBudgetBytes(cacheSetting?std::string_view(cacheSetting):std::string_view{}));
+ log::info("subtitle",std::format("compressed cue cache budgetBytes={} (on demand, not preallocated)",maxCacheBytes));
size_t cacheBytes=0,totalCues=0;uint64_t packets=0;
- struct DecodeStats {uint64_t packets=0,displays=0,errors=0;int lastError=0;};
+ struct DecodeStats {uint64_t packets=0,displays=0,errors=0,rejected=0;int lastError=0;};
std::vector<DecodeStats> stats(tracks.size());
int videoWidth=1920,videoHeight=1080;
for(unsigned i=0;i<input->nb_streams;++i)if(input->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_VIDEO){
@@ -583,7 +587,8 @@ static std::vector<SubtitleTrack> loadDemuxedSubtitleTracks(const std::wstring&
cue.bitmap=std::move(frame);
if(totalCues<kMaxCues&&bytes<=maxCacheBytes-cacheBytes){cacheBytes+=bytes;++totalCues;track.cues.push_back(std::move(cue));}
else track.note=L"字幕缓存已达上限,后续字幕未加载";
- }else if(!valid){track.note=L"图形字幕数据无效或超出缓存上限";log::warn("subtitle","bitmap display rejected: invalid rectangle or cache budget");}
+ }else if(!valid){track.note=L"图形字幕数据无效或超出缓存上限";
+ if(++stat.rejected<=3)log::warn("subtitle",std::format("bitmap display rejected stream={} cachedBytes={} budgetBytes={}: invalid rectangle or cache budget",track.streamIndex,cacheBytes,maxCacheBytes));}
}
for(unsigned rect=0;rect<subtitle.num_rects;++rect){
const auto* entry=subtitle.rects[rect];
@@ -633,8 +638,8 @@ static std::vector<SubtitleTrack> loadDemuxedSubtitleTracks(const std::wstring&
else track.note=L"未解码出可显示的字幕";
}
track.rebuildIndex();
- log::info("subtitle",std::format("track stream={} codec={} packets={} displays={} errors={} lastRet={} cues={} note={}",
- track.streamIndex,utf8(track.codec),stat.packets,stat.displays,stat.errors,stat.lastError,track.cues.size(),utf8(track.note)));
+ log::info("subtitle",std::format("track stream={} codec={} packets={} displays={} errors={} rejected={} lastRet={} cues={} note={}",
+ track.streamIndex,utf8(track.codec),stat.packets,stat.displays,stat.errors,stat.rejected,stat.lastError,track.cues.size(),utf8(track.note)));
}
log::info("subtitle",std::format("single-pass complete tracks={} packets={} cues={} cacheBytes={} elapsedMs={:.3f}",tracks.size(),packets,totalCues,cacheBytes,std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-started).count()));
return tracks;
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index 4e8c1d94..c3fcb7ab 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -25,6 +25,7 @@
#include <QCursor>
#include <QScreen>
#include <QWindow>
+#include <QPointer>
#include <QDateTime>
#include <QDir>
@@ -524,6 +525,8 @@ struct QmlPlayerBridge::Impl {
uint64_t gameModeSessionId = 0; // its engine session once the open ran
bool gameModeLive = false, gamePanelOpen = false, gameRefused = false;
bool gameModeShown = false, passthroughShown = false;
+ QRectF gameVideoRect;
+ QPointer<QWindow> gameWindow;
HMONITOR gameMonitor = nullptr;
// The monitored GPU also computes when 设置 -> "同时用这块显卡运算" is on
// and a specific GPU (not 自动) is chosen; otherwise the default order.
@@ -1184,6 +1187,9 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
// The compute GPU decides which effects exist, so it is settled before
// anything below samples the capabilities or restores the saved chain.
impl_->loadPrefs();
+ const auto gameKeys=shortcuts();
+ impl_->game.setHotkeys(ui::gameKey(QKeySequence(gameKeys.value("gamePanel").toString(),QKeySequence::PortableText)),
+ ui::gameKey(QKeySequence(gameKeys.value("gameExit").toString(),QKeySequence::PortableText)));
impl_->enumerateGpuAdapters();
impl_->resolveGpuMonitor();
impl_->applyComputeGpu();
@@ -1220,10 +1226,8 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
switch (event) {
case E::PanelHotkey: emit gameHotkey(0); break;
case E::ExitHotkey: emit gameHotkey(1); break;
- case E::HomeUnavailable:
- emit notice(tr("Home 已被其它软件占用:游戏模式里不能用 Home 呼出调整面板,按 Ctrl+Alt+Home 退出后再调整"), true); break;
case E::ExitUnavailable:
- emit notice(tr("Ctrl+Alt+Home 已被其它软件占用,游戏模式不能穿透操作;关闭占用它的软件后重新全屏"), true); break;
+ emit notice(tr("游戏模式键盘监听启动失败,未开启鼠标穿透;请退出全屏后重试"), true); break;
case E::HangReleased:
// Publish Off before the foreground goes back to Veyra; stay out of
// click-through until fullscreen is left.
@@ -1234,7 +1238,10 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
}
};
auto* gameBeat = new QTimer(this);
- connect(gameBeat, &QTimer::timeout, this, [this] { impl_->game.heartbeat(); });
+ connect(gameBeat, &QTimer::timeout, this, [this] {
+ impl_->game.heartbeat();
+ updateGameGeometry();
+ });
gameBeat->start(250);
#ifdef VEYRA_ENABLE_MOONLIGHT
setupMoonlight();
@@ -2768,30 +2775,37 @@ bool QmlPlayerBridge::startScreenCapture() {
impl_->gameMonitor = window ? MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST) : reinterpret_cast<HMONITOR>(value.target);
impl_->game.setTarget(window, impl_->gameMonitor, !window);
impl_->gameModeUri = value.uri();
- // Two cases the picture cannot cover well, said up front.
+ // Exclusive fullscreen still cannot be covered by another process.
QUERY_USER_NOTIFICATION_STATE state{};
if (SUCCEEDED(SHQueryUserNotificationState(&state)) && state == QUNS_RUNNING_D3D_FULL_SCREEN)
emit notice(tr("检测到独占全屏的游戏:Windows 不允许其它窗口盖在它上面,请把游戏改成无边框窗口或窗口化"), true);
- MONITORINFO monitor{}; monitor.cbSize = sizeof(monitor);
- RECT client{}; POINT origin{};
- if (window && GetMonitorInfoW(impl_->gameMonitor, &monitor) && GetClientRect(window, &client) && ClientToScreen(window, &origin) &&
- (origin.x != monitor.rcMonitor.left || origin.y != monitor.rcMonitor.top ||
- client.right != monitor.rcMonitor.right - monitor.rcMonitor.left || client.bottom != monitor.rcMonitor.bottom - monitor.rcMonitor.top)) {
- veyra::log::info("game-mode", std::format("captured window does not fill its monitor: client={}x{} at {},{}", client.right, client.bottom, origin.x, origin.y));
- emit notice(tr("游戏窗口没有铺满屏幕:画面会放大显示,鼠标点到的位置可能和看到的不一致;建议把游戏设为无边框全屏"), false);
- }
} else impl_->gameModeUri.clear();
veyra::log::info("screen-ui", std::format("start kind={} method={} fps={} cursor={} crop={},{},{},{} fill={} gameMode={}", int(value.kind), int(value.method),
value.fps, value.cursor, value.left, value.top, value.right, value.bottom, o.value("fill").toBool(), game));
openSourceUri(value.uri(), wideOf(screenTargetLabel()));
- impl_->screenFillActive = o.value("fill").toBool();
+ impl_->screenFillActive = !game && o.value("fill").toBool();
impl_->screenFitClient = impl_->screenFitImage = QSize();
rememberSource(QStringLiteral("screen"), screenTargetLabel());
return true;
}
bool QmlPlayerBridge::gameMode() const { return impl_->gameModeSessionId != 0; }
bool QmlPlayerBridge::passthroughActive() const { return impl_->passthroughShown; }
-void QmlPlayerBridge::attachMainWindow(qulonglong nativeHandle) { impl_->game.attach(reinterpret_cast<HWND>(nativeHandle)); }
+QRectF QmlPlayerBridge::gameVideoRect() const { return impl_->gameVideoRect; }
+void QmlPlayerBridge::attachMainWindow(qulonglong nativeHandle) {
+ impl_->game.attach(reinterpret_cast<HWND>(nativeHandle));
+ for (auto* window:QGuiApplication::allWindows())
+ if (qulonglong(window->winId())==nativeHandle) { impl_->gameWindow=window; break; }
+}
+void QmlPlayerBridge::updateGameGeometry() {
+ if (!gameMode() || !impl_->presentation.fullscreen || !impl_->gameWindow) return;
+ const RECT r=impl_->game.pictureBounds();
+ const qreal scale=impl_->gameWindow->devicePixelRatio();
+ if (scale<=0) return;
+ const QRectF rect(r.left/scale,r.top/scale,(r.right-r.left)/scale,(r.bottom-r.top)/scale);
+ if (!rect.isEmpty() && rect!=impl_->gameVideoRect) {
+ impl_->gameVideoRect=rect; emit gameModeChanged();
+ }
+}
void QmlPlayerBridge::setGamePanelOpen(bool open) {
if (impl_->gamePanelOpen == open) return;
impl_->gamePanelOpen = open;
@@ -2837,7 +2851,8 @@ void QmlPlayerBridge::updateGameMode() {
Mode want = Mode::Off;
if (i.gameModeSessionId && i.gameModeLive && i.presentation.fullscreen && !i.gameRefused)
want = i.gamePanelOpen ? Mode::Panel : Mode::Through;
- // A refusal (the exit hotkey is taken) holds until fullscreen is left.
+ if (want!=Mode::Off && i.gameVideoRect.isEmpty()) updateGameGeometry();
+ // A listener failure holds until fullscreen is left.
if (want != Mode::Off && i.game.mode() == Mode::Off && !i.game.arm()) { i.gameRefused = true; want = Mode::Off; }
if (want != i.game.mode()) {
// QML binds the window's click-through flags to passthroughActive: publish
@@ -2847,6 +2862,9 @@ void QmlPlayerBridge::updateGameMode() {
i.game.apply(want);
}
const bool mode = i.gameModeSessionId != 0;
+ if ((!mode || !i.presentation.fullscreen) && !i.gameVideoRect.isEmpty()) {
+ i.gameVideoRect={}; emit gameModeChanged();
+ }
if (mode != i.gameModeShown) { i.gameModeShown = mode; emit gameModeChanged(); }
}
QString QmlPlayerBridge::screenTargetId() const { return impl_->screenTarget; }
@@ -6443,7 +6461,8 @@ void QmlPlayerBridge::refreshAudioDevices() {
namespace {
const QVariantMap& shortcutDefaults() {
static const QVariantMap d{{"playPause", "Space"}, {"fullscreen", "F"}, {"lock", "Ctrl+L"},
- {"hold", "V"}, {"screenshot", "Ctrl+S"}, {"toggleMode", "Tab"}};
+ {"hold", "V"}, {"screenshot", "Ctrl+S"}, {"toggleMode", "Tab"},
+ {"gamePanel", "Home"}, {"gameExit", "Ctrl+Alt+Home"}};
return d;
}
}
@@ -6451,7 +6470,10 @@ QVariantMap QmlPlayerBridge::shortcuts() const {
QVariantMap out = shortcutDefaults();
const auto custom = impl_->prefs.value("shortcuts").toMap();
for (auto it = custom.begin(); it != custom.end(); ++it)
- if (out.contains(it.key())) out[it.key()] = it.value();
+ if (out.contains(it.key())) {
+ if ((it.key()=="gamePanel"||it.key()=="gameExit") && !ui::gameKey(QKeySequence(it.value().toString(),QKeySequence::PortableText)).vk) continue;
+ out[it.key()] = it.value();
+ }
return out;
}
bool QmlPlayerBridge::setShortcut(const QString& action, const QString& sequence) {
@@ -6459,6 +6481,13 @@ bool QmlPlayerBridge::setShortcut(const QString& action, const QString& sequence
const QKeySequence seq(sequence, QKeySequence::PortableText);
if (seq.isEmpty() || seq.count() != 1) { emit notice(tr("无效的按键"), true); return false; }
const QString text = seq.toString(QKeySequence::PortableText);
+ if ((action=="gamePanel"||action=="gameExit") && !ui::gameKey(seq).vk) {
+ emit notice(tr("无效的按键"),true); return false;
+ }
+ if ((action=="gamePanel"||action=="gameExit") &&
+ (text=="Ctrl+Alt+Del"||text=="Alt+Tab"||text=="Alt+F4"||text=="Ctrl+Shift+Esc"||text=="Alt+Enter")) {
+ emit notice(tr("%1 已被固定功能占用").arg(text),true); return false;
+ }
// Keys the shell already owns cannot be taken over.
static const QStringList reserved{"Esc", "F11", "Left", "Right", "Up", "Down", "Ctrl+O", "Ctrl+E",
"B", "Z", "X", "T", "Y", "Shift+Z", "Shift+X", "Alt+Return"};
@@ -6474,6 +6503,9 @@ bool QmlPlayerBridge::setShortcut(const QString& action, const QString& sequence
impl_->prefs["shortcuts"] = custom;
if (!impl_->savePrefs()) { impl_->prefs = previous; emit notice(tr("快捷键保存失败"), true); return false; }
veyra::log::info("ui-prefs", std::format("shortcut {}={}", action.toStdString(), text.toStdString()));
+ const auto keys=shortcuts();
+ impl_->game.setHotkeys(ui::gameKey(QKeySequence(keys.value("gamePanel").toString(),QKeySequence::PortableText)),
+ ui::gameKey(QKeySequence(keys.value("gameExit").toString(),QKeySequence::PortableText)));
emit preferencesChanged();
return true;
}
@@ -6481,6 +6513,7 @@ void QmlPlayerBridge::resetShortcuts() {
const auto previous = impl_->prefs;
impl_->prefs.remove("shortcuts");
if (!impl_->savePrefs()) { impl_->prefs = previous; return; }
+ impl_->game.setHotkeys(ui::gameKey(QKeySequence("Home")),ui::gameKey(QKeySequence("Ctrl+Alt+Home")));
emit preferencesChanged();
}
bool QmlPlayerBridge::obsGameCaptureActive() const { return qApp && qApp->property("veyraObsGameCapture").toBool(); }
@@ -7804,7 +7837,7 @@ void QmlPlayerBridge::setPresentationFullscreen(bool value) {
updateGameMode();
}
double QmlPlayerBridge::previewAspect() const {
- const int mode=impl_->screenFillActive?2:impl_->aspectMode;
+ const int mode=gameMode()&&impl_->presentation.fullscreen?0:impl_->screenFillActive?2:impl_->aspectMode;
if(mode==4)return 16.0/9;if(mode==5)return 4.0/3;if(mode==6)return 21.0/9;
const auto e=impl_->snapshot.metrics.resolution.output;
if(mode==1&&e.height){
@@ -7919,14 +7952,15 @@ void QmlPlayerBridge::setAspectMode(int value) {
}
void QmlPlayerBridge::applyAspect(bool force) {
auto& i = *impl_;
- const int mode = i.screenFillActive ? 2 : i.aspectMode;
+ const bool aligned=gameMode()&&i.presentation.fullscreen;
+ const int mode = aligned ? 0 : i.screenFillActive ? 2 : i.aspectMode;
if (!i.videoWindow) return;
RECT r{}; GetClientRect(i.videoWindow, &r);
const auto e = i.snapshot.metrics.resolution.output;
const QSize client(r.right, r.bottom), image(int(e.width), int(e.height));
if (!force && mode == i.aspectApplied && client == i.screenFitClient && image == i.screenFitImage) return;
i.screenFitClient = client; i.screenFitImage = image; i.aspectApplied = mode;
- auto view=force?engine::PreviewView{}:i.engine.previewView();
+ auto view=force||aligned?engine::PreviewView{}:i.engine.previewView();
view.mode=mode;
const double dar=sourceAspect();
view.displayAspect=dar>0&&image.height()>0&&std::abs(dar-double(image.width())/image.height())>.001?dar:0;
diff --git a/tests/integration/GamePassthroughTests.cpp b/tests/integration/GamePassthroughTests.cpp
new file mode 100644
index 00000000..2b09c5fe
--- /dev/null
+++ b/tests/integration/GamePassthroughTests.cpp
@@ -0,0 +1,75 @@
+#include "veyra/ui/GamePassthrough.h"
+#include <QCoreApplication>
+#include <iostream>
+
+using namespace veyra::ui;
+namespace {
+int failures=0, panels=0, exits=0;
+GameHotkeyListener* listener=nullptr;
+void check(bool ok,const char* text){std::cout<<(ok?"PASS ":"FAIL ")<<text<<std::endl;failures+=!ok;}
+LRESULT CALLBACK proc(HWND w,UINT m,WPARAM wp,LPARAM lp){
+ if(m==GameHotkeyListener::message){if(listener&&listener->current(lp)){if(wp==0)++panels;else if(wp==1)++exits;}return 0;}
+ return DefWindowProcW(w,m,wp,lp);
+}
+void pump(unsigned ms){const auto end=GetTickCount64()+ms;do{MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}Sleep(1);}while(GetTickCount64()<end);}
+bool key(WORD vk,bool up=false){INPUT i{};i.type=INPUT_KEYBOARD;i.ki.wVk=vk;i.ki.dwFlags=up?KEYEVENTF_KEYUP:0;return SendInput(1,&i,sizeof(i))==1;}
+bool send(std::initializer_list<std::pair<WORD,bool>> keys){bool ok=true;for(auto [vk,up]:keys)ok=key(vk,up)&&ok;return ok;}
+void tap(WORD vk){check(send({{vk,false},{vk,true}}),"SendInput reaches our test foreground");pump(80);}
+}
+int main(int argc,char** argv){
+ QCoreApplication app(argc,argv);
+ check(gameKey(QKeySequence("Home"))==GameKey{VK_HOME,0},"default panel maps to Home");
+ check(gameKey(QKeySequence("Ctrl+Alt+Home"))==GameKey{VK_HOME,3},"default exit maps to Ctrl Alt Home");
+ for(const auto* invalid:{"Ctrl", "Meta+F9", "F9, F10", "UnknownKey", "Ctrl++"})check(gameKey(QKeySequence(invalid)).vk==0,"unsupported bindings cannot arm listener");
+ GameKeyState state;const GameKey panel{VK_HOME,0},exit{VK_HOME,3};
+ auto input=[&](unsigned vk,bool down,bool owned=true){return state.input(vk,down,panel,exit,owned);};
+ check(!input('A',true).consume&&!input('A',false).consume,"ordinary typing passes through");
+ check(!input(VK_HOME,true,false).consume&&!input(VK_HOME,false,false).consume,"other programs retain panel key");
+ check(input(VK_HOME,true).action==0&&input(VK_HOME,true).action<0,"held panel key toggles only once");
+ check(input(VK_HOME,false).consume,"claimed key release is paired");
+ input(VK_LCONTROL,true);input(VK_RCONTROL,true);input(VK_LCONTROL,false);input(VK_RMENU,true);
+ check(input(VK_HOME,true).action==1,"right Ctrl remains held after left Ctrl release");
+ check(input(VK_HOME,false).consume,"exit key release is paired");
+ input(VK_RCONTROL,false);input(VK_RMENU,false);input(VK_LSHIFT,true);
+ check(!input(VK_HOME,true).consume,"extra Shift does not trigger plain Home");input(VK_HOME,false);input(VK_LSHIFT,false);
+ GameKeyState changed;changed.input(VK_F9,true,{VK_F9,0},{VK_F10,3},false);
+ changed.input(VK_F9,false,{VK_F8,0},{VK_F10,3},false);
+ check(changed.input(VK_F9,true,{VK_F9,0},{VK_F10,3},true).action==0,"released old binding does not stay latched after rebinding");
+
+ const HWND previous=GetForegroundWindow();
+ WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraGameHotkeyTest";RegisterClassW(&wc);
+ HWND window=CreateWindowW(wc.lpszClassName,L"Veyra hotkey test (temporary)",WS_OVERLAPPEDWINDOW,200,150,800,500,nullptr,nullptr,wc.hInstance,nullptr);
+ HWND target=CreateWindowW(wc.lpszClassName,L"Veyra geometry test",WS_POPUP,350,280,640,360,nullptr,nullptr,wc.hInstance,nullptr);
+ if(!window||!target)return 2;
+ ShowWindow(window,SW_SHOW);SetForegroundWindow(window);pump(40);
+ if(GetForegroundWindow()!=window){const DWORD fg=GetWindowThreadProcessId(GetForegroundWindow(),nullptr),self=GetCurrentThreadId();
+ const bool attached=fg&&fg!=self&&AttachThreadInput(fg,self,TRUE);BringWindowToTop(window);SetForegroundWindow(window);if(attached)AttachThreadInput(fg,self,FALSE);}
+ check(GetForegroundWindow()==window,"input test owns foreground before sending keys");
+ if(GetForegroundWindow()!=window){DestroyWindow(target);DestroyWindow(window);return 1;}
+ {
+ GamePassthrough geometry;geometry.attach(window);geometry.setTarget(target,MonitorFromWindow(target,MONITOR_DEFAULTTONEAREST),false);
+ RECT source{};DwmGetWindowAttribute(target,DWMWA_EXTENDED_FRAME_BOUNDS,&source,sizeof(source));POINT origin{};ClientToScreen(window,&origin);
+ const auto r=geometry.pictureBounds();
+ check(r.left+origin.x==source.left&&r.top+origin.y==source.top&&r.right-r.left==640&&r.bottom-r.top==360,"window picture retains native location and extent");
+ SetWindowPos(target,nullptr,420,300,720,400,SWP_NOACTIVATE|SWP_NOZORDER);const auto moved=geometry.pictureBounds();
+ check(moved.left-r.left==70&&moved.top-r.top==20&&moved.right-moved.left==720,"window move and resize keep physical coordinates");
+ }
+ GameHotkeyListener hook;listener=&hook;hook.bindings({VK_F9,0},{VK_F10,3});
+ check(hook.start(window),"real WH_KEYBOARD_LL installs on its own message thread");hook.panelOwned(true);
+ if(hook.running()){
+ check(send({{VK_F9,false},{VK_F9,false},{VK_F9,true}}),"real repeat input delivered");pump(100);
+ check(panels==1,"real key repeat emits one panel event");
+ hook.panelOwned(false);tap(VK_F9);check(panels==1,"listener leaves panel key to other contexts");hook.panelOwned(true);
+ RAWINPUTDEVICE raw{1,6,RIDEV_NOLEGACY,window};check(RegisterRawInputDevices(&raw,1,sizeof(raw))!=0,"test foreground uses raw keyboard without legacy messages");
+ tap(VK_F9);check(panels==2,"hotkey still arrives with raw keyboard foreground");
+ check(send({{VK_LCONTROL,false},{VK_LMENU,false},{VK_F10,false},{VK_F10,true},{VK_LMENU,true},{VK_LCONTROL,true}}),"custom exit chord delivered");pump(100);
+ check(exits==1,"custom Ctrl Alt F10 exits once");
+ std::thread inputThread([]{Sleep(100);key(VK_F9);key(VK_F9,true);});Sleep(1500);inputThread.join();pump(100);
+ check(panels==3,"keyboard listener survives a busy GUI thread");
+ raw.dwFlags=RIDEV_REMOVE;raw.hwndTarget=nullptr;RegisterRawInputDevices(&raw,1,sizeof(raw));
+ hook.stop();tap(VK_F9);check(panels==3&&!hook.running(),"stopped listener does not consume or trigger keys");
+ check(hook.start(window),"listener can reenter after exit");hook.panelOwned(true);tap(VK_F9);check(panels==4,"new session responds to custom key");hook.stop();
+ }
+ listener=nullptr;DestroyWindow(target);DestroyWindow(window);if(IsWindow(previous))SetForegroundWindow(previous);
+ std::cout<<"TOTAL failures="<<failures<<std::endl;return failures?1:0;
+}
diff --git a/tests/integration/SubtitleCacheTests.cpp b/tests/integration/SubtitleCacheTests.cpp
new file mode 100644
index 00000000..1e75b726
--- /dev/null
+++ b/tests/integration/SubtitleCacheTests.cpp
@@ -0,0 +1,31 @@
+#include "veyra/engine/Subtitles.h"
+#include "veyra/engine/SubtitleCacheBudget.h"
+#include <cstdlib>
+#include <iostream>
+#include <numeric>
+
+int wmain(int argc,wchar_t** argv){
+ using namespace veyra::engine;
+ if(argc!=2)return 2;
+ int failures=0;auto check=[&](bool ok,const char* text){std::cout<<(ok?"PASS ":"FAIL ")<<text<<std::endl;failures+=!ok;};
+ check(subtitleCacheBudgetBytes({})==4294967296ull,"default budget is 4 GiB, not 32-bit overflow to zero");
+ check(subtitleCacheBudgetBytes("65536")==68719476736ull&&subtitleCacheBudgetBytes("1")==1048576ull,"environment boundary values use 64-bit arithmetic");
+ for(auto value:{"0","-1","65537","64junk"," 64","1.5","18446744073709551616"})
+ check(subtitleCacheBudgetBytes(value)==kDefaultSubtitleCacheBytes,"malformed budget falls back safely");
+ _putenv_s("VEYRA_SUBTITLE_CACHE_MB","64");const auto capped=loadEmbeddedSubtitleTracks(argv[1]);
+ _putenv_s("VEYRA_SUBTITLE_CACHE_MB","");const auto complete=loadEmbeddedSubtitleTracks(argv[1]);
+ check(capped.size()==5&&complete.size()==5,"five PGS languages retained in both budget modes");
+ size_t stored=0;unsigned fullTracks=0,cappedTracks=0;
+ for(const auto& t:complete){
+ bool ok=t.usable()&&t.note.empty()&&t.cues.size()==40;
+ if(ok){++fullTracks;const auto last=cuesAt(t,119.0);ok=last.size()==1&&last.front()->bitmap;
+ if(ok){const auto pixels=last.front()->bitmap->images.front().pixels();ok=pixels.size()==512u*192u&&pixels.front()==pixels[2]&&pixels.front()!=pixels[1];}}
+ check(ok,"late subtitle survives beyond old 64 MiB total and expands to authored pixels");
+ for(const auto& cue:t.cues)if(cue.bitmap)for(const auto& image:cue.bitmap->images)stored+=image.runs.size()*sizeof(uint32_t);
+ }
+ for(const auto& t:capped)if(t.cues.size()<40&&!t.note.empty())++cappedTracks;
+ check(stored>64ull*1024*1024&&stored<96ull*1024*1024,"functional fixture crosses old limit with bounded actual cache");
+ check(fullTracks==5&&cappedTracks>0,"same decoder reproduces old cutoff and corrected late cues");
+ std::cout<<"CACHE runBytes="<<stored<<" fullTracks="<<fullTracks<<" oldBudgetTruncated="<<cappedTracks<<" failures="<<failures<<std::endl;
+ return failures?1:0;
+}