codekingpro commited on
Commit
ea55f45
·
verified ·
1 Parent(s): 451ef6a

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. video_codec_sdk/Deprecation_Notices.pdf +0 -0
  3. video_codec_sdk/Doc/FFMPEG_with_NVIDIA_GPU.pdf +0 -0
  4. video_codec_sdk/Doc/NVDEC_Application_Note.pdf +0 -0
  5. video_codec_sdk/Doc/NVDEC_VideoDecoder_API_ProgGuide.pdf +3 -0
  6. video_codec_sdk/Doc/NVENC_Application_Note.pdf +0 -0
  7. video_codec_sdk/Doc/NVENC_Preset_Migration_Guide.pdf +3 -0
  8. video_codec_sdk/Doc/NVENC_VideoEncoder_API_ProgGuide.pdf +3 -0
  9. video_codec_sdk/Interface/cuviddec.h +1209 -0
  10. video_codec_sdk/Interface/nvEncodeAPI.h +0 -0
  11. video_codec_sdk/Interface/nvcuvid.h +554 -0
  12. video_codec_sdk/Lib/linux/stubs/aarch64/libnvcuvid.so +0 -0
  13. video_codec_sdk/Lib/linux/stubs/aarch64/libnvidia-encode.so +0 -0
  14. video_codec_sdk/Lib/linux/stubs/x86_64/libnvcuvid.so +0 -0
  15. video_codec_sdk/Lib/linux/stubs/x86_64/libnvidia-encode.so +0 -0
  16. video_codec_sdk/Lib/win/Win32/nvcuvid.lib +0 -0
  17. video_codec_sdk/Lib/win/Win32/nvencodeapi.lib +0 -0
  18. video_codec_sdk/Lib/win/x64/nvcuvid.lib +0 -0
  19. video_codec_sdk/Lib/win/x64/nvencodeapi.lib +0 -0
  20. video_codec_sdk/License.pdf +0 -0
  21. video_codec_sdk/NOTICES.txt +167 -0
  22. video_codec_sdk/Read_Me.pdf +3 -0
  23. video_codec_sdk/Samples/AppDecode/AppDec/AppDec.cpp +423 -0
  24. video_codec_sdk/Samples/AppDecode/AppDec/CMakeLists.txt +105 -0
  25. video_codec_sdk/Samples/AppDecode/AppDecD3D/AppDecD3D.cpp +163 -0
  26. video_codec_sdk/Samples/AppDecode/AppDecD3D/CMakeLists.txt +136 -0
  27. video_codec_sdk/Samples/AppDecode/AppDecD3D/FramePresenterD3D.h +139 -0
  28. video_codec_sdk/Samples/AppDecode/AppDecD3D/FramePresenterD3D11.h +236 -0
  29. video_codec_sdk/Samples/AppDecode/AppDecD3D/FramePresenterD3D9.h +226 -0
  30. video_codec_sdk/Samples/AppDecode/AppDecGL/AppDecGL.cpp +145 -0
  31. video_codec_sdk/Samples/AppDecode/AppDecGL/CMakeLists.txt +199 -0
  32. video_codec_sdk/Samples/AppDecode/AppDecGL/FramePresenter.h +44 -0
  33. video_codec_sdk/Samples/AppDecode/AppDecGL/FramePresenterGLUT.h +357 -0
  34. video_codec_sdk/Samples/AppDecode/AppDecGL/FramePresenterGLX.cpp +360 -0
  35. video_codec_sdk/Samples/AppDecode/AppDecGL/FramePresenterGLX.h +125 -0
  36. video_codec_sdk/Samples/AppDecode/AppDecImageProvider/AppDecImageProvider.cpp +498 -0
  37. video_codec_sdk/Samples/AppDecode/AppDecImageProvider/CMakeLists.txt +129 -0
  38. video_codec_sdk/Samples/AppDecode/AppDecLowLatency/AppDecLowLatency.cpp +113 -0
  39. video_codec_sdk/Samples/AppDecode/AppDecLowLatency/CMakeLists.txt +112 -0
  40. video_codec_sdk/Samples/AppDecode/AppDecMem/AppDecMem.cpp +123 -0
  41. video_codec_sdk/Samples/AppDecode/AppDecMem/CMakeLists.txt +114 -0
  42. video_codec_sdk/Samples/AppDecode/AppDecMultiFiles/AppDecMultiFiles.cpp +452 -0
  43. video_codec_sdk/Samples/AppDecode/AppDecMultiFiles/CMakeLists.txt +118 -0
  44. video_codec_sdk/Samples/AppDecode/AppDecMultiInput/AppDecMultiInput.cpp +234 -0
  45. video_codec_sdk/Samples/AppDecode/AppDecMultiInput/CMakeLists.txt +125 -0
  46. video_codec_sdk/Samples/AppDecode/AppDecMultiInput/Image.cu +87 -0
  47. video_codec_sdk/Samples/AppDecode/AppDecPerf/AppDecPerf.cpp +451 -0
  48. video_codec_sdk/Samples/AppDecode/AppDecPerf/CMakeLists.txt +116 -0
  49. video_codec_sdk/Samples/AppDecode/Common/AppDecUtils.h +385 -0
  50. video_codec_sdk/Samples/AppEncode/AppEncCuda/AppEncCuda.cpp +727 -0
.gitattributes CHANGED
@@ -6341,3 +6341,7 @@ sqlite_gui/translations/qtbase_pl.qm filter=lfs diff=lfs merge=lfs -text
6341
  sqlite_gui/translations/qtbase_ru.qm filter=lfs diff=lfs merge=lfs -text
6342
  sqlite_gui/translations/qtbase_uk.qm filter=lfs diff=lfs merge=lfs -text
6343
  sqlite_gui/translations/qtxmlpatterns_cs.qm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
6341
  sqlite_gui/translations/qtbase_ru.qm filter=lfs diff=lfs merge=lfs -text
6342
  sqlite_gui/translations/qtbase_uk.qm filter=lfs diff=lfs merge=lfs -text
6343
  sqlite_gui/translations/qtxmlpatterns_cs.qm filter=lfs diff=lfs merge=lfs -text
6344
+ video_codec_sdk/Doc/NVDEC_VideoDecoder_API_ProgGuide.pdf filter=lfs diff=lfs merge=lfs -text
6345
+ video_codec_sdk/Doc/NVENC_Preset_Migration_Guide.pdf filter=lfs diff=lfs merge=lfs -text
6346
+ video_codec_sdk/Doc/NVENC_VideoEncoder_API_ProgGuide.pdf filter=lfs diff=lfs merge=lfs -text
6347
+ video_codec_sdk/Read_Me.pdf filter=lfs diff=lfs merge=lfs -text
video_codec_sdk/Deprecation_Notices.pdf ADDED
Binary file (34.3 kB). View file
 
video_codec_sdk/Doc/FFMPEG_with_NVIDIA_GPU.pdf ADDED
Binary file (88.7 kB). View file
 
video_codec_sdk/Doc/NVDEC_Application_Note.pdf ADDED
Binary file (53.8 kB). View file
 
video_codec_sdk/Doc/NVDEC_VideoDecoder_API_ProgGuide.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eda5d74f4be28f0a46b670a6423e102c69e9830f27d5aeb0b0382d4ec7391332
3
+ size 179138
video_codec_sdk/Doc/NVENC_Application_Note.pdf ADDED
Binary file (65.4 kB). View file
 
video_codec_sdk/Doc/NVENC_Preset_Migration_Guide.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:573b70ddfecd1b3be50ea98348f8aa7414535ce090b579b6bedd88fded4b68a4
3
+ size 198767
video_codec_sdk/Doc/NVENC_VideoEncoder_API_ProgGuide.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83952743e36e90afbd50ee92aa17fc8a4cf38b9efb949010add3ee9d9515ae8c
3
+ size 223336
video_codec_sdk/Interface/cuviddec.h ADDED
@@ -0,0 +1,1209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * This copyright notice applies to this header file only:
3
+ *
4
+ * Copyright (c) 2010-2024 NVIDIA Corporation
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person
7
+ * obtaining a copy of this software and associated documentation
8
+ * files (the "Software"), to deal in the Software without
9
+ * restriction, including without limitation the rights to use,
10
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the software, and to permit persons to whom the
12
+ * software is furnished to do so, subject to the following
13
+ * conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be
16
+ * included in all copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25
+ * OTHER DEALINGS IN THE SOFTWARE.
26
+ */
27
+
28
+ /*****************************************************************************************************/
29
+ //! \file cuviddec.h
30
+ //! NVDECODE API provides video decoding interface to NVIDIA GPU devices.
31
+ //! This file contains constants, structure definitions and function prototypes used for decoding.
32
+ /*****************************************************************************************************/
33
+
34
+ #if !defined(__CUDA_VIDEO_H__)
35
+ #define __CUDA_VIDEO_H__
36
+
37
+ #ifndef __cuda_cuda_h__
38
+ #include <cuda.h>
39
+ #endif // __cuda_cuda_h__
40
+
41
+ #if defined(_WIN64) || defined(__LP64__) || defined(__x86_64) || defined(AMD64) || defined(_M_AMD64)
42
+ #if (CUDA_VERSION >= 3020) && (!defined(CUDA_FORCE_API_VERSION) || (CUDA_FORCE_API_VERSION >= 3020))
43
+ #define __CUVID_DEVPTR64
44
+ #endif
45
+ #endif
46
+
47
+ #if defined(__cplusplus)
48
+ extern "C" {
49
+ #endif /* __cplusplus */
50
+
51
+ typedef void *CUvideodecoder;
52
+ typedef struct _CUcontextlock_st *CUvideoctxlock;
53
+
54
+ /*********************************************************************************/
55
+ //! \enum cudaVideoCodec
56
+ //! Video codec enums
57
+ //! These enums are used in CUVIDDECODECREATEINFO and CUVIDDECODECAPS structures
58
+ /*********************************************************************************/
59
+ typedef enum cudaVideoCodec_enum {
60
+ cudaVideoCodec_MPEG1=0, /**< MPEG1 */
61
+ cudaVideoCodec_MPEG2, /**< MPEG2 */
62
+ cudaVideoCodec_MPEG4, /**< MPEG4 */
63
+ cudaVideoCodec_VC1, /**< VC1 */
64
+ cudaVideoCodec_H264, /**< H264 */
65
+ cudaVideoCodec_JPEG, /**< JPEG */
66
+ cudaVideoCodec_H264_SVC, /**< H264-SVC */
67
+ cudaVideoCodec_H264_MVC, /**< H264-MVC */
68
+ cudaVideoCodec_HEVC, /**< HEVC */
69
+ cudaVideoCodec_VP8, /**< VP8 */
70
+ cudaVideoCodec_VP9, /**< VP9 */
71
+ cudaVideoCodec_AV1, /**< AV1 */
72
+ cudaVideoCodec_NumCodecs, /**< Max codecs */
73
+ // Uncompressed YUV
74
+ cudaVideoCodec_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')), /**< Y,U,V (4:2:0) */
75
+ cudaVideoCodec_YV12 = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')), /**< Y,V,U (4:2:0) */
76
+ cudaVideoCodec_NV12 = (('N'<<24)|('V'<<16)|('1'<<8)|('2')), /**< Y,UV (4:2:0) */
77
+ cudaVideoCodec_YUYV = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')), /**< YUYV/YUY2 (4:2:2) */
78
+ cudaVideoCodec_UYVY = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y')) /**< UYVY (4:2:2) */
79
+ } cudaVideoCodec;
80
+
81
+ /*********************************************************************************/
82
+ //! \enum cudaVideoSurfaceFormat
83
+ //! Video surface format enums used for output format of decoded output
84
+ //! These enums are used in CUVIDDECODECREATEINFO structure
85
+ /*********************************************************************************/
86
+ typedef enum cudaVideoSurfaceFormat_enum {
87
+ cudaVideoSurfaceFormat_NV12=0, /**< Semi-Planar YUV [Y plane followed by interleaved UV plane] */
88
+ cudaVideoSurfaceFormat_P016=1, /**< 16 bit Semi-Planar YUV [Y plane followed by interleaved UV plane].
89
+ Can be used for 10 bit(6LSB bits 0), 12 bit (4LSB bits 0) */
90
+ cudaVideoSurfaceFormat_YUV444=2, /**< Planar YUV [Y plane followed by U and V planes] */
91
+ cudaVideoSurfaceFormat_YUV444_16Bit=3, /**< 16 bit Planar YUV [Y plane followed by U and V planes].
92
+ Can be used for 10 bit(6LSB bits 0), 12 bit (4LSB bits 0) */
93
+ cudaVideoSurfaceFormat_NV16=4, /**< Semi-Planar YUV 422 [Y plane followed by interleaved UV plane] */
94
+ cudaVideoSurfaceFormat_P216=5 /**< 16 bit Semi-Planar YUV 422[Y plane followed by interleaved UV plane].
95
+ Can be used for 10 bit(6LSB bits 0), 12 bit (4LSB bits 0) */
96
+ } cudaVideoSurfaceFormat;
97
+
98
+ /******************************************************************************************************************/
99
+ //! \enum cudaVideoDeinterlaceMode
100
+ //! Deinterlacing mode enums
101
+ //! These enums are used in CUVIDDECODECREATEINFO structure
102
+ //! Use cudaVideoDeinterlaceMode_Weave for progressive content and for content that doesn't need deinterlacing
103
+ //! cudaVideoDeinterlaceMode_Adaptive needs more video memory than other DImodes
104
+ /******************************************************************************************************************/
105
+ typedef enum cudaVideoDeinterlaceMode_enum {
106
+ cudaVideoDeinterlaceMode_Weave=0, /**< Weave both fields (no deinterlacing) */
107
+ cudaVideoDeinterlaceMode_Bob, /**< Drop one field */
108
+ cudaVideoDeinterlaceMode_Adaptive /**< Adaptive deinterlacing */
109
+ } cudaVideoDeinterlaceMode;
110
+
111
+ /**************************************************************************************************************/
112
+ //! \enum cudaVideoChromaFormat
113
+ //! Chroma format enums
114
+ //! These enums are used in CUVIDDECODECREATEINFO and CUVIDDECODECAPS structures
115
+ /**************************************************************************************************************/
116
+ typedef enum cudaVideoChromaFormat_enum {
117
+ cudaVideoChromaFormat_Monochrome=0, /**< MonoChrome */
118
+ cudaVideoChromaFormat_420, /**< YUV 4:2:0 */
119
+ cudaVideoChromaFormat_422, /**< YUV 4:2:2 */
120
+ cudaVideoChromaFormat_444 /**< YUV 4:4:4 */
121
+ } cudaVideoChromaFormat;
122
+
123
+ /*************************************************************************************************************/
124
+ //! \enum cudaVideoCreateFlags
125
+ //! Decoder flag enums to select preferred decode path
126
+ //! cudaVideoCreate_Default and cudaVideoCreate_PreferCUVID are most optimized, use these whenever possible
127
+ /*************************************************************************************************************/
128
+ typedef enum cudaVideoCreateFlags_enum {
129
+ cudaVideoCreate_Default = 0x00, /**< Default operation mode: use dedicated video engines */
130
+ cudaVideoCreate_PreferCUDA = 0x01, /**< Use CUDA-based decoder (requires valid vidLock object for multi-threading) */
131
+ cudaVideoCreate_PreferDXVA = 0x02, /**< Go through DXVA internally if possible (requires D3D9 interop) */
132
+ cudaVideoCreate_PreferCUVID = 0x04 /**< Use dedicated video engines directly */
133
+ } cudaVideoCreateFlags;
134
+
135
+
136
+ /*************************************************************************/
137
+ //! \enum cuvidDecodeStatus
138
+ //! Decode status enums
139
+ //! These enums are used in CUVIDGETDECODESTATUS structure
140
+ /*************************************************************************/
141
+ typedef enum cuvidDecodeStatus_enum
142
+ {
143
+ cuvidDecodeStatus_Invalid = 0, // Decode status is not valid
144
+ cuvidDecodeStatus_InProgress = 1, // Decode is in progress
145
+ cuvidDecodeStatus_Success = 2, // Decode is completed without any errors
146
+ // 3 to 7 enums are reserved for future use
147
+ cuvidDecodeStatus_Error = 8, // Decode is completed with an error (error is not concealed)
148
+ cuvidDecodeStatus_Error_Concealed = 9, // Decode is completed with an error and error is concealed
149
+ } cuvidDecodeStatus;
150
+
151
+ /**************************************************************************************************************/
152
+ //! \struct CUVIDDECODECAPS;
153
+ //! This structure is used in cuvidGetDecoderCaps API
154
+ /**************************************************************************************************************/
155
+ typedef struct _CUVIDDECODECAPS
156
+ {
157
+ cudaVideoCodec eCodecType; /**< IN: cudaVideoCodec_XXX */
158
+ cudaVideoChromaFormat eChromaFormat; /**< IN: cudaVideoChromaFormat_XXX */
159
+ unsigned int nBitDepthMinus8; /**< IN: The Value "BitDepth minus 8" */
160
+ unsigned int reserved1[3]; /**< Reserved for future use - set to zero */
161
+
162
+ unsigned char bIsSupported; /**< OUT: 1 if codec supported, 0 if not supported */
163
+ unsigned char nNumNVDECs; /**< OUT: Number of NVDECs that can support IN params */
164
+ unsigned short nOutputFormatMask; /**< OUT: each bit represents corresponding cudaVideoSurfaceFormat enum */
165
+ unsigned int nMaxWidth; /**< OUT: Max supported coded width in pixels */
166
+ unsigned int nMaxHeight; /**< OUT: Max supported coded height in pixels */
167
+ unsigned int nMaxMBCount; /**< OUT: Max supported macroblock count
168
+ CodedWidth*CodedHeight/256 must be <= nMaxMBCount */
169
+ unsigned short nMinWidth; /**< OUT: Min supported coded width in pixels */
170
+ unsigned short nMinHeight; /**< OUT: Min supported coded height in pixels */
171
+ unsigned char bIsHistogramSupported; /**< OUT: 1 if Y component histogram output is supported, 0 if not
172
+ Note: histogram is computed on original picture data before
173
+ any post-processing like scaling, cropping, etc. is applied */
174
+ unsigned char nCounterBitDepth; /**< OUT: histogram counter bit depth */
175
+ unsigned short nMaxHistogramBins; /**< OUT: Max number of histogram bins */
176
+ unsigned int reserved3[10]; /**< Reserved for future use - set to zero */
177
+ } CUVIDDECODECAPS;
178
+
179
+ /**************************************************************************************************************/
180
+ //! \struct CUVIDDECODECREATEINFO
181
+ //! This structure is used in cuvidCreateDecoder API
182
+ /**************************************************************************************************************/
183
+ typedef struct _CUVIDDECODECREATEINFO
184
+ {
185
+ unsigned long ulWidth; /**< IN: Coded sequence width in pixels */
186
+ unsigned long ulHeight; /**< IN: Coded sequence height in pixels */
187
+ unsigned long ulNumDecodeSurfaces; /**< IN: Maximum number of internal decode surfaces */
188
+ cudaVideoCodec CodecType; /**< IN: cudaVideoCodec_XXX */
189
+ cudaVideoChromaFormat ChromaFormat; /**< IN: cudaVideoChromaFormat_XXX */
190
+ unsigned long ulCreationFlags; /**< IN: Decoder creation flags (cudaVideoCreateFlags_XXX) */
191
+ unsigned long bitDepthMinus8; /**< IN: The value "BitDepth minus 8" */
192
+ unsigned long ulIntraDecodeOnly; /**< IN: Set 1 only if video has all intra frames (default value is 0). This will
193
+ optimize video memory for Intra frames only decoding. The support is limited
194
+ to specific codecs - H264, HEVC, VP9, the flag will be ignored for codecs which
195
+ are not supported. However decoding might fail if the flag is enabled in case
196
+ of supported codecs for regular bit streams having P and/or B frames. */
197
+ unsigned long ulMaxWidth; /**< IN: Coded sequence max width in pixels used with reconfigure Decoder */
198
+ unsigned long ulMaxHeight; /**< IN: Coded sequence max height in pixels used with reconfigure Decoder */
199
+ unsigned long Reserved1; /**< Reserved for future use - set to zero */
200
+ /**
201
+ * IN: area of the frame that should be displayed
202
+ */
203
+ struct {
204
+ short left;
205
+ short top;
206
+ short right;
207
+ short bottom;
208
+ } display_area;
209
+
210
+ cudaVideoSurfaceFormat OutputFormat; /**< IN: cudaVideoSurfaceFormat_XXX */
211
+ cudaVideoDeinterlaceMode DeinterlaceMode; /**< IN: cudaVideoDeinterlaceMode_XXX */
212
+ unsigned long ulTargetWidth; /**< IN: Post-processed output width (Should be aligned to 2) */
213
+ unsigned long ulTargetHeight; /**< IN: Post-processed output height (Should be aligned to 2) */
214
+ unsigned long ulNumOutputSurfaces; /**< IN: Maximum number of output surfaces simultaneously mapped */
215
+ CUvideoctxlock vidLock; /**< IN: If non-NULL, context lock used for synchronizing ownership of
216
+ the cuda context. Needed for cudaVideoCreate_PreferCUDA decode */
217
+ /**
218
+ * IN: target rectangle in the output frame (for aspect ratio conversion)
219
+ * if a null rectangle is specified, {0,0,ulTargetWidth,ulTargetHeight} will be used
220
+ */
221
+ struct {
222
+ short left;
223
+ short top;
224
+ short right;
225
+ short bottom;
226
+ } target_rect;
227
+
228
+ unsigned long enableHistogram; /**< IN: enable histogram output, if supported */
229
+ unsigned long Reserved2[4]; /**< Reserved for future use - set to zero */
230
+ } CUVIDDECODECREATEINFO;
231
+
232
+ /*********************************************************/
233
+ //! \struct CUVIDH264DPBENTRY
234
+ //! H.264 DPB entry
235
+ //! This structure is used in CUVIDH264PICPARAMS structure
236
+ /*********************************************************/
237
+ typedef struct _CUVIDH264DPBENTRY
238
+ {
239
+ int PicIdx; /**< picture index of reference frame */
240
+ int FrameIdx; /**< frame_num(short-term) or LongTermFrameIdx(long-term) */
241
+ int is_long_term; /**< 0=short term reference, 1=long term reference */
242
+ int not_existing; /**< non-existing reference frame (corresponding PicIdx should be set to -1) */
243
+ int used_for_reference; /**< 0=unused, 1=top_field, 2=bottom_field, 3=both_fields */
244
+ int FieldOrderCnt[2]; /**< field order count of top and bottom fields */
245
+ } CUVIDH264DPBENTRY;
246
+
247
+ /************************************************************/
248
+ //! \struct CUVIDH264MVCEXT
249
+ //! H.264 MVC picture parameters ext
250
+ //! This structure is used in CUVIDH264PICPARAMS structure
251
+ /************************************************************/
252
+ typedef struct _CUVIDH264MVCEXT
253
+ {
254
+ int num_views_minus1; /**< Max number of coded views minus 1 in video : Range - 0 to 1023 */
255
+ int view_id; /**< view identifier */
256
+ unsigned char inter_view_flag; /**< 1 if used for inter-view prediction, 0 if not */
257
+ unsigned char num_inter_view_refs_l0; /**< number of inter-view ref pics in RefPicList0 */
258
+ unsigned char num_inter_view_refs_l1; /**< number of inter-view ref pics in RefPicList1 */
259
+ unsigned char MVCReserved8Bits; /**< Reserved bits */
260
+ int InterViewRefsL0[16]; /**< view id of the i-th view component for inter-view prediction in RefPicList0 */
261
+ int InterViewRefsL1[16]; /**< view id of the i-th view component for inter-view prediction in RefPicList1 */
262
+ } CUVIDH264MVCEXT;
263
+
264
+ /*********************************************************/
265
+ //! \struct CUVIDH264SVCEXT
266
+ //! H.264 SVC picture parameters ext
267
+ //! This structure is used in CUVIDH264PICPARAMS structure
268
+ /*********************************************************/
269
+ typedef struct _CUVIDH264SVCEXT
270
+ {
271
+ unsigned char profile_idc;
272
+ unsigned char level_idc;
273
+ unsigned char DQId;
274
+ unsigned char DQIdMax;
275
+ unsigned char disable_inter_layer_deblocking_filter_idc;
276
+ unsigned char ref_layer_chroma_phase_y_plus1;
277
+ signed char inter_layer_slice_alpha_c0_offset_div2;
278
+ signed char inter_layer_slice_beta_offset_div2;
279
+
280
+ unsigned short DPBEntryValidFlag;
281
+ unsigned char inter_layer_deblocking_filter_control_present_flag;
282
+ unsigned char extended_spatial_scalability_idc;
283
+ unsigned char adaptive_tcoeff_level_prediction_flag;
284
+ unsigned char slice_header_restriction_flag;
285
+ unsigned char chroma_phase_x_plus1_flag;
286
+ unsigned char chroma_phase_y_plus1;
287
+
288
+ unsigned char tcoeff_level_prediction_flag;
289
+ unsigned char constrained_intra_resampling_flag;
290
+ unsigned char ref_layer_chroma_phase_x_plus1_flag;
291
+ unsigned char store_ref_base_pic_flag;
292
+ unsigned char Reserved8BitsA;
293
+ unsigned char Reserved8BitsB;
294
+
295
+ short scaled_ref_layer_left_offset;
296
+ short scaled_ref_layer_top_offset;
297
+ short scaled_ref_layer_right_offset;
298
+ short scaled_ref_layer_bottom_offset;
299
+ unsigned short Reserved16Bits;
300
+ struct _CUVIDPICPARAMS *pNextLayer; /**< Points to the picparams for the next layer to be decoded.
301
+ Linked list ends at the target layer. */
302
+ int bRefBaseLayer; /**< whether to store ref base pic */
303
+ } CUVIDH264SVCEXT;
304
+
305
+ /******************************************************/
306
+ //! \struct CUVIDH264PICPARAMS
307
+ //! H.264 picture parameters
308
+ //! This structure is used in CUVIDPICPARAMS structure
309
+ /******************************************************/
310
+ typedef struct _CUVIDH264PICPARAMS
311
+ {
312
+ // SPS
313
+ int log2_max_frame_num_minus4;
314
+ int pic_order_cnt_type;
315
+ int log2_max_pic_order_cnt_lsb_minus4;
316
+ int delta_pic_order_always_zero_flag;
317
+ int frame_mbs_only_flag;
318
+ int direct_8x8_inference_flag;
319
+ int num_ref_frames;
320
+ unsigned char residual_colour_transform_flag;
321
+ unsigned char bit_depth_luma_minus8;
322
+ unsigned char bit_depth_chroma_minus8;
323
+ unsigned char qpprime_y_zero_transform_bypass_flag;
324
+ // PPS
325
+ int entropy_coding_mode_flag;
326
+ int pic_order_present_flag;
327
+ int num_ref_idx_l0_active_minus1;
328
+ int num_ref_idx_l1_active_minus1;
329
+ int weighted_pred_flag;
330
+ int weighted_bipred_idc;
331
+ int pic_init_qp_minus26;
332
+ int deblocking_filter_control_present_flag;
333
+ int redundant_pic_cnt_present_flag;
334
+ int transform_8x8_mode_flag;
335
+ int MbaffFrameFlag;
336
+ int constrained_intra_pred_flag;
337
+ int chroma_qp_index_offset;
338
+ int second_chroma_qp_index_offset;
339
+ int ref_pic_flag;
340
+ int frame_num;
341
+ int CurrFieldOrderCnt[2];
342
+ // DPB
343
+ CUVIDH264DPBENTRY dpb[16]; // List of reference frames within the DPB
344
+ // Quantization Matrices (raster-order)
345
+ unsigned char WeightScale4x4[6][16];
346
+ unsigned char WeightScale8x8[2][64];
347
+ // FMO/ASO
348
+ unsigned char fmo_aso_enable;
349
+ unsigned char num_slice_groups_minus1;
350
+ unsigned char slice_group_map_type;
351
+ signed char pic_init_qs_minus26;
352
+ unsigned int slice_group_change_rate_minus1;
353
+ union
354
+ {
355
+ unsigned long long slice_group_map_addr;
356
+ const unsigned char *pMb2SliceGroupMap;
357
+ } fmo;
358
+ unsigned int mb_adaptive_frame_field_flag : 2; // bit 0 represent SPS flag mb_adaptive_frame_field_flag
359
+ // if bit 1 is not set, flag is ignored. Bit 1 is set to maintain backward compatibility
360
+ unsigned int Reserved1 : 30;
361
+ unsigned int Reserved[11];
362
+ // SVC/MVC
363
+ union
364
+ {
365
+ CUVIDH264MVCEXT mvcext;
366
+ CUVIDH264SVCEXT svcext;
367
+ };
368
+ } CUVIDH264PICPARAMS;
369
+
370
+
371
+ /********************************************************/
372
+ //! \struct CUVIDMPEG2PICPARAMS
373
+ //! MPEG-2 picture parameters
374
+ //! This structure is used in CUVIDPICPARAMS structure
375
+ /********************************************************/
376
+ typedef struct _CUVIDMPEG2PICPARAMS
377
+ {
378
+ int ForwardRefIdx; // Picture index of forward reference (P/B-frames)
379
+ int BackwardRefIdx; // Picture index of backward reference (B-frames)
380
+ int picture_coding_type;
381
+ int full_pel_forward_vector;
382
+ int full_pel_backward_vector;
383
+ int f_code[2][2];
384
+ int intra_dc_precision;
385
+ int frame_pred_frame_dct;
386
+ int concealment_motion_vectors;
387
+ int q_scale_type;
388
+ int intra_vlc_format;
389
+ int alternate_scan;
390
+ int top_field_first;
391
+ // Quantization matrices (raster order)
392
+ unsigned char QuantMatrixIntra[64];
393
+ unsigned char QuantMatrixInter[64];
394
+ } CUVIDMPEG2PICPARAMS;
395
+
396
+ // MPEG-4 has VOP types instead of Picture types
397
+ #define I_VOP 0
398
+ #define P_VOP 1
399
+ #define B_VOP 2
400
+ #define S_VOP 3
401
+
402
+ /*******************************************************/
403
+ //! \struct CUVIDMPEG4PICPARAMS
404
+ //! MPEG-4 picture parameters
405
+ //! This structure is used in CUVIDPICPARAMS structure
406
+ /*******************************************************/
407
+ typedef struct _CUVIDMPEG4PICPARAMS
408
+ {
409
+ int ForwardRefIdx; // Picture index of forward reference (P/B-frames)
410
+ int BackwardRefIdx; // Picture index of backward reference (B-frames)
411
+ // VOL
412
+ int video_object_layer_width;
413
+ int video_object_layer_height;
414
+ int vop_time_increment_bitcount;
415
+ int top_field_first;
416
+ int resync_marker_disable;
417
+ int quant_type;
418
+ int quarter_sample;
419
+ int short_video_header;
420
+ int divx_flags;
421
+ // VOP
422
+ int vop_coding_type;
423
+ int vop_coded;
424
+ int vop_rounding_type;
425
+ int alternate_vertical_scan_flag;
426
+ int interlaced;
427
+ int vop_fcode_forward;
428
+ int vop_fcode_backward;
429
+ int trd[2];
430
+ int trb[2];
431
+ // Quantization matrices (raster order)
432
+ unsigned char QuantMatrixIntra[64];
433
+ unsigned char QuantMatrixInter[64];
434
+ int gmc_enabled;
435
+ } CUVIDMPEG4PICPARAMS;
436
+
437
+ /********************************************************/
438
+ //! \struct CUVIDVC1PICPARAMS
439
+ //! VC1 picture parameters
440
+ //! This structure is used in CUVIDPICPARAMS structure
441
+ /********************************************************/
442
+ typedef struct _CUVIDVC1PICPARAMS
443
+ {
444
+ int ForwardRefIdx; /**< Picture index of forward reference (P/B-frames) */
445
+ int BackwardRefIdx; /**< Picture index of backward reference (B-frames) */
446
+ int FrameWidth; /**< Actual frame width */
447
+ int FrameHeight; /**< Actual frame height */
448
+ // PICTURE
449
+ int intra_pic_flag; /**< Set to 1 for I,BI frames */
450
+ int ref_pic_flag; /**< Set to 1 for I,P frames */
451
+ int progressive_fcm; /**< Progressive frame */
452
+ // SEQUENCE
453
+ int profile;
454
+ int postprocflag;
455
+ int pulldown;
456
+ int interlace;
457
+ int tfcntrflag;
458
+ int finterpflag;
459
+ int psf;
460
+ int multires;
461
+ int syncmarker;
462
+ int rangered;
463
+ int maxbframes;
464
+ // ENTRYPOINT
465
+ int panscan_flag;
466
+ int refdist_flag;
467
+ int extended_mv;
468
+ int dquant;
469
+ int vstransform;
470
+ int loopfilter;
471
+ int fastuvmc;
472
+ int overlap;
473
+ int quantizer;
474
+ int extended_dmv;
475
+ int range_mapy_flag;
476
+ int range_mapy;
477
+ int range_mapuv_flag;
478
+ int range_mapuv;
479
+ int rangeredfrm; // range reduction state
480
+ } CUVIDVC1PICPARAMS;
481
+
482
+ /***********************************************************/
483
+ //! \struct CUVIDJPEGPICPARAMS
484
+ //! JPEG picture parameters
485
+ //! This structure is used in CUVIDPICPARAMS structure
486
+ /***********************************************************/
487
+ typedef struct _CUVIDJPEGPICPARAMS
488
+ {
489
+ unsigned char numComponents;
490
+ unsigned char bitDepth;
491
+ unsigned char quantizationTableSelector[4];
492
+ unsigned int scanOffset[4];
493
+ unsigned int scanSize[4];
494
+
495
+ unsigned short restartInterval;
496
+ unsigned char componentIdentifier[4];
497
+
498
+ unsigned char hasQMatrix;
499
+ unsigned char hasHuffman;
500
+ unsigned short quantvals[4][64];
501
+
502
+ unsigned char bits_ac[4][16];
503
+ unsigned char table_ac[4][256]; // there can only be max of 162 ac symbols
504
+
505
+ unsigned char bits_dc[4][16];
506
+ unsigned char table_dc[4][256]; // there can only be max of 12 dc symbols
507
+ } CUVIDJPEGPICPARAMS;
508
+
509
+
510
+ /*******************************************************/
511
+ //! \struct CUVIDHEVCPICPARAMS
512
+ //! HEVC picture parameters
513
+ //! This structure is used in CUVIDPICPARAMS structure
514
+ /*******************************************************/
515
+ typedef struct _CUVIDHEVCPICPARAMS
516
+ {
517
+ // sps
518
+ int pic_width_in_luma_samples;
519
+ int pic_height_in_luma_samples;
520
+ unsigned char log2_min_luma_coding_block_size_minus3;
521
+ unsigned char log2_diff_max_min_luma_coding_block_size;
522
+ unsigned char log2_min_transform_block_size_minus2;
523
+ unsigned char log2_diff_max_min_transform_block_size;
524
+ unsigned char pcm_enabled_flag;
525
+ unsigned char log2_min_pcm_luma_coding_block_size_minus3;
526
+ unsigned char log2_diff_max_min_pcm_luma_coding_block_size;
527
+ unsigned char pcm_sample_bit_depth_luma_minus1;
528
+
529
+ unsigned char pcm_sample_bit_depth_chroma_minus1;
530
+ unsigned char pcm_loop_filter_disabled_flag;
531
+ unsigned char strong_intra_smoothing_enabled_flag;
532
+ unsigned char max_transform_hierarchy_depth_intra;
533
+ unsigned char max_transform_hierarchy_depth_inter;
534
+ unsigned char amp_enabled_flag;
535
+ unsigned char separate_colour_plane_flag;
536
+ unsigned char log2_max_pic_order_cnt_lsb_minus4;
537
+
538
+ unsigned char num_short_term_ref_pic_sets;
539
+ unsigned char long_term_ref_pics_present_flag;
540
+ unsigned char num_long_term_ref_pics_sps;
541
+ unsigned char sps_temporal_mvp_enabled_flag;
542
+ unsigned char sample_adaptive_offset_enabled_flag;
543
+ unsigned char scaling_list_enable_flag;
544
+ unsigned char IrapPicFlag;
545
+ unsigned char IdrPicFlag;
546
+
547
+ unsigned char bit_depth_luma_minus8;
548
+ unsigned char bit_depth_chroma_minus8;
549
+ //sps/pps extension fields
550
+ unsigned char log2_max_transform_skip_block_size_minus2;
551
+ unsigned char log2_sao_offset_scale_luma;
552
+ unsigned char log2_sao_offset_scale_chroma;
553
+ unsigned char high_precision_offsets_enabled_flag;
554
+ unsigned char reserved1[10];
555
+
556
+ // pps
557
+ unsigned char dependent_slice_segments_enabled_flag;
558
+ unsigned char slice_segment_header_extension_present_flag;
559
+ unsigned char sign_data_hiding_enabled_flag;
560
+ unsigned char cu_qp_delta_enabled_flag;
561
+ unsigned char diff_cu_qp_delta_depth;
562
+ signed char init_qp_minus26;
563
+ signed char pps_cb_qp_offset;
564
+ signed char pps_cr_qp_offset;
565
+
566
+ unsigned char constrained_intra_pred_flag;
567
+ unsigned char weighted_pred_flag;
568
+ unsigned char weighted_bipred_flag;
569
+ unsigned char transform_skip_enabled_flag;
570
+ unsigned char transquant_bypass_enabled_flag;
571
+ unsigned char entropy_coding_sync_enabled_flag;
572
+ unsigned char log2_parallel_merge_level_minus2;
573
+ unsigned char num_extra_slice_header_bits;
574
+
575
+ unsigned char loop_filter_across_tiles_enabled_flag;
576
+ unsigned char loop_filter_across_slices_enabled_flag;
577
+ unsigned char output_flag_present_flag;
578
+ unsigned char num_ref_idx_l0_default_active_minus1;
579
+ unsigned char num_ref_idx_l1_default_active_minus1;
580
+ unsigned char lists_modification_present_flag;
581
+ unsigned char cabac_init_present_flag;
582
+ unsigned char pps_slice_chroma_qp_offsets_present_flag;
583
+
584
+ unsigned char deblocking_filter_override_enabled_flag;
585
+ unsigned char pps_deblocking_filter_disabled_flag;
586
+ signed char pps_beta_offset_div2;
587
+ signed char pps_tc_offset_div2;
588
+ unsigned char tiles_enabled_flag;
589
+ unsigned char uniform_spacing_flag;
590
+ unsigned char num_tile_columns_minus1;
591
+ unsigned char num_tile_rows_minus1;
592
+
593
+ unsigned short column_width_minus1[21];
594
+ unsigned short row_height_minus1[21];
595
+
596
+ // sps and pps extension HEVC-main 444
597
+ unsigned char sps_range_extension_flag;
598
+ unsigned char transform_skip_rotation_enabled_flag;
599
+ unsigned char transform_skip_context_enabled_flag;
600
+ unsigned char implicit_rdpcm_enabled_flag;
601
+
602
+ unsigned char explicit_rdpcm_enabled_flag;
603
+ unsigned char extended_precision_processing_flag;
604
+ unsigned char intra_smoothing_disabled_flag;
605
+ unsigned char persistent_rice_adaptation_enabled_flag;
606
+
607
+ unsigned char cabac_bypass_alignment_enabled_flag;
608
+ unsigned char pps_range_extension_flag;
609
+ unsigned char cross_component_prediction_enabled_flag;
610
+ unsigned char chroma_qp_offset_list_enabled_flag;
611
+
612
+ unsigned char diff_cu_chroma_qp_offset_depth;
613
+ unsigned char chroma_qp_offset_list_len_minus1;
614
+ signed char cb_qp_offset_list[6];
615
+
616
+ signed char cr_qp_offset_list[6];
617
+ unsigned char reserved2[2];
618
+
619
+ unsigned int reserved3[8];
620
+
621
+ // RefPicSets
622
+ int NumBitsForShortTermRPSInSlice;
623
+ int NumDeltaPocsOfRefRpsIdx;
624
+ int NumPocTotalCurr;
625
+ int NumPocStCurrBefore;
626
+ int NumPocStCurrAfter;
627
+ int NumPocLtCurr;
628
+ int CurrPicOrderCntVal;
629
+ int RefPicIdx[16]; // [refpic] Indices of valid reference pictures (-1 if unused for reference)
630
+ int PicOrderCntVal[16]; // [refpic]
631
+ unsigned char IsLongTerm[16]; // [refpic] 0=not a long-term reference, 1=long-term reference
632
+ unsigned char RefPicSetStCurrBefore[8]; // [0..NumPocStCurrBefore-1] -> refpic (0..15)
633
+ unsigned char RefPicSetStCurrAfter[8]; // [0..NumPocStCurrAfter-1] -> refpic (0..15)
634
+ unsigned char RefPicSetLtCurr[8]; // [0..NumPocLtCurr-1] -> refpic (0..15)
635
+ unsigned char RefPicSetInterLayer0[8];
636
+ unsigned char RefPicSetInterLayer1[8];
637
+ unsigned int reserved4[12];
638
+
639
+ // scaling lists (diag order)
640
+ unsigned char ScalingList4x4[6][16]; // [matrixId][i]
641
+ unsigned char ScalingList8x8[6][64]; // [matrixId][i]
642
+ unsigned char ScalingList16x16[6][64]; // [matrixId][i]
643
+ unsigned char ScalingList32x32[2][64]; // [matrixId][i]
644
+ unsigned char ScalingListDCCoeff16x16[6]; // [matrixId]
645
+ unsigned char ScalingListDCCoeff32x32[2]; // [matrixId]
646
+ } CUVIDHEVCPICPARAMS;
647
+
648
+
649
+ /***********************************************************/
650
+ //! \struct CUVIDVP8PICPARAMS
651
+ //! VP8 picture parameters
652
+ //! This structure is used in CUVIDPICPARAMS structure
653
+ /***********************************************************/
654
+ typedef struct _CUVIDVP8PICPARAMS
655
+ {
656
+ int width;
657
+ int height;
658
+ unsigned int first_partition_size;
659
+ //Frame Indexes
660
+ unsigned char LastRefIdx;
661
+ unsigned char GoldenRefIdx;
662
+ unsigned char AltRefIdx;
663
+ union {
664
+ struct {
665
+ unsigned char frame_type : 1; /**< 0 = KEYFRAME, 1 = INTERFRAME */
666
+ unsigned char version : 3;
667
+ unsigned char show_frame : 1;
668
+ unsigned char update_mb_segmentation_data : 1; /**< Must be 0 if segmentation is not enabled */
669
+ unsigned char Reserved2Bits : 2;
670
+ }vp8_frame_tag;
671
+ unsigned char wFrameTagFlags;
672
+ };
673
+ unsigned char Reserved1[4];
674
+ unsigned int Reserved2[3];
675
+ } CUVIDVP8PICPARAMS;
676
+
677
+ /***********************************************************/
678
+ //! \struct CUVIDVP9PICPARAMS
679
+ //! VP9 picture parameters
680
+ //! This structure is used in CUVIDPICPARAMS structure
681
+ /***********************************************************/
682
+ typedef struct _CUVIDVP9PICPARAMS
683
+ {
684
+ unsigned int width;
685
+ unsigned int height;
686
+
687
+ //Frame Indices
688
+ unsigned char LastRefIdx;
689
+ unsigned char GoldenRefIdx;
690
+ unsigned char AltRefIdx;
691
+ unsigned char colorSpace;
692
+
693
+ unsigned short profile : 3;
694
+ unsigned short frameContextIdx : 2;
695
+ unsigned short frameType : 1;
696
+ unsigned short showFrame : 1;
697
+ unsigned short errorResilient : 1;
698
+ unsigned short frameParallelDecoding : 1;
699
+ unsigned short subSamplingX : 1;
700
+ unsigned short subSamplingY : 1;
701
+ unsigned short intraOnly : 1;
702
+ unsigned short allow_high_precision_mv : 1;
703
+ unsigned short refreshEntropyProbs : 1;
704
+ unsigned short reserved2Bits : 2;
705
+
706
+ unsigned short reserved16Bits;
707
+
708
+ unsigned char refFrameSignBias[4];
709
+
710
+ unsigned char bitDepthMinus8Luma;
711
+ unsigned char bitDepthMinus8Chroma;
712
+ unsigned char loopFilterLevel;
713
+ unsigned char loopFilterSharpness;
714
+
715
+ unsigned char modeRefLfEnabled;
716
+ unsigned char log2_tile_columns;
717
+ unsigned char log2_tile_rows;
718
+
719
+ unsigned char segmentEnabled : 1;
720
+ unsigned char segmentMapUpdate : 1;
721
+ unsigned char segmentMapTemporalUpdate : 1;
722
+ unsigned char segmentFeatureMode : 1;
723
+ unsigned char reserved4Bits : 4;
724
+
725
+
726
+ unsigned char segmentFeatureEnable[8][4];
727
+ short segmentFeatureData[8][4];
728
+ unsigned char mb_segment_tree_probs[7];
729
+ unsigned char segment_pred_probs[3];
730
+ unsigned char reservedSegment16Bits[2];
731
+
732
+ int qpYAc;
733
+ int qpYDc;
734
+ int qpChDc;
735
+ int qpChAc;
736
+
737
+ unsigned int activeRefIdx[3];
738
+ unsigned int resetFrameContext;
739
+ unsigned int mcomp_filter_type;
740
+ unsigned int mbRefLfDelta[4];
741
+ unsigned int mbModeLfDelta[2];
742
+ unsigned int frameTagSize;
743
+ unsigned int offsetToDctParts;
744
+ unsigned int reserved128Bits[4];
745
+
746
+ } CUVIDVP9PICPARAMS;
747
+
748
+ /***********************************************************/
749
+ //! \struct CUVIDAV1PICPARAMS
750
+ //! AV1 picture parameters
751
+ //! This structure is used in CUVIDPICPARAMS structure
752
+ /***********************************************************/
753
+ typedef struct _CUVIDAV1PICPARAMS
754
+ {
755
+ unsigned int width; // coded width, if superres enabled then it is upscaled width
756
+ unsigned int height; // coded height
757
+ unsigned int frame_offset; // defined as order_hint in AV1 specification
758
+ int decodePicIdx; // decoded output pic index, if film grain enabled, it will keep decoded (without film grain) output
759
+ // It can be used as reference frame for future frames
760
+
761
+ // sequence header
762
+ unsigned int profile : 3; // 0 = profile0, 1 = profile1, 2 = profile2
763
+ unsigned int use_128x128_superblock : 1; // superblock size 0:64x64, 1: 128x128
764
+ unsigned int subsampling_x : 1; // (subsampling_x, _y) 1,1 = 420, 1,0 = 422, 0,0 = 444
765
+ unsigned int subsampling_y : 1;
766
+ unsigned int mono_chrome : 1; // for monochrome content, mono_chrome = 1 and (subsampling_x, _y) should be 1,1
767
+ unsigned int bit_depth_minus8 : 4; // bit depth minus 8
768
+ unsigned int enable_filter_intra : 1; // tool enable in seq level, 0 : disable 1: frame header control
769
+ unsigned int enable_intra_edge_filter : 1; // intra edge filtering process, 0 : disable 1: enabled
770
+ unsigned int enable_interintra_compound : 1; // interintra, 0 : not present 1: present
771
+ unsigned int enable_masked_compound : 1; // 1: mode info for inter blocks may contain the syntax element compound_type.
772
+ // 0: syntax element compound_type will not be present
773
+ unsigned int enable_dual_filter : 1; // vertical and horiz filter selection, 1: enable and 0: disable
774
+ unsigned int enable_order_hint : 1; // order hint, and related tools, 1: enable and 0: disable
775
+ unsigned int order_hint_bits_minus1 : 3; // is used to compute OrderHintBits
776
+ unsigned int enable_jnt_comp : 1; // joint compound modes, 1: enable and 0: disable
777
+ unsigned int enable_superres : 1; // superres in seq level, 0 : disable 1: frame level control
778
+ unsigned int enable_cdef : 1; // cdef filtering in seq level, 0 : disable 1: frame level control
779
+ unsigned int enable_restoration : 1; // loop restoration filtering in seq level, 0 : disable 1: frame level control
780
+ unsigned int enable_fgs : 1; // defined as film_grain_params_present in AV1 specification
781
+ unsigned int reserved0_7bits : 7; // reserved bits; must be set to 0
782
+
783
+ // frame header
784
+ unsigned int frame_type : 2 ; // 0:Key frame, 1:Inter frame, 2:intra only, 3:s-frame
785
+ unsigned int show_frame : 1 ; // show_frame = 1 implies that frame should be immediately output once decoded
786
+ unsigned int disable_cdf_update : 1; // CDF update during symbol decoding, 1: disabled, 0: enabled
787
+ unsigned int allow_screen_content_tools : 1; // 1: intra blocks may use palette encoding, 0: palette encoding is never used
788
+ unsigned int force_integer_mv : 1; // 1: motion vectors will always be integers, 0: can contain fractional bits
789
+ unsigned int coded_denom : 3; // coded_denom of the superres scale as specified in AV1 specification
790
+ unsigned int allow_intrabc : 1; // 1: intra block copy may be used, 0: intra block copy is not allowed
791
+ unsigned int allow_high_precision_mv : 1; // 1/8 precision mv enable
792
+ unsigned int interp_filter : 3; // interpolation filter. Refer to section 6.8.9 of the AV1 specification Version 1.0.0 with Errata 1
793
+ unsigned int switchable_motion_mode : 1; // defined as is_motion_mode_switchable in AV1 specification
794
+ unsigned int use_ref_frame_mvs : 1; // 1: current frame can use the previous frame mv information, 0: will not use.
795
+ unsigned int disable_frame_end_update_cdf : 1; // 1: indicates that the end of frame CDF update is disabled
796
+ unsigned int delta_q_present : 1; // quantizer index delta values are present in the block level
797
+ unsigned int delta_q_res : 2; // left shift which should be applied to decoded quantizer index delta values
798
+ unsigned int using_qmatrix : 1; // 1: quantizer matrix will be used to compute quantizers
799
+ unsigned int coded_lossless : 1; // 1: all segments use lossless coding
800
+ unsigned int use_superres : 1; // 1: superres enabled for frame
801
+ unsigned int tx_mode : 2; // 0: ONLY4x4,1:LARGEST,2:SELECT
802
+ unsigned int reference_mode : 1; // 0: SINGLE, 1: SELECT
803
+ unsigned int allow_warped_motion : 1; // 1: allow_warped_motion may be present, 0: allow_warped_motion will not be present
804
+ unsigned int reduced_tx_set : 1; // 1: frame is restricted to subset of the full set of transform types, 0: no such restriction
805
+ unsigned int skip_mode : 1; // 1: most of the mode info is skipped, 0: mode info is not skipped
806
+ unsigned int reserved1_3bits : 3; // reserved bits; must be set to 0
807
+
808
+ // tiling info
809
+ unsigned int num_tile_cols : 8; // number of tiles across the frame., max is 64
810
+ unsigned int num_tile_rows : 8; // number of tiles down the frame., max is 64
811
+ unsigned int context_update_tile_id : 16; // specifies which tile to use for the CDF update
812
+ unsigned short tile_widths[64]; // Width of each column in superblocks
813
+ unsigned short tile_heights[64]; // height of each row in superblocks
814
+
815
+ // CDEF - refer to section 6.10.14 of the AV1 specification Version 1.0.0 with Errata 1
816
+ unsigned char cdef_damping_minus_3 : 2; // controls the amount of damping in the deringing filter
817
+ unsigned char cdef_bits : 2; // the number of bits needed to specify which CDEF filter to apply
818
+ unsigned char reserved2_4bits : 4; // reserved bits; must be set to 0
819
+ unsigned char cdef_y_strength[8]; // 0-3 bits: y_pri_strength, 4-7 bits y_sec_strength
820
+ unsigned char cdef_uv_strength[8]; // 0-3 bits: uv_pri_strength, 4-7 bits uv_sec_strength
821
+
822
+ // SkipModeFrames
823
+ unsigned char SkipModeFrame0 : 4; // specifies the frames to use for compound prediction when skip_mode is equal to 1.
824
+ unsigned char SkipModeFrame1 : 4;
825
+
826
+ // qp information - refer to section 6.8.11 of the AV1 specification Version 1.0.0 with Errata 1
827
+ unsigned char base_qindex; // indicates the base frame qindex. Defined as base_q_idx in AV1 specification
828
+ char qp_y_dc_delta_q; // indicates the Y DC quantizer relative to base_q_idx. Defined as DeltaQYDc in AV1 specification
829
+ char qp_u_dc_delta_q; // indicates the U DC quantizer relative to base_q_idx. Defined as DeltaQUDc in AV1 specification
830
+ char qp_v_dc_delta_q; // indicates the V DC quantizer relative to base_q_idx. Defined as DeltaQVDc in AV1 specification
831
+ char qp_u_ac_delta_q; // indicates the U AC quantizer relative to base_q_idx. Defined as DeltaQUAc in AV1 specification
832
+ char qp_v_ac_delta_q; // indicates the V AC quantizer relative to base_q_idx. Defined as DeltaQVAc in AV1 specification
833
+ unsigned char qm_y; // specifies the level in the quantizer matrix that should be used for luma plane decoding
834
+ unsigned char qm_u; // specifies the level in the quantizer matrix that should be used for chroma U plane decoding
835
+ unsigned char qm_v; // specifies the level in the quantizer matrix that should be used for chroma V plane decoding
836
+
837
+ // segmentation - refer to section 6.8.13 of the AV1 specification Version 1.0.0 with Errata 1
838
+ unsigned char segmentation_enabled : 1; // 1 indicates that this frame makes use of the segmentation tool
839
+ unsigned char segmentation_update_map : 1; // 1 indicates that the segmentation map are updated during the decoding of this frame
840
+ unsigned char segmentation_update_data : 1; // 1 indicates that new parameters are about to be specified for each segment
841
+ unsigned char segmentation_temporal_update : 1; // 1 indicates that the updates to the segmentation map are coded relative to the existing segmentation map
842
+ unsigned char reserved3_4bits : 4; // reserved bits; must be set to 0
843
+ short segmentation_feature_data[8][8]; // specifies the feature data for a segment feature
844
+ unsigned char segmentation_feature_mask[8]; // indicates that the corresponding feature is unused or feature value is coded
845
+
846
+ // loopfilter - refer to section 6.8.10 of the AV1 specification Version 1.0.0 with Errata 1
847
+ unsigned char loop_filter_level[2]; // contains loop filter strength values
848
+ unsigned char loop_filter_level_u; // loop filter strength value of U plane
849
+ unsigned char loop_filter_level_v; // loop filter strength value of V plane
850
+ unsigned char loop_filter_sharpness; // indicates the sharpness level
851
+ char loop_filter_ref_deltas[8]; // contains the adjustment needed for the filter level based on the chosen reference frame
852
+ char loop_filter_mode_deltas[2]; // contains the adjustment needed for the filter level based on the chosen mode
853
+ unsigned char loop_filter_delta_enabled : 1; // indicates that the filter level depends on the mode and reference frame used to predict a block
854
+ unsigned char loop_filter_delta_update : 1; // indicates that additional syntax elements are present that specify which mode and
855
+ // reference frame deltas are to be updated
856
+ unsigned char delta_lf_present : 1; // specifies whether loop filter delta values are present in the block level
857
+ unsigned char delta_lf_res : 2; // specifies the left shift to apply to the decoded loop filter values
858
+ unsigned char delta_lf_multi : 1; // separate loop filter deltas for Hy,Vy,U,V edges
859
+ unsigned char reserved4_2bits : 2; // reserved bits; must be set to 0
860
+
861
+ // restoration - refer to section 6.10.15 of the AV1 specification Version 1.0.0 with Errata 1
862
+ unsigned char lr_unit_size[3]; // specifies the size of loop restoration units: 0: 32, 1: 64, 2: 128, 3: 256
863
+ unsigned char lr_type[3] ; // used to compute FrameRestorationType
864
+
865
+ // reference frames
866
+ unsigned char primary_ref_frame; // specifies which reference frame contains the CDF values and other state that should be
867
+ // loaded at the start of the frame
868
+ unsigned char ref_frame_map[8]; // frames in dpb that can be used as reference for current or future frames
869
+
870
+ unsigned char temporal_layer_id : 4; // temporal layer id
871
+ unsigned char spatial_layer_id : 4; // spatial layer id
872
+
873
+ unsigned char reserved5_32bits[4]; // reserved bits; must be set to 0
874
+
875
+ // ref frame list
876
+ struct
877
+ {
878
+ unsigned int width;
879
+ unsigned int height;
880
+ unsigned char index;
881
+ unsigned char reserved24Bits[3]; // reserved bits; must be set to 0
882
+ } ref_frame[7]; // frames used as reference frame for current frame.
883
+
884
+ // global motion
885
+ struct {
886
+ unsigned char invalid : 1;
887
+ unsigned char wmtype : 2; // defined as GmType in AV1 specification
888
+ unsigned char reserved5Bits : 5; // reserved bits; must be set to 0
889
+ char reserved24Bits[3]; // reserved bits; must be set to 0
890
+ int wmmat[6]; // defined as gm_params[] in AV1 specification
891
+ } global_motion[7]; // global motion params for reference frames
892
+
893
+ // film grain params - refer to section 6.8.20 of the AV1 specification Version 1.0.0 with Errata 1
894
+ unsigned short apply_grain : 1;
895
+ unsigned short overlap_flag : 1;
896
+ unsigned short scaling_shift_minus8 : 2;
897
+ unsigned short chroma_scaling_from_luma : 1;
898
+ unsigned short ar_coeff_lag : 2;
899
+ unsigned short ar_coeff_shift_minus6 : 2;
900
+ unsigned short grain_scale_shift : 2;
901
+ unsigned short clip_to_restricted_range : 1;
902
+ unsigned short reserved6_4bits : 4; // reserved bits; must be set to 0
903
+ unsigned char num_y_points;
904
+ unsigned char scaling_points_y[14][2];
905
+ unsigned char num_cb_points;
906
+ unsigned char scaling_points_cb[10][2];
907
+ unsigned char num_cr_points;
908
+ unsigned char scaling_points_cr[10][2];
909
+ unsigned char reserved7_8bits; // reserved bits; must be set to 0
910
+ unsigned short random_seed;
911
+ short ar_coeffs_y[24];
912
+ short ar_coeffs_cb[25];
913
+ short ar_coeffs_cr[25];
914
+ unsigned char cb_mult;
915
+ unsigned char cb_luma_mult;
916
+ short cb_offset;
917
+ unsigned char cr_mult;
918
+ unsigned char cr_luma_mult;
919
+ short cr_offset;
920
+
921
+ int reserved[7]; // reserved bits; must be set to 0
922
+ } CUVIDAV1PICPARAMS;
923
+
924
+ /******************************************************************************************/
925
+ //! \struct CUVIDPICPARAMS
926
+ //! Picture parameters for decoding
927
+ //! This structure is used in cuvidDecodePicture API
928
+ //! IN for cuvidDecodePicture
929
+ /******************************************************************************************/
930
+ typedef struct _CUVIDPICPARAMS
931
+ {
932
+ int PicWidthInMbs; /**< IN: Coded frame size in macroblocks */
933
+ int FrameHeightInMbs; /**< IN: Coded frame height in macroblocks */
934
+ int CurrPicIdx; /**< IN: Output index of the current picture */
935
+ int field_pic_flag; /**< IN: 0=frame picture, 1=field picture */
936
+ int bottom_field_flag; /**< IN: 0=top field, 1=bottom field (ignored if field_pic_flag=0) */
937
+ int second_field; /**< IN: Second field of a complementary field pair */
938
+ // Bitstream data
939
+ unsigned int nBitstreamDataLen; /**< IN: Number of bytes in bitstream data buffer */
940
+ const unsigned char *pBitstreamData; /**< IN: Ptr to bitstream data for this picture (slice-layer) */
941
+ unsigned int nNumSlices; /**< IN: Number of slices in this picture */
942
+ const unsigned int *pSliceDataOffsets; /**< IN: nNumSlices entries, contains offset of each slice within
943
+ the bitstream data buffer */
944
+ int ref_pic_flag; /**< IN: This picture is a reference picture */
945
+ int intra_pic_flag; /**< IN: This picture is entirely intra coded */
946
+ unsigned int Reserved[30]; /**< Reserved for future use */
947
+ // IN: Codec-specific data
948
+ union {
949
+ CUVIDMPEG2PICPARAMS mpeg2; /**< Also used for MPEG-1 */
950
+ CUVIDH264PICPARAMS h264;
951
+ CUVIDVC1PICPARAMS vc1;
952
+ CUVIDMPEG4PICPARAMS mpeg4;
953
+ CUVIDJPEGPICPARAMS jpeg;
954
+ CUVIDHEVCPICPARAMS hevc;
955
+ CUVIDVP8PICPARAMS vp8;
956
+ CUVIDVP9PICPARAMS vp9;
957
+ CUVIDAV1PICPARAMS av1;
958
+ unsigned int CodecReserved[1024];
959
+ } CodecSpecific;
960
+ } CUVIDPICPARAMS;
961
+
962
+
963
+ /******************************************************/
964
+ //! \struct CUVIDPROCPARAMS
965
+ //! Picture parameters for postprocessing
966
+ //! This structure is used in cuvidMapVideoFrame API
967
+ /******************************************************/
968
+ typedef struct _CUVIDPROCPARAMS
969
+ {
970
+ int progressive_frame; /**< IN: Input is progressive (deinterlace_mode will be ignored) */
971
+ int second_field; /**< IN: Output the second field (ignored if deinterlace mode is Weave) */
972
+ int top_field_first; /**< IN: Input frame is top field first (1st field is top, 2nd field is bottom) */
973
+ int unpaired_field; /**< IN: Input only contains one field (2nd field is invalid) */
974
+ // The fields below are used for raw YUV input
975
+ unsigned int reserved_flags; /**< Reserved for future use (set to zero) */
976
+ unsigned int reserved_zero; /**< Reserved (set to zero) */
977
+ unsigned long long raw_input_dptr; /**< IN: Input CUdeviceptr for raw YUV extensions */
978
+ unsigned int raw_input_pitch; /**< IN: pitch in bytes of raw YUV input (should be aligned appropriately) */
979
+ unsigned int raw_input_format; /**< IN: Input YUV format (cudaVideoCodec_enum) */
980
+ unsigned long long raw_output_dptr; /**< IN: Output CUdeviceptr for raw YUV extensions */
981
+ unsigned int raw_output_pitch; /**< IN: pitch in bytes of raw YUV output (should be aligned appropriately) */
982
+ unsigned int Reserved1; /**< Reserved for future use (set to zero) */
983
+ CUstream output_stream; /**< IN: stream object used by cuvidMapVideoFrame */
984
+ unsigned int Reserved[46]; /**< Reserved for future use (set to zero) */
985
+ unsigned long long *histogram_dptr; /**< OUT: Output CUdeviceptr for histogram extensions */
986
+ void *Reserved2[1]; /**< Reserved for future use (set to zero) */
987
+ } CUVIDPROCPARAMS;
988
+
989
+ /*********************************************************************************************************/
990
+ //! \struct CUVIDGETDECODESTATUS
991
+ //! Struct for reporting decode status.
992
+ //! This structure is used in cuvidGetDecodeStatus API.
993
+ /*********************************************************************************************************/
994
+ typedef struct _CUVIDGETDECODESTATUS
995
+ {
996
+ cuvidDecodeStatus decodeStatus;
997
+ unsigned int reserved[31];
998
+ void *pReserved[8];
999
+ } CUVIDGETDECODESTATUS;
1000
+
1001
+ /****************************************************/
1002
+ //! \struct CUVIDRECONFIGUREDECODERINFO
1003
+ //! Struct for decoder reset
1004
+ //! This structure is used in cuvidReconfigureDecoder() API
1005
+ /****************************************************/
1006
+ typedef struct _CUVIDRECONFIGUREDECODERINFO
1007
+ {
1008
+ unsigned int ulWidth; /**< IN: Coded sequence width in pixels, MUST be < = ulMaxWidth defined at CUVIDDECODECREATEINFO */
1009
+ unsigned int ulHeight; /**< IN: Coded sequence height in pixels, MUST be < = ulMaxHeight defined at CUVIDDECODECREATEINFO */
1010
+ unsigned int ulTargetWidth; /**< IN: Post processed output width */
1011
+ unsigned int ulTargetHeight; /**< IN: Post Processed output height */
1012
+ unsigned int ulNumDecodeSurfaces; /**< IN: Maximum number of internal decode surfaces */
1013
+ unsigned int reserved1[12]; /**< Reserved for future use. Set to Zero */
1014
+ /**
1015
+ * IN: Area of frame to be displayed. Use-case : Source Cropping
1016
+ */
1017
+ struct {
1018
+ short left;
1019
+ short top;
1020
+ short right;
1021
+ short bottom;
1022
+ } display_area;
1023
+ /**
1024
+ * IN: Target Rectangle in the OutputFrame. Use-case : Aspect ratio Conversion
1025
+ */
1026
+ struct {
1027
+ short left;
1028
+ short top;
1029
+ short right;
1030
+ short bottom;
1031
+ } target_rect;
1032
+ unsigned int reserved2[11]; /**< Reserved for future use. Set to Zero */
1033
+ } CUVIDRECONFIGUREDECODERINFO;
1034
+
1035
+
1036
+ /***********************************************************************************************************/
1037
+ //! VIDEO_DECODER
1038
+ //!
1039
+ //! In order to minimize decode latencies, there should be always at least 2 pictures in the decode
1040
+ //! queue at any time, in order to make sure that all decode engines are always busy.
1041
+ //!
1042
+ //! Overall data flow:
1043
+ //! - cuvidGetDecoderCaps(...)
1044
+ //! - cuvidCreateDecoder(...)
1045
+ //! - For each picture:
1046
+ //! + cuvidDecodePicture(N)
1047
+ //! + cuvidMapVideoFrame(N-4)
1048
+ //! + do some processing in cuda
1049
+ //! + cuvidUnmapVideoFrame(N-4)
1050
+ //! + cuvidDecodePicture(N+1)
1051
+ //! + cuvidMapVideoFrame(N-3)
1052
+ //! + ...
1053
+ //! - cuvidDestroyDecoder(...)
1054
+ //!
1055
+ //! NOTE:
1056
+ //! - When the cuda context is created from a D3D device, the D3D device must also be created
1057
+ //! with the D3DCREATE_MULTITHREADED flag.
1058
+ //! - There is a limit to how many pictures can be mapped simultaneously (ulNumOutputSurfaces)
1059
+ //! - cuvidDecodePicture may block the calling thread if there are too many pictures pending
1060
+ //! in the decode queue
1061
+ /***********************************************************************************************************/
1062
+
1063
+
1064
+ /**********************************************************************************************************************/
1065
+ //! \fn CUresult CUDAAPI cuvidGetDecoderCaps(CUVIDDECODECAPS *pdc)
1066
+ //! Queries decode capabilities of NVDEC-HW based on CodecType, ChromaFormat and BitDepthMinus8 parameters.
1067
+ //! 1. Application fills IN parameters CodecType, ChromaFormat and BitDepthMinus8 of CUVIDDECODECAPS structure
1068
+ //! 2. On calling cuvidGetDecoderCaps, driver fills OUT parameters if the IN parameters are supported
1069
+ //! If IN parameters passed to the driver are not supported by NVDEC-HW, then all OUT params are set to 0.
1070
+ //! E.g. on Geforce GTX 960:
1071
+ //! App fills - eCodecType = cudaVideoCodec_H264; eChromaFormat = cudaVideoChromaFormat_420; nBitDepthMinus8 = 0;
1072
+ //! Given IN parameters are supported, hence driver fills: bIsSupported = 1; nMinWidth = 48; nMinHeight = 16;
1073
+ //! nMaxWidth = 4096; nMaxHeight = 4096; nMaxMBCount = 65536;
1074
+ //! CodedWidth*CodedHeight/256 must be less than or equal to nMaxMBCount
1075
+ /**********************************************************************************************************************/
1076
+ extern CUresult CUDAAPI cuvidGetDecoderCaps(CUVIDDECODECAPS *pdc);
1077
+
1078
+ /*****************************************************************************************************/
1079
+ //! \fn CUresult CUDAAPI cuvidCreateDecoder(CUvideodecoder *phDecoder, CUVIDDECODECREATEINFO *pdci)
1080
+ //! Create the decoder object based on pdci. A handle to the created decoder is returned
1081
+ /*****************************************************************************************************/
1082
+ extern CUresult CUDAAPI cuvidCreateDecoder(CUvideodecoder *phDecoder, CUVIDDECODECREATEINFO *pdci);
1083
+
1084
+ /*****************************************************************************************************/
1085
+ //! \fn CUresult CUDAAPI cuvidDestroyDecoder(CUvideodecoder hDecoder)
1086
+ //! Destroy the decoder object
1087
+ /*****************************************************************************************************/
1088
+ extern CUresult CUDAAPI cuvidDestroyDecoder(CUvideodecoder hDecoder);
1089
+
1090
+ /*****************************************************************************************************/
1091
+ //! \fn CUresult CUDAAPI cuvidDecodePicture(CUvideodecoder hDecoder, CUVIDPICPARAMS *pPicParams)
1092
+ //! Decode a single picture (field or frame)
1093
+ //! Kicks off HW decoding
1094
+ /*****************************************************************************************************/
1095
+ extern CUresult CUDAAPI cuvidDecodePicture(CUvideodecoder hDecoder, CUVIDPICPARAMS *pPicParams);
1096
+
1097
+ /************************************************************************************************************/
1098
+ //! \fn CUresult CUDAAPI cuvidGetDecodeStatus(CUvideodecoder hDecoder, int nPicIdx);
1099
+ //! Get the decode status for frame corresponding to nPicIdx
1100
+ //! API is supported for Maxwell and above generation GPUs.
1101
+ //! API is currently supported for HEVC, H264 and JPEG codecs.
1102
+ //! API returns CUDA_ERROR_NOT_SUPPORTED error code for unsupported GPU or codec.
1103
+ /************************************************************************************************************/
1104
+ extern CUresult CUDAAPI cuvidGetDecodeStatus(CUvideodecoder hDecoder, int nPicIdx, CUVIDGETDECODESTATUS* pDecodeStatus);
1105
+
1106
+ /*********************************************************************************************************/
1107
+ //! \fn CUresult CUDAAPI cuvidReconfigureDecoder(CUvideodecoder hDecoder, CUVIDRECONFIGUREDECODERINFO *pDecReconfigParams)
1108
+ //! Used to reuse single decoder for multiple clips. Currently supports resolution change, resize params, display area
1109
+ //! params, target area params change for same codec. Must be called during CUVIDPARSERPARAMS::pfnSequenceCallback
1110
+ /*********************************************************************************************************/
1111
+ extern CUresult CUDAAPI cuvidReconfigureDecoder(CUvideodecoder hDecoder, CUVIDRECONFIGUREDECODERINFO *pDecReconfigParams);
1112
+
1113
+
1114
+ #if !defined(__CUVID_DEVPTR64) || defined(__CUVID_INTERNAL)
1115
+ /************************************************************************************************************************/
1116
+ //! \fn CUresult CUDAAPI cuvidMapVideoFrame(CUvideodecoder hDecoder, int nPicIdx, unsigned int *pDevPtr,
1117
+ //! unsigned int *pPitch, CUVIDPROCPARAMS *pVPP);
1118
+ //! Post-process and map video frame corresponding to nPicIdx for use in cuda. Returns cuda device pointer and associated
1119
+ //! pitch of the video frame
1120
+ /************************************************************************************************************************/
1121
+ extern CUresult CUDAAPI cuvidMapVideoFrame(CUvideodecoder hDecoder, int nPicIdx,
1122
+ unsigned int *pDevPtr, unsigned int *pPitch,
1123
+ CUVIDPROCPARAMS *pVPP);
1124
+
1125
+ /*****************************************************************************************************/
1126
+ //! \fn CUresult CUDAAPI cuvidUnmapVideoFrame(CUvideodecoder hDecoder, unsigned int DevPtr)
1127
+ //! Unmap a previously mapped video frame
1128
+ /*****************************************************************************************************/
1129
+ extern CUresult CUDAAPI cuvidUnmapVideoFrame(CUvideodecoder hDecoder, unsigned int DevPtr);
1130
+ #endif
1131
+
1132
+ /****************************************************************************************************************************/
1133
+ //! \fn CUresult CUDAAPI cuvidMapVideoFrame64(CUvideodecoder hDecoder, int nPicIdx, unsigned long long *pDevPtr,
1134
+ //! unsigned int * pPitch, CUVIDPROCPARAMS *pVPP);
1135
+ //! Post-process and map video frame corresponding to nPicIdx for use in cuda. Returns cuda device pointer and associated
1136
+ //! pitch of the video frame
1137
+ /****************************************************************************************************************************/
1138
+ extern CUresult CUDAAPI cuvidMapVideoFrame64(CUvideodecoder hDecoder, int nPicIdx, unsigned long long *pDevPtr,
1139
+ unsigned int *pPitch, CUVIDPROCPARAMS *pVPP);
1140
+
1141
+ /**************************************************************************************************/
1142
+ //! \fn CUresult CUDAAPI cuvidUnmapVideoFrame64(CUvideodecoder hDecoder, unsigned long long DevPtr);
1143
+ //! Unmap a previously mapped video frame
1144
+ /**************************************************************************************************/
1145
+ extern CUresult CUDAAPI cuvidUnmapVideoFrame64(CUvideodecoder hDecoder, unsigned long long DevPtr);
1146
+
1147
+ #if defined(__CUVID_DEVPTR64) && !defined(__CUVID_INTERNAL)
1148
+ #define cuvidMapVideoFrame cuvidMapVideoFrame64
1149
+ #define cuvidUnmapVideoFrame cuvidUnmapVideoFrame64
1150
+ #endif
1151
+
1152
+
1153
+
1154
+ /********************************************************************************************************************/
1155
+ //!
1156
+ //! Context-locking: to facilitate multi-threaded implementations, the following 4 functions
1157
+ //! provide a simple mutex-style host synchronization. If a non-NULL context is specified
1158
+ //! in CUVIDDECODECREATEINFO, the codec library will acquire the mutex associated with the given
1159
+ //! context before making any cuda calls.
1160
+ //! A multi-threaded application could create a lock associated with a context handle so that
1161
+ //! multiple threads can safely share the same cuda context:
1162
+ //! - use cuCtxPopCurrent immediately after context creation in order to create a 'floating' context
1163
+ //! that can be passed to cuvidCtxLockCreate.
1164
+ //! - When using a floating context, all cuda calls should only be made within a cuvidCtxLock/cuvidCtxUnlock section.
1165
+ //!
1166
+ //! NOTE: This is a safer alternative to cuCtxPushCurrent and cuCtxPopCurrent, and is not related to video
1167
+ //! decoder in any way (implemented as a critical section associated with cuCtx{Push|Pop}Current calls).
1168
+ /********************************************************************************************************************/
1169
+
1170
+ /********************************************************************************************************************/
1171
+ //! \fn CUresult CUDAAPI cuvidCtxLockCreate(CUvideoctxlock *pLock, CUcontext ctx)
1172
+ //! This API is used to create CtxLock object
1173
+ /********************************************************************************************************************/
1174
+ extern CUresult CUDAAPI cuvidCtxLockCreate(CUvideoctxlock *pLock, CUcontext ctx);
1175
+
1176
+ /********************************************************************************************************************/
1177
+ //! \fn CUresult CUDAAPI cuvidCtxLockDestroy(CUvideoctxlock lck)
1178
+ //! This API is used to free CtxLock object
1179
+ /********************************************************************************************************************/
1180
+ extern CUresult CUDAAPI cuvidCtxLockDestroy(CUvideoctxlock lck);
1181
+
1182
+ /********************************************************************************************************************/
1183
+ //! \fn CUresult CUDAAPI cuvidCtxLock(CUvideoctxlock lck, unsigned int reserved_flags)
1184
+ //! This API is used to acquire ctxlock
1185
+ /********************************************************************************************************************/
1186
+ extern CUresult CUDAAPI cuvidCtxLock(CUvideoctxlock lck, unsigned int reserved_flags);
1187
+
1188
+ /********************************************************************************************************************/
1189
+ //! \fn CUresult CUDAAPI cuvidCtxUnlock(CUvideoctxlock lck, unsigned int reserved_flags)
1190
+ //! This API is used to release ctxlock
1191
+ /********************************************************************************************************************/
1192
+ extern CUresult CUDAAPI cuvidCtxUnlock(CUvideoctxlock lck, unsigned int reserved_flags);
1193
+
1194
+ /**********************************************************************************************/
1195
+
1196
+ #if defined(__cplusplus)
1197
+ }
1198
+ // Auto-lock helper for C++ applications
1199
+ class CCtxAutoLock
1200
+ {
1201
+ private:
1202
+ CUvideoctxlock m_ctx;
1203
+ public:
1204
+ CCtxAutoLock(CUvideoctxlock ctx):m_ctx(ctx) { cuvidCtxLock(m_ctx,0); }
1205
+ ~CCtxAutoLock() { cuvidCtxUnlock(m_ctx,0); }
1206
+ };
1207
+ #endif /* __cplusplus */
1208
+
1209
+ #endif // __CUDA_VIDEO_H__
video_codec_sdk/Interface/nvEncodeAPI.h ADDED
The diff for this file is too large to render. See raw diff
 
video_codec_sdk/Interface/nvcuvid.h ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * This copyright notice applies to this header file only:
3
+ *
4
+ * Copyright (c) 2010-2024 NVIDIA Corporation
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person
7
+ * obtaining a copy of this software and associated documentation
8
+ * files (the "Software"), to deal in the Software without
9
+ * restriction, including without limitation the rights to use,
10
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the software, and to permit persons to whom the
12
+ * software is furnished to do so, subject to the following
13
+ * conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be
16
+ * included in all copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25
+ * OTHER DEALINGS IN THE SOFTWARE.
26
+ */
27
+
28
+ /********************************************************************************************************************/
29
+ //! \file nvcuvid.h
30
+ //! NVDECODE API provides video decoding interface to NVIDIA GPU devices.
31
+ //! \date 2015-2024
32
+ //! This file contains the interface constants, structure definitions and function prototypes.
33
+ /********************************************************************************************************************/
34
+
35
+ #if !defined(__NVCUVID_H__)
36
+ #define __NVCUVID_H__
37
+
38
+ #include "cuviddec.h"
39
+
40
+ #if defined(__cplusplus)
41
+ extern "C" {
42
+ #endif /* __cplusplus */
43
+
44
+ #define MAX_CLOCK_TS 3
45
+
46
+ /***********************************************/
47
+ //!
48
+ //! High-level helper APIs for video sources
49
+ //!
50
+ /***********************************************/
51
+
52
+ typedef void *CUvideosource;
53
+ typedef void *CUvideoparser;
54
+ typedef long long CUvideotimestamp;
55
+
56
+
57
+ /************************************************************************/
58
+ //! \enum cudaVideoState
59
+ //! Video source state enums
60
+ //! Used in cuvidSetVideoSourceState and cuvidGetVideoSourceState APIs
61
+ /************************************************************************/
62
+ typedef enum {
63
+ cudaVideoState_Error = -1, /**< Error state (invalid source) */
64
+ cudaVideoState_Stopped = 0, /**< Source is stopped (or reached end-of-stream) */
65
+ cudaVideoState_Started = 1 /**< Source is running and delivering data */
66
+ } cudaVideoState;
67
+
68
+ /************************************************************************/
69
+ //! \enum cudaAudioCodec
70
+ //! Audio compression enums
71
+ //! Used in CUAUDIOFORMAT structure
72
+ /************************************************************************/
73
+ typedef enum {
74
+ cudaAudioCodec_MPEG1=0, /**< MPEG-1 Audio */
75
+ cudaAudioCodec_MPEG2, /**< MPEG-2 Audio */
76
+ cudaAudioCodec_MP3, /**< MPEG-1 Layer III Audio */
77
+ cudaAudioCodec_AC3, /**< Dolby Digital (AC3) Audio */
78
+ cudaAudioCodec_LPCM, /**< PCM Audio */
79
+ cudaAudioCodec_AAC, /**< AAC Audio */
80
+ } cudaAudioCodec;
81
+
82
+ /************************************************************************/
83
+ //! \ingroup STRUCTS
84
+ //! \struct TIMECODESET
85
+ //! Used to store Time code set extracted from H264 and HEVC codecs
86
+ /************************************************************************/
87
+ typedef struct _TIMECODESET
88
+ {
89
+ unsigned int time_offset_value;
90
+ unsigned short n_frames;
91
+ unsigned char clock_timestamp_flag;
92
+ unsigned char units_field_based_flag;
93
+ unsigned char counting_type;
94
+ unsigned char full_timestamp_flag;
95
+ unsigned char discontinuity_flag;
96
+ unsigned char cnt_dropped_flag;
97
+ unsigned char seconds_value;
98
+ unsigned char minutes_value;
99
+ unsigned char hours_value;
100
+ unsigned char seconds_flag;
101
+ unsigned char minutes_flag;
102
+ unsigned char hours_flag;
103
+ unsigned char time_offset_length;
104
+ unsigned char reserved;
105
+ } TIMECODESET;
106
+
107
+ /************************************************************************/
108
+ //! \ingroup STRUCTS
109
+ //! \struct TIMECODE
110
+ //! Used to extract Time code in H264 and HEVC codecs
111
+ /************************************************************************/
112
+ typedef struct _TIMECODE
113
+ {
114
+ TIMECODESET time_code_set[MAX_CLOCK_TS];
115
+ unsigned char num_clock_ts;
116
+ } TIMECODE;
117
+
118
+ /**********************************************************************************/
119
+ //! \ingroup STRUCTS
120
+ //! \struct SEIMASTERINGDISPLAYINFO
121
+ //! Used to extract mastering display color volume SEI in H264 and HEVC codecs
122
+ /**********************************************************************************/
123
+ typedef struct _SEIMASTERINGDISPLAYINFO
124
+ {
125
+ unsigned short display_primaries_x[3];
126
+ unsigned short display_primaries_y[3];
127
+ unsigned short white_point_x;
128
+ unsigned short white_point_y;
129
+ unsigned int max_display_mastering_luminance;
130
+ unsigned int min_display_mastering_luminance;
131
+ } SEIMASTERINGDISPLAYINFO;
132
+
133
+ /**********************************************************************************/
134
+ //! \ingroup STRUCTS
135
+ //! \struct SEICONTENTLIGHTLEVELINFO
136
+ //! Used to extract content light level info SEI in H264 and HEVC codecs
137
+ /**********************************************************************************/
138
+ typedef struct _SEICONTENTLIGHTLEVELINFO
139
+ {
140
+ unsigned short max_content_light_level;
141
+ unsigned short max_pic_average_light_level;
142
+ unsigned int reserved;
143
+ } SEICONTENTLIGHTLEVELINFO;
144
+
145
+ /**********************************************************************************/
146
+ //! \ingroup STRUCTS
147
+ //! \struct TIMECODEMPEG2
148
+ //! Used to extract Time code in MPEG2 codec
149
+ /**********************************************************************************/
150
+ typedef struct _TIMECODEMPEG2
151
+ {
152
+ unsigned char drop_frame_flag;
153
+ unsigned char time_code_hours;
154
+ unsigned char time_code_minutes;
155
+ unsigned char marker_bit;
156
+ unsigned char time_code_seconds;
157
+ unsigned char time_code_pictures;
158
+ } TIMECODEMPEG2;
159
+
160
+ /**********************************************************************************/
161
+ //! \ingroup STRUCTS
162
+ //! \struct SEIALTERNATIVETRANSFERCHARACTERISTICS
163
+ //! Used to extract alternative transfer characteristics SEI in H264 and HEVC codecs
164
+ /**********************************************************************************/
165
+ typedef struct _SEIALTERNATIVETRANSFERCHARACTERISTICS
166
+ {
167
+ unsigned char preferred_transfer_characteristics;
168
+ } SEIALTERNATIVETRANSFERCHARACTERISTICS;
169
+
170
+ /**********************************************************************************/
171
+ //! \ingroup STRUCTS
172
+ //! \struct CUSEIMESSAGE;
173
+ //! Used in CUVIDSEIMESSAGEINFO structure
174
+ /**********************************************************************************/
175
+ typedef struct _CUSEIMESSAGE
176
+ {
177
+ unsigned char sei_message_type; /**< OUT: SEI Message Type */
178
+ unsigned char reserved[3];
179
+ unsigned int sei_message_size; /**< OUT: SEI Message Size */
180
+ } CUSEIMESSAGE;
181
+
182
+ /************************************************************************************************/
183
+ //! \ingroup STRUCTS
184
+ //! \struct CUVIDEOFORMAT
185
+ //! Video format
186
+ //! Used in cuvidGetSourceVideoFormat API
187
+ /************************************************************************************************/
188
+ typedef struct
189
+ {
190
+ cudaVideoCodec codec; /**< OUT: Compression format */
191
+ /**
192
+ * OUT: frame rate = numerator / denominator (for example: 30000/1001)
193
+ */
194
+ struct {
195
+ /**< OUT: frame rate numerator (0 = unspecified or variable frame rate) */
196
+ unsigned int numerator;
197
+ /**< OUT: frame rate denominator (0 = unspecified or variable frame rate) */
198
+ unsigned int denominator;
199
+ } frame_rate;
200
+ unsigned char progressive_sequence; /**< OUT: 0=interlaced, 1=progressive */
201
+ unsigned char bit_depth_luma_minus8; /**< OUT: high bit depth luma. E.g, 2 for 10-bitdepth, 4 for 12-bitdepth */
202
+ unsigned char bit_depth_chroma_minus8; /**< OUT: high bit depth chroma. E.g, 2 for 10-bitdepth, 4 for 12-bitdepth */
203
+ unsigned char min_num_decode_surfaces; /**< OUT: Minimum number of decode surfaces to be allocated for correct
204
+ decoding. The client can send this value in ulNumDecodeSurfaces
205
+ (in CUVIDDECODECREATEINFO structure).
206
+ This guarantees correct functionality and optimal video memory
207
+ usage but not necessarily the best performance, which depends on
208
+ the design of the overall application. The optimal number of
209
+ decode surfaces (in terms of performance and memory utilization)
210
+ should be decided by experimentation for each application, but it
211
+ cannot go below min_num_decode_surfaces.
212
+ If this value is used for ulNumDecodeSurfaces then it must be
213
+ returned to parser during sequence callback. */
214
+ unsigned int coded_width; /**< OUT: coded frame width in pixels */
215
+ unsigned int coded_height; /**< OUT: coded frame height in pixels */
216
+ /**
217
+ * area of the frame that should be displayed
218
+ * typical example:
219
+ * coded_width = 1920, coded_height = 1088
220
+ * display_area = { 0,0,1920,1080 }
221
+ */
222
+ struct {
223
+ int left; /**< OUT: left position of display rect */
224
+ int top; /**< OUT: top position of display rect */
225
+ int right; /**< OUT: right position of display rect */
226
+ int bottom; /**< OUT: bottom position of display rect */
227
+ } display_area;
228
+ cudaVideoChromaFormat chroma_format; /**< OUT: Chroma format */
229
+ unsigned int bitrate; /**< OUT: video bitrate (bps, 0=unknown) */
230
+ /**
231
+ * OUT: Display Aspect Ratio = x:y (4:3, 16:9, etc)
232
+ */
233
+ struct {
234
+ int x;
235
+ int y;
236
+ } display_aspect_ratio;
237
+ /**
238
+ * Video Signal Description
239
+ * Refer section E.2.1 (VUI parameters semantics) of H264 spec file
240
+ */
241
+ struct {
242
+ unsigned char video_format : 3; /**< OUT: 0-Component, 1-PAL, 2-NTSC, 3-SECAM, 4-MAC, 5-Unspecified */
243
+ unsigned char video_full_range_flag : 1; /**< OUT: indicates the black level and luma and chroma range */
244
+ unsigned char reserved_zero_bits : 4; /**< Reserved bits */
245
+ unsigned char color_primaries; /**< OUT: chromaticity coordinates of source primaries */
246
+ unsigned char transfer_characteristics; /**< OUT: opto-electronic transfer characteristic of the source picture */
247
+ unsigned char matrix_coefficients; /**< OUT: used in deriving luma and chroma signals from RGB primaries */
248
+ } video_signal_description;
249
+ unsigned int seqhdr_data_length; /**< OUT: Additional bytes following (CUVIDEOFORMATEX) */
250
+ } CUVIDEOFORMAT;
251
+
252
+ /****************************************************************/
253
+ //! \ingroup STRUCTS
254
+ //! \struct CUVIDOPERATINGPOINTINFO
255
+ //! Operating point information of scalable bitstream
256
+ /****************************************************************/
257
+ typedef struct
258
+ {
259
+ cudaVideoCodec codec;
260
+ union
261
+ {
262
+ struct
263
+ {
264
+ unsigned char operating_points_cnt;
265
+ unsigned char reserved24_bits[3];
266
+ unsigned short operating_points_idc[32];
267
+ } av1;
268
+ unsigned char CodecReserved[1024];
269
+ };
270
+ } CUVIDOPERATINGPOINTINFO;
271
+
272
+ /**********************************************************************************/
273
+ //! \ingroup STRUCTS
274
+ //! \struct CUVIDSEIMESSAGEINFO
275
+ //! Used in cuvidParseVideoData API with PFNVIDSEIMSGCALLBACK pfnGetSEIMsg
276
+ /**********************************************************************************/
277
+ typedef struct _CUVIDSEIMESSAGEINFO
278
+ {
279
+ void *pSEIData; /**< OUT: SEI Message Data */
280
+ CUSEIMESSAGE *pSEIMessage; /**< OUT: SEI Message Info */
281
+ unsigned int sei_message_count; /**< OUT: SEI Message Count */
282
+ unsigned int picIdx; /**< OUT: SEI Message Pic Index */
283
+ } CUVIDSEIMESSAGEINFO;
284
+
285
+ /****************************************************************/
286
+ //! \ingroup STRUCTS
287
+ //! \struct CUVIDAV1SEQHDR
288
+ //! AV1 specific sequence header information
289
+ /****************************************************************/
290
+ typedef struct {
291
+ unsigned int max_width;
292
+ unsigned int max_height;
293
+ unsigned char reserved[1016];
294
+ } CUVIDAV1SEQHDR;
295
+
296
+ /****************************************************************/
297
+ //! \ingroup STRUCTS
298
+ //! \struct CUVIDEOFORMATEX
299
+ //! Video format including raw sequence header information
300
+ //! Used in cuvidGetSourceVideoFormat API
301
+ /****************************************************************/
302
+ typedef struct
303
+ {
304
+ CUVIDEOFORMAT format; /**< OUT: CUVIDEOFORMAT structure */
305
+ union {
306
+ CUVIDAV1SEQHDR av1;
307
+ unsigned char raw_seqhdr_data[1024]; /**< OUT: Sequence header data */
308
+ };
309
+ } CUVIDEOFORMATEX;
310
+
311
+ /****************************************************************/
312
+ //! \ingroup STRUCTS
313
+ //! \struct CUAUDIOFORMAT
314
+ //! Audio formats
315
+ //! Used in cuvidGetSourceAudioFormat API
316
+ /****************************************************************/
317
+ typedef struct
318
+ {
319
+ cudaAudioCodec codec; /**< OUT: Compression format */
320
+ unsigned int channels; /**< OUT: number of audio channels */
321
+ unsigned int samplespersec; /**< OUT: sampling frequency */
322
+ unsigned int bitrate; /**< OUT: For uncompressed, can also be used to determine bits per sample */
323
+ unsigned int reserved1; /**< Reserved for future use */
324
+ unsigned int reserved2; /**< Reserved for future use */
325
+ } CUAUDIOFORMAT;
326
+
327
+
328
+ /***************************************************************/
329
+ //! \enum CUvideopacketflags
330
+ //! Data packet flags
331
+ //! Used in CUVIDSOURCEDATAPACKET structure
332
+ /***************************************************************/
333
+ typedef enum {
334
+ CUVID_PKT_ENDOFSTREAM = 0x01, /**< Set when this is the last packet for this stream */
335
+ CUVID_PKT_TIMESTAMP = 0x02, /**< Timestamp is valid */
336
+ CUVID_PKT_DISCONTINUITY = 0x04, /**< Set when a discontinuity has to be signalled */
337
+ CUVID_PKT_ENDOFPICTURE = 0x08, /**< Set when the packet contains exactly one frame or one field */
338
+ CUVID_PKT_NOTIFY_EOS = 0x10, /**< If this flag is set along with CUVID_PKT_ENDOFSTREAM, an additional (dummy)
339
+ display callback will be invoked with null value of CUVIDPARSERDISPINFO which
340
+ should be interpreted as end of the stream. */
341
+ } CUvideopacketflags;
342
+
343
+ /*****************************************************************************/
344
+ //! \ingroup STRUCTS
345
+ //! \struct CUVIDSOURCEDATAPACKET
346
+ //! Data Packet
347
+ //! Used in cuvidParseVideoData API
348
+ //! IN for cuvidParseVideoData
349
+ /*****************************************************************************/
350
+ typedef struct _CUVIDSOURCEDATAPACKET
351
+ {
352
+ unsigned long flags; /**< IN: Combination of CUVID_PKT_XXX flags */
353
+ unsigned long payload_size; /**< IN: number of bytes in the payload (may be zero if EOS flag is set) */
354
+ const unsigned char *payload; /**< IN: Pointer to packet payload data (may be NULL if EOS flag is set) */
355
+ CUvideotimestamp timestamp; /**< IN: Presentation time stamp (10MHz clock), only valid if
356
+ CUVID_PKT_TIMESTAMP flag is set */
357
+ } CUVIDSOURCEDATAPACKET;
358
+
359
+ // Callback for packet delivery
360
+ typedef int (CUDAAPI *PFNVIDSOURCECALLBACK)(void *, CUVIDSOURCEDATAPACKET *);
361
+
362
+ /**************************************************************************************************************************/
363
+ //! \ingroup STRUCTS
364
+ //! \struct CUVIDSOURCEPARAMS
365
+ //! Describes parameters needed in cuvidCreateVideoSource API
366
+ //! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported
367
+ //! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed.
368
+ /**************************************************************************************************************************/
369
+ typedef struct _CUVIDSOURCEPARAMS
370
+ {
371
+ unsigned int ulClockRate; /**< IN: Time stamp units in Hz (0=default=10000000Hz) */
372
+ unsigned int bAnnexb : 1; /**< IN: AV1 annexB stream */
373
+ unsigned int uReserved : 31; /**< Reserved for future use - set to zero */
374
+ unsigned int uReserved1[6]; /**< Reserved for future use - set to zero */
375
+ void *pUserData; /**< IN: User private data passed in to the data handlers */
376
+ PFNVIDSOURCECALLBACK pfnVideoDataHandler; /**< IN: Called to deliver video packets */
377
+ PFNVIDSOURCECALLBACK pfnAudioDataHandler; /**< IN: Called to deliver audio packets. */
378
+ void *pvReserved2[8]; /**< Reserved for future use - set to NULL */
379
+ } CUVIDSOURCEPARAMS;
380
+
381
+
382
+ /**********************************************/
383
+ //! \ingroup ENUMS
384
+ //! \enum CUvideosourceformat_flags
385
+ //! CUvideosourceformat_flags
386
+ //! Used in cuvidGetSourceVideoFormat API
387
+ /**********************************************/
388
+ typedef enum {
389
+ CUVID_FMT_EXTFORMATINFO = 0x100 /**< Return extended format structure (CUVIDEOFORMATEX) */
390
+ } CUvideosourceformat_flags;
391
+
392
+ #if !defined(__APPLE__)
393
+ /***************************************************************************************************************************/
394
+ //! \ingroup FUNCTS
395
+ //! \fn CUresult CUDAAPI cuvidCreateVideoSource(CUvideosource *pObj, const char *pszFileName, CUVIDSOURCEPARAMS *pParams)
396
+ //! Create CUvideosource object. CUvideosource spawns demultiplexer thread that provides two callbacks:
397
+ //! pfnVideoDataHandler() and pfnAudioDataHandler()
398
+ //! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported
399
+ //! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed.
400
+ /***************************************************************************************************************************/
401
+ CUresult CUDAAPI cuvidCreateVideoSource(CUvideosource *pObj, const char *pszFileName, CUVIDSOURCEPARAMS *pParams);
402
+
403
+ /***************************************************************************************************************************/
404
+ //! \ingroup FUNCTS
405
+ //! \fn CUresult CUDAAPI cuvidCreateVideoSourceW(CUvideosource *pObj, const wchar_t *pwszFileName, CUVIDSOURCEPARAMS *pParams)
406
+ //! Create video source
407
+ /***************************************************************************************************************************/
408
+ CUresult CUDAAPI cuvidCreateVideoSourceW(CUvideosource *pObj, const wchar_t *pwszFileName, CUVIDSOURCEPARAMS *pParams);
409
+
410
+ /********************************************************************/
411
+ //! \ingroup FUNCTS
412
+ //! \fn CUresult CUDAAPI cuvidDestroyVideoSource(CUvideosource obj)
413
+ //! Destroy video source
414
+ /********************************************************************/
415
+ CUresult CUDAAPI cuvidDestroyVideoSource(CUvideosource obj);
416
+
417
+ /******************************************************************************************/
418
+ //! \ingroup FUNCTS
419
+ //! \fn CUresult CUDAAPI cuvidSetVideoSourceState(CUvideosource obj, cudaVideoState state)
420
+ //! Set video source state to:
421
+ //! cudaVideoState_Started - to signal the source to run and deliver data
422
+ //! cudaVideoState_Stopped - to stop the source from delivering the data
423
+ //! cudaVideoState_Error - invalid source
424
+ /******************************************************************************************/
425
+ CUresult CUDAAPI cuvidSetVideoSourceState(CUvideosource obj, cudaVideoState state);
426
+
427
+ /******************************************************************************************/
428
+ //! \ingroup FUNCTS
429
+ //! \fn cudaVideoState CUDAAPI cuvidGetVideoSourceState(CUvideosource obj)
430
+ //! Get video source state
431
+ //! Returns:
432
+ //! cudaVideoState_Started - if Source is running and delivering data
433
+ //! cudaVideoState_Stopped - if Source is stopped or reached end-of-stream
434
+ //! cudaVideoState_Error - if Source is in error state
435
+ /******************************************************************************************/
436
+ cudaVideoState CUDAAPI cuvidGetVideoSourceState(CUvideosource obj);
437
+
438
+ /******************************************************************************************************************/
439
+ //! \ingroup FUNCTS
440
+ //! \fn CUresult CUDAAPI cuvidGetSourceVideoFormat(CUvideosource obj, CUVIDEOFORMAT *pvidfmt, unsigned int flags)
441
+ //! Gets video source format in pvidfmt, flags is set to combination of CUvideosourceformat_flags as per requirement
442
+ /******************************************************************************************************************/
443
+ CUresult CUDAAPI cuvidGetSourceVideoFormat(CUvideosource obj, CUVIDEOFORMAT *pvidfmt, unsigned int flags);
444
+
445
+ /**************************************************************************************************************************/
446
+ //! \ingroup FUNCTS
447
+ //! \fn CUresult CUDAAPI cuvidGetSourceAudioFormat(CUvideosource obj, CUAUDIOFORMAT *paudfmt, unsigned int flags)
448
+ //! Get audio source format
449
+ //! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported
450
+ //! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed.
451
+ /**************************************************************************************************************************/
452
+ CUresult CUDAAPI cuvidGetSourceAudioFormat(CUvideosource obj, CUAUDIOFORMAT *paudfmt, unsigned int flags);
453
+
454
+ #endif
455
+ /**********************************************************************************/
456
+ //! \ingroup STRUCTS
457
+ //! \struct CUVIDPARSERDISPINFO
458
+ //! Used in cuvidParseVideoData API with PFNVIDDISPLAYCALLBACK pfnDisplayPicture
459
+ /**********************************************************************************/
460
+ typedef struct _CUVIDPARSERDISPINFO
461
+ {
462
+ int picture_index; /**< OUT: Index of the current picture */
463
+ int progressive_frame; /**< OUT: 1 if progressive frame; 0 otherwise */
464
+ int top_field_first; /**< OUT: 1 if top field is displayed first; 0 otherwise */
465
+ int repeat_first_field; /**< OUT: Number of additional fields (1=ivtc, 2=frame doubling, 4=frame tripling,
466
+ -1=unpaired field) */
467
+ CUvideotimestamp timestamp; /**< OUT: Presentation time stamp */
468
+ } CUVIDPARSERDISPINFO;
469
+
470
+ /***********************************************************************************************************************/
471
+ //! Parser callbacks
472
+ //! The parser will call these synchronously from within cuvidParseVideoData(), whenever there is sequence change or a picture
473
+ //! is ready to be decoded and/or displayed. First argument in functions is "void *pUserData" member of structure CUVIDSOURCEPARAMS
474
+ //! Return values from these callbacks are interpreted as below. If the callbacks return failure, it will be propagated by
475
+ //! cuvidParseVideoData() to the application.
476
+ //! Parser picks default operating point as 0 and outputAllLayers flag as 0 if PFNVIDOPPOINTCALLBACK is not set or return value is
477
+ //! -1 or invalid operating point.
478
+ //! PFNVIDSEQUENCECALLBACK : 0: fail, 1: succeeded, > 1: override dpb size of parser (set by CUVIDPARSERPARAMS::ulMaxNumDecodeSurfaces
479
+ //! while creating parser)
480
+ //! PFNVIDDECODECALLBACK : 0: fail, >=1: succeeded
481
+ //! PFNVIDDISPLAYCALLBACK : 0: fail, >=1: succeeded
482
+ //! PFNVIDOPPOINTCALLBACK : <0: fail, >=0: succeeded (bit 0-9: OperatingPoint, bit 10-10: outputAllLayers, bit 11-30: reserved)
483
+ //! PFNVIDSEIMSGCALLBACK : 0: fail, >=1: succeeded
484
+ /***********************************************************************************************************************/
485
+ typedef int (CUDAAPI *PFNVIDSEQUENCECALLBACK)(void *, CUVIDEOFORMAT *);
486
+ typedef int (CUDAAPI *PFNVIDDECODECALLBACK)(void *, CUVIDPICPARAMS *);
487
+ typedef int (CUDAAPI *PFNVIDDISPLAYCALLBACK)(void *, CUVIDPARSERDISPINFO *);
488
+ typedef int (CUDAAPI *PFNVIDOPPOINTCALLBACK)(void *, CUVIDOPERATINGPOINTINFO*);
489
+ typedef int (CUDAAPI *PFNVIDSEIMSGCALLBACK) (void *, CUVIDSEIMESSAGEINFO *);
490
+
491
+ /**************************************/
492
+ //! \ingroup STRUCTS
493
+ //! \struct CUVIDPARSERPARAMS
494
+ //! Used in cuvidCreateVideoParser API
495
+ /**************************************/
496
+ typedef struct _CUVIDPARSERPARAMS
497
+ {
498
+ cudaVideoCodec CodecType; /**< IN: cudaVideoCodec_XXX */
499
+ unsigned int ulMaxNumDecodeSurfaces; /**< IN: Max # of decode surfaces (parser will cycle through these) */
500
+ unsigned int ulClockRate; /**< IN: Timestamp units in Hz (0=default=10000000Hz) */
501
+ unsigned int ulErrorThreshold; /**< IN: % Error threshold (0-100) for calling pfnDecodePicture (100=always
502
+ IN: call pfnDecodePicture even if picture bitstream is fully corrupted) */
503
+ unsigned int ulMaxDisplayDelay; /**< IN: Max display queue delay (improves pipelining of decode with display)
504
+ 0=no delay (recommended values: 2..4) */
505
+ unsigned int bAnnexb : 1; /**< IN: AV1 annexB stream */
506
+ unsigned int bMemoryOptimize : 1; /**< IN: Utilize minimum picIdx from dpb to allow memory saving at the
507
+ decoder layer, use cuvidReconfigureDecoder() to increase the
508
+ decode surfaces if needed (perf may get impacted) */
509
+ unsigned int uReserved : 30; /**< Reserved for future use - set to zero */
510
+ unsigned int uReserved1[4]; /**< IN: Reserved for future use - set to 0 */
511
+ void *pUserData; /**< IN: User data for callbacks */
512
+ PFNVIDSEQUENCECALLBACK pfnSequenceCallback; /**< IN: Called before decoding frames and/or whenever there is a fmt change */
513
+ PFNVIDDECODECALLBACK pfnDecodePicture; /**< IN: Called when a picture is ready to be decoded (decode order) */
514
+ PFNVIDDISPLAYCALLBACK pfnDisplayPicture; /**< IN: Called whenever a picture is ready to be displayed (display order) */
515
+ PFNVIDOPPOINTCALLBACK pfnGetOperatingPoint; /**< IN: Called from AV1 sequence header to get operating point of a AV1
516
+ scalable bitstream */
517
+ PFNVIDSEIMSGCALLBACK pfnGetSEIMsg; /**< IN: Called when all SEI messages are parsed for particular frame */
518
+ void *pvReserved2[5]; /**< Reserved for future use - set to NULL */
519
+ CUVIDEOFORMATEX *pExtVideoInfo; /**< IN: [Optional] sequence header data from system layer */
520
+ } CUVIDPARSERPARAMS;
521
+
522
+ /************************************************************************************************/
523
+ //! \ingroup FUNCTS
524
+ //! \fn CUresult CUDAAPI cuvidCreateVideoParser(CUvideoparser *pObj, CUVIDPARSERPARAMS *pParams)
525
+ //! Create video parser object and initialize
526
+ /************************************************************************************************/
527
+ CUresult CUDAAPI cuvidCreateVideoParser(CUvideoparser *pObj, CUVIDPARSERPARAMS *pParams);
528
+
529
+ /************************************************************************************************/
530
+ //! \ingroup FUNCTS
531
+ //! \fn CUresult CUDAAPI cuvidParseVideoData(CUvideoparser obj, CUVIDSOURCEDATAPACKET *pPacket)
532
+ //! Parse the video data from source data packet in pPacket
533
+ //! Extracts parameter sets like SPS, PPS, bitstream etc. from pPacket and
534
+ //! calls back pfnDecodePicture with CUVIDPICPARAMS data for kicking of HW decoding
535
+ //! calls back pfnSequenceCallback with CUVIDEOFORMAT data for initial sequence header or when
536
+ //! the decoder encounters a video format change
537
+ //! calls back pfnDisplayPicture with CUVIDPARSERDISPINFO data to display a video frame
538
+ /************************************************************************************************/
539
+ CUresult CUDAAPI cuvidParseVideoData(CUvideoparser obj, CUVIDSOURCEDATAPACKET *pPacket);
540
+
541
+ /************************************************************************************************/
542
+ //! \ingroup FUNCTS
543
+ //! \fn CUresult CUDAAPI cuvidDestroyVideoParser(CUvideoparser obj)
544
+ //! Destroy the video parser
545
+ /************************************************************************************************/
546
+ CUresult CUDAAPI cuvidDestroyVideoParser(CUvideoparser obj);
547
+
548
+ /**********************************************************************************************/
549
+
550
+ #if defined(__cplusplus)
551
+ }
552
+ #endif /* __cplusplus */
553
+
554
+ #endif // __NVCUVID_H__
video_codec_sdk/Lib/linux/stubs/aarch64/libnvcuvid.so ADDED
Binary file (4.74 kB). View file
 
video_codec_sdk/Lib/linux/stubs/aarch64/libnvidia-encode.so ADDED
Binary file (4.74 kB). View file
 
video_codec_sdk/Lib/linux/stubs/x86_64/libnvcuvid.so ADDED
Binary file (3.53 kB). View file
 
video_codec_sdk/Lib/linux/stubs/x86_64/libnvidia-encode.so ADDED
Binary file (1.48 kB). View file
 
video_codec_sdk/Lib/win/Win32/nvcuvid.lib ADDED
Binary file (9 kB). View file
 
video_codec_sdk/Lib/win/Win32/nvencodeapi.lib ADDED
Binary file (2.15 kB). View file
 
video_codec_sdk/Lib/win/x64/nvcuvid.lib ADDED
Binary file (8.15 kB). View file
 
video_codec_sdk/Lib/win/x64/nvencodeapi.lib ADDED
Binary file (2.23 kB). View file
 
video_codec_sdk/License.pdf ADDED
Binary file (45.5 kB). View file
 
video_codec_sdk/NOTICES.txt ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This SDK includes portions of FFMPEG, under the following license:
2
+
3
+ GNU LESSER GENERAL PUBLIC LICENSE
4
+ Version 3, 29 June 2007
5
+
6
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
7
+ Everyone is permitted to copy and distribute verbatim copies
8
+ of this license document, but changing it is not allowed.
9
+
10
+
11
+ This version of the GNU Lesser General Public License incorporates
12
+ the terms and conditions of version 3 of the GNU General Public
13
+ License, supplemented by the additional permissions listed below.
14
+
15
+ 0. Additional Definitions.
16
+
17
+ As used herein, "this License" refers to version 3 of the GNU Lesser
18
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
19
+ General Public License.
20
+
21
+ "The Library" refers to a covered work governed by this License,
22
+ other than an Application or a Combined Work as defined below.
23
+
24
+ An "Application" is any work that makes use of an interface provided
25
+ by the Library, but which is not otherwise based on the Library.
26
+ Defining a subclass of a class defined by the Library is deemed a mode
27
+ of using an interface provided by the Library.
28
+
29
+ A "Combined Work" is a work produced by combining or linking an
30
+ Application with the Library. The particular version of the Library
31
+ with which the Combined Work was made is also called the "Linked
32
+ Version".
33
+
34
+ The "Minimal Corresponding Source" for a Combined Work means the
35
+ Corresponding Source for the Combined Work, excluding any source code
36
+ for portions of the Combined Work that, considered in isolation, are
37
+ based on the Application, and not on the Linked Version.
38
+
39
+ The "Corresponding Application Code" for a Combined Work means the
40
+ object code and/or source code for the Application, including any data
41
+ and utility programs needed for reproducing the Combined Work from the
42
+ Application, but excluding the System Libraries of the Combined Work.
43
+
44
+ 1. Exception to Section 3 of the GNU GPL.
45
+
46
+ You may convey a covered work under sections 3 and 4 of this License
47
+ without being bound by section 3 of the GNU GPL.
48
+
49
+ 2. Conveying Modified Versions.
50
+
51
+ If you modify a copy of the Library, and, in your modifications, a
52
+ facility refers to a function or data to be supplied by an Application
53
+ that uses the facility (other than as an argument passed when the
54
+ facility is invoked), then you may convey a copy of the modified
55
+ version:
56
+
57
+ a) under this License, provided that you make a good faith effort to
58
+ ensure that, in the event an Application does not supply the
59
+ function or data, the facility still operates, and performs
60
+ whatever part of its purpose remains meaningful, or
61
+
62
+ b) under the GNU GPL, with none of the additional permissions of
63
+ this License applicable to that copy.
64
+
65
+ 3. Object Code Incorporating Material from Library Header Files.
66
+
67
+ The object code form of an Application may incorporate material from
68
+ a header file that is part of the Library. You may convey such object
69
+ code under terms of your choice, provided that, if the incorporated
70
+ material is not limited to numerical parameters, data structure
71
+ layouts and accessors, or small macros, inline functions and templates
72
+ (ten or fewer lines in length), you do both of the following:
73
+
74
+ a) Give prominent notice with each copy of the object code that the
75
+ Library is used in it and that the Library and its use are
76
+ covered by this License.
77
+
78
+ b) Accompany the object code with a copy of the GNU GPL and this license
79
+ document.
80
+
81
+ 4. Combined Works.
82
+
83
+ You may convey a Combined Work under terms of your choice that,
84
+ taken together, effectively do not restrict modification of the
85
+ portions of the Library contained in the Combined Work and reverse
86
+ engineering for debugging such modifications, if you also do each of
87
+ the following:
88
+
89
+ a) Give prominent notice with each copy of the Combined Work that
90
+ the Library is used in it and that the Library and its use are
91
+ covered by this License.
92
+
93
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
94
+ document.
95
+
96
+ c) For a Combined Work that displays copyright notices during
97
+ execution, include the copyright notice for the Library among
98
+ these notices, as well as a reference directing the user to the
99
+ copies of the GNU GPL and this license document.
100
+
101
+ d) Do one of the following:
102
+
103
+ 0) Convey the Minimal Corresponding Source under the terms of this
104
+ License, and the Corresponding Application Code in a form
105
+ suitable for, and under terms that permit, the user to
106
+ recombine or relink the Application with a modified version of
107
+ the Linked Version to produce a modified Combined Work, in the
108
+ manner specified by section 6 of the GNU GPL for conveying
109
+ Corresponding Source.
110
+
111
+ 1) Use a suitable shared library mechanism for linking with the
112
+ Library. A suitable mechanism is one that (a) uses at run time
113
+ a copy of the Library already present on the user's computer
114
+ system, and (b) will operate properly with a modified version
115
+ of the Library that is interface-compatible with the Linked
116
+ Version.
117
+
118
+ e) Provide Installation Information, but only if you would otherwise
119
+ be required to provide such information under section 6 of the
120
+ GNU GPL, and only to the extent that such information is
121
+ necessary to install and execute a modified version of the
122
+ Combined Work produced by recombining or relinking the
123
+ Application with a modified version of the Linked Version. (If
124
+ you use option 4d0, the Installation Information must accompany
125
+ the Minimal Corresponding Source and Corresponding Application
126
+ Code. If you use option 4d1, you must provide the Installation
127
+ Information in the manner specified by section 6 of the GNU GPL
128
+ for conveying Corresponding Source.)
129
+
130
+ 5. Combined Libraries.
131
+
132
+ You may place library facilities that are a work based on the
133
+ Library side by side in a single library together with other library
134
+ facilities that are not Applications and are not covered by this
135
+ License, and convey such a combined library under terms of your
136
+ choice, if you do both of the following:
137
+
138
+ a) Accompany the combined library with a copy of the same work based
139
+ on the Library, uncombined with any other library facilities,
140
+ conveyed under the terms of this License.
141
+
142
+ b) Give prominent notice with the combined library that part of it
143
+ is a work based on the Library, and explaining where to find the
144
+ accompanying uncombined form of the same work.
145
+
146
+ 6. Revised Versions of the GNU Lesser General Public License.
147
+
148
+ The Free Software Foundation may publish revised and/or new versions
149
+ of the GNU Lesser General Public License from time to time. Such new
150
+ versions will be similar in spirit to the present version, but may
151
+ differ in detail to address new problems or concerns.
152
+
153
+ Each version is given a distinguishing version number. If the
154
+ Library as you received it specifies that a certain numbered version
155
+ of the GNU Lesser General Public License "or any later version"
156
+ applies to it, you have the option of following the terms and
157
+ conditions either of that published version or of any later version
158
+ published by the Free Software Foundation. If the Library as you
159
+ received it does not specify a version number of the GNU Lesser
160
+ General Public License, you may choose any version of the GNU Lesser
161
+ General Public License ever published by the Free Software Foundation.
162
+
163
+ If the Library as you received it specifies that a proxy can decide
164
+ whether future versions of the GNU Lesser General Public License shall
165
+ apply, that proxy's public statement of acceptance of any version is
166
+ permanent authorization for you to choose that version for the
167
+ Library.
video_codec_sdk/Read_Me.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f794785ac920951fcb5cac95821ea58e2b63c51494c72c777bc62a87c1f8914c
3
+ size 107645
video_codec_sdk/Samples/AppDecode/AppDec/AppDec.cpp ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDec.cpp
14
+ //! \brief Source file for AppDec sample
15
+ //!
16
+ //! This sample application illustrates the demuxing and decoding of a media file followed by resize and crop of the output frames.
17
+ //! The application supports both planar (YUV420P and YUV420P16) and non-planar (NV12 and P016) output formats.
18
+ //---------------------------------------------------------------------------
19
+
20
+ #include <iostream>
21
+ #include <algorithm>
22
+ #include <thread>
23
+ #include <cuda.h>
24
+ #include "NvDecoder/NvDecoder.h"
25
+ #include "../Utils/NvCodecUtils.h"
26
+ #include "../Utils/FFmpegDemuxer.h"
27
+ #include "../Common/AppDecUtils.h"
28
+
29
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
30
+
31
+
32
+ void ConvertSemiplanarToPlanar(uint8_t *pHostFrame, int nWidth, int nHeight, int nBitDepth, uint8_t nChromaFormat) {
33
+ if (nBitDepth == 8) {
34
+ YuvConverter<uint8_t> converter8(nWidth, nHeight, nChromaFormat);
35
+ converter8.UVInterleavedToPlanar(pHostFrame);
36
+ } else {
37
+ YuvConverter<uint16_t> converter16(nWidth, nHeight, nChromaFormat);
38
+ converter16.UVInterleavedToPlanar((uint16_t *)pHostFrame);
39
+ }
40
+ }
41
+
42
+ /**
43
+ * @brief Function to decode media file and write raw frames into an output file.
44
+ * @param cuContext - Handle to CUDA context
45
+ * @param szInFilePath - Path to file to be decoded
46
+ * @param szOutFilePath - Path to output file into which raw frames are stored
47
+ * @param bOutPlanar - Flag to indicate whether output needs to be converted to planar format
48
+ * @param cropRect - Cropping rectangle coordinates
49
+ * @param resizeDim - Resizing dimensions for output
50
+ * @param opPoint - Select an operating point of an AV1 scalable bitstream
51
+ * @param bDispAllLayers - Output all decoded frames of an AV1 scalable bitstream
52
+ * @param bExtractUserSEIMessage - Output unregistered user SEI messages in display order
53
+ @param bExtStream - Flag to indicate whether to create the cuda stream in the App.
54
+ */
55
+ void DecodeMediaFile(CUcontext cuContext, const char *szInFilePath, const char *szOutFilePath, bool bOutPlanar,
56
+ const Rect &cropRect, const Dim &resizeDim, const unsigned int opPoint, const bool bDispAllLayers, const bool bExtractUserSEIMessage,
57
+ unsigned int decsurf,bool bExtStream)
58
+ {
59
+ std::ofstream fpOut(szOutFilePath, std::ios::out | std::ios::binary);
60
+ if (!fpOut)
61
+ {
62
+ std::ostringstream err;
63
+ err << "Unable to open output file: " << szOutFilePath << std::endl;
64
+ throw std::invalid_argument(err.str());
65
+ }
66
+ CUstream cuStream = NULL;
67
+
68
+ if(bExtStream)
69
+ {
70
+ ck(cuCtxPushCurrent(cuContext));
71
+ ck(cuStreamCreate(&cuStream, CU_STREAM_DEFAULT));
72
+ }
73
+
74
+ FFmpegDemuxer demuxer(szInFilePath);
75
+ NvDecoder dec(cuContext, false, FFmpeg2NvCodecId(demuxer.GetVideoCodec()), false, false, &cropRect, &resizeDim, bExtractUserSEIMessage, 0, 0, 1000, false, decsurf, cuStream);
76
+
77
+ /* Set operating point for AV1 SVC. It has no impact for other profiles or codecs
78
+ * PFNVIDOPPOINTCALLBACK Callback from video parser will pick operating point set to NvDecoder */
79
+ dec.SetOperatingPoint(opPoint, bDispAllLayers);
80
+
81
+ int nVideoBytes = 0, nFrameReturned = 0, nFrame = 0;
82
+ uint8_t *pVideo = NULL, *pFrame;
83
+ bool bDecodeOutSemiPlanar = false;
84
+ do {
85
+ demuxer.Demux(&pVideo, &nVideoBytes);
86
+ nFrameReturned = dec.Decode(pVideo, nVideoBytes);
87
+ if (!nFrame && nFrameReturned)
88
+ LOG(INFO) << dec.GetVideoInfo();
89
+
90
+ bDecodeOutSemiPlanar = (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12) || (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
91
+ || (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV16) || (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P216);
92
+
93
+ for (int i = 0; i < nFrameReturned; i++) {
94
+ pFrame = dec.GetFrame();
95
+ if(bExtStream)
96
+ {
97
+ // If using external stream App needs to wait for memcpy to complete.
98
+ ck(cuStreamSynchronize(cuStream));
99
+ }
100
+ if (bOutPlanar && bDecodeOutSemiPlanar) {
101
+ ConvertSemiplanarToPlanar(pFrame, dec.GetWidth(), dec.GetHeight(), dec.GetBitDepth(), dec.GetOutputChromaFormat());
102
+ }
103
+ // dump YUV to disk
104
+ if (dec.GetWidth() == dec.GetDecodeWidth())
105
+ {
106
+ fpOut.write(reinterpret_cast<char*>(pFrame), dec.GetFrameSize());
107
+ }
108
+ else
109
+ {
110
+ // 4:2:0/4:2:2 output width is 2 byte aligned. If decoded width is odd , luma has 1 pixel padding
111
+ // Remove padding from luma while dumping it to disk
112
+ // dump luma
113
+ for (auto i = 0; i < dec.GetHeight(); i++)
114
+ {
115
+ fpOut.write(reinterpret_cast<char*>(pFrame), dec.GetDecodeWidth()*dec.GetBPP());
116
+ pFrame += dec.GetWidth() * dec.GetBPP();
117
+ }
118
+ // dump Chroma
119
+ fpOut.write(reinterpret_cast<char*>(pFrame), dec.GetChromaPlaneSize());
120
+ }
121
+ }
122
+ nFrame += nFrameReturned;
123
+ } while (nVideoBytes);
124
+
125
+ if(cuStream)
126
+ {
127
+ ck(cuStreamDestroy(cuStream));
128
+ cuStream = NULL;
129
+ CUcontext tempCuContext;
130
+ ck(cuCtxPopCurrent(&tempCuContext));
131
+ }
132
+
133
+ std::vector <std::string> aszDecodeOutFormat = { "NV12", "P016", "YUV444", "YUV444P16", "NV16", "P216" };
134
+ if (bOutPlanar) {
135
+ aszDecodeOutFormat[0] = "iyuv"; aszDecodeOutFormat[1] = "yuv420p16";
136
+ aszDecodeOutFormat[4] = "yuv422p"; aszDecodeOutFormat[5] = "yuv422p16";
137
+ }
138
+ std::cout << "Total frame decoded: " << nFrame << std::endl
139
+ << "Saved in file " << szOutFilePath << " in "
140
+ << aszDecodeOutFormat[dec.GetOutputFormat()]
141
+ << " format" << std::endl;
142
+ fpOut.close();
143
+ }
144
+
145
+ void ShowBriefHelp()
146
+ {
147
+ std::ostringstream oss;
148
+ oss << "NVIDIA Video Decoder Sample Application\n";
149
+ oss << "====================================\n\n";
150
+
151
+ oss << "Usage: AppDec -i <input_file> [options]\n\n";
152
+
153
+ // Brief table of core arguments
154
+ oss << "Common Arguments:\n";
155
+ oss << std::left << std::setw(25) << "Argument"
156
+ << std::setw(12) << "Type"
157
+ << "Default Value\n";
158
+ oss << std::string(50, '-') << "\n";
159
+
160
+ oss << std::left << std::setw(25) << "-i <path>"
161
+ << std::setw(12) << "Required"
162
+ << "N/A\n";
163
+ oss << std::left << std::setw(25) << "-o <path>"
164
+ << std::setw(12) << "Optional"
165
+ << "out.native/.planar\n";
166
+ oss << std::left << std::setw(25) << "-gpu <n>"
167
+ << std::setw(12) << "Optional"
168
+ << "0\n";
169
+
170
+ oss << "\nFor detailed help, use -A/--advanced-options\n";
171
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
172
+ std::cout << oss.str();
173
+ exit(0);
174
+ }
175
+
176
+ void ShowDetailedHelp()
177
+ {
178
+ std::ostringstream oss;
179
+ oss << "NVIDIA Video Decoder Sample Application - Detailed Help\n";
180
+ oss << "================================================\n\n";
181
+
182
+ oss << "Usage: AppDec -i <input_file> [options]\n\n";
183
+
184
+ // Full table of all arguments
185
+ oss << "All Arguments:\n";
186
+ oss << std::left << std::setw(25) << "Argument"
187
+ << std::setw(12) << "Type"
188
+ << std::setw(20) << "Default Value"
189
+ << "Example\n";
190
+ oss << std::string(80, '-') << "\n";
191
+
192
+ // Required arguments
193
+ oss << std::left << std::setw(25) << "-i <path>"
194
+ << std::setw(12) << "Required"
195
+ << std::setw(20) << "N/A"
196
+ << "-i input.h264\n";
197
+
198
+ // Optional arguments
199
+ oss << std::left << std::setw(25) << "-o <path>"
200
+ << std::setw(12) << "Optional"
201
+ << std::setw(20) << "out.native/.planar"
202
+ << "-o output.yuv\n";
203
+ oss << std::left << std::setw(25) << "-outplanar"
204
+ << std::setw(12) << "Optional"
205
+ << std::setw(20) << "false"
206
+ << "-outplanar\n";
207
+ oss << std::left << std::setw(25) << "-gpu <n>"
208
+ << std::setw(12) << "Optional"
209
+ << std::setw(20) << "0"
210
+ << "-gpu 1\n";
211
+ oss << std::left << std::setw(25) << "-crop <l,t,r,b>"
212
+ << std::setw(12) << "Optional"
213
+ << std::setw(20) << "No cropping"
214
+ << "-crop 0,0,1920,1080\n";
215
+ oss << std::left << std::setw(25) << "-resize <WxH>"
216
+ << std::setw(12) << "Optional"
217
+ << std::setw(20) << "No resizing"
218
+ << "-resize 1280x720\n";
219
+ oss << std::left << std::setw(25) << "-oppoint <n>"
220
+ << std::setw(12) << "Optional"
221
+ << std::setw(20) << "0"
222
+ << "-oppoint 2\n";
223
+ oss << std::left << std::setw(25) << "-alllayers"
224
+ << std::setw(12) << "Optional"
225
+ << std::setw(20) << "false"
226
+ << "-alllayers\n";
227
+ oss << std::left << std::setw(25) << "-extractUserSEIMessage"
228
+ << std::setw(12) << "Optional"
229
+ << std::setw(20) << "false"
230
+ << "-extractUserSEIMessage\n";
231
+ oss << std::left << std::setw(25) << "-decsurf <n>"
232
+ << std::setw(12) << "Optional"
233
+ << std::setw(20) << "0"
234
+ << "-decsurf 8\n";
235
+ oss << std::left << std::setw(25) << "-extCudaStrm"
236
+ << std::setw(12) << "Optional"
237
+ << std::setw(20) << "false"
238
+ << "-extCudaStrm\n";
239
+
240
+ // Detailed descriptions
241
+ oss << "\nDetailed Descriptions:\n";
242
+ oss << "-------------------\n";
243
+ oss << std::left << std::setw(25) << "-i" << ": Input file path\n";
244
+ oss << std::left << std::setw(25) << "-o" << ": Output file path (defaults based on -outplanar flag)\n";
245
+ oss << std::left << std::setw(25) << "-outplanar" << ": Convert output to planar format\n";
246
+ oss << std::left << std::setw(25) << "-gpu" << ": Ordinal of GPU to use\n";
247
+ oss << std::left << std::setw(25) << "-crop" << ": Crop rectangle in left,top,right,bottom (ignored for case 0)\n";
248
+ oss << std::left << std::setw(25) << "-resize" << ": Resize to dimension W times H (ignored for case 0)\n";
249
+ oss << std::left << std::setw(25) << "-oppoint" << ": Select an operating point of an AV1 scalable bitstream\n";
250
+ oss << std::left << std::setw(25) << "-alllayers" << ": Output all decoded frames of an AV1 scalable bitstream\n";
251
+ oss << std::left << std::setw(25) << "-extractUserSEIMessage" << ": Output unregistered user SEI messages in display order\n";
252
+ oss << std::left << std::setw(25) << "-decsurf" << ": Allocate n number of decode surfaces at initialization\n";
253
+ oss << std::left << std::setw(25) << "-extCudaStrm" << ": Use external CUDA stream for memory operations\n";
254
+ oss << std::left << std::setw(25) << "-h/--help" << ": Print usage information for common commandline options\n";
255
+ oss << std::left << std::setw(25) << "-A/--advanced-options" << ": Print usage information for common and advanced commandline options\n";
256
+ oss << std::left << std::setw(25) << "-dc/--decode-caps" << ": Print decode capabilities of GPU\n";
257
+
258
+ // Important notes
259
+ oss << "\nNotes:\n";
260
+ oss << "------\n";
261
+ oss << "* Width and height for crop and resize must be even numbers\n";
262
+ oss << "* Output format will be out.native unless -outplanar is specified\n";
263
+ oss << std::endl;
264
+
265
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
266
+ std::cout << oss.str();
267
+ exit(0);
268
+ }
269
+
270
+ void ShowHelpAndExit(const char *szBadOption = NULL)
271
+ {
272
+ if (szBadOption)
273
+ {
274
+ std::ostringstream oss;
275
+ oss << "Error parsing \"" << szBadOption << "\"\n";
276
+ oss << "Use -h/--help for basic usage or -A/--advanced-options for detailed information\n";
277
+ throw std::invalid_argument(oss.str());
278
+ }
279
+ }
280
+
281
+ void ParseCommandLine(int argc, char *argv[], char *szInputFileName, char *szOutputFileName,
282
+ bool &bOutPlanar, int &iGpu, Rect &cropRect, Dim &resizeDim, unsigned int &opPoint, bool &bDispAllLayers, bool &bExtractUserSEIMessage, unsigned int &decsurf, bool &bExtStream)
283
+ {
284
+ std::ostringstream oss;
285
+ int i;
286
+ bDispAllLayers = false;
287
+ opPoint = 0;
288
+ if (argc == 1) {
289
+ std::cout << "No Arguments provided! Please refer to the following for options:" << "\"\n";
290
+ ShowBriefHelp();
291
+ }
292
+
293
+ for (i = 1; i < argc; i++) {
294
+ if (!_stricmp(argv[i], "-h") || !_stricmp(argv[i], "--help")) {
295
+ ShowBriefHelp();
296
+ }
297
+ if (!_stricmp(argv[i], "-A") || !_stricmp(argv[i], "--advanced-options")) {
298
+ ShowDetailedHelp();
299
+ }
300
+ if (!_stricmp(argv[i], "-dc") || !_stricmp(argv[i], "--decode-caps")) {
301
+ ShowDecoderCapability();
302
+ }
303
+ if (!_stricmp(argv[i], "-i")) {
304
+ if (++i == argc) {
305
+ ShowHelpAndExit("-i");
306
+ }
307
+ sprintf(szInputFileName, "%s", argv[i]);
308
+ continue;
309
+ }
310
+ if (!_stricmp(argv[i], "-o")) {
311
+ if (++i == argc) {
312
+ ShowHelpAndExit("-o");
313
+ }
314
+ sprintf(szOutputFileName, "%s", argv[i]);
315
+ continue;
316
+ }
317
+ if (!_stricmp(argv[i], "-outplanar")) {
318
+ bOutPlanar = true;
319
+ continue;
320
+ }
321
+ if (!_stricmp(argv[i], "-gpu")) {
322
+ if (++i == argc) {
323
+ ShowHelpAndExit("-gpu");
324
+ }
325
+ iGpu = atoi(argv[i]);
326
+ continue;
327
+ }
328
+ if (!_stricmp(argv[i], "-crop")) {
329
+ if (++i == argc || 4 != sscanf(
330
+ argv[i], "%d,%d,%d,%d",
331
+ &cropRect.l, &cropRect.t, &cropRect.r, &cropRect.b)) {
332
+ ShowHelpAndExit("-crop");
333
+ }
334
+ if ((cropRect.r - cropRect.l) % 2 == 1 || (cropRect.b - cropRect.t) % 2 == 1) {
335
+ std::cout << "Cropping rect must have width and height of even numbers" << std::endl;
336
+ exit(1);
337
+ }
338
+ continue;
339
+ }
340
+ if (!_stricmp(argv[i], "-resize")) {
341
+ if (++i == argc || 2 != sscanf(argv[i], "%dx%d", &resizeDim.w, &resizeDim.h)) {
342
+ ShowHelpAndExit("-resize");
343
+ }
344
+ if (resizeDim.w % 2 == 1 || resizeDim.h % 2 == 1) {
345
+ std::cout << "Resizing rect must have width and height of even numbers" << std::endl;
346
+ exit(1);
347
+ }
348
+ continue;
349
+ }
350
+ if (!_stricmp(argv[i], "-oppoint")) {
351
+ if (++i == argc ) {
352
+ ShowHelpAndExit("-oppoint");
353
+ }
354
+ opPoint = atoi(argv[i]);
355
+ continue;
356
+ }
357
+ if (!_stricmp(argv[i], "-alllayers")) {
358
+
359
+ bDispAllLayers = true;
360
+ continue;
361
+ }
362
+ if (!_stricmp(argv[i], "-extractUserSEIMessage")) {
363
+ bExtractUserSEIMessage = true;
364
+ continue;
365
+ }
366
+ if (!_stricmp(argv[i], "-decsurf")) {
367
+ if (++i == argc) {
368
+ ShowHelpAndExit("-decsurf");
369
+ }
370
+ decsurf = atoi(argv[i]);
371
+ continue;
372
+ }
373
+ if (!_stricmp(argv[i], "-extCudaStrm")) {
374
+ bExtStream = true;
375
+ continue;
376
+ }
377
+ ShowHelpAndExit(argv[i]);
378
+ }
379
+ }
380
+
381
+ int main(int argc, char **argv)
382
+ {
383
+ char szInFilePath[256] = "", szOutFilePath[256] = "";
384
+ bool bOutPlanar = false;
385
+ int iGpu = 0;
386
+ Rect cropRect = {};
387
+ Dim resizeDim = {};
388
+ unsigned int opPoint = 0;
389
+ bool bDispAllLayers = false;
390
+ bool bExtractUserSEIMessage = false;
391
+ unsigned int decsurf = 0;
392
+ bool bExtStream = false;
393
+ try
394
+ {
395
+ ParseCommandLine(argc, argv, szInFilePath, szOutFilePath, bOutPlanar, iGpu, cropRect, resizeDim, opPoint, bDispAllLayers, bExtractUserSEIMessage, decsurf, bExtStream);
396
+ CheckInputFile(szInFilePath);
397
+
398
+ if (!*szOutFilePath) {
399
+ sprintf(szOutFilePath, bOutPlanar ? "out.planar" : "out.native");
400
+ }
401
+
402
+ ck(cuInit(0));
403
+ int nGpu = 0;
404
+ ck(cuDeviceGetCount(&nGpu));
405
+ if (iGpu < 0 || iGpu >= nGpu) {
406
+ std::cout << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
407
+ return 1;
408
+ }
409
+
410
+ CUcontext cuContext = NULL;
411
+ createCudaContext(&cuContext, iGpu, 0);
412
+
413
+ std::cout << "Decode with demuxing." << std::endl;
414
+ DecodeMediaFile(cuContext, szInFilePath, szOutFilePath, bOutPlanar, cropRect, resizeDim, opPoint, bDispAllLayers, bExtractUserSEIMessage, decsurf, bExtStream);
415
+ }
416
+ catch (const std::exception& ex)
417
+ {
418
+ std::cout << ex.what();
419
+ exit(1);
420
+ }
421
+
422
+ return 0;
423
+ }
video_codec_sdk/Samples/AppDecode/AppDec/CMakeLists.txt ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDec)
13
+
14
+ set(APP_SOURCES
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDec.cpp
16
+ )
17
+
18
+ set(NV_DEC_SOURCES
19
+ ${NV_DEC_DIR}/NvDecoder.cpp
20
+ )
21
+
22
+ set(NV_DEC_HDRS
23
+ ${NV_DEC_DIR}/NvDecoder.h
24
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
25
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
26
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
27
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
28
+ ${NV_APPDEC_COMMON_DIR}/AppDecUtils.h
29
+ )
30
+
31
+ if(WIN32)
32
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
33
+ endif()
34
+
35
+ source_group( "headers" FILES ${NV_DEC_HDRS} )
36
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} )
37
+
38
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
39
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
40
+ find_package(CUDAToolkit QUIET)
41
+ if(CUDAToolkit_FOUND)
42
+ # Map CUDAToolkit variables to legacy CUDA variable names
43
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
44
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
45
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
46
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
47
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
48
+ endif()
49
+ endif()
50
+ if(NOT CUDAToolkit_FOUND)
51
+ find_package(CUDA)
52
+ endif()
53
+
54
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
55
+
56
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
57
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
58
+ else()
59
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
60
+ endif()
61
+
62
+ if ( CMAKE_COMPILER_IS_GNUCC )
63
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
64
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
65
+ endif()
66
+ endif()
67
+
68
+ if(MSVC)
69
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
70
+ endif()
71
+
72
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS})
73
+
74
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
75
+
76
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
77
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
78
+ ${NVCODEC_UTILS_DIR}
79
+ ${NV_DEC_DIR}
80
+ ${NV_APPDEC_COMMON_DIR}
81
+ ${NV_FFMPEG_HDRS}
82
+ ${NV_CODEC_DIR}
83
+ )
84
+
85
+ if(WIN32)
86
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
87
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
88
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
89
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
90
+ #copy dll's
91
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.dll")
92
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.lib")
93
+ endif()
94
+
95
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
96
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB})
97
+
98
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
99
+ if (MSVC)
100
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
101
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
102
+ #copy pdb's
103
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
104
+ endif()
105
+
video_codec_sdk/Samples/AppDecode/AppDecD3D/AppDecD3D.cpp ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecD3D.cpp
14
+ //! \brief Source file for AppDecD3D sample
15
+ //!
16
+ //! This sample application illustrates the decoding of media file and display of decoded frames in a window.
17
+ //! This is done by CUDA interop with D3D(both D3D9 and D3D11).
18
+ //! For a detailed list of supported codecs on your NVIDIA GPU, refer : https://developer.nvidia.com/nvidia-video-codec-sdk#NVDECFeatures
19
+
20
+
21
+ #include <cuda.h>
22
+ #include <iostream>
23
+ #include "NvDecoder/NvDecoder.h"
24
+ #include "../Utils/NvCodecUtils.h"
25
+ #include "../Utils/FFmpegDemuxer.h"
26
+ #include "FramePresenterD3D9.h"
27
+ #include "FramePresenterD3D11.h"
28
+ #include "../Common/AppDecUtils.h"
29
+ #include "../Utils/ColorSpace.h"
30
+
31
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
32
+
33
+ /**
34
+ * @brief Function template to decode media file pointed to by szInFilePath parameter.
35
+ The decoded frames are displayed by using the D3D-CUDA interop.
36
+ In this app FramePresenterType is either FramePresenterD3D9 or FramePresenterD3D11.
37
+ The presentation rate is based on per frame time stamp.
38
+ * @param cuContext - Handle to CUDA context
39
+ * @param szInFilePath - Path to file to be decoded
40
+ * @return 0 on success
41
+ */
42
+ template<class FramePresenterType, typename = std::enable_if<std::is_base_of<FramePresenterD3D, FramePresenterType>::value>>
43
+ int NvDecD3D(CUcontext cuContext, char *szInFilePath)
44
+ {
45
+ unsigned int timescale = 1000; // get timestamp in milisecond
46
+ FFmpegDemuxer demuxer(szInFilePath, timescale);
47
+ NvDecoder dec(cuContext, true, FFmpeg2NvCodecId(demuxer.GetVideoCodec()), false, false, NULL, NULL, false, 0, 0, timescale);
48
+ int nRGBWidth = (demuxer.GetWidth() + 1) & ~1;
49
+ FramePresenterType presenter(cuContext, nRGBWidth, demuxer.GetHeight());
50
+ CUdeviceptr dpFrame = 0;
51
+ ck(cuMemAlloc(&dpFrame, nRGBWidth * demuxer.GetHeight() * 4));
52
+ int nVideoBytes = 0, nFrameReturned = 0, nFrame = 0;
53
+ uint8_t *pVideo = NULL, *pFrame;
54
+ int64_t pts, timestamp = 0;
55
+ bool m_bFirstFrame = true;
56
+ int64_t firstPts = 0, startTime = 0;
57
+ LARGE_INTEGER m_Freq;
58
+ int iMatrix = 0;
59
+
60
+ QueryPerformanceFrequency(&m_Freq);
61
+
62
+ do
63
+ {
64
+ demuxer.Demux(&pVideo, &nVideoBytes, &pts);
65
+ nFrameReturned = dec.Decode(pVideo, nVideoBytes, 0, pts);
66
+ if (!nFrame && nFrameReturned)
67
+ LOG(INFO) << dec.GetVideoInfo();
68
+
69
+ for (int i = 0; i < nFrameReturned; i++)
70
+ {
71
+ pFrame = dec.GetFrame(&timestamp);
72
+ iMatrix = dec.GetVideoFormatInfo().video_signal_description.matrix_coefficients;
73
+ if (dec.GetBitDepth() == 8)
74
+ {
75
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
76
+ YUV444ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t *)dpFrame, 4 * nRGBWidth, dec.GetWidth(), dec.GetHeight(), iMatrix);
77
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
78
+ Nv12ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t *)dpFrame, 4 * nRGBWidth, dec.GetWidth(), dec.GetHeight(), iMatrix);
79
+ else
80
+ Nv16ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t *)dpFrame, 4 * nRGBWidth, dec.GetWidth(), dec.GetHeight(), iMatrix);
81
+ }
82
+ else
83
+ {
84
+ if(dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
85
+ YUV444P16ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t *)dpFrame, 4 * nRGBWidth, dec.GetWidth(), dec.GetHeight(), iMatrix);
86
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
87
+ P016ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t *)dpFrame, 4 * nRGBWidth, dec.GetWidth(), dec.GetHeight(), iMatrix);
88
+ else
89
+ P216ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t *)dpFrame, 4 * nRGBWidth, dec.GetWidth(), dec.GetHeight(), iMatrix);
90
+ }
91
+
92
+ LARGE_INTEGER counter;
93
+ if (m_bFirstFrame)
94
+ {
95
+ firstPts = timestamp;
96
+ QueryPerformanceCounter(&counter);
97
+ startTime = 1000 * counter.QuadPart / m_Freq.QuadPart;
98
+ m_bFirstFrame = false;
99
+ }
100
+
101
+ QueryPerformanceCounter(&counter);
102
+ int64_t curTime = timescale * counter.QuadPart / m_Freq.QuadPart;
103
+
104
+ int64_t expectedRenderTime = timestamp - firstPts + startTime;
105
+ int64_t delay = expectedRenderTime - curTime;
106
+ if (timestamp == 0)
107
+ delay = 0;
108
+ if (delay < 0)
109
+ continue;
110
+
111
+ presenter.PresentDeviceFrame((uint8_t *)dpFrame, nRGBWidth * 4, delay);
112
+ }
113
+ nFrame += nFrameReturned;
114
+ } while (nVideoBytes);
115
+ ck(cuMemFree(dpFrame));
116
+ std::cout << "Total frame decoded: " << nFrame << std::endl;
117
+ return 0;
118
+ }
119
+
120
+ int main(int argc, char **argv)
121
+ {
122
+ char szInFilePath[256] = "";
123
+ int iGpu = 0;
124
+ int iD3d = 0;
125
+ try
126
+ {
127
+ ParseCommandLine(argc, argv, szInFilePath, NULL, iGpu, NULL, &iD3d);
128
+ CheckInputFile(szInFilePath);
129
+
130
+ ck(cuInit(0));
131
+ int nGpu = 0;
132
+ ck(cuDeviceGetCount(&nGpu));
133
+ if (iGpu < 0 || iGpu >= nGpu)
134
+ {
135
+ std::ostringstream err;
136
+ err << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
137
+ throw std::invalid_argument(err.str());
138
+ }
139
+ CUdevice cuDevice = 0;
140
+ ck(cuDeviceGet(&cuDevice, iGpu));
141
+ char szDeviceName[80];
142
+ ck(cuDeviceGetName(szDeviceName, sizeof(szDeviceName), cuDevice));
143
+ std::cout << "GPU in use: " << szDeviceName << std::endl;
144
+ CUcontext cuContext = NULL;
145
+ ck(NVCODEC_CUDA_CTX_CREATE(&cuContext, CU_CTX_SCHED_BLOCKING_SYNC, cuDevice));
146
+
147
+ switch (iD3d) {
148
+ default:
149
+ case 9:
150
+ std::cout << "Display with D3D9." << std::endl;
151
+ return NvDecD3D<FramePresenterD3D9>(cuContext, szInFilePath);
152
+ case 11:
153
+ std::cout << "Display with D3D11." << std::endl;
154
+ return NvDecD3D<FramePresenterD3D11>(cuContext, szInFilePath);
155
+ }
156
+ }
157
+ catch (const std::exception& ex)
158
+ {
159
+ std::cout << ex.what();
160
+ exit(1);
161
+ }
162
+ return 0;
163
+ }
video_codec_sdk/Samples/AppDecode/AppDecD3D/CMakeLists.txt ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDecD3D)
13
+
14
+ set(APP_SOURCES
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecD3D.cpp
16
+ )
17
+
18
+ if(WIN32)
19
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
20
+ endif()
21
+
22
+ set(NV_DEC_SOURCES
23
+ ${NV_DEC_DIR}/NvDecoder.cpp
24
+ )
25
+
26
+ set(NV_ENC_CUDA_UTILS
27
+ ${NVCODEC_UTILS_DIR}/ColorSpace.cu
28
+ )
29
+
30
+ set(NV_DEC_COMMON_HDR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../Common)
31
+
32
+ set(NV_DEC_HDRS
33
+ ${NV_DEC_DIR}/NvDecoder.h
34
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
35
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
36
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
37
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
38
+ ${NVCODEC_UTILS_DIR}/ColorSpace.h
39
+ ${NV_APPDEC_COMMON_DIR}/AppDecUtils.h
40
+ )
41
+
42
+ source_group( "headers" FILES ${NV_DEC_HDRS} )
43
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_ENC_CUDA_UTILS})
44
+
45
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
46
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
47
+ find_package(CUDAToolkit QUIET)
48
+ if(CUDAToolkit_FOUND)
49
+ # Map CUDAToolkit variables to legacy CUDA variable names
50
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
51
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
52
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
53
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
54
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
55
+ endif()
56
+ endif()
57
+ if(NOT CUDAToolkit_FOUND)
58
+ find_package(CUDA)
59
+ endif()
60
+
61
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
62
+
63
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
64
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
65
+ else()
66
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
67
+ endif()
68
+ # CUDA 11.7 and later is compiled with /MT option (staticaly linked with C runtime),
69
+ # since we are statically linking cudart_static.lib with the app,
70
+ # we need to make sure that all .obj files linked are compiled with /MT to avoid linker warning LNK4098
71
+ if (WIN32 AND CUDA_VERSION_MAJOR GREATER_EQUAL 11 AND CUDA_VERSION_MINOR GREATER_EQUAL 7)
72
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-Xcompiler /MT)
73
+ endif()
74
+ if ( CMAKE_COMPILER_IS_GNUCC )
75
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
76
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
77
+ endif()
78
+ endif()
79
+
80
+ if(MSVC)
81
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
82
+ endif()
83
+
84
+ # Use modern approach with CUDAToolkit when available, fallback to legacy FindCUDA
85
+ if(CUDAToolkit_FOUND AND CUDAToolkit_NVCC_EXECUTABLE)
86
+ set(CMAKE_CUDA_COMPILER ${CUDAToolkit_NVCC_EXECUTABLE})
87
+ enable_language(CUDA)
88
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
89
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_STANDARD 11)
90
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
91
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "75")
92
+ else()
93
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "50")
94
+ endif()
95
+ else()
96
+ cuda_add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
97
+ endif()
98
+
99
+ if (WIN32 AND CUDA_VERSION_MAJOR GREATER_EQUAL 11 AND CUDA_VERSION_MINOR GREATER_EQUAL 7)
100
+ target_compile_options(${PROJECT_NAME} PRIVATE "/MT")
101
+ endif()
102
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
103
+
104
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
105
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
106
+ ${NVCODEC_UTILS_DIR}
107
+ ${NV_CODEC_DIR}
108
+ ${NV_APPDEC_COMMON_DIR}
109
+ ${NV_FFMPEG_HDRS}
110
+ )
111
+
112
+ set(D3D9_LIBS d3d9.lib dxva2.lib d3dcompiler.lib)
113
+ set(D3D11_LIBS d3d11.lib dxgi.lib d3dcompiler.lib)
114
+
115
+ if(WIN32)
116
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
117
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
118
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
119
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
120
+ #copy dll's
121
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.dll")
122
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.lib")
123
+
124
+ endif ()
125
+
126
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
127
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB} ${D3D9_LIBS} ${D3D11_LIBS})
128
+
129
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
130
+ if (MSVC)
131
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
132
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
133
+ #copy pdb's
134
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
135
+ endif()
136
+
video_codec_sdk/Samples/AppDecode/AppDecD3D/FramePresenterD3D.h ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+ #pragma once
12
+ #include <cuda.h>
13
+ #include "../Utils/NvCodecUtils.h"
14
+
15
+ /**
16
+ * @brief Base class for D3D presentation of decoded frames
17
+ */
18
+ class FramePresenterD3D {
19
+ public:
20
+ /**
21
+ * @brief FramePresenterD3D constructor.
22
+ * @param cuContext - CUDA context handle
23
+ * @param nWidth - Width of D3D Surface
24
+ * @param nHeight - Height of D3D Surface
25
+ */
26
+ FramePresenterD3D(CUcontext cuContext, int nWidth, int nHeight) : cuContext(cuContext), nWidth(nWidth), nHeight(nHeight) {}
27
+ /**
28
+ * @brief FramePresenterD3D destructor.
29
+ */
30
+ virtual ~FramePresenterD3D() {};
31
+ /**
32
+ * @brief Pure virtual to be implemented by derived classes. Should present decoded frames available in device memory
33
+ * @param dpBgra - CUDA device pointer to BGRA surface
34
+ * @param nPitch - pitch of the BGRA surface. Typically width in pixels * number of bytes per pixel
35
+ * @param delay - presentation delay. Cue to D3D presenter to inform about the time at which this frame needs to be presented
36
+ * @return true on success
37
+ * @return false on failure
38
+ */
39
+ virtual bool PresentDeviceFrame(unsigned char *dpBgra, int nPitch, int64_t delay) = 0;
40
+
41
+ protected:
42
+ /**
43
+ * @brief Create and show D3D window.
44
+ * @param nWidth - Width of the window
45
+ * @param nHeight - Height of the window
46
+ * @return hwndMain - handle to the created window
47
+ */
48
+ static HWND CreateAndShowWindow(int nWidth, int nHeight) {
49
+ double r = max(nWidth / 1280.0, nHeight / 720.0);
50
+ if (r > 1.0) {
51
+ nWidth = (int)(nWidth / r);
52
+ nHeight = (int)(nHeight / r);
53
+ }
54
+
55
+ static char szAppName[] = "D3DPresenter";
56
+ WNDCLASS wndclass;
57
+ wndclass.style = CS_HREDRAW | CS_VREDRAW;
58
+ wndclass.lpfnWndProc = WndProc;
59
+ wndclass.cbClsExtra = 0;
60
+ wndclass.cbWndExtra = 0;
61
+ wndclass.hInstance = (HINSTANCE)GetModuleHandle(NULL);
62
+ wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
63
+ wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
64
+ wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
65
+ wndclass.lpszMenuName = NULL;
66
+ wndclass.lpszClassName = szAppName;
67
+ RegisterClass(&wndclass);
68
+
69
+ RECT rc{
70
+ (GetSystemMetrics(SM_CXSCREEN) - nWidth) / 2,
71
+ (GetSystemMetrics(SM_CYSCREEN) - nHeight) / 2,
72
+ (GetSystemMetrics(SM_CXSCREEN) + nWidth) / 2,
73
+ (GetSystemMetrics(SM_CYSCREEN) + nHeight) / 2
74
+ };
75
+ AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
76
+
77
+ HWND hwndMain = CreateWindow(szAppName, szAppName, WS_OVERLAPPEDWINDOW,
78
+ rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,
79
+ NULL, NULL, wndclass.hInstance, NULL);
80
+ ShowWindow(hwndMain, SW_SHOW);
81
+ UpdateWindow(hwndMain);
82
+
83
+ return hwndMain;
84
+ }
85
+
86
+ /**
87
+ * @brief Copy device frame to cuda registered D3D surface. More specifically, this function maps the
88
+ * D3D swap chain backbuffer into a cuda array and copies the contents of dpBgra into it.
89
+ * This ensures that the swap chain back buffer will contain the next surface to be presented.
90
+ * @param dpBgra - CUDA device pointer to BGRA surface
91
+ * @param nPitch - pitch of the BGRA surface. Typically width in pixels * number of bytes per pixel
92
+ */
93
+ void CopyDeviceFrame(unsigned char *dpBgra, int nPitch) {
94
+ ck(cuCtxPushCurrent(cuContext));
95
+ ck(cuGraphicsMapResources(1, &cuResource, 0));
96
+ CUarray dstArray;
97
+ ck(cuGraphicsSubResourceGetMappedArray(&dstArray, cuResource, 0, 0));
98
+
99
+ CUDA_MEMCPY2D m = { 0 };
100
+ m.srcMemoryType = CU_MEMORYTYPE_DEVICE;
101
+ m.srcDevice = (CUdeviceptr)dpBgra;
102
+ m.srcPitch = nPitch ? nPitch : nWidth * 4;
103
+ m.dstMemoryType = CU_MEMORYTYPE_ARRAY;
104
+ m.dstArray = dstArray;
105
+ m.WidthInBytes = nWidth * 4;
106
+ m.Height = nHeight;
107
+ ck(cuMemcpy2D(&m));
108
+
109
+ ck(cuGraphicsUnmapResources(1, &cuResource, 0));
110
+ ck(cuCtxPopCurrent(NULL));
111
+ }
112
+
113
+ private:
114
+ /**
115
+ * @brief Callback called by D3D runtime. This callback is registered during window creation.
116
+ * On Window close this function posts a quit message. The thread runs to completion once
117
+ * it retrieves this quit message in its message queue. Refer to Run() function in each of the
118
+ * derived classes.
119
+ * @param hwnd - handle to the window
120
+ * @param msg - The message sent to this window
121
+ * @param wParam - Message specific additional information (No Op in this case)
122
+ * @param lParam - Message specific additional information (No Op on this case)
123
+ * @return 0 on posting quit message
124
+ * @return result of default window procedure in cases other than the above
125
+ */
126
+ static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
127
+ switch (msg) {
128
+ case WM_CLOSE:
129
+ PostQuitMessage(0);
130
+ return 0;
131
+ }
132
+ return DefWindowProc(hwnd, msg, wParam, lParam);
133
+ }
134
+
135
+ protected:
136
+ int nWidth = 0, nHeight = 0;
137
+ CUcontext cuContext = NULL;
138
+ CUgraphicsResource cuResource = NULL;
139
+ };
video_codec_sdk/Samples/AppDecode/AppDecD3D/FramePresenterD3D11.h ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+ #pragma once
12
+
13
+ #include <iostream>
14
+ #include <mutex>
15
+ #include <thread>
16
+ #include <d3d11.h>
17
+ #include <cuda.h>
18
+ #include <cudaD3D11.h>
19
+ #include "FramePresenterD3D.h"
20
+ #include "../Utils/NvCodecUtils.h"
21
+
22
+ /**
23
+ * @brief D3D11 presenter class derived from FramePresenterD3D
24
+ */
25
+ class FramePresenterD3D11 : public FramePresenterD3D
26
+ {
27
+ public:
28
+ /**
29
+ * @brief FramePresenterD3D11 constructor. This will launch a rendering thread which will be fed with decoded frames
30
+ * @param cuContext - CUDA context handle
31
+ * @param nWidth - Width of D3D surface
32
+ * @param nHeight - Height of D3D surface
33
+ */
34
+ FramePresenterD3D11(CUcontext cuContext, int nWidth, int nHeight) :
35
+ FramePresenterD3D(cuContext, nWidth, nHeight)
36
+ {
37
+ pthMsgLoop = new std::thread(ThreadProc, this);
38
+ while (!bReady) {
39
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
40
+ }
41
+ hTimerQueue = CreateTimerQueue();
42
+ hPresentEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
43
+ }
44
+
45
+ /**
46
+ * @brief FramePresenterD3D11 destructor.
47
+ */
48
+ ~FramePresenterD3D11() {
49
+ if (hTimerQueue)
50
+ {
51
+ DeleteTimerQueue(hTimerQueue);
52
+ }
53
+ if (hPresentEvent)
54
+ {
55
+ CloseHandle(hPresentEvent);
56
+ }
57
+ bQuit = true;
58
+ pthMsgLoop->join();
59
+ delete pthMsgLoop;
60
+ }
61
+
62
+ /**
63
+ * @brief Presents a frame present in host memory. More specifically, it copies the host surface
64
+ * data to a d3d staging texture and then copies it to the swap chain backbuffer for presentation
65
+ * @param pData - pointer to host surface data
66
+ * @param nBytes - number of bytes to copy
67
+ * @return true on success
68
+ * @return false when the windowing thread is not ready to be served
69
+ */
70
+ bool PresentHostFrame(BYTE *pData, int nBytes) {
71
+ mtx.lock();
72
+ if (!bReady) {
73
+ mtx.unlock();
74
+ return false;
75
+ }
76
+
77
+ D3D11_MAPPED_SUBRESOURCE mappedTexture;
78
+ ck(pContext->Map(pStagingTexture, 0, D3D11_MAP_WRITE, 0, &mappedTexture));
79
+ memcpy(mappedTexture.pData, pData, min(nWidth * nHeight * 4, nBytes));
80
+ pContext->Unmap(pStagingTexture, 0);
81
+ pContext->CopyResource(pBackBuffer, pStagingTexture);
82
+ ck(pSwapChain->Present(0, 0));
83
+ mtx.unlock();
84
+ return true;
85
+ }
86
+
87
+ bool PresentDeviceFrame(unsigned char *dpBgra, int nPitch, int64_t delay) {
88
+ mtx.lock();
89
+ if (!bReady) {
90
+ mtx.unlock();
91
+ return false;
92
+ }
93
+ CopyDeviceFrame(dpBgra, nPitch);
94
+ if (!CreateTimerQueueTimer(&hTimer, hTimerQueue,
95
+ (WAITORTIMERCALLBACK)PresentRoutine, this, (DWORD)delay, 0, 0))
96
+ {
97
+ std::cout << "Problem in createtimer" << std::endl;
98
+ }
99
+ while (WaitForSingleObject(hPresentEvent, 0) != WAIT_OBJECT_0)
100
+ {
101
+ }
102
+ if (hTimer)
103
+ {
104
+ DeleteTimerQueueTimer(hTimerQueue, hTimer, nullptr);
105
+ }
106
+ mtx.unlock();
107
+ return true;
108
+ }
109
+
110
+ private:
111
+ /**
112
+ * @brief Launches the windowing functionality
113
+ * @param This - pointer to FramePresenterD3D11 object
114
+ */
115
+ static void ThreadProc(FramePresenterD3D11 *This) {
116
+ This->Run();
117
+ }
118
+ /**
119
+ * @brief Callback called by D3D runtime. This callback is registered during call to
120
+ * CreateTimerQueueTimer in PresentDeviceFrame. In CreateTimerQueueTimer we also
121
+ * set a timer. When this timer expires this callback is called. This functionality
122
+ * is present to facilitate timestamp based presentation.
123
+ * @param lpParam - void pointer to client data
124
+ * @param TimerOrWaitFired - TRUE for this callback as this is a Timer based callback (Refer:https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms687066(v=vs.85))
125
+ */
126
+ static VOID CALLBACK PresentRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired)
127
+ {
128
+ if (!lpParam) return;
129
+ FramePresenterD3D11* presenter = (FramePresenterD3D11 *)lpParam;
130
+ presenter->pSwapChain->Present(1, 0);
131
+ SetEvent(presenter->hPresentEvent);
132
+ }
133
+
134
+ /**
135
+ * @brief This function is on a thread spawned during FramePresenterD3D11 construction.
136
+ * It creates the D3D window and monitors window messages in a loop. This function
137
+ * also creates swap chain for presentation and also registers the swap chain backbuffer
138
+ * with cuda.
139
+ */
140
+ void Run() {
141
+ HWND hwndMain = CreateAndShowWindow(nWidth, nHeight);
142
+
143
+ DXGI_SWAP_CHAIN_DESC sc = { 0 };
144
+ sc.BufferCount = 1;
145
+ sc.BufferDesc.Width = nWidth;
146
+ sc.BufferDesc.Height = nHeight;
147
+ sc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
148
+ sc.BufferDesc.RefreshRate.Numerator = 0;
149
+ sc.BufferDesc.RefreshRate.Denominator = 1;
150
+ sc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
151
+ sc.OutputWindow = hwndMain;
152
+ sc.SampleDesc.Count = 1;
153
+ sc.SampleDesc.Quality = 0;
154
+ sc.Windowed = TRUE;
155
+
156
+ ID3D11Device *pDevice = NULL;
157
+ ck(D3D11CreateDeviceAndSwapChain(GetAdapterByContext(cuContext), D3D_DRIVER_TYPE_UNKNOWN,
158
+ NULL, 0, NULL, 0, D3D11_SDK_VERSION, &sc, &pSwapChain, &pDevice, NULL, &pContext));
159
+ ck(pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer));
160
+
161
+ D3D11_TEXTURE2D_DESC td;
162
+ pBackBuffer->GetDesc(&td);
163
+ td.BindFlags = 0;
164
+ td.Usage = D3D11_USAGE_STAGING;
165
+ td.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
166
+ ck(pDevice->CreateTexture2D(&td, NULL, &pStagingTexture));
167
+
168
+ ck(cuCtxPushCurrent(cuContext));
169
+ ck(cuGraphicsD3D11RegisterResource(&cuResource, pBackBuffer, CU_GRAPHICS_REGISTER_FLAGS_NONE));
170
+ ck(cuGraphicsResourceSetMapFlags(cuResource, CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD));
171
+ ck(cuCtxPopCurrent(NULL));
172
+
173
+ bReady = true;
174
+ MSG msg = { 0 };
175
+ while (!bQuit && msg.message != WM_QUIT) {
176
+ if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
177
+ TranslateMessage(&msg);
178
+ DispatchMessage(&msg);
179
+ }
180
+ }
181
+
182
+ mtx.lock();
183
+ bReady = false;
184
+ ck(cuCtxPushCurrent(cuContext));
185
+ ck(cuGraphicsUnregisterResource(cuResource));
186
+ ck(cuCtxPopCurrent(NULL));
187
+ pStagingTexture->Release();
188
+ pBackBuffer->Release();
189
+ pContext->Release();
190
+ pDevice->Release();
191
+ pSwapChain->Release();
192
+ DestroyWindow(hwndMain);
193
+ mtx.unlock();
194
+ }
195
+
196
+ /**
197
+ * @brief Gets the DXGI adapter on which the given cuda context is current
198
+ * @param CUcontext - handle to cuda context
199
+ * @return pAdapter - pointer to DXGI adapter
200
+ * @return NULL - In case there is no adapter corresponding to the supplied cuda context
201
+ */
202
+ static IDXGIAdapter *GetAdapterByContext(CUcontext cuContext) {
203
+ CUdevice cuDeviceTarget;
204
+ ck(cuCtxPushCurrent(cuContext));
205
+ ck(cuCtxGetDevice(&cuDeviceTarget));
206
+ ck(cuCtxPopCurrent(NULL));
207
+
208
+ IDXGIFactory1 *pFactory = NULL;
209
+ ck(CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void **)&pFactory));
210
+ IDXGIAdapter *pAdapter = NULL;
211
+ for (unsigned i = 0; pFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND; i++) {
212
+ CUdevice cuDevice;
213
+ ck(cuD3D11GetDevice(&cuDevice, pAdapter));
214
+ if (cuDevice == cuDeviceTarget) {
215
+ pFactory->Release();
216
+ return pAdapter;
217
+ }
218
+ pAdapter->Release();
219
+ }
220
+ pFactory->Release();
221
+ return NULL;
222
+ }
223
+
224
+ private:
225
+ bool bReady = false;
226
+ bool bQuit = false;
227
+ std::mutex mtx;
228
+ std::thread *pthMsgLoop = NULL;
229
+
230
+ IDXGISwapChain *pSwapChain = NULL;
231
+ ID3D11DeviceContext *pContext = NULL;
232
+ ID3D11Texture2D *pBackBuffer = NULL, *pStagingTexture = NULL;
233
+ HANDLE hTimer;
234
+ HANDLE hTimerQueue;
235
+ HANDLE hPresentEvent;
236
+ };
video_codec_sdk/Samples/AppDecode/AppDecD3D/FramePresenterD3D9.h ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+ #pragma once
12
+
13
+ #include <iostream>
14
+ #include <mutex>
15
+ #include <thread>
16
+ #include <d3d9.h>
17
+ #include <cuda.h>
18
+ #include <cudaD3D9.h>
19
+ #include "FramePresenterD3D.h"
20
+ #include "../Utils/NvCodecUtils.h"
21
+
22
+ /**
23
+ * @brief D3D9 presenter class derived from FramePresenterD3D
24
+ */
25
+ class FramePresenterD3D9 : public FramePresenterD3D
26
+ {
27
+ public:
28
+ /**
29
+ * @brief FramePresenterD3D9 constructor. This will launch a rendering thread which will be fed with decoded frames
30
+ * @param cuContext - CUDA context handle
31
+ * @param nWidth - Width of D3D surface
32
+ * @param nHeight - Height of D3D surface
33
+ */
34
+ FramePresenterD3D9(CUcontext cuContext, int nWidth, int nHeight) :
35
+ FramePresenterD3D(cuContext, nWidth, nHeight)
36
+ {
37
+ pthMsgLoop = new std::thread(ThreadProc, this);
38
+ while (!bReady) {
39
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
40
+ }
41
+ hTimerQueue = CreateTimerQueue();
42
+ hPresentEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
43
+ }
44
+
45
+ /**
46
+ * @brief FramePresenterD3D9 destructor.
47
+ */
48
+ ~FramePresenterD3D9() {
49
+ if (hTimerQueue)
50
+ {
51
+ DeleteTimerQueue(hTimerQueue);
52
+ }
53
+ if (hPresentEvent)
54
+ {
55
+ CloseHandle(hPresentEvent);
56
+ }
57
+ bQuit = true;
58
+ pthMsgLoop->join();
59
+ delete pthMsgLoop;
60
+ }
61
+
62
+ /**
63
+ * @brief Presents a frame present in host memory. More specifically, it copies the host surface
64
+ * data to a d3d offscreenplain surface and then copies it to the swap chain backbuffer for presentation
65
+ * @param pData - pointer to host surface data
66
+ * @param nBytes - number of bytes to copy
67
+ * @return true on success
68
+ * @return false when the windowing thread is not ready to be served
69
+ */
70
+ bool PresentHostFrame(BYTE *pData, int nBytes) {
71
+ mtx.lock();
72
+ if (!bReady) {
73
+ mtx.unlock();
74
+ return false;
75
+ }
76
+
77
+ D3DLOCKED_RECT lockedRect;
78
+ ck(pSurface->LockRect(&lockedRect, NULL, 0));
79
+ for (int y = 0; y < nHeight; y++) {
80
+ memcpy((uint8_t *)lockedRect.pBits + y * lockedRect.Pitch, pData + y * nWidth * 4, nWidth * 4);
81
+ }
82
+ ck(pSurface->UnlockRect());
83
+ pDevice->UpdateSurface(pSurface, NULL, pBackBuffer, NULL);
84
+ mtx.unlock();
85
+ return true;
86
+ }
87
+
88
+ bool PresentDeviceFrame(unsigned char *dpBgra, int nPitch, int64_t delay) {
89
+ mtx.lock();
90
+ if (!bReady) {
91
+ mtx.unlock();
92
+ return false;
93
+ }
94
+ CopyDeviceFrame(dpBgra, nPitch);
95
+ if (!CreateTimerQueueTimer(&hTimer, hTimerQueue,
96
+ (WAITORTIMERCALLBACK)PresentRoutine, this, (DWORD)delay, 0, 0))
97
+ {
98
+ std::cout << "Problem in createtimer" << std::endl;
99
+ }
100
+ while (WaitForSingleObject(hPresentEvent, 0) != WAIT_OBJECT_0)
101
+ {
102
+ }
103
+ if (hTimer)
104
+ {
105
+ DeleteTimerQueueTimer(hTimerQueue, hTimer, nullptr);
106
+ }
107
+ mtx.unlock();
108
+ return true;
109
+ }
110
+
111
+ private:
112
+ /**
113
+ * @brief Launches the windowing functionality
114
+ * @param This - pointer to FramePresenterD3D9 object
115
+ */
116
+ static void ThreadProc(FramePresenterD3D9 *This) {
117
+ This->Run();
118
+ }
119
+ /**
120
+ * @brief Callback called by D3D runtime. This callback is registered during call to
121
+ * CreateTimerQueueTimer in PresentDeviceFrame. In CreateTimerQueueTimer we also
122
+ * set a timer. When this timer expires this callback is called. This functionality
123
+ * is present to facilitate timestamp based presentation.
124
+ * @param lpParam - void pointer to client data
125
+ * @param TimerOrWaitFired - TRUE for this callback as this is a Timer based callback (Refer:https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms687066(v=vs.85))
126
+ */
127
+ static VOID CALLBACK PresentRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired)
128
+ {
129
+ if (!lpParam) return;
130
+ FramePresenterD3D9* presenter = (FramePresenterD3D9 *)lpParam;
131
+ ck(presenter->pDevice->Present(NULL, NULL, NULL, NULL));
132
+ SetEvent(presenter->hPresentEvent);
133
+ }
134
+
135
+ /**
136
+ * @brief This function is on a thread spawned during FramePresenterD3D9 construction.
137
+ * It creates the D3D window and monitors window messages in a loop. This function
138
+ * also creates swap chain for presentation and also registers the swap chain backbuffer
139
+ * with cuda.
140
+ */
141
+ void Run() {
142
+ HWND hwndMain = CreateAndShowWindow(nWidth, nHeight);
143
+
144
+ IDirect3D9Ex* pD3D = NULL;
145
+ ck(Direct3DCreate9Ex(D3D_SDK_VERSION, &pD3D));
146
+ D3DPRESENT_PARAMETERS d3dpp = { 0 };
147
+ d3dpp.BackBufferWidth = nWidth;
148
+ d3dpp.BackBufferHeight = nHeight;
149
+ d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
150
+ d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
151
+ d3dpp.EnableAutoDepthStencil = FALSE;
152
+ d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
153
+ d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
154
+ d3dpp.Windowed = TRUE;
155
+ d3dpp.hDeviceWindow = hwndMain;
156
+ ck(pD3D->CreateDevice(GetAdapterByContext(cuContext), D3DDEVTYPE_HAL, NULL, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &pDevice));
157
+ pD3D->Release();
158
+
159
+ ck(pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer));
160
+ ck(pDevice->CreateOffscreenPlainSurface(nWidth, nHeight, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &pSurface, NULL));
161
+
162
+ ck(cuCtxPushCurrent(cuContext));
163
+ ck(cuGraphicsD3D9RegisterResource(&cuResource, pBackBuffer, CU_GRAPHICS_REGISTER_FLAGS_NONE));
164
+ ck(cuGraphicsResourceSetMapFlags(cuResource, CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD));
165
+ ck(cuCtxPopCurrent(NULL));
166
+
167
+ bReady = true;
168
+ MSG msg = { 0 };
169
+ while (!bQuit && msg.message != WM_QUIT) {
170
+ if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
171
+ TranslateMessage(&msg);
172
+ DispatchMessage(&msg);
173
+ }
174
+ }
175
+
176
+ mtx.lock();
177
+ bReady = false;
178
+ ck(cuCtxPushCurrent(cuContext));
179
+ ck(cuGraphicsUnregisterResource(cuResource));
180
+ ck(cuCtxPopCurrent(NULL));
181
+ pSurface->Release();
182
+ pBackBuffer->Release();
183
+ pDevice->Release();
184
+ DestroyWindow(hwndMain);
185
+ mtx.unlock();
186
+ }
187
+
188
+ /**
189
+ * @brief Gets the D3D9 adapter ID on which the given cuda context is current
190
+ * @param CUcontext - handle to cuda context
191
+ * @return pAdapter - pointer to DXGI adapter
192
+ * @return NULL - In case there is no adapter corresponding to the supplied cuda context
193
+ */
194
+ static UINT GetAdapterByContext(CUcontext cuContext) {
195
+ CUdevice cuDeviceTarget;
196
+ ck(cuCtxPushCurrent(cuContext));
197
+ ck(cuCtxGetDevice(&cuDeviceTarget));
198
+ ck(cuCtxPopCurrent(NULL));
199
+
200
+ IDirect3D9Ex* pD3D = NULL;
201
+ ck(Direct3DCreate9Ex(D3D_SDK_VERSION, &pD3D));
202
+ for (unsigned i = 0; i < pD3D->GetAdapterCount(); i++) {
203
+ D3DADAPTER_IDENTIFIER9 identifier;
204
+ pD3D->GetAdapterIdentifier(i, 0, &identifier);
205
+ CUdevice cuDevice;
206
+ ck(cuD3D9GetDevice(&cuDevice, identifier.DeviceName));
207
+ if (cuDevice == cuDeviceTarget) {
208
+ return i;
209
+ }
210
+ }
211
+ pD3D->Release();
212
+ return NULL;
213
+ }
214
+
215
+ private:
216
+ bool bReady = false;
217
+ bool bQuit = false;
218
+ std::mutex mtx;
219
+ std::thread *pthMsgLoop = NULL;
220
+
221
+ IDirect3DDevice9 *pDevice = NULL;
222
+ IDirect3DSurface9 *pBackBuffer = NULL, *pSurface = NULL;
223
+ HANDLE hTimer;
224
+ HANDLE hTimerQueue;
225
+ HANDLE hPresentEvent;
226
+ };
video_codec_sdk/Samples/AppDecode/AppDecGL/AppDecGL.cpp ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecGL.cpp
14
+ //! \brief Source file for AppDecGL sample
15
+ //!
16
+ //! This sample application illustrates the decoding of media file and display of decoded frames in a window.
17
+ //! This is done by CUDA interop with OpenGL.
18
+ //! Synchronization between rendering and decode thread is achieved using ConcurrentQueue implementation.
19
+ //! For a detailed list of supported codecs on your NVIDIA GPU, refer : https://developer.nvidia.com/nvidia-video-codec-sdk#NVDECFeatures
20
+ //---------------------------------------------------------------------------
21
+
22
+ #include <cuda.h>
23
+ #include <iostream>
24
+ #include "NvDecoder/NvDecoder.h"
25
+ #include "../Utils/NvCodecUtils.h"
26
+ #include "../Utils/FFmpegDemuxer.h"
27
+ #include "../Common/AppDecUtils.h"
28
+ #include "../Utils/ColorSpace.h"
29
+
30
+ #include "FramePresenter.h"
31
+ #include "FramePresenterGLUT.h"
32
+
33
+ #if !defined (_WIN32)
34
+ #include "FramePresenterGLX.h"
35
+ #endif
36
+
37
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
38
+
39
+ /**
40
+ * @brief Function to decode media file pointed by "szInFilePath" parameter.
41
+ * The decoded frames are displayed by using the OpenGL-CUDA interop.
42
+ * @param cuContext - Handle to CUDA context
43
+ * @param szInFilePath - Path to file to be decoded
44
+ * @return 0 on failure
45
+ * @return 1 on success
46
+ */
47
+ int Decode(CUcontext cuContext, char *szInFilePath) {
48
+
49
+ FFmpegDemuxer demuxer(szInFilePath);
50
+ NvDecoder dec(cuContext, true, FFmpeg2NvCodecId(demuxer.GetVideoCodec()));
51
+
52
+ // Presenter need aligned width
53
+ int nWidth = (demuxer.GetWidth() + 1) & ~1;
54
+ int nPitch = nWidth * 4;
55
+
56
+ #if defined (_WIN32)
57
+ FramePresenterGLUT gInstance(cuContext, nWidth, demuxer.GetHeight());
58
+ #else
59
+ FramePresenterGLX gInstance(nWidth, demuxer.GetHeight());
60
+ #endif
61
+
62
+ int &nFrame = gInstance.nFrame;
63
+
64
+ // Check whether we have valid NVIDIA libraries installed
65
+ if (!gInstance.isVendorNvidia()) {
66
+ std::cout<<"\nFailed to find NVIDIA libraries\n";
67
+ return 0;
68
+ }
69
+
70
+ CUdeviceptr dpFrame;
71
+ int nVideoBytes = 0, nFrameReturned = 0, iMatrix = 0;
72
+ uint8_t *pVideo = NULL;
73
+ uint8_t *pFrame;
74
+ do {
75
+ demuxer.Demux(&pVideo, &nVideoBytes);
76
+ nFrameReturned = dec.Decode(pVideo, nVideoBytes);
77
+ if (!nFrame && nFrameReturned)
78
+ LOG(INFO) << dec.GetVideoInfo();
79
+
80
+ for (int i = 0; i < nFrameReturned; i++) {
81
+ pFrame = dec.GetFrame();
82
+ gInstance.GetDeviceFrameBuffer(&dpFrame, &nPitch);
83
+ iMatrix = dec.GetVideoFormatInfo().video_signal_description.matrix_coefficients;
84
+ // Launch cuda kernels for colorspace conversion from raw video to raw image formats which OpenGL textures can work with
85
+ if (dec.GetBitDepth() == 8) {
86
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
87
+ YUV444ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t *)dpFrame, nPitch, dec.GetWidth(), dec.GetHeight(), iMatrix);
88
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
89
+ Nv12ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t *)dpFrame, nPitch, dec.GetWidth(), dec.GetHeight(), iMatrix);
90
+ else
91
+ Nv16ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t *)dpFrame, nPitch, dec.GetWidth(), dec.GetHeight(), iMatrix);
92
+ }
93
+ else {
94
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
95
+ YUV444P16ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t *)dpFrame, nPitch, dec.GetWidth(), dec.GetHeight(), iMatrix);
96
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
97
+ P016ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t *)dpFrame, nPitch, dec.GetWidth(), dec.GetHeight(), iMatrix);
98
+ else
99
+ P216ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t *)dpFrame, nPitch, dec.GetWidth(), dec.GetHeight(), iMatrix);
100
+ }
101
+
102
+ gInstance.ReleaseDeviceFrameBuffer();
103
+
104
+ }
105
+ nFrame += nFrameReturned;
106
+ } while (nVideoBytes);
107
+
108
+ std::cout << "Total frame decoded: " << nFrame << std::endl;
109
+ return 1;
110
+ }
111
+
112
+ int main(int argc, char **argv)
113
+ {
114
+ char szInFilePath[256] = "";
115
+ int iGpu = 0;
116
+ try
117
+ {
118
+ ParseCommandLine(argc, argv, szInFilePath, NULL, iGpu, NULL, NULL);
119
+ CheckInputFile(szInFilePath);
120
+
121
+ ck(cuInit(0));
122
+ int nGpu = 0;
123
+ ck(cuDeviceGetCount(&nGpu));
124
+ if (iGpu < 0 || iGpu >= nGpu)
125
+ {
126
+ std::ostringstream err;
127
+ err << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
128
+ throw std::invalid_argument(err.str());
129
+ }
130
+
131
+ CUcontext cuContext = NULL;
132
+ createCudaContext(&cuContext, iGpu, CU_CTX_SCHED_BLOCKING_SYNC);
133
+
134
+ std::cout << "Decode with NvDecoder." << std::endl;
135
+ Decode(cuContext, szInFilePath);
136
+
137
+ ck(cuCtxDestroy(cuContext));
138
+ }
139
+ catch(const std::exception& ex)
140
+ {
141
+ std::cout << ex.what();
142
+ exit(1);
143
+ }
144
+ return 0;
145
+ }
video_codec_sdk/Samples/AppDecode/AppDecGL/CMakeLists.txt ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDecGL)
13
+
14
+ if(WIN32)
15
+ set(APP_SOURCES
16
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecGL.cpp
17
+ )
18
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
19
+ else ()
20
+ set(APP_SOURCES
21
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecGL.cpp
22
+ ${CMAKE_CURRENT_SOURCE_DIR}/FramePresenterGLX.cpp
23
+ )
24
+ endif()
25
+
26
+ if(WIN32)
27
+ set(NV_GL_HDRS ${CMAKE_CURRENT_SOURCE_DIR}/../../External/)
28
+ set(NV_GLEW_HDRS ${GLEW_DIR}/include)
29
+ set(NV_GLUT_HDRS ${GLUT_INC})
30
+ else ()
31
+ set(NV_GL_HDRS "")
32
+ endif()
33
+
34
+ set(NV_DEC_SOURCES
35
+ ${NV_DEC_DIR}/NvDecoder.cpp
36
+ )
37
+
38
+ set(NV_ENC_CUDA_UTILS
39
+ ${NVCODEC_UTILS_DIR}/ColorSpace.cu
40
+ )
41
+
42
+ set(NV_DEC_HDRS
43
+ ${NV_DEC_DIR}/NvDecoder.h
44
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
45
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
46
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
47
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
48
+ ${NVCODEC_UTILS_DIR}/ColorSpace.h
49
+ ${NV_APPDEC_COMMON_DIR}/AppDecUtils.h
50
+ ${CMAKE_CURRENT_SOURCE_DIR}/FramePresenter.h
51
+ ${CMAKE_CURRENT_SOURCE_DIR}/FramePresenterGLUT.h
52
+ )
53
+
54
+ if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
55
+ set(NV_DEC_HDRS ${NV_DEC_HDRS} ${CMAKE_CURRENT_SOURCE_DIR}/FramePresenterGLX.h)
56
+ endif()
57
+
58
+ source_group( "headers" FILES ${NV_DEC_HDRS})
59
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_ENC_CUDA_UTILS})
60
+
61
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
62
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
63
+ find_package(CUDAToolkit QUIET)
64
+ if(CUDAToolkit_FOUND)
65
+ # Map CUDAToolkit variables to legacy CUDA variable names
66
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
67
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
68
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
69
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
70
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
71
+ endif()
72
+ endif()
73
+ if(NOT CUDAToolkit_FOUND)
74
+ find_package(CUDA)
75
+ endif()
76
+
77
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
78
+
79
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
80
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
81
+ else()
82
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
83
+ endif()
84
+ # CUDA 11.7 and later is compiled with /MT option (staticaly linked with C runtime),
85
+ # since we are statically linking cudart_static.lib with the app,
86
+ # we need to make sure that all .obj files linked are compiled with /MT to avoid linker warning LNK4098
87
+ if (WIN32 AND CUDA_VERSION_MAJOR GREATER_EQUAL 11 AND CUDA_VERSION_MINOR GREATER_EQUAL 7)
88
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-Xcompiler /MT)
89
+ endif()
90
+ if ( CMAKE_COMPILER_IS_GNUCC )
91
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
92
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
93
+ endif()
94
+ endif()
95
+
96
+ # Use modern approach with CUDAToolkit when available, fallback to legacy FindCUDA
97
+ if(CUDAToolkit_FOUND AND CUDAToolkit_NVCC_EXECUTABLE)
98
+ set(CMAKE_CUDA_COMPILER ${CUDAToolkit_NVCC_EXECUTABLE})
99
+ enable_language(CUDA)
100
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
101
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_STANDARD 11)
102
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
103
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "75")
104
+ else()
105
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "50")
106
+ endif()
107
+ else()
108
+ cuda_add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
109
+ endif()
110
+
111
+ if (WIN32 AND CUDA_VERSION_MAJOR GREATER_EQUAL 11 AND CUDA_VERSION_MINOR GREATER_EQUAL 7)
112
+ target_compile_options(${PROJECT_NAME} PRIVATE "/MT")
113
+ endif()
114
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
115
+
116
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
117
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
118
+ ${NVCODEC_UTILS_DIR}
119
+ ${NV_CODEC_DIR}
120
+ ${NV_APPDEC_COMMON_DIR}
121
+ ${NV_FFMPEG_HDRS}
122
+ ${NV_GL_HDRS}
123
+ ${NV_GLEW_HDRS}
124
+ ${NV_GLUT_HDRS}
125
+ )
126
+
127
+ if(WIN32)
128
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
129
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
130
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
131
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
132
+ Set(FREEGLUT_LIB ${GLUT_DIR}/lib/Release/freeglut.lib)
133
+ Set(FREEGLUT_STATIC_LIB ${GLUT_DIR}/lib/Release/freeglut_static.lib)
134
+ Set(FREEGLUT_STATICD_LIB ${GLUT_DIR}/lib/Debug/freeglut_staticd.lib)
135
+ Set(FREEGLUTD_LIB ${GLUT_DIR}/lib/Debug/freeglutd.lib)
136
+ if(CMAKE_SIZEOF_VOID_P EQUAL 8)
137
+ Set(GLEW32_LIB ${GLEW_DIR}/lib/Release/x64/glew32.lib)
138
+ Set(GLEW32S_LIB ${GLEW_DIR}/lib/Release/x64/glew32s.lib)
139
+ Set(GLEW_DLL_DIR ${GLEW_DIR}/bin/Release/x64/)
140
+ Set(GLEW_LIB_DIR ${GLEW_DIR}/lib/Release/x64/)
141
+ else()
142
+ Set(GLEW32_LIB ${GLEW_DIR}/lib/Release/Win32/glew32.lib)
143
+ Set(GLEW32S_LIB ${GLEW_DIR}/lib/Release/Win32/glew32s.lib)
144
+ Set(GLEW_DLL_DIR ${GLEW_DIR}/bin/Release/Win32/)
145
+ Set(GLEW_LIB_DIR ${GLEW_DIR}/lib/Release/Win32/)
146
+ endif()
147
+
148
+ Set(GLUT_LIB_DIR ${GLUT_DIR}/lib)
149
+ Set(GLUT_DLL_DIR ${GLUT_DIR}/bin)
150
+
151
+ #copy .dll and .lib files
152
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.dll")
153
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.lib")
154
+
155
+ install(DIRECTORY ${GLUT_LIB_DIR}/Release/ DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.lib")
156
+ install(DIRECTORY ${GLUT_DLL_DIR}/Release/ DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.dll")
157
+ install(DIRECTORY ${GLUT_LIB_DIR}/Debug/ DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.lib")
158
+ install(DIRECTORY ${GLUT_DLL_DIR}/Debug/ DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.dll")
159
+
160
+ install(DIRECTORY ${GLEW_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.lib")
161
+ install(DIRECTORY ${GLEW_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.dll")
162
+
163
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
164
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB} ${FREEGLUT_LIB} ${FREEGLUT_STATIC_LIB} ${FREEGLUT_STATICD_LIB}
165
+ ${FREEGLUTD_LIB} ${GLEW32_LIB} ${GLEW32S_LIB})
166
+ else ()
167
+ find_library(FREEGLUT_LIB glut)
168
+ find_library(GLEW32_LIB GLEW)
169
+ find_library(X11_LIB X11)
170
+ find_library(GL_LIB GL)
171
+ find_library(CUDART_LIB cudart HINTS ${CUDA_TOOLKIT_ROOT_DIR}/lib64)
172
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CUDART_LIB} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
173
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB} ${FREEGLUT_LIB} ${GLEW32_LIB} ${X11_LIB} ${GL_LIB})
174
+ endif()
175
+
176
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
177
+ if (MSVC)
178
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
179
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
180
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
181
+
182
+ # copy ffmpeg, GLUT and GLEW .dll and .lib files
183
+ file(GLOB externalLibList
184
+ ${GLUT_LIB_DIR}/Release/*.lib
185
+ ${GLUT_LIB_DIR}/Debug/*.lib
186
+ ${GLUT_DLL_DIR}/Release/*.dll
187
+ ${GLUT_DLL_DIR}/Debug/*.dll
188
+ ${GLEW_LIB_DIR}/*.lib
189
+ ${GLEW_DLL_DIR}/*.dll
190
+ )
191
+
192
+ foreach(externalLib ${externalLibList})
193
+ add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${externalLib} ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/)
194
+ endforeach()
195
+
196
+ #copy pdb's
197
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
198
+ endif()
199
+
video_codec_sdk/Samples/AppDecode/AppDecGL/FramePresenter.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+ #include <atomic>
12
+
13
+ #pragma once
14
+
15
+ // Base class for GLX and GLUT code paths.
16
+ // Declares essintial function as pure virtual.
17
+ class FramePresenter {
18
+
19
+ public:
20
+
21
+ FramePresenter(): nFrame(0), width(0), height(0) {
22
+ }
23
+
24
+ virtual ~FramePresenter(){
25
+ }
26
+
27
+ std::atomic<bool> endOfDecoding ; /*!< Indicates end of decoding for rendering thread to exit */
28
+ std::atomic<bool> endOfRendering; /*!< Indicates end of rendering to ensure main thread does not
29
+ release graphics resources when they are being used by rendering thread */
30
+
31
+ int nFrame; /*!< Variable to indicate the current count of decoded frames */
32
+
33
+ int width, height; /*!< Denotes dimensions of the decoded frame */
34
+
35
+ virtual void initWindowSystem() = 0;
36
+ virtual void initOpenGLResources() = 0;
37
+ virtual void releaseWindowSystem() = 0;
38
+
39
+ virtual void Render() = 0;
40
+ virtual bool isVendorNvidia() = 0;
41
+ virtual int getWidth() = 0;
42
+ virtual bool GetDeviceFrameBuffer(CUdeviceptr*, int *) = 0;
43
+ virtual void ReleaseDeviceFrameBuffer() = 0;
44
+ };
video_codec_sdk/Samples/AppDecode/AppDecGL/FramePresenterGLUT.h ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ #pragma once
13
+
14
+ #include <iostream>
15
+ #include <algorithm>
16
+ #include <string.h>
17
+ #include <stdlib.h>
18
+ #include <mutex>
19
+ #include <thread>
20
+ #include <chrono>
21
+ #include <GL/glew.h>
22
+ #include <GL/glut.h>
23
+ #include <GL/freeglut_ext.h>
24
+ #include <cuda.h>
25
+ #include <cudaGL.h>
26
+ #include "../Utils/NvCodecUtils.h"
27
+ #include "../Utils/Logger.h"
28
+ #include "FramePresenter.h"
29
+
30
+ class FramePresenterGLUT;
31
+ static FramePresenterGLUT *pInstance;
32
+
33
+ /**
34
+ * @brief OpenGL utility class to display decoded frames using OpenGL textures
35
+ */
36
+ class FramePresenterGLUT : public FramePresenter
37
+ {
38
+ public:
39
+ /**
40
+ * @brief FramePresenterGLUT constructor function. This will launch a rendering thread which will be fed by decoded frames
41
+ * @param cuContext - CUDA Context handle
42
+ * @param nWidth - Width of OpenGL texture
43
+ * @param nHeight - Height of OpenGL texture
44
+ */
45
+ FramePresenterGLUT(CUcontext cuContext, int nWidth, int nHeight) :
46
+ cuContext(cuContext), nWidth(nWidth), nHeight(nHeight)
47
+ {
48
+ pthMessageLoop = new NvThread(std::thread(ThreadProc, this));
49
+
50
+ // This loop will ensure that OpenGL/glew/glut initialization is finished before we return from this constructor
51
+ while (!pInstance) {
52
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
53
+ }
54
+ }
55
+
56
+ /**
57
+ * @brief Destructor function. Also breaks glutMainLoopEvent
58
+ */
59
+ ~FramePresenterGLUT() {
60
+ bStop = true;
61
+ pthMessageLoop->join();
62
+ delete pthMessageLoop;
63
+ }
64
+
65
+ /**
66
+ * @brief Writes CUdeviceptr handle which is later used for OpenGL rendering
67
+ * @param pdpFrame - Pointer to frame data into which decoded frame is written
68
+ * @param pnPitch - Pointer to pitch value. This function will write pitch value based on nWidth
69
+ * @return False if dpFrame is NULL or rendering loop is exited
70
+ * @return True when input params are successfully updated
71
+ */
72
+ bool GetDeviceFrameBuffer(CUdeviceptr *pdpFrame, int *pnPitch) {
73
+ if (bStop || !dpFrame) {
74
+ return false;
75
+ }
76
+
77
+ *pdpFrame = (CUdeviceptr) dpFrame;
78
+ *pnPitch = nWidth * 4;
79
+ return true;
80
+ }
81
+
82
+ void SetText(std::string strText) {
83
+ this->strText = strText;
84
+ }
85
+
86
+ /**
87
+ * @brief Function to check whether underlying vendor is NVIDIA or not
88
+ * @return True if OpenGL vendor is NVIDIA
89
+ * @return False if OpenGL vendor is not NVIDIA
90
+ */
91
+ bool isVendorNvidia() {
92
+ return this->vendorStatus;
93
+ }
94
+
95
+ void initWindowSystem() {
96
+ // No op in GLUT
97
+ }
98
+
99
+ void initOpenGLResources() {
100
+ // No op in GLUT
101
+ }
102
+
103
+ void releaseWindowSystem() {
104
+ // No op in GLUT
105
+ }
106
+
107
+ void ReleaseDeviceFrameBuffer() {
108
+ // No op in GLUT
109
+ }
110
+
111
+ int getWidth() {
112
+ return this->nWidth;
113
+ }
114
+
115
+ private:
116
+ /**
117
+ * @brief Thread launcher function. Launches the graphics initialization code
118
+ * @param This - Pointer to FramePresenterGLUT object
119
+ * @return void
120
+ */
121
+ static void ThreadProc(FramePresenterGLUT *This) {
122
+ This->Run();
123
+ }
124
+
125
+ /**
126
+ * @brief Registered with glutDisplayFunc() as rendering function
127
+ * @return void
128
+ */
129
+ static void DisplayProc() {
130
+ if (!pInstance) {
131
+ return;
132
+ }
133
+ pInstance->Render();
134
+ }
135
+
136
+ static void CloseWindowProc() {
137
+ if (!pInstance) {
138
+ return;
139
+ }
140
+ // Enable the flag to break glutMainLoopEvent
141
+ pInstance->bStop = true;
142
+ }
143
+
144
+ /**
145
+ * @brief This function is responsible for OpenGL/glew/glut initialization and also for initiating display loop
146
+ * @return void
147
+ */
148
+ void Run() {
149
+ int w = nWidth, h = nHeight;
150
+
151
+ // Calculate the ratio to restrict viewport dimensions to 1280x720
152
+ double r = (std::max)(nWidth / 1280.0, nHeight / 720.0);
153
+ if (r > 1.0) {
154
+ w = (int)(nWidth / r);
155
+ h = (int)(nHeight / r);
156
+ }
157
+
158
+ int argc = 1;
159
+ const char *argv[] = {"dummy"};
160
+ glutInit(&argc, (char **)argv);
161
+ glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
162
+ glutInitWindowSize(w, h);
163
+ glutCreateWindow("FramePresenterGLUT");
164
+ glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
165
+
166
+ char * vendor = (char*) glGetString(GL_VENDOR);
167
+
168
+ if (!strcmp(vendor, "NVIDIA Corporation")) {
169
+ this->vendorStatus = true;
170
+ } else {
171
+ // To prevent infinite loop in constructor, initialize pInstance
172
+ pInstance = this;
173
+ this->vendorStatus = false;
174
+ return;
175
+ }
176
+
177
+ glViewport(0, 0, w, h);
178
+ glMatrixMode(GL_MODELVIEW);
179
+ glLoadIdentity();
180
+ glMatrixMode(GL_PROJECTION);
181
+ glLoadIdentity();
182
+ glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
183
+
184
+ glewInit();
185
+ // Prepare OpenGL buffer object for uploading texture data
186
+ glGenBuffersARB(1, &pbo);
187
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
188
+ glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, nWidth * nHeight * 4, NULL, GL_STREAM_DRAW_ARB);
189
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
190
+
191
+ // Create OpenGL texture and upload frame data
192
+ glGenTextures(1, &tex);
193
+ glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex);
194
+ glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
195
+ glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
196
+ glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
197
+ glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
198
+
199
+ // Create and initialize fragment program
200
+ static const char *code =
201
+ "!!ARBfp1.0\n"
202
+ "TEX result.color, fragment.texcoord, texture[0], RECT; \n"
203
+ "END";
204
+ glGenProgramsARB(1, &shader);
205
+ glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader);
206
+ glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(code), (GLubyte *)code);
207
+
208
+ // Register display function
209
+ glutDisplayFunc(DisplayProc);
210
+ // Register window close event callback function
211
+ glutCloseFunc(CloseWindowProc);
212
+
213
+ ck(cuCtxSetCurrent(cuContext));
214
+ ck(cuMemAlloc(&dpFrame, nWidth * nHeight * 4));
215
+ ck(cuMemsetD8(dpFrame, 0, nWidth * nHeight * 4));
216
+
217
+ pInstance = this;
218
+
219
+ // Launch the rendering loop
220
+ while (!bStop) {
221
+ glutMainLoopEvent();
222
+ }
223
+ pInstance = NULL;
224
+
225
+ ck(cuMemFree(dpFrame));
226
+
227
+ glDeleteBuffersARB(1, &pbo);
228
+ glDeleteTextures(1, &tex);
229
+ glDeleteProgramsARB(1, &shader);
230
+ }
231
+
232
+ /**
233
+ * @brief Rendering function called by glut
234
+ * @return void
235
+ */
236
+ void Render(void) {
237
+
238
+ // Register the OpenGL buffer object with CUDA and map a CUdeviceptr onto it
239
+ // The decoder code will receive this CUdeviceptr and copy the decoded frame into the associated device memory allocation
240
+ CUgraphicsResource cuResource;
241
+ ck(cuGraphicsGLRegisterBuffer(&cuResource, pbo, CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD));
242
+ ck(cuGraphicsMapResources(1, &cuResource, 0));
243
+ CUdeviceptr dpBackBuffer;
244
+ size_t nSize = 0;
245
+ ck(cuGraphicsResourceGetMappedPointer(&dpBackBuffer, &nSize, cuResource));
246
+
247
+ CUDA_MEMCPY2D m = { 0 };
248
+ m.srcMemoryType = CU_MEMORYTYPE_DEVICE;
249
+
250
+ // Source is dpFrame into which Decode() function writes data of individual frame present in BGRA32 format
251
+ // Destination is OpenGL buffer object mapped as a CUDA resource
252
+ m.srcDevice = dpFrame;
253
+ m.srcPitch = nWidth * 4;
254
+ m.dstMemoryType = CU_MEMORYTYPE_DEVICE;
255
+ m.dstDevice = dpBackBuffer;
256
+ m.dstPitch = nSize / nHeight;
257
+ m.WidthInBytes = nWidth * 4;
258
+ m.Height = nHeight;
259
+ ck(cuMemcpy2DAsync(&m, 0));
260
+
261
+ ck(cuGraphicsUnmapResources(1, &cuResource, 0));
262
+ ck(cuGraphicsUnregisterResource(cuResource));
263
+
264
+ // Bind OpenGL buffer object and upload the data
265
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
266
+ glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex);
267
+ glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, nWidth, nHeight, GL_BGRA, GL_UNSIGNED_BYTE, 0);
268
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
269
+
270
+ glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader);
271
+ glEnable(GL_FRAGMENT_PROGRAM_ARB);
272
+ glDisable(GL_DEPTH_TEST);
273
+
274
+ // Specify vertex and texture co-ordinates
275
+ glBegin(GL_QUADS);
276
+ glTexCoord2f(0, (GLfloat)nHeight);
277
+ glVertex2f(0, 0);
278
+ glTexCoord2f((GLfloat)nWidth, (GLfloat)nHeight);
279
+ glVertex2f(1, 0);
280
+ glTexCoord2f((GLfloat)nWidth, 0);
281
+ glVertex2f(1, 1);
282
+ glTexCoord2f(0, 0);
283
+ glVertex2f(0, 1);
284
+ glEnd();
285
+ glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
286
+ glDisable(GL_FRAGMENT_PROGRAM_ARB);
287
+
288
+ if (!strText.empty()) {
289
+ PrintText(0, strText, 0, 0, true);
290
+ }
291
+
292
+ glutSwapBuffers();
293
+ glutPostRedisplay();
294
+ }
295
+
296
+ static void PrintText(int iFont, std::string strText, int x, int y, bool bFillBackground) {
297
+ struct {void *font; int d1; int d2;} fontData[] = {
298
+ /*0*/ GLUT_BITMAP_9_BY_15, 13, 4,
299
+ /*1*/ GLUT_BITMAP_8_BY_13, 11, 4,
300
+ /*2*/ GLUT_BITMAP_TIMES_ROMAN_10, 9, 3,
301
+ /*3*/ GLUT_BITMAP_TIMES_ROMAN_24, 20, 7,
302
+ /*4*/ GLUT_BITMAP_HELVETICA_10, 10, 3,
303
+ /*5*/ GLUT_BITMAP_HELVETICA_12, 11, 4,
304
+ /*6*/ GLUT_BITMAP_HELVETICA_18, 16, 5,
305
+ };
306
+ const int nFont = sizeof(fontData) / sizeof(fontData[0]);
307
+
308
+ if (iFont >= nFont) {
309
+ iFont = 0;
310
+ }
311
+ void *font = fontData[iFont].font;
312
+ int d1 = fontData[iFont].d1, d2 = fontData[iFont].d2, d = d1 + d2,
313
+ w = glutGet(GLUT_WINDOW_WIDTH), h = glutGet(GLUT_WINDOW_HEIGHT);
314
+
315
+ glMatrixMode(GL_PROJECTION);
316
+ glPushMatrix();
317
+ glLoadIdentity();
318
+ glOrtho(0.0, w, 0.0, h, 0.0, 1.0);
319
+
320
+ std::stringstream ss(strText);
321
+ std::string str;
322
+ int iLine = 0;
323
+ while (std::getline(ss, str)) {
324
+ glColor3f(1.0, 1.0, 1.0);
325
+ if (bFillBackground) {
326
+ glRasterPos2i(x, h - y - iLine * d - d1);
327
+ for (char c : str) {
328
+ glutBitmapCharacter(font, c);
329
+ }
330
+ GLint pos[4];
331
+ glGetIntegerv(GL_CURRENT_RASTER_POSITION, pos);
332
+ glRecti(x, h - y - iLine * d, pos[0], h - y - (iLine + 1) * d);
333
+ glColor3f(0.0, 0.0, 0.0);
334
+ }
335
+ glRasterPos2i(x, h - y - iLine * d - d1);
336
+ for (char c : str) {
337
+ glutBitmapCharacter(font, c);
338
+ }
339
+ iLine++;
340
+ }
341
+
342
+ glPopMatrix();
343
+ }
344
+
345
+ private:
346
+ bool bStop = false; /*!< Variable to control rendering loop */
347
+ int nWidth = 0, nHeight = 0;/*!< Dimensions of the frame being decoded */
348
+ CUcontext cuContext = NULL;
349
+ CUdeviceptr dpFrame = 0; /*!< CUdeviceptr referenced by main thread to write decoded frames into */
350
+ NvThread *pthMessageLoop = NULL;
351
+ std::string strText;
352
+ GLuint pbo; /*!< Buffer object to upload texture data */
353
+ GLuint tex; /*!< OpenGL texture handle */
354
+ GLuint shader;
355
+ bool vendorStatus = false; /*!< true if OpenGL vendor is NVIDIA, false otherwise */
356
+
357
+ };
video_codec_sdk/Samples/AppDecode/AppDecGL/FramePresenterGLX.cpp ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ #include "FramePresenterGLX.h"
13
+ #include <iostream>
14
+ #include <cstring>
15
+ #include <thread>
16
+
17
+ #include "../Utils/NvCodecUtils.h"
18
+ /**
19
+ * @brief Constructor to initialize GLX, OpenGL and CUDA resources. Also launches rendering thread.
20
+ * @param None
21
+ * @return None
22
+ */
23
+ FramePresenterGLX::FramePresenterGLX(int w, int h) {
24
+
25
+ frameFeeder.setSize(BUFFER_COUNT);
26
+
27
+ currentFrame = 0;
28
+ endOfDecoding = false;
29
+ endOfRendering = false;
30
+
31
+ cuResource[0] = 0;
32
+ cuResource[1] = 0;
33
+
34
+ // Initialize the width and height to be used in texture updates
35
+ setDimensions(w, h);
36
+
37
+ // Initliaze GLX window, context
38
+ initWindowSystem();
39
+
40
+ // Initialize OpenGL resources
41
+ initOpenGLResources();
42
+
43
+ for (int i = 0; i < BUFFER_COUNT; i++) {
44
+
45
+ // Attach pbo to each of the cuda graphics resource
46
+ ck(cuGraphicsGLRegisterBuffer(&cuResource[i], pbo[i], CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD));
47
+ }
48
+
49
+ // Create a thread handle using Render function of the class for execution
50
+ renderingThread = NvThread(std::thread(&FramePresenterGLX::Render, this));
51
+ }
52
+
53
+ /**
54
+ * @brief Check if valid NVIDIA libraries are installed.
55
+ * @param None
56
+ * @return None
57
+ */
58
+ bool FramePresenterGLX::isVendorNvidia() {
59
+
60
+ char * vendor = (char*) glGetString(GL_VENDOR);
61
+
62
+ if (!strcmp(vendor, "NVIDIA Corporation")) {
63
+ return true;
64
+ } else {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * @brief Create PBO and CUResource binding.
71
+ * @param None
72
+ * @return None
73
+ */
74
+ bool FramePresenterGLX::GetDeviceFrameBuffer(CUdeviceptr *dpFrame, int *pitch) {
75
+
76
+ mapBufferObject(dpFrame);
77
+ *pitch = getWidth()*4;
78
+
79
+ return true;
80
+ }
81
+
82
+ /**
83
+ * @brief Release the mapping so that, Rendering thread can consume the updated PBO.
84
+ * @param None
85
+ * @return None
86
+ */
87
+ void FramePresenterGLX::ReleaseDeviceFrameBuffer() {
88
+
89
+ unmapBufferObject();
90
+ }
91
+
92
+ /**
93
+ * @brief Binds CUResource to PBO and returns the CUdeviceptr that caller can work with.
94
+ * @param None
95
+ * @return None
96
+ */
97
+ void FramePresenterGLX::mapBufferObject(CUdeviceptr* dpBuffer) {
98
+
99
+ ck(cuGraphicsMapResources(1, &cuResource[currentFrame], 0));
100
+
101
+ size_t nSize = 0;
102
+ ck(cuGraphicsResourceGetMappedPointer(dpBuffer, &nSize, cuResource[currentFrame]));
103
+ }
104
+
105
+ /**
106
+ * @brief Unmap the binding between CUResource and PBO.
107
+ * @param None
108
+ * @return None
109
+ */
110
+ void FramePresenterGLX::unmapBufferObject() {
111
+
112
+ ck(cuGraphicsUnmapResources(1, &cuResource[currentFrame], 0));
113
+
114
+ frameFeeder.push_back(currentFrame);
115
+
116
+ // CurrentFrame goes from between 0 and (BUFFER_COUNT - 1)
117
+ currentFrame = (currentFrame + 1) % BUFFER_COUNT;
118
+ }
119
+
120
+ /**
121
+ * @brief Function to render decoded frame using OpenGL calls.
122
+ * The PBO used here is populated by Decode function.
123
+ * Rendering is done using shared GLX context.
124
+ * @param None
125
+ * @return None
126
+ */
127
+ void FramePresenterGLX::Render() {
128
+
129
+ int w = getWidth();
130
+ int h = getHeight();
131
+
132
+ glXMakeCurrent(display, win, shared_ctx);
133
+
134
+ int currentRender = 0;
135
+
136
+ glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, program);
137
+ glEnable(GL_FRAGMENT_PROGRAM_ARB);
138
+ glDisable(GL_DEPTH_TEST);
139
+
140
+ while (!endOfDecoding) {
141
+
142
+ currentRender = frameFeeder.front();
143
+
144
+ // Bind OpenGL buffer object and upload the data
145
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo[currentRender]);
146
+
147
+ glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex[currentRender]);
148
+ glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, w, h, GL_BGRA, GL_UNSIGNED_BYTE, 0);
149
+
150
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
151
+
152
+ glBegin(GL_QUADS);
153
+ glTexCoord2f(0, (GLfloat)h);
154
+ glVertex2f(-1.0f, -1.0f);
155
+ glTexCoord2f((GLfloat)w, (GLfloat)h);
156
+ glVertex2f(1.0f, -1.0f);
157
+ glTexCoord2f((GLfloat)w, 0);
158
+ glVertex2f(1.0f, 1.0f);
159
+ glTexCoord2f(0, 0);
160
+ glVertex2f(-1.0f, 1.0f);
161
+ glEnd();
162
+ glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
163
+
164
+ glXSwapBuffers(display, win);
165
+
166
+ frameFeeder.pop_front();
167
+ }
168
+
169
+ glDisable(GL_FRAGMENT_PROGRAM_ARB);
170
+
171
+ glXMakeCurrent(display, 0, 0);
172
+
173
+ endOfRendering = true;
174
+ }
175
+
176
+ /**
177
+ * @brief Function to release GLX resources like display, window, context and colormap.
178
+ * @param None
179
+ * @return None
180
+ */
181
+ void FramePresenterGLX::releaseWindowSystem() {
182
+
183
+ glXMakeCurrent(display, 0, 0);
184
+ glXDestroyContext(display, ctx);
185
+ glXDestroyContext(display, shared_ctx);
186
+
187
+ XDestroyWindow(display, win);
188
+ XFreeColormap(display, cmap);
189
+ XCloseDisplay(display);
190
+ }
191
+
192
+ /**
193
+ * @brief Function to create GLX resources like display, window, context and colormap.
194
+ * Exits the app in case any GLX API fails.
195
+ * @param None
196
+ * @return None
197
+ */
198
+ void FramePresenterGLX::initWindowSystem() {
199
+
200
+ XInitThreads();
201
+
202
+ XVisualInfo *visinfo;
203
+ GLXFBConfig config;
204
+
205
+ display = XOpenDisplay(NULL);
206
+ if (display == NULL) {
207
+ std::cout << "\nDisplay not found ! Make sure X server is running and DISPLAY environment variable set appropriately !\n";
208
+ exit(1);
209
+ }
210
+
211
+ int configAttr[] = {
212
+ GLX_CONFIG_CAVEAT ,GLX_NONE,
213
+ GLX_RENDER_TYPE ,GLX_RGBA_BIT,
214
+ GLX_RED_SIZE , 8,
215
+ GLX_GREEN_SIZE , 8,
216
+ GLX_BLUE_SIZE , 8,
217
+ GLX_ALPHA_SIZE , 8,
218
+ GLX_DEPTH_SIZE , 24,
219
+ GLX_STENCIL_SIZE , 8,
220
+ GLX_DOUBLEBUFFER , True,
221
+ None,
222
+ };
223
+
224
+ GLXFBConfig *configs = NULL;
225
+ int numConfigs = 0;
226
+
227
+ int screen = DefaultScreen(display);
228
+
229
+ configs = glXChooseFBConfig(display, screen, configAttr, &numConfigs);
230
+ if (numConfigs <= 0 || configs == NULL) {
231
+ std::cout << "\nFailed to find a suitable GLXFBConfig!\n";
232
+ exit(1);
233
+ }
234
+
235
+ config = configs[0];
236
+ XFree(configs);
237
+
238
+ visinfo = glXGetVisualFromFBConfig(display, config);
239
+ if (!visinfo) {
240
+ std::cout << "\nFailed to find a suitable visual!\n";
241
+ exit(1);
242
+ }
243
+
244
+ Window root;
245
+ XSetWindowAttributes wattr;
246
+ int wattr_mask;
247
+
248
+ root = RootWindow(display, screen);
249
+
250
+ cmap = XCreateColormap(display, root, visinfo->visual, AllocNone);
251
+
252
+ if (!cmap) {
253
+ std::cout << "\nFailed to create colormap!\n";
254
+ exit(1);
255
+ }
256
+
257
+ wattr_mask = CWBackPixmap | CWBorderPixel | CWColormap;
258
+ wattr.background_pixmap = None;
259
+ wattr.border_pixel = 0;
260
+ wattr.bit_gravity = StaticGravity;
261
+ wattr.colormap = cmap;
262
+
263
+ win = XCreateWindow(display, root, 0, 0, 640, 480, 0,
264
+ visinfo->depth, InputOutput,
265
+ visinfo->visual, wattr_mask, &wattr);
266
+
267
+ if (!win) {
268
+ std::cout << "\nFailed to create window!\n";
269
+ exit(1);
270
+ }
271
+
272
+ XMapWindow(display, win);
273
+
274
+ ctx = glXCreateNewContext(display, config, GLX_RGBA_TYPE, 0, True);
275
+
276
+ if (!ctx) {
277
+ std::cout << "\nFailed to create GLX context !\n";
278
+ exit(1);
279
+ }
280
+
281
+ shared_ctx = glXCreateNewContext(display, config, GLX_RGBA_TYPE, ctx, True);
282
+
283
+ if (!shared_ctx) {
284
+ std::cout << "\nFailed to create shared GLX context !\n";
285
+ exit(1);
286
+ }
287
+
288
+ glXMakeCurrent(display, win, ctx);
289
+ }
290
+
291
+ /**
292
+ * @brief Function to create OpenGL resources viz. pixel buffer objects, textures, program objects.
293
+ * @param None
294
+ * @return None
295
+ */
296
+ void FramePresenterGLX::initOpenGLResources() {
297
+
298
+ glewInit();
299
+
300
+ GLuint &shader = getProgramObject();
301
+
302
+ glGenTextures(BUFFER_COUNT, tex);
303
+ glGenBuffers(BUFFER_COUNT, pbo);
304
+
305
+ for (int i=0; i<BUFFER_COUNT; i++) {
306
+
307
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo[i]);
308
+ glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, width * height * 4, NULL, GL_DYNAMIC_DRAW_ARB);
309
+ glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
310
+
311
+ glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex[i]);
312
+ glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
313
+ glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
314
+ glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
315
+
316
+ glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
317
+ }
318
+
319
+ // Create and initialize fragment program
320
+ static const char *code =
321
+ "!!ARBfp1.0\n"
322
+ "TEX result.color, fragment.texcoord, texture[0], RECT; \n"
323
+ "END";
324
+
325
+ glGenProgramsARB(1, &shader);
326
+ glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, shader);
327
+ glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)strlen(code), (GLubyte *)code);
328
+ }
329
+
330
+ /**
331
+ * @brief Function to release OpenGL resources viz. pixel buffer objects, textures, program objects.
332
+ * @param None
333
+ * @return None
334
+ */
335
+ FramePresenterGLX::~FramePresenterGLX() {
336
+
337
+ endOfDecoding = true;
338
+
339
+ // Don't release resources till rendering is finished.
340
+ while (!endOfRendering) {
341
+ }
342
+
343
+ renderingThread.join();
344
+
345
+ for (int i = 0; i < BUFFER_COUNT; i++) {
346
+ ck(cuGraphicsUnregisterResource(cuResource[i]));
347
+ }
348
+
349
+ GLuint &shader = getProgramObject();
350
+
351
+ // Release OpenGL resources
352
+ glDeleteBuffersARB(BUFFER_COUNT, pbo);
353
+ glDeleteTextures(BUFFER_COUNT, tex);
354
+ glDeleteProgramsARB(1, &shader);
355
+
356
+ // Release GLX resources
357
+ releaseWindowSystem();
358
+ }
359
+
360
+
video_codec_sdk/Samples/AppDecode/AppDecGL/FramePresenterGLX.h ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+ #include <X11/Xlib.h>
12
+ #include <X11/Xutil.h>
13
+ #include <GL/glew.h>
14
+ #include <GL/gl.h>
15
+ #include <GL/glx.h>
16
+ #include <iostream>
17
+ #include <mutex>
18
+
19
+ #include <cuda.h>
20
+ #include <cudaGL.h>
21
+
22
+ #include "../Utils/NvCodecUtils.h"
23
+ #include "FramePresenter.h"
24
+
25
+ #include <thread>
26
+ #include <queue>
27
+
28
+ #pragma once
29
+
30
+ // Controls the number of OpenGL and CUDA resources to be created.
31
+ // Increasing this will increase the GPU memory utilization.
32
+ #define BUFFER_COUNT 2
33
+
34
+ // Singleton class to manage graphics resources
35
+ class FramePresenterGLX : public FramePresenter {
36
+
37
+ CUgraphicsResource cuResource[BUFFER_COUNT];
38
+ GLuint pbo[BUFFER_COUNT]; /*!< Buffer object to upload texture data */
39
+ GLuint tex[BUFFER_COUNT]; /*!< OpenGL texture handle */
40
+ GLuint program;
41
+
42
+ // GLX resources
43
+ Display *display;
44
+ Window win;
45
+ GLXContext ctx;
46
+ GLXContext shared_ctx;
47
+ Colormap cmap;
48
+
49
+ CUcontext cuContext;
50
+
51
+ int currentFrame;
52
+ float totalWaitTime;
53
+
54
+ NvThread renderingThread;
55
+
56
+ public:
57
+
58
+ FramePresenterGLX(int w, int h);
59
+
60
+ ~FramePresenterGLX();
61
+
62
+ void init(int w, int h, CUcontext context);
63
+
64
+ // Following are pure virtual functions in FramePresenter class
65
+ void initWindowSystem();
66
+ void initOpenGLResources();
67
+ void releaseWindowSystem();
68
+
69
+ bool isVendorNvidia();
70
+ void Render();
71
+
72
+ bool GetDeviceFrameBuffer(CUdeviceptr*, int *);
73
+ void ReleaseDeviceFrameBuffer();
74
+
75
+ ConcurrentQueue<int> frameFeeder;
76
+
77
+ Display*& getDisplay() {
78
+ return this->display;
79
+ }
80
+
81
+ Window& getWindow() {
82
+ return this->win;
83
+ }
84
+
85
+ GLXContext& getContext() {
86
+ return this->ctx;
87
+ }
88
+
89
+ GLXContext& getSharedContext() {
90
+ return this->shared_ctx;
91
+ }
92
+
93
+ Colormap& getColorMap() {
94
+ return this->cmap;
95
+ }
96
+
97
+ GLuint* getPBO() {
98
+ return this->pbo;
99
+ }
100
+
101
+ GLuint* getTextures() {
102
+ return this->tex;
103
+ }
104
+
105
+ GLuint& getProgramObject() {
106
+ return this->program;
107
+ }
108
+
109
+ void setDimensions(unsigned int w, unsigned int h) {
110
+
111
+ this->width = w;
112
+ this->height = h;
113
+ }
114
+
115
+ int getWidth() {
116
+ return this->width;
117
+ }
118
+
119
+ int getHeight() {
120
+ return this->height;
121
+ }
122
+
123
+ void mapBufferObject(CUdeviceptr*);
124
+ void unmapBufferObject();
125
+ };
video_codec_sdk/Samples/AppDecode/AppDecImageProvider/AppDecImageProvider.cpp ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecImageProvider.cpp
14
+ //! \brief Source file for AppDecImageProvider sample
15
+ //!
16
+ //! This sample application illustrates the decoding of a media file in a desired color format.
17
+ //! The application supports native (nv12 or p016), bgra, bgrp and bgra64 output formats.
18
+ //---------------------------------------------------------------------------
19
+
20
+ #include <cuda.h>
21
+ #include <iostream>
22
+ #include <algorithm>
23
+ #include <memory>
24
+ #include "NvDecoder/NvDecoder.h"
25
+ #include "../Utils/FFmpegDemuxer.h"
26
+ #include "../Utils/ColorSpace.h"
27
+ #include "../Common/AppDecUtils.h"
28
+
29
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
30
+
31
+ /**
32
+ * @brief Function to copy image data from CUDA device pointer to host buffer
33
+ * @param dpSrc - CUDA device pointer which holds decoded raw frame
34
+ * @param pDst - Pointer to host buffer which acts as the destination for the copy
35
+ * @param nWidth - Width of decoded frame
36
+ * @param nHeight - Height of decoded frame
37
+ */
38
+ void GetImage(CUdeviceptr dpSrc, uint8_t *pDst, int nWidth, int nHeight)
39
+ {
40
+ CUDA_MEMCPY2D m = { 0 };
41
+ m.WidthInBytes = nWidth;
42
+ m.Height = nHeight;
43
+ m.srcMemoryType = CU_MEMORYTYPE_DEVICE;
44
+ m.srcDevice = (CUdeviceptr)dpSrc;
45
+ m.srcPitch = m.WidthInBytes;
46
+ m.dstMemoryType = CU_MEMORYTYPE_HOST;
47
+ m.dstDevice = (CUdeviceptr)(m.dstHost = pDst);
48
+ m.dstPitch = m.WidthInBytes;
49
+ cuMemcpy2D(&m);
50
+ }
51
+
52
+ enum OutputFormat
53
+ {
54
+ native = 0, bgrp, rgbp, bgra, rgba, bgra64, rgba64, rgb, bgr
55
+ };
56
+
57
+ std::vector<std::string> vstrOutputFormatName =
58
+ {
59
+ "native", "bgrp", "rgbp", "bgra", "rgba", "bgra64", "rgba64", "rgb", "bgr"
60
+ };
61
+
62
+ std::string GetSupportedFormats()
63
+ {
64
+ std::ostringstream oss;
65
+ for (auto& v : vstrOutputFormatName)
66
+ {
67
+ oss << " " << v;
68
+ }
69
+
70
+ return oss.str();
71
+ }
72
+
73
+ static void ShowBriefHelp()
74
+ {
75
+ std::ostringstream oss;
76
+ oss << "NVIDIA Video Decoder Image Provider Sample Application\n";
77
+ oss << "================================================\n\n";
78
+
79
+ oss << "Usage: AppDecImageProvider -i <input_file> [options]\n\n";
80
+
81
+ // Brief table of core arguments
82
+ oss << "Common Arguments:\n";
83
+ oss << std::left << std::setw(25) << "Argument"
84
+ << std::setw(12) << "Type"
85
+ << "Default Value\n";
86
+ oss << std::string(50, '-') << "\n";
87
+
88
+ oss << std::left << std::setw(25) << "-i <path>"
89
+ << std::setw(12) << "Required"
90
+ << "N/A\n";
91
+
92
+ oss << std::left << std::setw(25) << "-o <path>"
93
+ << std::setw(12) << "Optional"
94
+ << "out.<format>\n";
95
+
96
+ oss << std::left << std::setw(25) << "-of <format>"
97
+ << std::setw(12) << "Optional"
98
+ << "native\n";
99
+
100
+ oss << std::left << std::setw(25) << "-gpu <n>"
101
+ << std::setw(12) << "Optional"
102
+ << "0\n";
103
+
104
+ oss << "\nSupported output formats:" << GetSupportedFormats() << "\n";
105
+ oss << "\nFor detailed help, use -A/--advanced-options\n";
106
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
107
+ std::cout << oss.str();
108
+ exit(0);
109
+ }
110
+
111
+ static void ShowDetailedHelp()
112
+ {
113
+ std::ostringstream oss;
114
+ oss << "NVIDIA Video Decoder Image Provider Sample Application - Detailed Help\n";
115
+ oss << "=============================================================\n\n";
116
+
117
+ oss << "Usage: AppDecImageProvider -i <input_file> [options]\n\n";
118
+
119
+ // Full table of all arguments
120
+ oss << "All Arguments:\n";
121
+ oss << std::left << std::setw(25) << "Argument"
122
+ << std::setw(12) << "Type"
123
+ << std::setw(20) << "Default Value"
124
+ << "Description\n";
125
+ oss << std::string(80, '-') << "\n";
126
+
127
+ // Required arguments
128
+ oss << std::left << std::setw(25) << "-i <path>"
129
+ << std::setw(12) << "Required"
130
+ << std::setw(20) << "N/A"
131
+ << "Input video file path\n";
132
+
133
+ // Optional arguments
134
+ oss << std::left << std::setw(25) << "-o <path>"
135
+ << std::setw(12) << "Optional"
136
+ << std::setw(20) << "out.<format>"
137
+ << "Output file path\n";
138
+
139
+ oss << std::left << std::setw(25) << "-of <format>"
140
+ << std::setw(12) << "Optional"
141
+ << std::setw(20) << "native"
142
+ << "Output format\n";
143
+
144
+ oss << std::left << std::setw(25) << "-gpu <n>"
145
+ << std::setw(12) << "Optional"
146
+ << std::setw(20) << "0"
147
+ << "GPU device ordinal\n";
148
+
149
+ // Detailed descriptions
150
+ oss << "\nDetailed Descriptions:\n";
151
+ oss << "-------------------\n";
152
+ oss << std::left << std::setw(25) << "-i" << ": Input video file path. Supported formats include H.264, HEVC, MPEG-2, VP8, VP9, AV1\n";
153
+ oss << std::left << std::setw(25) << "-o" << ": Output file path. If not specified, defaults to 'out.<format>'\n";
154
+ oss << std::left << std::setw(25) << "-of" << ": Output format for decoded frames. See supported formats below\n";
155
+ oss << std::left << std::setw(25) << "-gpu" << ": GPU device ordinal for decoding. Must be within available GPU range\n";
156
+ oss << std::left << std::setw(25) << "-h/--help" << ": Print usage information for common commandline options\n";
157
+ oss << std::left << std::setw(25) << "-A/--advanced-options" << ": Print usage information for common and advanced commandline options\n";
158
+ oss << std::left << std::setw(25) << "-dc/--decode-caps" << ": Print decode capabilities of GPU\n";
159
+
160
+ // Output format details
161
+ oss << "\nSupported Output Formats:\n";
162
+ oss << "----------------------\n";
163
+ oss << "native : Original decoded format (NV12/P016)\n";
164
+ oss << "bgrp : Planar BGR\n";
165
+ oss << "rgbp : Planar RGB\n";
166
+ oss << "bgra : Interleaved BGRA-8bit\n";
167
+ oss << "rgba : Interleaved RGBA-8bit\n";
168
+ oss << "bgra64 : Interleaved BGRA-16bit\n";
169
+ oss << "rgba64 : Interleaved RGBA-16bit\n";
170
+ oss << "rgb : Interleaved RGB-8bit\n";
171
+ oss << "bgr : Interleaved BGR-8bit\n";
172
+
173
+ // Important notes
174
+ oss << "\nNotes:\n";
175
+ oss << "------\n";
176
+ oss << "* Native format is used by default if -of is not specified\n";
177
+ oss << "* Output filename will be 'out.<format>' if -o is not specified\n";
178
+ oss << "* GPU ordinal must be within available GPU range\n";
179
+ oss << std::endl;
180
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
181
+
182
+ std::cout << oss.str();
183
+ exit(0);
184
+ }
185
+
186
+ static void ShowHelpAndExit(const char *szBadOption = NULL)
187
+ {
188
+ if (szBadOption)
189
+ {
190
+ std::ostringstream oss;
191
+ oss << "Error parsing \"" << szBadOption << "\"\n";
192
+ oss << "Use -h/--help for basic usage or -A/--advanced-options for detailed information\n";
193
+ throw std::invalid_argument(oss.str());
194
+ }
195
+ }
196
+
197
+ void ParseCommandLine(int argc, char *argv[], char *szInputFileName,
198
+ OutputFormat &eOutputFormat, char *szOutputFileName, int &iGpu)
199
+ {
200
+ std::ostringstream oss;
201
+ if (argc == 1) {
202
+ std::cout << "No Arguments provided! Please refer to the following for options:" << "\"\n";
203
+ ShowBriefHelp();
204
+ }
205
+
206
+ int i;
207
+ for (i = 1; i < argc; i++) {
208
+ if (!_stricmp(argv[i], "-h") || !_stricmp(argv[i], "--help")) {
209
+ ShowBriefHelp();
210
+ }
211
+ if (!_stricmp(argv[i], "-A") || !_stricmp(argv[i], "--advanced-options")) {
212
+ ShowDetailedHelp();
213
+ }
214
+ if (!_stricmp(argv[i], "-dc") || !_stricmp(argv[i], "--decode-caps")) {
215
+ ShowDecoderCapability();
216
+ }
217
+ if (!_stricmp(argv[i], "-i")) {
218
+ if (++i == argc) {
219
+ ShowHelpAndExit("-i");
220
+ }
221
+ sprintf(szInputFileName, "%s", argv[i]);
222
+ continue;
223
+ }
224
+ if (!_stricmp(argv[i], "-o")) {
225
+ if (++i == argc) {
226
+ ShowHelpAndExit("-o");
227
+ }
228
+ sprintf(szOutputFileName, "%s", argv[i]);
229
+ continue;
230
+ }
231
+ if (!_stricmp(argv[i], "-of")) {
232
+ if (++i == argc) {
233
+ ShowHelpAndExit("-of");
234
+ }
235
+ auto it = find(vstrOutputFormatName.begin(), vstrOutputFormatName.end(), argv[i]);
236
+ if (it == vstrOutputFormatName.end()) {
237
+ ShowHelpAndExit("-of");
238
+ }
239
+ eOutputFormat = (OutputFormat)(it - vstrOutputFormatName.begin());
240
+ continue;
241
+ }
242
+ if (!_stricmp(argv[i], "-gpu")) {
243
+ if (++i == argc) {
244
+ ShowHelpAndExit("-gpu");
245
+ }
246
+ iGpu = atoi(argv[i]);
247
+ continue;
248
+ }
249
+ ShowHelpAndExit(argv[i]);
250
+ }
251
+ }
252
+
253
+ int main(int argc, char **argv)
254
+ {
255
+ char szInFilePath[256] = "", szOutFilePath[256] = "";
256
+ OutputFormat eOutputFormat = native;
257
+ int iGpu = 0;
258
+ bool bReturn = 1;
259
+ CUdeviceptr pTmpImage = 0;
260
+
261
+ try
262
+ {
263
+ ParseCommandLine(argc, argv, szInFilePath, eOutputFormat, szOutFilePath, iGpu);
264
+ CheckInputFile(szInFilePath);
265
+
266
+ if (!*szOutFilePath)
267
+ {
268
+ sprintf(szOutFilePath, "out.%s", vstrOutputFormatName[eOutputFormat].c_str());
269
+ }
270
+
271
+ std::ofstream fpOut(szOutFilePath, std::ios::out | std::ios::binary);
272
+ if (!fpOut)
273
+ {
274
+ std::ostringstream err;
275
+ err << "Unable to open output file: " << szOutFilePath << std::endl;
276
+ throw std::invalid_argument(err.str());
277
+ }
278
+
279
+ ck(cuInit(0));
280
+ int nGpu = 0;
281
+ ck(cuDeviceGetCount(&nGpu));
282
+ if (iGpu < 0 || iGpu >= nGpu)
283
+ {
284
+ std::ostringstream err;
285
+ err << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]";
286
+ throw std::invalid_argument(err.str());
287
+ }
288
+
289
+ CUcontext cuContext = NULL;
290
+ createCudaContext(&cuContext, iGpu, 0);
291
+
292
+ FFmpegDemuxer demuxer(szInFilePath);
293
+ NvDecoder dec(cuContext, true, FFmpeg2NvCodecId(demuxer.GetVideoCodec()));
294
+ int nWidth = 0, nHeight = 0, nFrameSize = 0;
295
+ int anSize[] = { 0, 3, 3, 4, 4, 8, 8, 3, 3 };
296
+ std::unique_ptr<uint8_t[]> pImage;
297
+
298
+ int nVideoBytes = 0, nFrameReturned = 0, nFrame = 0, iMatrix = 0;
299
+ uint8_t *pVideo = nullptr;
300
+ uint8_t *pFrame;
301
+
302
+ do {
303
+ demuxer.Demux(&pVideo, &nVideoBytes);
304
+ nFrameReturned = dec.Decode(pVideo, nVideoBytes);
305
+ if (!nFrame && nFrameReturned)
306
+ {
307
+ LOG(INFO) << dec.GetVideoInfo();
308
+ // Get output frame size from decoder
309
+ nWidth = dec.GetWidth(); nHeight = dec.GetHeight();
310
+ nFrameSize = eOutputFormat == native ? dec.GetFrameSize() : nWidth * nHeight * anSize[eOutputFormat];
311
+ std::unique_ptr<uint8_t[]> pTemp(new uint8_t[nFrameSize]);
312
+ pImage = std::move(pTemp);
313
+ cuMemAlloc(&pTmpImage, nWidth * nHeight * anSize[eOutputFormat]);
314
+ }
315
+
316
+ for (int i = 0; i < nFrameReturned; i++)
317
+ {
318
+ iMatrix = dec.GetVideoFormatInfo().video_signal_description.matrix_coefficients;
319
+ pFrame = dec.GetFrame();
320
+ if (dec.GetBitDepth() == 8) {
321
+ switch (eOutputFormat) {
322
+ case native:
323
+ GetImage((CUdeviceptr)pFrame, reinterpret_cast<uint8_t*>(pImage.get()), dec.GetWidth(), dec.GetHeight() + (dec.GetChromaHeight() * dec.GetNumChromaPlanes()));
324
+ break;
325
+ case bgrp:
326
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
327
+ YUV444ToColorPlanar<BGRA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
328
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
329
+ Nv12ToColorPlanar<BGRA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
330
+ else
331
+ Nv16ToColorPlanar<BGRA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
332
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), dec.GetWidth(), 3 * dec.GetHeight());
333
+ break;
334
+ case rgbp:
335
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
336
+ YUV444ToColorPlanar<RGBA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
337
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
338
+ Nv12ToColorPlanar<RGBA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
339
+ else
340
+ Nv16ToColorPlanar<RGBA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
341
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), dec.GetWidth(), 3 * dec.GetHeight());
342
+ break;
343
+ case bgra:
344
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
345
+ YUV444ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
346
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
347
+ Nv12ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
348
+ else
349
+ Nv16ToColor32<BGRA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
350
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 4 * dec.GetWidth(), dec.GetHeight());
351
+ break;
352
+ case rgba:
353
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
354
+ YUV444ToColor32<RGBA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
355
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
356
+ Nv12ToColor32<RGBA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
357
+ else
358
+ Nv16ToColor32<RGBA32>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
359
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 4 * dec.GetWidth(), dec.GetHeight());
360
+ break;
361
+ case rgb:
362
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
363
+ YUV444ToColor24<RGB24>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
364
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
365
+ Nv12ToColor24<RGB24>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
366
+ else
367
+ Nv16ToColor24<RGB24>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
368
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 3 * dec.GetWidth(), dec.GetHeight());
369
+ break;
370
+ case bgr:
371
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
372
+ YUV444ToColor24<BGR24>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
373
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
374
+ Nv12ToColor24<BGR24>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
375
+ else
376
+ Nv16ToColor24<BGR24>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
377
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 3 * dec.GetWidth(), dec.GetHeight());
378
+ break;
379
+ case bgra64:
380
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
381
+ YUV444ToColor64<BGRA64>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
382
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
383
+ Nv12ToColor64<BGRA64>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
384
+ else
385
+ Nv16ToColor64<BGRA64>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
386
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 8 * dec.GetWidth(), dec.GetHeight());
387
+ break;
388
+ case rgba64:
389
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444)
390
+ YUV444ToColor64<RGBA64>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
391
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_NV12)
392
+ Nv12ToColor64<RGBA64>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
393
+ else
394
+ Nv16ToColor64<RGBA64>(pFrame, dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
395
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 8 * dec.GetWidth(), dec.GetHeight());
396
+ break;
397
+ }
398
+ }
399
+ else
400
+ {
401
+ switch (eOutputFormat) {
402
+ case native:
403
+ GetImage((CUdeviceptr)pFrame, reinterpret_cast<uint8_t*>(pImage.get()), 2 * dec.GetWidth(), dec.GetHeight() + (dec.GetChromaHeight() * dec.GetNumChromaPlanes()));
404
+ break;
405
+ case bgrp:
406
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
407
+ YUV444P16ToColorPlanar<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
408
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
409
+ P016ToColorPlanar<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
410
+ else
411
+ P216ToColorPlanar<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
412
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), dec.GetWidth(), 3 * dec.GetHeight());
413
+ break;
414
+ case rgbp:
415
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
416
+ YUV444P16ToColorPlanar<RGBA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
417
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
418
+ P016ToColorPlanar<RGBA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
419
+ else
420
+ P216ToColorPlanar<RGBA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
421
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), dec.GetWidth(), 3 * dec.GetHeight());
422
+ break;
423
+ case bgra:
424
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
425
+ YUV444P16ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
426
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
427
+ P016ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
428
+ else
429
+ P216ToColor32<BGRA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
430
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 4 * dec.GetWidth(), dec.GetHeight());
431
+ break;
432
+ case rgba:
433
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
434
+ YUV444P16ToColor32<RGBA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
435
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
436
+ P016ToColor32<RGBA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
437
+ else
438
+ P216ToColor32<RGBA32>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 4 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
439
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 4 * dec.GetWidth(), dec.GetHeight());
440
+ break;
441
+ case rgb:
442
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
443
+ YUV444P16ToColor24<RGB24>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
444
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
445
+ P016ToColor24<RGB24>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
446
+ else
447
+ P216ToColor24<RGB24>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
448
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 3 * dec.GetWidth(), dec.GetHeight());
449
+ break;
450
+ case bgr:
451
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
452
+ YUV444P16ToColor24<BGR24>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
453
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
454
+ P016ToColor24<BGR24>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
455
+ else
456
+ P216ToColor24<BGR24>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 3 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
457
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 3 * dec.GetWidth(), dec.GetHeight());
458
+ break;
459
+ case bgra64:
460
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
461
+ YUV444P16ToColor64<BGRA64>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
462
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
463
+ P016ToColor64<BGRA64>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
464
+ else
465
+ P216ToColor64<BGRA64>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
466
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 8 * dec.GetWidth(), dec.GetHeight());
467
+ break;
468
+ case rgba64:
469
+ if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_YUV444_16Bit)
470
+ YUV444P16ToColor64<RGBA64>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
471
+ else if (dec.GetOutputFormat() == cudaVideoSurfaceFormat_P016)
472
+ P016ToColor64<RGBA64>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
473
+ else
474
+ P216ToColor64<RGBA64>(pFrame, 2 * dec.GetWidth(), (uint8_t*)pTmpImage, 8 * dec.GetWidth(), dec.GetWidth(), dec.GetHeight(), iMatrix);
475
+ GetImage(pTmpImage, reinterpret_cast<uint8_t*>(pImage.get()), 8 * dec.GetWidth(), dec.GetHeight());
476
+ break;
477
+ }
478
+ }
479
+
480
+ fpOut.write(reinterpret_cast<char*>(pImage.get()), nFrameSize);
481
+ }
482
+ nFrame += nFrameReturned;
483
+ } while (nVideoBytes);
484
+
485
+ if (pTmpImage) {
486
+ cuMemFree(pTmpImage);
487
+ }
488
+
489
+ std::cout << "Total frame decoded: " << nFrame << std::endl << "Saved in file " << szOutFilePath << std::endl;
490
+ fpOut.close();
491
+ }
492
+ catch (const std::exception& ex)
493
+ {
494
+ std::cout << ex.what();
495
+ exit(1);
496
+ }
497
+ return 0;
498
+ }
video_codec_sdk/Samples/AppDecode/AppDecImageProvider/CMakeLists.txt ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDecImageProvider)
13
+
14
+ set(APP_SOURCES
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecImageProvider.cpp
16
+ )
17
+
18
+ if(WIN32)
19
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
20
+ endif()
21
+
22
+ set(NV_DEC_SOURCES
23
+ ${NV_DEC_DIR}/NvDecoder.cpp
24
+ )
25
+
26
+ set(NV_ENC_CUDA_UTILS
27
+ ${NVCODEC_UTILS_DIR}/ColorSpace.cu
28
+ )
29
+
30
+ set(NV_DEC_HDRS
31
+ ${NV_DEC_DIR}/NvDecoder.h
32
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
33
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
34
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
35
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
36
+ ${NVCODEC_UTILS_DIR}/ColorSpace.h
37
+ ${NV_APPDEC_COMMON_DIR}/AppDecUtils.h
38
+ )
39
+
40
+ source_group( "headers" FILES ${NV_DEC_HDRS} )
41
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_ENC_CUDA_UTILS})
42
+
43
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
44
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
45
+ find_package(CUDAToolkit QUIET)
46
+ if(CUDAToolkit_FOUND)
47
+ # Map CUDAToolkit variables to legacy CUDA variable names
48
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
49
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
50
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
51
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
52
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
53
+ endif()
54
+ endif()
55
+ if(NOT CUDAToolkit_FOUND)
56
+ find_package(CUDA)
57
+ endif()
58
+
59
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
60
+
61
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
62
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
63
+ else()
64
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
65
+ endif()
66
+ # CUDA 11.7 and later is compiled with /MT option (staticaly linked with C runtime),
67
+ # since we are statically linking cudart_static.lib with the app,
68
+ # we need to make sure that all .obj files linked are compiled with /MT to avoid linker warning LNK4098
69
+ if (WIN32 AND CUDA_VERSION_MAJOR GREATER_EQUAL 11 AND CUDA_VERSION_MINOR GREATER_EQUAL 7)
70
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-Xcompiler /MT)
71
+ endif()
72
+ if ( CMAKE_COMPILER_IS_GNUCC )
73
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
74
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
75
+ endif()
76
+ endif()
77
+
78
+ # Use modern approach with CUDAToolkit when available, fallback to legacy FindCUDA
79
+ if(CUDAToolkit_FOUND AND CUDAToolkit_NVCC_EXECUTABLE)
80
+ set(CMAKE_CUDA_COMPILER ${CUDAToolkit_NVCC_EXECUTABLE})
81
+ enable_language(CUDA)
82
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
83
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_STANDARD 11)
84
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
85
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "75")
86
+ else()
87
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "50")
88
+ endif()
89
+ else()
90
+ cuda_add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
91
+ endif()
92
+
93
+ if (WIN32 AND CUDA_VERSION_MAJOR GREATER_EQUAL 11 AND CUDA_VERSION_MINOR GREATER_EQUAL 7)
94
+ target_compile_options(${PROJECT_NAME} PRIVATE "/MT")
95
+ endif()
96
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
97
+
98
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
99
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
100
+ ${NVCODEC_UTILS_DIR}
101
+ ${NV_CODEC_DIR}
102
+ ${NV_APPDEC_COMMON_DIR}
103
+ ${NV_FFMPEG_HDRS}
104
+ )
105
+
106
+ if(WIN32)
107
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
108
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
109
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
110
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
111
+
112
+ #copy dll's
113
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.dll")
114
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.lib")
115
+
116
+ endif ()
117
+
118
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
119
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB} )
120
+
121
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
122
+ if (MSVC)
123
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
124
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
125
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
126
+ #copy pdb's
127
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
128
+ endif()
129
+
video_codec_sdk/Samples/AppDecode/AppDecLowLatency/AppDecLowLatency.cpp ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecLowLatency.cpp
14
+ //! \brief Source file for AppDecLowLatency sample
15
+ //!
16
+ //! This sample application demonstrates low latency decoding feature.
17
+ //! This feature helps to get output frame as soon as it is decoded without any delay.
18
+ //! The feature will work for streams having I and P frames only.
19
+ //---------------------------------------------------------------------------
20
+
21
+ #include <vector>
22
+ #include <cuda.h>
23
+ #include "NvDecoder/NvDecoder.h"
24
+ #include "../Utils/NvCodecUtils.h"
25
+ #include "../Utils/FFmpegDemuxer.h"
26
+ #include "../Common/AppDecUtils.h"
27
+
28
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
29
+
30
+ int main(int argc, char *argv[])
31
+ {
32
+ char szInFilePath[256] = "", szOutFilePath[256] = "out.yuv";
33
+ int iGpu = 0;
34
+ bool bVerbose = false;
35
+ // With zero latency flag enabled, HandlePictureDisplay() callback happens immediately for
36
+ // the All-Intra/IPPP streams
37
+ bool force_zero_latency = false;
38
+ try
39
+ {
40
+ ParseCommandLine(argc, argv, szInFilePath, szOutFilePath, iGpu, &bVerbose, NULL, &force_zero_latency);
41
+ CheckInputFile(szInFilePath);
42
+
43
+ ck(cuInit(0));
44
+ int nGpu = 0;
45
+ ck(cuDeviceGetCount(&nGpu));
46
+ if (iGpu < 0 || iGpu >= nGpu)
47
+ {
48
+ std::ostringstream err;
49
+ err << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
50
+ throw std::invalid_argument(err.str());
51
+ }
52
+
53
+ CUcontext cuContext = NULL;
54
+ createCudaContext(&cuContext, iGpu, 0);
55
+
56
+ FFmpegDemuxer demuxer(szInFilePath);
57
+ // Here set bLowLatency=true in the constructor.
58
+ // Please don't use this flag except for low latency, it is harder to get 100% utilization of
59
+ // hardware decoder with this flag set.
60
+ NvDecoder dec(cuContext, false, FFmpeg2NvCodecId(demuxer.GetVideoCodec()), true, false, NULL, NULL, false, 0, 0, 1000, force_zero_latency);
61
+
62
+ int nFrame = 0;
63
+ uint8_t *pVideo = NULL;
64
+ int nVideoBytes = 0;
65
+ std::ofstream fpOut(szOutFilePath, std::ios::out | std::ios::binary);
66
+ if (!fpOut)
67
+ {
68
+ std::ostringstream err;
69
+ err << "Unable to open output file: " << szOutFilePath << std::endl;
70
+ throw std::invalid_argument(err.str());
71
+ }
72
+
73
+ int n = 0;
74
+ bool bOneInOneOut = true;
75
+ int nFrameReturned = 0;
76
+ int64_t timestamp = 0;
77
+ do {
78
+ demuxer.Demux(&pVideo, &nVideoBytes);
79
+ // Set flag CUVID_PKT_ENDOFPICTURE to signal that a complete packet has been sent to decode
80
+ nFrameReturned = dec.Decode(pVideo, nVideoBytes, CUVID_PKT_ENDOFPICTURE, n++);
81
+ if (!nFrame && nFrameReturned)
82
+ LOG(INFO) << dec.GetVideoInfo();
83
+
84
+ nFrame += nFrameReturned;
85
+ // For a stream without B-frames, "one in and one out" is expected, and nFrameReturned should be always 1 for each input packet
86
+ if (bVerbose)
87
+ {
88
+ std::cout << "Decode: nVideoBytes=" << nVideoBytes << ", nFrameReturned=" << nFrameReturned << ", total=" << nFrame << std::endl;
89
+ }
90
+ if (nVideoBytes && nFrameReturned != 1)
91
+ {
92
+ bOneInOneOut = false;
93
+ }
94
+ for (int i = 0; i < nFrameReturned; i++)
95
+ {
96
+ fpOut.write(reinterpret_cast<char*>(dec.GetFrame(&timestamp)), dec.GetFrameSize());
97
+ if (bVerbose)
98
+ {
99
+ std::cout << "Timestamp: " << timestamp << std::endl;
100
+ }
101
+ }
102
+ } while (nVideoBytes);
103
+
104
+ fpOut.close();
105
+ std::cout << "One packet in and one frame out: " << (bOneInOneOut ? "true" : "false") << std::endl;
106
+ }
107
+ catch(const std::exception& ex)
108
+ {
109
+ std::cout << ex.what();
110
+ exit(1);
111
+ }
112
+ return 0;
113
+ }
video_codec_sdk/Samples/AppDecode/AppDecLowLatency/CMakeLists.txt ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDecLowLatency)
13
+
14
+ set(APP_SOURCES
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecLowLatency.cpp
16
+ )
17
+
18
+ if(WIN32)
19
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
20
+ endif()
21
+
22
+ set(NV_DEC_SOURCES
23
+ ${NV_DEC_DIR}/NvDecoder.cpp
24
+ )
25
+
26
+ set(NV_DEC_HDRS
27
+ ${NV_DEC_DIR}/NvDecoder.h
28
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
29
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
30
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
31
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
32
+ ${NV_APPDEC_COMMON_DIR}/AppDecUtils.h
33
+ )
34
+
35
+ source_group( "headers" FILES ${NV_DEC_HDRS} )
36
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_ENC_CUDA_UTILS})
37
+
38
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
39
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
40
+ find_package(CUDAToolkit QUIET)
41
+ if(CUDAToolkit_FOUND)
42
+ # Map CUDAToolkit variables to legacy CUDA variable names
43
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
44
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
45
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
46
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
47
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
48
+ endif()
49
+ endif()
50
+ if(NOT CUDAToolkit_FOUND)
51
+ find_package(CUDA)
52
+ endif()
53
+
54
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
55
+
56
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
57
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
58
+ else()
59
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
60
+ endif()
61
+ if ( CMAKE_COMPILER_IS_GNUCC )
62
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
63
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
64
+ endif()
65
+ endif()
66
+
67
+ # Use modern approach with CUDAToolkit when available, fallback to legacy FindCUDA
68
+ if(CUDAToolkit_FOUND AND CUDAToolkit_NVCC_EXECUTABLE)
69
+ set(CMAKE_CUDA_COMPILER ${CUDAToolkit_NVCC_EXECUTABLE})
70
+ enable_language(CUDA)
71
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
72
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_STANDARD 11)
73
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
74
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "75")
75
+ else()
76
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "50")
77
+ endif()
78
+ else()
79
+ cuda_add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
80
+ endif()
81
+
82
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
83
+
84
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
85
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
86
+ ${NVCODEC_UTILS_DIR}
87
+ ${NV_CODEC_DIR}
88
+ ${NV_APPDEC_COMMON_DIR}
89
+ ${NV_FFMPEG_HDRS}
90
+ )
91
+
92
+ if(WIN32)
93
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
94
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
95
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
96
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
97
+ #copy dll's
98
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.dll")
99
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} FILES_MATCHING PATTERN "*.lib")
100
+ endif ()
101
+
102
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
103
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB})
104
+
105
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
106
+ if (MSVC)
107
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
108
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
109
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
110
+ #copy pdb's
111
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
112
+ endif()
video_codec_sdk/Samples/AppDecode/AppDecMem/AppDecMem.cpp ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecMem.cpp
14
+ //! \brief Source file for AppDecMem sample
15
+ //!
16
+ //! This sample application is similar to AppDec. It illustrates how to demux and decode media content from memory buffer.
17
+ //! It allocates AVIOContext explicitely and also defines method to read data packets from input file.
18
+ //! For simplicity, this application reads the input stream and stores it in a buffer before invoking the demuxer.
19
+ //---------------------------------------------------------------------------
20
+
21
+ #include <cuda.h>
22
+ #include "NvDecoder/NvDecoder.h"
23
+ #include "../Utils/NvCodecUtils.h"
24
+ #include "../Utils/FFmpegDemuxer.h"
25
+ #include "../Common/AppDecUtils.h"
26
+
27
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
28
+
29
+ class FileDataProvider : public FFmpegDemuxer::DataProvider {
30
+ public:
31
+ FileDataProvider(const char *szInFilePath) {
32
+ fpIn.open(szInFilePath, std::ifstream::in | std::ifstream::binary);
33
+ if (!fpIn)
34
+ {
35
+ std::cout << "Unable to open input file: " << szInFilePath << std::endl;
36
+ return;
37
+ }
38
+ }
39
+ ~FileDataProvider() {
40
+ fpIn.close();
41
+ }
42
+ // Fill in the buffer owned by the demuxer/decoder
43
+ int GetData(uint8_t *pBuf, int nBuf) {
44
+ if (fpIn.eof())
45
+ {
46
+ return AVERROR_EOF;
47
+ }
48
+
49
+ // We read a file for this example. You may get your data from network or somewhere else
50
+ return (int)fpIn.read(reinterpret_cast<char*>(pBuf), nBuf).gcount();
51
+ }
52
+
53
+ private:
54
+ std::ifstream fpIn;
55
+ };
56
+
57
+ int main(int argc, char *argv[])
58
+ {
59
+ char szInFilePath[256] = "", szOutFilePath[256] = "out.yuv";
60
+ int iGpu = 0;
61
+ try
62
+ {
63
+ ParseCommandLine(argc, argv, szInFilePath, szOutFilePath, iGpu);
64
+ CheckInputFile(szInFilePath);
65
+
66
+ ck(cuInit(0));
67
+ int nGpu = 0;
68
+ ck(cuDeviceGetCount(&nGpu));
69
+ if (iGpu < 0 || iGpu >= nGpu)
70
+ {
71
+ std::ostringstream err;
72
+ err << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
73
+ throw std::invalid_argument(err.str());
74
+ }
75
+
76
+ CUcontext cuContext = NULL;
77
+ createCudaContext(&cuContext, iGpu, 0);
78
+
79
+ FileDataProvider dp(szInFilePath);
80
+ // Instead of passing in a media file path, here we pass in a DataProvider, which reads from the file.
81
+ // Note that the data is passed into the demuxer chunk-by-chunk sequentially. If the meta data is at the end of the file
82
+ // (as for MP4) and the buffer isn't large enough to hold the whole file, the file may never get demuxed.
83
+ // Allocated buffer size is 32 MB. Please increase buffer size (avioc_buffer_size) in CreateFormatContext(DataProvider *pDataProvider)
84
+ // if this limitation is faced.
85
+ FFmpegDemuxer demuxer(&dp);
86
+ NvDecoder dec(cuContext, false, FFmpeg2NvCodecId(demuxer.GetVideoCodec()));
87
+
88
+ int nFrame = 0;
89
+ uint8_t *pVideo = NULL;
90
+ int nVideoBytes = 0;
91
+ uint8_t *pFrame;
92
+ int nFrameReturned = 0;
93
+ std::ofstream fpOut(szOutFilePath, std::ios::out | std::ios::binary);
94
+ if (!fpOut)
95
+ {
96
+ std::ostringstream err;
97
+ err << "Unable to open output file: " << szOutFilePath << std::endl;
98
+ throw std::invalid_argument(err.str());
99
+ }
100
+ do
101
+ {
102
+ demuxer.Demux(&pVideo, &nVideoBytes);
103
+ nFrameReturned = dec.Decode(pVideo, nVideoBytes);
104
+ if (!nFrame && nFrameReturned)
105
+ LOG(INFO) << dec.GetVideoInfo();
106
+
107
+ nFrame += nFrameReturned;
108
+ for (int i = 0; i < nFrameReturned; i++) {
109
+ pFrame = dec.GetFrame();
110
+ fpOut.write(reinterpret_cast<char*>(pFrame), dec.GetFrameSize());
111
+ }
112
+ } while (nVideoBytes);
113
+ fpOut.close();
114
+ const char *aszDecodeOutFormat[] = { "NV12", "P016", "YUV444", "YUV444P16", "NV16", "P216"};
115
+ std::cout << "Total frame decoded: " << nFrame << std::endl << "Saved in file " << szOutFilePath << " in format " << aszDecodeOutFormat[dec.GetOutputFormat()] << std::endl;
116
+ }
117
+ catch (const std::exception& ex)
118
+ {
119
+ std::cout << ex.what();
120
+ exit(1);
121
+ }
122
+ return 0;
123
+ }
video_codec_sdk/Samples/AppDecode/AppDecMem/CMakeLists.txt ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDecMem)
13
+
14
+ set(APP_SOURCES
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecMem.cpp
16
+ )
17
+
18
+ if(WIN32)
19
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
20
+ endif()
21
+
22
+ set(NV_DEC_SOURCES
23
+ ${NV_DEC_DIR}/NvDecoder.cpp
24
+ )
25
+
26
+ set(NV_DEC_HDRS
27
+ ${NV_DEC_DIR}/NvDecoder.h
28
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
29
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
30
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
31
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
32
+ ${NV_APPDEC_COMMON_DIR}/AppDecUtils.h
33
+ )
34
+
35
+ source_group( "headers" FILES ${NV_DEC_HDRS} )
36
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_ENC_CUDA_UTILS})
37
+
38
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
39
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
40
+ find_package(CUDAToolkit QUIET)
41
+ if(CUDAToolkit_FOUND)
42
+ # Map CUDAToolkit variables to legacy CUDA variable names
43
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
44
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
45
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
46
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
47
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
48
+ endif()
49
+ endif()
50
+ if(NOT CUDAToolkit_FOUND)
51
+ find_package(CUDA)
52
+ endif()
53
+
54
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
55
+
56
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
57
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
58
+ else()
59
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
60
+ endif()
61
+ if ( CMAKE_COMPILER_IS_GNUCC )
62
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
63
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
64
+ endif()
65
+ endif()
66
+
67
+ # Use modern approach with CUDAToolkit when available, fallback to legacy FindCUDA
68
+ if(CUDAToolkit_FOUND AND CUDAToolkit_NVCC_EXECUTABLE)
69
+ set(CMAKE_CUDA_COMPILER ${CUDAToolkit_NVCC_EXECUTABLE})
70
+ enable_language(CUDA)
71
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
72
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_STANDARD 11)
73
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
74
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "75")
75
+ else()
76
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "50")
77
+ endif()
78
+ else()
79
+ cuda_add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
80
+ endif()
81
+
82
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
83
+
84
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
85
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
86
+ ${NVCODEC_UTILS_DIR}
87
+ ${NV_CODEC_DIR}
88
+ ${NV_APPDEC_COMMON_DIR}
89
+ ${NV_FFMPEG_HDRS}
90
+ )
91
+
92
+ if(WIN32)
93
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
94
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
95
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
96
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
97
+ #copy dll's
98
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.dll")
99
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.lib")
100
+ endif()
101
+
102
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
103
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB})
104
+
105
+
106
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
107
+ if (MSVC)
108
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
109
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
110
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
111
+ #copy pdb's
112
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
113
+ endif()
114
+
video_codec_sdk/Samples/AppDecode/AppDecMultiFiles/AppDecMultiFiles.cpp ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecMultiFiles.cpp
14
+ //! \brief Source file for AppDecMultiFiles sample
15
+ //!
16
+ //! This sample application illustrates the decoding of multiple files with/without using the decoder Reconfigure API.
17
+ //! It also displays the time taken for decoder creation and destruction.
18
+ //! Multiple files are specified using '-filelist' commandline option.
19
+ //! The app will decode files in a sequential manner.
20
+ //---------------------------------------------------------------------------
21
+
22
+ #include <iostream>
23
+ #include <algorithm>
24
+ #include <thread>
25
+ #include <cuda.h>
26
+ #include <deque>
27
+ #include <fstream>
28
+ #include <sstream>
29
+ #include <string>
30
+ #include "NvDecoder/NvDecoder.h"
31
+ #include "../Utils/NvCodecUtils.h"
32
+ #include "../Utils/FFmpegDemuxer.h"
33
+ #include "../Common/AppDecUtils.h"
34
+
35
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
36
+
37
+ typedef struct
38
+ {
39
+ char inFile[256];
40
+ char outFile[256];
41
+ Dim resizeDim;
42
+ Rect cropRect;
43
+ bool outplanar;
44
+ } FILEINFO;
45
+
46
+ void ConvertToPlanar(uint8_t *pHostFrame, int nWidth, int nHeight, int nBitDepth, uint8_t nChromaFormat) {
47
+ if (nBitDepth == 8) {
48
+ YuvConverter<uint8_t> converter8(nWidth, nHeight, nChromaFormat);
49
+ converter8.UVInterleavedToPlanar(pHostFrame);
50
+ } else {
51
+ YuvConverter<uint16_t> converter16(nWidth, nHeight, nChromaFormat);
52
+ converter16.UVInterleavedToPlanar((uint16_t *)pHostFrame);
53
+ }
54
+ }
55
+
56
+ void getMaxWidthandMaxHeight(int &maxWidth, int &maxHeight, cudaVideoCodec aeCodec, int anBitDepthMinus8)
57
+ {
58
+ CUVIDDECODECAPS decodeCaps = {};
59
+ decodeCaps.eCodecType = aeCodec;
60
+ decodeCaps.eChromaFormat = cudaVideoChromaFormat_420;
61
+ decodeCaps.nBitDepthMinus8 = anBitDepthMinus8;
62
+
63
+ cuvidGetDecoderCaps(&decodeCaps);
64
+
65
+ maxWidth = decodeCaps.nMaxWidth;
66
+ maxHeight = decodeCaps.nMaxHeight;
67
+
68
+ }
69
+
70
+ /**
71
+ * @brief Function to decode media file and write raw frames into another file.
72
+ * @param cuContext - Handle to CUDA context
73
+ * @param pDec - Handle to NvDecoder
74
+ * @param fileData - FILEINFO variable which holds various file details
75
+ * @param useReconfigure - Flag to enable/disable reconfigure api for decoding multiple files
76
+ * @param maxWidth - The maximum width that the decoder session can be reconfigured to.
77
+ * The widths of all the input streams in the files specified by the -filelist option,
78
+ * must not exceed this value. This value defaults to 0.
79
+ * @param maxHeight - The maximum height that the decoder session can be reconfigured to.
80
+ * The heights of all the input streams in the files specified by the -filelist option,
81
+ * must not exceed this value. This value defaults to 0.
82
+ */
83
+ void DecodeMediaFile(CUcontext cuContext, NvDecoder **pDec, FILEINFO fileData, int useReconfigure, int maxWidth = 0, int maxHeight = 0)
84
+ {
85
+ std::ofstream fpOut(fileData.outFile, std::ios::out | std::ios::binary);
86
+ if (!fpOut)
87
+ {
88
+ std::ostringstream err;
89
+ err << "Unable to open output file: " << fileData.outFile << std::endl;
90
+ throw std::invalid_argument(err.str());
91
+ }
92
+
93
+ FFmpegDemuxer demuxer(fileData.inFile);
94
+ NvDecoder *dec = *pDec;
95
+
96
+ if (useReconfigure)
97
+ {
98
+ if (dec == NULL)
99
+ {
100
+ if ((!maxWidth) || (!maxHeight))
101
+ {
102
+ // Get MaxWidth/MaxHeight for particular codec and bitdepth if not set in commandline
103
+ getMaxWidthandMaxHeight(maxWidth, maxHeight, FFmpeg2NvCodecId(demuxer.GetVideoCodec()), demuxer.GetBitDepth() - 8);
104
+ }
105
+
106
+ dec = new NvDecoder(cuContext, false, FFmpeg2NvCodecId(demuxer.GetVideoCodec()),
107
+ false, false, &fileData.cropRect, &fileData.resizeDim, false, maxWidth, maxHeight);
108
+ *pDec = dec;
109
+ }
110
+ else
111
+ {
112
+ dec->setReconfigParams(&fileData.cropRect, &fileData.resizeDim);
113
+ }
114
+
115
+ }
116
+ else
117
+ {
118
+ dec = new NvDecoder(cuContext, false, FFmpeg2NvCodecId(demuxer.GetVideoCodec()),
119
+ false, false, &fileData.cropRect, &fileData.resizeDim);
120
+ }
121
+
122
+ int nVideoBytes = 0, nFrameReturned = 0, nFrame = 0;
123
+ uint8_t *pVideo = NULL, *pFrame;
124
+ bool bDecodeOutSemiPlanar = false;
125
+ do {
126
+ demuxer.Demux(&pVideo, &nVideoBytes);
127
+ nFrameReturned = dec->Decode(pVideo, nVideoBytes);
128
+ if (!nFrame && nFrameReturned)
129
+ LOG(INFO) << dec->GetVideoInfo();
130
+
131
+ bDecodeOutSemiPlanar = (dec->GetOutputFormat() == cudaVideoSurfaceFormat_NV12) || (dec->GetOutputFormat() == cudaVideoSurfaceFormat_P016)
132
+ || (dec->GetOutputFormat() == cudaVideoSurfaceFormat_NV16) || (dec->GetOutputFormat() == cudaVideoSurfaceFormat_P216);
133
+ for (int i = 0; i < nFrameReturned; i++) {
134
+ pFrame = dec->GetFrame();
135
+ if (fileData.outplanar && bDecodeOutSemiPlanar) {
136
+ ConvertToPlanar(pFrame, dec->GetWidth(), dec->GetHeight(), dec->GetBitDepth(), dec->GetOutputChromaFormat());
137
+ }
138
+ fpOut.write(reinterpret_cast<char*>(pFrame), dec->GetFrameSize());
139
+ }
140
+ nFrame += nFrameReturned;
141
+ } while (nVideoBytes);
142
+
143
+ std::vector<std::string> aszDecodeOutFormat = { "NV12", "P016", "YUV444", "YUV444P16", "NV16", "P216" };
144
+ if (fileData.outplanar) {
145
+ aszDecodeOutFormat[0] = "iyuv"; aszDecodeOutFormat[1] = "yuv420p16";
146
+ aszDecodeOutFormat[4] = "yuv422p"; aszDecodeOutFormat[5] = "yuv422p16";
147
+ }
148
+ std::cout << "Total frame decoded: " << nFrame << std::endl
149
+ << "Saved in file " << fileData.outFile << " in "
150
+ << aszDecodeOutFormat[dec->GetOutputFormat()]
151
+ << " format" << std::endl;
152
+ if (!useReconfigure)
153
+ {
154
+ delete dec;
155
+ dec = NULL;
156
+ }
157
+ fpOut.close();
158
+ }
159
+
160
+ static void ShowBriefHelp()
161
+ {
162
+ std::ostringstream oss;
163
+ oss << "NVIDIA Video Decoder Multi-File Sample Application\n";
164
+ oss << "============================================\n\n";
165
+
166
+ oss << "Usage: AppDecMultiFiles -filelist <list.txt> [options]\n\n";
167
+
168
+ // Brief table of core arguments
169
+ oss << "Common Arguments:\n";
170
+ oss << std::left << std::setw(25) << "Argument"
171
+ << std::setw(12) << "Type"
172
+ << "Default Value\n";
173
+ oss << std::string(50, '-') << "\n";
174
+
175
+ oss << std::left << std::setw(25) << "-filelist <path>"
176
+ << std::setw(12) << "Required"
177
+ << "N/A\n";
178
+
179
+ oss << std::left << std::setw(25) << "-gpu <n>"
180
+ << std::setw(12) << "Optional"
181
+ << "0\n";
182
+
183
+ oss << std::left << std::setw(25) << "-usereconfigure <n>"
184
+ << std::setw(12) << "Optional"
185
+ << "1\n";
186
+
187
+ oss << std::left << std::setw(25) << "-maxwidth <n>"
188
+ << std::setw(12) << "Optional"
189
+ << "0\n";
190
+
191
+ oss << std::left << std::setw(25) << "-maxheight <n>"
192
+ << std::setw(12) << "Optional"
193
+ << "0\n";
194
+
195
+ oss << "\nFor detailed help, use -A/--advanced-options\n";
196
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
197
+ std::cout << oss.str();
198
+ exit(0);
199
+ }
200
+
201
+ static void ShowDetailedHelp()
202
+ {
203
+ std::ostringstream oss;
204
+ oss << "NVIDIA Video Decoder Multi-File Sample Application - Detailed Help\n";
205
+ oss << "========================================================\n\n";
206
+
207
+ oss << "Usage: AppDecMultiFiles -filelist <list.txt> [options]\n\n";
208
+
209
+ // Full table of all arguments
210
+ oss << "All Arguments:\n";
211
+ oss << std::left << std::setw(25) << "Argument"
212
+ << std::setw(12) << "Type"
213
+ << std::setw(20) << "Default Value"
214
+ << "Usage\n";
215
+ oss << std::string(80, '-') << "\n";
216
+
217
+ // Required arguments
218
+ oss << std::left << std::setw(25) << "-filelist <path>"
219
+ << std::setw(12) << "Required"
220
+ << std::setw(20) << "N/A"
221
+ << "-filelist list.txt\n";
222
+
223
+ // Optional arguments
224
+ oss << std::left << std::setw(25) << "-gpu <n>"
225
+ << std::setw(12) << "Optional"
226
+ << std::setw(20) << "0"
227
+ << "-gpu 1\n";
228
+
229
+ oss << std::left << std::setw(25) << "-usereconfigure <n>"
230
+ << std::setw(12) << "Optional"
231
+ << std::setw(20) << "1"
232
+ << "-usereconfigure 0\n";
233
+
234
+ oss << std::left << std::setw(25) << "-maxwidth <n>"
235
+ << std::setw(12) << "Optional"
236
+ << std::setw(20) << "0"
237
+ << "-maxwidth 1920\n";
238
+
239
+ oss << std::left << std::setw(25) << "-maxheight <n>"
240
+ << std::setw(12) << "Optional"
241
+ << std::setw(20) << "0"
242
+ << "-maxheight 1080\n";
243
+
244
+ // Detailed descriptions
245
+ oss << "\nDetailed Descriptions:\n";
246
+ oss << "-------------------\n";
247
+ oss << std::left << std::setw(25) << "-filelist" << ": Input file path\n";
248
+ oss << std::left << std::setw(25) << "-gpu" << ": Ordinal of GPU to use\n";
249
+ oss << std::left << std::setw(25) << "-usereconfigure" << ": Use decoder reconfigure API\n";
250
+ oss << std::left << std::setw(25) << "-maxwidth" << ": Maximum width for reconfigure\n";
251
+ oss << std::left << std::setw(25) << "-maxheight" << ": Maximum height for reconfigure\n";
252
+ oss << std::left << std::setw(25) << "-h/--help" << ": Print usage information for common commandline options\n";
253
+ oss << std::left << std::setw(25) << "-A/--advanced-options" << ": Print usage information for common and advanced commandline options\n";
254
+ oss << std::left << std::setw(25) << "-dc/--decode-caps" << ": Print decode capabilities of GPU\n";
255
+
256
+ // File list format
257
+ oss << "\nFile List Format:\n";
258
+ oss << "-----------------\n";
259
+ oss << "infile input1.h264 (Input file path)\n";
260
+ oss << "outfile out1.yuv (Output file path)\n";
261
+ oss << "outplanar 1 (Convert output to planar format)\n";
262
+ oss << "resize WxH (Resize to dimension Width x Height)\n";
263
+ oss << "crop l,t,r,b (Crop rectangle in left,top,right,bottom)\n";
264
+
265
+ // Important notes
266
+ oss << "\nNotes:\n";
267
+ oss << "------\n";
268
+ oss << "* Reconfigure API is enabled by default for decoding multiple files\n";
269
+ oss << "* Width and height in resize must be even numbers\n";
270
+ oss << "* Crop rectangle dimensions must be even numbers\n";
271
+ oss << "* When using reconfigure, all input files must be same codec\n";
272
+ oss << std::endl;
273
+
274
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
275
+ std::cout << oss.str();
276
+ exit(0);
277
+ }
278
+
279
+ static void ShowHelpAndExit(const char *szBadOption = NULL)
280
+ {
281
+ if (szBadOption)
282
+ {
283
+ std::ostringstream oss;
284
+ oss << "Error parsing \"" << szBadOption << "\"\n";
285
+ oss << "Use -h/--help for basic usage or -A/--advanced-options for detailed information\n";
286
+ throw std::invalid_argument(oss.str());
287
+ }
288
+ }
289
+
290
+ void ParseCommandLine(std::deque<FILEINFO> *multiFileData, int &maxWidth, int &maxHeight, int &iGpu, bool &useReconfigure, int argc, char *argv[])
291
+ {
292
+ FILEINFO fileData;
293
+ if (argc == 1) {
294
+ std::cout << "No Arguments provided! Please refer to the following for options:" << "\"\n";
295
+ ShowBriefHelp();
296
+ }
297
+
298
+ char filelistPath[256];
299
+
300
+ for (int i = 1; i < argc; i++) {
301
+ if (!_stricmp(argv[i], "-h") || !_stricmp(argv[i], "--help")) {
302
+ ShowBriefHelp();
303
+ }
304
+ if (!_stricmp(argv[i], "-A") || !_stricmp(argv[i], "--advanced-options")) {
305
+ ShowDetailedHelp();
306
+ }
307
+ if (!_stricmp(argv[i], "-dc") || !_stricmp(argv[i], "--decode-caps")) {
308
+ ShowDecoderCapability();
309
+ }
310
+ if (!_stricmp(argv[i], "-filelist")) {
311
+ if (++i == argc) {
312
+ ShowHelpAndExit("-filelist");
313
+ }
314
+ sprintf(filelistPath, "%s", argv[i]);
315
+ continue;
316
+ }
317
+ if (!_stricmp(argv[i], "-gpu")) {
318
+ if (++i == argc) {
319
+ ShowHelpAndExit("-gpu");
320
+ }
321
+ iGpu = atoi(argv[i]);
322
+ continue;
323
+ }
324
+ if (!_stricmp(argv[i], "-usereconfigure")) {
325
+ if (++i == argc) {
326
+ ShowHelpAndExit("-usereconfigure");
327
+ }
328
+ useReconfigure = atoi(argv[i]) ? true : false;
329
+ continue;
330
+ }
331
+ if (!_stricmp(argv[i], "-maxwidth")) {
332
+ if (++i == argc) {
333
+ ShowHelpAndExit("-maxwidth");
334
+ }
335
+ maxWidth = atoi(argv[i]);
336
+ continue;
337
+ }
338
+ if (!_stricmp(argv[i], "-maxheight")) {
339
+ if (++i == argc) {
340
+ ShowHelpAndExit("-maxheight");
341
+ }
342
+ maxHeight = atoi(argv[i]);
343
+ continue;
344
+ }
345
+ ShowHelpAndExit(argv[i]);
346
+ }
347
+
348
+ // Parse the input filelist
349
+ std::ifstream filestream(filelistPath);
350
+ std::string line;
351
+ char* str;
352
+ char param[256];
353
+ char value[256];
354
+ int fileIdx = 0;
355
+ while (std::getline(filestream, line))
356
+ {
357
+ str = (char *)line.c_str();
358
+ sscanf(str,"%s %s", param, value);
359
+ if (0 == _stricmp(param, "infile"))
360
+ {
361
+ if (fileIdx > 0)
362
+ {
363
+ multiFileData->push_back(fileData);
364
+ }
365
+ sprintf(fileData.inFile, "%s", value);
366
+ fileIdx++;
367
+ fileData.resizeDim = { 0, 0 };
368
+ fileData.cropRect = { 0, 0, 0, 0 };
369
+ fileData.outplanar = 0;
370
+ }
371
+ else if (0 == _stricmp(param, "outfile"))
372
+ {
373
+ sprintf(fileData.outFile, "%s", value);
374
+ }
375
+ else if (0 == _stricmp(param, "outplanar"))
376
+ {
377
+ fileData.outplanar = atoi(value) ? true : false;
378
+ }
379
+ else if (0 == _stricmp(param, "resize"))
380
+ {
381
+ sscanf(value, "%dx%d", &fileData.resizeDim.w, &fileData.resizeDim.h);
382
+ if (fileData.resizeDim.w % 2 == 1 || fileData.resizeDim.h % 2 == 1) {
383
+ std::cout << "Resizing rect must have width and height of even numbers" << std::endl;
384
+ exit(1);
385
+ }
386
+ }
387
+ else if (0 == _stricmp(param, "crop"))
388
+ {
389
+ sscanf(value, "%d,%d,%d,%d", &fileData.cropRect.l, &fileData.cropRect.t, &fileData.cropRect.r, &fileData.cropRect.b);
390
+ if ((fileData.cropRect.r - fileData.cropRect.l) % 2 == 1 || (fileData.cropRect.b - fileData.cropRect.t) % 2 == 1) {
391
+ std::cout << "Cropping rect must have width and height of even numbers" << std::endl;
392
+ exit(1);
393
+ }
394
+ }
395
+ }
396
+ if (fileIdx > 0)
397
+ {
398
+ multiFileData->push_back(fileData);
399
+ }
400
+ }
401
+
402
+ int main(int argc, char **argv)
403
+ {
404
+ std::deque<FILEINFO> multiFileData;
405
+
406
+ int iGpu = 0;
407
+ int maxWidth = 0, maxHeight = 0;
408
+ bool useReconfigure = true;
409
+ FILEINFO fileData;
410
+ try
411
+ {
412
+ ParseCommandLine(&multiFileData, maxWidth, maxHeight, iGpu, useReconfigure, argc, argv);
413
+
414
+ ck(cuInit(0));
415
+ int nGpu = 0;
416
+ ck(cuDeviceGetCount(&nGpu));
417
+ if (iGpu < 0 || iGpu >= nGpu) {
418
+ std::cout << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
419
+ return 1;
420
+ }
421
+
422
+ CUcontext cuContext = NULL;
423
+ createCudaContext(&cuContext, iGpu, 0);
424
+
425
+ std::cout << "Decode with demuxing." << std::endl;
426
+ NvDecoder* dec = NULL;
427
+
428
+ while (!multiFileData.empty())
429
+ {
430
+ fileData = multiFileData.front();
431
+ multiFileData.pop_front();
432
+
433
+ CheckInputFile(fileData.inFile);
434
+
435
+ DecodeMediaFile(cuContext, &dec, fileData, useReconfigure, maxWidth, maxHeight);
436
+
437
+ }
438
+
439
+ if (dec != NULL)
440
+ {
441
+ delete dec;
442
+ dec = NULL;
443
+ }
444
+ }
445
+ catch (const std::exception& ex)
446
+ {
447
+ std::cout << ex.what();
448
+ exit(1);
449
+ }
450
+
451
+ return 0;
452
+ }
video_codec_sdk/Samples/AppDecode/AppDecMultiFiles/CMakeLists.txt ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDecMultiFiles)
13
+
14
+ set(APP_SOURCES
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecMultiFiles.cpp
16
+ )
17
+
18
+ if(WIN32)
19
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
20
+ endif()
21
+
22
+ set(NV_DEC_SOURCES
23
+ ${NV_DEC_DIR}/NvDecoder.cpp
24
+ )
25
+
26
+ set(NV_DEC_COMMON_HDR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../Common)
27
+
28
+ set(NV_DEC_HDRS
29
+ ${NV_DEC_DIR}/NvDecoder.h
30
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
31
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
32
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
33
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
34
+ ${NV_DEC_COMMON_HDR_DIR}/AppDecUtils.h
35
+ )
36
+
37
+ source_group( "headers" FILES ${NV_DEC_HDRS} )
38
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_ENC_CUDA_UTILS})
39
+
40
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
41
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
42
+ find_package(CUDAToolkit QUIET)
43
+ if(CUDAToolkit_FOUND)
44
+ # Map CUDAToolkit variables to legacy CUDA variable names
45
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
46
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
47
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
48
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
49
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
50
+ endif()
51
+ endif()
52
+ if(NOT CUDAToolkit_FOUND)
53
+ find_package(CUDA)
54
+ endif()
55
+
56
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
57
+
58
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
59
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
60
+ else()
61
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
62
+ endif()
63
+ if ( CMAKE_COMPILER_IS_GNUCC )
64
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
65
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
66
+ endif()
67
+ endif()
68
+
69
+ # Use modern approach with CUDAToolkit when available, fallback to legacy FindCUDA
70
+ if(CUDAToolkit_FOUND AND CUDAToolkit_NVCC_EXECUTABLE)
71
+ set(CMAKE_CUDA_COMPILER ${CUDAToolkit_NVCC_EXECUTABLE})
72
+ enable_language(CUDA)
73
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
74
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_STANDARD 11)
75
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
76
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "75")
77
+ else()
78
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "50")
79
+ endif()
80
+ else()
81
+ cuda_add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
82
+ endif()
83
+
84
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
85
+
86
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
87
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
88
+ ${NVCODEC_UTILS_DIR}
89
+ ${NV_CODEC_DIR}
90
+ ${NV_APPDEC_COMMON_DIR}
91
+ ${NV_FFMPEG_HDRS}
92
+ )
93
+
94
+ if(WIN32)
95
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
96
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
97
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
98
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
99
+ #copy dll's
100
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.dll")
101
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.lib")
102
+ endif()
103
+
104
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
105
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB})
106
+
107
+
108
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
109
+ if (MSVC)
110
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
111
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
112
+
113
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
114
+
115
+ #copy pdb's
116
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
117
+ endif()
118
+
video_codec_sdk/Samples/AppDecode/AppDecMultiInput/AppDecMultiInput.cpp ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecMultiInput.cpp
14
+ //! \brief Source file for AppDecMultiInput sample
15
+ //!
16
+ //! This sample application demonstrates how to decode multiple raw video files and
17
+ //! post-process them with CUDA kernels on different CUDA streams.
18
+ //! This sample applies Ripple effect as a part of post processing.
19
+ //! The effect consists of ripples expanding across the surface of decoded frames
20
+ //---------------------------------------------------------------------------
21
+
22
+ #include <iostream>
23
+ #include <algorithm>
24
+ #include <thread>
25
+ #include <memory>
26
+ #include <cuda.h>
27
+ #include <cuda_runtime.h>
28
+ #include <cuda_profiler_api.h>
29
+ #include "NvDecoder/NvDecoder.h"
30
+ #include "../Utils/NvCodecUtils.h"
31
+ #include "../Utils/FFmpegDemuxer.h"
32
+ #include "../Common/AppDecUtils.h"
33
+
34
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
35
+
36
+ void LaunchRipple(cudaStream_t stream, uint8_t *dpImage, int nWidth, int nHeight, int xCenter, int yCenter, int iTime);
37
+ void LaunchOverlayRipple(cudaStream_t stream, uint8_t *dpNv12, uint8_t *dpRipple, int nWidth, int nHeight);
38
+ void LaunchMerge(cudaStream_t stream, uint8_t *dpNv12Merged, uint8_t **pdpNv12, int nImage, int nWidth, int nHeight);
39
+
40
+ /**
41
+ * @brief Function to decode frame from media file and post process it using CUDA kernels.
42
+ * @param pDec - Pointer to NvDecoder object which is already initialized
43
+ * @param szInFilePath - Path to file to be decoded
44
+ * @param nWidth - Width of the decoded video
45
+ * @param nHeight - Height of the decoded video
46
+ * @param apFrameBuffer - Pointer to decoded frame
47
+ * @param nFrameBuffer - Capacity of decoder's own circular queue
48
+ * @param piEnd - Pointer to hold value of queue's end
49
+ * @param piHead - Pointer to hold value of queue's start
50
+ * @param pbStop - Boolean to mark the end of post processing by this function
51
+ * @param stream - Pointer to CUDA stream
52
+ * @param xCenter - X co-ordinate of ripple center
53
+ * @param yCenter - Y co-ordinate of ripple center
54
+ * @param ex - Stores exception value in case exception is raised
55
+ *
56
+ */
57
+ void DecProc(NvDecoder *pDec, const char *szInFilePath, int nWidth, int nHeight, uint8_t **apFrameBuffer,
58
+ int nFrameBuffer, int *piEnd, int *piHead, bool *pbStop, cudaStream_t stream,
59
+ int xCenter, int yCenter, std::exception_ptr &ex)
60
+ {
61
+ try
62
+ {
63
+ FFmpegDemuxer demuxer(szInFilePath);
64
+ ck(cuCtxSetCurrent(pDec->GetContext()));
65
+ uint8_t *dpRippleImage;
66
+ ck(cudaMalloc(&dpRippleImage, (size_t)nWidth * nHeight));
67
+ int iTime = 0;
68
+ // Render a ripple image on dpRippleImage
69
+ LaunchRipple(stream, dpRippleImage, nWidth, nHeight, xCenter, yCenter, iTime++);
70
+ int nVideoBytes = 0, nFrameReturned = 0, nFrame = 0;
71
+ uint8_t *pVideo = NULL, *pFrame;
72
+
73
+ do
74
+ {
75
+ demuxer.Demux(&pVideo, &nVideoBytes);
76
+ nFrameReturned = pDec->Decode(pVideo, nVideoBytes);
77
+
78
+ for (int i = 0; i < nFrameReturned; i++) {
79
+ pFrame = pDec->GetLockedFrame();
80
+ // For each decoded frame
81
+ while (*piHead == *piEnd) {
82
+ // Queue is full
83
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
84
+ }
85
+ // Frame buffer is locked, so no data copy is needed here
86
+ apFrameBuffer[*piHead % nFrameBuffer] = pFrame;
87
+ // Overlay dpRippleImage onto the frame buffer
88
+ LaunchOverlayRipple(stream, apFrameBuffer[*piHead % nFrameBuffer], dpRippleImage, nWidth, nHeight);
89
+ // Make sure CUDA kernel is finished before marking the current position as ready
90
+ ck(cudaStreamSynchronize(stream));
91
+ // Mark as ready
92
+ ++*piHead;
93
+ LaunchRipple(stream, dpRippleImage, nWidth, nHeight, xCenter, yCenter, iTime++);
94
+ }
95
+ } while (nVideoBytes);
96
+
97
+ ck(cudaFree(dpRippleImage));
98
+ *pbStop = true;
99
+ }
100
+ catch (std::exception&)
101
+ {
102
+ ex = std::current_exception();
103
+ }
104
+ }
105
+
106
+ int main(int argc, char *argv[])
107
+ {
108
+ char szInFilePath[256] = "", szOutFilePath[256] = "out.nv12";
109
+ int iGpu = 0;
110
+ std::vector<std::exception_ptr> vExceptionPtrs;
111
+ try
112
+ {
113
+ ParseCommandLine(argc, argv, szInFilePath, szOutFilePath, iGpu);
114
+ CheckInputFile(szInFilePath);
115
+
116
+ ck(cuInit(0));
117
+ int nGpu = 0;
118
+ ck(cuDeviceGetCount(&nGpu));
119
+ if (iGpu < 0 || iGpu >= nGpu)
120
+ {
121
+ std::ostringstream err;
122
+ err << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
123
+ throw std::invalid_argument(err.str());
124
+
125
+ }
126
+
127
+ CUcontext cuContext = NULL;
128
+ createCudaContext(&cuContext, iGpu, 0);
129
+
130
+ FFmpegDemuxer demuxer(szInFilePath);
131
+ // 4:2:0 output need 2 byte width alignment
132
+ int nWidth = (demuxer.GetWidth() + 1) & ~1, nHeight = demuxer.GetHeight(), nByte = nWidth * nHeight * 3 / 2;
133
+ Dim decodeDim = { nWidth , nHeight };
134
+ // Number of decoders
135
+ const int n = 4;
136
+ // Every decoder has its own round queue
137
+ uint8_t *aapFrameBuffer[n][8];
138
+ // Queue capacity
139
+ const int nFrameBuffer = sizeof(aapFrameBuffer[0]) / sizeof(aapFrameBuffer[0][0]);
140
+ int iEnd = nFrameBuffer;
141
+ bool abStop[n] = {};
142
+ int aiHead[n] = {};
143
+ std::vector <NvThread> vThreads;
144
+ std::vector <std::unique_ptr<NvDecoder>> vDecoders;
145
+ // Coordinate of the ripple center for each decoder
146
+ int axCenter[] = { nWidth / 4, nWidth / 4 * 3, nWidth / 4, nWidth / 4 * 3 };
147
+ int ayCenter[] = { nHeight / 4, nHeight / 4, nHeight / 4 * 3, nHeight / 4 * 3 };
148
+ cudaStream_t aStream[n];
149
+ vExceptionPtrs.resize(n);
150
+ for (int i = 0; i < n; i++)
151
+ {
152
+ ck(cudaStreamCreate(&aStream[i]));
153
+ std::unique_ptr<NvDecoder> dec(new NvDecoder(cuContext, true, FFmpeg2NvCodecId(demuxer.GetVideoCodec()), false, false, NULL, &decodeDim));
154
+ vDecoders.push_back(std::move(dec));
155
+ vThreads.push_back(NvThread(std::thread(DecProc, vDecoders[i].get(), szInFilePath, nWidth, nHeight, aapFrameBuffer[i],
156
+ nFrameBuffer, &iEnd, aiHead + i, abStop + i, aStream[i], axCenter[i], ayCenter[i], std::ref(vExceptionPtrs[i]))));
157
+ }
158
+
159
+ std::unique_ptr<uint8_t[]> pImage(new uint8_t[nByte]);
160
+ uint8_t* dpImage = nullptr;
161
+ ck(cudaMalloc(&dpImage, nByte));
162
+ std::ofstream fpOut(szOutFilePath, std::ios::out | std::ios::binary);
163
+ if (!fpOut)
164
+ {
165
+ std::ostringstream err;
166
+ err << "Unable to open output file: " << szOutFilePath << std::endl;
167
+ throw std::invalid_argument(err.str());
168
+ }
169
+
170
+ int nFrame = 0;
171
+ for (int i = 0;; i++)
172
+ {
173
+ // For each decoded frame #i
174
+ // iHead is used for ensuring all decoders have made progress
175
+ int iHead = INT_MAX;
176
+ for (int j = 0; j < n; j++)
177
+ {
178
+ while (!abStop[j] && aiHead[j] <= i)
179
+ {
180
+ // Decoder #j hasn't decoded frame #i
181
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
182
+ }
183
+ iHead = (std::min)(iHead, aiHead[j]);
184
+ }
185
+ if (iHead <= i)
186
+ {
187
+ // Some decoder stops
188
+ nFrame = i;
189
+ break;
190
+ }
191
+
192
+ std::cout << "Merge frames at #" << i << "\r";
193
+ uint8_t *apNv12[] = { aapFrameBuffer[0][i % nFrameBuffer], aapFrameBuffer[1][i % nFrameBuffer], aapFrameBuffer[2][i % nFrameBuffer], aapFrameBuffer[3][i % nFrameBuffer] };
194
+ // Merge all frames into dpImage
195
+ LaunchMerge(0, dpImage, apNv12, n, nWidth, nHeight);
196
+ ck(cudaMemcpy(pImage.get(), dpImage, nByte, cudaMemcpyDeviceToHost));
197
+ fpOut.write(reinterpret_cast<char*>(pImage.get()), nByte);
198
+
199
+ for (int j = 0; j < n; j++)
200
+ {
201
+ vDecoders[j]->UnlockFrame(&aapFrameBuffer[j][i % nFrameBuffer]);
202
+ }
203
+ iEnd++;
204
+ }
205
+ fpOut.close();
206
+ ck(cudaFree(dpImage));
207
+
208
+ for (int i = 0; i < n; i++)
209
+ {
210
+ if (vExceptionPtrs[i])
211
+ {
212
+ std::rethrow_exception(vExceptionPtrs[i]);
213
+ }
214
+ }
215
+
216
+ ck(cudaProfilerStop());
217
+ if (nFrame)
218
+ {
219
+ std::cout << "Merged video saved in " << szOutFilePath << ". A total of " << nFrame << " frames were decoded." << std::endl;
220
+ return 0;
221
+ }
222
+ else
223
+ {
224
+ std::cout << "Warning: no video frame decoded. Please don't use container formats (such as mp4/avi/webm) as the input, but use raw elementary stream file instead." << std::endl;
225
+ return 1;
226
+ }
227
+ }
228
+ catch (const std::exception &ex)
229
+ {
230
+ std::cout << ex.what();
231
+ exit(1);
232
+ }
233
+ return 0;
234
+ }
video_codec_sdk/Samples/AppDecode/AppDecMultiInput/CMakeLists.txt ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDecMultiInput)
13
+
14
+ set(APP_SOURCES
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecMultiInput.cpp
16
+ ${CMAKE_CURRENT_SOURCE_DIR}/Image.cu
17
+ )
18
+
19
+ if(WIN32)
20
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
21
+ endif()
22
+
23
+ set(NV_DEC_SOURCES
24
+ ${NV_DEC_DIR}/NvDecoder.cpp
25
+ )
26
+
27
+ set(NV_DEC_COMMON_HDR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../Common)
28
+
29
+ set(NV_DEC_HDRS
30
+ ${NV_DEC_DIR}/NvDecoder.h
31
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
32
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
33
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
34
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
35
+ ${NV_DEC_COMMON_HDR_DIR}/AppDecUtils.h
36
+ )
37
+
38
+ source_group( "headers" FILES ${NV_DEC_HDRS} )
39
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_ENC_CUDA_UTILS})
40
+
41
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
42
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
43
+ find_package(CUDAToolkit QUIET)
44
+ if(CUDAToolkit_FOUND)
45
+ # Map CUDAToolkit variables to legacy CUDA variable names
46
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
47
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
48
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
49
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
50
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
51
+ endif()
52
+ endif()
53
+ if(NOT CUDAToolkit_FOUND)
54
+ find_package(CUDA)
55
+ endif()
56
+
57
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
58
+
59
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
60
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
61
+ else()
62
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
63
+ endif()
64
+ # CUDA 11.7 and later is compiled with /MT option (staticaly linked with C runtime),
65
+ # since we are statically linking cudart_static.lib with the app,
66
+ # we need to make sure that all .obj files linked are compiled with /MT to avoid linker warning LNK4098
67
+ if (WIN32 AND CUDA_VERSION_MAJOR GREATER_EQUAL 11 AND CUDA_VERSION_MINOR GREATER_EQUAL 7)
68
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-Xcompiler /MT)
69
+ endif()
70
+ if ( CMAKE_COMPILER_IS_GNUCC )
71
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
72
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
73
+ endif()
74
+ endif()
75
+
76
+ # Use modern approach with CUDAToolkit when available, fallback to legacy FindCUDA
77
+ if(CUDAToolkit_FOUND AND CUDAToolkit_NVCC_EXECUTABLE)
78
+ set(CMAKE_CUDA_COMPILER ${CUDAToolkit_NVCC_EXECUTABLE})
79
+ enable_language(CUDA)
80
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
81
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_STANDARD 11)
82
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
83
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "75")
84
+ else()
85
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "50")
86
+ endif()
87
+ else()
88
+ cuda_add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
89
+ endif()
90
+
91
+ if (WIN32 AND CUDA_VERSION_MAJOR GREATER_EQUAL 11 AND CUDA_VERSION_MINOR GREATER_EQUAL 7)
92
+ target_compile_options(${PROJECT_NAME} PRIVATE "/MT")
93
+ endif()
94
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
95
+
96
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
97
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
98
+ ${NVCODEC_UTILS_DIR}
99
+ ${NV_CODEC_DIR}
100
+ ${NV_APPDEC_COMMON_DIR}
101
+ ${NV_FFMPEG_HDRS}
102
+ )
103
+
104
+ if(WIN32)
105
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
106
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
107
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
108
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
109
+ #copy dll's
110
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.dll" )
111
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.lib")
112
+ endif()
113
+
114
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
115
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB} )
116
+
117
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
118
+ if (MSVC)
119
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
120
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
121
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
122
+ #copy pdb's
123
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
124
+ endif()
125
+
video_codec_sdk/Samples/AppDecode/AppDecMultiInput/Image.cu ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ #include <stdint.h>
13
+ #include <cuda_runtime.h>
14
+ #include "../Utils/NvCodecUtils.h"
15
+
16
+ #define SLEEP_TIME 0
17
+
18
+ inline __device__ double sleep(int n) {
19
+ double d = 1.0;
20
+ for (int i = 0; i < n; i++) {
21
+ d += sin(d);
22
+ }
23
+ return d;
24
+ }
25
+
26
+ static __global__ void Ripple(uint8_t *pImage, int nWidth, int nHeight, int xCenter, int yCenter, int iTime) {
27
+ int ix = blockIdx.x * blockDim.x + threadIdx.x,
28
+ iy = blockIdx.y * blockDim.y + threadIdx.y;
29
+ if (ix >= nWidth || iy >= nHeight) {
30
+ return;
31
+ }
32
+ float dx = ix - xCenter, dy = iy - yCenter, d = sqrtf(dx * dx + dy * dy), dmax = sqrtf(nWidth * nWidth + nHeight * nHeight) / 2.0f;
33
+ pImage[iy * nWidth + ix] = (uint8_t)(127.0f * (1.0f - d / dmax) * sinf((d - iTime * 10)* 0.1) + 128.0f);
34
+ sleep(SLEEP_TIME);
35
+ }
36
+
37
+ void LaunchRipple(cudaStream_t stream, uint8_t *dpImage, int nWidth, int nHeight, int xCenter, int yCenter, int iTime) {
38
+ Ripple<<<dim3((nWidth + 15) / 16, (nHeight + 15) / 16), dim3(16, 16), 0, stream>>>(dpImage, nWidth, nHeight, xCenter, yCenter, iTime);
39
+ }
40
+
41
+ inline __device__ uint8_t clamp(int i) {
42
+ return (uint8_t)min(max(i, 0), 255);
43
+ }
44
+
45
+ static __global__ void OverlayRipple(uint8_t *pNv12, uint8_t *pRipple, int nWidth, int nHeight) {
46
+ int ix = blockIdx.x * blockDim.x + threadIdx.x,
47
+ iy = blockIdx.y * blockDim.y + threadIdx.y;
48
+ if (ix >= nWidth || iy >= nHeight) {
49
+ return;
50
+ }
51
+ pNv12[iy * nWidth + ix] = clamp(pNv12[iy * nWidth + ix] + (pRipple[iy * nWidth + ix] - 127.0f) * 0.8f);
52
+ sleep(SLEEP_TIME);
53
+ }
54
+
55
+ void LaunchOverlayRipple(cudaStream_t stream, uint8_t *dpNv12, uint8_t *dpRipple, int nWidth, int nHeight) {
56
+ OverlayRipple<<<dim3((nWidth + 15) / 16, (nHeight + 15) / 16), dim3(16, 16), 0, stream>>>(dpNv12, dpRipple, nWidth, nHeight);
57
+ }
58
+
59
+ static __global__ void Merge(uint8_t *pNv12Merged, uint8_t **apNv12, int nImage, int nWidth, int nHeight) {
60
+ int ix = blockIdx.x * blockDim.x + threadIdx.x,
61
+ iy = blockIdx.y * blockDim.y + threadIdx.y;
62
+ if (ix >= nWidth / 2 || iy >= nHeight / 2) {
63
+ return;
64
+ }
65
+ uint2 y01 = {}, y23 = {}, uv = {};
66
+ for (int i = 0; i < nImage; i++) {
67
+ uchar2 c2;
68
+ c2 = *(uchar2 *)(apNv12[i] + nWidth * iy * 2 + ix * 2);
69
+ y01.x += c2.x; y01.y += c2.y;
70
+ c2 = *(uchar2 *)(apNv12[i] + nWidth * (iy * 2 + 1) + ix * 2);
71
+ y23.x += c2.x; y23.y += c2.y;
72
+ c2 = *(uchar2 *)(apNv12[i] + nWidth * (nHeight + iy) + ix * 2);
73
+ uv.x += c2.x; uv.y += c2.y;
74
+ }
75
+ *(uchar2 *)(pNv12Merged + nWidth * iy * 2 + ix * 2) = uchar2 {(uint8_t)(y01.x / nImage), (uint8_t)(y01.y / nImage)};
76
+ *(uchar2 *)(pNv12Merged + nWidth * (iy * 2 + 1) + ix * 2) = uchar2 {(uint8_t)(y23.x / nImage), (uint8_t)(y23.y / nImage)};
77
+ *(uchar2 *)(pNv12Merged + nWidth * (nHeight + iy) + ix * 2) = uchar2 {(uint8_t)(uv.x / nImage), (uint8_t)(uv.y / nImage)};
78
+ sleep(SLEEP_TIME);
79
+ }
80
+
81
+ void LaunchMerge(cudaStream_t stream, uint8_t *dpNv12Merged, uint8_t **pdpNv12, int nImage, int nWidth, int nHeight) {
82
+ uint8_t **dadpNv12;
83
+ ck(cudaMalloc(&dadpNv12, sizeof(uint8_t *) * nImage));
84
+ ck(cudaMemcpy(dadpNv12, pdpNv12, sizeof(uint8_t *) * nImage, cudaMemcpyHostToDevice));
85
+ Merge<<<dim3((nWidth + 15) / 16, (nHeight + 15) / 16), dim3(8, 8), 0, stream>>>(dpNv12Merged, dadpNv12, nImage, nWidth, nHeight);
86
+ ck(cudaFree(dadpNv12));
87
+ }
video_codec_sdk/Samples/AppDecode/AppDecPerf/AppDecPerf.cpp ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecPerf.cpp
14
+ //! \brief Source file for AppDecPerf sample
15
+ //!
16
+ //! This sample application measures decoding performance in FPS.
17
+ //! The application creates multiple host threads and runs a different decoding session on each thread.
18
+ //! The number of threads can be controlled by the CLI option "-thread".
19
+ //! The application creates 2 host threads, each with a separate decode session, by default.
20
+ //! The application supports measuring the decode performance only (keeping decoded
21
+ //! frames in device memory as well as measuring the decode performance including transfer
22
+ //! of frames to the host memory.
23
+ //---------------------------------------------------------------------------
24
+
25
+ #include <cuda.h>
26
+ #include <cudaProfiler.h>
27
+ #include <stdio.h>
28
+ #include <iostream>
29
+ #include <thread>
30
+ #include <chrono>
31
+ #include <string.h>
32
+ #include <memory>
33
+ #include "NvDecoder/NvDecoder.h"
34
+ #include "../Utils/NvCodecUtils.h"
35
+ #include "../Utils/FFmpegDemuxer.h"
36
+ #include "../Common/AppDecUtils.h"
37
+ #include <chrono>
38
+ #include <future>
39
+ #include <iomanip>
40
+
41
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
42
+
43
+ struct SessionStats
44
+ {
45
+ int64_t initTime; // session initialization time
46
+ int64_t decodeTime; // time taken by actual decoding operation
47
+ int frames; // number of frames decoded
48
+ };
49
+
50
+ using NvDecodePromise = std::promise<SessionStats>;
51
+ using NvDecodeFuture = std::future<SessionStats>;
52
+
53
+
54
+ class NvDecoderPerf : public NvDecoder
55
+ {
56
+ public:
57
+ NvDecoderPerf(CUcontext cuContext, bool bUseDeviceFrame, cudaVideoCodec eCodec);
58
+ void SetSessionInitTime(int64_t duration) { m_sessionInitTime = duration; }
59
+ int64_t GetSessionInitTime() { return m_sessionInitTime; }
60
+
61
+ static void IncrementSessionInitCounter() { m_sessionInitCounter++; }
62
+ static uint32_t GetSessionInitCounter() { return m_sessionInitCounter; }
63
+ static void SetSessionCount(uint32_t count) { m_sessionCount = count; }
64
+ static uint32_t GetSessionCount(void) { return m_sessionCount; }
65
+
66
+ protected:
67
+ int HandleVideoSequence(CUVIDEOFORMAT *pVideoFormat);
68
+
69
+ int64_t m_sessionInitTime;
70
+ static std::mutex m_initMutex;
71
+ static std::condition_variable m_cvInit;
72
+ static uint32_t m_sessionInitCounter;
73
+ static uint32_t m_sessionCount;
74
+ };
75
+
76
+ std::mutex NvDecoderPerf::m_initMutex;
77
+ std::condition_variable NvDecoderPerf::m_cvInit;
78
+ uint32_t NvDecoderPerf::m_sessionInitCounter = 0;
79
+ uint32_t NvDecoderPerf::m_sessionCount = 1;
80
+
81
+ NvDecoderPerf::NvDecoderPerf(CUcontext cuContext, bool bUseDeviceFrame, cudaVideoCodec eCodec)
82
+ : NvDecoder(cuContext, bUseDeviceFrame, eCodec)
83
+ {
84
+ }
85
+
86
+ int NvDecoderPerf::HandleVideoSequence(CUVIDEOFORMAT *pVideoFormat)
87
+ {
88
+ auto sessionStart = std::chrono::high_resolution_clock::now();
89
+
90
+ int nDecodeSurface = NvDecoder::HandleVideoSequence(pVideoFormat);
91
+
92
+ std::unique_lock<std::mutex> lock(m_initMutex);
93
+
94
+ IncrementSessionInitCounter();
95
+
96
+ // Wait for all threads to finish initialization of the decoder session.
97
+ // This ensures that all threads start decoding frames at the same
98
+ // time and saturate the decoder engines. This also leads to more
99
+ // accurate measurement of decoding performance.
100
+ if (GetSessionInitCounter() == GetSessionCount())
101
+ {
102
+ m_cvInit.notify_all();
103
+ }
104
+ else
105
+ {
106
+ m_cvInit.wait(lock, [] { return NvDecoderPerf::GetSessionInitCounter() >= NvDecoderPerf::GetSessionCount(); });
107
+ }
108
+
109
+ auto sessionEnd = std::chrono::high_resolution_clock::now();
110
+ int64_t elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(sessionEnd - sessionStart).count();
111
+
112
+ SetSessionInitTime(elapsedTime);
113
+ return nDecodeSurface;
114
+ }
115
+
116
+
117
+ /**
118
+ * @brief Function to decode media file using NvDecoder interface
119
+ * @param pDec - Handle to NvDecoder
120
+ * @param demuxer - Pointer to an FFmpegDemuxer instance
121
+ * @param pnFrame - Variable to record the number of frames decoded
122
+ * @param ex - Stores current exception in case of failure
123
+ */
124
+ void DecProc(NvDecoderPerf *pDec, FFmpegDemuxer *demuxer, NvDecodePromise& promise, std::exception_ptr &ex)
125
+ {
126
+ SessionStats stats = {0, 0, 0};
127
+ auto sessionStart = std::chrono::high_resolution_clock::now();
128
+
129
+ try
130
+ {
131
+ int nVideoBytes = 0, nFrameReturned = 0, nFrame = 0;
132
+ uint8_t *pVideo = NULL, *pFrame = NULL;
133
+
134
+ do {
135
+ demuxer->Demux(&pVideo, &nVideoBytes);
136
+ nFrameReturned = pDec->Decode(pVideo, nVideoBytes);
137
+ if (!nFrame && nFrameReturned)
138
+ LOG(INFO) << pDec->GetVideoInfo();
139
+
140
+ nFrame += nFrameReturned;
141
+ } while (nVideoBytes);
142
+ stats.frames = nFrame;
143
+ stats.initTime = pDec->GetSessionInitTime();
144
+ }
145
+ catch (std::exception&)
146
+ {
147
+ ex = std::current_exception();
148
+ }
149
+
150
+ auto sessionEnd = std::chrono::high_resolution_clock::now();
151
+ stats.decodeTime = std::chrono::duration_cast<std::chrono::milliseconds>(sessionEnd - sessionStart).count();
152
+
153
+ promise.set_value(stats);
154
+ }
155
+
156
+ static void ShowBriefHelp()
157
+ {
158
+ std::ostringstream oss;
159
+ oss << "NVIDIA Video Decoder Performance Sample Application\n";
160
+ oss << "============================================\n\n";
161
+
162
+ oss << "Usage: AppDecPerf -i <input_file> [options]\n\n";
163
+
164
+ // Brief table of core arguments
165
+ oss << "Common Arguments:\n";
166
+ oss << std::left << std::setw(25) << "Argument"
167
+ << std::setw(12) << "Type"
168
+ << "Default Value\n";
169
+ oss << std::string(50, '-') << "\n";
170
+
171
+ oss << std::left << std::setw(25) << "-i <path>"
172
+ << std::setw(12) << "Required"
173
+ << "N/A\n";
174
+
175
+ oss << std::left << std::setw(25) << "-gpu <n>"
176
+ << std::setw(12) << "Optional"
177
+ << "0\n";
178
+
179
+ oss << std::left << std::setw(25) << "-thread <n>"
180
+ << std::setw(12) << "Optional"
181
+ << "2\n";
182
+
183
+ oss << std::left << std::setw(25) << "-single"
184
+ << std::setw(12) << "Optional"
185
+ << "false\n";
186
+
187
+ oss << std::left << std::setw(25) << "-host"
188
+ << std::setw(12) << "Optional"
189
+ << "false\n";
190
+
191
+ oss << "\nFor detailed help, use -A/--advanced-options\n";
192
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
193
+ std::cout << oss.str();
194
+ exit(0);
195
+ }
196
+
197
+ static void ShowDetailedHelp()
198
+ {
199
+ std::ostringstream oss;
200
+ oss << "NVIDIA Video Decoder Performance Sample Application - Detailed Help\n";
201
+ oss << "========================================================\n\n";
202
+
203
+ oss << "Usage: AppDecPerf -i <input_file> [options]\n\n";
204
+
205
+ // Full table of all arguments
206
+ oss << "All Arguments:\n";
207
+ oss << std::left << std::setw(25) << "Argument"
208
+ << std::setw(12) << "Type"
209
+ << std::setw(20) << "Default Value"
210
+ << "Usage\n";
211
+ oss << std::string(80, '-') << "\n";
212
+
213
+ // Required arguments
214
+ oss << std::left << std::setw(25) << "-i <path>"
215
+ << std::setw(12) << "Required"
216
+ << std::setw(20) << "N/A"
217
+ << "-i input.h264\n";
218
+
219
+ // Optional arguments
220
+ oss << std::left << std::setw(25) << "-gpu <n>"
221
+ << std::setw(12) << "Optional"
222
+ << std::setw(20) << "0"
223
+ << "-gpu 1\n";
224
+
225
+ oss << std::left << std::setw(25) << "-thread <n>"
226
+ << std::setw(12) << "Optional"
227
+ << std::setw(20) << "2"
228
+ << "-thread 4\n";
229
+
230
+ oss << std::left << std::setw(25) << "-single"
231
+ << std::setw(12) << "Optional"
232
+ << std::setw(20) << "false"
233
+ << "-single\n";
234
+
235
+ oss << std::left << std::setw(25) << "-host"
236
+ << std::setw(12) << "Optional"
237
+ << std::setw(20) << "false"
238
+ << "-host\n";
239
+
240
+ // Detailed descriptions
241
+ oss << "\nDetailed Descriptions:\n";
242
+ oss << "-------------------\n";
243
+ oss << std::left << std::setw(25) << "-i" << ": Input file path\n";
244
+ oss << std::left << std::setw(25) << "-gpu" << ": Ordinal of GPU to use\n";
245
+ oss << std::left << std::setw(25) << "-thread" << ": Number of decoding threads\n";
246
+ oss << std::left << std::setw(25) << "-single" << ": Use single context\n";
247
+ oss << std::left << std::setw(25) << "-host" << ": Copy frame to host memory\n";
248
+ oss << std::left << std::setw(25) << "-h/--help" << ": Print usage information for common commandline options\n";
249
+ oss << std::left << std::setw(25) << "-A/--advanced-options" << ": Print usage information for common and advanced commandline options\n";
250
+ oss << std::left << std::setw(25) << "-dc/--decode-caps" << ": Print decode capabilities of GPU\n";
251
+
252
+ // Important notes
253
+ oss << "\nNotes:\n";
254
+ oss << "------\n";
255
+ oss << "* Single context may result in suboptimal performance\n";
256
+ oss << "* Host memory copy may result in suboptimal performance\n";
257
+ oss << "* Multiple contexts are used by default\n";
258
+ oss << "* Device memory is used by default\n";
259
+ oss << std::endl;
260
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
261
+
262
+ std::cout << oss.str();
263
+ exit(0);
264
+ }
265
+
266
+ static void ShowHelpAndExit(const char *szBadOption = NULL)
267
+ {
268
+ if (szBadOption)
269
+ {
270
+ std::ostringstream oss;
271
+ oss << "Error parsing \"" << szBadOption << "\"\n";
272
+ oss << "Use -h/--help for basic usage or -A/--advanced-options for detailed information\n";
273
+ throw std::invalid_argument(oss.str());
274
+ }
275
+ }
276
+
277
+ void ParseCommandLine(int argc, char *argv[], char *szInputFileName, int &iGpu, int &nThread, bool &bSingle, bool &bHost)
278
+ {
279
+ if (argc == 1) {
280
+ std::cout << "No Arguments provided! Please refer to the following for options:" << "\"\n";
281
+ ShowBriefHelp();
282
+ }
283
+ for (int i = 1; i < argc; i++) {
284
+ if (!_stricmp(argv[i], "-h") || !_stricmp(argv[i], "--help")) {
285
+ ShowBriefHelp();
286
+ }
287
+ if (!_stricmp(argv[i], "-A") || !_stricmp(argv[i], "--advanced-options")) {
288
+ ShowDetailedHelp();
289
+ }
290
+ if (!_stricmp(argv[i], "-dc") || !_stricmp(argv[i], "--decode-caps")) {
291
+ ShowDecoderCapability();
292
+ }
293
+ if (!_stricmp(argv[i], "-i")) {
294
+ if (++i == argc) {
295
+ ShowHelpAndExit("-i");
296
+ }
297
+ sprintf(szInputFileName, "%s", argv[i]);
298
+ continue;
299
+ }
300
+ if (!_stricmp(argv[i], "-gpu")) {
301
+ if (++i == argc) {
302
+ ShowHelpAndExit("-gpu");
303
+ }
304
+ iGpu = atoi(argv[i]);
305
+ continue;
306
+ }
307
+ if (!_stricmp(argv[i], "-thread")) {
308
+ if (++i == argc) {
309
+ ShowHelpAndExit("-thread");
310
+ }
311
+ nThread = atoi(argv[i]);
312
+ continue;
313
+ }
314
+ if (!_stricmp(argv[i], "-single")) {
315
+ bSingle = true;
316
+ continue;
317
+ }
318
+ if (!_stricmp(argv[i], "-host")) {
319
+ bHost = true;
320
+ continue;
321
+ }
322
+ ShowHelpAndExit(argv[i]);
323
+ }
324
+ }
325
+
326
+ struct NvDecPerfData
327
+ {
328
+ uint8_t *pBuf;
329
+ std::vector<uint8_t *> *pvpPacketData;
330
+ std::vector<int> *pvpPacketDataSize;
331
+ };
332
+
333
+ int CUDAAPI HandleVideoData(void *pUserData, CUVIDSOURCEDATAPACKET *pPacket) {
334
+ NvDecPerfData *p = (NvDecPerfData *)pUserData;
335
+ memcpy(p->pBuf, pPacket->payload, pPacket->payload_size);
336
+ p->pvpPacketData->push_back(p->pBuf);
337
+ p->pvpPacketDataSize->push_back(pPacket->payload_size);
338
+ p->pBuf += pPacket->payload_size;
339
+ return 1;
340
+ }
341
+
342
+ int main(int argc, char **argv)
343
+ {
344
+ char szInFilePath[256] = "";
345
+ int iGpu = 0;
346
+ int nThread = 2;
347
+ bool bSingle = false;
348
+ bool bHost = false;
349
+ std::vector<std::exception_ptr> vExceptionPtrs;
350
+ std::vector<NvDecodePromise> vPromise;
351
+ std::vector<NvDecodeFuture> vFuture;
352
+
353
+ try {
354
+ ParseCommandLine(argc, argv, szInFilePath, iGpu, nThread, bSingle, bHost);
355
+ CheckInputFile(szInFilePath);
356
+
357
+ struct stat st;
358
+ if (stat(szInFilePath, &st) != 0) {
359
+ return 1;
360
+ }
361
+ int nBufSize = st.st_size;
362
+
363
+ uint8_t *pBuf = NULL;
364
+ try {
365
+ pBuf = new uint8_t[nBufSize];
366
+ }
367
+ catch (std::bad_alloc) {
368
+ std::cout << "Failed to allocate memory in BufferedReader" << std::endl;
369
+ return 1;
370
+ }
371
+ std::vector<uint8_t *> vpPacketData;
372
+ std::vector<int> vnPacketData;
373
+
374
+ NvDecPerfData userData = { pBuf, &vpPacketData, &vnPacketData };
375
+
376
+ ck(cuInit(0));
377
+ int nGpu = 0;
378
+ ck(cuDeviceGetCount(&nGpu));
379
+ if (iGpu < 0 || iGpu >= nGpu) {
380
+ std::cout << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
381
+ return 1;
382
+ }
383
+ CUdevice cuDevice = 0;
384
+ ck(cuDeviceGet(&cuDevice, iGpu));
385
+ char szDeviceName[80];
386
+ ck(cuDeviceGetName(szDeviceName, sizeof(szDeviceName), cuDevice));
387
+ std::cout << "GPU in use: " << szDeviceName << std::endl;
388
+
389
+ std::vector<std::unique_ptr<FFmpegDemuxer>> vDemuxer;
390
+ std::vector<std::unique_ptr<NvDecoderPerf>> vDec;
391
+ CUcontext cuContext = NULL;
392
+ ck(NVCODEC_CUDA_CTX_CREATE(&cuContext, 0, cuDevice));
393
+ vExceptionPtrs.resize(nThread);
394
+ vPromise.resize(nThread);
395
+
396
+ for (int i = 0; i < nThread; i++)
397
+ {
398
+ if (!bSingle)
399
+ {
400
+ ck(NVCODEC_CUDA_CTX_CREATE(&cuContext, 0, cuDevice));
401
+ }
402
+ std::unique_ptr<FFmpegDemuxer> demuxer(new FFmpegDemuxer(szInFilePath));
403
+
404
+ NvDecoderPerf* sessionObject = new NvDecoderPerf(cuContext, !bHost, FFmpeg2NvCodecId(demuxer->GetVideoCodec()));
405
+ std::unique_ptr<NvDecoderPerf> dec(sessionObject);
406
+ vDemuxer.push_back(std::move(demuxer));
407
+ vDec.push_back(std::move(dec));
408
+ }
409
+
410
+ NvDecoderPerf::SetSessionCount(nThread);
411
+
412
+ float totalFPS = 0;
413
+ std::vector<NvThread> vThread;
414
+
415
+ for (int i = 0; i < nThread; i++)
416
+ {
417
+ vThread.push_back(NvThread(std::thread(DecProc, vDec[i].get(), vDemuxer[i].get(), std::ref(vPromise[i]), std::ref(vExceptionPtrs[i]))));
418
+ vFuture.push_back(vPromise[i].get_future());
419
+ }
420
+
421
+ int nTotal = 0;
422
+ for (int i = 0; i < nThread; i++)
423
+ {
424
+ SessionStats stats = vFuture[i].get();
425
+ nTotal += stats.frames;
426
+
427
+ totalFPS += (stats.frames / ((stats.decodeTime - stats.initTime) / 1000.0f));
428
+
429
+ vThread[i].join();
430
+ vDec[i].reset(nullptr);
431
+ }
432
+
433
+ std::cout << "Total Frames Decoded=" << nTotal << " FPS = " << totalFPS << std::endl;
434
+
435
+ ck(cuProfilerStop());
436
+
437
+ for (int i = 0; i < nThread; i++)
438
+ {
439
+ if (vExceptionPtrs[i])
440
+ {
441
+ std::rethrow_exception(vExceptionPtrs[i]);
442
+ }
443
+ }
444
+ }
445
+ catch (const std::exception& ex)
446
+ {
447
+ std::cout << ex.what();
448
+ exit(1);
449
+ }
450
+ return 0;
451
+ }
video_codec_sdk/Samples/AppDecode/AppDecPerf/CMakeLists.txt ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2024 NVIDIA Corporation. All rights reserved.
2
+ #
3
+ # Please refer to the NVIDIA end user license agreement (EULA) associated
4
+ # with this source code for terms and conditions that govern your use of
5
+ # this software. Any use, reproduction, disclosure, or distribution of
6
+ # this software and related documentation outside the terms of the EULA
7
+ # is strictly prohibited.
8
+
9
+ # 3.7 is required for FindVulkan module support in CMake.
10
+ cmake_minimum_required(VERSION 3.7)
11
+
12
+ project(AppDecPerf)
13
+
14
+ set(APP_SOURCES
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/AppDecPerf.cpp
16
+ )
17
+
18
+ if(WIN32)
19
+ set(NV_FFMPEG_HDRS ${FFMPEG_DIR}/include)
20
+ endif()
21
+
22
+ set(NV_DEC_SOURCES
23
+ ${NV_DEC_DIR}/NvDecoder.cpp
24
+ )
25
+
26
+ set(NV_DEC_COMMON_HDR_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../Common)
27
+
28
+ set(NV_DEC_HDRS
29
+ ${NV_DEC_DIR}/NvDecoder.h
30
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/cuviddec.h
31
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}/nvcuvid.h
32
+ ${NVCODEC_UTILS_DIR}/NvCodecUtils.h
33
+ ${NVCODEC_UTILS_DIR}/FFmpegDemuxer.h
34
+ ${NV_DEC_COMMON_HDR_DIR}/AppDecUtils.h
35
+ )
36
+
37
+ source_group( "headers" FILES ${NV_DEC_HDRS} )
38
+ source_group( "sources" FILES ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_ENC_CUDA_UTILS})
39
+
40
+ # Try modern CUDAToolkit first for CMake 3.17+, fallback to deprecated CUDA module
41
+ if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
42
+ find_package(CUDAToolkit QUIET)
43
+ if(CUDAToolkit_FOUND)
44
+ # Map CUDAToolkit variables to legacy CUDA variable names
45
+ set(CUDA_CUDA_LIBRARY CUDA::cuda_driver)
46
+ set(CUDA_TOOLKIT_ROOT_DIR ${CUDAToolkit_TARGET_DIR})
47
+ set(CUDA_INCLUDE_DIRS ${CUDAToolkit_INCLUDE_DIRS})
48
+ set(CUDA_VERSION_MAJOR ${CUDAToolkit_VERSION_MAJOR})
49
+ set(CUDA_VERSION_MINOR ${CUDAToolkit_VERSION_MINOR})
50
+ endif()
51
+ endif()
52
+ if(NOT CUDAToolkit_FOUND)
53
+ find_package(CUDA)
54
+ endif()
55
+
56
+ set(CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
57
+
58
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
59
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_75,code=\"sm_75,compute_75\")
60
+ else()
61
+ set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS};-gencode arch=compute_50,code=\"sm_50,compute_50\")
62
+ endif()
63
+ if ( CMAKE_COMPILER_IS_GNUCC )
64
+ if(NOT "${CUDA_NVCC_FLAGS}" MATCHES "-std=c\\+\\+11" )
65
+ list(APPEND CUDA_NVCC_FLAGS -std=c++11)
66
+ endif()
67
+ endif()
68
+
69
+ # Use modern approach with CUDAToolkit when available, fallback to legacy FindCUDA
70
+ if(CUDAToolkit_FOUND AND CUDAToolkit_NVCC_EXECUTABLE)
71
+ set(CMAKE_CUDA_COMPILER ${CUDAToolkit_NVCC_EXECUTABLE})
72
+ enable_language(CUDA)
73
+ add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
74
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_STANDARD 11)
75
+ if(NVCODEC_CUDA_VERSION_13_OR_GREATER)
76
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "75")
77
+ else()
78
+ set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURES "50")
79
+ endif()
80
+ else()
81
+ cuda_add_executable(${PROJECT_NAME} ${APP_SOURCES} ${NV_DEC_SOURCES} ${NV_DEC_HDRS} ${NV_ENC_CUDA_UTILS})
82
+ endif()
83
+
84
+ set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
85
+
86
+ target_include_directories(${PROJECT_NAME} PUBLIC ${CUDA_INCLUDE_DIRS}
87
+ ${NVCODEC_PUBLIC_INTERFACE_DIR}
88
+ ${NVCODEC_UTILS_DIR}
89
+ ${NV_CODEC_DIR}
90
+ ${NV_APPDEC_COMMON_DIR}
91
+ ${NV_FFMPEG_HDRS}
92
+ )
93
+
94
+ if(WIN32)
95
+ Set(AVCODEC_LIB ${FFMPEG_DIR}/lib/avcodec.lib)
96
+ Set(AVFORMAT_LIB ${FFMPEG_DIR}/lib/avformat.lib)
97
+ Set(AVUTIL_LIB ${FFMPEG_DIR}/lib/avutil.lib)
98
+ Set(SWRESAMPLE_LIB ${FFMPEG_DIR}/lib/swresample.lib)
99
+ #copy dll's
100
+ install(DIRECTORY ${FFMPEG_DLL_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.dll")
101
+ install(DIRECTORY ${FFMPEG_LIB_DIR} DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} OPTIONAL FILES_MATCHING PATTERN "*.lib")
102
+ endif()
103
+
104
+
105
+ target_link_libraries(${PROJECT_NAME} ${CUDA_CUDA_LIBRARY} ${CMAKE_DL_LIBS} ${NVENCODEAPI_LIB} ${CUVID_LIB} ${AVCODEC_LIB}
106
+ ${AVFORMAT_LIB} ${AVUTIL_LIB} ${SWRESAMPLE_LIB})
107
+
108
+ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR})
109
+ if (MSVC)
110
+ add_definitions(-D_CRT_SECURE_NO_WARNINGS)
111
+ set_target_properties( ${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${NVCODEC_SAMPLES_INSTALL_DIR}/$<CONFIG>/ )
112
+ add_dependencies(${PROJECT_NAME} copyFFMPEGFiles)
113
+ #copy pdb's
114
+ install(FILES $<TARGET_PDB_FILE:${PROJECT_NAME}> DESTINATION ${NVCODEC_SAMPLES_INSTALL_DIR} CONFIGURATIONS Debug)
115
+ endif()
116
+
video_codec_sdk/Samples/AppDecode/Common/AppDecUtils.h ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ //---------------------------------------------------------------------------
13
+ //! \file AppDecUtils.h
14
+ //! \brief Header file containing definitions of miscellaneous functions used by Decode samples
15
+ //---------------------------------------------------------------------------
16
+
17
+ #pragma once
18
+ #include <sstream>
19
+ #include <iostream>
20
+
21
+ static void ShowDecoderCapability();
22
+ static void getOutputFormatNames(unsigned short nOutputFormatMask, char *OutputFormats);
23
+ static void createCudaContext(CUcontext* cuContext, int iGpu, unsigned int flags);
24
+
25
+ static void ShowBriefHelp(char *szOutputFileName, bool *pbVerbose, int *piD3d, bool *pbForce_zero_latency)
26
+ {
27
+ std::ostringstream oss;
28
+ oss << "NVIDIA Video Decoder Sample Application\n";
29
+ oss << "====================================\n\n";
30
+
31
+ oss << "Usage: AppDec -i <input_file> [options]\n\n";
32
+
33
+ // Brief table of core arguments
34
+ oss << "Common Arguments:\n";
35
+ oss << std::left << std::setw(25) << "Argument"
36
+ << std::setw(12) << "Type"
37
+ << "Default Value\n";
38
+ oss << std::string(50, '-') << "\n";
39
+
40
+ oss << std::left << std::setw(25) << "-i <path>"
41
+ << std::setw(12) << "Required"
42
+ << "N/A\n";
43
+
44
+ if (szOutputFileName) {
45
+ oss << std::left << std::setw(25) << "-o <path>"
46
+ << std::setw(12) << "Optional"
47
+ << "out.native/.planar\n";
48
+ }
49
+
50
+ oss << std::left << std::setw(25) << "-gpu <n>"
51
+ << std::setw(12) << "Optional"
52
+ << "0\n";
53
+
54
+ if (pbVerbose) {
55
+ oss << std::left << std::setw(25) << "-v"
56
+ << std::setw(12) << "Optional"
57
+ << "false\n";
58
+ }
59
+
60
+ if (piD3d) {
61
+ oss << std::left << std::setw(25) << "-d3d <n>"
62
+ << std::setw(12) << "Optional"
63
+ << "9\n";
64
+ }
65
+
66
+ if (pbForce_zero_latency) {
67
+ oss << std::left << std::setw(25) << "-force_zero_latency"
68
+ << std::setw(12) << "Optional"
69
+ << "false\n";
70
+ }
71
+
72
+ oss << "\nFor detailed help, use -A/--advanced-options\n";
73
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
74
+ std::cout << oss.str();
75
+ exit(0);
76
+ }
77
+
78
+ static void ShowDetailedHelp(char *szOutputFileName, bool *pbVerbose, int *piD3d, bool *pbForce_zero_latency)
79
+ {
80
+ std::ostringstream oss;
81
+ oss << "NVIDIA Video Decoder Sample Application - Detailed Help\n";
82
+ oss << "================================================\n\n";
83
+
84
+ oss << "Usage: AppDec -i <input_file> [options]\n\n";
85
+
86
+ // Full table of all arguments
87
+ oss << "All Arguments:\n";
88
+ oss << std::left << std::setw(25) << "Argument"
89
+ << std::setw(12) << "Type"
90
+ << std::setw(20) << "Default Value"
91
+ << "Example\n";
92
+ oss << std::string(80, '-') << "\n";
93
+
94
+ // Required arguments
95
+ oss << std::left << std::setw(25) << "-i <path>"
96
+ << std::setw(12) << "Required"
97
+ << std::setw(20) << "N/A"
98
+ << "-i input.h264\n";
99
+
100
+ // Optional arguments
101
+ if (szOutputFileName) {
102
+ oss << std::left << std::setw(25) << "-o <path>"
103
+ << std::setw(12) << "Optional"
104
+ << std::setw(20) << "out.native/.planar"
105
+ << "-o output.yuv\n";
106
+ }
107
+
108
+ oss << std::left << std::setw(25) << "-gpu <n>"
109
+ << std::setw(12) << "Optional"
110
+ << std::setw(20) << "0"
111
+ << "-gpu 1\n";
112
+
113
+ if (pbVerbose) {
114
+ oss << std::left << std::setw(25) << "-v"
115
+ << std::setw(12) << "Optional"
116
+ << std::setw(20) << "false"
117
+ << "-v\n";
118
+ }
119
+
120
+ if (piD3d) {
121
+ oss << std::left << std::setw(25) << "-d3d <n>"
122
+ << std::setw(12) << "Optional"
123
+ << std::setw(20) << "9"
124
+ << "-d3d 11\n";
125
+ }
126
+
127
+ if (pbForce_zero_latency) {
128
+ oss << std::left << std::setw(25) << "-force_zero_latency"
129
+ << std::setw(12) << "Optional"
130
+ << std::setw(20) << "false"
131
+ << "-force_zero_latency\n";
132
+ }
133
+
134
+ // Detailed descriptions
135
+ oss << "\nDetailed Descriptions:\n";
136
+ oss << "-------------------\n";
137
+ oss << std::left << std::setw(25) << "-i" << ": Input file path\n";
138
+ if (szOutputFileName) {
139
+ oss << std::left << std::setw(25) << "-o" << ": Output file path\n";
140
+ }
141
+ oss << std::left << std::setw(25) << "-gpu" << ": Ordinal of GPU to use\n";
142
+ if (pbVerbose) {
143
+ oss << std::left << std::setw(25) << "-v" << ": Enable verbose message output\n";
144
+ }
145
+ if (piD3d) {
146
+ oss << std::left << std::setw(25) << "-d3d" << ": DirectX version to use (9 or 11)\n";
147
+ }
148
+ if (pbForce_zero_latency) {
149
+ oss << std::left << std::setw(25) << "-force_zero_latency" << ": Enable zero latency for All-Intra/IPPP streams\n";
150
+ }
151
+ oss << std::left << std::setw(25) << "-h/--help" << ": Print usage information for common commandline options\n";
152
+ oss << std::left << std::setw(25) << "-A/--advanced-options" << ": Print usage information for common and advanced commandline options\n";
153
+ oss << std::left << std::setw(25) << "-dc/--decode-caps" << ": Print decode capabilities of GPU\n";
154
+
155
+ // Important notes
156
+ oss << "\nNotes:\n";
157
+ oss << "------\n";
158
+ if (pbForce_zero_latency) {
159
+ oss << "* Do not use -force_zero_latency if the stream contains B-frames\n";
160
+ }
161
+ if (piD3d) {
162
+ oss << "* D3D version 9 is used by default\n";
163
+ }
164
+ oss << std::endl;
165
+ oss << "To view decode capabilities, use -dc/--decode-caps\n";
166
+
167
+ std::cout << oss.str();
168
+ exit(0);
169
+ }
170
+
171
+ static void ShowHelpAndExit(const char *szBadOption, char *szOutputFileName, bool *pbVerbose, int *piD3d, bool *pbForce_zero_latency)
172
+ {
173
+ if (szBadOption)
174
+ {
175
+ std::ostringstream oss;
176
+ oss << "Error parsing \"" << szBadOption << "\"\n";
177
+ oss << "Use -h/--help for basic usage or -A/--advanced-options for detailed information\n";
178
+ throw std::invalid_argument(oss.str());
179
+ }
180
+ }
181
+
182
+ static void ParseCommandLine(int argc, char *argv[], char *szInputFileName,
183
+ char *szOutputFileName, int &iGpu, bool *pbVerbose = NULL, int *piD3d = NULL,
184
+ bool *pbForce_zero_latency = NULL)
185
+ {
186
+ std::ostringstream oss;
187
+ if (argc == 1) {
188
+ std::cout << "No Arguments provided! Please refer to the following for options:" << "\"\n";
189
+ ShowBriefHelp(szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
190
+ }
191
+ int i;
192
+ for (i = 1; i < argc; i++) {
193
+ if (!_stricmp(argv[i], "-h") || !_stricmp(argv[i], "--help")) {
194
+ ShowBriefHelp(szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
195
+ }
196
+ if (!_stricmp(argv[i], "-A") || !_stricmp(argv[i], "--advanced-options")) {
197
+ ShowDetailedHelp(szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
198
+ }
199
+ if (!_stricmp(argv[i], "-dc") || !_stricmp(argv[i], "--decode-caps")) {
200
+ ShowDecoderCapability();
201
+ }
202
+ if (!_stricmp(argv[i], "-i")) {
203
+ if (++i == argc) {
204
+ ShowHelpAndExit("-i", szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
205
+ }
206
+ sprintf(szInputFileName, "%s", argv[i]);
207
+ continue;
208
+ }
209
+ if (!_stricmp(argv[i], "-o")) {
210
+ if (++i == argc || !szOutputFileName) {
211
+ ShowHelpAndExit("-o", szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
212
+ }
213
+ sprintf(szOutputFileName, "%s", argv[i]);
214
+ continue;
215
+ }
216
+ if (!_stricmp(argv[i], "-gpu")) {
217
+ if (++i == argc) {
218
+ ShowHelpAndExit("-gpu", szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
219
+ }
220
+ iGpu = atoi(argv[i]);
221
+ continue;
222
+ }
223
+ if (!_stricmp(argv[i], "-v")) {
224
+ if (!pbVerbose) {
225
+ ShowHelpAndExit("-v", szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
226
+ }
227
+ *pbVerbose = true;
228
+ continue;
229
+ }
230
+ if (!_stricmp(argv[i], "-d3d")) {
231
+ if (++i == argc || !piD3d) {
232
+ ShowHelpAndExit("-d3d", szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
233
+ }
234
+ *piD3d = atoi(argv[i]);
235
+ continue;
236
+ }
237
+ if (!_stricmp(argv[i], "-force_zero_latency")) {
238
+ if (!pbForce_zero_latency) {
239
+ ShowHelpAndExit("-force_zero_latency", szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
240
+ }
241
+ *pbForce_zero_latency = true;
242
+ continue;
243
+ }
244
+ ShowHelpAndExit(argv[i], szOutputFileName, pbVerbose, piD3d, pbForce_zero_latency);
245
+ }
246
+ }
247
+
248
+ /**
249
+ * @brief Function to generate space-separated list of supported video surface formats
250
+ * @param nOutputFormatMask - Bit mask to represent supported cudaVideoSurfaceFormat in decoder
251
+ * @param OutputFormats - Variable into which output string is written
252
+ */
253
+ static void getOutputFormatNames(unsigned short nOutputFormatMask, char *OutputFormats)
254
+ {
255
+ if (nOutputFormatMask == 0) {
256
+ strcpy(OutputFormats, "N/A");
257
+ return;
258
+ }
259
+
260
+ if (nOutputFormatMask & (1U << cudaVideoSurfaceFormat_NV12)) {
261
+ strcat(OutputFormats, "NV12 ");
262
+ }
263
+
264
+ if (nOutputFormatMask & (1U << cudaVideoSurfaceFormat_P016)) {
265
+ strcat(OutputFormats, "P016 ");
266
+ }
267
+
268
+ if (nOutputFormatMask & (1U << cudaVideoSurfaceFormat_YUV444)) {
269
+ strcat(OutputFormats, "YUV444 ");
270
+ }
271
+
272
+ if (nOutputFormatMask & (1U << cudaVideoSurfaceFormat_YUV444_16Bit)) {
273
+ strcat(OutputFormats, "YUV444P16 ");
274
+ }
275
+
276
+ if (nOutputFormatMask & (1U << cudaVideoSurfaceFormat_NV16)) {
277
+ strcat(OutputFormats, "NV16 ");
278
+ }
279
+
280
+ if (nOutputFormatMask & (1U << cudaVideoSurfaceFormat_P216)) {
281
+ strcat(OutputFormats, "P216 ");
282
+ }
283
+ return;
284
+ }
285
+
286
+ /**
287
+ * @brief Utility function to create CUDA context
288
+ * @param cuContext - Pointer to CUcontext. Updated by this function.
289
+ * @param iGpu - Device number to get handle for
290
+ */
291
+ static void createCudaContext(CUcontext* cuContext, int iGpu, unsigned int flags)
292
+ {
293
+ CUdevice cuDevice = 0;
294
+ ck(cuDeviceGet(&cuDevice, iGpu));
295
+ char szDeviceName[80];
296
+ ck(cuDeviceGetName(szDeviceName, sizeof(szDeviceName), cuDevice));
297
+ std::cout << "GPU in use: " << szDeviceName << std::endl;
298
+ ck(NVCODEC_CUDA_CTX_CREATE(cuContext, flags, cuDevice));
299
+ }
300
+
301
+ /**
302
+ * @brief Print decoder capabilities on std::cout
303
+ */
304
+ static void ShowDecoderCapability()
305
+ {
306
+ ck(cuInit(0));
307
+ int nGpu = 0;
308
+ ck(cuDeviceGetCount(&nGpu));
309
+ std::cout << "Decoder Capability" << std::endl << std::endl;
310
+
311
+ struct caps {
312
+ const char *aszCodecName;
313
+ cudaVideoCodec aeCodec;
314
+ cudaVideoChromaFormat aeChromaFormat;
315
+ int anBitDepthMinus8;
316
+ };
317
+
318
+ caps queryList[] = {
319
+ {"JPEG", cudaVideoCodec_JPEG, cudaVideoChromaFormat_420, 0},
320
+ {"MPEG1", cudaVideoCodec_MPEG1, cudaVideoChromaFormat_420, 0},
321
+ {"MPEG2", cudaVideoCodec_MPEG2, cudaVideoChromaFormat_420, 0},
322
+ {"MPEG4", cudaVideoCodec_MPEG4, cudaVideoChromaFormat_420, 0},
323
+ {"H264", cudaVideoCodec_H264, cudaVideoChromaFormat_420, 0},
324
+ {"H264", cudaVideoCodec_H264, cudaVideoChromaFormat_420, 2},
325
+ {"H264", cudaVideoCodec_H264, cudaVideoChromaFormat_422, 0},
326
+ {"H264", cudaVideoCodec_H264, cudaVideoChromaFormat_422, 2},
327
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_420, 0},
328
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_420, 2},
329
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_420, 4},
330
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_422, 0},
331
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_422, 2},
332
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_422, 4},
333
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_444, 0},
334
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_444, 2},
335
+ {"HEVC", cudaVideoCodec_HEVC, cudaVideoChromaFormat_444, 4},
336
+ {"VC1", cudaVideoCodec_VC1, cudaVideoChromaFormat_420, 0},
337
+ {"VP8", cudaVideoCodec_VP8, cudaVideoChromaFormat_420, 0},
338
+ {"VP9", cudaVideoCodec_VP9, cudaVideoChromaFormat_420, 0},
339
+ {"VP9", cudaVideoCodec_VP9, cudaVideoChromaFormat_420, 2},
340
+ {"VP9", cudaVideoCodec_VP9, cudaVideoChromaFormat_420, 4},
341
+ {"AV1", cudaVideoCodec_AV1, cudaVideoChromaFormat_420, 0},
342
+ {"AV1", cudaVideoCodec_AV1, cudaVideoChromaFormat_420, 2},
343
+ {"AV1", cudaVideoCodec_AV1, cudaVideoChromaFormat_Monochrome, 0},
344
+ {"AV1", cudaVideoCodec_AV1, cudaVideoChromaFormat_Monochrome, 2},
345
+ };
346
+
347
+ const char *aszChromaFormat[] = { "4:0:0", "4:2:0", "4:2:2", "4:4:4" };
348
+ char strOutputFormats[64];
349
+
350
+ for (int iGpu = 0; iGpu < nGpu; iGpu++) {
351
+
352
+ CUcontext cuContext = NULL;
353
+ createCudaContext(&cuContext, iGpu, 0);
354
+
355
+ for (int i = 0; i < sizeof(queryList) / sizeof(queryList[0]); i++) {
356
+
357
+ CUVIDDECODECAPS decodeCaps = {};
358
+ decodeCaps.eCodecType = queryList[i].aeCodec;
359
+ decodeCaps.eChromaFormat = queryList[i].aeChromaFormat;
360
+ decodeCaps.nBitDepthMinus8 = queryList[i].anBitDepthMinus8;
361
+
362
+ cuvidGetDecoderCaps(&decodeCaps);
363
+
364
+ strOutputFormats[0] = '\0';
365
+ getOutputFormatNames(decodeCaps.nOutputFormatMask, strOutputFormats);
366
+
367
+ // setw() width = maximum_width_of_string + 2 spaces
368
+ std::cout << "Codec " << std::left << std::setw(7) << queryList[i].aszCodecName <<
369
+ "BitDepth " << std::setw(4) << decodeCaps.nBitDepthMinus8 + 8 <<
370
+ "ChromaFormat " << std::setw(7) << aszChromaFormat[decodeCaps.eChromaFormat] <<
371
+ "Supported " << std::setw(3) << (int)decodeCaps.bIsSupported <<
372
+ "MaxWidth " << std::setw(7) << decodeCaps.nMaxWidth <<
373
+ "MaxHeight " << std::setw(7) << decodeCaps.nMaxHeight <<
374
+ "MaxMBCount " << std::setw(10) << decodeCaps.nMaxMBCount <<
375
+ "MinWidth " << std::setw(5) << decodeCaps.nMinWidth <<
376
+ "MinHeight " << std::setw(5) << decodeCaps.nMinHeight <<
377
+ "SurfaceFormat " << std::setw(11) << strOutputFormats << std::endl;
378
+ }
379
+
380
+ std::cout << std::endl;
381
+
382
+ ck(cuCtxDestroy(cuContext));
383
+ }
384
+ exit(0);
385
+ }
video_codec_sdk/Samples/AppEncode/AppEncCuda/AppEncCuda.cpp ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2017-2024 NVIDIA Corporation. All rights reserved.
3
+ *
4
+ * Please refer to the NVIDIA end user license agreement (EULA) associated
5
+ * with this source code for terms and conditions that govern your use of
6
+ * this software. Any use, reproduction, disclosure, or distribution of
7
+ * this software and related documentation outside the terms of the EULA
8
+ * is strictly prohibited.
9
+ *
10
+ */
11
+
12
+ /**
13
+ * This sample application illustrates encoding of frames in CUDA device buffers.
14
+ * The application reads the image data from file and loads it to CUDA input
15
+ * buffers obtained from the encoder using NvEncoder::GetNextInputFrame().
16
+ * The encoder subsequently maps the CUDA buffers for encoder using NvEncodeAPI
17
+ * and submits them to NVENC hardware for encoding as part of EncodeFrame() function.
18
+ * The NVENC hardware output is written in system memory for this case.
19
+ *
20
+ * This sample application also illustrates the use of video memory buffer allocated
21
+ * by the application to get the NVENC hardware output. This feature can be used
22
+ * for H264 ME-only mode, H264 encode and HEVC encode. This application copies the NVENC output
23
+ * from video memory buffer to host memory buffer in order to dump to a file, but this
24
+ * is not needed if application choose to use it in some other way.
25
+ *
26
+ * Since, encoding may involve CUDA pre-processing on the input and post-processing on
27
+ * output, use of CUDA streams is also illustrated to pipeline the CUDA pre-processing
28
+ * and post-processing tasks, for output in video memory case.
29
+ *
30
+ * CUDA streams can be used for H.264 ME-only, HEVC ME-only, H264 encode, HEVC encode and AV1 encode.
31
+ */
32
+
33
+ #include <fstream>
34
+ #include <iostream>
35
+ #include <memory>
36
+ #include <cuda.h>
37
+ #include "../Utils/NvCodecUtils.h"
38
+ #include "NvEncoder/NvEncoderCuda.h"
39
+ #include "NvEncoder/NvEncoderOutputInVidMemCuda.h"
40
+ #include "../Utils/Logger.h"
41
+ #include "../Utils/NvEncoderCLIOptions.h"
42
+ #include "../Common/AppEncUtils.h"
43
+
44
+ simplelogger::Logger *logger = simplelogger::LoggerFactory::CreateConsoleLogger();
45
+
46
+ // This class allocates CUStream.
47
+ // It also sets the input and output CUDA stream in the driver, which will be used for pipelining
48
+ // pre and post processing CUDA tasks
49
+ class NvCUStream
50
+ {
51
+ public:
52
+ NvCUStream(CUcontext cuDevice, int cuStreamType, std::unique_ptr<NvEncoderOutputInVidMemCuda> &pEnc)
53
+ {
54
+ device = cuDevice;
55
+ CUDA_DRVAPI_CALL(cuCtxPushCurrent(device));
56
+
57
+ // Create CUDA streams
58
+ if (cuStreamType == 1)
59
+ {
60
+ ck(cuStreamCreate(&inputStream, CU_STREAM_DEFAULT));
61
+ outputStream = inputStream;
62
+ }
63
+ else if (cuStreamType == 2)
64
+ {
65
+ ck(cuStreamCreate(&inputStream, CU_STREAM_DEFAULT));
66
+ ck(cuStreamCreate(&outputStream, CU_STREAM_DEFAULT));
67
+ }
68
+
69
+ CUDA_DRVAPI_CALL(cuCtxPopCurrent(NULL));
70
+
71
+ // Set input and output CUDA streams in driver
72
+ pEnc->SetIOCudaStreams((NV_ENC_CUSTREAM_PTR)&inputStream, (NV_ENC_CUSTREAM_PTR)&outputStream);
73
+ }
74
+
75
+ ~NvCUStream()
76
+ {
77
+ ck(cuCtxPushCurrent(device));
78
+
79
+ if (inputStream == outputStream)
80
+ {
81
+ if (inputStream != NULL)
82
+ ck(cuStreamDestroy(inputStream));
83
+ }
84
+ else
85
+ {
86
+ if (inputStream != NULL)
87
+ ck(cuStreamDestroy(inputStream));
88
+
89
+ if (outputStream != NULL)
90
+ ck(cuStreamDestroy(outputStream));
91
+ }
92
+
93
+ ck(cuCtxPopCurrent(NULL));
94
+ }
95
+
96
+ CUstream GetOutputCUStream() { return outputStream; };
97
+ CUstream GetInputCUStream() { return inputStream; };
98
+
99
+ private:
100
+ CUcontext device;
101
+ CUstream inputStream = NULL, outputStream = NULL;
102
+ };
103
+
104
+ // This class computes CRC of encode frame using CUDA kernel
105
+ class CRC
106
+ {
107
+ public:
108
+ CRC(CUcontext cuDevice, uint32_t bufferSize)
109
+ {
110
+ device = cuDevice;
111
+
112
+ ck(cuCtxPushCurrent(device));
113
+
114
+ // Allocate video memory buffer to store CRC of encoded frame
115
+ ck(cuMemAlloc(&crcVidMem, bufferSize));
116
+
117
+ ck(cuCtxPopCurrent(NULL));
118
+ }
119
+
120
+ ~CRC()
121
+ {
122
+ ck(cuCtxPushCurrent(device));
123
+
124
+ ck(cuMemFree(crcVidMem));
125
+
126
+ ck(cuCtxPopCurrent(NULL));
127
+ }
128
+
129
+ void GetCRC(NV_ENC_OUTPUT_PTR pVideoMemBfr, CUstream outputStream)
130
+ {
131
+ ComputeCRC((uint8_t *)pVideoMemBfr, (uint32_t *)crcVidMem, outputStream);
132
+ }
133
+
134
+ CUdeviceptr GetCRCVidMemPtr() { return crcVidMem; };
135
+
136
+ private:
137
+ CUcontext device;
138
+ CUdeviceptr crcVidMem = 0;
139
+ };
140
+
141
+ // This class dumps the output - CRC and encoded stream, to a file.
142
+ // Output is first copied to host buffer and then dumped to a file.
143
+ class DumpVidMemOutput
144
+ {
145
+ public:
146
+ DumpVidMemOutput(CUcontext cuDevice, uint32_t size, char *outFilePath, bool bUseCUStream)
147
+ {
148
+ device = cuDevice;
149
+ bfrSize = size;
150
+ bCRC = bUseCUStream;
151
+
152
+ ck(cuCtxPushCurrent(device));
153
+
154
+ // Allocate host memory buffer to copy encoded output and CRC
155
+ ck(cuMemAllocHost((void **)&pHostMemEncOp, (bfrSize + (bCRC ? 4 : 0))));
156
+
157
+ ck(cuCtxPopCurrent(NULL));
158
+
159
+ // Open file to dump CRC
160
+ if (bCRC)
161
+ {
162
+ crcFile = std::string(outFilePath) + "_crc.txt";
163
+ fpCRCOut.open(crcFile, std::ios::out);
164
+ pHostMemCRC = (uint32_t *)((uint8_t *)pHostMemEncOp + bfrSize);
165
+ }
166
+ }
167
+
168
+ ~DumpVidMemOutput()
169
+ {
170
+ ck(cuCtxPushCurrent(device));
171
+
172
+ ck(cuMemFreeHost(pHostMemEncOp));
173
+
174
+ ck(cuCtxPopCurrent(NULL));
175
+
176
+ if (bCRC)
177
+ {
178
+ fpCRCOut.close();
179
+ std::cout << "CRC saved in file: " << crcFile << std::endl;
180
+ }
181
+ }
182
+
183
+ void DumpOutputToFile(CUdeviceptr pEncFrameBfr, CUdeviceptr pCRCBfr, std::ofstream &fpOut, uint32_t nFrame, bool &bWriteIVFFileHeader, NV_ENC_INITIALIZE_PARAMS &pInitializeParams)
184
+ {
185
+ ck(cuCtxPushCurrent(device));
186
+
187
+ // Copy encoded frame from video memory buffer to host memory buffer
188
+ ck(cuMemcpyDtoH(pHostMemEncOp, pEncFrameBfr, bfrSize));
189
+
190
+ // Copy encoded frame CRC from video memory buffer to host memory buffer
191
+ if (bCRC)
192
+ {
193
+ ck(cuMemcpyDtoH(pHostMemCRC, pCRCBfr, 4));
194
+ }
195
+
196
+ ck(cuCtxPopCurrent(NULL));
197
+
198
+ // Write encoded bitstream in file
199
+ uint32_t offset = sizeof(NV_ENC_ENCODE_OUT_PARAMS);
200
+ uint32_t bitstream_size = ((NV_ENC_ENCODE_OUT_PARAMS *)pHostMemEncOp)->bitstreamSizeInBytes;
201
+ uint8_t * ptr = pHostMemEncOp + offset;
202
+
203
+ IVFUtils iVFUtils;
204
+ int64_t pts = 0;
205
+ std::vector<uint8_t> vPacket;
206
+ if (pInitializeParams.encodeGUID == NV_ENC_CODEC_AV1_GUID)
207
+ {
208
+ if (bWriteIVFFileHeader)
209
+ {
210
+ iVFUtils.WriteFileHeader(vPacket, MAKE_FOURCC('A', 'V', '0', '1'), pInitializeParams.encodeWidth, pInitializeParams.encodeHeight, pInitializeParams.frameRateNum, pInitializeParams.frameRateDen, 0xFFFF);
211
+ fpOut.write(reinterpret_cast<char*>(vPacket.data()), vPacket.size());
212
+ bWriteIVFFileHeader = false;
213
+ vPacket.clear();
214
+ }
215
+ iVFUtils.WriteFrameHeader(vPacket, bitstream_size, pts);
216
+ fpOut.write(reinterpret_cast<char*>(vPacket.data()), vPacket.size());
217
+ }
218
+
219
+ fpOut.write((const char *)ptr, bitstream_size);
220
+
221
+ // Write CRC in file
222
+ if (bCRC)
223
+ {
224
+ if (!nFrame)
225
+ {
226
+ fpCRCOut << "Frame num" << std::setw(10) << "CRC" << std::endl;
227
+ }
228
+ fpCRCOut << std::dec << std::setfill(' ') << std::setw(5) << nFrame << " ";
229
+ fpCRCOut << std::hex << std::setfill('0') << std::setw(8) << *pHostMemCRC << std::endl;
230
+ }
231
+ }
232
+ private:
233
+ CUcontext device;
234
+ uint32_t bfrSize;
235
+ uint8_t *pHostMemEncOp = NULL;
236
+ uint32_t *pHostMemCRC = NULL;
237
+ bool bCRC;
238
+ std::string crcFile;
239
+ std::ofstream fpCRCOut;
240
+ };
241
+
242
+ void ShowEncoderBriefHelp()
243
+ {
244
+ std::ostringstream oss;
245
+ oss << "NVIDIA Video Encoder AppEncCuda Sample Application\n";
246
+ oss << "============================================\n\n";
247
+
248
+ oss << "Usage: AppEncCuda -i <input_file> [options]\n\n";
249
+
250
+ // Brief table of core arguments
251
+ oss << "Common Arguments:\n";
252
+ oss << std::left << std::setw(25) << "Argument"
253
+ << std::setw(12) << "Type"
254
+ << "Default Value\n";
255
+ oss << std::string(50, '-') << "\n";
256
+
257
+ oss << std::left << std::setw(25) << "-i <path>"
258
+ << std::setw(12) << "Required"
259
+ << "N/A\n";
260
+ oss << std::left << std::setw(25) << "-o <path>"
261
+ << std::setw(12) << "Optional"
262
+ << "codec-based (out.h264/hevc/av1)\n";
263
+ oss << std::left << std::setw(25) << "-s <WxH>"
264
+ << std::setw(12) << "Required"
265
+ << "N/A\n";
266
+ oss << std::left << std::setw(25) << "-if <format>"
267
+ << std::setw(12) << "Optional"
268
+ << "iyuv\n";
269
+ oss << std::left << std::setw(25) << "-gpu <n>"
270
+ << std::setw(12) << "Optional"
271
+ << "0\n";
272
+
273
+ oss << "\nFor detailed help, use -A/--advanced-options\n";
274
+ oss << "To view encoder capabilities, use -ec/--encode-caps\n";
275
+ std::cout << oss.str();
276
+ exit(0);
277
+ }
278
+
279
+ void ShowEncoderDetailedHelp()
280
+ {
281
+ std::ostringstream oss;
282
+ oss << "NVIDIA Video Encoder AppEncCuda Sample Application - Detailed Help\n";
283
+ oss << "=======================================================\n\n";
284
+
285
+ oss << "Usage: AppEncCuda -i <input_file> [options]\n\n";
286
+
287
+ // Full table of all arguments
288
+ oss << "All Arguments:\n";
289
+ oss << std::left << std::setw(25) << "Argument"
290
+ << std::setw(12) << "Type"
291
+ << std::setw(20) << "Default Value"
292
+ << "Example\n";
293
+ oss << std::string(80, '-') << "\n";
294
+
295
+ // Required arguments
296
+ oss << std::left << std::setw(25) << "-i <path>"
297
+ << std::setw(12) << "Required"
298
+ << std::setw(20) << "N/A"
299
+ << "-i input.yuv\n";
300
+ oss << std::left << std::setw(25) << "-s <WxH>"
301
+ << std::setw(12) << "Required"
302
+ << std::setw(20) << "N/A"
303
+ << "-s 1920x1080\n";
304
+
305
+ // Optional arguments
306
+ oss << std::left << std::setw(25) << "-o <path>"
307
+ << std::setw(12) << "Optional"
308
+ << std::setw(20) << "codec-based"
309
+ << "-o output.h264\n";
310
+ oss << std::left << std::setw(25) << "-if <format>"
311
+ << std::setw(12) << "Optional"
312
+ << std::setw(20) << "iyuv"
313
+ << "-if yuv444\n";
314
+ oss << std::left << std::setw(25) << "-gpu <n>"
315
+ << std::setw(12) << "Optional"
316
+ << std::setw(20) << "0"
317
+ << "-gpu 1\n";
318
+ oss << std::left << std::setw(25) << "-outputInVidMem <n>"
319
+ << std::setw(12) << "Optional"
320
+ << std::setw(20) << "0"
321
+ << "-outputInVidMem 1\n";
322
+ oss << std::left << std::setw(25) << "-cuStreamType <n>"
323
+ << std::setw(12) << "Optional"
324
+ << std::setw(20) << "disabled"
325
+ << "-cuStreamType 1\n";
326
+
327
+ // Detailed descriptions
328
+ oss << "\nDetailed Descriptions:\n";
329
+ oss << "-------------------\n";
330
+ oss << std::left << std::setw(25) << "-i" << ": Input file path\n";
331
+ oss << std::left << std::setw(25) << "-o" << ": Output file path\n";
332
+ oss << std::left << std::setw(25) << "-s" << ": Input resolution in WxH format\n";
333
+ oss << std::left << std::setw(25) << "-if" << ": Input format (iyuv/nv12/nv16/yuv444/p010/p210/yuv444p16/bgra/bgra10/ayuv/abgr/abgr10)\n";
334
+ oss << std::left << std::setw(25) << "-gpu" << ": Ordinal of GPU to use\n";
335
+ oss << std::left << std::setw(25) << "-outputInVidMem" << ": Enable output in Video Memory (0/1)\n";
336
+ oss << std::left << std::setw(25) << "-cuStreamType" << ": CUDA stream type for pre/post processing (0: NULL, 1: SAME, 2: DIFFERENT)\n";
337
+ oss << std::left << std::setw(25) << "-h/--help" << ": Print basic usage information\n";
338
+ oss << std::left << std::setw(25) << "-A/--advanced-options" << ": Print detailed usage information\n";
339
+ oss << std::left << std::setw(25) << "-ec/--encode-caps" << ": Print encode capabilities of GPU\n";
340
+
341
+ // Important notes
342
+ oss << "\nNotes:\n";
343
+ oss << "------\n";
344
+ oss << "* When outputInVidMem is enabled, CRC of encoded frames will be computed\n";
345
+ oss << " and dumped to file with suffix '_crc.txt' added to output file\n";
346
+ oss << "* Width and height must be specified for encoding\n";
347
+ oss << std::endl;
348
+
349
+ oss << NvEncoderInitParam().GetHelpMessage(false, false, false, false, true, false, false, false) << std::endl;
350
+ oss << "\nTo view encode capabilities, use -ec/--encode-caps\n";
351
+ std::cout << oss.str();
352
+ exit(0);
353
+ }
354
+
355
+ void ShowHelpAndExit(const char *szBadOption = NULL)
356
+ {
357
+ if (szBadOption)
358
+ {
359
+ std::ostringstream oss;
360
+ oss << "Error parsing \"" << szBadOption << "\"\n";
361
+ oss << "Use -h/--help for basic usage or -A/--advanced-options for detailed information\n";
362
+ throw std::invalid_argument(oss.str());
363
+ }
364
+ }
365
+
366
+ void ParseCommandLine(int argc, char *argv[], char *szInputFileName, int &nWidth, int &nHeight,
367
+ NV_ENC_BUFFER_FORMAT &eFormat, char *szOutputFileName, NvEncoderInitParam &initParam, int &iGpu,
368
+ bool &bOutputInVidMem, int32_t &cuStreamType)
369
+ {
370
+ std::ostringstream oss;
371
+ int i;
372
+
373
+ if (argc == 1) {
374
+ std::cout << "No Arguments provided! Please refer to the following for options:\n";
375
+ ShowEncoderBriefHelp();
376
+ }
377
+
378
+ for (i = 1; i < argc; i++)
379
+ {
380
+ if (!_stricmp(argv[i], "-h") || !_stricmp(argv[i], "--help")) {
381
+ ShowEncoderBriefHelp();
382
+ }
383
+ if (!_stricmp(argv[i], "-A") || !_stricmp(argv[i], "--advanced-options")) {
384
+ ShowEncoderDetailedHelp();
385
+ }
386
+ if (!_stricmp(argv[i], "-ec") || !_stricmp(argv[i], "--encode-caps")) {
387
+ ShowEncoderCapability();
388
+ }
389
+ if (!_stricmp(argv[i], "-i"))
390
+ {
391
+ if (++i == argc)
392
+ {
393
+ ShowHelpAndExit("-i");
394
+ }
395
+ sprintf(szInputFileName, "%s", argv[i]);
396
+ continue;
397
+ }
398
+ if (!_stricmp(argv[i], "-o"))
399
+ {
400
+ if (++i == argc)
401
+ {
402
+ ShowHelpAndExit("-o");
403
+ }
404
+ sprintf(szOutputFileName, "%s", argv[i]);
405
+ continue;
406
+ }
407
+ if (!_stricmp(argv[i], "-s"))
408
+ {
409
+ if (++i == argc || 2 != sscanf(argv[i], "%dx%d", &nWidth, &nHeight))
410
+ {
411
+ ShowHelpAndExit("-s");
412
+ }
413
+ continue;
414
+ }
415
+ std::vector<std::string> vszFileFormatName =
416
+ {
417
+ "iyuv", "nv12", "yv12", "nv16", "yuv444", "p010", "p210", "yuv444p16", "bgra", "bgra10", "ayuv", "abgr", "abgr10"
418
+ };
419
+ NV_ENC_BUFFER_FORMAT aFormat[] =
420
+ {
421
+ NV_ENC_BUFFER_FORMAT_IYUV,
422
+ NV_ENC_BUFFER_FORMAT_NV12,
423
+ NV_ENC_BUFFER_FORMAT_YV12,
424
+ NV_ENC_BUFFER_FORMAT_NV16,
425
+ NV_ENC_BUFFER_FORMAT_YUV444,
426
+ NV_ENC_BUFFER_FORMAT_YUV420_10BIT,
427
+ NV_ENC_BUFFER_FORMAT_P210,
428
+ NV_ENC_BUFFER_FORMAT_YUV444_10BIT,
429
+ NV_ENC_BUFFER_FORMAT_ARGB,
430
+ NV_ENC_BUFFER_FORMAT_ARGB10,
431
+ NV_ENC_BUFFER_FORMAT_AYUV,
432
+ NV_ENC_BUFFER_FORMAT_ABGR,
433
+ NV_ENC_BUFFER_FORMAT_ABGR10,
434
+ };
435
+ if (!_stricmp(argv[i], "-if"))
436
+ {
437
+ if (++i == argc) {
438
+ ShowHelpAndExit("-if");
439
+ }
440
+ auto it = std::find(vszFileFormatName.begin(), vszFileFormatName.end(), argv[i]);
441
+ if (it == vszFileFormatName.end())
442
+ {
443
+ ShowHelpAndExit("-if");
444
+ }
445
+ eFormat = aFormat[it - vszFileFormatName.begin()];
446
+ continue;
447
+ }
448
+ if (!_stricmp(argv[i], "-gpu"))
449
+ {
450
+ if (++i == argc)
451
+ {
452
+ ShowHelpAndExit("-gpu");
453
+ }
454
+ iGpu = atoi(argv[i]);
455
+ continue;
456
+ }
457
+ if (!_stricmp(argv[i], "-outputInVidMem"))
458
+ {
459
+ if (++i == argc)
460
+ {
461
+ ShowHelpAndExit("-outputInVidMem");
462
+ }
463
+ bOutputInVidMem = (atoi(argv[i]) != 0) ? true : false;
464
+ continue;
465
+ }
466
+ if (!_stricmp(argv[i], "-cuStreamType"))
467
+ {
468
+ if (++i == argc)
469
+ {
470
+ ShowHelpAndExit("-cuStreamType");
471
+ }
472
+ cuStreamType = atoi(argv[i]);
473
+ continue;
474
+ }
475
+
476
+ // Regard as encoder parameter
477
+ if (argv[i][0] != '-')
478
+ {
479
+ ShowHelpAndExit(argv[i]);
480
+ }
481
+ oss << argv[i] << " ";
482
+ while (i + 1 < argc && argv[i + 1][0] != '-')
483
+ {
484
+ oss << argv[++i] << " ";
485
+ }
486
+ }
487
+ initParam = NvEncoderInitParam(oss.str().c_str());
488
+ }
489
+
490
+ template<class EncoderClass>
491
+ void InitializeEncoder(EncoderClass &pEnc, NvEncoderInitParam encodeCLIOptions, NV_ENC_BUFFER_FORMAT eFormat)
492
+ {
493
+ NV_ENC_INITIALIZE_PARAMS initializeParams = { NV_ENC_INITIALIZE_PARAMS_VER };
494
+ NV_ENC_CONFIG encodeConfig = { NV_ENC_CONFIG_VER };
495
+
496
+ initializeParams.encodeConfig = &encodeConfig;
497
+ pEnc->CreateDefaultEncoderParams(&initializeParams, encodeCLIOptions.GetEncodeGUID(), encodeCLIOptions.GetPresetGUID(), encodeCLIOptions.GetTuningInfo());
498
+ encodeCLIOptions.SetInitParams(&initializeParams, eFormat);
499
+
500
+ pEnc->CreateEncoder(&initializeParams);
501
+ }
502
+
503
+ void EncodeCuda(int nWidth, int nHeight, NV_ENC_BUFFER_FORMAT eFormat, NvEncoderInitParam encodeCLIOptions, CUcontext cuContext, std::ifstream &fpIn, std::ofstream &fpOut)
504
+ {
505
+ std::unique_ptr<NvEncoderCuda> pEnc(new NvEncoderCuda(cuContext, nWidth, nHeight, eFormat));
506
+
507
+ InitializeEncoder(pEnc, encodeCLIOptions, eFormat);
508
+
509
+ int nFrameSize = pEnc->GetFrameSize();
510
+
511
+ uint32_t enableMVHEVC = pEnc->IsMVHEVC();
512
+ int nTotalFrameSize = nFrameSize;
513
+ if (enableMVHEVC)
514
+ {
515
+ nTotalFrameSize = nTotalFrameSize << 1;
516
+ }
517
+ int viewID = 0;
518
+ std::streamsize nRead = 0;
519
+
520
+ std::unique_ptr<uint8_t[]> pHostFrame(new uint8_t[nTotalFrameSize]);
521
+ int nFrame = 0;
522
+ while (true)
523
+ {
524
+ if (viewID == 0)
525
+ {
526
+ // Load the next frame or two frames from disk depending upon enableMVHEVC
527
+ nRead = fpIn.read(reinterpret_cast<char*>(pHostFrame.get()), nTotalFrameSize).gcount();
528
+ }
529
+ // For receiving encoded packets
530
+ std::vector<NvEncOutputFrame> vPacket;
531
+ if (nRead == nTotalFrameSize)
532
+ {
533
+ const NvEncInputFrame* encoderInputFrame = pEnc->GetNextInputFrame();
534
+ NvEncoderCuda::CopyToDeviceFrame(cuContext,
535
+ pHostFrame.get() + viewID * nFrameSize, 0,
536
+ (CUdeviceptr)encoderInputFrame->inputPtr,
537
+ (int)encoderInputFrame->pitch,
538
+ pEnc->GetEncodeWidth(),
539
+ pEnc->GetEncodeHeight(),
540
+ CU_MEMORYTYPE_HOST,
541
+ encoderInputFrame->bufferFormat,
542
+ encoderInputFrame->chromaOffsets,
543
+ encoderInputFrame->numChromaPlanes);
544
+
545
+ pEnc->EncodeFrame(vPacket);
546
+ }
547
+ else
548
+ {
549
+ // If we couldn't read both frames, signal the end of encoding
550
+ pEnc->EndEncode(vPacket);
551
+ }
552
+ nFrame += (int)vPacket.size();
553
+ for (const NvEncOutputFrame &packet : vPacket)
554
+ {
555
+ // For each encoded packet
556
+ fpOut.write(reinterpret_cast<const char*>(packet.frame.data()), packet.frame.size());
557
+ }
558
+
559
+ if (nRead != nTotalFrameSize) break;
560
+ if (enableMVHEVC)
561
+ {
562
+ viewID = viewID ^ 1;
563
+ }
564
+ }
565
+ pEnc->DestroyEncoder();
566
+
567
+ std::cout << "Total frames encoded: " << nFrame << std::endl;
568
+ }
569
+
570
+ void EncodeCudaOpInVidMem(int nWidth, int nHeight, NV_ENC_BUFFER_FORMAT eFormat, NvEncoderInitParam encodeCLIOptions, CUcontext cuContext, std::ifstream &fpIn, std::ofstream &fpOut, char *outFilePath, int32_t cuStreamType)
571
+ {
572
+ std::unique_ptr<NvEncoderOutputInVidMemCuda> pEnc(new NvEncoderOutputInVidMemCuda(cuContext, nWidth, nHeight, eFormat));
573
+
574
+ InitializeEncoder(pEnc, encodeCLIOptions, eFormat);
575
+
576
+ int nFrameSize = pEnc->GetFrameSize();
577
+ bool bUseCUStream = cuStreamType != -1 ? true : false;
578
+
579
+ NV_ENC_INITIALIZE_PARAMS initializeParams = pEnc->GetinitializeParams();
580
+ bool bWriteIVFFileHeader = true;
581
+
582
+ std::unique_ptr<CRC> pCRC;
583
+ std::unique_ptr<NvCUStream> pCUStream;
584
+ if (bUseCUStream)
585
+ {
586
+ // Allocate CUDA streams
587
+ pCUStream.reset(new NvCUStream(reinterpret_cast<CUcontext>(pEnc->GetDevice()), cuStreamType, pEnc));
588
+
589
+ // When CUDA streams are used, the encoded frame's CRC is computed using cuda kernel
590
+ pCRC.reset(new CRC(reinterpret_cast<CUcontext>(pEnc->GetDevice()), pEnc->GetOutputBufferSize()));
591
+ }
592
+
593
+ // For dumping output - encoded frame and CRC, to a file
594
+ std::unique_ptr<DumpVidMemOutput> pDumpVidMemOutput(new DumpVidMemOutput(reinterpret_cast<CUcontext>(pEnc->GetDevice()), pEnc->GetOutputBufferSize(), outFilePath, bUseCUStream));
595
+
596
+ std::unique_ptr<uint8_t[]> pHostFrame(new uint8_t[nFrameSize]);
597
+ int nFrame = 0;
598
+
599
+ // Encoding loop
600
+ while (true)
601
+ {
602
+ // Load the next frame from disk
603
+ std::streamsize nRead = fpIn.read(reinterpret_cast<char*>(pHostFrame.get()), nFrameSize).gcount();
604
+ // For receiving encoded packets
605
+ std::vector<NV_ENC_OUTPUT_PTR>pVideoMemBfr;
606
+
607
+ if (nRead == nFrameSize)
608
+ {
609
+ const NvEncInputFrame* encoderInputFrame = pEnc->GetNextInputFrame();
610
+ NvEncoderCuda::CopyToDeviceFrame(cuContext, pHostFrame.get(), 0, (CUdeviceptr)encoderInputFrame->inputPtr,
611
+ (int)encoderInputFrame->pitch,
612
+ pEnc->GetEncodeWidth(),
613
+ pEnc->GetEncodeHeight(),
614
+ CU_MEMORYTYPE_HOST,
615
+ encoderInputFrame->bufferFormat,
616
+ encoderInputFrame->chromaOffsets,
617
+ encoderInputFrame->numChromaPlanes,
618
+ false,
619
+ bUseCUStream ? pCUStream->GetInputCUStream() : NULL);
620
+
621
+ pEnc->EncodeFrame(pVideoMemBfr);
622
+ }
623
+ else
624
+ {
625
+ pEnc->EndEncode(pVideoMemBfr);
626
+ }
627
+
628
+ for (uint32_t i = 0; i < pVideoMemBfr.size(); ++i)
629
+ {
630
+ if (bUseCUStream)
631
+ {
632
+ // Compute CRC of encoded stream
633
+ pCRC->GetCRC(pVideoMemBfr[i], pCUStream->GetOutputCUStream());
634
+ }
635
+
636
+ pDumpVidMemOutput->DumpOutputToFile((CUdeviceptr)(pVideoMemBfr[i]), bUseCUStream ? pCRC->GetCRCVidMemPtr() : 0, fpOut, nFrame, bWriteIVFFileHeader, initializeParams);
637
+
638
+ nFrame++;
639
+ }
640
+
641
+ if (nRead != nFrameSize) break;
642
+ }
643
+
644
+ pEnc->DestroyEncoder();
645
+
646
+ std::cout << "Total frames encoded: " << nFrame << std::endl;
647
+ }
648
+
649
+ int main(int argc, char **argv)
650
+ {
651
+ char szInFilePath[256] = "",
652
+ szOutFilePath[256] = "";
653
+ int nWidth = 0, nHeight = 0;
654
+ NV_ENC_BUFFER_FORMAT eFormat = NV_ENC_BUFFER_FORMAT_IYUV;
655
+ int iGpu = 0;
656
+ try
657
+ {
658
+ NvEncoderInitParam encodeCLIOptions;
659
+ int cuStreamType = -1;
660
+ bool bOutputInVideoMem = false;
661
+ ParseCommandLine(argc, argv, szInFilePath, nWidth, nHeight, eFormat, szOutFilePath, encodeCLIOptions, iGpu,
662
+ bOutputInVideoMem, cuStreamType);
663
+
664
+ CheckInputFile(szInFilePath);
665
+ ValidateResolution(nWidth, nHeight);
666
+
667
+ if (!*szOutFilePath)
668
+ {
669
+ sprintf(szOutFilePath, encodeCLIOptions.IsCodecH264() ? "out.h264" : encodeCLIOptions.IsCodecHEVC() ? "out.hevc" : "out.av1");
670
+ }
671
+
672
+ ck(cuInit(0));
673
+ int nGpu = 0;
674
+ ck(cuDeviceGetCount(&nGpu));
675
+ if (iGpu < 0 || iGpu >= nGpu)
676
+ {
677
+ std::cout << "GPU ordinal out of range. Should be within [" << 0 << ", " << nGpu - 1 << "]" << std::endl;
678
+ return 1;
679
+ }
680
+ CUdevice cuDevice = 0;
681
+ ck(cuDeviceGet(&cuDevice, iGpu));
682
+ char szDeviceName[80];
683
+ ck(cuDeviceGetName(szDeviceName, sizeof(szDeviceName), cuDevice));
684
+ std::cout << "GPU in use: " << szDeviceName << std::endl;
685
+ CUcontext cuContext = NULL;
686
+ ck(NVCODEC_CUDA_CTX_CREATE(&cuContext, 0, cuDevice));
687
+
688
+ // Open input file
689
+ std::ifstream fpIn(szInFilePath, std::ifstream::in | std::ifstream::binary);
690
+ if (!fpIn)
691
+ {
692
+ std::ostringstream err;
693
+ err << "Unable to open input file: " << szInFilePath << std::endl;
694
+ throw std::invalid_argument(err.str());
695
+ }
696
+
697
+ // Open output file
698
+ std::ofstream fpOut(szOutFilePath, std::ios::out | std::ios::binary);
699
+ if (!fpOut)
700
+ {
701
+ std::ostringstream err;
702
+ err << "Unable to open output file: " << szOutFilePath << std::endl;
703
+ throw std::invalid_argument(err.str());
704
+ }
705
+
706
+ // Encode
707
+ if (bOutputInVideoMem)
708
+ {
709
+ EncodeCudaOpInVidMem(nWidth, nHeight, eFormat, encodeCLIOptions, cuContext, fpIn, fpOut, szOutFilePath, cuStreamType);
710
+ }
711
+ else
712
+ {
713
+ EncodeCuda(nWidth, nHeight, eFormat, encodeCLIOptions, cuContext, fpIn, fpOut);
714
+ }
715
+
716
+ fpOut.close();
717
+ fpIn.close();
718
+
719
+ std::cout << "Bitstream saved in file " << szOutFilePath << std::endl;
720
+ }
721
+ catch (const std::exception &ex)
722
+ {
723
+ std::cout << ex.what();
724
+ return 1;
725
+ }
726
+ return 0;
727
+ }