File size: 29,108 Bytes
ea55f45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*

* Copyright 2017-2024 NVIDIA Corporation.  All rights reserved.

*

* Please refer to the NVIDIA end user license agreement (EULA) associated

* with this source code for terms and conditions that govern your use of

* this software. Any use, reproduction, disclosure, or distribution of

* this software and related documentation outside the terms of the EULA

* is strictly prohibited.

*

*/

/*

* This sample application was created to accelerate file compression storage applications.

* It does this by splitting the input video into N separate and independent video portions,

* i.e., independent GOPs (Split GOP). After being encoded independently, the compressed video

* portions are then written to file preserving the original order generating a single output

* bitstream.

* More than one encoding session thread can be used to encode the several independent video

* portions. Using more than 1 encoding session threads should allow for speedups when using

* NVIDIA GPUs with more than 1 NVENC.

* The number of portions the input video should be partitioned in is controlled by the CLI

* option "-nf" and the number of encoding session threads "-thread". Note that on systems

* with GeForce GPUs, the number of simultaneous encode sessions allowed on the system is

* restricted to 5 sessions.

* There are separate threads for: 1. reading the RAW input frames from disk; 2. copying the RAW

* frames from RAM to VRAM, encoding and copying the compressed data from VRAM to RAM; 3. writing

* the compressed data to the output file. Additionally, the main thread is only used for

* initialization and to create work queues for the described threads.

*/

#include "AppEncMultiInstance.h"
#include "../Common/AppEncUtils.h"
#include <iomanip>

simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();

inline void gatherEncodedData(std::vector<uint8_t>& encOutBuf, uint8_t* hostOutVidBuf, uint64_t &totalBitStreamSize, std::vector<EncodedFrameData>& hostEncodedData)

{
	EncodedFrameData frameData;
	frameData.offset = 0;
	frameData.data = hostOutVidBuf + totalBitStreamSize;
	frameData.size = static_cast<uint32_t>(encOutBuf.size()); // get size of the bitstream chunk
	std::memcpy(frameData.data, reinterpret_cast<char*>(encOutBuf.data()), encOutBuf.size());
	totalBitStreamSize += frameData.size + frameData.offset; // increment copied size
	hostEncodedData.push_back(std::ref(frameData));
}

void asyncFread(ConcurrentQueue<fileReadData>& freadeQueue, std::atomic<bool>& freadWorking)

{
	fileReadData input;
	while (freadWorking) {
		if (freadeQueue.size()) {
			input = freadeQueue.pop_front(); // always pop front to preserve order of video portions
			safeBuffer* inSafeBuf = input.ioVideoMem->hostInBuf;
			std::ifstream fpIn(input.filePath, std::ifstream::in | std::ifstream::binary); // open input file
			fpIn.seekg(input.offset, fpIn.beg); // get desired video portion
			if (!fpIn) {
				LOG(ERROR) << "Unable to open input file: " << input.filePath;
				break;
			}
			uint64_t nFrameSize = input.threadData->encSession->GetFrameSize();
			ck(cuCtxSetCurrent((CUcontext)input.threadData->encSession->GetDevice()));
			for (uint32_t i = 0; i < input.numFrames; i++)
			{
				int bufIdx = i % bufSize;
				std::unique_lock<std::mutex> inLock{ inSafeBuf[bufIdx].mutex };
				while (!inSafeBuf[bufIdx].readyToEdit) {
					inSafeBuf[bufIdx].condVarReady.wait(inLock); // wait until INPUT buffer is ready to be EDITED
				}
				std::streamsize nRead = fpIn.read(reinterpret_cast<char*>(inSafeBuf[bufIdx].data), nFrameSize).gcount(); // read one frame from desired video portion
				inSafeBuf[bufIdx].readyToEdit = false; // ENCODE step can start
				inSafeBuf[bufIdx].condVarReady.notify_all();
			}
			fpIn.close(); // close file
			if (input.isLast) { // if last end thread
				freadWorking = false;
				break;
			}
		}
	}
}

