Repository navigation
Expand file tree
/
Copy pathMainWindow.cpp
More file actions
1284 lines (1212 loc) · 70.8 KB
/
Copy pathMainWindow.cpp
File metadata and controls
1284 lines (1212 loc) · 70.8 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "app/MainWindow.h"
#include "ui/AgentPage.h"
#include "agent/AgentSession.h"
#include "agent/AgentMcp.h"
#include "agent/AgentInstructions.h"
#include "agent/AgentTaskQueue.h"
#include "agent/AgentModelCapabilities.h"
#include "app/ProjectProtection.inc"
#include "app/RenderRoute.h"
#include "ui/PageTheme.h"
#include "ui/NavigationIcons.h"
#include "ui/WrappedFileCombo.h"
#include "app/Style.h"
#include "player/PlayerLanguage.h"
#include "ui/About.h"
#include "update/ComponentDownloads.h"
#include "backend/FrameTimeline.h"
#include "ui/ExportWindow.h"
#include "ui/AnalysisPage.h"
#include "bluray/BlurayWidget.h"
#include <QProcess>
#include "graph/PresetStore.h"
#include "graph/HlslPreview.h"
#include "render/ShaderPackage.h"
#include <QStackedWidget>
#include <QToolButton>
#include <QStyle>
#include <QProgressBar>
#include <QSettings>
#include "update/PortableUpdater.h"
#include <QCloseEvent>
#include <QMessageBox>
#include "backend/ThreeFpPlayer.h"
#include "backend/VapourSynthFrameServer.h"
#include "graph/FilterCatalog.h"
#include "graph/VpyScriptBuilder.h"
#include "ui/CollapsibleSection.h"
#include "ui/CompareView.h"
#include "ui/ParameterEditor.h"
#include "ui/PresetCommunityDialog.h"
#include "ui/PreviewPane.h"
#include <QAction>
#include <QAbstractItemModel>
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QDateTime>
#include <QDialog>
#include <QDir>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QFormLayout>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QMessageBox>
#include <QMimeData>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QSaveFile>
#include <QScrollArea>
#include <QSignalBlocker>
#include <QSlider>
#include <QSplitter>
#include <QStandardPaths>
#include <QStatusBar>
#include <QTimer>
#include <QToolBar>
#include <QUrl>
#include <QVBoxLayout>
#include <QPainter>
#include <QStyleOptionToolButton>
#include <algorithm>
#include <utility>
namespace vsr {
namespace {
class NavigationButton final : public QToolButton {
public:
explicit NavigationButton(QWidget *parent):QToolButton(parent){setFixedHeight(40);setIconSize(QSize(22,22));setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);}
protected:
void paintEvent(QPaintEvent *event) override {
if (toolButtonStyle() == Qt::ToolButtonIconOnly) { QToolButton::paintEvent(event); return; }
QStyleOptionToolButton option; initStyleOption(&option);
option.text.clear(); option.icon = QIcon();
QPainter painter(this);
style()->drawComplexControl(QStyle::CC_ToolButton, &option, &painter, this);
icon().paint(&painter, QRect(9, (height() - 22) / 2, 22, 22));
painter.setPen(palette().color(QPalette::ButtonText));
painter.drawText(QRect(38, 0, width() - 48, height()), Qt::AlignLeft | Qt::AlignVCenter, text());
}
};
QString formatTime(std::int64_t value100ns)
{
const auto totalMs = std::max<std::int64_t>(0, value100ns / 10000);
const auto hours = totalMs / 3600000;
const auto minutes = (totalMs / 60000) % 60;
const auto seconds = (totalMs / 1000) % 60;
const auto millis = totalMs % 1000;
return QStringLiteral("%1:%2:%3.%4")
.arg(hours, 2, 10, QLatin1Char('0')).arg(minutes, 2, 10, QLatin1Char('0'))
.arg(seconds, 2, 10, QLatin1Char('0')).arg(millis, 3, 10, QLatin1Char('0'));
}
QPushButton *compactButton(const QString &text, QWidget *parent)
{
auto *button = new QPushButton(text, parent);
button->setFixedHeight(30);
return button;
}
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
language_=std::make_unique<PlayerLanguage>(QSettings().value("appearance/language","zh_CN").toString());
setWindowTitle(QStringLiteral("VS Renderer — VapourSynth 实时滤镜工作台"));
setAcceptDrops(true);
resize(1800, 900);
setMinimumSize(1120, 700);
buildToolbar();
auto *root = new QWidget(this);
auto *rootLayout = new QVBoxLayout(root);
rootLayout->setContentsMargins(0, 0, 0, 0);
rootLayout->setSpacing(0);
auto *content = content_ = new QSplitter(Qt::Horizontal, root);
content->setHandleWidth(1);
content->addWidget(featureOne_ = buildSidebar());
content->addWidget(featureTwo_ = buildParameterPanel());
content->addWidget(buildWorkspace());
content->setSizes({280, 320, 1156});
content->setStretchFactor(0, 0);
content->setStretchFactor(1, 0);
content->setStretchFactor(2, 1);
rootLayout->addWidget(content, 1);
auto *routeRow=new QGridLayout;routeChoice_=new QComboBox(root);routeChoice_->setObjectName("rendererRouteChoice");routeRow->addWidget(routeChoice_,0,0,1,4);
addRouteButton_=new QPushButton(QStringLiteral("加路"),root);addRouteButton_->setObjectName("rendererAddRoute");removeRouteButton_=new QPushButton(QStringLiteral("减路"),root);routeRow->addWidget(addRouteButton_,1,0);routeRow->addWidget(removeRouteButton_,1,1);
auto *showRoute=new QPushButton(QStringLiteral("显示"),root),*hideRoute=new QPushButton(QStringLiteral("隐藏"),root);showRoute->setObjectName("rendererShowRoute");hideRoute->setObjectName("rendererHideRoute");routeRow->addWidget(showRoute,1,2);routeRow->addWidget(hideRoute,1,3);qobject_cast<QVBoxLayout*>(featureOne_->layout())->addLayout(routeRow);
connect(addRouteButton_,&QPushButton::clicked,this,[this]{addRoute();});connect(removeRouteButton_,&QPushButton::clicked,this,&MainWindow::removeRoute);connect(routeChoice_,&QComboBox::currentIndexChanged,this,&MainWindow::selectRoute);
const auto visibility=[this](bool visible){routes_[routeIndex_].visible=visible;compareView_->setRouteVisible(routeIndex_,visible);if(routeIndex_>0)additionalRoutes_[routeIndex_-1]->setVisible(visible);else if(!visible){frameServer_->unloadScript();processedPlayer_->stop();vsScriptReady_=false;}updateRouteChoices();};
connect(showRoute,&QPushButton::clicked,this,[visibility]{visibility(true);});connect(hideRoute,&QPushButton::clicked,this,[visibility]{visibility(false);});updateRouteChoices();
auto *shell = new QWidget(this);
auto *shellLayout = new QHBoxLayout(shell);
shellLayout->setContentsMargins(0, 0, 0, 0);
shellLayout->setSpacing(0);
navigation_ = new QWidget(shell);
navigation_->setObjectName(QStringLiteral("pageNavigation"));
navigation_->setFixedWidth(44);
auto *navigationLayout = new QVBoxLayout(navigation_);
navigationLayout->setContentsMargins(2, 4, 2, 4);
for (int i = 0; i < 2; ++i) {
auto *button = new NavigationButton(navigation_);
button->setText(i == 0 ? QStringLiteral("VS 实时渲染") : QStringLiteral("图像分析比对"));
button->setToolTip(button->text());
button->setIcon(navigationIcon(i==0?NavigationGlyph::Render:NavigationGlyph::Compare));
button->setToolButtonStyle(Qt::ToolButtonIconOnly);
button->setCheckable(true);
button->setChecked(i == 0);
navigationButtons_.append(button);
navigationLayout->addWidget(button);
connect(button, &QToolButton::clicked, this, [this, i] { selectPage(i); });
}
navigationLayout->addStretch();
auto *settings = new NavigationButton(navigation_);
settings->setObjectName(QStringLiteral("applicationSettings"));
settings->setText(QStringLiteral("设置"));
settings->setToolTip(settings->text());
settings->setIcon(navigationIcon(NavigationGlyph::Settings));
settings->setToolButtonStyle(Qt::ToolButtonIconOnly);
settings->setCheckable(true);
navigationButtons_.append(settings);
navigationLayout->addWidget(settings);
connect(settings, &QToolButton::clicked, this, &MainWindow::showSettings);
pages_ = new QStackedWidget(shell);
pages_->addWidget(root);
pages_->addWidget(new QWidget(pages_)); // Reserve the lazily initialized analysis page.
pages_->addWidget(buildSettingsPage());
auto *bluray = new BlurayWidget(pages_);
pages_->addWidget(bluray);
auto *bdButton = new NavigationButton(navigation_);
bdButton->setText(QStringLiteral("BD 一键 Remux"));
bdButton->setToolTip(bdButton->text());
bdButton->setIcon(navigationIcon(NavigationGlyph::Disc));
bdButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
bdButton->setCheckable(true);
navigationButtons_.append(bdButton);
navigationLayout->insertWidget(2, bdButton);
connect(bdButton, &QToolButton::clicked, this, [this] { selectPage(3); });
initializeAgent();
auto *agentButton = new NavigationButton(navigation_);
agentButton->setObjectName("rendererAgentNavigation");
agentButton->setText(QStringLiteral("Agent 智能体"));
agentButton->setToolTip(agentButton->text());
agentButton->setIcon(navigationIcon(NavigationGlyph::Agent));
agentButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
agentButton->setCheckable(true);
navigationButtons_.append(agentButton);
navigationLayout->insertWidget(3, agentButton);
connect(agentButton, &QToolButton::clicked, this, [this] { selectPage(4); });
connect(bluray, &BlurayWidget::playRequested, this, [this](const QVector<BlurayTitle> &titles, int index) {
QString error;
const auto playlist = BlurayCatalog::prepare(titles.at(index), &error);
if (playlist.isEmpty()) { setStatus(error, true); return; }
if (!QProcess::startDetached(QDir(QCoreApplication::applicationDirPath()).filePath("vs-player.exe"), {playlist}))
setStatus(QStringLiteral("无法启动 VS Player"), true);
});
shellLayout->addWidget(navigation_);
shellLayout->addWidget(pages_, 1);
setCentralWidget(shell);
statusBar()->setFixedHeight(24);
taskStatus_ = new QLabel(this);
taskStatusTimer_=new QTimer(this);taskStatusTimer_->setSingleShot(true);taskStatusTimer_->setInterval(3000);connect(taskStatusTimer_,&QTimer::timeout,taskStatus_,&QWidget::hide);
frameStatus_ = new QLabel(QStringLiteral("帧 -- | VS -- | 3FP --"), this);
statusBar()->addWidget(taskStatus_, 1);
statusBar()->addPermanentWidget(frameStatus_);
sourcePlayer_ = std::make_unique<ThreeFpPlayer>(api_, sourcePane_->surface(), this);
processedPlayer_ = std::make_unique<ThreeFpPlayer>(api_, processedPane_->surface(), this);
sourcePlayer_->setScalingAlgorithms(static_cast<ThreeFpScalingAlgorithm>(7),static_cast<ThreeFpScalingAlgorithm>(7));
processedPlayer_->setScalingAlgorithms(static_cast<ThreeFpScalingAlgorithm>(7),static_cast<ThreeFpScalingAlgorithm>(7));
frameServer_ = std::make_unique<VapourSynthFrameServer>(this,false);
processedPlayer_->setMuted(true);
runtimeStatus_->setText(QStringLiteral("就绪"));
runtimeStatus_->setToolTip(QStringLiteral("3FP: %1\nVSScript: %2")
.arg(api_.libraryPath(), frameServer_->libraryPath()));
setStatus(QStringLiteral("就绪;打开源并点击“渲染预览”。"));
connectPlayback();
populateCatalog();
connect(frameServer_.get(), &VapourSynthFrameServer::scriptLoaded, this,
[this](const VapourSynthClipInfo &processed, const VapourSynthClipInfo &source) {
if(!hlslPreviewPackage_.isEmpty()){
const auto size=hlslOutputSize(hlslPreviewParameters_,QSize(processed.width,processed.height));
if(size.isEmpty() || !hlslAspectCompatible(hlslPreviewParameters_,QSize(processed.width,processed.height),size) || !processedPlayer_->setCustomShader(hlslPreviewPackage_,size.width(),size.height())){
hlslPreviewRetryGlSl_=true;hlslPreviewFallback_=QStringLiteral("HLSL 输出不兼容,已回退原 GLSL。");validateScript();return;
}
}
vsScriptReady_ = true;
sourceTotalFrames_ = source.totalFrames;
sourceFpsNumerator_ = source.fpsNumerator;
sourceFpsDenominator_ = source.fpsDenominator;
vsTotalFrames_ = processed.totalFrames;
vsFpsNumerator_ = processed.fpsNumerator;
vsFpsDenominator_ = processed.fpsDenominator;
requestedVsFrame_ = -1;
lastVsFrame_ = -1;
vsFramePending_ = false;
processedPane_->setBadge((hlslPreviewPackage_.isEmpty()?QStringLiteral("VS"):QStringLiteral("VS + HLSL"))+QStringLiteral(" · %1 · 首帧渲染中").arg(processed.formatName));
processedPane_->setSurfaceActive(true);
processedPlayer_->redraw();
setStatus(QStringLiteral("VPY 已载入:源 %1 帧,处理后 %2×%3 / %4 帧 / %5;正在定位当前帧。")
.arg(source.totalFrames).arg(processed.width).arg(processed.height)
.arg(processed.totalFrames).arg(processed.formatName)+(hlslPreviewFallback_.isEmpty()?QString():"\n"+hlslPreviewFallback_));
const auto snap = sourcePlayer_->snapshot();
requestProcessedFrame(static_cast<int>(frameAtPosition100ns(
snap.position100ns, vsTotalFrames_, vsFpsNumerator_, vsFpsDenominator_)));
});
connect(frameServer_.get(), &VapourSynthFrameServer::frameReady, this,
[this](const VapourSynthFrame &frame) {
vsFramePending_ = false;
if (timelineSeekPending_ || requestedVsFrame_ < 0 || frame.frameIndex != requestedVsFrame_)
return;
if(!hlslPreviewPackage_.isEmpty() && (frame.colorTransfer==16 || frame.colorTransfer==18 || frame.colorMatrix==9 || frame.colorMatrix==10 || (frame.colorPrimaries!=1 && frame.colorPrimaries!=2))){
hlslPreviewRetryGlSl_=true;hlslPreviewFallback_=QStringLiteral("当前色彩设置不兼容 HLSL 预览,已回退 GLSL。");validateScript();return;
}
bool recoveredDevice = false;
bool submitted = processedPlayer_->submitFrame(frame);
if (!submitted && processedPlayer_->lastError().contains(QStringLiteral("DeviceFailure"))) {
processedPane_->setSurfaceActive(true);
if (processedPlayer_->resetVideoOutput()) {
processedPlayer_->setMuted(true);
submitted = processedPlayer_->submitFrame(frame);
recoveredDevice = submitted;
}
}
if(!submitted && !hlslPreviewPackage_.isEmpty()){
hlslPreviewRetryGlSl_=true;hlslPreviewFallback_=QStringLiteral("HLSL 执行失败,已回退 GLSL:%1").arg(processedPlayer_->lastError());validateScript();return;
}
if (submitted) {
lastVsFrame_ = static_cast<int>(frame.frameIndex);
processedPane_->setSurfaceActive(true);
processedPane_->setBadge((hlslPreviewPackage_.isEmpty()?QStringLiteral("VS"):QStringLiteral("VS + HLSL"))+QStringLiteral(" · 实时 · 帧 %1").arg(frame.frameIndex));
if (recoveredDevice)
setStatus(QStringLiteral("右侧渲染设备已重建,处理链继续实时预览。"));
const auto source = sourcePlayer_->snapshot();
const int latest = static_cast<int>(frameAtPosition100ns(
source.position100ns, vsTotalFrames_, vsFpsNumerator_, vsFpsDenominator_));
if (!timelineSeekPending_ && latest >= 0 && latest != lastVsFrame_)
requestProcessedFrame(latest);
} else {
processedPane_->setPlaceholderText(processedPlayer_->lastError());
processedPane_->setSurfaceActive(false);
}
});
connect(frameServer_.get(), &VapourSynthFrameServer::errorOccurred, this,
[this](const QString &message) {
vsScriptReady_ = false;
vsFramePending_ = false;
processedPane_->setPlaceholderText(message);
processedPane_->setSurfaceActive(false);
processedPane_->setBadge(QStringLiteral("VS · 错误"));
setStatus(message, true);
});
qApp->installEventFilter(this);
stateTimer_ = new QTimer(this);
stateTimer_->setInterval(33);
connect(stateTimer_, &QTimer::timeout, this, &MainWindow::updatePlaybackState);
stateTimer_->start();
initializeProjectProtection();
connect(frameServer_.get(), &VapourSynthFrameServer::initialized, this, [this](bool ok) {
if (!pendingPreview_) return;
pendingPreview_ = false;
if (ok) {const int editing=routeIndex_;selectRoute(0);validateScript();selectRoute(editing);}else setStatus(frameServer_->errorString(),true);
});
language_->updateWidgets(this);
selectPage(pages_->currentIndex());
}
MainWindow::~MainWindow()
{
if (agentPage_) agentPage_->shutdown();
for(auto *queue:findChildren<AgentTaskQueue*>())queue->cancelAll();
delete agentModels_;
for(auto *queue:findChildren<AgentTaskQueue*>())delete queue;
delete agentMcp_; delete agentInstructions_;
}
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (pages_ && pages_->currentIndex() == 4)
return QMainWindow::eventFilter(watched, event);
if (isActiveWindow() && event->type() == QEvent::ShortcutOverride) {
auto *key = static_cast<QKeyEvent *>(event);
if (key->key() == Qt::Key_Space && key->modifiers() == Qt::NoModifier) {
event->accept();
return true;
}
}
if (isActiveWindow() && event->type() == QEvent::KeyPress) {
auto *key = static_cast<QKeyEvent *>(event);
if (key->key() == Qt::Key_Space && key->modifiers() == Qt::NoModifier) {
if (!key->isAutoRepeat())
togglePlayback();
event->accept();
return true;
}
}
return QMainWindow::eventFilter(watched, event);
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasUrls() && !event->mimeData()->urls().isEmpty() &&
event->mimeData()->urls().first().isLocalFile())
event->acceptProposedAction();
}
void MainWindow::dropEvent(QDropEvent *event)
{
if (!event->mimeData()->hasUrls() || event->mimeData()->urls().isEmpty())
return;
if (pages_->currentIndex() == 1) {
QStringList paths;
for (const auto &url : event->mimeData()->urls()) if (url.isLocalFile()) paths.append(url.toLocalFile());
analysisPage_->openFiles(paths);
event->acceptProposedAction();
return;
}
const QString path = event->mimeData()->urls().first().toLocalFile();
if(QFileInfo(path).isDir()){scanWorkingFolder(path);event->acceptProposedAction();return;}
if (!path.isEmpty() && QFileInfo(path).isFile() && loadSource(path))
event->acceptProposedAction();
}
void MainWindow::selectPage(int index)
{
QTimer::singleShot(0,this,[this,index]{if(index>=0 && index<pages_->count())applyPageTheme(pages_->widget(index),QDir(QCoreApplication::applicationDirPath()).filePath("themes.ini"),QStringList{"VSR-Main","VSR-Compare","VSR-Settings","VSR-BDRemux","VSR-Agent"}.value(index));});
if (index == 1 && !analysisPage_) {
analysisPage_ = std::make_unique<AnalysisPage>(api_);
auto *placeholder = pages_->widget(1);
pages_->removeWidget(placeholder);
delete placeholder;
pages_->insertWidget(1, analysisPage_.get());
}
if (index != pages_->currentIndex()) {
if (index != 0 && sourcePlayer_ && sourcePlayer_->snapshot().state == ThreeFpState::Playing)
sourcePlayer_->pause();
if (index != 1 && analysisPage_) analysisPage_->pause();
pages_->setCurrentIndex(index);
}
for (int i = 0; i < navigationButtons_.size(); ++i) navigationButtons_[i]->setChecked(i == index);
for (auto *action : vsActions_) action->setVisible(index == 0);
frameStatus_->setVisible(index == 0);
setStatus(index == 0 ? QStringLiteral("VS 实时渲染") : index == 1 ? QStringLiteral("图像分析比对 · 最大9路 ") : index == 3 ? QStringLiteral("BD 一键 Remux") : index == 4 ? QStringLiteral("Agent 智能体") : QStringLiteral("设置"));
}
void MainWindow::showSettings()
{
selectPage(2);
}
QWidget *MainWindow::buildSettingsPage()
{
auto *scroll = new QScrollArea(this);
scroll->setObjectName(QStringLiteral("rendererSettingsPage"));
scroll->setWidgetResizable(true);
auto *page = new QWidget(scroll);
scroll->setWidget(page);
page->setObjectName(QStringLiteral("rendererSettingsContent"));
auto *layout = new QVBoxLayout(page);
layout->setContentsMargins(20, 16, 20, 16);
layout->setAlignment(Qt::AlignTop);
layout->setSpacing(14);
layout->addWidget(new QLabel(QStringLiteral("设置"), page));
auto *label = new QLabel(QStringLiteral("VapourSynth 源滤镜"), page);
layout->addWidget(label);
auto *source = new QComboBox(page);
source->setObjectName(QStringLiteral("rendererSettingsSource"));
source->addItems({QStringLiteral("L-SMASH Works"), QStringLiteral("FFMS2"), QStringLiteral("3FP 原生(色彩保留)")});
source->setItemData(2, QStringLiteral("保留解码像素、浮点与HDR元数据;首次打开会完整解码建立索引,耗时取决于片长。不支持的格式会明确报错。"), Qt::ToolTipRole);
source->setCurrentIndex(sourceFilter_->currentIndex());
connect(sourceFilter_, &QComboBox::currentIndexChanged, source, &QComboBox::setCurrentIndex);
layout->addWidget(source);
auto *hint = new QLabel(QStringLiteral("用于 VS 预览与导出。更改后重新生成并验证脚本生效。"), page);
hint->setWordWrap(true); layout->addWidget(hint);
layout->addWidget(new QLabel(QStringLiteral("语言和主题"), page));
const auto skinPath=QDir(QCoreApplication::applicationDirPath()).filePath("themes.ini");
auto *skinButton=new QPushButton(QStringLiteral("多页面背景主题…"),page);skinButton->setObjectName("rendererPageThemes");layout->addWidget(skinButton);
connect(skinButton,&QPushButton::clicked,this,[this,skinPath]{if(editPageThemes(this,skinPath,{"VSR-Main","VSR-Compare","VSR-BDRemux","VSR-Settings","VSR-Agent","VSR-About"}))for(int i=0;i<pages_->count();++i)applyPageTheme(pages_->widget(i),skinPath,QStringList{"VSR-Main","VSR-Compare","VSR-Settings","VSR-BDRemux","VSR-Agent"}.value(i));});
auto *scanDepth=new QSpinBox(page);scanDepth->setObjectName("rendererScanDepth");scanDepth->setRange(0,16);scanDepth->setValue(QSettings().value("source/scanDepth",3).toInt());layout->addWidget(new QLabel(QStringLiteral("工作文件夹递归深度(0 仅当前目录)"),page));layout->addWidget(scanDepth);connect(scanDepth,&QSpinBox::valueChanged,this,[](int depth){QSettings().setValue("source/scanDepth",depth);});
auto *language=new QComboBox(page);language->setObjectName("rendererLanguage");language->addItem(QStringLiteral("中文"),"zh_CN");language->addItem("English","en_US");language->setCurrentIndex(qMax(0,language->findData(QSettings().value("appearance/language","zh_CN"))));layout->addWidget(language);
connect(language,&QComboBox::currentIndexChanged,this,[this,language]{const auto name=language->currentData().toString();QSettings().setValue("appearance/language",name);language_->setLanguage(name);language_->updateWidgets(this);});
auto *theme = new QComboBox(page);
theme->setObjectName("rendererTheme");
theme->addItems({QStringLiteral("浅色"),QStringLiteral("深色")});
theme->setCurrentIndex(QSettings().value("appearance/dark",false).toBool()?1:0);
layout->addWidget(theme);
connect(theme,&QComboBox::currentIndexChanged,page,[](int index){
QSettings().setValue("appearance/dark",index==1);
qApp->setStyleSheet(applicationStyleSheet(index==1));
});
auto *apply = new QPushButton(QStringLiteral("应用"), page);
apply->setObjectName(QStringLiteral("rendererApplySettings"));
layout->addWidget(apply);
layout->addWidget(new QLabel(QStringLiteral("预设下载源(ModelScope 公开目录链接或 JSON 清单)"),page));
auto *communitySource=new QLineEdit(page);communitySource->setMinimumWidth(650);communitySource->setObjectName("rendererCommunitySource");
auto communityUrl=QSettings().value("community/sourceUrl",PresetCommunityDialog::defaultSource()).toString();
if(communityUrl.contains("/api/v1/datasets/ARXChem/Software-List/repo/tree"))communityUrl=PresetCommunityDialog::defaultSource();
communitySource->setText(communityUrl);layout->addWidget(communitySource);
layout->removeWidget(apply);layout->addWidget(apply);
connect(apply, &QPushButton::clicked, this, [this, source,communitySource] {
const QUrl url(communitySource->text().trimmed());if(!url.isValid() || (url.scheme()!="http" && url.scheme()!="https")){setStatus(QStringLiteral("预设源必须是有效 HTTP / HTTPS 地址。"),true);return;}
QSettings().setValue("community/sourceUrl",url.toString());
sourceFilter_->setCurrentIndex(source->currentIndex());
QSettings().setValue(QStringLiteral("sourceFilter"), source->currentIndex());
setStatus(QStringLiteral("设置已保存,重新生成并验证脚本后生效。"));
});
layout->addWidget(new QLabel(QStringLiteral("当前版本:") + VSR_VERSION, page));
auto *updates = new QPushButton(QStringLiteral("检查更新"), page);
layout->addWidget(updates);
connect(updates, &QPushButton::clicked, page, [page] { PortableUpdater updater(page); updater.check(); updater.exec(); });
layout->addWidget(new QLabel(QStringLiteral("组件更新"),page));
auto *components = new ComponentDownloads(page);
components->setMinimumHeight(360);
layout->addWidget(components);
return scroll;
}
void MainWindow::buildToolbar()
{
auto *bar = addToolBar(QStringLiteral("命令栏"));
bar->setMovable(false);
bar->setFloatable(false);
bar->setFixedHeight(44);
bar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
auto *menu = bar->addAction(QStringLiteral("☰"));
menu->setObjectName(QStringLiteral("navigationToggle"));
menu->setToolTip(QStringLiteral("展开 / 收起页面导航"));
connect(menu, &QAction::triggered, this, [this] {
const bool expand = navigation_->width() == 44;
navigation_->setFixedWidth(expand ? 180 : 44);
for (auto *button : navigationButtons_)
button->setToolButtonStyle(expand ? Qt::ToolButtonTextBesideIcon : Qt::ToolButtonIconOnly);
});
auto *openSourceAction = bar->addAction(QStringLiteral("打开源"));
auto *openProjectAction = bar->addAction(QStringLiteral("打开项目"));
auto *saveProjectAction = bar->addAction(QStringLiteral("保存项目"));
auto *presetsAction = bar->addAction(QStringLiteral("预设管理"));
presetsAction->setObjectName("presetManagement");
auto *communityAction=bar->addAction(QStringLiteral("预设社区"));connect(communityAction,&QAction::triggered,this,&MainWindow::showCommunity);
auto *about = bar->addAction(QStringLiteral("关于"));
connect(about,&QAction::triggered,this,[this]{
QDialog dialog(this);dialog.setWindowTitle(QStringLiteral("关于 VS Renderer"));
QVBoxLayout layout(&dialog);layout.addWidget(aboutLabel("VS Renderer",&dialog));applyPageTheme(&dialog,QDir(QCoreApplication::applicationDirPath()).filePath("themes.ini"),"VSR-About");dialog.exec();
});
for(int index=0;index<2;++index){
auto *toggle=bar->addAction(QStringLiteral("隐藏功能区%1").arg(index+1));toggle->setCheckable(true);toggle->setChecked(true);toggle->setObjectName(QString("rendererToggleArea%1").arg(index+1));
connect(toggle,&QAction::triggered,this,[this,toggle,index](bool visible){
auto *area=index==0?featureOne_:featureTwo_;auto sizes=content_->sizes();if(!visible)featureWidths_[index]=sizes[index];
area->setVisible(visible);sizes[index]=visible?featureWidths_[index]:0;
sizes[2]=qMax(200,content_->width()-sizes[0]-sizes[1]);content_->setSizes(sizes);
toggle->setText(QStringLiteral("%1功能区%2").arg(visible?QStringLiteral("隐藏"):QStringLiteral("显示")).arg(index+1));
});
}
auto *loadVpyAction = bar->addAction(QStringLiteral("导入所有时间组"));
auto *loadGroupAction = bar->addAction(QStringLiteral("导入当前时间组"));
connect(loadGroupAction,&QAction::triggered,this,[this]{const auto path=QFileDialog::getOpenFileName(this,QStringLiteral("导入当前时间组"),PresetStore::directory(),"VapourSynth (*.vpy)");if(!path.isEmpty())loadPreset(path,true);});
connect(presetsAction, &QAction::triggered, this, &MainWindow::showPresets);
connect(loadVpyAction, &QAction::triggered, this, [this] {
const auto path = QFileDialog::getOpenFileName(this, QStringLiteral("加载 VPY"), PresetStore::directory(), "VapourSynth (*.vpy)");
if (!path.isEmpty()) loadPreset(path);
});
bar->addSeparator();
auto *viewScriptAction = bar->addAction(QStringLiteral("查看 VPY"));
auto *validateAction = bar->addAction(QStringLiteral("生成并验证"));
auto *previewAction = bar->addAction(QStringLiteral("渲染预览"));
previewAction->setToolTip(QStringLiteral("通过 VSScript 载入脚本,并把当前帧直接提交给 3FP。"));
auto *exportAction = bar->addAction(QStringLiteral("导出当前处理结果"));
exportAction->setToolTip(QStringLiteral("用 vspipe 输出当前 VS 处理链,再套用粘贴的 3FUI FFmpeg 参数。"));
auto *spacer = new QWidget(bar);
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
bar->addWidget(spacer);
vsActions_ = bar->actions();
vsActions_.removeFirst();
connect(openSourceAction, &QAction::triggered, this, &MainWindow::openSource);
connect(openProjectAction, &QAction::triggered, this, &MainWindow::openProject);
connect(saveProjectAction, &QAction::triggered, this, &MainWindow::saveProject);
connect(viewScriptAction, &QAction::triggered, this, &MainWindow::showScript);
connect(validateAction, &QAction::triggered, this, &MainWindow::validateScript);
connect(previewAction, &QAction::triggered, this, &MainWindow::validateScript);
connect(exportAction, &QAction::triggered, this, &MainWindow::exportCurrentResult);
}
QWidget *MainWindow::buildSidebar()
{
auto *sidebar = new QWidget(this);
sidebar->setMinimumWidth(250);
sidebar->setObjectName(QStringLiteral("processingSidebar"));
auto *layout = new QVBoxLayout(sidebar);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(1);
auto *input = fileInput_ = new QWidget(this);
auto *inputLayout = new QVBoxLayout(input);
inputLayout->setContentsMargins(0, 0, 0, 0);
inputLayout->setSpacing(4);
sourcePath_ = new QLineEdit(input);
sourcePath_->setObjectName(QStringLiteral("rendererSourcePath"));
sourcePath_->setMinimumWidth(0);
sourcePath_->setReadOnly(true);
sourcePath_->setAcceptDrops(false);
sourcePath_->setPlaceholderText(QStringLiteral("选择或拖入视频"));
fileInput_->setMinimumWidth(120);
fileInput_->setMaximumWidth(360);
fileInput_->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Preferred);
auto *inputRow = new QHBoxLayout;
sourceFilter_ = new QComboBox(this);
sourceFilter_->hide();
sourceFilter_->setObjectName(QStringLiteral("sourceFilter"));
sourceFilter_->addItem(QStringLiteral("L-SMASH Works"), static_cast<int>(SourceFilter::Lsmas));
sourceFilter_->addItem(QStringLiteral("FFMS2"), static_cast<int>(SourceFilter::Ffms2));
sourceFilter_->addItem(QStringLiteral("3FP 原生(色彩保留)"), static_cast<int>(SourceFilter::Native));
sourceFilter_->setItemData(2, QStringLiteral("保留解码像素、浮点与HDR元数据;首次打开会完整解码建立索引,耗时取决于片长。不支持的格式会明确报错。"), Qt::ToolTipRole);
auto *browse = compactButton(QStringLiteral("浏览…"), input);
browse->setObjectName(QStringLiteral("rendererBrowse"));
sourceFilter_->setCurrentIndex(QSettings().value(QStringLiteral("sourceFilter"),static_cast<int>(SourceFilter::Native)).toInt());
sourceInputStack_=new QStackedWidget(input);sourceInputStack_->setMinimumWidth(0);sourceInputStack_->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Preferred);sourceInputStack_->addWidget(sourcePath_);
sourceChoice_=new WrappedFileCombo(input);sourceChoice_->setObjectName("rendererSourceChoice");sourceChoice_->setMinimumContentsLength(6);sourceChoice_->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);sourceInputStack_->addWidget(sourceChoice_);
inputRow->addWidget(sourceInputStack_,1);
auto *folder=new QPushButton(QStringLiteral("打开文件夹"),input);folder->setObjectName("rendererFolderImport");connect(folder,&QPushButton::clicked,this,[this]{scanWorkingFolder();});
connect(sourceChoice_,&QComboBox::currentIndexChanged,this,[this](int index){if(index>=0)loadSource(sourceChoice_->itemData(index).toString());});
inputRow->setContentsMargins(0,0,0,0);
for(auto *control:QList<QWidget*>{sourcePath_,sourceChoice_,sourceInputStack_,browse,folder})control->setFixedHeight(30);
inputRow->addWidget(browse);inputRow->addWidget(folder);
inputLayout->addLayout(inputRow);
connect(browse, &QPushButton::clicked, this, &MainWindow::openSource);
connect(sourceFilter_, &QComboBox::currentIndexChanged, this, [this] { setStatus(QStringLiteral("源滤镜已更改,脚本待验证。")); });
auto *filters = new QWidget(sidebar);
auto *filtersLayout = new QVBoxLayout(filters);
filtersLayout->setContentsMargins(8, 8, 8, 8);
filtersLayout->setSpacing(4);
catalogSearch_ = new QLineEdit(filters);
catalogSearch_->setPlaceholderText(QStringLiteral("搜索滤镜"));
catalogList_ = new QListWidget(filters);
catalogList_->setObjectName(QStringLiteral("rendererCatalog"));
catalogList_->setMinimumHeight(190);
pipelineList_ = new QListWidget(filters);
pipelineList_->setMinimumHeight(68);
pipelineList_->setSelectionMode(QAbstractItemView::SingleSelection);
auto *add = compactButton(QStringLiteral("添加到处理链"), filters);
auto *nodeButtons = new QHBoxLayout;
auto *up = compactButton(QStringLiteral("上移"), filters);
auto *down = compactButton(QStringLiteral("下移"), filters);
auto *remove = compactButton(QStringLiteral("删除"), filters);
nodeButtons->addWidget(up);
nodeButtons->addWidget(down);
nodeButtons->addWidget(remove);
catalogCategory_=new QComboBox(filters);catalogCategory_->setObjectName("rendererCatalogCategory");catalogCategory_->addItem(QStringLiteral("全部"));catalogCategory_->addItems(FilterCatalog::categories());
filtersLayout->addWidget(catalogSearch_);filtersLayout->addWidget(catalogCategory_);
filtersLayout->addWidget(catalogList_, 3);
filtersLayout->addWidget(add);
pipelinePanel_=new QWidget(this);pipelinePanel_->setObjectName("rendererPipelinePanel");
auto *chainLayout=new QVBoxLayout(pipelinePanel_);chainLayout->setContentsMargins(8,8,8,8);
chainLayout->addWidget(new QLabel(QStringLiteral("当前时间组已导入的滤镜"),pipelinePanel_));
pipelineList_->setObjectName("rendererPipeline");chainLayout->addWidget(pipelineList_,1);chainLayout->addLayout(nodeButtons);
const auto filterCatalog=[this]{
const auto text=catalogSearch_->text();const auto category=catalogCategory_->currentText();
for(int i=0;i<catalogList_->count();++i){auto *item=catalogList_->item(i);item->setHidden(!item->data(Qt::UserRole+1).toString().contains(text,Qt::CaseInsensitive) || (catalogCategory_->currentIndex()>0 && item->data(Qt::UserRole+2).toString()!=category));}
if(catalogList_->currentItem() && catalogList_->currentItem()->isHidden())catalogList_->setCurrentRow(-1);
};
connect(catalogSearch_,&QLineEdit::textChanged,this,filterCatalog);connect(catalogCategory_,&QComboBox::currentTextChanged,this,filterCatalog);
connect(add, &QPushButton::clicked, this, [this] {
const auto *item = catalogList_->currentItem();
if (!item || item->isHidden())
return;
activePreset_.clear();
const int row = graph_.add(item->data(Qt::UserRole).toString());
refreshPipeline(row);
setStatus(QStringLiteral("已添加滤镜,VPY 待验证。"));
});
connect(catalogList_, &QListWidget::itemDoubleClicked, add, &QPushButton::click);
connect(pipelineList_, &QListWidget::currentRowChanged, this, &MainWindow::selectPipelineRow);
connect(pipelineList_, &QListWidget::itemChanged, this, [this](QListWidgetItem *item) {
activePreset_.clear();
graph_.setEnabled(pipelineList_->row(item), item->checkState() == Qt::Checked);checkpointProject();
setStatus(QStringLiteral("节点状态已更改,VPY 待验证。"));
});
connect(up, &QPushButton::clicked, this, [this] {
const int row = pipelineList_->currentRow();
activePreset_.clear();
if (row > 0 && graph_.move(row, row - 1)) refreshPipeline(row - 1);
});
connect(down, &QPushButton::clicked, this, [this] {
const int row = pipelineList_->currentRow();
activePreset_.clear();
if (row >= 0 && row + 1 < graph_.nodes().size() && graph_.move(row, row + 1)) refreshPipeline(row + 1);
});
connect(remove, &QPushButton::clicked, this, [this] {
const int row = pipelineList_->currentRow();
activePreset_.clear();
if (graph_.remove(row)) refreshPipeline(std::min(row, static_cast<int>(graph_.nodes().size()) - 1));
});
auto *split=new QSplitter(Qt::Vertical,sidebar);split->setObjectName("rendererLeftColumn");
split->addWidget(filters);split->addWidget(buildTimeGroups());split->setSizes({400,400});layout->addWidget(split,1);
return sidebar;
}
QWidget *MainWindow::buildParameterPanel()
{
auto *parameters = new QWidget(this);
parameters->setObjectName(QStringLiteral("rendererParameterPanel"));
parameters->setMinimumWidth(260);
auto *parameterLayout = new QVBoxLayout(parameters);
parameterLayout->setContentsMargins(0, 0, 0, 0);
parameterLayout->setSpacing(0);
auto *header = new QLabel(QStringLiteral("高级参数"), parameters);
header->setFixedHeight(32);
header->setStyleSheet(QStringLiteral("font-weight:600;padding:0 8px;"));
parameterLayout->addWidget(header);
parameterEditor_ = new ParameterEditor(parameters);
auto *parameterScroll = new QScrollArea(parameters);
parameterScroll->setObjectName(QStringLiteral("rendererParameters"));
parameterScroll->setWidgetResizable(true);
parameterScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
parameterScroll->setStyleSheet(QStringLiteral("QScrollArea#rendererParameters{border:0;}"));
parameterScroll->setWidget(parameterEditor_);
parameterLayout->addWidget(parameterScroll, 1);
connect(parameterEditor_, &ParameterEditor::parameterChanged, this,
[this](const QString &id, const QVariant &value) {
activePreset_.clear();
if (id == "mode" && value.toString() != QStringLiteral("自定义 GLSL")) graph_.setParameter(pipelineList_->currentRow(), "shader", "");
if (id == "shader" && !value.toString().isEmpty()) graph_.setParameter(pipelineList_->currentRow(), "mode", QStringLiteral("自定义 GLSL"));
if (graph_.setParameter(pipelineList_->currentRow(), id, value))
setStatus(QStringLiteral("参数已更新,VPY 待验证。"));
checkpointProject();
});
auto *column=new QSplitter(Qt::Vertical,this);column->setObjectName("rendererRightColumn");
column->addWidget(parameters);column->addWidget(pipelinePanel_);column->setSizes({400,400});
return column;
}
QWidget *MainWindow::buildWorkspace()
{
auto *workspace = new QWidget(this);
auto *layout = new QVBoxLayout(workspace);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
auto *compareBar = new QWidget(workspace);
compareBar->setFixedHeight(36);
auto *compareLayout = new QHBoxLayout(compareBar);
compareLayout->setContentsMargins(8, 2, 8, 2);
compareLayout->setSpacing(12);
compareLayout->addWidget(new QLabel(QStringLiteral("2-4路对比 · 左侧播放时钟 / 右侧 VS 同帧"), compareBar));
runtimeStatus_ = new QLabel(QStringLiteral("就绪"), compareBar);
runtimeStatus_->setObjectName(QStringLiteral("rendererWarmupState"));
runtimeStatus_->setStyleSheet(QStringLiteral("border:0;"));
compareLayout->addWidget(runtimeStatus_);
compareLayout->addStretch();
syncView_ = new QCheckBox(QStringLiteral("同步视图"), compareBar);
syncView_->setChecked(true);
vrrPresent_ = new QCheckBox(QStringLiteral("VRR 低延迟 (实验)"), compareBar);
vrrPacing_ = new QCheckBox(QStringLiteral("VRR Pacing (实验)"), compareBar);
vrrPresent_->setProperty("vrrToggle", true); vrrPacing_->setProperty("vrrToggle", true);
vrrPresent_->setToolTip(QStringLiteral("调用 FFF3FP_SetPresentConfig;不支持时保持 VSync。"));
vrrPacing_->setToolTip(QStringLiteral("调用 FFF3FP_SetPacingConfig;建议与 VRR 低延迟配合。"));
compareLayout->addWidget(syncView_);
compareLayout->addWidget(vrrPresent_);
compareLayout->addWidget(vrrPacing_);
compareView_ = new CompareView(workspace);
sourcePane_ = compareView_->sourcePane();
processedPane_ = compareView_->processedPane();
sourcePane_->setActive(true);
layout->addWidget(compareBar);
layout->addWidget(compareView_, 1);
auto *monitorRow=new QWidget(workspace);monitorRow->setStyleSheet("background:#17191c;color:#c6d3e1;font-family:Consolas;padding:5px;");
auto *monitors=new QHBoxLayout(monitorRow);monitors->setContentsMargins(4,0,4,0);
sourceMonitor_=new QLabel(QStringLiteral("源视频 · CPU -- GPU -- 内存 -- 丢帧 --"),monitorRow);
processedMonitor_=new QLabel(QStringLiteral("处理后 · CPU -- GPU -- 内存 -- 丢帧 --"),monitorRow);
sourceMonitor_->setObjectName("rendererSourceMonitor");processedMonitor_->setObjectName("rendererProcessedMonitor");
monitors->addWidget(sourceMonitor_,1);monitors->addWidget(processedMonitor_,1);layout->addWidget(monitorRow);
auto *monitorTimer=new QTimer(this);monitorTimer->setInterval(1000);
connect(monitorTimer,&QTimer::timeout,this,[this]{
if(!isVisible() || !sourcePlayer_ || !processedPlayer_)return;
const auto usage=resources_.sample();
const auto percent=[](double value){return value<0?QString("--"):QString::number(value,'f',1)+"%";};
const auto update=[&](QLabel *label,ThreeFpPlayer *player,const QString &name){const auto snap=player->snapshot();const auto total=snap.presentedVideoFrames+snap.droppedVideoFrames;
label->setText(QStringLiteral("%1 · CPU %2 GPU %3 内存 %4 MiB\n丢帧 %5 / %6 (%7%)").arg(name,percent(usage.cpu),percent(usage.gpu)).arg(usage.memoryMiB).arg(snap.droppedVideoFrames).arg(total).arg(total?100.0*snap.droppedVideoFrames/total:0,0,'f',2));};
update(sourceMonitor_,sourcePlayer_.get(),QStringLiteral("源视频"));update(processedMonitor_,processedPlayer_.get(),routes_.size()==1?QStringLiteral("处理后"):QStringLiteral("路1"));
});monitorTimer->start();
layout->addWidget(buildTransport());
return workspace;
}
QWidget *MainWindow::buildTransport()
{
auto *transport = new QWidget(this);
transport->setObjectName(QStringLiteral("rendererTransport"));
transport->setMinimumHeight(76);
auto *layout = new QVBoxLayout(transport);
layout->setContentsMargins(8, 2, 8, 2);
layout->setSpacing(2);
auto *timelineRow = new QHBoxLayout;
positionLabel_ = new QLabel(QStringLiteral("00:00:00.000"), transport);
positionLabel_->setObjectName(QStringLiteral("rendererPosition"));
durationLabel_ = new QLabel(QStringLiteral("00:00:00.000"), transport);
positionLabel_->setFixedWidth(92);
durationLabel_->setFixedWidth(92);
durationLabel_->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
timeline_ = new QSlider(Qt::Horizontal, transport);
timeline_->setObjectName(QStringLiteral("rendererTimeline"));
timeline_->setRange(0, 100000);
timelineRow->addWidget(positionLabel_);
timelineRow->addWidget(timeline_,1);
timelineRow->addWidget(durationLabel_);
auto *controlRow = new QHBoxLayout;
controlRow->setContentsMargins(0, 0, 0, 0);
auto *mode = new QComboBox(transport);
mode->setObjectName(QStringLiteral("rendererCompareMode"));
mode->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred);
mode->addItems({QStringLiteral("并排"), QStringLiteral("A/B 滑块")});
connect(compareView_,&CompareView::visiblePaneCountChanged,mode,[mode](int count){mode->setItemText(1,count==4?QStringLiteral("A/B/C/D 滑块"):count==3?QStringLiteral("A/B/C 滑块"):QStringLiteral("A/B 滑块"));});
auto *previous = compactButton(QStringLiteral("◀ 帧"), transport);
playButton_ = compactButton(QStringLiteral("播放"), transport);
auto *next = compactButton(QStringLiteral("帧 ▶"), transport);
auto *scaler = new QComboBox(transport);
scaler->setObjectName(QStringLiteral("rendererScaling"));
scaler->addItem(QStringLiteral("放大:Nearest"), static_cast<int>(ThreeFpScalingAlgorithm::Nearest));
scaler->addItem(QStringLiteral("放大:Bilinear"), static_cast<int>(ThreeFpScalingAlgorithm::Bilinear));
scaler->addItem(QStringLiteral("放大:Bicubic"), static_cast<int>(ThreeFpScalingAlgorithm::Bicubic));
scaler->addItem(QStringLiteral("放大:Lanczos 3"), static_cast<int>(ThreeFpScalingAlgorithm::Lanczos3));
scaler->addItem(QStringLiteral("放大:Jinc 2"), static_cast<int>(ThreeFpScalingAlgorithm::Jinc2));
scaler->addItem(QStringLiteral("放大:Spline36"), static_cast<int>(ThreeFpScalingAlgorithm::Spline36));
scaler->addItem(QStringLiteral("放大:Super-XBR (单阶段)"), static_cast<int>(ThreeFpScalingAlgorithm::SuperXbrSinglePass));
scaler->addItem(QStringLiteral("放大:Lanczos 4"), static_cast<int>(ThreeFpScalingAlgorithm::Lanczos4));
scaler->addItem(QStringLiteral("缩放:D3D11 原生直通"),7);
scaler->setCurrentIndex(scaler->count()-1);
scaler->addItem(QStringLiteral("放大:OpenNGU"),15);
scaler->setItemData(scaler->count()-1,QStringLiteral("OpenNGU 仅用于 BT.709 SDR 放大;缩小默认回退 D3D11 原生直通。不兼容色彩或缺失资源时回退 Jinc。"),Qt::ToolTipRole);
scaler->setToolTip(QStringLiteral("D3D11 使用与播放器相同的原生直通;其他算法的缩小使用 Lanczos 3。"));
auto *frameControls = new QWidget(transport);
frameControls->setObjectName(QStringLiteral("rendererFrameControls"));
auto *frames = new QHBoxLayout(frameControls);
frames->setContentsMargins(0, 0, 0, 0);
frameControls->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Preferred);
frames->addWidget(previous); frames->addWidget(playButton_); frames->addWidget(next);
fileInput_->setFixedHeight(30);mode->setFixedHeight(30);scaler->setFixedHeight(30);frameControls->setFixedHeight(30);
controlRow->addWidget(fileInput_,1);
controlRow->addStretch(1);
controlRow->addWidget(frameControls);
controlRow->addWidget(mode);
scaler->setSizeAdjustPolicy(QComboBox::AdjustToContents);
scaler->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Preferred);
controlRow->addWidget(scaler);
layout->addLayout(timelineRow);
layout->addLayout(controlRow);
connect(mode, &QComboBox::currentIndexChanged, this, [this](int index) {
compareView_->setMode(index == 1 ? CompareMode::Slider : CompareMode::SideBySide);
QTimer::singleShot(40, this, [this] {
sourcePlayer_->redraw();
processedPlayer_->redraw();
});
setStatus(index == 1 ? QStringLiteral("拖动蓝色分界线比较各路同一位置;三路/四路复用 Compare 滑块。")
: QStringLiteral("已切换为并排比较。"));
});
connect(timeline_, &QSlider::sliderPressed, this, [this] { timelinePressed_ = true; });
connect(timeline_, &QSlider::sliderMoved, this, [this](int value) {
const auto snap = sourcePlayer_ ? sourcePlayer_->snapshot() : ThreeFpSnapshot{};
if (snap.duration100ns > 0)
positionLabel_->setText(formatTime(snap.duration100ns * value / timeline_->maximum()));
seekTimeline(value);
});
connect(timeline_, &QSlider::sliderReleased, this, [this] {
timelinePressed_ = false;
seekTimeline(timeline_->value());
});
connect(previous, &QPushButton::clicked, this, [this] {
if (sourcePlayer_) sourcePlayer_->stepFrame(-1);
playing_ = false;
});
connect(next, &QPushButton::clicked, this, [this] {
if (sourcePlayer_) sourcePlayer_->stepFrame(1);
playing_ = false;
});
connect(scaler, &QComboBox::currentIndexChanged, this, &MainWindow::applyPreviewScaling);
return transport;
}
void MainWindow::applyPreviewScaling()
{
auto *scaler=findChild<QComboBox*>(QStringLiteral("rendererScaling"));
const bool ngu=scaler->currentData().toInt()==15;
scaler->setToolTip(ngu?scaler->currentData(Qt::ToolTipRole).toString():QStringLiteral("D3D11 使用与播放器相同的原生直通;其他算法的缩小使用 Lanczos 3。"));
const auto shader=ngu?ShaderPackage::prepare(QDir(QCoreApplication::applicationDirPath()).filePath("shaders/OpenNGU-AA-Medium-BestMatch-2x-SDR.hlsl")):ShaderPackageResult{};
auto upscale=static_cast<ThreeFpScalingAlgorithm>(ngu && !shader.error.isEmpty()?4:scaler->currentData().toInt());
const auto downscale=ngu || upscale==ThreeFpScalingAlgorithm::D3D11Native?ThreeFpScalingAlgorithm::D3D11Native:ThreeFpScalingAlgorithm::Lanczos3;
bool ok=sourcePlayer_->setUpscaleShader(shader.packagePath);
ok=processedPlayer_->setUpscaleShader(shader.packagePath) && ok;
for(auto &route:additionalRoutes_)ok=route->setUpscaleShader(shader.packagePath) && ok;
if(!ok && ngu)upscale=ThreeFpScalingAlgorithm::Jinc2;
ok=sourcePlayer_->setScalingAlgorithms(upscale,downscale) && ok;
ok=processedPlayer_->setScalingAlgorithms(upscale,downscale) && ok;
for(auto &route:additionalRoutes_)route->setScalingAlgorithms(upscale,downscale);
setStatus(!shader.error.isEmpty()?QStringLiteral("OpenNGU → Jinc: %1").arg(shader.error):ok?QStringLiteral("缩放算法:%1").arg(scaler->currentText().section(QStringLiteral(":"),1)):QStringLiteral("3FP 缩放算法切换失败,OpenNGU 放大回退 Jinc。"),!ok || !shader.error.isEmpty());
}
void MainWindow::connectPlayback()
{
connect(playButton_, &QPushButton::clicked, this, &MainWindow::togglePlayback);
connect(vrrPresent_, &QCheckBox::toggled, this, [this](bool enabled) {
const bool left = sourcePlayer_->setVrrPresent(enabled);
const bool right = processedPlayer_->setVrrPresent(enabled);
setStatus(enabled && !(left && right) ? QStringLiteral("显示链不支持 tearing,已保持 VSync。")
: QStringLiteral("VRR low-latency present 已更新。"));
});
connect(vrrPacing_, &QCheckBox::toggled, this, [this](bool enabled) {
const bool left = sourcePlayer_->setVrrPacing(enabled);
const bool right = processedPlayer_->setVrrPacing(enabled);
setStatus(enabled && !(left && right) ? QStringLiteral("当前 3FP 不支持 VRR Pacing。")
: QStringLiteral("VRR Pacing 已更新。"));
});
const auto wireView = [this](PreviewPane *from, PreviewPane *other, ThreeFpPlayer *first, ThreeFpPlayer *second) {
connect(from, &PreviewPane::viewChanged, this, [this, other, first, second](float zoom, float x, float y) {
first->setView(zoom, x, y);
if (syncView_->isChecked()) {
other->adoptView(zoom, x, y);
second->setView(zoom, x, y);
for(auto &route:additionalRoutes_)route->setView(zoom,x,y);
}
});
};
wireView(sourcePane_, processedPane_, sourcePlayer_.get(), processedPlayer_.get());
wireView(processedPane_, sourcePane_, processedPlayer_.get(), sourcePlayer_.get());
connect(sourcePane_, &PreviewPane::redrawRequested, sourcePlayer_.get(), &ThreeFpPlayer::redraw);
connect(processedPane_, &PreviewPane::redrawRequested, processedPlayer_.get(), &ThreeFpPlayer::redraw);
connect(sourcePane_, &PreviewPane::pixelHovered, this, [this](int x, int y) { updatePixel(sourcePlayer_.get(), sourcePane_, x, y); });
connect(processedPane_, &PreviewPane::pixelHovered, this, [this](int x, int y) { updatePixel(processedPlayer_.get(), processedPane_, x, y); });
connect(sourcePane_, &PreviewPane::activated, this, [this] { sourcePane_->setActive(true); processedPane_->setActive(false); });
connect(processedPane_, &PreviewPane::activated, this, [this] { sourcePane_->setActive(false); processedPane_->setActive(true); });
connect(sourcePlayer_.get(), &ThreeFpPlayer::errorOccurred, this, [this](const QString &e) { setStatus(e, true); });
connect(processedPlayer_.get(), &ThreeFpPlayer::errorOccurred, this, [this](const QString &e) { setStatus(e, true); });
}
void MainWindow::populateCatalog()
{
int textWidth = 0;
for (const auto &definition : FilterCatalog::all()) {
auto *item = new QListWidgetItem(definition.name, catalogList_);
textWidth = std::max(textWidth, catalogList_->fontMetrics().horizontalAdvance(definition.name));
item->setData(Qt::UserRole, definition.id);
item->setData(Qt::UserRole + 1, definition.name + ' ' + definition.category);item->setData(Qt::UserRole+2,definition.category);
item->setToolTip(QStringLiteral("%1 · %2\n%3\n依赖 namespace: %4").arg(definition.name, definition.category, definition.description, definition.pluginNamespace));
}
auto *sidebar = findChild<QWidget *>(QStringLiteral("processingSidebar"));
sidebar->setMinimumWidth(std::max(250, textWidth + 44));
sidebar->setMaximumWidth(std::max(360, sidebar->minimumWidth()));
if (catalogList_->count() > 0)
catalogList_->setCurrentRow(0);
}
void MainWindow::refreshPipeline(int selectRow)
{
QTimer::singleShot(0,this,&MainWindow::checkpointProject);
QSignalBlocker blocker(pipelineList_);
pipelineList_->clear();
for (const auto &node : graph_.nodes()) {
const auto *definition = FilterCatalog::find(node.definitionId);
auto *item = new QListWidgetItem(definition ? definition->name : node.definitionId, pipelineList_);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setCheckState(node.enabled ? Qt::Checked : Qt::Unchecked);
}
pipelineList_->setCurrentRow(selectRow);
selectPipelineRow(selectRow);
}
void MainWindow::selectPipelineRow(int row)
{
const auto *node = graph_.at(row);
parameterEditor_->setNode(node ? FilterCatalog::find(node->definitionId) : nullptr, node);
updateParameterInputSize();
}
void MainWindow::updateParameterInputSize()
{
if(!sourcePlayer_ || !parameterEditor_)return;
const auto source=sourcePlayer_->snapshot();QSize size(source.videoWidth,source.videoHeight);
if(size.isEmpty())return;
for(int i=0;i<pipelineList_->currentRow();++i){
if(size.isEmpty())return;
const auto *node=graph_.at(i);if(!node || !node->enabled)continue;const auto &p=node->parameters;
if(node->definitionId=="crop")size-=QSize(p.value("left").toInt()+p.value("right").toInt(),p.value("top").toInt()+p.value("bottom").toInt());
else if(node->definitionId=="transpose")size.transpose();
else if(node->definitionId=="resize" || node->definitionId=="descale")size=QSize(p.value("width").toInt(),p.value("height").toInt());
else if(node->definitionId=="anime4k"){
if(p.value("output_mode").toString()!="指定分辨率"){const auto scale=p.value("scale").toString().section(QChar(0x00d7),0,0).toDouble();size=QSize(qMax(2,int(size.width()*scale)),qMax(2,int(size.height()*scale)));}
else if(!p.value("keep_aspect",true).toBool())size=QSize(p.value("width",1920).toInt(),p.value("height",1080).toInt());
else if(p.value("dimension_axis","width")=="height")size=QSize(qMax(2,qRound(double(p.value("height",1080).toInt())*size.width()/size.height())),p.value("height",1080).toInt());
else size=QSize(p.value("width",1920).toInt(),qMax(2,qRound(double(p.value("width",1920).toInt())*size.height()/size.width())));
}
}
parameterEditor_->setInputSize(size);
}
void MainWindow::openSource()
{
const QString path = QFileDialog::getOpenFileName(this, QStringLiteral("打开源视频"), {},
QStringLiteral("视频与图像 (*.mkv *.mp4 *.m2ts *.ts *.mov *.avi *.webm *.vpy *.png *.jpg *.tif);;所有文件 (*.*)"));
if (!path.isEmpty())
loadSource(path);
}
bool MainWindow::loadSource(const QString &path)
{
playerRangeIn_=playerRangeOut_=-1;
++folderScanGeneration_;
const int folderIndex=sourceChoice_->findData(path);const QSignalBlocker sourceBlocker(sourceChoice_);sourceInputStack_->setCurrentIndex(folderIndex<0?0:1);if(folderIndex>=0)sourceChoice_->setCurrentIndex(folderIndex);
if (QFileInfo(path).suffix().compare("vpy", Qt::CaseInsensitive) == 0) { loadPreset(path); return true; }
if (!QFileInfo(path).isFile()) {
setStatus(QStringLiteral("源文件不存在:%1").arg(path), true);
return false;