-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVfxEnc.cpp
More file actions
1575 lines (1371 loc) · 49.9 KB
/
VfxEnc.cpp
File metadata and controls
1575 lines (1371 loc) · 49.9 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
// VfxEnc.cpp
// Win32 + libmpv preview, drag&drop video + mpv .hook GLSL shaders,
// reorder shaders by drag inside list, and re-encode via ffmpeg+libplacebo.
//
// Build: link against mpv.lib, ensure mpv-2.dll is available at runtime.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <commdlg.h>
#include <commctrl.h>
#include <ShlObj.h>
#include <mpv/client.h>
#include <string>
#include <vector>
#include <algorithm>
#include <thread>
#include <fstream>
#include <sstream>
#pragma comment(lib, "Comdlg32.lib")
#pragma comment(lib, "Shell32.lib")
#pragma comment(lib, "Ole32.lib")
#pragma comment(lib, "Comctl32.lib")
#ifndef LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
#endif
#ifndef LOAD_LIBRARY_SEARCH_USER_DIRS
#define LOAD_LIBRARY_SEARCH_USER_DIRS 0x00000400
#endif
// ----------------------------
// Globals (small app, simple)
// ----------------------------
static HINSTANCE g_hInst = nullptr;
static HWND g_hwndMain = nullptr;
static HWND g_hwndVideo = nullptr;
static HWND g_hwndList = nullptr;
static HWND g_hwndStatus = nullptr;
static HWND g_hwndBitrate = nullptr;
static HWND g_hwndBitrateLabel = nullptr;
static HWND g_hwndPlayPause = nullptr;
static HWND g_hwndAddVideo = nullptr;
static HWND g_hwndAddShader = nullptr;
static HWND g_hwndFiltersLabel = nullptr;
static HWND g_hwndEncoder = nullptr;
static HWND g_hwndEncoderLabel = nullptr;
static mpv_handle* g_mpv = nullptr;
static std::wstring g_loadedVideo;
static std::vector<std::wstring> g_shaders;
static std::vector<bool> g_shaderBypass;
static int g_bitrateMbps = 0; // 0 = same as input
static std::wstring g_encoderChoice = L"auto";
static bool g_isPlaying = false;
static std::wstring g_lastVideoDir;
static std::wstring g_lastShaderDir;
// (no custom brushes)
// listbox drag reorder state
static WNDPROC g_listOrigProc = nullptr;
static bool g_dragging = false;
static int g_dragIndex = -1;
// ----------------------------
// Helpers
// ----------------------------
static std::wstring JoinPath(const std::wstring& a, const std::wstring& b);
static void ListRefresh();
static void MpvApplyShaderList();
static void AddShaderPath(const std::wstring& path);
static std::wstring GetExeDir()
{
wchar_t path[MAX_PATH];
GetModuleFileNameW(nullptr, path, MAX_PATH);
std::wstring s = path;
auto pos = s.find_last_of(L"\\/");
return (pos == std::wstring::npos) ? L"." : s.substr(0, pos);
}
static void SetupDllSearchPath()
{
std::wstring deps = JoinPath(GetExeDir(), L"deps");
HMODULE k32 = GetModuleHandleW(L"kernel32.dll");
if (!k32) {
SetDllDirectoryW(deps.c_str());
return;
}
typedef BOOL (WINAPI *SetDefaultDllDirectoriesFn)(DWORD);
typedef PVOID (WINAPI *AddDllDirectoryFn)(PCWSTR);
auto pSetDefault = (SetDefaultDllDirectoriesFn)GetProcAddress(k32, "SetDefaultDllDirectories");
auto pAdd = (AddDllDirectoryFn)GetProcAddress(k32, "AddDllDirectory");
if (pSetDefault && pAdd) {
pSetDefault(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
pAdd(deps.c_str());
} else {
SetDllDirectoryW(deps.c_str());
}
}
static std::wstring GetAppDataDir()
{
PWSTR path = nullptr;
std::wstring dir;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path)) && path) {
dir = JoinPath(path, L"VfxEnc");
CoTaskMemFree(path);
} else {
dir = GetExeDir();
}
CreateDirectoryW(dir.c_str(), nullptr);
return dir;
}
static std::wstring GetShadersSavePath()
{
return JoinPath(GetAppDataDir(), L"shaders.txt");
}
static std::wstring GetSettingsPath()
{
return JoinPath(GetAppDataDir(), L"settings.txt");
}
static std::string WideToUtf8(const std::wstring& s)
{
if (s.empty()) return {};
int len = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string out(len > 0 ? len - 1 : 0, '\0');
if (len > 1) WideCharToMultiByte(CP_UTF8, 0, s.c_str(), -1, out.data(), len, nullptr, nullptr);
return out;
}
static std::wstring Utf8ToWide(const std::string& s)
{
if (s.empty()) return {};
int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
std::wstring out(len > 0 ? len - 1 : 0, L'\0');
if (len > 1) MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, out.data(), len);
return out;
}
static void WriteLogLine(HANDLE h, const std::wstring& line)
{
if (h == INVALID_HANDLE_VALUE) return;
std::string utf8 = WideToUtf8(line);
if (utf8.empty()) return;
DWORD written = 0;
WriteFile(h, utf8.data(), (DWORD)utf8.size(), &written, nullptr);
}
static bool EndsWithI(const std::wstring& s, const std::wstring& suf)
{
if (s.size() < suf.size()) return false;
auto a = s.substr(s.size() - suf.size());
auto lower = [](wchar_t c){ return (wchar_t)CharLowerW((LPWSTR)(ULONG_PTR)c); };
for (size_t i=0;i<suf.size();++i) {
wchar_t ca = towlower(a[i]);
wchar_t cb = towlower(suf[i]);
if (ca != cb) return false;
}
return true;
}
static bool IsShaderFile(const std::wstring& p)
{
// accept common mpv/libplacebo shader suffixes
return EndsWithI(p, L".glsl") || EndsWithI(p, L".hook.glsl") || EndsWithI(p, L".hook") || EndsWithI(p, L".frag") || EndsWithI(p, L".fs");
}
static bool IsLikelyVideo(const std::wstring& p)
{
// crude but practical; mpv will accept many containers
return EndsWithI(p,L".mp4")||EndsWithI(p,L".mkv")||EndsWithI(p,L".mov")||EndsWithI(p,L".avi")||
EndsWithI(p,L".ts") ||EndsWithI(p,L".m2ts")||EndsWithI(p,L".webm")||EndsWithI(p,L".m4v");
}
static void SetStatus(const std::wstring& msg)
{
if (g_hwndStatus) SetWindowTextW(g_hwndStatus, msg.c_str());
}
static void UpdatePlayPauseLabel()
{
if (!g_hwndPlayPause) return;
int pause = 1;
if (g_mpv) {
mpv_get_property(g_mpv, "pause", MPV_FORMAT_FLAG, &pause);
}
g_isPlaying = (pause == 0);
SetWindowTextW(g_hwndPlayPause, L"Play");
InvalidateRect(g_hwndPlayPause, nullptr, TRUE);
}
static std::wstring Quote(const std::wstring& s)
{
std::wstring out = L"\"";
out += s;
out += L"\"";
return out;
}
static std::wstring BasenameNoExt(const std::wstring& path)
{
auto slash = path.find_last_of(L"\\/");
std::wstring file = (slash == std::wstring::npos) ? path : path.substr(slash+1);
auto dot = file.find_last_of(L'.');
if (dot != std::wstring::npos) file = file.substr(0, dot);
return file;
}
static std::wstring FilenameOnly(const std::wstring& path)
{
auto slash = path.find_last_of(L"\\/");
return (slash == std::wstring::npos) ? path : path.substr(slash+1);
}
static std::wstring Dirname(const std::wstring& path)
{
auto slash = path.find_last_of(L"\\/");
return (slash == std::wstring::npos) ? L"." : path.substr(0, slash);
}
static std::wstring JoinPath(const std::wstring& a, const std::wstring& b)
{
if (a.empty()) return b;
wchar_t last = a.back();
if (last == L'\\' || last == L'/') return a + b;
return a + L"\\" + b;
}
static double GetMpvDurationSeconds()
{
if (!g_mpv) return 0.0;
double duration = 0.0;
if (mpv_get_property(g_mpv, "duration", MPV_FORMAT_DOUBLE, &duration) >= 0 && duration > 0.0) {
return duration;
}
return 0.0;
}
static std::wstring BuildEncoderArgs(const std::wstring& enc, int targetMbps)
{
wchar_t rate[64];
wchar_t buf[64];
swprintf_s(rate, L"%dM", targetMbps);
swprintf_s(buf, L"%dM", targetMbps * 2);
if (enc == L"hevc_amf") {
return L"-c:v hevc_amf -rc cbr -b:v " + std::wstring(rate) + L" -maxrate " + rate + L" -bufsize " + buf;
}
if (enc == L"hevc_nvenc") {
return L"-c:v hevc_nvenc -preset p5 -rc vbr -cq 23 -b:v " + std::wstring(rate) + L" -maxrate " + rate + L" -bufsize " + buf;
}
if (enc == L"hevc_qsv") {
return L"-c:v hevc_qsv -b:v " + std::wstring(rate) + L" -maxrate " + rate + L" -bufsize " + buf;
}
if (enc == L"hevc_mf") {
return L"-c:v hevc_mf -b:v " + std::wstring(rate);
}
// software fallback
return L"-c:v libx265 -b:v " + std::wstring(rate) + L" -maxrate " + rate + L" -bufsize " + buf;
}
static int ParseBitrateKbps(const std::string& text)
{
size_t pos = text.find("bitrate:");
while (pos != std::string::npos) {
pos += 8;
while (pos < text.size() && (text[pos] == ' ' || text[pos] == '\t')) pos++;
if (pos + 2 < text.size() && text.compare(pos, 3, "N/A") == 0) return 0;
int val = 0;
bool any = false;
while (pos < text.size() && text[pos] >= '0' && text[pos] <= '9') {
any = true;
val = val * 10 + (text[pos] - '0');
pos++;
}
if (any && val > 0) return val;
pos = text.find("bitrate:", pos);
}
return 0;
}
static int64_t ParseOutTimeMs(const std::string& line)
{
const char* key = "out_time_ms=";
if (line.rfind(key, 0) != 0) return -1;
int64_t v = 0;
bool any = false;
for (size_t i = strlen(key); i < line.size(); ++i) {
char c = line[i];
if (c < '0' || c > '9') break;
any = true;
v = v * 10 + (c - '0');
}
return any ? v : -1;
}
static int ProbeBitrateKbpsWithFfmpeg(const std::wstring& ffmpeg, const std::wstring& file)
{
std::wstring cmd = Quote(ffmpeg) + L" -hide_banner -i " + Quote(file);
SECURITY_ATTRIBUTES sa{};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = nullptr;
HANDLE hRead = nullptr;
HANDLE hWrite = nullptr;
if (!CreatePipe(&hRead, &hWrite, &sa, 0)) return 0;
SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
STARTUPINFOW si{};
si.cb = sizeof(si);
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdOutput = hWrite;
si.hStdError = hWrite;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
PROCESS_INFORMATION pi{};
std::wstring mutableCmd = cmd;
BOOL ok = CreateProcessW(
nullptr,
mutableCmd.data(),
nullptr, nullptr,
TRUE,
CREATE_NO_WINDOW,
nullptr,
nullptr,
&si, &pi
);
CloseHandle(hWrite);
if (!ok) {
CloseHandle(hRead);
return 0;
}
std::string output;
char buf[4096];
DWORD read = 0;
while (ReadFile(hRead, buf, sizeof(buf), &read, nullptr) && read > 0) {
output.append(buf, buf + read);
}
CloseHandle(hRead);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return ParseBitrateKbps(output);
}
static std::wstring FfmpegEscapeFilterValue(const std::wstring& value)
{
// ffmpeg filter args use ':' as option separators; escape special chars.
std::wstring out;
out.reserve(value.size() * 2);
for (wchar_t c : value) {
if (c == L'\\') {
out.push_back(L'/');
continue;
}
switch (c) {
case L':': out += L"\\:"; break;
case L',': out += L"\\,"; break;
case L'=': out += L"\\="; break;
default: out.push_back(c); break;
}
}
return out;
}
static bool ReadTextFile(const std::wstring& path, std::string& out)
{
std::ifstream f(path, std::ios::binary);
if (!f) return false;
std::ostringstream ss;
ss << f.rdbuf();
out = ss.str();
return true;
}
static std::wstring WriteCombinedShaderTemp(const std::vector<std::wstring>& shaders, std::wstring* outFilename)
{
std::wstring outDir = GetExeDir();
SYSTEMTIME st{};
GetSystemTime(&st);
wchar_t name[256];
swprintf_s(name, L"combined_shaders_%04u%02u%02u_%02u%02u%02u.glsl",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
if (outFilename) *outFilename = name;
std::wstring outPath = JoinPath(outDir, name);
std::ofstream o(outPath, std::ios::binary);
if (!o) return L"";
for (const auto& s : shaders) {
std::string text;
if (ReadTextFile(s, text)) {
o << "\n// ---- BEGIN: " << std::string(s.begin(), s.end()) << "\n";
o << text;
o << "\n// ---- END\n";
}
}
return outPath;
}
static void SaveSettings()
{
std::ofstream o(GetSettingsPath(), std::ios::binary);
if (!o) return;
if (!g_lastVideoDir.empty()) {
o << "video=" << WideToUtf8(g_lastVideoDir) << "\n";
}
if (!g_lastShaderDir.empty()) {
o << "shader=" << WideToUtf8(g_lastShaderDir) << "\n";
}
}
static void LoadSettings()
{
g_lastVideoDir.clear();
g_lastShaderDir.clear();
std::ifstream f(GetSettingsPath(), std::ios::binary);
if (!f) return;
std::string line;
while (std::getline(f, line)) {
if (line.rfind("video=", 0) == 0) {
g_lastVideoDir = Utf8ToWide(line.substr(6));
} else if (line.rfind("shader=", 0) == 0) {
g_lastShaderDir = Utf8ToWide(line.substr(7));
}
}
}
static void UpdateLastVideoDir(const std::wstring& path)
{
std::wstring dir = Dirname(path);
if (!dir.empty()) {
g_lastVideoDir = dir;
SaveSettings();
}
}
static void UpdateLastShaderDir(const std::wstring& path)
{
std::wstring dir = Dirname(path);
if (!dir.empty()) {
g_lastShaderDir = dir;
SaveSettings();
}
}
static void SaveShaders()
{
std::ofstream o(GetShadersSavePath(), std::ios::binary);
if (!o) return;
for (size_t i = 0; i < g_shaders.size(); ++i) {
bool bypass = (i < g_shaderBypass.size()) ? g_shaderBypass[i] : false;
o << (bypass ? "1|" : "0|") << WideToUtf8(g_shaders[i]) << "\n";
}
}
static void LoadShaders()
{
g_shaders.clear();
g_shaderBypass.clear();
std::ifstream f(GetShadersSavePath(), std::ios::binary);
if (!f) return;
std::string line;
while (std::getline(f, line)) {
if (line.empty()) continue;
bool bypass = false;
if (line.size() > 2 && (line[0] == '0' || line[0] == '1') && line[1] == '|') {
bypass = (line[0] == '1');
line = line.substr(2);
}
std::wstring w = Utf8ToWide(line);
if (w.empty()) continue;
if (IsShaderFile(w)) {
g_shaders.push_back(w);
g_shaderBypass.push_back(bypass);
}
}
}
static void MoveShader(int from, int to)
{
if (from < 0 || to < 0 || from >= (int)g_shaders.size() || to >= (int)g_shaders.size()) return;
auto item = g_shaders[from];
g_shaders.erase(g_shaders.begin() + from);
g_shaders.insert(g_shaders.begin() + to, item);
bool b = g_shaderBypass[from];
g_shaderBypass.erase(g_shaderBypass.begin() + from);
g_shaderBypass.insert(g_shaderBypass.begin() + to, b);
ListRefresh();
SendMessageW(g_hwndList, LB_SETCURSEL, to, 0);
MpvApplyShaderList();
SaveShaders();
}
static void EditShaderInNotepad(const std::wstring& path)
{
std::wstring npp1 = L"C:\\Program Files\\Notepad++\\notepad++.exe";
std::wstring npp2 = L"C:\\Program Files (x86)\\Notepad++\\notepad++.exe";
std::wstring npp;
if (GetFileAttributesW(npp1.c_str()) != INVALID_FILE_ATTRIBUTES) npp = npp1;
else if (GetFileAttributesW(npp2.c_str()) != INVALID_FILE_ATTRIBUTES) npp = npp2;
if (npp.empty()) {
const wchar_t* url = L"https://notepad-plus-plus.org/downloads/";
MessageBoxW(g_hwndMain, L"Notepad++ not found.\nDownload: https://notepad-plus-plus.org/downloads/", L"Notepad++", MB_OK | MB_ICONINFORMATION);
ShellExecuteW(nullptr, L"open", url, nullptr, nullptr, SW_SHOWNORMAL);
return;
}
ShellExecuteW(nullptr, L"open", npp.c_str(), Quote(path).c_str(), nullptr, SW_SHOWNORMAL);
}
static bool FindFfmpeg(std::wstring& outFfmpeg)
{
// Prefer ffmpeg.exe in dist\deps; then next to exe; else rely on PATH.
std::wstring exeDir = GetExeDir();
std::wstring deps = JoinPath(exeDir, L"deps");
std::wstring depsFfmpeg = JoinPath(deps, L"ffmpeg.exe");
DWORD attrsDeps = GetFileAttributesW(depsFfmpeg.c_str());
if (attrsDeps != INVALID_FILE_ATTRIBUTES && !(attrsDeps & FILE_ATTRIBUTE_DIRECTORY)) {
outFfmpeg = depsFfmpeg;
return true;
}
std::wstring local = JoinPath(exeDir, L"ffmpeg.exe");
DWORD attrs = GetFileAttributesW(local.c_str());
if (attrs != INVALID_FILE_ATTRIBUTES && !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
outFfmpeg = local;
return true;
}
outFfmpeg = L"ffmpeg.exe";
return true;
}
// ----------------------------
// mpv integration
// ----------------------------
static void MpvApplyShaderList()
{
if (!g_mpv) return;
// Build mpv_node array of strings for "glsl-shaders"
mpv_node node{};
node.format = MPV_FORMAT_NODE_ARRAY;
mpv_node_list list{};
std::vector<mpv_node> elems;
size_t activeCount = 0;
for (size_t i = 0; i < g_shaders.size(); ++i) {
if (i < g_shaderBypass.size() && g_shaderBypass[i]) continue;
activeCount++;
}
elems.resize(activeCount);
// mpv expects UTF-8 strings
std::vector<std::string> utf8;
utf8.reserve(activeCount);
size_t outIdx = 0;
for (size_t i = 0; i < g_shaders.size(); ++i) {
if (i < g_shaderBypass.size() && g_shaderBypass[i]) continue;
int len = WideCharToMultiByte(CP_UTF8, 0, g_shaders[i].c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string s(len > 0 ? len-1 : 0, '\0');
if (len > 1) WideCharToMultiByte(CP_UTF8, 0, g_shaders[i].c_str(), -1, s.data(), len, nullptr, nullptr);
utf8.push_back(s);
elems[outIdx].format = MPV_FORMAT_STRING;
elems[outIdx].u.string = (char*)utf8[outIdx].c_str();
outIdx++;
}
list.num = (int)elems.size();
list.values = elems.data();
node.u.list = &list;
// This overwrites the shader list with our current vector
mpv_set_property(g_mpv, "glsl-shaders", MPV_FORMAT_NODE, &node);
mpv_command_string(g_mpv, "show-text \"Shaders updated\"");
}
static void MpvLoadVideo(const std::wstring& path)
{
if (!g_mpv) return;
g_loadedVideo = path;
UpdateLastVideoDir(path);
int pause = 1;
mpv_set_property(g_mpv, "pause", MPV_FORMAT_FLAG, &pause);
int len = WideCharToMultiByte(CP_UTF8, 0, path.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string u8(len > 0 ? len-1 : 0, '\0');
if (len > 1) WideCharToMultiByte(CP_UTF8, 0, path.c_str(), -1, u8.data(), len, nullptr, nullptr);
const char* cmd[] = {"loadfile", u8.c_str(), "replace", nullptr};
mpv_command(g_mpv, cmd);
pause = 1;
mpv_set_property(g_mpv, "pause", MPV_FORMAT_FLAG, &pause);
UpdatePlayPauseLabel();
SetStatus(L"Loaded: " + path);
}
static void MpvTogglePause()
{
if (!g_mpv) return;
int pause = 0;
mpv_get_property(g_mpv, "pause", MPV_FORMAT_FLAG, &pause);
pause = !pause;
mpv_set_property(g_mpv, "pause", MPV_FORMAT_FLAG, &pause);
UpdatePlayPauseLabel();
}
static void MpvFrameStep(bool backwards)
{
if (!g_mpv) return;
mpv_command_string(g_mpv, backwards ? "frame-back-step" : "frame-step");
}
static void OpenVideoDialog()
{
wchar_t file[MAX_PATH] = {};
OPENFILENAMEW ofn{};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_hwndMain;
ofn.lpstrFile = file;
ofn.nMaxFile = MAX_PATH;
std::wstring initialDir = g_lastVideoDir.empty() ? GetExeDir() : g_lastVideoDir;
ofn.lpstrInitialDir = initialDir.c_str();
ofn.lpstrFilter = L"Video Files\0*.mp4;*.mkv;*.mov;*.avi;*.ts;*.m2ts;*.webm;*.m4v\0All Files\0*.*\0";
ofn.nFilterIndex = 1;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
if (GetOpenFileNameW(&ofn)) {
MpvLoadVideo(file);
}
}
static void OpenShaderDialog()
{
wchar_t buffer[4096] = {};
OPENFILENAMEW ofn{};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_hwndMain;
ofn.lpstrFile = buffer;
ofn.nMaxFile = (DWORD)sizeof(buffer) / sizeof(wchar_t);
std::wstring initialDir = g_lastShaderDir.empty() ? GetExeDir() : g_lastShaderDir;
ofn.lpstrInitialDir = initialDir.c_str();
ofn.lpstrFilter = L"Shader Files\0*.glsl;*.hook.glsl;*.hook;*.frag;*.fs\0All Files\0*.*\0";
ofn.nFilterIndex = 1;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER;
if (!GetOpenFileNameW(&ofn)) return;
std::wstring dir = buffer;
const wchar_t* p = buffer + dir.size() + 1;
if (*p == L'\0') {
AddShaderPath(dir);
return;
}
while (*p) {
std::wstring name = p;
AddShaderPath(JoinPath(dir, name));
p += name.size() + 1;
}
}
static bool MpvInit(HWND hwndVideo)
{
g_mpv = mpv_create();
if (!g_mpv) return false;
// Keep UI snappy / no console noise
mpv_set_option_string(g_mpv, "terminal", "no");
mpv_set_option_string(g_mpv, "msg-level", "all=no");
// Tell mpv to render inside our child window
int64_t wid = (int64_t)(intptr_t)hwndVideo;
mpv_set_option(g_mpv, "wid", MPV_FORMAT_INT64, &wid);
// Useful defaults
mpv_set_option_string(g_mpv, "keep-open", "yes");
mpv_set_option_string(g_mpv, "loop-file", "inf");
if (mpv_initialize(g_mpv) < 0) return false;
return true;
}
static void MpvShutdown()
{
if (g_mpv) {
mpv_terminate_destroy(g_mpv);
g_mpv = nullptr;
}
}
// ----------------------------
// UI list helpers
// ----------------------------
static void ListRefresh()
{
SendMessageW(g_hwndList, LB_RESETCONTENT, 0, 0);
for (size_t i = 0; i < g_shaders.size(); ++i) {
std::wstring name = FilenameOnly(g_shaders[i]);
if (i < g_shaderBypass.size() && g_shaderBypass[i]) {
name += L" (Bypassed)";
}
SendMessageW(g_hwndList, LB_ADDSTRING, 0, (LPARAM)name.c_str());
}
}
static void AddShaderPath(const std::wstring& path)
{
if (std::find(g_shaders.begin(), g_shaders.end(), path) != g_shaders.end())
return;
g_shaders.push_back(path);
g_shaderBypass.push_back(false);
UpdateLastShaderDir(path);
ListRefresh();
MpvApplyShaderList();
SaveShaders();
}
static void RemoveSelectedShader()
{
int sel = (int)SendMessageW(g_hwndList, LB_GETCURSEL, 0, 0);
if (sel == LB_ERR) return;
g_shaders.erase(g_shaders.begin() + sel);
if (sel >= 0 && sel < (int)g_shaderBypass.size()) {
g_shaderBypass.erase(g_shaderBypass.begin() + sel);
}
ListRefresh();
MpvApplyShaderList();
SaveShaders();
}
static void ClearShaders()
{
g_shaders.clear();
g_shaderBypass.clear();
ListRefresh();
MpvApplyShaderList();
SaveShaders();
}
static std::vector<std::wstring> GetActiveShaders()
{
std::vector<std::wstring> out;
out.reserve(g_shaders.size());
for (size_t i = 0; i < g_shaders.size(); ++i) {
if (i < g_shaderBypass.size() && g_shaderBypass[i]) continue;
out.push_back(g_shaders[i]);
}
return out;
}
// ----------------------------
// Encoding (ffmpeg + libplacebo)
// ----------------------------
static bool GetMpvVideoSize(int& w, int& h)
{
w = h = 0;
if (!g_mpv) return false;
// mpv properties "width"/"height" refer to current video size
mpv_get_property(g_mpv, "width", MPV_FORMAT_INT64, &w);
mpv_get_property(g_mpv, "height", MPV_FORMAT_INT64, &h);
return (w > 0 && h > 0);
}
static int GetInputBitrateMbps()
{
if (!g_mpv) return 0;
int64_t bps = 0;
if (mpv_get_property(g_mpv, "video-bitrate", MPV_FORMAT_INT64, &bps) >= 0 && bps > 0) {
int mbps = (int)((bps + 500000) / 1000000);
if (mbps < 1) mbps = 1;
return mbps;
}
// Fallback: estimate from file size and duration
double duration = 0.0;
if (mpv_get_property(g_mpv, "duration", MPV_FORMAT_DOUBLE, &duration) >= 0 && duration > 0.0) {
WIN32_FILE_ATTRIBUTE_DATA fad{};
if (GetFileAttributesExW(g_loadedVideo.c_str(), GetFileExInfoStandard, &fad)) {
ULARGE_INTEGER sz{};
sz.HighPart = fad.nFileSizeHigh;
sz.LowPart = fad.nFileSizeLow;
double bits = (double)sz.QuadPart * 8.0;
int mbps = (int)((bits / duration) / 1000000.0 + 0.5);
if (mbps < 1) mbps = 1;
return mbps;
}
}
// Final fallback: ask ffmpeg for container bitrate
std::wstring ffmpeg;
if (FindFfmpeg(ffmpeg)) {
int kbps = ProbeBitrateKbpsWithFfmpeg(ffmpeg, g_loadedVideo);
if (kbps > 0) {
int mbps = (kbps + 500) / 1000;
if (mbps < 1) mbps = 1;
return mbps;
}
}
return 0;
}
static void RunEncode(bool to1440p)
{
if (g_loadedVideo.empty()) {
SetStatus(L"No video loaded.");
return;
}
std::wstring ffmpeg;
FindFfmpeg(ffmpeg);
// Combine shaders into one file for libplacebo custom_shader_path
std::wstring combinedName;
std::vector<std::wstring> activeShaders = GetActiveShaders();
std::wstring combined = WriteCombinedShaderTemp(activeShaders, &combinedName);
// Output file
std::wstring dir = Dirname(g_loadedVideo);
std::wstring base = BasenameNoExt(g_loadedVideo);
std::wstring out = JoinPath(dir, base + (to1440p ? L"_shaded_1440p.mp4" : L"_shaded.mp4"));
// Build libplacebo filter string
std::wstringstream vf;
if (!combined.empty()) {
// libplacebo supports mpv .hook shaders via custom_shader_path :contentReference[oaicite:3]{index=3}
const std::wstring& shaderArg = combinedName.empty() ? combined : combinedName;
vf << L"libplacebo=custom_shader_path=" << FfmpegEscapeFilterValue(shaderArg);
} else {
vf << L"libplacebo";
}
if (to1440p) {
// Compute aspect-correct width for 1440p, keep even width
int iw=0, ih=0;
if (!GetMpvVideoSize(iw, ih) || ih <= 0) {
iw = 1920; ih = 1080; // fallback
}
int outH = 1440;
int outW = (int)((double)iw * (double)outH / (double)ih + 0.5);
outW &= ~1; // make even
// libplacebo can scale using w/h parameters; see docs/examples :contentReference[oaicite:4]{index=4}
// We just append another libplacebo stage to scale (clean and GPU-friendly).
vf << L",libplacebo=w=" << outW << L":h=" << outH;
}
std::vector<std::wstring> encoders;
if (g_encoderChoice != L"auto") {
encoders.push_back(g_encoderChoice);
} else {
encoders = {
L"hevc_amf",
L"hevc_nvenc",
L"hevc_qsv",
L"hevc_mf",
L"libx265"
};
}
int targetMbps = g_bitrateMbps;
if (targetMbps <= 0) {
targetMbps = GetInputBitrateMbps();
if (targetMbps <= 0) targetMbps = 20;
}
// Log path next to exe (helps troubleshooting ffmpeg failures).
std::wstring logPath = JoinPath(GetExeDir(), BasenameNoExt(out) + L".log");
SetStatus(L"Encoding...");
double durationSec = GetMpvDurationSeconds();
// Run in background thread
std::thread([ffmpeg, vfStr = vf.str(), out, logPath, encoders, targetMbps, combined, durationSec]() {
STARTUPINFOW si{};
si.cb = sizeof(si);
PROCESS_INFORMATION pi{};
SECURITY_ATTRIBUTES sa{};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = nullptr;
HANDLE hLog = CreateFileW(
logPath.c_str(),
GENERIC_WRITE,
FILE_SHARE_READ,
&sa,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
nullptr
);
if (hLog != INVALID_HANDLE_VALUE) {
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdOutput = hLog;
si.hStdError = hLog;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
}
bool success = false;
std::wstring workDir = GetExeDir();
for (const auto& enc : encoders) {
std::wstring cmd =
Quote(ffmpeg) + L" -hide_banner -y -i " + Quote(g_loadedVideo) +
L" -vf " + Quote(vfStr) + L" " + BuildEncoderArgs(enc, targetMbps) +
L" -c:a copy ";
if (durationSec > 0.0) {
cmd += L"-progress pipe:1 -nostats ";
}
cmd += Quote(out);
if (hLog != INVALID_HANDLE_VALUE) {
SetFilePointer(hLog, 0, nullptr, FILE_END);
WriteLogLine(hLog, L"\r\n=== Attempt encoder: " + enc + L" ===\r\n");
WriteLogLine(hLog, cmd + L"\r\n");
}
std::wstring status = L"Encoding (" + enc + L")...";
PostMessageW(g_hwndMain, WM_APP + 1, 0, (LPARAM)new std::wstring(status));
HANDLE hRead = nullptr;
HANDLE hWrite = nullptr;
if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
continue;
}
SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
si.hStdOutput = hWrite;
si.hStdError = hWrite;
// CreateProcess wants mutable buffer
std::wstring mutableCmd = cmd;
BOOL ok = CreateProcessW(
nullptr,
mutableCmd.data(),
nullptr, nullptr,
TRUE,
CREATE_NO_WINDOW,
nullptr,
workDir.c_str(),
&si, &pi
);
CloseHandle(hWrite);
if (!ok) {
CloseHandle(hRead);
continue;
}
std::string buffer;
buffer.reserve(8192);
char chunk[4096];
DWORD read = 0;
double lastPct = -1.0;
while (ReadFile(hRead, chunk, sizeof(chunk), &read, nullptr) && read > 0) {
if (hLog != INVALID_HANDLE_VALUE) {
DWORD written = 0;
WriteFile(hLog, chunk, read, &written, nullptr);
}
buffer.append(chunk, chunk + read);
size_t pos = 0;
while (true) {
size_t nl = buffer.find('\n', pos);
if (nl == std::string::npos) break;
std::string line = buffer.substr(pos, nl - pos);
if (!line.empty() && line.back() == '\r') line.pop_back();