forked from facebookarchive/360-Capture-SDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncoderMain.cpp
564 lines (464 loc) · 19.6 KB
/
EncoderMain.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
/*
* 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 "EncoderMain.h"
namespace FBCapture {
namespace Common {
// Capture SDK Version Update String
const string sdkVersion = "2.35";
EncoderMain::EncoderMain() {
DEBUG_LOG_VAR("Capture SDK Version: ", sdkVersion);
}
EncoderMain::~EncoderMain() {
}
vector<wstring> EncoderMain::splitString(wstring& str) {
vector<wstring> stringArr;
wstringstream stringStream(str); // Turn the string into a stream.
wstring tok;
while (getline(stringStream, tok, L'.')) {
stringArr.push_back(tok);
}
return stringArr;
}
FBCAPTURE_STATUS EncoderMain::initEncoderComponents() {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (checkGPUManufacturer() == GRAPHICS_CARD::NVIDIA && this->nvEncoder == nullptr) {
this->nvEncoder = std::make_unique<NVEncoder>(this->device_);
}
if (checkGPUManufacturer() == GRAPHICS_CARD::AMD && this->amdEncoder == nullptr) {
this->amdEncoder = std::make_unique<AMDEncoder>(this->device_);
}
if (this->flvMuxer == nullptr) {
this->flvMuxer = std::make_unique<FLVMuxer>();
}
if (this->mp4Muxer == nullptr) {
this->mp4Muxer = std::make_unique<MP4Muxer>();
}
if (this->audioDeviceCapture == nullptr) {
this->audioDeviceCapture = std::make_unique<AudioDeviceCapture>();
}
if (this->audioCustomRawDataCapture == nullptr) {
this->audioCustomRawDataCapture = std::make_unique<AudioCustomRawDataCapture>();
}
if (this->audioEncoder == nullptr) {
this->audioEncoder = std::make_unique<AudioEncoder>();
}
if (this->rtmp == nullptr) {
this->rtmp = std::make_unique<LibRTMP>();
}
// Using "%AppData%" folder for saving sliced live video files
LPWSTR wszPath = nullptr;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_CREATE, nullptr, &wszPath);
if (SUCCEEDED(hr)) {
this->liveFolder = wszPath;
this->liveFolder += L"\\FBEncoder\\";
if (!CreateDirectory(this->liveFolder.c_str(), nullptr)) {
if (ERROR_ALREADY_EXISTS == GetLastError()) {
DEBUG_LOG("Output folder already existed");
}
}
} else {
this->liveFolder.clear(); // Just use root folder when it failed to create folder
}
return status;
}
FBCAPTURE_STATUS EncoderMain::checkGraphicsCardCapability() {
if (checkGPUManufacturer() == GRAPHICS_CARD::UNSUPPORTED_DEVICE) {
DEBUG_ERROR("Unsupported graphics card. It will use software encoder.");
return FBCAPTURE_STATUS_UNSUPPORTED_GRAPHICS_CARD;
}
return FBCAPTURE_STATUS_OK;
}
GRAPHICS_CARD EncoderMain::checkGPUManufacturer() {
if (this->amdDevice) {
return GRAPHICS_CARD::AMD;
} else if (this->nvidiaDevice) {
return GRAPHICS_CARD::NVIDIA;
} else {
return GRAPHICS_CARD::UNSUPPORTED_DEVICE;
}
}
FBCAPTURE_STATUS EncoderMain::releaseEncodeResources() {
this->needEncodingSessionInit = true;
// We want to destroy nvidia encoder only because AMF doesn't open encoding session on AMF init
if (checkGPUManufacturer() == GRAPHICS_CARD::NVIDIA && this->nvEncoder) {
return this->nvEncoder->releaseEncodingResources();
}
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS EncoderMain::dummyEncodingSession() {
this->needEncodingSessionInit = true;
// Only nVidia driver requires real input buffer to destroy encoder clearly.
// Otherwise, nVidia driver keeps holding endoer session created before, even though we called "NvEncDestroyEncoder" function.
if (checkGPUManufacturer() == GRAPHICS_CARD::NVIDIA && this->nvEncoder) {
return this->nvEncoder->dummyTextureEncoding();
}
return FBCAPTURE_STATUS_OK;
}
FBCAPTURE_STATUS EncoderMain::initSessionANDcheckDriverCapability() {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (isSoftwareEncoderEnabled()) {
if (this->swEncoder == nullptr) {
this->swEncoder = std::make_unique<OpenH264Encoder>(this->device_);
}
status = this->swEncoder->initEncodingSession();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
} else if (checkGPUManufacturer() == GRAPHICS_CARD::NVIDIA && this->nvEncoder) {
status = this->nvEncoder->initEncodingSession();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
} else if (checkGPUManufacturer() == GRAPHICS_CARD::AMD && this->amdEncoder) {
status = this->amdEncoder->initEncodingSession();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
}
this->needEncodingSessionInit = false;
return status;
}
wstring EncoderMain::generateLiveVideoFileWString() {
wstring liveVideoFile = this->prevVideoH264;
liveVideoFile.erase(this->prevVideoH264.length() - this->h264Extension.length(), this->h264Extension.length());
liveVideoFile += this->flvExtension;
return liveVideoFile;
}
FBCAPTURE_STATUS EncoderMain::startEncoding(const void* texturePtr, const TCHAR* fullSavePath, bool isLive, int bitrate, int fps, bool needFlipping) {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (this->stopEncProcess)
return status;
this->isLive = isLive;
if (needEncodingSessionInit) {
status = initSessionANDcheckDriverCapability();
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
}
if (!this->initiatedUnixTime) {
this->initiatedUnixTime = true;
this->unixTime = std::time(nullptr); // Using unix time for live video files' identity
}
if (!this->isLive && this->updateInputName) { // VOD mode
this->updateInputName = false;
this->videoH264 = fullSavePath;
if (this->videoH264.find(this->mp4Extension) != string::npos) { // Convert file name to h264 when input name is mp4 format
this->videoH264.replace(this->videoH264.find(this->mp4Extension), this->mp4Extension.length(), this->h264Extension);
}
} else if (this->isLive) { // Live mode
this->videoH264 = this->liveFolder + to_wstring(this->unixTime) + this->h264Extension;
}
// Encoding with render texture
if (texturePtr == nullptr) {
DEBUG_LOG("It's invalid texture pointer: null");
} else if (isSoftwareEncoderEnabled()) {
status = this->swEncoder->encodeProcess(texturePtr, this->videoH264, bitrate, fps, needFlipping);
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
} else if (checkGPUManufacturer() == GRAPHICS_CARD::NVIDIA) {
status = this->nvEncoder->encodeProcess(texturePtr, this->videoH264, bitrate, fps, needFlipping);
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
} else if (checkGPUManufacturer() == GRAPHICS_CARD::AMD) {
status = this->amdEncoder->encodeProcess(texturePtr, this->videoH264, bitrate, fps, needFlipping);
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
return status;
}
FBCAPTURE_STATUS EncoderMain::audioDeviceCaptureEncoding(bool useVRAudioEndpoint, bool enabledAudioCapture, bool enabledMicCapture,
VRDeviceType vrDevice, LPCWSTR useMicIMMDeviceId) {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (this->stopEncProcess || this->videoH264.empty()) {
return status;
}
if (this->audioDeviceCapture->needToInitializeResources) {
status = this->audioDeviceCapture->initializeCaptureResources(useVRAudioEndpoint, vrDevice, useMicIMMDeviceId);
if (status == FBCAPTURE_STATUS_AUDIO_DEVICE_ENUMERATION_FAILED) {
this->noAvailableAudioDevice = true;
return status;
} else if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
if (this->audioDeviceCapture->needToOpenCaptureFile) {
if (!this->isLive) { // VOD mode
wstring videoPath = this->videoH264;
videoPath.erase(this->videoH264.length() - this->h264Extension.length(), this->h264Extension.length());
wstring_convert<std::codecvt_utf8<wchar_t>> stringTypeConversion;
string audioPath = stringTypeConversion.to_bytes(videoPath);
this->audioWAV = audioPath + this->wavExtension;
this->audioAAC = audioPath + this->aacExtension;
} else { // Live mode
wstring_convert<std::codecvt_utf8<wchar_t>> stringTypeConversion;
string folderPath = stringTypeConversion.to_bytes(this->liveFolder);
this->audioWAV = folderPath + to_string(this->unixTime) + this->wavExtension;
this->audioAAC = folderPath + to_string(this->unixTime) + this->aacExtension;
}
status = this->audioDeviceCapture->openCaptureFile(this->audioWAV);
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
if (!this->audioDeviceCapture->needToCloseCaptureFile) {
this->audioDeviceCapture->continueAudioCapture(enabledAudioCapture, enabledMicCapture);
} else {
status = this->audioDeviceCapture->closeCaptureFile();
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
return status;
}
FBCAPTURE_STATUS EncoderMain::audioRawDataEncoding(float* audioData, uint32_t channel, uint32_t sampleRate, uint32_t bufferSize) {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (this->stopEncProcess || this->videoH264.empty()) {
return status;
}
if (this->audioCustomRawDataCapture->needToOpenCaptureFile) {
if (!this->isLive) { // VOD mode
wstring videoPath = this->videoH264;
videoPath.erase(this->videoH264.length() - this->h264Extension.length(), this->h264Extension.length());
wstring_convert<std::codecvt_utf8<wchar_t>> stringTypeConversion;
string audioPath = stringTypeConversion.to_bytes(videoPath);
this->audioWAV = audioPath + this->wavExtension;
this->audioAAC = audioPath + this->aacExtension;
} else { // Live mode
wstring_convert<std::codecvt_utf8<wchar_t>> stringTypeConversion;
string folderPath = stringTypeConversion.to_bytes(this->liveFolder);
this->audioWAV = folderPath + to_string(this->unixTime) + this->wavExtension;
this->audioAAC = folderPath + to_string(this->unixTime) + this->aacExtension;
}
status = this->audioCustomRawDataCapture->openCaptureFile(this->audioWAV, sampleRate, channel);
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
if (!this->audioCustomRawDataCapture->needToCloseCaptureFile) {
this->audioCustomRawDataCapture->continueAudioCapture(audioData, bufferSize);
} else {
status = this->audioCustomRawDataCapture->closeCaptureFile();
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
return status;
}
FBCAPTURE_STATUS EncoderMain::stopEncoding(bool forceStop) {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (this->stopEncProcess) // Only we can flush buffers after encoding starts
return status;
this->updateInputName = true;
if (this->updateInputName) { // Update unix time for next frame video and audio
this->unixTime = std::time(nullptr);
this->updateInputName = !this->updateInputName;
}
// Store previous file name to use in muxing
this->prevAudioWAV = this->audioWAV;
this->prevAudioAAC = this->audioAAC;
this->prevVideoH264 = this->videoH264;
// Update file names for next slice
if (this->isLive) {
wstring_convert<std::codecvt_utf8<wchar_t>> stringTypeConversion;
string folderPath = stringTypeConversion.to_bytes(this->liveFolder);
this->audioWAV = folderPath + to_string(this->unixTime) + this->wavExtension;
this->audioAAC = folderPath + to_string(this->unixTime) + this->aacExtension;
this->videoH264 = this->liveFolder + to_wstring(this->unixTime) + this->h264Extension;
}
// Flushing inputs
if (isSoftwareEncoderEnabled()) {
status = this->swEncoder->flushInputTextures();
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
} else if (checkGPUManufacturer() == GRAPHICS_CARD::NVIDIA) {
status = this->nvEncoder->flushInputTextures();
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
} else if (checkGPUManufacturer() == GRAPHICS_CARD::AMD) {
status = this->amdEncoder->flushInputTextures();
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
this->needEncodingSessionInit = true;
this->movingToMuxingStage = true;
if (isClientPcmAudioInputEnabled()) {
if (!this->audioCustomRawDataCapture->needToInitializeResources) {
this->audioCustomRawDataCapture->needToCloseCaptureFile = true;
this->stopEncodingSession = forceStop;
if (this->stopEncodingSession) {
this->audioCustomRawDataCapture->closeCaptureFile();
}
}
} else {
if (!this->audioDeviceCapture->needToInitializeResources) {
this->audioDeviceCapture->needToCloseCaptureFile = true;
this->stopEncodingSession = forceStop;
if (this->stopEncodingSession) {
this->audioDeviceCapture->closeCaptureFile();
}
}
}
return status;
}
FBCAPTURE_STATUS EncoderMain::muxingData(PROJECTIONTYPE projectionType, STEREO_MODE stereMode, const float fps, bool is360) {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (!this->movingToMuxingStage || this->stopEncProcess)
return status;
while (true) {
if (this->stopEncProcess)
break;
Sleep(1);
if ((!isClientPcmAudioInputEnabled() && this->audioDeviceCapture->needToCloseCaptureFile) ||
(isClientPcmAudioInputEnabled() && this->audioCustomRawDataCapture->needToCloseCaptureFile))
continue;
// Transcoding wav to aac when we get audio input
if (this->noAvailableAudioDevice) {
this->prevAudioAAC = {}; // Generate video only on muxing layer when no available audio device is attached
} else {
status = this->audioEncoder->continueAudioTranscoding(this->prevAudioWAV, this->prevAudioAAC);
if (status == FBCAPTURE_STATUS_MF_SOURCE_READER_CREATION_FAILED) {
this->prevAudioAAC = {}; // Generate video only on muxing layer when we fail to create aac audio file
} else if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
// Muxing
if (this->isLive) {
status = this->flvMuxer->muxingMedia(this->prevVideoH264, this->prevAudioAAC, fps);
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
} else {
status = this->mp4Muxer->muxingMedia(this->prevVideoH264, this->prevAudioAAC, projectionType, stereMode, fps, is360);
if (status != FBCAPTURE_STATUS_OK) {
this->stopEncProcess = true;
return status;
}
}
// Clean up audio resouces in same thread
if (this->stopEncodingSession) {
this->stopEncodingSession = false; // Reset for next encoding session
if (!isClientPcmAudioInputEnabled() && this->audioDeviceCapture) {
this->audioDeviceCapture->releaseCaptureResources();
} else {
this->audioCustomRawDataCapture->releaseCaptureResources();
}
if (this->audioEncoder) {
this->audioEncoder->shutdown();
}
}
break;
}
this->movingToMuxingStage = false;
this->isMuxed = true;
this->stopEncProcess = false;
return status;
}
FBCAPTURE_STATUS EncoderMain::saveScreenShot(const void* texturePtr, const TCHAR* fullSavePath, bool is360) {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (texturePtr == nullptr) {
DEBUG_ERROR("Invalid render texture pointer(null)");
return FBCAPTURE_STATUS_INVALID_TEXTURE_POINTER;
}
if (_tcslen(fullSavePath) == 0) { //No input file path for screenshot
DEBUG_ERROR("Didn't put screenshot file name");
return FBCAPTURE_STATUS_NO_INPUT_FILE;
}
screenShotEncoder = std::make_unique<ScreenShotEncoder>(this->device_);
status = screenShotEncoder->saveScreenShot(texturePtr, fullSavePath, is360);
if (status != FBCAPTURE_STATUS_OK) {
return status;
}
DEBUG_LOG("Finished screenshot successfully");
return status;
}
FBCAPTURE_STATUS EncoderMain::startLiveStream(const TCHAR* streamUrl) {
FBCAPTURE_STATUS status = FBCAPTURE_STATUS_OK;
if (!this->isMuxed || this->stopEncProcess || !this->isLive)
return status;
if (this->rtmp && this->isLive) {
wstring liveVideoFile = generateLiveVideoFileWString();
if (!liveVideoFile.empty() && (status = this->rtmp->connectRTMPWithFlv(streamUrl, liveVideoFile.c_str())) != FBCAPTURE_STATUS_OK) {
return status;
}
} else {
DEBUG_LOG("Need to enable live streaming option in Unity script");
}
return status;
}
void EncoderMain::stopLiveStream() {
if (this->rtmp) {
this->rtmp->close();
}
// Remove any potential lingering files due to failures
remove(this->audioWAV.c_str());
remove(this->audioAAC.c_str());
_wremove(this->videoH264.c_str());
remove(this->prevAudioWAV.c_str());
remove(this->prevAudioAAC.c_str());
_wremove(this->prevVideoH264.c_str());
if (!this->prevVideoH264.empty()) {
wstring liveVideoFile = generateLiveVideoFileWString();
_wremove(liveVideoFile.c_str());
}
}
void EncoderMain::resetResources() {
this->initiatedUnixTime = false;
this->stopEncProcess = false;
this->isLive = false;
this->unixTime = 0;
this->updateInputName = true;
this->isMuxed = false;
this->stopEncodingSession = false;
this->needEncodingSessionInit = true;
this->movingToMuxingStage = false;
this->noAvailableAudioDevice = false;
this->softwareEncoder = false;
}
void EncoderMain::setGraphicsDeviceD3D11(ID3D11Device* device) {
this->device_ = (ID3D11Device*)device;
}
void EncoderMain::setGPUManufacturer(GRAPHICS_CARD gpuDevice) {
if (gpuDevice == GRAPHICS_CARD::NVIDIA) {
this->nvidiaDevice = true;
} else if (gpuDevice == GRAPHICS_CARD::AMD) {
this->amdDevice = true;
}
}
void EncoderMain::setSoftwareEncoder() {
// Need to disable other GPU device when SW encoder is enabled
this->nvidiaDevice = false;
this->amdDevice = false;
this->softwareEncoder = true;
}
void EncoderMain::setClientPcmAudioInput(bool enabled) {
this->clientPcmAudioInputEnabled = true;
}
}
}