forked from NVIDIA/VideoProcessingFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTasks.cpp
More file actions
1649 lines (1381 loc) · 49.6 KB
/
Copy pathTasks.cpp
File metadata and controls
1649 lines (1381 loc) · 49.6 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
/*
* Copyright 2019 NVIDIA Corporation
* Copyright 2021 Videonetics Technology Private Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <chrono>
#include <fstream>
#include <map>
#include <queue>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include "CodecsSupport.hpp"
#include "MemoryInterfaces.hpp"
#include "NppCommon.hpp"
#include "Tasks.hpp"
#include "NvCodecCLIOptions.h"
#include "NvCodecUtils.h"
#include "NvEncoderCuda.h"
#include "FFmpegDemuxer.h"
#include "NvDecoder.h"
extern "C" {
#include <libavutil/pixdesc.h>
}
using namespace VPF;
using namespace std;
using namespace chrono;
constexpr auto TASK_EXEC_SUCCESS = TaskExecStatus::TASK_EXEC_SUCCESS;
constexpr auto TASK_EXEC_FAIL = TaskExecStatus::TASK_EXEC_FAIL;
namespace VPF
{
static auto ThrowOnCudaError = [](CUresult res, int lineNum = -1) {
if (CUDA_SUCCESS != res) {
stringstream ss;
if (lineNum > 0) {
ss << __FILE__ << ":";
ss << lineNum << endl;
}
const char* errName = nullptr;
if (CUDA_SUCCESS != cuGetErrorName(res, &errName)) {
ss << "CUDA error with code " << res << endl;
} else {
ss << "CUDA error: " << errName << endl;
}
const char* errDesc = nullptr;
cuGetErrorString(res, &errDesc);
if (!errDesc) {
ss << "No error string available" << endl;
} else {
ss << errDesc << endl;
}
throw runtime_error(ss.str());
}
};
auto const cuda_stream_sync = [](void* stream) {
cuStreamSynchronize((CUstream)stream);
};
struct NvencEncodeFrame_Impl {
using packet = vector<uint8_t>;
NV_ENC_BUFFER_FORMAT enc_buffer_format;
queue<packet> packetQueue;
vector<uint8_t> lastPacket;
Buffer* pElementaryVideo;
NvEncoderCuda* pEncoderCuda = nullptr;
CUcontext context = nullptr;
CUstream stream = 0;
bool didEncode = false;
bool didFlush = false;
NV_ENC_RECONFIGURE_PARAMS recfg_params;
NV_ENC_INITIALIZE_PARAMS& init_params;
NV_ENC_CONFIG encodeConfig;
std::map<NV_ENC_CAPS, int> capabilities;
NvencEncodeFrame_Impl() = delete;
NvencEncodeFrame_Impl(const NvencEncodeFrame_Impl& other) = delete;
NvencEncodeFrame_Impl& operator=(const NvencEncodeFrame_Impl& other) = delete;
uint32_t GetWidth() const { return pEncoderCuda->GetEncodeWidth(); };
uint32_t GetHeight() const { return pEncoderCuda->GetEncodeHeight(); };
int GetCap(NV_ENC_CAPS cap) const
{
auto it = capabilities.find(cap);
if (it != capabilities.end()) {
return it->second;
}
return -1;
}
NvencEncodeFrame_Impl(NV_ENC_BUFFER_FORMAT format,
NvEncoderClInterface& cli_iface, CUcontext ctx,
CUstream str, int32_t width, int32_t height,
bool verbose)
: init_params(recfg_params.reInitEncodeParams)
{
pElementaryVideo = Buffer::Make(0U);
context = ctx;
stream = str;
pEncoderCuda = new NvEncoderCuda(context, width, height, format);
enc_buffer_format = format;
init_params = {NV_ENC_INITIALIZE_PARAMS_VER};
encodeConfig = {NV_ENC_CONFIG_VER};
init_params.encodeConfig = &encodeConfig;
cli_iface.SetupInitParams(init_params, false, pEncoderCuda->GetApi(),
pEncoderCuda->GetEncoder(), capabilities,
verbose);
pEncoderCuda->CreateEncoder(&init_params);
pEncoderCuda->SetIOCudaStreams((NV_ENC_CUSTREAM_PTR)&stream,
(NV_ENC_CUSTREAM_PTR)&stream);
}
bool Reconfigure(NvEncoderClInterface& cli_iface, bool force_idr,
bool reset_enc, bool verbose)
{
recfg_params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
recfg_params.resetEncoder = reset_enc;
recfg_params.forceIDR = force_idr;
cli_iface.SetupInitParams(init_params, true, pEncoderCuda->GetApi(),
pEncoderCuda->GetEncoder(), capabilities,
verbose);
return pEncoderCuda->Reconfigure(&recfg_params);
}
~NvencEncodeFrame_Impl()
{
pEncoderCuda->DestroyEncoder();
delete pEncoderCuda;
delete pElementaryVideo;
}
};
} // namespace VPF
NvencEncodeFrame* NvencEncodeFrame::Make(CUstream cuStream, CUcontext cuContext,
NvEncoderClInterface& cli_iface,
NV_ENC_BUFFER_FORMAT format,
uint32_t width, uint32_t height,
bool verbose)
{
return new NvencEncodeFrame(cuStream, cuContext, cli_iface, format, width,
height, verbose);
}
bool VPF::NvencEncodeFrame::Reconfigure(NvEncoderClInterface& cli_iface,
bool force_idr, bool reset_enc,
bool verbose)
{
return pImpl->Reconfigure(cli_iface, force_idr, reset_enc, verbose);
}
NvencEncodeFrame::NvencEncodeFrame(CUstream cuStream, CUcontext cuContext,
NvEncoderClInterface& cli_iface,
NV_ENC_BUFFER_FORMAT format, uint32_t width,
uint32_t height, bool verbose)
:
Task("NvencEncodeFrame", NvencEncodeFrame::numInputs,
NvencEncodeFrame::numOutputs, nullptr, nullptr)
{
pImpl = new NvencEncodeFrame_Impl(format, cli_iface, cuContext, cuStream,
width, height, verbose);
}
NvencEncodeFrame::~NvencEncodeFrame() { delete pImpl; };
TaskExecStatus NvencEncodeFrame::Run()
{
NvtxMark tick(GetName());
SetOutput(nullptr, 0U);
try {
auto& pEncoderCuda = pImpl->pEncoderCuda;
auto& didFlush = pImpl->didFlush;
auto& didEncode = pImpl->didEncode;
auto& context = pImpl->context;
auto input = (Surface*)GetInput(0U);
vector<vector<uint8_t>> encPackets;
if (input) {
auto& stream = pImpl->stream;
const NvEncInputFrame* encoderInputFrame =
pEncoderCuda->GetNextInputFrame();
auto width = input->Width(), height = input->Height(),
pitch = input->Pitch();
bool is_resize_needed = (pEncoderCuda->GetEncodeWidth() != width) ||
(pEncoderCuda->GetEncodeHeight() != height);
if (is_resize_needed) {
return TASK_EXEC_FAIL;
} else {
NvEncoderCuda::CopyToDeviceFrame(
context, stream, (void*)input->PlanePtr(), pitch,
(CUdeviceptr)encoderInputFrame->inputPtr,
(int32_t)encoderInputFrame->pitch, pEncoderCuda->GetEncodeWidth(),
pEncoderCuda->GetEncodeHeight(), CU_MEMORYTYPE_DEVICE,
encoderInputFrame->bufferFormat, encoderInputFrame->chromaOffsets,
encoderInputFrame->numChromaPlanes);
}
auto pSEI = (Buffer*)GetInput(2U);
NV_ENC_SEI_PAYLOAD payload = {0};
if (pSEI) {
payload.payloadSize = pSEI->GetRawMemSize();
// Unregistered user data for H.265 and H.264 both;
payload.payloadType = 5;
payload.payload = pSEI->GetDataAs<uint8_t>();
}
auto const seiNumber = pSEI ? 1U : 0U;
auto pPayload = pSEI ? &payload : nullptr;
auto sync = GetInput(1U);
if (sync) {
pEncoderCuda->EncodeFrame(encPackets, nullptr, false, seiNumber,
pPayload);
} else {
pEncoderCuda->EncodeFrame(encPackets, nullptr, true, seiNumber,
pPayload);
}
didEncode = true;
} else if (didEncode && !didFlush) {
// No input after a while means we're flushing;
pEncoderCuda->EndEncode(encPackets);
didFlush = true;
}
/* Push encoded packets into queue;
*/
for (auto& packet : encPackets) {
pImpl->packetQueue.push(packet);
}
/* Then return least recent packet;
*/
pImpl->lastPacket.clear();
if (!pImpl->packetQueue.empty()) {
pImpl->lastPacket = pImpl->packetQueue.front();
pImpl->pElementaryVideo->Update(pImpl->lastPacket.size(),
(void*)pImpl->lastPacket.data());
pImpl->packetQueue.pop();
SetOutput(pImpl->pElementaryVideo, 0U);
}
return TASK_EXEC_SUCCESS;
} catch (exception& e) {
cerr << e.what() << endl;
return TASK_EXEC_FAIL;
}
}
uint32_t NvencEncodeFrame::GetWidth() const { return pImpl->GetWidth(); }
uint32_t NvencEncodeFrame::GetHeight() const { return pImpl->GetHeight(); }
int NvencEncodeFrame::GetCapability(NV_ENC_CAPS cap) const
{
return pImpl->GetCap(cap);
}
namespace VPF
{
struct NvdecDecodeFrame_Impl {
NvDecoder nvDecoder;
Surface* pLastSurface = nullptr;
Buffer* pPacketData = nullptr;
CUstream stream = 0;
CUcontext context = nullptr;
bool didDecode = false;
NvdecDecodeFrame_Impl() = delete;
NvdecDecodeFrame_Impl(const NvdecDecodeFrame_Impl& other) = delete;
NvdecDecodeFrame_Impl& operator=(const NvdecDecodeFrame_Impl& other) = delete;
NvdecDecodeFrame_Impl(CUstream cuStream, CUcontext cuContext,
cudaVideoCodec videoCodec, Pixel_Format format)
: stream(cuStream), context(cuContext),
nvDecoder(cuStream, cuContext, videoCodec)
{
pLastSurface = Surface::Make(format);
pPacketData = Buffer::MakeOwnMem(sizeof(PacketData));
}
~NvdecDecodeFrame_Impl()
{
delete pLastSurface;
delete pPacketData;
}
};
} // namespace VPF
NvdecDecodeFrame* NvdecDecodeFrame::Make(CUstream cuStream, CUcontext cuContext,
cudaVideoCodec videoCodec,
uint32_t decodedFramesPoolSize,
uint32_t coded_width,
uint32_t coded_height,
Pixel_Format format)
{
return new NvdecDecodeFrame(cuStream, cuContext, videoCodec,
decodedFramesPoolSize, coded_width, coded_height,
format);
}
NvdecDecodeFrame::NvdecDecodeFrame(CUstream cuStream, CUcontext cuContext,
cudaVideoCodec videoCodec,
uint32_t decodedFramesPoolSize,
uint32_t coded_width, uint32_t coded_height,
Pixel_Format format)
:
Task("NvdecDecodeFrame", NvdecDecodeFrame::numInputs,
NvdecDecodeFrame::numOutputs, nullptr, nullptr)
{
pImpl = new NvdecDecodeFrame_Impl(cuStream, cuContext, videoCodec, format);
}
NvdecDecodeFrame::~NvdecDecodeFrame()
{
auto lastSurface = pImpl->pLastSurface->PlanePtr();
pImpl->nvDecoder.UnlockSurface(lastSurface);
delete pImpl;
}
TaskExecStatus NvdecDecodeFrame::Run()
{
NvtxMark tick(GetName());
ClearOutputs();
try {
auto& decoder = pImpl->nvDecoder;
auto pEncFrame = (Buffer*)GetInput();
if (!pEncFrame && !pImpl->didDecode) {
/* Empty input given + we've never did decoding means something went
* wrong; Otherwise (no input + we did decode) means we're flushing;
*/
return TASK_EXEC_FAIL;
}
bool isSurfaceReturned = false;
uint64_t timestamp = 0U;
auto pPktData = (Buffer*)GetInput(1U);
if (pPktData) {
auto p_pkt_data = pPktData->GetDataAs<PacketData>();
timestamp = p_pkt_data->pts;
pImpl->pPacketData->Update(sizeof(*p_pkt_data), p_pkt_data);
}
auto const no_eos = nullptr != GetInput(2);
/* This will feed decoder with input timestamp.
* It will also return surface + it's timestamp.
* So timestamp is input + output parameter. */
DecodedFrameContext dec_ctx;
if (no_eos) {
dec_ctx.no_eos = true;
}
{
/* Do this in separate scope because we don't want to measure
* DecodeLockSurface() function run time;
*/
stringstream ss;
ss << "Start decode for frame with pts " << timestamp;
NvtxMark decode_k_off(ss.str().c_str());
}
PacketData in_pkt_data = {0};
if (pPktData) {
auto p_pkt_data = pPktData->GetDataAs<PacketData>();
in_pkt_data = *p_pkt_data;
}
isSurfaceReturned =
decoder.DecodeLockSurface(pEncFrame, in_pkt_data, dec_ctx);
pImpl->didDecode = true;
if (isSurfaceReturned) {
// Unlock last surface because we will use it later;
auto lastSurface = pImpl->pLastSurface->PlanePtr();
decoder.UnlockSurface(lastSurface);
// Update the reconstructed frame data;
auto rawW = decoder.GetWidth();
auto rawH = decoder.GetHeight() + decoder.GetChromaHeight();
auto rawP = decoder.GetDeviceFramePitch();
// Element size for different bit depth;
auto elem_size = 0U;
switch (pImpl->nvDecoder.GetBitDepth()) {
case 8U:
elem_size = sizeof(uint8_t);
break;
case 10U:
elem_size = sizeof(uint16_t);
break;
case 12U:
elem_size = sizeof(uint16_t);
break;
default:
return TASK_EXEC_FAIL;
}
SurfacePlane tmpPlane(rawW, rawH, rawP, elem_size, dec_ctx.mem);
pImpl->pLastSurface->Update(&tmpPlane, 1);
SetOutput(pImpl->pLastSurface, 0U);
// Update the reconstructed frame timestamp;
auto p_packet_data = pImpl->pPacketData->GetDataAs<PacketData>();
memset(p_packet_data, 0, sizeof(*p_packet_data));
*p_packet_data = dec_ctx.out_pdata;
SetOutput(pImpl->pPacketData, 1U);
{
stringstream ss;
ss << "End decode for frame with pts " << dec_ctx.pts;
NvtxMark display_ready(ss.str().c_str());
}
return TASK_EXEC_SUCCESS;
}
/* If we have input and don't get output so far that's fine.
* Otherwise input is NULL and we're flusing so we shall get frame.
*/
return pEncFrame ? TASK_EXEC_SUCCESS : TASK_EXEC_FAIL;
} catch (exception& e) {
cerr << e.what() << endl;
return TASK_EXEC_FAIL;
}
}
void NvdecDecodeFrame::GetDecodedFrameParams(uint32_t& width, uint32_t& height,
uint32_t& elem_size)
{
width = pImpl->nvDecoder.GetWidth();
height = pImpl->nvDecoder.GetHeight();
elem_size = (pImpl->nvDecoder.GetBitDepth() + 7) / 8;
}
uint32_t NvdecDecodeFrame::GetDeviceFramePitch()
{
return uint32_t(pImpl->nvDecoder.GetDeviceFramePitch());
}
int NvdecDecodeFrame::GetCapability(NV_DEC_CAPS cap) const
{
CUVIDDECODECAPS decode_caps;
memset((void*)&decode_caps, 0, sizeof(decode_caps));
decode_caps.eCodecType = pImpl->nvDecoder.GetCodec();
decode_caps.eChromaFormat = pImpl->nvDecoder.GetChromaFormat();
decode_caps.nBitDepthMinus8 = pImpl->nvDecoder.GetBitDepth() - 8;
auto ret = pImpl->nvDecoder._api().cuvidGetDecoderCaps(&decode_caps);
if (CUDA_SUCCESS != ret) {
return -1;
}
switch (cap) {
case BIT_DEPTH_MINUS_8:
return decode_caps.nBitDepthMinus8;
case IS_CODEC_SUPPORTED:
return decode_caps.bIsSupported;
case OUTPUT_FORMAT_MASK:
return decode_caps.nOutputFormatMask;
case MAX_WIDTH:
return decode_caps.nMaxWidth;
case MAX_HEIGHT:
return decode_caps.nMaxHeight;
case MAX_MB_COUNT:
return decode_caps.nMaxMBCount;
case MIN_WIDTH:
return decode_caps.nMinWidth;
case MIN_HEIGHT:
return decode_caps.nMinHeight;
#if CHECK_API_VERSION(11, 0)
case IS_HIST_SUPPORTED:
return decode_caps.bIsHistogramSupported;
case HIST_COUNT_BIT_DEPTH:
return decode_caps.nCounterBitDepth;
case HIST_COUNT_BINS:
return decode_caps.nMaxHistogramBins;
#endif
default:
return -1;
}
}
namespace VPF
{
#define TC_PIXEL_FORMAT_STRINGIFY(s) TC_PIXEL_FORMAT_STRINGIFY_(s)
#define TC_PIXEL_FORMAT_STRINGIFY_(s) #s##sv
#define TC_PIXEL_FORMAT_ENUM_CASE(s) \
case s: \
return TC_PIXEL_FORMAT_STRINGIFY(s)
auto const format_name = [](Pixel_Format format) {
using namespace std::literals::string_view_literals;
switch (format) {
TC_PIXEL_FORMAT_ENUM_CASE(UNDEFINED);
TC_PIXEL_FORMAT_ENUM_CASE(Y);
TC_PIXEL_FORMAT_ENUM_CASE(RGB);
TC_PIXEL_FORMAT_ENUM_CASE(NV12);
TC_PIXEL_FORMAT_ENUM_CASE(YUV420);
TC_PIXEL_FORMAT_ENUM_CASE(YCBCR);
TC_PIXEL_FORMAT_ENUM_CASE(YUV444);
TC_PIXEL_FORMAT_ENUM_CASE(RGB_32F);
TC_PIXEL_FORMAT_ENUM_CASE(RGB_32F_PLANAR);
TC_PIXEL_FORMAT_ENUM_CASE(YUV422);
default:
throw std::runtime_error("Invalid variant for Pixel_Format constructed!");
}
};
static size_t GetElemSize(Pixel_Format format)
{
stringstream ss;
switch (format) {
case RGB_PLANAR:
case YUV444:
case YUV420:
case YUV422:
case YCBCR:
case NV12:
case RGB:
case BGR:
case Y:
return sizeof(uint8_t);
case P10:
case P12:
case YUV420_10bit:
case YUV444_10bit:
return sizeof(uint16_t);
case RGB_32F:
case RGB_32F_PLANAR:
return sizeof(float);
default:
ss << __FUNCTION__;
ss << ": unsupported pixel format: " << format_name(format);
throw invalid_argument(ss.str());
}
}
struct CudaUploadFrame_Impl {
CUstream cuStream;
CUcontext cuContext;
Surface* pSurface = nullptr;
Pixel_Format pixelFormat;
CudaUploadFrame_Impl() = delete;
CudaUploadFrame_Impl(const CudaUploadFrame_Impl& other) = delete;
CudaUploadFrame_Impl& operator=(const CudaUploadFrame_Impl& other) = delete;
CudaUploadFrame_Impl(CUstream stream, CUcontext context, uint32_t _width,
uint32_t _height, Pixel_Format _pix_fmt)
: cuStream(stream), cuContext(context), pixelFormat(_pix_fmt)
{
pSurface = Surface::Make(pixelFormat, _width, _height, context);
}
~CudaUploadFrame_Impl() { delete pSurface; }
};
} // namespace VPF
CudaUploadFrame* CudaUploadFrame::Make(CUstream cuStream, CUcontext cuContext,
uint32_t width, uint32_t height,
Pixel_Format pixelFormat)
{
return new CudaUploadFrame(cuStream, cuContext, width, height, pixelFormat);
}
CudaUploadFrame::CudaUploadFrame(CUstream cuStream, CUcontext cuContext,
uint32_t width, uint32_t height,
Pixel_Format pix_fmt)
:
Task("CudaUploadFrame", CudaUploadFrame::numInputs,
CudaUploadFrame::numOutputs, cuda_stream_sync, (void*)cuStream)
{
pImpl = new CudaUploadFrame_Impl(cuStream, cuContext, width, height, pix_fmt);
}
CudaUploadFrame::~CudaUploadFrame() { delete pImpl; }
TaskExecStatus CudaUploadFrame::Run()
{
NvtxMark tick(GetName());
if (!GetInput()) {
return TASK_EXEC_FAIL;
}
ClearOutputs();
auto stream = pImpl->cuStream;
auto context = pImpl->cuContext;
auto pSurface = pImpl->pSurface;
auto pSrcHost = ((Buffer*)GetInput())->GetDataAs<uint8_t>();
CUDA_MEMCPY2D m = {0};
m.srcMemoryType = CU_MEMORYTYPE_HOST;
m.dstMemoryType = CU_MEMORYTYPE_DEVICE;
for (auto plane = 0; plane < pSurface->NumPlanes(); plane++) {
CudaCtxPush lock(context);
m.srcHost = pSrcHost;
m.srcPitch = pSurface->WidthInBytes(plane);
m.dstDevice = pSurface->PlanePtr(plane);
m.dstPitch = pSurface->Pitch(plane);
m.WidthInBytes = pSurface->WidthInBytes(plane);
m.Height = pSurface->Height(plane);
if (CUDA_SUCCESS != cuMemcpy2DAsync(&m, stream)) {
return TASK_EXEC_FAIL;
}
pSrcHost += m.WidthInBytes * m.Height;
}
SetOutput(pSurface, 0);
return TASK_EXEC_SUCCESS;
}
namespace VPF
{
struct UploadBuffer_Impl {
CUstream cuStream;
CUcontext cuContext;
CudaBuffer* pBuffer = nullptr;
UploadBuffer_Impl() = delete;
UploadBuffer_Impl(const UploadBuffer_Impl& other) = delete;
UploadBuffer_Impl& operator=(const UploadBuffer_Impl& other) = delete;
UploadBuffer_Impl(CUstream stream, CUcontext context, uint32_t elem_size,
uint32_t num_elems)
: cuStream(stream), cuContext(context)
{
pBuffer = CudaBuffer::Make(elem_size, num_elems, context);
}
~UploadBuffer_Impl() { delete pBuffer; }
};
} // namespace VPF
UploadBuffer* UploadBuffer::Make(CUstream cuStream, CUcontext cuContext,
uint32_t elem_size, uint32_t num_elems)
{
return new UploadBuffer(cuStream, cuContext, elem_size, num_elems);
}
UploadBuffer::UploadBuffer(CUstream cuStream, CUcontext cuContext,
uint32_t elem_size, uint32_t num_elems)
:
Task("UploadBuffer", UploadBuffer::numInputs, UploadBuffer::numOutputs,
cuda_stream_sync, (void*)cuStream)
{
pImpl = new UploadBuffer_Impl(cuStream, cuContext, elem_size, num_elems);
}
UploadBuffer::~UploadBuffer() { delete pImpl; }
TaskExecStatus UploadBuffer::Run()
{
NvtxMark tick(GetName());
if (!GetInput()) {
return TASK_EXEC_FAIL;
}
ClearOutputs();
auto stream = pImpl->cuStream;
auto context = pImpl->cuContext;
auto pBuffer = pImpl->pBuffer;
auto pSrcHost = ((Buffer*)GetInput())->GetDataAs<void>();
CudaCtxPush lock(context);
if (CUDA_SUCCESS != cuMemcpyHtoDAsync(pBuffer->GpuMem(),
(const void*)pSrcHost,
pBuffer->GetRawMemSize(), stream)) {
return TASK_EXEC_FAIL;
}
SetOutput(pBuffer, 0);
return TASK_EXEC_SUCCESS;
}
namespace VPF
{
struct CudaDownloadSurface_Impl {
CUstream cuStream;
CUcontext cuContext;
Pixel_Format format;
Buffer* pHostFrame = nullptr;
CudaDownloadSurface_Impl() = delete;
CudaDownloadSurface_Impl(const CudaDownloadSurface_Impl& other) = delete;
CudaDownloadSurface_Impl&
operator=(const CudaDownloadSurface_Impl& other) = delete;
CudaDownloadSurface_Impl(CUstream stream, CUcontext context, uint32_t _width,
uint32_t _height, Pixel_Format _pix_fmt)
: cuStream(stream), cuContext(context), format(_pix_fmt)
{
auto bufferSize = _width * _height * GetElemSize(_pix_fmt);
stringstream ss;
if (YUV420 == _pix_fmt || NV12 == _pix_fmt || YCBCR == _pix_fmt ||
P10 == _pix_fmt || P12 == _pix_fmt || YUV420_10bit == _pix_fmt) {
bufferSize = bufferSize * 3U / 2U;
} else if (RGB == _pix_fmt || RGB_PLANAR == _pix_fmt || BGR == _pix_fmt ||
YUV444 == _pix_fmt || RGB_32F == _pix_fmt ||
RGB_32F_PLANAR == _pix_fmt || YUV444_10bit == _pix_fmt ) {
bufferSize = bufferSize * 3U;
} else if (YUV422 == _pix_fmt) {
bufferSize = bufferSize * 2U;
} else if (Y == _pix_fmt) {
} else {
stringstream ss;
ss << __FUNCTION__ << ": unsupported pixel format: " << _pix_fmt << endl;
throw invalid_argument(ss.str());
}
pHostFrame = Buffer::MakeOwnMem(bufferSize, context);
}
~CudaDownloadSurface_Impl() { delete pHostFrame; }
};
struct DownloadCudaBuffer_Impl {
CUstream cuStream;
CUcontext cuContext;
Buffer* pHostBuffer = nullptr;
DownloadCudaBuffer_Impl() = delete;
DownloadCudaBuffer_Impl(const DownloadCudaBuffer_Impl& other) = delete;
DownloadCudaBuffer_Impl&
operator=(const DownloadCudaBuffer_Impl& other) = delete;
DownloadCudaBuffer_Impl(CUstream stream, CUcontext context,
uint32_t elem_size, uint32_t num_elems)
: cuStream(stream), cuContext(context)
{
pHostBuffer = Buffer::MakeOwnMem(elem_size * num_elems, context);
}
~DownloadCudaBuffer_Impl() { delete pHostBuffer; }
};
} // namespace VPF
CudaDownloadSurface* CudaDownloadSurface::Make(CUstream cuStream,
CUcontext cuContext,
uint32_t width, uint32_t height,
Pixel_Format pixelFormat)
{
return new CudaDownloadSurface(cuStream, cuContext, width, height,
pixelFormat);
}
CudaDownloadSurface::CudaDownloadSurface(CUstream cuStream, CUcontext cuContext,
uint32_t width, uint32_t height,
Pixel_Format pix_fmt)
:
Task("CudaDownloadSurface", CudaDownloadSurface::numInputs,
CudaDownloadSurface::numOutputs, cuda_stream_sync, (void*)cuStream)
{
pImpl =
new CudaDownloadSurface_Impl(cuStream, cuContext, width, height, pix_fmt);
}
CudaDownloadSurface::~CudaDownloadSurface() { delete pImpl; }
TaskExecStatus CudaDownloadSurface::Run()
{
NvtxMark tick(GetName());
if (!GetInput()) {
return TASK_EXEC_FAIL;
}
ClearOutputs();
auto stream = pImpl->cuStream;
auto context = pImpl->cuContext;
auto pSurface = (Surface*)GetInput();
auto pDstHost = ((Buffer*)pImpl->pHostFrame)->GetDataAs<uint8_t>();
CUDA_MEMCPY2D m = {0};
m.srcMemoryType = CU_MEMORYTYPE_DEVICE;
m.dstMemoryType = CU_MEMORYTYPE_HOST;
for (auto plane = 0; plane < pSurface->NumPlanes(); plane++) {
CudaCtxPush lock(context);
m.srcDevice = pSurface->PlanePtr(plane);
m.srcPitch = pSurface->Pitch(plane);
m.dstHost = pDstHost;
m.dstPitch = pSurface->WidthInBytes(plane);
m.WidthInBytes = pSurface->WidthInBytes(plane);
m.Height = pSurface->Height(plane);
auto const ret = cuMemcpy2DAsync(&m, stream);
if (CUDA_SUCCESS != ret) {
return TASK_EXEC_FAIL;
}
pDstHost += m.WidthInBytes * m.Height;
}
SetOutput(pImpl->pHostFrame, 0);
return TASK_EXEC_SUCCESS;
}
DownloadCudaBuffer* DownloadCudaBuffer::Make(CUstream cuStream,
CUcontext cuContext,
uint32_t elem_size,
uint32_t num_elems)
{
return new DownloadCudaBuffer(cuStream, cuContext, elem_size, num_elems);
}
DownloadCudaBuffer::DownloadCudaBuffer(CUstream cuStream, CUcontext cuContext,
uint32_t elem_size, uint32_t num_elems)
: Task("DownloadCudaBuffer", DownloadCudaBuffer::numInputs,
DownloadCudaBuffer::numOutputs, cuda_stream_sync, (void*)cuStream)
{
pImpl =
new DownloadCudaBuffer_Impl(cuStream, cuContext, elem_size, num_elems);
}
DownloadCudaBuffer::~DownloadCudaBuffer() { delete pImpl; }
TaskExecStatus DownloadCudaBuffer::Run()
{
NvtxMark tick(GetName());
if (!GetInput()) {
return TASK_EXEC_FAIL;
}
ClearOutputs();
auto stream = pImpl->cuStream;
auto context = pImpl->cuContext;
auto pCudaBuffer = (CudaBuffer*)GetInput();
auto pDstHost = ((Buffer*)pImpl->pHostBuffer)->GetDataAs<void>();
CudaCtxPush lock(context);
if (CUDA_SUCCESS != cuMemcpyDtoHAsync(pDstHost, pCudaBuffer->GpuMem(),
pCudaBuffer->GetRawMemSize(), stream)) {
return TASK_EXEC_FAIL;
}
SetOutput(pImpl->pHostBuffer, 0);
return TASK_EXEC_SUCCESS;
}
namespace VPF
{
struct DemuxFrame_Impl {
size_t videoBytes = 0U;
Buffer* pElementaryVideo;
Buffer* pMuxingParams;
Buffer* pSei;
Buffer* pPktData;
unique_ptr<FFmpegDemuxer> demuxer;
unique_ptr<DataProvider> d_prov;
DemuxFrame_Impl() = delete;
DemuxFrame_Impl(const DemuxFrame_Impl& other) = delete;
DemuxFrame_Impl& operator=(const DemuxFrame_Impl& other) = delete;
explicit DemuxFrame_Impl(const string& url,
const map<string, string>& ffmpeg_options)
{
demuxer.reset(new FFmpegDemuxer(url.c_str(), ffmpeg_options));
pElementaryVideo = Buffer::MakeOwnMem(0U);
pMuxingParams = Buffer::MakeOwnMem(sizeof(MuxingParams));
pSei = Buffer::MakeOwnMem(0U);
pPktData = Buffer::MakeOwnMem(0U);
}
explicit DemuxFrame_Impl(istream& istr,
const map<string, string>& ffmpeg_options)
{
d_prov.reset(new DataProvider(istr));
demuxer.reset(new FFmpegDemuxer(*d_prov.get(), ffmpeg_options));
pElementaryVideo = Buffer::MakeOwnMem(0U);
pMuxingParams = Buffer::MakeOwnMem(sizeof(MuxingParams));
pSei = Buffer::MakeOwnMem(0U);
pPktData = Buffer::MakeOwnMem(0U);
}
~DemuxFrame_Impl()
{
delete pElementaryVideo;
delete pMuxingParams;
delete pSei;
delete pPktData;
}
};
} // namespace VPF
DemuxFrame* DemuxFrame::Make(istream& i_str, const char** ffmpeg_options,
uint32_t opts_size)
{
return new DemuxFrame(i_str, ffmpeg_options, opts_size);
}
DemuxFrame* DemuxFrame::Make(const char* url, const char** ffmpeg_options,
uint32_t opts_size)
{
return new DemuxFrame(url, ffmpeg_options, opts_size);
}
DemuxFrame::DemuxFrame(istream& i_str, const char** ffmpeg_options,
uint32_t opts_size)
: Task("DemuxFrame", DemuxFrame::numInputs, DemuxFrame::numOutputs)
{
map<string, string> options;
if (0 == opts_size % 2) {
for (auto i = 0; i < opts_size;) {
auto key = string(ffmpeg_options[i]);
i++;
auto value = string(ffmpeg_options[i]);
i++;
options.insert(pair<string, string>(key, value));
}
}
pImpl = new DemuxFrame_Impl(i_str, options);
}
DemuxFrame::DemuxFrame(const char* url, const char** ffmpeg_options,
uint32_t opts_size)
: Task("DemuxFrame", DemuxFrame::numInputs, DemuxFrame::numOutputs)
{
map<string, string> options;
if (0 == opts_size % 2) {
for (auto i = 0; i < opts_size;) {
auto key = string(ffmpeg_options[i]);
i++;
auto value = string(ffmpeg_options[i]);
i++;
options.insert(pair<string, string>(key, value));
}
}
pImpl = new DemuxFrame_Impl(url, options);
}
DemuxFrame::~DemuxFrame() { delete pImpl; }
void DemuxFrame::Flush() { pImpl->demuxer->Flush(); }
int64_t DemuxFrame::TsFromTime(double ts_sec)