forked from facebookarchive/360-Capture-SDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFBCaptureSystem.cpp
1742 lines (1486 loc) · 68.5 KB
/
FBCaptureSystem.cpp
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
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "FBCaptureSystem.h"
#include "Camera/CameraDevices.h"
#include "Camera/CameraDeviceManager.h"
#include "Camera/CameraReader.h"
#include "EncoderMain.h"
#include "Microphone/MicDevices.h"
#include "Common/Log.h"
#include "Graphics/GraphicsDeviceCaptureD3D11.h"
#include <mfapi.h>
#include <mfreadwrite.h>
// Graphics device identifiers in Unity
enum UnityGfxRenderer {
kUnityGfxRendererOpenGL = 0, // Legacy OpenGL
kUnityGfxRendererD3D9 = 1, // Direct3D 9
kUnityGfxRendererD3D11 = 2, // Direct3D 11
kUnityGfxRendererGCM = 3, // PlayStation 3
kUnityGfxRendererNull = 4, // "null" device (used in batch mode)
kUnityGfxRendererXenon = 6, // Xbox 360
kUnityGfxRendererOpenGLES20 = 8, // OpenGL ES 2.0
kUnityGfxRendererOpenGLES30 = 11, // OpenGL ES 3.x
kUnityGfxRendererGXM = 12, // PlayStation Vita
kUnityGfxRendererPS4 = 13, // PlayStation 4
kUnityGfxRendererXboxOne = 14, // Xbox One
kUnityGfxRendererMetal = 16, // iOS Metal
kUnityGfxRendererOpenGLCore = 17, // OpenGL core
kUnityGfxRendererD3D12 = 18, // Direct3D 12
kGfxRendererCount
};
// Event types for UnitySetGraphicsDevice
enum UnityGfxDeviceEventType {
kUnityGfxDeviceEventInitialize = 0,
kUnityGfxDeviceEventShutdown = 1,
kUnityGfxDeviceEventBeforeReset = 2,
kUnityGfxDeviceEventAfterReset = 3,
};
namespace FBCapture {
namespace Common {
FBCAPTURE_STATUS FBCaptureSystem::initialize() {
if (pClientDevice_ == nullptr) {
DEBUG_ERROR(
"DirectX device hasn't set up. Please set up DirectX 11 device with fbc_setGraphicsDeviceD3D11 function.");
return FBCAPTURE_STATUS_DEVICE_CREATING_FAILED;
}
HRESULT hr = S_OK;
if (isInitialized()) {
return FBCAPTURE_STATUS_OK;
}
hr = MFStartup(MF_VERSION);
if (FAILED(hr)) {
DEBUG_ERROR_VAR(
"Failed to MFStartup in fb capture system. [Error code] ", to_string(hr));
return FBCAPTURE_STATUS_SYSTEM_INITIALIZE_FAILED;
}
pEncoder_.reset(new EncoderMain());
const int nvidiaVenderID = 4318; // NVIDIA Vendor ID: 0x10DE
const int amdVenderID1 = 4098; // AMD Vendor ID: 0x1002
const int amdVenderID2 = 4130; // AMD Vendor ID: 0x1022
// Get adater where DX device was created by client
ScopedCOMPtr<IDXGIDevice1> dxgidevice = {};
ScopedCOMPtr<IDXGIAdapter> displayAdapter = {};
ScopedCOMPtr<IDXGIFactory1> factory = {};
DXGI_ADAPTER_DESC adapterDescription = {};
hr = pClientDevice_->QueryInterface(IID_PPV_ARGS(&dxgidevice));
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR(
"Failed to get DXGI device. [Error code] ", hr);
return FBCAPTURE_STATUS_DXGI_CREATING_FAILED;
}
hr = dxgidevice->GetAdapter(&displayAdapter);
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR(
"Failed to get DXGI adapter. [Error code] ", hr);
return FBCAPTURE_STATUS_DXGI_CREATING_FAILED;
}
if (displayAdapter != nullptr) {
displayAdapter->GetDesc(&adapterDescription);
wstring wDeviceName(adapterDescription.Description);
string sDeviceName(wDeviceName.begin(), wDeviceName.end());
DEBUG_LOG_VAR("Default Graphics Card Info: ", sDeviceName);
if (adapterDescription.VendorId == nvidiaVenderID) {
pEncoder_->setGPUManufacturer(GRAPHICS_CARD::NVIDIA);
}
else if (adapterDescription.VendorId == amdVenderID1 || adapterDescription.VendorId == amdVenderID2) {
pEncoder_->setGPUManufacturer(GRAPHICS_CARD::AMD);
}
}
// We want to enumerate more GPUs if DX device created by client is on unsupported GPU
if (pEncoder_->checkGPUManufacturer() == GRAPHICS_CARD::UNSUPPORTED_DEVICE) {
if (FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&factory))) {
DEBUG_ERROR("Failed to create DXGI factory object");
return FBCAPTURE_STATUS_DXGI_CREATING_FAILED;
}
for (UINT i = 0; factory->EnumAdapters(i, &displayAdapter) != DXGI_ERROR_NOT_FOUND; ++i) {
displayAdapter->GetDesc(&adapterDescription);
// Getting graphics card information in use
wstring wDeviceName(adapterDescription.Description);
string sDeviceName(wDeviceName.begin(), wDeviceName.end());
DEBUG_LOG_VAR("Graphics Card Info: ", sDeviceName);
if (adapterDescription.VendorId == nvidiaVenderID) {
pEncoder_->setGPUManufacturer(GRAPHICS_CARD::NVIDIA);
break;
} else if (adapterDescription.VendorId == amdVenderID1 || adapterDescription.VendorId == amdVenderID2) {
pEncoder_->setGPUManufacturer(GRAPHICS_CARD::AMD);
break;
}
}
}
D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_11_0 };
DWORD createDeviceFlags = 0;
//Commenting this line by default since only few test cases require this flag
//#ifdef DEBUG
// createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
//#endif
hr = D3D11CreateDevice(displayAdapter, displayAdapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE, nullptr,
createDeviceFlags, levels, ARRAYSIZE(levels),
D3D11_SDK_VERSION, &pDevice_, nullptr, &pContext_);
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR(
"Failed to D3D11CreateDevice in fb capture system. [Error code] ",
hr);
return FBCAPTURE_STATUS_SYSTEM_INITIALIZE_FAILED;
}
// Yes, this is D10 Multithread versus D11. It's compatible with D11. Using this as D11Multithread requires an extra Dll:
// D3d11_4.dll
ScopedCOMPtr<ID3D10Multithread> pMultithread;
hr = pDevice_->QueryInterface(__uuidof(ID3D10Multithread),
(void **)&pMultithread);
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR("Failed to Query ID3D10Multithread Interface in fb capture system. [Error code] ",
hr);
return FBCAPTURE_STATUS_SYSTEM_INITIALIZE_FAILED;
}
hr = pMultithread->SetMultithreadProtected(TRUE);
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR("Failed to SetMultithreadProtected fb capture system. [Error code] ",
hr);
return FBCAPTURE_STATUS_SYSTEM_INITIALIZE_FAILED;
}
pEncoder_->setGraphicsDeviceD3D11(pDevice_);
initialized_ = true;
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::getCaptureCapability() {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
// Check OS version capbility
status = checkOSCapability();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
status = initializeSystemIfNeeded();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
status = pEncoder_->initEncoderComponents();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
// Check graphics card capability
status = pEncoder_->checkGraphicsCardCapability();
if (status != FBCAPTURE_STATUS_OK) {
pEncoder_->releaseEncodeResources();
DEBUG_ERROR_VAR("Unsupported graphics card. Software encoder will be enabled.", to_string(status));
pEncoder_->setSoftwareEncoder();
return FBCAPTURE_STATUS_SW_ENCODER_ENABLED;
}
// Check graphics driver version capability
status = pEncoder_->initSessionANDcheckDriverCapability();
if (status != FBCAPTURE_STATUS_OK) {
pEncoder_->releaseEncodeResources();
DEBUG_ERROR_VAR("Failed on initializing GPU encoder. Software encoder will be enabled.", to_string(status));
pEncoder_->setSoftwareEncoder();
return FBCAPTURE_STATUS_SW_ENCODER_ENABLED;
}
// Need dummy encoding session to clearly clean up nvidia encoder activated to check gpu driver capability
status = pEncoder_->dummyEncodingSession();
if (status != FBCAPTURE_STATUS_OK) {
DEBUG_ERROR_VAR("Failed on GPU encoding of dummy encoding session. Software encoder will be enabled.", to_string(status));
pEncoder_->setSoftwareEncoder();
return FBCAPTURE_STATUS_SW_ENCODER_ENABLED;
}
DEBUG_LOG("Passed capture capability tests. Ready to start encoding");
return status;
}
FBCAPTURE_STATUS FBCaptureSystem::checkOSCapability() {
if (!IsWindows7SP1OrGreater()) {
DEBUG_ERROR("We're supporting Windows 7 SP1 or greater only");
return FBCAPTURE_STATUS_UNSUPPORTED_OS_VERSION;
}
/// Commenting out codes checking os bit for now
/// But since we haven't tested 32bit enough, we might need to get back them once we see issues on 32 bit
/*
BOOL is64bit = false;
fnIsWow64Process
= (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")),
"IsWow64Process");
if (nullptr != fnIsWow64Process) {
if (!fnIsWow64Process(GetCurrentProcess(), &is64bit)) {
// TODO ADD handle error
}
}
if (is64bit == false) {
DEBUG_ERROR("We're supporting 64bit OS only");
return FBCAPTURE_STATUS_UNSUPPORTED_OS_PROCESSOR;
}
*/
return FBCAPTURE_STATUS_OK;
}
bool FBCaptureSystem::isCameraDevicesInitialized() {
return pCameraDevices_ && pCameraDeviceManager_ &&
pCameraDeviceManager_->isInitialized();
}
FBCAPTURE_STATUS FBCaptureSystem::initializeCameraDevices() {
pCameraDevices_.reset(new CameraDevices());
pCameraDeviceManager_.reset(new CameraDeviceManager());
HRESULT hr = pCameraDeviceManager_->initialize();
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR("Failed to initialize CameraDeviceManager. [Error code] ", hr);
return FBCAPTURE_STATUS_CAMERA_ENUMERATION_FAILED;
}
return FBCAPTURE_STATUS_OK;
}
bool FBCaptureSystem::isMicDevicesInitialized() {
return pMicDevices_ != nullptr;
}
FBCAPTURE_STATUS FBCaptureSystem::initializeMicDevices() {
pMicDevices_.reset(new MicDevices());
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::setGraphicsDeviceD3D11(ID3D11Device* device) {
if (pClientDevice_ == nullptr) {
pClientDevice_ = device;
}
pGraphicsDeviceCapture_.reset(new GraphicsDeviceCaptureD3D11(device));
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::setLiveCaptureSettings(int width, int height, int frameRate, int bitRate,
float flushCycleStart, float flushCycleAfter,
const TCHAR* streamUrl, bool is360, bool verticalFlip, bool horizontalFlip,
PROJECTIONTYPE projectionType, STEREO_MODE stereoMode) {
pLiveCaptureSettings_.reset(new LiveCaptureSettings);
pLiveCaptureSettings_->width_ = width;
pLiveCaptureSettings_->height_ = height;
pLiveCaptureSettings_->frameRate_ = frameRate;
pLiveCaptureSettings_->encodeCycle_ = 1.0f / frameRate;
pLiveCaptureSettings_->videoBitRate_ = bitRate;
pLiveCaptureSettings_->flushCycleStart_ = flushCycleStart;
pLiveCaptureSettings_->flushCycleAfter_ = flushCycleAfter;
pLiveCaptureSettings_->streamUrl_ = std::wstring(streamUrl);
pLiveCaptureSettings_->is360_ = is360;
pLiveCaptureSettings_->verticalFlip_ = verticalFlip;
pLiveCaptureSettings_->horizontalFlip_ = horizontalFlip;
pLiveCaptureSettings_->flushCycle_ = pLiveCaptureSettings_->flushCycleStart_;
pLiveCaptureSettings_->projectionType_ = projectionType;
pLiveCaptureSettings_->stereoMode_ = stereoMode;
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::setVodCaptureSettings(int width, int height, int frameRate, int bitRate,
const TCHAR* fullSavePath, bool is360, bool verticalFlip, bool horizontalFlip,
PROJECTIONTYPE projectionType, STEREO_MODE stereoMode) {
pVodCaptureSettings_.reset(new VodCaptureSettings);
pVodCaptureSettings_->width_ = width;
pVodCaptureSettings_->height_ = height;
pVodCaptureSettings_->frameRate_ = frameRate;
pVodCaptureSettings_->encodeCycle_ = 1.0f / frameRate;
pVodCaptureSettings_->videoBitRate_ = bitRate;
pVodCaptureSettings_->fullSavePath_ = std::wstring(fullSavePath);
pVodCaptureSettings_->is360_ = is360;
pVodCaptureSettings_->verticalFlip_ = verticalFlip;
pVodCaptureSettings_->horizontalFlip_ = horizontalFlip;
pVodCaptureSettings_->projectionType_ = projectionType;
pVodCaptureSettings_->stereoMode_ = stereoMode;
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::setPreviewCaptureSettings(int width, int height, int frameRate, bool is360,
bool verticalFlip, bool horizontalFlip) {
pPreviewCaptureSettings_.reset(new PreviewCaptureSettings);
pPreviewCaptureSettings_->width_ = width;
pPreviewCaptureSettings_->height_ = height;
pPreviewCaptureSettings_->frameRate_ = frameRate;
pPreviewCaptureSettings_->encodeCycle_ = 1.0f / frameRate;
pPreviewCaptureSettings_->is360_ = is360;
pPreviewCaptureSettings_->verticalFlip_ = verticalFlip;
pPreviewCaptureSettings_->horizontalFlip_ = horizontalFlip;
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::setScreenshotSettings(int width, int height, const TCHAR* fullsavePath, bool is360,
bool verticalFlip, bool horizontalFlip) {
pScreenshotSettings_.reset(new ScreenshotSettings);
pScreenshotSettings_->width_ = width;
pScreenshotSettings_->height_ = height;
pScreenshotSettings_->fullSavePath_ = fullsavePath;
pScreenshotSettings_->is360_ = is360;
pScreenshotSettings_->verticalFlip_ = verticalFlip;
pScreenshotSettings_->horizontalFlip_ = horizontalFlip;
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::setCameraOverlaySettings(float widthPercentage, uint32_t viewPortTopLeftX, uint32_t viewPortTopLeftY) {
std::lock_guard<std::mutex> lock(cameraModificationMutex_);
pCameraOverlaySettings_.reset(new CameraOverlaySettings);
pCameraOverlaySettings_->widthPercentage_ = widthPercentage;
pCameraOverlaySettings_->viewPortTopLeftX_ = viewPortTopLeftX;
pCameraOverlaySettings_->viewPortTopLeftY_ = viewPortTopLeftY;
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::enumerateMicDevices() {
if (!isMicDevicesInitialized()) {
FBCAPTURE_STATUS status = initializeMicDevices();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
}
HRESULT hr = pMicDevices_->enumerateDevices();
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR("Failed to enumerate mic devices. [Error code] ", hr);
return FBCAPTURE_STATUS_MIC_ENUMERATION_FAILED;
}
return FBCAPTURE_STATUS_OK;
}
size_t FBCaptureSystem::getMicDevicesCount() {
if (!isMicDevicesInitialized()) {
DEBUG_ERROR("enumerateMicDevices must be called before getMicDevicesCount. ");
return FBCAPTURE_STATUS_MIC_REQUIRES_ENUMERATION;
}
return pMicDevices_->count();
}
const char * FBCaptureSystem::getMicDeviceName(uint32_t index) {
if (!isMicDevicesInitialized()) {
DEBUG_ERROR("enumerateMicDevices must be called before getMicDeviceName. ");
return nullptr;
}
if (index >= pMicDevices_->count()) {
DEBUG_ERROR_VAR("index out of bounds for getMicDeviceName. [Count] ", to_string(pMicDevices_->count()));
return nullptr;
}
std::string name;
pMicDevices_->getDeviceName(index, name);
size_t allocSize = name.length() + sizeof(char);
char *result = (char*)::CoTaskMemAlloc(allocSize);
strcpy_s(result, allocSize, name.c_str());
return result;
}
FBCAPTURE_STATUS FBCaptureSystem::setMicDevice(uint32_t index) {
if (!isMicDevicesInitialized()) {
DEBUG_ERROR("enumerateMicDevices must be called before setMicDevice. ");
return FBCAPTURE_STATUS_MIC_REQUIRES_ENUMERATION;
}
if (index >= pMicDevices_->count()) {
DEBUG_ERROR_VAR("index out of bounds for setMicDevice. [Count] ", to_string(pMicDevices_->count()));
return FBCAPTURE_STATUS_MIC_INDEX_INVALID;
}
FBCAPTURE_STATUS status = unsetMicDevice();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
// Support mic switching during capture through lock_guard
std::lock_guard<std::mutex> lock(micModificationMutex_);
pMicSettings_.reset(new MicSettings);
pMicSettings_->micDeviceIndexChosen_ = index;
pMicSettings_->enabledDuringCapture_ = true;
HRESULT hr = pMicDevices_->getDeviceId(index, &pMicSettings_->micDeviceIdChosen_);
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR("Failed to get device id for mic. [Error code] ", hr);
return FBCAPTURE_STATUS_MIC_ENUMERATION_FAILED;
}
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::unsetMicDevice() {
// Support mic switching during capture through lock_guard
std::lock_guard<std::mutex> lock(micModificationMutex_);
if (!pMicSettings_) {
return FBCAPTURE_STATUS_OK;
}
if (pMicSettings_ && pMicSettings_->micDeviceIdChosen_) {
pMicDevices_->freeDeviceId(pMicSettings_->micDeviceIdChosen_);
}
if (pMicSettings_) {
pMicSettings_.reset(nullptr);
}
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::setMicEnabledDuringCapture(bool enabled) {
if (!pMicSettings_) {
pMicSettings_.reset(new MicSettings);
pMicSettings_->micDeviceIdChosen_ = nullptr;
}
pMicSettings_->enabledDuringCapture_ = enabled;
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::setAudioEnabledDuringCapture(bool enabled) {
audioEnabledDuringCapture_ = enabled;
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::enumerateCameraDevices() {
if (!isCameraDevicesInitialized()) {
FBCAPTURE_STATUS status = initializeCameraDevices();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
}
HRESULT hr = pCameraDevices_->enumerateDevices();
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR("Failed to enumerate camera devices. [Error code] ", hr);
return FBCAPTURE_STATUS_CAMERA_ENUMERATION_FAILED;
}
return FBCAPTURE_STATUS_OK;
}
size_t FBCaptureSystem::getCameraDevicesCount() {
if (!isCameraDevicesInitialized()) {
DEBUG_ERROR("enumerateCameraDevices must be called before getCameraDevicesCount. ");
return FBCAPTURE_STATUS_CAMERA_REQUIRES_ENUMERATION;
}
return pCameraDevices_->count();
}
const char * FBCaptureSystem::getCameraDeviceName(uint32_t index) {
if (!isCameraDevicesInitialized()) {
DEBUG_ERROR("enumerateCameraDevices must be called before getCameraDeviceName. ");
return nullptr;
}
if (index >= pCameraDevices_->count()) {
DEBUG_ERROR_VAR("index out of bounds for getCameraDeviceName. [Count] ", to_string(pCameraDevices_->count()));
return nullptr;
}
std::string name;
pCameraDevices_->getDeviceName(index, name);
size_t allocSize = name.length() + sizeof(char);
char *result = (char*)::CoTaskMemAlloc(allocSize);
strcpy_s(result, allocSize, name.c_str());
return result;
}
FBCAPTURE_STATUS FBCaptureSystem::setCameraDevice(uint32_t index) {
if (!isCameraDevicesInitialized()) {
DEBUG_ERROR("enumerateCameraDevices must be called before setCameraDevice. ");
return FBCAPTURE_STATUS_CAMERA_REQUIRES_ENUMERATION;
}
if (index >= pCameraDevices_->count()) {
DEBUG_ERROR_VAR("index out of bounds for setCameraDevice. [Count] ", to_string(pCameraDevices_->count()));
return FBCAPTURE_STATUS_CAMERA_INDEX_INVALID;
}
FBCAPTURE_STATUS result = unsetCameraDevice();
if (result != FBCAPTURE_STATUS_OK) {
return result;
}
// Support camera switching during capture through lock_guard
std::lock_guard<std::mutex> lock(cameraModificationMutex_);
pCameraSettings_.reset(new CameraSettings);
pCameraSettings_->cameraDeviceIndexChosen_ = index;
pCameraSettings_->enabledDuringCapture_ = true;
pCameraOverlay_.reset(new CameraOverlay);
if (!activateCameraDevice(lock)) {
return FBCAPTURE_STATUS_CAMERA_SET_FAILED;
}
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::unsetCameraDevice() {
FBCAPTURE_STATUS result = FBCAPTURE_STATUS_OK;
// Support camera switching during capture through lock_guard
std::lock_guard<std::mutex> lock(cameraModificationMutex_);
if (pCameraSettings_ && pCameraOverlay_ && !deactivateCameraDevice(lock)) {
return FBCAPTURE_STATUS_CAMERA_UNSET_FAILED;
}
pCameraOverlay_.reset(nullptr);
pCameraSettings_.reset(nullptr);
return result;
}
FBCAPTURE_STATUS FBCaptureSystem::setCameraEnabledDuringCapture(bool enabled) {
if (!pCameraSettings_) {
DEBUG_ERROR("setCameraDevice must be called before setCameraEnabledDuringCapture. ");
return FBCAPTURE_STATUS_CAMERA_DEVICE_NOT_SET;
}
pCameraSettings_->enabledDuringCapture_ = enabled;
return FBCAPTURE_STATUS_OK;
}
// TODO AudioRenderSettings
FBCAPTURE_STATUS FBCaptureSystem::setMicAndAudioRenderDeviceByVRDeviceType(VRDeviceType vrDevice) {
// TODO setMicAndAudioRenderDeviceByVRDeviceType
vrDevice_ = vrDevice;
vrDeviceRequested_ = true;
// TODO iterate mics and find that which matches the vr device type and call setMicDevice to that index
// TODO when AudioRenderSettings exist, find that audio render device which matches the vr device type and call setAudioRenderDevice to that index
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::initializeSystemIfNeeded() {
// Initialize the system device and context if necessary
if (!isInitialized()) {
return initialize();
}
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::startCapture(FBCaptureType type) {
FBCAPTURE_STATUS status = getCaptureStatus();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
if (captureInProgress_) {
DEBUG_ERROR("capture is already in progress. Call stopCapture to stop existing capture. ");
return FBCAPTURE_STATUS_SYSTEM_CAPTURE_IN_PROGRESS;
}
if (type == FBCaptureType::kLive && !pLiveCaptureSettings_) {
DEBUG_ERROR("setLiveCaptureSettings must be called before starting a live capture. ");
return FBCAPTURE_STATUS_LIVE_CAPTURE_SETTINGS_NOT_CONFIGURED;
} else if (type == FBCaptureType::kVod && !pVodCaptureSettings_) {
DEBUG_ERROR("setVodCaptureSettings must be called before starting a vod capture. ");
return FBCAPTURE_STATUS_VOD_CAPTURE_SETTINGS_NOT_CONFIGURED;
} else if (type == FBCaptureType::kPreview && !pPreviewCaptureSettings_) {
DEBUG_ERROR("setPreviewCaptureSettings must be called before starting a preview capture. ");
return FBCAPTURE_STATUS_PREVIEW_CAPTURE_SETTINGS_NOT_CONFIGURED;
}
// Prepare the system shared texture for passing to the encoder
const uint32_t width = getCaptureWidth(type);
const uint32_t height = getCaptureHeight(type);
D3D11_TEXTURE2D_DESC desc = {};
HRESULT hr = S_OK;
pEncodingTexture_ = nullptr;
ZeroMemory(&desc, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.ArraySize = 1;
desc.MipLevels = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
hr = pDevice_->CreateTexture2D(&desc, nullptr,
&pEncodingTexture_);
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR(
"Failed to create encoding Texture2D FBCaptureSystem. [Error code] ",
hr);
return FBCAPTURE_STATUS_SYSTEM_ENCODING_TEXTURE_CREATION_FAILED;
}
pPreviewTexture_ = nullptr;
ZeroMemory(&desc, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.ArraySize = 1;
desc.MipLevels = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;
hr = pDevice_->CreateTexture2D(&desc, nullptr,
&pPreviewTexture_);
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR(
"Failed to create preview Texture2D in FBCaptureSystem. [Error code] ",
hr);
return FBCAPTURE_STATUS_SYSTEM_PREVIEW_TEXTURE_CREATION_FAILED;
}
pTextureFormatConversion_.reset(new TextureRender());
bool success = pTextureFormatConversion_->initialize(
pDevice_, pContext_,
pEncodingTexture_,
screenVertexShaderCode, sizeof(screenVertexShaderCode),
pEncoder_->isSoftwareEncoderEnabled() ? yuvPixelShaderCode : screenPixelShaderCode,
pEncoder_->isSoftwareEncoderEnabled() ? sizeof(yuvPixelShaderCode) : sizeof(screenPixelShaderCode),
getCaptureNeedsVerticalFlip(type),
getCaptureNeedsHorizontalFlip(type));
if (!success) {
hr = S_FALSE;
DEBUG_ERROR(
"Failed to initialize TextureFormatConversion in FBCaptureSystem.");
return FBCAPTURE_STATUS_SYSTEM_ENCODING_TEXTURE_FORMAT_CREATION_FAILED;
}
pTextureFormatConversion_->setViewport(0, 0, width,
height);
pPreviewTextureFormatConversion_.reset(new TextureRender());
success = pPreviewTextureFormatConversion_->initialize(
pDevice_, pContext_,
pPreviewTexture_, screenVertexShaderCode,
sizeof(screenVertexShaderCode), screenPixelShaderCode,
sizeof(screenPixelShaderCode),
getCaptureNeedsVerticalFlip(type),
getCaptureNeedsHorizontalFlip(type));
if (!success) {
hr = S_FALSE;
DEBUG_ERROR(
"Failed to initialize TextureFormatConversion in FBCaptureSystem.");
return FBCAPTURE_STATUS_SYSTEM_ENCODING_TEXTURE_FORMAT_CREATION_FAILED;
}
pPreviewTextureFormatConversion_->setViewport(0, 0, width, height);
if (isCameraReaderInitialized()) {
pCameraOverlay_->cameraTextureOverlayWidth_ = (uint32_t)(
width * (pCameraOverlaySettings_->widthPercentage_ / 100.0f));
// Set camera overlay to 4:3 as that's what CameraReader filters to
pCameraOverlay_->cameraTextureOverlayHeight_ = (uint32_t)(pCameraOverlay_->cameraTextureOverlayWidth_ * 3 / 4);
}
if (muxThread_ || audioThread_ || encodeThread_ || cameraThread_) {
stopCapture();
}
continueCapture_ = true;
captureFailed_ = false;
captureFailureReason_ = FBCAPTURE_STATUS_OK;
encoding_ = false;
flush_ = false;
captureInProgress_ = true;
stopRequested_ = false;
captureInProgressType_ = type;
if (!pEncoder_->isClientPcmAudioInputEnabled()) {
audioThread_ = new std::thread(&FBCaptureSystem::audioThreadRun, this);
}
muxThread_ = new std::thread(&FBCaptureSystem::muxThreadRun, this);
encodeThread_ = new std::thread(&FBCaptureSystem::encodeThreadRun, this);
cameraThread_ = new std::thread(&FBCaptureSystem::cameraThreadRun, this);
stopRoutineThread_ = new std::thread(&FBCaptureSystem::stopRoutineThreadRun, this);
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::startScreenshot(FBCaptureType type) {
FBCAPTURE_STATUS status = initializeSystemIfNeeded();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
status = getScreenshotStatus();
if (status == FBCAPTURE_STATUS_SYSTEM_CAPTURE_IN_PROGRESS) {
DEBUG_LOG("Screenshot is in progress.");
return status;
}
if (type == FBCaptureType::kScreenShot && !pScreenshotSettings_) {
DEBUG_ERROR("setScreenshotCaptureSettings must be called before starting a screenshot capture. ");
return FBCAPTURE_STATUS_SCREENSHOT_CAPTURE_SETTINGS_NOT_CONFIGURED;
}
// Prepare the system shared texture for passing to the encoder
const uint32_t width = getCaptureWidth(type);
const uint32_t height = getCaptureHeight(type);
D3D11_TEXTURE2D_DESC desc = {};
HRESULT hr = S_OK;
pScreenshotTexture_ = nullptr;
ZeroMemory(&desc, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.ArraySize = 1;
desc.MipLevels = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
hr = pDevice_->CreateTexture2D(&desc, nullptr,
&pScreenshotTexture_);
if (FAILED(hr)) {
DEBUG_HRESULT_ERROR(
"Failed to create screenshot Texture2D FBCaptureSystem. [Error code] ", hr);
status = FBCAPTURE_STATUS_SYSTEM_ENCODING_TEXTURE_FORMAT_CREATION_FAILED;
screenshotFailed(status);
return status;
}
pScreenShotTextureFormatConversion_.reset(new TextureRender());
bool success = pScreenShotTextureFormatConversion_->initialize(
pDevice_, pContext_,
pScreenshotTexture_, screenVertexShaderCode,
sizeof(screenVertexShaderCode), screenPixelShaderCode,
sizeof(screenPixelShaderCode),
getCaptureNeedsVerticalFlip(type),
getCaptureNeedsHorizontalFlip(type));
if (!success) {
hr = S_FALSE;
DEBUG_ERROR("Failed to initialize ScreenShotTextureFormatConversion in FBCaptureSystem.");
status = FBCAPTURE_STATUS_SYSTEM_ENCODING_TEXTURE_FORMAT_CREATION_FAILED;
screenshotFailed(status);
return status;
}
pScreenShotTextureFormatConversion_->setViewport(0, 0, width, height);
pGraphicsDeviceScreenshot_.reset(new GraphicsDeviceCaptureD3D11(pDevice_));
terminateScreenshotThread_ = false;
screenshotTextureReceieved_ = false;
screenshotInProgress_ = true;
screenshotThread_ = new std::thread(&FBCaptureSystem::screenshotThreadRun, this);
screenshotThreadManager_ = new std::thread(&FBCaptureSystem::screenshotThreadManagerRun, this);
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::captureTexture(void* texturePtr) {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
// Sometimes Unity is failed on invoking texture pointer on init and it causes encoding failure with null texture
// So I want to skip invaild texture pointer here
if (texturePtr == nullptr) {
DEBUG_LOG("Null texture was received.");
return status;
}
status = getCaptureStatus();
if (status != FBCAPTURE_STATUS_OK && status != FBCAPTURE_STATUS_SYSTEM_CAPTURE_IN_PROGRESS) {
if (!captureInProgress_) {
DEBUG_ERROR("capture is not in progress. Call startCapture to start. ");
return FBCAPTURE_STATUS_SYSTEM_CAPTURE_NOT_IN_PROGRESS;
} else {
return status;
}
}
// Copy the user graphics device texturePtr to a separate shared texture on the user graphics device
FBCAPTURE_STATUS result = pGraphicsDeviceCapture_->captureTextureToSharedHandle(texturePtr);
if (result == FBCAPTURE_STATUS_OK) {
captureTextureReceieved_ = true;
} else {
captureFailed(result);
stopCapture();
}
return result;
}
FBCAPTURE_STATUS FBCaptureSystem::previewCapture(void* texturePtr) {
FBCAPTURE_STATUS status = getCaptureStatus();
if (status != FBCAPTURE_STATUS_OK && status != FBCAPTURE_STATUS_SYSTEM_CAPTURE_IN_PROGRESS) {
return status;
}
return doPreview(texturePtr, false);
}
FBCAPTURE_STATUS FBCaptureSystem::previewCamera(void* texturePtr) {
FBCAPTURE_STATUS status = getCaptureStatus();
if (status != FBCAPTURE_STATUS_OK && status != FBCAPTURE_STATUS_SYSTEM_CAPTURE_IN_PROGRESS) {
return status;
}
return doPreview(texturePtr, true);
}
FBCAPTURE_STATUS FBCaptureSystem::getCaptureStatus() {
// getCaptureStatus is a polling mechanism to officially stop a failed capture or check the end of encoding process
if (captureInProgress_ && captureFailed_) {
FBCAPTURE_STATUS status = captureFailureReason_;
stopCapture();
return status;
} else if (captureInProgress_) {
return FBCAPTURE_STATUS_SYSTEM_CAPTURE_IN_PROGRESS;
}
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::getScreenshotStatus() {
if (screenshotFailed_) {
FBCAPTURE_STATUS status = captureFailureReason_;
screenshotInProgress_ = false;
return status;
} else if (screenshotInProgress_) {
return FBCAPTURE_STATUS_SYSTEM_CAPTURE_IN_PROGRESS;
}
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS FBCaptureSystem::doPreview(void* texturePtr, bool onlyCamera) {
if (!captureInProgress_ || captureInProgressType_ != FBCaptureType::kPreview) {
DEBUG_ERROR("preview capture is not in progress. Call startPreviewCapture to start. ");
return FBCAPTURE_STATUS_SYSTEM_CAPTURE_PREVIEW_NOT_IN_PROGRESS;
}
if (!onlyCamera && !captureTextureReceieved_) {
DEBUG_ERROR("capture texture has not been received. Call captureTexture first. ");
return FBCAPTURE_STATUS_SYSTEM_CAPTURE_TEXTURE_NOT_RECEIVED;
}
// Fill pEncodingTexture_ on system device
doEncodeTextureRender(onlyCamera);
if (captureFailed_) {
return captureFailureReason_;
}
// Copy pEncodingTexture_ to pPreviewTexture_ on system device
HANDLE sharedHandle;
FBCAPTURE_STATUS result = doPreviewTextureRender(&sharedHandle);
if (result != FBCAPTURE_STATUS_OK) {
captureFailed(result);
return result;
}
// Have the user graphics device copy pPreviewTexture_ to texturePtr
result = pGraphicsDeviceCapture_->copyTexture(texturePtr, sharedHandle);
if (result != FBCAPTURE_STATUS_OK) {
captureFailed(result);
}
return result;
}
void FBCaptureSystem::stopCapture() {
stopRequested_ = true;
}
void FBCaptureSystem::doEncoderStopRoutine() {
if (captureInProgressType_ == FBCaptureType::kPreview) {
return;
}
FBCAPTURE_STATUS status = pEncoder_->stopEncoding(true);
if (status != FBCAPTURE_STATUS_OK) {
DEBUG_ERROR_VAR("Final stop encoding failed", std::to_string(status));
captureFailed(status);
}
if (status == FBCAPTURE_STATUS_OK && captureInProgressType_ == FBCaptureType::kVod) {
status = pEncoder_->muxingData(pVodCaptureSettings_->projectionType_, pVodCaptureSettings_->stereoMode_, pVodCaptureSettings_->frameRate_, pVodCaptureSettings_->is360_);
if (status != FBCAPTURE_STATUS_OK) {
DEBUG_ERROR_VAR("Final MP4 muxing failed", std::to_string(status));
captureFailed(status);
}
} else if (status == FBCAPTURE_STATUS_OK && captureInProgressType_ == FBCaptureType::kLive) {
status = pEncoder_->muxingData(pLiveCaptureSettings_->projectionType_, pLiveCaptureSettings_->stereoMode_, pLiveCaptureSettings_->frameRate_, pLiveCaptureSettings_->is360_);
if (status != FBCAPTURE_STATUS_OK) {
DEBUG_ERROR_VAR("Final FLV muxing failed", std::to_string(status));
captureFailed(status);
} else {
status = pEncoder_->startLiveStream(pLiveCaptureSettings_->streamUrl_.c_str());
if (status != FBCAPTURE_STATUS_OK) {
DEBUG_ERROR_VAR("Start livestream failed", std::to_string(status));
captureFailed(status);
}
}
}
pEncoder_->stopLiveStream();
pEncoder_->resetResources();
}
void FBCaptureSystem::captureFailed(FBCAPTURE_STATUS reason) {
std::lock_guard<std::mutex> lock(captureFailedMutex_);
continueCapture_ = false;
captureFailed_ = true;
captureFailureReason_ = reason;
if (pEncoder_) pEncoder_->releaseEncodeResources();
}
void FBCaptureSystem::screenshotFailed(FBCAPTURE_STATUS reason) {
std::lock_guard<std::mutex> lock(screenshotFailedMutex_);
screenshotFailed_ = true;
captureFailureReason_ = reason;
screenshotInProgress_ = false;
}
uint32_t FBCaptureSystem::getCaptureWidth(FBCaptureType type) {
// Needs to be aligned to 16
if (type == FBCaptureType::kLive) {
return ((pLiveCaptureSettings_->width_ + kResolutionAlignment - 1) / kResolutionAlignment) * kResolutionAlignment;
} else if (type == FBCaptureType::kVod) {
return ((pVodCaptureSettings_->width_ + kResolutionAlignment - 1) / kResolutionAlignment) * kResolutionAlignment;
} else if (type == FBCaptureType::kScreenShot) {
return pScreenshotSettings_->width_;
} else {
return ((pPreviewCaptureSettings_->width_ + kResolutionAlignment - 1) / kResolutionAlignment) * kResolutionAlignment;
}
}
uint32_t FBCaptureSystem::getCaptureHeight(FBCaptureType type) {
// Needs to be aligned to 16
if (type == FBCaptureType::kLive) {
return ((pLiveCaptureSettings_->height_ + kResolutionAlignment - 1) / kResolutionAlignment) * kResolutionAlignment;
} else if (type == FBCaptureType::kVod) {
return ((pVodCaptureSettings_->height_ + kResolutionAlignment - 1) / kResolutionAlignment) * kResolutionAlignment;
} else if (type == FBCaptureType::kScreenShot) {
return pScreenshotSettings_->height_;
} else {
return ((pPreviewCaptureSettings_->height_ + kResolutionAlignment - 1) / kResolutionAlignment) * kResolutionAlignment;
}
}
float FBCaptureSystem::getCaptureEncodeCycle(FBCaptureType type) {
if (type == FBCaptureType::kLive) {
return pLiveCaptureSettings_->encodeCycle_;
} else if (type == FBCaptureType::kVod) {
return pVodCaptureSettings_->encodeCycle_;
} else {
return pPreviewCaptureSettings_->encodeCycle_;
}
}
bool FBCaptureSystem::getCaptureNeedsVerticalFlip(FBCaptureType type) {
if (type == FBCaptureType::kLive) {
return pLiveCaptureSettings_->verticalFlip_;
} else if (type == FBCaptureType::kVod) {
return pVodCaptureSettings_->verticalFlip_;
} else if (type == FBCaptureType::kScreenShot) {
return pScreenshotSettings_->verticalFlip_;
} else {
return pPreviewCaptureSettings_->verticalFlip_;
}
}
bool FBCaptureSystem::getCaptureNeedsHorizontalFlip(FBCaptureType type) {
if (type == FBCaptureType::kLive) {
return pLiveCaptureSettings_->horizontalFlip_;
} else if (type == FBCaptureType::kVod) {
return pVodCaptureSettings_->horizontalFlip_;
} else if (type == FBCaptureType::kScreenShot) {
return pScreenshotSettings_->horizontalFlip_;
} else {
return pPreviewCaptureSettings_->horizontalFlip_;
}