void asyncEncode(ConcurrentQueue<encodeData>& encodeQueue, std::atomic<bool>& encoderWorking)

{
	encodeData enc;
	while (encoderWorking) {
		if (encodeQueue.size()) {
			enc = encodeQueue.pop_front(); // always pop front to preserve order of video portions
			safeBuffer* inSafeBuf = enc.ioVideoMem->hostInBuf;
			safeBuffer* outSafeBuf = &enc.ioVideoMem->hostOutBuf;
			std::unique_lock<std::mutex> outLock{ outSafeBuf->mutex };
			while (!outSafeBuf->readyToEdit) {
				outSafeBuf->condVarReady.wait(outLock); // wait until OUTPUT buffer is ready to be EDITED
			}
			std::ifstream fpIn(enc.filePath, std::ifstream::in | std::ifstream::binary); // open input file
			fpIn.seekg(enc.offset, fpIn.beg); // get desired video portion
			if (!fpIn) {
				LOG(ERROR) << "Unable to open input file: " << enc.filePath;
				break;
			}
			enc.ioVideoMem->hostEncodedData.clear(); // clear last ouput data
			uint64_t nFrameSize = enc.threadData->encSession->GetFrameSize();
			uint64_t totalBitStreamSize = 0; // need to keep track of the size of each compressed frame
			ck(cuCtxSetCurrent((CUcontext)enc.threadData->encSession->GetDevice()));
			std::vector<NvEncOutputFrame> encOutBuf;
			NV_ENC_PIC_PARAMS nvEncPicParams = { NV_ENC_PIC_PARAMS_VER };
			if (!enc.isSingleThread)
				nvEncPicParams.encodePicFlags = NV_ENC_PIC_FLAG_FORCEIDR; // force IDR frame for the first frame of each video portion

			std::vector <std::unique_lock<std::mutex>> inBufLocks;
			for (uint32_t i = 0; i < bufSize; i++)
				inBufLocks.push_back(std::unique_lock<std::mutex>(inSafeBuf[i].mutex, std::defer_lock));

			for (uint32_t i = 0; i < enc.numFrames; i++)
			{
				int bufIdx = i % bufSize;
				int lastBufIdx = bufIdx == 0 ? (bufSize-1) : (bufIdx-1);
				if(i > 0){
					ck(cuStreamSynchronize(enc.threadData->cuStream->GetInputCUStream())); // make sure the last memcpy is complete
					inSafeBuf[lastBufIdx].readyToEdit = true; // ENCODE step can start
					inSafeBuf[lastBufIdx].condVarReady.notify_all();
					inBufLocks[lastBufIdx].unlock();
				}
				inBufLocks[bufIdx].lock();
				while (inSafeBuf[bufIdx].readyToEdit) {
					inSafeBuf[bufIdx].condVarReady.wait(inBufLocks[bufIdx]); // wait until INPUT buffer is ready to be EDITED
				}
				const NvEncInputFrame* encoderInputFrame = enc.threadData->encSession->GetNextInputFrame();
				NvEncoderCuda::CopyToDeviceFrame((CUcontext)enc.threadData->encSession->GetDevice(),
					(uint8_t*)inSafeBuf[bufIdx].data,
					0,
					(CUdeviceptr)encoderInputFrame->inputPtr,
					encoderInputFrame->pitch,
					enc.threadData->encSession->GetEncodeWidth(),
					enc.threadData->encSession->GetEncodeHeight(),
					CU_MEMORYTYPE_HOST,
					encoderInputFrame->bufferFormat,
					encoderInputFrame->chromaOffsets,
					encoderInputFrame->numChromaPlanes,
					false,
					enc.threadData->cuStream->GetInputCUStream()); // do async frame copy from host to device
				enc.threadData->encSession->EncodeFrame(encOutBuf, i || enc.isSingleThread ? NULL : &nvEncPicParams); // if first frame than use IDR frame
				for (uint32_t j = 0; j < encOutBuf.size(); ++j) { // gather encoded data in output buffer to write to file later
					gatherEncodedData(encOutBuf[j].frame, outSafeBuf->data, totalBitStreamSize, enc.ioVideoMem->hostEncodedData);
				}
			}
			if (!enc.isSingleThread || enc.isLast) {
				enc.threadData->encSession->EndEncode(encOutBuf); // get last compressed frames
				for (uint32_t j = 0; j < encOutBuf.size(); ++j) { // gather encoded data in output buffer to write to file later
					gatherEncodedData(encOutBuf[j].frame, outSafeBuf->data, totalBitStreamSize, enc.ioVideoMem->hostEncodedData);
				}
			}
			outSafeBuf->readyToEdit = false; // OUTPUT buffer is ready to be READ
			outSafeBuf->condVarReady.notify_all();
			int lastBufIdx = (enc.numFrames-1) % bufSize;
			inSafeBuf[lastBufIdx].readyToEdit = true;
			inSafeBuf[lastBufIdx].condVarReady.notify_all();
			if (enc.isLast) { // if last end thread
				encoderWorking = false;
				break;
			}
		}
	}
}

