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

fix(remoteplay): repair first-frame decode, PCM continuity and decoded timestamps

Veyra Goal Agent88277213b2e9
diff --git a/docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md b/docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md
index 7bebcb74..7047d77b 100644
--- a/docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md
+++ b/docs/REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md
@@ -1,5 +1,7 @@
# Veyra PS5 Remote Play 集成交接
+> 二次审计后用户授权当前 Agent 继续施工,节点状态改由 [修复执行记录](REMOTEPLAY_REPAIR_EXECUTION_2026-09-11.md) 维护。本文第18节保留修复前证据,不应据旧缺陷表断言新代码仍未修。
+
日期:2026-09-11
当前分支:`agent/remoteplay-integration`
代码基线:`0f78cc29f34365589bcd4757e7017236e3ac9cb1`
diff --git a/docs/REMOTEPLAY_REPAIR_EXECUTION_2026-09-11.md b/docs/REMOTEPLAY_REPAIR_EXECUTION_2026-09-11.md
new file mode 100644
index 00000000..7b3801a9
--- /dev/null
+++ b/docs/REMOTEPLAY_REPAIR_EXECUTION_2026-09-11.md
@@ -0,0 +1,41 @@
+# Remote Play 修复与产品集成执行记录
+
+用户在二次审计后授权本 Agent 继续修复并完成产品集成,要求大节点本地 Git 存档和更新文档。未授权本轮远端发布。原问题、架构、依赖和验收边界见 [交接第18节](REMOTEPLAY_INTEGRATION_HANDOFF_2026-09-11.md#18-2026-09-11-二次代码审计用户要求交给其他-agent-修)。
+
+## 存档与当前节点
+
+- 修复前存档 `bf21bef`,标签 `checkpoint/remoteplay-audited-2026-09-11`。保留原代码和审计,不冒充可用版本。
+- 当前分支 `agent/remoteplay-integration`。
+- 节点一:源层首帧/PCM/时间戳闭环。已完成下列修改和针对性验证,仍未接主程序。
+
+## 节点一已实现
+
+1. H.264 配置前缀与首个 AU 合并送入 FFmpeg,避免只含 SPS/PPS 的输入终止首帧。
+2. 给提交包分配独立 ID,解码输出按 AVFrame PTS 查回有界元数据表;不再套当前输入包。未知/重复输出 ID 明确失败并触发恢复,不伪造额外帧时间。
+3. PCM 保存 block/cursor,固定音频段相对起点+样本差值;到达抖动不改变连续播放速度,断点不混拼到同次 pull。
+4. 首帧交付进入 Streaming;解析实际颜色与尺寸,更新 SourceInfo/Resize,720p fallback 改 BT.709;释放旧 decoder frame 后重建。
+5. source owner 路径消费 IDR 请求,送 backend;decode 失败 flush、请求关键帧并返回 Waiting。尚需补模拟后端失败/恢复超时测试。
+6. 16位wire序号经展开器进入 source(普通callback尚未恢复metadata,此项尚不能算实机验证)。
+7. Opus settings 保持会话内样本序号,不因同格式header重来归零;明确48k限制。close检查stop结果,失败不标Idle并拒绝重连,及时清空request凭据。上述异常backend分支只有静态核对和编译,尚需注入回归。
+
+## 实际验证
+
+日志目录 `logs/remoteplay-audit-20260911/`,新增 `tests/remoteplay/SourceTests.cpp` 通过friend测试入口访问真实source,编译独立实现,不用shadow头也不复制生产实现。
+
+- `native-source-build.log`:从全新目录配置并构建254目标,末尾因FFmpeg头的conversion warning被/WX升级失败。只把第三方include标为SYSTEM,保留自有代码/WX;`native-source-build2.log`后续配置/编译/链接成功。
+- 完整构建入口:忽略目录 `out/remoteplay/audit-20260911/build-native-source.cmd`,vcvars64+UTF8+Windows TEMP,CMake目录 `native-source-repair`;传固定stage/verify、PrefixPath、PROTOC、PKG_CONFIG_EXECUTABLE、`VEYRA_RP_FFMPEG_ROOT=C:/veyra-deps/installed/x64-windows`。构建真实Chiaki adapter/native probe/core/source targets。
+- 新source目标输出 `REMOTEPLAY_SOURCE_REGRESSIONS_PASS`,`source-fixed.stdout.log`:PCM 480/480、相对PTS30ms、后续到达抖动仍按样本前进、断点分段;split config首帧Frame/Streaming;SourceInfo1920→真实1280;重排10帧错配0。
+- 新编译core 67/67,native初始化exit0:`core-fixed/native-fixed.stdout.log`。
+- 所有运行均经 `scripts/run-short-test.ps1`、30秒上限;本地合成素材ffmpeg每次60秒上限。`scripts/remoteplay/make-source-fixtures.py --output <ignored-directory>` 生成可重现fixture,不提交媒体。
+- 本轮初次诊断编译误用了旧shadow头而失败,重新生成后成功;另一个短暂源码编辑误把connect guard放入析构,在构建前读回时发现并改正。没有把这些状态作为通过证据。
+- 暂存基线时 `git diff --cached --check` 发现之前未跟踪Markdown的硬换行和patch上下文空白;此前 `git diff --check` 不覆盖未跟踪文件,应据此理解旧格式结论。patch上下文空白不能删除,否则会改变补丁。当前源代码diff检查通过。
+
+## 后续必须继续,不算整体完成
+
+1. 恢复真实metadata通道并验证16位回绕、实际profile;完善stage全文/index/子模块校验。
+2. H.265、配置切换、坏包→IDR、stop失败、同格式音频重启/非48k、PCM随机粒度等补回归。尚未完成source层全部18项验收。
+3. 正式生产CMake OFF/ON闭环,把解码owner与GPU解耦、复用同一EngineController/run/graph/presenter。
+4. 独立音频owner、DPAPI、配对/取消/PIN、Win32入口、手柄、发现/唤醒。
+5. 完整Veyra构建/delivery、PS5实机声音/画面/输入/增强/重连和延迟验收。
+
+没有关闭用户播放器、占用采集卡、连接PS5、执行NVIDIA runtime或完整产品测试。节点一测试只证明上述真实FFmpeg与离线行为,不证明串流可用。原交接第18节是修复前缺陷账本,当前实现状态以本文节点证据更新。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index bba82fd7..d47bcac6 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1622,3 +1622,7 @@ FRUC候选bSkipWarp/延后重建/时间归零/首对预热均未通过新增rese
本轮未修产品、未改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/压缩包/合成媒体后缀扫描无未忽略二进制。用户原有未提交代码完整保留。
+
+## 2026-09-11 Remote Play 开工与源层首批修复
+
+用户授权继续完成并在大节点创建Git/更新文档。先存档 `bf21bef`(`checkpoint/remoteplay-audited-2026-09-11`),然后修配置/AU首帧、PCM尾部与固定相对锚点、重排PTS映射、Streaming状态、实际尺寸/颜色、decoder frame释放,并补IDR消费、wire展开、48k/Opus样本序号和stop失败状态。详细文件、实际命令、失败及未测项见 `docs/REMOTEPLAY_REPAIR_EXECUTION_2026-09-11.md`。真实FFmpeg source回归显示480/480样本、首帧成功、重排错配10→0;新目录真实Chiaki/core/source构建通过,core67/67、native初始化exit0,单次测试30秒上限。首建遇第三方头/WX失败,标SYSTEM后通过;保留日志 `logs/remoteplay-audit-20260911/native-source-build*.log`、`source-fixed/core-fixed/native-fixed.stdout.log`。尚未接主程序/PS5/音频设备/GPU;其余审计项和UI/手柄等继续,不声明整体完成。源码/SDK/媒体分离,未push发布。
diff --git a/docs/remoteplay/NEXT_AGENT.md b/docs/remoteplay/NEXT_AGENT.md
index 987550a7..bdbf67ea 100644
--- a/docs/remoteplay/NEXT_AGENT.md
+++ b/docs/remoteplay/NEXT_AGENT.md
@@ -1,5 +1,7 @@
# 交给下一位 Agent 的接续指令
+> 用户已改为由当前 Agent 继续施工。修复前审计保留;最新完成项与下一步见 [执行记录](../REMOTEPLAY_REPAIR_EXECUTION_2026-09-11.md),不要把下文修复前状态当作最新代码结论。
+
唯一交接入口:[`../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 正确。
diff --git a/include/veyra/source/RemotePlaySource.h b/include/veyra/source/RemotePlaySource.h
index 5f1360be..181f7e9a 100644
--- a/include/veyra/source/RemotePlaySource.h
+++ b/include/veyra/source/RemotePlaySource.h
@@ -50,6 +50,7 @@ public:
std::size_t pullAudio(float* stereo, std::size_t frames, double* firstPtsMs);
private:
+ friend struct RemotePlaySourceTestAccess;
struct DecodedFrame {
std::shared_ptr<AVFrame> frame;
pipeline::FramePacket packet;
@@ -73,11 +74,22 @@ private:
AVFrame* decoderFrame_ = nullptr;
std::deque<DecodedFrame> ready_;
std::shared_ptr<AVFrame> lastFrame_;
+ struct PacketStamp { std::int64_t id; pipeline::FramePacket packet; };
+ std::deque<PacketStamp> packetStamps_;
+ std::optional<remoteplay::PcmBlock> audioBlock_;
+ std::size_t audioOffset_ = 0;
+ std::optional<std::uint64_t> audioAnchorSample_;
+ std::int64_t audioAnchorPts_ = 0;
+ std::uint64_t audioNextSample_ = 0;
+ std::uint32_t audioRate_ = 0;
+ std::int64_t nextPacketId_ = 0;
+ remoteplay::Sequence16Extender wireSequence_;
std::uint64_t sequence_ = 0;
std::uint64_t fallbackSourceIndex_ = 0;
std::uint64_t decoderEpoch_ = 1;
std::uint64_t origin100ns_ = 0;
bool connected_ = false;
+ bool stopFailed_ = false;
bool decoderReady_ = false;
bool waitingForFirstFrame_ = true;
bool pendingOpenFlag_ = true;
diff --git a/scripts/remoteplay/make-source-fixtures.py b/scripts/remoteplay/make-source-fixtures.py
new file mode 100644
index 00000000..75751107
--- /dev/null
+++ b/scripts/remoteplay/make-source-fixtures.py
@@ -0,0 +1,31 @@
+"""Generate public synthetic source fixtures; no captured media is required."""
+import argparse
+from pathlib import Path
+import re
+import subprocess
+
+parser = argparse.ArgumentParser(description=__doc__)
+parser.add_argument('--output', type=Path, required=True)
+parser.add_argument('--ffmpeg', default='ffmpeg')
+args = parser.parse_args()
+args.output.mkdir(parents=True, exist_ok=True)
+for name, extra in [('single', ['-frames:v', '1', '-tune', 'zerolatency']),
+ ('reorder', ['-frames:v', '12', '-bf', '2'])]:
+ subprocess.run([args.ffmpeg, '-hide_banner', '-loglevel', 'error', '-y',
+ '-f', 'lavfi', '-i', 'testsrc2=size=1280x720:rate=60',
+ '-c:v', 'libx264', '-preset', 'fast', '-color_primaries', 'bt709',
+ '-color_trc', 'bt709', '-colorspace', 'bt709', *extra,
+ '-f', 'h264', str(args.output / (name + '.h264'))],
+ check=True, timeout=60)
+data = (args.output / 'single.h264').read_bytes()
+starts = list(re.finditer(b'\x00\x00(?:\x00)?\x01', data))
+config, picture = bytearray(), bytearray()
+for i, match in enumerate(starts):
+ end = starts[i + 1].start() if i + 1 < len(starts) else len(data)
+ chunk = data[match.start():end]
+ (config if data[match.end()] & 31 in (7, 8) else picture).extend(chunk)
+if not config or not picture:
+ raise RuntimeError('Encoder did not emit required SPS/PPS and picture NALs')
+(args.output / 'single-config.bin').write_bytes(config)
+(args.output / 'single-au.bin').write_bytes(picture)
+print('Generated synthetic H.264 configuration, first AU and reordered stream')
diff --git a/services/remoteplay-probe/NativeChiaki.cmake b/services/remoteplay-probe/NativeChiaki.cmake
index 1d228a94..0f1c612d 100644
--- a/services/remoteplay-probe/NativeChiaki.cmake
+++ b/services/remoteplay-probe/NativeChiaki.cmake
@@ -73,3 +73,19 @@ target_compile_definitions(veyra_remoteplay_native_probe PRIVATE NOMINMAX WIN32_
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")
+
+# Optional source regressions link the production adapter and real FFmpeg.
+set(VEYRA_RP_FFMPEG_ROOT "" CACHE PATH "Existing Veyra FFmpeg installation")
+if(VEYRA_RP_FFMPEG_ROOT)
+ add_executable(veyra_remoteplay_source_tests
+ "${VEYRA_ROOT}/tests/remoteplay/SourceTests.cpp"
+ "${VEYRA_ROOT}/src/source/RemotePlaySource.cpp"
+ "${VEYRA_ROOT}/src/base/Log.cpp")
+ target_compile_features(veyra_remoteplay_source_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_remoteplay_source_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_include_directories(veyra_remoteplay_source_tests SYSTEM PRIVATE "${VEYRA_RP_FFMPEG_ROOT}/include")
+ target_link_libraries(veyra_remoteplay_source_tests PRIVATE veyra_remoteplay_chiaki
+ "${VEYRA_RP_FFMPEG_ROOT}/lib/avcodec.lib"
+ "${VEYRA_RP_FFMPEG_ROOT}/lib/avutil.lib"
+ "${VEYRA_RP_FFMPEG_ROOT}/lib/avformat.lib")
+endif()
diff --git a/src/remoteplay/ChiakiBackend.cpp b/src/remoteplay/ChiakiBackend.cpp
index f78183eb..5bbe6f6f 100644
--- a/src/remoteplay/ChiakiBackend.cpp
+++ b/src/remoteplay/ChiakiBackend.cpp
@@ -55,6 +55,7 @@ struct ChiakiBackend::Impl {
// Only the upstream audio/Opus callback thread reads/writes these fields.
std::uint32_t channels=0,rate=0;
std::uint64_t sampleIndex=0;
+ bool audioDiscontinuity=true;
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.
@@ -93,8 +94,10 @@ struct ChiakiBackend::Impl {
}
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);}
+ // Sample position stays monotonic across repeated Opus headers within
+ // one session; restarting at zero makes AudioIngress reject new PCM.
+ self.channels=channels;self.rate=rate;self.audioDiscontinuity=true;
+ if((channels!=1&&channels!=2)||rate!=48000){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);
@@ -102,10 +105,10 @@ struct ChiakiBackend::Impl {
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;
+ block.firstSample=self.sampleIndex;block.arrival100ns=monotonic100ns();block.discontinuity=self.audioDiscontinuity;
// 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));
+ if(self.token.audio(std::move(block))) self.audioDiscontinuity=false;
}catch(...){self.apiError=-1002;self.token.failed(-1002);}
}
BackendResult record(ChiakiErrorCode code,const char* name){apiError=static_cast<int>(code);return result(code,name);}
diff --git a/src/source/RemotePlaySource.cpp b/src/source/RemotePlaySource.cpp
index 41c5cfd4..445de7b0 100644
--- a/src/source/RemotePlaySource.cpp
+++ b/src/source/RemotePlaySource.cpp
@@ -65,6 +65,10 @@ bool RemotePlaySource::open(const SourceOpenDesc&)
bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)
{
close();
+ if (stopFailed_) {
+ veyra::log::error("remoteplay", "connect refused: previous session did not stop successfully");
+ return false;
+ }
if (desc.request.video.validate() || !remoteplay::validHost(desc.request.host)) {
veyra::log::error("remoteplay", "connect rejected: invalid host or video profile");
return false;
@@ -80,6 +84,7 @@ bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)
try {
inbox_ = std::make_unique<remoteplay::SessionInbox>(desc.queueLimits);
} catch (...) {
+ request_.credentials = remoteplay::PairingCredentials{};
veyra::log::error("remoteplay", "invalid queue limits");
return false;
}
@@ -87,10 +92,8 @@ bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)
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));
+ close();
return false;
}
info_ = SourceInfo{};
@@ -107,7 +110,7 @@ bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)
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.matrix = pipeline::YuvMatrix::BT709;
info_.color.matrixAssumed = true;
info_.color.transfer = pipeline::TransferFunction::BT709;
info_.color.transferAssumed = true;
@@ -144,6 +147,7 @@ bool RemotePlaySource::openDecoder(remoteplay::Codec codec, std::uint32_t width,
avcodec_free_context(&codecContext_);
decoderReady_ = false;
}
+ av_frame_free(&decoderFrame_);
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) {
@@ -158,6 +162,7 @@ bool RemotePlaySource::openDecoder(remoteplay::Codec codec, std::uint32_t width,
codecContext_->width = static_cast<int>(width);
codecContext_->height = static_cast<int>(height);
codecContext_->time_base = AVRational{1, static_cast<int>(request_.video.fps)};
+ codecContext_->pkt_timebase = codecContext_->time_base;
codecContext_->thread_count = 1;
codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
if (avcodec_open2(codecContext_, decoder, nullptr) < 0) {
@@ -216,14 +221,34 @@ bool RemotePlaySource::drainDecoder(std::uint64_t sourceIndex, const pipeline::F
}
auto clone = cloneFrame(decoderFrame_);
if (!clone) return false;
- pipeline::FramePacket packet = sourcePacket;
+ const auto stamp = std::find_if(packetStamps_.begin(), packetStamps_.end(),
+ [&](const PacketStamp& value) { return value.id == decoderFrame_->pts; });
+ if (stamp == packetStamps_.end()) {
+ veyra::log::error("remoteplay", "decoded frame has no matching packet timestamp");
+ return false;
+ }
+ pipeline::FramePacket packet = stamp->packet;
+ packetStamps_.erase(stamp);
packet.sequence = ++sequence_;
+ packet.colorInfo = pipeline::resolveFrameColor(*decoderFrame_, info_.color);
packet.colorInfo.pixelFormat = pixelFormatFromFrame(*decoderFrame_);
+ if (decoderFrame_->width <= 0 || decoderFrame_->height <= 0 ||
+ decoderFrame_->width > 1920 || decoderFrame_->height > 1080 ||
+ packet.colorInfo.pixelFormat == pipeline::SourcePixelFormat::Unknown ||
+ packet.colorInfo.isHdrPath()) return false;
+ if (info_.width != static_cast<uint32_t>(decoderFrame_->width) ||
+ info_.height != static_cast<uint32_t>(decoderFrame_->height)) {
+ info_.width = static_cast<uint32_t>(decoderFrame_->width);
+ info_.height = static_cast<uint32_t>(decoderFrame_->height);
+ packet.flags |= static_cast<pipeline::FrameFlags>(pipeline::FrameFlagBits::Resize);
+ }
+ info_.color = packet.colorInfo;
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;
+ // The AU contract is one picture per input. Unknown/reused timestamps
+ // are rejected above instead of fabricating timing for extra pictures.
+ (void)sourcePacket;
(void)sourceIndex;
+ if (ready_.size() >= 4) return false;
ready_.push_back({std::move(clone), packet});
}
}
@@ -238,8 +263,13 @@ bool RemotePlaySource::submitPacket(std::span<const std::uint8_t> bytes,
return false;
}
std::memcpy(packet->data, bytes.data(), bytes.size());
- packet->pts = static_cast<int64_t>(sourceIndex);
- packet->dts = packet->pts;
+ if (packetStamps_.size() >= 64 || nextPacketId_ == INT64_MAX) {
+ av_packet_free(&packet);
+ return false;
+ }
+ packet->pts = nextPacketId_++;
+ packet->dts = AV_NOPTS_VALUE;
+ packetStamps_.push_back({packet->pts, sourcePacket});
bool ok = true;
for (;;) {
const int send = avcodec_send_packet(codecContext_, packet);
@@ -263,12 +293,20 @@ SourceReadStatus RemotePlaySource::read(pipeline::FramePacket& out, const AVFram
{
if (decodedFrame) *decodedFrame = nullptr;
if (!connected_) return SourceReadStatus::Error;
+ if (inbox_->takeIdrRequest(remoteplay::monotonic100ns())) {
+ const auto idr = backend_.requestIdr();
+ if (!idr.ok) {
+ veyra::log::warn("remoteplay", std::format("{} code={}", idr.operation, idr.code));
+ if (token_) inbox_->decodeFailed(token_->generation());
+ }
+ }
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();
+ if (token_) inbox_->decodedFrameReady(token_->generation());
return SourceReadStatus::Frame;
}
const auto now = remoteplay::monotonic100ns();
@@ -279,7 +317,7 @@ SourceReadStatus RemotePlaySource::read(pipeline::FramePacket& out, const AVFram
return SourceReadStatus::Waiting;
}
const auto& sample = queued->sample;
- if (!decoderReady_ && !openDecoder(sample.codec, sample.width, sample.height)) {
+ if ((!decoderReady_ || queued->resetDecoder) && !openDecoder(sample.codec, sample.width, sample.height)) {
inbox_->decodeFailed(sample.generation);
return SourceReadStatus::Error;
}
@@ -289,17 +327,24 @@ SourceReadStatus RemotePlaySource::read(pipeline::FramePacket& out, const AVFram
clock_.reset(static_cast<remoteplay::HostTime>(origin100ns_), request_.video.fps);
pendingOpenFlag_ = true;
}
- const std::uint64_t sourceIndex = sample.wireFrameIndex
- ? *sample.wireFrameIndex
- : ++fallbackSourceIndex_;
+ const auto extended = sample.wireFrameIndex ? wireSequence_.observe(*sample.wireFrameIndex)
+ : remoteplay::Sequence16Extender::Result{++fallbackSourceIndex_,true,false,0};
+ if (!extended.accepted) { inbox_->decodeFailed(sample.generation); return SourceReadStatus::Waiting; }
+ const std::uint64_t sourceIndex = extended.value;
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;
+ std::vector<uint8_t> combined;
+ auto payload = sample.payload.bytes();
+ if (queued->configBefore) {
+ const auto config = queued->configBefore->payload.bytes();
+ combined.reserve(config.size() + payload.size());
+ combined.insert(combined.end(), config.begin(), config.end());
+ combined.insert(combined.end(), payload.begin(), payload.end());
+ payload = combined;
}
- if (!submitPacket(sample.payload.bytes(), sourceIndex, sourcePacket)) {
+ if (!submitPacket(payload, sourceIndex, sourcePacket)) {
+ flushDecoder();
inbox_->decodeFailed(sample.generation);
- return SourceReadStatus::Error;
+ return SourceReadStatus::Waiting;
}
if (ready_.empty()) return SourceReadStatus::Waiting;
auto item = std::move(ready_.front());
@@ -308,12 +353,14 @@ SourceReadStatus RemotePlaySource::read(pipeline::FramePacket& out, const AVFram
lastFrame_ = std::move(item.frame);
if (decodedFrame) *decodedFrame = lastFrame_.get();
waitingForFirstFrame_ = false;
+ inbox_->decodedFrameReady(sample.generation);
return SourceReadStatus::Frame;
}
void RemotePlaySource::flushDecoder() noexcept
{
ready_.clear();
+ packetStamps_.clear();
if (codecContext_) avcodec_flush_buffers(codecContext_);
}
@@ -322,25 +369,40 @@ std::size_t RemotePlaySource::pullAudio(float* stereo, std::size_t frames, doubl
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 (!audioBlock_) {
+ audioBlock_ = inbox_->tryAudio();
+ audioOffset_ = 0;
+ }
+ if (!audioBlock_) break;
+ auto* block = &*audioBlock_;
+ if (!block->valid() || block->rate != 48000) { audioBlock_.reset(); continue; }
+ if (audioOffset_ == 0) {
+ const bool reset = !audioAnchorSample_ || block->discontinuity ||
+ block->firstSample != audioNextSample_ || block->rate != audioRate_;
+ if (reset && written) break;
+ if (reset) {
+ audioAnchorSample_ = block->firstSample;
+ audioAnchorPts_ = block->arrival100ns - static_cast<int64_t>(origin100ns_);
+ audioRate_ = block->rate;
+ }
+ }
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;
+ *firstPtsMs = static_cast<double>(audioAnchorPts_) / 10000.0 +
+ 1000.0 * static_cast<double>(block->firstSample - *audioAnchorSample_ + audioOffset_) / block->rate;
}
- const auto copyFrames = std::min(frames - written, block->frames());
+ const auto copyFrames = std::min(frames - written, block->frames() - audioOffset_);
for (std::size_t i = 0; i < copyFrames; ++i) {
const auto sourceChannels = block->channels;
- const auto sourceIndex = i * sourceChannels;
+ const auto sourceIndex = (i + audioOffset_) * 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;
+ audioOffset_ += copyFrames;
+ audioNextSample_ = block->firstSample + audioOffset_;
+ if (audioOffset_ == block->frames()) audioBlock_.reset();
}
return written;
}
@@ -351,15 +413,25 @@ void RemotePlaySource::close() noexcept
ready_.clear();
lastFrame_.reset();
if (token_) {
- inbox_->invalidate();
- (void)backend_.stop();
- try { inbox_->finishStop(); } catch (...) {}
- token_.reset();
+ try {
+ inbox_->invalidate();
+ const auto stopped = backend_.stop();
+ stopFailed_ = !stopped.ok;
+ if (stopped.ok) {
+ inbox_->finishStop();
+ token_.reset();
+ } else {
+ veyra::log::error("remoteplay", std::format("{} failed code={}; session remains stopping",stopped.operation,stopped.code));
+ }
+ } catch (...) { stopFailed_ = true; }
}
flushDecoder();
av_frame_free(&decoderFrame_);
avcodec_free_context(&codecContext_);
decoderReady_ = false;
+ audioBlock_.reset(); audioAnchorSample_.reset(); audioOffset_ = 0;
+ audioNextSample_ = 0; audioRate_ = 0; wireSequence_.reset();
+ request_.credentials = remoteplay::PairingCredentials{};
info_ = SourceInfo{};
}
diff --git a/tests/remoteplay/SourceTests.cpp b/tests/remoteplay/SourceTests.cpp
new file mode 100644
index 00000000..b5331c2f
--- /dev/null
+++ b/tests/remoteplay/SourceTests.cpp
@@ -0,0 +1,109 @@
+#include "veyra/source/RemotePlaySource.h"
+#include "veyra/pipeline/ColorMetadata.h"
+#include <algorithm>
+#include <stdexcept>
+#include <cmath>
+extern "C" {
+#include <libavcodec/avcodec.h>
+}
+extern "C" {
+#include <libavformat/avformat.h>
+}
+#include <fstream>
+#include <iostream>
+#include <iterator>
+using namespace veyra;
+using namespace veyra::remoteplay;
+using namespace veyra::source;
+namespace veyra::source {
+struct RemotePlaySourceTestAccess {
+static void check(bool ok) { if(!ok) throw std::runtime_error("RemotePlay source regression failed"); }
+static std::vector<uint8_t> bytes(const char* path) {
+ std::ifstream f(path,std::ios::binary); return {std::istreambuf_iterator<char>(f),{}};
+}
+static void setup(RemotePlaySource& s) {
+ s.origin100ns_=monotonic100ns();
+ s.token_=s.inbox_->begin(static_cast<HostTime>(s.origin100ns_));
+ s.token_->connected(); s.connected_=true;
+ s.clock_.reset(static_cast<HostTime>(s.origin100ns_),60);
+ s.info_.width=1280;s.info_.height=720;
+ s.info_.color.matrix=pipeline::YuvMatrix::BT601;
+ s.info_.color.range=pipeline::ColorRange::Limited;
+ s.info_.color.transfer=pipeline::TransferFunction::BT709;
+}
+static void pcm() {
+ RemotePlaySource s;setup(s);
+ PcmBlock b;b.generation=s.token_->generation();b.channels=2;b.rate=48000;
+ b.arrival100ns=static_cast<HostTime>(s.origin100ns_)+300000;
+ for(int i=0;i<480;++i){b.samples.push_back(static_cast<int16_t>(i));b.samples.push_back(static_cast<int16_t>(i));}
+ s.token_->audio(std::move(b));float out[960]{};double pts=0;
+ auto n1=s.pullAudio(out,100,&pts);auto n2=s.pullAudio(out,380,nullptr);
+ std::cout<<"PCM supplied=480 pulled="<<n1+n2<<" first_pts_ms="<<pts<<" expected_relative_ms=30\n";
+ check(n1==100 && n2==380 && std::abs(pts-30.0)<0.001);
+ for(int i=0;i<380;++i) check(std::abs(out[i*2]-(i+100)/32768.0f)<1e-6f);
+ // Network arrival jitter must not change steady sample cadence.
+ PcmBlock next;next.generation=s.token_->generation();next.channels=2;next.rate=48000;
+ next.firstSample=480;next.arrival100ns=static_cast<HostTime>(s.origin100ns_)+490000;
+ next.samples.resize(960,17);check(s.token_->audio(std::move(next)));
+ check(s.pullAudio(out,480,&pts)==480 && std::abs(pts-40.0)<0.001);
+ // A genuine new segment is returned separately, not concatenated across a gap.
+ for(int i=0;i<2;++i){PcmBlock x;x.generation=s.token_->generation();x.channels=2;x.rate=48000;
+ x.firstSample=960+static_cast<uint64_t>(i)*480;x.arrival100ns=static_cast<HostTime>(s.origin100ns_)+600000+i*100000;
+ x.discontinuity=i==1;x.samples.resize(960,18);check(s.token_->audio(std::move(x)));}
+ float large[1920];check(s.pullAudio(large,960,&pts)==480);
+ check(s.pullAudio(large,480,&pts)==480 && std::abs(pts-70.0)<0.001);
+}
+static void splitTest(const char* prefix) {
+ RemotePlaySource s;setup(s);auto config=bytes((std::string(prefix)+"-config.bin").c_str());
+ auto au=bytes((std::string(prefix)+"-au.bin").c_str());
+ VideoSample c;c.generation=s.token_->generation();c.width=1280;c.height=720;
+ c.arrival100ns=monotonic100ns();c.kind=SampleKind::CodecConfig;c.payload=PaddedBytes::copy(config);
+ VideoSample f;f.generation=c.generation;f.width=1280;f.height=720;
+ f.arrival100ns=monotonic100ns();f.wireFrameIndex=1;f.payload=PaddedBytes::copy(au);
+ const auto ca=s.token_->video(std::move(c));const auto fa=s.token_->video(std::move(f));
+ pipeline::FramePacket p;const AVFrame* frame=nullptr;auto r=s.read(p,&frame);
+ std::cout<<"SPLIT_H264 config_accepted="<<ca<<" au_accepted="<<fa<<" read_status="<<int(r)
+ <<" frame="<<bool(frame)<<" session_state="<<int(s.sessionSnapshot().state)<<"\n";
+ check(ca && fa && r==SourceReadStatus::Frame && frame && s.sessionSnapshot().state==SessionState::Streaming);
+ // Same actual decoder/stream, with SPS/PPS prepended to AU in one packet.
+ RemotePlaySource combined;setup(combined);combined.openDecoder(Codec::H264,1920,1080);
+ config.insert(config.end(),au.begin(),au.end());pipeline::FramePacket sp;sp.pts={0,60};sp.colorInfo=combined.info_.color;
+ bool ok=combined.submitPacket(config,0,sp);
+ std::cout<<"COMBINED_H264 ok="<<ok<<" decoded="<<combined.ready_.size();
+ if(!combined.ready_.empty()){
+ auto& d=combined.ready_.front();std::cout<<" av_matrix="<<int(d.frame->colorspace)
+ <<" packet_matrix="<<int(d.packet.colorInfo.matrix)<<" av_range="<<int(d.frame->color_range)
+ <<" packet_range="<<int(d.packet.colorInfo.range)
+ <<" resolved_matrix="<<int(pipeline::resolveFrameColor(*d.frame,d.packet.colorInfo).matrix)
+ <<" info_width="<<combined.info_.width<<" decoded_width="<<d.frame->width;
+ }
+ std::cout<<"\n";
+ pipeline::FramePacket decodedPacket;const AVFrame* decodedView=nullptr;
+ auto rr=combined.read(decodedPacket,&decodedView);
+ check(rr==SourceReadStatus::Frame && decodedView && combined.info_.width==1280 && combined.sessionSnapshot().state==SessionState::Streaming);
+ std::cout<<"REAL_FRAME_STATE read_status="<<int(rr)<<" frame="<<bool(decodedView)
+ <<" session_state="<<int(combined.sessionSnapshot().state)<<" streaming_enum="<<int(SessionState::Streaming)<<"\n";
+}
+static void reorder(const char* path) {
+ RemotePlaySource s;setup(s);s.openDecoder(Codec::H264,1280,720);
+ AVFormatContext* fmt=nullptr;if(avformat_open_input(&fmt,path,nullptr,nullptr)<0)throw std::runtime_error("open fixture");
+ AVPacket* p=av_packet_alloc();uint64_t n=0;int mismatches=0,outputs=0;
+ while(av_read_frame(fmt,p)>=0){pipeline::FramePacket sp;sp.pts={static_cast<int64_t>(n),60};sp.colorInfo=s.info_.color;
+ if(!s.submitPacket({p->data,static_cast<size_t>(p->size)},n,sp))throw std::runtime_error("submit AU");
+ while(!s.ready_.empty()) {auto d=std::move(s.ready_.front());s.ready_.pop_front();++outputs;
+ if(d.frame->pts!=d.packet.pts.num){++mismatches;std::cout<<"REORDER actual_packet_id="<<d.frame->pts<<" assigned="<<d.packet.pts.num<<"\n";}}
+ ++n;av_packet_unref(p);
+ }
+ av_packet_free(&p);avformat_close_input(&fmt);
+ check(n==12 && outputs==10 && mismatches==0);
+ std::cout<<"REORDER input="<<n<<" output_before_eof="<<outputs<<" wrong_pts="<<mismatches<<"\n";
+}
+};
+}
+int main(int argc,char**argv) {
+ if(argc!=3)return 2;
+ std::cout<<"SOURCE_TEST: real FFmpeg, direct inbox injection; NO PS5/WASAPI/GPU validation\n";
+ try{RemotePlaySourceTestAccess::pcm();RemotePlaySourceTestAccess::splitTest(argv[1]);RemotePlaySourceTestAccess::reorder(argv[2]);}
+ catch(const std::exception& e){std::cerr<<e.what()<<"\n";return 2;}
+ std::cout<<"REMOTEPLAY_SOURCE_REGRESSIONS_PASS\n"; return 0;
+}