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++

checkpoint: preserve Remote Play prototype and verified audit before repairs

Veyra Goal Agentbf21bef35700
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4c4fa90f..d13003c4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -409,6 +409,12 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
src/source/NativeCaptureSink.cpp
src/source/MediaFileSource.cpp
src/source/CaptureCardSource.cpp
+ src/source/RemotePlaySource.cpp
+ src/remoteplay/Validation.cpp
+ src/remoteplay/AnnexB.cpp
+ src/remoteplay/Timeline.cpp
+ src/remoteplay/VideoIngress.cpp
+ src/remoteplay/SessionInbox.cpp
)
veyra_apply_warnings(veyra_sources)
target_compile_options(veyra_sources PRIVATE /WX-)
@@ -420,6 +426,18 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_link_libraries(veyra_sources PUBLIC veyra_pipeline veyra_media veyra_base)
target_link_libraries(veyra_sources PRIVATE ${FFMPEG_LIBRARIES} strmiids ole32 oleaut32)
+ # Chiaki is an optional source backend. Keep the normal player build free
+ # of AGPL native symbols unless the caller explicitly provides the pinned
+ # native library/include tree.
+ if(VEYRA_ENABLE_REMOTEPLAY AND VEYRA_REMOTEPLAY_INCLUDE_DIR AND VEYRA_REMOTEPLAY_LIBRARY)
+ target_compile_definitions(veyra_sources PRIVATE VEYRA_ENABLE_REMOTEPLAY=1)
+ target_include_directories(veyra_sources PRIVATE "${VEYRA_REMOTEPLAY_INCLUDE_DIR}")
+ target_link_libraries(veyra_sources PRIVATE "${VEYRA_REMOTEPLAY_LIBRARY}")
+ target_sources(veyra_sources PRIVATE
+ src/remoteplay/ChiakiBackend.cpp
+ src/remoteplay/ChiakiRegistration.cpp)
+ endif()
+
add_executable(veyra_source_tests
tests/integration/MediaFileSourceTests.cpp
)
diff --git a/docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md b/docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md
new file mode 100644
index 00000000..7bebcb74
--- /dev/null
+++ b/docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md
@@ -0,0 +1,591 @@
+# Veyra PS5 Remote Play 集成交接
+
+日期:2026-09-11
+当前分支:`agent/remoteplay-integration`
+代码基线:`0f78cc29f34365589bcd4757e7017236e3ac9cb1`
+开工存档:`checkpoint/remoteplay-preintegration-2026-09-11`
+Chiaki 固定提交:`0e16950165f06e5c3291537c2eeba6e852be7120`
+
+**2026-09-11 二次代码审计修订:本工作树不能作为可用串流功能交付。** 除原交接列出的缺陷,已真实复现 H.264 配置头导致首帧失败,并确认元数据回调被移植过程删去、音频重启丢弃、尺寸和构建复现问题。先读第 18 节的审计与证据,再按第 17 节执行;旧交接的音频 PTS 修法已经纠正。以下“已通过”仅在各自测试范围内成立。
+
+本文是 Remote Play 后续施工的唯一交接入口。`docs/remoteplay/WORKLOG_CODE01.md` 和用户提供包中的报告是历史阶段记录。`NATIVE_GATE.md` 已更新本机状态;“Windows native 未执行”已经过期,但 native 初始化通过不代表视频回调运行或主程序已接通。
+
+## 1. 最终目标
+
+把 PS5 Remote Play 作为 Veyra 的第四种输入源接入现有产品:
+
+```text
+PS5 / Chiaki transport
+ -> compressed H.264/H.265 access units + Opus PCM + controller channel
+ -> RemotePlaySource
+ -> existing EnhanceGraph
+ -> existing realtime scheduler
+ -> existing VideoPresenter
+
+RemotePlay PCM
+ -> dedicated audio owner thread
+ -> existing AudioRenderer / WASAPI
+```
+
+必须复用现有 `FrameSource -> EnhanceGraph -> FrameSink`,不能复制 `EngineController::run()`、增强图、Presenter、NR/SR/FG 或 reset 逻辑。Remote Play 是实时预览源,不进入视频导出路径。
+
+完成状态的含义是:用户能在 Win32 界面配对或选择已保存的 PS5,连接串流,看到视频,听到连续音频,使用手柄,正常停止/重连,并能在同一条 Veyra 增强链上启用 NR/SR/FG。只有 probe 初始化不算完成。
+
+## 2. 当前结论
+
+用户提供的 `C:\Users\123\Desktop\Veyra_RemotePlay_Code_01` 不是可直接交付的 PS5 功能,而是一套质量尚可的协议桥原型。可以继续用,但必须先修数据正确性,再接主程序。
+
+已经成立的事实:
+
+- 固定的 chiaki-ng 源码能在本机 Windows x64/MSVC 下真实编译并链接。
+- `ChiakiBackend` 能调用真实 `chiaki_lib_init()`,不是 stub。
+- 回调边界、有界压缩队列、PCM 队列、代次隔离和基础输入校验已有实现;IDR 请求只接到队列,尚未从 source 转发给 backend,不能称恢复链已经跑通。
+- `RemotePlaySource.cpp` 已经能与 Veyra 的 FFmpeg、source 和 sink 库编译链接。
+- 当前代码没有进入 `EngineController` 或 `AppShell`,所以用户现在仍看不到 Remote Play 入口。
+- 没有 PS5 实机连接、PS5 码流解码、Remote Play 音频播放、手柄、增强、OBS 或延迟验证证据。二次审计新增了本地合成 H.264 经真实 FFmpeg 解码的故障复现,不冒充 PS5 实测。
+
+## 3. 已验证证据
+
+### 3.1 离线核心
+
+当前可执行文件:
+
+```text
+out/remoteplay/core-windows/veyra_remoteplay_core_tests.exe
+```
+
+本次交接前重新运行结果:
+
+```text
+TOTAL 67 PASS 67 FAIL 0
+```
+
+覆盖:输入校验、Base64 Account ID、序号展开、相对时钟、Annex-B 分类、有界视频/PCM 队列、IDR 恢复、EAGAIN 状态机、输入失焦归零和 SessionInbox 生命周期。它不包含完整 FFmpeg 解码、WASAPI、PS5 或 GPU。
+
+### 3.2 Windows 原生 Chiaki 核心
+
+真实构建目录:
+
+```text
+out/remoteplay/native-fresh5
+```
+
+实际环境:
+
+```text
+Generator: Ninja
+Compiler: MSVC 19.44 / Visual Studio 2022 Build Tools
+Build type: Release
+Chiaki stage: C:/Users/123/Desktop/Veyra DLSS Video Player/out/remoteplay/chiaki-msvc-stage
+Clean verification checkout: C:/veyra-deps/chiaki-source
+Static dependency prefix: C:/veyra-deps/remoteplay-installed/x64-windows-static
+```
+
+构建完成 248/248 个步骤。`Testing/Temporary/LastTest.log` 记录:
+
+```text
+rp.native_core_initialization PASS
+REAL_CHIAKI_CORE_INITIALIZED upstream_video_callback=1
+PS5_CONNECTION_NOT_TESTED VIDEO_DECODE_NOT_TESTED WINDOWS_PLAYER_NOT_TESTED
+```
+
+本次交接前直接重跑 `veyra_remoteplay_native_probe.exe`,退出码为 0,输出相同。普通 PowerShell 当前没有把 `ctest.exe` 加入 `PATH`;需要使用 VS Developer PowerShell 或 CMake 自带工具的绝对路径。这不是产品失败。
+
+注意:`upstream_video_callback=1` 是 `native_main.cpp:15` 的固定文字,**不是回调计数**。该 probe 只调用 `initializeChiaki()`、profile preset 和手柄 idle 初始化;没有 start session、注册/触发视频回调、pairing 或输入发送。下一位 Agent 应把文案改成不可能被误解为回调实测成功的标识。
+
+### 3.3 Veyra source 回归
+
+`out/build/x64-release/veyra_source_tests.exe` 本次重跑结果:23 checks,0 failures。它验证现有文件源,没有验证 Remote Play 真码流。
+
+此前主项目已编译出 `veyra_sources.lib` 和 `veyra_engine.lib`。旧的 `veyra.exe` 链接尝试只因正在运行的程序占用目标文件而报 `LNK1104`;下一位 Agent 应使用全新的构建目录,不要关闭用户正在使用的程序。
+
+## 4. 工作树与外部依赖
+
+当前未提交代码改动:
+
+```text
+M CMakeLists.txt
+M include/veyra/pipeline/FramePacket.h
+?? docs/remoteplay/
+?? include/veyra/remoteplay/
+?? include/veyra/source/RemotePlaySource.h
+?? scripts/remoteplay/
+?? services/remoteplay-probe/
+?? src/remoteplay/
+?? src/source/RemotePlaySource.cpp
+?? tests/remoteplay/
+```
+
+本交接还会修改 `docs/WORKLOG.md` 并新增本文。不要 reset、checkout 或重新运行用户包的 `apply.py`;代码已经合入工作树,再跑可能覆盖已经完成的本机修复。
+
+本机依赖位置:
+
+```text
+干净 chiaki-ng checkout:
+ C:\veyra-deps\chiaki-source
+
+只含已审查 MSVC 兼容补丁的 stage:
+ C:\Users\123\Desktop\Veyra DLSS Video Player\out\remoteplay\chiaki-msvc-stage
+
+静态依赖 prefix:
+ C:\veyra-deps\remoteplay-installed\x64-windows-static
+```
+
+干净 checkout 当前 HEAD 已核对为固定提交,tracked status 为空。不要把上述依赖目录、生成物、凭据、PS5 抓包或日志提交到 Git。
+
+## 5. 当前代码职责
+
+| 模块 | 位置 | 当前职责 | 当前状态 |
+|---|---|---|---|
+| 类型与校验 | `include/veyra/remoteplay/Types.h`, `src/remoteplay/Validation.cpp` | 主机、Account ID、PIN、profile、PCM/视频数据结构 | 离线通过 |
+| Annex-B | `src/remoteplay/AnnexB.cpp` | H.264/H.265 config/picture/IDR 分类 | 合成输入通过;真码流未测 |
+| 有界 ingress | `VideoIngress.cpp`, `SessionInbox.cpp` | 代次隔离、积压恢复、IDR 请求、PCM 队列 | 离线通过 |
+| Chiaki 协议桥 | `ChiakiBackend.cpp`, `ChiakiRegistration.cpp` | 会话、回调、Opus、配对、控制输入 | 原生初始化通过;PS5 未测 |
+| Veyra source 适配 | `RemotePlaySource.cpp` | AU -> FFmpeg AVFrame,PCM -> AudioPcmSource | 可编译;存在下列正确性缺陷 |
+| 主引擎 | `EngineController.cpp` | 现有文件/采集/图片增强与呈现 | Remote Play 未接 |
+| UI | `apps/veyra/ui/AppShell.cpp` | 现有本地媒体、采集、专业设置 | Remote Play 未接 |
+| 凭据存储 | 无 | DPAPI profile | 未实现 |
+| 发现/唤醒 | 无 | LAN discovery / wakeup | 未实现 |
+| 手柄 | 只有 `InputGate` | 状态门控 | 设备枚举和轮询未实现 |
+
+## 6. 必须先修的正确性问题
+
+这些问题必须在主程序接线之前修。否则实机联调会把基础数据错误伪装成网络、性能或 PS5 问题。下列 `P0.x` 是原交接步骤编号;本次审计的缺陷优先级和复现状态统一见第 18 节,不能把这些编号当作“已修复”。
+
+### 新增首要阻断:H.264 配置头提交失败(审计 R01,P1)
+
+`read()` 先单独 `submitPacket(configBefore)`,当前 FFmpeg H.264 decoder 对仅 SPS/PPS 的包实际返回 `AVERROR_INVALIDDATA`(`-1094995529`,stderr `no frame!`),source 在首个 AU 提交前就返回 Error。审计使用本地生成的合法 1280×720 H.264:两条 ingress 投递成功,`read_status=2 frame=0`;同样的 SPS/PPS 与首个 AU 合并后 `decoded=1`。
+
+需要为 config 与 AU 建立正确的解码输入契约,例如把配置前缀与首个 AU 组成一个合法包,或在经过 H.264/H.265 真解码验证的初始化流程中设置 extradata。不能单纯吞掉所有 INVALIDDATA 当作成功。恢复/更换配置时同样适用。首先添加能够复现当前首帧失败的 source 测试,再修实现。
+
+### P0.1 PCM 尾部被永久丢弃
+
+位置:`src/source/RemotePlaySource.cpp` 的 `pullAudio()`,约 320 行。
+
+当前每次从 `SessionInbox` 取出整个 `PcmBlock`,只复制调用者还需要的帧。如果输出缓冲比块小,未复制的块尾直接丢失。必须给 `RemotePlaySource` 增加当前 PCM block 和帧偏移 cursor,例如:
+
+```cpp
+std::optional<remoteplay::PcmBlock> audioBlock_;
+std::size_t audioOffsetFrames_ = 0;
+```
+
+一个 block 必须被完整消费后才能弹下一个。discontinuity 到来时不要在一次 `pull()` 中跨越两个时间段拼接;返回当前段,让 AudioRenderer 下一次拉取并重新锚定或显式 reset。
+
+### P0.2 音频 PTS 和视频 PTS 零点不一致
+
+位置:`pullAudio()` 约 329 行。
+
+视频 `RemotePlayClock::video()` 输出相对 common origin 的 100ns PTS;音频当前把 `commonOrigin100ns` 绝对值再次加回,得到 steady-clock 绝对时间。两条时间线不能比较。
+
+**撤回旧交接的逐块 `audioPts(firstSample, rate, arrival100ns)` 建议。** 这个函数的第三参数是固定的 `audioStart`;每块都传当前 arrival,会同时加上到达时间增长与累计样本增长,重复计时。实际离线演示中,两块相隔 10ms、样本数增加 480,计算结果却增加 20ms。
+
+每个连续音频段固定一个起始锚点:首块到达的共同相对时间对应首样本序号,后续只加 `(block.firstSample - firstBlockSample + cursor) / rate`。arrival 仅用于首锚、网络断点和诊断,不逐块追逐到达抖动。由于到达时间不是远端音视频采样时间,仍需实机校准/估计固定相对偏移;“共用 steady-clock origin”本身不证明物理同步。首块采样序号可能非零,恢复时要同时保存段起始序号。
+
+### P0.3 decoder 重建会覆盖 `decoderFrame_`
+
+位置:`openDecoder()` 约 135-174 行。
+
+编码或尺寸变化时先释放 `codecContext_`,随后直接把新 `av_frame_alloc()` 赋给旧 `decoderFrame_`。旧 frame 需要先 `av_frame_free(&decoderFrame_)`。失败路径也要保持对象可再次连接。
+
+### P0.4 首帧状态永远没有进入 Streaming
+
+位置:`read()` 约 300-311 行。
+
+第一张 AVFrame 成功交付后必须调用:
+
+```cpp
+inbox_->decodedFrameReady(sample.generation);
+```
+
+只在对应 generation 的第一张真实解码帧上调用。`waitingForFirstFrame_` 应成为这个一次性门控,或者删除并用明确状态替代。不能在收到压缩包时提前标记 Streaming。
+
+### P0.5 IDR 请求没有送回 PS5
+
+`VideoIngress` 会在丢包、积压或配置变化时设置 IDR 请求,但 `RemotePlaySource` 从不消费 `inbox_->takeIdrRequest(now)`。
+
+会话 owner 线程必须周期性检查并调用 `backend_.requestIdr()`。记录固定操作名和错误码,不记录未过滤的 Chiaki 原始文本。调用必须留在创建 `ChiakiBackend` 的同一线程。
+
+### P0.6 解码输出 PTS 错配
+
+位置:`submitPacket()` / `drainDecoder()`,约 206-259 行。
+
+当前把 `sourceIndex` 写入 `AVPacket::pts`,但 `drainDecoder()` 无条件使用“当前输入包”的 `sourcePacket`。有 B 帧、decoder delay、EAGAIN drain 或单包多帧时,输出可能对应更早的包。
+
+应维护严格有界的输入 timestamp/packet 元数据表,以 `AVFrame::best_effort_timestamp` / `frame->pts` 按真实解码契约查回对应输入 packet,并设置一致的 `pkt_timebase`。没有匹配时显式失败或按已定义的估计策略处理、标记 LocalEstimated,不能静默套用当前包或把重建值称为真实源 PTS。多帧输出的时间必须有可验证来源;同 timestamp 不能直接复制成几帧相同 PTS。flush、config change、stop、reconnect 时清空 timestamp 历史。
+
+建议不要只用 `std::map<int64_t, FramePacket>`:同 timestamp 可能有多帧。用带上限的 deque entry,包含 timestamp、基础 packet 和已发出子帧数;上限与 decoder reorder 深度绑定,异常超限触发 reset/IDR。
+
+### P0.7 Opus 采样率契约过宽
+
+位置:`src/remoteplay/ChiakiBackend.cpp` 的 `opusSettings()`,约 94 行。
+
+现有 WASAPI 路径固定 48 kHz,backend 却接受 8 kHz 到 192 kHz。当前最小安全实现只接受 1/2 声道和 48000 Hz;其他 rate 明确失败。后续若确有非 48 kHz 设备证据,再增加 libswresample,不要假定 AudioRenderer 会自动重采样。
+
+### P0.8 stop 和失败状态需要完整覆盖
+
+当前正确顺序已经改为:
+
+```text
+inbox.invalidate
+ -> backend.stop / chiaki_session_stop + join + fini
+ -> inbox.finishStop
+```
+
+这只是正常成功路径的顺序,**当前失败路径不正确**:`close()` 丢弃 `backend_.stop()` 返回值后无条件 finishStop 并清空 token;wrong-owner/join 失败时旧 session 可能仍存在。必须确认 stop/join/fini 的实际结果,失败留在明确故障状态,不得宣称 Idle 或开启新会话。新增音频、手柄和 pairing worker 后,先停止输入和音频 owner,再销毁 source;callback join 前不得释放 inbox、decoder 或 credential storage。成功 close 与 connect 失败后还应清零 `request_.credentials`,不能仅依赖最终析构。
+
+## 7. CMake 和构建问题
+
+根 `CMakeLists.txt` 当前无条件把 `RemotePlaySource.cpp` 和 remoteplay core 编进 `veyra_sources`,但 `ChiakiBackend.cpp` 只在三个未正式声明的变量都成立时加入:
+
+```cmake
+VEYRA_ENABLE_REMOTEPLAY
+VEYRA_REMOTEPLAY_INCLUDE_DIR
+VEYRA_REMOTEPLAY_LIBRARY
+```
+
+这不是可维护的产品配置。静态库暂时可能因没人引用 `RemotePlaySource` 而隐藏悬空符号;一旦 UI 真正引用就会在默认配置链接失败。
+
+必须显式声明:
+
+```cmake
+option(VEYRA_ENABLE_REMOTEPLAY "Enable PS5 Remote Play through pinned chiaki-ng" OFF)
+set(VEYRA_REMOTEPLAY_CHIAKI_SOURCE_DIR "" CACHE PATH "...")
+set(VEYRA_REMOTEPLAY_CHIAKI_VERIFY_DIR "" CACHE PATH "...")
+```
+
+启用时提取/完善 `services/remoteplay-probe/NativeChiaki.cmake` 的真实 `add_subdirectory()` 接法,直接链接 `chiaki-lib`;不要把 probe 的完整 target 定义原样复制到主工程。现有 provenance 检查还需修复:clean verify checkout 的 HEAD 不能证明另一个 stage 的内容,限定改动文件名与 reverse-apply 检查也不能证明文件中没有额外改动。必须核对 stage HEAD、全部差异内容、index/worktree 和递归子模块。不要发明只有 include/lib 路径、无法追溯 commit 的旁路。关闭时应排除 backend、`RemotePlaySource`、Remote Play UI 和相应测试,或者提供完整的编译期 disabled 实现。
+
+`scripts/build.ps1` 还没有传 Remote Play 参数。应检测上述三个本机目录,在明确启用时追加 CMake 参数。不要把机器路径写进 `CMakePresets.json`。本机 Ninja/MSVC 曾受代码页 936 的 `/showIncludes` 影响并生成缺失的 `rules.ninja`;构建批处理先执行 `chcp 65001 >nul`,并使用 Windows本地 TEMP。
+
+## 8. 主程序接线方案
+
+### 8.1 请求模型
+
+`EngineController::open(HWND, path, options)` 现在靠字符串前缀识别采集卡,不适合塞入密钥。增加独立入口:
+
+```cpp
+void openRemotePlay(
+ HWND video,
+ source::RemotePlayConnectDesc request,
+ PlayerOptions options);
+```
+
+`PairingCredentials` 是 move-only,现有 `post(std::function<void()>)` 要求闭包可复制。不要为了方便把凭据类型改成可复制。可把请求放入 `std::shared_ptr<RemotePlayConnectDesc>`,闭包复制 shared_ptr,worker 取得后立刻移动到只属于本次会话的对象,并在关闭时清零。更彻底的方案是让任务队列支持 move-only callable,但不要在本次顺手重写整个 dispatcher。
+
+### 8.2 统一 run 路径
+
+不要新增一份 `runRemotePlay()` 复制约千行播放循环。将 source 选择收敛为内部 `OpenRequest`/variant:
+
+```text
+Local file/image request
+Capture request
+RemotePlay request
+```
+
+完成 source 创建和 open/connect 后,仍走同一个 extent、ResolutionPlan、EnhanceGraph、LiveGpuScheduler、FrameFlowWindow 和 VideoPresenter。Remote Play 需要与 physical capture 一样走实时 admission/latest-deadline 策略,但 source identity 必须保持 `SourceKind::RemotePlay`,不能把它伪装成 CaptureCard。
+
+`gd.rgbInput`、`gd.yuy2Input` 必须根据实际解码 AVFrame 格式设置。源码已确认现有 `EnhanceGraph.cpp:818` 支持 YUV420P/YUVJ420P/NV12 的上传路径,不要另加一套重复颜色转换。图在 `:663` 会通过 `resolveFrameColor` 读取明确 VUI,能缓解 source 未解析颜色的问题;但 source 当前的 720p BT.601 fallback 错误,VUI 缺省时会透传到图。需在 source 输出统一正确的 metadata、assumed 标记,并验证未知格式/不支持 HDR 的拒绝行为。
+
+新增独立解码 owner 是实时集成的必要环节:Chiaki 网络回调只投递,CPU owner 按压缩参考顺序持续解码,再通过现有 `LatestMailbox<owned AVFrame>` 或同等有界候选把解码结果交给唯一 GPU owner。保持同一个引擎/graph/presenter,不等于把协议、解码和慢 NR 全串在一个线程。当前 source 的 FFmpeg 工作就在 `read()` 内;若直接由每次增强后调用一次 read,4 个 AU/100ms 队列会在 GPU 欠速时反复溢出并等待 IDR,不能靠扩大队列解决。
+
+### 8.3 实时调度和 reset
+
+Remote Play 适用现有实时预览规则:持续欠速时按真实 PTS 均匀跳过过期增强机会,音频保持一倍速,不能堆积无界延迟。网络丢包、IDR 恢复、codec config、分辨率变化、重连和 decoder flush 必须原子 reset SR/NR/FG/NVOF 历史。
+
+至少增加这些 reset cause 的日志:
+
+```text
+RemotePlayOpen
+RemotePlayPacketGap
+RemotePlayDecoderReset
+RemotePlayReconnect
+RemotePlayResolutionChange
+```
+
+如果现有 enum 不允许扩展,映射到已有准确语义并在日志 detail 中标出 remote source;不要写成 Seek。
+
+## 9. Remote Play 音频
+
+Remote Play PCM 已由 Chiaki 的 Opus decoder callback 产出,不能走文件 `AudioPipeline::open(path)`,也不应该套采集卡 DirectShow 音频类。
+
+增加 Remote Play 专用音频 owner:
+
+```text
+wait until first real PCM block is available
+ -> AudioRenderer::start()
+ -> AudioRenderer::startAnchored(RemotePlayAudioSource)
+ -> event-driven AudioRenderer::pumpOnce(...)
+```
+
+具体实现可作为 `RemotePlayAudioSession`,持有 `RemotePlayAudioSource`、`AudioRenderer`、stop token 和线程。WASAPI 对象只在音频 owner 线程创建、pump、reset 和销毁。引擎线程只发布音量、暂停和诊断状态。
+
+音频以共同相对 PTS 为媒体时钟。视频处理变慢时跳过过期视频机会,不能停 PCM、丢 PCM 或频繁重锚来追逐 5-10 ms 抖动。真正的网络 discontinuity、队列 overflow 或 reconnect 才允许一次受控 reset/re-anchor。把 underrun、buffered ms、音频 PTS、视频 PTS、A/V delta 和 reset 次数放进现有实时状态。
+
+生命周期顺序:停止 Remote Play 音频线程并 shutdown endpoint,然后停止/加入 Chiaki session,最后销毁 source。不能让音频线程在 source 析构后继续调用 `pullAudio()`。
+
+## 10. 配对、凭据和 UI
+
+### 10.1 DPAPI profile
+
+实现独立的 `RemotePlayProfileStore`:
+
+- profile 元数据可保存 nickname、host、MAC、最后使用的 video profile。
+- Account ID、registration key、session key 使用 Windows DPAPI `CryptProtectData`,绑定当前用户。
+- 磁盘文件写到 `runtime::localDataDirectory()` 下的 Remote Play 子目录。
+- 使用原子临时文件 + rename,设置合理 ACL;解析长度严格有界。
+- 解密后的 buffer 和临时 `PairingCredentials` 用后立即清零。
+- 禁止写入 INI、命令行、环境变量、日志、崩溃诊断或 UI 文本。
+
+### 10.2 配对流程
+
+`pairLocalPs5()` 是同步所有权操作,最长可到 30 秒,必须在独立 setup worker 执行。UI 提供取消,退出窗口时 request stop 并等待 worker 清理。不能在 HWND 线程调用。
+
+首版页面至少包含:
+
+- 手动 IP/主机名。
+- PSN Account ID,支持当前校验器接受的十进制或 Base64。
+- PS5 显示的 8 位配对码,保留前导零。
+- 配对、取消。
+- 已保存主机列表:连接、删除、重新配对。
+- 720p/1080p、30/60、H.264/H.265 和 bitrate 选择。
+- 连接状态:正在连接、等待首帧、串流中、需要登录 PIN、失败码。
+
+Remote Play 应作为专业模式左侧 rail 的独立入口,不要塞进“采集卡”弹窗。日常模式可以在已有空页面增加“PS5 串流”命令,但精细连接参数放专业模式。
+
+### 10.3 发现和唤醒
+
+先完成手动 IP 的真实连接,再接 discovery/wakeup。复用固定 chiaki-ng commit 的 discovery 和 wakeup API,不抄 chiaki-ng GUI/Qt 页面。发现结果是易变网络状态,不能直接覆盖持久 profile。唤醒失败不应删除配对凭据。
+
+## 11. 手柄
+
+`InputGate` 只做 generation、焦点和 stale timeout 门控,不负责发现设备。需要新增设备服务,把 Windows 手柄状态映射到 `remoteplay::ControllerState`,在 session owner 线程调用 `backend_.submitController()`。
+
+最低行为:
+
+- 有焦点时按固定频率采样并去重发送。
+- 窗口失焦、设备拔出、停止、重连时立即发送一次中立状态。
+- 输入线程不能等待 GPU 或网络 callback。
+- 连接代次变化时旧输入不能进入新 session。
+- 先覆盖常用按键、双摇杆、L2/R2、方向键、Options/Create、PS、触摸板点击。
+
+可以选 SDL 或 Windows 原生 GameInput/XInput,但只能引入一套明确依赖。若使用 SDL,记录版本、许可证、构建和 Release 文件;不要把 chiaki-ng GUI 整体编进 Veyra。
+
+## 12. 推荐施工顺序
+
+每一步通过后再进入下一步,单次测试不超过 300 秒。
+
+1. **源层正确性**:首先修 H.264 config/AU 首帧失败;然后按第 18 节修 PCM cursor/共同音频锚点、元数据与解码 PTS、尺寸/颜色、IDR/恢复、首帧状态、48 kHz/音频段重启和清理失败。
+2. **源层测试**:给上述每个缺陷写独立回归;增加真实 FFmpeg config + AU 解码 fixture,验证输出帧数、PTS、flush 和尺寸变化。
+3. **生产 CMake**:显式 option,固定上游验证,主项目链接真实 `chiaki-lib`,更新 `scripts/build.ps1`,Remote Play OFF/ON 两种全新构建都通过。
+4. **引擎接线**:新增安全的 remote open request,复用同一 run loop、增强图、实时调度、reset 和诊断。
+5. **音频**:专用 owner thread + AudioRenderer,共同 PTS,停止/重连完整生命周期。
+6. **DPAPI 和配对 UI**:后台配对、取消、保存主机、连接/删除/重配。
+7. **发现、唤醒和手柄**:手动 IP 基线通过后再加;后台 owner 须能接收 login PIN、IDR、控制输入且不能等待 GPU。当前 source 还没有公开这些控制入口。
+8. **离线总回归**:Remote Play tests、source tests、engine tests、UI smoke、`scripts/gates/delivery.ps1`。
+9. **PS5 实机验收**:视频、音频、手柄、断线恢复、暂停/停止、NR/SR/FG、OBS、窗口调整和延迟。
+10. **许可证和提交**:补 notices、exact source/build recipe,扫描 Git 不含凭据/依赖/二进制;经用户明确授权后才能 push 或 Release。
+
+不要先写完整 UI 再回头修 PTS,也不要先接硬件解码。首个实机基线使用当前软件解码,先证明协议、时序和生命周期正确;基线稳定后再评估 D3D12VA 零拷贝是否值得做。
+
+## 13. 构建命令
+
+### 13.1 离线 core
+
+在已配置 MSVC 的 x64 Developer PowerShell:
+
+```powershell
+powershell.exe -NoProfile -File scripts/remoteplay/test-core.ps1 `
+ -Root . `
+ -BuildDirectory out/remoteplay/core-handoff `
+ -Configuration Release
+```
+
+### 13.2 原生 Chiaki probe
+
+若现有 stage 已在,不要删除或覆盖,脚本会验证补丁:
+
+```powershell
+powershell.exe -NoProfile -File scripts/remoteplay/build-native.ps1 `
+ -Root . `
+ -ChiakiCheckout C:/veyra-deps/chiaki-source `
+ -StageDirectory "C:/Users/123/Desktop/Veyra DLSS Video Player/out/remoteplay/chiaki-msvc-stage" `
+ -BuildDirectory out/remoteplay/native-handoff `
+ -PrefixPath C:/veyra-deps/remoteplay-installed/x64-windows-static `
+ -ProtocPath C:/veyra-deps/remoteplay-installed/x64-windows/tools/protobuf/protoc.exe `
+ -PkgConfigPath C:/veyra-deps/vcpkg/downloads/tools/msys2/3e71d1f8e22ab23f/mingw64/bin/pkg-config.exe
+```
+
+前版漏掉后两项,在相同机器全新配置目录真实复现 `Could not find protoc`(exit 1);不能依赖 `native-fresh5` 的旧 cache。以上路径来自成功目录的 CMakeCache,换机需要定位实际工具。二次审计仅复现旧命令的失败,没有重新执行这份修订命令的完整 248 步构建。
+
+### 13.3 主项目
+
+用户可能仍在运行旧 `out/build/x64-release/veyra.exe`。使用新目录:
+
+```powershell
+powershell.exe -NoProfile -File scripts/build.ps1 `
+ -Root "C:/Users/123/Desktop/Veyra DLSS Video Player" `
+ -Preset x64-release `
+ -BuildDirectory "C:/Users/123/Desktop/Veyra DLSS Video Player/out/build/remoteplay-main-fresh"
+```
+
+完成生产 CMake 接线后,命令必须在 Remote Play ON 和 OFF 两种模式分别执行。ON 模式的具体参数应由更新后的 `scripts/build.ps1` 生成,不要手写不可审计的 `.lib` 旁路。
+
+## 14. 验收矩阵
+
+| 项目 | 当前 | 完成标准 |
+|---|---|---|
+| Offline core | PASS 67/67 | 新回归加入后仍全绿 |
+| Native Chiaki init | PASS | 固定 commit、真实库、干净 source 复现 |
+| Production OFF build | 未形成稳定配置 | 全新目录构建和原有 gate 通过 |
+| Production ON build | 未完成 | `veyra.exe` 链接真实 chiaki-lib |
+| FFmpeg 合成真 AU 解码 | 审计失败:split H.264 首帧、重排 PTS | 修复后 H.264/H.265 fixture 帧数和 PTS 正确;PS5 输入单独验收 |
+| Pairing | 未执行 | 后台配对、取消、DPAPI 保存成功 |
+| PS5 video | 未执行 | 连续画面、真实分辨率/帧率、断线可恢复 |
+| PS5 audio | 未执行 | 48 kHz 连续、无 PCM 尾丢失、A/V 维持同步 |
+| Controller | 未执行 | 常用输入、失焦/拔插归零、无 stuck input |
+| EnhanceGraph | 未执行 | NR/SR/FG 复用同图且 reset 正确 |
+| OBS/window/fullscreen | 未执行 | Windows Graphics Capture 可见,调整窗口稳定 |
+| Latency | 未执行 | 分别测回调后排队、解码、增强、呈现及软件总延迟;PS5渲染/编码/网络与屏幕扫描无证据时明确未测,不能把回调时刻冒充源端时间 |
+| License/package | 未完成 | AGPL 对应源码、notices、依赖清单和包扫描完整 |
+
+## 15. 许可证和安全边界
+
+chiaki-ng 固定提交的许可证是 `AGPL-3.0-only`,附 OpenSSL exception。Veyra 当前根许可证是 GPLv3。把 Chiaki 链接进发布的 Veyra 组合程序时,不能只保留当前 GPL 文件并声称已经满足要求;发布物需要履行适用于组合程序的 AGPL 条款,提供用于构建该二进制的完整对应源码、Veyra 修改、Chiaki 固定源码/补丁、构建脚本和许可证/例外文本。发布前应把准确归因加入 `THIRD_PARTY_NOTICES.md`,并由项目维护者确认整个发行方式。
+
+允许参考或调用 chiaki-ng 的协议库,不等于可以机械复制它的 Qt GUI。若复制任何上游实现,保留版权、来源路径和修改记录。优先调用 upstream `chiaki-lib` API,并独立实现 Veyra UI/engine adapter。
+
+严禁:
+
+- 提交 `C:\veyra-deps`、stage、静态依赖、构建目录或用户提供包中的缓存。
+- 提交 Account ID、registration key、session key、配对码、PS5 MAC、抓包或含密钥日志。
+- 直接转发 Chiaki 原始日志或 hexdump;当前 backend 故意只计 warning/error。
+- 把 NVIDIA SDK、runtime、模型或其他本机二进制混入 Remote Play 源码提交。
+- 未经用户明确授权 push、创建 Release 或上传任何二进制。
+
+## 16. 对抗式检查清单
+
+下一位 Agent 每次声称完成前都要反问并给证据:
+
+- 初始化通过是否被误说成 PS5 已连接?
+- 收到压缩包是否被误说成解码帧已显示?
+- `SourceReadStatus::Frame` 是否真的带有效 AVFrame、真实 PTS 和正确 pixel format?
+- 处理欠速时是否在丢过期视频机会,而不是堆积延迟、停音频或丢 PCM?
+- 断线/重连时旧 callback、音频和手柄是否可能进入新 generation?
+- UI 是否在等待 30 秒同步 pairing?
+- 运行目录是否因 DLL/依赖搜索顺序加载了未审计文件?
+- Git diff 是否包含凭据、上游 checkout、SDK、DLL、LIB、PDB、日志或抓帧?
+- AGPL 对应源码是否与发布二进制完全一致?
+
+任何一项没有证据就保持 `NOT_RUN` 或 `INCOMPLETE`,不得用“应该可用”代替。
+
+## 17. 下一步唯一任务
+
+只做第 6、18 节的源层正确性修复和对应测试。先写出当前会失败的真实 H.264 config/AU 测试,再修首帧;不要先接 UI。完成门槛:
+
+1. 配置与真实 AU 可解码,H.264/H.265 及更新配置均有独立证据。
+2. PCM 任意分块拉取不丢样本;固定锚点加样本偏移,连续段、溢出和重启不混接。
+3. 解码实际尺寸/颜色与 source/graph 契约一致;重建无 frame 泄漏。
+4. 第一张真实解码帧进入 Streaming;IDR 确实转发,解码可恢复错误不直接终止整个播放器。
+5. decoder delay/重排不会配错 PTS,真实帧号完整展开;没有源时间则标记本机估计。
+6. 48 kHz 契约和同格式音频重启正确;停止失败不得冒充已停止,凭据及时清零。
+7. core、新增 source tests、既有 23 项文件 source 回归通过;故障复现日志不能作为成功测试计数。
+
+完成后把命令、退出码、日志路径和仍未执行的硬件项追加到 `docs/WORKLOG.md`,再进入生产 CMake 接线。
+
+## 18. 2026-09-11 二次代码审计(用户要求交给其他 Agent 修)
+
+### 18.1 审查范围、代码来源与结论
+
+这轮审查从用户要求移植 Remote Play 的存档 `0f78cc29` 起覆盖全部工作树增量:根 CMake、`FramePacket.h`、全部 Remote Play header/cpp、`RemotePlaySource`、独立 probe、67 项 core tests、构建脚本和 MSVC patch,并核对用户 Code 01 原包、固定 Chiaki 上游与现有 EnhanceGraph/AudioRenderer 接口。是本 Agent 的重新审查,没有第二位 Reviewer,也不能根据截图确认平台路由到过哪个模型。
+
+按 UTF-8 文本统一换行后比较,原包的 core headers、Validation/Timeline/Ingress/Registration 和 CoreTests 没有实质改写;移植中实质改写了 `ChiakiBackend.cpp`、native 构建/probe,新增 `RemotePlaySource`、根 CMake 接线、SourceKind 和 MSVC patch。逐字节初比把 CRLF 差异也计入 changed,因此以 `origin-comparison-normalized.json` 为准。原包 `prepare_chiaki.py`、`chiaki_metadata_patch.json` 和 `PatchToolsTests.py` 没有进入当前工作树,文档仍引用它们是错误。
+
+**结论:基础模块可以保留;不能把这一批代码直接接 UI 后交付。** 问题集中在真实数据适配层、原包元数据契约被移除以及文档/测试覆盖误读。下面区分实际失败、静态确认、接线后才触发的风险;不把尚未实现的 UI/手柄说成“写坏了”。
+
+### 18.2 缺陷清单与修复要求
+
+| 编号 | 优先级 | 位置(审计时行号) | 确认的问题与触发 | 下一位 Agent 的动作 |
+| --- | --- | --- | --- | --- |
+| R01 | P1 | `RemotePlaySource.cpp:296` | 配置头独立 send 导致合法 H.264 首帧 Error;真实 FFmpeg 已复现 | 明确 config/AU 输入契约,首帧/配置更新均写真解码回归;见第 6 节 |
+| R02 | P1 | `RemotePlaySource.cpp:320–346` | PCM block 尾部永久丢弃;480 帧分两次拉取只得到 100 帧 | 保存 block/cursor,任何合法拉取粒度总样本一致 |
+| R03 | P1 | `RemotePlaySource.cpp:329`、`Timeline.cpp:44` | source 输出绝对 PTS;旧交接的“当前 arrival+累计样本”方案又会双重计时 | 固定音频段锚点+样本偏移;处理首样本非零、断点,不混拼时间段 |
+| R04 | P1 | `RemotePlaySource.cpp:206–227` | 解码输出一律套当前输入 packet;B 帧样本 10 张输出全部错配 PTS;多帧注释与实际相同 PTS 也不一致 | 有界元数据匹配和真实 send/receive adapter;不能拿独立 FakeCodec 测试代替 source 测试 |
+| R05 | P1 | `ChiakiBackend.cpp:77–91,152` | 原包 metadata callback 被替换为普通回调,wireFrameIndex 永远缺失,width/height 用请求值冒充实际值 | 恢复经过审查的元数据通道,或实现并证明等价的受限方案;不要整包 apply 覆盖修订 |
+| R06 | P1 | `RemotePlaySource.cpp:282,286,219` | decoderReady 后不再调用 openDecoder;reset 只 flush。实际尺寸变化未更新 SourceInfo/Resize/graph 契约;观测 info.width=1920 而 AVFrame.width=1280 | 首帧按实际帧建立图,配置/尺寸改变发原子重建;先拒绝不匹配,防 YUV 上传使用错误 buffer/stride |
+| R07 | P1 | `RemotePlaySource.cpp:275–302` | 没有消费 takeIdrRequest;可恢复 decode error 虽 requireKeyframe 却返回终止性 Error | owner 周期转发 IDR,区分恢复中的 Waiting 与致命错误;真实错误码、节流、取消/恢复超时需可观测 |
+| R08 | P1 | `ChiakiBackend.cpp:94–97`、`VideoIngress.cpp:111–112` | 同格式 Opus settings 重来会把 sampleIndex 归零,AudioIngress 的 nextSample 仍为旧值;标记 discontinuity 也被判乱序拒绝,静音直到计数追上 | 使用明确音频段/代次重启或连续计数契约;不能仅凭任意乱序块带 discontinuity 就接受旧数据 |
+| R09 | P1 | `RemotePlaySource.cpp:353–358,89–95` | stop 返回值丢弃,未确认 join 就标 Idle 并丢 token;后续重连失败,可能隔离泄漏旧 session | 成功和失败清理分别建状态机;wrong-owner/join/启动失败注入测试,失败不重新连接 |
+| R10 | P1(接线门槛) | 根 `CMakeLists.txt:412–441` | 默认无条件编入 source,却条件性定义其 backend;没人引用时静态库能藏住未解析符号;ON 也没有正式选项/依赖闭环 | 生产 OFF/ON 全新构建,ON 可执行文件真实引用/链接 source,完整依赖 target 和构建参数 |
+| R11 | P2 | `RemotePlaySource.cpp:168` | decoder 真正重建时覆写旧 AVFrame 指针,未 free;当前 read 的重建缺陷还把它部分掩盖 | RAII/先释放;在修 R06 后加重复重建/分配失败回归 |
+| R12 | P2 | `RemotePlaySource.cpp:262–311` | 成功交付真实帧仍不调用 decodedFrameReady;观测 Frame 返回、状态仍 WaitingFirstFrame | 两处交付路径统一更新状态,generation 一致,失败/恢复不能复活旧帧 |
+| R13 | P2 | `RemotePlaySource.cpp:110,219` | 720p fallback 错设 BT.601;source 不解析 VUI。明确 VUI 会被现有图再次解析缓解,缺省时仍错 | HD SDR fallback BT.709;复用颜色解析并保留 assumed;明确 VUI/缺省 VUI 各测,勿重复色彩转换 |
+| R14 | P2 | `RemotePlaySource.cpp:292–294`、`VideoIngress.cpp:59` | queue 的 16 位展开结果未向 source 传递;source 直接用原始 16 位数,65535→0 后 PTS unknown | 将扩展序号传到 source 并统一使用;当前普通 callback 无 wire index,此项是恢复 R05 后必然暴露的潜伏问题,非已证明当前 PS5 每18分钟卡死 |
+| R15 | P2 | `ChiakiBackend.cpp:94–108`、`RemotePlayAudioSource::pull` | Opus 接受多个 rate,而 AudioRenderer/尾 PTS 写死 48000;有效24k等会以48k解释 | 当前范围显式要求48k且传出失败;或加入真实测试的重采样,不静默按48k播放 |
+| R16 | P2 | `RemotePlaySource.cpp:72–77,348–364` | 手工复制凭据到 request_,成功 close 和部分连接失败不清除,直到下次 connect/最终析构 | 限制凭据所有者和存活时间,及时清零临时/会话副本;当前未发现真实凭据被提交 |
+| R17 | P2 | `NativeChiaki.cmake:10–32`、`build-native.ps1:43–48` | stage 验证只看文件名/补丁可反向应用,不核对完整内容;直接 CMake 未核对 stage HEAD、index/子模块闭环 | 收紧源码构建可追溯性,不是恢复 NVIDIA DLL 加载哈希锁;本次当前 stage 差异全文与审查 patch 一致,没有证据表明已混入异常改动 |
+| R18 | P2 | 第13节旧命令、`NATIVE_GATE.md`、`SOURCES_CODE01.md`、`dependency-lock.json` | 旧命令缺 protoc(已复现配置失败),文档引用不存在 metadata 脚本;probe 固定输出容易误读为回调验证 | 本轮已修交接/文档入口;后续改 native probe 文案、构建依赖发现和相应测试/机器可读状态 |
+
+R02/R03/R04/R06/R07/R11/R12/R14/R16 主要位于移植时新增的 source;R05 是对原包 backend 的实质退化。R08/R15 的基础行为已存在原包,移植者仍需负责在接 AudioRenderer 前修正,不能仅以“另一个 AI 写的”放行。
+
+R06 必须在接 graph 前解决:现有 YUV 分支会按 graph 的 `srcW_/srcH_` 分配/采样,而 source 可能返回另一尺寸的 AVFrame。这里只复现尺寸契约错配,未运行 GPU 越界测试、未声称已发生崩溃。
+
+R05 的普通回调只带数据、frames_lost 和 reference_recovered,不带真实帧号与实际 profile。当前 fallbackSourceIndex 只按被消费 AU 自增,不是远端帧号;FramePacket.sequence 也只是已解码输出编号。不能把本机名义 cadence PTS 当远端原生 PTS 或端到端延迟依据。`TimestampProvenance::LocalEstimated` 在时钟类型中存在,但 source 未把这个来源信息传到产品诊断,后续必须保留。
+
+### 18.3 未完成的架构工作,不能与已修缺陷混为一谈
+
+- 生产引擎和 UI 仍没有 Remote Play 入口;本轮没有改现有文件/采集的播放循环。未发现这批移植修改了已经完成的欠速音频策略。
+- 必须把压缩流连续解码与 GPU 慢任务解耦,复用已有参考帧 mailbox/有限候选。`PacketPump` 和 `LatestMailbox` 都已有单测,但实际 source 没用它们,`ready_` 也没有显式容量/时间预算。不能据此声称正常 FFmpeg 会无限产帧;应建立可测试的上界和取消点。
+- Remote Play 音频 owner、DPAPI、异步配对/取消、发现/唤醒、手柄轮询,以及公开的 login PIN/控制消息入口都未接。`SessionInbox` 不替代 owner 线程,`InputGate` 不替代设备服务。
+- 保留完整 source 错误原因、帧 provenance、队列/时钟统计;超时、源断流、GPU 欠速需分别报告。回调后计时不能命名为 PS5→屏幕总延迟。
+- MSVC VLA patch 的 Windows 分配/释放、错误分支已静态审阅;没有发现必须直接撤销的证据。其修改包含大小检查和错误处理,不能仅以“编译兼容”宣称所有网络行为等价;RUDP/洞穿/配对/OOM 分支均没有实机执行。当前任务先做 LAN,不能把编译了这些文件写成公网串流可用。
+
+### 18.4 本轮实际命令、结果与可复现证据
+
+证据目录:`logs/remoteplay-audit-20260911/`。临时观察程序和合成样本:`out/remoteplay/audit-20260911/`(全部 gitignored)。程序只把 RemotePlaySource 的访问控制在隔离 shadow header 中改为 public 以注入 inbox;**实际编译的是当前未改动的 `src/source/RemotePlaySource.cpp`**,链接本机真实 FFmpeg DLL、Veyra base 和既有真实 Chiaki/core 静态库。没有伪造 backend 初始化/连接成功,没有网络连接、WASAPI 或 GPU 操作。
+
+```powershell
+# 创建诊断编译参数和两个本地合成 H.264 样本;每个 ffmpeg 进程有60秒上限
+python out/remoteplay/audit-20260911/prepare.py
+# MSVC x64 /MT;build.cmd 内载入 vcvars64、codepage65001
+cmd.exe /d /c out\remoteplay\audit-20260911\build.cmd
+# 给本次诊断进程定位现有FFmpeg DLL,无文件复制/替换
+$env:PATH='C:\veyra-deps\installed\x64-windows\bin;'+$env:PATH
+& scripts/run-short-test.ps1 `
+ -Exe out/remoteplay/audit-20260911/audit.exe `
+ -Arguments @('out/remoteplay/audit-20260911/single','out/remoteplay/audit-20260911/reorder.h264') `
+ -TimeoutSeconds 30 -LogPrefix logs/remoteplay-audit-20260911/observations2
+```
+
+观察程序 exit 0 仅代表收集完结果,**不是产品 PASS**。`build.log/build2.log` 记录两次诊断编译;`observations.stdout.log` 是初次输出,`observations2.stdout.log` 补充颜色解析和真实帧状态对照;两次均保留。代表性结果:
+
+```text
+PCM supplied=480 pulled=100 first_pts_ms=1.36365e+08 expected_relative_ms=30
+HANDOFF_AUDIO_RECIPE first=300000 next=500000 expected_step=100000
+AUDIO_SAME_FORMAT_RESTART accepted=0 rejected=1
+WIRE_WRAP before_known=1 after_known=0
+avcodec_send_packet failed code=-1094995529
+SPLIT_H264 config_accepted=1 au_accepted=1 read_status=2 frame=0 session_state=2
+COMBINED_H264 ok=1 decoded=1 ... resolved_matrix=2 info_width=1920 decoded_width=1280
+REAL_FRAME_STATE read_status=0 frame=1 session_state=2 streaming_enum=3
+REORDER input=12 output_before_eof=10 wrong_pts=10
+```
+
+这里 `REORDER` 故意没有发送 EOF drain,所以没有输出的两帧不是额外“丢尾”结论;错误是已经输出的 10 帧都套了另一个 packet 的 PTS。颜色枚举的 AV 与 Veyra 数字不同,必须按类型解释;`resolved_matrix=2` 在 Veyra 表示 BT.709,证明图能读取明确 VUI,不能只看 raw 数值不同判颜色错误。
+
+既有测试重跑(均通过 `scripts/run-short-test.ps1`、每进程30秒上限):
+
+| Exe | LogPrefix | 实际结果 | 范围 |
+| --- | --- | --- | --- |
+| `out/remoteplay/core-windows/veyra_remoteplay_core_tests.exe` | `logs/remoteplay-audit-20260911/core` | exit0,67/67 | 基础模块,未包含真实 source adapter |
+| `out/remoteplay/native-fresh5/veyra_remoteplay_native_probe.exe` | `logs/remoteplay-audit-20260911/native` | exit0,初始化成功 | 不执行配对/视频callback/session |
+| `out/build/x64-release/veyra_source_tests.exe` | `logs/remoteplay-audit-20260911/source` | exit0,23 checks/0 failures | 既有文件source,未覆盖Remote Play |
+
+构建复现:执行隔离 `out/remoteplay/audit-20260911/configure.cmd`(vcvars64+UTF-8+Windows TEMP,从第13节旧参数组创建全新 native-doc-repro 目录),CMake exit1,`Could not find protoc`,日志 `configure-from-handoff.log`。这证明旧交接命令不完整,不推翻此前成功目录真实构建/初始化的记录。修订命令的 ProtocPath/PkgConfigPath 取自成功 cache,尚待下一位执行完整复现。
+
+源码证据:`origin-comparison-normalized.json` 保存与用户原包的文本差异列表;`reviewed-files-sha256.json` 保存审查范围内的文件 hash;`stage-current.patch` 与项目 MSVC patch 的文本一致性比较为 True,stage submodule status 版本匹配。不要把这些日志、二进制或本机依赖提交到 Git。
+
+### 18.5 本轮更新和未做项
+
+本轮仅更正本交接、文档入口/原生指南/来源记录与 WORKLOG,并在忽略目录建立审计工具。没有修产品、修改 SDK/runtime、关闭用户程序、连接 PS5、commit、push 或 Release。没有新增完整 Veyra 构建/delivery/GPU测试;下一位必须以修复后新代码重新构建和验证,不能拿本次故障观察程序 exit0 或旧67项结果放行。
+
+API核对参考:[FFmpeg send/receive 官方契约](https://ffmpeg.org/doxygen/trunk/group__lavc__encdec.html)、[固定版本 Chiaki decoder](https://github.com/streetpea/chiaki-ng/blob/0e16950165f06e5c3291537c2eeba6e852be7120/lib/src/ffmpegdecoder.c)、[固定版本 video receiver](https://github.com/streetpea/chiaki-ng/blob/0e16950165f06e5c3291537c2eeba6e852be7120/lib/src/videoreceiver.c)。源码定位使用同一提交的本地 clean checkout;上游播放器的简化解码处理不构成照抄许可之外的正确性证明。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 791f6e09..bba82fd7 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1596,3 +1596,29 @@ FRUC候选bSkipWarp/延后重建/时间归零/首对预热均未通过新增rese
失败与修正保留:file-overload 首跑把 seek(.3→.5) 前跳与暂停窗口计入稳态间隙(maxSteadyGap=200ms 撞界),改为向后跳变后首个前向间隙按显式重同步处理后通过;A/B 期间误用 `git checkout --` 还原未提交的 WasapiAudioSink 修改(下一构建报缺 AudioVideoContinuity.h 暴露),重做修改并立即提交隔离分支;无产品级回退。
未执行/边界:4060 实机复验(用户以相同 60fps 文件与设置复测,日志需能独立说明真实处理速率/媒体速度/停音与跳帧原因)、物理扬声器/屏幕同步测量、长时间直播稳定性、真实采集卡 XeSS 欠速门控触发(本轮仅文件路径与单元验证;30fps 非欠速场景门控正确不动作)。不因本机 5070 通过宣称 4060 通过;不承诺持续 30→15 下 NR/FG 时序画质不变。下一条:用户实机验收与 4060 日志复核。
+
+## 2026-09-11 PS5 Remote Play 集成交接
+
+用户要求把 `C:\Users\123\Desktop\Veyra_RemotePlay_Code_01` 中基于 chiaki-ng 的代码接入 Veyra,并在当前进度上整理给下一位 Agent。当前隔离分支为 `agent/remoteplay-integration`,基线 `0f78cc29f34365589bcd4757e7017236e3ac9cb1`,开工标签 `checkpoint/remoteplay-preintegration-2026-09-11`。完整架构、工作树、依赖、缺陷、施工顺序、命令、验收矩阵和许可证边界已整理到 `docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md`,`docs/remoteplay/NEXT_AGENT.md` 已改为唯一入口跳转。
+
+固定 chiaki-ng 提交 `0e16950165f06e5c3291537c2eeba6e852be7120` 已在 Windows x64/MSVC 下完成 248/248 个真实构建步骤;原生 probe 退出码 0,输出 `REAL_CHIAKI_CORE_INITIALIZED upstream_video_callback=1`,并明确输出 `PS5_CONNECTION_NOT_TESTED VIDEO_DECODE_NOT_TESTED WINDOWS_PLAYER_NOT_TESTED`。Remote Play 离线核心测试 67/67 PASS;现有 `veyra_source_tests.exe` 23 checks、0 failures。上述证据只覆盖协议桥基础和原生初始化,不覆盖 PS5 连接、真码流、音频、手柄、增强、OBS、窗口行为或实际延迟。
+
+当前 `RemotePlaySource` 在接入主程序前有七类必修问题:PCM block 被截断后尾部丢失、音视频 PTS 零点不一致、decoder 重建泄漏旧 AVFrame、首帧未进入 Streaming、IDR 请求未转发、decoder delay/多帧输出会错配输入 PTS、非 48 kHz Opus 与固定 48 kHz AudioRenderer 契约冲突;新增 worker 后还要维持严格停止顺序。`EngineController`、`AppShell`、Remote Play 专用音频 owner、DPAPI profile、discovery/wakeup 和手柄设备服务均未接入。下一条唯一任务是先修这些源层正确性问题及测试,再处理生产 CMake 和主程序接线。
+
+外部依赖位于 `C:\veyra-deps\chiaki-source`、忽略的 `out\remoteplay\chiaki-msvc-stage` 和 `C:\veyra-deps\remoteplay-installed\x64-windows-static`,不得提交。chiaki-ng 为 `AGPL-3.0-only` 并带 OpenSSL exception;未来发布组合程序必须提供与二进制对应的完整源码、固定上游版本和补丁、构建脚本、许可证及归因。本轮只更新交接文档,没有修改产品代码、SDK/DLL/模型或运行时,也没有 commit、push 或 Release。
+
+## 2026-09-11 Remote Play 移植代码二次审计(不修产品,交其他 Agent)
+
+用户要求从开始移植时重新审查所有代码并更新交接。审查基线仍为 `0f78cc29` / `agent/remoteplay-integration`,没有新增产品提交。逐文件比对用户 Code 01 包(统一换行后)、当前未提交代码、固定 Chiaki 上游、本机 MSVC patch 与 Veyra graph/audio 接口;结论和18条分级事项已加入 `docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md` 第18节,并同步更正其第6/8/13/17节及 `docs/remoteplay/{NEXT_AGENT,NATIVE_GATE,SOURCES_CODE01,WORKLOG_CODE01}.md`。未谎称其他 Reviewer 或特定模型路由已确认。
+
+新增实际故障证据:使用本机 MSVC 编译隔离审计程序,编译的实现是当前未改动的 `RemotePlaySource.cpp`(仅隔离shadow header打开访问控制以直接注入合成inbox),链接真实FFmpeg、Veyra base、既有Chiaki/core库,无网络/PS5/WASAPI/GPU调用。合法720p H.264 SPS/PPS独立送入当前source返回 `-1094995529` / `no frame!`,`read_status=2 frame=0`;同数据合并配置与AU成功解出1帧。PCM供应480帧、先拉100再拉380,实际仅得到100;音频PTS是约1.36e8ms绝对时钟。12包带重排H.264解出10帧(没有EOF drain,不能把另两帧列为丢尾),已输出的10帧全部配错PTS。实际帧已交付而session仍WaitingFirstFrame;请求1920宽但实际解码1280宽时SourceInfo未更新。另复现音频同格式重启首样本归零被拒绝,以及16位帧号回绕时PTS unknown(后者当前callback不提供wire index,是恢复metadata后会暴露的潜伏问题)。
+
+修正原交接:不能逐块用 `audioPts(firstSample,rate,currentArrival)`,会把10ms推进算成20ms,需固定段起始锚点+样本差值;现有EnhanceGraph已支持YUV420P且会读取明确VUI,因此不是所有画面颜色都错,但source的720p BT.601 fallback和metadata缺失必须修。移植中的普通回调替换删掉了原包真实帧号/profile元数据,三个metadata脚本/测试未导入;core文本主体仍与用户包一致。其余事项包括IDR未转发、decode error直接终止而非恢复、decoder重建与AVFrame泄漏、stop失败被吞、48k契约、凭据驻留、生产CMake未闭环、解码与GPU解耦未接。完整触发条件和修复验收见主交接,不把代码桩和未接UI冒充功能完成。
+
+实际命令/日志:`python out/remoteplay/audit-20260911/prepare.py`(生成两段本地合成素材,每个ffmpeg60秒上限);`cmd.exe /d /c out\remoteplay\audit-20260911\build.cmd` 两次诊断构建成功(`build.log/build2.log`);`scripts/run-short-test.ps1 -Exe <audit.exe> -Arguments <single prefix,reorder.h264> -TimeoutSeconds 30` 输出 `observations[2].stdout/stderr.log`。观察程序exit0只代表记录完成,其中是失败证据,不计产品PASS。另通过同一wrapper、各30秒上限重跑core67/67、native初始化exit0、既有文件source23/23;日志 `core/native/source.stdout.log`。native输出的 `upstream_video_callback=1` 为固定文字,不是真回调计数。
+
+全新CMake配置复现旧交接参数组:`out/remoteplay/audit-20260911/configure.cmd` 使用vcvars64/UTF-8/Windows TEMP,真实exit1 `Could not find protoc`,证据 `configure-from-handoff.log`;交接现补ProtocPath/PkgConfigPath,但修订命令的全量构建尚未执行。当前stage的差异全文与MSVC patch一致,递归子模块版本匹配;脚本的文件名/reverse-apply校验不能证明完整源码身份,已列待修而未声称当前stage被污染。证据全部位于 `logs/remoteplay-audit-20260911/`,包含原包文本比对和审查文件SHA256清单;诊断源/生成物在忽略的out目录。
+
+本轮未修产品、未改SDK/DLL/模型、未连接PS5/占用采集卡/关闭用户程序,没有完整Veyra/delivery/GPU/实机测试,无commit/push/Release。下一条唯一任务:先建立H.264 config/AU真实source失败回归并修首帧,再依第18节完成源层正确性闭环,之后接主程序;不能只补UI或继续重复native probe来宣称移植完成。
+
+收尾检查:`git diff --check` 无格式错误(仅既有LF/CRLF提示);6份Markdown围栏/相对文件链接检查0错误;按审查SHA256清单复核产品/构建/测试代码改动列表为空;`git ls-files --others --exclude-standard` 按DLL/LIB/EXE/PDB/压缩包/合成媒体后缀扫描无未忽略二进制。用户原有未提交代码完整保留。
diff --git a/docs/remoteplay/NATIVE_GATE.md b/docs/remoteplay/NATIVE_GATE.md
new file mode 100644
index 00000000..490d4622
--- /dev/null
+++ b/docs/remoteplay/NATIVE_GATE.md
@@ -0,0 +1,102 @@
+# Windows 原生 Chiaki 构建门槛
+
+**当前状态:Windows x64/MSVC 原生门槛已通过。** 固定 chiaki-ng 提交 `0e16950165f06e5c3291537c2eeba6e852be7120` 在本机完成 248/248 个构建步骤;真实 probe 退出码为 0,并输出 `REAL_CHIAKI_CORE_INITIALIZED upstream_video_callback=1`。这只证明真实 `chiaki-lib` 能构建、链接和初始化,PS5 连接、真码流解码、音频、手柄、Windows 播放器和增强均未执行。当前状态和后续任务以 [`../REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md`](../REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md) 为准。
+
+本次通过使用的目录:
+
+```text
+Clean checkout: C:\veyra-deps\chiaki-source
+Patched stage: C:\Users\123\Desktop\Veyra DLSS Video Player\out\remoteplay\chiaki-msvc-stage
+Dependencies: C:\veyra-deps\remoteplay-installed\x64-windows-static
+Build: out\remoteplay\native-fresh5
+```
+
+原生 probe 的完整边界输出:
+
+```text
+REAL_CHIAKI_CORE_INITIALIZED upstream_video_callback=1
+PS5_CONNECTION_NOT_TESTED VIDEO_DECODE_NOT_TESTED WINDOWS_PLAYER_NOT_TESTED
+```
+
+**二次审计补充:** `upstream_video_callback=1` 是 probe 的固定文字,不是实际回调次数,probe 没有启动会话或执行视频回调。主程序适配层已有真实离线失败,详见交接第18节。此前构建248步的记录仍有效,但旧命令漏了工具参数,不能凭成功 cache 认为新目录可直接复现。
+
+## 1. 输入条件
+
+在与 Veyra 一致的 Windows x64 MSVC 环境准备 CMake 3.24+、Ninja、Python 和真实开发依赖。协议库使用 C,Veyra 新基础库保持 C++20;静态 MSVC runtime 与原应用统一。不要把 MinGW `.a` 当成 MSVC `.lib` 混用。
+
+准备:Opus、OpenSSL、json-c、libevent、miniupnpc 的匹配工具链版本及 pkg-config/CMake 包配置;nanopb 和 protobuf 生成工具;固定上游的 Jerasure、gf-complete、curl 递归子模块。关闭 RUDP 不代表这些 CMake 依赖会自动消失。
+
+本门槛不引入 Qt、libplacebo、另一套 FFmpeg 或任何 NVIDIA SDK。不要因为配置失败创建空 imported target、删除 FEC 源码或忽略链接错误。
+
+## 2. 固定上游源代码
+
+以下目录为例子,不能覆盖已有工作区;这些命令需要联网:
+
+```powershell
+git clone --no-checkout https://github.com/streetpea/chiaki-ng.git C:/veyra-deps/chiaki-source
+git -C C:/veyra-deps/chiaki-source checkout --detach 0e16950165f06e5c3291537c2eeba6e852be7120
+git -C C:/veyra-deps/chiaki-source submodule update --init --recursive
+git -C C:/veyra-deps/chiaki-source status --short
+```
+
+当前使用 `scripts/remoteplay/build-native.ps1` 创建独立 git worktree,并应用 `patches/0001-chiaki-msvc-vla-compat.patch`。原用户包的 `prepare_chiaki.py` 与 metadata JSON 没有导入;当前 backend 使用未扩展的上游 callback,缺少真实帧号/实际 profile 元数据,这已列为必修项。不要把原包的两文件 metadata patch 误当成当前本机五文件 MSVC patch。
+
+当前 stage 差异全文经本次审计与 MSVC patch 比较一致;但脚本只凭文件名和 reverse-apply 检查,尚不足以拒绝同文件内的额外修改。下一位必须完善全量 stage、index、commit 和递归子模块验证。恢复元数据扩展时,新 header 与库必须共同重建,不得混用旧二进制。
+
+## 3. 运行原生构建
+
+在 Veyra 根目录、已配置 MSVC 的 x64 Developer PowerShell 中:
+
+```powershell
+powershell.exe -NoProfile -File scripts/remoteplay/build-native.ps1 `
+ -Root . `
+ -ChiakiCheckout C:/veyra-deps/chiaki-source `
+ -StageDirectory "C:/Users/123/Desktop/Veyra DLSS Video Player/out/remoteplay/chiaki-msvc-stage" `
+ -BuildDirectory out/remoteplay/native-handoff `
+ -PrefixPath C:/veyra-deps/remoteplay-installed/x64-windows-static `
+ -ProtocPath C:/veyra-deps/remoteplay-installed/x64-windows/tools/protobuf/protoc.exe `
+ -PkgConfigPath C:/veyra-deps/vcpkg/downloads/tools/msys2/3e71d1f8e22ab23f/mingw64/bin/pkg-config.exe
+```
+
+以上依赖路径来自本机成功 cache,换机需定位实际文件。旧参数组没有 ProtocPath,在全新目录真实失败 `Could not find protoc`,日志 `logs/remoteplay-audit-20260911/configure-from-handoff.log`;这份补全后的命令尚未重新全量执行。使用 vcpkg 时可通过 `-ToolchainFile` 指定真实文件;库要选择与 `/MT` 一致的 triplet。脚本不自动切换/覆盖 Veyra 原 FFmpeg 包。
+
+若此前已生成本机 staging 且要直接运行 CMake,不删除旧目录;须同时传 clean verify checkout 和工具位置:
+
+```powershell
+cmake -S services/remoteplay-probe -B out/remoteplay/native-handoff -G Ninja `
+ -DCMAKE_BUILD_TYPE=Release -DVEYRA_RP_BUILD_NATIVE=ON `
+ "-DVEYRA_RP_CHIAKI_SOURCE_DIR=C:/Users/123/Desktop/Veyra DLSS Video Player/out/remoteplay/chiaki-msvc-stage" `
+ -DVEYRA_RP_CHIAKI_VERIFY_DIR=C:/veyra-deps/chiaki-source `
+ -DCMAKE_PREFIX_PATH=C:/veyra-deps/remoteplay-installed/x64-windows-static `
+ -DPROTOC=C:/veyra-deps/remoteplay-installed/x64-windows/tools/protobuf/protoc.exe `
+ -DPKG_CONFIG_EXECUTABLE=C:/veyra-deps/vcpkg/downloads/tools/msys2/3e71d1f8e22ab23f/mingw64/bin/pkg-config.exe `
+ -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded
+cmake --build out/remoteplay/native-handoff --config Release --target veyra_remoteplay_native_probe
+ctest --test-dir out/remoteplay/native-handoff -C Release -L native-core --output-on-failure --timeout 30
+```
+
+## 4. 真实通过标准
+
+必须链接实际 `chiaki-lib`,执行 `chiaki_lib_init`、上游 profile 预设和手柄 idle 契约检查。记录 CMakeCache、编译器、架构、依赖版本、完整命令及退出码。
+
+只有真实执行后打印的 `REAL_CHIAKI_CORE_INITIALIZED` 才能作为这个小门槛的结果;字符串出现在源码里不算执行。**即使通过,也未测试 PS5 连接、解码、音频播放、GPU 和增强。**
+
+## 5. 协议桥使用契约
+
+所有 `ChiakiBackend` 操作(包括 snapshot)在同一个会话 owner 线程调用。网络回调仅复制输入、投递到 SessionInbox;不调用增强图、Present、UI、磁盘日志或 join。
+
+每次建立会话:`SessionInbox.begin(commonOrigin)` → 将其 token 传给 `ChiakiBackend.start(request, token)`。请求含明确的 host、720/1080p 30/60 SDR 预设和 8/16/16 字节配对凭据;不把它们塞进路径、环境变量或命令行。
+
+解码消费端 `RemotePlaySource` 已落盘但有未修缺陷。`configBefore` 必须与 AU 形成经真解码验证的输入契约;当前单独送 H.264 配置头已复现失败,不能照旧代码直接接 UI。decoder reset、PTS/尺寸、EAGAIN adapter 与 metadata 的详细动作见主交接。`PacketPump` 的独立测试不能证明实际 source 使用了它。
+
+`takeIdrRequest()` 须由 owner 周期性取走并调用 `backend.requestIdr()`,当前 source 尚未转发。PCM 经 Remote Play 专用音频 owner 适配现有 AudioRenderer/WASAPI,不套用采集卡 DirectShow 的 CaptureAudioSession。样本按每声道计数,固定音频段锚点+样本偏移,不逐块用arrival重建时钟。
+
+终止必须:inbox.invalidate → backend.stop(包含 stop/join/fini)→ 确认成功清理 → inbox.finishStop。新会话前先真实关闭旧 backend,不能只重置 inbox 来假装线程已经停止。
+
+## 6. 未完成项和策略风险
+
+保守的丢包处理会等待 IDR;H.265 CRA 并不被当作 IDR。需要真机确认编码习惯和恢复行为。`pairLocalPs5` 的超时是请求取消的时点,不是已证实的底层 join 时限;UI 不应同步等待它。
+
+日志仅记录安全计数和操作错误码,未开启原始上游日志/hexdump。后续若引入更详细诊断,需要逐项脱敏,不能直接转发含注册响应的字符串。
+
+本机原生门槛已记录为通过,但不能据此假定其他 Windows 环境或完整产品 CMake 已兼容。下一批工作是修复 `RemotePlaySource` 正确性并建立生产 CMake 的 ON/OFF 两种稳定配置。
diff --git a/docs/remoteplay/NEXT_AGENT.md b/docs/remoteplay/NEXT_AGENT.md
new file mode 100644
index 00000000..987550a7
--- /dev/null
+++ b/docs/remoteplay/NEXT_AGENT.md
@@ -0,0 +1,9 @@
+# 交给下一位 Agent 的接续指令
+
+唯一交接入口:[`../REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md`](../REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md)。先完整阅读该文档和工作区最新 `AGENTS.md`,保护当前未提交改动,不要 reset、checkout 或重新运行用户包中的 `apply.py`,也不要自动 push 或发布。
+
+**先读交接文档第 18 节二次审计。** Windows/MSVC 原生 Chiaki 初始化已通过,但新审计真实复现了 H.264 配置头导致首帧失败、PCM 截断、音频时间轴错误和解码重排 PTS 错配;同时发现移植删去了原包的元数据回调。不能拿67项 core测试通过当作 source 正确。
+
+当前唯一任务:按第 17 节先建立会失败的 H.264 config/AU 真解码 source 回归,再修第6、18节的数据适配问题。音频必须用固定段锚点加样本偏移,旧交接逐块使用当前 arrival 的建议已撤回;元数据、实际尺寸、IDR/解码恢复、音频重启和停止失败都需覆盖。原始错误与审计工具在忽略的 `logs/remoteplay-audit-20260911/`、`out/remoteplay/audit-20260911/`。
+
+完成上述闭环后,按交接文档第 12 节继续生产 CMake、统一引擎路径、Remote Play 音频、DPAPI/UI、手柄和 PS5 实机验收。不能因为离线测试或 native 初始化通过就声称串流功能已经完成。
diff --git a/docs/remoteplay/SOURCES_CODE01.md b/docs/remoteplay/SOURCES_CODE01.md
new file mode 100644
index 00000000..ee456b73
--- /dev/null
+++ b/docs/remoteplay/SOURCES_CODE01.md
@@ -0,0 +1,39 @@
+# 源码依据与许可证记录
+
+> 本文原主体为用户 Code 01 包的历史来源记录。2026-09-11 二次审计确认:当前工作树未导入其 `prepare_chiaki.py` / metadata JSON / PatchToolsTests;实际 backend 改用普通视频 callback,metadata 丢失已列为必须修复的问题。当前 native build 使用五文件 MSVC patch,初始化已通过;当前 source adapter 则有真解码/PCM/PTS失败。状态和命令以 [主交接第18节](../REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md#18-2026-09-11-二次代码审计用户要求交给其他-agent-修) 为准,不能照下方历史描述寻找不存在的元数据脚本。
+
+## Veyra 审查基线
+
+`https://github.com/Likely7/Veyra-NRVideo/tree/ff4122befc5909682d7a4df29da086d5f5bb619d`
+
+本轮通过 GitHub 连接确认 HEAD,读取 `AGENTS.md`、相关输入/引擎/UI 文件,与前次审查方案对照。本地直接 clone 未成功,因此没有声称完整仓库在本容器构建通过。
+
+## Chiaki 真实 API 来源
+
+固定:`https://github.com/streetpea/chiaki-ng/tree/0e16950165f06e5c3291537c2eeba6e852be7120`
+
+使用与核对的位置:
+
+- `lib/include/chiaki/common.h`:`chiaki_lib_init`、target、codec。
+- `lib/include/chiaki/session.h`:连接资料、事件、视频回调、stop/join、PIN、控制和 IDR。
+- `lib/src/session.c`:结构归零、连接初始化、profile 与码率单位。
+- `lib/include/chiaki/regist.h`、`lib/src/regist.c`:配对资料与 `fini` 内 join。
+- `lib/include/chiaki/opusdecoder.h`、`lib/src/opusdecoder.c`:每声道 `samples_count`。
+- `lib/include/chiaki/controller.h`:按钮枚举与 idle 初始化。
+- `lib/include/chiaki/log.h`:回调签名;避免转发原始密钥日志。
+- `lib/src/videoreceiver.c`:配置头及画面样本的不同发出点、frame_index 和 reference-recovered。
+- 根及 `lib/CMakeLists.txt`、`third-party/CMakeLists.txt`:实际依赖与目标 `chiaki-lib`。
+- `COPYING`、`LICENSES/AGPL-3.0-only-OpenSSL.txt`:上游许可与 OpenSSL 附加许可。
+
+元数据补丁是可审查的改动数据,并非伪造上游 API 已经存在;`prepare_chiaki.py` 明确添加 `CHIAKI_VEYRA_VIDEO_METADATA_API`,adapter 没有它就编译失败。
+
+## FFmpeg 包泵行为参考
+
+官方 send/receive API 说明:
+`https://ffmpeg.org/doxygen/trunk/group__lavc__encdec.html`
+
+EAGAIN 不消费输入;必须先 receive,再重送原 packet。当前 PacketPump 的控制流已用脚本化 codec 验证;本包未包含 FFmpeg,也没有声称实际解码或硬解通过。
+
+## 本包许可边界
+
+新写源码:GPL-3.0-only。Chiaki 本体及修改后派生文件保留其 AGPL-3.0-only/OpenSSL 许可标识。本包没有专有 SDK、运行时、模型、第三方二进制或真实 PSN 凭据。源码许可记录不替代未来完整程序/运行时组合的分发审查。
diff --git a/docs/remoteplay/WORKLOG_CODE01.md b/docs/remoteplay/WORKLOG_CODE01.md
new file mode 100644
index 00000000..d9e858c3
--- /dev/null
+++ b/docs/remoteplay/WORKLOG_CODE01.md
@@ -0,0 +1,35 @@
+# Remote Play 代码交付 01 — 实施记录
+
+> 历史阶段记录:本文保留 Code 01 交付当时的状态,其中“原生编译未执行”和 `BLOCKED_NATIVE_BUILD` 已过期。Windows x64/MSVC 原生 Chiaki probe 后续已完成 248/248 步并真实初始化成功。当前事实、必修缺陷和下一步只以 [`../REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md`](../REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md) 为准。
+
+> 二次审计已写入主交接第18节:普通 callback 替换了本包的 metadata 扩展;H.264 首帧、PCM 和 PTS 在实际 source 中失败,67项原包核心测试不覆盖它们。当前不是继续重复 native 初始化,而是先修数据适配层。
+
+2026-09-11,基线:Veyra `ff4122befc5909682d7a4df29da086d5f5bb619d`;Chiaki `0e16950165f06e5c3291537c2eeba6e852be7120`。
+
+## 已实现(代码)
+
+`Types/Validation`、`AnnexB`、`Timeline`、`VideoIngress/AudioIngress`、`LatestMailbox`、`PacketPump`、`InputGate`、`SessionInbox` 已有真实实现和离线测试。
+
+`ChiakiBackend/ChiakiRegistration` 使用已核对的真实 API,元数据扩展保存在可审查 JSON 中;这部分仅完成源码,原生编译和真机调用未执行。
+
+## 对总方案的对应关系
+
+| 总方案职责 | 本包实现位置 | 状态 |
+|---|---|---|
+| 配置、Account-ID、配对码严格校验 | `Types.h` / `Validation.cpp` | 离线测试通过 |
+| 回调元数据扩展 | `chiaki_metadata_patch.json` / `prepare_chiaki.py` | 片段变换测试通过;完整上游应用未在本环境执行 |
+| 有界视频输入与恢复 | `VideoIngress` | 离线测试通过 |
+| 音频缓冲与每声道采样计数 | `AudioIngress` | 离线测试通过;WASAPI 未接 |
+| 时基、帧编号展开 | `Timeline` | 离线测试通过;本机估计不是远端 PTS |
+| AVFrame 最新帧邮箱 | `LatestMailbox<T>` | 所有权逻辑测试通过;实际 T 需绑定 AVFrame 引用 |
+| EAGAIN 包泵 | `PacketPump<Packet>` | 控制流测试通过;真实 FFmpeg 适配未接 |
+| 会话回调代次 | `SessionInbox` | 离线测试通过;不冒充完整会话控制器 |
+| Chiaki 核心会话/配对/音频/控制 | `ChiakiBackend.cpp` / `ChiakiRegistration.cpp` | 源码完成,BLOCKED_NATIVE_BUILD |
+| 现有 IFrameSource 接入、引擎、界面 | 无生产挂接 | NOT_IMPLEMENTED_IN_CODE01 |
+| PS5、GPU、OBS、低延迟 | 无硬件验证 | BLOCKED_HARDWARE |
+
+测试证据随交付包 `TEST_REPORT.md` 与 `evidence/` 提供。没有改变生产主程序、已有采集卡、旧增强后端、发布版本或运行时。
+
+## 下一条唯一任务
+
+Windows 上配置真实依赖、应用固定上游元数据补丁,并构建/运行 native probe。若失败,保留真实错误定位编译依赖,不先写 UI 来掩盖 native 缺口。
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index 57d3cf01..1082dd00 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -40,6 +40,7 @@ enum class SourceKind : uint8_t {
Unknown = 0,
File, // FFmpeg demux/decode (player, export)
CaptureCard, // physical DirectShow/UVC capture
+ RemotePlay, // PS5 Remote Play stream (Chiaki transport)
Image, // WIC single image
TestPattern, // synthetic harness input
};
@@ -48,6 +49,7 @@ inline const char* sourceKindName(SourceKind k) {
switch (k) {
case SourceKind::File: return "File";
case SourceKind::CaptureCard: return "CaptureCard";
+ case SourceKind::RemotePlay: return "RemotePlay";
case SourceKind::Image: return "Image";
case SourceKind::TestPattern: return "TestPattern";
default: return "Unknown";
diff --git a/include/veyra/remoteplay/ChiakiBackend.h b/include/veyra/remoteplay/ChiakiBackend.h
new file mode 100644
index 00000000..1289cd3a
--- /dev/null
+++ b/include/veyra/remoteplay/ChiakiBackend.h
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include "SessionInbox.h"
+#include <array>
+#include <chrono>
+#include <memory>
+#include <stop_token>
+#include <string>
+
+namespace veyra::remoteplay {
+// No serialization/ostream support: never put registration/session keys into
+// command lines, logs, fixtures or source control. DPAPI storage is NOT in patch 01.
+struct PairingCredentials {
+ PairingCredentials() = default;
+ PairingCredentials(const PairingCredentials&) = delete;
+ PairingCredentials& operator=(const PairingCredentials&) = delete;
+ PairingCredentials(PairingCredentials&&) noexcept;
+ PairingCredentials& operator=(PairingCredentials&&) noexcept;
+ AccountId accountId{};
+ std::array<char,16> registrationKey{};
+ std::array<std::uint8_t,16> sessionKey{};
+ ~PairingCredentials();
+};
+struct BackendResult {
+ bool ok=false;
+ int code=0;
+ // One of our fixed operation names, never an unfiltered server string.
+ std::string operation;
+};
+struct NativeConnectRequest {
+ std::string host;
+ VideoProfile video;
+ PairingCredentials credentials;
+};
+struct NativeSnapshot {
+ bool started=false,connected=false;
+ std::uint64_t warnings=0,errors=0,videoCallbacks=0,audioCallbacks=0;
+ int lastQuitReason=0,lastApiError=0;
+};
+BackendResult initializeChiaki();
+class ChiakiBackend {
+public:
+ ChiakiBackend();
+ ~ChiakiBackend();
+ ChiakiBackend(const ChiakiBackend&)=delete;
+ 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);
+ BackendResult stop(); // Does not call PS5 goto_bed; must precede inbox.finishStop().
+ BackendResult requestIdr();
+ BackendResult submitController(const ControllerState&);
+ BackendResult submitLoginPin(std::string_view);
+ NativeSnapshot snapshot() const;
+private:
+ struct Impl;
+ std::unique_ptr<Impl> p_;
+};
+struct PairResult {
+ BackendResult result;
+ PairingCredentials credentials;
+ std::array<std::uint8_t,6> mac{};
+ std::string nickname;
+ bool canceled=false,timedOut=false;
+};
+// Synchronous OWNERSHIP operation; run on a dedicated session/setup worker, not HWND.
+// Cancellation stops the upstream registration and joins before returning.
+PairResult pairLocalPs5(std::string host,const AccountId&,std::string_view eightDigitPin,
+ std::stop_token stop={},std::chrono::milliseconds timeout=std::chrono::seconds(30));
+} // namespace veyra::remoteplay
diff --git a/include/veyra/remoteplay/InputGate.h b/include/veyra/remoteplay/InputGate.h
new file mode 100644
index 00000000..fa671dab
--- /dev/null
+++ b/include/veyra/remoteplay/InputGate.h
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include "Types.h"
+#include <mutex>
+#include <stdexcept>
+namespace veyra::remoteplay {
+// Device polling remains outside the GPU render loop. UI focus loss must call
+// setFocused(false) immediately. A new session starts neutral and unfocused.
+class InputGate {
+public:
+ void begin(Generation g) {if(!g)throw std::invalid_argument("Generation zero is invalid");std::lock_guard l(mutex_);generation_=g;focused_=false;state_={};stamp_=0;}
+ void setFocused(bool value) {std::lock_guard l(mutex_);focused_=value;state_={};stamp_=0;}
+ bool update(Generation g,const ControllerState& s,HostTime now) {
+ std::lock_guard l(mutex_);if(g!=generation_||!focused_||now<0||now<stamp_)return false;
+ state_=s;state_.buttons&=0xffffu;stamp_=now;return true;
+ }
+ ControllerState sample(Generation g,HostTime now) const {
+ std::lock_guard l(mutex_);
+ if(!focused_||g!=generation_||now<stamp_||now-stamp_>1000000)return {}; // 100 ms stale input fails neutral.
+ return state_;
+ }
+private:
+ mutable std::mutex mutex_;Generation generation_=0;bool focused_=false;ControllerState state_{};HostTime stamp_=0;
+};
+} // namespace veyra::remoteplay
diff --git a/include/veyra/remoteplay/LatestMailbox.h b/include/veyra/remoteplay/LatestMailbox.h
new file mode 100644
index 00000000..5d320265
--- /dev/null
+++ b/include/veyra/remoteplay/LatestMailbox.h
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include "Types.h"
+#include <mutex>
+#include <optional>
+#include <stdexcept>
+#include <utility>
+namespace veyra::remoteplay {
+// Only for DECODED reference-counted frames. Never feed compressed packets here.
+// T should own an av_frame_clone/ref (custom deleter); a raw AVFrame* is not ownership.
+template<class T> class LatestMailbox {
+public:
+ struct Entry {Generation generation;std::uint64_t sequence;T value;};
+ void begin(Generation generation) {
+ if(!generation)throw std::invalid_argument("Generation zero is invalid");
+ std::optional<Entry> retired;
+ {std::lock_guard lock(mutex_);retired.swap(entry_);generation_=generation;closed_=false;overwritten_=0;lastSequence_=0;}
+ }
+ bool publish(Entry incoming) {
+ std::optional<Entry> retired;
+ {std::lock_guard lock(mutex_);
+ if(closed_||incoming.generation!=generation_||incoming.sequence<=lastSequence_)return false;
+ lastSequence_=incoming.sequence;if(entry_){++overwritten_;retired.swap(entry_);}entry_.emplace(std::move(incoming));}
+ return true; // Retired frame released outside the mailbox mutex.
+ }
+ std::optional<Entry> take() {
+ std::lock_guard lock(mutex_);auto out=std::move(entry_);entry_.reset();return out;
+ }
+ void close() {
+ std::optional<Entry> retired;
+ {std::lock_guard lock(mutex_);closed_=true;retired.swap(entry_);}
+ }
+ std::uint64_t overwritten() const {std::lock_guard lock(mutex_);return overwritten_;}
+private:
+ mutable std::mutex mutex_;std::optional<Entry> entry_;
+ Generation generation_=0;std::uint64_t lastSequence_=0,overwritten_=0;bool closed_=true;
+};
+} // namespace veyra::remoteplay
diff --git a/include/veyra/remoteplay/PacketPump.h b/include/veyra/remoteplay/PacketPump.h
new file mode 100644
index 00000000..e698ccaf
--- /dev/null
+++ b/include/veyra/remoteplay/PacketPump.h
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <utility>
+namespace veyra::remoteplay {
+enum class SendStatus {Accepted,NeedDrain,End,Error};
+enum class ReceiveStatus {Frame,NeedInput,End,Error};
+enum class PumpStatus {Idle,Yield,End,Error,ProtocolViolation};
+struct PumpStats {std::uint64_t accepted=0,frames=0,eagain=0;};
+// Codec requirements: send(const Packet&) -> SendStatus, receive() -> ReceiveStatus.
+// receive() must transfer/clone each actual decoded frame before the next call.
+// EAGAIN NEVER consumes pending_. A small work budget bounds each invocation.
+template<class Packet> class PacketPump {
+public:
+ bool submit(Packet packet) {
+ if(pending_||ended_||failed_) return false;
+ pending_.emplace(std::move(packet));
+ return true;
+ }
+ template<class Codec> PumpStatus step(Codec& codec,std::size_t budget=64) {
+ if(failed_) return PumpStatus::Error;
+ if(ended_) return PumpStatus::End;
+ if(!budget)return PumpStatus::Yield;
+ for(std::size_t i=0;i<budget;++i){
+ if(draining_){
+ switch(codec.receive()){
+ case ReceiveStatus::Frame:++stats_.frames;drainProgress_=true;break;
+ case ReceiveStatus::NeedInput:
+ draining_=false;
+ if(retry_&&!drainProgress_){failed_=true;return PumpStatus::ProtocolViolation;}
+ retry_=false;drainProgress_=false;
+ if(!pending_)return PumpStatus::Idle;
+ break;
+ case ReceiveStatus::End:ended_=true;pending_.reset();return PumpStatus::End;
+ case ReceiveStatus::Error:failed_=true;return PumpStatus::Error;
+ }
+ }else{
+ if(!pending_)return PumpStatus::Idle;
+ switch(codec.send(*pending_)){
+ case SendStatus::Accepted:++stats_.accepted;pending_.reset();draining_=true;drainProgress_=false;retry_=false;break;
+ case SendStatus::NeedDrain:++stats_.eagain;draining_=true;drainProgress_=false;retry_=true;break;
+ case SendStatus::End:ended_=true;pending_.reset();return PumpStatus::End;
+ case SendStatus::Error:failed_=true;return PumpStatus::Error;
+ }
+ }
+ }
+ return PumpStatus::Yield;
+ }
+ bool hasPending() const noexcept {return pending_.has_value();}
+ bool drained() const noexcept {return !pending_&&!draining_;}
+ const PumpStats& stats() const noexcept {return stats_;}
+ void reset(){pending_.reset();draining_=retry_=drainProgress_=ended_=failed_=false;stats_={};}
+private:
+ std::optional<Packet> pending_;bool draining_=false,retry_=false,drainProgress_=false,ended_=false,failed_=false;PumpStats stats_{};
+};
+} // namespace veyra::remoteplay
diff --git a/include/veyra/remoteplay/SessionInbox.h b/include/veyra/remoteplay/SessionInbox.h
new file mode 100644
index 00000000..d69e7eb7
--- /dev/null
+++ b/include/veyra/remoteplay/SessionInbox.h
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include "VideoIngress.h"
+#include <memory>
+#include <stdexcept>
+namespace veyra::remoteplay {
+// Thread-safe callback boundary, NOT a replacement Remote Play protocol/session.
+// Invalidate before stopping Chiaki, join all its callbacks, then finishStop().
+// Tokens hold weak ownership so a saved callback cannot resurrect a destroyed inbox.
+class SessionInbox {
+ struct Shared;
+public:
+ struct Snapshot {
+ Generation generation=0;SessionState state=SessionState::Idle;HostTime commonOrigin100ns=0;
+ std::uint64_t staleCallbacks=0;int errorCode=0;
+ VideoQueueStats video;AudioQueueStats audio;
+ };
+ class Token {
+ public:
+ bool video(VideoSample sample) const noexcept;
+ bool audio(PcmBlock block) const noexcept;
+ void connected() const noexcept;
+ void loginPinRequired() const noexcept;
+ void failed(int code) const noexcept;
+ Generation generation()const noexcept{return generation_;}
+ private:
+ friend class SessionInbox;Token(std::weak_ptr<Shared> shared,Generation g):shared_(std::move(shared)),generation_(g){}
+ std::weak_ptr<Shared> shared_;Generation generation_=0;
+ };
+ explicit SessionInbox(QueueLimits limits={});
+ ~SessionInbox();
+ SessionInbox(const SessionInbox&)=delete;SessionInbox& operator=(const SessionInbox&)=delete;
+ Token begin(HostTime commonOrigin);
+ void invalidate();
+ void finishStop(); // Only after actual backend stop/join, not from a callback.
+ bool decodedFrameReady(Generation);
+ std::optional<QueuedVideo> tryVideo(HostTime now);
+ std::optional<PcmBlock> tryAudio();
+ bool takeIdrRequest(HostTime now);
+ void decodeFailed(Generation);
+ bool isCurrent(Generation)const;
+ Snapshot snapshot()const;
+private:
+ std::shared_ptr<Shared> shared_;
+};
+} // namespace veyra::remoteplay
diff --git a/include/veyra/remoteplay/Timeline.h b/include/veyra/remoteplay/Timeline.h
new file mode 100644
index 00000000..1086ecd5
--- /dev/null
+++ b/include/veyra/remoteplay/Timeline.h
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include "Types.h"
+namespace veyra::remoteplay {
+class Sequence16Extender {
+public:
+ struct Result {std::uint64_t value=0;bool accepted=false,first=false;std::uint32_t gap=0;};
+ Result observe(std::uint16_t) noexcept;
+ void reset() noexcept {*this={};}
+private:
+ bool initialized_=false;std::uint16_t previous_=0;std::uint64_t extended_=0;
+};
+struct EstimatedStamp {
+ std::int64_t pts100ns=0,duration100ns=0;
+ bool discontinuity=false;
+ TimestampProvenance provenance=TimestampProvenance::LocalEstimated;
+};
+// A shared local origin for audio and video, NOT independent zero-at-first-frame clocks.
+// Source index gives cadence, host arrival provides an anchor. Reset after network
+// discontinuity; consumer must advance its epoch and reset temporal GPU history.
+class RemotePlayClock {
+public:
+ void reset(HostTime commonOrigin,std::uint32_t fps);
+ std::optional<EstimatedStamp> video(std::uint64_t index,HostTime arrival);
+ std::optional<std::int64_t> audioPts(std::uint64_t firstSample,std::uint32_t rate,HostTime audioStart) const noexcept;
+private:
+ HostTime origin_=0,videoAnchor_=0,lastArrival_=0;
+ std::uint64_t firstIndex_=0,lastIndex_=0;
+ std::uint32_t fps_=0;bool anchored_=false;
+};
+} // namespace veyra::remoteplay
diff --git a/include/veyra/remoteplay/Types.h b/include/veyra/remoteplay/Types.h
new file mode 100644
index 00000000..a0d4d206
--- /dev/null
+++ b/include/veyra/remoteplay/Types.h
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <span>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace veyra::remoteplay {
+using HostTime = std::int64_t; // Local steady-clock, 100 ns. NEVER PS5 render time.
+using Generation = std::uint64_t;
+HostTime monotonic100ns() noexcept;
+
+enum class Codec : std::uint8_t { H264, H265 };
+enum class TimestampProvenance : std::uint8_t { Unknown, SourceProvided, LocalEstimated };
+enum class SessionState : std::uint8_t { Idle, Connecting, WaitingFirstFrame, Streaming, LoginPinRequired, Failed, Stopping };
+enum class SampleKind : std::uint8_t { CodecConfig, AccessUnit };
+struct VideoProfile {
+ std::uint32_t width = 1920, height = 1080, fps = 60, bitrateKbps = 15000;
+ Codec codec = Codec::H264;
+ std::optional<std::string> validate() const;
+};
+using AccountId = std::array<std::uint8_t, 8>;
+std::optional<AccountId> accountIdFromBase64(std::string_view);
+std::optional<AccountId> accountIdFromDecimal(std::string_view);
+std::string accountIdToBase64(const AccountId&);
+std::optional<std::uint32_t> parsePairingPin(std::string_view);
+bool validHost(std::string_view) noexcept; // IPv4 or DNS hostname; no URL/userinfo/path/port.
+bool validProfileId(std::string_view) noexcept;
+
+// 64 is the required FFmpeg input padding at the audited API. Consumers using
+// another ABI must static_assert against AV_INPUT_BUFFER_PADDING_SIZE.
+class PaddedBytes {
+public:
+ static constexpr std::size_t Padding = 64;
+ PaddedBytes() = default;
+ static PaddedBytes copy(std::span<const std::uint8_t>);
+ std::span<const std::uint8_t> bytes() const noexcept { return {storage_.data(), size_}; }
+ const std::uint8_t* data() const noexcept { return storage_.data(); }
+ std::size_t size() const noexcept { return size_; }
+ bool paddingIsZero() const noexcept;
+private:
+ std::vector<std::uint8_t> storage_;
+ std::size_t size_ = 0;
+};
+struct VideoSample {
+ Generation generation = 0;
+ SampleKind kind = SampleKind::AccessUnit;
+ Codec codec = Codec::H264;
+ PaddedBytes payload;
+ // Present only when supplied by the metadata extension, never invented.
+ std::optional<std::uint16_t> wireFrameIndex;
+ std::uint32_t width = 0, height = 0;
+ std::int32_t framesLost = 0;
+ bool referenceRecovered = false; // NOT a FEC success or a keyframe indicator.
+ HostTime arrival100ns = 0;
+};
+struct NalInfo {
+ bool valid = false, hasPicture = false, hasConfig = false, idr = false;
+};
+// Annex-B only. H.265 CRA is intentionally NOT considered a clean IDR.
+NalInfo inspectAnnexB(std::span<const std::uint8_t>, Codec) noexcept;
+
+struct PcmBlock {
+ Generation generation = 0;
+ std::uint32_t channels = 0, rate = 0;
+ std::uint64_t firstSample = 0; // Per channel, not interleaved element count.
+ HostTime arrival100ns = 0;
+ bool discontinuity = false;
+ std::vector<std::int16_t> samples;
+ std::size_t frames() const noexcept { return channels ? samples.size()/channels : 0; }
+ bool valid() const noexcept;
+};
+struct ControllerState {
+ // Semantic buttons; translated explicitly to Chiaki in the native bridge.
+ enum Button : std::uint32_t { Cross=1u<<0, Circle=1u<<1, Square=1u<<2, Triangle=1u<<3,
+ Left=1u<<4, Right=1u<<5, Up=1u<<6, Down=1u<<7, L1=1u<<8, R1=1u<<9,
+ L3=1u<<10, R3=1u<<11, Options=1u<<12, Share=1u<<13, Touchpad=1u<<14, PS=1u<<15 };
+ std::uint32_t buttons = 0;
+ std::int16_t leftX=0, leftY=0, rightX=0, rightY=0;
+ std::uint8_t l2=0, r2=0;
+ bool operator==(const ControllerState&) const = default;
+};
+} // namespace veyra::remoteplay
diff --git a/include/veyra/remoteplay/VideoIngress.h b/include/veyra/remoteplay/VideoIngress.h
new file mode 100644
index 00000000..967e4850
--- /dev/null
+++ b/include/veyra/remoteplay/VideoIngress.h
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+#include "Types.h"
+#include "Timeline.h"
+#include <chrono>
+#include <condition_variable>
+#include <deque>
+#include <memory>
+#include <mutex>
+namespace veyra::remoteplay {
+struct QueueLimits {
+ std::size_t maxFrames=4, maxBytes=8u*1024u*1024u, maxConfigBytes=64u*1024u;
+ HostTime maxAge100ns=1000000; // 100 ms development safety ceiling, not target latency.
+ void validate() const;
+};
+enum class PushStatus {Accepted,ConfigStored,WaitingForIdr,Malformed,WrongGeneration,Closed};
+struct VideoQueueStats {
+ std::uint64_t accessUnits=0,configMessages=0,accepted=0,consumed=0,dropped=0,
+ rejected=0,recoveries=0,idrRequests=0;
+ std::size_t depth=0,bytes=0,highWaterDepth=0,highWaterBytes=0;
+ bool waitingForIdr=true;std::uint64_t epoch=1;
+};
+struct QueuedVideo {
+ VideoSample sample;
+ // Full configuration snapshot must be fed before this AU when non-null.
+ // The caller drains EAGAIN then retries; do not drop it as "not a picture".
+ std::shared_ptr<const VideoSample> configBefore;
+ std::uint64_t epoch=1;
+ bool resetDecoder=false;
+};
+class VideoIngress {
+public:
+ explicit VideoIngress(QueueLimits limits={});
+ void begin(Generation);
+ PushStatus push(VideoSample,HostTime now);
+ std::optional<QueuedVideo> tryPop(HostTime now);
+ bool waitForData(std::chrono::milliseconds timeout);
+ // Poll from the protocol OWNER, never request an IDR while holding a C callback's lock.
+ bool takeIdrRequest(HostTime now);
+ void requireKeyframe(); // Decoder reports fatal error / lost references.
+ void close();
+ VideoQueueStats stats() const;
+private:
+ void recoverLocked();
+ void updateStatsLocked();
+ bool expiredLocked(HostTime now) const;
+ QueueLimits limits_;mutable std::mutex mutex_;std::condition_variable cv_;
+ std::deque<QueuedVideo> queue_;std::shared_ptr<const VideoSample> config_;
+ Generation generation_=0;std::size_t payloadBytes_=0;bool closed_=true,waiting_=true,pendingIdr_=false;
+ HostTime lastIdr_=-1;Sequence16Extender sequence_;VideoQueueStats stats_{};
+};
+struct AudioQueueStats {std::uint64_t accepted=0,consumed=0,dropped=0,rejected=0;double bufferedMs=0;};
+class AudioIngress {
+public:
+ explicit AudioIngress(std::uint32_t maxBufferedMs=100);
+ void begin(Generation);
+ bool push(PcmBlock);
+ std::optional<PcmBlock> tryPop();
+ void close();
+ AudioQueueStats stats() const;
+private:
+ mutable std::mutex mutex_;std::deque<PcmBlock> queue_;
+ Generation generation_=0;std::uint32_t rate_=0,channels_=0,maxMs_;std::size_t frames_=0;
+ std::uint64_t nextSample_=0;bool closed_=true,gap_=false;AudioQueueStats stats_{};
+};
+} // namespace veyra::remoteplay
diff --git a/include/veyra/source/RemotePlaySource.h b/include/veyra/source/RemotePlaySource.h
new file mode 100644
index 00000000..5f1360be
--- /dev/null
+++ b/include/veyra/source/RemotePlaySource.h
@@ -0,0 +1,98 @@
+#pragma once
+
+// RemotePlaySource adapts the Chiaki callback stream to the same source
+// contract used by local files and capture cards. Chiaki owns the network
+// protocol; this class owns FFmpeg decoder state and decoded-frame lifetime.
+#include "veyra/source/IFrameSource.h"
+#include "veyra/remoteplay/ChiakiBackend.h"
+#include "veyra/remoteplay/SessionInbox.h"
+#include "veyra/remoteplay/Timeline.h"
+#include "veyra/sink/AudioPcmSource.h"
+
+#include <cstdint>
+#include <deque>
+#include <memory>
+#include <optional>
+#include <span>
+#include <string>
+
+struct AVCodecContext;
+struct AVFrame;
+
+namespace veyra::source {
+
+struct RemotePlayConnectDesc {
+ remoteplay::NativeConnectRequest request;
+ remoteplay::QueueLimits queueLimits{};
+};
+
+class RemotePlaySource final : public IFrameSource {
+public:
+ RemotePlaySource();
+ ~RemotePlaySource() override;
+
+ RemotePlaySource(const RemotePlaySource&) = delete;
+ RemotePlaySource& operator=(const RemotePlaySource&) = delete;
+
+ // IFrameSource::open cannot carry credentials. Product callers use
+ // connect() and then read(); open() deliberately fails closed.
+ bool open(const SourceOpenDesc& desc) override;
+ bool connect(const RemotePlayConnectDesc& desc);
+ bool connected() const noexcept { return connected_; }
+ remoteplay::SessionInbox::Snapshot sessionSnapshot() const;
+
+ const SourceInfo& info() const override { return info_; }
+ SourceReadStatus read(pipeline::FramePacket& out, const AVFrame** decodedFrame) override;
+ bool seek(const pipeline::Rational&) override { return false; }
+ void close() noexcept override;
+
+ // Pull decoded Opus PCM for the existing WASAPI AudioPcmSource adapter.
+ std::size_t pullAudio(float* stereo, std::size_t frames, double* firstPtsMs);
+
+private:
+ struct DecodedFrame {
+ std::shared_ptr<AVFrame> frame;
+ pipeline::FramePacket packet;
+ };
+
+ bool openDecoder(remoteplay::Codec codec, std::uint32_t width, std::uint32_t height);
+ bool submitPacket(std::span<const std::uint8_t> bytes, std::uint64_t sourceIndex,
+ const pipeline::FramePacket& sourcePacket);
+ bool drainDecoder(std::uint64_t sourceIndex, const pipeline::FramePacket& sourcePacket);
+ void flushDecoder() noexcept;
+ pipeline::FramePacket makePacket(const remoteplay::VideoSample& sample,
+ std::uint64_t sourceIndex, std::uint64_t epoch, bool reset);
+
+ std::unique_ptr<remoteplay::SessionInbox> inbox_;
+ remoteplay::ChiakiBackend backend_;
+ std::optional<remoteplay::SessionInbox::Token> token_;
+ remoteplay::RemotePlayClock clock_;
+ remoteplay::NativeConnectRequest request_;
+ SourceInfo info_{};
+ AVCodecContext* codecContext_ = nullptr;
+ AVFrame* decoderFrame_ = nullptr;
+ std::deque<DecodedFrame> ready_;
+ std::shared_ptr<AVFrame> lastFrame_;
+ std::uint64_t sequence_ = 0;
+ std::uint64_t fallbackSourceIndex_ = 0;
+ std::uint64_t decoderEpoch_ = 1;
+ std::uint64_t origin100ns_ = 0;
+ bool connected_ = false;
+ bool decoderReady_ = false;
+ bool waitingForFirstFrame_ = true;
+ bool pendingOpenFlag_ = true;
+};
+
+class RemotePlayAudioSource final : public sink::AudioPcmSource {
+public:
+ explicit RemotePlayAudioSource(RemotePlaySource& source) : source_(source) {}
+ std::size_t pull(float* stereo, std::size_t frames, double* firstPtsMs) override;
+ std::optional<double> lastPullEndPtsMs() const override { return lastEndPtsMs_; }
+ bool padUnderruns() const override { return false; }
+
+private:
+ RemotePlaySource& source_;
+ std::optional<double> lastEndPtsMs_;
+};
+
+} // namespace veyra::source
diff --git a/scripts/remoteplay/build-native.ps1 b/scripts/remoteplay/build-native.ps1
new file mode 100644
index 00000000..a8f13789
--- /dev/null
+++ b/scripts/remoteplay/build-native.ps1
@@ -0,0 +1,67 @@
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory=$true)][string]$ChiakiCheckout,
+ [string]$Root = "",
+ [string]$StageDirectory = "",
+ [string]$BuildDirectory = "",
+ [string]$PrefixPath = "",
+ [string]$ToolchainFile = "",
+ [string]$ProtocPath = "",
+ [string]$PkgConfigPath = "",
+ [string]$Generator = "Ninja"
+)
+$ErrorActionPreference = "Stop"
+if (-not $Root) { $Root = (Resolve-Path (Join-Path $PSScriptRoot "../..")).Path }
+else { $Root = (Resolve-Path $Root).Path }
+$ChiakiCheckout = (Resolve-Path $ChiakiCheckout).Path
+if (-not $BuildDirectory) { $BuildDirectory = Join-Path $Root "out/remoteplay/native" }
+if (-not $StageDirectory) { $StageDirectory = Join-Path $Root "out/remoteplay/chiaki-msvc-stage" }
+function Invoke-Checked([string]$Command, [string[]]$Arguments) {
+ & $Command @Arguments
+ if ($LASTEXITCODE -ne 0) { throw "$Command failed with exit code $LASTEXITCODE" }
+}
+$PinnedCommit = "0e16950165f06e5c3291537c2eeba6e852be7120"
+$PatchFile = Join-Path $Root "scripts/remoteplay/patches/0001-chiaki-msvc-vla-compat.patch"
+$head = (& git -C $ChiakiCheckout rev-parse HEAD).Trim()
+if ($LASTEXITCODE -ne 0 -or $head -ne $PinnedCommit) { throw "Chiaki source pin mismatch: $head" }
+$sourceStatus = (& git -C $ChiakiCheckout status --porcelain --untracked-files=no) -join "`n"
+if ($LASTEXITCODE -ne 0 -or $sourceStatus) { throw "Chiaki source checkout must be clean" }
+if (-not (Test-Path -LiteralPath (Join-Path $StageDirectory ".git"))) {
+ if (Test-Path -LiteralPath $StageDirectory) { throw "Refusing to replace an existing non-worktree stage: $StageDirectory" }
+ New-Item -ItemType Directory -Force -Path (Split-Path -Parent $StageDirectory) | Out-Null
+ Invoke-Checked "git" @("-C",$ChiakiCheckout,"worktree","add","--detach",$StageDirectory,$PinnedCommit)
+ Invoke-Checked "git" @("-C",$StageDirectory,"submodule","update","--init","--recursive")
+}
+$stageHead = (& git -C $StageDirectory rev-parse HEAD).Trim()
+if ($LASTEXITCODE -ne 0 -or $stageHead -ne $PinnedCommit) { throw "Chiaki staging pin mismatch: $stageHead" }
+$stageStatus = @(& git -C $StageDirectory status --porcelain --untracked-files=no)
+if ($LASTEXITCODE -ne 0) { throw "Unable to inspect Chiaki staging worktree" }
+if ($stageStatus.Count -eq 0) {
+ Invoke-Checked "git" @("-C",$StageDirectory,"apply","--check",$PatchFile)
+ Invoke-Checked "git" @("-C",$StageDirectory,"apply",$PatchFile)
+} else {
+ Invoke-Checked "git" @("-C",$StageDirectory,"apply","--reverse","--check",$PatchFile)
+}
+$patchedFiles = @(& git -C $StageDirectory diff --name-only)
+if ($LASTEXITCODE -ne 0 -or ($patchedFiles -join "|") -ne "lib/src/ctrl.c|lib/src/regist.c|lib/src/remote/holepunch.c|lib/src/remote/rudp.c|lib/src/session.c") {
+ throw "Chiaki staging contains changes outside the reviewed MSVC patch: $($patchedFiles -join ', ')"
+}
+Invoke-Checked "git" @("-C",$StageDirectory,"diff","--check")
+$Args = @("-S", (Join-Path $Root "services/remoteplay-probe"), "-B", $BuildDirectory,
+ "-G", $Generator, "-DCMAKE_BUILD_TYPE=Release", "-DVEYRA_RP_BUILD_NATIVE=ON",
+ "-DVEYRA_RP_CHIAKI_SOURCE_DIR=$StageDirectory", "-DVEYRA_RP_CHIAKI_VERIFY_DIR=$ChiakiCheckout",
+ "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded")
+if ($PrefixPath) { $Args += "-DCMAKE_PREFIX_PATH=$PrefixPath" }
+if ($ToolchainFile) { $Args += "-DCMAKE_TOOLCHAIN_FILE=$ToolchainFile" }
+if ($ProtocPath) {
+ $ProtocPath = (Resolve-Path $ProtocPath).Path
+ $Args += "-DPROTOC=$ProtocPath"
+}
+if ($PkgConfigPath) {
+ $PkgConfigPath = (Resolve-Path $PkgConfigPath).Path
+ $Args += "-DPKG_CONFIG_EXECUTABLE=$PkgConfigPath"
+}
+Invoke-Checked "cmake" $Args
+Invoke-Checked "cmake" @("--build", $BuildDirectory, "--config", "Release", "--target", "veyra_remoteplay_native_probe")
+Invoke-Checked "ctest" @("--test-dir", $BuildDirectory, "-C", "Release", "-L", "native-core", "--output-on-failure", "--timeout", "30")
+Write-Host "Native initialization gate completed. PS5 connection, decoder and GPU are still NOT tested by this probe."
diff --git a/scripts/remoteplay/dependency-lock.json b/scripts/remoteplay/dependency-lock.json
new file mode 100644
index 00000000..f3fe9b63
--- /dev/null
+++ b/scripts/remoteplay/dependency-lock.json
@@ -0,0 +1,13 @@
+{
+ "veyra_reviewed_commit": "ff4122befc5909682d7a4df29da086d5f5bb619d",
+ "chiaki_repository": "https://github.com/streetpea/chiaki-ng.git",
+ "chiaki_commit": "0e16950165f06e5c3291537c2eeba6e852be7120",
+ "recursive_submodules": "must match gitlinks in the pinned tree",
+ "native_api": "unmodified chiaki_session_set_video_sample_cb",
+ "native_dependencies": ["Opus", "OpenSSL", "nanopb/protobuf tooling", "Jerasure/gf-complete", "curl", "json-c", "libevent", "miniupnpc"],
+ "ffmpeg": "reuse Veyra's installed version; not needed by patch-01 core or Chiaki-native probe",
+ "msvc_compatibility_patch": "patches/0001-chiaki-msvc-vla-compat.patch",
+ "msvc_compatibility_scope": ["lib/src/ctrl.c", "lib/src/regist.c", "lib/src/remote/holepunch.c", "lib/src/remote/rudp.c", "lib/src/session.c"],
+ "native_build_status_at_delivery": "PATCH_READY_REBUILD_PENDING",
+ "no_runtime_dlls_or_vendor_sdks_in_this_package": true
+}
diff --git a/scripts/remoteplay/patches/0001-chiaki-msvc-vla-compat.patch b/scripts/remoteplay/patches/0001-chiaki-msvc-vla-compat.patch
new file mode 100644
index 00000000..f061c61e
--- /dev/null
+++ b/scripts/remoteplay/patches/0001-chiaki-msvc-vla-compat.patch
@@ -0,0 +1,502 @@
+diff --git a/lib/src/ctrl.c b/lib/src/ctrl.c
+index 6a3b762..1e4dae0 100644
+--- a/lib/src/ctrl.c
++++ b/lib/src/ctrl.c
+@@ -673,14 +673,25 @@ static ChiakiErrorCode ctrl_message_send(ChiakiCtrl *ctrl, uint16_t type, const
+
+ if(ctrl->session->rudp)
+ {
+- uint8_t buf_size = 8 + payload_size;
+- uint8_t buf[buf_size];
++ if(payload_size > SIZE_MAX - sizeof(header))
++ {
++ free(enc);
++ return CHIAKI_ERR_INVALID_DATA;
++ }
++ size_t buf_size = sizeof(header) + payload_size;
++ uint8_t *buf = malloc(buf_size);
++ if(!buf)
++ {
++ free(enc);
++ return CHIAKI_ERR_MEMORY;
++ }
+ memcpy(buf, header, 8);
+ if(enc)
+ memcpy(buf + 8, enc, payload_size);
+ free(enc);
+ ChiakiErrorCode err;
+ err = chiaki_rudp_send_ctrl_message(ctrl->session->rudp, buf, buf_size);
++ free(buf);
+ if(err != CHIAKI_ERR_SUCCESS)
+ {
+ CHIAKI_LOGE(ctrl->session->log, "Failed to send Ctrl Message");
+@@ -1172,11 +1183,28 @@ static ChiakiErrorCode ctrl_connect(ChiakiCtrl *ctrl)
+ CHIAKI_LOGE(session->log, "CTRL - Failed to init rudp");
+ goto error;
+ }
++ if(message.data_size < 8)
++ {
++ chiaki_rudp_message_pointers_free(&message);
++ err = CHIAKI_ERR_INVALID_RESPONSE;
++ goto error;
++ }
+ size_t init_response_size = message.data_size - 8;
+- uint8_t init_response[init_response_size];
+- memcpy(init_response, message.data + 8, init_response_size);
++ uint8_t *init_response = NULL;
++ if(init_response_size > 0)
++ {
++ init_response = malloc(init_response_size);
++ if(!init_response)
++ {
++ chiaki_rudp_message_pointers_free(&message);
++ err = CHIAKI_ERR_MEMORY;
++ goto error;
++ }
++ memcpy(init_response, message.data + 8, init_response_size);
++ }
+ chiaki_rudp_message_pointers_free(&message);
+ err = chiaki_rudp_send_recv(session->rudp, &message, init_response, init_response_size, 0, COOKIE_REQUEST, COOKIE_RESPONSE, 2, 3);
++ free(init_response);
+ if(err != CHIAKI_ERR_SUCCESS)
+ {
+ CHIAKI_LOGE(session->log, "CTRL - Failed to pass rudp cookie");
+diff --git a/lib/src/regist.c b/lib/src/regist.c
+index 88f3001..a6ee796 100644
+--- a/lib/src/regist.c
++++ b/lib/src/regist.c
+@@ -287,11 +287,28 @@ static void *regist_thread_func(void *user)
+ CHIAKI_LOGE(regist->log, "REGIST - Failed to init rudp");
+ goto fail;
+ }
++ if(message.data_size < 8)
++ {
++ chiaki_rudp_message_pointers_free(&message);
++ err = CHIAKI_ERR_INVALID_RESPONSE;
++ goto fail;
++ }
+ size_t init_response_size = message.data_size - 8;
+- uint8_t init_response[init_response_size];
+- memcpy(init_response, message.data + 8, init_response_size);
++ uint8_t *init_response = NULL;
++ if(init_response_size > 0)
++ {
++ init_response = malloc(init_response_size);
++ if(!init_response)
++ {
++ chiaki_rudp_message_pointers_free(&message);
++ err = CHIAKI_ERR_MEMORY;
++ goto fail;
++ }
++ memcpy(init_response, message.data + 8, init_response_size);
++ }
+ chiaki_rudp_message_pointers_free(&message);
+ err = chiaki_rudp_send_recv(regist->info.rudp, &message, init_response, init_response_size, 0, COOKIE_REQUEST, COOKIE_RESPONSE, 2, 3);
++ free(init_response);
+ if(err != CHIAKI_ERR_SUCCESS)
+ {
+ CHIAKI_LOGE(regist->log, "REGIST - Failed to pass rudp cookie");
+diff --git a/lib/src/remote/holepunch.c b/lib/src/remote/holepunch.c
+index 9a5bc69..6cf89d7 100644
+--- a/lib/src/remote/holepunch.c
++++ b/lib/src/remote/holepunch.c
+@@ -3271,12 +3271,35 @@ static ChiakiErrorCode http_send_session_message(Session *session, SessionMessag
+ char *payload_str = NULL;
+ size_t payload_len = 0;
+ if(short_msg)
+- short_message_serialize(session, message, &payload_str, &payload_len);
++ err = short_message_serialize(session, message, &payload_str, &payload_len);
+ else
+- session_message_serialize(session, message, &payload_str, &payload_len);
+- char msg_buf[sizeof(session_message_envelope_fmt) * 2 + payload_len];
++ err = session_message_serialize(session, message, &payload_str, &payload_len);
++ if(err != CHIAKI_ERR_SUCCESS || !payload_str)
++ {
++ free(payload_str);
++ free(response_data.data);
++ return err != CHIAKI_ERR_SUCCESS ? err : CHIAKI_ERR_INVALID_DATA;
++ }
++ int msg_len = snprintf(
++ NULL, 0, session_message_envelope_fmt,
++ payload_str, session->account_id, console_uid_str,
++ session->console_type == CHIAKI_HOLEPUNCH_CONSOLE_TYPE_PS4 ? "PS4" : "PS5"
++ );
++ if(msg_len < 0 || (size_t)msg_len == SIZE_MAX)
++ {
++ free(payload_str);
++ free(response_data.data);
++ return CHIAKI_ERR_INVALID_DATA;
++ }
++ char *msg_buf = malloc((size_t)msg_len + 1);
++ if(!msg_buf)
++ {
++ free(payload_str);
++ free(response_data.data);
++ return CHIAKI_ERR_MEMORY;
++ }
+ snprintf(
+- msg_buf, sizeof(msg_buf), session_message_envelope_fmt,
++ msg_buf, (size_t)msg_len + 1, session_message_envelope_fmt,
+ payload_str, session->account_id, console_uid_str,
+ session->console_type == CHIAKI_HOLEPUNCH_CONSOLE_TYPE_PS4 ? "PS4" : "PS5"
+ );
+@@ -3284,6 +3307,7 @@ static ChiakiErrorCode http_send_session_message(Session *session, SessionMessag
+ CURL *curl = curl_easy_init();
+ if(!curl)
+ {
++ free(msg_buf);
+ free(payload_str);
+ free(response_data.data);
+ CHIAKI_LOGE(session->log, "Curl could not init");
+@@ -3339,6 +3363,7 @@ static ChiakiErrorCode http_send_session_message(Session *session, SessionMessag
+
+ cleanup:
+ curl_easy_cleanup(curl);
++ free(msg_buf);
+ free(payload_str);
+ free(response_data.data);
+ return err;
+@@ -3820,19 +3845,38 @@ static ChiakiErrorCode check_candidates(
+ Candidate *local_candidate = &local_candidates[0];
+ Candidate *remote_candidate = &local_candidates[1];
+
++ if(num_candidates == 0 || !candidates_received || num_candidates > SIZE_MAX - EXTRA_CANDIDATE_ADDRESSES)
++ return CHIAKI_ERR_INVALID_DATA;
+ size_t extra_addresses_used = 0;
+- // Set up addresses for each candidate + extras (use sockaddr_storage and cast bc needs to be at least that big if we get ipv6)
+- struct sockaddr_storage addrs[num_candidates + EXTRA_CANDIDATE_ADDRESSES];
+- socklen_t lens[num_candidates + EXTRA_CANDIDATE_ADDRESSES];
+- Candidate candidates[num_candidates + EXTRA_CANDIDATE_ADDRESSES];
++ size_t candidate_capacity = num_candidates + EXTRA_CANDIDATE_ADDRESSES;
++ if(candidate_capacity > SIZE_MAX / sizeof(struct sockaddr_storage)
++ || candidate_capacity > SIZE_MAX / sizeof(socklen_t)
++ || candidate_capacity > SIZE_MAX / sizeof(Candidate)
++ || candidate_capacity > SIZE_MAX / sizeof(int))
++ return CHIAKI_ERR_INVALID_DATA;
++ // Candidate count comes from the network. Keep these buffers bounded by checked heap allocations.
++ struct sockaddr_storage *addrs = calloc(candidate_capacity, sizeof(*addrs));
++ socklen_t *lens = calloc(candidate_capacity, sizeof(*lens));
++ Candidate *candidates = calloc(candidate_capacity, sizeof(*candidates));
++ int *responses_received = calloc(candidate_capacity, sizeof(*responses_received));
++ if(!addrs || !lens || !candidates || !responses_received)
++ {
++ free(addrs);
++ free(lens);
++ free(candidates);
++ free(responses_received);
++ return CHIAKI_ERR_MEMORY;
++ }
+ memcpy(candidates, candidates_received, num_candidates * sizeof(Candidate));
+- int responses_received[num_candidates + EXTRA_CANDIDATE_ADDRESSES];
+ #ifdef __SWITCH__
+ // Use poll() on Switch — select() fails when FD numbers >= FD_SETSIZE (256)
+ struct pollfd *pollfds = NULL;
+ #endif
+ #ifdef __ANDROID__
+ fd_set fds;
++#endif
++#if !defined(__SWITCH__) && !defined(__ANDROID__)
++ CandidateEventContext poll_ctx = {0};
+ #endif
+ bool failed = true;
+ char service_remote[6];
+@@ -4019,7 +4063,6 @@ static ChiakiErrorCode check_candidates(
+ bool connecting = false;
+ int retry_counter = 0;
+ #if !defined(__SWITCH__) && !defined(__ANDROID__)
+- CandidateEventContext poll_ctx = {0};
+ size_t socket_slots = 0;
+ if (!CHIAKI_SOCKET_IS_INVALID(session->ipv4_sock))
+ socket_slots++;
+@@ -4614,6 +4657,10 @@ static ChiakiErrorCode check_candidates(
+ free(pollfds);
+ #endif
+ free(socks);
++ free(addrs);
++ free(lens);
++ free(candidates);
++ free(responses_received);
+ return CHIAKI_ERR_SUCCESS;
+
+ cleanup_sockets:
+@@ -4654,6 +4701,10 @@ cleanup_sockets:
+ }
+ }
+ free(socks);
++ free(addrs);
++ free(lens);
++ free(candidates);
++ free(responses_received);
+ return err;
+ }
+
+@@ -4966,12 +5017,16 @@ static json_object* session_message_get_payload(ChiakiLog *log, json_object *ses
+ // Insert empty object as key for localPeerAddr key
+ size_t prefix_len = peeraddr_end - json;
+ size_t suffix_len = strlen(peeraddr_end);
+- char fixed_json[strlen(json) + 3]; // {} + \0
+- memset(fixed_json, 0, sizeof(fixed_json));
+- strncpy(fixed_json, json, prefix_len);
++ size_t json_len = strlen(json);
++ if(json_len > SIZE_MAX - 3)
++ return NULL;
++ char *fixed_json = calloc(json_len + 3, 1); // {} + \0
++ if(!fixed_json)
++ return NULL;
++ memcpy(fixed_json, json, prefix_len);
+ fixed_json[prefix_len] = '{';
+ fixed_json[prefix_len + 1] = '}';
+- strncpy(fixed_json + prefix_len + 2, peeraddr_end, suffix_len);
++ memcpy(fixed_json + prefix_len + 2, peeraddr_end, suffix_len);
+
+ message_json = json_tokener_parse(fixed_json);
+ if(message_json == NULL)
+@@ -4979,6 +5034,7 @@ static json_object* session_message_get_payload(ChiakiLog *log, json_object *ses
+ CHIAKI_LOGE(log, "Couldn't parse the following fixed json: %s", fixed_json);
+ CHIAKI_LOGE(log, json_object_to_json_string_ext(payload_json, JSON_C_TO_STRING_PRETTY));
+ }
++ free(fixed_json);
+ }
+ // check if parse fails
+ if(message_json == NULL)
+diff --git a/lib/src/remote/rudp.c b/lib/src/remote/rudp.c
+index d2b9c22..a4f5067 100644
+--- a/lib/src/remote/rudp.c
++++ b/lib/src/remote/rudp.c
+@@ -89,7 +89,7 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_init_message(RudpInstance *rudp)
+ message.type = INIT_REQUEST;
+ message.subMessage = NULL;
+ message.data_size = 14;
+- uint8_t data[message.data_size];
++ uint8_t data[14];
+ size_t alloc_size = 8 + message.data_size;
+ uint8_t *serialized_msg = malloc(alloc_size * sizeof(uint8_t));
+ if(!serialized_msg)
+@@ -114,6 +114,8 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_init_message(RudpInstance *rudp)
+
+ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_cookie_message(RudpInstance *rudp, uint8_t *response_buf, size_t response_size)
+ {
++ if(response_size > 0x0FFFu - 22u || (response_size > 0 && !response_buf))
++ return CHIAKI_ERR_INVALID_DATA;
+ RudpMessage message;
+ uint16_t local_counter = get_then_increase_counter(rudp);
+ message.type = COOKIE_REQUEST;
+@@ -121,14 +123,16 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_cookie_message(RudpInstance *rudp
+ message.data_size = 14 + response_size;
+ size_t alloc_size = 8 + message.data_size;
+ uint8_t *serialized_msg = malloc(alloc_size * sizeof(uint8_t));
+- if(!serialized_msg)
++ uint8_t *data = malloc(message.data_size);
++ if(!serialized_msg || !data)
+ {
++ free(serialized_msg);
++ free(data);
+ CHIAKI_LOGE(rudp->log, "Error allocating memory for rudp message");
+ return CHIAKI_ERR_MEMORY;
+ }
+ size_t msg_size = 0;
+ message.size = (0xC << 12) | alloc_size;
+- uint8_t data[message.data_size];
+ const uint8_t after_header[0x2] = { 0x05, 0x82 };
+ const uint8_t after_counter[0x6] = { 0x0B, 0x01, 0x01, 0x00, 0x01, 0x00 };
+ *(chiaki_unaligned_uint16_t *)(data) = htons(local_counter);
+@@ -139,19 +143,24 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_cookie_message(RudpInstance *rudp
+ message.data = data;
+ rudp_message_serialize(&message, serialized_msg, &msg_size);
+ ChiakiErrorCode err = chiaki_rudp_send_raw(rudp, serialized_msg, msg_size);
++ free(data);
+ free(serialized_msg);
+ return err;
+ }
+
+ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_session_message(RudpInstance *rudp, uint16_t remote_counter, uint8_t *session_msg, size_t session_msg_size)
+ {
++ if(session_msg_size > 0x0FFFu - 10u || (session_msg_size > 0 && !session_msg))
++ return CHIAKI_ERR_INVALID_DATA;
+ RudpMessage subMessage;
+ uint16_t local_counter = get_then_increase_counter(rudp);
+ subMessage.type = CTRL_MESSAGE;
+ subMessage.subMessage = NULL;
+ subMessage.data_size = 2 + session_msg_size;
+ subMessage.size = (0xC << 12) | (8 + subMessage.data_size);
+- uint8_t subdata[subMessage.data_size];
++ uint8_t *subdata = malloc(subMessage.data_size);
++ if(!subdata)
++ return CHIAKI_ERR_MEMORY;
+ *(chiaki_unaligned_uint16_t *)(subdata) = htons(local_counter);
+ memcpy(subdata + 2, session_msg, session_msg_size);
+ subMessage.data = subdata;
+@@ -164,17 +173,19 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_session_message(RudpInstance *rud
+ uint8_t *serialized_msg = malloc(alloc_size * sizeof(uint8_t));
+ if(!serialized_msg)
+ {
++ free(subdata);
+ CHIAKI_LOGE(rudp->log, "Error allocating memory for rudp message");
+ return CHIAKI_ERR_MEMORY;
+ }
+ size_t msg_size = 0;
+ message.size = (0xC << 12) | (8 + message.data_size);
+- uint8_t data[message.data_size];
++ uint8_t data[4];
+ *(chiaki_unaligned_uint16_t *)(data) = htons(local_counter);
+ *(chiaki_unaligned_uint16_t *)(data + 2) = htons(remote_counter);
+ message.data = data;
+ rudp_message_serialize(&message, serialized_msg, &msg_size);
+ ChiakiErrorCode err = chiaki_rudp_send_raw(rudp, serialized_msg, msg_size);
++ free(subdata);
+ free(serialized_msg);
+ return err;
+ }
+@@ -195,7 +206,7 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_ack_message(RudpInstance *rudp, u
+ }
+ size_t msg_size = 0;
+ message.size = (0xC << 12) | alloc_size;
+- uint8_t data[message.data_size];
++ uint8_t data[6];
+ const uint8_t after_counters[0x2] = { 0x00, 0x92 };
+ *(chiaki_unaligned_uint16_t *)(data) = htons(counter);
+ *(chiaki_unaligned_uint16_t *)(data + 2) = htons(remote_counter);
+@@ -209,6 +220,8 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_ack_message(RudpInstance *rudp, u
+
+ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_ctrl_message(RudpInstance *rudp, uint8_t *ctrl_message, size_t ctrl_message_size)
+ {
++ if(ctrl_message_size > 0x0FFFu - 10u || (ctrl_message_size > 0 && !ctrl_message))
++ return CHIAKI_ERR_INVALID_DATA;
+ RudpMessage message;
+ uint16_t counter = get_then_increase_counter(rudp);
+ uint16_t counter_ack = rudp->counter;
+@@ -217,19 +230,22 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_ctrl_message(RudpInstance *rudp,
+ message.data_size = 2 + ctrl_message_size;
+ size_t alloc_size = 8 + message.data_size;
+ uint8_t *serialized_msg = malloc(alloc_size * sizeof(uint8_t));
+- if(!serialized_msg)
++ uint8_t *data = malloc(message.data_size);
++ if(!serialized_msg || !data)
+ {
++ free(serialized_msg);
++ free(data);
+ CHIAKI_LOGE(rudp->log, "Error allocating memory for rudp message");
+ return CHIAKI_ERR_MEMORY;
+ }
+ size_t msg_size = 0;
+ message.size = (0xC << 12) | alloc_size;
+- uint8_t data[message.data_size];
+ *(chiaki_unaligned_uint16_t *)(data) = htons(counter);
+ memcpy(data + 2, ctrl_message, ctrl_message_size);
+ message.data = data;
+ rudp_message_serialize(&message, serialized_msg, &msg_size);
+ ChiakiErrorCode err = chiaki_rudp_send_raw(rudp, serialized_msg, msg_size);
++ free(data);
+ if(err != CHIAKI_ERR_SUCCESS)
+ {
+ free(serialized_msg);
+@@ -256,9 +272,9 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_switch_to_stream_connection_messa
+ }
+ size_t msg_size = 0;
+ message.size = (0xC << 12) | alloc_size;
+- uint8_t data[message.data_size];
++ uint8_t data[26];
+ const size_t buf_size = 16;
+- uint8_t buf[buf_size];
++ uint8_t buf[16];
+ const uint8_t before_buf[8] = { 0x00, 0x00, 0x00, 0x10, 0x00, 0x0D, 0x00, 0x00 };
+ chiaki_random_bytes_crypt(buf, buf_size);
+ *(chiaki_unaligned_uint16_t *)(data) = htons(counter);
+@@ -393,13 +409,21 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_send_raw(RudpInstance *rudp, uint8_t *
+
+ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_select_recv(RudpInstance *rudp, size_t buf_size, RudpMessage *message)
+ {
+- uint8_t buf[buf_size];
++ if(buf_size <= 8 || buf_size > 64u * 1024u)
++ return CHIAKI_ERR_INVALID_DATA;
++ uint8_t *buf = malloc(buf_size);
++ if(!buf)
++ return CHIAKI_ERR_MEMORY;
+ ChiakiErrorCode err = chiaki_stop_pipe_select_single(&rudp->stop_pipe, rudp->sock, false, RUDP_EXPECT_TIMEOUT_MS);
+ if(err == CHIAKI_ERR_TIMEOUT || err == CHIAKI_ERR_CANCELED)
++ {
++ free(buf);
+ return err;
++ }
+ if(err != CHIAKI_ERR_SUCCESS)
+ {
+ CHIAKI_LOGE(rudp->log, "Rudp select failed: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
++ free(buf);
+ return err;
+ }
+
+@@ -410,19 +434,25 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_select_recv(RudpInstance *rudp, size_t
+ CHIAKI_LOGE(rudp->log, "Rudp recv failed: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
+ else
+ CHIAKI_LOGE(rudp->log, "Rudp recv returned less than the required 8 byte RUDP header");
++ free(buf);
+ return CHIAKI_ERR_NETWORK;
+ }
+ CHIAKI_LOGV(rudp->log, "Receiving message:");
+ chiaki_log_hexdump(rudp->log, CHIAKI_LOG_VERBOSE, buf, received_sz);
+
+ err = chiaki_rudp_message_parse(buf, received_sz, message);
++ free(buf);
+
+ return err;
+ }
+
+ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_recv_only(RudpInstance *rudp, size_t buf_size, RudpMessage *message)
+ {
+- uint8_t buf[buf_size];
++ if(buf_size <= 8 || buf_size > 64u * 1024u)
++ return CHIAKI_ERR_INVALID_DATA;
++ uint8_t *buf = malloc(buf_size);
++ if(!buf)
++ return CHIAKI_ERR_MEMORY;
+ CHIAKI_SSIZET_TYPE received_sz = recv(rudp->sock, (CHIAKI_SOCKET_BUF_TYPE) buf, buf_size, 0);
+ if(received_sz <= 8)
+ {
+@@ -430,12 +460,14 @@ CHIAKI_EXPORT ChiakiErrorCode chiaki_rudp_recv_only(RudpInstance *rudp, size_t b
+ CHIAKI_LOGE(rudp->log, "Rudp recv failed: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
+ else
+ CHIAKI_LOGE(rudp->log, "Rudp recv returned less than the required 8 byte RUDP header");
++ free(buf);
+ return CHIAKI_ERR_NETWORK;
+ }
+ CHIAKI_LOGV(rudp->log, "Receiving message:");
+ chiaki_log_hexdump(rudp->log, CHIAKI_LOG_VERBOSE, buf, received_sz);
+
+ ChiakiErrorCode err = chiaki_rudp_message_parse(buf, received_sz, message);
++ free(buf);
+
+ return err;
+ }
+diff --git a/lib/src/session.c b/lib/src/session.c
+index 41c6bbf..396df74 100644
+--- a/lib/src/session.c
++++ b/lib/src/session.c
+@@ -771,11 +771,26 @@ static ChiakiErrorCode session_thread_request_session(ChiakiSession *session, Ch
+ CHIAKI_LOGE(session->log, "SESSION START THREAD - Failed to init rudp");
+ return err;
+ }
++ if(message.data_size < 8)
++ {
++ chiaki_rudp_message_pointers_free(&message);
++ return CHIAKI_ERR_INVALID_RESPONSE;
++ }
+ size_t init_response_size = message.data_size - 8;
+- uint8_t init_response[init_response_size];
+- memcpy(init_response, message.data + 8, init_response_size);
++ uint8_t *init_response = NULL;
++ if(init_response_size > 0)
++ {
++ init_response = malloc(init_response_size);
++ if(!init_response)
++ {
++ chiaki_rudp_message_pointers_free(&message);
++ return CHIAKI_ERR_MEMORY;
++ }
++ memcpy(init_response, message.data + 8, init_response_size);
++ }
+ chiaki_rudp_message_pointers_free(&message);
+ err = chiaki_rudp_send_recv(session->rudp, &message, init_response, init_response_size, 0, COOKIE_REQUEST, COOKIE_RESPONSE, 2, 3);
++ free(init_response);
+ if(err != CHIAKI_ERR_SUCCESS)
+ {
+ CHIAKI_LOGE(session->log, "SESSION START THREAD - Failed to pass rudp cookie");
diff --git a/scripts/remoteplay/test-core.ps1 b/scripts/remoteplay/test-core.ps1
new file mode 100644
index 00000000..308ea6de
--- /dev/null
+++ b/scripts/remoteplay/test-core.ps1
@@ -0,0 +1,19 @@
+[CmdletBinding()]
+param(
+ [string]$Root = (Resolve-Path (Join-Path $PSScriptRoot "../..")),
+ [string]$BuildDirectory = "",
+ [string]$Generator = "Ninja",
+ [ValidateSet("Debug", "Release")][string]$Configuration = "Debug"
+)
+$ErrorActionPreference = "Stop"
+if (-not $BuildDirectory) { $BuildDirectory = Join-Path $Root "out/remoteplay/core-$Configuration" }
+function Invoke-Checked([string]$Command, [string[]]$Arguments) {
+ & $Command @Arguments
+ if ($LASTEXITCODE -ne 0) { throw "$Command failed with exit code $LASTEXITCODE" }
+}
+# For Ninja/MSVC use an x64 Developer PowerShell. No administrator permission needed.
+Invoke-Checked "cmake" @("-S", (Join-Path $Root "services/remoteplay-probe"), "-B", $BuildDirectory,
+ "-G", $Generator, "-DCMAKE_BUILD_TYPE=$Configuration", "-DVEYRA_RP_BUILD_NATIVE=OFF")
+Invoke-Checked "cmake" @("--build", $BuildDirectory, "--config", $Configuration)
+Invoke-Checked "ctest" @("--test-dir", $BuildDirectory, "-C", $Configuration, "--output-on-failure", "--timeout", "30")
+Write-Host "Offline core tests completed. This does NOT test the Windows player, Chiaki native linkage, PS5 or GPU."
diff --git a/services/remoteplay-probe/CMakeLists.txt b/services/remoteplay-probe/CMakeLists.txt
new file mode 100644
index 00000000..fe36372f
--- /dev/null
+++ b/services/remoteplay-probe/CMakeLists.txt
@@ -0,0 +1,40 @@
+cmake_minimum_required(VERSION 3.24)
+project(veyra_remoteplay_core_probe LANGUAGES CXX)
+include(CTest)
+find_package(Threads REQUIRED)
+get_filename_component(VEYRA_ROOT "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE)
+option(VEYRA_RP_SANITIZERS "Enable AddressSanitizer and UndefinedBehaviorSanitizer" OFF)
+option(VEYRA_RP_BUILD_NATIVE "Build the REAL pinned Chiaki adapter (requires dependencies)" OFF)
+add_library(veyra_remoteplay_core STATIC
+ "${VEYRA_ROOT}/src/remoteplay/Validation.cpp"
+ "${VEYRA_ROOT}/src/remoteplay/AnnexB.cpp"
+ "${VEYRA_ROOT}/src/remoteplay/Timeline.cpp"
+ "${VEYRA_ROOT}/src/remoteplay/VideoIngress.cpp"
+ "${VEYRA_ROOT}/src/remoteplay/SessionInbox.cpp")
+target_include_directories(veyra_remoteplay_core PUBLIC "${VEYRA_ROOT}/include")
+target_compile_features(veyra_remoteplay_core PUBLIC cxx_std_20)
+set_target_properties(veyra_remoteplay_core PROPERTIES CXX_EXTENSIONS OFF)
+target_link_libraries(veyra_remoteplay_core PUBLIC Threads::Threads)
+if(MSVC)
+ target_compile_options(veyra_remoteplay_core PUBLIC /utf-8 /W4 /WX /permissive-)
+else()
+ target_compile_options(veyra_remoteplay_core PUBLIC -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror)
+ if(VEYRA_RP_SANITIZERS)
+ target_compile_options(veyra_remoteplay_core PUBLIC -fsanitize=address,undefined -fno-omit-frame-pointer)
+ target_link_options(veyra_remoteplay_core PUBLIC -fsanitize=address,undefined)
+ endif()
+endif()
+add_executable(veyra_remoteplay_core_tests "${VEYRA_ROOT}/tests/remoteplay/CoreTests.cpp")
+target_link_libraries(veyra_remoteplay_core_tests PRIVATE veyra_remoteplay_core)
+# Deliberately no NVIDIA/FFmpeg/Win32 dependency in these tests. A pass here does
+# NOT establish native Chiaki compilation, video decoding, PS5 connection or latency.
+file(STRINGS "${VEYRA_ROOT}/tests/remoteplay/CoreTests.cpp" TEST_DECLS REGEX "^TEST\\([A-Za-z0-9_]+\\)")
+foreach(DECL IN LISTS TEST_DECLS)
+ string(REGEX MATCH "^TEST\\(([A-Za-z0-9_]+)\\)" _match "${DECL}")
+ set(NAME "${CMAKE_MATCH_1}")
+ add_test(NAME "rp.${NAME}" COMMAND veyra_remoteplay_core_tests --case "${NAME}")
+ set_tests_properties("rp.${NAME}" PROPERTIES TIMEOUT 30 LABELS "offline-core")
+endforeach()
+if(VEYRA_RP_BUILD_NATIVE)
+ include("${CMAKE_CURRENT_LIST_DIR}/NativeChiaki.cmake")
+endif()
diff --git a/services/remoteplay-probe/NativeChiaki.cmake b/services/remoteplay-probe/NativeChiaki.cmake
new file mode 100644
index 00000000..1d228a94
--- /dev/null
+++ b/services/remoteplay-probe/NativeChiaki.cmake
@@ -0,0 +1,75 @@
+# Native gate. No stub target is substituted when a dependency is absent.
+# Intentionally separate from the production player's CMake graph in patch 01.
+enable_language(C)
+set(VEYRA_RP_CHIAKI_SOURCE_DIR "" CACHE PATH "Patched chiaki-ng staging source tree")
+set(VEYRA_RP_CHIAKI_VERIFY_DIR "${VEYRA_RP_CHIAKI_SOURCE_DIR}" CACHE PATH "Clean pinned chiaki-ng checkout used to verify provenance")
+if(NOT EXISTS "${VEYRA_RP_CHIAKI_SOURCE_DIR}/lib/include/chiaki/session.h")
+ message(FATAL_ERROR "VEYRA_RP_BUILD_NATIVE needs the pinned chiaki-ng source tree")
+endif()
+find_package(Git REQUIRED)
+execute_process(
+ COMMAND "${GIT_EXECUTABLE}" -C "${VEYRA_RP_CHIAKI_VERIFY_DIR}" rev-parse HEAD
+ OUTPUT_VARIABLE CHIAKI_HEAD OUTPUT_STRIP_TRAILING_WHITESPACE
+ RESULT_VARIABLE CHIAKI_HEAD_RESULT)
+if(NOT CHIAKI_HEAD_RESULT EQUAL 0 OR NOT CHIAKI_HEAD STREQUAL "0e16950165f06e5c3291537c2eeba6e852be7120")
+ message(FATAL_ERROR "Chiaki source pin mismatch: ${CHIAKI_HEAD}")
+endif()
+execute_process(
+ COMMAND "${GIT_EXECUTABLE}" -C "${VEYRA_RP_CHIAKI_VERIFY_DIR}" status --porcelain --untracked-files=no
+ OUTPUT_VARIABLE CHIAKI_STATUS OUTPUT_STRIP_TRAILING_WHITESPACE
+ RESULT_VARIABLE CHIAKI_STATUS_RESULT)
+if(NOT CHIAKI_STATUS_RESULT EQUAL 0 OR NOT CHIAKI_STATUS STREQUAL "")
+ message(FATAL_ERROR "Chiaki source tree must be clean")
+endif()
+execute_process(
+ COMMAND "${GIT_EXECUTABLE}" -C "${VEYRA_RP_CHIAKI_SOURCE_DIR}" diff --name-only
+ OUTPUT_VARIABLE CHIAKI_STAGE_FILES OUTPUT_STRIP_TRAILING_WHITESPACE
+ RESULT_VARIABLE CHIAKI_STAGE_RESULT)
+string(REPLACE "\r\n" ";" CHIAKI_STAGE_FILES "${CHIAKI_STAGE_FILES}")
+string(REPLACE "\n" ";" CHIAKI_STAGE_FILES "${CHIAKI_STAGE_FILES}")
+list(SORT CHIAKI_STAGE_FILES)
+if(NOT CHIAKI_STAGE_RESULT EQUAL 0 OR NOT CHIAKI_STAGE_FILES STREQUAL "lib/src/ctrl.c;lib/src/regist.c;lib/src/remote/holepunch.c;lib/src/remote/rudp.c;lib/src/session.c")
+ message(FATAL_ERROR "Chiaki staging must contain only the reviewed MSVC compatibility patch: ${CHIAKI_STAGE_FILES}")
+endif()
+# Scope is this independent probe, NOT the production project. Target C++20
+# requirements remain explicit, despite the upstream top-level C++11 default.
+set(CHIAKI_ENABLE_GUI OFF CACHE BOOL "" FORCE)
+set(CHIAKI_ENABLE_CLI OFF CACHE BOOL "" FORCE)
+set(CHIAKI_ENABLE_TESTS OFF CACHE BOOL "" FORCE)
+set(CHIAKI_ENABLE_ANDROID OFF CACHE BOOL "" FORCE)
+set(CHIAKI_ENABLE_BOREALIS OFF CACHE BOOL "" FORCE)
+set(CHIAKI_ENABLE_FFMPEG_DECODER OFF CACHE STRING "" FORCE)
+set(CHIAKI_ENABLE_PI_DECODER OFF CACHE STRING "" FORCE)
+set(CHIAKI_ENABLE_SETSU OFF CACHE STRING "" FORCE)
+set(CHIAKI_ENABLE_STEAMDECK_NATIVE OFF CACHE STRING "" FORCE)
+set(CHIAKI_ENABLE_STEAM_SHORTCUT OFF CACHE BOOL "" FORCE)
+set(CHIAKI_ENABLE_SPEEX OFF CACHE STRING "" FORCE)
+set(CHIAKI_ENABLE_RUDP OFF CACHE STRING "" FORCE)
+set(CHIAKI_LIB_ENABLE_OPUS ON CACHE BOOL "" FORCE)
+set(CHIAKI_LIB_ENABLE_MBEDTLS OFF CACHE BOOL "" FORCE)
+set(CHIAKI_USE_SYSTEM_NANOPB OFF CACHE STRING "" FORCE)
+set(CHIAKI_USE_SYSTEM_JERASURE OFF CACHE STRING "" FORCE)
+set(CHIAKI_USE_SYSTEM_CURL OFF CACHE STRING "" FORCE)
+# Disabling RUDP does NOT remove curl/json-c/libevent/miniupnpc in the pinned lib.
+# Provision their REAL matching-toolchain dev libraries; never replace them with
+# empty imported targets or remove FEC to force the native gate green.
+add_subdirectory("${VEYRA_RP_CHIAKI_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/chiaki" EXCLUDE_FROM_ALL)
+if(NOT TARGET chiaki-lib)
+ message(FATAL_ERROR "Upstream chiaki-lib target was not created")
+endif()
+# vcpkg's static miniupnpc headers default to dllimport on Windows unless the
+# caller opts into the static ABI. Without this definition the static library
+# is found correctly but Chiaki emits unresolved __imp_* references.
+target_compile_definitions(chiaki-lib PRIVATE MINIUPNP_STATICLIB)
+add_library(veyra_remoteplay_chiaki STATIC
+ "${VEYRA_ROOT}/src/remoteplay/ChiakiBackend.cpp"
+ "${VEYRA_ROOT}/src/remoteplay/ChiakiRegistration.cpp")
+target_compile_features(veyra_remoteplay_chiaki PUBLIC cxx_std_20)
+target_compile_definitions(veyra_remoteplay_chiaki PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+target_link_libraries(veyra_remoteplay_chiaki PUBLIC veyra_remoteplay_core PRIVATE chiaki-lib)
+add_executable(veyra_remoteplay_native_probe "${CMAKE_CURRENT_LIST_DIR}/native_main.cpp")
+target_compile_features(veyra_remoteplay_native_probe PRIVATE cxx_std_20)
+target_compile_definitions(veyra_remoteplay_native_probe PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+target_link_libraries(veyra_remoteplay_native_probe PRIVATE veyra_remoteplay_chiaki chiaki-lib)
+add_test(NAME rp.native_core_initialization COMMAND veyra_remoteplay_native_probe)
+set_tests_properties(rp.native_core_initialization PROPERTIES TIMEOUT 30 LABELS "native-core;not-ps5")
diff --git a/services/remoteplay-probe/native_main.cpp b/services/remoteplay-probe/native_main.cpp
new file mode 100644
index 00000000..ce36e137
--- /dev/null
+++ b/services/remoteplay-probe/native_main.cpp
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/remoteplay/ChiakiBackend.h"
+#include <chiaki/session.h>
+#include <chiaki/controller.h>
+#include <iostream>
+int main(){
+ auto init=veyra::remoteplay::initializeChiaki();
+ if(!init.ok){std::cerr<<init.operation<<" failed code="<<init.code<<'\n';return 1;}
+ ChiakiConnectVideoProfile p{};
+ chiaki_connect_video_profile_preset(&p,CHIAKI_VIDEO_RESOLUTION_PRESET_1080p,CHIAKI_VIDEO_FPS_PRESET_60);
+ ChiakiControllerState c{};chiaki_controller_state_set_idle(&c);
+ if(p.width!=1920||p.height!=1080||p.max_fps!=60||c.buttons!=0){std::cerr<<"Native profile/controller contract failed\n";return 1;}
+ std::cout<<"REAL_CHIAKI_CORE_INITIALIZED upstream_video_callback=1\n";
+ std::cout<<"PS5_CONNECTION_NOT_TESTED VIDEO_DECODE_NOT_TESTED WINDOWS_PLAYER_NOT_TESTED\n";
+ return 0;
+}
diff --git a/src/remoteplay/AnnexB.cpp b/src/remoteplay/AnnexB.cpp
new file mode 100644
index 00000000..6056a00b
--- /dev/null
+++ b/src/remoteplay/AnnexB.cpp
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/remoteplay/Types.h"
+namespace veyra::remoteplay {
+NalInfo inspectAnnexB(std::span<const std::uint8_t> b,Codec codec) noexcept {
+ NalInfo out; if(codec!=Codec::H264 && codec!=Codec::H265)return out;
+ std::size_t pos=0;bool any=false;
+ while(pos+3<=b.size()) {
+ std::size_t prefix=0;
+ if(b[pos]==0 && b[pos+1]==0){
+ if(b[pos+2]==1)prefix=3;
+ else if(pos+4<=b.size()&&b[pos+2]==0&&b[pos+3]==1)prefix=4;
+ }
+ if(!prefix){if(!any && b[pos]!=0)return {}; ++pos;continue;}
+ const auto h=pos+prefix;
+ if(h>=b.size() || (b[h]&0x80u))return {};
+ unsigned type=0;
+ if(codec==Codec::H264){
+ type=b[h]&31u; if(type==0 || type>23)return {};
+ out.hasPicture|=type>=1 && type<=5;out.idr|=type==5;out.hasConfig|=type==7 || type==8;
+ }else{
+ if(h+1>=b.size() || (b[h+1]&7u)==0)return {}; // nuh_temporal_id_plus1 != 0
+ type=(b[h]>>1)&63u;out.hasPicture|=type<=31;
+ out.idr|=type==19||type==20;out.hasConfig|=type==32||type==33||type==34;
+ }
+ any=true;pos=h+(codec==Codec::H264?1u:2u);
+ }
+ out.valid=any;return out;
+}
+} // namespace veyra::remoteplay
diff --git a/src/remoteplay/ChiakiBackend.cpp b/src/remoteplay/ChiakiBackend.cpp
new file mode 100644
index 00000000..f78183eb
--- /dev/null
+++ b/src/remoteplay/ChiakiBackend.cpp
@@ -0,0 +1,213 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Uses chiaki-ng's AGPL-3.0-only + OpenSSL-exception APIs; retain both licenses.
+// NOT compiled/tested in the Linux delivery environment: see the native gate.
+#include "veyra/remoteplay/ChiakiBackend.h"
+#include <chiaki/session.h>
+#include <chiaki/opusdecoder.h>
+#include <chiaki/controller.h>
+#include <chiaki/log.h>
+#include <algorithm>
+#include <atomic>
+#include <cstring>
+#include <limits>
+#include <mutex>
+#include <thread>
+namespace veyra::remoteplay {
+static_assert(CHIAKI_PSN_ACCOUNT_ID_SIZE == 8);
+static_assert(CHIAKI_SESSION_AUTH_SIZE == 16);
+namespace {
+void wipe(void* ptr,std::size_t n) noexcept {
+ auto* p=static_cast<volatile unsigned char*>(ptr);
+ while(n--) *p++=0;
+}
+BackendResult result(ChiakiErrorCode code,const char* operation) {
+ return {code==CHIAKI_ERR_SUCCESS,static_cast<int>(code),operation};
+}
+}
+PairingCredentials::PairingCredentials(PairingCredentials&& other) noexcept { *this=std::move(other); }
+PairingCredentials& PairingCredentials::operator=(PairingCredentials&& other) noexcept {
+ if(this==&other) return *this;
+ registrationKey=other.registrationKey;sessionKey=other.sessionKey;accountId=other.accountId;
+ wipe(other.registrationKey.data(),other.registrationKey.size());
+ wipe(other.sessionKey.data(),other.sessionKey.size());wipe(other.accountId.data(),other.accountId.size());
+ return *this;
+}
+PairingCredentials::~PairingCredentials(){wipe(registrationKey.data(),registrationKey.size());wipe(sessionKey.data(),sessionKey.size());wipe(accountId.data(),accountId.size());}
+BackendResult initializeChiaki(){
+ static std::once_flag flag;
+ static ChiakiErrorCode code=CHIAKI_ERR_UNKNOWN;
+ std::call_once(flag,[]{code=chiaki_lib_init();});
+ return result(code,"chiaki_lib_init");
+}
+struct ChiakiBackend::Impl {
+ explicit Impl(SessionInbox::Token t):token(std::move(t)),owner(std::this_thread::get_id()){}
+ SessionInbox::Token token;
+ std::thread::id owner;
+ ChiakiSession session{};
+ ChiakiOpusDecoder opus{};
+ ChiakiLog log{};
+ VideoProfile profile;
+ std::string host;
+ bool initialized=false,opusInitialized=false;
+ std::atomic<bool> active=false,started=false,connected=false;
+ std::atomic<std::uint64_t> warnings=0,errors=0,videoCallbacks=0,audioCallbacks=0;
+ std::atomic<int> quitReason=0,apiError=0;
+ // Only the upstream audio/Opus callback thread reads/writes these fields.
+ std::uint32_t channels=0,rate=0;
+ std::uint64_t sampleIndex=0;
+ static void logCallback(ChiakiLogLevel level,const char*,void* user) noexcept {
+ auto& self=*static_cast<Impl*>(user);
+ // Raw upstream log strings/hexdumps may contain keys. Do not forward them.
+ if(level==CHIAKI_LOG_ERROR)++self.errors;
+ if(level==CHIAKI_LOG_WARNING)++self.warnings;
+ }
+ static void eventCallback(ChiakiEvent* event,void* user) noexcept {
+ auto& self=*static_cast<Impl*>(user);
+ if(!event||!self.active.load())return;
+ switch(event->type){
+ case CHIAKI_EVENT_CONNECTED:self.connected=true;self.token.connected();break;
+ case CHIAKI_EVENT_LOGIN_PIN_REQUEST:self.token.loginPinRequired();break;
+ case CHIAKI_EVENT_QUIT:
+ self.connected=false;self.quitReason=static_cast<int>(event->quit.reason);
+ // A remote termination is not a successful decoded EOF.
+ self.token.failed(2000+static_cast<int>(event->quit.reason));break;
+ default:break; // No unsolicited mic, standby, haptics or keyboard side effects.
+ }
+ }
+ static bool videoCallback(std::uint8_t* data,std::size_t size,
+ std::int32_t framesLost,bool frameRecovered,void* user) noexcept {
+ auto& self=*static_cast<Impl*>(user);
+ if(!self.active.load()||!data||!size)return false;
+ try{
+ const auto nal=inspectAnnexB({data,size},self.profile.codec);
+ if(!nal.valid || (!nal.hasConfig&&!nal.hasPicture))return false;
+ VideoSample sample;
+ sample.generation=self.token.generation();sample.arrival100ns=monotonic100ns();
+ sample.codec=self.profile.codec;
+ sample.kind=nal.hasPicture?SampleKind::AccessUnit:SampleKind::CodecConfig;
+ sample.width=self.profile.width;sample.height=self.profile.height;
+ sample.framesLost=framesLost;sample.referenceRecovered=frameRecovered;
+ sample.payload=PaddedBytes::copy({data,size});++self.videoCallbacks;
+ return self.token.video(std::move(sample));
+ }catch(...){self.apiError=-1001;self.token.failed(-1001);return false;}
+ }
+ static void opusSettings(std::uint32_t channels,std::uint32_t rate,void* user) noexcept {
+ auto& self=*static_cast<Impl*>(user);
+ self.channels=channels;self.rate=rate;self.sampleIndex=0;
+ if((channels!=1&&channels!=2)||rate<8000||rate>192000){self.channels=0;self.token.failed(-1003);}
+ }
+ static void opusFrame(std::int16_t* data,std::size_t count,void* user) noexcept {
+ auto& self=*static_cast<Impl*>(user);
+ if(!self.active.load()||!self.channels||!data)return;
+ if(count==0||count>self.rate/5u||count>(std::numeric_limits<std::uint64_t>::max)()-self.sampleIndex){self.token.failed(-1004);return;}
+ try{
+ PcmBlock block;block.generation=self.token.generation();block.channels=self.channels;block.rate=self.rate;
+ block.firstSample=self.sampleIndex;block.arrival100ns=monotonic100ns();block.discontinuity=self.sampleIndex==0;
+ // Opus count is samples PER CHANNEL, not bytes or interleaved elements.
+ block.samples.assign(data,data+count*self.channels);self.sampleIndex+=count;++self.audioCallbacks;
+ (void)self.token.audio(std::move(block));
+ }catch(...){self.apiError=-1002;self.token.failed(-1002);}
+ }
+ BackendResult record(ChiakiErrorCode code,const char* name){apiError=static_cast<int>(code);return result(code,name);}
+ bool onOwner()const noexcept{return owner==std::this_thread::get_id();}
+};
+ChiakiBackend::ChiakiBackend()=default;
+ChiakiBackend::~ChiakiBackend(){
+ if(!p_)return;
+ try{
+ const auto stopped=stop();
+ if(!stopped.ok && p_){
+ // A failed join cannot be repaired by freeing memory still used by callbacks.
+ // Quarantine/leak this one session rather than create a use-after-free.
+ // The owner must treat stop failure as fatal and not reconnect this object.
+ p_->active=false;(void)p_.release();
+ }
+ }catch(...){if(p_){p_->active=false;(void)p_.release();}}
+}
+BackendResult ChiakiBackend::start(const NativeConnectRequest& request,SessionInbox::Token token){
+ 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;
+ chiaki_log_init(&s.log,CHIAKI_LOG_WARNING|CHIAKI_LOG_ERROR,Impl::logCallback,&s);
+ ChiakiConnectInfo info{};info.ps5=true;info.host=s.host.c_str();
+ std::memcpy(info.regist_key,request.credentials.registrationKey.data(),request.credentials.registrationKey.size());
+ std::memcpy(info.morning,request.credentials.sessionKey.data(),request.credentials.sessionKey.size());
+ std::memcpy(info.psn_account_id,request.credentials.accountId.data(),request.credentials.accountId.size());
+ chiaki_connect_video_profile_preset(&info.video_profile,
+ request.video.height==720?CHIAKI_VIDEO_RESOLUTION_PRESET_720p:CHIAKI_VIDEO_RESOLUTION_PRESET_1080p,
+ request.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:CHIAKI_CODEC_H265;
+ info.video_profile.bitrate=request.video.bitrateKbps;
+ info.video_profile_auto_downgrade=false;info.enable_keyboard=false;info.enable_dualsense=false;
+ 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);
+ chiaki_session_set_event_cb(&s.session,Impl::eventCallback,&s);
+ chiaki_session_set_video_sample_cb(&s.session,Impl::videoCallback,&s);
+ s.active=true;
+ const auto startCode=chiaki_session_start(&s.session);
+ if(startCode!=CHIAKI_ERR_SUCCESS){auto out=s.record(startCode,"chiaki_session_start");s.active=false;s.token.failed(out.code);(void)stop();return out;}
+ s.started=true;return s.record(startCode,"chiaki_session_start");
+}
+BackendResult ChiakiBackend::stop(){
+ if(!p_)return {true,0,"already_stopped"};
+ auto& s=*p_;
+ if(!s.onOwner())return {false,-1102,"wrong_owner_thread"};
+ s.active=false;
+ ChiakiErrorCode stopResult=CHIAKI_ERR_SUCCESS;
+ if(s.started){
+ ChiakiControllerState idle;chiaki_controller_state_set_idle(&idle);
+ (void)s.record(chiaki_session_set_controller_state(&s.session,&idle),"release_controller");
+ const auto stopCode=chiaki_session_stop(&s.session);
+ stopResult=stopCode;
+ // Join even if stop reported an error. Never fini while a callback is alive.
+ const auto joinCode=chiaki_session_join(&s.session);
+ if(joinCode!=CHIAKI_ERR_SUCCESS)return s.record(joinCode,"chiaki_session_join");
+ s.started=false;s.connected=false;
+ if(stopCode!=CHIAKI_ERR_SUCCESS)s.apiError=static_cast<int>(stopCode);
+ }
+ if(s.opusInitialized){chiaki_opus_decoder_fini(&s.opus);s.opusInitialized=false;}
+ if(s.initialized){chiaki_session_fini(&s.session);s.initialized=false;}
+ wipe(&s.session,sizeof(s.session));
+ p_.reset();return result(stopResult,"stop_join_fini");
+}
+BackendResult ChiakiBackend::requestIdr(){
+ if(!p_||!p_->onOwner()||!p_->started)return {false,-1103,"idr_without_session"};
+ return p_->record(chiaki_session_request_idr(&p_->session),"chiaki_session_request_idr");
+}
+BackendResult ChiakiBackend::submitLoginPin(std::string_view pin){
+ if(!p_||!p_->onOwner()||!p_->started)return {false,-1104,"pin_without_session"};
+ if(pin.empty()||pin.size()>8||!std::all_of(pin.begin(),pin.end(),[](char c){return c>='0'&&c<='9';}))return {false,-1105,"invalid_login_pin"};
+ return p_->record(chiaki_session_set_login_pin(&p_->session,reinterpret_cast<const std::uint8_t*>(pin.data()),pin.size()),"chiaki_session_set_login_pin");
+}
+BackendResult ChiakiBackend::submitController(const ControllerState& state){
+ if(!p_||!p_->onOwner()||!p_->started)return {false,-1106,"controller_without_session"};
+ ChiakiControllerState c;chiaki_controller_state_set_idle(&c);
+ struct Mapping{std::uint32_t semantic;ChiakiControllerButton target;};
+ static constexpr Mapping buttons[]={
+ {ControllerState::Cross,CHIAKI_CONTROLLER_BUTTON_CROSS},{ControllerState::Circle,CHIAKI_CONTROLLER_BUTTON_MOON},
+ {ControllerState::Square,CHIAKI_CONTROLLER_BUTTON_BOX},{ControllerState::Triangle,CHIAKI_CONTROLLER_BUTTON_PYRAMID},
+ {ControllerState::Left,CHIAKI_CONTROLLER_BUTTON_DPAD_LEFT},{ControllerState::Right,CHIAKI_CONTROLLER_BUTTON_DPAD_RIGHT},
+ {ControllerState::Up,CHIAKI_CONTROLLER_BUTTON_DPAD_UP},{ControllerState::Down,CHIAKI_CONTROLLER_BUTTON_DPAD_DOWN},
+ {ControllerState::L1,CHIAKI_CONTROLLER_BUTTON_L1},{ControllerState::R1,CHIAKI_CONTROLLER_BUTTON_R1},
+ {ControllerState::L3,CHIAKI_CONTROLLER_BUTTON_L3},{ControllerState::R3,CHIAKI_CONTROLLER_BUTTON_R3},
+ {ControllerState::Options,CHIAKI_CONTROLLER_BUTTON_OPTIONS},{ControllerState::Share,CHIAKI_CONTROLLER_BUTTON_SHARE},
+ {ControllerState::Touchpad,CHIAKI_CONTROLLER_BUTTON_TOUCHPAD},{ControllerState::PS,CHIAKI_CONTROLLER_BUTTON_PS}};
+ for(auto b:buttons)if(state.buttons&b.semantic)c.buttons|=static_cast<std::uint32_t>(b.target);
+ c.l2_state=state.l2;c.r2_state=state.r2;c.left_x=state.leftX;c.left_y=state.leftY;c.right_x=state.rightX;c.right_y=state.rightY;
+ return p_->record(chiaki_session_set_controller_state(&p_->session,&c),"chiaki_session_set_controller_state");
+}
+NativeSnapshot ChiakiBackend::snapshot()const{
+ // Like start/stop, pointer ownership requires the owner; the atomic counters
+ // themselves may be updated by callbacks. Do not call concurrently with reset.
+ if(!p_)return {};
+ const auto& s=*p_;
+ return {s.started.load(),s.connected.load(),s.warnings.load(),s.errors.load(),s.videoCallbacks.load(),s.audioCallbacks.load(),s.quitReason.load(),s.apiError.load()};
+}
+} // namespace veyra::remoteplay
diff --git a/src/remoteplay/ChiakiRegistration.cpp b/src/remoteplay/ChiakiRegistration.cpp
new file mode 100644
index 00000000..5c1832c6
--- /dev/null
+++ b/src/remoteplay/ChiakiRegistration.cpp
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Native implementation: unbuilt in this cloud delivery; do not call from UI thread.
+#include "veyra/remoteplay/ChiakiBackend.h"
+#include <chiaki/regist.h>
+#include <chiaki/log.h>
+#include <condition_variable>
+#include <algorithm>
+#include <cstring>
+#include <mutex>
+namespace veyra::remoteplay {
+namespace {
+struct RegistrationWait {
+ std::mutex mutex;std::condition_variable cv;bool done=false,success=false;
+ std::array<char,16> registrationKey{};std::array<std::uint8_t,16> sessionKey{};
+ std::array<std::uint8_t,6> mac{};std::array<char,32> nickname{};
+ ~RegistrationWait(){
+ auto wipe=[](void* p,std::size_t n){auto* b=static_cast<volatile unsigned char*>(p);while(n--)*b++=0;};
+ wipe(registrationKey.data(),registrationKey.size());wipe(sessionKey.data(),sessionKey.size());
+ }
+ static void callback(ChiakiRegistEvent* event,void* user) noexcept{
+ auto& s=*static_cast<RegistrationWait*>(user);
+ try{
+ std::lock_guard lock(s.mutex);
+ s.success=event&&event->type==CHIAKI_REGIST_EVENT_TYPE_FINISHED_SUCCESS&&event->registered_host;
+ if(s.success){
+ const auto& h=*event->registered_host;
+ std::memcpy(s.registrationKey.data(),h.rp_regist_key,s.registrationKey.size());
+ std::memcpy(s.sessionKey.data(),h.rp_key,s.sessionKey.size());
+ std::memcpy(s.mac.data(),h.server_mac,s.mac.size());
+ std::memcpy(s.nickname.data(),h.server_nickname,s.nickname.size());
+ }
+ s.done=true;s.cv.notify_all();
+ }catch(...){/* Allocation-free callback; owner still has timeout/cancel. */}
+ }
+ static void log(ChiakiLogLevel,const char*,void*)noexcept{}
+};
+}
+PairResult pairLocalPs5(std::string host,const AccountId& account,std::string_view pin,
+ std::stop_token cancel,std::chrono::milliseconds timeout){
+ PairResult out;auto numericPin=parsePairingPin(pin);
+ if(!validHost(host)||!numericPin||timeout<std::chrono::seconds(1)||timeout>std::chrono::seconds(60)){
+ out.result={false,-1200,"validate_registration"};return out;
+ }
+ if(cancel.stop_requested()){out.canceled=true;out.result={false,-1201,"registration_canceled"};return out;}
+ out.result=initializeChiaki();if(!out.result.ok)return out;
+ RegistrationWait wait;ChiakiRegist registration{};ChiakiLog log{};
+ // Do not emit raw registration responses: they contain pairing credentials.
+ chiaki_log_init(&log,0,RegistrationWait::log,nullptr);
+ ChiakiRegistInfo info{};info.target=CHIAKI_TARGET_PS5_1;info.host=host.c_str();info.broadcast=false;
+ info.psn_online_id=nullptr;info.pin=*numericPin;
+ std::memcpy(info.psn_account_id,account.data(),account.size());
+ const auto started=chiaki_regist_start(&registration,&log,&info,RegistrationWait::callback,&wait);
+ info.pin=0;
+ if(started!=CHIAKI_ERR_SUCCESS){out.result={false,static_cast<int>(started),"chiaki_regist_start"};return out;}
+ {
+ // stop_callback only wakes the owner. No upstream stop/join on callback thread.
+ std::stop_callback notify(cancel,[&wait]{std::lock_guard lock(wait.mutex);wait.cv.notify_all();});
+ std::unique_lock lock(wait.mutex);
+ const bool ready=wait.cv.wait_for(lock,timeout,[&]{return wait.done||cancel.stop_requested();});
+ out.canceled=cancel.stop_requested();out.timedOut=!ready;
+ }
+ // fini includes join in the pinned upstream. Must not hold wait.mutex here.
+ chiaki_regist_stop(&registration);chiaki_regist_fini(&registration);
+ if(out.canceled||out.timedOut){out.result={false,out.canceled?-1201:-1202,out.canceled?"registration_canceled":"registration_timeout"};return out;}
+ if(!wait.success){out.result={false,-1203,"registration_failed"};return out;}
+ out.credentials.accountId=account;out.credentials.registrationKey=wait.registrationKey;out.credentials.sessionKey=wait.sessionKey;out.mac=wait.mac;
+ const auto length=std::find(wait.nickname.begin(),wait.nickname.end(),'\0')-wait.nickname.begin();
+ out.nickname.assign(wait.nickname.data(),static_cast<std::size_t>(length));
+ out.result={true,0,"registration_completed"};return out;
+}
+} // namespace veyra::remoteplay
diff --git a/src/remoteplay/SessionInbox.cpp b/src/remoteplay/SessionInbox.cpp
new file mode 100644
index 00000000..42c599a1
--- /dev/null
+++ b/src/remoteplay/SessionInbox.cpp
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/remoteplay/SessionInbox.h"
+#include <limits>
+namespace veyra::remoteplay {
+struct SessionInbox::Shared {
+ explicit Shared(QueueLimits limits):video(limits){}
+ mutable std::mutex mutex;Generation generation=0;SessionState state=SessionState::Idle;
+ HostTime origin=0;bool accepting=false;std::uint64_t stale=0;int error=0;
+ VideoIngress video;AudioIngress audio;
+ bool current(Generation g){if(!accepting||g!=generation){++stale;return false;}return true;}
+};
+SessionInbox::SessionInbox(QueueLimits l):shared_(std::make_shared<Shared>(l)){}
+SessionInbox::~SessionInbox(){invalidate();}
+SessionInbox::Token SessionInbox::begin(HostTime origin){
+ if(origin<0)throw std::invalid_argument("Negative local clock origin");
+ auto& s=*shared_;std::lock_guard lock(s.mutex);
+ if(s.state!=SessionState::Idle)throw std::logic_error("Stop and join previous backend before a new session");
+ if(s.generation==std::numeric_limits<Generation>::max())throw std::overflow_error("Session generation exhausted");
+ ++s.generation;s.video.begin(s.generation);s.audio.begin(s.generation);s.origin=origin;s.state=SessionState::Connecting;s.accepting=true;s.error=0;
+ return Token{shared_,s.generation};
+}
+void SessionInbox::invalidate(){auto& s=*shared_;std::lock_guard l(s.mutex);s.accepting=false;if(s.state!=SessionState::Idle)s.state=SessionState::Stopping;s.video.close();s.audio.close();}
+void SessionInbox::finishStop(){auto& s=*shared_;std::lock_guard l(s.mutex);if(s.accepting)throw std::logic_error("Invalidate before join/finishStop");s.state=SessionState::Idle;}
+bool SessionInbox::isCurrent(Generation g)const{auto& s=*shared_;std::lock_guard l(s.mutex);return s.accepting&&s.generation==g;}
+bool SessionInbox::decodedFrameReady(Generation g){
+ auto& s=*shared_;std::lock_guard l(s.mutex);
+ if(!s.accepting||s.generation!=g||(s.state!=SessionState::WaitingFirstFrame&&s.state!=SessionState::Streaming))return false;
+ s.state=SessionState::Streaming;return true;
+}
+std::optional<QueuedVideo> SessionInbox::tryVideo(HostTime now){auto& s=*shared_;std::lock_guard l(s.mutex);if(!s.accepting)return {};return s.video.tryPop(now);}
+std::optional<PcmBlock> SessionInbox::tryAudio(){auto& s=*shared_;std::lock_guard l(s.mutex);if(!s.accepting)return {};return s.audio.tryPop();}
+bool SessionInbox::takeIdrRequest(HostTime now){auto& s=*shared_;std::lock_guard l(s.mutex);return s.accepting&&s.video.takeIdrRequest(now);}
+void SessionInbox::decodeFailed(Generation g){auto& s=*shared_;std::lock_guard l(s.mutex);if(s.accepting&&s.generation==g)s.video.requireKeyframe();}
+SessionInbox::Snapshot SessionInbox::snapshot()const{
+ auto& s=*shared_;std::lock_guard l(s.mutex);return {s.generation,s.state,s.origin,s.stale,s.error,s.video.stats(),s.audio.stats()};
+}
+bool SessionInbox::Token::video(VideoSample sample)const noexcept{
+ try{auto s=shared_.lock();if(!s)return false;std::lock_guard l(s->mutex);if(!s->current(generation_))return false;
+ if(sample.generation!=generation_)return false;
+ const auto r=s->video.push(std::move(sample),monotonic100ns());return r==PushStatus::Accepted||r==PushStatus::ConfigStored;
+ }catch(...){failed(-1001);return false;}
+}
+bool SessionInbox::Token::audio(PcmBlock block)const noexcept{
+ try{auto s=shared_.lock();if(!s)return false;std::lock_guard l(s->mutex);if(!s->current(generation_)||block.generation!=generation_)return false;return s->audio.push(std::move(block));}
+ catch(...){failed(-1002);return false;}
+}
+void SessionInbox::Token::connected()const noexcept{
+ try{auto s=shared_.lock();if(!s)return;std::lock_guard l(s->mutex);if(!s->current(generation_))return;
+ if(s->state==SessionState::Connecting||s->state==SessionState::LoginPinRequired)s->state=SessionState::WaitingFirstFrame;
+ }catch(...){}
+}
+void SessionInbox::Token::loginPinRequired()const noexcept{
+ try{auto s=shared_.lock();if(!s)return;std::lock_guard l(s->mutex);if(s->current(generation_))s->state=SessionState::LoginPinRequired;}catch(...){}
+}
+void SessionInbox::Token::failed(int code)const noexcept{
+ try{auto s=shared_.lock();if(!s)return;std::lock_guard l(s->mutex);if(!s->current(generation_))return;
+ s->error=code;s->state=SessionState::Failed;s->accepting=false;s->video.close();s->audio.close();
+ }catch(...){}
+}
+} // namespace veyra::remoteplay
diff --git a/src/remoteplay/Timeline.cpp b/src/remoteplay/Timeline.cpp
new file mode 100644
index 00000000..97fca307
--- /dev/null
+++ b/src/remoteplay/Timeline.cpp
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/remoteplay/Timeline.h"
+#include <limits>
+#include <stdexcept>
+namespace veyra::remoteplay {
+Sequence16Extender::Result Sequence16Extender::observe(std::uint16_t n) noexcept {
+ if(!initialized_){initialized_=true;previous_=n;extended_=n;return {extended_,true,true,0};}
+ const auto delta=static_cast<std::uint16_t>(n-previous_);
+ if(delta==0 || delta>=0x8000u)return {extended_,false,false,0};
+ if(extended_>std::numeric_limits<std::uint64_t>::max()-delta)return {};
+ extended_+=delta;previous_=n;return {extended_,true,false,static_cast<std::uint32_t>(delta-1)};
+}
+namespace {
+std::optional<std::int64_t> rescale(std::uint64_t n,std::uint32_t den) noexcept {
+ if(den==0)return {};
+ constexpr auto max=static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max());
+ const auto whole=n/den,rem=n%den;
+ if(whole>max/10000000u)return {};
+ const auto a=whole*10000000u,b=rem*10000000u/den;
+ if(a>max-b) return {};
+ return static_cast<std::int64_t>(a+b);
+}
+}
+void RemotePlayClock::reset(HostTime origin,std::uint32_t fps) {
+ if(origin<0 || (fps!=30&&fps!=60))throw std::invalid_argument("Invalid local clock origin/rate");
+ *this={};origin_=origin;fps_=fps;
+}
+std::optional<EstimatedStamp> RemotePlayClock::video(std::uint64_t index,HostTime arrival) {
+ if(!fps_ || arrival<origin_)return {};
+ if(anchored_ && (index<=lastIndex_ || arrival<lastArrival_))return {};
+ bool gap=false;
+ if(!anchored_){videoAnchor_=arrival-origin_;firstIndex_=index;anchored_=true;}
+ else if(arrival-lastArrival_>2000000 || index-lastIndex_>fps_/2u){
+ videoAnchor_=arrival-origin_;firstIndex_=index;gap=true;
+ }
+ const auto delta=rescale(index-firstIndex_,fps_);
+ if(!delta || videoAnchor_>std::numeric_limits<std::int64_t>::max()-*delta)return {};
+ lastArrival_=arrival;lastIndex_=index;
+ return EstimatedStamp{videoAnchor_+*delta,10000000/static_cast<std::int64_t>(fps_),gap};
+}
+std::optional<std::int64_t> RemotePlayClock::audioPts(std::uint64_t first,std::uint32_t rate,HostTime start) const noexcept {
+ if(!fps_ || start<origin_ || rate<8000 || rate>192000)return {};
+ const auto delta=rescale(first,rate);const auto base=start-origin_;
+ if(!delta || base>std::numeric_limits<std::int64_t>::max()-*delta) return {};
+ return base+*delta;
+}
+} // namespace veyra::remoteplay
diff --git a/src/remoteplay/Validation.cpp b/src/remoteplay/Validation.cpp
new file mode 100644
index 00000000..5cdabf00
--- /dev/null
+++ b/src/remoteplay/Validation.cpp
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/remoteplay/Types.h"
+#include <algorithm>
+#include <charconv>
+#include <chrono>
+#include <limits>
+#include <stdexcept>
+
+namespace veyra::remoteplay {
+HostTime monotonic100ns() noexcept {
+ return std::chrono::duration_cast<std::chrono::nanoseconds>(
+ std::chrono::steady_clock::now().time_since_epoch()).count()/100;
+}
+std::optional<std::string> VideoProfile::validate() const {
+ if (!((width==1280 && height==720) || (width==1920 && height==1080)))
+ return "Only 720p/1080p SDR are supported by this integration profile";
+ if (fps!=30 && fps!=60) return "Frame rate must be 30 or 60";
+ if (bitrateKbps<1000 || bitrateKbps>100000) return "Bitrate must be 1000..100000 kbit/s";
+ if (codec!=Codec::H264 && codec!=Codec::H265) return "Unsupported codec";
+ return {};
+}
+namespace {
+constexpr std::string_view b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+int sextet(char c) { const auto p=b64.find(c); return p==b64.npos ? -1 : static_cast<int>(p); }
+bool digit(char c) noexcept { return c>='0' && c<='9'; }
+bool alpha(char c) noexcept { return (c>='a'&&c<='z')||(c>='A'&&c<='Z'); }
+}
+std::optional<AccountId> accountIdFromBase64(std::string_view text) {
+ // Exactly 8 decoded bytes => 11 alphabet characters and one '='.
+ if (text.size()!=12 || text[11]!='=') return {};
+ AccountId out{}; std::uint32_t acc=0; unsigned bits=0; std::size_t n=0;
+ for (std::size_t i=0;i<11;++i) {
+ const int v=sextet(text[i]); if (v<0) return {};
+ acc=(acc<<6)|static_cast<unsigned>(v); bits+=6;
+ if (bits>=8) { bits-=8; if(n>=out.size()) return {}; out[n++]=static_cast<std::uint8_t>(acc>>bits); }
+ }
+ if(n!=out.size() || bits!=2 || (acc&3u)!=0) return {}; // Reject non-canonical padding bits.
+ return out;
+}
+std::optional<AccountId> accountIdFromDecimal(std::string_view text) {
+ if(text.empty() || text.size()>20 || !std::all_of(text.begin(),text.end(),digit)) return {};
+ std::uint64_t value=0;
+ auto [end,err]=std::from_chars(text.data(),text.data()+text.size(),value);
+ if(err!=std::errc{} || end!=text.data()+text.size()) return {};
+ AccountId out{}; for(auto& b:out){b=static_cast<std::uint8_t>(value&255u);value>>=8;}
+ return out;
+}
+std::string accountIdToBase64(const AccountId& id) {
+ std::string out; out.reserve(12); std::uint32_t acc=0; unsigned bits=0;
+ for(auto b:id){acc=(acc<<8)|b;bits+=8;while(bits>=6){bits-=6;out.push_back(b64[(acc>>bits)&63u]);}}
+ if(bits)out.push_back(b64[(acc<<(6-bits))&63u]);
+ while(out.size()%4) { out.push_back('='); }
+ return out;
+}
+std::optional<std::uint32_t> parsePairingPin(std::string_view text) {
+ if(text.size()!=8 || !std::all_of(text.begin(),text.end(),digit))return {};
+ std::uint32_t pin=0;for(char c:text)pin=pin*10+static_cast<unsigned>(c-'0');return pin;
+}
+bool validHost(std::string_view host) noexcept {
+ if(host.empty() || host.size()>253 || host.front()=='.' || host.back()=='.')return false;
+ bool numeric=true;
+ for(char c:host){if(!digit(c)&&c!='.')numeric=false;if(!(digit(c)||alpha(c)||c=='.'||c=='-'))return false;}
+ std::size_t begin=0,labels=0;
+ while(begin<host.size()){
+ const auto end=host.find('.',begin);auto label=host.substr(begin,end==host.npos?host.size()-begin:end-begin);
+ if(label.empty()||label.size()>63||label.front()=='-'||label.back()=='-')return false;
+ if(numeric){
+ if(label.size()>3 || (label.size()>1&&label.front()=='0'))return false;
+ unsigned value=0;for(char c:label)value=value*10+static_cast<unsigned>(c-'0');if(value>255)return false;
+ }
+ ++labels;if(end==host.npos)break;begin=end+1;
+ }
+ return !numeric || labels==4;
+}
+bool validProfileId(std::string_view id) noexcept {
+ if(id.size()!=32)return false;
+ for(char c:id) { if(!digit(c)&&!(c>='a'&&c<='f')) return false; }
+ return true;
+}
+PaddedBytes PaddedBytes::copy(std::span<const std::uint8_t> data) {
+ // Bound before allocation; config has a stricter bound at the ingress.
+ if(data.size()>8u*1024u*1024u)throw std::length_error("Encoded sample exceeds 8 MiB");
+ PaddedBytes p;p.size_=data.size();p.storage_.resize(data.size()+Padding,0);
+ std::copy(data.begin(),data.end(),p.storage_.begin());return p;
+}
+bool PaddedBytes::paddingIsZero() const noexcept {
+ if(storage_.size()<size_+Padding)return size_==0 && storage_.empty();
+ return std::all_of(storage_.begin()+static_cast<std::ptrdiff_t>(size_),storage_.end(),[](auto b){return b==0;});
+}
+bool PcmBlock::valid() const noexcept {
+ return generation>0 && (channels==1||channels==2) && rate>=8000 && rate<=192000 &&
+ !samples.empty() && samples.size()%channels==0 && frames()<=rate/5u; // <=200 ms/block
+}
+} // namespace veyra::remoteplay
diff --git a/src/remoteplay/VideoIngress.cpp b/src/remoteplay/VideoIngress.cpp
new file mode 100644
index 00000000..0c7408fd
--- /dev/null
+++ b/src/remoteplay/VideoIngress.cpp
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/remoteplay/VideoIngress.h"
+#include <algorithm>
+#include <limits>
+#include <stdexcept>
+namespace veyra::remoteplay {
+void QueueLimits::validate() const {
+ if(maxFrames<1||maxFrames>64||maxBytes<1024||maxBytes>64u*1024u*1024u ||
+ maxConfigBytes<1||maxConfigBytes>maxBytes||maxConfigBytes>1024u*1024u ||
+ maxAge100ns<10000||maxAge100ns>5000000)
+ throw std::invalid_argument("Unsafe remote-play queue limits");
+}
+VideoIngress::VideoIngress(QueueLimits limits):limits_(limits){limits_.validate();}
+void VideoIngress::begin(Generation g) {
+ if(!g)throw std::invalid_argument("Generation zero is invalid");
+ std::lock_guard lock(mutex_);queue_.clear();config_.reset();generation_=g;payloadBytes_=0;
+ closed_=false;waiting_=true;pendingIdr_=false;lastIdr_=-1;sequence_.reset();stats_={};cv_.notify_all();
+}
+void VideoIngress::recoverLocked() {
+ stats_.dropped+=queue_.size();queue_.clear();payloadBytes_=0;
+ // Only one epoch increment per recovery episode; repeated P frames do not reset forever.
+ if(!waiting_){++stats_.epoch;++stats_.recoveries;}
+ waiting_=true;pendingIdr_=true;updateStatsLocked();
+}
+void VideoIngress::updateStatsLocked() {
+ stats_.depth=queue_.size();stats_.bytes=payloadBytes_+(config_?config_->payload.size():0);
+ stats_.waitingForIdr=waiting_;
+ stats_.highWaterDepth=std::max(stats_.highWaterDepth,stats_.depth);
+ stats_.highWaterBytes=std::max(stats_.highWaterBytes,stats_.bytes);
+}
+bool VideoIngress::expiredLocked(HostTime now) const {
+ return !queue_.empty() && (now<queue_.front().sample.arrival100ns ||
+ now-queue_.front().sample.arrival100ns>limits_.maxAge100ns);
+}
+PushStatus VideoIngress::push(VideoSample sample,HostTime now) {
+ std::lock_guard lock(mutex_);
+ if(closed_)return PushStatus::Closed;
+ if(sample.generation!=generation_)return PushStatus::WrongGeneration;
+ if(sample.payload.size()==0 || sample.arrival100ns<0 || now<sample.arrival100ns ||
+ !sample.payload.paddingIsZero() || sample.framesLost<0 ||
+ !((sample.width==1280&&sample.height==720)||(sample.width==1920&&sample.height==1080))){
+ ++stats_.rejected;recoverLocked();return PushStatus::Malformed;
+ }
+ const auto nal=inspectAnnexB(sample.payload.bytes(),sample.codec);
+ if(!nal.valid){++stats_.rejected;recoverLocked();return PushStatus::Malformed;}
+ if(sample.kind==SampleKind::CodecConfig){
+ if(!nal.hasConfig||nal.hasPicture||sample.wireFrameIndex||sample.payload.size()>limits_.maxConfigBytes){
+ ++stats_.rejected;recoverLocked();return PushStatus::Malformed;
+ }
+ ++stats_.configMessages;
+ const bool same=config_&&config_->codec==sample.codec&&config_->width==sample.width&&config_->height==sample.height&&
+ std::ranges::equal(config_->payload.bytes(),sample.payload.bytes());
+ if(!same){recoverLocked();config_=std::make_shared<const VideoSample>(std::move(sample));}
+ updateStatsLocked();return PushStatus::ConfigStored;
+ }
+ if(sample.kind!=SampleKind::AccessUnit || !nal.hasPicture){++stats_.rejected;recoverLocked();return PushStatus::Malformed;}
+ ++stats_.accessUnits;
+ if(sample.wireFrameIndex){
+ const auto seq=sequence_.observe(*sample.wireFrameIndex);
+ if(!seq.accepted){++stats_.rejected;return PushStatus::Malformed;}
+ if(seq.gap)recoverLocked();
+ }
+ if(sample.framesLost>0 || sample.referenceRecovered)recoverLocked();
+ if(now-sample.arrival100ns>limits_.maxAge100ns){++stats_.dropped;recoverLocked();return PushStatus::WaitingForIdr;}
+ if(!config_ || sample.codec!=config_->codec || sample.width!=config_->width || sample.height!=config_->height){
+ ++stats_.dropped;recoverLocked();return PushStatus::WaitingForIdr;
+ }
+ const auto headerBytes=config_->payload.size();
+ if(sample.payload.size()>limits_.maxBytes-headerBytes){++stats_.dropped;recoverLocked();return PushStatus::WaitingForIdr;}
+ if(expiredLocked(now)||queue_.size()>=limits_.maxFrames||payloadBytes_>limits_.maxBytes-headerBytes-sample.payload.size())recoverLocked();
+ if(waiting_&&!nal.idr){++stats_.dropped;pendingIdr_=true;return PushStatus::WaitingForIdr;}
+ const bool reset=waiting_;
+ queue_.push_back(QueuedVideo{std::move(sample),reset?config_:nullptr,stats_.epoch,reset});
+ payloadBytes_+=queue_.back().sample.payload.size();waiting_=false;
+ if(reset)pendingIdr_=false;
+ ++stats_.accepted;updateStatsLocked();cv_.notify_one();return PushStatus::Accepted;
+}
+std::optional<QueuedVideo> VideoIngress::tryPop(HostTime now) {
+ std::lock_guard lock(mutex_);
+ if(closed_)return {};
+ if(expiredLocked(now)){recoverLocked();return {};}
+ if(queue_.empty())return {};
+ auto out=std::move(queue_.front());queue_.pop_front();payloadBytes_-=out.sample.payload.size();
+ ++stats_.consumed;updateStatsLocked();return out;
+}
+bool VideoIngress::waitForData(std::chrono::milliseconds timeout) {
+ std::unique_lock lock(mutex_);cv_.wait_for(lock,timeout,[&]{return closed_||!queue_.empty();});return !closed_&&!queue_.empty();
+}
+bool VideoIngress::takeIdrRequest(HostTime now) {
+ std::lock_guard lock(mutex_);
+ if(closed_||!pendingIdr_||now<0||(lastIdr_>=0&&(now<lastIdr_||now-lastIdr_<5000000)))return false;
+ lastIdr_=now;pendingIdr_=false;++stats_.idrRequests;return true;
+}
+void VideoIngress::requireKeyframe(){std::lock_guard lock(mutex_);if(!closed_)recoverLocked();}
+void VideoIngress::close(){std::lock_guard lock(mutex_);closed_=true;queue_.clear();config_.reset();payloadBytes_=0;pendingIdr_=false;updateStatsLocked();cv_.notify_all();}
+VideoQueueStats VideoIngress::stats()const{std::lock_guard lock(mutex_);return stats_;}
+
+AudioIngress::AudioIngress(std::uint32_t maxMs):maxMs_(maxMs){if(maxMs<10||maxMs>200)throw std::invalid_argument("Audio buffer must be 10..200 ms");}
+void AudioIngress::begin(Generation g){
+ if(!g)throw std::invalid_argument("Generation zero is invalid");
+ std::lock_guard lock(mutex_);generation_=g;rate_=channels_=0;frames_=0;nextSample_=0;closed_=false;gap_=true;queue_.clear();stats_={};
+}
+bool AudioIngress::push(PcmBlock block){
+ std::lock_guard lock(mutex_);
+ if(closed_||block.generation!=generation_)return false;
+ if(!block.valid()||block.arrival100ns<0||block.firstSample>std::numeric_limits<std::uint64_t>::max()-block.frames()){
+ ++stats_.rejected;return false;
+ }
+ const auto budget=static_cast<std::size_t>(block.rate)*maxMs_/1000u;
+ if(block.frames()>budget){++stats_.rejected;gap_=true;return false;}
+ if(rate_!=block.rate||channels_!=block.channels){stats_.dropped+=queue_.size();queue_.clear();frames_=0;rate_=block.rate;channels_=block.channels;nextSample_=block.firstSample;gap_=true;}
+ if(block.firstSample<nextSample_){++stats_.rejected;return false;}
+ if(block.firstSample!=nextSample_)gap_=true;
+ while(!queue_.empty()&&frames_+block.frames()>budget){frames_-=queue_.front().frames();queue_.pop_front();++stats_.dropped;gap_=true;}
+ if(gap_&&!queue_.empty())queue_.front().discontinuity=true;
+ block.discontinuity|=gap_;gap_=false;nextSample_=block.firstSample+block.frames();frames_+=block.frames();
+ queue_.push_back(std::move(block));++stats_.accepted;stats_.bufferedMs=1000.0*static_cast<double>(frames_)/rate_;return true;
+}
+std::optional<PcmBlock> AudioIngress::tryPop(){
+ std::lock_guard lock(mutex_);if(closed_||queue_.empty())return {};
+ auto out=std::move(queue_.front());queue_.pop_front();frames_-=out.frames();++stats_.consumed;
+ stats_.bufferedMs=rate_?1000.0*static_cast<double>(frames_)/rate_:0;return out;
+}
+void AudioIngress::close(){std::lock_guard lock(mutex_);closed_=true;queue_.clear();frames_=0;stats_.bufferedMs=0;}
+AudioQueueStats AudioIngress::stats()const{std::lock_guard lock(mutex_);return stats_;}
+} // namespace veyra::remoteplay
diff --git a/src/source/RemotePlaySource.cpp b/src/source/RemotePlaySource.cpp
new file mode 100644
index 00000000..41c5cfd4
--- /dev/null
+++ b/src/source/RemotePlaySource.cpp
@@ -0,0 +1,375 @@
+#include "veyra/source/RemotePlaySource.h"
+
+#include "veyra/Log.h"
+#include "veyra/pipeline/ColorMetadata.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cstring>
+#include <cmath>
+#include <format>
+#include <limits>
+#include <span>
+
+extern "C" {
+#include <libavcodec/avcodec.h>
+#include <libavutil/frame.h>
+#include <libavutil/mem.h>
+#include <libavutil/pixfmt.h>
+}
+
+namespace veyra::source {
+namespace {
+
+std::shared_ptr<AVFrame> cloneFrame(const AVFrame* frame)
+{
+ AVFrame* clone = av_frame_clone(frame);
+ if (clone == nullptr) {
+ return {};
+ }
+ return std::shared_ptr<AVFrame>(clone, [](AVFrame* value) {
+ av_frame_free(&value);
+ });
+}
+
+pipeline::SourcePixelFormat pixelFormatFromFrame(const AVFrame& frame)
+{
+ switch (frame.format) {
+ case AV_PIX_FMT_NV12: return pipeline::SourcePixelFormat::NV12;
+ case AV_PIX_FMT_P010: return pipeline::SourcePixelFormat::P010;
+ case AV_PIX_FMT_YUV420P: return pipeline::SourcePixelFormat::Yuv420P;
+ case AV_PIX_FMT_YUYV422: return pipeline::SourcePixelFormat::Yuy2;
+ case AV_PIX_FMT_BGRA: return pipeline::SourcePixelFormat::Bgra8;
+ default: return pipeline::SourcePixelFormat::Unknown;
+ }
+}
+
+} // namespace
+
+RemotePlaySource::RemotePlaySource()
+ : inbox_(std::make_unique<remoteplay::SessionInbox>())
+{
+}
+
+RemotePlaySource::~RemotePlaySource()
+{
+ close();
+}
+
+bool RemotePlaySource::open(const SourceOpenDesc&)
+{
+ veyra::log::error("remoteplay", "RemotePlaySource requires connect() with PS5 credentials");
+ return false;
+}
+
+bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)
+{
+ close();
+ if (desc.request.video.validate() || !remoteplay::validHost(desc.request.host)) {
+ veyra::log::error("remoteplay", "connect rejected: invalid host or video profile");
+ return false;
+ }
+ request_ = remoteplay::NativeConnectRequest{};
+ request_.host = desc.request.host;
+ request_.video = desc.request.video;
+ request_.credentials.accountId = desc.request.credentials.accountId;
+ request_.credentials.registrationKey = desc.request.credentials.registrationKey;
+ request_.credentials.sessionKey = desc.request.credentials.sessionKey;
+
+ origin100ns_ = static_cast<std::uint64_t>(remoteplay::monotonic100ns());
+ try {
+ inbox_ = std::make_unique<remoteplay::SessionInbox>(desc.queueLimits);
+ } catch (...) {
+ veyra::log::error("remoteplay", "invalid queue limits");
+ return false;
+ }
+ auto token = inbox_->begin(static_cast<remoteplay::HostTime>(origin100ns_));
+ token_ = token; // Keep a second weak token; backend owns the moved copy.
+ const auto started = backend_.start(request_, token);
+ if (!started.ok) {
+ token_.reset();
+ inbox_->invalidate();
+ try { inbox_->finishStop(); } catch (...) {}
+ veyra::log::error("remoteplay", std::format("{} failed code={}", started.operation, started.code));
+ return false;
+ }
+ info_ = SourceInfo{};
+ info_.opened = true;
+ info_.kind = pipeline::SourceKind::RemotePlay;
+ info_.width = request_.video.width;
+ info_.height = request_.video.height;
+ info_.averageFps = static_cast<double>(request_.video.fps);
+ info_.nominalRateNum = static_cast<int>(request_.video.fps);
+ info_.nominalRateDen = 1;
+ info_.timestampQuantum = 1.0 / info_.averageFps;
+ info_.duration = pipeline::Rational::unknown();
+ info_.hardwareDecodeActive = false;
+ info_.color.pixelFormat = pipeline::SourcePixelFormat::Yuv420P;
+ info_.color.range = pipeline::ColorRange::Limited;
+ info_.color.rangeAssumed = true;
+ info_.color.matrix = request_.video.width > 1280 ? pipeline::YuvMatrix::BT709 : pipeline::YuvMatrix::BT601;
+ info_.color.matrixAssumed = true;
+ info_.color.transfer = pipeline::TransferFunction::BT709;
+ info_.color.transferAssumed = true;
+ info_.color.primaries = pipeline::ColorPrimaries::BT709;
+ info_.color.primariesAssumed = true;
+ clock_.reset(static_cast<remoteplay::HostTime>(origin100ns_), request_.video.fps);
+ sequence_ = 0;
+ fallbackSourceIndex_ = 0;
+ decoderEpoch_ = 1;
+ connected_ = true;
+ decoderReady_ = false;
+ waitingForFirstFrame_ = true;
+ pendingOpenFlag_ = true;
+ veyra::log::info("remoteplay", std::format("session started host={} profile={}x{}@{} codec={}",
+ request_.host, request_.video.width, request_.video.height, request_.video.fps,
+ request_.video.codec == remoteplay::Codec::H264 ? "H264" : "H265"));
+ return true;
+}
+
+remoteplay::SessionInbox::Snapshot RemotePlaySource::sessionSnapshot() const
+{
+ return inbox_->snapshot();
+}
+
+bool RemotePlaySource::openDecoder(remoteplay::Codec codec, std::uint32_t width, std::uint32_t height)
+{
+ if (codecContext_ != nullptr) {
+ if (codecContext_->codec_id == (codec == remoteplay::Codec::H264 ? AV_CODEC_ID_H264 : AV_CODEC_ID_HEVC)
+ && static_cast<std::uint32_t>(codecContext_->width) == width
+ && static_cast<std::uint32_t>(codecContext_->height) == height) {
+ return true;
+ }
+ flushDecoder();
+ avcodec_free_context(&codecContext_);
+ decoderReady_ = false;
+ }
+ const AVCodecID codecId = codec == remoteplay::Codec::H264 ? AV_CODEC_ID_H264 : AV_CODEC_ID_HEVC;
+ const AVCodec* decoder = avcodec_find_decoder(codecId);
+ if (decoder == nullptr) {
+ veyra::log::error("remoteplay", "FFmpeg decoder unavailable");
+ return false;
+ }
+ codecContext_ = avcodec_alloc_context3(decoder);
+ if (codecContext_ == nullptr) {
+ return false;
+ }
+ codecContext_->codec_id = codecId;
+ codecContext_->width = static_cast<int>(width);
+ codecContext_->height = static_cast<int>(height);
+ codecContext_->time_base = AVRational{1, static_cast<int>(request_.video.fps)};
+ codecContext_->thread_count = 1;
+ codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
+ if (avcodec_open2(codecContext_, decoder, nullptr) < 0) {
+ veyra::log::error("remoteplay", "FFmpeg remote decoder open failed");
+ avcodec_free_context(&codecContext_);
+ return false;
+ }
+ decoderFrame_ = av_frame_alloc();
+ if (decoderFrame_ == nullptr) {
+ avcodec_free_context(&codecContext_);
+ return false;
+ }
+ decoderReady_ = true;
+ info_.width = width;
+ info_.height = height;
+ veyra::log::info("remoteplay", std::format("software decoder opened codec={} {}x{}", decoder->name, width, height));
+ return true;
+}
+
+pipeline::FramePacket RemotePlaySource::makePacket(const remoteplay::VideoSample& sample,
+ std::uint64_t sourceIndex, std::uint64_t epoch, bool reset)
+{
+ pipeline::FramePacket packet{};
+ packet.sequence = 0;
+ packet.sourceKind = pipeline::SourceKind::RemotePlay;
+ packet.sourceEpoch = epoch;
+ packet.arrivalHost100ns = sample.arrival100ns;
+ const auto stamp = clock_.video(sourceIndex, sample.arrival100ns);
+ if (stamp) {
+ packet.pts = pipeline::Rational{stamp->pts100ns, 10000000};
+ packet.duration = pipeline::Rational{stamp->duration100ns, 10000000};
+ if (stamp->discontinuity) packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity);
+ } else {
+ packet.pts = pipeline::Rational::unknown();
+ packet.duration = pipeline::Rational::unknown();
+ }
+ if (pendingOpenFlag_) {
+ packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Open);
+ pendingOpenFlag_ = false;
+ }
+ if (reset) packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Discontinuity);
+ packet.colorInfo = info_.color;
+ return packet;
+}
+
+bool RemotePlaySource::drainDecoder(std::uint64_t sourceIndex, const pipeline::FramePacket& sourcePacket)
+{
+ for (;;) {
+ const int result = avcodec_receive_frame(codecContext_, decoderFrame_);
+ if (result == AVERROR(EAGAIN) || result == AVERROR_EOF) {
+ return true;
+ }
+ if (result < 0) {
+ veyra::log::error("remoteplay", std::format("avcodec_receive_frame failed code={}", result));
+ return false;
+ }
+ auto clone = cloneFrame(decoderFrame_);
+ if (!clone) return false;
+ pipeline::FramePacket packet = sourcePacket;
+ packet.sequence = ++sequence_;
+ packet.colorInfo.pixelFormat = pixelFormatFromFrame(*decoderFrame_);
+ packet.color.resource = nullptr;
+ // A packet can legally produce more than one decoded frame. Keep each
+ // frame in order and give additional frames the source cadence PTS.
+ packet.pts = sourcePacket.pts;
+ (void)sourceIndex;
+ ready_.push_back({std::move(clone), packet});
+ }
+}
+
+bool RemotePlaySource::submitPacket(std::span<const std::uint8_t> bytes,
+ std::uint64_t sourceIndex, const pipeline::FramePacket& sourcePacket)
+{
+ if (!decoderReady_ || bytes.empty()) return false;
+ AVPacket* packet = av_packet_alloc();
+ if (packet == nullptr || av_new_packet(packet, static_cast<int>(bytes.size())) < 0) {
+ av_packet_free(&packet);
+ return false;
+ }
+ std::memcpy(packet->data, bytes.data(), bytes.size());
+ packet->pts = static_cast<int64_t>(sourceIndex);
+ packet->dts = packet->pts;
+ bool ok = true;
+ for (;;) {
+ const int send = avcodec_send_packet(codecContext_, packet);
+ if (send == 0) {
+ ok = drainDecoder(sourceIndex, sourcePacket);
+ break;
+ }
+ if (send == AVERROR(EAGAIN)) {
+ if (!drainDecoder(sourceIndex, sourcePacket)) { ok = false; break; }
+ continue;
+ }
+ veyra::log::error("remoteplay", std::format("avcodec_send_packet failed code={}", send));
+ ok = false;
+ break;
+ }
+ av_packet_free(&packet);
+ return ok;
+}
+
+SourceReadStatus RemotePlaySource::read(pipeline::FramePacket& out, const AVFrame** decodedFrame)
+{
+ if (decodedFrame) *decodedFrame = nullptr;
+ if (!connected_) return SourceReadStatus::Error;
+ if (!ready_.empty()) {
+ auto item = std::move(ready_.front());
+ ready_.pop_front();
+ out = item.packet;
+ lastFrame_ = std::move(item.frame);
+ if (decodedFrame) *decodedFrame = lastFrame_.get();
+ return SourceReadStatus::Frame;
+ }
+ const auto now = remoteplay::monotonic100ns();
+ auto queued = inbox_->tryVideo(now);
+ if (!queued) {
+ const auto state = inbox_->snapshot().state;
+ if (state == remoteplay::SessionState::Failed || state == remoteplay::SessionState::Idle) return SourceReadStatus::Error;
+ return SourceReadStatus::Waiting;
+ }
+ const auto& sample = queued->sample;
+ if (!decoderReady_ && !openDecoder(sample.codec, sample.width, sample.height)) {
+ inbox_->decodeFailed(sample.generation);
+ return SourceReadStatus::Error;
+ }
+ if (queued->resetDecoder) {
+ flushDecoder();
+ ++decoderEpoch_;
+ clock_.reset(static_cast<remoteplay::HostTime>(origin100ns_), request_.video.fps);
+ pendingOpenFlag_ = true;
+ }
+ const std::uint64_t sourceIndex = sample.wireFrameIndex
+ ? *sample.wireFrameIndex
+ : ++fallbackSourceIndex_;
+ const pipeline::FramePacket sourcePacket = makePacket(sample, sourceIndex, decoderEpoch_, queued->resetDecoder);
+ if (queued->configBefore && !submitPacket(queued->configBefore->payload.bytes(), sourceIndex, sourcePacket)) {
+ inbox_->decodeFailed(sample.generation);
+ return SourceReadStatus::Error;
+ }
+ if (!submitPacket(sample.payload.bytes(), sourceIndex, sourcePacket)) {
+ inbox_->decodeFailed(sample.generation);
+ return SourceReadStatus::Error;
+ }
+ if (ready_.empty()) return SourceReadStatus::Waiting;
+ auto item = std::move(ready_.front());
+ ready_.pop_front();
+ out = item.packet;
+ lastFrame_ = std::move(item.frame);
+ if (decodedFrame) *decodedFrame = lastFrame_.get();
+ waitingForFirstFrame_ = false;
+ return SourceReadStatus::Frame;
+}
+
+void RemotePlaySource::flushDecoder() noexcept
+{
+ ready_.clear();
+ if (codecContext_) avcodec_flush_buffers(codecContext_);
+}
+
+std::size_t RemotePlaySource::pullAudio(float* stereo, std::size_t frames, double* firstPtsMs)
+{
+ if (!stereo || frames == 0) return 0;
+ std::size_t written = 0;
+ while (written < frames) {
+ auto block = inbox_->tryAudio();
+ if (!block) break;
+ if (block->channels == 0 || block->rate == 0) continue;
+ if (firstPtsMs && written == 0) {
+ const auto pts = inbox_->snapshot().commonOrigin100ns +
+ static_cast<std::int64_t>(block->firstSample) * 10000000ll / block->rate;
+ *firstPtsMs = static_cast<double>(pts) / 10000.0;
+ }
+ const auto copyFrames = std::min(frames - written, block->frames());
+ for (std::size_t i = 0; i < copyFrames; ++i) {
+ const auto sourceChannels = block->channels;
+ const auto sourceIndex = i * sourceChannels;
+ stereo[(written + i) * 2] = static_cast<float>(block->samples[sourceIndex]) / 32768.0f;
+ stereo[(written + i) * 2 + 1] = sourceChannels > 1
+ ? static_cast<float>(block->samples[sourceIndex + 1]) / 32768.0f
+ : stereo[(written + i) * 2];
+ }
+ written += copyFrames;
+ if (copyFrames < block->frames()) break;
+ }
+ return written;
+}
+
+void RemotePlaySource::close() noexcept
+{
+ connected_ = false;
+ ready_.clear();
+ lastFrame_.reset();
+ if (token_) {
+ inbox_->invalidate();
+ (void)backend_.stop();
+ try { inbox_->finishStop(); } catch (...) {}
+ token_.reset();
+ }
+ flushDecoder();
+ av_frame_free(&decoderFrame_);
+ avcodec_free_context(&codecContext_);
+ decoderReady_ = false;
+ info_ = SourceInfo{};
+}
+
+std::size_t RemotePlayAudioSource::pull(float* stereo, std::size_t frames, double* firstPtsMs)
+{
+ const auto count = source_.pullAudio(stereo, frames, firstPtsMs);
+ if (count && firstPtsMs && std::isfinite(*firstPtsMs)) {
+ lastEndPtsMs_ = *firstPtsMs + 1000.0 * static_cast<double>(count) / 48000.0;
+ }
+ return count;
+}
+
+} // namespace veyra::source
diff --git a/tests/remoteplay/CoreTests.cpp b/tests/remoteplay/CoreTests.cpp
new file mode 100644
index 00000000..27efd270
--- /dev/null
+++ b/tests/remoteplay/CoreTests.cpp
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/remoteplay/Types.h"
+#include "veyra/remoteplay/Timeline.h"
+#include "veyra/remoteplay/VideoIngress.h"
+#include "veyra/remoteplay/LatestMailbox.h"
+#include "veyra/remoteplay/PacketPump.h"
+#include "veyra/remoteplay/InputGate.h"
+#include "veyra/remoteplay/SessionInbox.h"
+#include <atomic>
+#include <chrono>
+#include <functional>
+#include <iostream>
+#include <limits>
+#include <memory>
+#include <random>
+#include <stdexcept>
+#include <thread>
+#include <utility>
+using namespace veyra::remoteplay;
+namespace {
+using Test=std::pair<const char*,void(*)()>;
+std::vector<Test>& tests(){static std::vector<Test> value;return value;}
+struct AddTest{AddTest(const char* n,void(*f)()){tests().emplace_back(n,f);}};
+#define TEST(name) void name(); AddTest reg_##name(#name,name); void name()
+#define CHECK(expr) do { if(!(expr))throw std::runtime_error(std::string(__FILE__)+":"+std::to_string(__LINE__)+": " #expr); } while(false)
+#define THROWS(expr) do{bool caught=false;try{(void)(expr);}catch(const std::exception&){caught=true;}CHECK(caught);}while(false)
+std::vector<std::uint8_t> configBytes(){return {0,0,0,1,0x67,0x42,0,0x1f,0,0,1,0x68,0xee,0x3c};}
+VideoSample config(Generation g=1,HostTime t=0){
+ VideoSample s;s.generation=g;s.kind=SampleKind::CodecConfig;s.width=1920;s.height=1080;
+ s.payload=PaddedBytes::copy(configBytes());s.arrival100ns=t;return s;
+}
+VideoSample frame(std::uint16_t index,bool idr,HostTime t=0,Generation g=1){
+ VideoSample s;s.generation=g;s.wireFrameIndex=index;s.width=1920;s.height=1080;s.arrival100ns=t;
+ const std::array<std::uint8_t,6> bytes{0,0,1,static_cast<std::uint8_t>(idr?0x65:0x41),0x88,0x99};
+ s.payload=PaddedBytes::copy(bytes);return s;
+}
+PcmBlock audio(std::uint64_t index=0,std::size_t count=480,Generation g=1){
+ PcmBlock b;b.generation=g;b.firstSample=index;b.channels=2;b.rate=48000;b.samples.resize(count*2,42);return b;
+}
+void start(VideoIngress& q){q.begin(1);CHECK(q.push(config(),0)==PushStatus::ConfigStored);CHECK(q.push(frame(0,true),0)==PushStatus::Accepted);}
+
+TEST(account_base64_exact){AccountId id{1,0,0,0,0,0,0,0};CHECK(accountIdToBase64(id)=="AQAAAAAAAAA=");CHECK(accountIdFromBase64("AQAAAAAAAAA=")==id);}
+TEST(account_decimal_endian){auto id=accountIdFromDecimal("72623859790382856");CHECK(id);CHECK((*id==AccountId{8,7,6,5,4,3,2,1}));}
+TEST(account_uint64_boundary){auto id=accountIdFromDecimal("18446744073709551615");CHECK(id);for(auto b:*id)CHECK(b==255);CHECK(!accountIdFromDecimal("18446744073709551616"));}
+TEST(account_decimal_strict){for(auto s:{"","-1","+1"," 1","1 ","1a","1.0","184467440737095516150"})CHECK(!accountIdFromDecimal(s));CHECK(accountIdFromDecimal("0"));}
+TEST(account_base64_strict){for(auto s:{"","AQAAAAAAAAA","AQAAAAAAAAA==","AQAAAAAAAAA=\n","AQAAAAAAAAB=","AQAAAAAAAA-=","AQAAAA=AAAA="})CHECK(!accountIdFromBase64(s));}
+TEST(account_roundtrip_property){std::mt19937 rng(2731);for(int i=0;i<10000;++i){AccountId a{};for(auto& b:a)b=static_cast<std::uint8_t>(rng());CHECK(accountIdFromBase64(accountIdToBase64(a))==a);}}
+TEST(pairing_pin_leading_zero){CHECK(parsePairingPin("00123456")==123456u);CHECK(parsePairingPin("00000000")==0u);}
+TEST(pairing_pin_reject){for(auto s:{"1234567","123456789","12 45678","-1234567","1234567a"})CHECK(!parsePairingPin(s));}
+TEST(host_validation){CHECK(validHost("192.168.1.2"));CHECK(validHost("ps5.local"));CHECK(validHost("console-1"));for(auto s:{"","256.1.1.1","192.168.001.2","https://ps5","user@host","host:9295","foo/bar","-foo","foo-","a..b","a.","127.1","a\nb"})CHECK(!validHost(s));}
+TEST(profile_id_validation){CHECK(validProfileId("0123456789abcdef0123456789abcdef"));CHECK(!validProfileId("../../credentials"));CHECK(!validProfileId("0123456789ABCDEF0123456789ABCDEF"));}
+TEST(video_profile_validation){VideoProfile p;CHECK(!p.validate());p.width=3840;CHECK(p.validate());p={};p.fps=120;CHECK(p.validate());p={};p.bitrateKbps=999;CHECK(p.validate());p={};p.codec=static_cast<Codec>(99);CHECK(p.validate());}
+TEST(padding_ownership){std::vector<std::uint8_t> b{1,2,3};auto p=PaddedBytes::copy(b);b[0]=99;CHECK(p.bytes()[0]==1);CHECK(p.size()==3);CHECK(p.paddingIsZero());}
+TEST(padding_reject_oversize){std::vector<std::uint8_t> b(8u*1024u*1024u+1);THROWS(PaddedBytes::copy(b));}
+TEST(nal_h264_classification){const auto c=inspectAnnexB(configBytes(),Codec::H264);CHECK(c.valid&&c.hasConfig&&!c.hasPicture&&!c.idr);auto f=frame(1,true);const auto i=inspectAnnexB(f.payload.bytes(),Codec::H264);CHECK(i.valid&&i.hasPicture&&i.idr);}
+TEST(nal_h265_idr_not_cra){for(auto type:{19u,20u,21u}){std::array<std::uint8_t,6>b{0,0,1,static_cast<std::uint8_t>(type<<1),1,99};auto n=inspectAnnexB(b,Codec::H265);CHECK(n.valid&&n.hasPicture);CHECK(n.idr==(type!=21));}}
+TEST(nal_reject_malformed){for(const auto& b:std::vector<std::vector<std::uint8_t>>{{1,2,3},{0,0,1},{0,0,1,0xff},{0,0,1,0}})CHECK(!inspectAnnexB(b,Codec::H264).valid);std::array<std::uint8_t,5>b{0,0,1,38,0};CHECK(!inspectAnnexB(b,Codec::H265).valid);}
+TEST(nal_random_input_bounds){std::mt19937 rng(11);for(int j=0;j<20000;++j){std::vector<std::uint8_t>b(rng()%128);for(auto& v:b)v=static_cast<std::uint8_t>(rng());(void)inspectAnnexB(b,Codec::H264);(void)inspectAnnexB(b,Codec::H265);}}
+TEST(sequence_wrap){Sequence16Extender x;CHECK(x.observe(65534).first);CHECK(x.observe(65535).value==65535);CHECK(x.observe(0).value==65536);CHECK(x.observe(1).value==65537);}
+TEST(sequence_duplicates_and_old){Sequence16Extender x;CHECK(x.observe(1).accepted);CHECK(!x.observe(1).accepted);CHECK(!x.observe(0).accepted);CHECK(!x.observe(32769).accepted);CHECK(x.observe(4).gap==2);}
+TEST(sequence_multiple_wraps){Sequence16Extender x;for(std::uint64_t i=0;i<200000;++i){auto r=x.observe(static_cast<std::uint16_t>(i));CHECK(r.accepted&&r.value==i);}}
+TEST(clock_common_origin){RemotePlayClock c;c.reset(1000000,60);auto v=c.video(123,1300000);CHECK(v&&v->pts100ns==300000);CHECK(c.audioPts(480,48000,1100000)==200000);CHECK(v->provenance==TimestampProvenance::LocalEstimated);}
+TEST(clock_cadence_no_cumulative_rounding){RemotePlayClock c;c.reset(0,60);for(std::uint64_t i=0;i<60000;++i){const auto time=static_cast<std::int64_t>(i*10000000/60);auto s=c.video(i,time);CHECK(s&&s->pts100ns==time);}}
+TEST(clock_gap_reanchors){RemotePlayClock c;c.reset(0,60);CHECK(c.video(0,0));auto s=c.video(60,10000000);CHECK(s&&s->discontinuity&&s->pts100ns==10000000);}
+TEST(clock_reject_invalid){RemotePlayClock c;CHECK(!c.video(0,0));THROWS(c.reset(0,120));THROWS(c.reset(-1,60));c.reset(10,60);CHECK(!c.video(0,9));CHECK(c.video(1,20));CHECK(!c.video(1,20));CHECK(!c.video(2,19));CHECK(!c.audioPts(0,0,10));CHECK(!c.audioPts(std::numeric_limits<std::uint64_t>::max(),8000,10));}
+TEST(queue_limits_validation){QueueLimits l;l.maxFrames=0;THROWS(VideoIngress{l});l={};l.maxConfigBytes=l.maxBytes+1;THROWS(VideoIngress{l});l={};l.maxAge100ns=0;THROWS(VideoIngress{l});}
+TEST(config_not_counted_as_picture){VideoIngress q;q.begin(1);CHECK(q.push(config(),0)==PushStatus::ConfigStored);CHECK(q.stats().accessUnits==0);CHECK(q.stats().depth==0);CHECK(!q.tryPop(0));}
+TEST(queue_starts_at_keyframe){VideoIngress q;q.begin(1);q.push(config(),0);CHECK(q.push(frame(1,false),0)==PushStatus::WaitingForIdr);CHECK(q.push(frame(2,true),0)==PushStatus::Accepted);auto v=q.tryPop(0);CHECK(v&&v->configBefore&&v->resetDecoder);CHECK(q.stats().accepted==1);}
+TEST(queue_fifo_not_latest_compressed){VideoIngress q;start(q);q.push(frame(1,false),0);q.push(frame(2,false),0);for(std::uint16_t i=0;i<3;++i){auto s=q.tryPop(0);CHECK(s&&s->sample.wireFrameIndex==i);CHECK(static_cast<bool>(s->configBefore)==(i==0));}}
+TEST(queue_overflow_requires_idr){QueueLimits l;l.maxFrames=2;VideoIngress q(l);start(q);q.push(frame(1,false),0);CHECK(q.push(frame(2,false),0)==PushStatus::WaitingForIdr);CHECK(q.stats().depth==0);CHECK(q.stats().waitingForIdr);CHECK(q.push(frame(3,false),0)==PushStatus::WaitingForIdr);CHECK(q.push(frame(4,true),0)==PushStatus::Accepted);auto s=q.tryPop(0);CHECK(s&&s->resetDecoder&&s->configBefore);CHECK(s->epoch==2);}
+TEST(queue_overflow_incoming_idr){QueueLimits l;l.maxFrames=1;VideoIngress q(l);start(q);CHECK(q.push(frame(1,true),0)==PushStatus::Accepted);auto s=q.tryPop(0);CHECK(s&&s->sample.wireFrameIndex==1&&s->resetDecoder);}
+TEST(queue_age_recovery){VideoIngress q;start(q);CHECK(!q.tryPop(1000001));CHECK(q.stats().waitingForIdr&&q.stats().depth==0);}
+TEST(queue_idr_coalescing){VideoIngress q;q.begin(1);q.push(config(),0);q.push(frame(0,false),0);CHECK(q.takeIdrRequest(0));q.push(frame(1,false),0);CHECK(!q.takeIdrRequest(100000));CHECK(q.takeIdrRequest(5000000));CHECK(!q.takeIdrRequest(10000000));}
+TEST(queue_config_change_clears_history){VideoIngress q;start(q);auto c=config();c.width=1280;c.height=720;q.push(std::move(c),0);CHECK(q.stats().depth==0&&q.stats().epoch==2);auto f=frame(1,true);f.width=1280;f.height=720;CHECK(q.push(std::move(f),0)==PushStatus::Accepted);CHECK(q.tryPop(0)->configBefore->width==1280);}
+TEST(queue_identical_config_no_reset){VideoIngress q;start(q);q.push(config(),0);CHECK(q.stats().depth==1&&q.stats().epoch==1);}
+TEST(queue_wrong_generation){VideoIngress q;start(q);CHECK(q.push(frame(1,false,0,2),0)==PushStatus::WrongGeneration);CHECK(q.stats().depth==1);}
+TEST(queue_reference_recovery_not_keyframe){VideoIngress q;start(q);q.tryPop(0);auto f=frame(1,false);f.referenceRecovered=true;CHECK(q.push(std::move(f),0)==PushStatus::WaitingForIdr);CHECK(q.stats().waitingForIdr);}
+TEST(queue_frame_gap_resets){VideoIngress q;start(q);q.tryPop(0);CHECK(q.push(frame(3,false),0)==PushStatus::WaitingForIdr);CHECK(q.stats().epoch==2);}
+TEST(queue_reject_injected_config_picture){VideoIngress q;q.begin(1);auto f=frame(0,true);f.kind=SampleKind::CodecConfig;CHECK(q.push(std::move(f),0)==PushStatus::Malformed);}
+TEST(queue_close_unblocks){VideoIngress q;q.begin(1);std::atomic<bool> result{true};std::thread t([&]{result=q.waitForData(std::chrono::seconds(2));});q.close();t.join();CHECK(!result);CHECK(q.push(config(),0)==PushStatus::Closed);}
+TEST(queue_bytes_bound){QueueLimits l;l.maxBytes=1024;l.maxConfigBytes=64;VideoIngress q(l);start(q);std::vector<std::uint8_t>b(1000,0x88);b[0]=0;b[1]=0;b[2]=1;b[3]=0x41;auto f=frame(1,false);f.payload=PaddedBytes::copy(b);q.push(std::move(f),0);CHECK(q.stats().bytes<=1024);CHECK(q.stats().highWaterBytes<=1024);}
+TEST(queue_malformed_time){VideoIngress q;start(q);CHECK(q.push(frame(1,false,10),9)==PushStatus::Malformed);CHECK(q.stats().waitingForIdr);}
+TEST(queue_concurrent_bound){VideoIngress q;q.begin(1);q.push(config(),0);std::atomic<bool> done=false,ok=true;std::thread producer([&]{for(std::uint16_t i=0;i<20000;++i){q.push(frame(i,i%10==0),0);auto s=q.stats();if(s.depth>4||s.bytes>8u*1024u*1024u)ok=false;}done=true;});std::thread consumer([&]{while(!done){(void)q.tryPop(0);std::this_thread::yield();}});producer.join();consumer.join();CHECK(ok);}
+TEST(audio_sample_count_per_channel){auto b=audio();CHECK(b.valid());CHECK(b.frames()==480);CHECK(b.samples.size()*sizeof(std::int16_t)==1920);}
+TEST(audio_overflow_discontinuous){AudioIngress q(20);q.begin(1);q.push(audio(0));q.push(audio(480));q.push(audio(960));CHECK(q.stats().dropped==1);CHECK(q.stats().bufferedMs==20);auto b=q.tryPop();CHECK(b&&b->firstSample==480&&b->discontinuity);}
+TEST(audio_out_of_order){AudioIngress q;q.begin(1);CHECK(q.push(audio(480)));CHECK(!q.push(audio(0)));CHECK(q.stats().rejected==1);}
+TEST(audio_reject_odd_channels){AudioIngress q;q.begin(1);auto b=audio();b.samples.pop_back();CHECK(!q.push(std::move(b)));CHECK(!q.push(audio(0,10000)));}
+TEST(audio_format_change){AudioIngress q;q.begin(1);q.push(audio());auto b=audio();b.rate=24000;b.channels=1;b.samples.resize(240);CHECK(q.push(std::move(b)));auto a=q.tryPop();CHECK(a&&a->rate==24000&&a->channels==1&&a->discontinuity);}
+TEST(audio_close_and_generation){AudioIngress q;q.begin(1);CHECK(!q.push(audio(0,480,2)));q.close();CHECK(!q.push(audio()));CHECK(!q.tryPop());}
+TEST(mailbox_latest_owned){LatestMailbox<std::shared_ptr<int>> m;m.begin(1);auto a=std::make_shared<int>(1);std::weak_ptr<int>w=a;m.publish({1,1,a});a.reset();m.publish({1,2,std::make_shared<int>(2)});CHECK(w.expired());auto s=m.take();CHECK(s&&*s->value==2);CHECK(m.overwritten()==1);CHECK(!m.take());}
+TEST(mailbox_generation_and_order){LatestMailbox<int> m;m.begin(1);CHECK(!m.publish({2,1,1}));CHECK(m.publish({1,2,2}));CHECK(!m.publish({1,1,1}));CHECK(!m.publish({1,2,22}));m.close();CHECK(!m.publish({1,3,3}));CHECK(!m.take());}
+struct FakeCodec {std::vector<SendStatus> sends;std::vector<ReceiveStatus> receives;std::vector<int> seen;std::size_t si=0,ri=0;SendStatus send(const int& n){seen.push_back(n);CHECK(si<sends.size());return sends[si++];}ReceiveStatus receive(){CHECK(ri<receives.size());return receives[ri++];}};
+TEST(pump_retries_same_packet){PacketPump<int> p;FakeCodec c{{SendStatus::NeedDrain,SendStatus::Accepted},{ReceiveStatus::Frame,ReceiveStatus::NeedInput,ReceiveStatus::Frame,ReceiveStatus::NeedInput},{},0,0};CHECK(p.submit(42));CHECK(p.step(c)==PumpStatus::Idle);CHECK((c.seen==std::vector<int>{42,42}));CHECK(p.stats().accepted==1&&p.stats().frames==2&&p.stats().eagain==1);}
+TEST(pump_double_eagain_rejected){PacketPump<int> p;FakeCodec c{{SendStatus::NeedDrain},{ReceiveStatus::NeedInput},{},0,0};p.submit(7);CHECK(p.step(c)==PumpStatus::ProtocolViolation);CHECK(p.stats().accepted==0&&p.hasPending());}
+TEST(pump_budget_retains_pending){PacketPump<int> p;FakeCodec c{{SendStatus::NeedDrain,SendStatus::Accepted},{ReceiveStatus::Frame,ReceiveStatus::NeedInput,ReceiveStatus::NeedInput},{},0,0};p.submit(9);CHECK(p.step(c,1)==PumpStatus::Yield&&p.hasPending());CHECK(!p.submit(10));CHECK(p.step(c)==PumpStatus::Idle);CHECK(c.seen.back()==9);}
+TEST(pump_error_not_accepted){PacketPump<int> p;FakeCodec c{{SendStatus::Error},{},{},0,0};p.submit(1);CHECK(p.step(c)==PumpStatus::Error);CHECK(p.stats().accepted==0);CHECK(!p.submit(2));p.reset();CHECK(p.submit(2));}
+TEST(pump_drain_all_frames){PacketPump<int> p;FakeCodec c{{SendStatus::Accepted},{ReceiveStatus::Frame,ReceiveStatus::Frame,ReceiveStatus::Frame,ReceiveStatus::NeedInput},{},0,0};p.submit(1);CHECK(p.step(c)==PumpStatus::Idle);CHECK(p.stats().frames==3&&p.drained());}
+TEST(pump_end_not_success){PacketPump<int> p;FakeCodec c{{SendStatus::End},{},{},0,0};p.submit(1);CHECK(p.step(c)==PumpStatus::End&&p.stats().accepted==0);CHECK(!p.submit(2));}
+TEST(input_focus_release){InputGate g;g.begin(1);ControllerState s;s.buttons=ControllerState::Cross;CHECK(!g.update(1,s,10));g.setFocused(true);CHECK(g.update(1,s,10));CHECK(g.sample(1,11)==s);g.setFocused(false);CHECK(g.sample(1,12)==ControllerState{});}
+TEST(input_stale_and_new_session){InputGate g;g.begin(1);g.setFocused(true);ControllerState s;s.l2=255;g.update(1,s,10);CHECK(g.sample(1,1000011)==ControllerState{});CHECK(g.sample(2,11)==ControllerState{});g.begin(2);g.setFocused(true);CHECK(!g.update(1,s,20));CHECK(g.sample(2,20)==ControllerState{});}
+TEST(inbox_connected_is_not_streaming){SessionInbox q;auto t=q.begin(monotonic100ns());CHECK(q.snapshot().state==SessionState::Connecting);t.connected();CHECK(q.snapshot().state==SessionState::WaitingFirstFrame);CHECK(q.decodedFrameReady(t.generation()));CHECK(q.snapshot().state==SessionState::Streaming);}
+TEST(inbox_reject_stale_callbacks){SessionInbox q;auto a=q.begin(monotonic100ns());q.invalidate();q.finishStop();auto b=q.begin(monotonic100ns());a.connected();CHECK(q.snapshot().state==SessionState::Connecting);CHECK(!a.video(config(a.generation(),monotonic100ns())));b.connected();CHECK(q.snapshot().state==SessionState::WaitingFirstFrame);CHECK(q.snapshot().staleCallbacks>=2);}
+TEST(inbox_weak_token_after_destruction){std::optional<SessionInbox::Token> t;{SessionInbox q;t=q.begin(monotonic100ns());}CHECK(!t->video(config(t->generation(),monotonic100ns())));t->connected();t->failed(99);}
+TEST(inbox_failure_closes_media){SessionInbox q;auto t=q.begin(monotonic100ns());CHECK(t.video(config(t.generation(),monotonic100ns())));t.failed(32);CHECK(q.snapshot().state==SessionState::Failed);CHECK(!q.isCurrent(t.generation()));CHECK(!q.tryVideo(monotonic100ns()));CHECK(q.snapshot().errorCode==32);}
+TEST(inbox_begin_and_stop_guards){SessionInbox q;THROWS(q.begin(-1));auto t=q.begin(monotonic100ns());THROWS(q.begin(monotonic100ns()));THROWS(q.finishStop());q.invalidate();THROWS(q.begin(monotonic100ns()));q.finishStop();CHECK(q.begin(monotonic100ns()).generation()>t.generation());}
+TEST(inbox_callbacks_race_invalidate){SessionInbox q;auto t=q.begin(monotonic100ns());std::atomic<bool> finish=false;std::thread worker([&]{while(!finish){t.connected();(void)t.audio(audio(0,480,t.generation()));}});q.invalidate();finish=true;worker.join();CHECK(!q.isCurrent(t.generation()));CHECK(!q.tryAudio());q.finishStop();CHECK(q.snapshot().state==SessionState::Idle);}
+TEST(inbox_failed_requires_backend_join){SessionInbox q;auto t=q.begin(monotonic100ns());t.failed(42);THROWS(q.begin(monotonic100ns()));q.invalidate();q.finishStop();CHECK(q.begin(monotonic100ns()).generation()>t.generation());}
+TEST(input_and_mailbox_zero_generation){InputGate g;THROWS(g.begin(0));LatestMailbox<int> m;THROWS(m.begin(0));VideoIngress v;THROWS(v.begin(0));AudioIngress a;THROWS(a.begin(0));}
+TEST(inbox_real_sample_vs_config_counts){SessionInbox q;auto t=q.begin(monotonic100ns());auto now=monotonic100ns();CHECK(t.video(config(t.generation(),now)));CHECK(q.snapshot().video.accessUnits==0);CHECK(t.video(frame(0,true,monotonic100ns(),t.generation())));CHECK(q.snapshot().video.accessUnits==1);auto v=q.tryVideo(monotonic100ns());CHECK(v&&v->sample.generation==t.generation());}
+}
+int main(int argc,char**argv){
+ std::string filter;
+ if(argc==2&&std::string_view(argv[1])=="--list"){for(auto [name,f]:tests()){(void)f;std::cout<<name<<'\n';}return 0;}
+ if(argc==3&&std::string_view(argv[1])=="--case")filter=argv[2];
+ else if(argc!=1){std::cerr<<"Usage: core_tests [--list | --case NAME]\n";return 2;}
+ unsigned pass=0,fail=0;
+ for(auto [name,f]:tests()){
+ if(!filter.empty()&&filter!=name)continue;
+ try{f();++pass;std::cout<<"PASS "<<name<<'\n';}
+ catch(const std::exception& e){++fail;std::cerr<<"FAIL "<<name<<": "<<e.what()<<'\n';}
+ }
+ if(pass+fail==0){std::cerr<<"No test matched\n";return 2;}
+ std::cout<<"TOTAL "<<pass+fail<<" PASS "<<pass<<" FAIL "<<fail<<'\n';
+ return fail?1:0;
+}