void asyncFwrite(ConcurrentQueue<fileWriteData>& fwriteQueue, std::atomic<bool>& fwriteWorking)

{
	fileWriteData output;
    uint8_t skipIVF = 32;
	while (fwriteWorking) {
		if (fwriteQueue.size()) {
			output = fwriteQueue.pop_front(); // always pop front to preserve order of video portions
			safeBuffer* sB = &output.ioVideoMem->hostOutBuf;
			std::unique_lock<std::mutex> lock{ sB->mutex };
			while (sB->readyToEdit) {
				sB->condVarReady.wait(lock); // wait until OUTPUT buffer is ready to be READ
			}
            bool firstPackage = true;
            for(auto compressedData : output.ioVideoMem->hostEncodedData) {
                if(output.isAV1 && output.vidThreadIdx > 0 && output.isFirst && firstPackage){ // for AV1 we only need an IVF header on the first video portion
                    output.fpOut->write((char*)(compressedData.data + skipIVF), compressedData.size - skipIVF); // write all the compressed data to file skipping IVF header
                    firstPackage = false;
                }
                else{
				    output.fpOut->write((char*)(compressedData.data), compressedData.size); // write all the compressed data to file
                }
            }
			sB->readyToEdit = true;
			sB->condVarReady.notify_all();
			if (output.isLast) { // if last end thread
				output.fpOut->close(); // close file
				std::cout << "Bitstream saved in file " << output.outPath << std::endl;
				fwriteWorking = false;
				break;
			}
		}
	}
}

void ShowEncoderBriefHelp()

{
    std::ostringstream oss;
    oss << "NVIDIA Video Multi-Instance Encoder Sample Application\n";
    oss << "==============================================\n\n";

    oss << "Usage: AppEncMultiInstance -i <input_file> [options]\n\n";

    // Brief table of core arguments
    oss << "Common Arguments:\n";
    oss << std::left << std::setw(25) << "Argument"
        << std::setw(12) << "Type"
        << "Default Value\n";
    oss << std::string(50, '-') << "\n";

    oss << std::left << std::setw(25) << "-i <path>"
        << std::setw(12) << "Required"
        << "N/A\n";
    oss << std::left << std::setw(25) << "-o <path>"
        << std::setw(12) << "Required"
        << "N/A\n";
    oss << std::left << std::setw(25) << "-s <WxH>"
        << std::setw(12) << "Required"
        << "N/A\n";
    oss << std::left << std::setw(25) << "-if <format>"
        << std::setw(12) << "Optional"
        << "iyuv\n";
    oss << std::left << std::setw(25) << "-gpu <n>"
        << std::setw(12) << "Optional"
        << "0\n";
    oss << std::left << std::setw(25) << "-nf <n>"
        << std::setw(12) << "Optional"
        << "120\n";
    oss << std::left << std::setw(25) << "-thread <n>"
        << std::setw(12) << "Optional"
        << "2\n";

    oss << "\nFor detailed help, use -A/--advanced-options\n";
    oss << "To view encoder capabilities, use -ec/--encode-caps\n";
    std::cout << oss.str();
    exit(0);
}

