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"
36 typedef struct CuvidContext
40 CUvideodecoder cudecoder;
41 CUvideoparser cuparser;
46 AVBufferRef *hwdevice;
51 AVFifoBuffer *frame_queue;
59 cudaVideoCodec codec_type;
60 cudaVideoChromaFormat chroma_format;
62 CUVIDPARSERPARAMS cuparseinfo;
63 CUVIDEOFORMATEX cuparse_ext;
69 typedef struct CuvidParsedFrame
71 CUVIDPARSERDISPINFO dispinfo;
76 static int check_cu(AVCodecContext *avctx, CUresult err, const char *func)
78 CuvidContext *ctx = avctx->priv_data;
80 const char *err_string;
82 av_log(avctx, AV_LOG_TRACE, "Calling %s\n", func);
84 if (err == CUDA_SUCCESS)
87 ctx->cudl->cuGetErrorName(err, &err_name);
88 ctx->cudl->cuGetErrorString(err, &err_string);
90 av_log(avctx, AV_LOG_ERROR, "%s failed", func);
91 if (err_name && err_string)
92 av_log(avctx, AV_LOG_ERROR, " -> %s: %s", err_name, err_string);
93 av_log(avctx, AV_LOG_ERROR, "\n");
95 return AVERROR_EXTERNAL;
98 #define CHECK_CU(x) check_cu(avctx, (x), #x)
100 static int CUDAAPI cuvid_handle_video_sequence(void *opaque, CUVIDEOFORMAT* format)
102 AVCodecContext *avctx = opaque;
103 CuvidContext *ctx = avctx->priv_data;
104 AVHWFramesContext *hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
105 CUVIDDECODECREATEINFO cuinfo;
108 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
109 AV_PIX_FMT_NONE, // Will be updated below
112 av_log(avctx, AV_LOG_TRACE, "pfnSequenceCallback, progressive_sequence=%d\n", format->progressive_sequence);
114 ctx->internal_error = 0;
116 switch (format->bit_depth_luma_minus8) {
118 pix_fmts[1] = AV_PIX_FMT_NV12;
121 pix_fmts[1] = AV_PIX_FMT_P010;
124 pix_fmts[1] = AV_PIX_FMT_P016;
127 av_log(avctx, AV_LOG_ERROR, "unsupported bit depth: %d\n",
128 format->bit_depth_luma_minus8 + 8);
129 ctx->internal_error = AVERROR(EINVAL);
132 surface_fmt = ff_get_format(avctx, pix_fmts);
133 if (surface_fmt < 0) {
134 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", surface_fmt);
135 ctx->internal_error = AVERROR(EINVAL);
139 av_log(avctx, AV_LOG_VERBOSE, "Formats: Original: %s | HW: %s | SW: %s\n",
140 av_get_pix_fmt_name(avctx->pix_fmt),
141 av_get_pix_fmt_name(surface_fmt),
142 av_get_pix_fmt_name(avctx->sw_pix_fmt));
144 avctx->pix_fmt = surface_fmt;
146 avctx->width = format->display_area.right;
147 avctx->height = format->display_area.bottom;
149 ff_set_sar(avctx, av_div_q(
150 (AVRational){ format->display_aspect_ratio.x, format->display_aspect_ratio.y },
151 (AVRational){ avctx->width, avctx->height }));
153 if (!format->progressive_sequence && ctx->deint_mode == cudaVideoDeinterlaceMode_Weave)
154 avctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT;
156 avctx->flags &= ~AV_CODEC_FLAG_INTERLACED_DCT;
158 if (format->video_signal_description.video_full_range_flag)
159 avctx->color_range = AVCOL_RANGE_JPEG;
161 avctx->color_range = AVCOL_RANGE_MPEG;
163 avctx->color_primaries = format->video_signal_description.color_primaries;
164 avctx->color_trc = format->video_signal_description.transfer_characteristics;
165 avctx->colorspace = format->video_signal_description.matrix_coefficients;
168 avctx->bit_rate = format->bitrate;
170 if (format->frame_rate.numerator && format->frame_rate.denominator) {
171 avctx->framerate.num = format->frame_rate.numerator;
172 avctx->framerate.den = format->frame_rate.denominator;
176 && avctx->coded_width == format->coded_width
177 && avctx->coded_height == format->coded_height
178 && ctx->chroma_format == format->chroma_format
179 && ctx->codec_type == format->codec)
182 if (ctx->cudecoder) {
183 av_log(avctx, AV_LOG_TRACE, "Re-initializing decoder\n");
184 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder));
185 if (ctx->internal_error < 0)
187 ctx->cudecoder = NULL;
190 if (hwframe_ctx->pool && (
191 hwframe_ctx->width < avctx->width ||
192 hwframe_ctx->height < avctx->height ||
193 hwframe_ctx->format != AV_PIX_FMT_CUDA ||
194 hwframe_ctx->sw_format != avctx->sw_pix_fmt)) {
195 av_log(avctx, AV_LOG_ERROR, "AVHWFramesContext is already initialized with incompatible parameters\n");
196 ctx->internal_error = AVERROR(EINVAL);
200 if (format->chroma_format != cudaVideoChromaFormat_420) {
201 av_log(avctx, AV_LOG_ERROR, "Chroma formats other than 420 are not supported\n");
202 ctx->internal_error = AVERROR(EINVAL);
206 avctx->coded_width = format->coded_width;
207 avctx->coded_height = format->coded_height;
209 ctx->chroma_format = format->chroma_format;
211 memset(&cuinfo, 0, sizeof(cuinfo));
213 cuinfo.CodecType = ctx->codec_type = format->codec;
214 cuinfo.ChromaFormat = format->chroma_format;
216 switch (avctx->sw_pix_fmt) {
217 case AV_PIX_FMT_NV12:
218 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
220 case AV_PIX_FMT_P010:
221 case AV_PIX_FMT_P016:
222 cuinfo.OutputFormat = cudaVideoSurfaceFormat_P016;
225 av_log(avctx, AV_LOG_ERROR, "Output formats other than NV12, P010 or P016 are not supported\n");
226 ctx->internal_error = AVERROR(EINVAL);
230 cuinfo.ulWidth = avctx->coded_width;
231 cuinfo.ulHeight = avctx->coded_height;
232 cuinfo.ulTargetWidth = cuinfo.ulWidth;
233 cuinfo.ulTargetHeight = cuinfo.ulHeight;
235 cuinfo.target_rect.left = 0;
236 cuinfo.target_rect.top = 0;
237 cuinfo.target_rect.right = cuinfo.ulWidth;
238 cuinfo.target_rect.bottom = cuinfo.ulHeight;
240 cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
241 cuinfo.ulNumOutputSurfaces = 1;
242 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
243 cuinfo.bitDepthMinus8 = format->bit_depth_luma_minus8;
245 if (format->progressive_sequence) {
246 ctx->deint_mode = cuinfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave;
248 cuinfo.DeinterlaceMode = ctx->deint_mode;
251 if (ctx->deint_mode != cudaVideoDeinterlaceMode_Weave)
252 avctx->framerate = av_mul_q(avctx->framerate, (AVRational){2, 1});
254 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&ctx->cudecoder, &cuinfo));
255 if (ctx->internal_error < 0)
258 if (!hwframe_ctx->pool) {
259 hwframe_ctx->format = AV_PIX_FMT_CUDA;
260 hwframe_ctx->sw_format = avctx->sw_pix_fmt;
261 hwframe_ctx->width = avctx->width;
262 hwframe_ctx->height = avctx->height;
264 if ((ctx->internal_error = av_hwframe_ctx_init(ctx->hwframe)) < 0) {
265 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_init failed\n");
273 static int CUDAAPI cuvid_handle_picture_decode(void *opaque, CUVIDPICPARAMS* picparams)
275 AVCodecContext *avctx = opaque;
276 CuvidContext *ctx = avctx->priv_data;
278 av_log(avctx, AV_LOG_TRACE, "pfnDecodePicture\n");
280 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDecodePicture(ctx->cudecoder, picparams));
281 if (ctx->internal_error < 0)
287 static int CUDAAPI cuvid_handle_picture_display(void *opaque, CUVIDPARSERDISPINFO* dispinfo)
289 AVCodecContext *avctx = opaque;
290 CuvidContext *ctx = avctx->priv_data;
291 CuvidParsedFrame parsed_frame = { { 0 } };
293 parsed_frame.dispinfo = *dispinfo;
294 ctx->internal_error = 0;
296 if (ctx->deint_mode == cudaVideoDeinterlaceMode_Weave) {
297 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
299 parsed_frame.is_deinterlacing = 1;
300 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
301 parsed_frame.second_field = 1;
302 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
308 static int cuvid_decode_packet(AVCodecContext *avctx, const AVPacket *avpkt)
310 CuvidContext *ctx = avctx->priv_data;
311 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
312 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
313 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
314 CUVIDSOURCEDATAPACKET cupkt;
315 AVPacket filter_packet = { 0 };
316 AVPacket filtered_packet = { 0 };
317 int ret = 0, eret = 0, is_flush = ctx->decoder_flushing;
319 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_packet\n");
321 if (is_flush && avpkt && avpkt->size)
324 if ((av_fifo_size(ctx->frame_queue) / sizeof(CuvidParsedFrame)) + 2 > ctx->nb_surfaces && avpkt && avpkt->size)
325 return AVERROR(EAGAIN);
327 if (ctx->bsf && avpkt && avpkt->size) {
328 if ((ret = av_packet_ref(&filter_packet, avpkt)) < 0) {
329 av_log(avctx, AV_LOG_ERROR, "av_packet_ref failed\n");
333 if ((ret = av_bsf_send_packet(ctx->bsf, &filter_packet)) < 0) {
334 av_log(avctx, AV_LOG_ERROR, "av_bsf_send_packet failed\n");
335 av_packet_unref(&filter_packet);
339 if ((ret = av_bsf_receive_packet(ctx->bsf, &filtered_packet)) < 0) {
340 av_log(avctx, AV_LOG_ERROR, "av_bsf_receive_packet failed\n");
344 avpkt = &filtered_packet;
347 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
349 av_packet_unref(&filtered_packet);
353 memset(&cupkt, 0, sizeof(cupkt));
355 if (avpkt && avpkt->size) {
356 cupkt.payload_size = avpkt->size;
357 cupkt.payload = avpkt->data;
359 if (avpkt->pts != AV_NOPTS_VALUE) {
360 cupkt.flags = CUVID_PKT_TIMESTAMP;
361 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
362 cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000});
364 cupkt.timestamp = avpkt->pts;
367 cupkt.flags = CUVID_PKT_ENDOFSTREAM;
368 ctx->decoder_flushing = 1;
371 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &cupkt));
373 av_packet_unref(&filtered_packet);
378 // cuvidParseVideoData doesn't return an error just because stuff failed...
379 if (ctx->internal_error) {
380 av_log(avctx, AV_LOG_ERROR, "cuvid decode callback error\n");
381 ret = ctx->internal_error;
386 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
398 static int cuvid_output_frame(AVCodecContext *avctx, AVFrame *frame)
400 CuvidContext *ctx = avctx->priv_data;
401 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
402 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
403 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
404 CUdeviceptr mapped_frame = 0;
405 int ret = 0, eret = 0;
407 av_log(avctx, AV_LOG_TRACE, "cuvid_output_frame\n");
409 if (ctx->decoder_flushing) {
410 ret = cuvid_decode_packet(avctx, NULL);
411 if (ret < 0 && ret != AVERROR_EOF)
415 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
419 if (av_fifo_size(ctx->frame_queue)) {
420 CuvidParsedFrame parsed_frame;
421 CUVIDPROCPARAMS params;
422 unsigned int pitch = 0;
426 av_fifo_generic_read(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
428 memset(¶ms, 0, sizeof(params));
429 params.progressive_frame = parsed_frame.dispinfo.progressive_frame;
430 params.second_field = parsed_frame.second_field;
431 params.top_field_first = parsed_frame.dispinfo.top_field_first;
433 ret = CHECK_CU(ctx->cvdl->cuvidMapVideoFrame(ctx->cudecoder, parsed_frame.dispinfo.picture_index, &mapped_frame, &pitch, ¶ms));
437 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
438 ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0);
440 av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n");
444 ret = ff_decode_frame_props(avctx, frame);
446 av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n");
450 for (i = 0; i < 2; i++) {
451 CUDA_MEMCPY2D cpy = {
452 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
453 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
454 .srcDevice = mapped_frame,
455 .dstDevice = (CUdeviceptr)frame->data[i],
457 .dstPitch = frame->linesize[i],
459 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
460 .Height = avctx->height >> (i ? 1 : 0),
463 ret = CHECK_CU(ctx->cudl->cuMemcpy2D(&cpy));
467 offset += avctx->coded_height;
469 } else if (avctx->pix_fmt == AV_PIX_FMT_NV12 ||
470 avctx->pix_fmt == AV_PIX_FMT_P010 ||
471 avctx->pix_fmt == AV_PIX_FMT_P016) {
472 AVFrame *tmp_frame = av_frame_alloc();
474 av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n");
475 ret = AVERROR(ENOMEM);
479 tmp_frame->format = AV_PIX_FMT_CUDA;
480 tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe);
481 tmp_frame->data[0] = (uint8_t*)mapped_frame;
482 tmp_frame->linesize[0] = pitch;
483 tmp_frame->data[1] = (uint8_t*)(mapped_frame + avctx->coded_height * pitch);
484 tmp_frame->linesize[1] = pitch;
485 tmp_frame->width = avctx->width;
486 tmp_frame->height = avctx->height;
488 ret = ff_get_buffer(avctx, frame, 0);
490 av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n");
491 av_frame_free(&tmp_frame);
495 ret = av_hwframe_transfer_data(frame, tmp_frame, 0);
497 av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n");
498 av_frame_free(&tmp_frame);
501 av_frame_free(&tmp_frame);
507 frame->width = avctx->width;
508 frame->height = avctx->height;
509 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
510 frame->pts = av_rescale_q(parsed_frame.dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase);
512 frame->pts = parsed_frame.dispinfo.timestamp;
514 if (parsed_frame.second_field) {
515 if (ctx->prev_pts == INT64_MIN) {
516 ctx->prev_pts = frame->pts;
517 frame->pts += (avctx->pkt_timebase.den * avctx->framerate.den) / (avctx->pkt_timebase.num * avctx->framerate.num);
519 int pts_diff = (frame->pts - ctx->prev_pts) / 2;
520 ctx->prev_pts = frame->pts;
521 frame->pts += pts_diff;
525 /* CUVIDs opaque reordering breaks the internal pkt logic.
526 * So set pkt_pts and clear all the other pkt_ fields.
529 FF_DISABLE_DEPRECATION_WARNINGS
530 frame->pkt_pts = frame->pts;
531 FF_ENABLE_DEPRECATION_WARNINGS
533 av_frame_set_pkt_pos(frame, -1);
534 av_frame_set_pkt_duration(frame, 0);
535 av_frame_set_pkt_size(frame, -1);
537 frame->interlaced_frame = !parsed_frame.is_deinterlacing && !parsed_frame.dispinfo.progressive_frame;
539 if (frame->interlaced_frame)
540 frame->top_field_first = parsed_frame.dispinfo.top_field_first;
541 } else if (ctx->decoder_flushing) {
544 ret = AVERROR(EAGAIN);
549 eret = CHECK_CU(ctx->cvdl->cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame));
551 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
559 static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
561 CuvidContext *ctx = avctx->priv_data;
562 AVFrame *frame = data;
565 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_frame\n");
567 if (ctx->deint_mode != cudaVideoDeinterlaceMode_Weave) {
568 av_log(avctx, AV_LOG_ERROR, "Deinterlacing is not supported via the old API\n");
569 return AVERROR(EINVAL);
572 if (!ctx->decoder_flushing) {
573 ret = cuvid_decode_packet(avctx, avpkt);
578 ret = cuvid_output_frame(avctx, frame);
579 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
581 } else if (ret < 0) {
590 static av_cold int cuvid_decode_end(AVCodecContext *avctx)
592 CuvidContext *ctx = avctx->priv_data;
594 av_fifo_freep(&ctx->frame_queue);
597 av_bsf_free(&ctx->bsf);
600 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
603 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
607 av_buffer_unref(&ctx->hwframe);
608 av_buffer_unref(&ctx->hwdevice);
610 cuvid_free_functions(&ctx->cvdl);
615 static int cuvid_test_dummy_decoder(AVCodecContext *avctx, CUVIDPARSERPARAMS *cuparseinfo)
617 CuvidContext *ctx = avctx->priv_data;
618 CUVIDDECODECREATEINFO cuinfo;
619 CUvideodecoder cudec = 0;
622 memset(&cuinfo, 0, sizeof(cuinfo));
624 cuinfo.CodecType = cuparseinfo->CodecType;
625 cuinfo.ChromaFormat = cudaVideoChromaFormat_420;
626 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
628 cuinfo.ulWidth = 1280;
629 cuinfo.ulHeight = 720;
630 cuinfo.ulTargetWidth = cuinfo.ulWidth;
631 cuinfo.ulTargetHeight = cuinfo.ulHeight;
633 cuinfo.target_rect.left = 0;
634 cuinfo.target_rect.top = 0;
635 cuinfo.target_rect.right = cuinfo.ulWidth;
636 cuinfo.target_rect.bottom = cuinfo.ulHeight;
638 cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
639 cuinfo.ulNumOutputSurfaces = 1;
640 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
641 cuinfo.bitDepthMinus8 = 0;
643 cuinfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave;
645 ret = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&cudec, &cuinfo));
649 ret = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(cudec));
656 static av_cold int cuvid_decode_init(AVCodecContext *avctx)
658 CuvidContext *ctx = avctx->priv_data;
659 AVCUDADeviceContext *device_hwctx;
660 AVHWDeviceContext *device_ctx;
661 AVHWFramesContext *hwframe_ctx;
662 CUVIDSOURCEDATAPACKET seq_pkt;
663 CUcontext cuda_ctx = NULL;
665 const AVBitStreamFilter *bsf;
668 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
672 // Accelerated transcoding scenarios with 'ffmpeg' require that the
673 // pix_fmt be set to AV_PIX_FMT_CUDA early. The sw_pix_fmt, and the
674 // pix_fmt for non-accelerated transcoding, do not need to be correct
675 // but need to be set to something. We arbitrarily pick NV12.
676 ret = ff_get_format(avctx, pix_fmts);
678 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);
681 avctx->pix_fmt = ret;
683 ret = cuvid_load_functions(&ctx->cvdl);
685 av_log(avctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
689 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
690 if (!ctx->frame_queue) {
691 ret = AVERROR(ENOMEM);
695 if (avctx->hw_frames_ctx) {
696 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
698 ret = AVERROR(ENOMEM);
702 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
704 ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);
705 if (!ctx->hwdevice) {
706 ret = AVERROR(ENOMEM);
710 ret = av_hwdevice_ctx_create(&ctx->hwdevice, AV_HWDEVICE_TYPE_CUDA, ctx->cu_gpu, NULL, 0);
714 ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);
716 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");
717 ret = AVERROR(ENOMEM);
721 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
724 device_ctx = hwframe_ctx->device_ctx;
725 device_hwctx = device_ctx->hwctx;
727 cuda_ctx = device_hwctx->cuda_ctx;
728 ctx->cudl = device_hwctx->internal->cuda_dl;
730 memset(&ctx->cuparseinfo, 0, sizeof(ctx->cuparseinfo));
731 memset(&ctx->cuparse_ext, 0, sizeof(ctx->cuparse_ext));
732 memset(&seq_pkt, 0, sizeof(seq_pkt));
734 ctx->cuparseinfo.pExtVideoInfo = &ctx->cuparse_ext;
736 switch (avctx->codec->id) {
737 #if CONFIG_H264_CUVID_DECODER
738 case AV_CODEC_ID_H264:
739 ctx->cuparseinfo.CodecType = cudaVideoCodec_H264;
742 #if CONFIG_HEVC_CUVID_DECODER
743 case AV_CODEC_ID_HEVC:
744 ctx->cuparseinfo.CodecType = cudaVideoCodec_HEVC;
747 #if CONFIG_MJPEG_CUVID_DECODER
748 case AV_CODEC_ID_MJPEG:
749 ctx->cuparseinfo.CodecType = cudaVideoCodec_JPEG;
752 #if CONFIG_MPEG1_CUVID_DECODER
753 case AV_CODEC_ID_MPEG1VIDEO:
754 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG1;
757 #if CONFIG_MPEG2_CUVID_DECODER
758 case AV_CODEC_ID_MPEG2VIDEO:
759 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG2;
762 #if CONFIG_MPEG4_CUVID_DECODER
763 case AV_CODEC_ID_MPEG4:
764 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG4;
767 #if CONFIG_VP8_CUVID_DECODER
768 case AV_CODEC_ID_VP8:
769 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP8;
772 #if CONFIG_VP9_CUVID_DECODER
773 case AV_CODEC_ID_VP9:
774 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP9;
777 #if CONFIG_VC1_CUVID_DECODER
778 case AV_CODEC_ID_VC1:
779 ctx->cuparseinfo.CodecType = cudaVideoCodec_VC1;
783 av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");
787 if (avctx->codec->id == AV_CODEC_ID_H264 || avctx->codec->id == AV_CODEC_ID_HEVC) {
788 if (avctx->codec->id == AV_CODEC_ID_H264)
789 bsf = av_bsf_get_by_name("h264_mp4toannexb");
791 bsf = av_bsf_get_by_name("hevc_mp4toannexb");
794 ret = AVERROR_BSF_NOT_FOUND;
797 if (ret = av_bsf_alloc(bsf, &ctx->bsf)) {
800 if (((ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx)) < 0) || ((ret = av_bsf_init(ctx->bsf)) < 0)) {
801 av_bsf_free(&ctx->bsf);
805 ctx->cuparse_ext.format.seqhdr_data_length = ctx->bsf->par_out->extradata_size;
806 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
807 ctx->bsf->par_out->extradata,
808 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), ctx->bsf->par_out->extradata_size));
809 } else if (avctx->extradata_size > 0) {
810 ctx->cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;
811 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
813 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), avctx->extradata_size));
816 ctx->cuparseinfo.ulMaxNumDecodeSurfaces = ctx->nb_surfaces;
817 ctx->cuparseinfo.ulMaxDisplayDelay = 4;
818 ctx->cuparseinfo.pUserData = avctx;
819 ctx->cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;
820 ctx->cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;
821 ctx->cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;
823 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
827 ret = cuvid_test_dummy_decoder(avctx, &ctx->cuparseinfo);
831 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
835 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
836 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
838 if (seq_pkt.payload && seq_pkt.payload_size) {
839 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
844 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
848 ctx->prev_pts = INT64_MIN;
850 if (!avctx->pkt_timebase.num || !avctx->pkt_timebase.den)
851 av_log(avctx, AV_LOG_WARNING, "Invalid pkt_timebase, passing timestamps as-is.\n");
856 cuvid_decode_end(avctx);
860 static void cuvid_flush(AVCodecContext *avctx)
862 CuvidContext *ctx = avctx->priv_data;
863 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
864 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
865 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
866 CUVIDSOURCEDATAPACKET seq_pkt = { 0 };
869 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
873 av_fifo_freep(&ctx->frame_queue);
875 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
876 if (!ctx->frame_queue) {
877 av_log(avctx, AV_LOG_ERROR, "Failed to recreate frame queue on flush\n");
881 if (ctx->cudecoder) {
882 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
883 ctx->cudecoder = NULL;
887 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
888 ctx->cuparser = NULL;
891 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
895 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
896 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
898 if (seq_pkt.payload && seq_pkt.payload_size) {
899 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
904 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
908 ctx->prev_pts = INT64_MIN;
909 ctx->decoder_flushing = 0;
913 av_log(avctx, AV_LOG_ERROR, "CUDA reinit on flush failed\n");
916 #define OFFSET(x) offsetof(CuvidContext, x)
917 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
918 static const AVOption options[] = {
919 { "deint", "Set deinterlacing mode", OFFSET(deint_mode), AV_OPT_TYPE_INT, { .i64 = cudaVideoDeinterlaceMode_Weave }, cudaVideoDeinterlaceMode_Weave, cudaVideoDeinterlaceMode_Adaptive, VD, "deint" },
920 { "weave", "Weave deinterlacing (do nothing)", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Weave }, 0, 0, VD, "deint" },
921 { "bob", "Bob deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Bob }, 0, 0, VD, "deint" },
922 { "adaptive", "Adaptive deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Adaptive }, 0, 0, VD, "deint" },
923 { "gpu", "GPU to be used for decoding", OFFSET(cu_gpu), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
924 { "surfaces", "Maximum surfaces to be used for decoding", OFFSET(nb_surfaces), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, INT_MAX, VD },
928 #define DEFINE_CUVID_CODEC(x, X) \
929 static const AVClass x##_cuvid_class = { \
930 .class_name = #x "_cuvid", \
931 .item_name = av_default_item_name, \
933 .version = LIBAVUTIL_VERSION_INT, \
935 AVHWAccel ff_##x##_cuvid_hwaccel = { \
936 .name = #x "_cuvid", \
937 .type = AVMEDIA_TYPE_VIDEO, \
938 .id = AV_CODEC_ID_##X, \
939 .pix_fmt = AV_PIX_FMT_CUDA, \
941 AVCodec ff_##x##_cuvid_decoder = { \
942 .name = #x "_cuvid", \
943 .long_name = NULL_IF_CONFIG_SMALL("Nvidia CUVID " #X " decoder"), \
944 .type = AVMEDIA_TYPE_VIDEO, \
945 .id = AV_CODEC_ID_##X, \
946 .priv_data_size = sizeof(CuvidContext), \
947 .priv_class = &x##_cuvid_class, \
948 .init = cuvid_decode_init, \
949 .close = cuvid_decode_end, \
950 .decode = cuvid_decode_frame, \
951 .send_packet = cuvid_decode_packet, \
952 .receive_frame = cuvid_output_frame, \
953 .flush = cuvid_flush, \
954 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING, \
955 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_CUDA, \
962 #if CONFIG_HEVC_CUVID_DECODER
963 DEFINE_CUVID_CODEC(hevc, HEVC)
966 #if CONFIG_H264_CUVID_DECODER
967 DEFINE_CUVID_CODEC(h264, H264)
970 #if CONFIG_MJPEG_CUVID_DECODER
971 DEFINE_CUVID_CODEC(mjpeg, MJPEG)
974 #if CONFIG_MPEG1_CUVID_DECODER
975 DEFINE_CUVID_CODEC(mpeg1, MPEG1VIDEO)
978 #if CONFIG_MPEG2_CUVID_DECODER
979 DEFINE_CUVID_CODEC(mpeg2, MPEG2VIDEO)
982 #if CONFIG_MPEG4_CUVID_DECODER
983 DEFINE_CUVID_CODEC(mpeg4, MPEG4)
986 #if CONFIG_VP8_CUVID_DECODER
987 DEFINE_CUVID_CODEC(vp8, VP8)
990 #if CONFIG_VP9_CUVID_DECODER
991 DEFINE_CUVID_CODEC(vp9, VP9)
994 #if CONFIG_VC1_CUVID_DECODER
995 DEFINE_CUVID_CODEC(vc1, VC1)