-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.cpp
More file actions
executable file
·1477 lines (1227 loc) · 49 KB
/
Copy pathapp.cpp
File metadata and controls
executable file
·1477 lines (1227 loc) · 49 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 "app.h"
#include <fstream>
#include <vector>
#include <iostream>
#include <chrono>
#include <string>
#include <time.h>
//#include "dynlink_cuda.h" // <cuda.h>
#include "cuda.h"
#include "cuda_runtime.h"
//#include "image_io_util.hpp"
#include "VideoSource.h"
#include "audiocap.h"
#include "srs_librtmp.h"
#include "helper_functions.h"
#include "helper_cuda_drvapi.h"
//#include "dynlink_builtin_types.h" // <builtin_types.h>
#include "cudaProcessFrame.h"
#include "cudaModuleMgr.h"
CUmoduleManager *g_pCudaModule;
CUfunction g_kernelNV12toARGB = 0;
bool g_bUpdateCSC = true;
CUstream g_ReadbackSID = 0, g_KernelSID = 0; //
eColorSpace g_eColorSpace = ITU601;
float g_nHue = 0.0f;
using std::chrono::milliseconds;
using std::chrono::high_resolution_clock;
static unsigned int msecond()
{
timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec*1000 + tv.tv_usec/1000;
}
static void InitializeCriticalSection(CRITICAL_SECTION *pCS)
{
pthread_mutex_init(pCS, NULL);
}
static void EnterCriticalSection(CRITICAL_SECTION *pCS)
{
pthread_mutex_lock(pCS);
}
static void LeaveCriticalSection(CRITICAL_SECTION *pCS)
{
pthread_mutex_unlock(pCS);
}
// This is the CUDA stage for Video Post Processing. Last stage takes care of the NV12 to ARGB
static void cudaPostProcessFrame(CUdeviceptr *ppDecodedFrame, size_t nDecodedPitch, int nBytesPerSample,
CUdeviceptr *ppTextureData, size_t nTexturePitch, uint32 nWidth, uint32 nHeight,
CUmodule cuModNV12toARGB,
CUfunction fpCudaKernel, CUstream streamID)
{
// Upload the Color Space Conversion Matrices
if (g_bUpdateCSC)
{
// CCIR 601/709
float hueColorSpaceMat[9];
setColorSpaceMatrix(g_eColorSpace, hueColorSpaceMat, g_nHue);
updateConstantMemory_drvapi(cuModNV12toARGB, hueColorSpaceMat);
g_bUpdateCSC = false;
}
// TODO: Stage for handling video post processing
// Final Stage: NV12toARGB color space conversion
CUresult eResult;
eResult = cudaLaunchNV12toARGBDrv(*ppDecodedFrame, nDecodedPitch, nBytesPerSample,
*ppTextureData, nTexturePitch,
nWidth, nHeight, fpCudaKernel, streamID);
}
nvstitchResult
app::calibrate(appParams *params)
{
nvstitchResult res = NVSTITCH_SUCCESS;
// Create rig instance
RETURN_NVSTITCH_ERROR(nvstitchCreateVideoRigInstance(¶ms->rig_properties, ¶ms->stitcher_properties.video_rig));
uint32_t frame_count = (uint32_t)params->calib_filenames.size();
uint32_t camera_count = (uint32_t)params->calib_filenames.at(0).size();
// Create calibration instance
nvstitchCalibrationProperties_t calib_prop{};
calib_prop.version = NVSTITCH_VERSION;
calib_prop.frame_count = frame_count;
calib_prop.input_form = nvstitchMediaForm::NVSTITCH_MEDIA_FORM_HOST_BUFFER;
calib_prop.input_format = nvstitchMediaFormat::NVSTITCH_MEDIA_FORMAT_RGBA8UI; //NVSTITCH_MEDIA_FORMAT_RGBA8UI
calib_prop.rig_estimate = params->stitcher_properties.video_rig;
uint32_t input_image_channels = 4;
nvstitchCalibrationInstanceHandle h_calib;
RETURN_NVSTITCH_ERROR(nvstitchCreateCalibrationInstance(calib_prop, &h_calib));
// Read input images for calibration
uint32_t camera_num = params->rig_properties.num_cameras;
const auto calibration_start = high_resolution_clock::now();
/*for (uint32_t frame_index = 0; frame_index < 1; frame_index++) lihengz
{
for (uint32_t cam_index = 0; cam_index < camera_count; cam_index++)
{
std::string image_file_path = params->input_dir_base + params->calib_filenames[frame_index][cam_index];
unsigned char* rgba_bitmap_ptr = nullptr;
int image_width, image_height;
if (getRgbaImage(image_file_path, &rgba_bitmap_ptr, image_width, image_height) == false)
{
std::cout << "Error reading calibration image " << image_file_path << endl;
return NVSTITCH_ERROR_MISSING_FILE;
}
if (nullptr == rgba_bitmap_ptr)
{
std::cout << "Error reading input image:" << image_file_path << std::endl;
return NVSTITCH_ERROR_NULL_POINTER;
}
uint32_t width = params->rig_properties.cameras[cam_index].image_size.x;
uint32_t height = params->rig_properties.cameras[cam_index].image_size.y;
nvstitchPayload_t calib_payload = nvstitchPayload_t{ calib_prop.input_form,{ width, height } };
calib_payload.payload.buffer.ptr = rgba_bitmap_ptr;
calib_payload.payload.buffer.pitch = params->rig_properties.cameras[cam_index].image_size.x * input_image_channels;
RETURN_NVSTITCH_ERROR(nvstitchFeedCalibrationInput(frame_index, h_calib, cam_index, &calib_payload));
}
}*/
// Calibrate
nvstitchVideoRigHandle h_calibrated_video_rig;
RETURN_NVSTITCH_ERROR(nvstitchCalibrate(h_calib, &h_calibrated_video_rig));
// Report calibration time.
auto time = std::chrono::duration_cast<milliseconds>(high_resolution_clock::now() - calibration_start).count();
std::cout << "Calibration Time: " << time << " ms" << std::endl;
// Fetch calibrated rig properties
RETURN_NVSTITCH_ERROR(nvstitchGetVideoRigProperties(h_calibrated_video_rig, ¶ms->calibrated_rig_properties));
// Destroy calibration instance
RETURN_NVSTITCH_ERROR(nvstitchDestroyCalibrationInstance(h_calib));
return NVSTITCH_SUCCESS;
}
//FILE *fp_test = fopen("test.264", "wb"); //lihengz
//! [Stitcher output]
void NVSTITCHCALLBACK onStitchedOutput(unsigned char* buffer, int bufsize, int64_t timestamp,
void* app_data)
{
app *pApp = (app *)app_data;
if (pApp)
pApp->processStitchedOutput(buffer, bufsize, timestamp);
/*if (out_payload && out_payload->payload.frame.ptr)
{
fwrite(out_payload->payload.frame.ptr, 1, out_payload->payload.frame.size, fp_test);
fflush(fp_test);
}*/
}
//! [Stitcher output]
int app::processStitchedOutput(unsigned char* buffer, int bufsize, int64_t timestamp)
{
unsigned int nowMs = msecond();
if (buffer && bufsize>0)
{
if (rtmp_)
{
EnterCriticalSection(&rtmpCriticalSection_);
int ret = srs_h264_write_raw_frames(rtmp_, (char *)buffer,
bufsize, nowMs - startMS, nowMs - startMS); //out_payload->payload.frame.timestamp/10000
if (ret != 0) {
if (srs_h264_is_dvbsp_error(ret)) {
srs_human_trace("ignore drop video error, code=%d", ret);
}
else if (srs_h264_is_duplicated_sps_error(ret)) {
srs_human_trace("ignore duplicated sps, code=%d", ret);
}
else if (srs_h264_is_duplicated_pps_error(ret)) {
srs_human_trace("ignore duplicated pps, code=%d", ret);
}
else {
srs_human_trace("send h264 raw data failed. ret=%d", ret);
//goto rtmp_destroy;
}
}
srs_write_video_ = true;
LeaveCriticalSection(&rtmpCriticalSection_);
}
/*if (mp4VideoTrack_ && m_params->record_flag)
{
if (out_payload->payload.frame.size > 4)
{
uint32_t* p = (uint32_t*)out_payload->payload.frame.ptr;
*p = htonl(out_payload->payload.frame.size - 4);
}
MP4WriteSample(mp4fileHandle_, mp4VideoTrack_, (const uint8_t *)out_payload->payload.frame.ptr, out_payload->payload.frame.size, MP4_INVALID_DURATION, 0, 1);
}*/
if (flvHandle_)
{
int iskeyframe = ((uint8_t *)buffer)[4] == 0x67 || ((uint8_t *)buffer)[4] == 0x65;
flv_write_video_packet(flvHandle_, iskeyframe, (uint8_t *)buffer, bufsize, nowMs - startMS); /// 10000
}
}
return 0;
}
void *stitchAudioProc(void* lpParam)
{
app *pApp=(app*)lpParam;
pApp->stitch_audio_thread();
}
void *stitchProc(void* lpParam)
{
app *pApp=(app*)lpParam;
pApp->stitch_thread();
}
void *stitchOutProc(void* lpParam)
{
app *pApp=(app*)lpParam;
pApp->stitch_out_thread();
}
void *encodeProc(void* lpParam)
{
app *pApp=(app*)lpParam;
pApp->encode_thread();
}
nvstitchResult
app::run(appParams *params)
{
InitializeCriticalSection(&vCriticalSection_);
InitializeCriticalSection(&aCriticalSection_);
InitializeCriticalSection(&rtmpCriticalSection_);
srs_write_video_ = false;
rtmp_ = NULL;
//mp4fileHandle_ = NULL;
//mp4VideoTrack_ = 0;
//mp4AudioTrack_ = 0;
flvHandle_ = NULL;
m_aacEncHandle = NULL;
/*************mp4file******************************/
char filename[255];
if (params->record_flag)
{
time_t rawtime;
struct tm * timeinfo;
char timestr[100];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(timestr, sizeof(timestr), "%Y%m%d-%H%M%S", timeinfo);
sprintf(filename, "%s/Mugo_%s.flv", params->record_path.c_str(), timestr);
flvHandle_= flv_init( filename, 30, params->stitcher_properties.output_payloads->image_size.x, params->stitcher_properties.output_payloads->image_size.y);
/*sprintf(filename, "%s/test.mp4", params->record_path.c_str());
mp4fileHandle_ = MP4Create(filename);//´´½¨mp4Îļþ
if (mp4fileHandle_ == MP4_INVALID_FILE_HANDLE)
{
printf("open file fialed.\n");
}
MP4SetTimeScale(mp4fileHandle_, 90000);
//Ìí¼Óh264 track
mp4VideoTrack_ = MP4AddH264VideoTrack(mp4fileHandle_, 90000, 90000 / 25, 3840, 2160,
0x64,//0x64, //sps[1] AVCProfileIndication
0x00, //sps[2] profile_compat
0x1e,//0x1f, //sps[3] AVCLevelIndication
3); // 4 bytes length before each NAL unit
if (mp4VideoTrack_ == MP4_INVALID_TRACK_ID)
{
printf("add video track failed.\n");
}
//MP4SetVideoProfileLevel(mp4fileHandle_, 0x7F);
//Ìí¼ÓaacÒôƵ
if (params->audio_flag)
{
mp4AudioTrack_ = MP4AddAudioTrack(mp4fileHandle_, 44100, 1024, MP4_MPEG4_AUDIO_TYPE);
if (mp4AudioTrack_ == MP4_INVALID_TRACK_ID)
{
printf("add audio track failed.\n");
}
MP4SetAudioProfileLevel(mp4fileHandle_, 0x2);
}
//MP4Close(mp4fileHandle_);
//mp4fileHandle_=MP4Modify(filename); */
}
/*******rtmp**************************************/
if (!params->rtmp_addr.empty())
{
do {
rtmp_ = srs_rtmp_create(params->rtmp_addr.c_str()); //"rtmp://192.168.1.99/live/1"
if (srs_rtmp_handshake(rtmp_) != 0) {
srs_human_trace("simple handshake failed.");
continue;// break;
}
srs_human_trace("simple handshake success");
if (srs_rtmp_connect_app(rtmp_) != 0) {
srs_human_trace("connect vhost/app failed.");
continue;//break;
}
srs_human_trace("connect vhost/app success");
if (srs_rtmp_publish_stream(rtmp_) != 0) {
srs_human_trace("publish stream failed.");
continue;//break;
}
srs_human_trace("publish stream success");
break;
} while (1);
}
startMS = msecond();
/*********************************************************/
nvstitchResult res = NVSTITCH_SUCCESS;
m_params = params;
// Initialize stitcher instance
//nvssVideoHandle stitcher;
//RETURN_NVSS_ERROR(nvssVideoCreateInstance(&stitcher_props, ¶ms->rig_properties, &stitcher));
const auto stitch_start = high_resolution_clock::now();
// Setup input
// Loop for every video input
s_videoSources.resize(params->rig_properties.num_cameras);
for (int i = 0; i < params->rig_properties.num_cameras; i++)
{
s_videoSources[i] = new VideoSource();
char rtspurl[255];
//if(i==0)
// sprintf(rtspurl, "rtsp://192.168.1.88/av0_0");
//else
sprintf(rtspurl, "rtsp://192.168.1.1%d/av0_0", i+1 ); //params->rig_properties.num_cameras - i
s_videoSources[i]->init(rtspurl, i, this, params->audio_type=="ipcam");
if (params->record_flag)
s_videoSources[i]->setRecordPath(params->record_path);
//s_videoSources[i]->start();
}
if (params->audio_flag )
{
initAACEncode();
if (params->audio_type == "mic")
{
audioCap_ = new AudioCap(0, this);
audioCap_->StartCap();
}
/*else
{
const uint32_t processingSize = 1024;
float stereoSpread = 0.5;
NVSF_CALL(nvsfInitialize());
uint32_t version;
NVSF_CALL(nvsfGetVersion(&version));
NVSF_CALL(nvsfCreateContext(&nvsfContext_, "", 0));
NVSF_CALL(nvsfSetSampleRate(nvsfContext_, params->stitcher_properties.audio_output_format->sampleRate));
NVSF_CALL(nvsfSetOutputFormat(nvsfContext_, NVSTITCH_AUDIO_OUTPUT_STEREO_MIXDOWN));
NVSF_CALL(nvsfSetPullSize(nvsfContext_, processingSize));
NVSF_CALL(nvsfSetAlgorithmParameter(nvsfContext_, NVSF_OUTPUT_GAIN, ¶ms->stitcher_properties.audio_output_gain));
NVSF_CALL(nvsfSetAlgorithmParameter(nvsfContext_, NVSF_STEREO_SPREAD_MIX_COEFFICIENT, &stereoSpread));
uint32_t numInputs = params->audio_rig_properties.num_sources;
inputs_ = new nvsfInputDescriptor_t[numInputs];
inputHandles_ = new nvsfInput_t[numInputs];
for (int i = 0; i < numInputs; i++)
{
inputs_[i].numChannels = 1;
//memset(&inputs_[i].pose, 0, sizeof(nvstitchPose_t));//to modify lihengz
memcpy(&inputs_[i].pose, ¶ms->audio_rig_properties.sources[i].pose, sizeof(nvstitchPose_t));
inputs_[i].type = NVSTITCH_AUDIO_INPUT_TYPE_OMNI;
NVSF_CALL(nvsfAddInput(nvsfContext_, &inputHandles_[i], &inputs_[i]));
}
NVSF_CALL(nvsfCommitConfiguration(nvsfContext_));
outBuffers_[0] = new float[processingSize];
outBuffers_[1] = new float[processingSize];
outPcmBuffer = new short[processingSize*2];
//start stitch audio thread
bStitchAudioThreadExit = FALSE;
pthread_create(&stitch_audio_thread_ptr, NULL, stitchAudioProc, (void*)this);
}*/
}
//====================================================================
// Initialize the CUDA and NVDECODE
printf("__CUDA_API_VERSION=%d\n",__CUDA_API_VERSION);
CUresult cuResult;
typedef void *CUDADRIVER;
CUDADRIVER hHandleDriver = 0;
cuResult = cuInit(0, __CUDA_API_VERSION, hHandleDriver);
cuResult = cuvidInit(0);
CUdevice cuda_device = gpuGetMaxGflopsDeviceIdDRV();
cuDeviceGet(&oDevice_, cuda_device);
cuCtxCreate(&oContext_, CU_CTX_BLOCKING_SYNC, oDevice_);
cuCtxPushCurrent(oContext_);
/*try
{
char FilePath[MAX_PATH + 1] = { 0 };
char *p = NULL;
GetModuleFileNameA(NULL, FilePath, sizeof(FilePath));
p = strrchr(FilePath, '\\');
*p = '\0';
// Initialize CUDA releated Driver API (32-bit or 64-bit), depending the platform running
g_pCudaModule = new CUmoduleManager("NV12ToARGB_drvapi_x64.ptx", FilePath, 2, 2, 2);
}
catch (char const *p_file)
{
// If the CUmoduleManager constructor fails to load the PTX file, it will throw an exception
printf("\n>> CUmoduleManager::Exception! %s not found!\n", p_file);
printf(">> Please rebuild NV12ToARGB_drvapi.cu or re-install this sample.\n");
}*/
g_pCudaModule = new CUmoduleManager("NV12ToARGB_drvapi_x64.ptx", "./", 2, 2, 2);
g_pCudaModule->GetCudaFunction("NV12ToARGB_drvapi", &g_kernelNV12toARGB);
CUresult result;
memset(&stFormat_, 0, sizeof(CUVIDEOFORMAT));
stFormat_.codec = cudaVideoCodec_H264;
stFormat_.chroma_format = cudaVideoChromaFormat_420;
stFormat_.progressive_sequence = true;
stFormat_.coded_width = params->rig_properties.cameras->image_size.x;
stFormat_.coded_height = params->rig_properties.cameras->image_size.y;
stFormat_.display_area.right = params->rig_properties.cameras->image_size.x;
stFormat_.display_area.left = 0;
stFormat_.display_area.bottom = params->rig_properties.cameras->image_size.y;
stFormat_.display_area.top = 0;
CUVIDEOFORMATEX oFormatEx;
memset(&oFormatEx, 0, sizeof(CUVIDEOFORMATEX));
oFormatEx.format = stFormat_;
pFrameQueues.resize(params->rig_properties.num_cameras);
pVideoParsers.resize(params->rig_properties.num_cameras);
pVideoDecoders.resize(params->rig_properties.num_cameras);
for (int i = 0; i < params->rig_properties.num_cameras; i++)
{
// bind the context lock to the CUDA context
result = cuvidCtxLockCreate(&oCtxLock_[i], oContext_);
if (result != CUDA_SUCCESS)
{
printf("cuvidCtxLockCreate failed: %d\n", result);
assert(0);
}
pFrameQueues[i]= new CUVIDFrameQueue(oCtxLock_[i]);
pVideoDecoders[i] = new VideoDecoder(stFormat_, oContext_, cudaVideoCreate_PreferCUVID, oCtxLock_[i]);
pVideoParsers[i] = new VideoParser(pVideoDecoders[i], pFrameQueues[i], &oFormatEx);
s_videoSources[i]->setParser(*pVideoParsers[i], oContext_,0);
}
cuStreamCreate(&g_KernelSID, 0);
cuStreamCreate(&g_ReadbackSID, 0);
cudaMalloc((void **)&pCudaFrame_, (pVideoDecoders[0]->targetWidth() *4+1 ) * pVideoDecoders[0]->targetHeight() );
cudaMalloc((void **)&pCudaFrameNV12_, pVideoDecoders[0]->targetWidth() * pVideoDecoders[0]->targetHeight()*3/2);
cudaMallocHost((void **)&pFrameYUV_, pVideoDecoders[0]->targetWidth() * pVideoDecoders[0]->targetHeight() * 4);
//checkCudaErrors(result = cuMemAllocHost((void **)&pFrameRGBA_, pVideoDecoders[0]->targetWidth() * pVideoDecoders[0]->targetHeight() * 4));
cuCtxPopCurrent(NULL);
initNVEncode();
/******init nvss*****************************************/
if (!params->use_calibrate)
{
int num_gpus;
cudaGetDeviceCount(&num_gpus);
std::vector<int> gpus;
gpus.reserve(num_gpus); //num_gpus
//gpus.push_back(0);
for (int gpu = 0; gpu < num_gpus; ++gpu)
{
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, gpu);
// Require minimum compute 5.2
if (prop.major > 5 || (prop.major == 5 && prop.minor >= 2))
{
gpus.push_back(gpu);
// Multi-GPU not yet supported for mono, so just take the first GPU
//if (!params->stereo_flag)
break;
}
}
nvssVideoStitcherProperties_t stitcher_props{ 0 };
stitcher_props.version = NVSTITCH_VERSION;
stitcher_props.pano_width = m_params->stitcher_properties.output_payloads->image_size.x;
stitcher_props.quality = m_params->stitcher_properties.video_pipeline_options->stitch_quality;
stitcher_props.num_gpus = gpus.size();
stitcher_props.ptr_gpus = gpus.data();
stitcher_props.pipeline = NVSTITCH_STITCHER_PIPELINE_MONO;
stitcher_props.feather_width = 2.0f;
CHECK_NVSS_ERROR(nvssVideoCreateInstance(&stitcher_props, &m_params->calibrated_rig_properties, &stitcher));
calibrated_ = true;
}
//--------------------------------------------------------
//start stitch thread
bStitchThreadExit = FALSE;
pthread_create(&stitch_thread_ptr, NULL, stitchProc, (void*)this);
//start stitchout thread
bStitchOutThreadExit = FALSE;
pthread_create(&stitch_out_thread_ptr, NULL, stitchOutProc, (void*)this);
//start encode thread
//bEncodeThreadExit = FALSE;
//pthread_create(&encode_thread_ptr, NULL, encodeProc, (void*)this);
//--------------------------------------------------------------------
for (int i = 0; i < params->rig_properties.num_cameras; i++)
{
s_videoSources[i]->start();
}
//cv::waitKey();
while ( getchar() != 'q') {
usleep(1000*1000);
}
bStitchOutThreadExit = TRUE;
if (stitch_out_thread_ptr)
{
pthread_join(stitch_out_thread_ptr, NULL);
stitch_out_thread_ptr = 0;
}
for (int i = 0; i < params->rig_properties.num_cameras; i++)
{
delete s_videoSources[i];
}
bStitchThreadExit = TRUE;
if (stitch_thread_ptr)
{
pthread_join(stitch_thread_ptr, NULL);
stitch_thread_ptr = 0;
}
bStitchAudioThreadExit = TRUE;
if (stitch_audio_thread_ptr)
{
pthread_join(stitch_audio_thread_ptr, NULL);
stitch_audio_thread_ptr = 0;
}
bEncodeThreadExit = TRUE;
if (encode_thread_ptr)
{
pthread_join(encode_thread_ptr, NULL);
encode_thread_ptr = 0;
}
ReleaseIOBuffers();
if (m_pNvHWEncoder)
{
NVENCSTATUS nvStatus = m_pNvHWEncoder->NvEncDestroyEncoder();
delete m_pNvHWEncoder;
}
if (audioCap_)
{
delete audioCap_;
}
if(m_aacEncHandle)
aacEncClose(&m_aacEncHandle);
if (nvsfContext_)
{
NVSF_CALL(nvsfDestroyContext(nvsfContext_));
NVSF_CALL(nvsfFinalize());
}
delete[] outBuffers_[0];
delete[] outBuffers_[1];
delete[] outPcmBuffer;
delete[] inputHandles_;
delete[] inputs_;
for (int i = 0; i < params->rig_properties.num_cameras; i++)
{
delete pVideoParsers[i];
delete pVideoDecoders[i];
delete pFrameQueues[i];
}
/*if (oCtxLock_)
{
checkCudaErrors(cuvidCtxLockDestroy(oCtxLock_));
}
if (oContext_ )
{
checkCudaErrors(cuCtxDestroy(oContext_));
oContext_ = NULL;
}*/
// Report stitch time
auto time = std::chrono::duration_cast<milliseconds>(high_resolution_clock::now() - stitch_start).count();
std::cout << "Stitch Time: " << time << " ms" << std::endl;
// Clean up
RETURN_NVSS_ERROR(nvssVideoDestroyInstance(stitcher));
//if(mp4fileHandle_)
// MP4Close(mp4fileHandle_);
//MP4Optimize(filename);
if (flvHandle_)
flv_write_trailer(flvHandle_);
if(rtmp_)
srs_rtmp_destroy(rtmp_);
return NVSTITCH_SUCCESS;
}
void app::stitch_thread()
{
char *updateFrame = new char[m_params->rig_properties.num_cameras];
memset(updateFrame, 0, sizeof(char)*m_params->rig_properties.num_cameras);
int updateFrameNum = 0;
//-------------------------calibrate-----------------------------------------------
nvstitchCalibrationProperties_t calib_prop{};
nvstitchCalibrationInstanceHandle h_calib;
if (m_params->use_calibrate)
{
// Create rig instance
CHECK_NVSS_ERROR(nvstitchCreateVideoRigInstance(&m_params->rig_properties, &m_params->stitcher_properties.video_rig));
uint32_t frame_count = (uint32_t)m_params->calib_filenames.size();
// Create calibration instance
calib_prop.version = NVSTITCH_VERSION;
calib_prop.frame_count = 1;// frame_count;
calib_prop.input_form = nvstitchMediaForm::NVSTITCH_MEDIA_FORM_HOST_BUFFER;// NVSTITCH_MEDIA_FORM_DEVICE_BUFFER; // NVSTITCH_MEDIA_FORM_HOST_BUFFER;
calib_prop.input_format = nvstitchMediaFormat::NVSTITCH_MEDIA_FORMAT_RGBA8UI; //NVSTITCH_MEDIA_FORMAT_RGBA8UI
calib_prop.rig_estimate = m_params->stitcher_properties.video_rig;
uint32_t input_image_channels = 4;
CHECK_NVSS_ERROR(nvstitchCreateCalibrationInstance(calib_prop, &h_calib));
}
//=================================================================================
while (!bStitchThreadExit)
{
for (int i = 0; i < m_params->rig_properties.num_cameras; i++)
{
CUVIDPARSERDISPINFO oDisplayInfo;
if (!updateFrame[i] && pFrameQueues[i]->dequeue(&oDisplayInfo))
{
//CCtxAutoLock lck(oCtxLock_[i]);
// Push the current CUDA context (only if we are using CUDA decoding path)
//CUresult result = cuCtxPushCurrent(oContext_);
CUdeviceptr pDecodedFrame;
CUVIDPROCPARAMS oVideoProcessingParameters;
memset(&oVideoProcessingParameters, 0, sizeof(CUVIDPROCPARAMS));
oVideoProcessingParameters.progressive_frame = oDisplayInfo.progressive_frame;
oVideoProcessingParameters.second_field = 0;
oVideoProcessingParameters.top_field_first = oDisplayInfo.top_field_first;
oVideoProcessingParameters.unpaired_field = (oDisplayInfo.progressive_frame == 1 || oDisplayInfo.repeat_first_field <= 1);
unsigned int nDecodedPitch = 0;
// map decoded video frame to CUDA surfae
if (pVideoDecoders[i]->mapFrame(oDisplayInfo.picture_index, &pDecodedFrame, &nDecodedPitch, &oVideoProcessingParameters) != CUDA_SUCCESS)
{
// release the frame, so it can be re-used in decoder
pFrameQueues[i]->releaseFrame(&oDisplayInfo);
std::cout << "Error mapFrame pVideoDecoders" << std::endl;
// Detach from the Current thread
//checkCudaErrors(cuCtxPopCurrent(NULL));
continue;
}
if (!calibrated_)
{
cuvidCtxLock(oCtxLock_[i], 0);
cudaPostProcessFrame(&pDecodedFrame, nDecodedPitch, pVideoDecoders[i]->GetNumBytesPerSample(), &pCudaFrame_,
pVideoDecoders[i]->targetWidth() * 4, pVideoDecoders[i]->targetWidth(), pVideoDecoders[i]->targetHeight(),
g_pCudaModule->getModule(), g_kernelNV12toARGB, g_KernelSID); //g_pCudaModule->getModule()
/*CUresult result = cuMemcpyDtoHAsync(pFrameYUV_, pCudaFrame_, (pVideoDecoders[i]->targetWidth() * pVideoDecoders[i]->targetHeight() * 4), g_ReadbackSID);
if (result != CUDA_SUCCESS)
{
printf("cuMemAllocHost returned %d\n", (int)result);
checkCudaErrors(result);
}
cudaStreamSynchronize(g_ReadbackSID);*/
if (cudaMemcpy2D(pFrameYUV_, pVideoDecoders[i]->targetWidth() *4,
(void*)pCudaFrame_, pVideoDecoders[i]->targetWidth() * 4,
pVideoDecoders[i]->targetWidth()*4, pVideoDecoders[i]->targetHeight(),
cudaMemcpyDeviceToHost) != cudaSuccess)
{
std::cout << "Error copying output stacked panorama from CUDA buffer" << std::endl;
}
cuvidCtxUnlock(oCtxLock_[i], 0);
/******test to del***********/
char filename[256];
sprintf(filename, "./img/%d.bmp", i);
//putRgbaImage(filename, pFrameYUV_, pVideoDecoders[i]->targetWidth(), pVideoDecoders[i]->targetHeight()); lihengz
//----------------------------
nvstitchPayload_t calib_payload = nvstitchPayload_t{ calib_prop.input_form,{(uint32_t)pVideoDecoders[i]->targetWidth(), (uint32_t)pVideoDecoders[i]->targetHeight() } };
calib_payload.payload.buffer.ptr = (void*)pFrameYUV_;
calib_payload.payload.buffer.pitch = pVideoDecoders[i]->targetWidth() * 4;
CHECK_NVSS_ERROR(nvstitchFeedCalibrationInput(0, h_calib, i, &calib_payload));
}
//checkCudaErrors(cuCtxPopCurrent(NULL));
//feedVideoData(i, (void*)pFrameYUV_, pVideoDecoders[i]->targetWidth() * 4, oDisplayInfo.timestamp);
else
{
nvstitchImageBuffer_t input_image;
CHECK_NVSS_ERROR(nvssVideoGetInputBuffer(stitcher, i, &input_image));
CUstream_st *inStreamID;
CHECK_NVSS_ERROR(nvssVideoGetInputStream(stitcher, i, &inStreamID));
//cudaStreamSynchronize(inStreamID);
cuvidCtxLock(oCtxLock_[i], 0);
if (nDecodedPitch < pVideoDecoders[i]->targetWidth())
{
std::cout << "Error nDecodedPitch:" << nDecodedPitch << std::endl;
}
cudaPostProcessFrame(&pDecodedFrame, nDecodedPitch, pVideoDecoders[i]->GetNumBytesPerSample(),
(CUdeviceptr*)&input_image.dev_ptr,
pVideoDecoders[i]->targetWidth() * 4, pVideoDecoders[i]->targetWidth(), pVideoDecoders[i]->targetHeight(),
g_pCudaModule->getModule(), g_kernelNV12toARGB, g_KernelSID);
//cudaStreamSynchronize(g_KernelSID);
/*CUresult cudaerr;
if (cudaMemcpy((void *)pCudaFrameNV12_, (void *)pDecodedFrame, pVideoDecoders[i]->targetWidth()*pVideoDecoders[i]->targetHeight() * 3 / 2,
cudaMemcpyDeviceToDevice) != cudaSuccess)
{
std::cout << "Error copying output stacked panorama from CUDA buffer" << std::endl;
}
cudaPostProcessFrame(&pCudaFrameNV12_, nDecodedPitch, pVideoDecoders[i]->GetNumBytesPerSample(), &pCudaFrame_,
pVideoDecoders[i]->targetWidth()*4 , pVideoDecoders[i]->targetWidth(), pVideoDecoders[i]->targetHeight(),
g_pCudaModule->getModule(), g_kernelNV12toARGB, g_KernelSID);
cuStreamSynchronize(g_KernelSID);
if ((cudaerr = cudaMemcpy2D(input_image.dev_ptr, input_image.pitch,
(void *)pCudaFrame_, pVideoDecoders[i]->targetWidth()*4,
pVideoDecoders[i]->targetWidth()*4, pVideoDecoders[i]->targetHeight(),
cudaMemcpyDeviceToDevice)) != cudaSuccess)
{
std::cout << "Error copying RGBA image bitmap between CUDA buffer ,err="<< cudaGetErrorString(cudaerr) << std::endl;
cuvidCtxUnlock(oCtxLock_[i], 0);
pVideoDecoders[i]->unmapFrame(pDecodedFrame);
pFrameQueues[i]->releaseFrame(&oDisplayInfo);
continue;
//return NVSTITCH_ERROR_GENERAL;
}*/
/*if (cudaMemcpy(pFrameYUV_, (void *)pDecodedFrame, pVideoDecoders[i]->targetWidth()*pVideoDecoders[i]->targetHeight()*3/2,
cudaMemcpyDeviceToHost) != cudaSuccess)
{
std::cout << "Error copying output stacked panorama from CUDA buffer" << std::endl;
}*/
cuvidCtxUnlock(oCtxLock_[i], 0);
/*YCrCb2RGBConver(pFrameYUV_, pFrameYUV_ + pVideoDecoders[i]->targetWidth()*pVideoDecoders[i]->targetHeight(),
pVideoDecoders[i]->targetWidth(), pVideoDecoders[i]->targetWidth() / 2,
pFrameRGBA_, pVideoDecoders[i]->targetWidth(), pVideoDecoders[i]->targetHeight(), 4);*/
}
// unmap video frame
// unmapFrame() synchronizes with the VideoDecode API (ensures the frame has finished decoding)
pVideoDecoders[i]->unmapFrame(pDecodedFrame);
// Detach from the Current thread
//checkCudaErrors(cuCtxPopCurrent(NULL));
// release the frame, so it can be re-used in decoder
pFrameQueues[i]->releaseFrame(&oDisplayInfo);
updateFrame[i] = 1;
updateFrameNum++;
//i++;
}//end if
} //end for
if(updateFrameNum == m_params->rig_properties.num_cameras)
{
if (!calibrated_)
{
int num_gpus;
cudaGetDeviceCount(&num_gpus);
std::vector<int> gpus;
gpus.reserve(num_gpus); //num_gpus
//gpus.push_back(0);
for (int gpu = 0; gpu < num_gpus; ++gpu)
{
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, gpu);
// Require minimum compute 5.2
if (prop.major > 5 || (prop.major == 5 && prop.minor >= 2))
{
gpus.push_back(gpu);
// Multi-GPU not yet supported for mono, so just take the first GPU
//if (!params->stereo_flag)
break;
}
}
nvssVideoStitcherProperties_t stitcher_props{ 0 };
stitcher_props.version = NVSTITCH_VERSION;
stitcher_props.pano_width = m_params->stitcher_properties.output_payloads->image_size.x;
stitcher_props.quality = m_params->stitcher_properties.video_pipeline_options->stitch_quality;
stitcher_props.num_gpus = gpus.size();
stitcher_props.ptr_gpus = gpus.data();
/*if (params->stereo_flag)
{
stitcher_props.pipeline = NVSTITCH_STITCHER_PIPELINE_STEREO;
stitcher_props.stereo_ipd = 6.3f;
}
else */
{
stitcher_props.pipeline = NVSTITCH_STITCHER_PIPELINE_MONO;
stitcher_props.feather_width = 2.0f;
}
// Calibrate
nvstitchVideoRigHandle h_calibrated_video_rig;
if (nvstitchCalibrate(h_calib, &h_calibrated_video_rig) == NVSTITCH_SUCCESS)
{
// Fetch calibrated rig properties
if (nvstitchGetVideoRigProperties(h_calibrated_video_rig, &m_params->calibrated_rig_properties) == NVSTITCH_SUCCESS)
{
printf("======calibrate success=========\n");
CHECK_NVSS_ERROR(nvssVideoCreateInstance(&stitcher_props, &m_params->calibrated_rig_properties, &stitcher));
}
}
if (stitcher == NULL)
{
printf("======calibrate fail==========\n");
CHECK_NVSS_ERROR(nvssVideoCreateInstance(&stitcher_props, &m_params->calibrated_rig_properties, &stitcher));
}
// Destroy calibration instance
CHECK_NVSS_ERROR(nvstitchDestroyCalibrationInstance(h_calib));
//clear frame queue
for (int i = 0; i < m_params->rig_properties.num_cameras; i++)
{
CUVIDPARSERDISPINFO oDisplayInfo;
while (pFrameQueues[i]->dequeue(&oDisplayInfo))
{
pFrameQueues[i]->releaseFrame(&oDisplayInfo);
}
}
//start stitchout thread
//bStitchOutThreadExit = FALSE;
//pthread_create(&stitch_out_thread_ptr, NULL, stitchOutProc, (void*)this);
calibrated_ = true;
}
else
{
/*for (int i = 0; i < m_params->rig_properties.num_cameras; i++)
{
CUstream_st *inStreamID;
CHECK_NVSS_ERROR(nvssVideoGetInputStream(stitcher, i, &inStreamID));
cudaStreamSynchronize(inStreamID);
}*/
// Stitch
nvstitchResult pRes = nvssVideoStitch(stitcher);
pthread_cond_signal(&has_stitch);
//if(pRes == NVSTITCH_SUCCESS)
// getStitchedOut();
//else
// std::cerr << "Error at line " << __LINE__ << ": " << nvssVideoGetErrorString(pRes) << std::endl;
}
updateFrameNum = 0;
memset(updateFrame, 0, sizeof(char)*m_params->rig_properties.num_cameras);
}
}
}
nvstitchResult app::getStitchedOut()
{
// Synchronize CUDA before snapping start time
//cudaStreamSynchronize(cudaStreamDefault);
CUstream_st *outStreamID;
RETURN_NVSS_ERROR(nvssVideoGetOutputStream(stitcher, NVSTITCH_EYE_MONO, &outStreamID));
// Synchronize CUDA before snapping end time
cudaStreamSynchronize(outStreamID);
//unsigned char *out_stacked = nullptr;
nvstitchImageBuffer_t output_image;
RETURN_NVSS_ERROR(nvssVideoGetOutputBuffer(stitcher, NVSTITCH_EYE_MONO, &output_image));
//encode
EncodeBuffer *pEncodeBuffer = m_EncodeBufferQueue.GetAvailable();
if (!pEncodeBuffer)
{
std::cout << "Error m_EncodeBufferQueue.GetAvailable" << std::endl;
return NVSTITCH_ERROR_GENERAL;
}
if (cudaMemcpy2D((void*)pEncodeBuffer->stInputBfr.pNV12devPtr, pEncodeBuffer->stInputBfr.uNV12Stride,
output_image.dev_ptr, output_image.pitch,
output_image.row_bytes, output_image.height,
cudaMemcpyDeviceToDevice) != cudaSuccess)
{
std::cout << "Error copying RGBA image bitmap to CUDA buffer" << std::endl;
m_EncodeBufferQueue.incPending();
return NVSTITCH_ERROR_GENERAL;
}
NVENCSTATUS nvStatus = m_pNvHWEncoder->NvEncMapInputResource(pEncodeBuffer->stInputBfr.nvRegisteredResource, &pEncodeBuffer->stInputBfr.hInputSurface);
if (nvStatus != NV_ENC_SUCCESS)
{
PRINTERR("Failed to Map input buffer %p\n", pEncodeBuffer->stInputBfr.hInputSurface);
return NVSTITCH_ERROR_GENERAL;
}
m_pNvHWEncoder->NvEncEncodeFrame(pEncodeBuffer, NULL, m_stEncoderInput.width, m_stEncoderInput.height);
m_EncodeBufferQueue.incPending();
return NVSTITCH_SUCCESS;
}
void app::stitch_out_thread() //not use
{
// Synchronize CUDA before snapping start time
//cudaStreamSynchronize(cudaStreamDefault);