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