Repository navigation
Expand file tree
/
Copy pathPlayerProfiles.cpp
More file actions
399 lines (398 loc) · 31 KB
/
Copy pathPlayerProfiles.cpp
File metadata and controls
399 lines (398 loc) · 31 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#include "player/PlayerBuiltinProfiles.h"
#include "player/PlayerWindow.h"
#include "player/PlayerDiscMenu.h"
#include "player/PlayerAiSubtitles.h"
#include "backend/ThreeFpPlayer.h"
#include "graph/PresetStore.h"
#include "ui/PreviewPane.h"
#include "render/ShaderPackage.h"
#include <QCryptographicHash>
#include <QSaveFile>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QLabel>
#include <QSettings>
#include <QPushButton>
#include <QTimer>
#include <QThread>
#include <algorithm>
#include <numeric>
namespace vsr {
QString PlayerWindow::profile() const {
const QFileInfo file(preset_);
if(file.absolutePath()!=QDir(PresetStore::directory()).filePath("builtin"))return {};
if(file.fileName()=="Anime.vpy" || fixedAnimeStage()>=0)return "Anime";
if(file.fileName()=="Realistic.vpy")return "Realistic";
if(interpolationStage()>=0)return "Interpolation";
if(superInterpolationStage()>=0)return "SuperInterpolation";
return {};
}
bool PlayerWindow::animeSourceSupported() const {
for(const auto &entry:media_.value("streams").toArray()){
const auto stream=entry.toObject();
if(stream.value("type").toString()=="video")return stream.value("height").toInt()<2160;
}
return true;
}
int PlayerWindow::fixedAnimeStage() const {
const QFileInfo file(preset_);
if(file.absolutePath()!=QDir(PresetStore::directory()).filePath("builtin"))return -1;
return builtinAnimeStage(file.fileName());
}
int PlayerWindow::initialQualityStage() const {
#ifdef VSR_LITE_PLAYER
if(!settings_->value("player/animeAuto",false).toBool())return std::clamp(settings_->value("player/animeStage",5).toInt(),0,10);
#endif
if(interpolationStage()>=0)return 4;
const int fixed=fixedAnimeStage();
if(fixed>=0)return fixed;
if(profile()!="Anime")return 0;
const auto order=builtinAnimeOrder();
const auto allowed=settings_->value("player/animeStages",defaultAnimeStages()).toStringList();
const int start=0;
for(int n=start;n<order.size();++n)if(order[n]==5 || allowed.contains(QString::number(order[n])))return order[n];
return 5;
}
QStringList PlayerWindow::qualityNames() const {
return {tr("Anime4K AFast CNN + 额外增强"),tr("Anime4K AFast CNN"),{}, {},tr("Jinc 直通"),tr("D3D11 原生直通"),tr("Anime4K AFast 1X + 额外增强"),tr("Anime4K AFast 1X"),tr("Anime4K A CNN + 额外增强"),tr("Anime4K A CNN"),QStringLiteral("MoeSR-50K")};
}
int PlayerWindow::superInterpolationStage() const {
const QFileInfo file(preset_);if(file.absolutePath()!=QDir(PresetStore::directory()).filePath("builtin"))return -1;
return QStringList{"Super-0-A4K-RIFE-A4K.vpy","Super-1-A4K-RIFE-Jinc.vpy","Super-2-A4K-RIFE-D3D11.vpy","Super-3-RIFE-A4K.vpy"}.indexOf(file.fileName());
}
void PlayerWindow::updateAlgorithmBadges(){
message_->show();
const bool video=!minimalMode_ && !imageMode_ && !audioMode_ && !madvrMode() && !(discMenu_ && discMenu_->active());algorithmBadge_->setVisible(video);interpolationBadge_->hide();if(!video)return;
const int interpolation=interpolationStage();
if(superInterpolationStage()>=0 && !direct_){algorithmBadge_->setText(superInterpolationStage()==2?"D3D11":superInterpolationStage()==1?"Jinc":"A4K");interpolationBadge_->setText("RIFE 960×540");interpolationBadge_->show();}
else if(interpolation>=0 && !direct_){algorithmBadge_->setText(interpolationRenderer()?"D3D11":"Jinc");interpolationBadge_->setText(QStringList{"RIFE+","RIFE","MVT+","MVT"}.at(interpolation));interpolationBadge_->show();}
else if(profile()=="Anime" && (nativeAnime_ || !direct_) && qualityStage_!=4 && qualityStage_!=5)algorithmBadge_->setText(QStringList{"A4K-AFast-CNN+","A4K-AFast-CNN",{}, {},"Jinc","D3D11","A4K-AFast-1X+","A4K-AFast-1X","A4K-A-CNN+","A4K-A-CNN","MoeSR-50K"}.at(std::clamp(qualityStage_,0,10)));
else if(!customShaderPackage_.isEmpty() && !hlslFailed_ && hlslFallback_.isEmpty())algorithmBadge_->setText("HLSL");
else algorithmBadge_->setText(QStringList{"Nearest","Bilinear","Bicubic","Lanczos3","Jinc","Spline36","SuperXbr","D3D11","Lanczos4","A4KCNN","A4KCNN+","A4K+","A4K","A4K-1X-Jinc","A4K-1X-D3D11",openNguActive_?"OpenNGU":"Jinc"}.value(scalingAlgorithm(),"Jinc"));
if(algorithmBadge_->text()=="HLSL")algorithmBadge_->hide();
}
int PlayerWindow::interpolationStage() const {
const QFileInfo file(preset_);
if(file.absolutePath()!=QDir(PresetStore::directory()).filePath("builtin"))return -1;
const QStringList names{"Interpolation-0-RIFE.vpy","Interpolation-1-RIFE-Half.vpy","Interpolation-2-MVTools-HQ.vpy","Interpolation-3-MVTools.vpy"};
auto name=file.fileName();name.replace("-D3D11.vpy",".vpy");return names.indexOf(name);
}
int PlayerWindow::interpolationRenderer() const {return QFileInfo(preset_).fileName().endsWith("-D3D11.vpy")?1:0;}
QStringList PlayerWindow::interpolationStages(int renderer) const {
QStringList defaults;for(int stage=std::clamp(settings_->value("player/interpolationStart",0).toInt(),0,3);stage<4;++stage)defaults<<QString::number(stage);
return settings_->value(renderer?"player/interpolationStagesD3D11":"player/interpolationStagesJinc",defaults).toStringList();
}
QStringList PlayerWindow::interpolationNames() const {
return {tr("RIFE 4.26 · 4queue"),tr("RIFE 4.26 · 4queue · 半宽高"),tr("MVTools · 最高质量"),tr("MVTools · 低质量"),tr("关闭")};
}
void PlayerWindow::setInterpolation(int stage,bool automatic,int renderer) {
#ifdef VSR_LITE_PLAYER
return;
#endif
if(madvrMode() || imageMode_ || networkSource())return;
settings_->remove("render/customShader");customShaderPackage_.clear();hlslParameters_.clear();hlslFallback_.clear();hlslFailed_=false;nativeAnime_=false;clock_->setCustomShader({});output_->setCustomShader({});
const QStringList names{"Interpolation-0-RIFE.vpy","Interpolation-1-RIFE-Half.vpy","Interpolation-2-MVTools-HQ.vpy","Interpolation-3-MVTools.vpy"};
if(stage>=4){stage-=4;renderer=1;}
if(automatic){const auto allowed=interpolationStages(renderer);while(stage<4 && !allowed.contains(QString::number(stage)))++stage;if(stage>=4)return;}
auto name=stage>=0 && stage<names.size()?names[stage]:QString("Anime.vpy");
if(stage>=0 && renderer==1)name.replace(".vpy","-D3D11.vpy");
preset_=QDir(PresetStore::directory()).filePath("builtin/"+name);
interpolationAuto_=automatic && stage>=0 && stage<names.size();qualityStage_=interpolationStage()>=0?4:0;
settings_->setValue("player/preset",preset_);settings_->setValue("player/interpolationAuto",interpolationAuto_);
settings_->setValue("player/interpolationRenderer",renderer);
timer_->setInterval(interpolationStage()>=0?4:10);
usage_=resources_.sample();const auto cache=usage_.totalMemoryMiB*(settings_->value("performance/ram",50).toInt()-usage_.ram)/100.;
server_->setResourceLimits(qMax(1,QThread::idealThreadCount()),std::clamp(int(cache),256,8192));
if(!source_.isEmpty())refreshScript();
}
bool PlayerWindow::advanceInterpolation() {
const int stage=interpolationStage();if(stage<0 || !interpolationAuto_)return false;
const auto allowed=interpolationStages(interpolationRenderer());int next=stage+1;while(next<4 && !allowed.contains(QString::number(next)))++next;
if(next>=4){showInterpolationWarning(true);return false;}
if(resumeAt_<0)resumeAt_=position();autoPlay_=playing_ || autoPlay_;
setInterpolation(next,true,interpolationRenderer());showStatus(tr("自动补帧:切换到 %1。").arg(interpolationNames().at(next)));return true;
}
void PlayerWindow::showInterpolationWarning(bool visible) {
interpolationWarning_->setVisible(visible);if(visible){interpolationWarning_->adjustSize();interpolationWarning_->raise();}
}
void PlayerWindow::ensureProfiles() {
#ifdef VSR_LITE_PLAYER
// Lite identifies built-in presets by name and executes their native shaders.
return;
#endif
const QDir shaders(QDir(QCoreApplication::applicationDirPath()).filePath("shaders"));QDir().mkpath(shaders.absolutePath());
for(const auto &name:QStringList{"moesr-50k.hlsl","moesr-50k.hlsl.vsrhlsl","moesr-50k.hlsl.vsrhlsl.json","anime4k-mode-a.glsl","anime4k-mode-a.glsl.vsrhlsl","anime4k-mode-a.glsl.vsrhlsl.json"})
if(!QFileInfo::exists(shaders.filePath(name)))QFile::copy(":/filters/builtin-shaders/"+name,shaders.filePath(name));
if(!QFileInfo::exists(shaders.filePath("anime4k-a-fast.glsl")))QFile::copy(":/filters/anime4k-a-fast.glsl",shaders.filePath("anime4k-a-fast.glsl"));
const auto oldProcessing=QStringLiteral(
" if _stage == 0:\n"
" clip = _vsr_sharpen_chain(clip, [('sharpen_edges', 0.3, 2), ('enhance_detail', 0.3, 2)])\n"
" clip = core.resize.Spline36(clip, format=vs.YUV420P16)\n"
" clip = core.placebo.Shader(clip, shader=os.path.join(_vsr_directory, 'shaders', 'anime4k-a-fast.glsl'), width=_w, height=_h)\n");
const auto processing=QStringLiteral(
" _shader_name = 'anime4k-a-fast.glsl'\n"
" with open(os.path.join(_vsr_directory, 'shaders', _shader_name), encoding='utf-8') as _file: _shader = _file.read()\n"
" if _stage == 0:\n"
" _shader = '\\n'.join(_vsr_sharpen_shader(*s) for s in [('sharpen_edges', 0.3, 2), ('enhance_detail', 0.3, 2)]) + '\\n' + _shader\n"
" if clip.format.bits_per_sample != 16: clip = core.resize.Point(clip, format=clip.format.replace(bits_per_sample=16))\n"
" clip = getattr(core, 'vsrplacebo', core.placebo).Shader(clip, shader_s=_shader, width=_w, height=_h)\n");
const QDir builtin(QDir(PresetStore::directory()).filePath("builtin"));QDir().mkpath(builtin.absolutePath());
const QStringList superFiles{"Super-0-A4K-RIFE-A4K.vpy","Super-1-A4K-RIFE-Jinc.vpy","Super-2-A4K-RIFE-D3D11.vpy","Super-3-RIFE-A4K.vpy"};
for(int stage=0;stage<superFiles.size();++stage){
const auto path=builtin.filePath(superFiles[stage]);if(QFileInfo::exists(path))continue;
FilterGraph graph;
const auto anime=[&]{const int node=graph.add("anime4k");graph.setParameter(node,"mode","anime4k-a-fast.glsl");graph.setParameter(node,"output_mode","指定分辨率");graph.setParameter(node,"width",3840);graph.setParameter(node,"height",2160);graph.setParameter(node,"keep_aspect",false);};
if(stage<3)anime();
if(stage<3){const int resize=graph.add("resize");graph.setParameter(resize,"width",960);graph.setParameter(resize,"height",540);graph.setParameter(resize,"kernel","Bicubic");}
const int rife=graph.add("rife");graph.setParameter(rife,"threads",1);
if(stage==3)graph.setParameter(rife,"inference_scale","2 - 半宽半高");
if(stage==0 || stage==3)anime();
auto script=PresetStore::create(graph,SourceFilter::Native,{},{});
if(stage==3)script.replace("shader_s=_shader_text, ","shader_s=_shader_text, **({'subsampling': 1} if hasattr(core, 'vsrplacebo') else {}), ");
PresetStore::write(path,"# VSR_PLAYER_SUPER_INTERPOLATION\n"+script);
}
const QStringList interpolationFiles{"Interpolation-0-RIFE.vpy","Interpolation-1-RIFE-Half.vpy","Interpolation-2-MVTools-HQ.vpy","Interpolation-3-MVTools.vpy"};
for(int stage=0;stage<interpolationFiles.size();++stage) {
const auto path=builtin.filePath(interpolationFiles[stage]);if(QFileInfo::exists(path))continue;
FilterGraph graph;const int node=graph.add(stage<2?"rife":"mvtools");
if(stage<2){graph.setParameter(node,"threads",4);graph.setParameter(node,"inference_scale",stage==0?"1 - 原始":"2 - 半宽半高");}
else if(stage==2){graph.setParameter(node,"block","8");graph.setParameter(node,"pel","2");graph.setParameter(node,"overlap",true);graph.setParameter(node,"chroma",true);}
auto script=PresetStore::create(graph,SourceFilter::Native,{},interpolationNames().at(stage));
script.replace("clip = src","clip = core.resize.Point(src, format=vs.YUV444P16, **({'matrix': _vsr_matrix(src)} if src.format.color_family == vs.RGB else {}))");
PresetStore::write(path,script);
}
for(const auto &name:interpolationFiles){auto target=name;target.replace(".vpy","-D3D11.vpy");const auto path=builtin.filePath(target);if(!QFileInfo::exists(path))QFile::copy(builtin.filePath(name),path);}
for(const auto &mode:QStringList{"Anime","Realistic"}) {
const auto path=builtin.filePath(mode+".vpy");if(QFileInfo::exists(path)) {
QFile existing(path);if(existing.open(QIODevice::ReadOnly)){const auto original=existing.readAll();auto text=QString::fromUtf8(original);existing.close();
const auto line=QStringLiteral(" clip = core.placebo.Resample(clip, width=_w, height=_h, filter='ewa_lanczos', antiring=0.5)");
const auto conversion=QStringLiteral(" if clip.format.bits_per_sample not in (8, 16, 32): clip = core.resize.Point(clip, format=clip.format.replace(bits_per_sample=16))\n");
if(text.startsWith("# VSR_PLAYER_PROFILE ") && text.contains(line) && !text.contains(conversion.trimmed())) {
text.replace(line,conversion+line);const auto backup=path+".before-bitdepth-fix";
if(QFile::exists(backup) || QFile::copy(path,backup))PresetStore::write(path,text);
}
if(mode=="Anime" && text.startsWith("# VSR_PLAYER_PROFILE Anime\n") && text.contains(oldProcessing) && text.contains("_stage < 2\n")) {
text.replace(oldProcessing,processing);text.replace("_stage < 2\n","_stage < 4\n");const auto backup=path+".before-six-stage";
if(QFile::exists(backup) || QFile::copy(path,backup))PresetStore::write(path,text);
}
}
}
QString script="# VSR_PLAYER_PROFILE "+mode+'\n'+PresetStore::create(FilterGraph(),SourceFilter::Native,{},mode);
QFile helper(":/filters/gpu-sharpen.py");if(mode=="Anime" && helper.open(QIODevice::ReadOnly))script.replace("clip = src",QString::fromUtf8(helper.readAll())+"\nclip = src");
script.replace("clip.set_output(0)",QStringLiteral(
"# Editable profile. Player supplies the viewport target and quality stage.\n"
"_tw = max(2, int(globals().get('_vsr_target_width', 3840)))\n"
"_th = max(2, int(globals().get('_vsr_target_height', 2160)))\n"
"_fit = min(_tw / clip.width, _th / clip.height, 3840 / clip.width, 2160 / clip.height)\n"
"_w = max(2, int(clip.width * _fit) // 2 * 2)\n"
"_h = max(2, int(clip.height * _fit) // 2 * 2)\n"
"import math\n"
"_div = math.gcd(src.width, src.height)\n"
"_rw, _rh = src.width // _div, src.height // _div\n"
"_mul = min(_w // _rw, _h // _rh)\n"
"if _rw % 2 or _rh % 2: _mul = _mul // 2 * 2\n"
"if _mul > 0: _w, _h = _rw * _mul, _rh * _mul\n"
"_stage = int(globals().get('_vsr_quality_stage', 0))\n"
"_anime = %1 and clip.width < 3840 and clip.height < 2160 and _stage < 4\n"
"if globals().get('_vsr_resize_before_enhance', False) and (_w < clip.width or _h < clip.height):\n"
" if clip.format.bits_per_sample not in (8, 16, 32): clip = core.resize.Point(clip, format=clip.format.replace(bits_per_sample=16))\n"
" clip = core.placebo.Resample(clip, width=_w, height=_h, filter='ewa_lanczos', antiring=0.5)\n"
"if _anime:\n"
"%2"
"elif clip.width != _w or clip.height != _h:\n"
" if clip.format.bits_per_sample not in (8, 16, 32): clip = core.resize.Point(clip, format=clip.format.replace(bits_per_sample=16))\n"
" clip = core.placebo.Resample(clip, width=_w, height=_h, filter='ewa_lanczos', antiring=0.5)\n"
"import math\n"
"_props = src.get_frame(0).props\n"
"_sn = src.width * _h * int(_props.get('_SARNum', 1))\n"
"_sd = src.height * _w * int(_props.get('_SARDen', 1))\n"
"_g = math.gcd(_sn, _sd)\n"
"clip = core.std.SetFrameProps(clip, _SARNum=_sn // _g, _SARDen=_sd // _g)\n"
"clip.set_output(0)").arg(mode=="Anime"?"True":"False",processing));
builtinScripts_.insert(mode+".vpy",script);
if(!QFileInfo::exists(path))PresetStore::write(path,script);
}
{
const auto automatic=builtinScripts_.value("Anime.vpy");
const auto names=builtinAnimeFiles();
for(int stage:{0,1,4,5}) {
const auto path=builtin.filePath(names[stage]);
auto script=automatic;
script.replace("# VSR_PLAYER_PROFILE Anime\n",QString("# VSR_PLAYER_PROFILE Anime\n# VSR_PLAYER_FIXED_STAGE %1\n").arg(stage));
script.replace("_stage = int(globals().get('_vsr_quality_stage', 0))",QString("_stage = %1").arg(stage));
script.replace("_anime = True and clip.width < 3840 and clip.height < 2160 and _stage < 4","_anime = _stage < 4");
builtinScripts_.insert(names[stage],script);
if(!QFileInfo::exists(path))PresetStore::write(path,script);
}
}
for(int stage:{6,7}) {
const auto path=builtin.filePath(builtinAnimeFiles()[stage]);
auto script=PresetStore::create(FilterGraph(),SourceFilter::Native,{},{});
script.prepend(QString("# VSR_PLAYER_PROFILE Anime\n# VSR_PLAYER_FIXED_STAGE %1\n").arg(stage));
script.replace("clip.set_output(0)",QStringLiteral(
"if clip.format.bits_per_sample != 16: clip = core.resize.Point(clip, format=clip.format.replace(bits_per_sample=16))\n"
"clip = getattr(core, 'vsrplacebo', core.placebo).Shader(clip, shader=os.path.join(_vsr_directory, 'shaders', 'anime4k-a-fast.glsl'), width=clip.width, height=clip.height)\n"
"clip.set_output(0)"));
if(stage==6){QFile helper(":/filters/gpu-sharpen.py");if(helper.open(QIODevice::ReadOnly))script.replace("clip.set_output(0)",QString::fromUtf8(helper.readAll())+QStringLiteral("\nclip = _vsr_sharpen_chain(clip, [('sharpen_edges', 0.3, 2), ('enhance_detail', 0.3, 2)])\nclip.set_output(0)"));}
builtinScripts_.insert(QFileInfo(path).fileName(),script);
if(!QFileInfo::exists(path))PresetStore::write(path,script);
}
for(int stage:{8,9,10}){
const auto name=builtinAnimeFiles().at(stage),path=builtin.filePath(name);
FilterGraph graph;const int shader=graph.add("anime4k");graph.setParameter(shader,"shader",shaders.filePath(stage==10?"moesr-50k.hlsl":"anime4k-mode-a.glsl"));
if(stage==8)for(const auto &mode:QStringList{"sharpen_edges","enhance_detail"}){const int n=graph.add(mode);graph.setParameter(n,"strength",0.3);}
const auto script=PresetStore::create(graph,SourceFilter::Native,{},qualityNames().at(stage));builtinScripts_.insert(name,script);
if(!QFileInfo::exists(path))PresetStore::write(path,script);
}
const auto descriptions=QDir(PresetStore::directory()).filePath("preset-descriptions.json");
QFile descriptionFile(descriptions);QJsonObject entries;bool changed=!descriptionFile.exists();
if(descriptionFile.open(QIODevice::ReadOnly)){
const auto document=QJsonDocument::fromJson(descriptionFile.readAll());
if(!document.isObject())return;
entries=document.object();descriptionFile.close();
}else if(descriptionFile.exists())return;
QFile menuDescriptions(":/filters/player-menu-descriptions.json");if(menuDescriptions.open(QIODevice::ReadOnly)){const auto defaults=QJsonDocument::fromJson(menuDescriptions.readAll()).object();for(auto it=defaults.begin();it!=defaults.end();++it)if(!entries.contains(it.key())){entries.insert(it.key(),it.value());changed=true;}}
for(const auto &name:builtin.entryList({"*.vpy"},QDir::Files))if(!entries.contains("builtin/"+name)){entries.insert("builtin/"+name,QString());changed=true;}
if(changed)PresetStore::write(descriptions,QString::fromUtf8(QJsonDocument(entries).toJson(QJsonDocument::Indented)));
}
bool PlayerWindow::nativeBuiltinCompatible() const {
// Builtin menu entries select native models; legacy VPY files are not their execution backend.
return profile()=="Anime";
}
bool PlayerWindow::hlslColorCompatible() const {
const auto snap=clock_->snapshot();
if(snap.isHdrSource || settings_->value("color/engine",0).toInt()!=0)return false;
for(const auto &entry:media_.value("streams").toArray()){
const auto stream=entry.toObject();
if(stream.value("type").toString()!="video" || (snap.selectedVideoStream>=0 && stream.value("index").toInt(-1)!=snap.selectedVideoStream))continue;
const int transfer=stream.value("colorTransfer").toInt(2),primaries=stream.value("colorPrimaries").toInt(2),matrix=stream.value("colorSpace").toInt(2);
// 1 is BT.709; 2 is unspecified and remains subject to the native per-frame check.
if(transfer==16 || transfer==18 || matrix==9 || matrix==10 || (primaries!=1 && primaries!=2))return false;
}
return true;
}
QString PlayerWindow::customShaderDirectory() const {
return settings_->value("render/shaderDirectory",QDir(QFileInfo(settings_->fileName()).absolutePath()).filePath("shaders/custom")).toString();
}
bool PlayerWindow::importCustomShader(const QString &path) {
if(madvrMode()){setError(tr("请切换到 D3D11 播放后再启用着色器。"));return false;}
if(imageMode_ || audioMode_ || networkSource()){setError(tr("请在本地视频模式导入自定义着色器。"));return false;}
if(!hlslColorCompatible()){setError(tr("自定义 HLSL 当前仅支持原生 SDR 色彩路径。"));return false;}
QFile source(path);if(!source.open(QIODevice::ReadOnly)){setError(source.errorString());return false;}
const auto bytes=source.readAll();const auto suffix=QFileInfo(path).suffix().toLower();
if(!QStringList{"hlsl","glsl","hook"}.contains(suffix)){setError(tr("请选择 GLSL 或 HLSL 着色器。"));return false;}
const QDir directory(customShaderDirectory());if(!QDir().mkpath(directory.path())){setError(tr("无法创建着色器存储目录。"));return false;}
const auto name=QFileInfo(path).completeBaseName()+"-"+QString::fromLatin1(QCryptographicHash::hash(bytes,QCryptographicHash::Sha256).toHex().left(12))+'.'+suffix;
const auto stored=QFileInfo(path).absolutePath()==directory.absolutePath()?QFileInfo(path).absoluteFilePath():directory.filePath(name);
const auto package=ShaderPackage::prepare(path,directory.filePath("cache"));
if(package.packagePath.isEmpty()){setError(tr("HLSL 导入失败:%1").arg(package.error));return false;}
if(!QFileInfo::exists(stored)){QSaveFile copy(stored);if(!copy.open(QIODevice::WriteOnly) || copy.write(bytes)!=bytes.size() || !copy.commit()){setError(copy.errorString());return false;}}
// Validate before changing the selected preset or the remembered shader.
if(!clock_->setCustomShader(package.packagePath)){setError(clock_->lastError());return false;}
customShaderPackage_=package.packagePath;hlslParameters_.clear();hlslFallback_.clear();hlslFailed_=false;nativeAnime_=false;
settings_->setValue("render/customShader",stored);settings_->setValue("render/shaderDirectory",directory.absolutePath());
preset_.clear();settings_->setValue("player/preset",QString());interpolationAuto_=false;settings_->setValue("player/interpolationAuto",false);
qualityStage_=5;if(!source_.isEmpty() && !imageMode_)refreshScript();else applyScaling();
showStatus(tr("HLSL:%1").arg(QFileInfo(path).fileName()));updateAlgorithmBadges();return true;
}
QSize PlayerWindow::profileTarget() const {
QSize source(clip_.width,clip_.height);
for(const auto &entry:media_.value("streams").toArray()){const auto stream=entry.toObject();if(stream.value("type").toString()=="video"){source=QSize(stream.value("width").toInt(),stream.value("height").toInt());break;}}
if(source.isEmpty())return QSize(1920,1080);
const auto available=(pane_->surface()->size()*pane_->surface()->devicePixelRatioF()).boundedTo(QSize(3840,2160));
const auto fitted=source.scaled(available,Qt::KeepAspectRatio);
const int divisor=std::gcd(source.width(),source.height()),w=source.width()/divisor,h=source.height()/divisor;
int multiple=qMin(fitted.width()/w,fitted.height()/h);if(w%2 || h%2)multiple=multiple/2*2;
if(multiple>0)return QSize(w*multiple,h*multiple);
return QSize(qMax(2,fitted.width()/2*2),qMax(2,fitted.height()/2*2));
}
void PlayerWindow::setDirectMode(bool enabled) {
if(direct_==enabled)return;
if(aiSubtitles_)aiSubtitles_->stop();
const bool opened=!media_.isEmpty();const auto at=position();
const auto state=clock_->snapshot().state;if(state==ThreeFpState::Ready || state==ThreeFpState::Playing || state==ThreeFpState::Paused || state==ThreeFpState::Ended)clock_->stop();
clock_.swap(output_);direct_=enabled;
clock_->setClockOnly(!enabled);
output_->setMuted(true);clock_->setMuted(mute_->isChecked());
clock_->setDecodeMode(settings_->value("decode/mode",2).toUInt());
auto *visible=direct_?clock_.get():output_.get();
applyScaling();
visible->setView(pane_->zoom(),pane_->pan().x(),pane_->pan().y());
if(opened){clock_->openFile(mediaInput_);rateApplied_=false;if(resumeAt_<0)resumeAt_=at;}
}
void PlayerWindow::updateProfile() {
if(superInterpolationStage()>=0 || (interpolationStage()>=0 && !interpolationAuto_ && interpolationStage()!=3) || (fixedAnimeStage()>=0 && !profileFallback_) || madvrMode() || (profile().isEmpty() && !networkSource()) || qualityStage_==5 || !ready_ || !playing_ || seekPending_ || profileResize_->isActive() || !qualitySettling_.isValid() || qualitySettling_.elapsed()<2000) {qualityTimer_.invalidate();return;}
const auto output=outputSnapshot();const auto dropped=skippedFrames_+output.droppedVideoFrames+output.coalescedVideoFrames;
if(!qualityTimer_.isValid()){qualityTimer_.start();qualityDropped_=dropped;qualitySubmitted_=direct_?output.presentedVideoFrames:submittedFrames_;return;}
if(qualityTimer_.elapsed()<5000)return;
qualityTimer_.invalidate();
if(dropped<qualityDropped_ || (direct_?output.presentedVideoFrames:submittedFrames_)<qualitySubmitted_)return;
const auto missed=dropped-qualityDropped_;
const auto frames=(direct_?output.presentedVideoFrames:submittedFrames_)-qualitySubmitted_;
if(frames+missed<48)return;
const double lag=clip_.fpsNumerator>0?position()/1e7-lastFrame_*double(clip_.fpsDenominator)/clip_.fpsNumerator:0;
const bool overloaded=double(missed)/(frames+missed)>.05 || (!direct_ && lag>.2);
if(interpolationStage()>=0){if(!interpolationAuto_)showInterpolationWarning(overloaded);else if(overloaded)advanceInterpolation();else showInterpolationWarning(false);return;}
if(!overloaded)return;
if(direct_ && !nativeAnime_)qualityStage_=4;
const auto order=builtinAnimeOrder();
int next=order.indexOf(qualityStage_)+1;
const auto allowed=settings_->value("player/animeStages",defaultAnimeStages()).toStringList();
while(next<order.size()-1 && !allowed.contains(QString::number(order[next])))++next;
resumeAt_=position();autoPlay_=true;qualityStage_=order.value(next,5);refreshScript();
showStatus(tr("丢帧超过 5%:切换到 %1。").arg(qualityNames().at(qualityStage_)));
}
void PlayerWindow::suspendQualityCheck() {qualityTimer_.invalidate();qualitySettling_.restart();}
int PlayerWindow::scalingAlgorithm(bool downscale) const {
if(downscale)return std::clamp(settings_->value("render/downscale",4).toInt(),0,8);
if(!customShaderPackage_.isEmpty() && !hlslFailed_)return 7;
if(direct_ && nativeAnime_ && qualityStage_<8){const int algorithms[]{10,9,7,7,4,7,13,13};if(qualityStage_!=4 && qualityStage_!=5)return algorithms[std::clamp(qualityStage_,0,7)];}
if(direct_ && (qualityStage_==5 || preset_.isEmpty()))return std::clamp(settings_->value("render/upscale",settings_->value("render/d3d11Upscale",15)).toInt(),0,15);
if(direct_ && qualityStage_==4)return std::clamp(settings_->value("render/upscale",15).toInt(),0,15);
if(!direct_)return std::clamp(settings_->value("render/secondUpscale",4).toInt(),0,15);
if(superInterpolationStage()==2 || (interpolationStage()>=0 && interpolationRenderer()==1))return 7;
return 4;
}
void PlayerWindow::applyScaling() {
auto *visible=direct_?clock_.get():output_.get();const bool native=scalingAlgorithm()==7;
visible->setVideoEnhancement(false,settings_->value("render/rtxVsr",false).toBool());
visible->setVideoEnhancement(true,direct_ && native && settings_->value("render/trueHdr",false).toBool());
openNguActive_=false;
const bool wantsOpenNgu=scalingAlgorithm()==15 || settings_->value("render/secondUpscale",4).toInt()==15;
const bool openNguCompatible=(source_.isEmpty() || positionRestored_) && !imageMode_ && !audioMode_ && hlslColorCompatible();
if(wantsOpenNgu && openNguCompatible){
const auto path=settings_->value("render/openNguShader",QDir(QCoreApplication::applicationDirPath()).filePath("shaders/OpenNGU-AA-Medium-BestMatch-2x-SDR.hlsl")).toString();
const auto shader=ShaderPackage::prepare(path);
openNguActive_=shader.error.isEmpty() && visible->setUpscaleShader(shader.packagePath);
if(!openNguActive_)hlslFallback_=QStringLiteral("OpenNGU → Jinc: %1").arg(shader.error.isEmpty()?visible->lastError():shader.error);
else if(hlslFallback_.startsWith("OpenNGU"))hlslFallback_.clear();
}else if(wantsOpenNgu)hlslFallback_=tr("OpenNGU 仅用于 BT.709 SDR,当前回退到 Jinc。");
if(!wantsOpenNgu && hlslFallback_.startsWith("OpenNGU"))hlslFallback_.clear();
if(!openNguActive_)visible->setUpscaleShader({});
const int second=settings_->value("render/secondUpscale",4).toInt();
visible->setSecondaryScaling(second==15 && !openNguActive_?4:second);
visible->setAntiRinging(settings_->value("render/antiring",true).toBool());
const int primary=scalingAlgorithm()==15 && !openNguActive_?4:scalingAlgorithm();
if(!visible->setScalingAlgorithms(static_cast<ThreeFpScalingAlgorithm>(primary),static_cast<ThreeFpScalingAlgorithm>(scalingAlgorithm(true))) && primary==15){
openNguActive_=false;visible->setUpscaleShader({});
if(!visible->setScalingAlgorithms(ThreeFpScalingAlgorithm::Jinc2,static_cast<ThreeFpScalingAlgorithm>(scalingAlgorithm(true))))
visible->setScalingAlgorithms(ThreeFpScalingAlgorithm::D3D11Native,static_cast<ThreeFpScalingAlgorithm>(scalingAlgorithm(true)));
}
if(hlslParameters_.isEmpty()){
// A new source must publish its own metadata before reusing the remembered shader.
const bool sourceReady=source_.isEmpty() || positionRestored_;
const bool compatible=sourceReady && !hlslFailed_ && !imageMode_ && !audioMode_ && !networkSource() && hlslColorCompatible();
if(!visible->setCustomShader(compatible?customShaderPackage_:QString()) && compatible && !customShaderPackage_.isEmpty()){
hlslFallback_=tr("自定义 HLSL 未启用:%1").arg(visible->lastError());visible->setCustomShader({});
if(nativeAnime_ && (qualityStage_==6 || qualityStage_==7)){
customShaderPackage_.clear();hlslFailed_=true;nativeAnime_=false;qualityStage_=5;profileFallback_=true;
visible->setScalingAlgorithms(ThreeFpScalingAlgorithm::D3D11Native,static_cast<ThreeFpScalingAlgorithm>(scalingAlgorithm(true)));
}
}
if(sourceReady && !compatible && !hlslFailed_ && !customShaderPackage_.isEmpty())hlslFallback_=tr("当前色彩路径不兼容,自定义 HLSL 已停用。");
}
}
}