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++
ps5-control: PS5 controller-only Remote Play beside the capture card (PR #7, option A)
Veyra Goal Agenta79a7408cb7c
diff --git a/docs/PS5_CAPTURE_CONTROL_2026-10-14.md b/docs/PS5_CAPTURE_CONTROL_2026-10-14.mdnew file mode 100644index 00000000..fd3b8593--- /dev/null+++ b/docs/PS5_CAPTURE_CONTROL_2026-10-14.md@@ -0,0 +1,111 @@+# PS5 手柄控制(采集卡画面 + 远程游玩只传手柄)实施记录 2026-10-14(Claude)++方案见 [PS5_CAPTURE_CONTROL_QML_PLAN_2026-10-14.md](PS5_CAPTURE_CONTROL_QML_PLAN_2026-10-14.md)。用户拍板:“方案A吧,开工!”。+另外两个待定项没有回复,按方案里的推荐执行:++- “后台也转发手柄”默认关;+- 继续做在 `claude/fg-gpu-home-20261014` 上,提交单独成组,需要时可以挑出去。++证据在 `logs/claude-fg-gpu-home-20261014/`。++## 用法++1. 先在「PS5 串流」里配对一次(已有配对可跳过)。+2. 打开「采集卡」,在「PS5 手柄控制」分区打开“用远程游玩控制 PS5”。+ - PS5 主机:和「PS5 串流」共用配对和当前选择;+ - 后台也转发手柄:再串流时建议打开;+ - 手柄:谁按键就用谁,显示当前手柄名和是否有陀螺仪;+ - 登录 PIN:只在 PS5 要求时出现。+3. 点“连接并开始”:采集卡出画,同时连接 PS5,只传手柄。+ - 采集中拨开关:立即连上或断开 PS5,不重连采集卡;+ - 改采集格式重连、信号断了自动重连:PS5 手柄控制不断;+ - “断开”:两个一起停;+ - 打开文件、屏幕捕获、PS5 串流、PC 串流、Xbox:PS5 手柄控制先停。PS5 同一时间只允许一个远程游玩连接,PS5 串流会等它关完再连(最多 10 秒);+ - 失败后点“重连”,或关开一次开关。+4. 再串流给掌机:用 Sunshine / Apollo 等推这台电脑的画面。掌机手柄经串流软件变成电脑上的虚拟手柄,Veyra 读到后转发给 PS5。+ - 记得打开采集卡的“音频监听”,串流软件才收得到声音;+ - 虚拟 DS4 才有陀螺仪和触摸板。++PS5 串流对话框“仅观看”下面加了一行“画面用采集卡”,按钮打开采集卡设置。+主页“采集卡”卡片在开关打开时显示“PS5 手柄”标签。++## 实现++**后端(从 PR #7 移植,按方案第 4 节修正)**++- `RemotePlayConnectDesc.controlOnly` → `RemotePlaySource::discardMedia_` → `ChiakiBackend::start(..., discardMedia)`。+- **视频回调计数后返回 true(收下即丢)。**+ - PR #7 返回 false。读 `chiaki-msvc-stage/lib/src/videoreceiver.c`:false 会让 `frame_index_prev_complete` 停住,下一帧起每帧都 `stream_connection_send_corrupt_frame`,每帧写两条警告。+- **音频挂一个空回调的接收器,不是不挂。**+ - 方案原写“不挂 Opus 接收”。实施前再读 `audioreceiver.c`:没有 `frame_cb` 时,接收器在释放缓冲前就返回,每个音频帧都会泄漏。+ - 现在挂空回调,Chiaki 照常释放缓冲;不初始化 Opus 解码器,不解码。+- `enable_dualsense = !viewOnly || discardMedia`。+- `RemotePlaySessionSource` 控制专用循环:+ - 没有解码器、WASAPI、进度监视线程;+ - 每 4 ms 发一次手柄,等待用高精度可等待计时器(`Sleep(1)` 在默认计时精度下约 15.6 ms);+ - 保活视频回调数增加就算进度喂给 `StreamRecovery`;会话失败(QUIT)直接按失败处理,不等 30 秒;+ - 保留登录 PIN、RP_IN_USE 10/20/40 秒退避、重连提示(“PS5 手柄控制中断,正在重新连接(n/3)…”);+ - 新增 `alive()`、`failed()`。+- 保活档案 720p · 30fps · H.264 · 5 Mbps,只用于这次连接,不写回配对存档。++**引擎**++- `startRemoteControl` / `stopRemoteControl` 投递给专用控制线程(最后一次请求为准),界面线程从不等待主机。+ - 控制线程先关旧会话再开新会话;+ - 连接失败也保留会话对象,状态带出原因。+- `open()`:非采集卡路径停 PS5 手柄控制;采集卡重开不停。+- `openRemotePlay`:先停控制,串流任务里等控制线程关完(最多 10 秒,停止键可打断)。+- `openMoonlight`、`openXbox`、`startExport`:先停控制。+- 析构:先通知控制线程收尾,主线程结束后最多等 8 秒,超时按现有退出看门狗做法结束进程。+- `remotePlayController/Feedback/LoginPin`:有 PS5 串流时给串流,否则给 PS5 手柄控制。+- `remoteControlStatus()`:是否在启动、是否存活、是否已连接、是否要 PIN、是否在重连、失败原因、保活 fps;+ `remoteControlRequested()` 是给 8 ms 手柄定时器用的轻量查询。++**手柄**++- `ControllerInput::setFollowLastPressed`:打开全部手柄,谁按键就读谁。+ - 切换时关掉旧手柄的震动和扳机效果、陀螺仪,清空触摸和陀螺仪状态;+ - 只在“有焦点或允许后台”时切换;+ - 当前手柄拔掉后改读另一个已打开的手柄;+ - 关闭跟随时只保留当前手柄,行为与原来相同。+- `Capabilities.name`:当前手柄名。+- **共享手柄引用计数(顺手修的原有隐患)**:PS5 串流、PC 串流、Xbox 和 PS5 手柄控制共用一个手柄读取器。+ - 原来每个来源的定时器在自己结束时直接 `stop()`;切换来源时,旧来源的定时器可能把新来源刚打开的手柄关掉。+ - 现在每个来源 `acquirePad` / `releasePad`,最后一个释放才停;只有 PS5 手柄控制在用时打开跟随。++**桥接与界面**++- `ps5Control` 属性:可用、开关、后台、状态(off / starting / connected / pin / recovering / failed / nopair)、原因、保活 fps、手柄名、陀螺仪。+- `ps5ControlSet("enabled" | "background", bool)`:偏好 `ps5CaptureControl` / `ps5ControlBackground`。+- `ps5ControlRestart()`;登录 PIN 沿用 `ps5SendLoginPin`。+- 启动时机:+ - `startCaptureSession` 时启动,与采集卡打开并行;+ - 正在 PS5 串流时不在这里启动:串流还占着名额,等采集卡出画后由轮询启动;+ - 开关在采集卡还在打开时拨开的,也由轮询在出画后启动;+ - 失败的会话保持“已请求”,轮询不会反复重连。+- 换主机(任一对话框)时,正在运行的 PS5 手柄控制换到新主机。+- 测试开关(只认 `VEYRA_TEST_` 前缀):+ - `VEYRA_TEST_PS5_CONTROL_HOST`:用一个假配对连这个地址,完全不读已保存的配对,测试只用 192.0.2.1(RFC 5737 文档地址,不可路由);+ - `VEYRA_TEST_PS5_CONTROL_STATE`:只改显示的状态,用来截没有主机时到不了的状态。+- 文案:新增 38 条繁中/英/日;顺手补齐 latency-min 分支留下的 5 条显示同步状态翻译。+ `scripts/i18n/extract.py --check`:缺失 0、占位符问题 0。++## 测试++| 项目 | 结果 | 证据 |+|---|---|---|+| 全部目标构建 | 通过(70 秒);新增代码无警告,已有警告仅来自 MSVC `<utility>` 和 FFmpeg 头文件,与之前构建相同 | `build-20261014-222329` |+| 远程游玩边界测试 | 通过:非法主机拒绝 ×3、控制专用会话失败后 `alive=false`、手柄队列与失焦清空 | `tests-ps5control/boundarydefault.log` |+| 200 次控制专用连接/关闭 | 通过 | `boundary--control-stress.log` |+| 谁按键就用谁(两个 SDL 虚拟手柄) | 通过:按 B 读 B、按 A 读 A、无焦点不切换、拔掉 A 改读 B、关闭跟随后不切换 | `boundary--follow.log` |+| 原有虚拟手柄测试 | 通过 | `boundary--virtual.log` |+| UI 合同、repair | 通过(384 个布局用例;259/0) | `tests-ps5control/` |++(GUI 与回归结果见下节;真机项见“没做 / 待验证”。)++## 没做 / 待验证++- 没有真 PS5 可测:保活画面真实码率、HDMI 输出在远程游玩期间是否保持原分辨率/HDR/120Hz、手柄延迟、登录 PIN、RP_IN_USE 退避,都只能由用户或反馈者实测。+- 没有接入真 ViGEm 虚拟手柄测“谁按键就用谁”,用的是 SDL 虚拟手柄。+- `LivePresentationTests` 的 PS5 用例会连接本机已保存的真实配对,没有运行。+- DualSense 触觉音频在同时连着多个手柄时不转发(原有限制:要求只有一个手柄)。diff --git a/docs/PS5_CAPTURE_CONTROL_QML_PLAN_2026-10-14.md b/docs/PS5_CAPTURE_CONTROL_QML_PLAN_2026-10-14.mdindex edb997b5..6def79ec 100644--- a/docs/PS5_CAPTURE_CONTROL_QML_PLAN_2026-10-14.md+++ b/docs/PS5_CAPTURE_CONTROL_QML_PLAN_2026-10-14.md@@ -1,6 +1,7 @@# PS5 手柄控制 + 采集卡画面:2.0.x 适配方案 2026-10-14(Claude)-> 状态:**只出方案,未实施**。等用户选界面方案(推荐 A)并同意后再动代码。+> 状态:**已按方案 A 实施**(用户:“方案A吧,开工!”),实施记录见 [PS5_CAPTURE_CONTROL_2026-10-14.md](PS5_CAPTURE_CONTROL_2026-10-14.md)。+> 实施时更正一处:音频不能“不挂接收”(Chiaki 没有回调时会泄漏每个音频帧),改为挂空回调。下文保留当时的方案。用户原话:“你看一下 PR7,他可以只串流手柄到电脑上,输出依旧用采集卡,为什么要这个功能呢,有些人想先在电脑处理画面,然后再次串流给掌机或者其他电脑,玩 ps5,这样就可以通过电脑来控制 ps5 的游戏了,但是这个设置 ui 不知道怎么设计比较好,diff --git a/i18n/catalog.json b/i18n/catalog.jsonindex a8506761..15e78e71 100644--- a/i18n/catalog.json+++ b/i18n/catalog.json@@ -16122,6 +16122,307 @@"zh-TW": "如果要開啟 DLSS5(NR),建議幀率設定 60,減少 DLSS5 需要處理的畫面量,減輕負擔","en": "If you turn on DLSS5 (NR), set the frame rate limit to 60: DLSS5 then has fewer frames to process and less load","ja": "DLSS5(NR)を使う場合はフレームレート上限を 60 にしてください。DLSS5 が処理するフレームが減り、負荷が軽くなります"+ },+ {+ "zh": "PS5 主机",+ "src": "qml/DialogHost.qml",+ "zh-TW": "PS5 主機",+ "en": "PS5 console",+ "ja": "PS5 本体"+ },+ {+ "zh": "PS5 仍会发一路 720p 30fps、约 5 Mbps 的保活画面,本机收到即丢弃;PS5 同一时间只允许一个远程游玩连接。再串流时记得打开上面的「音频监听」。",+ "src": "qml/DialogHost.qml",+ "zh-TW": "PS5 仍會發一路 720p 30fps、約 5 Mbps 的保活畫面,本機收到即丟棄;PS5 同一時間只允許一個遠程遊玩連線。再串流時記得打開上面的「音訊監聽」。",+ "en": "The PS5 still sends a 720p 30 fps keepalive picture of about 5 Mbps, which this PC drops on arrival. A PS5 allows one Remote Play connection at a time. When re-streaming, turn on Audio monitoring above.",+ "ja": "PS5 は 720p 30fps・約 5 Mbps の維持用映像を送り続けますが、この PC は受け取ってすぐ破棄します。PS5 のリモートプレイ接続は同時に 1 つだけです。再ストリーミングするときは上の「音声モニター」をオンにしてください。"+ },+ {+ "zh": "PS5 手柄",+ "src": "qml/HomePage.qml",+ "zh-TW": "PS5 手把",+ "en": "PS5 pad",+ "ja": "PS5 コントローラー"+ },+ {+ "zh": "PS5 手柄控制",+ "src": "qml/DialogHost.qml",+ "zh-TW": "PS5 手把控制",+ "en": "PS5 controller control",+ "ja": "PS5 コントローラー操作"+ },+ {+ "zh": "PS5 手柄控制中断,正在重新连接({}/3)…",+ "src": "src/source/RemotePlaySessionSource.cpp",+ "zh-TW": "PS5 手把控制中斷,正在重新連接({}/3)…",+ "en": "PS5 controller control interrupted, reconnecting ({}/3)…",+ "ja": "PS5 コントローラー操作が中断されました。再接続中({}/3)…"+ },+ {+ "zh": "PS5 手柄控制已停止",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "PS5 手把控制已停止",+ "en": "PS5 controller control stopped",+ "ja": "PS5 コントローラー操作を停止しました"+ },+ {+ "zh": "PS5 手柄控制已连接",+ "src": "qml/DialogHost.qml",+ "zh-TW": "PS5 手把控制已連接",+ "en": "PS5 controller control connected",+ "ja": "PS5 コントローラー操作に接続しました"+ },+ {+ "zh": "PS5 手柄控制已连接 · 保活画面 %1 fps(收到即丢弃)",+ "src": "qml/DialogHost.qml",+ "zh-TW": "PS5 手把控制已連接 · 保活畫面 %1 fps(收到即丟棄)",+ "en": "PS5 controller control connected · keepalive picture %1 fps (dropped on arrival)",+ "ja": "PS5 コントローラー操作に接続しました · 維持用映像 %1 fps(受信後すぐ破棄)"+ },+ {+ "zh": "PS5 手柄控制没有恢复,请检查主机及网络后重新打开;无需重新配对。",+ "src": "src/source/RemotePlaySessionSource.cpp",+ "zh-TW": "PS5 手把控制沒有恢復,請檢查主機及網路後重新打開;無需重新配對。",+ "en": "PS5 controller control did not recover; check the console and network, then turn it on again. No need to pair again.",+ "ja": "PS5 コントローラー操作が復帰しませんでした。本体とネットワークを確認してからオンにし直してください。再ペアリングは不要です。"+ },+ {+ "zh": "PS5 手柄控制设置保存失败",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "PS5 手把控制設定儲存失敗",+ "en": "PS5 controller control setting could not be saved",+ "ja": "PS5 コントローラー操作の設定を保存できませんでした"+ },+ {+ "zh": "PS5 手柄控制连接失败,请检查主机及网络;已保存的配对无需重输。",+ "src": "src/source/RemotePlaySessionSource.cpp",+ "zh-TW": "PS5 手把控制連接失敗,請檢查主機及網路;已儲存的配對無需重輸。",+ "en": "PS5 controller control could not connect; check the console and network. Saved pairing does not need to be re-entered.",+ "ja": "PS5 コントローラー操作の接続に失敗しました。本体とネットワークを確認してください。保存済みのペアリングは再入力不要です。"+ },+ {+ "zh": "PS5 手柄控制:还没有配对的 PS5,先在「PS5 串流」里配对一次",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "PS5 手把控制:還沒有配對的 PS5,先在「PS5 串流」裡配對一次",+ "en": "PS5 controller control: no PS5 is paired yet. Pair one once under PS5 streaming",+ "ja": "PS5 コントローラー操作:ペアリング済みの PS5 がありません。先に「PS5 ストリーミング」で一度ペアリングしてください"+ },+ {+ "zh": "PS5 提示时填写,不是 8 位配对码",+ "src": "qml/DialogHost.qml",+ "zh-TW": "PS5 提示時填寫,不是 8 位配對碼",+ "en": "Enter it when the PS5 asks; not the 8-digit pairing code",+ "ja": "PS5 に求められたら入力します。8 桁のペアリングコードではありません"+ },+ {+ "zh": "PS5 的 HDMI 接了采集卡时,可以只用远程游玩传手柄、画面用采集卡原画(可 4K/HDR),也方便再串流给掌机",+ "src": "qml/DialogHost.qml",+ "zh-TW": "PS5 的 HDMI 接了擷取卡時,可以只用遠程遊玩傳手把、畫面用擷取卡原畫(可 4K/HDR),也方便再串流給掌機",+ "en": "With the PS5 HDMI on a capture card, Remote Play can carry only the controller while the picture comes from the capture card (4K/HDR possible), which also suits re-streaming to a handheld",+ "ja": "PS5 の HDMI をキャプチャーカードにつないでいる場合、リモートプレイはコントローラーだけを送り、映像はキャプチャーカードの元映像(4K/HDR 可)を使えます。携帯機への再ストリーミングにも便利です"+ },+ {+ "zh": "PS5 要求输入登录 PIN",+ "src": "qml/DialogHost.qml",+ "zh-TW": "PS5 要求輸入登入 PIN",+ "en": "The PS5 asks for the sign-in PIN",+ "ja": "PS5 がサインイン PIN を求めています"+ },+ {+ "zh": "PS5 要求输入登录 PIN:在采集卡面板「PS5 手柄控制」里填写",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "PS5 要求輸入登入 PIN:在擷取卡面板「PS5 手把控制」裡填寫",+ "en": "The PS5 asks for the sign-in PIN: enter it under PS5 controller control in the capture card panel",+ "ja": "PS5 がサインイン PIN を求めています:キャプチャーカードパネルの「PS5 コントローラー操作」で入力してください"+ },+ {+ "zh": "再串流时建议打开:Veyra 不在前台也继续转发。打开后在这台电脑上用别的程序时,手柄也会操作 PS5",+ "src": "qml/DialogHost.qml",+ "zh-TW": "再串流時建議打開:Veyra 不在前景也繼續轉發。打開後在這台電腦上用別的程式時,手把也會操作 PS5",+ "en": "Recommended when re-streaming: input keeps going while Veyra is not in front. While on, the controller also drives the PS5 when you use other programs on this PC",+ "ja": "再ストリーミングするときはオン推奨:Veyra が前面になくても転送を続けます。オンの間は、この PC で他のソフトを使っていてもコントローラーが PS5 を操作します"+ },+ {+ "zh": "去配对",+ "src": "qml/DialogHost.qml",+ "zh-TW": "去配對",+ "en": "Pair",+ "ja": "ペアリングへ"+ },+ {+ "zh": "后台也转发手柄",+ "src": "qml/DialogHost.qml",+ "zh-TW": "背景也轉發手把",+ "en": "Forward the controller in the background",+ "ja": "バックグラウンドでもコントローラーを転送"+ },+ {+ "zh": "和「PS5 串流」共用配对",+ "src": "qml/DialogHost.qml",+ "zh-TW": "和「PS5 串流」共用配對",+ "en": "Shares pairings with PS5 streaming",+ "ja": "「PS5 ストリーミング」とペアリングを共有"+ },+ {+ "zh": "已在「采集卡」里打开 PS5 手柄控制:连接采集卡时只用远程游玩传手柄",+ "src": "qml/DialogHost.qml",+ "zh-TW": "已在「擷取卡」裡打開 PS5 手把控制:連接擷取卡時只用遠程遊玩傳手把",+ "en": "PS5 controller control is on under Capture card: with the capture card connected, Remote Play carries only the controller",+ "ja": "「キャプチャーカード」で PS5 コントローラー操作がオンです:キャプチャーカード接続中はリモートプレイでコントローラーだけを送ります"+ },+ {+ "zh": "已结束 PS5 手柄控制:PS5 同一时间只允许一个远程游玩连接",+ "src": "src/ui/QmlPlayerBridge.cpp",+ "zh-TW": "已結束 PS5 手把控制:PS5 同一時間只允許一個遠程遊玩連線",+ "en": "PS5 controller control ended: a PS5 allows one Remote Play connection at a time",+ "ja": "PS5 コントローラー操作を終了しました:PS5 のリモートプレイ接続は同時に 1 つだけです"+ },+ {+ "zh": "已连接",+ "src": "qml/DialogHost.qml",+ "zh-TW": "已連接",+ "en": "Connected",+ "ja": "接続済み"+ },+ {+ "zh": "无陀螺仪",+ "src": "qml/DialogHost.qml",+ "zh-TW": "無陀螺儀",+ "en": "no gyro",+ "ja": "ジャイロなし"+ },+ {+ "zh": "有陀螺仪",+ "src": "qml/DialogHost.qml",+ "zh-TW": "有陀螺儀",+ "en": "gyro",+ "ja": "ジャイロあり"+ },+ {+ "zh": "未检测到手柄",+ "src": "qml/DialogHost.qml",+ "zh-TW": "未偵測到手把",+ "en": "No controller detected",+ "ja": "コントローラーが見つかりません"+ },+ {+ "zh": "用远程游玩控制 PS5",+ "src": "qml/DialogHost.qml",+ "zh-TW": "用遠程遊玩控制 PS5",+ "en": "Control the PS5 through Remote Play",+ "ja": "リモートプレイで PS5 を操作"+ },+ {+ "zh": "画面和声音来自采集卡,手柄经 PS5 远程游玩发给主机。把处理后的画面再串流给掌机或别的电脑时,用那边的手柄玩 PS5",+ "src": "qml/DialogHost.qml",+ "zh-TW": "畫面和聲音來自擷取卡,手把經 PS5 遠程遊玩發給主機。把處理後的畫面再串流給掌機或別的電腦時,用那邊的手把玩 PS5",+ "en": "Picture and sound come from the capture card; the controller goes to the console through PS5 Remote Play. When this picture is re-streamed to a handheld or another PC, play the PS5 with the controller there",+ "ja": "映像と音声はキャプチャーカードから、コントローラーは PS5 リモートプレイで本体へ送ります。処理した映像を携帯機や別の PC に再ストリーミングするとき、そちらのコントローラーで PS5 を遊べます"+ },+ {+ "zh": "画面用采集卡",+ "src": "qml/DialogHost.qml",+ "zh-TW": "畫面用擷取卡",+ "en": "Picture from a capture card",+ "ja": "映像はキャプチャーカード"+ },+ {+ "zh": "谁按键就用谁:本机手柄、串流软件建的虚拟手柄都可以",+ "src": "qml/DialogHost.qml",+ "zh-TW": "誰按鍵就用誰:本機手把、串流軟體建的虛擬手把都可以",+ "en": "Whichever controller pressed a button last is used: a controller on this PC or a virtual one made by streaming software",+ "ja": "最後にボタンを押したコントローラーを使います:この PC のコントローラーでも、ストリーミングソフトが作る仮想コントローラーでも可"+ },+ {+ "zh": "还没有配对的 PS5,先在「PS5 串流」里配对一次",+ "src": "qml/DialogHost.qml",+ "zh-TW": "還沒有配對的 PS5,先在「PS5 串流」裡配對一次",+ "en": "No PS5 is paired yet. Pair one once under PS5 streaming",+ "ja": "ペアリング済みの PS5 がありません。先に「PS5 ストリーミング」で一度ペアリングしてください"+ },+ {+ "zh": "连接中",+ "src": "qml/DialogHost.qml",+ "zh-TW": "連接中",+ "en": "Connecting",+ "ja": "接続中"+ },+ {+ "zh": "配对…",+ "src": "qml/DialogHost.qml",+ "zh-TW": "配對…",+ "en": "Pairing…",+ "ja": "ペアリング…"+ },+ {+ "zh": "采集卡设置",+ "src": "qml/DialogHost.qml",+ "zh-TW": "擷取卡設定",+ "en": "Capture card settings",+ "ja": "キャプチャーカード設定"+ },+ {+ "zh": "采集卡连上后自动连接 PS5",+ "src": "qml/DialogHost.qml",+ "zh-TW": "擷取卡連上後自動連接 PS5",+ "en": "Connects to the PS5 once the capture card is connected",+ "ja": "キャプチャーカードの接続後に PS5 へ自動接続します"+ },+ {+ "zh": "重连",+ "src": "qml/DialogHost.qml",+ "zh-TW": "重連",+ "en": "Reconnect",+ "ja": "再接続"+ },+ {+ "zh": "重连中",+ "src": "qml/DialogHost.qml",+ "zh-TW": "重連中",+ "en": "Reconnecting",+ "ja": "再接続中"+ },+ {+ "zh": "需要 PIN",+ "src": "qml/DialogHost.qml",+ "zh-TW": "需要 PIN",+ "en": "PIN needed",+ "ja": "PIN が必要"+ },+ {+ "zh": " + NVIDIA Reflex(实验)",+ "src": "src/engine/VideoPresenter.cpp",+ "zh-TW": " + NVIDIA Reflex(實驗)",+ "en": " + NVIDIA Reflex (experimental)",+ "ja": " + NVIDIA Reflex(実験的)"+ },+ {+ "zh": "可变刷新:超过屏幕最高刷新时只排 1 帧 · ",+ "src": "src/engine/VideoPresenter.cpp",+ "zh-TW": "可變刷新:超過螢幕最高刷新時只排 1 幀 · ",+ "en": "Variable refresh: only 1 frame queued above the display maximum · ",+ "ja": "可変リフレッシュ:画面の最大リフレッシュを超えると 1 フレームだけキュー · "+ },+ {+ "zh": "垂直同步:屏幕队列 1 帧,读帧前等待刷新 · ",+ "src": "src/engine/VideoPresenter.cpp",+ "zh-TW": "垂直同步:螢幕佇列 1 幀,讀幀前等待刷新 · ",+ "en": "VSync: 1-frame display queue, waits for refresh before reading a frame · ",+ "ja": "垂直同期:画面キュー 1 フレーム、フレーム読み込み前にリフレッシュを待機 · "+ },+ {+ "zh": "垂直同步:屏幕队列控制不可用 · ",+ "src": "src/engine/VideoPresenter.cpp",+ "zh-TW": "垂直同步:螢幕佇列控制不可用 · ",+ "en": "VSync: display queue control unavailable · ",+ "ja": "垂直同期:画面キュー制御は使用できません · "+ },+ {+ "zh": "显示队列恢复失败 · ",+ "src": "src/engine/VideoPresenter.cpp",+ "zh-TW": "顯示佇列恢復失敗 · ",+ "en": "Display queue could not be restored · ",+ "ja": "表示キューを復元できませんでした · "}]}diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.hindex 23c51d48..8e35114c 100644--- a/include/veyra/engine/EngineController.h+++ b/include/veyra/engine/EngineController.h@@ -7,6 +7,7 @@#include <condition_variable>#include <functional>#include <memory>+#include <optional>#include "veyra/engine/EnhancementSettings.h"#include "veyra/engine/EffectChain.h"#include "veyra/engine/PresentationSettings.h"@@ -173,6 +174,23 @@ public:remoteplay::ControllerFeedback remotePlayFeedback();void remotePlayController(const remoteplay::ControllerState&);void remotePlayLoginPin(std::string);+ // PS5 手柄控制 beside a capture card: a controller-only Remote Play session+ // (the console's keepalive video and audio are dropped on receipt). Start and+ // stop are queued to a dedicated thread, so callers never wait for the+ // console, and a newer request replaces a queued one. The session survives+ // capture re-opens; opening any other source, or a PS5 stream (the console has+ // one Remote Play slot), stops it. Pad, rumble and login PIN go through the+ // remotePlay* calls above when no PS5 stream runs.+ void startRemoteControl(source::RemotePlayConnectDesc);+ void stopRemoteControl();+ struct RemoteControlStatus{+ bool requested=false; // a start is queued or a session exists+ bool starting=false,alive=false,connected=false,pinRequired=false,recovering=false,failed=false;+ bool keepaliveReady=false;double keepaliveFps=0; // console video samples dropped per second+ std::wstring message;+ };+ RemoteControlStatus remoteControlStatus()const;+ bool remoteControlRequested()const; // cheap: a start is queued or a session exists#endif#ifdef VEYRA_ENABLE_MOONLIGHTvoid openMoonlight(HWND, source::MoonlightConnectDesc, PlayerOptions);@@ -211,12 +229,27 @@ private:void dispatch();void status(const std::wstring&,bool failed=false);void noteEngineHang(uint64_t stalledMs);+#ifdef VEYRA_ENABLE_REMOTEPLAY+ void controlLoop(std::stop_token);+ void waitRemoteControlIdle();+#endifmutable std::mutex mutex_;PlayerSnapshot snapshot_;PresentationSettings presentation_;uint64_t presentationRevision_=1;std::shared_ptr<FrameFlowWindow> activeFlow_;std::shared_ptr<source::RemotePlaySessionSource> activeRemote_;+#ifdef VEYRA_ENABLE_REMOTEPLAY+ std::shared_ptr<source::RemotePlaySessionSource> controlRemote_; // mutex_; PS5 手柄控制+ // controlMutex_ guards the queue below; the session thread never holds it+ // (nor mutex_) while it talks to the console.+ mutable std::mutex controlMutex_;+ std::condition_variable_any controlWake_;+ std::condition_variable controlIdle_;+ std::optional<std::shared_ptr<source::RemotePlayConnectDesc>> controlPending_; // empty pointer = stop+ bool controlBusy_=false,controlStarting_=false,controlExited_=false;+ std::jthread controlThread_; // started on first use; joined (bounded) in the destructor+#endifstd::shared_ptr<source::MoonlightSessionSource> activeMoonlight_;std::shared_ptr<source::XboxSessionSource> activeXbox_;PreviewView previewView_;diff --git a/include/veyra/remoteplay/ChiakiBackend.h b/include/veyra/remoteplay/ChiakiBackend.hindex a569b5e7..76a1548b 100644--- a/include/veyra/remoteplay/ChiakiBackend.h+++ b/include/veyra/remoteplay/ChiakiBackend.h@@ -54,7 +54,11 @@ public:ChiakiBackend& operator=(const ChiakiBackend&)=delete;// All methods, including snapshot(), must be called from one session-owner thread,// NEVER from a Chiaki callback. This object is not a renderer or a decoder.- BackendResult start(const NativeConnectRequest&,SessionInbox::Token);+ // discardMedia (PS5 手柄控制): video samples are counted and accepted without+ // a copy, audio goes to a no-op sink, so Chiaki keeps its reference-frame+ // bookkeeping and never reports a dropped sample to the console as a+ // corrupt frame. The DualSense channel is forced on; feedback is unchanged.+ BackendResult start(const NativeConnectRequest&,SessionInbox::Token,bool discardMedia=false);BackendResult stop(); // Does not call PS5 goto_bed; must precede inbox.finishStop().BackendResult requestIdr();BackendResult submitController(const ControllerState&);diff --git a/include/veyra/remoteplay/ControllerInput.h b/include/veyra/remoteplay/ControllerInput.hindex 8d182e38..763fae7c 100644--- a/include/veyra/remoteplay/ControllerInput.h+++ b/include/veyra/remoteplay/ControllerInput.h@@ -1,6 +1,8 @@#pragma once#include "Types.h"#include <deque>+#include <string>+#include <vector>struct SDL_Gamepad;struct SDL_AudioStream;namespace veyra::remoteplay {@@ -9,16 +11,25 @@ class ControllerInput {public:~ControllerInput(){stop();}bool start(uint32_t preferredDevice=0);- void stop();+ void stop(); // also turns follow mode off+ // 谁按键就用谁 (PS5 手柄控制): every pad is opened and the one whose button went+ // down last is the one read, so a streaming tool's virtual pad that appears+ // after a local pad still works. Off (default): the first pad found.+ void setFollowLastPressed(bool on);ControllerState poll(bool focused);void feedback(ControllerFeedback,bool focused);void releaseEffects();bool calibrate();bool connected()const{return gamepad_!=nullptr;}- struct Capabilities {bool connected=false,gyro=false,accel=false,touch=false,triggers=false,haptics=false,calibrating=false;};+ struct Capabilities {bool connected=false,gyro=false,accel=false,touch=false,triggers=false,haptics=false,calibrating=false;std::string name;};Capabilities capabilities()const;private:+ void activate(SDL_Gamepad*);+ void deactivate();+ bool opened(uint32_t id)const;SDL_Gamepad* gamepad_=nullptr;+ std::vector<SDL_Gamepad*> others_; // follow mode: open, not read+ bool follow_=false;bool initialized_=false;HostTime enumerateAt_=0;uint32_t preferredDevice_=0;std::array<int8_t,2> touchIds_{-1,-1};uint8_t nextTouchId_=0;diff --git a/include/veyra/source/RemotePlaySessionSource.h b/include/veyra/source/RemotePlaySessionSource.hindex ff3e12b8..b85422a7 100644--- a/include/veyra/source/RemotePlaySessionSource.h+++ b/include/veyra/source/RemotePlaySessionSource.h@@ -1,6 +1,7 @@#pragma once#include "RemotePlaySource.h"#include "veyra/sink/CaptureAudioSession.h"+#include <atomic>#include <condition_variable>#include <deque>#include <mutex>@@ -13,6 +14,9 @@ class RemotePlaySessionSource final : public IFrameSource {public:~RemotePlaySessionSource() override { close(); }bool connect(RemotePlayConnectDesc desc);+ // True while the owner loop, including its reconnect retries, still runs.+ bool alive() const { return alive_.load(); }+ bool failed() const { std::lock_guard lock(mutex_); return failed_; }bool open(const SourceOpenDesc&) override { return false; }const SourceInfo& info() const override { return info_; }SourceReadStatus read(pipeline::FramePacket&, const AVFrame**) override;@@ -41,6 +45,7 @@ private:mutable std::mutex mutex_;std::condition_variable ready_;std::jthread owner_;+ std::atomic<bool> alive_{false};bool initialized_=false, started_=false, failed_=false;std::optional<Frame> latest_;std::shared_ptr<AVFrame> view_;diff --git a/include/veyra/source/RemotePlaySource.h b/include/veyra/source/RemotePlaySource.hindex abdb68cf..7025db46 100644--- a/include/veyra/source/RemotePlaySource.h+++ b/include/veyra/source/RemotePlaySource.h@@ -28,6 +28,11 @@ struct RemotePlayConnectDesc {enum class DecodeMode { Automatic, Software, Hardware };DecodeMode decodeMode=DecodeMode::Automatic;bool highQualitySampling=true; // local reconstruction, never a server quality promise+ // PS5 手柄控制 beside a capture card: the controller, feedback and login-PIN+ // channels work as usual, video and audio are dropped on receipt. The+ // protocol has no "stop sending media" switch, so the console still sends a+ // keepalive stream; only this side drops it.+ bool controlOnly=false;// Set by the engine; shared ownership keeps the exact presentation adapter// alive until the decoder owner has stopped, including failed connects.std::shared_ptr<ID3D12Device> decodeDevice;@@ -110,6 +115,7 @@ private:RemotePlayConnectDesc::DecodeMode decodeMode_=RemotePlayConnectDesc::DecodeMode::Automatic;std::shared_ptr<ID3D12Device> decodeDevice_;bool hardwareFallback_=false;+ bool discardMedia_=false;};class RemotePlayAudioSource final : public sink::AudioPcmSource {diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.hindex 75f4d196..9c123b97 100644--- a/include/veyra/ui/QmlPlayerBridge.h+++ b/include/veyra/ui/QmlPlayerBridge.h@@ -181,6 +181,11 @@ class QmlPlayerBridge : public QObject {// forwarding and gyro calibration. `ps5` carries the form state.Q_PROPERTY(QVariantMap ps5 READ ps5 NOTIFY ps5Changed)Q_PROPERTY(QVariantList ps5Profiles READ ps5Profiles NOTIFY ps5Changed)+ // PS5 手柄控制 (采集卡对话框): a controller-only Remote Play session beside the+ // capture card, using the pairing selected in the PS5 dialog. {available,+ // enabled, background, state: off|starting|connected|pin|recovering|failed|+ // nopair, message, keepaliveFps (-1 = not yet), pad, gyro, touch}+ Q_PROPERTY(QVariantMap ps5Control READ ps5Control NOTIFY ps5ControlChanged)// PC streaming (Moonlight / Sunshine): hosts, pairing, apps and stream settings live in// `moonlight` (null when the build has no Moonlight); capture state and the stats overlay here.Q_PROPERTY(QObject* moonlight READ moonlightModel CONSTANT)@@ -666,6 +671,7 @@ public:QVariantMap ps5() const;QVariantList ps5Profiles() const;+ QVariantMap ps5Control() const;QObject* moonlightModel() const;bool moonlightCaptured() const;bool moonlightStatsVisible() const;@@ -690,6 +696,9 @@ public:Q_INVOKABLE void ps5SendLoginPin(const QString& pin);Q_INVOKABLE void ps5Cancel();Q_INVOKABLE void ps5Calibrate();+ // key: enabled | background (saved preferences ps5CaptureControl / ps5ControlBackground).+ Q_INVOKABLE void ps5ControlSet(const QString& key, const QVariant& value);+ Q_INVOKABLE void ps5ControlRestart();QString remotePlayHost() const;void setRemotePlayHost(const QString& value);QString remotePlayPin() const;@@ -1163,6 +1172,7 @@ signals:void playlistRequested();void nodeAnchorsChanged();void ps5Changed();+ void ps5ControlChanged();void moonlightUiChanged();void imageBatchChanged();void audioDevicesChanged();@@ -1237,6 +1247,11 @@ private:void tickImageBatch();void tickCapture();void tickPs5();+ void tickPs5Control(bool force = false);+ // restart: replace a running session (another pairing, or the user asked).+ void startPs5Control(bool restart);+ void stopPs5Control();+ bool captureCardLive() const;void tickMoonlight();void tickXbox();void tickPlaylist();diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qmlindex 8ef09e4e..dff32896 100644--- a/qml/Veyra/DialogHost.qml+++ b/qml/Veyra/DialogHost.qml@@ -235,10 +235,37 @@ Item {}Connections {target: host- function onDialogChanged() { if (host.dialog === "capture") veyra.refreshCaptureDevices() }+ function onDialogChanged() {+ if (host.dialog !== "capture") return+ veyra.refreshCaptureDevices()+ // The PS5 手柄控制 host list is the PS5 dialog's saved pairings.+ if (veyra.ps5Control.available === true) veyra.ps5Load()+ }}function labelOf(list, id, fallback) { const f = list.find(x => String(x.id) === String(id)); return f ? f.label : fallback }readonly property bool live: veyra.captureSignalLevel !== "idle"+ readonly property var pc: veyra.ps5Control+ readonly property bool pcOn: pc.available === true && pc.enabled === true+ readonly property string pcTag: {+ switch (pc.state) {+ case "starting": return qsTr("连接中")+ case "connected": return qsTr("已连接")+ case "recovering": return qsTr("重连中")+ case "pin": return qsTr("需要 PIN")+ case "failed": return qsTr("已停止")+ case "nopair": return qsTr("未配对")+ default: return qsTr("未连接")+ }+ }+ readonly property string pcStatus: {+ switch (pc.state) {+ case "starting": return qsTr("正在连接 PS5…")+ case "connected": return pc.keepaliveFps >= 0 ? qsTr("PS5 手柄控制已连接 · 保活画面 %1 fps(收到即丢弃)").arg(pc.keepaliveFps) : qsTr("PS5 手柄控制已连接")+ case "pin": return qsTr("PS5 要求输入登录 PIN")+ case "recovering": case "failed": case "nopair": return pc.message || ""+ default: return qsTr("采集卡连上后自动连接 PS5")+ }+ }// dialogs.js .cap-prev: the picture and a signal line under it. The// picture is the session's own poster still when the engine made one;@@ -463,6 +490,98 @@ Item {}}}+ // PS5 手柄控制: the capture card stays the picture and the sound; PS5 Remote+ // Play only carries the pad (also from a handheld this picture is re-streamed to).+ DSection { visible: captureDialog.pc.available === true; text: qsTr("PS5 手柄控制") }+ DGroup {+ visible: captureDialog.pc.available === true+ VRow {+ label: qsTr("用远程游玩控制 PS5")+ hint: qsTr("画面和声音来自采集卡,手柄经 PS5 远程游玩发给主机。把处理后的画面再串流给掌机或别的电脑时,用那边的手柄玩 PS5")+ VSwitch {+ objectName: "capture-ps5-control"+ checked: captureDialog.pcOn+ onToggled: checked => veyra.ps5ControlSet("enabled", checked)+ }+ }+ VRow {+ visible: captureDialog.pcOn+ label: qsTr("PS5 主机")+ hint: veyra.ps5Profiles.length === 0 ? qsTr("还没有配对的 PS5,先在「PS5 串流」里配对一次") : qsTr("和「PS5 串流」共用配对")+ RowLayout {+ spacing: 6+ VSelect {+ objectName: "capture-ps5-host"+ visible: veyra.ps5Profiles.length > 0+ implicitWidth: 170+ value: { const p = veyra.ps5Profiles.find(x => x.id === veyra.ps5.profile); return p ? p.label : qsTr("请选择") }+ options: veyra.ps5Profiles+ onPicked: id => veyra.ps5SelectProfile(id)+ }+ VTag {+ objectName: "capture-ps5-state"+ Layout.alignment: Qt.AlignVCenter+ text: captureDialog.pcTag+ kind: captureDialog.pc.state === "connected" ? "ok"+ : captureDialog.pc.state === "failed" || captureDialog.pc.state === "nopair" || captureDialog.pc.state === "pin" ? "warn" : ""+ }+ VButton {+ objectName: "capture-ps5-restart"+ visible: captureDialog.pc.state === "failed"+ text: qsTr("重连"); ghost: true+ onClicked: veyra.ps5ControlRestart()+ }+ VButton {+ objectName: "capture-ps5-pair"+ text: veyra.ps5Profiles.length === 0 ? qsTr("去配对") : qsTr("配对…")+ ghost: true+ onClicked: host.open("ps5")+ }+ }+ }+ VRow {+ visible: captureDialog.pcOn && captureDialog.pc.state === "pin"+ label: qsTr("登录 PIN")+ hint: qsTr("PS5 提示时填写,不是 8 位配对码")+ RowLayout {+ spacing: 6+ VTextField { id: controlPin; objectName: "capture-ps5-pin"; implicitWidth: 120 }+ VButton { text: qsTr("提交"); ghost: true; onClicked: { veyra.ps5SendLoginPin(controlPin.text); controlPin.text = "" } }+ }+ }+ VRow {+ visible: captureDialog.pcOn+ label: qsTr("后台也转发手柄")+ hint: qsTr("再串流时建议打开:Veyra 不在前台也继续转发。打开后在这台电脑上用别的程序时,手柄也会操作 PS5")+ VSwitch {+ objectName: "capture-ps5-background"+ checked: captureDialog.pc.background === true+ onToggled: checked => veyra.ps5ControlSet("background", checked)+ }+ }+ VRow {+ visible: captureDialog.pcOn+ label: qsTr("手柄")+ hint: qsTr("谁按键就用谁:本机手柄、串流软件建的虚拟手柄都可以")+ Text {+ objectName: "capture-ps5-pad"+ text: (captureDialog.pc.pad || "").length > 0+ ? captureDialog.pc.pad + " · " + (captureDialog.pc.gyro === true ? qsTr("有陀螺仪") : qsTr("无陀螺仪"))+ : captureDialog.pc.state === "off" || captureDialog.pc.state === "nopair" ? "—" : qsTr("未检测到手柄")+ color: Theme.t1+ font.family: Theme.fontUi+ font.pixelSize: Theme.fsSmall+ elide: Text.ElideRight+ width: Math.min(implicitWidth, 260)+ }+ }+ }+ DNote {+ objectName: "capture-ps5-note"+ visible: captureDialog.pcOn+ text: (captureDialog.pcStatus.length > 0 ? captureDialog.pcStatus + "\n" : "")+ + qsTr("PS5 仍会发一路 720p 30fps、约 5 Mbps 的保活画面,本机收到即丢弃;PS5 同一时间只允许一个远程游玩连接。再串流时记得打开上面的「音频监听」。")+ }DSection { text: qsTr("格式与画面") }DGroup {VRow {@@ -646,6 +765,15 @@ Item {hint: qsTr("不向 PS5 转发电脑手柄输入")VSwitch { checked: veyra.ps5.viewOnly === true; onToggled: checked => veyra.ps5Set("viewOnly", checked) }}+ // The mirror of 仅观看: only the pad, the picture from a capture card.+ VRow {+ visible: veyra.ps5Control.available === true+ label: qsTr("画面用采集卡")+ hint: veyra.ps5Control.enabled === true+ ? qsTr("已在「采集卡」里打开 PS5 手柄控制:连接采集卡时只用远程游玩传手柄")+ : qsTr("PS5 的 HDMI 接了采集卡时,可以只用远程游玩传手柄、画面用采集卡原画(可 4K/HDR),也方便再串流给掌机")+ VButton { objectName: "ps5-open-capture"; text: qsTr("采集卡设置"); ghost: true; onClicked: host.open("capture") }+ }VRow {label: qsTr("陀螺仪")hint: veyra.ps5.controller ? (veyra.ps5.gyro ? qsTr("手柄支持陀螺仪") : qsTr("手柄没有陀螺仪")) : qsTr("连接串流及电脑手柄后可校准")diff --git a/qml/Veyra/HomePage.qml b/qml/Veyra/HomePage.qmlindex 76a284b7..0c93fd37 100644--- a/qml/Veyra/HomePage.qml+++ b/qml/Veyra/HomePage.qml@@ -183,6 +183,15 @@ VPage {}}}+ // PS5 手柄控制 is switched on for the capture card.+ VTag {+ anchors.top: parent.top+ anchors.right: parent.right+ anchors.margins: 12+ visible: modelData.act === "capture" && veyra.ps5Control.enabled === true+ text: qsTr("PS5 手柄")+ kind: "acc"+ }HoverHandler { id: cardHover; cursorShape: Qt.PointingHandCursor }TapHandler {id: cardTapdiff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cppindex 8ca9adc8..7574a8a7 100644--- a/src/engine/EngineController.cpp+++ b/src/engine/EngineController.cpp@@ -81,6 +81,10 @@ EngineController::EngineController(){worker_=std::thread(&EngineController::dispatch,this);}EngineController::~EngineController(){+#ifdef VEYRA_ENABLE_REMOTEPLAY+ // The PS5 手柄控制 thread starts closing its session now; joined below.+ controlThread_.request_stop();+#endif{std::lock_guard lock(mutex_);shutdown_=true;pending_={};stop_=true;}wake_.notify_one();if(!worker_.joinable()){watchdog_.reset();return;}// Field logs(15): an owner thread blocked inside a driver call never returns,@@ -97,6 +101,20 @@ EngineController::~EngineController(){}}worker_.join();+#ifdef VEYRA_ENABLE_REMOTEPLAY+ if(controlThread_.joinable()){+ const auto closing=Clock::now();+ {std::unique_lock lock(controlMutex_);+ while(!controlIdle_.wait_for(lock,std::chrono::milliseconds(100),[&]{return controlExited_;})){+ if(elapsedMs(closing)<8000.0)continue;+ veyra::log::error("engine-hang","shutdown: PS5 controller-only session still closing after 8 s; ending the process instead of waiting");+ Logger::instance().flush();+ TerminateProcess(GetCurrentProcess(),0);+ }+ }+ controlThread_.join();+ }+#endif// The watchdog callback reads snapshot_ and hangPreviousStatus_. Detach it// while all controller members are still alive, before reverse destruction// reaches hangPreviousStatus_ (declared after watchdog_).@@ -162,6 +180,10 @@ void EngineController::open(HWND video,const std::wstring& path,PlayerOptions op// keep them across the snapshot round-trip below.const bool captureCpuUnpack=opts.captureCpuUnpack;const bool softwareDecode=opts.softwareDecode;const bool hardwareDecodeOnly=opts.hardwareDecodeOnly;+#ifdef VEYRA_ENABLE_REMOTEPLAY+ // PS5 手柄控制 belongs to a capture card source; any other source ends it.+ if(!path.starts_with(L"capture:")&&!path.starts_with(L"capture2:"))stopRemoteControl();+#endif{std::lock_guard lock(mutex_);snapshot_={};requestedPlaybackRate_=1;activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}opts.captureReplayForTest=captureReplay;opts.captureCpuUnpack=captureCpuUnpack;@@ -170,13 +192,82 @@ void EngineController::open(HWND video,const std::wstring& path,PlayerOptions op}#ifdef VEYRA_ENABLE_REMOTEPLAYvoid EngineController::openRemotePlay(HWND window,source::RemotePlayConnectDesc desc,PlayerOptions opts){+ stopRemoteControl();auto request=std::make_shared<source::RemotePlayConnectDesc>(std::move(desc));{std::lock_guard lock(mutex_);snapshot_={};requestedPlaybackRate_=1;activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.remotePlay=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}- post([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"remoteplay:",opts,request);});+ post([this,window,request,opts]{paused_=false;seekSeconds_=-1;waitRemoteControlIdle();run(window,L"remoteplay:",opts,request);});+}+// A PS5 stream (activeRemote_) takes precedence; otherwise PS5 手柄控制.+remoteplay::ControllerFeedback EngineController::remotePlayFeedback(){std::lock_guard lock(mutex_);if(activeRemote_)return activeRemote_->takeFeedback();return controlRemote_?controlRemote_->takeFeedback():remoteplay::ControllerFeedback{};}+void EngineController::remotePlayController(const remoteplay::ControllerState& state){std::lock_guard lock(mutex_);if(activeRemote_)activeRemote_->controller(state);else if(controlRemote_)controlRemote_->controller(state);}+void EngineController::remotePlayLoginPin(std::string pin){std::lock_guard lock(mutex_);if(activeRemote_)activeRemote_->loginPin(std::move(pin));else if(controlRemote_)controlRemote_->loginPin(std::move(pin));}+void EngineController::startRemoteControl(source::RemotePlayConnectDesc desc){+ desc.controlOnly=true;desc.request.viewOnly=false;+ auto request=std::make_shared<source::RemotePlayConnectDesc>(std::move(desc));+ {std::lock_guard lock(controlMutex_);controlPending_=std::move(request);+ if(!controlThread_.joinable())controlThread_=std::jthread([this](std::stop_token stop){controlLoop(stop);});}+ controlWake_.notify_all();+}+void EngineController::stopRemoteControl(){+ {std::lock_guard lock(controlMutex_);if(!controlThread_.joinable())return;+ controlPending_=std::shared_ptr<source::RemotePlayConnectDesc>{};}+ controlWake_.notify_all();+}+void EngineController::controlLoop(std::stop_token stop){+ for(;;){+ std::shared_ptr<source::RemotePlayConnectDesc> request;+ {std::unique_lock lock(controlMutex_);+ if(!controlWake_.wait(lock,stop,[&]{return controlPending_.has_value();}))break;+ request=std::move(*controlPending_);controlPending_.reset();controlBusy_=true;controlStarting_=bool(request);}+ // One Remote Play slot per console: the old session ends before a new one starts.+ std::shared_ptr<source::RemotePlaySessionSource> old;+ {std::lock_guard lock(mutex_);old=std::move(controlRemote_);}+ if(old){const auto closing=Clock::now();old->close();veyra::log::info("remoteplay-control",std::format("controller-only session closed in {:.0f} ms",elapsedMs(closing)));}+ if(request&&!stop.stop_requested()){+ auto session=std::make_shared<source::RemotePlaySessionSource>();+ const bool ok=session->connect(std::move(*request));+ veyra::log::info("remoteplay-control",std::format("controller-only session start ok={} alive={}",ok,session->alive()));+ // Kept even when the start failed: its status carries the reason.+ std::lock_guard lock(mutex_);controlRemote_=std::move(session);+ }+ {std::lock_guard lock(controlMutex_);controlBusy_=controlStarting_=false;}+ controlIdle_.notify_all();+ }+ std::shared_ptr<source::RemotePlaySessionSource> last;+ {std::lock_guard lock(mutex_);last=std::move(controlRemote_);}+ if(last)last->close();+ {std::lock_guard lock(controlMutex_);controlBusy_=controlStarting_=false;controlPending_.reset();controlExited_=true;}+ controlIdle_.notify_all();+}+// A PS5 stream needs the console's only Remote Play slot: wait until the+// controller-only session has closed (bounded, and cut short by Stop).+void EngineController::waitRemoteControlIdle(){+ const auto deadline=Clock::now()+std::chrono::seconds(10);+ std::unique_lock lock(controlMutex_);+ while((controlBusy_||controlPending_.has_value())&&!stop_.load()){+ if(Clock::now()>=deadline){veyra::log::warn("remoteplay-control","controller-only session still closing after 10 s; starting the PS5 stream anyway");return;}+ controlIdle_.wait_for(lock,std::chrono::milliseconds(100));+ }+}+EngineController::RemoteControlStatus EngineController::remoteControlStatus()const{+ RemoteControlStatus out;+ std::shared_ptr<source::RemotePlaySessionSource> session;+ {std::lock_guard lock(mutex_);session=controlRemote_;}+ {std::lock_guard lock(controlMutex_);out.starting=controlStarting_||(controlPending_.has_value()&&*controlPending_);}+ out.requested=out.starting||bool(session);+ if(!session)return out;+ out.alive=session->alive();out.failed=session->failed();+ const auto s=session->sessionSnapshot();+ out.connected=s.state==remoteplay::SessionState::WaitingFirstFrame||s.state==remoteplay::SessionState::Streaming;+ out.pinRequired=s.state==remoteplay::SessionState::LoginPinRequired;+ const auto recovery=session->recoveryStatus();out.recovering=recovery.active;out.message=recovery.message;+ const auto rates=session->rates();out.keepaliveReady=rates.ready;out.keepaliveFps=rates.receivedFps;+ return out;+}+bool EngineController::remoteControlRequested()const{+ {std::lock_guard lock(mutex_);if(controlRemote_)return true;}+ std::lock_guard lock(controlMutex_);return controlStarting_||(controlPending_.has_value()&&*controlPending_);}-remoteplay::ControllerFeedback EngineController::remotePlayFeedback(){std::lock_guard lock(mutex_);return activeRemote_?activeRemote_->takeFeedback():remoteplay::ControllerFeedback{};}-void EngineController::remotePlayController(const remoteplay::ControllerState& state){std::lock_guard lock(mutex_);if(activeRemote_)activeRemote_->controller(state);}-void EngineController::remotePlayLoginPin(std::string pin){std::lock_guard lock(mutex_);if(activeRemote_)activeRemote_->loginPin(std::move(pin));}#endif#ifdef VEYRA_ENABLE_MOONLIGHT// Input goes straight to the session: the shared pointer is copied under the lock, the send is not.@@ -196,6 +287,9 @@ remoteplay::ControllerFeedback EngineController::xboxFeedback(){std::shared_ptr<#endif#ifdef VEYRA_ENABLE_MOONLIGHTvoid EngineController::openMoonlight(HWND window,source::MoonlightConnectDesc desc,PlayerOptions opts){+#ifdef VEYRA_ENABLE_REMOTEPLAY+ stopRemoteControl();+#endifauto request=std::make_shared<source::MoonlightConnectDesc>(std::move(desc));{std::lock_guard lock(mutex_);snapshot_={};requestedPlaybackRate_=1;activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.moonlightActive=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}post([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"moonlight:",opts,{},request);});@@ -203,6 +297,9 @@ void EngineController::openMoonlight(HWND window,source::MoonlightConnectDesc de#endif#ifdef VEYRA_ENABLE_XBOXvoid EngineController::openXbox(HWND window,source::XboxConnectDesc desc,PlayerOptions opts){+#ifdef VEYRA_ENABLE_REMOTEPLAY+ stopRemoteControl();+#endifauto request=std::make_shared<source::XboxConnectDesc>(std::move(desc));{std::lock_guard lock(mutex_);snapshot_={};requestedPlaybackRate_=1;activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.xboxActive=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}post([this,window,request,opts]{paused_=false;seekSeconds_=-1;run(window,L"xbox:",opts,{},{},request);});@@ -271,6 +368,9 @@ void EngineController::startExport(const std::wstring& input,const std::wstring&veyra::log::warn("node-order","export has no runtime node-order transport; request rejected before posting");status(L"节点链尚未接入导出执行器,请切换列表模式后导出",false);return;}+#ifdef VEYRA_ENABLE_REMOTEPLAY+ stopRemoteControl(); // the export replaces the capture run it belonged to+#endifconst auto frozen=opts.snapshot();const int audioStream=opts.audioStreamIndex;post([this,input,output,frozen,audioStream,hevc]{prewarmed_.reset();CoInitializeEx(nullptr,COINIT_MULTITHREADED);auto options=PlayerOptions::from(frozen);options.audioStreamIndex=audioStream;bool ok=exportVideo(input,output,options,hevc,stop_,[this](double p,const std::wstring& s){std::lock_guard lock(mutex_);snapshot_.status=s;snapshot_.position=p;snapshot_.duration=1;snapshot_.running=true;});{std::lock_guard lock(mutex_);snapshot_.running=false;snapshot_.failed=!ok&&!stop_;}CoUninitialize();});}diff --git a/src/remoteplay/ChiakiBackend.cpp b/src/remoteplay/ChiakiBackend.cppindex 1584414b..9a25def7 100644--- a/src/remoteplay/ChiakiBackend.cpp+++ b/src/remoteplay/ChiakiBackend.cpp@@ -62,6 +62,8 @@ struct ChiakiBackend::Impl {std::atomic<uint64_t> callbackRejected=0,transportErrors=0,assemblyErrors=0;std::atomic<int64_t> serverTargetBitrate=-1;std::atomic<uint64_t> qualityReports=0;+ // PS5 手柄控制: set before the session starts, read only by the callbacks.+ bool discardMedia=false;// Only the upstream audio/Opus callback thread reads/writes these fields.std::uint32_t channels=0,rate=0;std::uint64_t sampleIndex=0;@@ -115,6 +117,10 @@ struct ChiakiBackend::Impl {const ChiakiVeyraVideoSampleInfo* info,void* user) noexcept {auto& self=*static_cast<Impl*>(user);if(!self.active.load()||!data||!size||!info)return false;+ // Counted and accepted, never rejected: a false return makes Chiaki drop+ // the reference frame, leave the last complete frame behind and send a+ // corrupt-frame report to the console for every following sample.+ if(self.discardMedia){++self.videoCallbacks;return true;}try{const auto nal=inspectAnnexB({data,size},self.profile.codec);if(!nal.valid || (!nal.hasConfig&&!nal.hasPicture)){++self.callbackRejected;return false;}@@ -131,6 +137,10 @@ struct ChiakiBackend::Impl {const bool accepted=self.token.video(std::move(sample));if(!accepted)++self.callbackRejected;return accepted;}catch(...){self.apiError=-1001;self.token.failed(-1001);return false;}}+ // PS5 手柄控制 plays the capture card's audio. A sink is still attached: with+ // no frame callback Chiaki's audio receiver returns before freeing each+ // buffered frame. Nothing is decoded.+ static void discardAudio(std::uint8_t*,std::size_t,void* user) noexcept {++static_cast<Impl*>(user)->audioCallbacks;}static void opusSettings(std::uint32_t channels,std::uint32_t rate,void* user) noexcept {auto& self=*static_cast<Impl*>(user);// Sample position stays monotonic across repeated Opus headers within@@ -166,11 +176,12 @@ ChiakiBackend::~ChiakiBackend(){}}catch(...){if(p_){p_->active=false;(void)p_.release();}}}-BackendResult ChiakiBackend::start(const NativeConnectRequest& request,SessionInbox::Token token){+BackendResult ChiakiBackend::start(const NativeConnectRequest& request,SessionInbox::Token token,bool discardMedia){if(p_)return {false,-1100,"already_initialized"};if(!validHost(request.host)||request.video.validate()||token.generation()==0)return {false,-1101,"validate_connect"};auto init=initializeChiaki();if(!init.ok)return init;p_=std::make_unique<Impl>(std::move(token));auto& s=*p_;s.host=request.host;s.profile=request.video;+ s.discardMedia=discardMedia;// Verbose formatting has per-packet overhead: enable only for explicit diagnostics.// Callback above whitelists numeric quality fields and never forwards raw text.const bool qualityTrace=std::getenv("VEYRA_TEST_PS5_QUALITY_TRACE")!=nullptr;@@ -184,15 +195,18 @@ BackendResult ChiakiBackend::start(const NativeConnectRequest& request,SessionInrequest.video.fps==30?CHIAKI_VIDEO_FPS_PRESET_30:CHIAKI_VIDEO_FPS_PRESET_60);info.video_profile.codec=request.video.codec==Codec::H264?CHIAKI_CODEC_H264:request.video.codec==Codec::H265Hdr?CHIAKI_CODEC_H265_HDR:CHIAKI_CODEC_H265;info.video_profile.bitrate=request.video.bitrateKbps;- info.video_profile_auto_downgrade=false;info.enable_keyboard=false;info.enable_dualsense=!request.viewOnly;+ info.video_profile_auto_downgrade=false;info.enable_keyboard=false;info.enable_dualsense=!request.viewOnly||discardMedia;info.auto_regist=false;info.packet_loss_max=0.05;info.enable_idr_on_fec_failure=true;const auto code=chiaki_session_init(&s.session,&info,&s.log);wipe(info.regist_key,sizeof(info.regist_key));wipe(info.morning,sizeof(info.morning));wipe(info.psn_account_id,sizeof(info.psn_account_id));if(code!=CHIAKI_ERR_SUCCESS){auto out=s.record(code,"chiaki_session_init");s.token.failed(out.code);p_.reset();return out;}s.initialized=true;- chiaki_opus_decoder_init(&s.opus,&s.log);s.opusInitialized=true;- chiaki_opus_decoder_set_cb(&s.opus,Impl::opusSettings,Impl::opusFrame,&s);- ChiakiAudioSink sink{};chiaki_opus_decoder_get_sink(&s.opus,&sink);chiaki_session_set_audio_sink(&s.session,&sink);+ if(discardMedia){ChiakiAudioSink sink{};sink.user=&s;sink.frame_cb=Impl::discardAudio;chiaki_session_set_audio_sink(&s.session,&sink);}+ else{+ chiaki_opus_decoder_init(&s.opus,&s.log);s.opusInitialized=true;+ chiaki_opus_decoder_set_cb(&s.opus,Impl::opusSettings,Impl::opusFrame,&s);+ ChiakiAudioSink sink{};chiaki_opus_decoder_get_sink(&s.opus,&sink);chiaki_session_set_audio_sink(&s.session,&sink);+ }ChiakiAudioSink hapticSink{};hapticSink.user=&s;hapticSink.frame_cb=Impl::hapticsCallback;chiaki_session_set_haptics_sink(&s.session,&hapticSink);chiaki_session_set_event_cb(&s.session,Impl::eventCallback,&s);diff --git a/src/remoteplay/ControllerInput.cpp b/src/remoteplay/ControllerInput.cppindex d11aa608..2a3c37d7 100644--- a/src/remoteplay/ControllerInput.cpp+++ b/src/remoteplay/ControllerInput.cpp@@ -19,27 +19,59 @@ bool ControllerInput::start(uint32_t preferredDevice){initialized_=SDL_InitSubSystem(SDL_INIT_GAMEPAD);return initialized_;}void ControllerInput::stop(){+ for(auto* pad:others_)SDL_CloseGamepad(pad);+ others_.clear();follow_=false;releaseEffects();if(hapticStream_){SDL_DestroyAudioStream(hapticStream_);hapticStream_=nullptr;}if(audioInitialized_){SDL_QuitSubSystem(SDL_INIT_AUDIO);audioInitialized_=false;}hapticAttempted_=false;touchQueue_.clear();touchState_={};haveGyro_=haveAccel_=false;calibrating_=false;gyroBias_={};enumerateAt_=0;if(gamepad_){SDL_CloseGamepad(gamepad_);gamepad_=nullptr;}if(initialized_){SDL_QuitSubSystem(SDL_INIT_GAMEPAD);initialized_=false;}}+void ControllerInput::setFollowLastPressed(bool on){+ if(!on){for(auto* pad:others_)SDL_CloseGamepad(pad);others_.clear();}+ if(on!=follow_)enumerateAt_=0;+ follow_=on;+}+bool ControllerInput::opened(uint32_t id)const{+ if(gamepad_&&SDL_GetGamepadID(gamepad_)==id)return true;+ return std::any_of(others_.begin(),others_.end(),[id](SDL_Gamepad* pad){return SDL_GetGamepadID(pad)==id;});+}+void ControllerInput::activate(SDL_Gamepad* pad){+ gamepad_=pad;+ touchQueue_.clear();touchState_={};sensorStamp_=0;haveGyro_=haveAccel_=false;gyroBias_={};calibrating_=false;touchIds_={-1,-1};gyro_=SDL_GamepadHasSensor(gamepad_,SDL_SENSOR_GYRO)&&SDL_SetGamepadSensorEnabled(gamepad_,SDL_SENSOR_GYRO,true);+ accel_=SDL_GamepadHasSensor(gamepad_,SDL_SENSOR_ACCEL)&&SDL_SetGamepadSensorEnabled(gamepad_,SDL_SENSOR_ACCEL,true);+ std::string line=std::string("device opened gyro=")+(gyro_?"1":"0")+" accel="+(accel_?"1":"0")+" touchpads="+std::to_string(SDL_GetNumGamepadTouchpads(gamepad_));+ if(follow_){const char* name=SDL_GetGamepadName(gamepad_);line+=std::string(" active (follow last pressed, ")+std::to_string(others_.size()+1)+" open) name="+(name?name:"?");}+ veyra::log::info("remoteplay-input",line);+}+// The pad stops being read: its rumble/trigger effects and haptic stream end.+void ControllerInput::deactivate(){+ releaseEffects();if(hapticStream_){SDL_DestroyAudioStream(hapticStream_);hapticStream_=nullptr;}hapticAttempted_=false;+ if(gamepad_&&SDL_GamepadConnected(gamepad_)){+ if(gyro_)SDL_SetGamepadSensorEnabled(gamepad_,SDL_SENSOR_GYRO,false);+ if(accel_)SDL_SetGamepadSensorEnabled(gamepad_,SDL_SENSOR_ACCEL,false);+ }+}ControllerState ControllerInput::poll(bool focused){ControllerState state;if(!initialized_)return state;SDL_PumpEvents();SDL_UpdateGamepads();// Only this module initializes SDL; drain its input events rather than// accumulating an unconsumed second application event queue.- if(gamepad_&&!SDL_GamepadConnected(gamepad_)){releaseEffects();if(hapticStream_){SDL_DestroyAudioStream(hapticStream_);hapticStream_=nullptr;}hapticAttempted_=false;SDL_CloseGamepad(gamepad_);gamepad_=nullptr;enumerateAt_=0;}+ if(gamepad_&&!SDL_GamepadConnected(gamepad_)){deactivate();SDL_CloseGamepad(gamepad_);gamepad_=nullptr;enumerateAt_=0;}+ if(follow_){+ std::erase_if(others_,[](SDL_Gamepad* pad){if(SDL_GamepadConnected(pad))return false;SDL_CloseGamepad(pad);return true;});+ if(!gamepad_&&!others_.empty()){auto* next=others_.front();others_.erase(others_.begin());activate(next);}+ }const auto now=monotonic100ns();- if(!gamepad_&&now>=enumerateAt_){+ // Follow mode keeps enumerating while a pad is open: a virtual pad created+ // by a streaming tool joins after the local one.+ if((!gamepad_||follow_)&&now>=enumerateAt_){int count=0;auto* ids=SDL_GetGamepads(&count);- for(int i=0;i<count&&!gamepad_;++i)if(!preferredDevice_||ids[i]==preferredDevice_)gamepad_=SDL_OpenGamepad(ids[i]);- if(gamepad_){- touchQueue_.clear();touchState_={};sensorStamp_=0;haveGyro_=haveAccel_=false;gyroBias_={};calibrating_=false;touchIds_={-1,-1};gyro_=SDL_GamepadHasSensor(gamepad_,SDL_SENSOR_GYRO)&&SDL_SetGamepadSensorEnabled(gamepad_,SDL_SENSOR_GYRO,true);- accel_=SDL_GamepadHasSensor(gamepad_,SDL_SENSOR_ACCEL)&&SDL_SetGamepadSensorEnabled(gamepad_,SDL_SENSOR_ACCEL,true);- veyra::log::info("remoteplay-input",std::string("device opened gyro=")+(gyro_?"1":"0")+" accel="+(accel_?"1":"0")+" touchpads="+std::to_string(SDL_GetNumGamepadTouchpads(gamepad_)));+ for(int i=0;i<count&&(follow_||!gamepad_);++i){+ if((preferredDevice_&&ids[i]!=preferredDevice_)||opened(ids[i]))continue;+ auto* pad=SDL_OpenGamepad(ids[i]);if(!pad)continue;+ if(!gamepad_)activate(pad);else others_.push_back(pad);}SDL_free(ids);enumerateAt_=now+10000000;}@@ -49,6 +81,10 @@ ControllerState ControllerInput::poll(bool focused){}SDL_Event event;while(SDL_PollEvent(&event)){+ if(follow_&&focused&&gamepad_&&event.type==SDL_EVENT_GAMEPAD_BUTTON_DOWN&&event.gbutton.which!=SDL_GetGamepadID(gamepad_)){+ const auto it=std::find_if(others_.begin(),others_.end(),[&](SDL_Gamepad* pad){return SDL_GetGamepadID(pad)==event.gbutton.which;});+ if(it!=others_.end()){auto* next=*it;others_.erase(it);deactivate();others_.push_back(gamepad_);activate(next);}+ }if(!focused||!gamepad_)continue;if((event.type==SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN||event.type==SDL_EVENT_GAMEPAD_TOUCHPAD_UP||event.type==SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION)&&event.gtouchpad.which==SDL_GetGamepadID(gamepad_)){const auto& touch=event.gtouchpad;@@ -164,8 +200,9 @@ bool ControllerInput::calibrate(){}ControllerInput::Capabilities ControllerInput::capabilities()const{if(!gamepad_)return {};+ const char* name=SDL_GetGamepadName(gamepad_);return {true,gyro_,accel_,SDL_GetNumGamepadTouchpads(gamepad_)>0,- SDL_GetGamepadType(gamepad_)==SDL_GAMEPAD_TYPE_PS5,hapticStream_!=nullptr,calibrating_};+ SDL_GetGamepadType(gamepad_)==SDL_GAMEPAD_TYPE_PS5,hapticStream_!=nullptr,calibrating_,name?name:""};}}diff --git a/src/source/RemotePlaySessionSource.cpp b/src/source/RemotePlaySessionSource.cppindex 3fbdeaea..e4718d78 100644--- a/src/source/RemotePlaySessionSource.cpp+++ b/src/source/RemotePlaySessionSource.cpp@@ -17,6 +17,7 @@ bool RemotePlaySessionSource::connect(RemotePlayConnectDesc desc) {return started_;}void RemotePlaySessionSource::run(std::stop_token stop, RemotePlayConnectDesc desc) {+ alive_.store(true);RemotePlaySource source;remoteplay::StreamRecovery recovery;bool repeatedTestDisconnect=false;@@ -37,9 +38,66 @@ void RemotePlaySessionSource::run(std::stop_token stop, RemotePlayConnectDesc deconst bool ok=source.connect(desc);if(!ok){retryWasRpInUse=source.nativeSnapshot().startupRetryAllowed;retry=recovery.poll(milliseconds(),false,true)==remoteplay::StreamRecovery::Action::Reconnect;}{std::lock_guard lock(mutex_);publishedInfo_=source.info();if(!initialized_)started_=ok;failed_=!ok&&!retry;initialized_=true;telemetryInbox_=source.telemetryInbox();- if(failed_)recovery_.message=L"PS5 串流连接失败,请检查主机及网络;已保存的配对无需重输。";}+ if(failed_)recovery_.message=desc.controlOnly?L"PS5 手柄控制连接失败,请检查主机及网络;已保存的配对无需重输。":L"PS5 串流连接失败,请检查主机及网络;已保存的配对无需重输。";}ready_.notify_all();- if(ok) {+ if(ok&&desc.controlOnly) {+ // PS5 手柄控制: the capture card is the picture. No decoder, no WASAPI,+ // no mailbox: the backend counts and drops the console's keepalive+ // video, and that count is the progress StreamRecovery watches.+ log::info("remoteplay-control",std::format("controller-only session attempt={} keepalive={}x{}@{} {} kbps (dropped on receipt; the console still sends it)",recovery.reconnects(),desc.request.video.width,desc.request.video.height,desc.request.video.fps,desc.request.video.bitrateKbps));+ // Sleep(1) without a raised timer resolution can take 15.6 ms; the+ // controller is sent every 4 ms, so wait on a high-resolution timer.+ const auto timer=std::unique_ptr<void,decltype(&CloseHandle)>(CreateWaitableTimerExW(nullptr,nullptr,CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,TIMER_ALL_ACCESS),&CloseHandle);+ auto nextController=std::chrono::steady_clock::now();+ auto nextLog=nextController,rateStart=nextController;+ uint64_t previousReceived=receivedBase,lastVideo=0;+ bool connectedLogged=false;+ while(!stop.stop_requested()) {+ std::string pin;+ {std::lock_guard lock(mutex_);pin.swap(pin_);}+ if(!pin.empty()) {+ const auto r=source.submitLoginPin(pin);SecureZeroMemory(pin.data(),pin.size());+ if(!r.ok)log::warn("remoteplay",std::format("{} code={}",r.operation,r.code));+ }+ auto now=std::chrono::steady_clock::now();+ if(now>=nextController) {+ remoteplay::ControllerState controller;+ {std::lock_guard lock(mutex_);controller=takeControllerLocked(remoteplay::monotonic100ns());}+ const auto r=source.submitController(controller);+ if(!r.ok)log::warn("remoteplay",std::format("{} code={}",r.operation,r.code));+ nextController=now+std::chrono::milliseconds(4);+ }+ const auto native=source.nativeSnapshot();+ const auto snapshot=source.sessionSnapshot();+ if(now>=nextLog){nextLog=now+std::chrono::seconds(1);+ log::info("remoteplay-transport",std::format("attempt={} connected={} videoCallbacks={} audioCallbacks={} packetWindowReceived={} packetWindowLost={} upstreamWarnings={} upstreamErrors={} transportErrors={} quitReason={} apiError={} (controller-only; media dropped on receipt)",recovery.reconnects(),native.connected,native.videoCallbacks,native.audioCallbacks,native.packetReceived,native.packetLost,native.warnings,native.errors,native.transportErrors,native.lastQuitReason,native.lastApiError));}+ if(native.connected&&!connectedLogged){connectedLogged=true;log::info("remoteplay-control","console connected; controller channel open");}+ {std::lock_guard lock(mutex_);snapshot_=snapshot;feedback_.merge(source.takeFeedback());+ rates_.received=receivedBase+native.videoCallbacks;+ const double elapsed=std::chrono::duration<double>(now-rateStart).count();+ if(elapsed>=1){rates_.receivedFps=double(rates_.received-previousReceived)/elapsed;rates_.ready=true;previousReceived=rates_.received;rateStart=now;}+ }+ if(native.videoCallbacks>lastVideo) {+ lastVideo=native.videoCallbacks;+ if(recovery.frame(milliseconds()))log::info("remoteplay-recovery",std::format("retry allowance renewed after 30s continuous keepalive; lifetimeAttempts={}",recovery.reconnects()));+ std::lock_guard lock(mutex_);recovery_.active=false;recovery_.message.clear();+ } else {+ // Keyframe actions are ignored: there is no decoder to repair.+ const auto action=recovery.poll(milliseconds(),snapshot.state==remoteplay::SessionState::LoginPinRequired,snapshot.state==remoteplay::SessionState::Failed,native.automaticRetryAllowed,native.startupRetryAllowed);+ if(action==remoteplay::StreamRecovery::Action::Reconnect){retryWasRpInUse=native.startupRetryAllowed;retry=true;break;}+ if(action==remoteplay::StreamRecovery::Action::Fail){+ log::error("remoteplay-recovery",std::format("controller-only recovery stopped attempts={} quitReason={} error={}",recovery.reconnects(),native.lastQuitReason,snapshot.errorCode));+ std::lock_guard lock(mutex_);failed_=true;recovery_.active=false;+ recovery_.message=snapshot.state==remoteplay::SessionState::LoginPinRequired?L"等待 PS5 登录 PIN 超时,请重新连接。":native.startupRetryAllowed?L"PS5 仍被串流会话占用,请结束其他串流或稍后重试;无需重新配对。":!native.automaticRetryAllowed?L"PS5 已结束或拒绝串流,请检查主机状态后重新连接。":L"PS5 手柄控制没有恢复,请检查主机及网络后重新打开;无需重新配对。";+ recovery_.message+=std::format(L"(终止码 {} / 错误 {})",native.lastQuitReason,snapshot.errorCode);break;+ }+ }+ now=std::chrono::steady_clock::now();+ const auto wait=std::clamp<int64_t>(std::chrono::duration_cast<std::chrono::microseconds>(nextController-now).count(),100,4000);+ if(timer){LARGE_INTEGER due;due.QuadPart=-wait*10;if(SetWaitableTimer(timer.get(),&due,0,nullptr,nullptr,FALSE))WaitForSingleObject(timer.get(),20);else Sleep(1);}+ else Sleep(1);+ }+ } else if(ok) {monitor=std::jthread([inbox=source.telemetryInbox()](std::stop_token cancel){while(!cancel.stop_requested()){const auto s=inbox->snapshot();const auto now=remoteplay::monotonic100ns();@@ -151,6 +209,7 @@ void RemotePlaySessionSource::run(std::stop_token stop, RemotePlayConnectDesc destd::lock_guard lock(mutex_);recovery_={true,recovery.episodeRetries(),retryWasRpInUse?std::format(L"PS5 正在释放上一个串流会话,等待后自动重试({}/3)…",recovery.episodeRetries())+ :desc.controlOnly?std::format(L"PS5 手柄控制中断,正在重新连接({}/3)…",recovery.episodeRetries()):std::format(L"串流中断,正在重新连接({}/3)…",recovery.episodeRetries())};latest_.reset();pendingControllers_.clear();controller_={};feedback_={};}@@ -173,6 +232,8 @@ void RemotePlaySessionSource::run(std::stop_token stop, RemotePlayConnectDesc deif(stop.stop_requested())break;}{std::lock_guard lock(mutex_);recovery_.active=false;}+ // run() has no early return: the owner loop and its retries are over.+ alive_.store(false);}void RemotePlaySessionSource::publishDecoded(const AVFrame* frame,pipeline::FramePacket packet,const SourceInfo& info){auto* cloned=av_frame_clone(frame);if(!cloned)throw std::bad_alloc();diff --git a/src/source/RemotePlaySource.cpp b/src/source/RemotePlaySource.cppindex 70ef32a0..677e5152 100644--- a/src/source/RemotePlaySource.cpp+++ b/src/source/RemotePlaySource.cpp@@ -92,6 +92,7 @@ bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)request_.credentials.registrationKey = desc.request.credentials.registrationKey;request_.credentials.sessionKey = desc.request.credentials.sessionKey;decodeMode_=desc.decodeMode;decodeDevice_=desc.decodeDevice;hardwareFallback_=false;+ discardMedia_=desc.controlOnly;origin100ns_ = static_cast<std::uint64_t>(remoteplay::monotonic100ns());try {@@ -104,7 +105,7 @@ bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)auto token = inbox_->begin(static_cast<remoteplay::HostTime>(origin100ns_));inbox_->streamProfile(request_.video);token_ = token; // Keep a second weak token; backend owns the moved copy.- const auto started = backend_.start(request_, token);+ const auto started = backend_.start(request_, token, discardMedia_);if (!started.ok) {veyra::log::error("remoteplay", std::format("{} failed code={}", started.operation, started.code));close();diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cppindex 9a0fecc8..3c567bc1 100644--- a/src/ui/QmlPlayerBridge.cpp+++ b/src/ui/QmlPlayerBridge.cpp@@ -373,8 +373,31 @@ struct QmlPlayerBridge::Impl {std::atomic<bool> ps5Done{false};bool ps5Busy = false;QTimer* controllerTimer = nullptr;+ // PS5 手柄控制 (capture card dialog).+ QTimer* ps5ControlTimer = nullptr;+ QVariantMap ps5ControlState;+ std::wstring ps5ControlProfile; // pairing (or test host) the session was started with+ QString ps5ControlNoticed; // state the last notice was shown for+ int ps5ControlTicks = 0;+ bool ps5ControlNoPair = false; // switched on without a pairing; cleared once pairings exist#ifdef VEYRA_ENABLE_REMOTEPLAYremoteplay::ControllerInput controller;+ // One SDL pad reader shared by PS5 stream, PS5 手柄控制, PC and Xbox streaming.+ // Each user acquires it and only the last release stops it, so the timer of a+ // source that just ended never cuts off the pad the next source started using.+ enum PadUser : unsigned { PadPs5 = 1, PadPs5Control = 2, PadMoonlight = 4, PadXbox = 8 };+ unsigned padUsers = 0;+ bool acquirePad(unsigned user) {+ const bool ok = controller.start(); // no-op once initialized+ padUsers |= user;+ controller.setFollowLastPressed((padUsers & PadPs5Control) != 0);+ return ok;+ }+ void releasePad(unsigned user) {+ padUsers &= ~user;+ if (!padUsers) controller.stop();+ else controller.setFollowLastPressed((padUsers & PadPs5Control) != 0);+ }#endifstd::jthread ps5Worker; // last: joined before what it touches// --- screen capture ---@@ -2475,6 +2498,10 @@ bool QmlPlayerBridge::startCaptureSession() {rememberSource(QStringLiteral("capture"), utf8Of(i.captureVideo[size_t(device)].name));i.prefs["captureFormatLabel"] = utf8Of(format->label);i.savePrefs();+ // Started beside the capture open, not after it. A running PS5 stream still+ // holds the console's slot until the capture replaces it; the tick starts+ // PS5 手柄控制 once the capture card is live instead.+ if (i.prefBool("ps5CaptureControl", false) && !i.snapshot.remotePlay) startPs5Control(false);openSourceUri(path, i.captureVideo[size_t(device)].name);emit snapshotChanged();return true;@@ -2819,13 +2846,13 @@ void QmlPlayerBridge::setupXbox() {#ifdef VEYRA_ENABLE_REMOTEPLAY// The pad is polled on the UI thread at 250 Hz; the session sends changes and a 33 ms heartbeat.if (pad) {- if (!k.controller.start()) veyra::log::warn("xbox-input", "SDL gamepad initialization failed");+ if (!k.acquirePad(Impl::PadXbox)) veyra::log::warn("xbox-input", "SDL gamepad initialization failed");if (!k.xboxTimer) {k.xboxTimer = new QTimer(this);k.xboxTimer->setTimerType(Qt::PreciseTimer);connect(k.xboxTimer, &QTimer::timeout, this, [this] {auto& m = *impl_;- if (!m.snapshot.xboxActive) { m.controller.stop(); m.xboxTimer->stop(); return; }+ if (!m.snapshot.xboxActive) { m.releasePad(Impl::PadXbox); m.xboxTimer->stop(); return; }const bool focused = QGuiApplication::focusWindow() != nullptr;m.engine.xboxController(m.controller.poll(focused));m.controller.feedback(m.engine.xboxFeedback(), focused);@@ -2834,7 +2861,7 @@ void QmlPlayerBridge::setupXbox() {k.xboxTimer->start(4);} else {if (k.xboxTimer) k.xboxTimer->stop();- k.controller.stop();+ k.releasePad(Impl::PadXbox);}#else(void)pad;@@ -2923,13 +2950,13 @@ void QmlPlayerBridge::setupMoonlight() {#ifdef VEYRA_ENABLE_REMOTEPLAY// The pad is polled on the UI thread at 250 Hz and sent only when it changes.if (pad) {- if (!k.controller.start()) veyra::log::warn("moonlight-input", "SDL gamepad initialization failed");+ if (!k.acquirePad(Impl::PadMoonlight)) veyra::log::warn("moonlight-input", "SDL gamepad initialization failed");if (!k.moonlightTimer) {k.moonlightTimer = new QTimer(this);k.moonlightTimer->setTimerType(Qt::PreciseTimer);connect(k.moonlightTimer, &QTimer::timeout, this, [this] {auto& m = *impl_;- if (!m.snapshot.moonlightActive) { m.controller.stop(); m.moonlightTimer->stop(); return; }+ if (!m.snapshot.moonlightActive) { m.releasePad(Impl::PadMoonlight); m.moonlightTimer->stop(); return; }const bool focused = QGuiApplication::focusWindow() != nullptr;m.engine.moonlightController(m.controller.poll(focused));m.controller.feedback(m.engine.moonlightFeedback(), focused);@@ -2938,7 +2965,7 @@ void QmlPlayerBridge::setupMoonlight() {k.moonlightTimer->start(4);} else {if (k.moonlightTimer) k.moonlightTimer->stop();- k.controller.stop();+ k.releasePad(Impl::PadMoonlight);}#else(void)pad;@@ -2999,6 +3026,8 @@ void QmlPlayerBridge::ps5Load() {std::all_of(id.begin(), id.end(), [](wchar_t c) { return (c >= L'0' && c <= L'9') || (c >= L'a' && c <= L'f'); }))add(it->path());}+ // A pairing made or found in the PS5 dialog lets a waiting PS5 手柄控制 start.+ if (!i.ps5ProfileList.isEmpty()) i.ps5ControlNoPair = false;bool known = false;for (const auto& p : i.ps5ProfileList) known = known || p.toMap().value("id").toString() == QString::fromStdWString(i.ps5Profile);if (!known) i.ps5Profile = i.ps5ProfileList.isEmpty() ? std::wstring{} : i.ps5ProfileList.front().toMap().value("id").toString().toStdWString();@@ -3048,6 +3077,7 @@ void QmlPlayerBridge::ps5SelectProfile(const QString& id) {WritePrivateProfileStringW(L"RemotePlay", L"LastProfile", impl_->ps5Profile.c_str(), ps5Settings().c_str());impl_->ps5Status.clear();ps5Load();+ if (impl_->engine.remoteControlRequested()) startPs5Control(true);#elseQ_UNUSED(id);#endif@@ -3148,6 +3178,8 @@ bool QmlPlayerBridge::ps5Connect() {WritePrivateProfileStringW(L"RemotePlay", L"DecodeMode", std::to_wstring(decode).c_str(), ps5Settings().c_str());WritePrivateProfileStringW(L"RemotePlay", L"FineSampling", desc.highQualitySampling ? L"1" : L"0", ps5Settings().c_str());const bool viewOnly = desc.request.viewOnly;+ // The console has one Remote Play slot; the engine ends PS5 手柄控制 first.+ if (i.engine.remoteControlRequested()) emit notice(tr("已结束 PS5 手柄控制:PS5 同一时间只允许一个远程游玩连接"), false);rememberPosition(true);// The session id is cleared with the flag: the previous session's id left over here// ended "opening" on the next snapshot while the old source still ran.@@ -3163,7 +3195,7 @@ bool QmlPlayerBridge::ps5Connect() {// Controller forwarding at 8 ms, as 1.4.4; view-only leaves the pad to the PS5.// Started with the session: the poll stops the pad when no session runs.if (!viewOnly) {- if (!i.controller.start()) veyra::log::warn("remoteplay-input", "SDL gamepad initialization failed");+ if (!i.acquirePad(Impl::PadPs5)) veyra::log::warn("remoteplay-input", "SDL gamepad initialization failed");if (!i.controllerTimer) {i.controllerTimer = new QTimer(this);connect(i.controllerTimer, &QTimer::timeout, this, [this] {@@ -3174,14 +3206,14 @@ bool QmlPlayerBridge::ps5Connect() {j.engine.remotePlayController(j.controller.poll(focused));j.controller.feedback(j.engine.remotePlayFeedback(), focused);} else {- j.engine.remotePlayController({}); j.controller.stop(); j.controllerTimer->stop();+ j.engine.remotePlayController({}); j.releasePad(Impl::PadPs5); j.controllerTimer->stop();}});}i.controllerTimer->start(8);} else {if (i.controllerTimer) i.controllerTimer->stop();- i.controller.stop();+ i.releasePad(Impl::PadPs5);}});i.ps5Watching = true;@@ -3335,6 +3367,163 @@ void QmlPlayerBridge::tickPs5() {}#endifif (changed) emit ps5Changed();+ tickPs5Control();+}++// --- PS5 手柄控制 (capture card dialog) ----------------------------------------+QVariantMap QmlPlayerBridge::ps5Control() const {+ QVariantMap out = impl_->ps5ControlState;+ if (!out.contains(QStringLiteral("state"))) out[QStringLiteral("state")] = QStringLiteral("off");+#ifdef VEYRA_ENABLE_REMOTEPLAY+ out[QStringLiteral("available")] = true;+#else+ out[QStringLiteral("available")] = false;+#endif+ out[QStringLiteral("enabled")] = impl_->prefBool("ps5CaptureControl", false);+ out[QStringLiteral("background")] = impl_->prefBool("ps5ControlBackground", false);+ return out;+}+// liveKind is "ps5", "screen", "moonlight" or "xbox" for those sources; a file+// leaves it alone but does not set snapshot.capture.+bool QmlPlayerBridge::captureCardLive() const {+ const auto& s = impl_->snapshot;+ return impl_->liveKind == QLatin1String("capture") && s.running && s.capture && !s.image && !s.remotePlay;+}+void QmlPlayerBridge::ps5ControlSet(const QString& key, const QVariant& value) {+ static const QHash<QString, QString> keys{{QStringLiteral("enabled"), QStringLiteral("ps5CaptureControl")},+ {QStringLiteral("background"), QStringLiteral("ps5ControlBackground")}};+ if (!keys.contains(key)) return;+ const bool on = value.toBool();+ const auto previous = impl_->prefs;+ impl_->prefs[keys.value(key)] = on;+ if (!impl_->savePrefs()) { impl_->prefs = previous; emit notice(tr("PS5 手柄控制设置保存失败"), true); emit ps5ControlChanged(); return; }+ veyra::log::info("remoteplay-control", std::format("ui {}={}", key.toStdString(), on));+ if (key == QLatin1String("enabled")) {+ impl_->ps5ControlNoPair = false;+ if (!on) stopPs5Control();+ else if (captureCardLive()) startPs5Control(false);+ tickPs5Control(true);+ }+ emit ps5ControlChanged();+}+void QmlPlayerBridge::ps5ControlRestart() {+ if (impl_->prefBool("ps5CaptureControl", false) && captureCardLive()) startPs5Control(true);+}+void QmlPlayerBridge::startPs5Control(bool restart) {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ auto& i = *impl_;+ source::RemotePlayConnectDesc desc;+ std::wstring profile;+ // Tests only: a dummy pairing to this host (an unroutable test address); the+ // saved pairings are not read, so no real console is ever contacted.+ const QString testHost = qEnvironmentVariable("VEYRA_TEST_PS5_CONTROL_HOST");+ if (!testHost.isEmpty()) {+ desc.request.host = testHost.toStdString();+ profile = L"test:" + testHost.toStdWString();+ } else {+ if (i.ps5Profile.empty()) ps5Load();+ auto saved = i.ps5Profile.empty() ? std::nullopt : remoteplay::loadProfile(remoteplay::profileDirectory() / i.ps5Profile);+ if (!saved) {+ i.engine.stopRemoteControl();+ if (!i.ps5ControlNoPair) emit notice(tr("PS5 手柄控制:还没有配对的 PS5,先在「PS5 串流」里配对一次"), true);+ i.ps5ControlNoPair = true;+ tickPs5Control(true);+ return;+ }+ desc.request = std::move(*saved);+ profile = i.ps5Profile;+ }+ const auto running = i.engine.remoteControlStatus();+ if (!restart && running.requested && (running.alive || running.starting) && profile == i.ps5ControlProfile) {+ if (!(i.padUsers & Impl::PadPs5Control)) i.acquirePad(Impl::PadPs5Control);+ if (i.ps5ControlTimer && !i.ps5ControlTimer->isActive()) i.ps5ControlTimer->start(8);+ return;+ }+ // Keepalive profile, the lightest the console accepts. Never written back to the pairing.+ remoteplay::VideoProfile keepalive;+ keepalive.width = 1280; keepalive.height = 720; keepalive.fps = 30; keepalive.bitrateKbps = 5000; keepalive.codec = remoteplay::Codec::H264;+ desc.request.video = keepalive;+ veyra::log::info("remoteplay-control", std::format("start host={} restart={} background={}", desc.request.host, restart, i.prefBool("ps5ControlBackground", false)));+ i.ps5ControlProfile = profile;+ i.ps5ControlNoticed.clear();+ i.ps5ControlNoPair = false;+ i.engine.startRemoteControl(std::move(desc));+ // The pad is read on the UI thread every 8 ms, as for the PS5 stream (the+ // session sends one state per 4 ms and queues the rest).+ if (!i.acquirePad(Impl::PadPs5Control)) veyra::log::warn("remoteplay-input", "SDL gamepad initialization failed");+ if (!i.ps5ControlTimer) {+ i.ps5ControlTimer = new QTimer(this);+ connect(i.ps5ControlTimer, &QTimer::timeout, this, [this] {+ auto& j = *impl_;+ // A PS5 stream polls the pad with its own timer and takes the slot.+ if (j.snapshot.remotePlay || !j.engine.remoteControlRequested()) {+ j.ps5ControlTimer->stop(); j.releasePad(Impl::PadPs5Control); return;+ }+ const bool focused = QGuiApplication::focusWindow() != nullptr || j.prefBool("ps5ControlBackground", false);+ j.engine.remotePlayController(j.controller.poll(focused));+ j.controller.feedback(j.engine.remotePlayFeedback(), focused);+ });+ }+ i.ps5ControlTimer->start(8);+ tickPs5Control(true);+#else+ (void)restart;+#endif+}+void QmlPlayerBridge::stopPs5Control() {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ auto& i = *impl_;+ if (!i.engine.remoteControlRequested()) return;+ veyra::log::info("remoteplay-control", "stop");+ i.engine.stopRemoteControl();+ i.ps5ControlProfile.clear();+ tickPs5Control(true);+#endif+}+void QmlPlayerBridge::tickPs5Control(bool force) {+#ifdef VEYRA_ENABLE_REMOTEPLAY+ auto& i = *impl_;+ if (!force && ++i.ps5ControlTicks % 15) return; // ~4 Hz from the 60 Hz poll+ // Switched on while the capture card was still opening, or the capture came+ // back by itself: start once it is live. A failed session stays requested+ // until the user restarts it, so this never loops.+ if (!force && !i.ps5ControlNoPair && i.prefBool("ps5CaptureControl", false) && captureCardLive() && !i.engine.remoteControlRequested())+ startPs5Control(false);+ const auto st = i.engine.remoteControlStatus();+ QString state = QStringLiteral("off");+ if (i.ps5ControlNoPair && !st.requested) state = QStringLiteral("nopair");+ else if (st.requested) {+ state = st.pinRequired ? QStringLiteral("pin")+ : st.recovering ? QStringLiteral("recovering")+ : st.alive && st.connected ? QStringLiteral("connected")+ : !st.alive && !st.starting ? QStringLiteral("failed")+ : QStringLiteral("starting");+ }+ // Tests only: show a state no console is available to produce here.+ if (const QString forced = qEnvironmentVariable("VEYRA_TEST_PS5_CONTROL_STATE"); !forced.isEmpty() && st.requested) state = forced;+ QVariantMap next;+ next[QStringLiteral("state")] = state;+ next[QStringLiteral("message")] = state == QLatin1String("nopair") ? tr("还没有配对的 PS5,先在「PS5 串流」里配对一次") : uiText(st.message);+ next[QStringLiteral("keepaliveFps")] = st.keepaliveReady ? std::round(st.keepaliveFps) : -1.0;+ const auto c = i.controller.capabilities();+ next[QStringLiteral("pad")] = (i.padUsers & Impl::PadPs5Control) && c.connected ? QString::fromStdString(c.name) : QString();+ next[QStringLiteral("gyro")] = c.gyro && c.accel;+ next[QStringLiteral("touch")] = c.touch;+ if (next == i.ps5ControlState) return;+ i.ps5ControlState = next;+ if (state != i.ps5ControlNoticed) {+ if (state == QLatin1String("connected")) emit notice(tr("PS5 手柄控制已连接"), false);+ else if (state == QLatin1String("pin")) emit notice(tr("PS5 要求输入登录 PIN:在采集卡面板「PS5 手柄控制」里填写"), false);+ else if (state == QLatin1String("failed")) {+ const QString reason = next.value(QStringLiteral("message")).toString();+ emit notice(reason.isEmpty() ? tr("PS5 手柄控制已停止") : reason, true);+ }+ if (state == QLatin1String("connected") || state == QLatin1String("pin") || state == QLatin1String("failed")) i.ps5ControlNoticed = state;+ }+ emit ps5ControlChanged();+#else+ (void)force;+#endif}// --- ps5 dialog --------------------------------------------------------------@@ -5353,6 +5542,7 @@ void QmlPlayerBridge::stopPlayback() {impl_->openingSource = false;impl_->openingSessionId = 0;impl_->engine.stop();+ stopPs5Control();}void QmlPlayerBridge::seekTo(double seconds) { impl_->engine.seek(seconds); }void QmlPlayerBridge::seekBy(double seconds) {diff --git a/tests/remoteplay/ProductBoundaryTests.cpp b/tests/remoteplay/ProductBoundaryTests.cppindex 10ef6f8f..7d7f0541 100644--- a/tests/remoteplay/ProductBoundaryTests.cpp+++ b/tests/remoteplay/ProductBoundaryTests.cpp@@ -46,6 +46,27 @@ static void mailbox(){s.publishDecoded(raw,packet,info);packet.sequence=2;packet.flags=0;s.publishDecoded(raw,packet,info);av_frame_free(&raw);if(s.read(out,&frame)!=SourceReadStatus::Frame||out.sequence!=4||out.sourceEpoch!=(uint64_t(1)<<32)||!pipeline::hasFrameFlag(out.flags,pipeline::FrameFlagBits::Discontinuity))throw std::runtime_error("reconnect keeps application sequence and pending clock reset across mailbox overwrite");}+// PS5 手柄控制 (from PR #7): the same local validation boundary as a stream, an+// owner loop that is over once the connect failed, and the shared pad queue.+// No console is contacted.+static void controlOnlyBoundary(){+ for(int i=0;i<3;++i){+ RemotePlaySessionSource s;RemotePlayConnectDesc request;+ request.controlOnly=true;request.request.host="invalid://host";+ if(s.connect(std::move(request)))throw std::runtime_error("controller-only connect must reject an invalid host");+ if(s.info().opened)throw std::runtime_error("failed controller-only connect must not report opened");+ if(!s.failed())throw std::runtime_error("failed controller-only connect must report failed");+ s.close();+ if(s.alive())throw std::runtime_error("closed controller-only session must not be alive");+ }+ RemotePlaySessionSource s;s.started_=true;+ const auto now=remoteplay::monotonic100ns();+ remoteplay::ControllerState down;down.inputActive=true;down.buttons=remoteplay::ControllerState::Cross;+ s.controller(down);+ if(s.takeControllerLocked(now)!=down)throw std::runtime_error("controller-only pad state must pass through the shared queue");+ s.controller({});+ if(s.takeControllerLocked(now)!=remoteplay::ControllerState{})throw std::runtime_error("focus loss must neutralize the controller-only queue");+}};}@@ -90,8 +111,62 @@ int virtualInput(){input.stop();SDL_CloseJoystick(joystick);SDL_DetachVirtualJoystick(id);SDL_QuitSubSystem(SDL_INIT_GAMEPAD);std::cout<<"VIRTUAL_INPUT motion_touch_lifecycle_focus_feedback_bounded="<<ok<<" REAL_PS5_NOT_TESTED=1\n";return ok?0:23;}+// 谁按键就用谁 (PS5 手柄控制): two virtual pads; the one whose button went down last+// is read. Real pads on the test machine may also be open, so only names of the+// virtual pads are asserted.+int followInput(){+ using namespace veyra::remoteplay;+ if(!SDL_InitSubSystem(SDL_INIT_GAMEPAD))return 30;+ // Distinct unknown product ids: pads with the same vendor/product share one+ // SDL mapping and so one reported name.+ auto attach=[](const char* name,Uint16 product){+ SDL_VirtualJoystickDesc desc;SDL_INIT_INTERFACE(&desc);desc.type=SDL_JOYSTICK_TYPE_GAMEPAD;+ desc.vendor_id=0x1209;desc.product_id=product;desc.name=name;+ desc.naxes=6;desc.nbuttons=15;desc.button_mask=(1u<<15)-1;desc.axis_mask=63;+ return SDL_AttachVirtualJoystick(&desc);+ };+ const auto a=attach("Veyra follow pad A",0x5641),b=attach("Veyra follow pad B",0x5642);if(!a||!b)return 31;+ auto* ja=SDL_OpenJoystick(a);auto* jb=SDL_OpenJoystick(b);if(!ja||!jb)return 32;+ const auto press=[&](SDL_Joystick* j,bool down){SDL_SetJoystickVirtualButton(j,SDL_GAMEPAD_BUTTON_SOUTH,down);};+ ControllerInput input;if(!input.start())return 33;+ input.setFollowLastPressed(true);+ bool ok=true;+ const auto check=[&](bool pass,const char* step){if(!pass)std::cout<<"FOLLOW_STEP_FAILED "<<step<<" active="<<input.capabilities().name<<'\n';ok&=pass;};+ input.poll(true); // opens every pad+ press(jb,true);auto state=input.poll(true);+ check(input.capabilities().name=="Veyra follow pad B"&&(state.buttons&ControllerState::Cross),"press B");+ press(jb,false);input.poll(true);+ press(ja,true);state=input.poll(true);+ check(input.capabilities().name=="Veyra follow pad A"&&(state.buttons&ControllerState::Cross),"press A");+ press(ja,false);input.poll(true);+ // Without focus (and no background permission) a press does not take over.+ press(jb,true);input.poll(false);press(jb,false);input.poll(false);+ check(input.capabilities().name=="Veyra follow pad A","unfocused press B");+ // The read pad leaves: another open pad is read instead.+ SDL_CloseJoystick(ja);SDL_DetachVirtualJoystick(a);input.poll(true);+ check(input.capabilities().connected&&input.capabilities().name!="Veyra follow pad A","detach A");+ // Follow off: a press on another pad no longer switches.+ input.setFollowLastPressed(false);+ const auto before=input.capabilities().name;+ press(jb,true);input.poll(true);press(jb,false);input.poll(true);+ check(input.capabilities().name==before,"follow off");+ input.stop();+ SDL_CloseJoystick(jb);SDL_DetachVirtualJoystick(b);SDL_QuitSubSystem(SDL_INIT_GAMEPAD);+ std::cout<<"FOLLOW_INPUT last_pressed_switch_focus_detach_off="<<ok<<" REAL_PS5_NOT_TESTED=1\n";return ok?0:34;+}int main(int argc,char** argv){if(argc==2&&std::string_view(argv[1])=="--virtual")return virtualInput();+ if(argc==2&&std::string_view(argv[1])=="--follow")return followInput();+ if(argc==2&&std::string_view(argv[1])=="--control-stress"){+ for(int i=0;i<200;++i){+ veyra::source::RemotePlaySessionSource s;veyra::source::RemotePlayConnectDesc request;+ request.controlOnly=true;request.request.host="invalid://host";+ if(s.connect(std::move(request)))return 11;+ s.close();if(s.alive())return 12;+ }+ std::cout<<"CONTROL_STRESS_PASS iterations=200 PS5_NOT_TESTED=1\n";+ return 0;+ }if(argc==2&&std::string_view(argv[1])=="--discover"){const auto report=veyra::remoteplay::discoverLocalPs5({});for(const auto& line:report.diagnostics)std::cout<<line<<'\n';@@ -102,6 +177,7 @@ int main(int argc,char** argv){std::stop_source cancelled;cancelled.request_stop();if(!veyra::remoteplay::discoverLocalPs5(cancelled.get_token()).hosts.empty())return 6;veyra::source::RemotePlaySessionSourceTestAccess::mailbox();+ veyra::source::RemotePlaySessionSourceTestAccess::controlOnlyBoundary();veyra::source::RemotePlaySessionSource source;for(int i=0;i<3;++i){veyra::source::RemotePlayConnectDesc request;request.request.host="invalid://host";@@ -112,6 +188,6 @@ int main(int argc,char** argv){if(!input.start()){std::cerr<<"SDL_GAMEPAD_INITIALIZATION_FAILED\n";return 3;}for(int i=0;i<3;++i)if(input.poll(false)!=veyra::remoteplay::ControllerState{})return 4;input.stop();input.stop();- std::cout<<"REMOTEPLAY_BOUNDARY_PASS invalid_connect_reopen=3 decoded_latest_mailbox=1 SDL_initialized=1 unfocused_neutral=1 PS5_NOT_TESTED=1\n";+ std::cout<<"REMOTEPLAY_BOUNDARY_PASS invalid_connect_reopen=3 decoded_latest_mailbox=1 control_only_boundary=1 SDL_initialized=1 unfocused_neutral=1 PS5_NOT_TESTED=1\n";return 0;}