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

feat: persist PS5 consoles and add PSN authorization and HDR preview

Veyra Goal Agent7c0b0d8a4fbb
diff --git a/AGENTS.md b/AGENTS.md
index 91445698..c5a618d8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,5 +1,7 @@
# Veyra 项目 Agent 执行规则
+> 2026-09-12 用户授权实施 PS5 HDR、PSN 登录与主机保留方案(docs/PS5_HDR_PSN_HOST_PLAN_2026-09-12.md)。仅对本次经过显式HDR输入/输出契约的PS5路径扩展旧SDR限制;文件/采集/导出不得全局放开HDR防错检查。原生HDR旁路显示与“HDR转SDR后增强”必须区分,不能将实验NR的SDR结果冒充原生HDR增强。PSN凭据及主机密钥只在用户数据目录DPAPI加密保存,不提交Git。当前状态按对应施工记录,不由本授权推断测试通过。
+
> 2026-09-12 用户授权默认关闭的“低延迟模式”:实时预览可选 NR→SR→FG,取代本文件对该选项的固定SR先行限制。NR在源尺寸(或明确的实时内部尺寸)执行,残差/保护合成后再进入SR;共享现有图、光流和生命周期,不另造播放循环。默认仍SR→NR→FG,图片/视频导出保持原有完整处理。不得保证所有素材延迟下降;提示可能增加拖影/边缘瑕疵,真实屏幕撕裂不能简单归因于算法顺序。见 docs/NR_BEFORE_SR_PREVIEW_2026-09-12.md。
> 2026-09-11 用户授权执行实时调度修复(方案见 `docs/REALTIME_AV_SCHEDULING_REPAIR_PLAN_2026-09-11.md`,开工前存档点 `checkpoint/av-scheduling-2026-09-11`,隔离分支施工):实时文件/采集**预览**在持续欠速时允许按真实 PTS 跳过已解码源帧的增强/呈现机会(先省补帧工作,再省原帧增强),稳态音频不停机、媒体时间保持一倍速、跳帧均匀覆盖时间线;源 PTS/序号/duration 保持真实,历史按断点 reset。该例外只限实时预览:视频导出、图片处理、暂停单帧查看仍必须完整处理,不得把丢帧扩大到导出,也不得把预览跳帧伪装成未丢帧。不得以停音频/丢 PCM/偷偷放慢声音制造同步。
diff --git a/CMakeLists.txt b/CMakeLists.txt
index c53a7260..cebebe2d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -572,6 +572,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
target_compile_options(veyra_popup_selector_tests PRIVATE /utf-8)
target_compile_definitions(veyra_popup_selector_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN UNICODE _UNICODE)
target_link_libraries(veyra_popup_selector_tests PRIVATE veyra_base comctl32)
+ add_executable(veyra_hdr_color_tests tests/integration/HdrColorTests.cpp)
+ target_compile_features(veyra_hdr_color_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_hdr_color_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_hdr_color_tests PRIVATE veyra_engine)
add_executable(veyra WIN32 apps/veyra/main.cpp apps/veyra/ui/AppShell.cpp apps/veyra/ui/CapturePanel.cpp apps/veyra/ui/SubtitleOverlay.cpp apps/veyra/SettingsWindow.cpp apps/veyra/TelemetryWindow.cpp)
if(VEYRA_ENABLE_REMOTEPLAY)
find_package(SDL3 3.4.14 EXACT CONFIG REQUIRED)
@@ -580,6 +584,10 @@ if(VEYRA_FFMPEG_ROOT AND EXISTS "${VEYRA_FFMPEG_ROOT}/include/libavformat/avform
add_executable(veyra_remoteplay_boundary_tests tests/remoteplay/ProductBoundaryTests.cpp src/remoteplay/ControllerInput.cpp)
target_compile_features(veyra_remoteplay_boundary_tests PRIVATE cxx_std_20)
target_link_libraries(veyra_remoteplay_boundary_tests PRIVATE veyra_sources SDL3::SDL3)
+ add_executable(veyra_remoteplay_profile_tests tests/remoteplay/ProfileStoreTests.cpp)
+ target_compile_features(veyra_remoteplay_profile_tests PRIVATE cxx_std_20)
+ target_compile_definitions(veyra_remoteplay_profile_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)
+ target_link_libraries(veyra_remoteplay_profile_tests PRIVATE veyra_remoteplay_chiaki)
endif()
target_compile_features(veyra PRIVATE cxx_std_20)
target_compile_options(veyra PRIVATE /utf-8)
diff --git a/README.md b/README.md
index 9c5ba57d..8ce08e76 100644
--- a/README.md
+++ b/README.md
@@ -32,7 +32,7 @@ Windows 视频播放器与采集卡增强工具。支持视频、图片和采集
### 开发分支:PS5 串流
-开发分支已接入 PS5 局域网串流、配对、加密保存与手柄输入,基础连接已通过用户实测。本次增加软硬解选择、串流状态和播放调度修复,新改动待实机验收。**现有 0.0.4 Release 不包含这些功能。** [本机测试步骤与范围](docs/PS5_REPAIR_ACCEPTANCE_2026-09-12.md)。
+开发分支已接入 PS5 局域网串流、配对、加密保存与手柄输入,基础连接已通过用户实测。本次增加软硬解选择、串流状态和播放调度修复,新改动待实机验收。**现有 0.0.4 Release 不包含这些功能。** 开发版另加入固定用户目录的主机保留、PSN浏览器授权及实验H.265 HDR;HDR原生旁路与HDR转SDR后增强分别标注,实际PS5与登录待验收。见[施工与测试边界](docs/PS5_HDR_PSN_EXECUTION_2026-09-12.md)。 [本机测试步骤与范围](docs/PS5_REPAIR_ACCEPTANCE_2026-09-12.md)。
## 下载与运行
diff --git a/README_EN.md b/README_EN.md
index da84be1b..5f698bb9 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -32,7 +32,7 @@ Version 0.0.4 fixes audio/video drift caused by enhancement processing, audio in
### Development branch: PS5 Remote Play
-The development branch supports LAN PS5 streaming, pairing, encrypted profiles and gamepad input; basic connectivity has passed user testing. Recent changes add software/hardware decoder selection, streaming telemetry and playback scheduling fixes, with console acceptance pending for these changes. **These features are not included in the published 0.0.4 Release.** See the [local test guide and scope (Chinese)](docs/PS5_REPAIR_ACCEPTANCE_2026-09-12.md).
+The development branch supports LAN PS5 streaming, pairing, encrypted profiles and gamepad input; basic connectivity has passed user testing. Recent changes add software/hardware decoder selection, streaming telemetry and playback scheduling fixes, with console acceptance pending for these changes. **These features are not included in the published 0.0.4 Release.** The development build also adds persistent per-user console profiles, browser-based PSN authorization, and experimental H.265 HDR. Native HDR passthrough and HDR-to-SDR enhancement are labeled separately; real PS5 and Sony login acceptance remains pending. See the [implementation record](docs/PS5_HDR_PSN_EXECUTION_2026-09-12.md). See the [local test guide and scope (Chinese)](docs/PS5_REPAIR_ACCEPTANCE_2026-09-12.md).
## Download and Run
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 3c300770..d73759e2 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -59,3 +59,7 @@ This local integration has not been pushed or released.
# Remote Play controller additions (2026-09-12)
Veyra calls the pinned Chiaki orientation tracker API (AGPL-3.0-only with OpenSSL exception). DualSense SDL report offsets and 3 kHz stereo to four-channel haptic routing were checked against chiaki-ng gui/src/controllermanager.cpp and streamsession.cpp. Existing Chiaki and SDL license notices apply. No third-party binary was added.
+
+### PSN browser authorization adapter (2026-09-12)
+
+`src/remoteplay/PsnAuth.cpp` adapts the OAuth request contract and public client identifiers from chiaki-ng, commit `0e16950165f06e5c3291537c2eeba6e852be7120`, `gui/src/psnaccountid.cpp`, `gui/include/psnaccountid.h`, and `gui/src/psntoken.cpp`. Upstream credits the Account ID script to grill2010. License: AGPL-3.0-only with the upstream OpenSSL exception. The Windows HTTP, protected storage and UI integration are Veyra code. This is an unofficial client, not Sony endorsement. json-c remains an existing Chiaki dependency; its license/notice must remain in binary distributions.
diff --git a/apps/veyra/ui/RemotePlayPanel.cpp b/apps/veyra/ui/RemotePlayPanel.cpp
index 85d85bd8..5a899b12 100644
--- a/apps/veyra/ui/RemotePlayPanel.cpp
+++ b/apps/veyra/ui/RemotePlayPanel.cpp
@@ -1,51 +1,61 @@
#include "RemotePlayPanel.h"
#include "Theme.h"
#include "SettingHelp.h"
+#include "veyra/remoteplay/PsnAuth.h"
+#include <shellapi.h>
#include "veyra/Log.h"
#include "veyra/remoteplay/ProfileStore.h"
#include "veyra/remoteplay/Discovery.h"
#include "veyra/RuntimePaths.h"
#include <atomic>
+#include <cctype>
#include <format>
#include <mutex>
#include <thread>
namespace veyra::ui {
namespace {
HWND window=nullptr;HFONT font=nullptr;
-enum {Host=1,Account,PairPin,Quality,CodecChoice,Pair,Connect,Cancel,Scan,Wake,LoginPin,SendPin,StatusText,Help,Bitrate,Forget,ViewOnly,Calibrate,DecodeChoice};
+enum {Host=1,Account,PairPin,Quality,CodecChoice,Pair,Connect,Cancel,Scan,Wake,LoginPin,SendPin,StatusText,Help,Bitrate,Forget,ViewOnly,Calibrate,DecodeChoice,LoginPsn,CompletePsn,ForgetPsn};
+uint64_t psnLoginStarted=0,psnRefreshAfter=0;
std::function<bool()> calibrate;
std::function<void(source::RemotePlayConnectDesc)> connect;
std::function<void(std::string)> login;
std::function<RemotePlayPanelStatus()> connectionStatus;std::function<void()> disconnect;bool watching=false;
std::jthread worker;std::atomic<bool> done=false;bool busy=false,closing=false;
-struct Outcome {std::wstring message;std::vector<remoteplay::DiscoveredConsole> hosts;std::filesystem::path savedPath;};
+struct Outcome {std::wstring message;std::vector<remoteplay::DiscoveredConsole> hosts;std::filesystem::path savedPath;std::optional<remoteplay::AccountId> account;};
std::mutex mutex;Outcome outcome;
struct SavedProfile {std::string host;std::filesystem::path path;};
+unsigned profileReadFailures=0;
std::vector<SavedProfile> profiles;std::filesystem::path currentProfile;
constexpr uint32_t bitrates[]={5000,10000,15000,20000,30000,50000,80000,100000};
auto profilePath(){return currentProfile;}
-std::filesystem::path pathForHost(std::string_view host){
- for(const auto& profile:profiles)if(profile.host==host)return profile.path;
+std::filesystem::path pathForHost(std::string_view host,const remoteplay::AccountId& account){
+ for(const auto& profile:profiles)if(profile.host==host){auto saved=remoteplay::loadProfile(profile.path);if(saved&&saved->credentials.accountId==account)return profile.path;}
GUID guid{};if(FAILED(CoCreateGuid(&guid)))return {};
std::string id;const auto* bytes=reinterpret_cast<const unsigned char*>(&guid);
for(size_t i=0;i<sizeof(guid);++i)id+=std::format("{:02x}",bytes[i]);
- return runtime::localDataDirectory()/"remoteplay"/(id+".dat");
+ return remoteplay::profileDirectory()/(id+".dat");
}
void loadSelection(){
if(auto saved=remoteplay::loadProfile(currentProfile)){
SetDlgItemTextW(window,Host,std::wstring(saved->host.begin(),saved->host.end()).c_str());
+ CheckDlgButton(window,ViewOnly,saved->viewOnly?BST_CHECKED:BST_UNCHECKED);
auto id=remoteplay::accountIdToBase64(saved->credentials.accountId);SetDlgItemTextW(window,Account,std::wstring(id.begin(),id.end()).c_str());
SendDlgItemMessageW(window,Quality,CB_SETCURSEL,(saved->video.height==1080?2:0)+(saved->video.fps==60?1:0),0);
- SendDlgItemMessageW(window,CodecChoice,CB_SETCURSEL,saved->video.codec==remoteplay::Codec::H265?1:0,0);
+ SendDlgItemMessageW(window,CodecChoice,CB_SETCURSEL,int(saved->video.codec),0);
const auto found=std::find(std::begin(bitrates),std::end(bitrates),saved->video.bitrateKbps);
SendDlgItemMessageW(window,Bitrate,CB_SETCURSEL,found==std::end(bitrates)?2:found-std::begin(bitrates),0);
}
}
void refreshProfiles(){
- profiles.clear();SendDlgItemMessageW(window,Host,CB_RESETCONTENT,0,0);
- auto add=[](const std::filesystem::path& path){if(auto saved=remoteplay::loadProfile(path))profiles.push_back({saved->host,path});};
- add(runtime::localDataDirectory()/"remoteplay-profile.dat");
- std::error_code ec;const auto directory=runtime::localDataDirectory()/"remoteplay";
+ if(currentProfile.empty()){
+ wchar_t last[80]{};GetPrivateProfileStringW(L"RemotePlay",L"LastProfile",L"",last,80,(remoteplay::profileDirectory()/L"settings.ini").c_str());
+ std::wstring name=last;if(!name.empty()&&name.find_first_of(L"/\\:")==name.npos)currentProfile=remoteplay::profileDirectory()/name;
+ }
+ profileReadFailures=0;profiles.clear();SendDlgItemMessageW(window,Host,CB_RESETCONTENT,0,0);
+ auto add=[](const std::filesystem::path& path){remoteplay::ProfileLoadError error;auto saved=remoteplay::loadProfile(path,&error);if(saved)profiles.push_back({saved->host,path});else if(error!=remoteplay::ProfileLoadError::Missing){++profileReadFailures;veyra::log::warn("remoteplay-profile",std::format("Cannot load saved profile: category={} (no credentials logged)",int(error)));}};
+ add(remoteplay::profileDirectory()/"remoteplay-profile.dat");
+ std::error_code ec;const auto directory=remoteplay::profileDirectory();
size_t scanned=0;
for(std::filesystem::directory_iterator it(directory,ec),end;!ec&&it!=end&&profiles.size()<64&&scanned<256;it.increment(ec),++scanned){
const auto id=it->path().stem().wstring();
@@ -61,9 +71,9 @@ std::string ascii(int id){auto s=text(id);if(std::any_of(s.begin(),s.end(),[](wc
remoteplay::VideoProfile video(){
remoteplay::VideoProfile p;const auto q=SendDlgItemMessageW(window,Quality,CB_GETCURSEL,0,0);
p.width=q<2?1280:1920;p.height=q<2?720:1080;p.fps=(q==0||q==2)?30:60;
- p.codec=SendDlgItemMessageW(window,CodecChoice,CB_GETCURSEL,0,0)==1?remoteplay::Codec::H265:remoteplay::Codec::H264;const auto rate=SendDlgItemMessageW(window,Bitrate,CB_GETCURSEL,0,0);p.bitrateKbps=bitrates[std::clamp<int>(int(rate),0,7)];return p;
+ p.codec=static_cast<remoteplay::Codec>(std::clamp<int>(int(SendDlgItemMessageW(window,CodecChoice,CB_GETCURSEL,0,0)),0,2));const auto rate=SendDlgItemMessageW(window,Bitrate,CB_GETCURSEL,0,0);p.bitrateKbps=bitrates[std::clamp<int>(int(rate),0,7)];return p;
}
-void buttons(){for(int id:{Pair,Connect,Scan,Wake,Host,Account,PairPin,Quality,CodecChoice,Bitrate,Forget})EnableWindow(GetDlgItem(window,id),!busy);EnableWindow(GetDlgItem(window,Cancel),busy);}
+void buttons(){for(int id:{Pair,Connect,Scan,Wake,Host,Account,PairPin,Quality,CodecChoice,Bitrate,Forget,LoginPsn,CompletePsn,ForgetPsn})EnableWindow(GetDlgItem(window,id),!busy);EnableWindow(GetDlgItem(window,Cancel),busy);}
template<class Work> void launch(Work work){
if(busy)return;if(worker.joinable())worker.join();busy=true;done=false;buttons();SetDlgItemTextW(window,StatusText,L"正在处理…可随时取消");
worker=std::jthread([work=std::move(work)](std::stop_token stop)mutable{
@@ -74,6 +84,7 @@ template<class Work> void launch(Work work){
}
void arrange(){
auto move=[](int id,int x,int y,int w,int h){MoveWindow(GetDlgItem(window,id),dip(window,x),dip(window,y),dip(window,w),dip(window,h),TRUE);};
+ move(LoginPsn,20,576,145,30);move(CompletePsn,175,576,200,30);move(ForgetPsn,385,576,167,30);
move(Host,160,18,270,180);move(Scan,440,18,112,28);
move(Account,160,62,392,28);move(PairPin,160,106,180,28);move(Pair,352,106,200,30);
move(Quality,160,150,220,150);move(CodecChoice,392,150,160,150);
@@ -81,7 +92,7 @@ void arrange(){
move(LoginPin,160,250,180,28);move(SendPin,352,250,200,30);
move(Bitrate,160,295,180,180);move(Forget,352,295,80,32);move(Cancel,440,295,112,32);move(StatusText,20,341,530,64);move(ViewOnly,20,408,400,28);move(Calibrate,432,408,120,28);move(DecodeChoice,160,442,392,150);move(Help,20,485,530,86);
}
-LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp){switch(msg){
+LRESULT CALLBACK proc(HWND h,UINT msg,WPARAM wp,LPARAM lp)try{switch(msg){
case WM_CREATE:{window=h;closing=false;font=makeFont(h);titleTheme(h);
auto add=[&](const wchar_t* cls,const wchar_t* label,int id,DWORD style,int x=0,int y=0,int w=1,int height=1){
auto c=CreateWindowExW(0,cls,label,WS_CHILD|WS_VISIBLE|style,dip(h,x),dip(h,y),dip(h,w),dip(h,height),h,HMENU(INT_PTR(id)),GetModuleHandleW(nullptr),nullptr);
@@ -92,26 +103,36 @@ case WM_CREATE:{window=h;closing=false;font=makeFont(h);titleTheme(h);
add(L"STATIC",L"解码(重连生效)",106,0,20,445,138,25);
add(L"COMBOBOX",L"",DecodeChoice,CBS_DROPDOWNLIST|WS_TABSTOP);
for(auto label:{L"自动 · 优先硬解",L"CPU 软件解码",L"D3D12VA 硬件解码"})SendDlgItemMessageW(h,DecodeChoice,CB_ADDSTRING,0,LPARAM(label));
- SendDlgItemMessageW(h,DecodeChoice,CB_SETCURSEL,std::min(2u,GetPrivateProfileIntW(L"RemotePlay",L"DecodeMode",0,(runtime::localDataDirectory()/"veyra.ini").c_str())),0);
+ SendDlgItemMessageW(h,DecodeChoice,CB_SETCURSEL,std::min(2u,GetPrivateProfileIntW(L"RemotePlay",L"DecodeMode",0,(remoteplay::profileDirectory()/L"settings.ini").c_str())),0);
add(L"STATIC",L"PS5 地址",100,0,20,21,130,25);add(L"STATIC",L"PSN Account ID",101,0,20,65,130,25);
add(L"STATIC",L"8 位配对码",102,0,20,109,130,25);add(L"STATIC",L"串流格式",103,0,20,153,130,25);add(L"STATIC",L"登录 PIN(可选)",104,0,20,253,135,25);
add(L"STATIC",L"码率",105,0,20,298,130,25);add(L"COMBOBOX",L"",Host,CBS_DROPDOWN|CBS_AUTOHSCROLL|WS_TABSTOP);SendDlgItemMessageW(h,Host,CB_LIMITTEXT,253,0);
for(int id:{Account,PairPin,LoginPin}){add(L"EDIT",L"",id,WS_TABSTOP|ES_AUTOHSCROLL|((id==PairPin||id==LoginPin)?ES_PASSWORD:0));SendDlgItemMessageW(h,id,EM_SETLIMITTEXT,id==Host?253:id==Account?24:8,0);}
add(L"COMBOBOX",L"",Quality,CBS_DROPDOWNLIST|WS_TABSTOP);for(auto label:{L"720p · 30 fps",L"720p · 60 fps",L"1080p · 30 fps",L"1080p · 60 fps"})SendDlgItemMessageW(h,Quality,CB_ADDSTRING,0,LPARAM(label));SendDlgItemMessageW(h,Quality,CB_SETCURSEL,3,0);
- add(L"COMBOBOX",L"",CodecChoice,CBS_DROPDOWNLIST|WS_TABSTOP);for(auto label:{L"H.264 · SDR",L"H.265 · SDR"})SendDlgItemMessageW(h,CodecChoice,CB_ADDSTRING,0,LPARAM(label));SendDlgItemMessageW(h,CodecChoice,CB_SETCURSEL,0,0);
+ add(L"COMBOBOX",L"",CodecChoice,CBS_DROPDOWNLIST|WS_TABSTOP);for(auto label:{L"H.264 · SDR",L"H.265 · SDR",L"H.265 · HDR(实验)"})SendDlgItemMessageW(h,CodecChoice,CB_ADDSTRING,0,LPARAM(label));SendDlgItemMessageW(h,CodecChoice,CB_SETCURSEL,0,0);
add(L"COMBOBOX",L"",Bitrate,CBS_DROPDOWNLIST|WS_TABSTOP);for(auto rate:bitrates){auto label=std::format(L"{} Mbps",rate/1000);SendDlgItemMessageW(h,Bitrate,CB_ADDSTRING,0,LPARAM(label.c_str()));}SendDlgItemMessageW(h,Bitrate,CB_SETCURSEL,2,0);
+ add(L"BUTTON",L"登录 PSN",LoginPsn,BS_PUSHBUTTON|WS_TABSTOP);
+ add(L"BUTTON",L"从剪贴板提交登录结果",CompletePsn,BS_PUSHBUTTON|WS_TABSTOP);
+ add(L"BUTTON",L"退出 PSN",ForgetPsn,BS_PUSHBUTTON|WS_TABSTOP);
add(L"BUTTON",L"删除配对",Forget,BS_PUSHBUTTON|WS_TABSTOP);
for(auto [id,label]:{std::pair{Pair,L"配对并保存"},{Connect,L"连接并观看"},{Cancel,L"取消操作"},{Scan,L"查找主机"},{Wake,L"唤醒已配对 PS5"},{SendPin,L"提交登录 PIN"}})add(L"BUTTON",label,id,BS_PUSHBUTTON|WS_TABSTOP);
marked(GetDlgItem(h,Connect));
add(L"STATIC",L"首次使用先配对,之后直接连接。",StatusText,0);
add(L"STATIC",L"PS5:设置 → 系统 → 远程游玩 → 启用远程游玩 → 关联设备。\nAccount ID 填账号数字 ID 或对应 8 字节 Base64,不是昵称或密码。\n电脑与 PS5 先连接同一局域网。配对信息仅在本机加密保存。\n登录 PIN 仅在 PS5 提示时填写;取消操作不会关闭当前视频。",Help,0);
+ const auto migration=remoteplay::migrateProfiles(runtime::localDataDirectory());
refreshProfiles();
+ if(profileReadFailures)SetDlgItemTextW(h,StatusText,L"有配对存档无法读取或解密,详情见日志。请使用原Windows账户;不要删除原件。");
+ else if(migration.failed)SetDlgItemTextW(h,StatusText,L"部分旧配对无法迁移;原件已保留,请检查用户权限。不要重复配对覆盖原件。");
+ else if(!currentProfile.empty())SetDlgItemTextW(h,StatusText,L"已加载保存的主机,直接点“连接并观看”,无需重新填写8位配对码。");
installDialogHelp(h,{
+ {LoginPsn,L"打开Sony登录页。登录后复制浏览器回调地址,再点提交登录结果;软件不接触密码。"},
+ {CompletePsn,L"读取你复制的Sony登录回调URL,获取并加密保存授权和Account ID。不会读取其他剪贴板格式。"},
+ {ForgetPsn,L"只删除PSN授权,已有局域网主机配对仍然保留。"},
{Host,L"PS5的局域网IP或已保存主机。找不到时可手填,别把PSN昵称填这里。"},
{Account,L"配对用的Base64 PSN Account ID,不是在线昵称。名字相同不代表身份证号码相同。"},
{PairPin,L"PS5远程游玩页面显示的8位配对码,有时效。过期了再领一张票。"},
{Quality,L"选择串流分辨率和帧率。请求的是PS5输出,不是增强后目标。"},
- {CodecChoice,L"H.264兼容性好,H.265通常更省码率。两边都得会说同一种视频语言。"},
+ {CodecChoice,L"H.264兼容性好,H.265通常更省码率。HDR需要PS5实际输出HDR;关闭增强且Windows HDR开启时原生显示,开启增强则先转SDR,别把两种效果认错。"},
{Pair,L"用账户ID和8位码注册主机,凭据在本机加密保存。"},
{Connect,L"使用保存的配对信息连接PS5,把画面送进当前增强链路。"},
{Cancel,L"取消当前操作或断开串流,让连接安静收工。"},
@@ -124,21 +145,62 @@ case WM_CREATE:{window=h;closing=false;font=makeFont(h);titleTheme(h);
{ViewOnly,L"只观看,不向PS5转发电脑手柄输入。不能保证同账号手柄仍能直连主机,这是PS5会话规则。"},
{Calibrate,L"手柄放稳后校准陀螺仪,让镜头别自己散步。"},
{DecodeChoice,L"自动优先硬解,失败回软件;强制硬解失败会报错。软件解码主要用CPU,硬解用视频解码单元。重连生效。"}});
- buttons();arrange();SetTimer(h,1,100,nullptr);return 0;}
-case WM_TIMER:if(busy&&done){if(worker.joinable())worker.join();busy=false;Outcome result;{std::lock_guard lock(mutex);result=std::move(outcome);}if(!result.savedPath.empty()){currentProfile=result.savedPath;refreshProfiles();}buttons();SetDlgItemTextW(h,StatusText,result.message.c_str());if(!result.hosts.empty())SetDlgItemTextW(h,Host,std::wstring(result.hosts[0].host.begin(),result.hosts[0].host.end()).c_str());if(closing)DestroyWindow(h);}
+ buttons();arrange();SetTimer(h,1,100,nullptr);
+ if(auto auth=remoteplay::loadPsnAuthorization()){
+ psnRefreshAfter=GetTickCount64()+300000;
+ const bool fillAccount=currentProfile.empty();
+ launch([fillAccount](std::stop_token stop){auto result=remoteplay::refreshPsn(stop);Outcome out;
+ out.message=result.ok?L"PSN授权已就绪;已配对主机直接连接,无需8位配对码。":std::format(L"PSN授权刷新失败({});局域网配对仍可连接,必要时重新登录PSN。",result.error);
+ if(fillAccount)out.account=result.account;
+ return out;});
+ }
+ return 0;}
+case WM_TIMER:if(busy&&done){if(worker.joinable())worker.join();busy=false;Outcome result;{std::lock_guard lock(mutex);result=std::move(outcome);}if(!result.savedPath.empty()){currentProfile=result.savedPath;WritePrivateProfileStringW(L"RemotePlay",L"LastProfile",currentProfile.filename().c_str(),(remoteplay::profileDirectory()/L"settings.ini").c_str());refreshProfiles();}buttons();SetDlgItemTextW(h,StatusText,result.message.c_str());if(result.account){auto id=remoteplay::accountIdToBase64(*result.account);SetDlgItemTextW(h,Account,std::wstring(id.begin(),id.end()).c_str());}if(!result.hosts.empty()){
+ auto selected=remoteplay::loadProfile(currentProfile);bool matched=false;
+ if(selected){for(auto& found:result.hosts){
+ std::transform(found.consoleId.begin(),found.consoleId.end(),found.consoleId.begin(),[](unsigned char c){return char(std::tolower(c));});
+ const bool sameId=!selected->consoleId.empty()&&selected->consoleId==found.consoleId;
+ const bool legacyMatch=selected->consoleId.empty()&&selected->host==found.host;
+ if(sameId||legacyMatch){
+ selected->host=found.host;
+ if(found.consoleId.size()==12)selected->consoleId=found.consoleId;
+ if(remoteplay::saveProfile(currentProfile,*selected)){refreshProfiles();matched=true;}
+ else SetDlgItemTextW(h,StatusText,L"找到主机,但保存新地址失败;原配对仍保留。");
+ break;
+ }
+ }}
+ if(!selected&&result.hosts.size()==1)SetDlgItemTextW(h,Host,std::wstring(result.hosts[0].host.begin(),result.hosts[0].host.end()).c_str());
+ else if(selected&&!matched)SetDlgItemTextW(h,StatusText,L"发现主机,但无法确认是已配对的这一台。保留原地址,可核对后手动修改。");
+ else if(!selected&&result.hosts.size()>1)SetDlgItemTextW(h,StatusText,L"发现多台PS5,请填写要配对的主机IP,避免选错主机。");
+ }if(closing)DestroyWindow(h);}
+ if(window&&!busy&&GetTickCount64()>psnRefreshAfter){
+ psnRefreshAfter=GetTickCount64()+300000;
+ if(remoteplay::loadPsnAuthorization())launch([](std::stop_token stop){auto result=remoteplay::refreshPsn(stop);Outcome out;out.message=result.ok?L"PSN授权已就绪;已配对主机直接连接。":std::format(L"PSN刷新失败({});局域网配对不受影响。",result.error);return out;});
+ }
if(window&&watching&&!busy){auto state=connectionStatus();SetDlgItemTextW(h,StatusText,state.message.c_str());SetDlgItemTextW(h,Cancel,state.active?L"断开连接":L"取消操作");EnableWindow(GetDlgItem(h,Cancel),state.active);if(!state.active)watching=false;}return 0;
case WM_COMMAND:switch(LOWORD(wp)){
+ case LoginPsn:{if(busy)break;auto url=remoteplay::psnLoginUrl();if(INT_PTR(ShellExecuteW(h,L"open",url.c_str(),nullptr,nullptr,SW_SHOWNORMAL))>32){psnLoginStarted=GetTickCount64();SetDlgItemTextW(h,StatusText,L"在Sony网页完成登录,复制最终回调URL,再点“从剪贴板提交登录结果”。");}else SetDlgItemTextW(h,StatusText,L"无法打开浏览器,请检查默认浏览器设置。");break;}
+ case CompletePsn:{
+ if(busy)break;
+ if(!psnLoginStarted||GetTickCount64()-psnLoginStarted>600000){SetDlgItemTextW(h,StatusText,L"请先点登录PSN,完成网页授权后再提交。");break;}
+ std::wstring callback;
+ if(OpenClipboard(h)){auto data=GetClipboardData(CF_UNICODETEXT);if(data){auto size=GlobalSize(data);if(size&&size<=16386){auto chars=static_cast<const wchar_t*>(GlobalLock(data));if(chars){size_t count=0;while(count<size/sizeof(wchar_t)&&chars[count])++count;if(count<size/sizeof(wchar_t))callback.assign(chars,count);GlobalUnlock(data);}}}CloseClipboard();}
+ if(!remoteplay::validPsnCallback(callback)){SecureZeroMemory(callback.data(),callback.size()*sizeof(wchar_t));SetDlgItemTextW(h,StatusText,L"剪贴板不是有效的Sony授权回调地址。请复制登录完成后的完整URL。");break;}
+ psnLoginStarted=0;
+ launch([callback=std::move(callback)](std::stop_token stop)mutable{auto result=remoteplay::authorizePsn(std::move(callback),stop);Outcome out;out.account=result.account;out.message=result.ok?L"PSN登录已保存,Account ID已填入。首次仍需配对;已配对主机直接连接。":std::format(L"PSN授权失败({});原有配对不受影响,可重新登录。",result.error);return out;});break;
+ }
+ case ForgetPsn:if(!busy){SetDlgItemTextW(h,StatusText,remoteplay::forgetPsnAuthorization()?L"PSN授权已删除,局域网配对保留。":L"删除授权失败,请检查目录权限。");}break;
case Calibrate:if(calibrate&&calibrate())MessageBoxW(h,L"将手柄平放并保持静止,关闭此提示后返回播放器。\n采集 120 个稳定样本完成校准;10 秒内不稳定则保留原校准。",L"陀螺仪校准",MB_OK);else MessageBoxW(h,L"请先连接串流及带陀螺仪的电脑手柄。仅观看模式不使用电脑手柄。",L"无法校准",MB_OK);break;
- case Host:if(HIWORD(wp)==CBN_SELCHANGE&&!busy){const auto index=SendDlgItemMessageW(h,Host,CB_GETCURSEL,0,0);if(index>=0&&size_t(index)<profiles.size()){currentProfile=profiles[size_t(index)].path;loadSelection();}}break;
+ case Host:if(HIWORD(wp)==CBN_SELCHANGE&&!busy){const auto index=SendDlgItemMessageW(h,Host,CB_GETCURSEL,0,0);if(index>=0&&size_t(index)<profiles.size()){currentProfile=profiles[size_t(index)].path;WritePrivateProfileStringW(L"RemotePlay",L"LastProfile",currentProfile.filename().c_str(),(remoteplay::profileDirectory()/L"settings.ini").c_str());loadSelection();}}break;
case Forget:if(!busy&&!currentProfile.empty()){std::error_code ec;const bool removed=std::filesystem::remove(currentProfile,ec);if(removed){currentProfile.clear();refreshProfiles();if(profiles.empty()){SetDlgItemTextW(h,Account,L"");SetDlgItemTextW(h,Host,L"");}SetDlgItemTextW(h,StatusText,L"配对已删除。现有串流会保留;下次连接需选择其他主机或重新配对。");}else SetDlgItemTextW(h,StatusText,L"删除失败,请检查文件权限。");}break;
case Pair:{if(busy)break;auto host=ascii(Host),id=ascii(Account),pin=ascii(PairPin);auto account=remoteplay::accountIdFromBase64(id);if(!account)account=remoteplay::accountIdFromDecimal(id);
if(!remoteplay::validHost(host)||!account||!remoteplay::parsePairingPin(pin)){SetDlgItemTextW(h,StatusText,L"请填写有效主机地址、Account ID 和 8 位配对码。");break;}
- auto targetPath=pathForHost(host);if(targetPath.empty()){SetDlgItemTextW(h,StatusText,L"无法分配配对存档,请重试。");break;}auto format=video();SetDlgItemTextW(h,PairPin,L"");
+ auto targetPath=pathForHost(host,*account);if(targetPath.empty()){SetDlgItemTextW(h,StatusText,L"无法分配配对存档,请重试。");break;}auto format=video();SetDlgItemTextW(h,PairPin,L"");
launch([host=std::move(host),account=*account,pin=std::move(pin),format,targetPath](std::stop_token stop)mutable{
auto result=remoteplay::pairLocalPs5(host,account,pin,stop);SecureZeroMemory(pin.data(),pin.size());Outcome out;
- if(result.result.ok&&!stop.stop_requested()){remoteplay::NativeConnectRequest request;request.host=host;request.video=format;request.credentials=std::move(result.credentials);if(remoteplay::saveProfile(targetPath,request)){out.savedPath=targetPath;out.message=L"配对成功并已加密保存,可以连接。";}else out.message=L"配对成功,但保存失败。请检查目录权限后重试。";}
+ if(result.result.ok&&!stop.stop_requested()){remoteplay::NativeConnectRequest request;request.host=host;request.video=format;request.credentials=std::move(result.credentials);for(auto byte:result.mac)request.consoleId+=std::format("{:02x}",byte);if(request.consoleId=="000000000000")request.consoleId.clear();if(remoteplay::saveProfile(targetPath,request)){out.savedPath=targetPath;out.message=L"配对成功并已加密保存,可以连接。";}else out.message=L"配对成功,但保存失败。请检查目录权限后重试。";}
else out.message=result.canceled||stop.stop_requested()?L"已取消配对":std::format(L"配对失败({}),检查 PS5 配对码、Account ID 与网络。",result.result.code);return out;});break;}
- case Connect:{if(busy)break;auto saved=remoteplay::loadProfile(profilePath());auto host=ascii(Host);if(!saved||!remoteplay::validHost(host)){SetDlgItemTextW(h,StatusText,L"请先完成配对,并填写有效主机地址。");break;}saved->host=host;saved->video=video();if(!remoteplay::saveProfile(currentProfile,*saved)){SetDlgItemTextW(h,StatusText,L"保存连接设置失败,请检查目录权限。");break;}source::RemotePlayConnectDesc desc;saved->viewOnly=IsDlgButtonChecked(h,ViewOnly)==BST_CHECKED;desc.request=std::move(*saved);const auto decode=std::clamp<int>(int(SendDlgItemMessageW(h,DecodeChoice,CB_GETCURSEL,0,0)),0,2);desc.decodeMode=static_cast<source::RemotePlayConnectDesc::DecodeMode>(decode);WritePrivateProfileStringW(L"RemotePlay",L"DecodeMode",std::to_wstring(decode).c_str(),(runtime::localDataDirectory()/"veyra.ini").c_str());connect(std::move(desc));watching=true;EnableWindow(GetDlgItem(h,Cancel),TRUE);SetDlgItemTextW(h,StatusText,L"连接已开始。需要登录 PIN 时在下方提交。关闭面板不停止串流。");break;}
+ case Connect:{if(busy)break;auto saved=remoteplay::loadProfile(profilePath());auto host=ascii(Host);if(!saved||!remoteplay::validHost(host)){SetDlgItemTextW(h,StatusText,L"请先完成配对,并填写有效主机地址。");break;}saved->host=host;saved->video=video();saved->viewOnly=IsDlgButtonChecked(h,ViewOnly)==BST_CHECKED;if(!remoteplay::saveProfile(currentProfile,*saved)){SetDlgItemTextW(h,StatusText,L"保存连接设置失败,请检查目录权限。");break;}source::RemotePlayConnectDesc desc;saved->viewOnly=IsDlgButtonChecked(h,ViewOnly)==BST_CHECKED;desc.request=std::move(*saved);const auto decode=std::clamp<int>(int(SendDlgItemMessageW(h,DecodeChoice,CB_GETCURSEL,0,0)),0,2);desc.decodeMode=static_cast<source::RemotePlayConnectDesc::DecodeMode>(decode);WritePrivateProfileStringW(L"RemotePlay",L"DecodeMode",std::to_wstring(decode).c_str(),(remoteplay::profileDirectory()/L"settings.ini").c_str());connect(std::move(desc));watching=true;EnableWindow(GetDlgItem(h,Cancel),TRUE);SetDlgItemTextW(h,StatusText,L"连接已开始。需要登录 PIN 时在下方提交。关闭面板不停止串流。");break;}
case Cancel:if(busy&&worker.joinable())worker.request_stop();else if(watching)disconnect();break;
case Scan:launch([](std::stop_token stop){Outcome out;auto report=remoteplay::discoverLocalPs5(stop);for(const auto& line:report.diagnostics)veyra::log::info("remoteplay-discovery",line);out.hosts=std::move(report.hosts);out.message=stop.stop_requested()?L"已取消查找":out.hosts.empty()?(report.error?std::format(L"主机搜索发生错误({}),详情见日志;可手填 IP。",report.error):L"搜索完成,未收到 PS5 回应;可手填 IP,检查主机开机和局域网。"):L"已填入发现的 PS5 地址。多台主机可手工输入目标 IP。";return out;});break;
case Wake:{if(busy)break;auto saved=remoteplay::loadProfile(profilePath());if(!saved){SetDlgItemTextW(h,StatusText,L"需要先配对才能唤醒。");break;}saved->host=ascii(Host);launch([request=std::move(*saved)](std::stop_token stop){Outcome out;if(stop.stop_requested()){out.message=L"已取消唤醒";return out;}auto r=remoteplay::wakeLocalPs5(request);out.message=r.ok?L"已发送唤醒请求,等待 PS5 启动后点击连接。":std::format(L"唤醒请求失败({})",r.code);return out;});break;}
@@ -149,11 +211,12 @@ case WM_CLOSE:if(busy){closing=true;worker.request_stop();SetDlgItemTextW(h,Stat
case WM_DESTROY:if(worker.joinable()){worker.request_stop();worker.join();}KillTimer(h,1);DeleteObject(font);window=nullptr;busy=false;return 0;
case WM_SIZE:arrange();return 0;
}return DefWindowProcW(h,msg,wp,lp);}
+catch(...){veyra::log::error("remoteplay-ui","Operation failed; no credentials logged");if(msg==WM_CREATE)return -1;SetDlgItemTextW(h,StatusText,L"操作失败,请检查用户目录权限;原有配对文件不会自动删除。");return 0;}
}
void showRemotePlayPanel(HWND parent,std::function<void(source::RemotePlayConnectDesc)> start,std::function<void(std::string)> pin,std::function<RemotePlayPanelStatus()> status,std::function<void()> stop,std::function<bool()> calibration){
calibrate=std::move(calibration);
connect=std::move(start);login=std::move(pin);connectionStatus=std::move(status);disconnect=std::move(stop);if(window){SetForegroundWindow(window);return;}
WNDCLASSW wc{};wc.lpfnWndProc=proc;wc.hInstance=GetModuleHandleW(nullptr);wc.lpszClassName=L"VeyraRemotePlaySetup";wc.hbrBackground=panelBrush();wc.hCursor=LoadCursorW(nullptr,IDC_ARROW);RegisterClassW(&wc);
- CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"PS5 · Remote Play",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,590),dip(parent,625),parent,nullptr,wc.hInstance,nullptr);
+ CreateWindowExW(WS_EX_TOOLWINDOW,wc.lpszClassName,L"PS5 · Remote Play",WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,dip(parent,590),dip(parent,665),parent,nullptr,wc.hInstance,nullptr);
}
}
diff --git a/cmake/VeyraRemotePlay.cmake b/cmake/VeyraRemotePlay.cmake
index 8c01084b..bc8d2bee 100644
--- a/cmake/VeyraRemotePlay.cmake
+++ b/cmake/VeyraRemotePlay.cmake
@@ -59,7 +59,10 @@ add_library(veyra_remoteplay_chiaki STATIC
"${VEYRA_ROOT}/src/remoteplay/ChiakiBackend.cpp"
"${VEYRA_ROOT}/src/remoteplay/ChiakiRegistration.cpp"
"${VEYRA_ROOT}/src/remoteplay/ProfileStore.cpp"
+ "${VEYRA_ROOT}/src/remoteplay/PsnAuth.cpp"
"${VEYRA_ROOT}/src/remoteplay/Discovery.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 crypt32 iphlpapi)
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(VEYRA_PSN_JSON REQUIRED IMPORTED_TARGET json-c)
+target_link_libraries(veyra_remoteplay_chiaki PUBLIC veyra_remoteplay_core PRIVATE chiaki-lib crypt32 iphlpapi shell32 ole32 winhttp PkgConfig::VEYRA_PSN_JSON)
diff --git a/docs/PS5_HDR_PSN_EXECUTION_2026-09-12.md b/docs/PS5_HDR_PSN_EXECUTION_2026-09-12.md
new file mode 100644
index 00000000..4af16a7e
--- /dev/null
+++ b/docs/PS5_HDR_PSN_EXECUTION_2026-09-12.md
@@ -0,0 +1,82 @@
+# PS5 HDR / PSN / 主机保留施工记录
+
+日期:2026-09-12。对应方案:PS5_HDR_PSN_HOST_PLAN_2026-09-12.md。
+开工源码基线5190487,方案提交37cfdf4,标签checkpoint/ps5-hdr-psn-preimplementation-2026-09-12。
+
+## 已实现
+
+### 主机存储
+
+- 独立固定目录 `%LOCALAPPDATA%/Veyra/remoteplay`;SDK、运行时仍使用原路径。
+- 从当前安装根runtime_local迁移旧单档及32位十六进制命名档案,DPAPI解密验证→原子保存→回读;保留原件,用迁移标记避免删除后复活。不能解密则保留并提示,禁止凭网络失败删除档案。
+- 档案v2兼容读取v1,新增主机ID和viewOnly。配对结果MAC作为稳定身份;发现按ID更新IP,旧档案只在原IP匹配时补身份;未知多机不取第一台替换已保存主机。
+- 同IP不同Account ID不覆盖同一档案。记录最后选中的档案;解码偏好转移至固定目录settings.ini。旧档案未保存的主机ID无法凭空恢复,旧IP已变时仍需一次人工核对。
+- 区分Missing/Read/Decrypt/Format加载错误;日志只输出错误类别。连接按钮不要求八位配对码。
+- 当前面板保留原配对表单及明确“直接连接”提示,尚未重做主机卡片式布局。登录PIN的记住功能尚未实现;不与8位关联设备码混淆。
+
+### PSN
+
+新增PsnAuth.h/.cpp、WinHTTP和现有json-c依赖、面板登录/提交回调/退出按钮。
+
+- 系统浏览器进入Sony页面;用户复制最终回调URL,点击“从剪贴板提交登录结果”。限定https回调host/path、单一code、长度/字符和十分钟操作窗口,不接受任意URL请求;不抓密码,不自动读取用户浏览器。
+- 授权码换token、Account ID查询、DPAPI加密保存、到期刷新;面板打开时和每五分钟检查,离线/撤销失败不影响局域网配对。
+- token文件原子替换,命名互斥量防并发授权写入;刷新复用已绑定Account ID,避免额外查询失败丢失旋转后的refresh token。日志只显示状态码,不记录URL、header、code/token。
+- 退出PSN不删除主机配对。上游归因已加入THIRD_PARTY_NOTICES.md。
+- **尚未真实登录Sony验证。首次主机配对仍用八位码;PSN自动免PIN注册尚未移植。** 固定上游自动注册依赖DUID/PSN会话与holepunch,本项目当前关闭RUDP。不能把账号ID自动填入宣传为免PIN注册或公网连接。
+
+### HDR
+
+- H265Hdr贯穿设置、持久化、AnnexB、Chiaki codec和RemotePlaySource;真实帧元数据覆盖假定值,8-bit降级不硬套PQ。
+- Main10软解(P010/YUV420P10LE)及D3D12VA P010 GPU纹理;16-bit plane/正确pitch。共享颜色元数据增加PQ/HLG识别及primaries解析;HLG和不支持的PQ色度明确拒绝。
+- YuvToLinearRgb shader正确处理P010高10位与64..940/512/896码值,BT2020 NCL矩阵、ST2084绝对亮度及BT2020→BT709转换。
+- 原生HDR:关闭NR/SR/FG且目标显示器Windows HDR启用时,FP16 scRGB(1=80nits)输出。补齐GraphicsPass可配置RTV格式、PresentSink颜色空间、浮点videoFrame及ScaleBlit去除unorm截断。参考画面不二次sRGB编码。每2秒检查输出HDR状态,通过原设置事务重建/reset。
+- 增强或SDR屏:先做HDR→SDR映射,使用固定1000nit参考峰值/203nit归一化的稳定亮度肩部及色域夹取;再走已有NR/SR/FG。该映射尚未用用户游戏校准,不宣称最佳算法,也不宣称原生HDR增强。状态与tooltip明确区分。
+- 原生HDR截图明确提示尚不支持,不生成伪8-bit HDR图片。公共文件/采集/导出仍保留HDR边界;不借本次扩大产品导出承诺。
+
+### 链路发现
+
+原software sws_scale目标planes/strides只分配2项。新10-bit Full范围测试触发访问异常;扩为完整4项后同组测试全部通过。这是本轮确实修复的缺陷,**不是用户“糊、灰”的已证实根因**。
+
+旧shader注释称P010归一化与8-bit相同,但实现只用/255;已改为明确位深码值。本轮没有用调饱和度/压黑来掩盖颜色错误。现有SessionInbox已经统计实际视频负载Mbps,面板已显示;继续复用,不新增第二套计数。
+
+## 实际验证
+
+每次命令均在300秒内。合成凭据测试不使用真实PSN账号。
+
+| 命令/证据 | 结果与边界 |
+| --- | --- |
+| cmd /c out/remoteplay/build-extra-delay.cmd | 多次对应构建;最终见logs/ps5-hdr-final5-build.log;构建目标veyra/contract/live/preset/quality/source |
+| cmd /c out/remoteplay/build-host-tests.cmd;veyra_remoteplay_profile_tests.exe | DPAPI存取、主机ID/观看模式、迁移/幂等/保留原件/删除不复活、损坏拒绝、callback白名单/重复code/非法字符拒绝。logs/ps5-host-final.log;不等于OAuth成功 |
+| veyra_hdr_color_tests.exe | 8组:P010/planar×Limited/Full×SDR/native。黑、100nit、1000nit ST2084参考;SDR归一化误差0.000357312,native最差0.046875 scRGB单位(含10-bit量化)。真实GPU处理、FP16/SDR交换链创建和Present通过;未测物理屏幕亮度 |
+| veyra_hdr_color_tests.exe logs/ps5-main10-fixture.mp4 | 真实HEVC Main10测试片(lavfi生成,不是PS5录制),软件/硬解各12帧,硬解实际AV_PIX_FMT_D3D12确认,各NR Evaluate 12次、非黑输出,logs/ps5-hdr-final-tests.log。验证的是HDR转SDR+NR |
+| veyra_yuy2_color_tests.exe --remote-yuv | 四组SDR全/有限、601/709回归,sourceError<=1 code value、displayError=0;logs/ps5-sdr-color-regression.log |
+| veyra_repair_contract_tests.exe | 90 checks 0 failures;logs/ps5-hdr-contract.log |
+| scripts/remoteplay/test-ui.ps1 -PlayerExe out/remoteplay/product-repair/veyra.exe -OutputDirectory logs/ps5-hdr-final-ui | PS5面板开关、非法配对、三个codec与三个decoder选项、PSN按钮、专业/日常及全屏切换通过;logs/ps5-hdr-final-ui.log。不点击真实授权、不连接PS5 |
+| scripts/gates/delivery.ps1 -Root . -BuildDirectory out/remoteplay/product-repair -PlayerExe out/remoteplay/product-repair/veyra.exe | 42.73秒软件gate通过,logs/delivery/2e696125b6d741af9bdbfaa71b8afe78/result.json;此gate早于最终RTV格式与错误提示收尾。后续相关HDR/Main10/Present与UI针对性测试单独记录,不能冒称gate哈希就是最终EXE |
+
+失败记录:PSN首次CMake imported target作用域不可见,改为父作用域独立pkg_check_modules,logs/ps5-psn-build.log→build2/build3。HDR测试首次缺ColorMetadata include导致编译失败,补后编译通过。第一次HDR运行在第二组Full范围访问异常(logs/ps5-hdr-color.log,exit -1073741819),扩目标平面数组后logs/ps5-hdr-color2.log通过;后续增加真实Present和Main10解码测试继续通过。没有删除失败日志来伪造首次成功。
+
+## 尚未验证/尚未落地,禁止省略
+
+1. 用户实际Sony登录、token刷新/撤销及真实Account ID;当前只验证代码构建和回调输入边界。
+2. 用户PS5 H265 HDR协商、游戏场景黑位/高光/色彩与软硬解对照;尚未证明“50Mbps糊灰”已消失。
+3. HDR物理显示器、Windows HDR切换/跨屏、HDR经WGC/OBS捕获;当前只验证交换链及GPU数值。
+4. HDR转SDR后的真实游戏画质矩阵仍待验收。合成Main10已验证RTX Video SR + NR + DLSS 2X标准/低延迟顺序;DLSS SR、XeSS及其他倍率未做本轮HDR专项。实验NR的原生HDR处理未接,明确使用SDR映射兼容路径。
+5. PSN免PIN自动注册、公网连接、记住主机登录PIN、主机卡片UI尚未实现。八位配对码保存问题通过本地主机档案解决,首次仍需要一次。
+6. 旧目录之外的配对文件不全盘搜索,跨Windows用户/电脑不能解密的档案不声称可迁移。
+
+## 用户验收步骤
+
+1. 使用桌面“Veyra PS5 测试版”。打开PS5面板直接“连接并观看”,不重新点配对;退出重开再连,检查是否无需8位码。
+2. 如能登录账号:点登录PSN,在Sony页自行完成,复制最终回调地址,点提交登录结果;看到Account ID与成功提示。不要把完整回调或token发到聊天/日志。
+3. PS5启用HDR后选“H.265 · HDR(实验)”,重连。先全关增强:HDR屏且Windows HDR开应显示原生HDR路径;普通屏应明确SDR映射。再开NR,确认状态切换为SDR映射后增强。
+4. 对照同一静止/运动场景及原H265 SDR,反馈发灰、细节和高光。保留请求/实际码率、codec和输出状态;不要只凭设置50Mbps判断真实带宽。
+
+下一步:完成以上真实验收及HDR组合矩阵;依赖实际PSN会话信息的自动注册独立实施。未发布、未push、未提交运行时或凭据。
+
+
+### 收尾追加证据
+
+`logs/ps5-hdr-combo.log`:同一Main10测试片,共6组(软件/硬解 × NR单独/RTX Video SR→NR→DLSS2X/NR→RTX Video SR→DLSS2X)。各12次NR Evaluate;组合各12次SR Evaluate、11张有效生成帧;所有返回0。4K输出,顺序2的NR源尺寸1080p。此为真实GPU执行与生成状态,不是PS5真实画质测评。最后测试文件为tests/integration/HdrColorTests.cpp,构建logs/ps5-hdr-combo-build.log。
+
+最终产品构建logs/ps5-hdr-final5-build.log。后续只修改测试/文档,不把临时夹具或运行时纳入Git。桌面快捷方式继续指向out/remoteplay/product-repair/veyra.exe,无需重装。
diff --git a/docs/PS5_HDR_PSN_HOST_PLAN_2026-09-12.md b/docs/PS5_HDR_PSN_HOST_PLAN_2026-09-12.md
index 9053a2b1..1c84e4c2 100644
--- a/docs/PS5_HDR_PSN_HOST_PLAN_2026-09-12.md
+++ b/docs/PS5_HDR_PSN_HOST_PLAN_2026-09-12.md
@@ -131,3 +131,7 @@ HDR屏:目标实现原生HDR旁路显示,优先评估RGBA16F scRGB交换链
- 本地chiaki固定提交0e16950165f06e5c3291537c2eeba6e852be7120:lib/include/chiaki/common.h、session.h,gui/src/psnaccountid.cpp、psntoken.cpp及自动注册调用。在线文档可能比固定源码更新,移植前逐项确认版本能力,不隐式升级依赖。
本轮核对:git status干净基线;源码rg/Get-Content检查及上述网页读取。未运行PS5连接、HDR、OAuth或构建测试;未修改产品代码。
+
+## 2026-09-12 实施状态
+
+方案已进入产品代码,详见 [施工记录](PS5_HDR_PSN_EXECUTION_2026-09-12.md)。原文“未实施”仅代表规划时点;完成、未验证和未落地以施工记录的分项为准,不能把所有计划项视为已完成。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 56e9923b..0acf835b 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1730,3 +1730,9 @@ apps/veyra/SettingsWindow.cpp调整布局;apps/veyra/ui/AppShell.cpp新增音
## 2026-09-12 PS5 HDR、PSN与主机保留规划
用户要求先写方案。新增 docs/PS5_HDR_PSN_HOST_PLAN_2026-09-12.md:画质分段定位、实测码率、稳定用户目录及旧配对迁移、PSN浏览器授权/刷新/条件性自动注册、Main10/HDR显示与SDR映射、增强兼容能力矩阵和验收节点。静态检查确认现有配对已DPAPI保存,目录随applicationRoot变化;RemotePlaySource与EnhanceGraph拒绝HDR,不能只增选项。重复配对根因与本次糊灰尚未实测确认;既有BT1886修复不能当作当前无问题的证明。本轮仅文档与代码/官方上游资料核对,无产品修改,无PS5/OAuth/HDR实测,无发布。
+
+## 2026-09-12 PS5 HDR/PSN/主机持久化实施
+
+开工标签checkpoint/ps5-hdr-psn-preimplementation-2026-09-12,方案提交37cfdf4。固定用户目录及DPAPI旧档迁移、稳定主机ID和观看模式、PSN浏览器回调授权/刷新/注销、H265 HDR与Main10输入、HDR原生旁路/SDR映射后增强已经进入产品代码。发现并修复sws_scale目标平面数组只有2项导致新10-bit Full测试访问异常;补齐P010码值、PQ/色域及FP16呈现。详细命令、失败与未完成边界见 docs/PS5_HDR_PSN_EXECUTION_2026-09-12.md。8组HDR GPU/呈现、Main10软硬解各12次真实NR、SDR颜色回归、90项contract及UI通过;42.73秒gate为收尾前二进制,最终按针对性测试报告。真实PS5画质、Sony登录未验收;免PIN自动注册、原生HDR增强不宣称完成。无发布/push/运行时入Git。
+
+收尾HDR组合回归:logs/ps5-hdr-combo.log,软/硬解 × NR单独/标准SR→NR→FG/低延迟NR→SR→FG,共6组通过;组合4K/2X各12次SR、12次NR、11有效生成帧。实际PS5画质与Sony授权仍待用户操作。
diff --git a/include/veyra/gfx/PresentSink.h b/include/veyra/gfx/PresentSink.h
index 1c6016fc..3a2ab171 100644
--- a/include/veyra/gfx/PresentSink.h
+++ b/include/veyra/gfx/PresentSink.h
@@ -24,6 +24,7 @@ using ComPtr = Microsoft::WRL::ComPtr<T>;
class PresentSink {
public:
+ static bool hdrDisplayActive(HWND);
PresentSink() = default;
~PresentSink();
@@ -36,6 +37,7 @@ public:
bool vsync = true;
bool xess = false;
bool captureCompatible = false;
+ bool hdr = false;
// Probe runs create their own window class name per process.
std::wstring title = L"Veyra";
HWND targetWindow = nullptr; // borrowed UI-owned child HWND; never destroyed by sink
diff --git a/include/veyra/pipeline/ColorMetadata.h b/include/veyra/pipeline/ColorMetadata.h
index 93da1c07..a6300c66 100644
--- a/include/veyra/pipeline/ColorMetadata.h
+++ b/include/veyra/pipeline/ColorMetadata.h
@@ -9,7 +9,7 @@ namespace veyra::pipeline {
inline ColorDescription resolveFrameColor(const AVFrame& frame,ColorDescription c={}){
switch(frame.format){
case AV_PIX_FMT_NV12:c.pixelFormat=SourcePixelFormat::NV12;break;
- case AV_PIX_FMT_P010:c.pixelFormat=SourcePixelFormat::P010;break;
+ case AV_PIX_FMT_YUV420P10LE:case AV_PIX_FMT_P010:c.pixelFormat=SourcePixelFormat::P010;break;
case AV_PIX_FMT_YUV420P:case AV_PIX_FMT_YUVJ420P:c.pixelFormat=SourcePixelFormat::Yuv420P;break;
case AV_PIX_FMT_YUYV422:c.pixelFormat=SourcePixelFormat::Yuy2;break;
case AV_PIX_FMT_BGRA:case AV_PIX_FMT_BGR0:c.pixelFormat=SourcePixelFormat::Bgra8;break;
@@ -29,7 +29,14 @@ inline ColorDescription resolveFrameColor(const AVFrame& frame,ColorDescription
case AVCOL_SPC_BT2020_CL:c.matrix=YuvMatrix::BT2020CL;c.matrixAssumed=false;break;
default:break;
}
+ switch(frame.color_primaries){
+ case AVCOL_PRI_BT709:c.primaries=ColorPrimaries::BT709;c.primariesAssumed=false;break;
+ case AVCOL_PRI_BT2020:c.primaries=ColorPrimaries::BT2020;c.primariesAssumed=false;break;
+ default:break;
+ }
switch(frame.color_trc){
+ case AVCOL_TRC_SMPTE2084:c.transfer=TransferFunction::PQ;c.transferAssumed=false;break;
+ case AVCOL_TRC_ARIB_STD_B67:c.transfer=TransferFunction::HLG;c.transferAssumed=false;break;
case AVCOL_TRC_BT709:case AVCOL_TRC_SMPTE170M:c.transfer=TransferFunction::BT709;c.transferAssumed=false;break;
case AVCOL_TRC_IEC61966_2_1:c.transfer=TransferFunction::SRGB;c.transferAssumed=false;break;
case AVCOL_TRC_LINEAR:c.transfer=TransferFunction::Linear;c.transferAssumed=false;break;
diff --git a/include/veyra/pipeline/EnhanceGraph.h b/include/veyra/pipeline/EnhanceGraph.h
index b6a32672..0828435a 100644
--- a/include/veyra/pipeline/EnhanceGraph.h
+++ b/include/veyra/pipeline/EnhanceGraph.h
@@ -68,6 +68,8 @@ struct EnhanceGraphDesc {
bool enableNvofStandalone = false; // run NVOF+densify per frame without FG (quality core)
bool noFeatures = false; // VEYRA_NO_FEATURES: NVOF/NGX objects skipped
bool noNgx = false; // VEYRA_NO_NGX: core/features skipped, NVOF only
+ bool hdrInput = false; // PS5 Main10 ingress; explicit SDR mapping unless hdrOutput.
+ bool hdrOutput = false; // Native scRGB passthrough, no SDR-only enhancement.
bool rgbInput = false; // allocate direct RGBA ingestion before NGX creation
bool yuy2Input = false; // packed Y0 U Y1 V -> linear FP16; never subsample to NV12
bool stillImage = false; // no temporal motion/FG history for a single image
@@ -182,6 +184,7 @@ public:
bool srEnabled() const { return srEnabled_; }
bool nrEnabled() const { return nrEnabled_; }
bool fgEnabled() const { return fgEnabled_; }
+ bool hdrOutput() const { return desc_.hdrOutput; }
bool xessEnabled() const { return desc_.enableFg && !desc_.noFeatures && !desc_.stillImage && desc_.frameGenerationBackend==engine::FrameGenerationBackend::XeSS; }
ID3D12Resource* presentMotion(uint32_t slot) const { return presentMotion_[slot%2].Get(); }
ID3D12Resource* presentDepth() const { return depthTex_.Get(); }
diff --git a/include/veyra/pipeline/FramePacket.h b/include/veyra/pipeline/FramePacket.h
index e4d9c572..c0ab6256 100644
--- a/include/veyra/pipeline/FramePacket.h
+++ b/include/veyra/pipeline/FramePacket.h
@@ -68,7 +68,7 @@ enum class SourcePixelFormat : uint8_t {
enum class ColorRange : uint8_t { Unknown = 0, Limited, Full };
enum class YuvMatrix : uint8_t { Unknown = 0, BT601, BT709, BT2020NCL, BT2020CL };
-enum class TransferFunction : uint8_t { Unknown = 0, SRGB, BT709, BT2020_10, Linear };
+enum class TransferFunction : uint8_t { Unknown = 0, SRGB, BT709, BT2020_10, Linear, PQ, HLG };
enum class ColorPrimaries : uint8_t { Unknown = 0, BT601_525, BT601_625, BT709, BT2020 };
struct SampleAspectRatio {
@@ -97,7 +97,7 @@ struct ColorDescription {
bool primariesAssumed = false;
bool isHdrPath() const {
- return pixelFormat == SourcePixelFormat::P010
+ return transfer == TransferFunction::PQ || transfer == TransferFunction::HLG || pixelFormat == SourcePixelFormat::P010
|| transfer == TransferFunction::BT2020_10;
}
};
diff --git a/include/veyra/pipeline/GpuPassUtils.h b/include/veyra/pipeline/GpuPassUtils.h
index 04cf99c3..3bed5509 100644
--- a/include/veyra/pipeline/GpuPassUtils.h
+++ b/include/veyra/pipeline/GpuPassUtils.h
@@ -285,7 +285,7 @@ struct GraphicsPass {
UINT increment = 0;
bool create(ID3D12Device* device, const std::vector<uint8_t>& vs,
- const std::vector<uint8_t>& ps, UINT heapSlots)
+ const std::vector<uint8_t>& ps, UINT heapSlots, DXGI_FORMAT outputFormat=DXGI_FORMAT_R8G8B8A8_UNORM)
{
D3D12_DESCRIPTOR_RANGE1 srvRange{};
srvRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
@@ -330,7 +330,7 @@ struct GraphicsPass {
pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
pd.NumRenderTargets = 1;
- pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
+ pd.RTVFormats[0] = outputFormat;
pd.SampleDesc.Count = 1;
if (FAILED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso)))) return false;
D3D12_DESCRIPTOR_HEAP_DESC hd{};
diff --git a/include/veyra/remoteplay/ChiakiBackend.h b/include/veyra/remoteplay/ChiakiBackend.h
index 2ec734bc..5a3c51ac 100644
--- a/include/veyra/remoteplay/ChiakiBackend.h
+++ b/include/veyra/remoteplay/ChiakiBackend.h
@@ -29,6 +29,7 @@ struct BackendResult {
};
struct NativeConnectRequest {
std::string host;
+ std::string consoleId; // Stable discovery host_id / registration MAC, normalized hex.
VideoProfile video;
bool viewOnly=false;
PairingCredentials credentials;
diff --git a/include/veyra/remoteplay/Discovery.h b/include/veyra/remoteplay/Discovery.h
index 828120bd..d30a4ede 100644
--- a/include/veyra/remoteplay/Discovery.h
+++ b/include/veyra/remoteplay/Discovery.h
@@ -2,7 +2,7 @@
#include "ChiakiBackend.h"
#include <vector>
namespace veyra::remoteplay {
-struct DiscoveredConsole {std::string host;bool standby=false;};
+struct DiscoveredConsole {std::string host;bool standby=false;std::string consoleId;};
struct DiscoveryReport {
std::vector<DiscoveredConsole> hosts;
std::vector<std::string> diagnostics;
diff --git a/include/veyra/remoteplay/ProfileStore.h b/include/veyra/remoteplay/ProfileStore.h
index 89edf81e..123672a2 100644
--- a/include/veyra/remoteplay/ProfileStore.h
+++ b/include/veyra/remoteplay/ProfileStore.h
@@ -3,8 +3,15 @@
#include <filesystem>
#include <optional>
namespace veyra::remoteplay {
+// Independent of the executable/runtime directory. Throws if Windows cannot
+// resolve the current user's data folder; never silently falls back to cwd.
+std::filesystem::path profileDirectory();
+struct ProfileMigration { unsigned imported=0, failed=0; };
+ProfileMigration migrateProfiles(const std::filesystem::path& legacyRoot);
+ProfileMigration migrateProfilesTo(const std::filesystem::path& legacyRoot,const std::filesystem::path& destination);
// Entire profile is protected for the current Windows user. Never serialize
// credentials to INI/JSON, command lines or diagnostic output.
bool saveProfile(const std::filesystem::path&, const NativeConnectRequest&);
-std::optional<NativeConnectRequest> loadProfile(const std::filesystem::path&);
+enum class ProfileLoadError { None, Missing, Read, Decrypt, Format };
+std::optional<NativeConnectRequest> loadProfile(const std::filesystem::path&,ProfileLoadError* error=nullptr);
}
diff --git a/include/veyra/remoteplay/PsnAuth.h b/include/veyra/remoteplay/PsnAuth.h
new file mode 100644
index 00000000..e0480b83
--- /dev/null
+++ b/include/veyra/remoteplay/PsnAuth.h
@@ -0,0 +1,19 @@
+#pragma once
+#include "Types.h"
+#include <filesystem>
+#include <stop_token>
+namespace veyra::remoteplay {
+struct PsnAuthorization {
+ std::string accessToken,refreshToken;
+ AccountId accountId{};
+ int64_t expiresAt=0;
+ ~PsnAuthorization();
+};
+struct PsnResult {bool ok=false;unsigned error=0;std::optional<AccountId> account;};
+std::wstring psnLoginUrl();
+bool validPsnCallback(std::wstring_view);
+PsnResult authorizePsn(std::wstring callback,std::stop_token);
+PsnResult refreshPsn(std::stop_token);
+std::optional<PsnAuthorization> loadPsnAuthorization();
+bool forgetPsnAuthorization();
+}
diff --git a/include/veyra/remoteplay/Types.h b/include/veyra/remoteplay/Types.h
index 66a01f23..c6fe9fcb 100644
--- a/include/veyra/remoteplay/Types.h
+++ b/include/veyra/remoteplay/Types.h
@@ -14,7 +14,7 @@ using HostTime = std::int64_t; // Local steady-clock, 100 ns. NEVER PS5 render t
using Generation = std::uint64_t;
HostTime monotonic100ns() noexcept;
-enum class Codec : std::uint8_t { H264, H265 };
+enum class Codec : std::uint8_t { H264, H265, H265Hdr };
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 };
diff --git a/scripts/remoteplay/test-ui.ps1 b/scripts/remoteplay/test-ui.ps1
index 776a0e07..ff5c2559 100644
--- a/scripts/remoteplay/test-ui.ps1
+++ b/scripts/remoteplay/test-ui.ps1
@@ -50,7 +50,9 @@ try {
if($panel -eq [IntPtr]::Zero){throw 'Remote Play panel missing'}
# Enumeration can see the HWND while WM_CREATE is still creating children.
[RpUi]::SendMessage($panel,0,[IntPtr]::Zero,[IntPtr]::Zero)|Out-Null
- foreach($control in @(15,16)){if([RpUi]::GetDlgItem($panel,$control) -eq [IntPtr]::Zero){throw 'Bitrate/profile management missing'}}
+ foreach($control in @(15,16,20,21,22)){if([RpUi]::GetDlgItem($panel,$control) -eq [IntPtr]::Zero){throw 'Bitrate/profile management missing'}}
+ $codec=[RpUi]::GetDlgItem($panel,5)
+ if([RpUi]::SendMessage($codec,0x146,[IntPtr]::Zero,[IntPtr]::Zero).ToInt32() -ne 3){throw 'HDR codec option missing'}
$decode=[RpUi]::GetDlgItem($panel,19)
if($decode -eq [IntPtr]::Zero -or [RpUi]::SendMessage($decode,0x146,[IntPtr]::Zero,[IntPtr]::Zero).ToInt32() -ne 3){throw 'Three decode choices missing'}
foreach($choice in @(0,1,2,0)){
diff --git a/shaders/ScaleBlit.hlsl b/shaders/ScaleBlit.hlsl
index 1b2b5975..c94f94ae 100644
--- a/shaders/ScaleBlit.hlsl
+++ b/shaders/ScaleBlit.hlsl
@@ -3,7 +3,7 @@
// from window extent). SDR path only: straight RGBA8 in, RGBA8 out.
Texture2D<float4> sourceTex : register(t0);
-RWTexture2D<unorm float4> outputTex : register(u0);
+RWTexture2D<float4> outputTex : register(u0);
cbuffer ScaleBlitConstants : register(b0)
{
diff --git a/shaders/YuvToLinearRgb.hlsl b/shaders/YuvToLinearRgb.hlsl
index a2a744d2..30f7d3bc 100644
--- a/shaders/YuvToLinearRgb.hlsl
+++ b/shaders/YuvToLinearRgb.hlsl
@@ -24,9 +24,19 @@ float ExpandLimited(float c)
float3 YuvToRgb(float y, float2 uv)
{
- float yy = colorParams0.x > 0.5 ? ExpandLimited(y) : y;
- float uu = (uv.x - 128.0/255.0) * (colorParams0.x > 0.5 ? 255.0/224.0 : 1.0);
- float vv = (uv.y - 128.0/255.0) * (colorParams0.x > 0.5 ? 255.0/224.0 : 1.0);
+ // P010 is stored as 10 significant HIGH bits in 16-bit UNORM. Its
+ // normalization is not 8-bit /255: decode legal code values explicitly.
+ bool ten=colorParams0.w>0.5;
+ float scale=ten?65535.0/64.0:255.0;
+ float black=ten?64.0:16.0,white=ten?940.0:235.0;
+ float middle=ten?512.0:128.0,span=ten?896.0:224.0;
+ float maximum=ten?1023.0:255.0;
+ float yy=colorParams0.x>0.5?(y*scale-black)/(white-black):y*scale/maximum;
+ yy=saturate(yy);
+ float uu=(uv.x*scale-middle)/(colorParams0.x>0.5?span:maximum);
+ float vv=(uv.y*scale-middle)/(colorParams0.x>0.5?span:maximum);
+
+ if(colorParams0.y>1.5)return float3(yy+1.4746*vv,yy-0.164553*uu-0.571353*vv,yy+1.8814*uu);
if (colorParams0.y > 0.5) {
// BT.709.
@@ -57,7 +67,21 @@ void main(uint3 dispatchThreadId : SV_DispatchThreadID)
const float2 uv = chromaPlane[uint2(dispatchThreadId.x / 2, dispatchThreadId.y / 2)];
float3 rgb = YuvToRgb(y, uv);
rgb = saturate(rgb);
- if (colorParams0.z > 2.5) {
+ if(colorParams0.z>3.5){
+ // ST2084 EOTF to absolute cd/m2, then BT.2020 -> BT.709 linear.
+ const float m1=2610.0/16384.0,m2=2523.0/32.0;
+ float3 p=pow(rgb,1.0/m2);
+ float3 nits=10000.0*pow(max(p-3424.0/4096.0,0.0)/max(2413.0/128.0-2392.0/128.0*p,1e-6),1.0/m1);
+ float3 linear709=mul(float3x3(1.660491,-0.587641,-0.072850,-0.124550,1.132900,-0.008349,-0.018151,-0.100579,1.118730),nits);
+ if(yuvDimensions.z!=0)rgb=linear709/80.0; // scRGB: 1.0 = 80 nits.
+ else{
+ // Stable luminance shoulder, fixed 1000-nit reference peak.
+ // This is SDR mapping, never advertised as native HDR output.
+ float3 c=max(linear709/203.0,0.0);float lum=dot(c,float3(.2126,.7152,.0722));
+ float peak=1000.0/203.0;float mapped=lum*(1.0+lum/(peak*peak))/(1.0+lum);
+ rgb=saturate(c*(mapped/max(lum,1e-6)));
+ }
+ } else if (colorParams0.z > 2.5) {
rgb = pow(rgb, 2.4); // BT.1886 EOTF, ideal black SDR display intent.
} else if (colorParams0.z > 1.5) {
rgb = float3(rgb.r < 0.081 ? rgb.r / 4.5 : pow((rgb.r + 0.099) / 1.099, 1.0/0.45),
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 056d52e8..38d7893c 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -180,7 +180,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
width=activeSource->info().width;height=activeSource->info().height;duration=isCapture?0:activeSource->info().duration.toDouble();
}
if(!pipeline::Extent{width,height}.valid()){status(L"图像尺寸超出单张GPU纹理能力,需要分块处理",true);break;}
- pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;
+ pipeline::EnhanceGraphDesc gd;gd.sourceWidth=width;gd.sourceHeight=height;gd.hdrInput=isRemote&&activeSource->info().color.isHdrPath();
gd.rgbInput=isImage||(isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Bgra8);
gd.yuy2Input=isCapture&&activeSource->info().color.pixelFormat==pipeline::SourcePixelFormat::Yuy2;gd.stillImage=isImage;
const auto resolution=pipeline::ResolutionPlan::make({width,height},options.sr,options.realtime?pipeline::NrSizePolicy::Realtime:pipeline::NrSizePolicy::Native,isImage,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);
@@ -190,16 +190,19 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
gd.nrBeforeSr=!isImage&&options.settings.lowLatency&&options.nr&&resolution.srApplied;gd.enableSr=resolution.srApplied&&nvidiaAdapter;gd.videoSrQuality=options.settings.videoSrQuality;gd.enableNr=options.nr&&nvidiaAdapter;gd.nrRuntime=options.settings.nrRuntime;gd.enableFg=options.fg&&(nvidiaAdapter||xessFg);gd.fgMultiplier=options.fgMultiplier;gd.frameGenerationBackend=options.settings.frameGenerationBackend;gd.enableNvofStandalone=gd.enableNr;
gd.noFeatures=false;gd.model=options.settings.model;gd.residual=options.settings.residual;gd.protection=options.settings.protection;gd.settingsRevision=options.settings.revision;gd.flowQuality=options.settings.flow;gd.contentRate=options.settings.content;
gd.opticalFlowBackend=options.settings.opticalFlowBackend;gd.amdFlowHalfResolution=options.settings.amdFlowHalfResolution;
+ gd.hdrOutput=gd.hdrInput&&!gd.enableNr&&!gd.enableSr&&!gd.enableFg&&gfx::PresentSink::hdrDisplayActive(window);
gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
if(!graph.initialize(gd)||!presenter.open(ctx,window,graph,options.settings.captureCompatible)||!graph.createViews()){status(L"增强初始化失败,请核对本地运行时",true);break;}
if(!nvidiaAdapter&&(options.nr||options.sr||(options.fg&&!xessFg))){
veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested features: nr={} sr={} fgBackend={} flowBackend={}",options.nr,options.sr,frameGenerationBackendName(options.settings.frameGenerationBackend),opticalFlowBackendName(options.settings.opticalFlowBackend)));
status(L"当前非 NVIDIA 适配器:NR、NVIDIA 超分与 DLSS 已禁用;可使用 XeSS 预览和 AMD 光流",false);
}
+ if(gd.hdrInput)status(gd.hdrOutput?L"PS5 HDR输入 · 原生HDR显示(关闭增强)":L"PS5 HDR输入 · SDR色调映射后增强/显示(1000nit参考峰值)",false);
if(graph.xessEnabled()&&!presenter.xessActive())status(L"XeSS 未启用:运行时或设备不兼容;当前为普通呈现",false);
{
std::lock_guard lock(mutex_);
if(!nvidiaAdapter&&(options.nr||options.sr||(options.fg&&!xessFg)))snapshot_.backendWarning=L"当前 GPU 不支持所选 NVIDIA 增强";
+ if(gd.hdrInput)snapshot_.backendWarning=gd.hdrOutput?L"HDR输入 → 原生HDR显示;增强关闭":L"HDR输入 → SDR色调映射后增强/显示";
if(graph.xessEnabled()&&!presenter.xessActive())snapshot_.backendWarning=L"XeSS 初始化失败;当前为普通呈现";
}
captureSource.setAudioSync(unsigned(options.settings.audioSync),options.settings.audioOffsetMs);
@@ -361,7 +364,13 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}
return lastAudioClockMs;
};
+ uint64_t hdrDisplayCheck=0;
while(!stop_){
+ if(gd.hdrInput&&GetTickCount64()-hdrDisplayCheck>2000){
+ hdrDisplayCheck=GetTickCount64();
+ const bool native=!gd.enableNr&&!gd.enableSr&&!gd.enableFg&&gfx::PresentSink::hdrDisplayActive(window);
+ if(native!=gd.hdrOutput){std::lock_guard lock(mutex_);if(desired_.revision==options.settings.revision){desired_.revision=++nextRevision_;snapshot_.desired=desired_;snapshot_.applying=true;}}
+ }
if(audioStarted)publishAudioStatus();
if(audioStarted&&injectFileEndpointLoss&&!fileEndpointLossInjected&&frames>=20){audioPipe.requestEndpointLossForTest();fileEndpointLossInjected=true;}
advanceLive();
@@ -379,7 +388,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
std::wstring save;EnhancementSettings requested;{std::lock_guard lock(mutex_);requested=desired_;if(hasOutput)save.swap(savePath_);}
if(!save.empty()){try{sink::RgbaImage result;const auto e=std::filesystem::path(save).extension().wstring();
drainLivePresentation();
- if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}
+ if(graph.hdrOutput())status(L"原生HDR截图尚未支持;可使用SDR映射模式保存图片",false);else if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),result)||!sink::saveImage(save,result,e==L".jpg"||e==L".jpeg"))status(L"保存失败(目标文件可能已存在),播放已保留",false);else{status(L"图片已保存:"+save);veyra::log::info("image-save",std::format("saved extent={}x{} revision={}",gd.workWidth,gd.workHeight,options.settings.revision));}}
catch(const std::exception& e){veyra::log::warn("image-save",std::format("save exception; retaining session: {}",e.what()));status(L"保存异常,播放已保留;可再次保存",false);}}
if(isImage)requested.multiplier=1;
if(requested.revision==options.settings.revision&&requested!=options.settings){
@@ -416,7 +425,8 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
nextDesc.nrBeforeSr=!isImage&&requested.lowLatency&&requested.nr&&plan.srApplied;nextDesc.enableSr=plan.srApplied&&nvidiaAdapter;nextDesc.videoSrQuality=next.settings.videoSrQuality;nextDesc.enableNr=next.nr&&nvidiaAdapter;nextDesc.nrRuntime=next.settings.nrRuntime;nextDesc.enableFg=next.fg&&(nvidiaAdapter||xessFg);nextDesc.fgMultiplier=next.fgMultiplier;nextDesc.frameGenerationBackend=next.settings.frameGenerationBackend;nextDesc.enableNvofStandalone=nextDesc.enableNr;
nextDesc.model=requested.model;nextDesc.residual=requested.residual;nextDesc.protection=requested.protection;nextDesc.settingsRevision=requested.revision;nextDesc.flowQuality=requested.flow;nextDesc.contentRate=requested.content;
nextDesc.opticalFlowBackend=requested.opticalFlowBackend;nextDesc.amdFlowHalfResolution=requested.amdFlowHalfResolution;
- const bool rebuild=previous.captureCompatible!=requested.captureCompatible||gd.nrRuntime!=nextDesc.nrRuntime||gd.opticalFlowBackend!=nextDesc.opticalFlowBackend||gd.amdFlowHalfResolution!=nextDesc.amdFlowHalfResolution||gd.enableNr!=nextDesc.enableNr||gd.enableFg!=nextDesc.enableFg||gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||gd.fgMultiplier!=nextDesc.fgMultiplier||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.nrBeforeSr!=nextDesc.nrBeforeSr||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;
+ nextDesc.hdrOutput=nextDesc.hdrInput&&!nextDesc.enableNr&&!nextDesc.enableSr&&!nextDesc.enableFg&&gfx::PresentSink::hdrDisplayActive(window);
+ const bool rebuild=gd.hdrOutput!=nextDesc.hdrOutput||previous.captureCompatible!=requested.captureCompatible||gd.nrRuntime!=nextDesc.nrRuntime||gd.opticalFlowBackend!=nextDesc.opticalFlowBackend||gd.amdFlowHalfResolution!=nextDesc.amdFlowHalfResolution||gd.enableNr!=nextDesc.enableNr||gd.enableFg!=nextDesc.enableFg||gd.frameGenerationBackend!=nextDesc.frameGenerationBackend||gd.fgMultiplier!=nextDesc.fgMultiplier||gd.videoSrQuality!=nextDesc.videoSrQuality||gd.flowQuality!=nextDesc.flowQuality||gd.nrBeforeSr!=nextDesc.nrBeforeSr||gd.workWidth!=nextDesc.workWidth||gd.workHeight!=nextDesc.workHeight||gd.nrWidth!=nextDesc.nrWidth||gd.nrHeight!=nextDesc.nrHeight||gd.flowWidth!=nextDesc.flowWidth||gd.flowHeight!=nextDesc.flowHeight;
bool accepted=ring.drainQueue();out={};hasOutput=false;
resetRecord->rebuilt=rebuild;
markResetStage(diagnostics::ResetStage::Drain);
@@ -431,6 +441,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
}else if(accepted)accepted=graph.applySettings(requested);
if(accepted){
options=next;gd=nextDesc;transaction=true;reset=true;
+ if(gd.hdrInput){std::lock_guard lock(mutex_);snapshot_.backendWarning=gd.hdrOutput?L"HDR输入 → 原生HDR显示;增强关闭":L"HDR输入 → SDR色调映射后增强/显示";}
resetRecord->epoch=0;
if(!nvidiaAdapter&&(next.nr||next.sr||(next.fg&&!xessFg)))veyra::log::warn("capability",std::format("non-NVIDIA adapter disabled requested settings revision={} nr={} sr={} fgBackend={} flowBackend={}",requested.revision,next.nr,next.sr,frameGenerationBackendName(requested.frameGenerationBackend),opticalFlowBackendName(requested.opticalFlowBackend)));
}
@@ -504,7 +515,7 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
width=uint32_t(frame->width);height=uint32_t(frame->height);
auto plan=pipeline::ResolutionPlan::make({width,height},options.sr,options.settings.nrPolicy,false,options.settings.revision,options.settings.srTarget,options.settings.lowLatency&&options.nr);
gd.nrBeforeSr=options.settings.lowLatency&&options.nr&&plan.srApplied;gd.enableSr=plan.srApplied&&ctx.adapter().isNvidia;
- gd.sourceWidth=width;gd.sourceHeight=height;gd.workWidth=plan.base.width;gd.workHeight=plan.base.height;gd.nrWidth=plan.nr.width;gd.nrHeight=plan.nr.height;gd.flowWidth=plan.flow.width;gd.flowHeight=plan.flow.height;
+ gd.sourceWidth=width;gd.sourceHeight=height;gd.hdrInput=isRemote&&activeSource->info().color.isHdrPath();gd.hdrOutput=gd.hdrInput&&!gd.enableNr&&!gd.enableSr&&!gd.enableFg&&gfx::PresentSink::hdrDisplayActive(window);gd.workWidth=plan.base.width;gd.workHeight=plan.base.height;gd.nrWidth=plan.nr.width;gd.nrHeight=plan.nr.height;gd.flowWidth=plan.flow.width;gd.flowHeight=plan.flow.height;
presenter.close();graph.shutdown();out={};hasOutput=false;
if(!graph.initialize(gd)||!presenter.open(ctx,window,graph,options.settings.captureCompatible)||!graph.createViews()){status(L"串流尺寸切换失败",true);break;}
reset=true;pendingResetCause=pipeline::ResetReason::Resize;
diff --git a/src/engine/VideoPresenter.cpp b/src/engine/VideoPresenter.cpp
index 3bc3740d..c243a0c6 100644
--- a/src/engine/VideoPresenter.cpp
+++ b/src/engine/VideoPresenter.cpp
@@ -7,14 +7,14 @@ namespace veyra::engine {
bool VideoPresenter::open(gfx::D3D12DeviceContext& ctx,HWND window,pipeline::EnhanceGraph& graph,bool captureCompatible) {
gpuTimer_.initialize(ctx.device(),ctx.directQueue());window_=window;RECT rc{};GetClientRect(window,&rc);
gfx::PresentSink::Desc d;d.targetWindow=window;d.width=std::max(1L,rc.right);d.height=std::max(1L,rc.bottom);d.vsync=false;
- d.xess=graph.xessEnabled();d.captureCompatible=captureCompatible;lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;
+ d.hdr=graph.hdrOutput();d.xess=graph.xessEnabled();d.captureCompatible=captureCompatible;lastXessFrame_={};lastXessIdentity_={};xessWasEnabled_=false;
Status st=Status::Ok;if(!sink_.initialize(ctx.device(),ctx.directQueue(),d,st))return false;
std::vector<uint8_t> vs,ps;
- if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,12))return false;
+ if(!pipeline::loadShaderBytes("PresentBlit_vs.dxil",vs)||!pipeline::loadShaderBytes("PresentBlit_ps.dxil",ps)||!pass_.create(ctx.device(),vs,ps,12,d.hdr?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM))return false;
D3D12_DESCRIPTOR_HEAP_DESC hd{};hd.Type=D3D12_DESCRIPTOR_HEAP_TYPE_RTV;hd.NumDescriptors=3;
if(FAILED(ctx.device()->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&rtvs_))))return false;
inc_=ctx.device()->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);refresh(ctx.device());
- for(unsigned i=0;i<8;++i)pipeline::makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),DXGI_FORMAT_R8G8B8A8_UNORM,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*pass_.increment});
+ for(unsigned i=0;i<8;++i)pipeline::makeSrv(ctx.device(),i<2?graph.videoFrameResource(i):graph.generatedFrameResource(i-2),i<2&&graph.hdrOutput()?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i)*pass_.increment});
for(unsigned i=0;i<4;++i)pipeline::makeSrv(ctx.device(),i<2?graph.sourceReference(i):graph.baseReference(i-2),DXGI_FORMAT_R16G16B16A16_FLOAT,{pass_.heap->GetCPUDescriptorHandleForHeapStart().ptr+size_t(i+8)*pass_.increment});
return true;
}
@@ -51,7 +51,7 @@ bool VideoPresenter::present(gfx::D3D12DeviceContext& ctx,gfx::CommandSlotRing&
if(comparison&&!generated&&referencesValid){
auto* reference=baseReference?graph.baseReference(slot):graph.sourceReference(slot);
D3D12_RESOURCE_BARRIER b{};b.Type=D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;b.Transition.pResource=reference;b.Transition.Subresource=D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;b.Transition.StateBefore=D3D12_RESOURCE_STATE_COMMON;b.Transition.StateAfter=D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;list->ResourceBarrier(1,&b);
- dims[2]=1;list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(8+slot+(baseReference?2:0))*pass_.increment});
+ dims[2]=graph.hdrOutput()?0:1;list->SetGraphicsRoot32BitConstants(0,8,dims,0);list->SetGraphicsRootDescriptorTable(1,{pass_.heap->GetGPUDescriptorHandleForHeapStart().ptr+size_t(8+slot+(baseReference?2:0))*pass_.increment});
if(comparison==2)rect.right=LONG(std::clamp((rc.right*.5f+(std::clamp(split,0.0f,1.0f)-view.centerX)*graph.workWidth()*scale*view.zoom)*sink_.bufferWidth()/rc.right,0.0f,float(sink_.bufferWidth())));list->RSSetScissorRects(1,&rect);list->DrawInstanced(3,1,0,0);
std::swap(b.Transition.StateBefore,b.Transition.StateAfter);list->ResourceBarrier(1,&b);
if(veyra::log::verboseFrameLogs())veyra::log::info("comparison",std::format("real-frame source={} epoch={} revision={} reference={} mode={} split={} (same leased frame)",identity.sourceFrameId,identity.epoch,identity.settingsRevision,baseReference?"base":"input",comparison,split));
diff --git a/src/gfx/PresentSink.cpp b/src/gfx/PresentSink.cpp
index 3cbf5add..5998c894 100644
--- a/src/gfx/PresentSink.cpp
+++ b/src/gfx/PresentSink.cpp
@@ -17,6 +17,17 @@ const wchar_t* kWindowClassName = L"VeyraPresentSink";
} // namespace
+bool PresentSink::hdrDisplayActive(HWND window){
+ const auto monitor=MonitorFromWindow(window,MONITOR_DEFAULTTONEAREST);
+ ComPtr<IDXGIFactory1> factory;if(FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))))return false;
+ for(UINT a=0;;++a){ComPtr<IDXGIAdapter1> adapter;if(factory->EnumAdapters1(a,&adapter)==DXGI_ERROR_NOT_FOUND)break;if(!adapter)break;
+ for(UINT i=0;;++i){ComPtr<IDXGIOutput> output;if(adapter->EnumOutputs(i,&output)==DXGI_ERROR_NOT_FOUND)break;if(!output)break;
+ ComPtr<IDXGIOutput6> advanced;if(FAILED(output.As(&advanced)))continue;DXGI_OUTPUT_DESC1 desc{};
+ if(SUCCEEDED(advanced->GetDesc1(&desc))&&desc.Monitor==monitor)return desc.ColorSpace==DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
+ }
+ }return false;
+}
+
PresentSink::~PresentSink()
{
shutdown();
@@ -100,7 +111,7 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
DXGI_SWAP_CHAIN_DESC1 scd{};
scd.Width = width_;
scd.Height = height_;
- scd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ scd.Format = desc.hdr?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM;
scd.SampleDesc.Count = 1;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.BufferCount = 3;
@@ -132,6 +143,10 @@ bool PresentSink::initialize(ID3D12Device* device, ID3D12CommandQueue* queue,
return false;
}
}
+ const auto space=desc.hdr?DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709:DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709;
+ UINT support=0;const auto check=swapChain_->CheckColorSpaceSupport(space,&support);
+ if(FAILED(check)||!(support&DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT)||FAILED(swapChain_->SetColorSpace1(space))){log::error("present","Requested output color space is unavailable");status=Status::WindowFailure;return false;}
+ log::info("present",desc.hdr?"output=scRGB FP16 (1=80 nits)":"output=SDR RGB G22");
// Block ALT+ENTER; the engine owns mode changes.
(void)factory_->MakeWindowAssociation(hwnd_, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);
queue_ = queue;
@@ -284,7 +299,7 @@ void PresentSink::resize(uint32_t width, uint32_t height)
if (!waitForQueueIdle()) return;
for (auto& b : backBuffers_) b.Reset();
HRESULT hr = swapChain_->ResizeBuffers(3, width, height,
- DXGI_FORMAT_R8G8B8A8_UNORM, flags);
+ desc_.hdr?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, flags);
if (FAILED(hr)) {
log::error("present", std::format("ResizeBuffers FAILED hr=0x{:X} (queue idle, buffers released)",
static_cast<unsigned>(hr)));
diff --git a/src/pipeline/EnhanceGraph.cpp b/src/pipeline/EnhanceGraph.cpp
index bc19b61f..960f0087 100644
--- a/src/pipeline/EnhanceGraph.cpp
+++ b/src/pipeline/EnhanceGraph.cpp
@@ -87,6 +87,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
diagnostics::DiagnosticEvent initDiagnostic;initDiagnostic.stage="initialize";initDiagnostic.identity={epoch_+1,desc.settingsRevision,0};initDiagnostic.resolution.source={srcW_,srcH_};initDiagnostic.resolution.base=initDiagnostic.resolution.fg=initDiagnostic.resolution.output={workW_,workH_};initDiagnostic.resolution.nr={nrW_,nrH_};initDiagnostic.resolution.flow={nvofW_,nvofH_};initDiagnostic.flowApplied=std::to_string(unsigned(desc.flowQuality));initDiagnostic.runtimeHash="unverified-user-replaceable";Logger::diagnosticContext(initDiagnostic);
veyra::log::info("resolution",std::format("source={}x{} base={}x{} nr={}x{} flow={}x{} fg={}x{} output={}x{}",srcW_,srcH_,workW_,workH_,nrW_,nrH_,nvofW_,nvofH_,workW_,workH_,workW_,workH_));
veyra::log::info("pipeline-order",desc.nrBeforeSr?"NR -> residual(source) -> SR -> FG (experimental preview)":"SR -> NR -> residual -> FG");
+ if(desc.hdrOutput&&(!desc.hdrInput||desc.enableNr||desc.enableSr||desc.enableFg)){veyra::log::error("hdr","Native HDR enhancement combination is not validated");return false;}
srEnabled_ = desc.enableSr && (srcW_ != workW_ || srcH_ != workH_);
nrEnabled_ = desc.enableNr && !desc.noFeatures && !desc.noNgx;
fgEnabled_ = desc.enableFg && !desc.noNgx && !desc.stillImage && desc.frameGenerationBackend!=engine::FrameGenerationBackend::XeSS;
@@ -100,7 +101,7 @@ bool EnhanceGraph::initialize(const EnhanceGraphDesc& desc)
}
Status st = Status::Ok;
- lumaPitch_ = (static_cast<size_t>(srcW_) + 255) & ~size_t(255);
+ lumaPitch_ = (static_cast<size_t>(srcW_)*(desc_.hdrInput?2:1) + 255) & ~size_t(255);
chromaPitch_ = lumaPitch_;
lumaSize_ = lumaPitch_ * srcH_;
chromaSize_ = chromaPitch_ * ((srcH_ + 1) / 2);
@@ -149,8 +150,8 @@ bool EnhanceGraph::createResources()
upDepth_ = makeUploadBuffer(context_.device(), dPitch_ * workH_);
upZeroDepth_ = makeUploadBuffer(context_.device(), dPitch_ * workH_);
upZeroMotion_ = makeUploadBuffer(context_.device(), dPitch_ * workH_);
- lumaTex_ = makeTexture(context_.device(), srcW_, srcH_, DXGI_FORMAT_R8_UNORM, true);
- chromaTex_ = makeTexture(context_.device(), (srcW_+1) / 2, (srcH_+1) / 2, DXGI_FORMAT_R8G8_UNORM, true);
+ lumaTex_ = makeTexture(context_.device(), srcW_, srcH_, desc_.hdrInput?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM, true);
+ chromaTex_ = makeTexture(context_.device(), (srcW_+1) / 2, (srcH_+1) / 2, desc_.hdrInput?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM, true);
if(desc_.rgbInput||desc_.yuy2Input){
if(desc_.yuy2Input&&(srcW_%2||desc_.rgbInput))return false;
const unsigned packedWidth=desc_.yuy2Input?srcW_/2:srcW_;
@@ -175,8 +176,8 @@ bool EnhanceGraph::createResources()
proxyTex_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
neuralTex_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
finalRgba_ = makeTexture(context_.device(), nrW_, nrH_, DXGI_FORMAT_R16G16B16A16_FLOAT, true);
- videoFrame_[0] = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
- videoFrame_[1] = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R8G8B8A8_UNORM, true);
+ videoFrame_[0] = makeTexture(context_.device(), workW_, workH_, desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, true);
+ videoFrame_[1] = makeTexture(context_.device(), workW_, workH_, desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, true);
confTex_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_R8_UNORM, true);
flowTex_ = makeTexture(context_.device(), nvofW_, nvofH_, DXGI_FORMAT_R16G16_FLOAT, true);
depthTex_ = makeTexture(context_.device(), workW_, workH_, DXGI_FORMAT_R32_FLOAT, false);
@@ -578,8 +579,8 @@ bool EnhanceGraph::createViews()
stagedSrv(rgbTex_.Get(),DXGI_FORMAT_R8G8B8A8_UNORM,rgbPass_,0);
makeUav(context_.device(),srcRgba_.Get(),DXGI_FORMAT_R16G16B16A16_FLOAT,cpu(rgbPass_,1));
}
- if (viewsTex) stagedSrv(lumaTex_.Get(), DXGI_FORMAT_R8_UNORM, yuvPass_, 0);
- if (viewsTex) stagedSrv(chromaTex_.Get(), DXGI_FORMAT_R8G8_UNORM, yuvPass_, 1);
+ if (viewsTex) stagedSrv(lumaTex_.Get(), desc_.hdrInput?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM, yuvPass_, 0);
+ if (viewsTex) stagedSrv(chromaTex_.Get(), desc_.hdrInput?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM, yuvPass_, 1);
if (viewsUav) makeUav(context_.device(), srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(yuvPass_, 2));
if (viewsTex) stagedSrv(nrInput_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, encPass_, 0);
if (viewsUav) makeUav(context_.device(), proxyTex_.Get(), DXGI_FORMAT_R8G8B8A8_UNORM, cpu(encPass_, 1));
@@ -587,8 +588,8 @@ bool EnhanceGraph::createViews()
if (viewsTex) stagedSrv(proxyTex_.Get(), DXGI_FORMAT_R8G8B8A8_UNORM, decPass_, 1);
if (viewsTex) stagedSrv(neuralTex_.Get(), DXGI_FORMAT_R8G8B8A8_UNORM, decPass_, 2);
if (viewsUav) makeUav(context_.device(), finalRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(decPass_, 3));
- if (viewsUav) makeUav(context_.device(), lumaTex_.Get(), DXGI_FORMAT_R8_UNORM, cpu(uploadPass_, 2));
- if (viewsUav) makeUav(context_.device(), chromaTex_.Get(), DXGI_FORMAT_R8G8_UNORM, cpu(uploadPass_, 3));
+ if (viewsUav) makeUav(context_.device(), lumaTex_.Get(), desc_.hdrInput?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM, cpu(uploadPass_, 2));
+ if (viewsUav) makeUav(context_.device(), chromaTex_.Get(), desc_.hdrInput?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM, cpu(uploadPass_, 3));
// Software NV12 ingestion uses plane copies; no raw-SRV dispatch.
// Blit pass layout (all static; per-use offsets chosen at bind time):
// 0: srcRgba SRV 1: workRgba UAV (SR bypass / NR-off blit)
@@ -603,17 +604,17 @@ bool EnhanceGraph::createViews()
if (viewsTex) stagedSrv(srcRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 0);
if (viewsUav) makeUav(context_.device(), workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, cpu(blitPass_, 1));
if (viewsTex) stagedSrv(nrEnabled_&&!desc_.nrBeforeSr ? residualRgba_.Get() : workRgba_.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, blitPass_, 2);
- if (viewsUav) makeUav(context_.device(), videoFrame_[0].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, cpu(blitPass_, 3));
- if (viewsUav) makeUav(context_.device(), videoFrame_[1].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, cpu(blitPass_, 4));
+ if (viewsUav) makeUav(context_.device(), videoFrame_[0].Get(), desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, cpu(blitPass_, 3));
+ if (viewsUav) makeUav(context_.device(), videoFrame_[1].Get(), desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, cpu(blitPass_, 4));
if (viewsTex) stagedSrv(nvofInB_.Get(), DXGI_FORMAT_B8G8R8A8_UNORM, blitPass_, 5);
if (viewsUav) makeUav(context_.device(), nvofInA_.Get(), DXGI_FORMAT_B8G8R8A8_UNORM, cpu(blitPass_, 6));
- if (viewsTex) stagedSrv(videoFrame_[0].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 7);
- if (viewsTex) stagedSrv(videoFrame_[1].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 8);
+ if (viewsTex) stagedSrv(videoFrame_[0].Get(), desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 7);
+ if (viewsTex) stagedSrv(videoFrame_[1].Get(), desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 8);
if (viewsUav) makeUav(context_.device(), nvofInB_.Get(), DXGI_FORMAT_B8G8R8A8_UNORM, cpu(blitPass_, 9));
if (viewsTex) stagedSrv(genFrame_[0].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 10);
if (viewsTex) stagedSrv(genFrame_[1].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 13);
- if (viewsTex) stagedSrv(videoFrame_[0].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 11);
- if (viewsTex) stagedSrv(videoFrame_[1].Get(), DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 12);
+ if (viewsTex) stagedSrv(videoFrame_[0].Get(), desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 11);
+ if (viewsTex) stagedSrv(videoFrame_[1].Get(), desc_.hdrOutput?DXGI_FORMAT_R16G16B16A16_FLOAT:DXGI_FORMAT_R8G8B8A8_UNORM, blitPass_, 12);
// Densify pass views: 0=rawFlow SRV(int2) 1=cost SRV(uint)
// 2=previous RGB,3=current RGB,4=AMD SCD;5=flow UAV,6=confidence UAV.
@@ -663,9 +664,12 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
static const bool graphOff = GetEnvironmentVariableW(L"VEYRA_GRAPH_OFF", nullptr, 0) != 0;
if (!frame || !initialized_ || !std::isfinite(ptsMs)) return false;
const auto resolved=resolveFrameColor(*frame,color?*color:ColorDescription{});
- if(resolved.matrix==YuvMatrix::BT2020NCL||resolved.matrix==YuvMatrix::BT2020CL||resolved.transfer==TransferFunction::BT2020_10){veyra::log::error("graph","BT.2020 input is not supported by the BT.601/709 SDR conversion");return false;}
+ if(resolved.matrix==YuvMatrix::BT2020CL||resolved.transfer==TransferFunction::BT2020_10||(resolved.matrix==YuvMatrix::BT2020NCL&&!desc_.hdrInput)){veyra::log::error("graph","BT.2020 input is not supported by the BT.601/709 SDR conversion");return false;}
+ if(resolved.transfer==TransferFunction::PQ&&(resolved.matrix!=YuvMatrix::BT2020NCL||resolved.primaries!=ColorPrimaries::BT2020)){
+ veyra::log::error("hdr","Unsupported PQ colorimetry: requires signaled/fallback BT2020 NCL and BT2020 primaries");return false;
+ }
if(reset||!realFrameIndex_)veyra::log::info("color",std::format("range={} assumed={} matrix={} assumed={} transfer={} assumed={} display709={}",int(resolved.range),resolved.rangeAssumed,int(resolved.matrix),resolved.matrixAssumed,int(resolved.transfer),resolved.transferAssumed,resolved.displayReferred709));
- if (frame->color_trc == AVCOL_TRC_SMPTE2084 || frame->color_trc == AVCOL_TRC_ARIB_STD_B67) {
+ if (resolved.transfer==TransferFunction::HLG || (resolved.transfer==TransferFunction::PQ&&!desc_.hdrInput)) {
veyra::log::error("graph", "HDR input is unsupported by the V1 SDR pipeline"); return false;
}
if(std::abs(ptsMs)>9e13){veyra::log::error("timeline","PTS outside representable range");return false;}
@@ -770,7 +774,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
const bool isArray = nv12Texture->GetDesc().DepthOrArraySize > 1;
D3D12_SHADER_RESOURCE_VIEW_DESC lumaSrv{};
- lumaSrv.Format = DXGI_FORMAT_R8_UNORM;
+ lumaSrv.Format = nv12Texture->GetDesc().Format==DXGI_FORMAT_P010?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM;
lumaSrv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
lumaSrv.Texture2D.MostDetailedMip = 0;
lumaSrv.Texture2D.MipLevels = 1;
@@ -790,7 +794,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
}
context_.device()->CreateShaderResourceView(nv12Texture, &lumaSrv, cpuHandleOf(yuvPass_, 0));
D3D12_SHADER_RESOURCE_VIEW_DESC chromaSrv{};
- chromaSrv.Format = DXGI_FORMAT_R8G8_UNORM;
+ chromaSrv.Format = nv12Texture->GetDesc().Format==DXGI_FORMAT_P010?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM;
chromaSrv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
chromaSrv.Texture2D.MostDetailedMip = 0;
chromaSrv.Texture2D.MipLevels = 1;
@@ -813,27 +817,27 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
} else {
nv12Ctx_ = sws_getCachedContext(nv12Ctx_, frame->width, frame->height,
static_cast<AVPixelFormat>(frame->format),
- frame->width, frame->height, AV_PIX_FMT_NV12, SWS_POINT,
+ frame->width, frame->height, desc_.hdrInput?AV_PIX_FMT_P010:AV_PIX_FMT_NV12, SWS_POINT,
nullptr, nullptr, nullptr);
if (nv12Ctx_ == nullptr) { veyra::log::error("graph", "sws"); return false; }
- const int colorSpace=resolved.matrix==YuvMatrix::BT601?SWS_CS_ITU601:SWS_CS_ITU709;
+ const int colorSpace=resolved.matrix==YuvMatrix::BT2020NCL?SWS_CS_BT2020:resolved.matrix==YuvMatrix::BT601?SWS_CS_ITU601:SWS_CS_ITU709;
const int* coefficients=sws_getCoefficients(colorSpace);
const int full=resolved.range==ColorRange::Full?1:0;
if(sws_setColorspaceDetails(nv12Ctx_,coefficients,full,coefficients,full,0,1<<16,1<<16)<0)return false;
// Planar 8-bit YUV already exposes CPU luma for cadence analysis.
// Convert directly into the fenced upload slot instead of writing and
// copying another full NV12 frame. Never sample write-combined memory.
- const bool directUpload=frame->format==AV_PIX_FMT_YUV420P||frame->format==AV_PIX_FMT_YUVJ420P||frame->format==AV_PIX_FMT_NV12;
- uint8_t* planes[2] = { directUpload?mappedLuma_[parity]:nv12Buf_.data(), directUpload?mappedChroma_[parity]:nv12Buf_.data() + lumaSize_ };
- const int strides[2] = { static_cast<int>(lumaPitch_), static_cast<int>(chromaPitch_) };
- sws_scale(nv12Ctx_, frame->data, frame->linesize, 0, frame->height, planes, strides);
+ const bool directUpload=!desc_.hdrInput&&(frame->format==AV_PIX_FMT_YUV420P||frame->format==AV_PIX_FMT_YUVJ420P||frame->format==AV_PIX_FMT_NV12);
+ uint8_t* planes[4] = { directUpload?mappedLuma_[parity]:nv12Buf_.data(), directUpload?mappedChroma_[parity]:nv12Buf_.data() + lumaSize_ };
+ const int strides[4] = { static_cast<int>(lumaPitch_), static_cast<int>(chromaPitch_) };
+ if(sws_scale(nv12Ctx_, frame->data, frame->linesize, 0, frame->height, planes, strides)!=frame->height){veyra::log::error("color","Software plane conversion failed");return false;}
std::vector<uint8_t> sample;sample.reserve(64*36);
- for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){const uint8_t v=directUpload?frame->data[0][ptrdiff_t(y*srcH_/36)*frame->linesize[0]+x*srcW_/64]:planes[0][size_t(y*srcH_/36)*lumaPitch_+x*srcW_/64];sample.push_back(v);}
+ for(unsigned y=0;y<36;++y)for(unsigned x=0;x<64;++x){const uint8_t v=directUpload?frame->data[0][ptrdiff_t(y*srcH_/36)*frame->linesize[0]+x*srcW_/64]:planes[0][size_t(y*srcH_/36)*lumaPitch_+(x*srcW_/64)*(desc_.hdrInput?2:1)+(desc_.hdrInput?1:0)];sample.push_back(v);}
analyzeLuma(std::move(sample));
if(!directUpload){for (uint32_t y = 0; y < srcH_; ++y)
- std::memcpy(mappedLuma_[parity] + y * lumaPitch_, planes[0] + y * lumaPitch_, srcW_);
+ std::memcpy(mappedLuma_[parity] + y * lumaPitch_, planes[0] + y * lumaPitch_, srcW_*(desc_.hdrInput?2:1));
for (uint32_t y = 0; y < (srcH_+1) / 2; ++y)
- std::memcpy(mappedChroma_[parity] + y * chromaPitch_, planes[1] + y * chromaPitch_, ((srcW_+1)/2)*2);}
+ std::memcpy(mappedChroma_[parity] + y * chromaPitch_, planes[1] + y * chromaPitch_, ((srcW_+1)/2)*(desc_.hdrInput?4:2));}
auto copyPlane = [&](ID3D12Resource* texture, ID3D12Resource* upload,
DXGI_FORMAT format, UINT width, UINT height, UINT pitch) {
tracker_.transition(list, texture, D3D12_RESOURCE_STATE_COPY_DEST);
@@ -845,9 +849,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
src.PlacedFootprint.Footprint = {format, width, height, 1, pitch};
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
};
- copyPlane(lumaTex_.Get(), upLuma_[parity].Get(), DXGI_FORMAT_R8_UNORM,
+ copyPlane(lumaTex_.Get(), upLuma_[parity].Get(), desc_.hdrInput?DXGI_FORMAT_R16_UNORM:DXGI_FORMAT_R8_UNORM,
srcW_, srcH_, static_cast<UINT>(lumaPitch_));
- copyPlane(chromaTex_.Get(), upChroma_[parity].Get(), DXGI_FORMAT_R8G8_UNORM,
+ copyPlane(chromaTex_.Get(), upChroma_[parity].Get(), desc_.hdrInput?DXGI_FORMAT_R16G16_UNORM:DXGI_FORMAT_R8G8_UNORM,
(srcW_+1)/2, (srcH_+1)/2, static_cast<UINT>(chromaPitch_));
tracker_.transition(list, lumaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
tracker_.transition(list, chromaTex_.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
@@ -863,9 +867,9 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
list->Dispatch((srcW_+15)/16,(srcH_+15)/16,1);
}else{
const float constants[8] = { resolved.range==ColorRange::Full?0.0f:1.0f,
- resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,
- float(workingTransferCode(resolved)), 0.0f,
- uintBits(srcW_), uintBits(srcH_), 0.0f, 0.0f };
+ resolved.matrix==YuvMatrix::BT2020NCL?2.0f:resolved.matrix==YuvMatrix::BT601?0.0f:1.0f,
+ resolved.transfer==TransferFunction::PQ?4.0f:float(workingTransferCode(resolved)), (nv12Texture?nv12Texture->GetDesc().Format==DXGI_FORMAT_P010:desc_.hdrInput)?1.0f:0.0f,
+ uintBits(srcW_), uintBits(srcH_), uintBits(desc_.hdrOutput?1u:0u), 0.0f };
yuvPass_.bind(list, constants, gpuHandleOf(yuvPass_, 0).ptr, gpuHandleOf(yuvPass_, 2).ptr);
list->Dispatch((srcW_ + 15) / 16, (srcH_ + 15) / 16, 1);
}
@@ -1112,7 +1116,7 @@ bool EnhanceGraph::process(const AVFrame* frame, double ptsMs, bool reset, Frame
tracker_.transition(list, videoFrame_[parity].Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
const float constants[8] = {
uintBits(workW_), uintBits(workH_),
- uintBits(workW_), uintBits(workH_), 1, 0, 0, 0 };
+ uintBits(workW_), uintBits(workH_), desc_.hdrOutput?0.0f:1.0f, 0, 0, 0 };
blitPass_.bind(list, constants, gpuHandleOf(blitPass_, srcSlot).ptr, gpuHandleOf(blitPass_, uavSlot).ptr);
list->Dispatch((workW_ + 15) / 16, (workH_ + 15) / 16, 1);
tracker_.uavBarrier(list, videoFrame_[parity].Get());
diff --git a/src/remoteplay/AnnexB.cpp b/src/remoteplay/AnnexB.cpp
index 6056a00b..d60c3ef4 100644
--- a/src/remoteplay/AnnexB.cpp
+++ b/src/remoteplay/AnnexB.cpp
@@ -2,7 +2,7 @@
#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;
+ NalInfo out; if(codec!=Codec::H264 && codec!=Codec::H265 && codec!=Codec::H265Hdr)return out;
std::size_t pos=0;bool any=false;
while(pos+3<=b.size()) {
std::size_t prefix=0;
diff --git a/src/remoteplay/ChiakiBackend.cpp b/src/remoteplay/ChiakiBackend.cpp
index 3b6c0767..cd40a699 100644
--- a/src/remoteplay/ChiakiBackend.cpp
+++ b/src/remoteplay/ChiakiBackend.cpp
@@ -164,7 +164,7 @@ BackendResult ChiakiBackend::start(const NativeConnectRequest& request,SessionIn
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.codec=request.video.codec==Codec::H264?CHIAKI_CODEC_H264:request.video.codec==Codec::H265Hdr?CHIAKI_CODEC_H265_HDR:CHIAKI_CODEC_H265;
info.video_profile.bitrate=request.video.bitrateKbps;
info.video_profile_auto_downgrade=false;info.enable_keyboard=false;info.enable_dualsense=!request.viewOnly;
info.auto_regist=false;info.packet_loss_max=0.05;info.enable_idr_on_fec_failure=true;
diff --git a/src/remoteplay/Discovery.cpp b/src/remoteplay/Discovery.cpp
index 987fd41b..7711c3b3 100644
--- a/src/remoteplay/Discovery.cpp
+++ b/src/remoteplay/Discovery.cpp
@@ -22,7 +22,7 @@ struct DiscoveryResult {
try{std::lock_guard lock(out.mutex);out.report.hosts.clear();
for(size_t i=0;i<std::min(count,size_t(16));++i)
if(chiaki_discovery_host_is_ps5(&hosts[i])&&hosts[i].host_addr&&validHost(hosts[i].host_addr))
- out.report.hosts.push_back({hosts[i].host_addr,hosts[i].state==CHIAKI_DISCOVERY_HOST_STATE_STANDBY});
+ out.report.hosts.push_back({hosts[i].host_addr,hosts[i].state==CHIAKI_DISCOVERY_HOST_STATE_STANDBY,hosts[i].host_id?hosts[i].host_id:""});
}catch(...){/* Keep callback exceptions out of C. */}
}
};
diff --git a/src/remoteplay/ProfileStore.cpp b/src/remoteplay/ProfileStore.cpp
index 223a5457..606675fb 100644
--- a/src/remoteplay/ProfileStore.cpp
+++ b/src/remoteplay/ProfileStore.cpp
@@ -1,11 +1,51 @@
#include "veyra/remoteplay/ProfileStore.h"
#include <windows.h>
#include <wincrypt.h>
+#include <shlobj.h>
+#include <stdexcept>
#include <algorithm>
#include <cstring>
#include <fstream>
#include <vector>
namespace veyra::remoteplay {
+std::filesystem::path profileDirectory(){
+ PWSTR raw=nullptr;
+ const auto hr=SHGetKnownFolderPath(FOLDERID_LocalAppData,0,nullptr,&raw);
+ if(FAILED(hr))throw std::runtime_error("Cannot resolve Remote Play user data directory");
+ std::filesystem::path result(raw);CoTaskMemFree(raw);
+ return result/L"Veyra"/L"remoteplay";
+}
+ProfileMigration migrateProfiles(const std::filesystem::path& legacyRoot){
+ return migrateProfilesTo(legacyRoot,profileDirectory());
+}
+ProfileMigration migrateProfilesTo(const std::filesystem::path& legacyRoot,const std::filesystem::path& destination){
+ ProfileMigration report;
+ auto migrate=[&](const std::filesystem::path& source){
+ std::error_code ec;
+ if(!std::filesystem::is_regular_file(source,ec))return;
+ auto target=destination/source.filename();
+ auto marker=target;marker+=L".migrated";
+ if(std::filesystem::exists(marker,ec))return;
+ if(std::filesystem::exists(target,ec)){
+ // A previous import may have completed its atomic write before a crash.
+ if(loadProfile(target)){std::ofstream migrated(marker,std::ios::binary);migrated<<"1";if(!migrated)++report.failed;}
+ else ++report.failed;
+ return; // Never overwrite a newer profile.
+ }
+ auto value=loadProfile(source);
+ if(!value||!saveProfile(target,*value)||!loadProfile(target)){++report.failed;return;}
+ std::ofstream migrated(marker,std::ios::binary);migrated<<"1";
+ if(!migrated){++report.failed;return;}
+ ++report.imported; // Keep the original: recovery must remain possible.
+ };
+ migrate(legacyRoot/L"remoteplay-profile.dat");
+ std::error_code ec;unsigned scanned=0;
+ for(std::filesystem::directory_iterator it(legacyRoot/L"remoteplay",ec),end;!ec&&it!=end&&scanned<256;it.increment(ec),++scanned){
+ auto id=it->path().stem().wstring();
+ if(it->path().extension()==L".dat"&&id.size()==32&&std::all_of(id.begin(),id.end(),[](wchar_t c){return(c>=L'0'&&c<=L'9')||(c>=L'a'&&c<=L'f');}))migrate(it->path());
+ }
+ return report;
+}
namespace {
struct SecretBytes {std::vector<uint8_t> data;~SecretBytes(){SecureZeroMemory(data.data(),data.size());}};
struct ProtectedBlob {DATA_BLOB value{};~ProtectedBlob(){if(value.pbData){SecureZeroMemory(value.pbData,value.cbData);LocalFree(value.pbData);}}};
@@ -14,14 +54,18 @@ uint32_t read32(const uint8_t* p){return uint32_t(p[0])|(uint32_t(p[1])<<8)|(uin
}
bool saveProfile(const std::filesystem::path& path,const NativeConnectRequest& request){
if(!validHost(request.host)||request.video.validate())return false;
+ if(!request.consoleId.empty()&&(request.consoleId.size()!=12||!std::all_of(request.consoleId.begin(),request.consoleId.end(),[](char c){return(c>='0'&&c<='9')||(c>='a'&&c<='f');})))return false;
SecretBytes plain;
- auto& b=plain.data;b.insert(b.end(),{'V','R','P',1});
+ auto& b=plain.data;b.insert(b.end(),{'V','R','P',2});
append32(b,uint32_t(request.host.size()));append32(b,request.video.width);append32(b,request.video.height);
append32(b,request.video.fps);append32(b,request.video.bitrateKbps);append32(b,uint32_t(request.video.codec));
b.insert(b.end(),request.credentials.accountId.begin(),request.credentials.accountId.end());
b.insert(b.end(),request.credentials.registrationKey.begin(),request.credentials.registrationKey.end());
b.insert(b.end(),request.credentials.sessionKey.begin(),request.credentials.sessionKey.end());
b.insert(b.end(),request.host.begin(),request.host.end());
+ b.push_back(request.viewOnly?1:0);
+ b.push_back(uint8_t(request.consoleId.size()));
+ b.insert(b.end(),request.consoleId.begin(),request.consoleId.end());
DATA_BLOB input{DWORD(b.size()),b.data()};ProtectedBlob encrypted;
if(!CryptProtectData(&input,L"Veyra PS5 pairing",nullptr,nullptr,nullptr,CRYPTPROTECT_UI_FORBIDDEN,&encrypted.value))return false;
std::error_code ec;std::filesystem::create_directories(path.parent_path(),ec);if(ec)return false;
@@ -33,23 +77,32 @@ bool saveProfile(const std::filesystem::path& path,const NativeConnectRequest& r
if(ok)ok=MoveFileExW(temp.c_str(),path.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)!=FALSE;
if(!ok)DeleteFileW(temp.c_str());return ok;
}
-std::optional<NativeConnectRequest> loadProfile(const std::filesystem::path& path){
- std::ifstream f(path,std::ios::binary|std::ios::ate);if(!f)return {};
+std::optional<NativeConnectRequest> loadProfile(const std::filesystem::path& path,ProfileLoadError* error){
+ if(error)*error=ProfileLoadError::Read;
+ std::ifstream f(path,std::ios::binary|std::ios::ate);if(!f){std::error_code ec;if(error&&!std::filesystem::exists(path,ec)&&!ec)*error=ProfileLoadError::Missing;return {};}
const auto size=f.tellg();if(size<=0||size>8192)return {};
std::vector<uint8_t> encrypted(static_cast<size_t>(size));f.seekg(0);if(!f.read(reinterpret_cast<char*>(encrypted.data()),size))return {};
DATA_BLOB input{DWORD(encrypted.size()),encrypted.data()};ProtectedBlob plain;
- if(!CryptUnprotectData(&input,nullptr,nullptr,nullptr,nullptr,CRYPTPROTECT_UI_FORBIDDEN,&plain.value))return {};
+ if(!CryptUnprotectData(&input,nullptr,nullptr,nullptr,nullptr,CRYPTPROTECT_UI_FORBIDDEN,&plain.value)){if(error)*error=ProfileLoadError::Decrypt;return {};}
+ if(error)*error=ProfileLoadError::Format;
const auto* p=plain.value.pbData;const auto n=plain.value.cbData;
constexpr size_t header=28,credentials=40;
- if(n<header+credentials||std::memcmp(p,"VRP\1",4)!=0)return {};
+ if(n<header+credentials||std::memcmp(p,"VRP",3)!=0||(p[3]!=1&&p[3]!=2))return {};
const auto hostSize=read32(p+4);
- if(hostSize>253||n!=header+credentials+hostSize||read32(p+24)>1)return {};
+ const size_t base=header+credentials+hostSize;
+ if(hostSize>253||n<base||read32(p+24)>2)return {};
+ if(p[3]==1&&n!=base)return {};
+ if(p[3]==2&&(n<base+2||p[base]>1||(p[base+1]!=0&&p[base+1]!=12)||n!=base+2+p[base+1]))return {};
NativeConnectRequest r;r.video.width=read32(p+8);r.video.height=read32(p+12);r.video.fps=read32(p+16);
r.video.bitrateKbps=read32(p+20);r.video.codec=Codec(read32(p+24));
std::memcpy(r.credentials.accountId.data(),p+header,8);std::memcpy(r.credentials.registrationKey.data(),p+header+8,16);
std::memcpy(r.credentials.sessionKey.data(),p+header+24,16);
r.host.assign(reinterpret_cast<const char*>(p+header+credentials),hostSize);
+ if(p[3]==2){
+ r.viewOnly=p[base]!=0;r.consoleId.assign(reinterpret_cast<const char*>(p+base+2),p[base+1]);
+ if(!std::all_of(r.consoleId.begin(),r.consoleId.end(),[](char c){return(c>='0'&&c<='9')||(c>='a'&&c<='f');}))return {};
+ }
if(!validHost(r.host)||r.video.validate())return {};
- return r;
+ if(error)*error=ProfileLoadError::None;return r;
}
}
diff --git a/src/remoteplay/PsnAuth.cpp b/src/remoteplay/PsnAuth.cpp
new file mode 100644
index 00000000..579660cc
--- /dev/null
+++ b/src/remoteplay/PsnAuth.cpp
@@ -0,0 +1,109 @@
+// OAuth request contract adapted from chiaki-ng (AGPL-3.0-only + OpenSSL exception),
+// gui/src/psnaccountid.cpp and psntoken.cpp, pinned 0e16950165f06e5c3291537c2eeba6e852be7120.
+#include "veyra/remoteplay/PsnAuth.h"
+#include "veyra/remoteplay/ProfileStore.h"
+#include <windows.h>
+#include <winhttp.h>
+#include <wincrypt.h>
+#include <json-c/json.h>
+#include <chrono>
+#include <fstream>
+#include <memory>
+namespace veyra::remoteplay {
+namespace {
+constexpr auto scope="psn:clientapp referenceDataService:countryConfig.read pushNotification:webSocket.desktop.connect sessionManager:remotePlaySession.system.update";
+constexpr auto redirect="https://remoteplay.dl.playstation.net/remoteplay/redirect";
+constexpr auto client="ba495a24-818c-472b-b12d-ff231c1b5745";
+// Public upstream client identifier pair, not a user's credential.
+constexpr auto clientPair="ba495a24-818c-472b-b12d-ff231c1b5745:mvaiZkRsAsI1IBkY";
+void wipe(std::string& s){if(!s.empty())SecureZeroMemory(s.data(),s.size());}
+struct Secret {std::string value;~Secret(){wipe(value);}};
+struct Handle {HINTERNET h=nullptr;~Handle(){if(h)WinHttpCloseHandle(h);}};
+struct Blob {DATA_BLOB b{};~Blob(){if(b.pbData){SecureZeroMemory(b.pbData,b.cbData);LocalFree(b.pbData);}}};
+struct AuthorizationLock {
+ HANDLE h=CreateMutexW(nullptr,FALSE,L"Local\\Veyra.PsnAuthorization");bool acquired=false;
+ AuthorizationLock(){if(h){auto result=WaitForSingleObject(h,0);acquired=result==WAIT_OBJECT_0||result==WAIT_ABANDONED;}}
+ ~AuthorizationLock(){if(h){if(acquired)ReleaseMutex(h);CloseHandle(h);}}
+};
+using Json=std::unique_ptr<json_object,decltype(&json_object_put)>;
+std::string field(json_object* o,const char* name){json_object* v=nullptr;return json_object_object_get_ex(o,name,&v)&&json_object_is_type(v,json_type_string)?json_object_get_string(v):"";}
+std::string encode(std::string_view value){std::string out;constexpr char hex[]="0123456789ABCDEF";for(unsigned char c:value){if((c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9')||c=='-'||c=='_'||c=='.'||c=='~')out+=c;else{out+='%';out+=hex[c>>4];out+=hex[c&15];}}return out;}
+std::wstring wide(std::string_view s){return {s.begin(),s.end()};}
+int64_t now(){return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();}
+std::optional<std::string> callbackCode(std::wstring_view input){
+ const std::wstring prefix=wide(redirect)+L"?";
+ if(input.size()>8192||!input.starts_with(prefix)||input.find(L'#')!=input.npos)return {};
+ std::string code;unsigned codes=0;
+ for(auto query=input.substr(prefix.size());!query.empty();){
+ auto end=query.find(L'&');auto item=query.substr(0,end);auto equals=item.find(L'=');
+ if(item.substr(0,equals)==L"code"&&equals!=item.npos){
+ if(++codes!=1)return {};auto value=item.substr(equals+1);
+ for(size_t i=0;i<value.size();++i){auto c=value[i];if(c==L'%'){
+ if(i+2>=value.size())return {};auto hex=[](wchar_t v){return v>=L'0'&&v<=L'9'?int(v-L'0'):v>=L'a'&&v<=L'f'?int(v-L'a'+10):v>=L'A'&&v<=L'F'?int(v-L'A'+10):-1;};
+ auto a=hex(value[++i]),b=hex(value[++i]);if(a<0||b<0)return {};c=wchar_t(a*16+b);
+ }if(c<33||c>126)return {};code+=char(c);}
+ }
+ if(end==query.npos)break;query.remove_prefix(end+1);
+ }
+ if(codes!=1||code.empty()||code.size()>2048)return {};return code;
+}
+unsigned request(std::wstring path,std::string_view body,bool post,Secret& output,std::stop_token stop){
+ if(stop.stop_requested())return ERROR_CANCELLED;
+ Handle session{WinHttpOpen(L"Veyra Remote Play",WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0)};
+ if(!session.h)return GetLastError();WinHttpSetTimeouts(session.h,5000,5000,10000,10000);
+ Handle connection{WinHttpConnect(session.h,L"auth.api.sonyentertainmentnetwork.com",INTERNET_DEFAULT_HTTPS_PORT,0)};
+ if(!connection.h)return GetLastError();
+ Handle req{WinHttpOpenRequest(connection.h,post?L"POST":L"GET",path.c_str(),nullptr,WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,WINHTTP_FLAG_SECURE)};
+ if(!req.h)return GetLastError();DWORD disabled=WINHTTP_DISABLE_REDIRECTS;WinHttpSetOption(req.h,WINHTTP_OPTION_DISABLE_FEATURE,&disabled,sizeof(disabled));
+ DWORD size=0;CryptBinaryToStringA(reinterpret_cast<const BYTE*>(clientPair),DWORD(strlen(clientPair)),CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF,nullptr,&size);
+ std::string basic(size,'\0');CryptBinaryToStringA(reinterpret_cast<const BYTE*>(clientPair),DWORD(strlen(clientPair)),CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF,basic.data(),&size);basic.resize(strlen(basic.c_str()));
+ auto headers=L"Content-Type: application/x-www-form-urlencoded\r\nAuthorization: Basic "+wide(basic)+L"\r\n";
+ if(!WinHttpSendRequest(req.h,headers.c_str(),DWORD(-1),post?const_cast<char*>(body.data()):nullptr,post?DWORD(body.size()):0,post?DWORD(body.size()):0,0)||!WinHttpReceiveResponse(req.h,nullptr))return GetLastError();
+ DWORD status=0,len=sizeof(status);if(!WinHttpQueryHeaders(req.h,WINHTTP_QUERY_STATUS_CODE|WINHTTP_QUERY_FLAG_NUMBER,WINHTTP_HEADER_NAME_BY_INDEX,&status,&len,WINHTTP_NO_HEADER_INDEX))return GetLastError();
+ if(status!=200)return status;
+ char bytes[4096];DWORD read=0;
+ do{if(stop.stop_requested())return ERROR_CANCELLED;if(!WinHttpReadData(req.h,bytes,sizeof(bytes),&read))return GetLastError();output.value.append(bytes,read);SecureZeroMemory(bytes,sizeof(bytes));if(output.value.size()>65536)return ERROR_BUFFER_OVERFLOW;}while(read);
+ return 0;
+}
+bool save(const PsnAuthorization& auth){
+ Secret plain;plain.value=std::to_string(auth.expiresAt)+"\n"+accountIdToBase64(auth.accountId)+"\n"+auth.accessToken+"\n"+auth.refreshToken;
+ DATA_BLOB input{DWORD(plain.value.size()),reinterpret_cast<BYTE*>(plain.value.data())};Blob encrypted;
+ if(!CryptProtectData(&input,L"Veyra PSN authorization",nullptr,nullptr,nullptr,CRYPTPROTECT_UI_FORBIDDEN,&encrypted.b))return false;
+ auto path=profileDirectory()/L"psn.auth",tmp=path;tmp+=L"."+std::to_wstring(GetCurrentProcessId())+L"."+std::to_wstring(GetTickCount64())+L".tmp";
+ std::error_code ec;std::filesystem::create_directories(path.parent_path(),ec);if(ec)return false;
+ std::ofstream out(tmp,std::ios::binary|std::ios::trunc);out.write(reinterpret_cast<const char*>(encrypted.b.pbData),encrypted.b.cbData);out.close();
+ if(!out||!MoveFileExW(tmp.c_str(),path.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH)){DeleteFileW(tmp.c_str());return false;}return true;
+}
+PsnResult exchange(std::string grant,std::stop_token stop,std::optional<AccountId> knownAccount={}){
+ AuthorizationLock lock;if(!lock.acquired)return {false,ERROR_BUSY};
+ Secret body;body.value=std::move(grant)+"&scope="+encode(scope)+"&redirect_uri="+encode(redirect);
+ Secret response;auto error=request(L"/2.0/oauth/token",body.value,true,response,stop);if(error)return {false,error};
+ Json json(json_tokener_parse(response.value.c_str()),json_object_put);if(!json)return {false,ERROR_INVALID_DATA};
+ PsnAuthorization auth;auth.accessToken=field(json.get(),"access_token");auth.refreshToken=field(json.get(),"refresh_token");
+ json_object* expires=nullptr;if(!json_object_object_get_ex(json.get(),"expires_in",&expires)||!json_object_is_type(expires,json_type_int))return {false,ERROR_INVALID_DATA};
+ const auto duration=json_object_get_int64(expires);
+ if(auth.accessToken.empty()||auth.refreshToken.empty()||auth.accessToken.size()>8192||auth.refreshToken.size()>8192||duration<1||duration>31536000)return {false,ERROR_INVALID_DATA};
+ if(auth.accessToken.find_first_of("\r\n")!=auth.accessToken.npos||auth.refreshToken.find_first_of("\r\n")!=auth.refreshToken.npos)return {false,ERROR_INVALID_DATA};
+ auth.expiresAt=now()+duration;
+ if(knownAccount){auth.accountId=*knownAccount;if(stop.stop_requested())return {false,ERROR_CANCELLED};return save(auth)?PsnResult{true,0,knownAccount}:PsnResult{false,ERROR_WRITE_FAULT};}
+ Secret account;error=request(L"/2.0/oauth/token/"+wide(encode(auth.accessToken)),{},false,account,stop);if(error)return {false,error};
+ Json details(json_tokener_parse(account.value.c_str()),json_object_put);if(!details)return {false,ERROR_INVALID_DATA};
+ auto id=accountIdFromDecimal(field(details.get(),"user_id"));if(!id)return {false,ERROR_INVALID_DATA};auth.accountId=*id;
+ if(stop.stop_requested())return {false,ERROR_CANCELLED};if(!save(auth))return {false,ERROR_WRITE_FAULT};return {true,0,id};
+}
+}
+PsnAuthorization::~PsnAuthorization(){wipe(accessToken);wipe(refreshToken);}
+std::wstring psnLoginUrl(){return L"https://auth.api.sonyentertainmentnetwork.com/2.0/oauth/authorize?service_entity=urn:service-entity:psn&response_type=code&client_id="+wide(client)+L"&redirect_uri="+wide(encode(redirect))+L"&scope="+wide(encode(scope))+L"&request_locale=zh_CN&ui=pr&service_logo=ps&layout_type=popup&smcid=remoteplay&prompt=always&PlatformPrivacyWs1=minimal";}
+bool validPsnCallback(std::wstring_view callback){return callbackCode(callback).has_value();}
+PsnResult authorizePsn(std::wstring callback,std::stop_token stop){auto code=callbackCode(callback);SecureZeroMemory(callback.data(),callback.size()*sizeof(wchar_t));if(!code)return {false,ERROR_INVALID_PARAMETER};Secret grant;grant.value="grant_type=authorization_code&code="+encode(*code);wipe(*code);return exchange(std::move(grant.value),stop);}
+std::optional<PsnAuthorization> loadPsnAuthorization(){
+ std::ifstream in(profileDirectory()/L"psn.auth",std::ios::binary|std::ios::ate);if(!in)return {};auto size=in.tellg();if(size<=0||size>65536)return {};std::string bytes(size_t(size),'\0');in.seekg(0);if(!in.read(bytes.data(),size))return {};
+ DATA_BLOB input{DWORD(bytes.size()),reinterpret_cast<BYTE*>(bytes.data())};Blob plain;if(!CryptUnprotectData(&input,nullptr,nullptr,nullptr,nullptr,CRYPTPROTECT_UI_FORBIDDEN,&plain.b))return {};
+ Secret value;value.value.assign(reinterpret_cast<const char*>(plain.b.pbData),plain.b.cbData);size_t a=value.value.find('\n'),b=value.value.find('\n',a+1),c=value.value.find('\n',b+1);
+ if(a==value.value.npos||b==value.value.npos||c==value.value.npos)return {};
+ PsnAuthorization auth;try{auth.expiresAt=std::stoll(value.value.substr(0,a));}catch(...){return {};}
+ auto id=accountIdFromBase64(value.value.substr(a+1,b-a-1));if(!id)return {};auth.accountId=*id;auth.accessToken=value.value.substr(b+1,c-b-1);auth.refreshToken=value.value.substr(c+1);if(auth.accessToken.empty()||auth.refreshToken.empty())return {};return auth;
+}
+PsnResult refreshPsn(std::stop_token stop){auto saved=loadPsnAuthorization();if(!saved)return {false,ERROR_NOT_FOUND};if(saved->expiresAt>now()+120)return {true,0,saved->accountId};return exchange("grant_type=refresh_token&refresh_token="+encode(saved->refreshToken),stop,saved->accountId);}
+bool forgetPsnAuthorization(){AuthorizationLock lock;if(!lock.acquired)return false;std::error_code ec;auto path=profileDirectory()/L"psn.auth";return !std::filesystem::exists(path,ec)||std::filesystem::remove(path,ec);}
+}
diff --git a/src/remoteplay/Validation.cpp b/src/remoteplay/Validation.cpp
index 5cdabf00..a331b030 100644
--- a/src/remoteplay/Validation.cpp
+++ b/src/remoteplay/Validation.cpp
@@ -13,10 +13,10 @@ HostTime monotonic100ns() noexcept {
}
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";
+ return "Only 720p/1080p 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";
+ if (codec!=Codec::H264 && codec!=Codec::H265 && codec!=Codec::H265Hdr) return "Unsupported codec";
return {};
}
namespace {
diff --git a/src/source/RemotePlaySource.cpp b/src/source/RemotePlaySource.cpp
index cc305ed8..ac639329 100644
--- a/src/source/RemotePlaySource.cpp
+++ b/src/source/RemotePlaySource.cpp
@@ -43,11 +43,11 @@ pipeline::SourcePixelFormat pixelFormatFromFrame(const AVFrame& frame)
{
if(frame.format==AV_PIX_FMT_D3D12&&frame.hw_frames_ctx){
const auto* context=reinterpret_cast<const AVHWFramesContext*>(frame.hw_frames_ctx->data);
- return context->sw_format==AV_PIX_FMT_NV12?pipeline::SourcePixelFormat::NV12:pipeline::SourcePixelFormat::Unknown;
+ return context->sw_format==AV_PIX_FMT_NV12?pipeline::SourcePixelFormat::NV12:context->sw_format==AV_PIX_FMT_P010?pipeline::SourcePixelFormat::P010:pipeline::SourcePixelFormat::Unknown;
}
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_YUV420P10LE: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;
@@ -131,6 +131,10 @@ bool RemotePlaySource::connect(const RemotePlayConnectDesc& desc)
info_.color.transferAssumed = true;
info_.color.primaries = pipeline::ColorPrimaries::BT709;
info_.color.primariesAssumed = true;
+ if(request_.video.codec==remoteplay::Codec::H265Hdr){
+ info_.color.pixelFormat=pipeline::SourcePixelFormat::P010;info_.color.matrix=pipeline::YuvMatrix::BT2020NCL;
+ info_.color.transfer=pipeline::TransferFunction::PQ;info_.color.primaries=pipeline::ColorPrimaries::BT2020;info_.color.displayReferred709=true;
+ }
clock_.reset(static_cast<remoteplay::HostTime>(origin100ns_), request_.video.fps);
sequence_ = 0;
fallbackSourceIndex_ = 0;
@@ -279,12 +283,19 @@ bool RemotePlaySource::drainDecoder(std::uint64_t sourceIndex, const pipeline::F
pipeline::FramePacket packet = stamp->packet;
packetStamps_.erase(stamp);
packet.sequence = ++sequence_;
- packet.colorInfo = pipeline::resolveFrameColor(*decoderFrame_, info_.color);
+ auto fallback=info_.color;
+ if(request_.video.codec==remoteplay::Codec::H265Hdr&&pixelFormatFromFrame(*decoderFrame_)!=pipeline::SourcePixelFormat::P010){
+ // A negotiated 8-bit fallback is not automatically a PQ signal.
+ fallback.transfer=pipeline::TransferFunction::BT709;fallback.transferAssumed=true;
+ fallback.matrix=pipeline::YuvMatrix::BT709;fallback.matrixAssumed=true;
+ fallback.primaries=pipeline::ColorPrimaries::BT709;fallback.primariesAssumed=true;
+ }
+ packet.colorInfo = pipeline::resolveFrameColor(*decoderFrame_, fallback);
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;
+ (packet.colorInfo.isHdrPath()&&request_.video.codec!=remoteplay::Codec::H265Hdr)) 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);
@@ -381,7 +392,11 @@ SourceReadStatus RemotePlaySource::read(pipeline::FramePacket& out, const AVFram
if (queued->resetDecoder) {
flushDecoder();
++decoderEpoch_;
- clock_.reset(static_cast<remoteplay::HostTime>(origin100ns_), request_.video.fps);
+ if(request_.video.codec==remoteplay::Codec::H265Hdr){
+ info_.color.pixelFormat=pipeline::SourcePixelFormat::P010;info_.color.matrix=pipeline::YuvMatrix::BT2020NCL;
+ info_.color.transfer=pipeline::TransferFunction::PQ;info_.color.primaries=pipeline::ColorPrimaries::BT2020;info_.color.displayReferred709=true;
+ }
+ clock_.reset(static_cast<remoteplay::HostTime>(origin100ns_), request_.video.fps);
pendingOpenFlag_ = true;
}
const auto extended = sample.wireFrameIndex ? wireSequence_.observe(*sample.wireFrameIndex)
diff --git a/tests/integration/HdrColorTests.cpp b/tests/integration/HdrColorTests.cpp
new file mode 100644
index 00000000..9bc2797e
--- /dev/null
+++ b/tests/integration/HdrColorTests.cpp
@@ -0,0 +1,75 @@
+#include "veyra/pipeline/ColorMetadata.h"
+#include "veyra/pipeline/EnhanceGraph.h"
+#include "veyra/gfx/D3D12DeviceContext.h"
+#include "veyra/gfx/CommandSlotRing.h"
+#include "veyra/sink/ImageExportSink.h"
+#include <DirectXPackedVector.h>
+#include "veyra/engine/VideoPresenter.h"
+#include "veyra/source/MediaFileSource.h"
+#include "veyra/RuntimePaths.h"
+#include <iostream>
+#include <cmath>
+extern "C" {
+#include <libavutil/frame.h>
+}
+using namespace veyra;
+int wmain(int argc,wchar_t** argv){
+ CoInitializeEx(nullptr,COINIT_MULTITHREADED);
+ gfx::D3D12DeviceContext ctx;gfx::CommandSlotRing ring;Status st;gfx::DeviceContextDesc dd;
+ if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 2;
+ int failures=0;
+ for(bool native:{false,true})for(bool planar:{false,true})for(bool full:{false,true}){
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;
+ gd.sourceWidth=gd.workWidth=64;gd.sourceHeight=gd.workHeight=32;gd.enableNr=gd.enableFg=gd.enableSr=false;gd.noFeatures=true;gd.hdrInput=true;gd.hdrOutput=native;
+ if(!graph.initialize(gd)||!graph.createViews())return 3;
+ AVFrame* f=av_frame_alloc();f->width=64;f->height=32;f->format=planar?AV_PIX_FMT_YUV420P10LE:AV_PIX_FMT_P010;f->color_range=full?AVCOL_RANGE_JPEG:AVCOL_RANGE_MPEG;f->colorspace=AVCOL_SPC_BT2020_NCL;f->color_trc=AVCOL_TRC_SMPTE2084;f->color_primaries=AVCOL_PRI_BT2020;
+ if(av_frame_get_buffer(f,32)<0)return 4;
+ // Published ST2084 reference encodings: black, 100 cd/m2, 1000 cd/m2.
+ constexpr double encoded[]={0,.5080784215,.7518270962};constexpr double nits[]={0,100,1000};
+ for(unsigned y=0;y<32;++y)for(unsigned x=0;x<64;++x){auto code=uint16_t(std::lround((full?0:64)+encoded[std::min(x/22,2u)]*(full?1023:876)));reinterpret_cast<uint16_t*>(f->data[0]+y*f->linesize[0])[x]=planar?code:uint16_t(code<<6);}
+ for(unsigned y=0;y<16;++y)for(unsigned x=0;x<(planar?32u:64u);++x)reinterpret_cast<uint16_t*>(f->data[1]+y*f->linesize[1])[x]=planar?512:32768;
+ if(planar)for(unsigned y=0;y<16;++y)for(unsigned x=0;x<32;++x)reinterpret_cast<uint16_t*>(f->data[2]+y*f->linesize[2])[x]=512;
+ pipeline::ColorDescription color;color.pixelFormat=pipeline::SourcePixelFormat::P010;color.transfer=pipeline::TransferFunction::PQ;color.matrix=pipeline::YuvMatrix::BT2020NCL;
+ pipeline::EnhanceGraph::FrameOutputs out;bool ok=graph.process(f,0,true,out,1,&color);double error=0;
+ if(ok&&!native){sink::RgbaImage image;ok=sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image);if(ok){for(unsigned i=0;i<3;++i){double l=nits[i]/203.0,p=1000.0/203.0,m=std::clamp(l*(1+l/(p*p))/(1+l),0.0,1.0);double expected=m<=.0031308?12.92*m:1.055*pow(m,1/2.4)-.055;double actual=image.pixels[(i*22+5)*4]/255.0;error=std::max(error,std::abs(expected-actual));}ok=error<.012;}}
+ if(ok&&native){
+ auto* texture=graph.videoFrameResource(out.videoSlot);auto desc=texture->GetDesc();D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};UINT64 size=0;ctx.device()->GetCopyableFootprints(&desc,0,1,0,&footprint,nullptr,nullptr,&size);
+ D3D12_HEAP_PROPERTIES hp{};hp.Type=D3D12_HEAP_TYPE_READBACK;D3D12_RESOURCE_DESC bd{};bd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER;bd.Width=size;bd.Height=1;bd.DepthOrArraySize=1;bd.MipLevels=1;bd.SampleDesc.Count=1;bd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ Microsoft::WRL::ComPtr<ID3D12Resource> read;if(FAILED(ctx.device()->CreateCommittedResource(&hp,D3D12_HEAP_FLAG_NONE,&bd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&read))))return 5;
+ uint32_t slot;auto* list=ring.acquireNext(slot,st);pipeline::StateTracker states;states.transition(list,texture,D3D12_RESOURCE_STATE_COPY_SOURCE);
+ D3D12_TEXTURE_COPY_LOCATION a{},b{};a.pResource=texture;a.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;b.pResource=read.Get();b.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;b.PlacedFootprint=footprint;list->CopyTextureRegion(&b,0,0,0,&a,nullptr);states.transition(list,texture,D3D12_RESOURCE_STATE_COMMON);
+ if(!ring.submitAndSignal(slot)||!ring.waitIdle())return 6;void* ptr=nullptr;D3D12_RANGE range{0,size};if(FAILED(read->Map(0,&range,&ptr)))return 7;
+ const auto* values=reinterpret_cast<uint16_t*>(static_cast<uint8_t*>(ptr)+footprint.Offset);
+ for(unsigned i=0;i<3;++i){auto actual=DirectX::PackedVector::XMConvertHalfToFloat(values[(i*22+5)*4]);error=std::max(error,std::abs(actual-nits[i]/80));}D3D12_RANGE written{};read->Unmap(0,&written);ok=error<.12;
+ }
+ if(ok){
+ HWND window=CreateWindowExW(0,L"STATIC",L"HDR contract",WS_POPUP,0,0,64,32,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
+ engine::VideoPresenter presenter;ok=window&&presenter.open(ctx,window,graph)&&presenter.present(ctx,ring,graph,out.videoSlot,false);
+ ring.drainQueue();presenter.close();if(window)DestroyWindow(window);
+ }
+ std::cout<<"HDR_COLOR native="<<native<<" planar="<<planar<<" full="<<full<<" error="<<error<<" pass="<<ok<<std::endl;if(!ok)++failures;
+ out={};ring.drainQueue();graph.shutdown();av_frame_free(&f);
+ }
+ if(argc>1)for(unsigned mode=0;mode<3;++mode)for(bool hardware:{false,true}){
+ source::MediaFileSource source;source::SourceOpenDesc sd;sd.path=argv[1];sd.preferHardwareDecode=hardware;sd.d3d12Device=ctx.device();sd.d3d12Queue=ctx.directQueue();
+ if(!source.open(sd))return 8;
+ pipeline::EnhanceGraph graph(ctx,ring);pipeline::EnhanceGraphDesc gd;gd.sourceWidth=gd.workWidth=source.info().width;gd.sourceHeight=gd.workHeight=source.info().height;
+ gd.hdrInput=true;gd.enableNr=true;gd.enableSr=mode>0;gd.enableFg=mode>0;gd.videoSrQuality=mode?1:0;gd.nrBeforeSr=mode==2;
+ if(mode){gd.workWidth=3840;gd.workHeight=2160;}
+ if(mode==2){gd.nrWidth=gd.sourceWidth;gd.nrHeight=gd.sourceHeight;}gd.runtimeAbsPath=runtime::localRuntimeDirectory().wstring();
+ if(!graph.initialize(gd)||!graph.createViews())return 9;unsigned count=0,generated=0;bool confirmed=false;
+ while(count<12){pipeline::FramePacket packet;const AVFrame* f=nullptr;auto result=source.read(packet,&f);if(result==source::SourceReadStatus::Waiting)continue;if(result!=source::SourceReadStatus::Frame)break;
+ confirmed|=f->format==AV_PIX_FMT_D3D12;
+ pipeline::EnhanceGraph::FrameOutputs out;
+ if(!graph.process(f,count*1000.0/30,count==0,out,count+1,&packet.colorInfo))return 10;
+ sink::RgbaImage image;if(!sink::readRgba8(ctx,ring,graph.videoFrameResource(out.videoSlot),image))return 11;
+ if(std::none_of(image.pixels.begin(),image.pixels.end(),[](uint8_t v){return v>0&&v<255;}))return 12;
+ if(mode){if(!graph.resolveGeneration(out))return 13;if(out.hasGenerated){sink::RgbaImage middle;if(!sink::readRgba8(ctx,ring,graph.generatedFrameResource(out.genSlot),middle))return 14;++generated;}}
+ out={};++count;
+ }
+ bool ok=count==12&&confirmed==hardware&&graph.metrics().nrEvaluateCount==12&&(!mode||(graph.metrics().srEvaluateCount==12&&generated>0));
+ std::cout<<"HDR_MAIN10_NR mode="<<mode<<" sr="<<graph.metrics().srEvaluateCount<<" generated="<<generated<<" hardware="<<hardware<<" confirmed="<<confirmed<<" frames="<<count<<" evaluate="<<graph.metrics().nrEvaluateCount<<" pass="<<ok<<std::endl;if(!ok)++failures;
+ ring.drainQueue();graph.shutdown();source.close();
+ }
+ ring.shutdown();ctx.shutdown();CoUninitialize();return failures?1:0;
+}
diff --git a/tests/remoteplay/ProfileStoreTests.cpp b/tests/remoteplay/ProfileStoreTests.cpp
index d214d091..552bb1df 100644
--- a/tests/remoteplay/ProfileStoreTests.cpp
+++ b/tests/remoteplay/ProfileStoreTests.cpp
@@ -1,4 +1,5 @@
#include "veyra/remoteplay/ProfileStore.h"
+#include "veyra/remoteplay/PsnAuth.h"
#include <windows.h>
#include <fstream>
#include <iostream>
@@ -10,11 +11,30 @@ int main(){
struct Cleanup {std::filesystem::path p;~Cleanup(){std::error_code ec;std::filesystem::remove(p,ec);}} cleanup{path};
auto require=[](bool ok){if(!ok)throw std::runtime_error("DPAPI profile test failed");};
try{
+ require(validPsnCallback(L"https://remoteplay.dl.playstation.net/remoteplay/redirect?code=test%2Bcode"));
+ require(!validPsnCallback(L"https://evil.invalid/remoteplay/redirect?code=test"));
+ require(!validPsnCallback(L"https://remoteplay.dl.playstation.net/remoteplay/redirect?code=a&code=b"));
+ require(!validPsnCallback(L"https://remoteplay.dl.playstation.net/remoteplay/redirect?code=%00"));
+ require(!validPsnCallback(L"https://remoteplay.dl.playstation.net/remoteplay/redirect?error=denied"));
NativeConnectRequest request;request.host="127.0.0.1";request.video.codec=Codec::H265;
+ request.consoleId="012345abcdef";request.viewOnly=true;
request.credentials.accountId.fill(7);request.credentials.registrationKey.fill('1');request.credentials.sessionKey.fill(42);
require(saveProfile(path,request));auto saved=loadProfile(path);require(saved.has_value());
+ require(saved->consoleId==request.consoleId&&saved->viewOnly);
+ require(profileDirectory().is_absolute());
require(saved->host==request.host&&saved->video.codec==Codec::H265&&saved->credentials.accountId==request.credentials.accountId&&saved->credentials.sessionKey==request.credentials.sessionKey&&saved->credentials.registrationKey==request.credentials.registrationKey);
request.video.fps=30;require(saveProfile(path,request));require(loadProfile(path)->video.fps==30);
+ const auto root=path.parent_path()/(path.stem().wstring()+L"-migration");
+ struct TreeCleanup {std::filesystem::path p;~TreeCleanup(){std::error_code ec;std::filesystem::remove_all(p,ec);}} tree{root};
+ const auto legacy=root/L"legacy",dest=root/L"new";
+ const auto name=L"0123456789abcdef0123456789abcdef.dat";
+ require(saveProfile(legacy/L"remoteplay"/name,request));
+ auto migrated=migrateProfilesTo(legacy,dest);require(migrated.imported==1&&migrated.failed==0);
+ require(loadProfile(dest/name).has_value());
+ require(migrateProfilesTo(legacy,dest).imported==0);
+ std::filesystem::remove(dest/name);
+ require(migrateProfilesTo(legacy,dest).imported==0&&!std::filesystem::exists(dest/name));
+ require(std::filesystem::exists(legacy/L"remoteplay"/name));
{std::fstream file(path,std::ios::binary|std::ios::in|std::ios::out);char byte=0;file.read(&byte,1);byte^=0x40;file.seekp(0);file.write(&byte,1);}
require(!loadProfile(path));request.host="http://invalid";require(!saveProfile(path,request));
std::cout<<"DPAPI_PROFILE_PASS roundtrip=1 atomic_replace=1 corrupted_rejected=1 invalid_host_rejected=1 synthetic_credentials_only=1\n";