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 av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
88 if (shift_h == 1 && shift_v == 1)
89 return cudaVideoChromaFormat_420;
90 else if (shift_h == 1 && shift_v == 0)
91 return cudaVideoChromaFormat_422;
92 else if (shift_h == 0 && shift_v == 0)
93 return cudaVideoChromaFormat_444;
98 static int nvdec_test_capabilities(NVDECDecoder *decoder,
99 CUVIDDECODECREATEINFO *params, void *logctx)
102 CUVIDDECODECAPS caps = { 0 };
104 caps.eCodecType = params->CodecType;
105 caps.eChromaFormat = params->ChromaFormat;
106 caps.nBitDepthMinus8 = params->bitDepthMinus8;
108 if (!decoder->cvdl->cuvidGetDecoderCaps) {
109 av_log(logctx, AV_LOG_WARNING, "Used Nvidia driver is too old to perform a capability check.\n");
110 av_log(logctx, AV_LOG_WARNING, "The minimum required version is "
111 #if defined(_WIN32) || defined(__CYGWIN__)
116 ". Continuing blind.\n");
120 ret = CHECK_CU(decoder->cvdl->cuvidGetDecoderCaps(&caps));
124 av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
125 av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
126 caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
127 av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
128 caps.nMinWidth, caps.nMaxWidth);
129 av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
130 caps.nMinHeight, caps.nMaxHeight);
132 if (!caps.bIsSupported) {
133 av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
134 return AVERROR(EINVAL);
137 if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
138 av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
139 (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
140 return AVERROR(EINVAL);
143 if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
144 av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
145 (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
146 return AVERROR(EINVAL);
149 if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
150 av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
151 (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
152 return AVERROR(EINVAL);
158 static void nvdec_decoder_free(void *opaque, uint8_t *data)
160 NVDECDecoder *decoder = (NVDECDecoder*)data;
162 if (decoder->decoder) {
163 void *logctx = decoder->hw_device_ref->data;
165 CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
166 CHECK_CU(decoder->cvdl->cuvidDestroyDecoder(decoder->decoder));
167 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
170 av_buffer_unref(&decoder->real_hw_frames_ref);
171 av_buffer_unref(&decoder->hw_device_ref);
173 cuvid_free_functions(&decoder->cvdl);
178 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
179 CUVIDDECODECREATEINFO *params, void *logctx)
181 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
182 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
184 AVBufferRef *decoder_ref;
185 NVDECDecoder *decoder;
190 decoder = av_mallocz(sizeof(*decoder));
192 return AVERROR(ENOMEM);
194 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
195 nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
198 return AVERROR(ENOMEM);
201 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
202 if (!decoder->hw_device_ref) {
203 ret = AVERROR(ENOMEM);
206 decoder->cuda_ctx = device_hwctx->cuda_ctx;
207 decoder->cudl = device_hwctx->internal->cuda_dl;
208 decoder->stream = device_hwctx->stream;
210 ret = cuvid_load_functions(&decoder->cvdl, logctx);
212 av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
216 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
220 ret = nvdec_test_capabilities(decoder, params, logctx);
222 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
226 ret = CHECK_CU(decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params));
228 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
238 av_buffer_unref(&decoder_ref);
242 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
244 NVDECFramePool *pool = opaque;
247 if (pool->nb_allocated >= pool->dpb_size)
250 ret = av_buffer_alloc(sizeof(unsigned int));
254 *(unsigned int*)ret->data = pool->nb_allocated++;
259 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
261 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
263 av_freep(&ctx->bitstream);
264 av_freep(&ctx->bitstream_internal);
265 ctx->bitstream_len = 0;
266 ctx->bitstream_allocated = 0;
268 av_freep(&ctx->slice_offsets);
270 ctx->slice_offsets_allocated = 0;
272 av_buffer_unref(&ctx->decoder_ref);
273 av_buffer_pool_uninit(&ctx->decoder_pool);
278 static void nvdec_free_dummy(struct AVHWFramesContext *ctx)
280 av_buffer_pool_uninit(&ctx->pool);
283 static AVBufferRef *nvdec_alloc_dummy(int size)
285 return av_buffer_create(NULL, 0, NULL, NULL, 0);
288 static int nvdec_init_hwframes(AVCodecContext *avctx, AVBufferRef **out_frames_ref, int dummy)
290 AVHWFramesContext *frames_ctx;
293 ret = avcodec_get_hw_frames_parameters(avctx,
294 avctx->hw_device_ctx,
295 avctx->hwaccel->pix_fmt,
300 frames_ctx = (AVHWFramesContext*)(*out_frames_ref)->data;
303 // Copied from ff_decode_get_hw_frames_ctx for compatibility
304 frames_ctx->initial_pool_size += 3;
306 frames_ctx->free = nvdec_free_dummy;
307 frames_ctx->pool = av_buffer_pool_init(0, nvdec_alloc_dummy);
309 if (!frames_ctx->pool) {
310 av_buffer_unref(out_frames_ref);
311 return AVERROR(ENOMEM);
314 // This is normally not used to actually allocate frames from
315 frames_ctx->initial_pool_size = 0;
318 ret = av_hwframe_ctx_init(*out_frames_ref);
320 av_buffer_unref(out_frames_ref);
327 int ff_nvdec_decode_init(AVCodecContext *avctx)
329 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
331 NVDECDecoder *decoder;
332 AVBufferRef *real_hw_frames_ref;
333 NVDECFramePool *pool;
334 AVHWFramesContext *frames_ctx;
335 const AVPixFmtDescriptor *sw_desc;
337 CUVIDDECODECREATEINFO params = { 0 };
339 cudaVideoSurfaceFormat output_format;
340 int cuvid_codec_type, cuvid_chroma_format, chroma_444;
343 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
347 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
348 if (cuvid_codec_type < 0) {
349 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
353 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
354 if (cuvid_chroma_format < 0) {
355 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
356 return AVERROR(ENOSYS);
358 chroma_444 = ctx->supports_444 && cuvid_chroma_format == cudaVideoChromaFormat_444;
360 if (!avctx->hw_frames_ctx) {
361 ret = nvdec_init_hwframes(avctx, &avctx->hw_frames_ctx, 1);
365 ret = nvdec_init_hwframes(avctx, &real_hw_frames_ref, 0);
369 real_hw_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
370 if (!real_hw_frames_ref)
371 return AVERROR(ENOMEM);
374 switch (sw_desc->comp[0].depth) {
376 output_format = chroma_444 ? cudaVideoSurfaceFormat_YUV444 :
377 cudaVideoSurfaceFormat_NV12;
381 output_format = chroma_444 ? cudaVideoSurfaceFormat_YUV444_16Bit :
382 cudaVideoSurfaceFormat_P016;
385 av_log(avctx, AV_LOG_ERROR, "Unsupported bit depth\n");
386 av_buffer_unref(&real_hw_frames_ref);
387 return AVERROR(ENOSYS);
390 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
392 params.ulWidth = avctx->coded_width;
393 params.ulHeight = avctx->coded_height;
394 params.ulTargetWidth = avctx->coded_width;
395 params.ulTargetHeight = avctx->coded_height;
396 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
397 params.OutputFormat = output_format;
398 params.CodecType = cuvid_codec_type;
399 params.ChromaFormat = cuvid_chroma_format;
400 params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
401 params.ulNumOutputSurfaces = frames_ctx->initial_pool_size;
403 ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
405 if (params.ulNumDecodeSurfaces > 32) {
406 av_log(avctx, AV_LOG_WARNING, "Using more than 32 (%d) decode surfaces might cause nvdec to fail.\n",
407 (int)params.ulNumDecodeSurfaces);
408 av_log(avctx, AV_LOG_WARNING, "Try lowering the amount of threads. Using %d right now.\n",
409 avctx->thread_count);
411 av_buffer_unref(&real_hw_frames_ref);
415 decoder = (NVDECDecoder*)ctx->decoder_ref->data;
416 decoder->real_hw_frames_ref = real_hw_frames_ref;
417 real_hw_frames_ref = NULL;
419 pool = av_mallocz(sizeof(*pool));
421 ret = AVERROR(ENOMEM);
424 pool->dpb_size = frames_ctx->initial_pool_size;
426 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
427 nvdec_decoder_frame_alloc, av_free);
428 if (!ctx->decoder_pool) {
429 ret = AVERROR(ENOMEM);
435 ff_nvdec_decode_uninit(avctx);
439 static void nvdec_fdd_priv_free(void *priv)
441 NVDECFrame *cf = priv;
446 av_buffer_unref(&cf->idx_ref);
447 av_buffer_unref(&cf->decoder_ref);
448 av_buffer_unref(&cf->ref_idx_ref);
453 static void nvdec_unmap_mapped_frame(void *opaque, uint8_t *data)
455 NVDECFrame *unmap_data = (NVDECFrame*)data;
456 NVDECDecoder *decoder = (NVDECDecoder*)unmap_data->decoder_ref->data;
457 void *logctx = decoder->hw_device_ref->data;
458 CUdeviceptr devptr = (CUdeviceptr)opaque;
462 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
466 CHECK_CU(decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr));
468 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
471 av_buffer_unref(&unmap_data->idx_ref);
472 av_buffer_unref(&unmap_data->decoder_ref);
473 av_buffer_unref(&unmap_data->ref_idx_ref);
477 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
479 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
480 NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
481 NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
483 AVHWFramesContext *hwctx = (AVHWFramesContext *)frame->hw_frames_ctx->data;
485 CUVIDPROCPARAMS vpp = { 0 };
486 NVDECFrame *unmap_data = NULL;
491 unsigned int pitch, i;
492 unsigned int offset = 0;
493 int shift_h = 0, shift_v = 0;
496 vpp.progressive_frame = 1;
497 vpp.output_stream = decoder->stream;
499 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
503 ret = CHECK_CU(decoder->cvdl->cuvidMapVideoFrame(decoder->decoder,
509 unmap_data = av_mallocz(sizeof(*unmap_data));
511 ret = AVERROR(ENOMEM);
515 frame->buf[1] = av_buffer_create((uint8_t *)unmap_data, sizeof(*unmap_data),
516 nvdec_unmap_mapped_frame, (void*)devptr,
517 AV_BUFFER_FLAG_READONLY);
518 if (!frame->buf[1]) {
519 ret = AVERROR(ENOMEM);
523 av_buffer_unref(&frame->hw_frames_ctx);
524 frame->hw_frames_ctx = av_buffer_ref(decoder->real_hw_frames_ref);
525 if (!frame->hw_frames_ctx) {
526 ret = AVERROR(ENOMEM);
530 unmap_data->idx = cf->idx;
531 unmap_data->idx_ref = av_buffer_ref(cf->idx_ref);
532 unmap_data->decoder_ref = av_buffer_ref(cf->decoder_ref);
534 av_pix_fmt_get_chroma_sub_sample(hwctx->sw_format, &shift_h, &shift_v);
535 for (i = 0; frame->linesize[i]; i++) {
536 frame->data[i] = (uint8_t*)(devptr + offset);
537 frame->linesize[i] = pitch;
538 offset += pitch * (frame->height >> (i ? shift_v : 0));
544 if (!frame->buf[1]) {
545 CHECK_CU(decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr));
546 av_freep(&unmap_data);
548 av_buffer_unref(&frame->buf[1]);
552 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
556 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
558 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
559 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
560 NVDECFrame *cf = NULL;
563 ctx->bitstream_len = 0;
566 if (fdd->hwaccel_priv)
569 cf = av_mallocz(sizeof(*cf));
571 return AVERROR(ENOMEM);
573 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
574 if (!cf->decoder_ref) {
575 ret = AVERROR(ENOMEM);
579 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
581 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
582 ret = AVERROR(ENOMEM);
585 cf->ref_idx = cf->idx = *(unsigned int*)cf->idx_ref->data;
587 fdd->hwaccel_priv = cf;
588 fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
589 fdd->post_process = nvdec_retrieve_data;
593 nvdec_fdd_priv_free(cf);
598 int ff_nvdec_start_frame_sep_ref(AVCodecContext *avctx, AVFrame *frame, int has_sep_ref)
600 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
601 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
605 ret = ff_nvdec_start_frame(avctx, frame);
609 cf = fdd->hwaccel_priv;
612 if (!cf->ref_idx_ref) {
613 cf->ref_idx_ref = av_buffer_pool_get(ctx->decoder_pool);
614 if (!cf->ref_idx_ref) {
615 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
616 ret = AVERROR(ENOMEM);
620 cf->ref_idx = *(unsigned int*)cf->ref_idx_ref->data;
622 av_buffer_unref(&cf->ref_idx_ref);
623 cf->ref_idx = cf->idx;
628 nvdec_fdd_priv_free(cf);
632 int ff_nvdec_end_frame(AVCodecContext *avctx)
634 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
635 NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
636 void *logctx = avctx;
637 CUVIDPICPARAMS *pp = &ctx->pic_params;
643 pp->nBitstreamDataLen = ctx->bitstream_len;
644 pp->pBitstreamData = ctx->bitstream;
645 pp->nNumSlices = ctx->nb_slices;
646 pp->pSliceDataOffsets = ctx->slice_offsets;
648 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
652 ret = CHECK_CU(decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params));
657 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
662 int ff_nvdec_simple_end_frame(AVCodecContext *avctx)
664 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
665 int ret = ff_nvdec_end_frame(avctx);
666 ctx->bitstream = NULL;
670 int ff_nvdec_simple_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
673 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
676 tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
677 (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));
679 return AVERROR(ENOMEM);
680 ctx->slice_offsets = tmp;
683 ctx->bitstream = (uint8_t*)buffer;
685 ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream;
686 ctx->bitstream_len += size;
692 int ff_nvdec_frame_params(AVCodecContext *avctx,
693 AVBufferRef *hw_frames_ctx,
697 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
698 const AVPixFmtDescriptor *sw_desc;
699 int cuvid_codec_type, cuvid_chroma_format, chroma_444;
701 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
705 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
706 if (cuvid_codec_type < 0) {
707 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
711 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
712 if (cuvid_chroma_format < 0) {
713 av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
714 return AVERROR(EINVAL);
716 chroma_444 = supports_444 && cuvid_chroma_format == cudaVideoChromaFormat_444;
718 frames_ctx->format = AV_PIX_FMT_CUDA;
719 frames_ctx->width = (avctx->coded_width + 1) & ~1;
720 frames_ctx->height = (avctx->coded_height + 1) & ~1;
722 * We add two extra frames to the pool to account for deinterlacing filters
723 * holding onto their frames.
725 frames_ctx->initial_pool_size = dpb_size + 2;
727 switch (sw_desc->comp[0].depth) {
729 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_NV12;
732 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P010;
735 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P016;
738 return AVERROR(EINVAL);
744 int ff_nvdec_get_ref_idx(AVFrame *frame)
746 FrameDecodeData *fdd;
749 if (!frame || !frame->private_ref)
752 fdd = (FrameDecodeData*)frame->private_ref->data;
753 cf = (NVDECFrame*)fdd->hwaccel_priv;