2 * HW decode acceleration through CUVID
4 * Copyright (c) 2016 Anton Khirnov
6 * This file is part of Libav.
8 * Libav 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 * Libav 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 Libav; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include "libavutil/common.h"
29 #include "libavutil/error.h"
30 #include "libavutil/hwcontext.h"
31 #include "libavutil/hwcontext_cuda.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavutil/pixfmt.h"
40 typedef struct CUVIDDecoder {
41 CUvideodecoder decoder;
43 AVBufferRef *hw_device_ref;
47 typedef struct CUVIDFramePool {
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;
60 static int map_chroma_format(enum AVPixelFormat pix_fmt)
62 int shift_h = 0, shift_v = 0;
64 av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
66 if (shift_h == 1 && shift_v == 1)
67 return cudaVideoChromaFormat_420;
68 else if (shift_h == 1 && shift_v == 0)
69 return cudaVideoChromaFormat_422;
70 else if (shift_h == 0 && shift_v == 0)
71 return cudaVideoChromaFormat_444;
76 static void cuvid_decoder_free(void *opaque, uint8_t *data)
78 CUVIDDecoder *decoder = (CUVIDDecoder*)data;
81 cuvidDestroyDecoder(decoder->decoder);
83 av_buffer_unref(&decoder->hw_device_ref);
88 static int cuvid_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
89 CUVIDDECODECREATEINFO *params, void *logctx)
91 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
92 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
94 AVBufferRef *decoder_ref;
95 CUVIDDecoder *decoder;
101 decoder = av_mallocz(sizeof(*decoder));
103 return AVERROR(ENOMEM);
105 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
106 cuvid_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
109 return AVERROR(ENOMEM);
112 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
113 if (!decoder->hw_device_ref) {
114 ret = AVERROR(ENOMEM);
117 decoder->cuda_ctx = device_hwctx->cuda_ctx;
119 err = cuCtxPushCurrent(decoder->cuda_ctx);
120 if (err != CUDA_SUCCESS) {
121 ret = AVERROR_UNKNOWN;
125 err = cuvidCreateDecoder(&decoder->decoder, params);
127 cuCtxPopCurrent(&dummy);
129 if (err != CUDA_SUCCESS) {
130 av_log(logctx, AV_LOG_ERROR, "Error creating a CUVID decoder: %d\n", err);
131 ret = AVERROR_UNKNOWN;
139 av_buffer_unref(&decoder_ref);
143 static AVBufferRef *cuvid_decoder_frame_alloc(void *opaque, int size)
145 CUVIDFramePool *pool = opaque;
148 if (pool->nb_allocated >= pool->dpb_size)
151 ret = av_buffer_alloc(sizeof(unsigned int));
155 *(unsigned int*)ret->data = pool->nb_allocated++;
160 int ff_cuvid_decode_uninit(AVCodecContext *avctx)
162 CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
164 av_freep(&ctx->bitstream);
165 ctx->bitstream_len = 0;
166 ctx->bitstream_allocated = 0;
168 av_freep(&ctx->slice_offsets);
170 ctx->slice_offsets_allocated = 0;
172 av_buffer_unref(&ctx->decoder_ref);
173 av_buffer_pool_uninit(&ctx->decoder_pool);
178 int ff_cuvid_decode_init(AVCodecContext *avctx, unsigned int dpb_size)
180 CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
182 CUVIDFramePool *pool;
183 AVHWFramesContext *frames_ctx;
184 const AVPixFmtDescriptor *sw_desc;
186 CUVIDDECODECREATEINFO params = { 0 };
188 int cuvid_codec_type, cuvid_chroma_format;
191 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
195 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
196 if (cuvid_codec_type < 0) {
197 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
201 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
202 if (cuvid_chroma_format < 0) {
203 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
204 return AVERROR(ENOSYS);
207 if (avctx->thread_type & FF_THREAD_FRAME)
208 dpb_size += avctx->thread_count;
210 if (!avctx->hw_frames_ctx) {
211 AVHWFramesContext *frames_ctx;
213 if (!avctx->hw_device_ctx) {
214 av_log(avctx, AV_LOG_ERROR, "A hardware device or frames context "
215 "is required for CUVID decoding.\n");
216 return AVERROR(EINVAL);
219 avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);
220 if (!avctx->hw_frames_ctx)
221 return AVERROR(ENOMEM);
222 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
224 frames_ctx->format = AV_PIX_FMT_CUDA;
225 frames_ctx->width = avctx->coded_width;
226 frames_ctx->height = avctx->coded_height;
227 frames_ctx->sw_format = AV_PIX_FMT_NV12;
228 frames_ctx->sw_format = sw_desc->comp[0].depth > 8 && HAVE_CUVIDDECODECREATEINFO_BITDEPTHMINUS8 ?
229 AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;
230 frames_ctx->initial_pool_size = dpb_size;
232 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
234 av_log(avctx, AV_LOG_ERROR, "Error initializing internal frames context\n");
238 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
240 params.ulWidth = avctx->coded_width;
241 params.ulHeight = avctx->coded_height;
242 params.ulTargetWidth = avctx->coded_width;
243 params.ulTargetHeight = avctx->coded_height;
244 #if HAVE_CUVIDDECODECREATEINFO_BITDEPTHMINUS8
245 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
246 params.OutputFormat = params.bitDepthMinus8 ?
247 cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
249 params.OutputFormat = cudaVideoSurfaceFormat_NV12;
251 params.CodecType = cuvid_codec_type;
252 params.ChromaFormat = cuvid_chroma_format;
253 params.ulNumDecodeSurfaces = dpb_size;
254 params.ulNumOutputSurfaces = 1;
256 ret = cuvid_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
260 pool = av_mallocz(sizeof(*pool));
262 ret = AVERROR(ENOMEM);
265 pool->dpb_size = dpb_size;
267 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
268 cuvid_decoder_frame_alloc, av_free);
269 if (!ctx->decoder_pool) {
270 ret = AVERROR(ENOMEM);
276 ff_cuvid_decode_uninit(avctx);
280 static void cuvid_fdd_priv_free(void *priv)
282 CUVIDFrame *cf = priv;
287 av_buffer_unref(&cf->idx_ref);
288 av_buffer_unref(&cf->decoder_ref);
293 static int cuvid_retrieve_data(void *logctx, AVFrame *frame)
295 FrameDecodeData *fdd = (FrameDecodeData*)frame->opaque_ref->data;
296 CUVIDFrame *cf = (CUVIDFrame*)fdd->hwaccel_priv;
297 CUVIDDecoder *decoder = (CUVIDDecoder*)cf->decoder_ref->data;
299 CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
305 unsigned int pitch, i;
306 unsigned int offset = 0;
309 err = cuCtxPushCurrent(decoder->cuda_ctx);
310 if (err != CUDA_SUCCESS)
311 return AVERROR_UNKNOWN;
313 err = cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr, &pitch, &vpp);
314 if (err != CUDA_SUCCESS) {
315 av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
317 ret = AVERROR_UNKNOWN;
321 for (i = 0; frame->data[i]; i++) {
322 CUDA_MEMCPY2D cpy = {
323 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
324 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
326 .dstDevice = (CUdeviceptr)frame->data[i],
328 .dstPitch = frame->linesize[i],
330 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
331 .Height = frame->height >> (i ? 1 : 0),
334 err = cuMemcpy2D(&cpy);
335 if (err != CUDA_SUCCESS) {
336 av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
338 ret = AVERROR_UNKNOWN;
342 offset += cpy.Height;
346 cuvidUnmapVideoFrame(decoder->decoder, devptr);
349 cuCtxPopCurrent(&dummy);
353 int ff_cuvid_start_frame(AVCodecContext *avctx, AVFrame *frame)
355 CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
356 FrameDecodeData *fdd = (FrameDecodeData*)frame->opaque_ref->data;
357 CUVIDFrame *cf = NULL;
360 ctx->bitstream_len = 0;
363 if (fdd->hwaccel_priv)
366 cf = av_mallocz(sizeof(*cf));
368 return AVERROR(ENOMEM);
370 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
371 if (!cf->decoder_ref)
374 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
376 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
377 ret = AVERROR(ENOMEM);
380 cf->idx = *(unsigned int*)cf->idx_ref->data;
382 fdd->hwaccel_priv = cf;
383 fdd->hwaccel_priv_free = cuvid_fdd_priv_free;
384 fdd->post_process = cuvid_retrieve_data;
388 cuvid_fdd_priv_free(cf);
393 int ff_cuvid_end_frame(AVCodecContext *avctx)
395 CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
396 CUVIDDecoder *decoder = (CUVIDDecoder*)ctx->decoder_ref->data;
397 CUVIDPICPARAMS *pp = &ctx->pic_params;
404 pp->nBitstreamDataLen = ctx->bitstream_len;
405 pp->pBitstreamData = ctx->bitstream;
406 pp->nNumSlices = ctx->nb_slices;
407 pp->pSliceDataOffsets = ctx->slice_offsets;
409 err = cuCtxPushCurrent(decoder->cuda_ctx);
410 if (err != CUDA_SUCCESS)
411 return AVERROR_UNKNOWN;
413 err = cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
414 if (err != CUDA_SUCCESS) {
415 av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with CUVID: %d\n",
417 ret = AVERROR_UNKNOWN;
422 cuCtxPopCurrent(&dummy);