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;
61 static int map_chroma_format(enum AVPixelFormat pix_fmt)
63 int shift_h = 0, shift_v = 0;
65 av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
67 if (shift_h == 1 && shift_v == 1)
68 return cudaVideoChromaFormat_420;
69 else if (shift_h == 1 && shift_v == 0)
70 return cudaVideoChromaFormat_422;
71 else if (shift_h == 0 && shift_v == 0)
72 return cudaVideoChromaFormat_444;
77 static void nvdec_decoder_free(void *opaque, uint8_t *data)
79 NVDECDecoder *decoder = (NVDECDecoder*)data;
82 decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
84 av_buffer_unref(&decoder->hw_device_ref);
86 cuvid_free_functions(&decoder->cvdl);
91 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
92 CUVIDDECODECREATEINFO *params, void *logctx)
94 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
95 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
97 AVBufferRef *decoder_ref;
98 NVDECDecoder *decoder;
104 decoder = av_mallocz(sizeof(*decoder));
106 return AVERROR(ENOMEM);
108 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
109 nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
112 return AVERROR(ENOMEM);
115 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
116 if (!decoder->hw_device_ref) {
117 ret = AVERROR(ENOMEM);
120 decoder->cuda_ctx = device_hwctx->cuda_ctx;
121 decoder->cudl = device_hwctx->internal->cuda_dl;
123 ret = cuvid_load_functions(&decoder->cvdl);
125 av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
129 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
130 if (err != CUDA_SUCCESS) {
131 ret = AVERROR_UNKNOWN;
135 err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
137 decoder->cudl->cuCtxPopCurrent(&dummy);
139 if (err != CUDA_SUCCESS) {
140 av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
141 ret = AVERROR_UNKNOWN;
149 av_buffer_unref(&decoder_ref);
153 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
155 NVDECFramePool *pool = opaque;
158 if (pool->nb_allocated >= pool->dpb_size)
161 ret = av_buffer_alloc(sizeof(unsigned int));
165 *(unsigned int*)ret->data = pool->nb_allocated++;
170 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
172 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
174 av_freep(&ctx->bitstream);
175 ctx->bitstream_len = 0;
176 ctx->bitstream_allocated = 0;
178 av_freep(&ctx->slice_offsets);
180 ctx->slice_offsets_allocated = 0;
182 av_buffer_unref(&ctx->decoder_ref);
183 av_buffer_pool_uninit(&ctx->decoder_pool);
188 int ff_nvdec_decode_init(AVCodecContext *avctx, unsigned int dpb_size)
190 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
192 NVDECFramePool *pool;
193 AVHWFramesContext *frames_ctx;
194 const AVPixFmtDescriptor *sw_desc;
196 CUVIDDECODECREATEINFO params = { 0 };
198 int cuvid_codec_type, cuvid_chroma_format;
201 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
205 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
206 if (cuvid_codec_type < 0) {
207 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
211 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
212 if (cuvid_chroma_format < 0) {
213 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
214 return AVERROR(ENOSYS);
217 if (avctx->thread_type & FF_THREAD_FRAME)
218 dpb_size += avctx->thread_count;
220 if (!avctx->hw_frames_ctx) {
221 AVHWFramesContext *frames_ctx;
223 if (!avctx->hw_device_ctx) {
224 av_log(avctx, AV_LOG_ERROR, "A hardware device or frames context "
225 "is required for CUVID decoding.\n");
226 return AVERROR(EINVAL);
229 avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);
230 if (!avctx->hw_frames_ctx)
231 return AVERROR(ENOMEM);
232 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
234 frames_ctx->format = AV_PIX_FMT_CUDA;
235 frames_ctx->width = avctx->coded_width;
236 frames_ctx->height = avctx->coded_height;
237 frames_ctx->sw_format = AV_PIX_FMT_NV12;
238 frames_ctx->sw_format = sw_desc->comp[0].depth > 8 ?
239 AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;
240 frames_ctx->initial_pool_size = dpb_size;
242 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
244 av_log(avctx, AV_LOG_ERROR, "Error initializing internal frames context\n");
248 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
250 params.ulWidth = avctx->coded_width;
251 params.ulHeight = avctx->coded_height;
252 params.ulTargetWidth = avctx->coded_width;
253 params.ulTargetHeight = avctx->coded_height;
254 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
255 params.OutputFormat = params.bitDepthMinus8 ?
256 cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
257 params.CodecType = cuvid_codec_type;
258 params.ChromaFormat = cuvid_chroma_format;
259 params.ulNumDecodeSurfaces = dpb_size;
260 params.ulNumOutputSurfaces = 1;
262 ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
266 pool = av_mallocz(sizeof(*pool));
268 ret = AVERROR(ENOMEM);
271 pool->dpb_size = dpb_size;
273 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
274 nvdec_decoder_frame_alloc, av_free);
275 if (!ctx->decoder_pool) {
276 ret = AVERROR(ENOMEM);
282 ff_nvdec_decode_uninit(avctx);
286 static void nvdec_fdd_priv_free(void *priv)
288 NVDECFrame *cf = priv;
293 av_buffer_unref(&cf->idx_ref);
294 av_buffer_unref(&cf->decoder_ref);
299 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
301 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
302 NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
303 NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
305 CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
311 unsigned int pitch, i;
312 unsigned int offset = 0;
315 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
316 if (err != CUDA_SUCCESS)
317 return AVERROR_UNKNOWN;
319 err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
321 if (err != CUDA_SUCCESS) {
322 av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
324 ret = AVERROR_UNKNOWN;
328 for (i = 0; frame->data[i]; i++) {
329 CUDA_MEMCPY2D cpy = {
330 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
331 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
333 .dstDevice = (CUdeviceptr)frame->data[i],
335 .dstPitch = frame->linesize[i],
337 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
338 .Height = frame->height >> (i ? 1 : 0),
341 err = decoder->cudl->cuMemcpy2D(&cpy);
342 if (err != CUDA_SUCCESS) {
343 av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
345 ret = AVERROR_UNKNOWN;
349 offset += cpy.Height;
353 decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
356 decoder->cudl->cuCtxPopCurrent(&dummy);
360 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
362 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
363 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
364 NVDECFrame *cf = NULL;
367 ctx->bitstream_len = 0;
370 if (fdd->hwaccel_priv)
373 cf = av_mallocz(sizeof(*cf));
375 return AVERROR(ENOMEM);
377 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
378 if (!cf->decoder_ref)
381 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
383 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
384 ret = AVERROR(ENOMEM);
387 cf->idx = *(unsigned int*)cf->idx_ref->data;
389 fdd->hwaccel_priv = cf;
390 fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
391 fdd->post_process = nvdec_retrieve_data;
395 nvdec_fdd_priv_free(cf);
400 int ff_nvdec_end_frame(AVCodecContext *avctx)
402 NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
403 NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
404 CUVIDPICPARAMS *pp = &ctx->pic_params;
411 pp->nBitstreamDataLen = ctx->bitstream_len;
412 pp->pBitstreamData = ctx->bitstream;
413 pp->nNumSlices = ctx->nb_slices;
414 pp->pSliceDataOffsets = ctx->slice_offsets;
416 err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
417 if (err != CUDA_SUCCESS)
418 return AVERROR_UNKNOWN;
420 err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
421 if (err != CUDA_SUCCESS) {
422 av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
424 ret = AVERROR_UNKNOWN;
429 decoder->cudl->cuCtxPopCurrent(&dummy);