2 * HW decode acceleration through NVDEC
4 * Copyright (c) 2016 Anton Khirnov
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "libavutil/common.h"
26 #include "libavutil/error.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/hwcontext_cuda_internal.h"
29 #include "libavutil/pixdesc.h"
30 #include "libavutil/pixfmt.h"
37 typedef struct NVDECDecoder {
38 CUvideodecoder decoder;
40 AVBufferRef *hw_device_ref;
47 typedef struct NVDECFramePool {
48 unsigned int dpb_size;
49 unsigned int nb_allocated;
52 static int map_avcodec_id(enum AVCodecID id)
55 case AV_CODEC_ID_H264: return cudaVideoCodec_H264;
56 case AV_CODEC_ID_HEVC: return cudaVideoCodec_HEVC;
57 case AV_CODEC_ID_VP9: return cudaVideoCodec_VP9;
62 static int map_chroma_format(enum AVPixelFormat pix_fmt)
64 int shift_h = 0, shift_v = 0;
66 av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
68 if (shift_h == 1 && shift_v == 1)
69 return cudaVideoChromaFormat_420;
70 else if (shift_h == 1 && shift_v == 0)
71 return cudaVideoChromaFormat_422;
72 else if (shift_h == 0 && shift_v == 0)
73 return cudaVideoChromaFormat_444;
78 static int nvdec_test_capabilities(NVDECDecoder *decoder,
79 CUVIDDECODECREATEINFO *params, void *logctx)
82 CUVIDDECODECAPS caps = { 0 };
84 caps.eCodecType = params->CodecType;
85 caps.eChromaFormat = params->ChromaFormat;
86 caps.nBitDepthMinus8 = params->bitDepthMinus8;
88 err = decoder->cvdl->cuvidGetDecoderCaps(&caps);
89 if (err != CUDA_SUCCESS) {
90 av_log(logctx, AV_LOG_ERROR, "Failed querying decoder capabilities\n");
91 return AVERROR_UNKNOWN;
94 av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
95 av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
96 caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
97 av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
98 caps.nMinWidth, caps.nMaxWidth);
99 av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
100 caps.nMinHeight, caps.nMaxHeight);
102 if (!caps.bIsSupported) {
103 av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
104 return AVERROR(EINVAL);
107 if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
108 av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
109 (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
110 return AVERROR(EINVAL);
113 if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
114 av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
115 (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
116 return AVERROR(EINVAL);
119 if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
120 av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
121 (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
122 return AVERROR(EINVAL);
128 static void nvdec_decoder_free(void *opaque, uint8_t *data)
130 NVDECDecoder *decoder = (NVDECDecoder*)data;
132 if (decoder->decoder)
133 decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
135 av_buffer_unref(&decoder->hw_device_ref);
137 cuvid_free_functions(&decoder->cvdl);
142 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
143 CUVIDDECODECREATEINFO *params, void *logctx)
145 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
146 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
148 AVBufferRef *decoder_ref;
149 NVDECDecoder *decoder;
155 decoder = av_mallocz(sizeof(*decoder));
157 return AVERROR(ENOMEM);
159 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
160 nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
163 return AVERROR(ENOMEM);
166 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
167 if (!decoder->hw_device_ref) {
168 ret = AVERROR(ENOMEM);
171 decoder->cuda_ctx = device_hwctx->cuda_ctx;
172 decoder->cudl = device_hwctx->internal->cuda_dl;
174 ret = cuvid_load_functions(&decoder->cvdl);
176 av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
180 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
181 if (err != CUDA_SUCCESS) {
182 ret = AVERROR_UNKNOWN;
186 ret = nvdec_test_capabilities(decoder, params, logctx);
188 decoder->cudl->cuCtxPopCurrent(&dummy);
192 err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
194 decoder->cudl->cuCtxPopCurrent(&dummy);
196 if (err != CUDA_SUCCESS) {
197 av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
198 ret = AVERROR_UNKNOWN;
206 av_buffer_unref(&decoder_ref);
210 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
212 NVDECFramePool *pool = opaque;
215 if (pool->nb_allocated >= pool->dpb_size)
218 ret = av_buffer_alloc(sizeof(unsigned int));
222 *(unsigned int*)ret->data = pool->nb_allocated++;
227 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
229 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
231 av_freep(&ctx->bitstream);
232 ctx->bitstream_len = 0;
233 ctx->bitstream_allocated = 0;
235 av_freep(&ctx->slice_offsets);
237 ctx->slice_offsets_allocated = 0;
239 av_buffer_unref(&ctx->decoder_ref);
240 av_buffer_pool_uninit(&ctx->decoder_pool);
245 int ff_nvdec_decode_init(AVCodecContext *avctx)
247 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
249 NVDECFramePool *pool;
250 AVHWFramesContext *frames_ctx;
251 const AVPixFmtDescriptor *sw_desc;
253 CUVIDDECODECREATEINFO params = { 0 };
255 int cuvid_codec_type, cuvid_chroma_format;
258 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
262 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
263 if (cuvid_codec_type < 0) {
264 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
268 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
269 if (cuvid_chroma_format < 0) {
270 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
271 return AVERROR(ENOSYS);
274 if (!avctx->hw_frames_ctx) {
275 ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_CUDA);
280 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
282 params.ulWidth = avctx->coded_width;
283 params.ulHeight = avctx->coded_height;
284 params.ulTargetWidth = avctx->coded_width;
285 params.ulTargetHeight = avctx->coded_height;
286 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
287 params.OutputFormat = params.bitDepthMinus8 ?
288 cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
289 params.CodecType = cuvid_codec_type;
290 params.ChromaFormat = cuvid_chroma_format;
291 params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
292 params.ulNumOutputSurfaces = 1;
294 ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
296 if (params.ulNumDecodeSurfaces > 32) {
297 av_log(avctx, AV_LOG_WARNING, "Using more than 32 (%d) decode surfaces might cause nvdec to fail.\n",
298 (int)params.ulNumDecodeSurfaces);
299 av_log(avctx, AV_LOG_WARNING, "Try lowering the amount of threads. Using %d right now.\n",
300 avctx->thread_count);
305 pool = av_mallocz(sizeof(*pool));
307 ret = AVERROR(ENOMEM);
310 pool->dpb_size = frames_ctx->initial_pool_size;
312 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
313 nvdec_decoder_frame_alloc, av_free);
314 if (!ctx->decoder_pool) {
315 ret = AVERROR(ENOMEM);
321 ff_nvdec_decode_uninit(avctx);
325 static void nvdec_fdd_priv_free(void *priv)
327 NVDECFrame *cf = priv;
332 av_buffer_unref(&cf->idx_ref);
333 av_buffer_unref(&cf->decoder_ref);
338 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
340 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
341 NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
342 NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
344 CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
350 unsigned int pitch, i;
351 unsigned int offset = 0;
354 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
355 if (err != CUDA_SUCCESS)
356 return AVERROR_UNKNOWN;
358 err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
360 if (err != CUDA_SUCCESS) {
361 av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
363 ret = AVERROR_UNKNOWN;
367 for (i = 0; frame->data[i]; i++) {
368 CUDA_MEMCPY2D cpy = {
369 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
370 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
372 .dstDevice = (CUdeviceptr)frame->data[i],
374 .dstPitch = frame->linesize[i],
376 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
377 .Height = frame->height >> (i ? 1 : 0),
380 err = decoder->cudl->cuMemcpy2D(&cpy);
381 if (err != CUDA_SUCCESS) {
382 av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
384 ret = AVERROR_UNKNOWN;
388 offset += cpy.Height;
392 decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
395 decoder->cudl->cuCtxPopCurrent(&dummy);
399 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
401 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
402 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
403 NVDECFrame *cf = NULL;
406 ctx->bitstream_len = 0;
409 if (fdd->hwaccel_priv)
412 cf = av_mallocz(sizeof(*cf));
414 return AVERROR(ENOMEM);
416 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
417 if (!cf->decoder_ref) {
418 ret = AVERROR(ENOMEM);
422 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
424 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
425 ret = AVERROR(ENOMEM);
428 cf->idx = *(unsigned int*)cf->idx_ref->data;
430 fdd->hwaccel_priv = cf;
431 fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
432 fdd->post_process = nvdec_retrieve_data;
436 nvdec_fdd_priv_free(cf);
441 int ff_nvdec_end_frame(AVCodecContext *avctx)
443 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
444 NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
445 CUVIDPICPARAMS *pp = &ctx->pic_params;
452 pp->nBitstreamDataLen = ctx->bitstream_len;
453 pp->pBitstreamData = ctx->bitstream;
454 pp->nNumSlices = ctx->nb_slices;
455 pp->pSliceDataOffsets = ctx->slice_offsets;
457 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
458 if (err != CUDA_SUCCESS)
459 return AVERROR_UNKNOWN;
461 err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
462 if (err != CUDA_SUCCESS) {
463 av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
465 ret = AVERROR_UNKNOWN;
470 decoder->cudl->cuCtxPopCurrent(&dummy);
475 int ff_nvdec_frame_params(AVCodecContext *avctx,
476 AVBufferRef *hw_frames_ctx,
479 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
480 const AVPixFmtDescriptor *sw_desc;
481 int cuvid_codec_type, cuvid_chroma_format;
483 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
487 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
488 if (cuvid_codec_type < 0) {
489 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
493 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
494 if (cuvid_chroma_format < 0) {
495 av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
496 return AVERROR(EINVAL);
499 frames_ctx->format = AV_PIX_FMT_CUDA;
500 frames_ctx->width = avctx->coded_width;
501 frames_ctx->height = avctx->coded_height;
502 frames_ctx->initial_pool_size = dpb_size;
504 switch (sw_desc->comp[0].depth) {
506 frames_ctx->sw_format = AV_PIX_FMT_NV12;
509 frames_ctx->sw_format = AV_PIX_FMT_P010;
512 frames_ctx->sw_format = AV_PIX_FMT_P016;
515 return AVERROR(EINVAL);