]> git.sesse.net Git - ffmpeg/blob - libavcodec/cuviddec.c
avutil/hwcontext_cuda: Define and use common CHECK_CU()
[ffmpeg] / libavcodec / cuviddec.c
1 /*
2  * Nvidia CUVID decoder
3  * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "compat/cuda/dynlink_loader.h"
23
24 #include "libavutil/buffer.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/hwcontext.h"
27 #include "libavutil/hwcontext_cuda_internal.h"
28 #include "libavutil/cuda_check.h"
29 #include "libavutil/fifo.h"
30 #include "libavutil/log.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
33
34 #include "avcodec.h"
35 #include "decode.h"
36 #include "hwaccel.h"
37 #include "internal.h"
38
39 typedef struct CuvidContext
40 {
41     AVClass *avclass;
42
43     CUvideodecoder cudecoder;
44     CUvideoparser cuparser;
45
46     char *cu_gpu;
47     int nb_surfaces;
48     int drop_second_field;
49     char *crop_expr;
50     char *resize_expr;
51
52     struct {
53         int left;
54         int top;
55         int right;
56         int bottom;
57     } crop;
58
59     struct {
60         int width;
61         int height;
62     } resize;
63
64     AVBufferRef *hwdevice;
65     AVBufferRef *hwframe;
66
67     AVBSFContext *bsf;
68
69     AVFifoBuffer *frame_queue;
70
71     int deint_mode;
72     int deint_mode_current;
73     int64_t prev_pts;
74
75     int internal_error;
76     int decoder_flushing;
77
78     int *key_frame;
79
80     cudaVideoCodec codec_type;
81     cudaVideoChromaFormat chroma_format;
82
83     CUVIDDECODECAPS caps8, caps10, caps12;
84
85     CUVIDPARSERPARAMS cuparseinfo;
86     CUVIDEOFORMATEX cuparse_ext;
87
88     CudaFunctions *cudl;
89     CuvidFunctions *cvdl;
90 } CuvidContext;
91
92 typedef struct CuvidParsedFrame
93 {
94     CUVIDPARSERDISPINFO dispinfo;
95     int second_field;
96     int is_deinterlacing;
97 } CuvidParsedFrame;
98
99 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, ctx->cudl, x)
100
101 static int CUDAAPI cuvid_handle_video_sequence(void *opaque, CUVIDEOFORMAT* format)
102 {
103     AVCodecContext *avctx = opaque;
104     CuvidContext *ctx = avctx->priv_data;
105     AVHWFramesContext *hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
106     CUVIDDECODECAPS *caps = NULL;
107     CUVIDDECODECREATEINFO cuinfo;
108     int surface_fmt;
109
110     int old_width = avctx->width;
111     int old_height = avctx->height;
112
113     enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
114                                        AV_PIX_FMT_NONE,  // Will be updated below
115                                        AV_PIX_FMT_NONE };
116
117     av_log(avctx, AV_LOG_TRACE, "pfnSequenceCallback, progressive_sequence=%d\n", format->progressive_sequence);
118
119     memset(&cuinfo, 0, sizeof(cuinfo));
120
121     ctx->internal_error = 0;
122
123     avctx->coded_width = cuinfo.ulWidth = format->coded_width;
124     avctx->coded_height = cuinfo.ulHeight = format->coded_height;
125
126     // apply cropping
127     cuinfo.display_area.left = format->display_area.left + ctx->crop.left;
128     cuinfo.display_area.top = format->display_area.top + ctx->crop.top;
129     cuinfo.display_area.right = format->display_area.right - ctx->crop.right;
130     cuinfo.display_area.bottom = format->display_area.bottom - ctx->crop.bottom;
131
132     // width and height need to be set before calling ff_get_format
133     if (ctx->resize_expr) {
134         avctx->width = ctx->resize.width;
135         avctx->height = ctx->resize.height;
136     } else {
137         avctx->width = cuinfo.display_area.right - cuinfo.display_area.left;
138         avctx->height = cuinfo.display_area.bottom - cuinfo.display_area.top;
139     }
140
141     // target width/height need to be multiples of two
142     cuinfo.ulTargetWidth = avctx->width = (avctx->width + 1) & ~1;
143     cuinfo.ulTargetHeight = avctx->height = (avctx->height + 1) & ~1;
144
145     // aspect ratio conversion, 1:1, depends on scaled resolution
146     cuinfo.target_rect.left = 0;
147     cuinfo.target_rect.top = 0;
148     cuinfo.target_rect.right = cuinfo.ulTargetWidth;
149     cuinfo.target_rect.bottom = cuinfo.ulTargetHeight;
150
151     switch (format->bit_depth_luma_minus8) {
152     case 0: // 8-bit
153         pix_fmts[1] = AV_PIX_FMT_NV12;
154         caps = &ctx->caps8;
155         break;
156     case 2: // 10-bit
157         pix_fmts[1] = AV_PIX_FMT_P010;
158         caps = &ctx->caps10;
159         break;
160     case 4: // 12-bit
161         pix_fmts[1] = AV_PIX_FMT_P016;
162         caps = &ctx->caps12;
163         break;
164     default:
165         break;
166     }
167
168     if (!caps || !caps->bIsSupported) {
169         av_log(avctx, AV_LOG_ERROR, "unsupported bit depth: %d\n",
170                format->bit_depth_luma_minus8 + 8);
171         ctx->internal_error = AVERROR(EINVAL);
172         return 0;
173     }
174
175     surface_fmt = ff_get_format(avctx, pix_fmts);
176     if (surface_fmt < 0) {
177         av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", surface_fmt);
178         ctx->internal_error = AVERROR(EINVAL);
179         return 0;
180     }
181
182     av_log(avctx, AV_LOG_VERBOSE, "Formats: Original: %s | HW: %s | SW: %s\n",
183            av_get_pix_fmt_name(avctx->pix_fmt),
184            av_get_pix_fmt_name(surface_fmt),
185            av_get_pix_fmt_name(avctx->sw_pix_fmt));
186
187     avctx->pix_fmt = surface_fmt;
188
189     // Update our hwframe ctx, as the get_format callback might have refreshed it!
190     if (avctx->hw_frames_ctx) {
191         av_buffer_unref(&ctx->hwframe);
192
193         ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
194         if (!ctx->hwframe) {
195             ctx->internal_error = AVERROR(ENOMEM);
196             return 0;
197         }
198
199         hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
200     }
201
202     ff_set_sar(avctx, av_div_q(
203         (AVRational){ format->display_aspect_ratio.x, format->display_aspect_ratio.y },
204         (AVRational){ avctx->width, avctx->height }));
205
206     ctx->deint_mode_current = format->progressive_sequence
207                               ? cudaVideoDeinterlaceMode_Weave
208                               : ctx->deint_mode;
209
210     if (!format->progressive_sequence && ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave)
211         avctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT;
212     else
213         avctx->flags &= ~AV_CODEC_FLAG_INTERLACED_DCT;
214
215     if (format->video_signal_description.video_full_range_flag)
216         avctx->color_range = AVCOL_RANGE_JPEG;
217     else
218         avctx->color_range = AVCOL_RANGE_MPEG;
219
220     avctx->color_primaries = format->video_signal_description.color_primaries;
221     avctx->color_trc = format->video_signal_description.transfer_characteristics;
222     avctx->colorspace = format->video_signal_description.matrix_coefficients;
223
224     if (format->bitrate)
225         avctx->bit_rate = format->bitrate;
226
227     if (format->frame_rate.numerator && format->frame_rate.denominator) {
228         avctx->framerate.num = format->frame_rate.numerator;
229         avctx->framerate.den = format->frame_rate.denominator;
230     }
231
232     if (ctx->cudecoder
233             && avctx->coded_width == format->coded_width
234             && avctx->coded_height == format->coded_height
235             && avctx->width == old_width
236             && avctx->height == old_height
237             && ctx->chroma_format == format->chroma_format
238             && ctx->codec_type == format->codec)
239         return 1;
240
241     if (ctx->cudecoder) {
242         av_log(avctx, AV_LOG_TRACE, "Re-initializing decoder\n");
243         ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder));
244         if (ctx->internal_error < 0)
245             return 0;
246         ctx->cudecoder = NULL;
247     }
248
249     if (hwframe_ctx->pool && (
250             hwframe_ctx->width < avctx->width ||
251             hwframe_ctx->height < avctx->height ||
252             hwframe_ctx->format != AV_PIX_FMT_CUDA ||
253             hwframe_ctx->sw_format != avctx->sw_pix_fmt)) {
254         av_log(avctx, AV_LOG_ERROR, "AVHWFramesContext is already initialized with incompatible parameters\n");
255         av_log(avctx, AV_LOG_DEBUG, "width: %d <-> %d\n", hwframe_ctx->width, avctx->width);
256         av_log(avctx, AV_LOG_DEBUG, "height: %d <-> %d\n", hwframe_ctx->height, avctx->height);
257         av_log(avctx, AV_LOG_DEBUG, "format: %s <-> cuda\n", av_get_pix_fmt_name(hwframe_ctx->format));
258         av_log(avctx, AV_LOG_DEBUG, "sw_format: %s <-> %s\n",
259                av_get_pix_fmt_name(hwframe_ctx->sw_format), av_get_pix_fmt_name(avctx->sw_pix_fmt));
260         ctx->internal_error = AVERROR(EINVAL);
261         return 0;
262     }
263
264     if (format->chroma_format != cudaVideoChromaFormat_420) {
265         av_log(avctx, AV_LOG_ERROR, "Chroma formats other than 420 are not supported\n");
266         ctx->internal_error = AVERROR(EINVAL);
267         return 0;
268     }
269
270     ctx->chroma_format = format->chroma_format;
271
272     cuinfo.CodecType = ctx->codec_type = format->codec;
273     cuinfo.ChromaFormat = format->chroma_format;
274
275     switch (avctx->sw_pix_fmt) {
276     case AV_PIX_FMT_NV12:
277         cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
278         break;
279     case AV_PIX_FMT_P010:
280     case AV_PIX_FMT_P016:
281         cuinfo.OutputFormat = cudaVideoSurfaceFormat_P016;
282         break;
283     default:
284         av_log(avctx, AV_LOG_ERROR, "Output formats other than NV12, P010 or P016 are not supported\n");
285         ctx->internal_error = AVERROR(EINVAL);
286         return 0;
287     }
288
289     cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
290     cuinfo.ulNumOutputSurfaces = 1;
291     cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
292     cuinfo.bitDepthMinus8 = format->bit_depth_luma_minus8;
293     cuinfo.DeinterlaceMode = ctx->deint_mode_current;
294
295     if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave && !ctx->drop_second_field)
296         avctx->framerate = av_mul_q(avctx->framerate, (AVRational){2, 1});
297
298     ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&ctx->cudecoder, &cuinfo));
299     if (ctx->internal_error < 0)
300         return 0;
301
302     if (!hwframe_ctx->pool) {
303         hwframe_ctx->format = AV_PIX_FMT_CUDA;
304         hwframe_ctx->sw_format = avctx->sw_pix_fmt;
305         hwframe_ctx->width = avctx->width;
306         hwframe_ctx->height = avctx->height;
307
308         if ((ctx->internal_error = av_hwframe_ctx_init(ctx->hwframe)) < 0) {
309             av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_init failed\n");
310             return 0;
311         }
312     }
313
314     return 1;
315 }
316
317 static int CUDAAPI cuvid_handle_picture_decode(void *opaque, CUVIDPICPARAMS* picparams)
318 {
319     AVCodecContext *avctx = opaque;
320     CuvidContext *ctx = avctx->priv_data;
321
322     av_log(avctx, AV_LOG_TRACE, "pfnDecodePicture\n");
323
324     ctx->key_frame[picparams->CurrPicIdx] = picparams->intra_pic_flag;
325
326     ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDecodePicture(ctx->cudecoder, picparams));
327     if (ctx->internal_error < 0)
328         return 0;
329
330     return 1;
331 }
332
333 static int CUDAAPI cuvid_handle_picture_display(void *opaque, CUVIDPARSERDISPINFO* dispinfo)
334 {
335     AVCodecContext *avctx = opaque;
336     CuvidContext *ctx = avctx->priv_data;
337     CuvidParsedFrame parsed_frame = { { 0 } };
338
339     parsed_frame.dispinfo = *dispinfo;
340     ctx->internal_error = 0;
341
342     if (ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave) {
343         av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
344     } else {
345         parsed_frame.is_deinterlacing = 1;
346         av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
347         if (!ctx->drop_second_field) {
348             parsed_frame.second_field = 1;
349             av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
350         }
351     }
352
353     return 1;
354 }
355
356 static int cuvid_is_buffer_full(AVCodecContext *avctx)
357 {
358     CuvidContext *ctx = avctx->priv_data;
359
360     int delay = ctx->cuparseinfo.ulMaxDisplayDelay;
361     if (ctx->deint_mode != cudaVideoDeinterlaceMode_Weave && !ctx->drop_second_field)
362         delay *= 2;
363
364     return (av_fifo_size(ctx->frame_queue) / sizeof(CuvidParsedFrame)) + delay >= ctx->nb_surfaces;
365 }
366
367 static int cuvid_decode_packet(AVCodecContext *avctx, const AVPacket *avpkt)
368 {
369     CuvidContext *ctx = avctx->priv_data;
370     AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
371     AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
372     CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
373     CUVIDSOURCEDATAPACKET cupkt;
374     AVPacket filter_packet = { 0 };
375     AVPacket filtered_packet = { 0 };
376     int ret = 0, eret = 0, is_flush = ctx->decoder_flushing;
377
378     av_log(avctx, AV_LOG_TRACE, "cuvid_decode_packet\n");
379
380     if (is_flush && avpkt && avpkt->size)
381         return AVERROR_EOF;
382
383     if (cuvid_is_buffer_full(avctx) && avpkt && avpkt->size)
384         return AVERROR(EAGAIN);
385
386     if (ctx->bsf && avpkt && avpkt->size) {
387         if ((ret = av_packet_ref(&filter_packet, avpkt)) < 0) {
388             av_log(avctx, AV_LOG_ERROR, "av_packet_ref failed\n");
389             return ret;
390         }
391
392         if ((ret = av_bsf_send_packet(ctx->bsf, &filter_packet)) < 0) {
393             av_log(avctx, AV_LOG_ERROR, "av_bsf_send_packet failed\n");
394             av_packet_unref(&filter_packet);
395             return ret;
396         }
397
398         if ((ret = av_bsf_receive_packet(ctx->bsf, &filtered_packet)) < 0) {
399             av_log(avctx, AV_LOG_ERROR, "av_bsf_receive_packet failed\n");
400             return ret;
401         }
402
403         avpkt = &filtered_packet;
404     }
405
406     ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
407     if (ret < 0) {
408         av_packet_unref(&filtered_packet);
409         return ret;
410     }
411
412     memset(&cupkt, 0, sizeof(cupkt));
413
414     if (avpkt && avpkt->size) {
415         cupkt.payload_size = avpkt->size;
416         cupkt.payload = avpkt->data;
417
418         if (avpkt->pts != AV_NOPTS_VALUE) {
419             cupkt.flags = CUVID_PKT_TIMESTAMP;
420             if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
421                 cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000});
422             else
423                 cupkt.timestamp = avpkt->pts;
424         }
425     } else {
426         cupkt.flags = CUVID_PKT_ENDOFSTREAM;
427         ctx->decoder_flushing = 1;
428     }
429
430     ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &cupkt));
431
432     av_packet_unref(&filtered_packet);
433
434     if (ret < 0)
435         goto error;
436
437     // cuvidParseVideoData doesn't return an error just because stuff failed...
438     if (ctx->internal_error) {
439         av_log(avctx, AV_LOG_ERROR, "cuvid decode callback error\n");
440         ret = ctx->internal_error;
441         goto error;
442     }
443
444 error:
445     eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
446
447     if (eret < 0)
448         return eret;
449     else if (ret < 0)
450         return ret;
451     else if (is_flush)
452         return AVERROR_EOF;
453     else
454         return 0;
455 }
456
457 static int cuvid_output_frame(AVCodecContext *avctx, AVFrame *frame)
458 {
459     CuvidContext *ctx = avctx->priv_data;
460     AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
461     AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
462     CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
463     CUdeviceptr mapped_frame = 0;
464     int ret = 0, eret = 0;
465
466     av_log(avctx, AV_LOG_TRACE, "cuvid_output_frame\n");
467
468     if (ctx->decoder_flushing) {
469         ret = cuvid_decode_packet(avctx, NULL);
470         if (ret < 0 && ret != AVERROR_EOF)
471             return ret;
472     }
473
474     if (!cuvid_is_buffer_full(avctx)) {
475         AVPacket pkt = {0};
476         ret = ff_decode_get_packet(avctx, &pkt);
477         if (ret < 0 && ret != AVERROR_EOF)
478             return ret;
479         ret = cuvid_decode_packet(avctx, &pkt);
480         av_packet_unref(&pkt);
481         // cuvid_is_buffer_full() should avoid this.
482         if (ret == AVERROR(EAGAIN))
483             ret = AVERROR_EXTERNAL;
484         if (ret < 0 && ret != AVERROR_EOF)
485             return ret;
486     }
487
488     ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
489     if (ret < 0)
490         return ret;
491
492     if (av_fifo_size(ctx->frame_queue)) {
493         CuvidParsedFrame parsed_frame;
494         CUVIDPROCPARAMS params;
495         unsigned int pitch = 0;
496         int offset = 0;
497         int i;
498
499         av_fifo_generic_read(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
500
501         memset(&params, 0, sizeof(params));
502         params.progressive_frame = parsed_frame.dispinfo.progressive_frame;
503         params.second_field = parsed_frame.second_field;
504         params.top_field_first = parsed_frame.dispinfo.top_field_first;
505
506         ret = CHECK_CU(ctx->cvdl->cuvidMapVideoFrame(ctx->cudecoder, parsed_frame.dispinfo.picture_index, &mapped_frame, &pitch, &params));
507         if (ret < 0)
508             goto error;
509
510         if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
511             ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0);
512             if (ret < 0) {
513                 av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n");
514                 goto error;
515             }
516
517             ret = ff_decode_frame_props(avctx, frame);
518             if (ret < 0) {
519                 av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n");
520                 goto error;
521             }
522
523             for (i = 0; i < 2; i++) {
524                 CUDA_MEMCPY2D cpy = {
525                     .srcMemoryType = CU_MEMORYTYPE_DEVICE,
526                     .dstMemoryType = CU_MEMORYTYPE_DEVICE,
527                     .srcDevice     = mapped_frame,
528                     .dstDevice     = (CUdeviceptr)frame->data[i],
529                     .srcPitch      = pitch,
530                     .dstPitch      = frame->linesize[i],
531                     .srcY          = offset,
532                     .WidthInBytes  = FFMIN(pitch, frame->linesize[i]),
533                     .Height        = avctx->height >> (i ? 1 : 0),
534                 };
535
536                 ret = CHECK_CU(ctx->cudl->cuMemcpy2DAsync(&cpy, device_hwctx->stream));
537                 if (ret < 0)
538                     goto error;
539
540                 offset += avctx->height;
541             }
542
543             ret = CHECK_CU(ctx->cudl->cuStreamSynchronize(device_hwctx->stream));
544             if (ret < 0)
545                 goto error;
546         } else if (avctx->pix_fmt == AV_PIX_FMT_NV12 ||
547                    avctx->pix_fmt == AV_PIX_FMT_P010 ||
548                    avctx->pix_fmt == AV_PIX_FMT_P016) {
549             AVFrame *tmp_frame = av_frame_alloc();
550             if (!tmp_frame) {
551                 av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n");
552                 ret = AVERROR(ENOMEM);
553                 goto error;
554             }
555
556             tmp_frame->format        = AV_PIX_FMT_CUDA;
557             tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe);
558             tmp_frame->data[0]       = (uint8_t*)mapped_frame;
559             tmp_frame->linesize[0]   = pitch;
560             tmp_frame->data[1]       = (uint8_t*)(mapped_frame + avctx->height * pitch);
561             tmp_frame->linesize[1]   = pitch;
562             tmp_frame->width         = avctx->width;
563             tmp_frame->height        = avctx->height;
564
565             ret = ff_get_buffer(avctx, frame, 0);
566             if (ret < 0) {
567                 av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n");
568                 av_frame_free(&tmp_frame);
569                 goto error;
570             }
571
572             ret = av_hwframe_transfer_data(frame, tmp_frame, 0);
573             if (ret) {
574                 av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n");
575                 av_frame_free(&tmp_frame);
576                 goto error;
577             }
578             av_frame_free(&tmp_frame);
579         } else {
580             ret = AVERROR_BUG;
581             goto error;
582         }
583
584         frame->key_frame = ctx->key_frame[parsed_frame.dispinfo.picture_index];
585         frame->width = avctx->width;
586         frame->height = avctx->height;
587         if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
588             frame->pts = av_rescale_q(parsed_frame.dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase);
589         else
590             frame->pts = parsed_frame.dispinfo.timestamp;
591
592         if (parsed_frame.second_field) {
593             if (ctx->prev_pts == INT64_MIN) {
594                 ctx->prev_pts = frame->pts;
595                 frame->pts += (avctx->pkt_timebase.den * avctx->framerate.den) / (avctx->pkt_timebase.num * avctx->framerate.num);
596             } else {
597                 int pts_diff = (frame->pts - ctx->prev_pts) / 2;
598                 ctx->prev_pts = frame->pts;
599                 frame->pts += pts_diff;
600             }
601         }
602
603         /* CUVIDs opaque reordering breaks the internal pkt logic.
604          * So set pkt_pts and clear all the other pkt_ fields.
605          */
606 #if FF_API_PKT_PTS
607 FF_DISABLE_DEPRECATION_WARNINGS
608         frame->pkt_pts = frame->pts;
609 FF_ENABLE_DEPRECATION_WARNINGS
610 #endif
611         frame->pkt_pos = -1;
612         frame->pkt_duration = 0;
613         frame->pkt_size = -1;
614
615         frame->interlaced_frame = !parsed_frame.is_deinterlacing && !parsed_frame.dispinfo.progressive_frame;
616
617         if (frame->interlaced_frame)
618             frame->top_field_first = parsed_frame.dispinfo.top_field_first;
619     } else if (ctx->decoder_flushing) {
620         ret = AVERROR_EOF;
621     } else {
622         ret = AVERROR(EAGAIN);
623     }
624
625 error:
626     if (mapped_frame)
627         eret = CHECK_CU(ctx->cvdl->cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame));
628
629     eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
630
631     if (eret < 0)
632         return eret;
633     else
634         return ret;
635 }
636
637 static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
638 {
639     CuvidContext *ctx = avctx->priv_data;
640     AVFrame *frame = data;
641     int ret = 0;
642
643     av_log(avctx, AV_LOG_TRACE, "cuvid_decode_frame\n");
644
645     if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave) {
646         av_log(avctx, AV_LOG_ERROR, "Deinterlacing is not supported via the old API\n");
647         return AVERROR(EINVAL);
648     }
649
650     if (!ctx->decoder_flushing) {
651         ret = cuvid_decode_packet(avctx, avpkt);
652         if (ret < 0)
653             return ret;
654     }
655
656     ret = cuvid_output_frame(avctx, frame);
657     if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
658         *got_frame = 0;
659     } else if (ret < 0) {
660         return ret;
661     } else {
662         *got_frame = 1;
663     }
664
665     return 0;
666 }
667
668 static av_cold int cuvid_decode_end(AVCodecContext *avctx)
669 {
670     CuvidContext *ctx = avctx->priv_data;
671
672     av_fifo_freep(&ctx->frame_queue);
673
674     if (ctx->bsf)
675         av_bsf_free(&ctx->bsf);
676
677     if (ctx->cuparser)
678         ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
679
680     if (ctx->cudecoder)
681         ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
682
683     ctx->cudl = NULL;
684
685     av_buffer_unref(&ctx->hwframe);
686     av_buffer_unref(&ctx->hwdevice);
687
688     av_freep(&ctx->key_frame);
689
690     cuvid_free_functions(&ctx->cvdl);
691
692     return 0;
693 }
694
695 static int cuvid_test_capabilities(AVCodecContext *avctx,
696                                    const CUVIDPARSERPARAMS *cuparseinfo,
697                                    int probed_width,
698                                    int probed_height,
699                                    int bit_depth)
700 {
701     CuvidContext *ctx = avctx->priv_data;
702     CUVIDDECODECAPS *caps;
703     int res8 = 0, res10 = 0, res12 = 0;
704
705     if (!ctx->cvdl->cuvidGetDecoderCaps) {
706         av_log(avctx, AV_LOG_WARNING, "Used Nvidia driver is too old to perform a capability check.\n");
707         av_log(avctx, AV_LOG_WARNING, "The minimum required version is "
708 #if defined(_WIN32) || defined(__CYGWIN__)
709             "378.66"
710 #else
711             "378.13"
712 #endif
713             ". Continuing blind.\n");
714         ctx->caps8.bIsSupported = ctx->caps10.bIsSupported = 1;
715         // 12 bit was not supported before the capability check was introduced, so disable it.
716         ctx->caps12.bIsSupported = 0;
717         return 0;
718     }
719
720     ctx->caps8.eCodecType = ctx->caps10.eCodecType = ctx->caps12.eCodecType
721         = cuparseinfo->CodecType;
722     ctx->caps8.eChromaFormat = ctx->caps10.eChromaFormat = ctx->caps12.eChromaFormat
723         = cudaVideoChromaFormat_420;
724
725     ctx->caps8.nBitDepthMinus8 = 0;
726     ctx->caps10.nBitDepthMinus8 = 2;
727     ctx->caps12.nBitDepthMinus8 = 4;
728
729     res8 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps8));
730     res10 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps10));
731     res12 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps12));
732
733     av_log(avctx, AV_LOG_VERBOSE, "CUVID capabilities for %s:\n", avctx->codec->name);
734     av_log(avctx, AV_LOG_VERBOSE, "8 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
735            ctx->caps8.bIsSupported, ctx->caps8.nMinWidth, ctx->caps8.nMaxWidth, ctx->caps8.nMinHeight, ctx->caps8.nMaxHeight);
736     av_log(avctx, AV_LOG_VERBOSE, "10 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
737            ctx->caps10.bIsSupported, ctx->caps10.nMinWidth, ctx->caps10.nMaxWidth, ctx->caps10.nMinHeight, ctx->caps10.nMaxHeight);
738     av_log(avctx, AV_LOG_VERBOSE, "12 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
739            ctx->caps12.bIsSupported, ctx->caps12.nMinWidth, ctx->caps12.nMaxWidth, ctx->caps12.nMinHeight, ctx->caps12.nMaxHeight);
740
741     switch (bit_depth) {
742     case 10:
743         caps = &ctx->caps10;
744         if (res10 < 0)
745             return res10;
746         break;
747     case 12:
748         caps = &ctx->caps12;
749         if (res12 < 0)
750             return res12;
751         break;
752     default:
753         caps = &ctx->caps8;
754         if (res8 < 0)
755             return res8;
756     }
757
758     if (!ctx->caps8.bIsSupported) {
759         av_log(avctx, AV_LOG_ERROR, "Codec %s is not supported.\n", avctx->codec->name);
760         return AVERROR(EINVAL);
761     }
762
763     if (!caps->bIsSupported) {
764         av_log(avctx, AV_LOG_ERROR, "Bit depth %d is not supported.\n", bit_depth);
765         return AVERROR(EINVAL);
766     }
767
768     if (probed_width > caps->nMaxWidth || probed_width < caps->nMinWidth) {
769         av_log(avctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
770                probed_width, caps->nMinWidth, caps->nMaxWidth);
771         return AVERROR(EINVAL);
772     }
773
774     if (probed_height > caps->nMaxHeight || probed_height < caps->nMinHeight) {
775         av_log(avctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
776                probed_height, caps->nMinHeight, caps->nMaxHeight);
777         return AVERROR(EINVAL);
778     }
779
780     return 0;
781 }
782
783 static av_cold int cuvid_decode_init(AVCodecContext *avctx)
784 {
785     CuvidContext *ctx = avctx->priv_data;
786     AVCUDADeviceContext *device_hwctx;
787     AVHWDeviceContext *device_ctx;
788     AVHWFramesContext *hwframe_ctx;
789     CUVIDSOURCEDATAPACKET seq_pkt;
790     CUcontext cuda_ctx = NULL;
791     CUcontext dummy;
792     const AVBitStreamFilter *bsf;
793     int ret = 0;
794
795     enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
796                                        AV_PIX_FMT_NV12,
797                                        AV_PIX_FMT_NONE };
798
799     int probed_width = avctx->coded_width ? avctx->coded_width : 1280;
800     int probed_height = avctx->coded_height ? avctx->coded_height : 720;
801     int probed_bit_depth = 8;
802
803     const AVPixFmtDescriptor *probe_desc = av_pix_fmt_desc_get(avctx->pix_fmt);
804     if (probe_desc && probe_desc->nb_components)
805         probed_bit_depth = probe_desc->comp[0].depth;
806
807     // Accelerated transcoding scenarios with 'ffmpeg' require that the
808     // pix_fmt be set to AV_PIX_FMT_CUDA early. The sw_pix_fmt, and the
809     // pix_fmt for non-accelerated transcoding, do not need to be correct
810     // but need to be set to something. We arbitrarily pick NV12.
811     ret = ff_get_format(avctx, pix_fmts);
812     if (ret < 0) {
813         av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);
814         return ret;
815     }
816     avctx->pix_fmt = ret;
817
818     if (ctx->resize_expr && sscanf(ctx->resize_expr, "%dx%d",
819                                    &ctx->resize.width, &ctx->resize.height) != 2) {
820         av_log(avctx, AV_LOG_ERROR, "Invalid resize expressions\n");
821         ret = AVERROR(EINVAL);
822         goto error;
823     }
824
825     if (ctx->crop_expr && sscanf(ctx->crop_expr, "%dx%dx%dx%d",
826                                  &ctx->crop.top, &ctx->crop.bottom,
827                                  &ctx->crop.left, &ctx->crop.right) != 4) {
828         av_log(avctx, AV_LOG_ERROR, "Invalid cropping expressions\n");
829         ret = AVERROR(EINVAL);
830         goto error;
831     }
832
833     ret = cuvid_load_functions(&ctx->cvdl, avctx);
834     if (ret < 0) {
835         av_log(avctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
836         goto error;
837     }
838
839     ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
840     if (!ctx->frame_queue) {
841         ret = AVERROR(ENOMEM);
842         goto error;
843     }
844
845     if (avctx->hw_frames_ctx) {
846         ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
847         if (!ctx->hwframe) {
848             ret = AVERROR(ENOMEM);
849             goto error;
850         }
851
852         hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
853
854         ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);
855         if (!ctx->hwdevice) {
856             ret = AVERROR(ENOMEM);
857             goto error;
858         }
859     } else {
860         if (avctx->hw_device_ctx) {
861             ctx->hwdevice = av_buffer_ref(avctx->hw_device_ctx);
862             if (!ctx->hwdevice) {
863                 ret = AVERROR(ENOMEM);
864                 goto error;
865             }
866         } else {
867             ret = av_hwdevice_ctx_create(&ctx->hwdevice, AV_HWDEVICE_TYPE_CUDA, ctx->cu_gpu, NULL, 0);
868             if (ret < 0)
869                 goto error;
870         }
871
872         ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);
873         if (!ctx->hwframe) {
874             av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");
875             ret = AVERROR(ENOMEM);
876             goto error;
877         }
878
879         hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
880     }
881
882     device_ctx = hwframe_ctx->device_ctx;
883     device_hwctx = device_ctx->hwctx;
884
885     cuda_ctx = device_hwctx->cuda_ctx;
886     ctx->cudl = device_hwctx->internal->cuda_dl;
887
888     memset(&ctx->cuparseinfo, 0, sizeof(ctx->cuparseinfo));
889     memset(&ctx->cuparse_ext, 0, sizeof(ctx->cuparse_ext));
890     memset(&seq_pkt, 0, sizeof(seq_pkt));
891
892     ctx->cuparseinfo.pExtVideoInfo = &ctx->cuparse_ext;
893
894     switch (avctx->codec->id) {
895 #if CONFIG_H264_CUVID_DECODER
896     case AV_CODEC_ID_H264:
897         ctx->cuparseinfo.CodecType = cudaVideoCodec_H264;
898         break;
899 #endif
900 #if CONFIG_HEVC_CUVID_DECODER
901     case AV_CODEC_ID_HEVC:
902         ctx->cuparseinfo.CodecType = cudaVideoCodec_HEVC;
903         break;
904 #endif
905 #if CONFIG_MJPEG_CUVID_DECODER
906     case AV_CODEC_ID_MJPEG:
907         ctx->cuparseinfo.CodecType = cudaVideoCodec_JPEG;
908         break;
909 #endif
910 #if CONFIG_MPEG1_CUVID_DECODER
911     case AV_CODEC_ID_MPEG1VIDEO:
912         ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG1;
913         break;
914 #endif
915 #if CONFIG_MPEG2_CUVID_DECODER
916     case AV_CODEC_ID_MPEG2VIDEO:
917         ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG2;
918         break;
919 #endif
920 #if CONFIG_MPEG4_CUVID_DECODER
921     case AV_CODEC_ID_MPEG4:
922         ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG4;
923         break;
924 #endif
925 #if CONFIG_VP8_CUVID_DECODER
926     case AV_CODEC_ID_VP8:
927         ctx->cuparseinfo.CodecType = cudaVideoCodec_VP8;
928         break;
929 #endif
930 #if CONFIG_VP9_CUVID_DECODER
931     case AV_CODEC_ID_VP9:
932         ctx->cuparseinfo.CodecType = cudaVideoCodec_VP9;
933         break;
934 #endif
935 #if CONFIG_VC1_CUVID_DECODER
936     case AV_CODEC_ID_VC1:
937         ctx->cuparseinfo.CodecType = cudaVideoCodec_VC1;
938         break;
939 #endif
940     default:
941         av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");
942         return AVERROR_BUG;
943     }
944
945     if (avctx->codec->id == AV_CODEC_ID_H264 || avctx->codec->id == AV_CODEC_ID_HEVC) {
946         if (avctx->codec->id == AV_CODEC_ID_H264)
947             bsf = av_bsf_get_by_name("h264_mp4toannexb");
948         else
949             bsf = av_bsf_get_by_name("hevc_mp4toannexb");
950
951         if (!bsf) {
952             ret = AVERROR_BSF_NOT_FOUND;
953             goto error;
954         }
955         if (ret = av_bsf_alloc(bsf, &ctx->bsf)) {
956             goto error;
957         }
958         if (((ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx)) < 0) || ((ret = av_bsf_init(ctx->bsf)) < 0)) {
959             av_bsf_free(&ctx->bsf);
960             goto error;
961         }
962
963         ctx->cuparse_ext.format.seqhdr_data_length = ctx->bsf->par_out->extradata_size;
964         memcpy(ctx->cuparse_ext.raw_seqhdr_data,
965                ctx->bsf->par_out->extradata,
966                FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), ctx->bsf->par_out->extradata_size));
967     } else if (avctx->extradata_size > 0) {
968         ctx->cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;
969         memcpy(ctx->cuparse_ext.raw_seqhdr_data,
970                avctx->extradata,
971                FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), avctx->extradata_size));
972     }
973
974     ctx->key_frame = av_mallocz(ctx->nb_surfaces * sizeof(int));
975     if (!ctx->key_frame) {
976         ret = AVERROR(ENOMEM);
977         goto error;
978     }
979
980     ctx->cuparseinfo.ulMaxNumDecodeSurfaces = ctx->nb_surfaces;
981     ctx->cuparseinfo.ulMaxDisplayDelay = 4;
982     ctx->cuparseinfo.pUserData = avctx;
983     ctx->cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;
984     ctx->cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;
985     ctx->cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;
986
987     ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
988     if (ret < 0)
989         goto error;
990
991     ret = cuvid_test_capabilities(avctx, &ctx->cuparseinfo,
992                                   probed_width,
993                                   probed_height,
994                                   probed_bit_depth);
995     if (ret < 0)
996         goto error;
997
998     ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
999     if (ret < 0)
1000         goto error;
1001
1002     seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
1003     seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
1004
1005     if (seq_pkt.payload && seq_pkt.payload_size) {
1006         ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
1007         if (ret < 0)
1008             goto error;
1009     }
1010
1011     ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
1012     if (ret < 0)
1013         goto error;
1014
1015     ctx->prev_pts = INT64_MIN;
1016
1017     if (!avctx->pkt_timebase.num || !avctx->pkt_timebase.den)
1018         av_log(avctx, AV_LOG_WARNING, "Invalid pkt_timebase, passing timestamps as-is.\n");
1019
1020     return 0;
1021
1022 error:
1023     cuvid_decode_end(avctx);
1024     return ret;
1025 }
1026
1027 static void cuvid_flush(AVCodecContext *avctx)
1028 {
1029     CuvidContext *ctx = avctx->priv_data;
1030     AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
1031     AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
1032     CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
1033     CUVIDSOURCEDATAPACKET seq_pkt = { 0 };
1034     int ret;
1035
1036     ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
1037     if (ret < 0)
1038         goto error;
1039
1040     av_fifo_freep(&ctx->frame_queue);
1041
1042     ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
1043     if (!ctx->frame_queue) {
1044         av_log(avctx, AV_LOG_ERROR, "Failed to recreate frame queue on flush\n");
1045         return;
1046     }
1047
1048     if (ctx->cudecoder) {
1049         ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
1050         ctx->cudecoder = NULL;
1051     }
1052
1053     if (ctx->cuparser) {
1054         ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
1055         ctx->cuparser = NULL;
1056     }
1057
1058     ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
1059     if (ret < 0)
1060         goto error;
1061
1062     seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
1063     seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
1064
1065     if (seq_pkt.payload && seq_pkt.payload_size) {
1066         ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
1067         if (ret < 0)
1068             goto error;
1069     }
1070
1071     ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
1072     if (ret < 0)
1073         goto error;
1074
1075     ctx->prev_pts = INT64_MIN;
1076     ctx->decoder_flushing = 0;
1077
1078     return;
1079  error:
1080     av_log(avctx, AV_LOG_ERROR, "CUDA reinit on flush failed\n");
1081 }
1082
1083 #define OFFSET(x) offsetof(CuvidContext, x)
1084 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1085 static const AVOption options[] = {
1086     { "deint",    "Set deinterlacing mode", OFFSET(deint_mode), AV_OPT_TYPE_INT,   { .i64 = cudaVideoDeinterlaceMode_Weave    }, cudaVideoDeinterlaceMode_Weave, cudaVideoDeinterlaceMode_Adaptive, VD, "deint" },
1087     { "weave",    "Weave deinterlacing (do nothing)",        0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Weave    }, 0, 0, VD, "deint" },
1088     { "bob",      "Bob deinterlacing",                       0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Bob      }, 0, 0, VD, "deint" },
1089     { "adaptive", "Adaptive deinterlacing",                  0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Adaptive }, 0, 0, VD, "deint" },
1090     { "gpu",      "GPU to be used for decoding", OFFSET(cu_gpu), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1091     { "surfaces", "Maximum surfaces to be used for decoding", OFFSET(nb_surfaces), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, INT_MAX, VD },
1092     { "drop_second_field", "Drop second field when deinterlacing", OFFSET(drop_second_field), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1093     { "crop",     "Crop (top)x(bottom)x(left)x(right)", OFFSET(crop_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1094     { "resize",   "Resize (width)x(height)", OFFSET(resize_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1095     { NULL }
1096 };
1097
1098 static const AVCodecHWConfigInternal *cuvid_hw_configs[] = {
1099     &(const AVCodecHWConfigInternal) {
1100         .public = {
1101             .pix_fmt     = AV_PIX_FMT_CUDA,
1102             .methods     = AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX |
1103                            AV_CODEC_HW_CONFIG_METHOD_INTERNAL,
1104             .device_type = AV_HWDEVICE_TYPE_CUDA
1105         },
1106         .hwaccel = NULL,
1107     },
1108     NULL
1109 };
1110
1111 #define DEFINE_CUVID_CODEC(x, X) \
1112     static const AVClass x##_cuvid_class = { \
1113         .class_name = #x "_cuvid", \
1114         .item_name = av_default_item_name, \
1115         .option = options, \
1116         .version = LIBAVUTIL_VERSION_INT, \
1117     }; \
1118     AVCodec ff_##x##_cuvid_decoder = { \
1119         .name           = #x "_cuvid", \
1120         .long_name      = NULL_IF_CONFIG_SMALL("Nvidia CUVID " #X " decoder"), \
1121         .type           = AVMEDIA_TYPE_VIDEO, \
1122         .id             = AV_CODEC_ID_##X, \
1123         .priv_data_size = sizeof(CuvidContext), \
1124         .priv_class     = &x##_cuvid_class, \
1125         .init           = cuvid_decode_init, \
1126         .close          = cuvid_decode_end, \
1127         .decode         = cuvid_decode_frame, \
1128         .receive_frame  = cuvid_output_frame, \
1129         .flush          = cuvid_flush, \
1130         .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_HARDWARE, \
1131         .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_CUDA, \
1132                                                         AV_PIX_FMT_NV12, \
1133                                                         AV_PIX_FMT_P010, \
1134                                                         AV_PIX_FMT_P016, \
1135                                                         AV_PIX_FMT_NONE }, \
1136         .hw_configs     = cuvid_hw_configs, \
1137         .wrapper_name   = "cuvid", \
1138     };
1139
1140 #if CONFIG_HEVC_CUVID_DECODER
1141 DEFINE_CUVID_CODEC(hevc, HEVC)
1142 #endif
1143
1144 #if CONFIG_H264_CUVID_DECODER
1145 DEFINE_CUVID_CODEC(h264, H264)
1146 #endif
1147
1148 #if CONFIG_MJPEG_CUVID_DECODER
1149 DEFINE_CUVID_CODEC(mjpeg, MJPEG)
1150 #endif
1151
1152 #if CONFIG_MPEG1_CUVID_DECODER
1153 DEFINE_CUVID_CODEC(mpeg1, MPEG1VIDEO)
1154 #endif
1155
1156 #if CONFIG_MPEG2_CUVID_DECODER
1157 DEFINE_CUVID_CODEC(mpeg2, MPEG2VIDEO)
1158 #endif
1159
1160 #if CONFIG_MPEG4_CUVID_DECODER
1161 DEFINE_CUVID_CODEC(mpeg4, MPEG4)
1162 #endif
1163
1164 #if CONFIG_VP8_CUVID_DECODER
1165 DEFINE_CUVID_CODEC(vp8, VP8)
1166 #endif
1167
1168 #if CONFIG_VP9_CUVID_DECODER
1169 DEFINE_CUVID_CODEC(vp9, VP9)
1170 #endif
1171
1172 #if CONFIG_VC1_CUVID_DECODER
1173 DEFINE_CUVID_CODEC(vc1, VC1)
1174 #endif