]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvdec.c
avcodec/nvdec: add av1 hwaccel
[ffmpeg] / libavcodec / nvdec.c
1 /*
2  * HW decode acceleration through NVDEC
3  *
4  * Copyright (c) 2016 Anton Khirnov
5  *
6  * This file is part of FFmpeg.
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include "config.h"
24
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"
32
33 #include "avcodec.h"
34 #include "decode.h"
35 #include "nvdec.h"
36 #include "internal.h"
37
38 #if !NVDECAPI_CHECK_VERSION(9, 0)
39 #define cudaVideoSurfaceFormat_YUV444 2
40 #define cudaVideoSurfaceFormat_YUV444_16Bit 3
41 #endif
42
43 typedef struct NVDECDecoder {
44     CUvideodecoder decoder;
45
46     AVBufferRef *hw_device_ref;
47     AVBufferRef *real_hw_frames_ref;
48     CUcontext    cuda_ctx;
49     CUstream     stream;
50
51     CudaFunctions *cudl;
52     CuvidFunctions *cvdl;
53 } NVDECDecoder;
54
55 typedef struct NVDECFramePool {
56     unsigned int dpb_size;
57     unsigned int nb_allocated;
58 } NVDECFramePool;
59
60 #define CHECK_CU(x) FF_CUDA_CHECK_DL(logctx, decoder->cudl, x)
61
62 static int map_avcodec_id(enum AVCodecID id)
63 {
64     switch (id) {
65 #if CONFIG_AV1_NVDEC_HWACCEL
66     case AV_CODEC_ID_AV1:        return cudaVideoCodec_AV1;
67 #endif
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;
78     }
79     return -1;
80 }
81
82 static int map_chroma_format(enum AVPixelFormat pix_fmt)
83 {
84     int shift_h = 0, shift_v = 0;
85
86     av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
87
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;
94
95     return -1;
96 }
97
98 static int nvdec_test_capabilities(NVDECDecoder *decoder,
99                                    CUVIDDECODECREATEINFO *params, void *logctx)
100 {
101     int ret;
102     CUVIDDECODECAPS caps = { 0 };
103
104     caps.eCodecType      = params->CodecType;
105     caps.eChromaFormat   = params->ChromaFormat;
106     caps.nBitDepthMinus8 = params->bitDepthMinus8;
107
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__)
112             "378.66"
113 #else
114             "378.13"
115 #endif
116             ". Continuing blind.\n");
117         return 0;
118     }
119
120     ret = CHECK_CU(decoder->cvdl->cuvidGetDecoderCaps(&caps));
121     if (ret < 0)
122         return ret;
123
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);
131
132     if (!caps.bIsSupported) {
133         av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
134         return AVERROR(EINVAL);
135     }
136
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);
141     }
142
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);
147     }
148
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);
153     }
154
155     return 0;
156 }
157
158 static void nvdec_decoder_free(void *opaque, uint8_t *data)
159 {
160     NVDECDecoder *decoder = (NVDECDecoder*)data;
161
162     if (decoder->decoder) {
163         void *logctx = decoder->hw_device_ref->data;
164         CUcontext dummy;
165         CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
166         CHECK_CU(decoder->cvdl->cuvidDestroyDecoder(decoder->decoder));
167         CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
168     }
169
170     av_buffer_unref(&decoder->real_hw_frames_ref);
171     av_buffer_unref(&decoder->hw_device_ref);
172
173     cuvid_free_functions(&decoder->cvdl);
174
175     av_freep(&decoder);
176 }
177
178 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
179                                 CUVIDDECODECREATEINFO *params, void *logctx)
180 {
181     AVHWDeviceContext  *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
182     AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
183
184     AVBufferRef *decoder_ref;
185     NVDECDecoder *decoder;
186
187     CUcontext dummy;
188     int ret;
189
190     decoder = av_mallocz(sizeof(*decoder));
191     if (!decoder)
192         return AVERROR(ENOMEM);
193
194     decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
195                                    nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
196     if (!decoder_ref) {
197         av_freep(&decoder);
198         return AVERROR(ENOMEM);
199     }
200
201     decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
202     if (!decoder->hw_device_ref) {
203         ret = AVERROR(ENOMEM);
204         goto fail;
205     }
206     decoder->cuda_ctx = device_hwctx->cuda_ctx;
207     decoder->cudl = device_hwctx->internal->cuda_dl;
208     decoder->stream = device_hwctx->stream;
209
210     ret = cuvid_load_functions(&decoder->cvdl, logctx);
211     if (ret < 0) {
212         av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
213         goto fail;
214     }
215
216     ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
217     if (ret < 0)
218         goto fail;
219
220     ret = nvdec_test_capabilities(decoder, params, logctx);
221     if (ret < 0) {
222         CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
223         goto fail;
224     }
225
226     ret = CHECK_CU(decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params));
227
228     CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
229
230     if (ret < 0) {
231         goto fail;
232     }
233
234     *out = decoder_ref;
235
236     return 0;
237 fail:
238     av_buffer_unref(&decoder_ref);
239     return ret;
240 }
241
242 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
243 {
244     NVDECFramePool *pool = opaque;
245     AVBufferRef *ret;
246
247     if (pool->nb_allocated >= pool->dpb_size)
248         return NULL;
249
250     ret = av_buffer_alloc(sizeof(unsigned int));
251     if (!ret)
252         return NULL;
253
254     *(unsigned int*)ret->data = pool->nb_allocated++;
255
256     return ret;
257 }
258
259 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
260 {
261     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
262
263     av_freep(&ctx->bitstream);
264     av_freep(&ctx->bitstream_internal);
265     ctx->bitstream_len       = 0;
266     ctx->bitstream_allocated = 0;
267
268     av_freep(&ctx->slice_offsets);
269     ctx->nb_slices               = 0;
270     ctx->slice_offsets_allocated = 0;
271
272     av_buffer_unref(&ctx->decoder_ref);
273     av_buffer_pool_uninit(&ctx->decoder_pool);
274
275     return 0;
276 }
277
278 static void nvdec_free_dummy(struct AVHWFramesContext *ctx)
279 {
280     av_buffer_pool_uninit(&ctx->pool);
281 }
282
283 static AVBufferRef *nvdec_alloc_dummy(int size)
284 {
285     return av_buffer_create(NULL, 0, NULL, NULL, 0);
286 }
287
288 static int nvdec_init_hwframes(AVCodecContext *avctx, AVBufferRef **out_frames_ref, int dummy)
289 {
290     AVHWFramesContext *frames_ctx;
291     int ret;
292
293     ret = avcodec_get_hw_frames_parameters(avctx,
294                                            avctx->hw_device_ctx,
295                                            avctx->hwaccel->pix_fmt,
296                                            out_frames_ref);
297     if (ret < 0)
298         return ret;
299
300     frames_ctx = (AVHWFramesContext*)(*out_frames_ref)->data;
301
302     if (dummy) {
303         // Copied from ff_decode_get_hw_frames_ctx for compatibility
304         frames_ctx->initial_pool_size += 3;
305
306         frames_ctx->free = nvdec_free_dummy;
307         frames_ctx->pool = av_buffer_pool_init(0, nvdec_alloc_dummy);
308
309         if (!frames_ctx->pool) {
310             av_buffer_unref(out_frames_ref);
311             return AVERROR(ENOMEM);
312         }
313     } else {
314         // This is normally not used to actually allocate frames from
315         frames_ctx->initial_pool_size = 0;
316     }
317
318     ret = av_hwframe_ctx_init(*out_frames_ref);
319     if (ret < 0) {
320         av_buffer_unref(out_frames_ref);
321         return ret;
322     }
323
324     return 0;
325 }
326
327 int ff_nvdec_decode_init(AVCodecContext *avctx)
328 {
329     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
330
331     NVDECDecoder        *decoder;
332     AVBufferRef         *real_hw_frames_ref;
333     NVDECFramePool      *pool;
334     AVHWFramesContext   *frames_ctx;
335     const AVPixFmtDescriptor *sw_desc;
336
337     CUVIDDECODECREATEINFO params = { 0 };
338
339     cudaVideoSurfaceFormat output_format;
340     int cuvid_codec_type, cuvid_chroma_format, chroma_444;
341     int ret = 0;
342
343     sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
344     if (!sw_desc)
345         return AVERROR_BUG;
346
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");
350         return AVERROR_BUG;
351     }
352
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);
357     }
358     chroma_444 = ctx->supports_444 && cuvid_chroma_format == cudaVideoChromaFormat_444;
359
360     if (!avctx->hw_frames_ctx) {
361         ret = nvdec_init_hwframes(avctx, &avctx->hw_frames_ctx, 1);
362         if (ret < 0)
363             return ret;
364
365         ret = nvdec_init_hwframes(avctx, &real_hw_frames_ref, 0);
366         if (ret < 0)
367             return ret;
368     } else {
369         real_hw_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
370         if (!real_hw_frames_ref)
371             return AVERROR(ENOMEM);
372     }
373
374     switch (sw_desc->comp[0].depth) {
375     case 8:
376         output_format = chroma_444 ? cudaVideoSurfaceFormat_YUV444 :
377                                      cudaVideoSurfaceFormat_NV12;
378         break;
379     case 10:
380     case 12:
381         output_format = chroma_444 ? cudaVideoSurfaceFormat_YUV444_16Bit :
382                                      cudaVideoSurfaceFormat_P016;
383         break;
384     default:
385         av_log(avctx, AV_LOG_ERROR, "Unsupported bit depth\n");
386         av_buffer_unref(&real_hw_frames_ref);
387         return AVERROR(ENOSYS);
388     }
389
390     frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
391
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;
402
403     ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, &params, avctx);
404     if (ret < 0) {
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);
410         }
411         av_buffer_unref(&real_hw_frames_ref);
412         return ret;
413     }
414
415     decoder = (NVDECDecoder*)ctx->decoder_ref->data;
416     decoder->real_hw_frames_ref = real_hw_frames_ref;
417     real_hw_frames_ref = NULL;
418
419     pool = av_mallocz(sizeof(*pool));
420     if (!pool) {
421         ret = AVERROR(ENOMEM);
422         goto fail;
423     }
424     pool->dpb_size = frames_ctx->initial_pool_size;
425
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);
430         goto fail;
431     }
432
433     return 0;
434 fail:
435     ff_nvdec_decode_uninit(avctx);
436     return ret;
437 }
438
439 static void nvdec_fdd_priv_free(void *priv)
440 {
441     NVDECFrame *cf = priv;
442
443     if (!cf)
444         return;
445
446     av_buffer_unref(&cf->idx_ref);
447     av_buffer_unref(&cf->decoder_ref);
448     av_buffer_unref(&cf->ref_idx_ref);
449
450     av_freep(&priv);
451 }
452
453 static void nvdec_unmap_mapped_frame(void *opaque, uint8_t *data)
454 {
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;
459     int ret;
460     CUcontext dummy;
461
462     ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
463     if (ret < 0)
464         goto finish;
465
466     CHECK_CU(decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr));
467
468     CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
469
470 finish:
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);
474     av_free(unmap_data);
475 }
476
477 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
478 {
479     FrameDecodeData  *fdd = (FrameDecodeData*)frame->private_ref->data;
480     NVDECFrame        *cf = (NVDECFrame*)fdd->hwaccel_priv;
481     NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
482
483     AVHWFramesContext *hwctx = (AVHWFramesContext *)frame->hw_frames_ctx->data;
484
485     CUVIDPROCPARAMS vpp = { 0 };
486     NVDECFrame *unmap_data = NULL;
487
488     CUcontext dummy;
489     CUdeviceptr devptr;
490
491     unsigned int pitch, i;
492     unsigned int offset = 0;
493     int shift_h = 0, shift_v = 0;
494     int ret = 0;
495
496     vpp.progressive_frame = 1;
497     vpp.output_stream = decoder->stream;
498
499     ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
500     if (ret < 0)
501         return ret;
502
503     ret = CHECK_CU(decoder->cvdl->cuvidMapVideoFrame(decoder->decoder,
504                                                      cf->idx, &devptr,
505                                                      &pitch, &vpp));
506     if (ret < 0)
507         goto finish;
508
509     unmap_data = av_mallocz(sizeof(*unmap_data));
510     if (!unmap_data) {
511         ret = AVERROR(ENOMEM);
512         goto copy_fail;
513     }
514
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);
520         goto copy_fail;
521     }
522
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);
527         goto copy_fail;
528     }
529
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);
533
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));
539     }
540
541     goto finish;
542
543 copy_fail:
544     if (!frame->buf[1]) {
545         CHECK_CU(decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr));
546         av_freep(&unmap_data);
547     } else {
548         av_buffer_unref(&frame->buf[1]);
549     }
550
551 finish:
552     CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
553     return ret;
554 }
555
556 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
557 {
558     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
559     FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
560     NVDECFrame *cf = NULL;
561     int ret;
562
563     ctx->bitstream_len = 0;
564     ctx->nb_slices     = 0;
565
566     if (fdd->hwaccel_priv)
567         return 0;
568
569     cf = av_mallocz(sizeof(*cf));
570     if (!cf)
571         return AVERROR(ENOMEM);
572
573     cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
574     if (!cf->decoder_ref) {
575         ret = AVERROR(ENOMEM);
576         goto fail;
577     }
578
579     cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
580     if (!cf->idx_ref) {
581         av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
582         ret = AVERROR(ENOMEM);
583         goto fail;
584     }
585     cf->ref_idx = cf->idx = *(unsigned int*)cf->idx_ref->data;
586
587     fdd->hwaccel_priv      = cf;
588     fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
589     fdd->post_process      = nvdec_retrieve_data;
590
591     return 0;
592 fail:
593     nvdec_fdd_priv_free(cf);
594     return ret;
595
596 }
597
598 int ff_nvdec_start_frame_sep_ref(AVCodecContext *avctx, AVFrame *frame, int has_sep_ref)
599 {
600     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
601     FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
602     NVDECFrame *cf;
603     int ret;
604
605     ret = ff_nvdec_start_frame(avctx, frame);
606     if (ret < 0)
607         return ret;
608
609     cf = fdd->hwaccel_priv;
610
611     if (has_sep_ref) {
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);
617                 goto fail;
618             }
619         }
620         cf->ref_idx = *(unsigned int*)cf->ref_idx_ref->data;
621     } else {
622         av_buffer_unref(&cf->ref_idx_ref);
623         cf->ref_idx = cf->idx;
624     }
625
626     return 0;
627 fail:
628     nvdec_fdd_priv_free(cf);
629     return ret;
630 }
631
632 int ff_nvdec_end_frame(AVCodecContext *avctx)
633 {
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;
638
639     CUcontext dummy;
640
641     int ret = 0;
642
643     pp->nBitstreamDataLen = ctx->bitstream_len;
644     pp->pBitstreamData    = ctx->bitstream;
645     pp->nNumSlices        = ctx->nb_slices;
646     pp->pSliceDataOffsets = ctx->slice_offsets;
647
648     ret = CHECK_CU(decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx));
649     if (ret < 0)
650         return ret;
651
652     ret = CHECK_CU(decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params));
653     if (ret < 0)
654         goto finish;
655
656 finish:
657     CHECK_CU(decoder->cudl->cuCtxPopCurrent(&dummy));
658
659     return ret;
660 }
661
662 int ff_nvdec_simple_end_frame(AVCodecContext *avctx)
663 {
664     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
665     int ret = ff_nvdec_end_frame(avctx);
666     ctx->bitstream = NULL;
667     return ret;
668 }
669
670 int ff_nvdec_simple_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
671                                  uint32_t size)
672 {
673     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
674     void *tmp;
675
676     tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
677                           (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));
678     if (!tmp)
679         return AVERROR(ENOMEM);
680     ctx->slice_offsets = tmp;
681
682     if (!ctx->bitstream)
683         ctx->bitstream = (uint8_t*)buffer;
684
685     ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream;
686     ctx->bitstream_len += size;
687     ctx->nb_slices++;
688
689     return 0;
690 }
691
692 int ff_nvdec_frame_params(AVCodecContext *avctx,
693                           AVBufferRef *hw_frames_ctx,
694                           int dpb_size,
695                           int supports_444)
696 {
697     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
698     const AVPixFmtDescriptor *sw_desc;
699     int cuvid_codec_type, cuvid_chroma_format, chroma_444;
700
701     sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
702     if (!sw_desc)
703         return AVERROR_BUG;
704
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");
708         return AVERROR_BUG;
709     }
710
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);
715     }
716     chroma_444 = supports_444 && cuvid_chroma_format == cudaVideoChromaFormat_444;
717
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;
721     /*
722      * We add two extra frames to the pool to account for deinterlacing filters
723      * holding onto their frames.
724      */
725     frames_ctx->initial_pool_size = dpb_size + 2;
726
727     switch (sw_desc->comp[0].depth) {
728     case 8:
729         frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_NV12;
730         break;
731     case 10:
732         frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P010;
733         break;
734     case 12:
735         frames_ctx->sw_format = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P016;
736         break;
737     default:
738         return AVERROR(EINVAL);
739     }
740
741     return 0;
742 }
743
744 int ff_nvdec_get_ref_idx(AVFrame *frame)
745 {
746     FrameDecodeData *fdd;
747     NVDECFrame *cf;
748
749     if (!frame || !frame->private_ref)
750         return -1;
751
752     fdd = (FrameDecodeData*)frame->private_ref->data;
753     cf  = (NVDECFrame*)fdd->hwaccel_priv;
754     if (!cf)
755         return -1;
756
757     return cf->ref_idx;
758 }