void ShowEncoderDetailedHelp()

{
    std::ostringstream oss;
    oss << "NVIDIA Video Multi-Instance Encoder Sample Application - Detailed Help\n";
    oss << "=======================================================\n\n";

    oss << "Usage: AppEncMultiInstance -i <input_file> [options]\n\n";

    // Full table of all arguments
    oss << "All Arguments:\n";
    oss << std::left << std::setw(25) << "Argument"
        << std::setw(12) << "Type"
        << std::setw(20) << "Default Value"
        << "Example\n";
    oss << std::string(80, '-') << "\n";

    // Required arguments
    oss << std::left << std::setw(25) << "-i <path>"
        << std::setw(12) << "Required"
        << std::setw(20) << "N/A"
        << "-i input.yuv\n";
    oss << std::left << std::setw(25) << "-s <WxH>"
        << std::setw(12) << "Required"
        << std::setw(20) << "N/A"
        << "-s 1920x1080\n";

    // Optional arguments
    oss << std::left << std::setw(25) << "-o <path>"
        << std::setw(12) << "Optional"
        << std::setw(20) << "codec-based"
        << "-o output.h264\n";
    oss << std::left << std::setw(25) << "-if <format>"
        << std::setw(12) << "Optional"
        << std::setw(20) << "iyuv"
        << "-if yuv444\n";
    oss << std::left << std::setw(25) << "-gpu <n>"
        << std::setw(12) << "Optional"
        << std::setw(20) << "0"
        << "-gpu 1\n";
    oss << std::left << std::setw(25) << "-nf <n>"
        << std::setw(12) << "Optional"
        << std::setw(20) << "120"
        << "-nf 240\n";
    oss << std::left << std::setw(25) << "-thread <n>"
        << std::setw(12) << "Optional"
        << std::setw(20) << "2"
        << "-thread 2\n";

    // Detailed descriptions
    oss << "\nDetailed Descriptions:\n";
    oss << "-------------------\n";
    oss << std::left << std::setw(25) << "-i" << ": Input file path\n";
    oss << std::left << std::setw(25) << "-o" << ": Output file path\n";
    oss << std::left << std::setw(25) << "-s" << ": Input resolution in WxH format\n";
    oss << std::left << std::setw(25) << "-if" << ": Input format (iyuv/nv12/yv12/yuv444/p010/yuv444p16/bgra/argb10/ayuv/abgr/abgr10)\n";
    oss << std::left << std::setw(25) << "-gpu" << ": Ordinal of GPU to use\n";
    oss << std::left << std::setw(25) << "-nf" << ": Number of frames per video portion\n";
    oss << std::left << std::setw(25) << "-thread" << ": Number of encoding session threads\n";
    oss << std::left << std::setw(25) << "-h/--help" << ": Print basic usage information\n";
    oss << std::left << std::setw(25) << "-A/--advanced-options" << ": Print detailed usage information\n";
    oss << std::left << std::setw(25) << "-ec/--encode-caps" << ": Print encode capabilities of GPU\n";

    // Important notes
    oss << "\nNotes:\n";
    oss << "------\n";
    oss << "* This sample demonstrates multi-instance encoding for faster compression\n";
    oss << "* Input video is split into N portions (controlled by -nf)\n";
    oss << "* Each portion is encoded independently with separate threads\n";
    oss << "* Encode session limits: 8 concurrent sessions (GeForce) or unlimited (Quadro/Tesla)\n";
    oss << "* Uses separate threads for reading, encoding, and writing\n";
    oss << "* Output preserves original video order\n";
    oss << std::endl;

    oss << NvEncoderInitParam().GetHelpMessage(false, false, true, false, false, false, false, true) << std::endl;
    oss << "\nTo view encode capabilities, use -ec/--encode-caps\n";
    std::cout << oss.str();
    exit(0);
}

void ShowHelpAndExit(const char *szBadOption = NULL)

{
    if (szBadOption)
    {
        std::ostringstream oss;
        oss << "Error parsing \"" << szBadOption << "\"\n";
        oss << "Use -h/--help for basic usage or -A/--advanced-options for detailed information\n";
        throw std::invalid_argument(oss.str());
    }
}

