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/fifo.h"
29 #include "libavutil/log.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/pixdesc.h"
37 typedef struct CuvidContext
41 CUvideodecoder cudecoder;
42 CUvideoparser cuparser;
46 int drop_second_field;
62 AVBufferRef *hwdevice;
67 AVFifoBuffer *frame_queue;
70 int deint_mode_current;
76 cudaVideoCodec codec_type;
77 cudaVideoChromaFormat chroma_format;
79 CUVIDDECODECAPS caps8, caps10, caps12;
81 CUVIDPARSERPARAMS cuparseinfo;
82 CUVIDEOFORMATEX cuparse_ext;
88 typedef struct CuvidParsedFrame
90 CUVIDPARSERDISPINFO dispinfo;
95 static int check_cu(AVCodecContext *avctx, CUresult err, const char *func)
97 CuvidContext *ctx = avctx->priv_data;
99 const char *err_string;
101 av_log(avctx, AV_LOG_TRACE, "Calling %s\n", func);
103 if (err == CUDA_SUCCESS)
106 ctx->cudl->cuGetErrorName(err, &err_name);
107 ctx->cudl->cuGetErrorString(err, &err_string);
109 av_log(avctx, AV_LOG_ERROR, "%s failed", func);
110 if (err_name && err_string)
111 av_log(avctx, AV_LOG_ERROR, " -> %s: %s", err_name, err_string);
112 av_log(avctx, AV_LOG_ERROR, "\n");
114 return AVERROR_EXTERNAL;
117 #define CHECK_CU(x) check_cu(avctx, (x), #x)
119 static int CUDAAPI cuvid_handle_video_sequence(void *opaque, CUVIDEOFORMAT* format)
121 AVCodecContext *avctx = opaque;
122 CuvidContext *ctx = avctx->priv_data;
123 AVHWFramesContext *hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
124 CUVIDDECODECAPS *caps = NULL;
125 CUVIDDECODECREATEINFO cuinfo;
128 int old_width = avctx->width;
129 int old_height = avctx->height;
131 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
132 AV_PIX_FMT_NONE, // Will be updated below
135 av_log(avctx, AV_LOG_TRACE, "pfnSequenceCallback, progressive_sequence=%d\n", format->progressive_sequence);
137 memset(&cuinfo, 0, sizeof(cuinfo));
139 ctx->internal_error = 0;
141 avctx->coded_width = cuinfo.ulWidth = format->coded_width;
142 avctx->coded_height = cuinfo.ulHeight = format->coded_height;
145 cuinfo.display_area.left = format->display_area.left + ctx->crop.left;
146 cuinfo.display_area.top = format->display_area.top + ctx->crop.top;
147 cuinfo.display_area.right = format->display_area.right - ctx->crop.right;
148 cuinfo.display_area.bottom = format->display_area.bottom - ctx->crop.bottom;
150 // width and height need to be set before calling ff_get_format
151 if (ctx->resize_expr) {
152 avctx->width = ctx->resize.width;
153 avctx->height = ctx->resize.height;
155 avctx->width = cuinfo.display_area.right - cuinfo.display_area.left;
156 avctx->height = cuinfo.display_area.bottom - cuinfo.display_area.top;
159 // target width/height need to be multiples of two
160 cuinfo.ulTargetWidth = avctx->width = (avctx->width + 1) & ~1;
161 cuinfo.ulTargetHeight = avctx->height = (avctx->height + 1) & ~1;
163 // aspect ratio conversion, 1:1, depends on scaled resolution
164 cuinfo.target_rect.left = 0;
165 cuinfo.target_rect.top = 0;
166 cuinfo.target_rect.right = cuinfo.ulTargetWidth;
167 cuinfo.target_rect.bottom = cuinfo.ulTargetHeight;
169 switch (format->bit_depth_luma_minus8) {
171 pix_fmts[1] = AV_PIX_FMT_NV12;
175 pix_fmts[1] = AV_PIX_FMT_P010;
179 pix_fmts[1] = AV_PIX_FMT_P016;
186 if (!caps || !caps->bIsSupported) {
187 av_log(avctx, AV_LOG_ERROR, "unsupported bit depth: %d\n",
188 format->bit_depth_luma_minus8 + 8);
189 ctx->internal_error = AVERROR(EINVAL);
193 surface_fmt = ff_get_format(avctx, pix_fmts);
194 if (surface_fmt < 0) {
195 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", surface_fmt);
196 ctx->internal_error = AVERROR(EINVAL);
200 av_log(avctx, AV_LOG_VERBOSE, "Formats: Original: %s | HW: %s | SW: %s\n",
201 av_get_pix_fmt_name(avctx->pix_fmt),
202 av_get_pix_fmt_name(surface_fmt),
203 av_get_pix_fmt_name(avctx->sw_pix_fmt));
205 avctx->pix_fmt = surface_fmt;
207 // Update our hwframe ctx, as the get_format callback might have refreshed it!
208 if (avctx->hw_frames_ctx) {
209 av_buffer_unref(&ctx->hwframe);
211 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
213 ctx->internal_error = AVERROR(ENOMEM);
217 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
220 ff_set_sar(avctx, av_div_q(
221 (AVRational){ format->display_aspect_ratio.x, format->display_aspect_ratio.y },
222 (AVRational){ avctx->width, avctx->height }));
224 ctx->deint_mode_current = format->progressive_sequence
225 ? cudaVideoDeinterlaceMode_Weave
228 if (!format->progressive_sequence && ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave)
229 avctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT;
231 avctx->flags &= ~AV_CODEC_FLAG_INTERLACED_DCT;
233 if (format->video_signal_description.video_full_range_flag)
234 avctx->color_range = AVCOL_RANGE_JPEG;
236 avctx->color_range = AVCOL_RANGE_MPEG;
238 avctx->color_primaries = format->video_signal_description.color_primaries;
239 avctx->color_trc = format->video_signal_description.transfer_characteristics;
240 avctx->colorspace = format->video_signal_description.matrix_coefficients;
243 avctx->bit_rate = format->bitrate;
245 if (format->frame_rate.numerator && format->frame_rate.denominator) {
246 avctx->framerate.num = format->frame_rate.numerator;
247 avctx->framerate.den = format->frame_rate.denominator;
251 && avctx->coded_width == format->coded_width
252 && avctx->coded_height == format->coded_height
253 && avctx->width == old_width
254 && avctx->height == old_height
255 && ctx->chroma_format == format->chroma_format
256 && ctx->codec_type == format->codec)
259 if (ctx->cudecoder) {
260 av_log(avctx, AV_LOG_TRACE, "Re-initializing decoder\n");
261 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder));
262 if (ctx->internal_error < 0)
264 ctx->cudecoder = NULL;
267 if (hwframe_ctx->pool && (
268 hwframe_ctx->width < avctx->width ||
269 hwframe_ctx->height < avctx->height ||
270 hwframe_ctx->format != AV_PIX_FMT_CUDA ||
271 hwframe_ctx->sw_format != avctx->sw_pix_fmt)) {
272 av_log(avctx, AV_LOG_ERROR, "AVHWFramesContext is already initialized with incompatible parameters\n");
273 av_log(avctx, AV_LOG_DEBUG, "width: %d <-> %d\n", hwframe_ctx->width, avctx->width);
274 av_log(avctx, AV_LOG_DEBUG, "height: %d <-> %d\n", hwframe_ctx->height, avctx->height);
275 av_log(avctx, AV_LOG_DEBUG, "format: %s <-> cuda\n", av_get_pix_fmt_name(hwframe_ctx->format));
276 av_log(avctx, AV_LOG_DEBUG, "sw_format: %s <-> %s\n",
277 av_get_pix_fmt_name(hwframe_ctx->sw_format), av_get_pix_fmt_name(avctx->sw_pix_fmt));
278 ctx->internal_error = AVERROR(EINVAL);
282 if (format->chroma_format != cudaVideoChromaFormat_420) {
283 av_log(avctx, AV_LOG_ERROR, "Chroma formats other than 420 are not supported\n");
284 ctx->internal_error = AVERROR(EINVAL);
288 ctx->chroma_format = format->chroma_format;
290 cuinfo.CodecType = ctx->codec_type = format->codec;
291 cuinfo.ChromaFormat = format->chroma_format;
293 switch (avctx->sw_pix_fmt) {
294 case AV_PIX_FMT_NV12:
295 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
297 case AV_PIX_FMT_P010:
298 case AV_PIX_FMT_P016:
299 cuinfo.OutputFormat = cudaVideoSurfaceFormat_P016;
302 av_log(avctx, AV_LOG_ERROR, "Output formats other than NV12, P010 or P016 are not supported\n");
303 ctx->internal_error = AVERROR(EINVAL);
307 cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
308 cuinfo.ulNumOutputSurfaces = 1;
309 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
310 cuinfo.bitDepthMinus8 = format->bit_depth_luma_minus8;
311 cuinfo.DeinterlaceMode = ctx->deint_mode_current;
313 if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave && !ctx->drop_second_field)
314 avctx->framerate = av_mul_q(avctx->framerate, (AVRational){2, 1});
316 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&ctx->cudecoder, &cuinfo));
317 if (ctx->internal_error < 0)
320 if (!hwframe_ctx->pool) {
321 hwframe_ctx->format = AV_PIX_FMT_CUDA;
322 hwframe_ctx->sw_format = avctx->sw_pix_fmt;
323 hwframe_ctx->width = avctx->width;
324 hwframe_ctx->height = avctx->height;
326 if ((ctx->internal_error = av_hwframe_ctx_init(ctx->hwframe)) < 0) {
327 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_init failed\n");
335 static int CUDAAPI cuvid_handle_picture_decode(void *opaque, CUVIDPICPARAMS* picparams)
337 AVCodecContext *avctx = opaque;
338 CuvidContext *ctx = avctx->priv_data;
340 av_log(avctx, AV_LOG_TRACE, "pfnDecodePicture\n");
342 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDecodePicture(ctx->cudecoder, picparams));
343 if (ctx->internal_error < 0)
349 static int CUDAAPI cuvid_handle_picture_display(void *opaque, CUVIDPARSERDISPINFO* dispinfo)
351 AVCodecContext *avctx = opaque;
352 CuvidContext *ctx = avctx->priv_data;
353 CuvidParsedFrame parsed_frame = { { 0 } };
355 parsed_frame.dispinfo = *dispinfo;
356 ctx->internal_error = 0;
358 if (ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave) {
359 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
361 parsed_frame.is_deinterlacing = 1;
362 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
363 if (!ctx->drop_second_field) {
364 parsed_frame.second_field = 1;
365 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
372 static int cuvid_is_buffer_full(AVCodecContext *avctx)
374 CuvidContext *ctx = avctx->priv_data;
376 return (av_fifo_size(ctx->frame_queue) / sizeof(CuvidParsedFrame)) + 2 > ctx->nb_surfaces;
379 static int cuvid_decode_packet(AVCodecContext *avctx, const AVPacket *avpkt)
381 CuvidContext *ctx = avctx->priv_data;
382 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
383 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
384 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
385 CUVIDSOURCEDATAPACKET cupkt;
386 AVPacket filter_packet = { 0 };
387 AVPacket filtered_packet = { 0 };
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 if (ctx->bsf && avpkt && avpkt->size) {
399 if ((ret = av_packet_ref(&filter_packet, avpkt)) < 0) {
400 av_log(avctx, AV_LOG_ERROR, "av_packet_ref failed\n");
404 if ((ret = av_bsf_send_packet(ctx->bsf, &filter_packet)) < 0) {
405 av_log(avctx, AV_LOG_ERROR, "av_bsf_send_packet failed\n");
406 av_packet_unref(&filter_packet);
410 if ((ret = av_bsf_receive_packet(ctx->bsf, &filtered_packet)) < 0) {
411 av_log(avctx, AV_LOG_ERROR, "av_bsf_receive_packet failed\n");
415 avpkt = &filtered_packet;
418 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
420 av_packet_unref(&filtered_packet);
424 memset(&cupkt, 0, sizeof(cupkt));
426 if (avpkt && avpkt->size) {
427 cupkt.payload_size = avpkt->size;
428 cupkt.payload = avpkt->data;
430 if (avpkt->pts != AV_NOPTS_VALUE) {
431 cupkt.flags = CUVID_PKT_TIMESTAMP;
432 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
433 cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000});
435 cupkt.timestamp = avpkt->pts;
438 cupkt.flags = CUVID_PKT_ENDOFSTREAM;
439 ctx->decoder_flushing = 1;
442 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &cupkt));
444 av_packet_unref(&filtered_packet);
449 // cuvidParseVideoData doesn't return an error just because stuff failed...
450 if (ctx->internal_error) {
451 av_log(avctx, AV_LOG_ERROR, "cuvid decode callback error\n");
452 ret = ctx->internal_error;
457 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
469 static int cuvid_output_frame(AVCodecContext *avctx, AVFrame *frame)
471 CuvidContext *ctx = avctx->priv_data;
472 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
473 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
474 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
475 CUdeviceptr mapped_frame = 0;
476 int ret = 0, eret = 0;
478 av_log(avctx, AV_LOG_TRACE, "cuvid_output_frame\n");
480 if (ctx->decoder_flushing) {
481 ret = cuvid_decode_packet(avctx, NULL);
482 if (ret < 0 && ret != AVERROR_EOF)
486 if (!cuvid_is_buffer_full(avctx)) {
488 ret = ff_decode_get_packet(avctx, &pkt);
489 if (ret < 0 && ret != AVERROR_EOF)
491 ret = cuvid_decode_packet(avctx, &pkt);
492 av_packet_unref(&pkt);
493 // cuvid_is_buffer_full() should avoid this.
494 if (ret == AVERROR(EAGAIN))
495 ret = AVERROR_EXTERNAL;
496 if (ret < 0 && ret != AVERROR_EOF)
500 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
504 if (av_fifo_size(ctx->frame_queue)) {
505 CuvidParsedFrame parsed_frame;
506 CUVIDPROCPARAMS params;
507 unsigned int pitch = 0;
511 av_fifo_generic_read(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
513 memset(¶ms, 0, sizeof(params));
514 params.progressive_frame = parsed_frame.dispinfo.progressive_frame;
515 params.second_field = parsed_frame.second_field;
516 params.top_field_first = parsed_frame.dispinfo.top_field_first;
518 ret = CHECK_CU(ctx->cvdl->cuvidMapVideoFrame(ctx->cudecoder, parsed_frame.dispinfo.picture_index, &mapped_frame, &pitch, ¶ms));
522 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
523 ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0);
525 av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n");
529 ret = ff_decode_frame_props(avctx, frame);
531 av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n");
535 for (i = 0; i < 2; i++) {
536 CUDA_MEMCPY2D cpy = {
537 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
538 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
539 .srcDevice = mapped_frame,
540 .dstDevice = (CUdeviceptr)frame->data[i],
542 .dstPitch = frame->linesize[i],
544 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
545 .Height = avctx->height >> (i ? 1 : 0),
548 ret = CHECK_CU(ctx->cudl->cuMemcpy2D(&cpy));
552 offset += avctx->height;
554 } else if (avctx->pix_fmt == AV_PIX_FMT_NV12 ||
555 avctx->pix_fmt == AV_PIX_FMT_P010 ||
556 avctx->pix_fmt == AV_PIX_FMT_P016) {
557 AVFrame *tmp_frame = av_frame_alloc();
559 av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n");
560 ret = AVERROR(ENOMEM);
564 tmp_frame->format = AV_PIX_FMT_CUDA;
565 tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe);
566 tmp_frame->data[0] = (uint8_t*)mapped_frame;
567 tmp_frame->linesize[0] = pitch;
568 tmp_frame->data[1] = (uint8_t*)(mapped_frame + avctx->height * pitch);
569 tmp_frame->linesize[1] = pitch;
570 tmp_frame->width = avctx->width;
571 tmp_frame->height = avctx->height;
573 ret = ff_get_buffer(avctx, frame, 0);
575 av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n");
576 av_frame_free(&tmp_frame);
580 ret = av_hwframe_transfer_data(frame, tmp_frame, 0);
582 av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n");
583 av_frame_free(&tmp_frame);
586 av_frame_free(&tmp_frame);
592 frame->width = avctx->width;
593 frame->height = avctx->height;
594 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
595 frame->pts = av_rescale_q(parsed_frame.dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase);
597 frame->pts = parsed_frame.dispinfo.timestamp;
599 if (parsed_frame.second_field) {
600 if (ctx->prev_pts == INT64_MIN) {
601 ctx->prev_pts = frame->pts;
602 frame->pts += (avctx->pkt_timebase.den * avctx->framerate.den) / (avctx->pkt_timebase.num * avctx->framerate.num);
604 int pts_diff = (frame->pts - ctx->prev_pts) / 2;
605 ctx->prev_pts = frame->pts;
606 frame->pts += pts_diff;
610 /* CUVIDs opaque reordering breaks the internal pkt logic.
611 * So set pkt_pts and clear all the other pkt_ fields.
614 FF_DISABLE_DEPRECATION_WARNINGS
615 frame->pkt_pts = frame->pts;
616 FF_ENABLE_DEPRECATION_WARNINGS
619 frame->pkt_duration = 0;
620 frame->pkt_size = -1;
622 frame->interlaced_frame = !parsed_frame.is_deinterlacing && !parsed_frame.dispinfo.progressive_frame;
624 if (frame->interlaced_frame)
625 frame->top_field_first = parsed_frame.dispinfo.top_field_first;
626 } else if (ctx->decoder_flushing) {
629 ret = AVERROR(EAGAIN);
634 eret = CHECK_CU(ctx->cvdl->cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame));
636 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
644 static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
646 CuvidContext *ctx = avctx->priv_data;
647 AVFrame *frame = data;
650 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_frame\n");
652 if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave) {
653 av_log(avctx, AV_LOG_ERROR, "Deinterlacing is not supported via the old API\n");
654 return AVERROR(EINVAL);
657 if (!ctx->decoder_flushing) {
658 ret = cuvid_decode_packet(avctx, avpkt);
663 ret = cuvid_output_frame(avctx, frame);
664 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
666 } else if (ret < 0) {
675 static av_cold int cuvid_decode_end(AVCodecContext *avctx)
677 CuvidContext *ctx = avctx->priv_data;
679 av_fifo_freep(&ctx->frame_queue);
682 av_bsf_free(&ctx->bsf);
685 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
688 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
692 av_buffer_unref(&ctx->hwframe);
693 av_buffer_unref(&ctx->hwdevice);
695 cuvid_free_functions(&ctx->cvdl);
700 static int cuvid_test_capabilities(AVCodecContext *avctx,
701 const CUVIDPARSERPARAMS *cuparseinfo,
706 CuvidContext *ctx = avctx->priv_data;
707 CUVIDDECODECAPS *caps;
708 int res8 = 0, res10 = 0, res12 = 0;
710 ctx->caps8.eCodecType = ctx->caps10.eCodecType = ctx->caps12.eCodecType
711 = cuparseinfo->CodecType;
712 ctx->caps8.eChromaFormat = ctx->caps10.eChromaFormat = ctx->caps12.eChromaFormat
713 = cudaVideoChromaFormat_420;
715 ctx->caps8.nBitDepthMinus8 = 0;
716 ctx->caps10.nBitDepthMinus8 = 2;
717 ctx->caps12.nBitDepthMinus8 = 4;
719 res8 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps8));
720 res10 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps10));
721 res12 = CHECK_CU(ctx->cvdl->cuvidGetDecoderCaps(&ctx->caps12));
723 av_log(avctx, AV_LOG_VERBOSE, "CUVID capabilities for %s:\n", avctx->codec->name);
724 av_log(avctx, AV_LOG_VERBOSE, "8 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
725 ctx->caps8.bIsSupported, ctx->caps8.nMinWidth, ctx->caps8.nMaxWidth, ctx->caps8.nMinHeight, ctx->caps8.nMaxHeight);
726 av_log(avctx, AV_LOG_VERBOSE, "10 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
727 ctx->caps10.bIsSupported, ctx->caps10.nMinWidth, ctx->caps10.nMaxWidth, ctx->caps10.nMinHeight, ctx->caps10.nMaxHeight);
728 av_log(avctx, AV_LOG_VERBOSE, "12 bit: supported: %d, min_width: %d, max_width: %d, min_height: %d, max_height: %d\n",
729 ctx->caps12.bIsSupported, ctx->caps12.nMinWidth, ctx->caps12.nMaxWidth, ctx->caps12.nMinHeight, ctx->caps12.nMaxHeight);
748 if (!ctx->caps8.bIsSupported) {
749 av_log(avctx, AV_LOG_ERROR, "Codec %s is not supported.\n", avctx->codec->name);
750 return AVERROR(EINVAL);
753 if (!caps->bIsSupported) {
754 av_log(avctx, AV_LOG_ERROR, "Bit depth %d is not supported.\n", bit_depth);
755 return AVERROR(EINVAL);
758 if (probed_width > caps->nMaxWidth || probed_width < caps->nMinWidth) {
759 av_log(avctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
760 probed_width, caps->nMinWidth, caps->nMaxWidth);
761 return AVERROR(EINVAL);
764 if (probed_height > caps->nMaxHeight || probed_height < caps->nMinHeight) {
765 av_log(avctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
766 probed_height, caps->nMinHeight, caps->nMaxHeight);
767 return AVERROR(EINVAL);
773 static av_cold int cuvid_decode_init(AVCodecContext *avctx)
775 CuvidContext *ctx = avctx->priv_data;
776 AVCUDADeviceContext *device_hwctx;
777 AVHWDeviceContext *device_ctx;
778 AVHWFramesContext *hwframe_ctx;
779 CUVIDSOURCEDATAPACKET seq_pkt;
780 CUcontext cuda_ctx = NULL;
782 const AVBitStreamFilter *bsf;
785 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
789 int probed_width = avctx->coded_width ? avctx->coded_width : 1280;
790 int probed_height = avctx->coded_height ? avctx->coded_height : 720;
791 int probed_bit_depth = 8;
793 const AVPixFmtDescriptor *probe_desc = av_pix_fmt_desc_get(avctx->pix_fmt);
794 if (probe_desc && probe_desc->nb_components)
795 probed_bit_depth = probe_desc->comp[0].depth;
797 // Accelerated transcoding scenarios with 'ffmpeg' require that the
798 // pix_fmt be set to AV_PIX_FMT_CUDA early. The sw_pix_fmt, and the
799 // pix_fmt for non-accelerated transcoding, do not need to be correct
800 // but need to be set to something. We arbitrarily pick NV12.
801 ret = ff_get_format(avctx, pix_fmts);
803 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);
806 avctx->pix_fmt = ret;
808 if (ctx->resize_expr && sscanf(ctx->resize_expr, "%dx%d",
809 &ctx->resize.width, &ctx->resize.height) != 2) {
810 av_log(avctx, AV_LOG_ERROR, "Invalid resize expressions\n");
811 ret = AVERROR(EINVAL);
815 if (ctx->crop_expr && sscanf(ctx->crop_expr, "%dx%dx%dx%d",
816 &ctx->crop.top, &ctx->crop.bottom,
817 &ctx->crop.left, &ctx->crop.right) != 4) {
818 av_log(avctx, AV_LOG_ERROR, "Invalid cropping expressions\n");
819 ret = AVERROR(EINVAL);
823 ret = cuvid_load_functions(&ctx->cvdl);
825 av_log(avctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
829 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
830 if (!ctx->frame_queue) {
831 ret = AVERROR(ENOMEM);
835 if (avctx->hw_frames_ctx) {
836 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
838 ret = AVERROR(ENOMEM);
842 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
844 ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);
845 if (!ctx->hwdevice) {
846 ret = AVERROR(ENOMEM);
850 if (avctx->hw_device_ctx) {
851 ctx->hwdevice = av_buffer_ref(avctx->hw_device_ctx);
852 if (!ctx->hwdevice) {
853 ret = AVERROR(ENOMEM);
857 ret = av_hwdevice_ctx_create(&ctx->hwdevice, AV_HWDEVICE_TYPE_CUDA, ctx->cu_gpu, NULL, 0);
862 ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);
864 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");
865 ret = AVERROR(ENOMEM);
869 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
872 device_ctx = hwframe_ctx->device_ctx;
873 device_hwctx = device_ctx->hwctx;
875 cuda_ctx = device_hwctx->cuda_ctx;
876 ctx->cudl = device_hwctx->internal->cuda_dl;
878 memset(&ctx->cuparseinfo, 0, sizeof(ctx->cuparseinfo));
879 memset(&ctx->cuparse_ext, 0, sizeof(ctx->cuparse_ext));
880 memset(&seq_pkt, 0, sizeof(seq_pkt));
882 ctx->cuparseinfo.pExtVideoInfo = &ctx->cuparse_ext;
884 switch (avctx->codec->id) {
885 #if CONFIG_H264_CUVID_DECODER
886 case AV_CODEC_ID_H264:
887 ctx->cuparseinfo.CodecType = cudaVideoCodec_H264;
890 #if CONFIG_HEVC_CUVID_DECODER
891 case AV_CODEC_ID_HEVC:
892 ctx->cuparseinfo.CodecType = cudaVideoCodec_HEVC;
895 #if CONFIG_MJPEG_CUVID_DECODER
896 case AV_CODEC_ID_MJPEG:
897 ctx->cuparseinfo.CodecType = cudaVideoCodec_JPEG;
900 #if CONFIG_MPEG1_CUVID_DECODER
901 case AV_CODEC_ID_MPEG1VIDEO:
902 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG1;
905 #if CONFIG_MPEG2_CUVID_DECODER
906 case AV_CODEC_ID_MPEG2VIDEO:
907 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG2;
910 #if CONFIG_MPEG4_CUVID_DECODER
911 case AV_CODEC_ID_MPEG4:
912 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG4;
915 #if CONFIG_VP8_CUVID_DECODER
916 case AV_CODEC_ID_VP8:
917 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP8;
920 #if CONFIG_VP9_CUVID_DECODER
921 case AV_CODEC_ID_VP9:
922 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP9;
925 #if CONFIG_VC1_CUVID_DECODER
926 case AV_CODEC_ID_VC1:
927 ctx->cuparseinfo.CodecType = cudaVideoCodec_VC1;
931 av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");
935 if (avctx->codec->id == AV_CODEC_ID_H264 || avctx->codec->id == AV_CODEC_ID_HEVC) {
936 if (avctx->codec->id == AV_CODEC_ID_H264)
937 bsf = av_bsf_get_by_name("h264_mp4toannexb");
939 bsf = av_bsf_get_by_name("hevc_mp4toannexb");
942 ret = AVERROR_BSF_NOT_FOUND;
945 if (ret = av_bsf_alloc(bsf, &ctx->bsf)) {
948 if (((ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx)) < 0) || ((ret = av_bsf_init(ctx->bsf)) < 0)) {
949 av_bsf_free(&ctx->bsf);
953 ctx->cuparse_ext.format.seqhdr_data_length = ctx->bsf->par_out->extradata_size;
954 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
955 ctx->bsf->par_out->extradata,
956 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), ctx->bsf->par_out->extradata_size));
957 } else if (avctx->extradata_size > 0) {
958 ctx->cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;
959 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
961 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), avctx->extradata_size));
964 ctx->cuparseinfo.ulMaxNumDecodeSurfaces = ctx->nb_surfaces;
965 ctx->cuparseinfo.ulMaxDisplayDelay = 4;
966 ctx->cuparseinfo.pUserData = avctx;
967 ctx->cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;
968 ctx->cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;
969 ctx->cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;
971 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
975 ret = cuvid_test_capabilities(avctx, &ctx->cuparseinfo,
982 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
986 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
987 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
989 if (seq_pkt.payload && seq_pkt.payload_size) {
990 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
995 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
999 ctx->prev_pts = INT64_MIN;
1001 if (!avctx->pkt_timebase.num || !avctx->pkt_timebase.den)
1002 av_log(avctx, AV_LOG_WARNING, "Invalid pkt_timebase, passing timestamps as-is.\n");
1007 cuvid_decode_end(avctx);
1011 static void cuvid_flush(AVCodecContext *avctx)
1013 CuvidContext *ctx = avctx->priv_data;
1014 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
1015 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
1016 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
1017 CUVIDSOURCEDATAPACKET seq_pkt = { 0 };
1020 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
1024 av_fifo_freep(&ctx->frame_queue);
1026 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
1027 if (!ctx->frame_queue) {
1028 av_log(avctx, AV_LOG_ERROR, "Failed to recreate frame queue on flush\n");
1032 if (ctx->cudecoder) {
1033 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
1034 ctx->cudecoder = NULL;
1037 if (ctx->cuparser) {
1038 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
1039 ctx->cuparser = NULL;
1042 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
1046 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
1047 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
1049 if (seq_pkt.payload && seq_pkt.payload_size) {
1050 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
1055 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
1059 ctx->prev_pts = INT64_MIN;
1060 ctx->decoder_flushing = 0;
1064 av_log(avctx, AV_LOG_ERROR, "CUDA reinit on flush failed\n");
1067 #define OFFSET(x) offsetof(CuvidContext, x)
1068 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1069 static const AVOption options[] = {
1070 { "deint", "Set deinterlacing mode", OFFSET(deint_mode), AV_OPT_TYPE_INT, { .i64 = cudaVideoDeinterlaceMode_Weave }, cudaVideoDeinterlaceMode_Weave, cudaVideoDeinterlaceMode_Adaptive, VD, "deint" },
1071 { "weave", "Weave deinterlacing (do nothing)", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Weave }, 0, 0, VD, "deint" },
1072 { "bob", "Bob deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Bob }, 0, 0, VD, "deint" },
1073 { "adaptive", "Adaptive deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Adaptive }, 0, 0, VD, "deint" },
1074 { "gpu", "GPU to be used for decoding", OFFSET(cu_gpu), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1075 { "surfaces", "Maximum surfaces to be used for decoding", OFFSET(nb_surfaces), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, INT_MAX, VD },
1076 { "drop_second_field", "Drop second field when deinterlacing", OFFSET(drop_second_field), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1077 { "crop", "Crop (top)x(bottom)x(left)x(right)", OFFSET(crop_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1078 { "resize", "Resize (width)x(height)", OFFSET(resize_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1082 #define DEFINE_CUVID_CODEC(x, X) \
1083 static const AVClass x##_cuvid_class = { \
1084 .class_name = #x "_cuvid", \
1085 .item_name = av_default_item_name, \
1086 .option = options, \
1087 .version = LIBAVUTIL_VERSION_INT, \
1089 AVHWAccel ff_##x##_cuvid_hwaccel = { \
1090 .name = #x "_cuvid", \
1091 .type = AVMEDIA_TYPE_VIDEO, \
1092 .id = AV_CODEC_ID_##X, \
1093 .pix_fmt = AV_PIX_FMT_CUDA, \
1095 AVCodec ff_##x##_cuvid_decoder = { \
1096 .name = #x "_cuvid", \
1097 .long_name = NULL_IF_CONFIG_SMALL("Nvidia CUVID " #X " decoder"), \
1098 .type = AVMEDIA_TYPE_VIDEO, \
1099 .id = AV_CODEC_ID_##X, \
1100 .priv_data_size = sizeof(CuvidContext), \
1101 .priv_class = &x##_cuvid_class, \
1102 .init = cuvid_decode_init, \
1103 .close = cuvid_decode_end, \
1104 .decode = cuvid_decode_frame, \
1105 .receive_frame = cuvid_output_frame, \
1106 .flush = cuvid_flush, \
1107 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING, \
1108 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_CUDA, \
1112 AV_PIX_FMT_NONE }, \
1115 #if CONFIG_HEVC_CUVID_DECODER
1116 DEFINE_CUVID_CODEC(hevc, HEVC)
1119 #if CONFIG_H264_CUVID_DECODER
1120 DEFINE_CUVID_CODEC(h264, H264)
1123 #if CONFIG_MJPEG_CUVID_DECODER
1124 DEFINE_CUVID_CODEC(mjpeg, MJPEG)
1127 #if CONFIG_MPEG1_CUVID_DECODER
1128 DEFINE_CUVID_CODEC(mpeg1, MPEG1VIDEO)
1131 #if CONFIG_MPEG2_CUVID_DECODER
1132 DEFINE_CUVID_CODEC(mpeg2, MPEG2VIDEO)
1135 #if CONFIG_MPEG4_CUVID_DECODER
1136 DEFINE_CUVID_CODEC(mpeg4, MPEG4)
1139 #if CONFIG_VP8_CUVID_DECODER
1140 DEFINE_CUVID_CODEC(vp8, VP8)
1143 #if CONFIG_VP9_CUVID_DECODER
1144 DEFINE_CUVID_CODEC(vp9, VP9)
1147 #if CONFIG_VC1_CUVID_DECODER
1148 DEFINE_CUVID_CODEC(vc1, VC1)