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