-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp.bak
More file actions
3776 lines (3248 loc) · 132 KB
/
main.cpp.bak
File metadata and controls
3776 lines (3248 loc) · 132 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
// MediaExplorer - Win32 file browser + libVLC player with recursive search
// Build: VS2022, x64, C++17 (fast folder load + async video metadata fill + cut/paste UI progress)
//
// Key speed-ups:
// 1) FindFirstFileExW(..., FindExInfoBasic, ..., FIND_FIRST_EX_LARGE_FETCH)
// 2) ListView redraw suspension during bulk insert
// 3) Deferred video metadata (resolution/duration) with fast cached try,
// then background worker fills remaining cells; cancelled on navigation.
// New in this file:
// 4) Ctrl+X removes selected files from view and fills app clipboard
// 5) Ctrl+V shows sub-modal progress window "copy/move <file>..." + Cancel
// - cancel immediately aborts the whole batch and drops the window
// - clipboard is cleared when the window closes
// 6) Ctrl+P during playback: show ffprobe-based video properties
// 7) Ctrl+Up / Ctrl+Down: reorder single selected row in list
// 8) Ctrl+Plus: combine selected files via video_combine.exe in background threads
// with per-task log windows; app cannot exit until all combines finish.
#ifndef UNICODE
# define UNICODE
#endif
#ifndef _UNICODE
# define _UNICODE
#endif
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
# define NOMINMAX
#endif
#include <windows.h>
#include <commctrl.h>
#include <shlwapi.h>
#include <shobjidl_core.h>
#include <propsys.h>
#include <propkey.h>
#include <wrl/client.h>
#include <string>
#include <vector>
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cwchar>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cwctype>
#include <shlobj.h> // SHCreateDirectoryExW
#include <cstdarg>
#include <io.h> // for _unlink
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "User32.lib")
#pragma comment(lib, "Gdi32.lib")
#pragma comment(lib, "Shell32.lib")
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "Ole32.lib")
#pragma comment(lib, "Propsys.lib")
#pragma comment(lib, "Uuid.lib")
#include <vlc/vlc.h>
#ifndef FIND_FIRST_EX_LARGE_FETCH
// Older SDKs may miss this flag; define to 0 (ignored) to stay compatible.
# define FIND_FIRST_EX_LARGE_FETCH 0x00000002
#endif
using Microsoft::WRL::ComPtr;
static void LogLine(const wchar_t* fmt, ...); // forward declaration
// ----------------------------- Globals
HINSTANCE g_hInst = NULL;
HWND g_hwndMain = NULL, g_hwndList = NULL, g_hwndVideo = NULL, g_hwndSeek = NULL;
enum class ViewKind { Drives, Folder, Search };
ViewKind g_view = ViewKind::Drives;
std::wstring g_folder; // valid in Folder view, ends with '\'
struct Row {
std::wstring name; // display (for Search, full path; for Folder, file name)
std::wstring full; // absolute path (dir ends with '\')
bool isDir;
ULONGLONG size;
FILETIME modified;
// video props
int vW, vH;
ULONGLONG vDur100ns;
Row() : isDir(false), size(0), vW(0), vH(0), vDur100ns(0) { modified.dwLowDateTime = modified.dwHighDateTime = 0; }
};
std::vector<Row> g_rows;
// sorting
int g_sortCol = 0; // 0=Name,1=Type,2=Size,3=Modified,4=Resolution,5=Duration
bool g_sortAsc = true;
// VLC
libvlc_instance_t* g_vlc = NULL;
libvlc_media_player_t* g_mp = NULL;
bool g_inPlayback = false;
std::vector<std::wstring> g_playlist;
size_t g_playlistIndex = 0;
bool g_userDragging = false;
libvlc_time_t g_lastLenForRange = -1;
// ----------------------------- Configuration (mediaexplorer.ini)
struct AppConfig {
std::wstring upscaleDirectory; // e.g. w:\upscale\autosubmit (may be empty)
bool ffmpegAvailable = false; // if true, ffmpeg-based tools are enabled & shown in help
bool ffprobeAvailable = false; // if true, ffprobe-based info is enabled & shown in help
// bool videoCombineAvailable = false; // if true, Ctrl+Plus / video_combine.exe is enabled
bool loggingEnabled = false; // master on/off
std::wstring loggingPath; // folder from INI
std::wstring logFile; // full path to mediaexplorer.log
};
AppConfig g_cfg;
// fullscreen (app-managed)
bool g_fullscreen = false;
WINDOWPLACEMENT g_wpPrev; // set .length before use
// timers
const UINT_PTR kTimerPlaybackUI = 1;
// post-playback actions
enum class ActionType { DeleteFile, RenameFile, CopyToPath };
struct PostAction { ActionType type; std::wstring src; std::wstring param; };
std::vector<PostAction> g_post;
// filename clipboard for browser
enum class ClipMode { None, Copy, Move };
ClipMode g_clipMode = ClipMode::None;
std::vector<std::wstring> g_clipFiles; // absolute file paths
// ----------------------------- Search state
struct SearchState {
bool active;
ViewKind originView;
std::wstring originFolder; // empty if origin was Drives
std::vector<std::wstring> termsLower; // intersection terms
// selection-aware explicit scope
bool useExplicitScope;
std::vector<std::wstring> explicitFolders; // each ends with '\'
std::vector<std::wstring> explicitFiles; // absolute file paths
SearchState()
: active(false),
originView(ViewKind::Drives),
useExplicitScope(false) {
}
} g_search;
// ----------------------------- Async metadata fill
constexpr UINT WM_APP_META = WM_APP + 100;
constexpr UINT WM_APP_COMBINE_OUTPUT = WM_APP + 200;
constexpr UINT WM_APP_COMBINE_DONE = WM_APP + 201;
// New for ffmpeg tools
constexpr UINT WM_APP_FFMPEG_OUTPUT = WM_APP + 300;
constexpr UINT WM_APP_FFMPEG_DONE = WM_APP + 301;
struct MetaResult {
std::wstring path;
int w, h;
ULONGLONG dur;
uint32_t gen;
};
std::atomic<uint32_t> g_metaGen{ 0 };
CRITICAL_SECTION g_metaLock; // protects g_metaTodoPaths
std::vector<std::wstring> g_metaTodoPaths; // paths that still need deep props
HANDLE g_metaThread = NULL;
// ----------------------------- Combine tasks (video_combine in background)
struct CombineTask {
HANDLE hThread;
HANDLE hProcess;
HWND hwnd; // log window
HWND hEdit; // multiline read-only edit inside log window
std::wstring workingDir; // dir where inputs are copied
std::vector<std::wstring> srcFiles; // original source file paths
std::wstring combinedFull; // final combined video path
std::wstring title; // short description (e.g., output file name)
bool running;
CombineTask() :
hThread(NULL),
hProcess(NULL),
hwnd(NULL),
hEdit(NULL),
running(false) {
}
};
CRITICAL_SECTION g_combineLock;
std::vector<CombineTask*> g_combineTasks;
// forward declarations for combine-related helpers
static void EnsureCombineLogClass();
static HWND CreateCombineLogWindow(CombineTask* task);
static void PostCombineOutput(CombineTask* task, const std::wstring& text);
static DWORD WINAPI CombineThreadProc(LPVOID param);
static bool HasRunningCombineTasks() {
EnterCriticalSection(&g_combineLock);
bool any = false;
for (CombineTask* t : g_combineTasks) {
if (t && t->running) { any = true; break; }
}
LeaveCriticalSection(&g_combineLock);
return any;
}
// ----------------------------- FFmpeg processing tasks (trim/flip in background)
enum class FfmpegOpKind { TrimFront, TrimEnd, HFlip };
struct FfmpegTask {
HANDLE hThread = NULL;
HANDLE hProcess = NULL;
HWND hwnd = NULL; // log window
HWND hEdit = NULL; // multiline read-only edit in log window
std::wstring sourceFull; // original video path
std::wstring workingDir; // ...video_process
std::wstring inputCopy; // workingDir + base.ext (copied original)
std::wstring outputTemp; // workingDir + base_<op>.ext (ffmpeg output)
std::wstring finalWorking; // after rename, path of final processed file in workingDir
std::wstring title; // short title, e.g. "Trim front: file.mp4"
FfmpegOpKind kind;
libvlc_time_t refMs = 0; // time in ms when user invoked operation
bool running = false;
bool done = false;
DWORD exitCode = 0;
};
CRITICAL_SECTION g_ffLock;
std::vector<FfmpegTask*> g_ffTasks;
static bool HasRunningFfmpegTasks() {
EnterCriticalSection(&g_ffLock);
bool any = false;
for (FfmpegTask* t : g_ffTasks) {
if (t && t->running) { any = true; break; }
}
LeaveCriticalSection(&g_ffLock);
return any;
}
// ----------------------------- FFmpeg task log window + helpers
static LRESULT CALLBACK FfmpegLogProc(HWND h, UINT m, WPARAM w, LPARAM l) {
FfmpegTask* task = reinterpret_cast<FfmpegTask*>(GetWindowLongPtrW(h, GWLP_USERDATA));
switch (m) {
case WM_CREATE: {
LPCREATESTRUCT pcs = (LPCREATESTRUCT)l;
task = (FfmpegTask*)pcs->lpCreateParams;
SetWindowLongPtrW(h, GWLP_USERDATA, (LONG_PTR)task);
HFONT hf = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
RECT rc; GetClientRect(h, &rc);
HWND hEdit = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"",
WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL,
4, 4, rc.right - 8, rc.bottom - 8, h, (HMENU)101, g_hInst, NULL);
SendMessageW(hEdit, WM_SETFONT, (WPARAM)hf, TRUE);
if (task) task->hEdit = hEdit;
return 0;
}
case WM_SIZE: {
if (task && task->hEdit) {
RECT rc; GetClientRect(h, &rc);
MoveWindow(task->hEdit, 4, 4, rc.right - 8, rc.bottom - 8, TRUE);
}
return 0;
}
case WM_CLOSE:
ShowWindow(h, SW_HIDE); // hide, don't destroy; keep log available
return 0;
}
return DefWindowProcW(h, m, w, l);
}
static void EnsureFfmpegLogClass() {
static bool reg = false;
if (!reg) {
WNDCLASSW wc{}; wc.lpfnWndProc = FfmpegLogProc; wc.hInstance = g_hInst;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = L"FfmpegLogClass";
RegisterClassW(&wc);
reg = true;
}
}
static HWND CreateFfmpegLogWindow(FfmpegTask* task) {
RECT r; SystemParametersInfoW(SPI_GETWORKAREA, 0, &r, 0);
int W = 640, H = 480;
int X = r.left + ((r.right - r.left) - W) / 2;
int Y = r.top + ((r.bottom - r.top) - H) / 2;
std::wstring title = L"FFmpeg task: ";
title += task ? task->title : L"(unknown)";
HWND hwnd = CreateWindowExW(WS_EX_TOOLWINDOW, L"FfmpegLogClass", title.c_str(),
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
X, Y, W, H, g_hwndMain, NULL, g_hInst, task);
return hwnd;
}
static void PostFfmpegOutput(FfmpegTask* task, const std::wstring& text) {
if (!task) return;
std::wstring* p = new std::wstring(text);
PostMessageW(g_hwndMain, WM_APP_FFMPEG_OUTPUT, (WPARAM)task, (LPARAM)p);
}
static DWORD WINAPI FfmpegThreadProc(LPVOID param) {
FfmpegTask* task = (FfmpegTask*)param;
if (!task) return 0;
LogLine(L"FFmpegTask start: src=\"%s\" inputCopy=\"%s\" outputTemp=\"%s\" kind=%d refMs=%lld",
task->sourceFull.c_str(), task->inputCopy.c_str(),
task->outputTemp.c_str(), (int)task->kind, (long long)task->refMs);
// 1) Create working directory
if (!CreateDirectoryW(task->workingDir.c_str(), NULL)) {
DWORD e = GetLastError();
if (e != ERROR_ALREADY_EXISTS) {
std::wstring msg = L"ERROR: Failed to create working directory:\r\n";
msg += task->workingDir;
msg += L"\r\n";
PostFfmpegOutput(task, msg);
task->exitCode = 1;
task->running = false;
PostMessageW(g_hwndMain, WM_APP_FFMPEG_DONE, (WPARAM)task, (LPARAM)task->exitCode);
return 0;
}
}
// Paths should already be filled in, but ensure theyre non-empty.
if (task->inputCopy.empty() || task->outputTemp.empty()) {
PostFfmpegOutput(task, L"ERROR: task paths are not initialized.\r\n");
task->exitCode = 2;
task->running = false;
PostMessageW(g_hwndMain, WM_APP_FFMPEG_DONE, (WPARAM)task, (LPARAM)task->exitCode);
return 0;
}
// 2) Copy input into working directory
{
std::wstring msg = L"Copying input to working directory:\r\n ";
msg += task->inputCopy;
msg += L"\r\n";
PostFfmpegOutput(task, msg);
if (!CopyFileW(task->sourceFull.c_str(), task->inputCopy.c_str(), FALSE)) {
std::wstring err = L"ERROR: Failed to copy file:\r\n ";
err += task->sourceFull;
err += L"\r\n";
PostFfmpegOutput(task, err);
task->exitCode = 3;
task->running = false;
PostMessageW(g_hwndMain, WM_APP_FFMPEG_DONE, (WPARAM)task, (LPARAM)task->exitCode);
return 0;
}
}
// 3) Build ffmpeg command line
double seconds = (double)task->refMs / 1000.0;
wchar_t secBuf[64];
swprintf_s(secBuf, L"%.3f", seconds);
std::wstring cmd = L"ffmpeg -y ";
switch (task->kind) {
case FfmpegOpKind::TrimFront:
// Keep from refMs -> end
cmd += L"-ss ";
cmd += secBuf;
cmd += L" -i \"";
cmd += task->inputCopy;
cmd += L"\" -c copy \"";
cmd += task->outputTemp;
cmd += L"\"";
break;
case FfmpegOpKind::TrimEnd:
// Keep from 0 -> refMs
cmd += L"-i \"";
cmd += task->inputCopy;
cmd += L"\" -t ";
cmd += secBuf;
cmd += L" -c copy \"";
cmd += task->outputTemp;
cmd += L"\"";
break;
case FfmpegOpKind::HFlip:
cmd += L"-i \"";
cmd += task->inputCopy;
cmd += L"\" -vf hflip -c:a copy \"";
cmd += task->outputTemp;
cmd += L"\"";
break;
}
PostFfmpegOutput(task, L"Running command:\r\n");
PostFfmpegOutput(task, cmd + L"\r\n\r\n");
SECURITY_ATTRIBUTES sa{};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
HANDLE hRead = NULL, hWrite = NULL;
if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
PostFfmpegOutput(task, L"ERROR: Failed to create pipe.\r\n");
task->exitCode = 4;
task->running = false;
PostMessageW(g_hwndMain, WM_APP_FFMPEG_DONE, (WPARAM)task, (LPARAM)task->exitCode);
return 0;
}
SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
STARTUPINFOW si{};
si.cb = sizeof(si);
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdOutput = hWrite;
si.hStdError = hWrite;
PROCESS_INFORMATION pi{};
std::vector<wchar_t> cmdBuf(cmd.size() + 1);
wcscpy_s(cmdBuf.data(), cmdBuf.size(), cmd.c_str());
BOOL ok = CreateProcessW(NULL, cmdBuf.data(),
NULL, NULL, TRUE,
CREATE_NO_WINDOW,
NULL, NULL,
&si, &pi);
CloseHandle(hWrite);
hWrite = NULL;
if (!ok) {
PostFfmpegOutput(task, L"ERROR: Failed to start ffmpeg.\r\n");
CloseHandle(hRead);
task->exitCode = 5;
task->running = false;
PostMessageW(g_hwndMain, WM_APP_FFMPEG_DONE, (WPARAM)task, (LPARAM)task->exitCode);
return 0;
}
task->hProcess = pi.hProcess;
CloseHandle(pi.hThread);
// 4) Read ffmpeg stdout/stderr
char buf[4096];
DWORD bytes = 0;
std::string accum;
while (ReadFile(hRead, buf, sizeof(buf), &bytes, NULL) && bytes > 0) {
accum.append(buf, buf + bytes);
size_t pos = 0;
while (true) {
size_t nl = accum.find('\n', pos);
if (nl == std::string::npos) {
accum.erase(0, pos);
break;
}
std::string line = accum.substr(pos, nl - pos + 1);
pos = nl + 1;
int n = MultiByteToWideChar(CP_ACP, 0, line.c_str(), (int)line.size(), NULL, 0);
if (n <= 0) continue;
std::wstring wline(n, L'\0');
MultiByteToWideChar(CP_ACP, 0, line.c_str(), (int)line.size(), &wline[0], n);
PostFfmpegOutput(task, wline);
}
}
CloseHandle(hRead);
WaitForSingleObject(task->hProcess, INFINITE);
DWORD exitCode = 0;
GetExitCodeProcess(task->hProcess, &exitCode);
CloseHandle(task->hProcess);
task->hProcess = NULL;
wchar_t doneMsg[128];
swprintf_s(doneMsg, L"\r\n[ffmpeg exited with code %lu]\r\n", exitCode);
PostFfmpegOutput(task, doneMsg);
task->exitCode = exitCode;
// On success, rename outputTemp -> inputCopy (so finalWorking is the "base.ext" in video_process)
if (exitCode == 0) {
// Delete original copy, then rename
DeleteFileW(task->inputCopy.c_str());
MoveFileExW(task->outputTemp.c_str(), task->inputCopy.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);
task->finalWorking = task->inputCopy;
}
task->running = false;
task->done = true;
PostMessageW(g_hwndMain, WM_APP_FFMPEG_DONE, (WPARAM)task, (LPARAM)exitCode);
LogLine(L"FFmpegTask done: src=\"%s\" exitCode=%lu finalWorking=\"%s\"",
task->sourceFull.c_str(), exitCode, task->finalWorking.c_str());
return 0;
}
// ----------------------------- Helpers
static inline bool IsDriveRoot(const std::wstring& p) {
return p.size() == 3 &&
((p[0] >= L'A' && p[0] <= L'Z') || (p[0] >= L'a' && p[0] <= L'z')) &&
p[1] == L':' && (p[2] == L'\\' || p[2] == L'/');
}
static inline std::wstring EnsureSlash(std::wstring p) {
if (!p.empty() && p.back() != L'\\' && p.back() != L'/') p.push_back(L'\\');
return p;
}
static void CollectSelection(std::vector<std::wstring>& outFolders, std::vector<std::wstring>& outFiles) {
outFolders.clear(); outFiles.clear();
int idx = -1;
while ((idx = ListView_GetNextItem(g_hwndList, idx, LVNI_SELECTED)) != -1) {
if (idx < 0 || idx >= (int)g_rows.size()) continue;
const Row& r = g_rows[idx];
if (r.isDir) {
outFolders.push_back(EnsureSlash(r.full)); // works for drives & folders
}
else {
outFiles.push_back(r.full);
}
}
}
// --- Search progress title + gentle UI pumping during long recursion ---
static void PumpMessagesThrottled(DWORD msInterval) {
static DWORD s_last = 0;
DWORD now = GetTickCount();
if (now - s_last < msInterval) return;
s_last = now;
MSG msg;
while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
static void SetTitleSearchingFolder(const std::wstring& folder) {
std::wstring t = L"Media Explorer (libVLC) - searching ";
t += EnsureSlash(folder);
SetWindowTextW(g_hwndMain, t.c_str());
PumpMessagesThrottled(50);
}
static inline std::wstring ParentDir(std::wstring p) {
p = EnsureSlash(p);
if (IsDriveRoot(p)) return L"";
p.pop_back();
size_t cut = p.find_last_of(L"\\/");
if (cut == std::wstring::npos) return L"";
return p.substr(0, cut + 1);
}
static std::wstring ToLower(const std::wstring& s) {
std::wstring t = s;
std::transform(t.begin(), t.end(), t.begin(), ::towlower);
return t;
}
static std::wstring Trim(const std::wstring& s) {
size_t start = 0, end = s.size();
while (start < end && iswspace(s[start])) ++start;
while (end > start && iswspace(s[end - 1])) --end;
return s.substr(start, end - start);
}
// ----------------------------- Logging helpers
static void InitLoggingFromConfig() {
if (!g_cfg.loggingEnabled) return;
if (g_cfg.loggingPath.empty()) return;
std::wstring folder = Trim(g_cfg.loggingPath);
if (folder.empty()) {
g_cfg.loggingEnabled = false;
return;
}
if (folder.back() != L'\\' && folder.back() != L'/')
folder.push_back(L'\\');
// Create directory tree (best-effort)
int rc = SHCreateDirectoryExW(NULL, folder.c_str(), NULL);
if (rc != ERROR_SUCCESS && rc != ERROR_ALREADY_EXISTS && rc != ERROR_FILE_EXISTS) {
// Cannot create folder -> disable logging
g_cfg.loggingEnabled = false;
return;
}
g_cfg.loggingPath = folder;
g_cfg.logFile = folder + L"mediaexplorer.log";
}
static void LogLine(const wchar_t* fmt, ...) {
if (!g_cfg.loggingEnabled || g_cfg.logFile.empty()) return;
FILE* f = _wfopen(g_cfg.logFile.c_str(), L"a, ccs=UTF-8");
if (!f) return;
SYSTEMTIME st; GetLocalTime(&st);
wchar_t timeBuf[64];
swprintf_s(timeBuf, L"%04u-%02u-%02u %02u:%02u:%02u.%03u",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
DWORD tid = GetCurrentThreadId();
wchar_t msgBuf[1024];
va_list ap;
va_start(ap, fmt);
_vsnwprintf_s(msgBuf, _countof(msgBuf), _TRUNCATE, fmt, ap);
va_end(ap);
fwprintf(f, L"%s [T%u] %s\n", timeBuf, (unsigned)tid, msgBuf);
fclose(f);
}
static std::wstring FormatSize(ULONGLONG bytes) {
const wchar_t* u[] = { L"B", L"KB", L"MB", L"GB", L"TB" };
double v = (double)bytes; int i = 0;
while (v >= 1024.0 && i < 4) { v /= 1024.0; ++i; }
wchar_t buf[64]; swprintf_s(buf, L"%.2f %s", v, u[i]); return buf;
}
static std::wstring FormatFileTime(const FILETIME& ft) {
SYSTEMTIME utc, loc; FileTimeToSystemTime(&ft, &utc);
SystemTimeToTzSpecificLocalTime(NULL, &utc, &loc);
wchar_t buf[64]; swprintf_s(buf, L"%04u-%02u-%02u %02u:%02u",
loc.wYear, loc.wMonth, loc.wDay, loc.wHour, loc.wMinute); return buf;
}
static std::wstring FormatHMSms(LONGLONG ms) {
if (ms < 0) ms = 0;
LONGLONG s = ms / 1000, h = s / 3600, m = (s % 3600) / 60, sec = s % 60;
wchar_t buf[64];
if (h > 0) swprintf_s(buf, L"%lld:%02lld:%02lld", h, m, sec);
else swprintf_s(buf, L"%lld:%02lld", m, sec);
return buf;
}
static std::wstring FormatDuration100ns(ULONGLONG d100) {
return FormatHMSms((LONGLONG)(d100 / 10000ULL));
}
static std::string ToUtf8(const std::wstring& ws) {
if (ws.empty()) return std::string();
int n = WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), (int)ws.size(), NULL, 0, NULL, NULL);
std::string s(n, '\0');
WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), (int)ws.size(), &s[0], n, NULL, NULL);
return s;
}
static std::wstring ExtLower(const std::wstring& p) {
size_t dot = p.find_last_of(L'.'); if (dot == std::wstring::npos) return L"";
std::wstring e = p.substr(dot); std::transform(e.begin(), e.end(), e.begin(), ::towlower); return e;
}
static bool IsVideoFile(const std::wstring& path) {
static const wchar_t* exts[] = {
L".mp4", L".mkv", L".mov", L".avi", L".wmv", L".m4v", L".ts", L".m2ts", L".webm", L".flv", L".rm",
};
std::wstring e = ExtLower(path);
for (size_t i = 0; i < _countof(exts); ++i) if (e == exts[i]) return true;
return false;
}
// Fast cached attempt (no I/O if system cache has props)
static bool GetVideoPropsFastCached(const std::wstring& path, int& outW, int& outH, ULONGLONG& outDur100ns) {
outW = outH = 0; outDur100ns = 0;
ComPtr<IShellItem2> item;
if (FAILED(SHCreateItemFromParsingName(path.c_str(), NULL, IID_PPV_ARGS(&item)))) return false;
ComPtr<IPropertyStore> store;
if (FAILED(item->GetPropertyStore(GPS_FASTPROPERTIESONLY, IID_PPV_ARGS(&store)))) return false;
PROPVARIANT v; PropVariantInit(&v);
if (SUCCEEDED(store->GetValue(PKEY_Video_FrameWidth, &v)) && v.vt == VT_UI4) outW = (int)v.ulVal;
PropVariantClear(&v);
if (SUCCEEDED(store->GetValue(PKEY_Video_FrameHeight, &v)) && v.vt == VT_UI4) outH = (int)v.ulVal;
PropVariantClear(&v);
if (SUCCEEDED(store->GetValue(PKEY_Media_Duration, &v)) && (v.vt == VT_UI8 || v.vt == VT_UI4)) {
outDur100ns = (v.vt == VT_UI8) ? v.uhVal.QuadPart : (ULONGLONG)v.ulVal;
}
PropVariantClear(&v);
return (outW | outH | outDur100ns) != 0;
}
// Full property read (may hit disk); used by worker
static bool GetVideoProps(const std::wstring& path, int& outW, int& outH, ULONGLONG& outDur100ns) {
outW = outH = 0; outDur100ns = 0;
ComPtr<IShellItem2> item;
if (FAILED(SHCreateItemFromParsingName(path.c_str(), NULL, IID_PPV_ARGS(&item)))) return false;
ComPtr<IPropertyStore> store;
if (FAILED(item->GetPropertyStore(GPS_DEFAULT, IID_PPV_ARGS(&store)))) return false;
PROPVARIANT v; PropVariantInit(&v);
if (SUCCEEDED(store->GetValue(PKEY_Video_FrameWidth, &v)) && v.vt == VT_UI4) outW = (int)v.ulVal;
PropVariantClear(&v);
if (SUCCEEDED(store->GetValue(PKEY_Video_FrameHeight, &v)) && v.vt == VT_UI4) outH = (int)v.ulVal;
PropVariantClear(&v);
if (SUCCEEDED(store->GetValue(PKEY_Media_Duration, &v)) && (v.vt == VT_UI8 || v.vt == VT_UI4)) {
outDur100ns = (v.vt == VT_UI8) ? v.uhVal.QuadPart : (ULONGLONG)v.ulVal;
}
PropVariantClear(&v);
return (outW | outH | outDur100ns) != 0;
}
// Title
static void SetTitlePlaying() {
if (!g_inPlayback || g_playlist.empty()) return;
const std::wstring& full = g_playlist[g_playlistIndex];
const wchar_t* base = wcsrchr(full.c_str(), L'\\'); base = base ? base + 1 : full.c_str();
libvlc_time_t cur = g_mp ? libvlc_media_player_get_time(g_mp) : 0;
libvlc_time_t len = g_mp ? libvlc_media_player_get_length(g_mp) : 0;
std::wstring left;
if (g_playlist.size() <= 1) {
left = L"(Single File) ";
}
else {
wchar_t buf[64];
swprintf_s(buf, L"(Play List %zu of %zu) ", g_playlistIndex + 1, g_playlist.size());
left = buf;
}
std::wstring t = left;
t += base; t += L" ";
t += FormatHMSms(cur); t += L" / "; t += FormatHMSms(len);
SetWindowTextW(g_hwndMain, t.c_str());
}
static std::wstring JoinTermsForTitle() {
if (!g_search.active || g_search.termsLower.empty()) return L"";
std::wstring s = L"\""; s += g_search.termsLower[0]; s += L"\"";
for (size_t i = 1; i < g_search.termsLower.size(); ++i) {
s += L" & \""; s += g_search.termsLower[i]; s += L"\"";
}
return s;
}
static void SetTitleFolderOrDrives() {
std::wstring t = L"Media Explorer (libVLC) - ";
if (g_view == ViewKind::Drives) t += L"[Drives]";
else if (g_view == ViewKind::Folder) t += EnsureSlash(g_folder);
else t += L"Search - " + JoinTermsForTitle();
SetWindowTextW(g_hwndMain, t.c_str());
}
// ----------------------------- ffprobe helpers (video properties during playback)
// Run a wide command line through ffprobe and collect stdout lines
static bool RunFfprobeCommand(const std::wstring& cmdLine, std::vector<std::string>& outLines) {
outLines.clear();
FILE* f = _wpopen(cmdLine.c_str(), L"rt");
if (!f) return false;
char buf[512];
while (fgets(buf, sizeof(buf), f)) {
size_t len = strlen(buf);
while (len && (buf[len - 1] == '\n' || buf[len - 1] == '\r')) {
buf[--len] = '\0';
}
outLines.emplace_back(buf);
}
int rc = _pclose(f);
return (rc == 0);
}
// Query width, height, video codec, audio codec for a given file via ffprobe.
// Query width, height, video codec, audio codec for a given file via ffprobe.
// Uses key=value output for robust parsing.
static bool GetMediaInfoFromFfprobe(const std::wstring& path,
int& outW,
int& outH,
std::wstring& outVideoCodec,
std::wstring& outAudioCodec) {
outW = outH = 0;
outVideoCodec.clear();
outAudioCodec.clear();
bool gotV = false;
bool gotA = false;
// ---------------- Video stream: width, height, codec_name ----------------
//
// We ask ffprobe to print ONLY:
// codec_name=...
// width=...
// height=...
//
// Example lines:
// codec_name=h264
// width=576
// height=768
//
std::wstring cmdV =
L"ffprobe -v error "
L"-select_streams v:0 "
L"-show_entries stream=codec_name,width,height "
L"-of default=noprint_wrappers=1 \"";
cmdV += path;
cmdV += L"\"";
std::vector<std::string> linesV;
if (RunFfprobeCommand(cmdV, linesV)) {
std::string codecV;
int wTmp = 0, hTmp = 0;
for (const auto& line : linesV) {
if (line.empty()) continue;
// codec_name=...
const char* kCodec = "codec_name=";
const size_t codecLen = sizeof("codec_name=") - 1;
if (line.size() >= codecLen && line.compare(0, codecLen, kCodec) == 0) {
codecV = line.substr(codecLen);
continue;
}
// width=...
const char* kWidth = "width=";
const size_t widthLen = sizeof("width=") - 1;
if (line.size() >= widthLen && line.compare(0, widthLen, kWidth) == 0) {
wTmp = std::strtol(line.c_str() + widthLen, nullptr, 10);
continue;
}
// height=...
const char* kHeight = "height=";
const size_t heightLen = sizeof("height=") - 1;
if (line.size() >= heightLen && line.compare(0, heightLen, kHeight) == 0) {
hTmp = std::strtol(line.c_str() + heightLen, nullptr, 10);
continue;
}
}
if (wTmp > 0 && hTmp > 0) {
outW = wTmp;
outH = hTmp;
}
if (!codecV.empty()) {
outVideoCodec.assign(codecV.begin(), codecV.end()); // ASCII-safe
}
gotV = (wTmp > 0 || hTmp > 0 || !codecV.empty());
}
// ---------------- Audio stream: codec_name ----------------
//
// Example line:
// codec_name=aac
//
std::wstring cmdA =
L"ffprobe -v error "
L"-select_streams a:0 "
L"-show_entries stream=codec_name "
L"-of default=noprint_wrappers=1 \"";
cmdA += path;
cmdA += L"\"";
std::vector<std::string> linesA;
if (RunFfprobeCommand(cmdA, linesA)) {
std::string codecA;
for (const auto& line : linesA) {
if (line.empty()) continue;
const char* kCodec = "codec_name=";
const size_t codecLen = sizeof("codec_name=") - 1;
if (line.size() >= codecLen && line.compare(0, codecLen, kCodec) == 0) {
codecA = line.substr(codecLen);
break;
}
}
if (!codecA.empty()) {
outAudioCodec.assign(codecA.begin(), codecA.end());
gotA = true;
}
}
return gotV || gotA;
}
// Show MessageBox with media properties for the currently playing item
static void ShowCurrentVideoProperties() {
if (!g_inPlayback || g_playlist.empty()) {
MessageBoxW(g_hwndMain, L"No video is currently playing.", L"Video properties",
MB_OK);
return;
}
const std::wstring& full = g_playlist[g_playlistIndex];
// 1) Start with resolution from Shell (same as file list) so we always have
// something sensible even if ffprobe parsing fails.
int wShell = 0, hShell = 0;
ULONGLONG durDummy = 0;
GetVideoPropsFastCached(full, wShell, hShell, durDummy); // ignores if it fails
int w = wShell;
int h = hShell;
std::wstring vCodec, aCodec;
// Pause playback BEFORE doing ffprobe and BEFORE showing the dialog
bool wasPlaying = (g_mp && libvlc_media_player_is_playing(g_mp) > 0);
if (g_mp && wasPlaying) {
libvlc_media_player_set_pause(g_mp, 1);
}
bool okFF = false;
if (g_cfg.ffprobeAvailable) {
LogLine(L"ffprobe: querying \"%s\"", full.c_str());
okFF = GetMediaInfoFromFfprobe(full, w, h, vCodec, aCodec);
LogLine(L"ffprobe: \"%s\" result ok=%d w=%d h=%d vCodec=\"%s\" aCodec=\"%s\"",
full.c_str(), okFF ? 1 : 0, w, h,
vCodec.c_str(), aCodec.c_str());
}
// If ffprobe didn't give us good values, fall back to Shell result
if (w <= 0) w = wShell;
if (h <= 0) h = hShell;
std::wstring msg = L"File: ";
msg += full;
msg += L"\n\n";
if (w > 0 && h > 0) {
wchar_t buf[64];
swprintf_s(buf, L"%d x %d", w, h);
msg += L"Resolution: ";
msg += buf;
msg += L"\n";
}
else {
msg += L"Resolution: (unknown)\n";
}
msg += L"Video codec: ";
msg += (vCodec.empty() ? L"(unknown)" : vCodec);
msg += L"\n";
msg += L"Audio codec: ";
msg += (aCodec.empty() ? L"(unknown)" : aCodec);
msg += L"\n";
if (g_cfg.ffprobeAvailable && !okFF) {
msg += L"\nNote: ffprobe.exe did not return information "
L"(not found in PATH or error running command).";
}
else if (!g_cfg.ffprobeAvailable) {
msg += L"\nNote: ffprobe-based details are disabled in mediaexplorer.ini.";
}
// Show dialog WHILE paused
MessageBoxW(g_hwndMain, msg.c_str(), L"Video properties", MB_OK);
// Resume playback only AFTER dialog closes
if (g_mp && wasPlaying) {
libvlc_media_player_set_pause(g_mp, 0);
}
}
static void LoadConfigFromIni() {
wchar_t exePath[MAX_PATH] = {};
if (!GetModuleFileNameW(NULL, exePath, MAX_PATH)) return;
PathRemoveFileSpecW(exePath);
std::wstring iniPath = exePath;
iniPath += L"\\mediaexplorer.ini";
std::wifstream in(iniPath);
if (!in) {
// No .ini file -> all defaults (ffmpeg/ffprobe disabled, no upscaleDirectory)
return;
}
std::wstring line;
while (std::getline(in, line)) {
line = Trim(line);
if (line.empty()) continue;
if (line[0] == L';' || line[0] == L'#') continue;
if (line.front() == L'[' && line.back() == L']') continue; // ignore sections
// Strip inline comments after ';'
size_t semi = line.find(L';');
if (semi != std::wstring::npos) {
line = Trim(line.substr(0, semi));
if (line.empty()) continue;
}