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_MPEG1VIDEO: return cudaVideoCodec_MPEG1;
58 case AV_CODEC_ID_MPEG2VIDEO: return cudaVideoCodec_MPEG2;
59 case AV_CODEC_ID_MPEG4: return cudaVideoCodec_MPEG4;
60 case AV_CODEC_ID_VC1: return cudaVideoCodec_VC1;
61 case AV_CODEC_ID_VP9: return cudaVideoCodec_VP9;
62 case AV_CODEC_ID_WMV3: return cudaVideoCodec_VC1;
67 static int map_chroma_format(enum AVPixelFormat pix_fmt)
69 int shift_h = 0, shift_v = 0;
71 av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
73 if (shift_h == 1 && shift_v == 1)
74 return cudaVideoChromaFormat_420;
75 else if (shift_h == 1 && shift_v == 0)
76 return cudaVideoChromaFormat_422;
77 else if (shift_h == 0 && shift_v == 0)
78 return cudaVideoChromaFormat_444;
83 static int nvdec_test_capabilities(NVDECDecoder *decoder,
84 CUVIDDECODECREATEINFO *params, void *logctx)
87 CUVIDDECODECAPS caps = { 0 };
89 caps.eCodecType = params->CodecType;
90 caps.eChromaFormat = params->ChromaFormat;
91 caps.nBitDepthMinus8 = params->bitDepthMinus8;
93 err = decoder->cvdl->cuvidGetDecoderCaps(&caps);
94 if (err != CUDA_SUCCESS) {
95 av_log(logctx, AV_LOG_ERROR, "Failed querying decoder capabilities\n");
96 return AVERROR_UNKNOWN;
99 av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
100 av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
101 caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
102 av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
103 caps.nMinWidth, caps.nMaxWidth);
104 av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
105 caps.nMinHeight, caps.nMaxHeight);
107 if (!caps.bIsSupported) {
108 av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
109 return AVERROR(EINVAL);
112 if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
113 av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
114 (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
115 return AVERROR(EINVAL);
118 if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
119 av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
120 (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
121 return AVERROR(EINVAL);
124 if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
125 av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
126 (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
127 return AVERROR(EINVAL);
133 static void nvdec_decoder_free(void *opaque, uint8_t *data)
135 NVDECDecoder *decoder = (NVDECDecoder*)data;
137 if (decoder->decoder)
138 decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
140 av_buffer_unref(&decoder->hw_device_ref);
142 cuvid_free_functions(&decoder->cvdl);
147 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
148 CUVIDDECODECREATEINFO *params, void *logctx)
150 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
151 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
153 AVBufferRef *decoder_ref;
154 NVDECDecoder *decoder;
160 decoder = av_mallocz(sizeof(*decoder));
162 return AVERROR(ENOMEM);
164 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
165 nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
168 return AVERROR(ENOMEM);
171 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
172 if (!decoder->hw_device_ref) {
173 ret = AVERROR(ENOMEM);
176 decoder->cuda_ctx = device_hwctx->cuda_ctx;
177 decoder->cudl = device_hwctx->internal->cuda_dl;
179 ret = cuvid_load_functions(&decoder->cvdl, logctx);
181 av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
185 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
186 if (err != CUDA_SUCCESS) {
187 ret = AVERROR_UNKNOWN;
191 ret = nvdec_test_capabilities(decoder, params, logctx);
193 decoder->cudl->cuCtxPopCurrent(&dummy);
197 err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
199 decoder->cudl->cuCtxPopCurrent(&dummy);
201 if (err != CUDA_SUCCESS) {
202 av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
203 ret = AVERROR_UNKNOWN;
211 av_buffer_unref(&decoder_ref);
215 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
217 NVDECFramePool *pool = opaque;
220 if (pool->nb_allocated >= pool->dpb_size)
223 ret = av_buffer_alloc(sizeof(unsigned int));
227 *(unsigned int*)ret->data = pool->nb_allocated++;
232 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
234 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
236 av_freep(&ctx->bitstream);
237 ctx->bitstream_len = 0;
238 ctx->bitstream_allocated = 0;
240 av_freep(&ctx->slice_offsets);
242 ctx->slice_offsets_allocated = 0;
244 av_buffer_unref(&ctx->decoder_ref);
245 av_buffer_pool_uninit(&ctx->decoder_pool);
250 int ff_nvdec_decode_init(AVCodecContext *avctx)
252 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
254 NVDECFramePool *pool;
255 AVHWFramesContext *frames_ctx;
256 const AVPixFmtDescriptor *sw_desc;
258 CUVIDDECODECREATEINFO params = { 0 };
260 int cuvid_codec_type, cuvid_chroma_format;
263 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
267 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
268 if (cuvid_codec_type < 0) {
269 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
273 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
274 if (cuvid_chroma_format < 0) {
275 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
276 return AVERROR(ENOSYS);
279 if (!avctx->hw_frames_ctx) {
280 ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_CUDA);
285 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
287 params.ulWidth = avctx->coded_width;
288 params.ulHeight = avctx->coded_height;
289 params.ulTargetWidth = avctx->coded_width;
290 params.ulTargetHeight = avctx->coded_height;
291 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
292 params.OutputFormat = params.bitDepthMinus8 ?
293 cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
294 params.CodecType = cuvid_codec_type;
295 params.ChromaFormat = cuvid_chroma_format;
296 params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
297 params.ulNumOutputSurfaces = 1;
299 ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
301 if (params.ulNumDecodeSurfaces > 32) {
302 av_log(avctx, AV_LOG_WARNING, "Using more than 32 (%d) decode surfaces might cause nvdec to fail.\n",
303 (int)params.ulNumDecodeSurfaces);
304 av_log(avctx, AV_LOG_WARNING, "Try lowering the amount of threads. Using %d right now.\n",
305 avctx->thread_count);
310 pool = av_mallocz(sizeof(*pool));
312 ret = AVERROR(ENOMEM);
315 pool->dpb_size = frames_ctx->initial_pool_size;
317 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
318 nvdec_decoder_frame_alloc, av_free);
319 if (!ctx->decoder_pool) {
320 ret = AVERROR(ENOMEM);
326 ff_nvdec_decode_uninit(avctx);
330 static void nvdec_fdd_priv_free(void *priv)
332 NVDECFrame *cf = priv;
337 av_buffer_unref(&cf->idx_ref);
338 av_buffer_unref(&cf->decoder_ref);
343 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
345 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
346 NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
347 NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
349 CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
355 unsigned int pitch, i;
356 unsigned int offset = 0;
359 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
360 if (err != CUDA_SUCCESS)
361 return AVERROR_UNKNOWN;
363 err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
365 if (err != CUDA_SUCCESS) {
366 av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
368 ret = AVERROR_UNKNOWN;
372 for (i = 0; frame->data[i]; i++) {
373 CUDA_MEMCPY2D cpy = {
374 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
375 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
377 .dstDevice = (CUdeviceptr)frame->data[i],
379 .dstPitch = frame->linesize[i],
381 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
382 .Height = frame->height >> (i ? 1 : 0),
385 err = decoder->cudl->cuMemcpy2D(&cpy);
386 if (err != CUDA_SUCCESS) {
387 av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
389 ret = AVERROR_UNKNOWN;
393 offset += cpy.Height;
397 decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
400 decoder->cudl->cuCtxPopCurrent(&dummy);
404 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
406 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
407 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
408 NVDECFrame *cf = NULL;
411 ctx->bitstream_len = 0;
414 if (fdd->hwaccel_priv)
417 cf = av_mallocz(sizeof(*cf));
419 return AVERROR(ENOMEM);
421 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
422 if (!cf->decoder_ref) {
423 ret = AVERROR(ENOMEM);
427 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
429 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
430 ret = AVERROR(ENOMEM);
433 cf->idx = *(unsigned int*)cf->idx_ref->data;
435 fdd->hwaccel_priv = cf;
436 fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
437 fdd->post_process = nvdec_retrieve_data;
441 nvdec_fdd_priv_free(cf);
446 int ff_nvdec_end_frame(AVCodecContext *avctx)
448 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
449 NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
450 CUVIDPICPARAMS *pp = &ctx->pic_params;
457 pp->nBitstreamDataLen = ctx->bitstream_len;
458 pp->pBitstreamData = ctx->bitstream;
459 pp->nNumSlices = ctx->nb_slices;
460 pp->pSliceDataOffsets = ctx->slice_offsets;
462 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
463 if (err != CUDA_SUCCESS)
464 return AVERROR_UNKNOWN;
466 err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
467 if (err != CUDA_SUCCESS) {
468 av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
470 ret = AVERROR_UNKNOWN;
475 decoder->cudl->cuCtxPopCurrent(&dummy);
480 int ff_nvdec_simple_end_frame(AVCodecContext *avctx)
482 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
483 int ret = ff_nvdec_end_frame(avctx);
484 ctx->bitstream = NULL;
488 int ff_nvdec_simple_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
491 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
494 tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
495 (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));
497 return AVERROR(ENOMEM);
498 ctx->slice_offsets = tmp;
501 ctx->bitstream = (uint8_t*)buffer;
503 ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream;
504 ctx->bitstream_len += size;
510 int ff_nvdec_frame_params(AVCodecContext *avctx,
511 AVBufferRef *hw_frames_ctx,
514 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
515 const AVPixFmtDescriptor *sw_desc;
516 int cuvid_codec_type, cuvid_chroma_format;
518 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
522 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
523 if (cuvid_codec_type < 0) {
524 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
528 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
529 if (cuvid_chroma_format < 0) {
530 av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
531 return AVERROR(EINVAL);
534 frames_ctx->format = AV_PIX_FMT_CUDA;
535 frames_ctx->width = avctx->coded_width;
536 frames_ctx->height = avctx->coded_height;
537 frames_ctx->initial_pool_size = dpb_size;
539 switch (sw_desc->comp[0].depth) {
541 frames_ctx->sw_format = AV_PIX_FMT_NV12;
544 frames_ctx->sw_format = AV_PIX_FMT_P010;
547 frames_ctx->sw_format = AV_PIX_FMT_P016;
550 return AVERROR(EINVAL);
556 int ff_nvdec_get_ref_idx(AVFrame *frame)
558 FrameDecodeData *fdd;
561 if (!frame || !frame->private_ref)
564 fdd = (FrameDecodeData*)frame->private_ref->data;
565 cf = (NVDECFrame*)fdd->hwaccel_priv;