Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1872 lines (1867 loc) · 64 KB
/
Copy pathmain.cpp
File metadata and controls
1872 lines (1867 loc) · 64 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
#define NOMINMAX
#include <windows.h>
#include "resource.h"
#include <algorithm>
#include <avrt.h>
#pragma comment(lib,"avrt.lib")
#include <cmath>
#include <gdiplus.h>
#include <memory>
#include <chrono>
#include <commdlg.h>
#include <commctrl.h>
#pragma comment(lib,"comctl32.lib")
#include <d3d10_1.h>
#include <d3d11_1.h>
#include <dcomp.h>
#include <dwmapi.h>
#include <dxgi1_4.h>
#include <filesystem>
#include <iomanip>
#include <fstream>
#include <condition_variable>
#include <deque>
#include <mfapi.h>
#include <mferror.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#include <mutex>
#include <mfmediaengine.h>
#include <psapi.h>
#include <shellapi.h>
#include <shlwapi.h>
#include <shobjidl.h>
#include <string>
#include <thread>
#include <vector>
#include <windowsx.h>
#include <wrl.h>
#include <wrl/implements.h>
#include <winternl.h>
#include <d3dkmthk.h>
#include <winstring.h>
#pragma comment(lib,"runtimeobject.lib")
#include <wtsapi32.h>
using Microsoft::WRL::ComPtr;
using namespace Microsoft::WRL;
namespace fs = std::filesystem;
constexpr UINT Tray = WM_APP + 1, Media = WM_APP + 2, Visibility = WM_APP + 3,
PosterApplied = WM_APP + 4, TestPower = WM_APP + 5;
constexpr UINT_PTR Draw = 1, Inspect = 2, Unload = 3, Settled = 5, UsageTick = 6;
constexpr UINT UsageItem = 98;
HWND controller;
HINSTANCE instance;
NOTIFYICONDATAW icon{sizeof(icon)};
UINT taskbarRestart;
std::vector<HWINEVENTHOOK> hooks;
HPOWERNOTIFY powerHook;
bool locked = false, screenOff = false, paused = false, covered = false,
ready = false, freezePending = false;
constexpr UINT SmoothResume = 4, MaximumSavings = 5;
bool maximumSavings = false, batteryRule = false, batteryOverride = false;
HPOWERNOTIFY acHook, saverHook;
void updateBattery();
// Hands idle pages back to Windows; they reload on demand.
void trimMemory() { SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T)-1, (SIZE_T)-1); }
void updateBatteryCopy();
void updatePlayFile();
extern int testPower;
void finishBatteryCopy();
void stopBatteryCopy(bool cancelled);
extern bool batteryFps;
extern HANDLE batteryCopyProcess;
bool posterPending = false, presented = false, parked = false;
bool mediaStarted = false, applyingPause = false, resumeAfterPause = false;
std::thread pauseWorker;
bool inspectQueued = false, probe = false, layoutDirty = true;
unsigned generation = 0, frames = 0;
double position = 0;
fs::path source, folder, snapshot;
std::wofstream report;
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
ComPtr<IMFDXGIDeviceManager> manager;
ComPtr<IMFMediaEngine> engine;
ComPtr<IDXGISwapChain1> chain;
ComPtr<IDCompositionDevice> compositor;
UINT width = 0, height = 0, cadence = 16;
double frameRate = 60;
struct Display {
RECT rect, work;
HWND window{};
bool visible = true;
ComPtr<IDCompositionTarget> target;
ComPtr<IDCompositionVisual> visual;
};
std::vector<Display> displays;
void check(HRESULT h) {
if (FAILED(h))
throw h;
}
void status(const wchar_t *msg) {
if (!wcscmp(icon.szTip, msg))
return;
SetWindowText(controller, msg);
wcscpy_s(icon.szTip, msg);
Shell_NotifyIconW(NIM_MODIFY, &icon);
}
void saveState() {
if (probe)
return;
auto file = (folder / L"settings.ini").wstring();
WritePrivateProfileStringW(L"wallpaper", L"file", source.c_str(),
file.c_str());
WritePrivateProfileStringW(L"wallpaper", L"paused", paused ? L"1" : L"0",
file.c_str());
WritePrivateProfileStringW(L"wallpaper", L"time",
std::to_wstring(position).c_str(), file.c_str());
}
HANDLE ticks;
ComPtr<IDXGIAdapter3> probeAdapter;
double cpuSeconds() {
FILETIME a, b, k, u;
GetProcessTimes(GetCurrentProcess(), &a, &b, &k, &u);
ULARGE_INTEGER x{}, y{};
x.LowPart = k.dwLowDateTime;
x.HighPart = k.dwHighDateTime;
y.LowPart = u.dwLowDateTime;
y.HighPart = u.dwHighDateTime;
return (x.QuadPart + y.QuadPart) / 1e7;
}
void memory(const wchar_t *label) {
if (probeAdapter) {
for (auto segment : {DXGI_MEMORY_SEGMENT_GROUP_LOCAL,
DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL}) {
DXGI_QUERY_VIDEO_MEMORY_INFO info{};
if (SUCCEEDED(probeAdapter->QueryVideoMemoryInfo(0, segment, &info)))
report << label
<< (segment == DXGI_MEMORY_SEGMENT_GROUP_LOCAL ? L" local"
: L" nonlocal")
<< L" GPU allocation MiB " << info.CurrentUsage / 1048576.0
<< std::endl;
}
}
PROCESS_MEMORY_COUNTERS_EX m{};
m.cb = sizeof(m);
if (GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *)&m,
sizeof(m)))
report << label << L" working set MiB " << m.WorkingSetSize / 1048576.0
<< L" private commit MiB " << m.PrivateUsage / 1048576.0
<< std::endl;
}
using Clock = std::chrono::steady_clock;
HANDLE surfaceHandle;
fs::path leanFailedFor, directFailedFor;
std::vector<fs::path> directRejected;
std::wstring playbackPath;
#include "direct_player.h"
#include "lean_player.h"
void closePlayer() {
if (ticks)
CancelWaitableTimer(ticks);
KillTimer(controller, Draw);
KillTimer(controller, Unload);
++generation;
if (engine) {
// position tracks the frame submitted to the compositor.
engine->Shutdown();
}
leanClose();
ready = presented = parked = false;
engine.Reset();
for (auto &d : displays) {
d.visual.Reset();
d.target.Reset();
if (d.window)
DestroyWindow(d.window);
d.window = nullptr;
}
chain.Reset();
if (surfaceHandle)
CloseHandle(surfaceHandle);
surfaceHandle = nullptr;
compositor.Reset();
manager.Reset();
context.Reset();
device.Reset();
}
class Events final
: public RuntimeClass<RuntimeClassFlags<ClassicCom>, IMFMediaEngineNotify> {
public:
unsigned id = generation;
HRESULT STDMETHODCALLTYPE EventNotify(DWORD e, DWORD_PTR a, DWORD) override {
if (e == MF_MEDIA_ENGINE_EVENT_NOTIFYSTABLESTATE)
SetEvent(reinterpret_cast<HANDLE>(a));
if (e == MF_MEDIA_ENGINE_EVENT_LOADEDDATA ||
e == MF_MEDIA_ENGINE_EVENT_ERROR)
PostMessage(controller, Media, id, e);
return S_OK;
}
};
fs::path playFile();
fs::path playingFile;
bool swapPending = false, swapKept = false;
double swapAt = 0;
bool playerOpen() { return engine || leanActive; }
HRESULT playerPlay() {
if (!leanActive)
return engine->Play();
leanPlay();
return S_OK;
}
HRESULT playerPause() {
if (!leanActive)
return engine->Pause();
leanPause();
return S_OK;
}
bool playerPaused() { return leanActive ? leanPaused() : engine->IsPaused() != FALSE; }
double playerTime() { return leanActive ? position : engine->GetCurrentTime(); }
double playerDuration() { return leanActive ? leanDuration : engine->GetDuration(); }
void playerSeek(double seconds) {
if (leanActive)
leanRestart(playingFile, seconds);
else
check(engine->SetCurrentTime(seconds));
}
void createDevice() {
UINT flags =
D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT;
// Test hook: LITELY_TEST_ADAPTER picks the GPU whose name contains this text.
ComPtr<IDXGIAdapter1> chosen;
wchar_t want[64]{};
if (GetEnvironmentVariableW(L"LITELY_TEST_ADAPTER", want, 64)) {
ComPtr<IDXGIFactory1> factory;
check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));
for (UINT i = 0; factory->EnumAdapters1(i, &chosen) == S_OK; i++, chosen.Reset()) {
DXGI_ADAPTER_DESC1 about;
if (SUCCEEDED(chosen->GetDesc1(&about)) && wcsstr(about.Description, want))
break;
}
}
check(D3D11CreateDevice(chosen.Get(), chosen ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE, nullptr, flags,
nullptr, 0, D3D11_SDK_VERSION, &device, nullptr,
&context));
ComPtr<ID3D10Multithread> multi;
check(context.As(&multi));
multi->SetMultithreadProtected(TRUE);
}
// Media Foundation is only needed by the lean decode thread and the Media Engine.
void ensureManager() {
if (manager)
return;
if (!mediaStarted) {
check(MFStartup(MF_VERSION));
mediaStarted = true;
}
UINT token;
check(MFCreateDXGIDeviceManager(&token, &manager));
check(manager->ResetDevice(device.Get(), token));
}
void openPlayer() {
if (playerOpen() || source.empty())
return;
createDevice();
playingFile = playFile();
wchar_t forced[16]{};
GetEnvironmentVariableW(L"LITELY_PIPELINE", forced, 16);
if (wcscmp(forced, L"legacy") && leanFailedFor != source) {
leanOpen(playingFile, position);
return;
}
ensureManager();
ComPtr<IMFAttributes> attr;
check(MFCreateAttributes(&attr, 4));
auto events = Make<Events>();
check(attr->SetUnknown(MF_MEDIA_ENGINE_CALLBACK, events.Get()));
check(attr->SetUnknown(MF_MEDIA_ENGINE_DXGI_MANAGER, manager.Get()));
check(attr->SetUINT32(MF_MEDIA_ENGINE_VIDEO_OUTPUT_FORMAT,
DXGI_FORMAT_B8G8R8A8_UNORM));
ComPtr<IMFMediaEngineClassFactory> factory;
check(CoCreateInstance(CLSID_MFMediaEngineClassFactory, nullptr,
CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory)));
check(factory->CreateInstance(0, attr.Get(), &engine));
check(engine->SetMuted(TRUE));
check(engine->SetLoop(TRUE));
DWORD chars = 32768;
wchar_t url[32768];
check(UrlCreateFromPathW(playingFile.c_str(), url, &chars, 0));
BSTR b = SysAllocString(url);
HRESULT result = engine->SetSource(b);
SysFreeString(b);
check(result);
check(engine->Load());
}
BOOL CALLBACK collectMonitor(HMONITOR monitor, HDC, LPRECT, LPARAM) {
MONITORINFO info{sizeof(info)};
if (GetMonitorInfo(monitor, &info)) {
Display d{};
d.rect = info.rcMonitor;
d.work = info.rcWork;
displays.push_back(d);
}
return TRUE;
}
HWND iconLayer;
BOOL CALLBACK findWorker(HWND w, LPARAM out) {
if (FindWindowEx(w, nullptr, L"SHELLDLL_DefView", nullptr)) {
HWND next = FindWindowEx(nullptr, w, L"WorkerW", nullptr);
if (next) {
*reinterpret_cast<HWND *>(out) = next;
return FALSE;
}
}
return TRUE;
}
HWND desktop() {
HWND prog = FindWindow(L"Progman", nullptr);
if (!prog)
throw E_HANDLE;
HWND worker = nullptr;
for (int attempt = 0; attempt < 2; ++attempt) {
iconLayer = FindWindowEx(prog, nullptr, L"SHELLDLL_DefView", nullptr);
if (iconLayer &&
(GetWindowLongPtr(prog, GWL_EXSTYLE) & WS_EX_NOREDIRECTIONBITMAP) &&
FindWindowEx(prog, nullptr, L"WorkerW", nullptr))
return prog;
iconLayer = nullptr;
EnumWindows(findWorker, reinterpret_cast<LPARAM>(&worker));
if (worker || attempt)
break;
DWORD_PTR result;
SendMessageTimeout(prog, 0x052C, 0xD, 1, SMTO_ABORTIFHUNG, 1000, &result);
}
if (!worker)
throw E_HANDLE;
return worker;
}
void createOutput(UINT videoWidth, UINT videoHeight, bool nv12) {
width = videoWidth;
height = videoHeight;
if (!width || !height)
throw E_FAIL;
UINT maxW = 0, maxH = 0;
for (auto &d : displays) {
maxW = std::max(maxW, UINT(d.rect.right - d.rect.left));
maxH = std::max(maxH, UINT(d.rect.bottom - d.rect.top));
}
double scale = nv12 ? 1 :
std::min(1.0, std::max(double(maxW) / width, double(maxH) / height));
width = std::max(1u, UINT(std::ceil(width * scale)));
height = std::max(1u, UINT(std::ceil(height * scale)));
ComPtr<IDXGIDevice> dx;
check(device.As(&dx));
ComPtr<IDXGIAdapter> adapter;
check(dx->GetAdapter(&adapter));
if (probe)
adapter.As(&probeAdapter);
ComPtr<IDXGIFactory2> f;
check(adapter->GetParent(IID_PPV_ARGS(&f)));
DXGI_SWAP_CHAIN_DESC1 desc{};
desc.Width = width;
desc.Height = height;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = 2;
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
desc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
desc.Scaling = DXGI_SCALING_STRETCH;
check(DCompositionCreateDevice(dx.Get(), IID_PPV_ARGS(&compositor)));
ComPtr<IUnknown> content;
if (nv12) {
desc.Format = DXGI_FORMAT_NV12;
desc.Flags = DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO | DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO;
ComPtr<IDXGIFactoryMedia> media;
check(f.As(&media));
check(DCompositionCreateSurfaceHandle(COMPOSITIONOBJECT_ALL_ACCESS, nullptr, &surfaceHandle));
check(media->CreateSwapChainForCompositionSurfaceHandle(device.Get(), surfaceHandle, &desc, nullptr, &chain));
ComPtr<IDXGISwapChain3> color;
check(chain.As(&color));
check(color->SetColorSpace1(leanColorSpace));
check(compositor->CreateSurfaceFromHandle(surfaceHandle, &content));
} else {
check(f->CreateSwapChainForComposition(device.Get(), &desc, nullptr, &chain));
content = chain;
}
// Probe only: a 1:1 topmost window whose screen pixels can be compared with the still.
bool topmost = probe && GetEnvironmentVariableW(L"LITELY_PROBE_TOPMOST", nullptr, 0);
HWND parent = topmost ? nullptr : desktop();
for (auto &d : displays) {
int w = d.rect.right - d.rect.left, h = d.rect.bottom - d.rect.top;
POINT p{d.rect.left, d.rect.top};
if (parent)
ScreenToClient(parent, &p);
DWORD ex = WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP;
if (topmost) {
w = width;
h = height;
p = {40, 40};
ex |= WS_EX_TOPMOST;
}
if (parent && iconLayer)
ex |= WS_EX_LAYERED;
d.window = CreateWindowEx(ex, L"LitelySurface", L"Litely",
parent ? WS_CHILD : WS_POPUP, p.x, p.y, w, h,
parent, nullptr, instance, nullptr);
if (!d.window) {
DWORD error = GetLastError();
if (probe)
report << L"CreateWindow error " << error << L" parent " << parent
<< L" icon layer " << iconLayer << std::endl;
throw HRESULT_FROM_WIN32(error);
}
if (ex & WS_EX_LAYERED)
SetLayeredWindowAttributes(d.window, 0, 255, LWA_ALPHA);
check(compositor->CreateTargetForHwnd(d.window, TRUE, &d.target));
check(compositor->CreateVisual(&d.visual));
D2D_MATRIX_3X2_F m{};
float k = std::max(float(w) / width, float(h) / height);
m._11 = m._22 = k;
m._31 = (w - width * k) / 2;
m._32 = (h - height * k) / 2;
check(d.visual->SetTransform(m));
check(d.visual->SetContent(content.Get()));
check(d.target->SetRoot(d.visual.Get()));
if (!topmost)
SetWindowPos(d.window, iconLayer ? iconLayer : HWND_BOTTOM, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
check(compositor->Commit());
}
void setupOutput() {
DWORD nativeW, nativeH;
check(engine->GetNativeVideoSize(&nativeW, &nativeH));
createOutput(nativeW, nativeH, false);
// Use source cadence where available. Poll only while the wallpaper is
// visible.
cadence = 16;
frameRate = 60;
ComPtr<IMFMediaEngineEx> ex;
if (SUCCEEDED(engine.As(&ex))) {
DWORD count = 0;
ex->GetNumberOfStreams(&count);
for (DWORD i = 0; i < count; i++) {
PROPVARIANT v{};
if (SUCCEEDED(ex->GetStreamAttribute(i, MF_MT_FRAME_RATE, &v)) &&
v.vt == VT_UI8 && v.uhVal.HighPart && v.uhVal.LowPart) {
frameRate = double(v.uhVal.HighPart) / v.uhVal.LowPart;
cadence = std::clamp(UINT(1000.0 * v.uhVal.LowPart / v.uhVal.HighPart),
1u, 1000u);
PropVariantClear(&v);
break;
}
PropVariantClear(&v);
}
}
}
fs::path posterPath(const fs::path &video) {
auto name = fs::weakly_canonical(video).wstring();
CharLowerBuffW(name.data(), static_cast<DWORD>(name.size()));
unsigned long long hash = 14695981039346656037ull;
for (wchar_t c : name) {
hash ^= c;
hash *= 1099511628211ull;
}
return folder / (L"wallpaper-" + std::to_wstring(hash) + L".bmp");
}
// Explorer records history after SetWallpaper returns, so the main loop
// watches this key and keeps Litely's stills out of Recent images.
HKEY historyKey;
HANDLE historyChanged;
void forgetPosterHistory() {
HKEY key = historyKey;
if (!key)
return;
// Re-arm first so Explorer writes that land during this pass trigger another.
RegNotifyChangeKeyValue(key, FALSE, REG_NOTIFY_CHANGE_LAST_SET,
historyChanged, TRUE);
auto prefix = folder.wstring() + L"\\";
std::vector<std::wstring> kept;
int slots = 0;
bool dropped = false;
for (int i = 0; i < 16; i++) {
wchar_t value[MAX_PATH * 4]{};
DWORD size = sizeof value - sizeof(wchar_t), type = 0;
auto name = L"BackgroundHistoryPath" + std::to_wstring(i);
if (RegQueryValueExW(key, name.c_str(), nullptr, &type, (BYTE *)value, &size) ||
(type != REG_SZ && type != REG_EXPAND_SZ))
continue;
slots = i + 1;
if (!_wcsnicmp(value, prefix.c_str(), prefix.size()))
dropped = true;
else
kept.push_back(value);
}
for (int i = 0; dropped && i < slots; i++) {
auto name = L"BackgroundHistoryPath" + std::to_wstring(i);
if (i < (int)kept.size())
RegSetValueExW(key, name.c_str(), 0, REG_SZ, (const BYTE *)kept[i].c_str(),
DWORD((kept[i].size() + 1) * sizeof(wchar_t)));
else
RegDeleteValueW(key, name.c_str());
}
}
extern "C" NTSTATUS NTAPI RtlGetVersion(PRTL_OSVERSIONINFOW version);
#pragma comment(lib, "ntdll.lib")
// Windows 11 keeps a wallpaper per virtual desktop, and switching between two different ones stalls Explorer for seconds.
// Uses the shell's private desktop manager, whose layout changes between builds: only from 24H2, and only if QueryService succeeds.
void wallpaperOnAllDesktops(const fs::path &path) {
RTL_OSVERSIONINFOW version{sizeof version};
if (RtlGetVersion(&version) != 0 || version.dwBuildNumber < 26100)
return;
GUID shellId, serviceId, managerId;
CLSIDFromString(L"{C2F03A33-21F5-47FA-B4BB-156362A2F239}", &shellId);
CLSIDFromString(L"{C5E0CDCA-7B6E-41B2-9FC4-D93975CC467B}", &serviceId);
CLSIDFromString(L"{53F5CA0B-158F-4124-900C-057158060B27}", &managerId);
ComPtr<IServiceProvider> shell;
ComPtr<IUnknown> desktops;
if (FAILED(CoCreateInstance(shellId, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&shell))) ||
FAILED(shell->QueryService(serviceId, managerId,
reinterpret_cast<void **>(desktops.GetAddressOf()))))
return;
auto text = path.wstring();
HSTRING_HEADER header;
HSTRING value;
if (FAILED(WindowsCreateStringReference(text.c_str(), UINT32(text.size()), &header, &value)))
return;
// UpdateWallpaperPathForAllDesktops, the 16th method after IUnknown's three.
using Update = HRESULT(STDMETHODCALLTYPE *)(IUnknown *, HSTRING);
reinterpret_cast<Update>((*reinterpret_cast<void ***>(desktops.Get()))[18])(desktops.Get(), value);
}
void applyPoster(bool changed, const fs::path &path) {
if (probe || GetEnvironmentVariableW(
L"LITELY_TEST_SKIP_PERSONALIZATION", nullptr, 0))
return;
// COM can't call Explorer while a sender waits on us (RPC_E_CANTCALLOUT_ININPUTSYNCCALL).
if (InSendMessage())
ReplyMessage(0);
ComPtr<IDesktopWallpaper> wallpaper;
check(CoCreateInstance(CLSID_DesktopWallpaper, nullptr, CLSCTX_ALL,
IID_PPV_ARGS(&wallpaper)));
PWSTR current = nullptr;
HRESULT hr = wallpaper->GetWallpaper(nullptr, ¤t);
bool same = hr == S_OK && current && !_wcsicmp(current, path.c_str());
CoTaskMemFree(current);
if (changed || !same)
check(wallpaper->SetWallpaper(nullptr, path.c_str()));
DESKTOP_WALLPAPER_POSITION style;
if (SUCCEEDED(wallpaper->GetPosition(&style)) && style != DWPOS_FILL)
check(wallpaper->SetPosition(DWPOS_FILL));
wallpaperOnAllDesktops(path);
}
void preparePoster(bool applyCached) {
snapshot = posterPath(source);
posterPending = !fs::exists(snapshot) ||
fs::last_write_time(snapshot) < fs::last_write_time(source);
if (!posterPending && applyCached)
applyPoster(false, snapshot);
}
void capture(ID3D11Texture2D *frame);
bool checkFrontBuffer = false;
Clock::time_point probeResume;
double millisecondsSince(Clock::time_point start) {
return std::chrono::duration<double, std::milli>(Clock::now() - start)
.count();
}
ULONGLONG seekStarted = 0;
bool drawEngine(LONGLONG &pts, ComPtr<ID3D11Texture2D> &texture) {
if (engine->OnVideoStreamTick(&pts) != S_OK)
return false;
// A successful tick can still belong to the beginning of the clip while the
// seek is pending.
if (!presented && position > 0 && pts / 1e7 + 0.0001 < position) {
const bool wrapped =
position + 2 * cadence / 1000.0 >= engine->GetDuration() &&
GetTickCount64() - seekStarted > 200 && !engine->IsSeeking() &&
engine->GetCurrentTime() < 0.5;
if (!wrapped)
return false;
}
check(chain->GetBuffer(0, IID_PPV_ARGS(&texture)));
RECT dest{0, 0, LONG(width), LONG(height)};
MFARGB black{};
check(engine->TransferVideoFrame(texture.Get(), nullptr, &dest, &black));
return true;
}
void draw() {
LONGLONG pts;
ComPtr<ID3D11Texture2D> texture;
if (leanActive) {
bool acquired = leanAcquire(&pts);
leanSchedule();
if (!acquired)
return;
if (posterPending || checkFrontBuffer) {
try {
texture = leanStill();
} catch (HRESULT) {
leanFailedFor = source;
closePlayer();
openPlayer();
return;
}
}
} else if (!drawEngine(pts, texture))
return;
if (posterPending) {
capture(texture.Get());
if (probe) {
auto first = snapshot;
CopyFileW(snapshot.c_str(), first.replace_extension(L".first.bmp").c_str(), FALSE);
}
applyPoster(true, snapshot);
posterPending = false;
}
if (checkFrontBuffer)
capture(texture.Get());
if (leanActive) {
texture.Reset();
leanDropStill();
}
check(chain->Present(0, 0));
if (directActive) {
leanAdvance();
leanSchedule();
}
if (!presented && probe)
report << L"resume offset (ms): " << (pts / 1e7 - position) * 1000
<< std::endl;
position = pts / 1e7;
if (swapPending) {
swapPending = false;
wchar_t log[MAX_PATH];
if (GetEnvironmentVariableW(L"LITELY_TEST_LOG", log, MAX_PATH)) {
std::wofstream out(log, std::ios::app);
out << L"swap " << playingFile.filename().wstring() << L" at " << std::fixed << swapAt << L" first "
<< position << (swapKept ? L" kept" : L" reopened") << std::endl;
}
}
if (!presented) {
presented = true;
for (auto &d : displays)
if (d.visible)
ShowWindow(d.window, SW_SHOWNOACTIVATE);
}
if (probe && probeResume.time_since_epoch().count()) {
report << L"resume to first frame ms " << millisecondsSince(probeResume)
<< std::endl;
probeResume = {};
}
++frames;
}
void capture(ID3D11Texture2D *frame) {
D3D11_TEXTURE2D_DESC desc{};
desc.Width = width;
desc.Height = height;
desc.MipLevels = desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.BindFlags = D3D11_BIND_RENDER_TARGET;
ComPtr<ID3D11Texture2D> staging;
desc.BindFlags = 0;
desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
check(device->CreateTexture2D(&desc, nullptr, &staging));
context->CopyResource(staging.Get(), frame);
D3D11_MAPPED_SUBRESOURCE map{};
check(context->Map(staging.Get(), 0, D3D11_MAP_READ, 0, &map));
BITMAPINFOHEADER ih{};
ih.biSize = sizeof(ih);
ih.biWidth = width;
ih.biHeight = -LONG(height);
ih.biPlanes = 1;
ih.biBitCount = 32;
BITMAPFILEHEADER header{};
header.bfType = 0x4d42;
header.bfOffBits = sizeof(header) + sizeof(ih);
header.bfSize = header.bfOffBits + width * height * 4;
auto tmp = snapshot;
tmp += L".tmp";
std::ofstream out(tmp, std::ios::binary);
out.write((char *)&header, sizeof(header));
out.write((char *)&ih, sizeof(ih));
for (UINT i = 0; i < height; i++)
out.write((char *)map.pData + i * map.RowPitch, width * 4);
out.close();
context->Unmap(staging.Get(), 0);
if (!out) {
DeleteFileW(tmp.c_str());
throw HRESULT_FROM_WIN32(ERROR_WRITE_FAULT);
}
// Explorer and thumbnailers briefly hold the current still open.
for (int attempt = 0;; attempt++) {
if (MoveFileEx(tmp.c_str(), snapshot.c_str(), MOVEFILE_REPLACE_EXISTING))
return;
DWORD error = GetLastError();
if (attempt == 20 || (error != ERROR_SHARING_VIOLATION &&
error != ERROR_ACCESS_DENIED &&
error != ERROR_LOCK_VIOLATION)) {
DeleteFileW(tmp.c_str());
throw HRESULT_FROM_WIN32(error);
}
Sleep(25);
}
}
void parkPlayer() {
if (maximumSavings || batteryOverride || locked || screenOff)
closePlayer();
else
parked = ready;
}
void finishPause() {
parkPlayer();
saveState();
status(L"Litely - paused");
}
void startClock();
void freeze(bool manual = true) {
if (applyingPause)return;
KillTimer(controller, Unload);
if (manual && covered && !playerOpen() && !posterPending && fs::exists(snapshot)) {
paused = true;
finishPause();
return;
}
if (!presented || (leanActive && !leanHasFrame())) {
freezePending = true;
if (!ready)
openPlayer();
else {
check(playerPlay());
startClock();
}
return;
}
check(playerPause());
CancelWaitableTimer(ticks);
ComPtr<ID3D11Texture2D> lastFrame;
if (leanActive)
lastFrame = leanStill();
else
check(chain->GetBuffer(1, IID_PPV_ARGS(&lastFrame)));
capture(lastFrame.Get());
lastFrame.Reset();
leanDropStill();
posterPending = freezePending = false;
paused = manual;
if (probe) {
finishPause();
return;
}
if (manual)
status(L"Litely - paused");
applyingPause = true;
pauseWorker = std::thread([path = snapshot, window = controller] {
HRESULT result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(result)) {
try {
applyPoster(true, path);
} catch (HRESULT error) {
result = error;
} catch (...) {
result = E_FAIL;
}
CoUninitialize();
}
PostMessage(window, PosterApplied, static_cast<WPARAM>(result), 0);
});
}
struct Coverage {
HRGN region;
};
BOOL CALLBACK subtractWindow(HWND w, LPARAM arg) {
if (!IsWindowVisible(w) || IsIconic(w) || w == controller)
return TRUE;
DWORD pid;
GetWindowThreadProcessId(w, &pid);
if (pid == GetCurrentProcessId())
return TRUE;
wchar_t cls[128];
GetClassName(w, cls, 128);
if ((!wcscmp(cls, L"Progman") || !wcscmp(cls, L"WorkerW")) &&
FindWindowEx(w, nullptr, L"SHELLDLL_DefView", nullptr))
return FALSE;
if (!wcscmp(cls, L"Progman") || !wcscmp(cls, L"WorkerW") ||
!wcscmp(cls, L"Shell_TrayWnd") || !wcscmp(cls, L"Shell_SecondaryTrayWnd"))
return TRUE;
DWORD cloak = 0;
DwmGetWindowAttribute(w, DWMWA_CLOAKED, &cloak, sizeof cloak);
if (cloak)
return TRUE;
auto style = GetWindowLongPtr(w, GWL_EXSTYLE);
if (style & WS_EX_TRANSPARENT)
return TRUE;
// Always-on-top tool windows are overlays, like the screenshot tool's dimmed screen; pausing for them stalls the capture.
if ((style & (WS_EX_TOPMOST | WS_EX_TOOLWINDOW)) == (WS_EX_TOPMOST | WS_EX_TOOLWINDOW))
return TRUE;
if (style & WS_EX_LAYERED) {
BYTE alpha{};
DWORD flags{};
if (!GetLayeredWindowAttributes(w, nullptr, &alpha, &flags) ||
flags != LWA_ALPHA || alpha != 255)
return TRUE;
}
RECT r;
if (FAILED(DwmGetWindowAttribute(w, DWMWA_EXTENDED_FRAME_BOUNDS, &r,
sizeof r)) &&
!GetWindowRect(w, &r))
return TRUE;
HRGN cut = CreateRectRgn(0, 0, 0, 0);
if (!cut)
return TRUE;
if (GetWindowRgn(w, cut) == ERROR)
SetRectRgn(cut, r.left, r.top, r.right, r.bottom);
else {
RECT wr;
GetWindowRect(w, &wr);
OffsetRgn(cut, wr.left, wr.top);
}
HRGN region = reinterpret_cast<Coverage *>(arg)->region;
int result = CombineRgn(region, region, cut, RGN_DIFF);
DeleteObject(cut);
return result != NULLREGION;
}
void startClock() {
if (leanActive) {
leanSchedule();
return;
}
LARGE_INTEGER due;
due.QuadPart = -10000;
if (!SetWaitableTimer(ticks, &due, cadence, nullptr, nullptr, FALSE))
throw E_FAIL;
}
void resumePlayer() {
check(playerPlay());
startClock();
parked = false;
}
bool testVisible = GetEnvironmentVariableW(L"LITELY_TEST_VISIBLE", nullptr, 0) != 0;
void visibility() {
if (probe)
return;
if (applyingPause)
return;
if (layoutDirty) {
closePlayer();
displays.clear();
EnumDisplayMonitors(nullptr, nullptr, collectMonitor, 0);
layoutDirty = false;
}
if (parked && (locked || screenOff))
closePlayer();
if (batteryOverride && !posterPending) {
if (parked)
closePlayer();
return;
}
if (paused || source.empty())
return;
bool any = false;
for (auto &d : displays) {
Coverage c{CreateRectRgnIndirect(&d.work)};
if (!locked && !screenOff && c.region && !testVisible)
EnumWindows(subtractWindow, reinterpret_cast<LPARAM>(&c));
RECT box{};
bool wasVisible = d.visible;
d.visible = !locked && !screenOff &&
(!c.region || GetRgnBox(c.region, &box) != NULLREGION);
if (c.region)
DeleteObject(c.region);
any |= d.visible;
if (d.window && presented && wasVisible != d.visible &&
(displays.size() > 1 || d.visible))
ShowWindow(d.window, d.visible ? SW_SHOWNOACTIVATE : SW_HIDE);
}
if (!any) {
if (posterPending && !playerOpen())
openPlayer();
if (!covered) {
covered = true;
if (playerOpen() && !posterPending && !parked) {
playerPause();
CancelWaitableTimer(ticks);
SetTimer(controller, Unload, 2000, nullptr);
}
}
status(L"Litely - desktop covered");
return;
}
KillTimer(controller, Unload);
bool resume = covered || parked;
covered = false;
if (!playerOpen())
openPlayer();
else if (resume && ready)
resumePlayer();
status(playingFile != source ? L"Litely - playing (30 fps on battery)" : L"Litely - playing");
}
void CALLBACK windowEvent(HWINEVENTHOOK, DWORD event, HWND w, LONG object,
LONG child, DWORD, DWORD) {
if (object != OBJID_WINDOW || child != CHILDID_SELF || !w ||
(event != EVENT_OBJECT_DESTROY && GetAncestor(w, GA_ROOT) != w) ||
paused || inspectQueued)
return;
inspectQueued = true;
PostMessage(controller, Visibility, 0, 0);
}
void updateHooks() {
for (auto h : hooks)
UnhookWinEvent(h);
hooks.clear();
if (paused)
return;
for (auto e :
{EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_MINIMIZEEND, EVENT_OBJECT_SHOW,
EVENT_OBJECT_HIDE, EVENT_OBJECT_DESTROY, EVENT_OBJECT_LOCATIONCHANGE,
EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED}) {
auto hook =
SetWinEventHook(e, e, nullptr, windowEvent, 0, 0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
if (hook)
hooks.push_back(hook);
}
}
void toggle() {
if (batteryOverride)
return;
if (applyingPause) {
if (!paused) {
paused = true;
resumeAfterPause = false;
} else
resumeAfterPause = !resumeAfterPause;
return;
}
if (source.empty())
return;
if (freezePending) {
freezePending = false;
visibility();
return;
}
if (paused) {
paused = covered = false;
if (!ready)
preparePoster(true);
if (hooks.empty())
updateHooks();
saveState();
visibility();
} else
freeze();
}
void activateSource(const fs::path &path) {
closePlayer();
leanFailedFor.clear();
directFailedFor.clear();
directRejected.clear();
source = path;
preparePoster(true);
position = 0;
paused = covered = freezePending = false;
updateHooks();
saveState();
updateBatteryCopy();
visibility();
}
fs::path importVideo(HWND owner, const wchar_t *initialDir);
// The sample wallpapers the installer adds, where choosing a video starts; empty without them.
fs::path samplesFolder() {
wchar_t exe[32768];
GetModuleFileName(nullptr, exe, 32768);
auto samples = fs::path(exe).parent_path() / L"wallpapers";
return fs::is_directory(samples) ? samples : fs::path();
}
void selectFile() {
auto samples = samplesFolder();
auto path = importVideo(controller, samples.empty() ? nullptr : samples.c_str());
if (path.empty())
return;
if (!paused && !source.empty() && posterPath(path) == posterPath(source)) {
preparePoster(true);
visibility();
return;
}
activateSource(path);
}
#include "transcode.h"
#include "library_ui.h"
bool menuOpen = false, menuDismissed = false;
DWORD menuDismissTime = 0;
// The tray menu's usage line, refreshed every second while the menu is open.
std::wstring trayUsage[3];
HMENU trayMenu;
ULONGLONG trayUsageAt = 0;
double trayUsageCPU = 0;