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