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;
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 cuvid_decoder_free(void *opaque, uint8_t *data)
79 CUVIDDecoder *decoder = (CUVIDDecoder*)data;
82 cuvidDestroyDecoder(decoder->decoder);
84 av_buffer_unref(&decoder->hw_device_ref);
89 static int cuvid_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
90 CUVIDDECODECREATEINFO *params, void *logctx)
92 AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
93 AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
95 AVBufferRef *decoder_ref;
96 CUVIDDecoder *decoder;
102 decoder = av_mallocz(sizeof(*decoder));
104 return AVERROR(ENOMEM);
106 decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
107 cuvid_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
110 return AVERROR(ENOMEM);
113 decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
114 if (!decoder->hw_device_ref) {
115 ret = AVERROR(ENOMEM);
118 decoder->cuda_ctx = device_hwctx->cuda_ctx;
120 err = cuCtxPushCurrent(decoder->cuda_ctx);
121 if (err != CUDA_SUCCESS) {
122 ret = AVERROR_UNKNOWN;
126 err = cuvidCreateDecoder(&decoder->decoder, params);
128 cuCtxPopCurrent(&dummy);
130 if (err != CUDA_SUCCESS) {
131 av_log(logctx, AV_LOG_ERROR, "Error creating a CUVID decoder: %d\n", err);
132 ret = AVERROR_UNKNOWN;
140 av_buffer_unref(&decoder_ref);
144 static AVBufferRef *cuvid_decoder_frame_alloc(void *opaque, int size)
146 CUVIDFramePool *pool = opaque;
149 if (pool->nb_allocated >= pool->dpb_size)
152 ret = av_buffer_alloc(sizeof(unsigned int));
156 *(unsigned int*)ret->data = pool->nb_allocated++;
161 int ff_cuvid_decode_uninit(AVCodecContext *avctx)
163 CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
165 av_freep(&ctx->bitstream);
166 ctx->bitstream_len = 0;
167 ctx->bitstream_allocated = 0;
169 av_freep(&ctx->slice_offsets);
171 ctx->slice_offsets_allocated = 0;
173 av_buffer_unref(&ctx->decoder_ref);
174 av_buffer_pool_uninit(&ctx->decoder_pool);
179 int ff_cuvid_decode_init(AVCodecContext *avctx, unsigned int dpb_size)
181 CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
183 CUVIDFramePool *pool;
184 AVHWFramesContext *frames_ctx;
185 const AVPixFmtDescriptor *sw_desc;
187 CUVIDDECODECREATEINFO params = { 0 };
189 int cuvid_codec_type, cuvid_chroma_format;
192 sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
196 cuvid_codec_type = map_avcodec_id(avctx->codec_id);
197 if (cuvid_codec_type < 0) {
198 av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
202 cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
203 if (cuvid_chroma_format < 0) {
204 av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
205 return AVERROR(ENOSYS);
208 if (avctx->thread_type & FF_THREAD_FRAME)
209 dpb_size += avctx->thread_count;
211 if (!avctx->hw_frames_ctx) {
212 AVHWFramesContext *frames_ctx;
214 if (!avctx->hw_device_ctx) {
215 av_log(avctx, AV_LOG_ERROR, "A hardware device or frames context "
216 "is required for CUVID decoding.\n");
217 return AVERROR(EINVAL);
220 avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);
221 if (!avctx->hw_frames_ctx)
222 return AVERROR(ENOMEM);
223 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
225 frames_ctx->format = AV_PIX_FMT_CUDA;
226 frames_ctx->width = avctx->coded_width;
227 frames_ctx->height = avctx->coded_height;
228 frames_ctx->sw_format = AV_PIX_FMT_NV12;
229 frames_ctx->sw_format = sw_desc->comp[0].depth > 8 && HAVE_CUVIDDECODECREATEINFO_BITDEPTHMINUS8 ?
230 AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;
231 frames_ctx->initial_pool_size = dpb_size;
233 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
235 av_log(avctx, AV_LOG_ERROR, "Error initializing internal frames context\n");
239 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
241 params.ulWidth = avctx->coded_width;
242 params.ulHeight = avctx->coded_height;
243 params.ulTargetWidth = avctx->coded_width;
244 params.ulTargetHeight = avctx->coded_height;
245 #if HAVE_CUVIDDECODECREATEINFO_BITDEPTHMINUS8
246 params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
247 params.OutputFormat = params.bitDepthMinus8 ?
248 cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
250 params.OutputFormat = cudaVideoSurfaceFormat_NV12;
252 params.CodecType = cuvid_codec_type;
253 params.ChromaFormat = cuvid_chroma_format;
254 params.ulNumDecodeSurfaces = dpb_size;
255 params.ulNumOutputSurfaces = 1;
257 ret = cuvid_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, ¶ms, avctx);
261 pool = av_mallocz(sizeof(*pool));
263 ret = AVERROR(ENOMEM);
266 pool->dpb_size = dpb_size;
268 ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
269 cuvid_decoder_frame_alloc, av_free);
270 if (!ctx->decoder_pool) {
271 ret = AVERROR(ENOMEM);
277 ff_cuvid_decode_uninit(avctx);
281 static void cuvid_fdd_priv_free(void *priv)
283 CUVIDFrame *cf = priv;
288 av_buffer_unref(&cf->idx_ref);
289 av_buffer_unref(&cf->decoder_ref);
294 static int cuvid_retrieve_data(void *logctx, AVFrame *frame)
296 FrameDecodeData *fdd = (FrameDecodeData*)frame->opaque_ref->data;
297 CUVIDFrame *cf = (CUVIDFrame*)fdd->hwaccel_priv;
298 CUVIDDecoder *decoder = (CUVIDDecoder*)cf->decoder_ref->data;
300 CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
306 unsigned int pitch, i;
307 unsigned int offset = 0;
310 err = cuCtxPushCurrent(decoder->cuda_ctx);
311 if (err != CUDA_SUCCESS)
312 return AVERROR_UNKNOWN;
314 err = cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr, &pitch, &vpp);
315 if (err != CUDA_SUCCESS) {
316 av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
318 ret = AVERROR_UNKNOWN;
322 for (i = 0; frame->data[i]; i++) {
323 CUDA_MEMCPY2D cpy = {
324 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
325 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
327 .dstDevice = (CUdeviceptr)frame->data[i],
329 .dstPitch = frame->linesize[i],
331 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
332 .Height = frame->height >> (i ? 1 : 0),
335 err = cuMemcpy2D(&cpy);
336 if (err != CUDA_SUCCESS) {
337 av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
339 ret = AVERROR_UNKNOWN;
343 offset += cpy.Height;
347 cuvidUnmapVideoFrame(decoder->decoder, devptr);
350 cuCtxPopCurrent(&dummy);
354 int ff_cuvid_start_frame(AVCodecContext *avctx, AVFrame *frame)
356 CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
357 FrameDecodeData *fdd = (FrameDecodeData*)frame->opaque_ref->data;
358 CUVIDFrame *cf = NULL;
361 ctx->bitstream_len = 0;
364 if (fdd->hwaccel_priv)
367 cf = av_mallocz(sizeof(*cf));
369 return AVERROR(ENOMEM);
371 cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
372 if (!cf->decoder_ref)
375 cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
377 av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
378 ret = AVERROR(ENOMEM);
381 cf->idx = *(unsigned int*)cf->idx_ref->data;
383 fdd->hwaccel_priv = cf;
384 fdd->hwaccel_priv_free = cuvid_fdd_priv_free;
385 fdd->post_process = cuvid_retrieve_data;
389 cuvid_fdd_priv_free(cf);
394 int ff_cuvid_end_frame(AVCodecContext *avctx)
396 CUVIDContext *ctx = avctx->internal->hwaccel_priv_data;
397 CUVIDDecoder *decoder = (CUVIDDecoder*)ctx->decoder_ref->data;
398 CUVIDPICPARAMS *pp = &ctx->pic_params;
405 pp->nBitstreamDataLen = ctx->bitstream_len;
406 pp->pBitstreamData = ctx->bitstream;
407 pp->nNumSlices = ctx->nb_slices;
408 pp->pSliceDataOffsets = ctx->slice_offsets;
410 err = cuCtxPushCurrent(decoder->cuda_ctx);
411 if (err != CUDA_SUCCESS)
412 return AVERROR_UNKNOWN;
414 err = cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
415 if (err != CUDA_SUCCESS) {
416 av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with CUVID: %d\n",
418 ret = AVERROR_UNKNOWN;
423 cuCtxPopCurrent(&dummy);