void ParseCommandLine(int argc, char *argv[], uint64_t &nNumVideoPortions, char *szInputFileName, char *szOutputFileName, uint32_t &nWidth, uint32_t &nHeight,

	NV_ENC_BUFFER_FORMAT &eFormat, int &iGpu, int &nThread, NvEncoderInitParam &initParam)

{
    std::ostringstream oss;

    if (argc == 1) {
        std::cout << "No Arguments provided! Please refer to the following for options:\n";
        ShowEncoderBriefHelp();
    }

    for (int i = 1; i < argc; i++)
    {
        if (!_stricmp(argv[i], "-h") || !_stricmp(argv[i], "--help")) {
            ShowEncoderBriefHelp();
        }
        if (!_stricmp(argv[i], "-A") || !_stricmp(argv[i], "--advanced-options")) {
            ShowEncoderDetailedHelp();
        }
        if (!_stricmp(argv[i], "-ec") || !_stricmp(argv[i], "--encode-caps")) {
            ShowEncoderCapability();
        }
        if (!_stricmp(argv[i], "-i"))
        {
            if (++i == argc)
            {
                ShowHelpAndExit("-i");
            }
            sprintf(szInputFileName, "%s", argv[i]);
            continue;
        }
        if (!_stricmp(argv[i], "-s"))
        {
            if (++i == argc || 2 != sscanf(argv[i], "%dx%d", &nWidth, &nHeight))
            {
                ShowHelpAndExit("-s");
            }
            continue;
        }
        if (!_stricmp(argv[i], "-nf"))
        {
            if (++i == argc)
            {
                ShowHelpAndExit("-nf");
            }
            nNumVideoPortions = atoi(argv[i]);
            continue;
        }
        if (!_stricmp(argv[i], "-o"))
        {
            if (++i == argc)
            {
                ShowHelpAndExit("-o");
            }
            sprintf(szOutputFileName, "%s", argv[i]);
            continue;
        }
        std::vector<std::string> vszFileFormatName =
        {
            "iyuv", "nv12", "yv12", "yuv444", "p010", "yuv444p16", "bgra", "argb10", "ayuv", "abgr", "abgr10"
        };
        NV_ENC_BUFFER_FORMAT aFormat[] =
        {
            NV_ENC_BUFFER_FORMAT_IYUV,
            NV_ENC_BUFFER_FORMAT_NV12,
            NV_ENC_BUFFER_FORMAT_YV12,
            NV_ENC_BUFFER_FORMAT_YUV444,
            NV_ENC_BUFFER_FORMAT_YUV420_10BIT,
            NV_ENC_BUFFER_FORMAT_YUV444_10BIT,
            NV_ENC_BUFFER_FORMAT_ARGB,
            NV_ENC_BUFFER_FORMAT_ARGB10,
            NV_ENC_BUFFER_FORMAT_AYUV,
            NV_ENC_BUFFER_FORMAT_ABGR,
            NV_ENC_BUFFER_FORMAT_ABGR10,
        };
        if (!_stricmp(argv[i], "-if"))
        {
            if (++i == argc)
            {
                ShowHelpAndExit("-if");
            }
            auto it = std::find(vszFileFormatName.begin(), vszFileFormatName.end(), argv[i]);
            if (it == vszFileFormatName.end())
            {
                ShowHelpAndExit("-if");
            }
            eFormat = aFormat[it - vszFileFormatName.begin()];
            continue;
        }
        if (!_stricmp(argv[i], "-gpu"))
        {
            if (++i == argc)
            {
                ShowHelpAndExit("-gpu");
            }
            iGpu = atoi(argv[i]);
            continue;
        }
        if (!_stricmp(argv[i], "-thread"))
        {
            if (++i == argc)
            {
                ShowHelpAndExit("-thread");
            }
            nThread = atoi(argv[i]);
            continue;
        }
        // Regard as encoder parameter
        if (argv[i][0] != '-')
        {
            ShowHelpAndExit(argv[i]);
        }
        oss << argv[i] << " ";
        while (i + 1 < argc && argv[i + 1][0] != '-')
        {
            oss << argv[++i] << " ";
        }
    }
    initParam = NvEncoderInitParam(oss.str().c_str());
}

