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 "libavutil/buffer.h"
23 #include "libavutil/mathematics.h"
24 #include "libavutil/hwcontext.h"
25 #include "libavutil/hwcontext_cuda.h"
26 #include "libavutil/fifo.h"
27 #include "libavutil/log.h"
28 #include "libavutil/opt.h"
33 #include "compat/cuda/nvcuvid.h"
35 #define MAX_FRAME_COUNT 25
37 typedef struct CuvidContext
41 CUvideodecoder cudecoder;
42 CUvideoparser cuparser;
46 AVBufferRef *hwdevice;
51 AVFifoBuffer *frame_queue;
59 cudaVideoCodec codec_type;
60 cudaVideoChromaFormat chroma_format;
62 CUVIDPARSERPARAMS cuparseinfo;
63 CUVIDEOFORMATEX cuparse_ext;
66 typedef struct CuvidParsedFrame
68 CUVIDPARSERDISPINFO dispinfo;
73 static int check_cu(AVCodecContext *avctx, CUresult err, const char *func)
76 const char *err_string;
78 av_log(avctx, AV_LOG_TRACE, "Calling %s\n", func);
80 if (err == CUDA_SUCCESS)
83 cuGetErrorName(err, &err_name);
84 cuGetErrorString(err, &err_string);
86 av_log(avctx, AV_LOG_ERROR, "%s failed", func);
87 if (err_name && err_string)
88 av_log(avctx, AV_LOG_ERROR, " -> %s: %s", err_name, err_string);
89 av_log(avctx, AV_LOG_ERROR, "\n");
91 return AVERROR_EXTERNAL;
94 #define CHECK_CU(x) check_cu(avctx, (x), #x)
96 static int CUDAAPI cuvid_handle_video_sequence(void *opaque, CUVIDEOFORMAT* format)
98 AVCodecContext *avctx = opaque;
99 CuvidContext *ctx = avctx->priv_data;
100 AVHWFramesContext *hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
101 CUVIDDECODECREATEINFO cuinfo;
103 av_log(avctx, AV_LOG_TRACE, "pfnSequenceCallback, progressive_sequence=%d\n", format->progressive_sequence);
105 ctx->internal_error = 0;
107 avctx->width = format->display_area.right;
108 avctx->height = format->display_area.bottom;
110 ff_set_sar(avctx, av_div_q(
111 (AVRational){ format->display_aspect_ratio.x, format->display_aspect_ratio.y },
112 (AVRational){ avctx->width, avctx->height }));
114 if (!format->progressive_sequence && ctx->deint_mode == cudaVideoDeinterlaceMode_Weave)
115 avctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT;
117 avctx->flags &= ~AV_CODEC_FLAG_INTERLACED_DCT;
119 if (format->video_signal_description.video_full_range_flag)
120 avctx->color_range = AVCOL_RANGE_JPEG;
122 avctx->color_range = AVCOL_RANGE_MPEG;
124 avctx->color_primaries = format->video_signal_description.color_primaries;
125 avctx->color_trc = format->video_signal_description.transfer_characteristics;
126 avctx->colorspace = format->video_signal_description.matrix_coefficients;
129 avctx->bit_rate = format->bitrate;
131 if (format->frame_rate.numerator && format->frame_rate.denominator) {
132 avctx->framerate.num = format->frame_rate.numerator;
133 avctx->framerate.den = format->frame_rate.denominator;
137 && avctx->coded_width == format->coded_width
138 && avctx->coded_height == format->coded_height
139 && ctx->chroma_format == format->chroma_format
140 && ctx->codec_type == format->codec)
143 if (ctx->cudecoder) {
144 av_log(avctx, AV_LOG_TRACE, "Re-initializing decoder\n");
145 ctx->internal_error = CHECK_CU(cuvidDestroyDecoder(ctx->cudecoder));
146 if (ctx->internal_error < 0)
148 ctx->cudecoder = NULL;
151 if (hwframe_ctx->pool && (
152 hwframe_ctx->width < avctx->width ||
153 hwframe_ctx->height < avctx->height ||
154 hwframe_ctx->format != AV_PIX_FMT_CUDA ||
155 hwframe_ctx->sw_format != AV_PIX_FMT_NV12)) {
156 av_log(avctx, AV_LOG_ERROR, "AVHWFramesContext is already initialized with incompatible parameters\n");
157 ctx->internal_error = AVERROR(EINVAL);
161 if (format->chroma_format != cudaVideoChromaFormat_420) {
162 av_log(avctx, AV_LOG_ERROR, "Chroma formats other than 420 are not supported\n");
163 ctx->internal_error = AVERROR(EINVAL);
167 avctx->coded_width = format->coded_width;
168 avctx->coded_height = format->coded_height;
170 ctx->chroma_format = format->chroma_format;
172 memset(&cuinfo, 0, sizeof(cuinfo));
174 cuinfo.CodecType = ctx->codec_type = format->codec;
175 cuinfo.ChromaFormat = format->chroma_format;
176 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
178 cuinfo.ulWidth = avctx->coded_width;
179 cuinfo.ulHeight = avctx->coded_height;
180 cuinfo.ulTargetWidth = cuinfo.ulWidth;
181 cuinfo.ulTargetHeight = cuinfo.ulHeight;
183 cuinfo.target_rect.left = 0;
184 cuinfo.target_rect.top = 0;
185 cuinfo.target_rect.right = cuinfo.ulWidth;
186 cuinfo.target_rect.bottom = cuinfo.ulHeight;
188 cuinfo.ulNumDecodeSurfaces = MAX_FRAME_COUNT;
189 cuinfo.ulNumOutputSurfaces = 1;
190 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
191 cuinfo.bitDepthMinus8 = format->bit_depth_luma_minus8;
193 if (format->progressive_sequence) {
194 ctx->deint_mode = cuinfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave;
196 cuinfo.DeinterlaceMode = ctx->deint_mode;
199 if (ctx->deint_mode != cudaVideoDeinterlaceMode_Weave)
200 avctx->framerate = av_mul_q(avctx->framerate, (AVRational){2, 1});
202 ctx->internal_error = CHECK_CU(cuvidCreateDecoder(&ctx->cudecoder, &cuinfo));
203 if (ctx->internal_error < 0)
206 if (!hwframe_ctx->pool) {
207 hwframe_ctx->format = AV_PIX_FMT_CUDA;
208 hwframe_ctx->sw_format = AV_PIX_FMT_NV12;
209 hwframe_ctx->width = avctx->width;
210 hwframe_ctx->height = avctx->height;
212 if ((ctx->internal_error = av_hwframe_ctx_init(ctx->hwframe)) < 0) {
213 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_init failed\n");
221 static int CUDAAPI cuvid_handle_picture_decode(void *opaque, CUVIDPICPARAMS* picparams)
223 AVCodecContext *avctx = opaque;
224 CuvidContext *ctx = avctx->priv_data;
226 av_log(avctx, AV_LOG_TRACE, "pfnDecodePicture\n");
228 ctx->internal_error = CHECK_CU(cuvidDecodePicture(ctx->cudecoder, picparams));
229 if (ctx->internal_error < 0)
235 static int CUDAAPI cuvid_handle_picture_display(void *opaque, CUVIDPARSERDISPINFO* dispinfo)
237 AVCodecContext *avctx = opaque;
238 CuvidContext *ctx = avctx->priv_data;
239 CuvidParsedFrame parsed_frame = { *dispinfo, 0, 0 };
241 ctx->internal_error = 0;
243 if (ctx->deint_mode == cudaVideoDeinterlaceMode_Weave) {
244 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
246 parsed_frame.is_deinterlacing = 1;
247 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
248 parsed_frame.second_field = 1;
249 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
255 static int cuvid_decode_packet(AVCodecContext *avctx, const AVPacket *avpkt)
257 CuvidContext *ctx = avctx->priv_data;
258 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
259 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
260 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
261 CUVIDSOURCEDATAPACKET cupkt;
262 AVPacket filter_packet = { 0 };
263 AVPacket filtered_packet = { 0 };
264 int ret = 0, eret = 0, is_flush = ctx->decoder_flushing;
266 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_packet\n");
268 if (is_flush && avpkt && avpkt->size)
271 if (av_fifo_size(ctx->frame_queue) / sizeof(CuvidParsedFrame) > MAX_FRAME_COUNT - 2 && avpkt && avpkt->size)
272 return AVERROR(EAGAIN);
274 if (ctx->bsf && avpkt && avpkt->size) {
275 if ((ret = av_packet_ref(&filter_packet, avpkt)) < 0) {
276 av_log(avctx, AV_LOG_ERROR, "av_packet_ref failed\n");
280 if ((ret = av_bsf_send_packet(ctx->bsf, &filter_packet)) < 0) {
281 av_log(avctx, AV_LOG_ERROR, "av_bsf_send_packet failed\n");
282 av_packet_unref(&filter_packet);
286 if ((ret = av_bsf_receive_packet(ctx->bsf, &filtered_packet)) < 0) {
287 av_log(avctx, AV_LOG_ERROR, "av_bsf_receive_packet failed\n");
291 avpkt = &filtered_packet;
294 ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));
296 av_packet_unref(&filtered_packet);
300 memset(&cupkt, 0, sizeof(cupkt));
302 if (avpkt && avpkt->size) {
303 cupkt.payload_size = avpkt->size;
304 cupkt.payload = avpkt->data;
306 if (avpkt->pts != AV_NOPTS_VALUE) {
307 cupkt.flags = CUVID_PKT_TIMESTAMP;
308 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
309 cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000});
311 cupkt.timestamp = avpkt->pts;
314 cupkt.flags = CUVID_PKT_ENDOFSTREAM;
315 ctx->decoder_flushing = 1;
318 ret = CHECK_CU(cuvidParseVideoData(ctx->cuparser, &cupkt));
320 av_packet_unref(&filtered_packet);
325 // cuvidParseVideoData doesn't return an error just because stuff failed...
326 if (ctx->internal_error) {
327 av_log(avctx, AV_LOG_ERROR, "cuvid decode callback error\n");
328 ret = ctx->internal_error;
333 eret = CHECK_CU(cuCtxPopCurrent(&dummy));
345 static int cuvid_output_frame(AVCodecContext *avctx, AVFrame *frame)
347 CuvidContext *ctx = avctx->priv_data;
348 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
349 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
350 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
351 CUdeviceptr mapped_frame = 0;
352 int ret = 0, eret = 0;
354 av_log(avctx, AV_LOG_TRACE, "cuvid_output_frame\n");
356 if (ctx->decoder_flushing) {
357 ret = cuvid_decode_packet(avctx, NULL);
358 if (ret < 0 && ret != AVERROR_EOF)
362 ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));
366 if (av_fifo_size(ctx->frame_queue)) {
367 CuvidParsedFrame parsed_frame;
368 CUVIDPROCPARAMS params;
369 unsigned int pitch = 0;
373 av_fifo_generic_read(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
375 memset(¶ms, 0, sizeof(params));
376 params.progressive_frame = parsed_frame.dispinfo.progressive_frame;
377 params.second_field = parsed_frame.second_field;
378 params.top_field_first = parsed_frame.dispinfo.top_field_first;
380 ret = CHECK_CU(cuvidMapVideoFrame(ctx->cudecoder, parsed_frame.dispinfo.picture_index, &mapped_frame, &pitch, ¶ms));
384 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
385 ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0);
387 av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n");
391 ret = ff_decode_frame_props(avctx, frame);
393 av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n");
397 for (i = 0; i < 2; i++) {
398 CUDA_MEMCPY2D cpy = {
399 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
400 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
401 .srcDevice = mapped_frame,
402 .dstDevice = (CUdeviceptr)frame->data[i],
404 .dstPitch = frame->linesize[i],
406 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
407 .Height = avctx->height >> (i ? 1 : 0),
410 ret = CHECK_CU(cuMemcpy2D(&cpy));
414 offset += avctx->coded_height;
416 } else if (avctx->pix_fmt == AV_PIX_FMT_NV12) {
417 AVFrame *tmp_frame = av_frame_alloc();
419 av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n");
420 ret = AVERROR(ENOMEM);
424 tmp_frame->format = AV_PIX_FMT_CUDA;
425 tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe);
426 tmp_frame->data[0] = (uint8_t*)mapped_frame;
427 tmp_frame->linesize[0] = pitch;
428 tmp_frame->data[1] = (uint8_t*)(mapped_frame + avctx->coded_height * pitch);
429 tmp_frame->linesize[1] = pitch;
430 tmp_frame->width = avctx->width;
431 tmp_frame->height = avctx->height;
433 ret = ff_get_buffer(avctx, frame, 0);
435 av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n");
436 av_frame_free(&tmp_frame);
440 ret = av_hwframe_transfer_data(frame, tmp_frame, 0);
442 av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n");
443 av_frame_free(&tmp_frame);
447 av_frame_free(&tmp_frame);
453 frame->width = avctx->width;
454 frame->height = avctx->height;
455 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
456 frame->pts = av_rescale_q(parsed_frame.dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase);
458 frame->pts = parsed_frame.dispinfo.timestamp;
460 if (parsed_frame.second_field) {
461 if (ctx->prev_pts == INT64_MIN) {
462 ctx->prev_pts = frame->pts;
463 frame->pts += (avctx->pkt_timebase.den * avctx->framerate.den) / (avctx->pkt_timebase.num * avctx->framerate.num);
465 int pts_diff = (frame->pts - ctx->prev_pts) / 2;
466 ctx->prev_pts = frame->pts;
467 frame->pts += pts_diff;
471 /* CUVIDs opaque reordering breaks the internal pkt logic.
472 * So set pkt_pts and clear all the other pkt_ fields.
475 FF_DISABLE_DEPRECATION_WARNINGS
476 frame->pkt_pts = frame->pts;
477 FF_ENABLE_DEPRECATION_WARNINGS
479 av_frame_set_pkt_pos(frame, -1);
480 av_frame_set_pkt_duration(frame, 0);
481 av_frame_set_pkt_size(frame, -1);
483 frame->interlaced_frame = !parsed_frame.is_deinterlacing && !parsed_frame.dispinfo.progressive_frame;
485 if (frame->interlaced_frame)
486 frame->top_field_first = parsed_frame.dispinfo.top_field_first;
487 } else if (ctx->decoder_flushing) {
490 ret = AVERROR(EAGAIN);
495 eret = CHECK_CU(cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame));
497 eret = CHECK_CU(cuCtxPopCurrent(&dummy));
505 static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
507 CuvidContext *ctx = avctx->priv_data;
508 AVFrame *frame = data;
511 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_frame\n");
513 if (ctx->deint_mode != cudaVideoDeinterlaceMode_Weave) {
514 av_log(avctx, AV_LOG_ERROR, "Deinterlacing is not supported via the old API\n");
515 return AVERROR(EINVAL);
518 if (!ctx->decoder_flushing) {
519 ret = cuvid_decode_packet(avctx, avpkt);
524 ret = cuvid_output_frame(avctx, frame);
525 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
527 } else if (ret < 0) {
536 static av_cold int cuvid_decode_end(AVCodecContext *avctx)
538 CuvidContext *ctx = avctx->priv_data;
540 av_fifo_freep(&ctx->frame_queue);
543 av_bsf_free(&ctx->bsf);
546 cuvidDestroyVideoParser(ctx->cuparser);
549 cuvidDestroyDecoder(ctx->cudecoder);
551 av_buffer_unref(&ctx->hwframe);
552 av_buffer_unref(&ctx->hwdevice);
557 static int cuvid_test_dummy_decoder(AVCodecContext *avctx, CUVIDPARSERPARAMS *cuparseinfo)
559 CUVIDDECODECREATEINFO cuinfo;
560 CUvideodecoder cudec = 0;
563 memset(&cuinfo, 0, sizeof(cuinfo));
565 cuinfo.CodecType = cuparseinfo->CodecType;
566 cuinfo.ChromaFormat = cudaVideoChromaFormat_420;
567 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
569 cuinfo.ulWidth = 1280;
570 cuinfo.ulHeight = 720;
571 cuinfo.ulTargetWidth = cuinfo.ulWidth;
572 cuinfo.ulTargetHeight = cuinfo.ulHeight;
574 cuinfo.target_rect.left = 0;
575 cuinfo.target_rect.top = 0;
576 cuinfo.target_rect.right = cuinfo.ulWidth;
577 cuinfo.target_rect.bottom = cuinfo.ulHeight;
579 cuinfo.ulNumDecodeSurfaces = MAX_FRAME_COUNT;
580 cuinfo.ulNumOutputSurfaces = 1;
581 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
582 cuinfo.bitDepthMinus8 = 0;
584 cuinfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave;
586 ret = CHECK_CU(cuvidCreateDecoder(&cudec, &cuinfo));
590 ret = CHECK_CU(cuvidDestroyDecoder(cudec));
597 static av_cold int cuvid_decode_init(AVCodecContext *avctx)
599 CuvidContext *ctx = avctx->priv_data;
600 AVCUDADeviceContext *device_hwctx;
601 AVHWDeviceContext *device_ctx;
602 AVHWFramesContext *hwframe_ctx;
603 CUVIDSOURCEDATAPACKET seq_pkt;
604 CUcontext cuda_ctx = NULL;
606 const AVBitStreamFilter *bsf;
609 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
613 ret = ff_get_format(avctx, pix_fmts);
615 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);
619 ctx->frame_queue = av_fifo_alloc(MAX_FRAME_COUNT * sizeof(CuvidParsedFrame));
620 if (!ctx->frame_queue) {
621 ret = AVERROR(ENOMEM);
625 avctx->pix_fmt = ret;
627 if (avctx->hw_frames_ctx) {
628 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
630 ret = AVERROR(ENOMEM);
634 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
636 ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);
637 if (!ctx->hwdevice) {
638 ret = AVERROR(ENOMEM);
642 ret = av_hwdevice_ctx_create(&ctx->hwdevice, AV_HWDEVICE_TYPE_CUDA, ctx->cu_gpu, NULL, 0);
646 ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);
648 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");
649 ret = AVERROR(ENOMEM);
653 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
656 device_ctx = hwframe_ctx->device_ctx;
657 device_hwctx = device_ctx->hwctx;
658 cuda_ctx = device_hwctx->cuda_ctx;
660 memset(&ctx->cuparseinfo, 0, sizeof(ctx->cuparseinfo));
661 memset(&ctx->cuparse_ext, 0, sizeof(ctx->cuparse_ext));
662 memset(&seq_pkt, 0, sizeof(seq_pkt));
664 ctx->cuparseinfo.pExtVideoInfo = &ctx->cuparse_ext;
666 switch (avctx->codec->id) {
667 #if CONFIG_H264_CUVID_DECODER
668 case AV_CODEC_ID_H264:
669 ctx->cuparseinfo.CodecType = cudaVideoCodec_H264;
672 #if CONFIG_HEVC_CUVID_DECODER
673 case AV_CODEC_ID_HEVC:
674 ctx->cuparseinfo.CodecType = cudaVideoCodec_HEVC;
677 #if CONFIG_MJPEG_CUVID_DECODER
678 case AV_CODEC_ID_MJPEG:
679 ctx->cuparseinfo.CodecType = cudaVideoCodec_JPEG;
682 #if CONFIG_MPEG1_CUVID_DECODER
683 case AV_CODEC_ID_MPEG1VIDEO:
684 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG1;
687 #if CONFIG_MPEG2_CUVID_DECODER
688 case AV_CODEC_ID_MPEG2VIDEO:
689 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG2;
692 #if CONFIG_MPEG4_CUVID_DECODER
693 case AV_CODEC_ID_MPEG4:
694 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG4;
697 #if CONFIG_VP8_CUVID_DECODER
698 case AV_CODEC_ID_VP8:
699 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP8;
702 #if CONFIG_VP9_CUVID_DECODER
703 case AV_CODEC_ID_VP9:
704 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP9;
707 #if CONFIG_VC1_CUVID_DECODER
708 case AV_CODEC_ID_VC1:
709 ctx->cuparseinfo.CodecType = cudaVideoCodec_VC1;
713 av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");
717 if (avctx->codec->id == AV_CODEC_ID_H264 || avctx->codec->id == AV_CODEC_ID_HEVC) {
718 if (avctx->codec->id == AV_CODEC_ID_H264)
719 bsf = av_bsf_get_by_name("h264_mp4toannexb");
721 bsf = av_bsf_get_by_name("hevc_mp4toannexb");
724 ret = AVERROR_BSF_NOT_FOUND;
727 if (ret = av_bsf_alloc(bsf, &ctx->bsf)) {
730 if (((ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx)) < 0) || ((ret = av_bsf_init(ctx->bsf)) < 0)) {
731 av_bsf_free(&ctx->bsf);
735 ctx->cuparse_ext.format.seqhdr_data_length = ctx->bsf->par_out->extradata_size;
736 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
737 ctx->bsf->par_out->extradata,
738 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), ctx->bsf->par_out->extradata_size));
739 } else if (avctx->extradata_size > 0) {
740 ctx->cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;
741 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
743 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), avctx->extradata_size));
746 ctx->cuparseinfo.ulMaxNumDecodeSurfaces = MAX_FRAME_COUNT;
747 ctx->cuparseinfo.ulMaxDisplayDelay = 4;
748 ctx->cuparseinfo.pUserData = avctx;
749 ctx->cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;
750 ctx->cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;
751 ctx->cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;
753 ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));
757 ret = cuvid_test_dummy_decoder(avctx, &ctx->cuparseinfo);
761 ret = CHECK_CU(cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
765 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
766 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
768 if (seq_pkt.payload && seq_pkt.payload_size) {
769 ret = CHECK_CU(cuvidParseVideoData(ctx->cuparser, &seq_pkt));
774 ret = CHECK_CU(cuCtxPopCurrent(&dummy));
778 ctx->prev_pts = INT64_MIN;
780 if (!avctx->pkt_timebase.num || !avctx->pkt_timebase.den)
781 av_log(avctx, AV_LOG_WARNING, "Invalid pkt_timebase, passing timestamps as-is.\n");
786 cuvid_decode_end(avctx);
790 static void cuvid_flush(AVCodecContext *avctx)
792 CuvidContext *ctx = avctx->priv_data;
793 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
794 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
795 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
796 CUVIDSOURCEDATAPACKET seq_pkt = { 0 };
799 ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx));
803 av_fifo_freep(&ctx->frame_queue);
805 ctx->frame_queue = av_fifo_alloc(MAX_FRAME_COUNT * sizeof(CuvidParsedFrame));
806 if (!ctx->frame_queue) {
807 av_log(avctx, AV_LOG_ERROR, "Failed to recreate frame queue on flush\n");
811 if (ctx->cudecoder) {
812 cuvidDestroyDecoder(ctx->cudecoder);
813 ctx->cudecoder = NULL;
817 cuvidDestroyVideoParser(ctx->cuparser);
818 ctx->cuparser = NULL;
821 ret = CHECK_CU(cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
825 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
826 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
828 if (seq_pkt.payload && seq_pkt.payload_size) {
829 ret = CHECK_CU(cuvidParseVideoData(ctx->cuparser, &seq_pkt));
834 ret = CHECK_CU(cuCtxPopCurrent(&dummy));
838 ctx->prev_pts = INT64_MIN;
839 ctx->decoder_flushing = 0;
843 av_log(avctx, AV_LOG_ERROR, "CUDA reinit on flush failed\n");
846 #define OFFSET(x) offsetof(CuvidContext, x)
847 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
848 static const AVOption options[] = {
849 { "deint", "Set deinterlacing mode", OFFSET(deint_mode), AV_OPT_TYPE_INT, { .i64 = cudaVideoDeinterlaceMode_Weave }, cudaVideoDeinterlaceMode_Weave, cudaVideoDeinterlaceMode_Adaptive, VD, "deint" },
850 { "weave", "Weave deinterlacing (do nothing)", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Weave }, 0, 0, VD, "deint" },
851 { "bob", "Bob deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Bob }, 0, 0, VD, "deint" },
852 { "adaptive", "Adaptive deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Adaptive }, 0, 0, VD, "deint" },
853 { "gpu", "GPU to be used for decoding", OFFSET(cu_gpu), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
857 #define DEFINE_CUVID_CODEC(x, X) \
858 static const AVClass x##_cuvid_class = { \
859 .class_name = #x "_cuvid", \
860 .item_name = av_default_item_name, \
862 .version = LIBAVUTIL_VERSION_INT, \
864 AVHWAccel ff_##x##_cuvid_hwaccel = { \
865 .name = #x "_cuvid", \
866 .type = AVMEDIA_TYPE_VIDEO, \
867 .id = AV_CODEC_ID_##X, \
868 .pix_fmt = AV_PIX_FMT_CUDA, \
870 AVCodec ff_##x##_cuvid_decoder = { \
871 .name = #x "_cuvid", \
872 .long_name = NULL_IF_CONFIG_SMALL("Nvidia CUVID " #X " decoder"), \
873 .type = AVMEDIA_TYPE_VIDEO, \
874 .id = AV_CODEC_ID_##X, \
875 .priv_data_size = sizeof(CuvidContext), \
876 .priv_class = &x##_cuvid_class, \
877 .init = cuvid_decode_init, \
878 .close = cuvid_decode_end, \
879 .decode = cuvid_decode_frame, \
880 .send_packet = cuvid_decode_packet, \
881 .receive_frame = cuvid_output_frame, \
882 .flush = cuvid_flush, \
883 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING, \
884 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_CUDA, \
889 #if CONFIG_HEVC_CUVID_DECODER
890 DEFINE_CUVID_CODEC(hevc, HEVC)
893 #if CONFIG_H264_CUVID_DECODER
894 DEFINE_CUVID_CODEC(h264, H264)
897 #if CONFIG_MJPEG_CUVID_DECODER
898 DEFINE_CUVID_CODEC(mjpeg, MJPEG)
901 #if CONFIG_MPEG1_CUVID_DECODER
902 DEFINE_CUVID_CODEC(mpeg1, MPEG1VIDEO)
905 #if CONFIG_MPEG2_CUVID_DECODER
906 DEFINE_CUVID_CODEC(mpeg2, MPEG2VIDEO)
909 #if CONFIG_MPEG4_CUVID_DECODER
910 DEFINE_CUVID_CODEC(mpeg4, MPEG4)
913 #if CONFIG_VP8_CUVID_DECODER
914 DEFINE_CUVID_CODEC(vp8, VP8)
917 #if CONFIG_VP9_CUVID_DECODER
918 DEFINE_CUVID_CODEC(vp9, VP9)
921 #if CONFIG_VC1_CUVID_DECODER
922 DEFINE_CUVID_CODEC(vc1, VC1)