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/cuda_check.h"
30 #include "libavutil/pixdesc.h"
31 #include "libavutil/pixfmt.h"
38 #if !NVDECAPI_CHECK_VERSION(9, 0)
39 #define cudaVideoSurfaceFormat_YUV444 2
40 #define cudaVideoSurfaceFormat_YUV444_16Bit 3
43 typedef struct NVDECDecoder {
44 CUvideodecoder decoder;
46 AVBufferRef *hw_device_ref;
47 AVBufferRef *real_hw_frames_ref;
55 typedef struct NVDECFramePool {
56 unsigned int dpb_size;
57 unsigned int nb_allocated;
60 #define CHECK_CU(x) FF_CUDA_CHECK_DL(logctx, decoder->cudl, x)
62 static int map_avcodec_id(enum AVCodecID id)
65 #if CONFIG_AV1_NVDEC_HWACCEL
66 case AV_CODEC_ID_AV1: return cudaVideoCodec_AV1;
68 case AV_CODEC_ID_H264: return cudaVideoCodec_H264;
69 case AV_CODEC_ID_HEVC: return cudaVideoCodec_HEVC;
70 case AV_CODEC_ID_MJPEG: return cudaVideoCodec_JPEG;
71 case AV_CODEC_ID_MPEG1VIDEO: return cudaVideoCodec_MPEG1;
72 case AV_CODEC_ID_MPEG2VIDEO: return cudaVideoCodec_MPEG2;
73 case AV_CODEC_ID_MPEG4: return cudaVideoCodec_MPEG4;
74 case AV_CODEC_ID_VC1: return cudaVideoCodec_VC1;
75 case AV_CODEC_ID_VP8: return cudaVideoCodec_VP8;
76 case AV_CODEC_ID_VP9: return cudaVideoCodec_VP9;
77 case AV_CODEC_ID_WMV3: return cudaVideoCodec_VC1;
82 static int map_chroma_format(enum AVPixelFormat pix_fmt)
84 int shift_h = 0, shift_v = 0;
86 if (av_pix_fmt_count_planes(pix_fmt) == 1)
87 return cudaVideoChromaFormat_Monochrome;
89 av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
91 if (shift_h == 1 && shift_v == 1)
92 return cudaVideoChromaFormat_420;
93 else if (shift_h == 1 && shift_v == 0)
94 return cudaVideoChromaFormat_422;
95 else if (shift_h == 0 && shift_v == 0)
96 return cudaVideoChromaFormat_444;
101 static int nvdec_test_capabilities(NVDECDecoder *decoder,
102 CUVIDDECODECREATEINFO *params, void *logctx)
105 CUVIDDECODECAPS caps = { 0 };
107 caps.eCodecType = params->CodecType;
108 caps.eChromaFormat = params->ChromaFormat;
109 caps.nBitDepthMinus8 = params->bitDepthMinus8;
111 if (!decoder->cvdl->cuvidGetDecoderCaps) {
112 av_log(logctx, AV_LOG_WARNING, "Used Nvidia driver is too old to perform a capability check.\n");
113 av_log(logctx, AV_LOG_WARNING, "The minimum required version is "
114 #if defined(_WIN32) || defined(__CYGWIN__)
119 ". Continuing blind.\n");
123 ret = CHECK_CU(decoder->cvdl->cuvidGetDecoderCaps(&caps));
127 av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
128 av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
129 caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
130 av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
131 caps.nMinWidth, caps.nMaxWidth);
132 av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
133 caps.nMinHeight, caps.nMaxHeight);
135 if (!caps.bIsSupported) {
136 av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
137 return AVERROR(EINVAL);
140 if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
141 av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
142 (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
143 return AVERROR(EINVAL);
146 if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
147 av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
148 (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
149 return AVERROR(EINVAL);
152 if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
153 av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
154 (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
155 return AVERROR(EINVAL);
161 static void nvdec_decoder_free(void *opaque, uint8_t *data)
163 NVDECDecoder *decoder = (NVDECDecoder*)data;
165 if (decoder->decoder) {
166 void *logctx = decoder->hw_device_ref->data;
168 CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
169 CHECK_CU(decoder->cvdl->cuvidDestroyDecoder(decoder->decoder));
170 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
173 av_buffer_unref(&decoder->real_hw_frames_ref);
174 av_buffer_unref(&decoder->hw_device_ref);
176 cuvid_free_functions(&decoder->cvdl);
181 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
182 CUVIDDECODECREATEINFO *params, void *logctx)
184 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
185 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
187 AVBufferRef *decoder_ref;
188 NVDECDecoder *decoder;
193 decoder = av_mallocz(sizeof(*decoder));
195 return AVERROR(ENOMEM);
197 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
198 nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
201 return AVERROR(ENOMEM);
204 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
205 if (!decoder->hw_device_ref) {
206 ret = AVERROR(ENOMEM);
209 decoder->cuda_ctx = device_hwctx->cuda_ctx;
210 decoder->cudl = device_hwctx->internal->cuda_dl;
211 decoder->stream = device_hwctx->stream;
213 ret = cuvid_load_functions(&decoder->cvdl, logctx);
215 av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
219 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
223 ret = nvdec_test_capabilities(decoder, params, logctx);
225 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
229 ret = CHECK_CU(decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params));
231 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
241 av_buffer_unref(&decoder_ref);
245 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
247 NVDECFramePool *pool = opaque;
250 if (pool->nb_allocated >= pool->dpb_size)
253 ret = av_buffer_alloc(sizeof(unsigned int));
257 *(unsigned int*)ret->data = pool->nb_allocated++;
262 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
264 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
266 av_freep(&ctx->bitstream);
267 av_freep(&ctx->bitstream_internal);
268 ctx->bitstream_len = 0;
269 ctx->bitstream_allocated = 0;
271 av_freep(&ctx->slice_offsets);
273 ctx->slice_offsets_allocated = 0;
275 av_buffer_unref(&ctx->decoder_ref);
276 av_buffer_pool_uninit(&ctx->decoder_pool);
281 static void nvdec_free_dummy(struct AVHWFramesContext *ctx)
283 av_buffer_pool_uninit(&ctx->pool);
286 static AVBufferRef *nvdec_alloc_dummy(int size)
288 return av_buffer_create(NULL, 0, NULL, NULL, 0);
291 static int nvdec_init_hwframes(AVCodecContext *avctx, AVBufferRef **out_frames_ref, int dummy)
293 AVHWFramesContext *frames_ctx;
296 ret = avcodec_get_hw_frames_parameters(avctx,
297 avctx->hw_device_ctx,
298 avctx->hwaccel->pix_fmt,
303 frames_ctx = (AVHWFramesContext*)(*out_frames_ref)->data;
306 // Copied from ff_decode_get_hw_frames_ctx for compatibility
307 frames_ctx->initial_pool_size += 3;
309 frames_ctx->free = nvdec_free_dummy;
310 frames_ctx->pool = av_buffer_pool_init(0, nvdec_alloc_dummy);
312 if (!frames_ctx->pool) {
313 av_buffer_unref(out_frames_ref);
314 return AVERROR(ENOMEM);
317 // This is normally not used to actually allocate frames from
318 frames_ctx->initial_pool_size = 0;
321 ret = av_hwframe_ctx_init(*out_frames_ref);
323 av_buffer_unref(out_frames_ref);
330 int ff_nvdec_decode_init(AVCodecContext *avctx)
332 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
334 NVDECDecoder *decoder;
335 AVBufferRef *real_hw_frames_ref;
336 NVDECFramePool *pool;
337 AVHWFramesContext *frames_ctx;
338 const AVPixFmtDescriptor *sw_desc;
340 CUVIDDECODECREATEINFO params = { 0 };
342 cudaVideoSurfaceFormat output_format;
343 int cuvid_codec_type, cuvid_chroma_format, chroma_444;
346 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
350 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
351 if (cuvid_codec_type < 0) {
352 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
356 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
357 if (cuvid_chroma_format < 0) {
358 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
359 return AVERROR(ENOSYS);
361 chroma_444 = ctx->supports_444 && cuvid_chroma_format == cudaVideoChromaFormat_444;
363 if (!avctx->hw_frames_ctx) {
364 ret = nvdec_init_hwframes(avctx, &avctx->hw_frames_ctx, 1);
368 ret = nvdec_init_hwframes(avctx, &real_hw_frames_ref, 0);
372 real_hw_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
373 if (!real_hw_frames_ref)
374 return AVERROR(ENOMEM);
377 switch (sw_desc->comp[0].depth) {
379 output_format = chroma_444 ? cudaVideoSurfaceFormat_YUV444 :
380 cudaVideoSurfaceFormat_NV12;
384 output_format = chroma_444 ? cudaVideoSurfaceFormat_YUV444_16Bit :
385 cudaVideoSurfaceFormat_P016;
388 av_log(avctx, AV_LOG_ERROR, "Unsupported bit depth\n");
389 av_buffer_unref(&real_hw_frames_ref);
390 return AVERROR(ENOSYS);
393 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
395 params.ulWidth = avctx->coded_width;
396 params.ulHeight = avctx->coded_height;
397 params.ulTargetWidth = avctx->coded_width;
398 params.ulTargetHeight = avctx->coded_height;
399 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
400 params.OutputFormat = output_format;
401 params.CodecType = cuvid_codec_type;
402 params.ChromaFormat = cuvid_chroma_format;
403 params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
404 params.ulNumOutputSurfaces = frames_ctx->initial_pool_size;
406 ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
408 if (params.ulNumDecodeSurfaces > 32) {
409 av_log(avctx, AV_LOG_WARNING, "Using more than 32 (%d) decode surfaces might cause nvdec to fail.\n",
410 (int)params.ulNumDecodeSurfaces);
411 av_log(avctx, AV_LOG_WARNING, "Try lowering the amount of threads. Using %d right now.\n",
412 avctx->thread_count);
414 av_buffer_unref(&real_hw_frames_ref);
418 decoder = (NVDECDecoder*)ctx->decoder_ref->data;
419 decoder->real_hw_frames_ref = real_hw_frames_ref;
420 real_hw_frames_ref = NULL;
422 pool = av_mallocz(sizeof(*pool));
424 ret = AVERROR(ENOMEM);
427 pool->dpb_size = frames_ctx->initial_pool_size;
429 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
430 nvdec_decoder_frame_alloc, av_free);
431 if (!ctx->decoder_pool) {
432 ret = AVERROR(ENOMEM);
438 ff_nvdec_decode_uninit(avctx);
442 static void nvdec_fdd_priv_free(void *priv)
444 NVDECFrame *cf = priv;
449 av_buffer_unref(&cf->idx_ref);
450 av_buffer_unref(&cf->decoder_ref);
451 av_buffer_unref(&cf->ref_idx_ref);
456 static void nvdec_unmap_mapped_frame(void *opaque, uint8_t *data)
458 NVDECFrame *unmap_data = (NVDECFrame*)data;
459 NVDECDecoder *decoder = (NVDECDecoder*)unmap_data->decoder_ref->data;
460 void *logctx = decoder->hw_device_ref->data;
461 CUdeviceptr devptr = (CUdeviceptr)opaque;
465 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
469 CHECK_CU(decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr));
471 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
474 av_buffer_unref(&unmap_data->idx_ref);
475 av_buffer_unref(&unmap_data->decoder_ref);
476 av_buffer_unref(&unmap_data->ref_idx_ref);
480 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
482 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
483 NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
484 NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
486 AVHWFramesContext *hwctx = (AVHWFramesContext *)frame->hw_frames_ctx->data;
488 CUVIDPROCPARAMS vpp = { 0 };
489 NVDECFrame *unmap_data = NULL;
494 unsigned int pitch, i;
495 unsigned int offset = 0;
496 int shift_h = 0, shift_v = 0;
499 vpp.progressive_frame = 1;
500 vpp.output_stream = decoder->stream;
502 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
506 ret = CHECK_CU(decoder->cvdl->cuvidMapVideoFrame(decoder->decoder,
512 unmap_data = av_mallocz(sizeof(*unmap_data));
514 ret = AVERROR(ENOMEM);
518 frame->buf[1] = av_buffer_create((uint8_t *)unmap_data, sizeof(*unmap_data),
519 nvdec_unmap_mapped_frame, (void*)devptr,
520 AV_BUFFER_FLAG_READONLY);
521 if (!frame->buf[1]) {
522 ret = AVERROR(ENOMEM);
526 av_buffer_unref(&frame->hw_frames_ctx);
527 frame->hw_frames_ctx = av_buffer_ref(decoder->real_hw_frames_ref);
528 if (!frame->hw_frames_ctx) {
529 ret = AVERROR(ENOMEM);
533 unmap_data->idx = cf->idx;
534 unmap_data->idx_ref = av_buffer_ref(cf->idx_ref);
535 unmap_data->decoder_ref = av_buffer_ref(cf->decoder_ref);
537 av_pix_fmt_get_chroma_sub_sample(hwctx->sw_format, &shift_h, &shift_v);
538 for (i = 0; frame->linesize[i]; i++) {
539 frame->data[i] = (uint8_t*)(devptr + offset);
540 frame->linesize[i] = pitch;
541 offset += pitch * (frame->height >> (i ? shift_v : 0));
547 if (!frame->buf[1]) {
548 CHECK_CU(decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr));
549 av_freep(&unmap_data);
551 av_buffer_unref(&frame->buf[1]);
555 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
559 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
561 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
562 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
563 NVDECFrame *cf = NULL;
566 ctx->bitstream_len = 0;
569 if (fdd->hwaccel_priv)
572 cf = av_mallocz(sizeof(*cf));
574 return AVERROR(ENOMEM);
576 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
577 if (!cf->decoder_ref) {
578 ret = AVERROR(ENOMEM);
582 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
584 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
585 ret = AVERROR(ENOMEM);
588 cf->ref_idx = cf->idx = *(unsigned int*)cf->idx_ref->data;
590 fdd->hwaccel_priv = cf;
591 fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
592 fdd->post_process = nvdec_retrieve_data;
596 nvdec_fdd_priv_free(cf);
601 int ff_nvdec_start_frame_sep_ref(AVCodecContext *avctx, AVFrame *frame, int has_sep_ref)
603 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
604 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
608 ret = ff_nvdec_start_frame(avctx, frame);
612 cf = fdd->hwaccel_priv;
615 if (!cf->ref_idx_ref) {
616 cf->ref_idx_ref = av_buffer_pool_get(ctx->decoder_pool);
617 if (!cf->ref_idx_ref) {
618 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
619 ret = AVERROR(ENOMEM);
623 cf->ref_idx = *(unsigned int*)cf->ref_idx_ref->data;
625 av_buffer_unref(&cf->ref_idx_ref);
626 cf->ref_idx = cf->idx;
631 nvdec_fdd_priv_free(cf);
635 int ff_nvdec_end_frame(AVCodecContext *avctx)
637 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
638 NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
639 void *logctx = avctx;
640 CUVIDPICPARAMS *pp = &ctx->pic_params;
646 pp->nBitstreamDataLen = ctx->bitstream_len;
647 pp->pBitstreamData = ctx->bitstream;
648 pp->nNumSlices = ctx->nb_slices;
649 pp->pSliceDataOffsets = ctx->slice_offsets;
651 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
655 ret = CHECK_CU(decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params));
660 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
665 int ff_nvdec_simple_end_frame(AVCodecContext *avctx)
667 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
668 int ret = ff_nvdec_end_frame(avctx);
669 ctx->bitstream = NULL;
673 int ff_nvdec_simple_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
676 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
679 tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
680 (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));
682 return AVERROR(ENOMEM);
683 ctx->slice_offsets = tmp;
686 ctx->bitstream = (uint8_t*)buffer;
688 ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream;
689 ctx->bitstream_len += size;
695 int ff_nvdec_frame_params(AVCodecContext *avctx,
696 AVBufferRef *hw_frames_ctx,
700 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
701 const AVPixFmtDescriptor *sw_desc;
702 int cuvid_codec_type, cuvid_chroma_format, chroma_444;
704 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
708 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
709 if (cuvid_codec_type < 0) {
710 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
714 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
715 if (cuvid_chroma_format < 0) {
716 av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
717 return AVERROR(EINVAL);
719 chroma_444 = supports_444 && cuvid_chroma_format == cudaVideoChromaFormat_444;
721 frames_ctx->format = AV_PIX_FMT_CUDA;
722 frames_ctx->width = (avctx->coded_width + 1) & ~1;
723 frames_ctx->height = (avctx->coded_height + 1) & ~1;
725 * We add two extra frames to the pool to account for deinterlacing filters
726 * holding onto their frames.
728 frames_ctx->initial_pool_size = dpb_size + 2;
730 switch (sw_desc->comp[0].depth) {
732 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_NV12;
735 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P010;
738 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P016;
741 return AVERROR(EINVAL);
747 int ff_nvdec_get_ref_idx(AVFrame *frame)
749 FrameDecodeData *fdd;
752 if (!frame || !frame->private_ref)
755 fdd = (FrameDecodeData*)frame->private_ref->data;
756 cf = (NVDECFrame*)fdd->hwaccel_priv;