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;
54 typedef struct NVDECFramePool {
55 unsigned int dpb_size;
56 unsigned int nb_allocated;
59 #define CHECK_CU(x) FF_CUDA_CHECK_DL(logctx, decoder->cudl, x)
61 static int map_avcodec_id(enum AVCodecID id)
64 case AV_CODEC_ID_H264: return cudaVideoCodec_H264;
65 case AV_CODEC_ID_HEVC: return cudaVideoCodec_HEVC;
66 case AV_CODEC_ID_MJPEG: return cudaVideoCodec_JPEG;
67 case AV_CODEC_ID_MPEG1VIDEO: return cudaVideoCodec_MPEG1;
68 case AV_CODEC_ID_MPEG2VIDEO: return cudaVideoCodec_MPEG2;
69 case AV_CODEC_ID_MPEG4: return cudaVideoCodec_MPEG4;
70 case AV_CODEC_ID_VC1: return cudaVideoCodec_VC1;
71 case AV_CODEC_ID_VP8: return cudaVideoCodec_VP8;
72 case AV_CODEC_ID_VP9: return cudaVideoCodec_VP9;
73 case AV_CODEC_ID_WMV3: return cudaVideoCodec_VC1;
78 static int map_chroma_format(enum AVPixelFormat pix_fmt)
80 int shift_h = 0, shift_v = 0;
82 av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
84 if (shift_h == 1 && shift_v == 1)
85 return cudaVideoChromaFormat_420;
86 else if (shift_h == 1 && shift_v == 0)
87 return cudaVideoChromaFormat_422;
88 else if (shift_h == 0 && shift_v == 0)
89 return cudaVideoChromaFormat_444;
94 static int nvdec_test_capabilities(NVDECDecoder *decoder,
95 CUVIDDECODECREATEINFO *params, void *logctx)
98 CUVIDDECODECAPS caps = { 0 };
100 caps.eCodecType = params->CodecType;
101 caps.eChromaFormat = params->ChromaFormat;
102 caps.nBitDepthMinus8 = params->bitDepthMinus8;
104 if (!decoder->cvdl->cuvidGetDecoderCaps) {
105 av_log(logctx, AV_LOG_WARNING, "Used Nvidia driver is too old to perform a capability check.\n");
106 av_log(logctx, AV_LOG_WARNING, "The minimum required version is "
107 #if defined(_WIN32) || defined(__CYGWIN__)
112 ". Continuing blind.\n");
116 ret = CHECK_CU(decoder->cvdl->cuvidGetDecoderCaps(&caps));
120 av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
121 av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
122 caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
123 av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
124 caps.nMinWidth, caps.nMaxWidth);
125 av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
126 caps.nMinHeight, caps.nMaxHeight);
128 if (!caps.bIsSupported) {
129 av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
130 return AVERROR(EINVAL);
133 if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
134 av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
135 (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
136 return AVERROR(EINVAL);
139 if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
140 av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
141 (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
142 return AVERROR(EINVAL);
145 if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
146 av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
147 (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
148 return AVERROR(EINVAL);
154 static void nvdec_decoder_free(void *opaque, uint8_t *data)
156 NVDECDecoder *decoder = (NVDECDecoder*)data;
158 if (decoder->decoder) {
159 void *logctx = decoder->hw_device_ref->data;
161 CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
162 CHECK_CU(decoder->cvdl->cuvidDestroyDecoder(decoder->decoder));
163 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
166 av_buffer_unref(&decoder->hw_device_ref);
168 cuvid_free_functions(&decoder->cvdl);
173 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
174 CUVIDDECODECREATEINFO *params, void *logctx)
176 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
177 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
179 AVBufferRef *decoder_ref;
180 NVDECDecoder *decoder;
185 decoder = av_mallocz(sizeof(*decoder));
187 return AVERROR(ENOMEM);
189 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
190 nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
193 return AVERROR(ENOMEM);
196 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
197 if (!decoder->hw_device_ref) {
198 ret = AVERROR(ENOMEM);
201 decoder->cuda_ctx = device_hwctx->cuda_ctx;
202 decoder->cudl = device_hwctx->internal->cuda_dl;
203 decoder->stream = device_hwctx->stream;
205 ret = cuvid_load_functions(&decoder->cvdl, logctx);
207 av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
211 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
215 ret = nvdec_test_capabilities(decoder, params, logctx);
217 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
221 ret = CHECK_CU(decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params));
223 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
233 av_buffer_unref(&decoder_ref);
237 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
239 NVDECFramePool *pool = opaque;
242 if (pool->nb_allocated >= pool->dpb_size)
245 ret = av_buffer_alloc(sizeof(unsigned int));
249 *(unsigned int*)ret->data = pool->nb_allocated++;
254 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
256 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
258 av_freep(&ctx->bitstream);
259 ctx->bitstream_len = 0;
260 ctx->bitstream_allocated = 0;
262 av_freep(&ctx->slice_offsets);
264 ctx->slice_offsets_allocated = 0;
266 av_buffer_unref(&ctx->decoder_ref);
267 av_buffer_pool_uninit(&ctx->decoder_pool);
272 int ff_nvdec_decode_init(AVCodecContext *avctx)
274 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
276 NVDECFramePool *pool;
277 AVHWFramesContext *frames_ctx;
278 const AVPixFmtDescriptor *sw_desc;
280 CUVIDDECODECREATEINFO params = { 0 };
282 cudaVideoSurfaceFormat output_format;
283 int cuvid_codec_type, cuvid_chroma_format, chroma_444;
286 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
290 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
291 if (cuvid_codec_type < 0) {
292 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
296 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
297 if (cuvid_chroma_format < 0) {
298 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
299 return AVERROR(ENOSYS);
301 chroma_444 = ctx->supports_444 && cuvid_chroma_format == cudaVideoChromaFormat_444;
303 if (!avctx->hw_frames_ctx) {
304 ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_CUDA);
309 switch (sw_desc->comp[0].depth) {
311 output_format = chroma_444 ? cudaVideoSurfaceFormat_YUV444 :
312 cudaVideoSurfaceFormat_NV12;
316 output_format = chroma_444 ? cudaVideoSurfaceFormat_YUV444_16Bit :
317 cudaVideoSurfaceFormat_P016;
320 av_log(avctx, AV_LOG_ERROR, "Unsupported bit depth\n");
321 return AVERROR(ENOSYS);
324 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
326 params.ulWidth = avctx->coded_width;
327 params.ulHeight = avctx->coded_height;
328 params.ulTargetWidth = avctx->coded_width;
329 params.ulTargetHeight = avctx->coded_height;
330 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
331 params.OutputFormat = output_format;
332 params.CodecType = cuvid_codec_type;
333 params.ChromaFormat = cuvid_chroma_format;
334 params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
335 params.ulNumOutputSurfaces = frames_ctx->initial_pool_size;
337 ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
339 if (params.ulNumDecodeSurfaces > 32) {
340 av_log(avctx, AV_LOG_WARNING, "Using more than 32 (%d) decode surfaces might cause nvdec to fail.\n",
341 (int)params.ulNumDecodeSurfaces);
342 av_log(avctx, AV_LOG_WARNING, "Try lowering the amount of threads. Using %d right now.\n",
343 avctx->thread_count);
348 pool = av_mallocz(sizeof(*pool));
350 ret = AVERROR(ENOMEM);
353 pool->dpb_size = frames_ctx->initial_pool_size;
355 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
356 nvdec_decoder_frame_alloc, av_free);
357 if (!ctx->decoder_pool) {
358 ret = AVERROR(ENOMEM);
364 ff_nvdec_decode_uninit(avctx);
368 static void nvdec_fdd_priv_free(void *priv)
370 NVDECFrame *cf = priv;
375 av_buffer_unref(&cf->idx_ref);
376 av_buffer_unref(&cf->decoder_ref);
381 static void nvdec_unmap_mapped_frame(void *opaque, uint8_t *data)
383 NVDECFrame *unmap_data = (NVDECFrame*)data;
384 NVDECDecoder *decoder = (NVDECDecoder*)unmap_data->decoder_ref->data;
385 void *logctx = decoder->hw_device_ref->data;
386 CUdeviceptr devptr = (CUdeviceptr)opaque;
390 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
394 CHECK_CU(decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr));
396 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
399 av_buffer_unref(&unmap_data->idx_ref);
400 av_buffer_unref(&unmap_data->decoder_ref);
404 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
406 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
407 NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
408 NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
410 AVHWFramesContext *hwctx = (AVHWFramesContext *)frame->hw_frames_ctx->data;
412 CUVIDPROCPARAMS vpp = { 0 };
413 NVDECFrame *unmap_data = NULL;
418 unsigned int pitch, i;
419 unsigned int offset = 0;
420 int shift_h = 0, shift_v = 0;
423 vpp.progressive_frame = 1;
424 vpp.output_stream = decoder->stream;
426 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
430 ret = CHECK_CU(decoder->cvdl->cuvidMapVideoFrame(decoder->decoder,
436 unmap_data = av_mallocz(sizeof(*unmap_data));
438 ret = AVERROR(ENOMEM);
442 frame->buf[1] = av_buffer_create((uint8_t *)unmap_data, sizeof(*unmap_data),
443 nvdec_unmap_mapped_frame, (void*)devptr,
444 AV_BUFFER_FLAG_READONLY);
445 if (!frame->buf[1]) {
446 ret = AVERROR(ENOMEM);
450 unmap_data->idx = cf->idx;
451 unmap_data->idx_ref = av_buffer_ref(cf->idx_ref);
452 unmap_data->decoder_ref = av_buffer_ref(cf->decoder_ref);
454 av_pix_fmt_get_chroma_sub_sample(hwctx->sw_format, &shift_h, &shift_v);
455 for (i = 0; frame->linesize[i]; i++) {
456 frame->data[i] = (uint8_t*)(devptr + offset);
457 frame->linesize[i] = pitch;
458 offset += pitch * (frame->height >> (i ? shift_v : 0));
464 if (!frame->buf[1]) {
465 CHECK_CU(decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr));
466 av_freep(&unmap_data);
468 av_buffer_unref(&frame->buf[1]);
472 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
476 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
478 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
479 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
480 NVDECFrame *cf = NULL;
483 ctx->bitstream_len = 0;
486 if (fdd->hwaccel_priv)
489 cf = av_mallocz(sizeof(*cf));
491 return AVERROR(ENOMEM);
493 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
494 if (!cf->decoder_ref) {
495 ret = AVERROR(ENOMEM);
499 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
501 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
502 ret = AVERROR(ENOMEM);
505 cf->idx = *(unsigned int*)cf->idx_ref->data;
507 fdd->hwaccel_priv = cf;
508 fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
509 fdd->post_process = nvdec_retrieve_data;
513 nvdec_fdd_priv_free(cf);
518 int ff_nvdec_end_frame(AVCodecContext *avctx)
520 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
521 NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
522 void *logctx = avctx;
523 CUVIDPICPARAMS *pp = &ctx->pic_params;
529 pp->nBitstreamDataLen = ctx->bitstream_len;
530 pp->pBitstreamData = ctx->bitstream;
531 pp->nNumSlices = ctx->nb_slices;
532 pp->pSliceDataOffsets = ctx->slice_offsets;
534 ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
538 ret = CHECK_CU(decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params));
543 CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
548 int ff_nvdec_simple_end_frame(AVCodecContext *avctx)
550 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
551 int ret = ff_nvdec_end_frame(avctx);
552 ctx->bitstream = NULL;
556 int ff_nvdec_simple_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
559 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
562 tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
563 (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));
565 return AVERROR(ENOMEM);
566 ctx->slice_offsets = tmp;
569 ctx->bitstream = (uint8_t*)buffer;
571 ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream;
572 ctx->bitstream_len += size;
578 static void nvdec_free_dummy(struct AVHWFramesContext *ctx)
580 av_buffer_pool_uninit(&ctx->pool);
583 static AVBufferRef *nvdec_alloc_dummy(int size)
585 return av_buffer_create(NULL, 0, NULL, NULL, 0);
588 int ff_nvdec_frame_params(AVCodecContext *avctx,
589 AVBufferRef *hw_frames_ctx,
593 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
594 const AVPixFmtDescriptor *sw_desc;
595 int cuvid_codec_type, cuvid_chroma_format, chroma_444;
597 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
601 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
602 if (cuvid_codec_type < 0) {
603 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
607 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
608 if (cuvid_chroma_format < 0) {
609 av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
610 return AVERROR(EINVAL);
612 chroma_444 = supports_444 && cuvid_chroma_format == cudaVideoChromaFormat_444;
614 frames_ctx->format = AV_PIX_FMT_CUDA;
615 frames_ctx->width = (avctx->coded_width + 1) & ~1;
616 frames_ctx->height = (avctx->coded_height + 1) & ~1;
618 * We add two extra frames to the pool to account for deinterlacing filters
619 * holding onto their frames.
621 frames_ctx->initial_pool_size = dpb_size + 2;
623 frames_ctx->free = nvdec_free_dummy;
624 frames_ctx->pool = av_buffer_pool_init(0, nvdec_alloc_dummy);
626 if (!frames_ctx->pool)
627 return AVERROR(ENOMEM);
629 switch (sw_desc->comp[0].depth) {
631 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_NV12;
634 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P010;
637 frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P016;
640 return AVERROR(EINVAL);
646 int ff_nvdec_get_ref_idx(AVFrame *frame)
648 FrameDecodeData *fdd;
651 if (!frame || !frame->private_ref)
654 fdd = (FrameDecodeData*)frame->private_ref->data;
655 cf = (NVDECFrame*)fdd->hwaccel_priv;