-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathmain.cpp
More file actions
1492 lines (1398 loc) · 65 KB
/
Copy pathmain.cpp
File metadata and controls
1492 lines (1398 loc) · 65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "audio_sample_utils.h"
#include "dpi_awareness.h"
#include "mf_encoder.h"
#include "monitor_utils.h"
#include "wasapi_loopback_capture.h"
#include "webcam_capture.h"
#include "wgc_session.h"
#include <winrt/Windows.Foundation.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cctype>
#include <cstdint>
#include <functional>
#include <iostream>
#include <memory>
#include <mutex>
#include <ratio>
#include <string>
#include <thread>
namespace {
struct CaptureConfig {
int schemaVersion = 1;
int64_t displayId = 0;
int64_t recordingId = 0;
std::string sourceType = "display";
std::string sourceId;
std::string windowHandle;
std::string outputPath;
std::string webcamOutputPath;
int fps = 60;
int width = 0;
int height = 0;
MonitorBounds bounds{};
bool hasDisplayBounds = false;
bool captureSystemAudio = false;
bool captureMic = false;
bool captureCursor = false;
bool webcamEnabled = false;
bool preferSoftwareEncoder = false;
std::string microphoneDeviceId;
std::string microphoneDeviceName;
double microphoneGain = 1.0;
std::string webcamDeviceId;
std::string webcamDeviceName;
std::string webcamDirectShowClsid;
int webcamWidth = 0;
int webcamHeight = 0;
int webcamFps = 0;
};
struct CaptureControl {
std::atomic<bool> stopRequested = false;
std::atomic<bool> paused = false;
std::mutex mutex;
std::condition_variable cv;
// Stop is signalled on its own mutex/CV pair, deliberately not on `mutex`
// (the frame-state lock in main) and not on this struct's `mutex` either.
//
// The frame lock is held across GPU work that cannot be interrupted: the
// WGC frame callback's CopyResource, and the video writer's staging-texture
// Map/readback. Waiting for a stop behind it made shutdown depend on the
// capture pipeline still being healthy -- and a `condition_variable` has to
// re-acquire its mutex before `wait` can return, so one wedged driver call
// left the main thread parked forever without emitting a single
// [stop-timing] line (issue #252). Nothing on this pair touches either
// frame lock, so a stop is always observed no matter what the GPU is doing.
//
// Threads that already hold the frame lock do call requestStop(), so the
// lock order is frame mutex -> stopMutex. Nothing ever takes them the other
// way round.
std::mutex stopMutex;
std::condition_variable stopCv;
std::chrono::steady_clock::time_point pauseStartedAt;
std::chrono::steady_clock::duration totalPausedDuration{};
// Shared T0 for every stream's timeline (screen video, audio, webcam).
// Set once, right before the video writer thread starts, so all streams
// measure elapsed time from the same real-world instant.
std::chrono::steady_clock::time_point recordingStartedAt;
int64_t pausedDurationHns() {
std::scoped_lock lock(mutex);
auto total = totalPausedDuration;
if (paused.load()) {
total += std::chrono::steady_clock::now() - pauseStartedAt;
}
return std::chrono::duration_cast<std::chrono::nanoseconds>(total).count() / 100;
}
void setPaused(bool nextPaused) {
std::scoped_lock lock(mutex);
if (nextPaused == paused.load()) {
return;
}
if (nextPaused) {
pauseStartedAt = std::chrono::steady_clock::now();
} else {
totalPausedDuration += std::chrono::steady_clock::now() - pauseStartedAt;
}
paused = nextPaused;
}
// The single way to ask for a stop. Every caller goes through here so that
// a future one cannot forget half of the handshake.
void requestStop() {
{
std::scoped_lock lock(stopMutex);
stopRequested = true;
}
// Publishing the flag under `stopMutex` before notifying is what makes
// waitForStop() immune to a wakeup landing between its predicate check
// and its enqueue on the CV.
stopCv.notify_all();
// The frame pipeline parks on `cv`; wake it too so the video writer
// notices on this pass instead of after its next 100 ms timeout.
cv.notify_all();
}
void waitForStop() {
std::unique_lock lock(stopMutex);
// Bounded even though requestStop() publishes under `stopMutex`. This
// is the one wait in the helper that must never be able to hang, and
// re-reading an atomic every 200 ms costs nothing to guarantee it.
while (!stopRequested.load()) {
stopCv.wait_for(lock, std::chrono::milliseconds(200));
}
}
};
int readEnvInt(const char* name, int fallback) {
char raw[32]{};
const DWORD length = GetEnvironmentVariableA(name, raw, static_cast<DWORD>(sizeof(raw)));
if (length == 0 || length >= sizeof(raw)) {
return fallback;
}
try {
return std::stoi(raw);
} catch (...) {
return fallback;
}
}
std::wstring utf8ToWide(const std::string& value) {
if (value.empty()) {
return {};
}
const int size = MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), nullptr, 0);
std::wstring result(static_cast<size_t>(size), L'\0');
MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), result.data(), size);
return result;
}
std::string wideToUtf8(const std::wstring& value) {
if (value.empty()) {
return {};
}
const int size = WideCharToMultiByte(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), nullptr, 0, nullptr, nullptr);
std::string result(static_cast<size_t>(size), '\0');
WideCharToMultiByte(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), result.data(), size, nullptr, nullptr);
return result;
}
std::string jsonEscape(const std::string& value) {
std::string result;
result.reserve(value.size());
for (const char c : value) {
switch (c) {
case '\\':
result += "\\\\";
break;
case '"':
result += "\\\"";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
default:
result.push_back(c);
break;
}
}
return result;
}
// HighPart:LowPart, matching how Windows tooling and QueryDisplayConfig traces
// spell a LUID, so a value from a bug report can be grepped against them.
std::string formatLuid(const LUID& luid) {
return std::to_string(luid.HighPart) + ":" + std::to_string(luid.LowPart);
}
// Reports which GPU the capture device landed on, and which one actually drives
// the monitor being captured.
//
// WgcSession creates its device with D3D11CreateDevice(nullptr, ...) -- the
// default adapter -- and nothing anywhere asks whether that is the adapter that
// owns the target display. On a single-GPU machine the question does not arise.
// On a hybrid laptop, a machine with a discrete card, or one with virtual
// display adapters, the two can differ, and then every frame WGC delivers has
// crossed an adapter boundary before the caller ever touches it. That crossing
// is driver work on both GPUs, and it is the most plausible remaining candidate
// for the stop hangs in #252 / #327, which nobody has reproduced on hardware we
// control.
//
// This does not change behaviour, and deliberately so: it turns the next bug
// report into evidence instead of another round of guessing. Failures here are
// silent -- a diagnostic that can abort a recording is worse than no diagnostic.
void reportCaptureAdapters(ID3D11Device* device, HMONITOR targetMonitor) {
if (!device) {
return;
}
Microsoft::WRL::ComPtr<IDXGIDevice> dxgiDevice;
if (FAILED(device->QueryInterface(IID_PPV_ARGS(&dxgiDevice)))) {
return;
}
Microsoft::WRL::ComPtr<IDXGIAdapter> deviceAdapter;
if (FAILED(dxgiDevice->GetAdapter(&deviceAdapter))) {
return;
}
DXGI_ADAPTER_DESC deviceDesc{};
if (FAILED(deviceAdapter->GetDesc(&deviceDesc))) {
return;
}
// The device's own adapter knows its factory, so there is no need to create
// one (and no second code path to keep alive if that ever needs a flag).
Microsoft::WRL::ComPtr<IDXGIFactory1> factory;
if (FAILED(deviceAdapter->GetParent(IID_PPV_ARGS(&factory)))) {
return;
}
std::wstring monitorAdapterName;
std::string monitorAdapterLuid;
bool monitorAdapterFound = false;
bool sameAdapter = false;
// Set when EnumOutputs says the outputs could not be looked at, rather than
// that there are none. The two are different answers and the event reports
// them differently -- see the comment on the inner loop.
bool enumerationUnavailable = false;
// The loops end on FAILED(), not on DXGI_ERROR_NOT_FOUND specifically.
// NOT_FOUND is itself a failure code, so one test covers the normal end of
// the enumeration and every other way it can stop -- and the other ways are
// what matter here: neither call fills its out-pointer when it fails, so
// testing only for NOT_FOUND left a null ComPtr to be dereferenced on the
// next line, taking down a recording from inside the one function in this
// file that promises never to.
for (UINT adapterIndex = 0;; ++adapterIndex) {
Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
if (FAILED(factory->EnumAdapters1(adapterIndex, &adapter)) || !adapter) {
break;
}
for (UINT outputIndex = 0;; ++outputIndex) {
Microsoft::WRL::ComPtr<IDXGIOutput> output;
// NOT_CURRENTLY_AVAILABLE is the exception to the rule above, and it
// has to be told apart: it is what EnumOutputs answers a process in
// session 0, and it means the outputs could not be inspected rather
// than that the adapter has none. Collapsing the two would report
// "no adapter claims this monitor" for a machine we never got to
// look at -- and that is a value this diagnostic tells its readers
// to interpret as an active virtual display. Same class of lie as
// the identical descriptions this event was just fixed for.
const HRESULT outputHr = adapter->EnumOutputs(outputIndex, &output);
if (outputHr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) {
enumerationUnavailable = true;
break;
}
if (FAILED(outputHr) || !output) {
break;
}
DXGI_OUTPUT_DESC outputDesc{};
if (FAILED(output->GetDesc(&outputDesc)) || outputDesc.Monitor != targetMonitor) {
continue;
}
DXGI_ADAPTER_DESC1 adapterDesc{};
if (FAILED(adapter->GetDesc1(&adapterDesc))) {
continue;
}
monitorAdapterName = adapterDesc.Description;
monitorAdapterLuid = formatLuid(adapterDesc.AdapterLuid);
monitorAdapterFound = true;
// Compared by LUID rather than by description, because two adapters
// of the same model report the same string.
sameAdapter = adapterDesc.AdapterLuid.LowPart == deviceDesc.AdapterLuid.LowPart &&
adapterDesc.AdapterLuid.HighPart == deviceDesc.AdapterLuid.HighPart;
}
if (monitorAdapterFound) {
break;
}
}
// The LUIDs are reported, not just the descriptions, because on the exact
// configuration this diagnostic exists to catch the two descriptions are
// IDENTICAL. An IddCx virtual display driver renders through the physical
// GPU and inherits its description string while being a separate DXGI
// adapter with its own LUID -- measured on a rented multi-adapter box:
//
// adapter[0] NVIDIA Quadro RTX 4000 LUID 0:24084 -> \\.\DISPLAY1
// adapter[1] NVIDIA Quadro RTX 4000 LUID 0:12889146 -> the IDD
//
// So a machine with the divergence would have printed two identical names
// next to sameAdapter:false, which reads as a bug in this reporting rather
// than as the finding it is. The comparison was always by LUID; only the
// output was ambiguous.
std::cout << "{\"event\":\"capture-adapter\",\"schemaVersion\":2,\"deviceAdapter\":\""
<< jsonEscape(wideToUtf8(deviceDesc.Description)) << "\",\"deviceLuid\":\""
<< formatLuid(deviceDesc.AdapterLuid) << "\",\"monitorAdapter\":";
if (monitorAdapterFound) {
std::cout << "\"" << jsonEscape(wideToUtf8(monitorAdapterName)) << "\",\"monitorLuid\":\""
<< monitorAdapterLuid << "\",\"monitorLookup\":\"ok\",\"sameAdapter\":"
<< (sameAdapter ? "true" : "false");
} else if (enumerationUnavailable) {
// Session 0: the outputs were never inspected. Reported as its own
// state so nobody reads it as a finding about the hardware.
std::cout << "null,\"monitorLuid\":null,\"monitorLookup\":\"unavailable\",\"sameAdapter\":null";
} else {
// The enumeration completed and no output claims this monitor: it is
// driven by something DXGI does not enumerate, which on the machines in
// #252 would mean a virtual display adapter. Worth seeing in its own
// right -- but only distinguishable from the case above because that
// one is now labelled.
std::cout << "null,\"monitorLuid\":null,\"monitorLookup\":\"no-output-claims-it\",\"sameAdapter\":null";
}
std::cout << "}" << std::endl;
// The full enumeration, to stderr, once at startup. Two adapters sharing a
// description is the thing a reader needs to see with their own eyes before
// they will believe sameAdapter over the names, and an adapter with no
// output at all is how an inactive virtual display presents.
for (UINT adapterIndex = 0;; ++adapterIndex) {
Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
if (FAILED(factory->EnumAdapters1(adapterIndex, &adapter)) || !adapter) {
break;
}
DXGI_ADAPTER_DESC1 desc{};
if (FAILED(adapter->GetDesc1(&desc))) {
continue;
}
std::cerr << "[adapters] " << adapterIndex << " luid=" << formatLuid(desc.AdapterLuid)
<< " \"" << wideToUtf8(desc.Description) << "\"";
UINT outputCount = 0;
bool outputsUnavailable = false;
for (UINT outputIndex = 0;; ++outputIndex) {
Microsoft::WRL::ComPtr<IDXGIOutput> output;
const HRESULT outputHr = adapter->EnumOutputs(outputIndex, &output);
if (outputHr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) {
outputsUnavailable = true;
break;
}
if (FAILED(outputHr) || !output) {
break;
}
DXGI_OUTPUT_DESC outputDesc{};
if (SUCCEEDED(output->GetDesc(&outputDesc))) {
std::cerr << (outputCount == 0 ? " outputs=" : ",") << wideToUtf8(outputDesc.DeviceName)
<< (outputDesc.Monitor == targetMonitor ? "(captured)" : "");
}
++outputCount;
}
if (outputsUnavailable) {
// Not the same as none: session 0 refuses the question entirely.
std::cerr << " outputs=unavailable";
} else if (outputCount == 0) {
std::cerr << " outputs=none";
}
std::cerr << std::endl;
}
}
bool hasVisibleBgraContent(const std::vector<BYTE>& frame) {
if (frame.size() < 4) {
return false;
}
uint64_t lumaTotal = 0;
BYTE maxLuma = 0;
const size_t pixelCount = frame.size() / 4;
const size_t step = std::max<size_t>(1, pixelCount / 4096);
size_t sampledPixels = 0;
for (size_t pixel = 0; pixel < pixelCount; pixel += step) {
const size_t offset = pixel * 4;
const BYTE b = frame[offset + 0];
const BYTE g = frame[offset + 1];
const BYTE r = frame[offset + 2];
const BYTE luma = static_cast<BYTE>((static_cast<uint16_t>(r) * 54 + static_cast<uint16_t>(g) * 183 + static_cast<uint16_t>(b) * 19) >> 8);
lumaTotal += luma;
maxLuma = std::max(maxLuma, luma);
sampledPixels += 1;
}
const uint64_t averageLuma = sampledPixels > 0 ? lumaTotal / sampledPixels : 0;
return maxLuma > 24 || averageLuma > 4;
}
bool findBool(const std::string& json, const std::string& key, bool fallback) {
auto pos = json.find("\"" + key + "\"");
if (pos == std::string::npos) {
return fallback;
}
pos = json.find(':', pos);
if (pos == std::string::npos) {
return fallback;
}
pos += 1;
while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos]))) {
pos += 1;
}
if (json.compare(pos, 4, "true") == 0) {
return true;
}
if (json.compare(pos, 5, "false") == 0) {
return false;
}
return fallback;
}
int64_t findInt64(const std::string& json, const std::string& key, int64_t fallback) {
auto pos = json.find("\"" + key + "\"");
if (pos == std::string::npos) {
return fallback;
}
pos = json.find(':', pos);
if (pos == std::string::npos) {
return fallback;
}
pos += 1;
while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos]))) {
pos += 1;
}
try {
return std::stoll(json.substr(pos));
} catch (...) {
return fallback;
}
}
int findInt(const std::string& json, const std::string& key, int fallback) {
return static_cast<int>(findInt64(json, key, fallback));
}
double findDouble(const std::string& json, const std::string& key, double fallback) {
auto pos = json.find("\"" + key + "\"");
if (pos == std::string::npos) {
return fallback;
}
pos = json.find(':', pos);
if (pos == std::string::npos) {
return fallback;
}
pos += 1;
while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos]))) {
pos += 1;
}
try {
return std::stod(json.substr(pos));
} catch (...) {
return fallback;
}
}
std::string findString(const std::string& json, const std::string& key) {
auto pos = json.find("\"" + key + "\"");
if (pos == std::string::npos) {
return {};
}
pos = json.find(':', pos);
if (pos == std::string::npos) {
return {};
}
pos += 1;
while (pos < json.size() && std::isspace(static_cast<unsigned char>(json[pos]))) {
pos += 1;
}
if (pos >= json.size() || json[pos] != '"') {
return {};
}
pos += 1;
std::string result;
while (pos < json.size()) {
const char c = json[pos++];
if (c == '"') {
break;
}
if (c == '\\' && pos < json.size()) {
const char escaped = json[pos++];
switch (escaped) {
case '\\':
case '"':
case '/':
result.push_back(escaped);
break;
case 'n':
result.push_back('\n');
break;
case 'r':
result.push_back('\r');
break;
case 't':
result.push_back('\t');
break;
default:
result.push_back(escaped);
break;
}
continue;
}
result.push_back(c);
}
return result;
}
std::string parseWindowHandleFromSourceId(const std::string& sourceId) {
constexpr char prefix[] = "window:";
if (sourceId.rfind(prefix, 0) != 0) {
return {};
}
const size_t start = sizeof(prefix) - 1;
const size_t end = sourceId.find(':', start);
const std::string handle = sourceId.substr(start, end == std::string::npos ? std::string::npos : end - start);
return handle.empty() ? std::string{} : handle;
}
HWND parseWindowHandle(const std::string& value) {
if (value.empty()) {
return nullptr;
}
try {
size_t parsed = 0;
const int base = value.rfind("0x", 0) == 0 || value.rfind("0X", 0) == 0 ? 16 : 10;
const uint64_t handleValue = std::stoull(value, &parsed, base);
if (parsed != value.size() || handleValue == 0) {
return nullptr;
}
return reinterpret_cast<HWND>(static_cast<uintptr_t>(handleValue));
} catch (...) {
return nullptr;
}
}
bool parseConfig(const std::string& json, CaptureConfig& config) {
config.schemaVersion = findInt(json, "schemaVersion", 1);
config.outputPath = findString(json, "screenPath");
if (config.outputPath.empty()) {
config.outputPath = findString(json, "outputPath");
}
if (config.outputPath.empty()) {
return false;
}
config.recordingId = findInt64(json, "recordingId", 0);
config.sourceType = findString(json, "sourceType");
if (config.sourceType.empty()) {
config.sourceType = "display";
}
config.sourceId = findString(json, "sourceId");
config.windowHandle = findString(json, "windowHandle");
if (config.windowHandle.empty()) {
config.windowHandle = parseWindowHandleFromSourceId(config.sourceId);
}
config.displayId = findInt64(json, "displayId", 0);
config.fps = std::clamp(findInt(json, "fps", 60), 1, 120);
config.width = findInt(json, "videoWidth", findInt(json, "width", 0));
config.height = findInt(json, "videoHeight", findInt(json, "height", 0));
config.bounds.x = findInt(json, "displayX", 0);
config.bounds.y = findInt(json, "displayY", 0);
config.bounds.width = findInt(json, "displayW", 0);
config.bounds.height = findInt(json, "displayH", 0);
config.hasDisplayBounds = findBool(json, "hasDisplayBounds", false);
config.captureSystemAudio = findBool(json, "captureSystemAudio", false);
config.captureMic = findBool(json, "captureMic", false);
config.captureCursor = findBool(json, "captureCursor", false);
config.webcamEnabled = findBool(json, "webcamEnabled", false);
config.preferSoftwareEncoder = findBool(json, "preferSoftwareEncoder", false);
config.microphoneDeviceId = findString(json, "microphoneDeviceId");
config.microphoneDeviceName = findString(json, "microphoneDeviceName");
config.microphoneGain = findDouble(json, "microphoneGain", 1.0);
config.webcamDeviceId = findString(json, "webcamDeviceId");
config.webcamDeviceName = findString(json, "webcamDeviceName");
config.webcamDirectShowClsid = findString(json, "webcamDirectShowClsid");
config.webcamOutputPath = findString(json, "webcamPath");
config.webcamWidth = findInt(json, "webcamWidth", 0);
config.webcamHeight = findInt(json, "webcamHeight", 0);
config.webcamFps = findInt(json, "webcamFps", 0);
return true;
}
void readCaptureCommands(CaptureControl& control, const std::function<void(bool)>& onPauseChanged) {
std::string line;
while (std::getline(std::cin, line)) {
// The comparisons below are exact, so a stray carriage return would
// drop the command in total silence -- the one command this helper
// must never fail to act on.
while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) {
line.pop_back();
}
if (line == "stop" || line == "q" || line == "quit") {
// Acknowledged before anything else runs. Issue #252 was reported
// with no way to tell "the helper never saw the stop" apart from
// "the helper saw it and then wedged"; this line settles that in
// every future report.
std::cerr << "[stop-timing] step=command-received elapsed_ms=0" << std::endl;
control.requestStop();
return;
}
if (line == "pause") {
control.setPaused(true);
onPauseChanged(true);
std::cout << "{\"event\":\"recording-paused\",\"schemaVersion\":2}" << std::endl;
control.cv.notify_all();
continue;
}
if (line == "resume") {
control.setPaused(false);
onPauseChanged(false);
std::cout << "{\"event\":\"recording-resumed\",\"schemaVersion\":2}" << std::endl;
control.cv.notify_all();
continue;
}
}
// stdin closed: the parent is gone or ended the channel, which is also a
// stop. Electron relies on this as a backstop for a dropped `stop` write.
std::cerr << "[stop-timing] step=stdin-eof elapsed_ms=0" << std::endl;
control.requestStop();
}
} // namespace
int main(int argc, char* argv[]) {
// Before anything reads a coordinate. `findMonitorForCapture` matches the
// config's display bounds against the rects `EnumDisplayMonitors` reports,
// and the caller sends those bounds in physical pixels; a DPI-unaware
// process would compare them against virtualized ones and silently record
// the wrong screen (getopenscreen/openscreen#346). Refusing to start is the
// honest outcome -- a recording of the wrong monitor is discovered far too
// late to be worth salvaging.
if (!enablePerMonitorV2DpiAwareness()) {
std::cerr << "ERROR: Could not enable per-monitor-v2 DPI awareness" << std::endl;
return 1;
}
if (argc < 2) {
std::cerr << "ERROR: Missing JSON config argument" << std::endl;
return 1;
}
winrt::init_apartment(winrt::apartment_type::multi_threaded);
CaptureConfig config;
if (!parseConfig(argv[1], config)) {
std::cerr << "ERROR: Failed to parse config JSON" << std::endl;
return 1;
}
char injectDefaultSinkWriterFailure[2]{};
const DWORD injectDefaultSinkWriterFailureLength = GetEnvironmentVariableA(
"OPENSCREEN_WGC_TEST_INJECT_DEFAULT_SINK_WRITER_FAILURE_ONCE",
injectDefaultSinkWriterFailure,
static_cast<DWORD>(sizeof(injectDefaultSinkWriterFailure)));
const bool injectDefaultSinkWriterFailureOnce =
injectDefaultSinkWriterFailureLength == 1 &&
injectDefaultSinkWriterFailure[0] == '1';
// Test-only: stall the video writer inside the frame lock the way a wedged
// GPU readback does. Issue #252 only reproduced on one multi-adapter machine
// with virtual display drivers; this makes the same failure reachable on
// ordinary hardware, so the stop path can be regression-tested at all.
const int testStallReadbackMs =
std::max(0, readEnvInt("OPENSCREEN_WGC_TEST_STALL_READBACK_MS", 0));
std::cout << "{\"event\":\"ready\",\"schemaVersion\":2}" << std::endl;
WgcSession session;
HMONITOR capturedMonitor = nullptr;
if (config.sourceType == "display") {
HMONITOR monitor = findMonitorForCapture(
config.displayId,
config.hasDisplayBounds ? &config.bounds : nullptr);
if (!monitor) {
std::cerr << "ERROR: Could not resolve monitor" << std::endl;
return 1;
}
capturedMonitor = monitor;
if (!session.initialize(monitor, config.fps, config.captureCursor)) {
std::cerr << "ERROR: Failed to initialize WGC display session" << std::endl;
return 1;
}
} else if (config.sourceType == "window") {
HWND window = parseWindowHandle(config.windowHandle);
if (!window || !IsWindow(window)) {
std::cerr << "ERROR: Native window capture requires a valid HWND" << std::endl;
return 1;
}
// A window is captured by whichever display it currently sits on, which
// is the adapter that matters for the same reason a monitor's does.
capturedMonitor = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST);
if (!session.initialize(window, config.fps, config.captureCursor)) {
std::cerr << "ERROR: Failed to initialize WGC window session" << std::endl;
return 1;
}
} else {
std::cerr << "ERROR: Unsupported native capture source type: " << config.sourceType << std::endl;
return 1;
}
reportCaptureAdapters(session.device(), capturedMonitor);
// WGC owns the captured texture size. Encoding must use that exact size
// until a dedicated GPU scaling pass is introduced; CopyResource requires
// matching resource dimensions.
int width = session.captureWidth();
int height = session.captureHeight();
width = (std::max(2, width) / 2) * 2;
height = (std::max(2, height) / 2) * 2;
const int pixels = width * height;
const int bitrate = pixels >= 3840 * 2160 ? 45'000'000 : pixels >= 2560 * 1440 ? 28'000'000 : 18'000'000;
WebcamCapture webcamCapture;
bool webcamActive = false;
bool writeSeparateWebcam = false;
if (config.webcamEnabled) {
if (!webcamCapture.initialize(
utf8ToWide(config.webcamDeviceId),
utf8ToWide(config.webcamDeviceName),
utf8ToWide(config.webcamDirectShowClsid),
config.webcamWidth,
config.webcamHeight,
config.webcamFps > 0 ? config.webcamFps : config.fps)) {
// Non-fatal: a screen+audio recording the user can still use is far
// better than losing the whole recording because one camera device
// didn't match. Report it so the renderer can inform the user (and,
// historically, fall back to a browser-recorded webcam sidecar), but
// let capture continue without a native webcam track.
std::cerr << "WARNING: Failed to initialize native webcam capture; continuing without webcam"
<< std::endl;
std::cout << "{\"event\":\"warning\",\"code\":\"webcam-unavailable\",\"message\":"
"\"Failed to initialize native webcam capture\"}"
<< std::endl;
config.webcamEnabled = false;
} else {
std::cout << "{\"event\":\"webcam-format\",\"schemaVersion\":2,\"width\":" << webcamCapture.width()
<< ",\"height\":" << webcamCapture.height()
<< ",\"fps\":" << webcamCapture.fps()
<< ",\"deviceName\":\"" << jsonEscape(wideToUtf8(webcamCapture.selectedDeviceName()))
<< "\"}" << std::endl;
writeSeparateWebcam = !config.webcamOutputPath.empty();
}
}
WasapiLoopbackCapture loopbackCapture;
WasapiLoopbackCapture microphoneCapture;
const AudioInputFormat* audioFormat = nullptr;
AudioInputFormat encoderAudioFormat{};
AudioInputFormat systemAudioFormat{};
AudioInputFormat microphoneAudioFormat{};
if (config.captureSystemAudio) {
if (!loopbackCapture.initializeSystemLoopback()) {
std::cerr << "ERROR: Failed to initialize WASAPI loopback capture" << std::endl;
return 1;
}
systemAudioFormat = loopbackCapture.inputFormat();
audioFormat = &loopbackCapture.inputFormat();
}
if (config.captureMic) {
if (!microphoneCapture.initializeMicrophone(
utf8ToWide(config.microphoneDeviceId),
utf8ToWide(config.microphoneDeviceName))) {
std::cerr << "ERROR: Failed to initialize WASAPI microphone capture" << std::endl;
return 1;
}
microphoneAudioFormat = microphoneCapture.inputFormat();
if (!audioFormat) {
audioFormat = µphoneCapture.inputFormat();
}
}
if (audioFormat) {
std::cout << "{\"event\":\"audio-format\",\"schemaVersion\":2,\"sampleRate\":" << audioFormat->sampleRate
<< ",\"channels\":" << audioFormat->channels
<< ",\"bitsPerSample\":" << audioFormat->bitsPerSample
<< ",\"system\":" << (config.captureSystemAudio ? "true" : "false")
<< ",\"microphone\":" << (config.captureMic ? "true" : "false");
if (config.captureMic) {
std::cout << ",\"microphoneDeviceName\":\""
<< jsonEscape(wideToUtf8(microphoneCapture.selectedDeviceName())) << "\"";
}
std::cout << "}" << std::endl;
encoderAudioFormat = makeAacCompatibleAudioFormat(*audioFormat);
std::cout << "{\"event\":\"encoder-audio-format\",\"schemaVersion\":2,\"sampleRate\":"
<< encoderAudioFormat.sampleRate
<< ",\"channels\":" << encoderAudioFormat.channels
<< ",\"bitsPerSample\":" << encoderAudioFormat.bitsPerSample
<< "}" << std::endl;
}
MFEncoderOptions encoderOptions{};
encoderOptions.preferSoftwareEncoder = config.preferSoftwareEncoder;
encoderOptions.injectDefaultSinkWriterFailureOnce = injectDefaultSinkWriterFailureOnce;
// OFF by default. The GPU path exists to dodge a Map() that wedges inside
// the display driver on the machine in #252, and it demonstrably fixed
// display and window capture there. It also broke recording outright for
// the reporter in #336, who had working video before it. Its fallbacks
// cover every check made during initialize(); nothing covers a failure that
// only appears once frames are flowing, which is what #336 is.
//
// So it is opt-in until a failure mid-encode degrades to the CPU path
// instead of ending the recording, or until someone confirms it closes
// #252. Neither has happened, and defaulting it on means every user carries
// the risk so that the few who reproduce #252 might not have to.
//
// Set OPENSCREEN_WGC_ENABLE_DXGI_INPUT=1 to turn it on -- that is what the
// people in #252 and #327 should be given to test with.
//
// The other two conditions are unchanged and still required: software
// encoding and inline webcam PiP both need the frame in system memory,
// which the DXGI path does not produce. config.webcamEnabled, not
// webcamActive -- the latter is only set once webcam capture has started,
// well after this.
encoderOptions.useDxgiInput =
readEnvInt("OPENSCREEN_WGC_ENABLE_DXGI_INPUT", 0) == 1 &&
!config.preferSoftwareEncoder &&
(!config.webcamEnabled || writeSeparateWebcam);
MFEncoder encoder;
if (!encoder.initialize(
utf8ToWide(config.outputPath),
width,
height,
config.fps,
bitrate,
session.device(),
session.context(),
audioFormat ? &encoderAudioFormat : nullptr,
encoderOptions)) {
std::cerr << "ERROR: Failed to initialize Media Foundation encoder" << std::endl;
return 1;
}
// `videoInput` reports what the encoder settled on, not what was asked for:
// it silently degrades to the CPU readback on any machine the GPU path does
// not fit, and a bug report that cannot tell the two apart is a bug report
// about the wrong path.
const bool usesDxgiInput = encoder.usesDxgiInput();
std::cout << "{\"event\":\"encoder-selection\",\"schemaVersion\":2,\"video\":\""
<< encoder.videoEncoderSelection()
<< "\",\"videoInput\":\"" << (usesDxgiInput ? "dxgi-nv12" : "cpu-rgb32")
// Reported for the same reason `videoInput` is: the encoder falls
// back to the plain container rather than failing a recording, and
// "was this file supposed to survive a kill?" is unanswerable from
// a bug report that cannot tell the two apart.
<< "\",\"container\":\"" << encoder.containerFormat()
<< "\",\"preferSoftwareEncoder\":"
<< (config.preferSoftwareEncoder ? "true" : "false")
<< "}" << std::endl;
MFEncoder webcamEncoder;
if (writeSeparateWebcam) {
MFEncoderOptions webcamEncoderOptions = encoderOptions;
webcamEncoderOptions.injectDefaultSinkWriterFailureOnce = false;
webcamEncoderOptions.useDxgiInput = false;
const int webcamPixels = std::max(1, webcamCapture.width()) * std::max(1, webcamCapture.height());
const int webcamBitrate = webcamPixels >= 1280 * 720 ? 8'000'000 : 4'000'000;
if (!webcamEncoder.initialize(
utf8ToWide(config.webcamOutputPath),
webcamCapture.width(),
webcamCapture.height(),
webcamCapture.fps(),
webcamBitrate,
session.device(),
session.context(),
nullptr,
webcamEncoderOptions)) {
std::cerr << "ERROR: Failed to initialize native webcam encoder" << std::endl;
return 1;
}
}
std::mutex mutex;
CaptureControl control;
std::atomic<bool> firstFrameWritten = false;
std::atomic<bool> encodeFailed = false;
// Frames the GPU bridge was too busy to take. Reported at stop rather than
// per frame: a handful over a recording is normal contention, a stream of
// them is the next bug report, and neither is worth a log line each.
std::atomic<uint64_t> contendedFrames = 0;
Microsoft::WRL::ComPtr<ID3D11Texture2D> latestFrameTexture;
int64_t latestFrameTimestampHns = 0;
int64_t firstFrameTimestampHns = -1;
std::vector<BYTE> latestWebcamFrame;
int latestWebcamWidth = 0;
int latestWebcamHeight = 0;
uint64_t latestWebcamSequence = 0;
bool hasVisibleWebcamFrame = false;
session.setFrameCallback([&](ID3D11Texture2D* texture, int64_t timestampHns) {
if (control.stopRequested || control.paused) {
return;
}
std::scoped_lock lock(mutex);
if (!latestFrameTexture) {
D3D11_TEXTURE2D_DESC desc{};
texture->GetDesc(&desc);
desc.BindFlags = 0;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
if (FAILED(session.device()->CreateTexture2D(&desc, nullptr, &latestFrameTexture))) {
encodeFailed = true;
control.requestStop();
return;
}
}
session.context()->CopyResource(latestFrameTexture.Get(), texture);
latestFrameTimestampHns = timestampHns;
if (!firstFrameWritten.exchange(true)) {
control.cv.notify_all();
}
});
auto writeVideoFrames = [&]() {
const auto frameDuration = std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::duration<double>(1.0 / config.fps));
uint64_t frameIndex = 0;
int64_t lastEncodedVideoTimestampHns = -1;
int64_t lastWebcamTimestampHns = -1;
// Media Foundation's H.264 encoder MFT does not honor irregular input
// sample times for a VFR source: it numbers output samples
// sequentially at its configured nominal frame rate regardless of the
// SampleTime we attach (confirmed empirically -- varying, correctly
// increasing input timestamps still produced perfectly even output
// spacing). Since we cannot make the encoder respect real capture
// time, we instead make the encoder's assumption true: feed the
// webcam encoder on a real-time-paced cadence (duplicating the
// latest available camera frame when the camera hasn't produced a
// newer one yet), so "sample N is at N/fps" is actually correct.
int64_t nextWebcamWriteDueHns = 0;
const int64_t nominalWebcamIntervalHns =
static_cast<int64_t>(10'000'000ULL / std::max(1, webcamCapture.fps()));
auto nextFrameDue = std::chrono::steady_clock::now();
while (!control.stopRequested && !encodeFailed) {
Microsoft::WRL::ComPtr<IMFSample> videoSample;
Microsoft::WRL::ComPtr<IMFSample> webcamSample;
bool hasVideoSample = false;
bool hasWebcamSample = false;
{
std::unique_lock lock(mutex);
control.cv.wait_for(lock, std::chrono::milliseconds(100), [&] {
return control.stopRequested.load() ||
encodeFailed.load() ||
(!control.paused.load() && latestFrameTexture);
});
if (control.stopRequested || encodeFailed) {
break;
}
if (webcamActive) {
WebcamFrameSnapshot candidateWebcamFrame;
if (webcamCapture.copyLatestFrame(candidateWebcamFrame) &&
candidateWebcamFrame.sequence != latestWebcamSequence &&
hasVisibleBgraContent(candidateWebcamFrame.data)) {
latestWebcamFrame = std::move(candidateWebcamFrame.data);
latestWebcamWidth = candidateWebcamFrame.width;
latestWebcamHeight = candidateWebcamFrame.height;
latestWebcamSequence = candidateWebcamFrame.sequence;
hasVisibleWebcamFrame = true;
}
}
const BgraFrameView webcamFrame{
hasVisibleWebcamFrame && !latestWebcamFrame.empty() ? latestWebcamFrame.data() : nullptr,
latestWebcamWidth,
latestWebcamHeight,
};
const int64_t syntheticTimestampHns =
static_cast<int64_t>((frameIndex * 10'000'000ULL) / config.fps);
const int64_t sourceTimestampHns =
latestFrameTimestampHns > 0 ? latestFrameTimestampHns : syntheticTimestampHns;
if (firstFrameTimestampHns < 0) {
firstFrameTimestampHns = sourceTimestampHns;
}
int64_t frameTimestampHns =
std::max<int64_t>(
0,
sourceTimestampHns - firstFrameTimestampHns - control.pausedDurationHns());
if (lastEncodedVideoTimestampHns >= 0 &&
frameTimestampHns <= lastEncodedVideoTimestampHns) {