Repository navigation
Expand file tree
/
Copy pathmedia.cpp
More file actions
302 lines (299 loc) · 16 KB
/
Copy pathmedia.cpp
File metadata and controls
302 lines (299 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#include "veyra/engine/EngineController.h"
#include "veyra/remoteplay/ProfileStore.h"
#include "veyra/remoteplay/ControllerInput.h"
#include "veyra/remoteplay/Discovery.h"
#include "veyra/source/RemotePlaySource.h"
#include <format>
#include "veyra/Log.h"
#include <chiaki/regist.h>
#include <chiaki/log.h>
#include <CommCtrl.h>
#include <atomic>
using namespace veyra;
#define API extern "C" __declspec(dllexport)
#include "cadence.h"
struct Player {
HWND parent, video, panel=nullptr;
ULONGLONG lastSample=0;
uint64_t loginPinRequest=0;
bool panelWanted=false, panelToast=false;
int panelTop=0, panelBottom=0;
engine::EngineController engine;
engine::EnhancementSettings quality;
remoteplay::ControllerInput pad;
bool padStarted=false, externalFg=false, detached=false;
explicit Player(HWND window):parent(window),video(CreateWindowExW(0,L"STATIC",nullptr,
WS_CHILD|WS_CLIPSIBLINGS,0,0,1,1,window,nullptr,GetModuleHandleW(nullptr),nullptr)) {}
~Player(){portal_cancel_measure();engine.stop();pad.stop();if(video)DestroyWindow(video);}
};
API Player* portal_new(HWND window,const wchar_t* logPath) noexcept {
auto& logger=Logger::instance();
logger.setConsoleEnabled(false);
logger.setRotation(8ull<<20,32ull<<20);
if(logPath)logger.openFile(logPath,true);
try {
// GPUI paints the parent HWND. Leave the child video rectangle to DXGI.
SetWindowLongPtrW(window,GWL_STYLE,GetWindowLongPtrW(window,GWL_STYLE)|WS_CLIPCHILDREN);
auto p=std::make_unique<Player>(window);
return p->video?p.release():nullptr;
}catch(...){return nullptr;}
}
API void portal_free(Player* p){delete p;}
// The Rust registration worker polls this Chiaki callback and owns the timeout.
struct Registration {
ChiakiRegist handle{};
ChiakiLog log{};
remoteplay::NativeConnectRequest saved;
std::array<uint8_t,6> mac{};
std::atomic<int> result{0};
static void completed(ChiakiRegistEvent* e,void* user) noexcept {
auto& r=*static_cast<Registration*>(user);
if(!e || e->type!=CHIAKI_REGIST_EVENT_TYPE_FINISHED_SUCCESS || !e->registered_host){
r.result.store(-2);return;
}
auto& h=*e->registered_host;
memcpy(r.mac.data(),h.server_mac,r.mac.size());
memcpy(r.saved.credentials.registrationKey.data(),h.rp_regist_key,16);
memcpy(r.saved.credentials.sessionKey.data(),h.rp_key,16);
r.result.store(1);
}
};
API Registration* portal_pair_start(const char* host,const unsigned char* account,unsigned pin) noexcept {
try {
if(!remoteplay::validHost(host)||pin>99999999||!remoteplay::initializeChiaki().ok)return nullptr;
auto r=std::make_unique<Registration>();
r->saved.host=host;memcpy(r->saved.credentials.accountId.data(),account,8);
chiaki_log_init(&r->log,0,nullptr,nullptr);
ChiakiRegistInfo info{};info.target=CHIAKI_TARGET_PS5_1;info.host=r->saved.host.c_str();info.pin=pin;
memcpy(info.psn_account_id,account,8);
if(chiaki_regist_start(&r->handle,&r->log,&info,Registration::completed,r.get())!=CHIAKI_ERR_SUCCESS)return nullptr;
return r.release();
}catch(...){return nullptr;}
}
API int portal_pair_status(Registration* r){return r->result.load();}
API bool portal_pair_finish(Registration* r,const wchar_t* profile) noexcept {
std::unique_ptr<Registration> owner(r);
chiaki_regist_stop(&r->handle);chiaki_regist_fini(&r->handle);
try{
if(!profile||r->result.load()!=1)return false;
for(auto b:r->mac)r->saved.consoleId+=std::format("{:02x}",b);
if(r->saved.consoleId=="000000000000")r->saved.consoleId.clear();
return remoteplay::saveProfile(profile,r->saved);
}catch(...){return false;}
}
API int portal_open(Player* p,const wchar_t* profile,bool wake,uint32_t bitrateKbps) noexcept {
try {auto saved=remoteplay::loadProfile(profile);if(!saved)return -1;
if(wake)return remoteplay::wakeLocalPs5(*saved).ok?0:-2;
saved->video.bitrateKbps=bitrateKbps;
if(saved->video.validate())return -4;
source::RemotePlayConnectDesc desc;desc.request=std::move(*saved);
p->loginPinRequest=0;
if(!p->padStarted)p->padStarted=p->pad.start();
p->engine.openRemotePlay(p->video,std::move(desc),engine::PlayerOptions::from(p->quality));return 0;
}catch(...){return -3;}
}
API void portal_event(const char* event){if(event)log::info("session-ui",event);}
static LRESULT CALLBACK panelFrame(HWND panel,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR id,DWORD_PTR){
if(msg==WM_NCCALCSIZE)return 0;
if(msg==WM_NCHITTEST && (GetWindowLongPtrW(panel,GWL_EXSTYLE)&WS_EX_TRANSPARENT))return HTTRANSPARENT;
if(msg==WM_NCDESTROY)RemoveWindowSubclass(panel,panelFrame,id);
return DefSubclassProc(panel,msg,wp,lp);
}
API void portal_attach_panel(Player* p,HWND panel){
p->panel=panel;
SetWindowSubclass(panel,panelFrame,1,0);
SetWindowLongPtrW(panel,GWL_STYLE,WS_POPUP|WS_CLIPCHILDREN);
SetWindowLongPtrW(panel,GWL_EXSTYLE,(GetWindowLongPtrW(panel,GWL_EXSTYLE)|WS_EX_TOOLWINDOW|WS_EX_NOACTIVATE)&~WS_EX_APPWINDOW);
SetWindowLongPtrW(panel,GWLP_HWNDPARENT,reinterpret_cast<LONG_PTR>(p->parent));
SetWindowTextW(panel,L"PSFlow - Ajustes rápidos");
SetWindowPos(panel,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER|SWP_HIDEWINDOW);
}
API void portal_panel_stage(Player* p,bool wanted,int width,int height,int top,int bottom){
p->panelTop=top;
p->panelBottom=bottom;
if(!p->panel)return;
const bool toast=height==48;
if(toast!=p->panelToast){
auto style=GetWindowLongPtrW(p->panel,GWL_EXSTYLE);
SetWindowLongPtrW(p->panel,GWL_EXSTYLE,toast?style|WS_EX_TRANSPARENT:style&~WS_EX_TRANSPARENT);
p->panelToast=toast;
}
const auto front=GetForegroundWindow();
const bool focused=front==p->parent||front==p->video||front==p->panel;
wanted=wanted&&focused&&!IsIconic(p->parent);
if(wanted!=p->panelWanted){
p->panelWanted=wanted;
log::info("session-ui",wanted?"overlay=visible":"overlay=hidden");
}
const bool visible=IsWindowVisible(p->panel);
if(!wanted){if(visible)ShowWindow(p->panel,SW_HIDE);return;}
RECT client{},old{};POINT origin{};
GetClientRect(p->parent,&client);ClientToScreen(p->parent,&origin);
const int dpi=GetDpiForWindow(p->parent);
auto scale=[dpi](int v){return MulDiv(v,dpi,96);};
int w=std::clamp<int>(scale(width),1,std::max<LONG>(1,client.right));
const int stageTop=scale(top);
const int stageHeight=client.bottom-stageTop-scale(bottom);
const int h=std::max(1,toast?std::min(scale(height),stageHeight):stageHeight);
const int x=origin.x, y=origin.y+stageTop;
GetWindowRect(p->panel,&old);
bool resized=old.right-old.left!=w||old.bottom-old.top!=h;
bool raise=!visible;
// A rebuilt FG output may have appeared above the panel.
if(!raise&&!toast){POINT point{x+w/2,y+scale(12)};HWND hit=WindowFromPoint(point);raise=hit&&GetAncestor(hit,GA_ROOT)!=p->panel;}
if((raise||resized||old.left!=x||old.top!=y) &&
!SetWindowPos(p->panel,HWND_TOPMOST,x,y,w,h,SWP_NOACTIVATE|(raise?0:SWP_NOZORDER)))return;
if(!visible)ShowWindow(p->panel,SW_SHOWNA);
}
API void portal_panel(Player* p,bool wanted,int width,int height){
portal_panel_stage(p,wanted,width,height,0,0);
}
API HWND portal_capture_window(Player* p){
return p->detached && IsWindowVisible(p->video) && !IsIconic(p->parent) ? p->video : nullptr;
}
API bool portal_preview(Player* p,const wchar_t* file) noexcept {
try {p->engine.open(p->video,file,engine::PlayerOptions::from(p->quality));return true;}
catch(...){return false;}
}
API bool portal_pause(Player* p,bool paused) noexcept {
try {
const auto playing=p->engine.snapshot().transport;
if(playing!=engine::TransportState::Playing&&playing!=engine::TransportState::Paused)return false;
p->engine.pause(paused);
return true;
} catch(...) {return false;}
}
API void portal_stop(Player* p){p->engine.stop();p->pad.stop();p->padStarted=false;}
// Logical client coordinates work for both the DXGI child and the owned capture window.
API int portal_pointer_x(Player* p){
HWND front=GetForegroundWindow();
POINT pt{};RECT r{};
if((front!=p->parent && front!=p->video && front!=p->panel) || IsIconic(p->parent) ||
!GetCursorPos(&pt) || !ScreenToClient(p->parent,&pt) || !GetClientRect(p->parent,&r) ||
!PtInRect(&r,pt))return -1;
const int dpi=GetDpiForWindow(p->parent);
if(pt.y<MulDiv(p->panelTop,dpi,96)||pt.y>=r.bottom-MulDiv(p->panelBottom,dpi,96))return -1;
return MulDiv(pt.x,96,dpi);
}
struct VideoViewport {int x,y,width,height;};
static int tickPresentation(Player* p,int sidebar,bool show,const VideoViewport* viewport){
// Windows Graphics Capture requires a top-level HWND. Keep the DXGI surface and its
// owner, but present the video as a borderless owned window while external capture is active.
if(p->externalFg != p->detached){
ShowWindow(p->video,SW_HIDE);
if(p->externalFg){
SetParent(p->video,nullptr);
SetWindowLongPtrW(p->video,GWL_STYLE,WS_POPUP|WS_CLIPSIBLINGS);
SetWindowLongPtrW(p->video,GWLP_HWNDPARENT,reinterpret_cast<LONG_PTR>(p->parent));
SetWindowLongPtrW(p->video,GWL_EXSTYLE,WS_EX_TOOLWINDOW|WS_EX_NOACTIVATE);
}else{
SetWindowLongPtrW(p->video,GWLP_HWNDPARENT,0);
SetWindowLongPtrW(p->video,GWL_STYLE,WS_CHILD|WS_CLIPSIBLINGS);
SetWindowLongPtrW(p->video,GWL_EXSTYLE,0);
SetParent(p->video,p->parent);
}
SetWindowPos(p->video,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER);
p->detached=p->externalFg;
}
RECT r{};GetClientRect(p->parent,&r);RECT rect{};GetWindowRect(p->video,&rect);
POINT origin{rect.left,rect.top};ScreenToClient(p->parent,&origin);
auto x=MulDiv(p->externalFg?0:sidebar,GetDpiForWindow(p->parent),96);
int y=0;
auto w=std::max<LONG>(1,r.right-x),h=std::max<LONG>(1,r.bottom);
if(viewport){
const auto dpi=GetDpiForWindow(p->parent);
auto scale=[dpi](int value){return MulDiv(value,dpi,96);};
x=std::clamp<int>(scale(viewport->x),0,std::max<LONG>(0,r.right-1));
y=std::clamp<int>(scale(viewport->y),0,std::max<LONG>(0,r.bottom-1));
w=std::clamp<LONG>(scale(viewport->width),1,std::max<LONG>(1,r.right-x));
h=std::clamp<LONG>(scale(viewport->height),1,std::max<LONG>(1,r.bottom-y));
}
if((!viewport||(show&&!IsIconic(p->parent)))&&
(origin.x!=x||origin.y!=y||rect.right-rect.left!=w||rect.bottom-rect.top!=h)){
POINT at{x,y};if(p->detached)ClientToScreen(p->parent,&at);
SetWindowPos(p->video,nullptr,at.x,at.y,w,h,SWP_NOACTIVATE|SWP_NOZORDER);
}
show=show&&!IsIconic(p->parent);
if(bool(IsWindowVisible(p->video))!=show)ShowWindow(p->video,show?SW_SHOWNA:SW_HIDE);
if(p->padStarted){auto front=GetForegroundWindow();bool focused=front==p->parent||front==p->video||front==p->panel;p->engine.remotePlayController(p->pad.poll(focused));p->pad.feedback(p->engine.remotePlayFeedback(),focused);}
auto state=p->engine.snapshot();
if(state.remoteStream.state==remoteplay::SessionState::LoginPinRequired){
if(!p->loginPinRequest&&!state.remoteStream.loginPin.pending)
p->loginPinRequest=state.remoteStream.loginPin.requestId;
return 7;
}
p->loginPinRequest=0;
const auto& flow=state.metrics.flow;
const auto& counts=flow.counters;
const bool vfg=state.applied.frameGenerationBackend==engine::FrameGenerationBackend::Vfg;
const bool vfgPresented=vfg&&state.fgActive&&counts.generatedPresented>0;
const unsigned hud=vfg&&state.applied.multiplier>1?(unsigned(state.hudLockState==1)
| (unsigned(state.dynamicHudState==1)<<1) | (unsigned(state.hudReticleActive)<<2)
| (unsigned(state.hudSubtitlesActive)<<3)):0u;
if(show && GetTickCount64()-p->lastSample>=1000){
p->lastSample=GetTickCount64();
log::info("session-sample",std::format("source={} sourceNominalFps={:.2f} receivedFps={:.2f} decodedFps={:.2f} ratesReady={} frames={} generated={} processCpuP95Ms={:.2f} presentCpuP95Ms={:.2f} lateP95Ms={:.2f} video={}x{} videoHwnd={:#x}",
state.remotePlay?"ps5":"file",state.nominalSourceFps,state.remoteStream.receivedFps,state.remoteStream.decodedFps,state.remoteStream.ratesReady,state.frames,state.generated,state.processCpuP95Ms,state.presentCpuP95Ms,state.lateP95Ms,w,h,reinterpret_cast<uintptr_t>(p->video)));
if(vfg)log::info("vfg-state",std::format("revision={} multiplier={} vfgPresented={} hudRequested={} hudStatic={} hudDynamic={} reticle={} subtitles={} realPresents={} syntheticPresents={} syntheticExpired={} seedEvals={} realPresentFps={:.2f} syntheticPresentFps={:.2f}",
state.applied.revision,state.applied.multiplier,vfgPresented,state.applied.hudLock,hud&1,(hud>>1)&1,(hud>>2)&1,(hud>>3)&1,
counts.realPresented,counts.generatedPresented,counts.generatedExpiredAfterEval,counts.fgWarmup,flow.realPresentFps,flow.generatedPresentFps));
}
const int effects = (int(state.applied.multiplier) << 8)
| (int(state.nrActive) << 12) | (int(state.applying || state.nrPreparing) << 13)
| (int(!state.backendWarning.empty()) << 14) | (int(state.srActive)<<15)
| (int(state.applied.antiAlias.enabled)<<16) | (int(state.applied.antiAlias.method)<<17)
| (int(state.applied.srTarget)<<19) | (int(state.fgActive)<<22)
| (int(vfgPresented)<<23) | (int(hud)<<24);
return int(state.transport) | effects;
}
API int portal_tick(Player* p,int sidebar,bool show){return tickPresentation(p,sidebar,show,nullptr);}
API int portal_tick_rect(Player* p,int x,int y,int width,int height,bool show){
const VideoViewport viewport{x,y,width,height};
return tickPresentation(p,0,show,&viewport);
}
API bool portal_quality(Player* p,const float* values,size_t count) noexcept {
try {
struct : engine::EnhancementSettings { int finalFpsOnly=0; } q;
size_t i=0;
#define FIELD(group,label,field,low,high,initial,step) \
if(i>=count || !std::isfinite(values[i]) || values[i]<low || values[i]>high)return false; \
q.field=static_cast<decltype(q.field)>(values[i++]);
#include "quality.def"
#undef FIELD
if(i!=count)return false;
// Next Boost capture consumes the final presented image. Only one engine interpolates.
const auto requestedMultiplier=q.multiplier;
bool externalCapture=static_cast<int>(q.frameGenerationBackend)>=9;
if(externalCapture){
q.frameGenerationBackend=engine::EnhancementSettings{}.frameGenerationBackend;
q.multiplier=1;
}
if(q.frameGenerationBackend==engine::FrameGenerationBackend::Vfg){
q.hudLock=q.hudLock&&q.multiplier>1;
q.dynamicHud=q.subtitleHold=q.hudLock;
q.hudProtect=q.hudLock?engine::HudProtectMode::Center:engine::HudProtectMode::Off;
}
for(auto& layer:q.nrLayers){layer.lowLatencyPairing=q.lowLatency;layer.runtime=q.nrRuntime;}
const auto& first=q.nrLayers[0];
q.nrPolicy=first.sizePolicy;q.model=first.model;q.residual=first.residual;q.nrTemporal=first.temporal;
if(!p->engine.requestSettings(q))return false;
p->externalFg=externalCapture && requestedMultiplier>1;
p->quality=q;return true;
}catch(...){return false;}
}
API void portal_login(Player* p,const char* pin){
if(pin&&p->loginPinRequest){
p->engine.remotePlayLoginPin(p->loginPinRequest,pin);
p->loginPinRequest=0;
}
}
// The callback is synchronous and its strings are borrowed for that call only.
using DiscoveryCallback = void (*)(void*,const char*,bool);
API int portal_discover(DiscoveryCallback callback,void* context) noexcept {
if(!callback)return -1;
try {
const auto report=remoteplay::discoverLocalPs5({});
for(const auto& host:report.hosts)callback(context,host.host.c_str(),host.standby);
return report.error;
}catch(...){return -1;}
}