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