3 * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "compat/cuda/dynlink_loader.h"
24 #include "libavutil/buffer.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/hwcontext.h"
27 #include "libavutil/hwcontext_cuda_internal.h"
28 #include "libavutil/cuda_check.h"
29 #include "libavutil/fifo.h"
30 #include "libavutil/log.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
40 #if !NVDECAPI_CHECK_VERSION(9, 0)
41 #define cudaVideoSurfaceFormat_YUV444 2
42 #define cudaVideoSurfaceFormat_YUV444_16Bit 3
45 typedef struct CuvidContext
49 CUvideodecoder cudecoder;
50 CUvideoparser cuparser;
54 int drop_second_field;
70 AVBufferRef *hwdevice;
73 AVFifoBuffer *frame_queue;
76 int deint_mode_current;
78 int progressive_sequence;
85 cudaVideoCodec codec_type;
86 cudaVideoChromaFormat chroma_format;
88 CUVIDDECODECAPS caps8, caps10, caps12;
90 CUVIDPARSERPARAMS cuparseinfo;
91 CUVIDEOFORMATEX cuparse_ext;
97 typedef struct CuvidParsedFrame
99 CUVIDPARSERDISPINFO dispinfo;
101 int is_deinterlacing;
104 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, ctx->cudl, x)
106 static int CUDAAPI cuvid_handle_video_sequence(void *opaque, CUVIDEOFORMAT* format)
108 AVCodecContext *avctx = opaque;
109 CuvidContext *ctx = avctx->priv_data;
110 AVHWFramesContext *hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
111 CUVIDDECODECAPS *caps = NULL;
112 CUVIDDECODECREATEINFO cuinfo;
116 int old_width = avctx->width;
117 int old_height = avctx->height;
119 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
120 AV_PIX_FMT_NONE, // Will be updated below
123 av_log(avctx, AV_LOG_TRACE, "pfnSequenceCallback, progressive_sequence=%d\n", format->progressive_sequence);
125 memset(&cuinfo, 0, sizeof(cuinfo));
127 ctx->internal_error = 0;
129 avctx->coded_width = cuinfo.ulWidth = format->coded_width;
130 avctx->coded_height = cuinfo.ulHeight = format->coded_height;
133 cuinfo.display_area.left = format->display_area.left + ctx->crop.left;
134 cuinfo.display_area.top = format->display_area.top + ctx->crop.top;
135 cuinfo.display_area.right = format->display_area.right - ctx->crop.right;
136 cuinfo.display_area.bottom = format->display_area.bottom - ctx->crop.bottom;
138 // width and height need to be set before calling ff_get_format
139 if (ctx->resize_expr) {
140 avctx->width = ctx->resize.width;
141 avctx->height = ctx->resize.height;
143 avctx->width = cuinfo.display_area.right - cuinfo.display_area.left;
144 avctx->height = cuinfo.display_area.bottom - cuinfo.display_area.top;
147 // target width/height need to be multiples of two
148 cuinfo.ulTargetWidth = avctx->width = (avctx->width + 1) & ~1;
149 cuinfo.ulTargetHeight = avctx->height = (avctx->height + 1) & ~1;
151 // aspect ratio conversion, 1:1, depends on scaled resolution
152 cuinfo.target_rect.left = 0;
153 cuinfo.target_rect.top = 0;
154 cuinfo.target_rect.right = cuinfo.ulTargetWidth;
155 cuinfo.target_rect.bottom = cuinfo.ulTargetHeight;
157 chroma_444 = format->chroma_format == cudaVideoChromaFormat_444;
159 switch (format->bit_depth_luma_minus8) {
161 pix_fmts[1] = chroma_444 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_NV12;
165 pix_fmts[1] = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P010;
169 pix_fmts[1] = chroma_444 ? AV_PIX_FMT_YUV444P16 : AV_PIX_FMT_P016;
176 if (!caps || !caps->bIsSupported) {
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);
183 surface_fmt = ff_get_format(avctx, pix_fmts);
184 if (surface_fmt < 0) {
185 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", surface_fmt);
186 ctx->internal_error = AVERROR(EINVAL);
190 av_log(avctx, AV_LOG_VERBOSE, "Formats: Original: %s | HW: %s | SW: %s\n",
191 av_get_pix_fmt_name(avctx->pix_fmt),
192 av_get_pix_fmt_name(surface_fmt),
193 av_get_pix_fmt_name(avctx->sw_pix_fmt));
195 avctx->pix_fmt = surface_fmt;
197 // Update our hwframe ctx, as the get_format callback might have refreshed it!
198 if (avctx->hw_frames_ctx) {
199 av_buffer_unref(&ctx->hwframe);
201 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
203 ctx->internal_error = AVERROR(ENOMEM);
207 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
210 ff_set_sar(avctx, av_div_q(
211 (AVRational){ format->display_aspect_ratio.x, format->display_aspect_ratio.y },
212 (AVRational){ avctx->width, avctx->height }));
214 ctx->deint_mode_current = format->progressive_sequence
215 ? cudaVideoDeinterlaceMode_Weave
218 ctx->progressive_sequence = format->progressive_sequence;
220 if (!format->progressive_sequence && ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave)
221 avctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT;
223 avctx->flags &= ~AV_CODEC_FLAG_INTERLACED_DCT;
225 if (format->video_signal_description.video_full_range_flag)
226 avctx->color_range = AVCOL_RANGE_JPEG;
228 avctx->color_range = AVCOL_RANGE_MPEG;
230 avctx->color_primaries = format->video_signal_description.color_primaries;
231 avctx->color_trc = format->video_signal_description.transfer_characteristics;
232 avctx->colorspace = format->video_signal_description.matrix_coefficients;
235 avctx->bit_rate = format->bitrate;
237 if (format->frame_rate.numerator && format->frame_rate.denominator) {
238 avctx->framerate.num = format->frame_rate.numerator;
239 avctx->framerate.den = format->frame_rate.denominator;
243 && avctx->coded_width == format->coded_width
244 && avctx->coded_height == format->coded_height
245 && avctx->width == old_width
246 && avctx->height == old_height
247 && ctx->chroma_format == format->chroma_format
248 && ctx->codec_type == format->codec)
251 if (ctx->cudecoder) {
252 av_log(avctx, AV_LOG_TRACE, "Re-initializing decoder\n");
253 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder));
254 if (ctx->internal_error < 0)
256 ctx->cudecoder = NULL;
259 if (hwframe_ctx->pool && (
260 hwframe_ctx->width < avctx->width ||
261 hwframe_ctx->height < avctx->height ||
262 hwframe_ctx->format != AV_PIX_FMT_CUDA ||
263 hwframe_ctx->sw_format != avctx->sw_pix_fmt)) {
264 av_log(avctx, AV_LOG_ERROR, "AVHWFramesContext is already initialized with incompatible parameters\n");
265 av_log(avctx, AV_LOG_DEBUG, "width: %d <-> %d\n", hwframe_ctx->width, avctx->width);
266 av_log(avctx, AV_LOG_DEBUG, "height: %d <-> %d\n", hwframe_ctx->height, avctx->height);
267 av_log(avctx, AV_LOG_DEBUG, "format: %s <-> cuda\n", av_get_pix_fmt_name(hwframe_ctx->format));
268 av_log(avctx, AV_LOG_DEBUG, "sw_format: %s <-> %s\n",
269 av_get_pix_fmt_name(hwframe_ctx->sw_format), av_get_pix_fmt_name(avctx->sw_pix_fmt));
270 ctx->internal_error = AVERROR(EINVAL);
274 ctx->chroma_format = format->chroma_format;
276 cuinfo.CodecType = ctx->codec_type = format->codec;
277 cuinfo.ChromaFormat = format->chroma_format;
279 switch (avctx->sw_pix_fmt) {
280 case AV_PIX_FMT_NV12:
281 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
283 case AV_PIX_FMT_P010:
284 case AV_PIX_FMT_P016:
285 cuinfo.OutputFormat = cudaVideoSurfaceFormat_P016;
287 case AV_PIX_FMT_YUV444P:
288 cuinfo.OutputFormat = cudaVideoSurfaceFormat_YUV444;
290 case AV_PIX_FMT_YUV444P16:
291 cuinfo.OutputFormat = cudaVideoSurfaceFormat_YUV444_16Bit;
294 av_log(avctx, AV_LOG_ERROR, "Unsupported output format: %s\n",
295 av_get_pix_fmt_name(avctx->sw_pix_fmt));
296 ctx->internal_error = AVERROR(EINVAL);
300 cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
301 cuinfo.ulNumOutputSurfaces = 1;
302 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
303 cuinfo.bitDepthMinus8 = format->bit_depth_luma_minus8;
304 cuinfo.DeinterlaceMode = ctx->deint_mode_current;
306 if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave && !ctx->drop_second_field)
307 avctx->framerate = av_mul_q(avctx->framerate, (AVRational){2, 1});
309 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&ctx->cudecoder, &cuinfo));
310 if (ctx->internal_error < 0)
313 if (!hwframe_ctx->pool) {
314 hwframe_ctx->format = AV_PIX_FMT_CUDA;
315 hwframe_ctx->sw_format = avctx->sw_pix_fmt;
316 hwframe_ctx->width = avctx->width;
317 hwframe_ctx->height = avctx->height;
319 if ((ctx->internal_error = av_hwframe_ctx_init(ctx->hwframe)) < 0) {
320 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_init failed\n");
328 static int CUDAAPI cuvid_handle_picture_decode(void *opaque, CUVIDPICPARAMS* picparams)
330 AVCodecContext *avctx = opaque;
331 CuvidContext *ctx = avctx->priv_data;
333 av_log(avctx, AV_LOG_TRACE, "pfnDecodePicture\n");
335 ctx->key_frame[picparams->CurrPicIdx] = picparams->intra_pic_flag;
337 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDecodePicture(ctx->cudecoder, picparams));
338 if (ctx->internal_error < 0)
344 static int CUDAAPI cuvid_handle_picture_display(void *opaque, CUVIDPARSERDISPINFO* dispinfo)
346 AVCodecContext *avctx = opaque;
347 CuvidContext *ctx = avctx->priv_data;
348 CuvidParsedFrame parsed_frame = { { 0 } };
350 parsed_frame.dispinfo = *dispinfo;
351 ctx->internal_error = 0;
353 // For some reason, dispinfo->progressive_frame is sometimes wrong.
354 parsed_frame.dispinfo.progressive_frame = ctx->progressive_sequence;
356 if (ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave) {
357 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
359 parsed_frame.is_deinterlacing = 1;
360 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
361 if (!ctx->drop_second_field) {
362 parsed_frame.second_field = 1;
363 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
370 static int cuvid_is_buffer_full(AVCodecContext *avctx)
372 CuvidContext *ctx = avctx->priv_data;
374 int delay = ctx->cuparseinfo.ulMaxDisplayDelay;
375 if (ctx->deint_mode != cudaVideoDeinterlaceMode_Weave && !ctx->drop_second_field)
378 return (av_fifo_size(ctx->frame_queue) / sizeof(CuvidParsedFrame)) + delay >= ctx->nb_surfaces;
381 static int cuvid_decode_packet(AVCodecContext *avctx, const AVPacket *avpkt)
383 CuvidContext *ctx = avctx->priv_data;
384 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
385 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
386 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
387 CUVIDSOURCEDATAPACKET cupkt;
388 int ret = 0, eret = 0, is_flush = ctx->decoder_flushing;
390 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_packet\n");
392 if (is_flush && avpkt && avpkt->size)
395 if (cuvid_is_buffer_full(avctx) && avpkt && avpkt->size)
396 return AVERROR(EAGAIN);
398 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
403 memset(&cupkt, 0, sizeof(cupkt));
405 if (avpkt && avpkt->size) {
406 cupkt.payload_size = avpkt->size;
407 cupkt.payload = avpkt->data;
409 if (avpkt->pts != AV_NOPTS_VALUE) {
410 cupkt.flags = CUVID_PKT_TIMESTAMP;
411 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
412 cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000});
414 cupkt.timestamp = avpkt->pts;
417 cupkt.flags = CUVID_PKT_ENDOFSTREAM;
418 ctx->decoder_flushing = 1;
421 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &cupkt));
426 // cuvidParseVideoData doesn't return an error just because stuff failed...
427 if (ctx->internal_error) {
428 av_log(avctx, AV_LOG_ERROR, "cuvid decode callback error\n");
429 ret = ctx->internal_error;
434 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
446 static int cuvid_output_frame(AVCodecContext *avctx, AVFrame *frame)
448 CuvidContext *ctx = avctx->priv_data;
449 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
450 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
451 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
452 CUdeviceptr mapped_frame = 0;
453 int ret = 0, eret = 0;
455 av_log(avctx, AV_LOG_TRACE, "cuvid_output_frame\n");
457 if (ctx->decoder_flushing) {
458 ret = cuvid_decode_packet(avctx, NULL);
459 if (ret < 0 && ret != AVERROR_EOF)
463 if (!cuvid_is_buffer_full(avctx)) {
465 ret = ff_decode_get_packet(avctx, &pkt);
466 if (ret < 0 && ret != AVERROR_EOF)
468 ret = cuvid_decode_packet(avctx, &pkt);
469 av_packet_unref(&pkt);
470 // cuvid_is_buffer_full() should avoid this.
471 if (ret == AVERROR(EAGAIN))
472 ret = AVERROR_EXTERNAL;
473 if (ret < 0 && ret != AVERROR_EOF)
477 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
481 if (av_fifo_size(ctx->frame_queue)) {
482 const AVPixFmtDescriptor *pixdesc;
483 CuvidParsedFrame parsed_frame;
484 CUVIDPROCPARAMS params;
485 unsigned int pitch = 0;
489 av_fifo_generic_read(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
491 memset(¶ms, 0, sizeof(params));
492 params.progressive_frame = parsed_frame.dispinfo.progressive_frame;
493 params.second_field = parsed_frame.second_field;
494 params.top_field_first = parsed_frame.dispinfo.top_field_first;
496 ret = CHECK_CU(ctx->cvdl->cuvidMapVideoFrame(ctx->cudecoder, parsed_frame.dispinfo.picture_index, &mapped_frame, &pitch, ¶ms));
500 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
501 ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0);
503 av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n");
507 ret = ff_decode_frame_props(avctx, frame);
509 av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n");
513 pixdesc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
515 for (i = 0; i < pixdesc->nb_components; i++) {
516 int height = avctx->height >> (i ? pixdesc->log2_chroma_h : 0);
517 CUDA_MEMCPY2D cpy = {
518 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
519 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
520 .srcDevice = mapped_frame,
521 .dstDevice = (CUdeviceptr)frame->data[i],
523 .dstPitch = frame->linesize[i],
525 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
529 ret = CHECK_CU(ctx->cudl->cuMemcpy2DAsync(&cpy, device_hwctx->stream));
535 } else if (avctx->pix_fmt == AV_PIX_FMT_NV12 ||
536 avctx->pix_fmt == AV_PIX_FMT_P010 ||
537 avctx->pix_fmt == AV_PIX_FMT_P016 ||
538 avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
539 avctx->pix_fmt == AV_PIX_FMT_YUV444P16) {
540 unsigned int offset = 0;
541 AVFrame *tmp_frame = av_frame_alloc();
543 av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n");
544 ret = AVERROR(ENOMEM);
548 pixdesc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
550 tmp_frame->format = AV_PIX_FMT_CUDA;
551 tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe);
552 tmp_frame->width = avctx->width;
553 tmp_frame->height = avctx->height;
556 * Note that the following logic would not work for three plane
557 * YUV420 because the pitch value is different for the chroma
560 for (i = 0; i < pixdesc->nb_components; i++) {
561 tmp_frame->data[i] = (uint8_t*)mapped_frame + offset;
562 tmp_frame->linesize[i] = pitch;
563 offset += pitch * (avctx->height >> (i ? pixdesc->log2_chroma_h : 0));
566 ret = ff_get_buffer(avctx, frame, 0);
568 av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n");
569 av_frame_free(&tmp_frame);
573 ret = av_hwframe_transfer_data(frame, tmp_frame, 0);
575 av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n");
576 av_frame_free(&tmp_frame);
579 av_frame_free(&tmp_frame);
585 frame->key_frame = ctx->key_frame[parsed_frame.dispinfo.picture_index];
586 frame->width = avctx->width;
587 frame->height = avctx->height;
588 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
589 frame->pts = av_rescale_q(parsed_frame.dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase);
591 frame->pts = parsed_frame.dispinfo.timestamp;
593 if (parsed_frame.second_field) {
594 if (ctx->prev_pts == INT64_MIN) {
595 ctx->prev_pts = frame->pts;
596 frame->pts += (avctx->pkt_timebase.den * avctx->framerate.den) / (avctx->pkt_timebase.num * avctx->framerate.num);
598 int pts_diff = (frame->pts - ctx->prev_pts) / 2;
599 ctx->prev_pts = frame->pts;
600 frame->pts += pts_diff;
604 /* CUVIDs opaque reordering breaks the internal pkt logic.
605 * So set pkt_pts and clear all the other pkt_ fields.
608 FF_DISABLE_DEPRECATION_WARNINGS
609 frame->pkt_pts = frame->pts;
610 FF_ENABLE_DEPRECATION_WARNINGS
613 frame->pkt_duration = 0;
614 frame->pkt_size = -1;
616 frame->interlaced_frame = !parsed_frame.is_deinterlacing && !parsed_frame.dispinfo.progressive_frame;
618 if (frame->interlaced_frame)
619 frame->top_field_first = parsed_frame.dispinfo.top_field_first;
620 } else if (ctx->decoder_flushing) {
623 ret = AVERROR(EAGAIN);
628 eret = CHECK_CU(ctx->cvdl->cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame));
630 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
638 static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
640 CuvidContext *ctx = avctx->priv_data;
641 AVFrame *frame = data;
644 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_frame\n");
646 if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave) {
647 av_log(avctx, AV_LOG_ERROR, "Deinterlacing is not supported via the old API\n");
648 return AVERROR(EINVAL);
651 if (!ctx->decoder_flushing) {
652 ret = cuvid_decode_packet(avctx, avpkt);
657 ret = cuvid_output_frame(avctx, frame);
658 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
660 } else if (ret < 0) {
669 static av_cold int cuvid_decode_end(AVCodecContext *avctx)
671 CuvidContext *ctx = avctx->priv_data;
673 av_fifo_freep(&ctx->frame_queue);
676 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
679 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
683 av_buffer_unref(&ctx->hwframe);
684 av_buffer_unref(&ctx->hwdevice);
686 av_freep(&ctx->key_frame);
688 cuvid_free_functions(&ctx->cvdl);
693 static int cuvid_test_capabilities(AVCodecContext *avctx,
694 const CUVIDPARSERPARAMS *cuparseinfo,
699 CuvidContext *ctx = avctx->priv_data;
700 CUVIDDECODECAPS *caps;
701 int res8 = 0, res10 = 0, res12 = 0;
703 if (!ctx->cvdl->cuvidGetDecoderCaps) {
704 av_log(avctx, AV_LOG_WARNING, "Used Nvidia driver is too old to perform a capability check.\n");
705 av_log(avctx, AV_LOG_WARNING, "The minimum required version is "
706 #if defined(_WIN32) || defined(__CYGWIN__)
711 ". Continuing blind.\n");
712 ctx->caps8.bIsSupported = ctx->caps10.bIsSupported = 1;
713 // 12 bit was not supported before the capability check was introduced, so disable it.
714 ctx->caps12.bIsSupported = 0;
718 ctx->caps8.eCodecType = ctx->caps10.eCodecType = ctx->caps12.eCodecType
719 = cuparseinfo->CodecType;
720 ctx->caps8.eChromaFormat = ctx->caps10.eChromaFormat = ctx->caps12.eChromaFormat
721 = cudaVideoChromaFormat_420;
723 ctx->caps8.nBitDepthMinus8 = 0;
724 ctx->caps10.nBitDepthMinus8 = 2;
725 ctx->caps12.nBitDepthMinus8 = 4;
727 res8 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps8));
728 res10 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps10));
729 res12 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps12));
731 av_log(avctx, AV_LOG_VERBOSE, "CUVID capabilities for %s:\n", avctx->codec->name);
732 av_log(avctx, AV_LOG_VERBOSE, "8 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
733 ctx->caps8.bIsSupported, ctx->caps8.nMinWidth, ctx->caps8.nMaxWidth, ctx->caps8.nMinHeight, ctx->caps8.nMaxHeight);
734 av_log(avctx, AV_LOG_VERBOSE, "10 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
735 ctx->caps10.bIsSupported, ctx->caps10.nMinWidth, ctx->caps10.nMaxWidth, ctx->caps10.nMinHeight, ctx->caps10.nMaxHeight);
736 av_log(avctx, AV_LOG_VERBOSE, "12 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
737 ctx->caps12.bIsSupported, ctx->caps12.nMinWidth, ctx->caps12.nMaxWidth, ctx->caps12.nMinHeight, ctx->caps12.nMaxHeight);
756 if (!ctx->caps8.bIsSupported) {
757 av_log(avctx, AV_LOG_ERROR, "Codec %s is not supported.\n", avctx->codec->name);
758 return AVERROR(EINVAL);
761 if (!caps->bIsSupported) {
762 av_log(avctx, AV_LOG_ERROR, "Bit depth %d is not supported.\n", bit_depth);
763 return AVERROR(EINVAL);
766 if (probed_width > caps->nMaxWidth || probed_width < caps->nMinWidth) {
767 av_log(avctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
768 probed_width, caps->nMinWidth, caps->nMaxWidth);
769 return AVERROR(EINVAL);
772 if (probed_height > caps->nMaxHeight || probed_height < caps->nMinHeight) {
773 av_log(avctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
774 probed_height, caps->nMinHeight, caps->nMaxHeight);
775 return AVERROR(EINVAL);
778 if ((probed_width * probed_height) / 256 > caps->nMaxMBCount) {
779 av_log(avctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
780 (int)(probed_width * probed_height) / 256, caps->nMaxMBCount);
781 return AVERROR(EINVAL);
787 static av_cold int cuvid_decode_init(AVCodecContext *avctx)
789 CuvidContext *ctx = avctx->priv_data;
790 AVCUDADeviceContext *device_hwctx;
791 AVHWDeviceContext *device_ctx;
792 AVHWFramesContext *hwframe_ctx;
793 CUVIDSOURCEDATAPACKET seq_pkt;
794 CUcontext cuda_ctx = NULL;
798 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
802 int probed_width = avctx->coded_width ? avctx->coded_width : 1280;
803 int probed_height = avctx->coded_height ? avctx->coded_height : 720;
804 int probed_bit_depth = 8;
806 const AVPixFmtDescriptor *probe_desc = av_pix_fmt_desc_get(avctx->pix_fmt);
807 if (probe_desc && probe_desc->nb_components)
808 probed_bit_depth = probe_desc->comp[0].depth;
810 // Accelerated transcoding scenarios with 'ffmpeg' require that the
811 // pix_fmt be set to AV_PIX_FMT_CUDA early. The sw_pix_fmt, and the
812 // pix_fmt for non-accelerated transcoding, do not need to be correct
813 // but need to be set to something. We arbitrarily pick NV12.
814 ret = ff_get_format(avctx, pix_fmts);
816 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);
819 avctx->pix_fmt = ret;
821 if (ctx->resize_expr && sscanf(ctx->resize_expr, "%dx%d",
822 &ctx->resize.width, &ctx->resize.height) != 2) {
823 av_log(avctx, AV_LOG_ERROR, "Invalid resize expressions\n");
824 ret = AVERROR(EINVAL);
828 if (ctx->crop_expr && sscanf(ctx->crop_expr, "%dx%dx%dx%d",
829 &ctx->crop.top, &ctx->crop.bottom,
830 &ctx->crop.left, &ctx->crop.right) != 4) {
831 av_log(avctx, AV_LOG_ERROR, "Invalid cropping expressions\n");
832 ret = AVERROR(EINVAL);
836 ret = cuvid_load_functions(&ctx->cvdl, avctx);
838 av_log(avctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
842 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
843 if (!ctx->frame_queue) {
844 ret = AVERROR(ENOMEM);
848 if (avctx->hw_frames_ctx) {
849 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
851 ret = AVERROR(ENOMEM);
855 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
857 ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);
858 if (!ctx->hwdevice) {
859 ret = AVERROR(ENOMEM);
863 if (avctx->hw_device_ctx) {
864 ctx->hwdevice = av_buffer_ref(avctx->hw_device_ctx);
865 if (!ctx->hwdevice) {
866 ret = AVERROR(ENOMEM);
870 ret = av_hwdevice_ctx_create(&ctx->hwdevice, AV_HWDEVICE_TYPE_CUDA, ctx->cu_gpu, NULL, 0);
875 ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);
877 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");
878 ret = AVERROR(ENOMEM);
882 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
885 device_ctx = hwframe_ctx->device_ctx;
886 device_hwctx = device_ctx->hwctx;
888 cuda_ctx = device_hwctx->cuda_ctx;
889 ctx->cudl = device_hwctx->internal->cuda_dl;
891 memset(&ctx->cuparseinfo, 0, sizeof(ctx->cuparseinfo));
892 memset(&ctx->cuparse_ext, 0, sizeof(ctx->cuparse_ext));
893 memset(&seq_pkt, 0, sizeof(seq_pkt));
895 ctx->cuparseinfo.pExtVideoInfo = &ctx->cuparse_ext;
897 switch (avctx->codec->id) {
898 #if CONFIG_H264_CUVID_DECODER
899 case AV_CODEC_ID_H264:
900 ctx->cuparseinfo.CodecType = cudaVideoCodec_H264;
903 #if CONFIG_HEVC_CUVID_DECODER
904 case AV_CODEC_ID_HEVC:
905 ctx->cuparseinfo.CodecType = cudaVideoCodec_HEVC;
908 #if CONFIG_MJPEG_CUVID_DECODER
909 case AV_CODEC_ID_MJPEG:
910 ctx->cuparseinfo.CodecType = cudaVideoCodec_JPEG;
913 #if CONFIG_MPEG1_CUVID_DECODER
914 case AV_CODEC_ID_MPEG1VIDEO:
915 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG1;
918 #if CONFIG_MPEG2_CUVID_DECODER
919 case AV_CODEC_ID_MPEG2VIDEO:
920 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG2;
923 #if CONFIG_MPEG4_CUVID_DECODER
924 case AV_CODEC_ID_MPEG4:
925 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG4;
928 #if CONFIG_VP8_CUVID_DECODER
929 case AV_CODEC_ID_VP8:
930 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP8;
933 #if CONFIG_VP9_CUVID_DECODER
934 case AV_CODEC_ID_VP9:
935 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP9;
938 #if CONFIG_VC1_CUVID_DECODER
939 case AV_CODEC_ID_VC1:
940 ctx->cuparseinfo.CodecType = cudaVideoCodec_VC1;
944 av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");
948 if (avctx->codec->bsfs) {
949 const AVCodecParameters *par = avctx->internal->bsf->par_out;
950 ctx->cuparse_ext.format.seqhdr_data_length = par->extradata_size;
951 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
953 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), par->extradata_size));
954 } else if (avctx->extradata_size > 0) {
955 ctx->cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;
956 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
958 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), avctx->extradata_size));
961 ctx->key_frame = av_mallocz(ctx->nb_surfaces * sizeof(int));
962 if (!ctx->key_frame) {
963 ret = AVERROR(ENOMEM);
967 ctx->cuparseinfo.ulMaxNumDecodeSurfaces = ctx->nb_surfaces;
968 ctx->cuparseinfo.ulMaxDisplayDelay = 4;
969 ctx->cuparseinfo.pUserData = avctx;
970 ctx->cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;
971 ctx->cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;
972 ctx->cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;
974 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
978 ret = cuvid_test_capabilities(avctx, &ctx->cuparseinfo,
985 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
989 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
990 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
992 if (seq_pkt.payload && seq_pkt.payload_size) {
993 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
998 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
1002 ctx->prev_pts = INT64_MIN;
1004 if (!avctx->pkt_timebase.num || !avctx->pkt_timebase.den)
1005 av_log(avctx, AV_LOG_WARNING, "Invalid pkt_timebase, passing timestamps as-is.\n");
1010 cuvid_decode_end(avctx);
1014 static void cuvid_flush(AVCodecContext *avctx)
1016 CuvidContext *ctx = avctx->priv_data;
1017 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
1018 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
1019 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
1020 CUVIDSOURCEDATAPACKET seq_pkt = { 0 };
1023 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
1027 av_fifo_freep(&ctx->frame_queue);
1029 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
1030 if (!ctx->frame_queue) {
1031 av_log(avctx, AV_LOG_ERROR, "Failed to recreate frame queue on flush\n");
1035 if (ctx->cudecoder) {
1036 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
1037 ctx->cudecoder = NULL;
1040 if (ctx->cuparser) {
1041 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
1042 ctx->cuparser = NULL;
1045 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
1049 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
1050 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
1052 if (seq_pkt.payload && seq_pkt.payload_size) {
1053 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
1058 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
1062 ctx->prev_pts = INT64_MIN;
1063 ctx->decoder_flushing = 0;
1067 av_log(avctx, AV_LOG_ERROR, "CUDA reinit on flush failed\n");
1070 #define OFFSET(x) offsetof(CuvidContext, x)
1071 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1072 static const AVOption options[] = {
1073 { "deint", "Set deinterlacing mode", OFFSET(deint_mode), AV_OPT_TYPE_INT, { .i64 = cudaVideoDeinterlaceMode_Weave }, cudaVideoDeinterlaceMode_Weave, cudaVideoDeinterlaceMode_Adaptive, VD, "deint" },
1074 { "weave", "Weave deinterlacing (do nothing)", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Weave }, 0, 0, VD, "deint" },
1075 { "bob", "Bob deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Bob }, 0, 0, VD, "deint" },
1076 { "adaptive", "Adaptive deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Adaptive }, 0, 0, VD, "deint" },
1077 { "gpu", "GPU to be used for decoding", OFFSET(cu_gpu), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1078 { "surfaces", "Maximum surfaces to be used for decoding", OFFSET(nb_surfaces), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, INT_MAX, VD },
1079 { "drop_second_field", "Drop second field when deinterlacing", OFFSET(drop_second_field), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1080 { "crop", "Crop (top)x(bottom)x(left)x(right)", OFFSET(crop_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1081 { "resize", "Resize (width)x(height)", OFFSET(resize_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1085 static const AVCodecHWConfigInternal *cuvid_hw_configs[] = {
1086 &(const AVCodecHWConfigInternal) {
1088 .pix_fmt = AV_PIX_FMT_CUDA,
1089 .methods = AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX |
1090 AV_CODEC_HW_CONFIG_METHOD_INTERNAL,
1091 .device_type = AV_HWDEVICE_TYPE_CUDA
1098 #define DEFINE_CUVID_CODEC(x, X, bsf_name) \
1099 static const AVClass x##_cuvid_class = { \
1100 .class_name = #x "_cuvid", \
1101 .item_name = av_default_item_name, \
1102 .option = options, \
1103 .version = LIBAVUTIL_VERSION_INT, \
1105 AVCodec ff_##x##_cuvid_decoder = { \
1106 .name = #x "_cuvid", \
1107 .long_name = NULL_IF_CONFIG_SMALL("Nvidia CUVID " #X " decoder"), \
1108 .type = AVMEDIA_TYPE_VIDEO, \
1109 .id = AV_CODEC_ID_##X, \
1110 .priv_data_size = sizeof(CuvidContext), \
1111 .priv_class = &x##_cuvid_class, \
1112 .init = cuvid_decode_init, \
1113 .close = cuvid_decode_end, \
1114 .decode = cuvid_decode_frame, \
1115 .receive_frame = cuvid_output_frame, \
1116 .flush = cuvid_flush, \
1118 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_HARDWARE, \
1119 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_CUDA, \
1123 AV_PIX_FMT_NONE }, \
1124 .hw_configs = cuvid_hw_configs, \
1125 .wrapper_name = "cuvid", \
1128 #if CONFIG_HEVC_CUVID_DECODER
1129 DEFINE_CUVID_CODEC(hevc, HEVC, "hevc_mp4toannexb")
1132 #if CONFIG_H264_CUVID_DECODER
1133 DEFINE_CUVID_CODEC(h264, H264, "h264_mp4toannexb")
1136 #if CONFIG_MJPEG_CUVID_DECODER
1137 DEFINE_CUVID_CODEC(mjpeg, MJPEG, NULL)
1140 #if CONFIG_MPEG1_CUVID_DECODER
1141 DEFINE_CUVID_CODEC(mpeg1, MPEG1VIDEO, NULL)
1144 #if CONFIG_MPEG2_CUVID_DECODER
1145 DEFINE_CUVID_CODEC(mpeg2, MPEG2VIDEO, NULL)
1148 #if CONFIG_MPEG4_CUVID_DECODER
1149 DEFINE_CUVID_CODEC(mpeg4, MPEG4, NULL)
1152 #if CONFIG_VP8_CUVID_DECODER
1153 DEFINE_CUVID_CODEC(vp8, VP8, NULL)
1156 #if CONFIG_VP9_CUVID_DECODER
1157 DEFINE_CUVID_CODEC(vp9, VP9, NULL)
1160 #if CONFIG_VC1_CUVID_DECODER
1161 DEFINE_CUVID_CODEC(vc1, VC1, NULL)