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;
48 typedef struct NVDECFramePool {
49 unsigned int dpb_size;
50 unsigned int nb_allocated;
53 static int map_avcodec_id(enum AVCodecID id)
56 case AV_CODEC_ID_H264: return cudaVideoCodec_H264;
57 case AV_CODEC_ID_HEVC: return cudaVideoCodec_HEVC;
58 case AV_CODEC_ID_MJPEG: return cudaVideoCodec_JPEG;
59 case AV_CODEC_ID_MPEG1VIDEO: return cudaVideoCodec_MPEG1;
60 case AV_CODEC_ID_MPEG2VIDEO: return cudaVideoCodec_MPEG2;
61 case AV_CODEC_ID_MPEG4: return cudaVideoCodec_MPEG4;
62 case AV_CODEC_ID_VC1: return cudaVideoCodec_VC1;
63 case AV_CODEC_ID_VP8: return cudaVideoCodec_VP8;
64 case AV_CODEC_ID_VP9: return cudaVideoCodec_VP9;
65 case AV_CODEC_ID_WMV3: return cudaVideoCodec_VC1;
70 static int map_chroma_format(enum AVPixelFormat pix_fmt)
72 int shift_h = 0, shift_v = 0;
74 av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
76 if (shift_h == 1 && shift_v == 1)
77 return cudaVideoChromaFormat_420;
78 else if (shift_h == 1 && shift_v == 0)
79 return cudaVideoChromaFormat_422;
80 else if (shift_h == 0 && shift_v == 0)
81 return cudaVideoChromaFormat_444;
86 static int nvdec_test_capabilities(NVDECDecoder *decoder,
87 CUVIDDECODECREATEINFO *params, void *logctx)
90 CUVIDDECODECAPS caps = { 0 };
92 caps.eCodecType = params->CodecType;
93 caps.eChromaFormat = params->ChromaFormat;
94 caps.nBitDepthMinus8 = params->bitDepthMinus8;
96 if (!decoder->cvdl->cuvidGetDecoderCaps) {
97 av_log(logctx, AV_LOG_WARNING, "Used Nvidia driver is too old to perform a capability check.\n");
98 av_log(logctx, AV_LOG_WARNING, "The minimum required version is "
99 #if defined(_WIN32) || defined(__CYGWIN__)
104 ". Continuing blind.\n");
108 err = decoder->cvdl->cuvidGetDecoderCaps(&caps);
109 if (err != CUDA_SUCCESS) {
110 av_log(logctx, AV_LOG_ERROR, "Failed querying decoder capabilities\n");
111 return AVERROR_UNKNOWN;
114 av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
115 av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
116 caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
117 av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
118 caps.nMinWidth, caps.nMaxWidth);
119 av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
120 caps.nMinHeight, caps.nMaxHeight);
122 if (!caps.bIsSupported) {
123 av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
124 return AVERROR(EINVAL);
127 if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
128 av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
129 (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
130 return AVERROR(EINVAL);
133 if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
134 av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
135 (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
136 return AVERROR(EINVAL);
139 if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
140 av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
141 (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
142 return AVERROR(EINVAL);
148 static void nvdec_decoder_free(void *opaque, uint8_t *data)
150 NVDECDecoder *decoder = (NVDECDecoder*)data;
152 if (decoder->decoder) {
154 decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
155 decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
156 decoder->cudl->cuCtxPopCurrent(&dummy);
159 av_buffer_unref(&decoder->hw_device_ref);
161 cuvid_free_functions(&decoder->cvdl);
166 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
167 CUVIDDECODECREATEINFO *params, void *logctx)
169 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
170 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
172 AVBufferRef *decoder_ref;
173 NVDECDecoder *decoder;
179 decoder = av_mallocz(sizeof(*decoder));
181 return AVERROR(ENOMEM);
183 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
184 nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
187 return AVERROR(ENOMEM);
190 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
191 if (!decoder->hw_device_ref) {
192 ret = AVERROR(ENOMEM);
195 decoder->cuda_ctx = device_hwctx->cuda_ctx;
196 decoder->cudl = device_hwctx->internal->cuda_dl;
197 decoder->stream = device_hwctx->stream;
199 ret = cuvid_load_functions(&decoder->cvdl, logctx);
201 av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
205 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
206 if (err != CUDA_SUCCESS) {
207 ret = AVERROR_UNKNOWN;
211 ret = nvdec_test_capabilities(decoder, params, logctx);
213 decoder->cudl->cuCtxPopCurrent(&dummy);
217 err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
219 decoder->cudl->cuCtxPopCurrent(&dummy);
221 if (err != CUDA_SUCCESS) {
222 av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
223 ret = AVERROR_UNKNOWN;
231 av_buffer_unref(&decoder_ref);
235 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
237 NVDECFramePool *pool = opaque;
240 if (pool->nb_allocated >= pool->dpb_size)
243 ret = av_buffer_alloc(sizeof(unsigned int));
247 *(unsigned int*)ret->data = pool->nb_allocated++;
252 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
254 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
256 av_freep(&ctx->bitstream);
257 ctx->bitstream_len = 0;
258 ctx->bitstream_allocated = 0;
260 av_freep(&ctx->slice_offsets);
262 ctx->slice_offsets_allocated = 0;
264 av_buffer_unref(&ctx->decoder_ref);
265 av_buffer_pool_uninit(&ctx->decoder_pool);
270 int ff_nvdec_decode_init(AVCodecContext *avctx)
272 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
274 NVDECFramePool *pool;
275 AVHWFramesContext *frames_ctx;
276 const AVPixFmtDescriptor *sw_desc;
278 CUVIDDECODECREATEINFO params = { 0 };
280 int cuvid_codec_type, cuvid_chroma_format;
283 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
287 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
288 if (cuvid_codec_type < 0) {
289 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
293 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
294 if (cuvid_chroma_format < 0) {
295 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
296 return AVERROR(ENOSYS);
299 if (!avctx->hw_frames_ctx) {
300 ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_CUDA);
305 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
307 params.ulWidth = avctx->coded_width;
308 params.ulHeight = avctx->coded_height;
309 params.ulTargetWidth = avctx->coded_width;
310 params.ulTargetHeight = avctx->coded_height;
311 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
312 params.OutputFormat = params.bitDepthMinus8 ?
313 cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
314 params.CodecType = cuvid_codec_type;
315 params.ChromaFormat = cuvid_chroma_format;
316 params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
317 params.ulNumOutputSurfaces = frames_ctx->initial_pool_size;
319 ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
321 if (params.ulNumDecodeSurfaces > 32) {
322 av_log(avctx, AV_LOG_WARNING, "Using more than 32 (%d) decode surfaces might cause nvdec to fail.\n",
323 (int)params.ulNumDecodeSurfaces);
324 av_log(avctx, AV_LOG_WARNING, "Try lowering the amount of threads. Using %d right now.\n",
325 avctx->thread_count);
330 pool = av_mallocz(sizeof(*pool));
332 ret = AVERROR(ENOMEM);
335 pool->dpb_size = frames_ctx->initial_pool_size;
337 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
338 nvdec_decoder_frame_alloc, av_free);
339 if (!ctx->decoder_pool) {
340 ret = AVERROR(ENOMEM);
346 ff_nvdec_decode_uninit(avctx);
350 static void nvdec_fdd_priv_free(void *priv)
352 NVDECFrame *cf = priv;
357 av_buffer_unref(&cf->idx_ref);
358 av_buffer_unref(&cf->decoder_ref);
363 static void nvdec_unmap_mapped_frame(void *opaque, uint8_t *data)
365 NVDECFrame *unmap_data = (NVDECFrame*)data;
366 NVDECDecoder *decoder = (NVDECDecoder*)unmap_data->decoder_ref->data;
367 CUdeviceptr devptr = (CUdeviceptr)opaque;
371 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
372 if (err != CUDA_SUCCESS) {
373 av_log(NULL, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
377 err = decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
378 if (err != CUDA_SUCCESS)
379 av_log(NULL, AV_LOG_ERROR, "cuvidUnmapVideoFrame failed\n");
381 decoder->cudl->cuCtxPopCurrent(&dummy);
384 av_buffer_unref(&unmap_data->idx_ref);
385 av_buffer_unref(&unmap_data->decoder_ref);
389 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
391 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
392 NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
393 NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
395 CUVIDPROCPARAMS vpp = { 0 };
396 NVDECFrame *unmap_data = NULL;
402 unsigned int pitch, i;
403 unsigned int offset = 0;
406 vpp.progressive_frame = 1;
407 vpp.output_stream = decoder->stream;
409 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
410 if (err != CUDA_SUCCESS)
411 return AVERROR_UNKNOWN;
413 err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
415 if (err != CUDA_SUCCESS) {
416 av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
418 ret = AVERROR_UNKNOWN;
422 unmap_data = av_mallocz(sizeof(*unmap_data));
424 ret = AVERROR(ENOMEM);
428 frame->buf[1] = av_buffer_create((uint8_t *)unmap_data, sizeof(*unmap_data),
429 nvdec_unmap_mapped_frame, (void*)devptr,
430 AV_BUFFER_FLAG_READONLY);
431 if (!frame->buf[1]) {
432 ret = AVERROR(ENOMEM);
436 unmap_data->idx = cf->idx;
437 unmap_data->idx_ref = av_buffer_ref(cf->idx_ref);
438 unmap_data->decoder_ref = av_buffer_ref(cf->decoder_ref);
440 for (i = 0; frame->linesize[i]; i++) {
441 frame->data[i] = (uint8_t*)(devptr + offset);
442 frame->linesize[i] = pitch;
443 offset += pitch * (frame->height >> (i ? 1 : 0));
449 if (!frame->buf[1]) {
450 decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
451 av_freep(&unmap_data);
453 av_buffer_unref(&frame->buf[1]);
457 decoder->cudl->cuCtxPopCurrent(&dummy);
461 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
463 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
464 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
465 NVDECFrame *cf = NULL;
468 ctx->bitstream_len = 0;
471 if (fdd->hwaccel_priv)
474 cf = av_mallocz(sizeof(*cf));
476 return AVERROR(ENOMEM);
478 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
479 if (!cf->decoder_ref) {
480 ret = AVERROR(ENOMEM);
484 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
486 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
487 ret = AVERROR(ENOMEM);
490 cf->idx = *(unsigned int*)cf->idx_ref->data;
492 fdd->hwaccel_priv = cf;
493 fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
494 fdd->post_process = nvdec_retrieve_data;
498 nvdec_fdd_priv_free(cf);
503 int ff_nvdec_end_frame(AVCodecContext *avctx)
505 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
506 NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
507 CUVIDPICPARAMS *pp = &ctx->pic_params;
514 pp->nBitstreamDataLen = ctx->bitstream_len;
515 pp->pBitstreamData = ctx->bitstream;
516 pp->nNumSlices = ctx->nb_slices;
517 pp->pSliceDataOffsets = ctx->slice_offsets;
519 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
520 if (err != CUDA_SUCCESS)
521 return AVERROR_UNKNOWN;
523 err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
524 if (err != CUDA_SUCCESS) {
525 av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
527 ret = AVERROR_UNKNOWN;
532 decoder->cudl->cuCtxPopCurrent(&dummy);
537 int ff_nvdec_simple_end_frame(AVCodecContext *avctx)
539 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
540 int ret = ff_nvdec_end_frame(avctx);
541 ctx->bitstream = NULL;
545 int ff_nvdec_simple_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
548 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
551 tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
552 (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));
554 return AVERROR(ENOMEM);
555 ctx->slice_offsets = tmp;
558 ctx->bitstream = (uint8_t*)buffer;
560 ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream;
561 ctx->bitstream_len += size;
567 static void nvdec_free_dummy(struct AVHWFramesContext *ctx)
569 av_buffer_pool_uninit(&ctx->pool);
572 static AVBufferRef *nvdec_alloc_dummy(int size)
574 return av_buffer_create(NULL, 0, NULL, NULL, 0);
577 int ff_nvdec_frame_params(AVCodecContext *avctx,
578 AVBufferRef *hw_frames_ctx,
581 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
582 const AVPixFmtDescriptor *sw_desc;
583 int cuvid_codec_type, cuvid_chroma_format;
585 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
589 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
590 if (cuvid_codec_type < 0) {
591 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
595 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
596 if (cuvid_chroma_format < 0) {
597 av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
598 return AVERROR(EINVAL);
601 frames_ctx->format = AV_PIX_FMT_CUDA;
602 frames_ctx->width = (avctx->coded_width + 1) & ~1;
603 frames_ctx->height = (avctx->coded_height + 1) & ~1;
605 * We add two extra frames to the pool to account for deinterlacing filters
606 * holding onto their frames.
608 frames_ctx->initial_pool_size = dpb_size + 2;
610 frames_ctx->free = nvdec_free_dummy;
611 frames_ctx->pool = av_buffer_pool_init(0, nvdec_alloc_dummy);
613 if (!frames_ctx->pool)
614 return AVERROR(ENOMEM);
616 switch (sw_desc->comp[0].depth) {
618 frames_ctx->sw_format = AV_PIX_FMT_NV12;
621 frames_ctx->sw_format = AV_PIX_FMT_P010;
624 frames_ctx->sw_format = AV_PIX_FMT_P016;
627 return AVERROR(EINVAL);
633 int ff_nvdec_get_ref_idx(AVFrame *frame)
635 FrameDecodeData *fdd;
638 if (!frame || !frame->private_ref)
641 fdd = (FrameDecodeData*)frame->private_ref->data;
642 cf = (NVDECFrame*)fdd->hwaccel_priv;