uint64_t getFileSize(const char *szFileName)

{
	struct _stat64 st;
	if (_stat64(szFileName, &st) != 0)
	{
		return 0;
	}
	return st.st_size;
}

uint64_t getNumberOfFrames(const char *szFileName, uint32_t width, uint32_t height, uint64_t frameSize)

{
	struct _stat64 st;
	if (_stat64(szFileName, &st) != 0)
	{
		return 0;
	}
	return (uint64_t)(st.st_size / frameSize);
}

int main(int argc, char **argv)

{
	char szInFilePath[256] = "",
		szOutFilePath[256] = "";
	uint32_t nWidth = 0, nHeight = 0;
	NV_ENC_BUFFER_FORMAT eFormat = NV_ENC_BUFFER_FORMAT_IYUV;
	int iGpu = 0;
	int nThread = 2;
	uint64_t numFramesPerVideoPortion = 120;
	try
	{
		StopWatch globalTime;
		globalTime.Start();

		NvEncoderInitParam encodeCLIOptions;
		ParseCommandLine(argc, argv, numFramesPerVideoPortion, szInFilePath, szOutFilePath, nWidth, nHeight, eFormat,
			iGpu, nThread, encodeCLIOptions);
		if (numFramesPerVideoPortion == 0) { // number of video frames per video portion cannot be 0
			std::cout << "numFramesPerVideoPortion (-nf) should be greater than 0!" << std::endl;
			return 1;
		}
		CheckInputFile(szInFilePath);
		ValidateResolution(nWidth, nHeight);

		if (!*szOutFilePath) {
			sprintf(szOutFilePath, encodeCLIOptions.IsCodecH264() ? "out.h264" : encodeCLIOptions.IsCodecHEVC() ? "out.hevc" : "out.av1");
		}

		ck(cuInit(0));
		int nGpu = 0;
		ck(cuDeviceGetCount(&nGpu));
		if (iGpu < 0 || iGpu >= nGpu) {
			std::cout << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
			return 1;
		}
		CUdevice cuDevice = 0;
		ck(cuDeviceGet(&cuDevice, iGpu));
		char szDeviceName[80];
		ck(cuDeviceGetName(szDeviceName, sizeof(szDeviceName), cuDevice));
		std::cout << "GPU in use: " << szDeviceName << std::endl;

		std::ofstream fpOut(szOutFilePath, std::ios::out | std::ios::binary);
		if (!fpOut) {
			std::ostringstream err;
			err << "Unable to open output file: " << szOutFilePath << std::endl;
			throw std::invalid_argument(err.str());
		}

		NV_ENC_INITIALIZE_PARAMS initializeParams = { NV_ENC_INITIALIZE_PARAMS_VER };
		NV_ENC_CONFIG encodeConfig = { NV_ENC_CONFIG_VER };
		initializeParams.encodeConfig = &encodeConfig;

		CUcontext cuContext;
        ck(NVCODEC_CUDA_CTX_CREATE(&(cuContext), CU_CTX_SCHED_BLOCKING_SYNC, cuDevice)); // Create single CUDA context
		// Create and initialize array of data required for each encoding session thread
		std::vector<ThreadData> vidEncThreads(nThread);
		for (int i = 0; i < nThread; i++) {
			vidEncThreads[i].cuContext = &cuContext; // same CUDA context for every encoding session thread
			vidEncThreads[i].encSession = make_unique<NvEncoderCuda>(cuContext, nWidth, nHeight, eFormat);
			vidEncThreads[i].encSession->CreateDefaultEncoderParams(&initializeParams, encodeCLIOptions.GetEncodeGUID(), encodeCLIOptions.GetPresetGUID(), encodeCLIOptions.GetTuningInfo());
			encodeCLIOptions.SetInitParams(&initializeParams, eFormat);
			vidEncThreads[i].encSession->CreateEncoder(&initializeParams);
			vidEncThreads[i].cuStream.reset(new NvCUStream(cuContext, 1, vidEncThreads[i].encSession)); // each encoding session thread is going to use one cuda stream
		}

		uint64_t frameSize = vidEncThreads[0].encSession->GetFrameSize(); // calculate frame size
		uint64_t numFramesTotal = getNumberOfFrames(szInFilePath, nWidth, nHeight, frameSize); // calculate total number of frames
		uint64_t nNumVideoPortions = 0;
		if (numFramesPerVideoPortion > numFramesTotal) { // the number of frames per video portion should not be larger than the total number of frames
			numFramesPerVideoPortion = numFramesTotal;
			std::cout << "Warning: Number of frames per video portions should be smaller or equal to total number of frames! Adjusting numFramesPerVideoPortion = " << numFramesPerVideoPortion << std::endl;
		}
		// calculations required for cases where the number of frames per video portions is not a multiple of the total number of frames
		if (nThread == 1) {
			std::cout << "SINGLE ENCODE SESSSION MODE - The video encoding pipeline is processed with no GOP splits, i.e., the input video is not split into video portions." << std::endl;
			numFramesPerVideoPortion = 16;
		}
		nNumVideoPortions = (numFramesTotal / numFramesPerVideoPortion) + ((numFramesTotal % numFramesPerVideoPortion) != 0);
		uint64_t sizePerVideoPortion = numFramesPerVideoPortion * frameSize;
		uint64_t numFramesLastVideoPortion = (numFramesTotal % numFramesPerVideoPortion);
		if (!numFramesLastVideoPortion) // if this is 0 it means the last video portion has the same number of frames as the other video portions
			numFramesLastVideoPortion = numFramesPerVideoPortion;
		uint64_t totalMemoryAllocation = (sizePerVideoPortion + 1) * nThread;
		// calculate and report total memory allocation required for the current settings
		std::cout << "Number of video portions: " << nNumVideoPortions << std::endl;
		std::cout << "Number of frames per video portions: " << numFramesPerVideoPortion << std::endl;
		std::cout << "Size of each video portion: " << sizePerVideoPortion / 1000000 << " MB." << std::endl;
		std::cout << "Number of video encoding threads: " << nThread << std::endl;
		std::cout << "Allocating " << totalMemoryAllocation / 1000000 << " MB of memory." << std::endl;
		// Allocate all the required memory for IO
		std::vector<IOEncoderMem> ioVideoMem(nThread);
		for (int i = 0; i < nThread; i++) {
			for (int inBuf = 0; inBuf < bufSize; inBuf++){
				ioVideoMem[i].hostInBuf[inBuf].readyToEdit = true;
				ck(cuMemAllocHost((void**)&ioVideoMem[i].hostInBuf[inBuf].data, frameSize)); // Allocate pinned memory for input RAW frame
			}
			ioVideoMem[i].hostOutBuf.readyToEdit = true;
			ck(cuMemAllocHost((void**)&ioVideoMem[i].hostOutBuf.data, sizePerVideoPortion)); // Allocate pinned memory for output compressed video portions
		}
		// Create fwrite and encode work queues
		ConcurrentQueue<fileWriteData> fwriteQueue;
		std::vector<ConcurrentQueue<encodeData>> encodeQueue(nThread);
		std::vector<ConcurrentQueue<fileReadData>> freadQueue(nThread);

		uint64_t nFrame = 0; // frame counter per video portion
		uint32_t videoPortion = 0; // video portion counter
		uint64_t nTotal = 0; // total frame counter
		float totalProcessingTime = 0;
		while (videoPortion < nNumVideoPortions) // go through every video portion
		{
			nFrame = 0; // reset number of frames per video portion
			for (int i = 0; i < nThread && videoPortion + i < nNumVideoPortions; i++) // split video portions across the several available encoding session threads
			{
				// FREAD thread work queue generation
				fileReadData currFreadData;
				currFreadData.offset = (videoPortion + i) * sizePerVideoPortion;
				currFreadData.filePath = szInFilePath;
				currFreadData.numFrames = static_cast<uint32_t>(((videoPortion + i + 1) == nNumVideoPortions) ? numFramesLastVideoPortion : numFramesPerVideoPortion);
				currFreadData.threadData = &vidEncThreads[i];
				currFreadData.vidPortionNum = videoPortion + i;
				currFreadData.vidThreadIdx = i;
				currFreadData.ioVideoMem = &ioVideoMem[i];
				currFreadData.isLast = (videoPortion + i + 1 == nNumVideoPortions); // check if last to end thread
				currFreadData.isSingleThread = (nThread == 1);
				freadQueue[i].push_back(currFreadData); // queue fread work
				// video ENCODING thread work queue generation
				encodeData currEncData;
				currEncData.offset = (videoPortion + i) * sizePerVideoPortion;
				currEncData.filePath = szInFilePath;
				currEncData.numFrames = static_cast<uint32_t>(((videoPortion + i + 1) == nNumVideoPortions) ? numFramesLastVideoPortion : numFramesPerVideoPortion);
				currEncData.threadData = &vidEncThreads[i];
				currEncData.vidPortionNum = videoPortion + i;
				currEncData.vidThreadIdx = i;
				currEncData.ioVideoMem = &ioVideoMem[i];
				currEncData.isLast = (videoPortion + i + 1 == nNumVideoPortions); // check if last to end thread
				currEncData.isSingleThread = (nThread == 1);
				encodeQueue[i].push_back(currEncData); // queue encode work
				// FWRITE thread work queue generation
				fileWriteData currFwriteData;
				currFwriteData.vidPortionNum = videoPortion + i;
				currFwriteData.fpOut = &fpOut;
				currFwriteData.vidThreadIdx = i;
				currFwriteData.ioVideoMem = &ioVideoMem[i];
                currFwriteData.isFirst = (videoPortion+i == i); // check if first
				currFwriteData.isLast = (videoPortion + i + 1 == nNumVideoPortions); // check if last to end thread
				currFwriteData.outPath = szOutFilePath;
                currFwriteData.isAV1 = encodeCLIOptions.IsCodecAV1();
				fwriteQueue.push_back(currFwriteData); // queue fwrite work
				nFrame += currEncData.numFrames; // increment number of frames
			}
			videoPortion += nThread;
			nTotal += nFrame;
		}

		// Launch fwite and encoding threads
		std::atomic<bool> fwriteWorking(true);
		std::thread fwriteThread = std::thread(&asyncFwrite, std::ref(fwriteQueue), std::ref(fwriteWorking));
		std::atomic<bool> encoderWorking(true);
		std::atomic<bool> freadWorking(true);
		std::vector<std::thread> encodeThread(nThread);
		std::vector<std::thread> freadThread(nThread);
		for (int i = 0; i < nThread; i++){
			encodeThread[i] = std::thread(&asyncEncode, std::ref(encodeQueue[i]), std::ref(encoderWorking));
			freadThread[i] = std::thread(&asyncFread, std::ref(freadQueue[i]), std::ref(freadWorking));
		}

		StopWatch processingTime;
		processingTime.Start();

		for (int i = 0; i < nThread; i++){
			freadThread[i].join();
			encodeThread[i].join();
		}
		fwriteThread.join();

		double gT = globalTime.Stop();
		double pT = processingTime.Stop();
		std::cout << "Total time = " << gT << " seconds, FPS=" << nTotal / gT << " (#frames=" << nTotal << ")" << std::endl;
		std::cout << "Total processing time [fread + H->D memcpy + Encode time + D->H memcpy + fwrite] = " << pT << " seconds, FPS=" << nTotal / pT << " (#frames=" << nTotal << ")" << std::endl;

		for (int i = 0; i < nThread; i++)
			vidEncThreads[i].encSession->DestroyEncoder();
		ck(cuCtxDestroy(cuContext));
	}
	catch (const std::exception &ex)
	{
		std::cout << ex.what();
		return 1;
	}

	return 0;
}