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 CUVIDPARSERPARAMS cuparseinfo;
80 CUVIDEOFORMATEX cuparse_ext;
86 typedef struct CuvidParsedFrame
88 CUVIDPARSERDISPINFO dispinfo;
93 static int check_cu(AVCodecContext *avctx, CUresult err, const char *func)
95 CuvidContext *ctx = avctx->priv_data;
97 const char *err_string;
99 av_log(avctx, AV_LOG_TRACE, "Calling %s\n", func);
101 if (err == CUDA_SUCCESS)
104 ctx->cudl->cuGetErrorName(err, &err_name);
105 ctx->cudl->cuGetErrorString(err, &err_string);
107 av_log(avctx, AV_LOG_ERROR, "%s failed", func);
108 if (err_name && err_string)
109 av_log(avctx, AV_LOG_ERROR, " -> %s: %s", err_name, err_string);
110 av_log(avctx, AV_LOG_ERROR, "\n");
112 return AVERROR_EXTERNAL;
115 #define CHECK_CU(x) check_cu(avctx, (x), #x)
117 static int CUDAAPI cuvid_handle_video_sequence(void *opaque, CUVIDEOFORMAT* format)
119 AVCodecContext *avctx = opaque;
120 CuvidContext *ctx = avctx->priv_data;
121 AVHWFramesContext *hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
122 CUVIDDECODECREATEINFO cuinfo;
125 int old_width = avctx->width;
126 int old_height = avctx->height;
128 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
129 AV_PIX_FMT_NONE, // Will be updated below
132 av_log(avctx, AV_LOG_TRACE, "pfnSequenceCallback, progressive_sequence=%d\n", format->progressive_sequence);
134 memset(&cuinfo, 0, sizeof(cuinfo));
136 ctx->internal_error = 0;
138 avctx->coded_width = cuinfo.ulWidth = format->coded_width;
139 avctx->coded_height = cuinfo.ulHeight = format->coded_height;
142 cuinfo.display_area.left = format->display_area.left + ctx->crop.left;
143 cuinfo.display_area.top = format->display_area.top + ctx->crop.top;
144 cuinfo.display_area.right = format->display_area.right - ctx->crop.right;
145 cuinfo.display_area.bottom = format->display_area.bottom - ctx->crop.bottom;
147 // width and height need to be set before calling ff_get_format
148 if (ctx->resize_expr) {
149 avctx->width = ctx->resize.width;
150 avctx->height = ctx->resize.height;
152 avctx->width = cuinfo.display_area.right - cuinfo.display_area.left;
153 avctx->height = cuinfo.display_area.bottom - cuinfo.display_area.top;
156 // target width/height need to be multiples of two
157 cuinfo.ulTargetWidth = avctx->width = (avctx->width + 1) & ~1;
158 cuinfo.ulTargetHeight = avctx->height = (avctx->height + 1) & ~1;
160 // aspect ratio conversion, 1:1, depends on scaled resolution
161 cuinfo.target_rect.left = 0;
162 cuinfo.target_rect.top = 0;
163 cuinfo.target_rect.right = cuinfo.ulTargetWidth;
164 cuinfo.target_rect.bottom = cuinfo.ulTargetHeight;
166 switch (format->bit_depth_luma_minus8) {
168 pix_fmts[1] = AV_PIX_FMT_NV12;
171 pix_fmts[1] = AV_PIX_FMT_P010;
174 pix_fmts[1] = AV_PIX_FMT_P016;
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);
182 surface_fmt = ff_get_format(avctx, pix_fmts);
183 if (surface_fmt < 0) {
184 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", surface_fmt);
185 ctx->internal_error = AVERROR(EINVAL);
189 av_log(avctx, AV_LOG_VERBOSE, "Formats: Original: %s | HW: %s | SW: %s\n",
190 av_get_pix_fmt_name(avctx->pix_fmt),
191 av_get_pix_fmt_name(surface_fmt),
192 av_get_pix_fmt_name(avctx->sw_pix_fmt));
194 avctx->pix_fmt = surface_fmt;
196 // Update our hwframe ctx, as the get_format callback might have refreshed it!
197 if (avctx->hw_frames_ctx) {
198 av_buffer_unref(&ctx->hwframe);
200 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
202 ctx->internal_error = AVERROR(ENOMEM);
206 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
209 ff_set_sar(avctx, av_div_q(
210 (AVRational){ format->display_aspect_ratio.x, format->display_aspect_ratio.y },
211 (AVRational){ avctx->width, avctx->height }));
213 ctx->deint_mode_current = format->progressive_sequence
214 ? cudaVideoDeinterlaceMode_Weave
217 if (!format->progressive_sequence && ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave)
218 avctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT;
220 avctx->flags &= ~AV_CODEC_FLAG_INTERLACED_DCT;
222 if (format->video_signal_description.video_full_range_flag)
223 avctx->color_range = AVCOL_RANGE_JPEG;
225 avctx->color_range = AVCOL_RANGE_MPEG;
227 avctx->color_primaries = format->video_signal_description.color_primaries;
228 avctx->color_trc = format->video_signal_description.transfer_characteristics;
229 avctx->colorspace = format->video_signal_description.matrix_coefficients;
232 avctx->bit_rate = format->bitrate;
234 if (format->frame_rate.numerator && format->frame_rate.denominator) {
235 avctx->framerate.num = format->frame_rate.numerator;
236 avctx->framerate.den = format->frame_rate.denominator;
240 && avctx->coded_width == format->coded_width
241 && avctx->coded_height == format->coded_height
242 && avctx->width == old_width
243 && avctx->height == old_height
244 && ctx->chroma_format == format->chroma_format
245 && ctx->codec_type == format->codec)
248 if (ctx->cudecoder) {
249 av_log(avctx, AV_LOG_TRACE, "Re-initializing decoder\n");
250 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder));
251 if (ctx->internal_error < 0)
253 ctx->cudecoder = NULL;
256 if (hwframe_ctx->pool && (
257 hwframe_ctx->width < avctx->width ||
258 hwframe_ctx->height < avctx->height ||
259 hwframe_ctx->format != AV_PIX_FMT_CUDA ||
260 hwframe_ctx->sw_format != avctx->sw_pix_fmt)) {
261 av_log(avctx, AV_LOG_ERROR, "AVHWFramesContext is already initialized with incompatible parameters\n");
262 av_log(avctx, AV_LOG_DEBUG, "width: %d <-> %d\n", hwframe_ctx->width, avctx->width);
263 av_log(avctx, AV_LOG_DEBUG, "height: %d <-> %d\n", hwframe_ctx->height, avctx->height);
264 av_log(avctx, AV_LOG_DEBUG, "format: %s <-> cuda\n", av_get_pix_fmt_name(hwframe_ctx->format));
265 av_log(avctx, AV_LOG_DEBUG, "sw_format: %s <-> %s\n",
266 av_get_pix_fmt_name(hwframe_ctx->sw_format), av_get_pix_fmt_name(avctx->sw_pix_fmt));
267 ctx->internal_error = AVERROR(EINVAL);
271 if (format->chroma_format != cudaVideoChromaFormat_420) {
272 av_log(avctx, AV_LOG_ERROR, "Chroma formats other than 420 are not supported\n");
273 ctx->internal_error = AVERROR(EINVAL);
277 ctx->chroma_format = format->chroma_format;
279 cuinfo.CodecType = ctx->codec_type = format->codec;
280 cuinfo.ChromaFormat = format->chroma_format;
282 switch (avctx->sw_pix_fmt) {
283 case AV_PIX_FMT_NV12:
284 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
286 case AV_PIX_FMT_P010:
287 case AV_PIX_FMT_P016:
288 cuinfo.OutputFormat = cudaVideoSurfaceFormat_P016;
291 av_log(avctx, AV_LOG_ERROR, "Output formats other than NV12, P010 or P016 are not supported\n");
292 ctx->internal_error = AVERROR(EINVAL);
296 cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
297 cuinfo.ulNumOutputSurfaces = 1;
298 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
299 cuinfo.bitDepthMinus8 = format->bit_depth_luma_minus8;
300 cuinfo.DeinterlaceMode = ctx->deint_mode_current;
302 if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave && !ctx->drop_second_field)
303 avctx->framerate = av_mul_q(avctx->framerate, (AVRational){2, 1});
305 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&ctx->cudecoder, &cuinfo));
306 if (ctx->internal_error < 0)
309 if (!hwframe_ctx->pool) {
310 hwframe_ctx->format = AV_PIX_FMT_CUDA;
311 hwframe_ctx->sw_format = avctx->sw_pix_fmt;
312 hwframe_ctx->width = avctx->width;
313 hwframe_ctx->height = avctx->height;
315 if ((ctx->internal_error = av_hwframe_ctx_init(ctx->hwframe)) < 0) {
316 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_init failed\n");
324 static int CUDAAPI cuvid_handle_picture_decode(void *opaque, CUVIDPICPARAMS* picparams)
326 AVCodecContext *avctx = opaque;
327 CuvidContext *ctx = avctx->priv_data;
329 av_log(avctx, AV_LOG_TRACE, "pfnDecodePicture\n");
331 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDecodePicture(ctx->cudecoder, picparams));
332 if (ctx->internal_error < 0)
338 static int CUDAAPI cuvid_handle_picture_display(void *opaque, CUVIDPARSERDISPINFO* dispinfo)
340 AVCodecContext *avctx = opaque;
341 CuvidContext *ctx = avctx->priv_data;
342 CuvidParsedFrame parsed_frame = { { 0 } };
344 parsed_frame.dispinfo = *dispinfo;
345 ctx->internal_error = 0;
347 if (ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave) {
348 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
350 parsed_frame.is_deinterlacing = 1;
351 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
352 if (!ctx->drop_second_field) {
353 parsed_frame.second_field = 1;
354 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
361 static int cuvid_is_buffer_full(AVCodecContext *avctx)
363 CuvidContext *ctx = avctx->priv_data;
365 return (av_fifo_size(ctx->frame_queue) / sizeof(CuvidParsedFrame)) + 2 > ctx->nb_surfaces;
368 static int cuvid_decode_packet(AVCodecContext *avctx, const AVPacket *avpkt)
370 CuvidContext *ctx = avctx->priv_data;
371 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
372 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
373 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
374 CUVIDSOURCEDATAPACKET cupkt;
375 AVPacket filter_packet = { 0 };
376 AVPacket filtered_packet = { 0 };
377 int ret = 0, eret = 0, is_flush = ctx->decoder_flushing;
379 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_packet\n");
381 if (is_flush && avpkt && avpkt->size)
384 if (cuvid_is_buffer_full(avctx) && avpkt && avpkt->size)
385 return AVERROR(EAGAIN);
387 if (ctx->bsf && avpkt && avpkt->size) {
388 if ((ret = av_packet_ref(&filter_packet, avpkt)) < 0) {
389 av_log(avctx, AV_LOG_ERROR, "av_packet_ref failed\n");
393 if ((ret = av_bsf_send_packet(ctx->bsf, &filter_packet)) < 0) {
394 av_log(avctx, AV_LOG_ERROR, "av_bsf_send_packet failed\n");
395 av_packet_unref(&filter_packet);
399 if ((ret = av_bsf_receive_packet(ctx->bsf, &filtered_packet)) < 0) {
400 av_log(avctx, AV_LOG_ERROR, "av_bsf_receive_packet failed\n");
404 avpkt = &filtered_packet;
407 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
409 av_packet_unref(&filtered_packet);
413 memset(&cupkt, 0, sizeof(cupkt));
415 if (avpkt && avpkt->size) {
416 cupkt.payload_size = avpkt->size;
417 cupkt.payload = avpkt->data;
419 if (avpkt->pts != AV_NOPTS_VALUE) {
420 cupkt.flags = CUVID_PKT_TIMESTAMP;
421 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
422 cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000});
424 cupkt.timestamp = avpkt->pts;
427 cupkt.flags = CUVID_PKT_ENDOFSTREAM;
428 ctx->decoder_flushing = 1;
431 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &cupkt));
433 av_packet_unref(&filtered_packet);
438 // cuvidParseVideoData doesn't return an error just because stuff failed...
439 if (ctx->internal_error) {
440 av_log(avctx, AV_LOG_ERROR, "cuvid decode callback error\n");
441 ret = ctx->internal_error;
446 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
458 static int cuvid_output_frame(AVCodecContext *avctx, AVFrame *frame)
460 CuvidContext *ctx = avctx->priv_data;
461 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
462 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
463 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
464 CUdeviceptr mapped_frame = 0;
465 int ret = 0, eret = 0;
467 av_log(avctx, AV_LOG_TRACE, "cuvid_output_frame\n");
469 if (ctx->decoder_flushing) {
470 ret = cuvid_decode_packet(avctx, NULL);
471 if (ret < 0 && ret != AVERROR_EOF)
475 if (!cuvid_is_buffer_full(avctx)) {
477 ret = ff_decode_get_packet(avctx, &pkt);
478 if (ret < 0 && ret != AVERROR_EOF)
480 ret = cuvid_decode_packet(avctx, &pkt);
481 av_packet_unref(&pkt);
482 // cuvid_is_buffer_full() should avoid this.
483 if (ret == AVERROR(EAGAIN))
484 ret = AVERROR_EXTERNAL;
485 if (ret < 0 && ret != AVERROR_EOF)
489 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
493 if (av_fifo_size(ctx->frame_queue)) {
494 CuvidParsedFrame parsed_frame;
495 CUVIDPROCPARAMS params;
496 unsigned int pitch = 0;
500 av_fifo_generic_read(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
502 memset(¶ms, 0, sizeof(params));
503 params.progressive_frame = parsed_frame.dispinfo.progressive_frame;
504 params.second_field = parsed_frame.second_field;
505 params.top_field_first = parsed_frame.dispinfo.top_field_first;
507 ret = CHECK_CU(ctx->cvdl->cuvidMapVideoFrame(ctx->cudecoder, parsed_frame.dispinfo.picture_index, &mapped_frame, &pitch, ¶ms));
511 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
512 ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0);
514 av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n");
518 ret = ff_decode_frame_props(avctx, frame);
520 av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n");
524 for (i = 0; i < 2; i++) {
525 CUDA_MEMCPY2D cpy = {
526 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
527 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
528 .srcDevice = mapped_frame,
529 .dstDevice = (CUdeviceptr)frame->data[i],
531 .dstPitch = frame->linesize[i],
533 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
534 .Height = avctx->height >> (i ? 1 : 0),
537 ret = CHECK_CU(ctx->cudl->cuMemcpy2D(&cpy));
541 offset += avctx->height;
543 } else if (avctx->pix_fmt == AV_PIX_FMT_NV12 ||
544 avctx->pix_fmt == AV_PIX_FMT_P010 ||
545 avctx->pix_fmt == AV_PIX_FMT_P016) {
546 AVFrame *tmp_frame = av_frame_alloc();
548 av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n");
549 ret = AVERROR(ENOMEM);
553 tmp_frame->format = AV_PIX_FMT_CUDA;
554 tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe);
555 tmp_frame->data[0] = (uint8_t*)mapped_frame;
556 tmp_frame->linesize[0] = pitch;
557 tmp_frame->data[1] = (uint8_t*)(mapped_frame + avctx->height * pitch);
558 tmp_frame->linesize[1] = pitch;
559 tmp_frame->width = avctx->width;
560 tmp_frame->height = avctx->height;
562 ret = ff_get_buffer(avctx, frame, 0);
564 av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n");
565 av_frame_free(&tmp_frame);
569 ret = av_hwframe_transfer_data(frame, tmp_frame, 0);
571 av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n");
572 av_frame_free(&tmp_frame);
575 av_frame_free(&tmp_frame);
581 frame->width = avctx->width;
582 frame->height = avctx->height;
583 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
584 frame->pts = av_rescale_q(parsed_frame.dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase);
586 frame->pts = parsed_frame.dispinfo.timestamp;
588 if (parsed_frame.second_field) {
589 if (ctx->prev_pts == INT64_MIN) {
590 ctx->prev_pts = frame->pts;
591 frame->pts += (avctx->pkt_timebase.den * avctx->framerate.den) / (avctx->pkt_timebase.num * avctx->framerate.num);
593 int pts_diff = (frame->pts - ctx->prev_pts) / 2;
594 ctx->prev_pts = frame->pts;
595 frame->pts += pts_diff;
599 /* CUVIDs opaque reordering breaks the internal pkt logic.
600 * So set pkt_pts and clear all the other pkt_ fields.
603 FF_DISABLE_DEPRECATION_WARNINGS
604 frame->pkt_pts = frame->pts;
605 FF_ENABLE_DEPRECATION_WARNINGS
607 av_frame_set_pkt_pos(frame, -1);
608 av_frame_set_pkt_duration(frame, 0);
609 av_frame_set_pkt_size(frame, -1);
611 frame->interlaced_frame = !parsed_frame.is_deinterlacing && !parsed_frame.dispinfo.progressive_frame;
613 if (frame->interlaced_frame)
614 frame->top_field_first = parsed_frame.dispinfo.top_field_first;
615 } else if (ctx->decoder_flushing) {
618 ret = AVERROR(EAGAIN);
623 eret = CHECK_CU(ctx->cvdl->cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame));
625 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
633 static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
635 CuvidContext *ctx = avctx->priv_data;
636 AVFrame *frame = data;
639 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_frame\n");
641 if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave) {
642 av_log(avctx, AV_LOG_ERROR, "Deinterlacing is not supported via the old API\n");
643 return AVERROR(EINVAL);
646 if (!ctx->decoder_flushing) {
647 ret = cuvid_decode_packet(avctx, avpkt);
652 ret = cuvid_output_frame(avctx, frame);
653 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
655 } else if (ret < 0) {
664 static av_cold int cuvid_decode_end(AVCodecContext *avctx)
666 CuvidContext *ctx = avctx->priv_data;
668 av_fifo_freep(&ctx->frame_queue);
671 av_bsf_free(&ctx->bsf);
674 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
677 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
681 av_buffer_unref(&ctx->hwframe);
682 av_buffer_unref(&ctx->hwdevice);
684 cuvid_free_functions(&ctx->cvdl);
689 static int cuvid_test_dummy_decoder(AVCodecContext *avctx,
690 const CUVIDPARSERPARAMS *cuparseinfo,
694 CuvidContext *ctx = avctx->priv_data;
695 CUVIDDECODECREATEINFO cuinfo;
696 CUvideodecoder cudec = 0;
699 memset(&cuinfo, 0, sizeof(cuinfo));
701 cuinfo.CodecType = cuparseinfo->CodecType;
702 cuinfo.ChromaFormat = cudaVideoChromaFormat_420;
703 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
705 cuinfo.ulWidth = probed_width;
706 cuinfo.ulHeight = probed_height;
707 cuinfo.ulTargetWidth = cuinfo.ulWidth;
708 cuinfo.ulTargetHeight = cuinfo.ulHeight;
710 cuinfo.target_rect.left = 0;
711 cuinfo.target_rect.top = 0;
712 cuinfo.target_rect.right = cuinfo.ulWidth;
713 cuinfo.target_rect.bottom = cuinfo.ulHeight;
715 cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
716 cuinfo.ulNumOutputSurfaces = 1;
717 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
718 cuinfo.bitDepthMinus8 = 0;
720 cuinfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave;
722 ret = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&cudec, &cuinfo));
726 ret = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(cudec));
733 static av_cold int cuvid_decode_init(AVCodecContext *avctx)
735 CuvidContext *ctx = avctx->priv_data;
736 AVCUDADeviceContext *device_hwctx;
737 AVHWDeviceContext *device_ctx;
738 AVHWFramesContext *hwframe_ctx;
739 CUVIDSOURCEDATAPACKET seq_pkt;
740 CUcontext cuda_ctx = NULL;
742 const AVBitStreamFilter *bsf;
745 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
749 int probed_width = avctx->coded_width ? avctx->coded_width : 1280;
750 int probed_height = avctx->coded_height ? avctx->coded_height : 720;
752 // Accelerated transcoding scenarios with 'ffmpeg' require that the
753 // pix_fmt be set to AV_PIX_FMT_CUDA early. The sw_pix_fmt, and the
754 // pix_fmt for non-accelerated transcoding, do not need to be correct
755 // but need to be set to something. We arbitrarily pick NV12.
756 ret = ff_get_format(avctx, pix_fmts);
758 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);
761 avctx->pix_fmt = ret;
763 if (ctx->resize_expr && sscanf(ctx->resize_expr, "%dx%d",
764 &ctx->resize.width, &ctx->resize.height) != 2) {
765 av_log(avctx, AV_LOG_ERROR, "Invalid resize expressions\n");
766 ret = AVERROR(EINVAL);
770 if (ctx->crop_expr && sscanf(ctx->crop_expr, "%dx%dx%dx%d",
771 &ctx->crop.top, &ctx->crop.bottom,
772 &ctx->crop.left, &ctx->crop.right) != 4) {
773 av_log(avctx, AV_LOG_ERROR, "Invalid cropping expressions\n");
774 ret = AVERROR(EINVAL);
778 ret = cuvid_load_functions(&ctx->cvdl);
780 av_log(avctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
784 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
785 if (!ctx->frame_queue) {
786 ret = AVERROR(ENOMEM);
790 if (avctx->hw_frames_ctx) {
791 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
793 ret = AVERROR(ENOMEM);
797 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
799 ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);
800 if (!ctx->hwdevice) {
801 ret = AVERROR(ENOMEM);
805 ret = av_hwdevice_ctx_create(&ctx->hwdevice, AV_HWDEVICE_TYPE_CUDA, ctx->cu_gpu, NULL, 0);
809 ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);
811 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");
812 ret = AVERROR(ENOMEM);
816 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
819 device_ctx = hwframe_ctx->device_ctx;
820 device_hwctx = device_ctx->hwctx;
822 cuda_ctx = device_hwctx->cuda_ctx;
823 ctx->cudl = device_hwctx->internal->cuda_dl;
825 memset(&ctx->cuparseinfo, 0, sizeof(ctx->cuparseinfo));
826 memset(&ctx->cuparse_ext, 0, sizeof(ctx->cuparse_ext));
827 memset(&seq_pkt, 0, sizeof(seq_pkt));
829 ctx->cuparseinfo.pExtVideoInfo = &ctx->cuparse_ext;
831 switch (avctx->codec->id) {
832 #if CONFIG_H264_CUVID_DECODER
833 case AV_CODEC_ID_H264:
834 ctx->cuparseinfo.CodecType = cudaVideoCodec_H264;
837 #if CONFIG_HEVC_CUVID_DECODER
838 case AV_CODEC_ID_HEVC:
839 ctx->cuparseinfo.CodecType = cudaVideoCodec_HEVC;
842 #if CONFIG_MJPEG_CUVID_DECODER
843 case AV_CODEC_ID_MJPEG:
844 ctx->cuparseinfo.CodecType = cudaVideoCodec_JPEG;
847 #if CONFIG_MPEG1_CUVID_DECODER
848 case AV_CODEC_ID_MPEG1VIDEO:
849 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG1;
852 #if CONFIG_MPEG2_CUVID_DECODER
853 case AV_CODEC_ID_MPEG2VIDEO:
854 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG2;
857 #if CONFIG_MPEG4_CUVID_DECODER
858 case AV_CODEC_ID_MPEG4:
859 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG4;
862 #if CONFIG_VP8_CUVID_DECODER
863 case AV_CODEC_ID_VP8:
864 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP8;
867 #if CONFIG_VP9_CUVID_DECODER
868 case AV_CODEC_ID_VP9:
869 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP9;
872 #if CONFIG_VC1_CUVID_DECODER
873 case AV_CODEC_ID_VC1:
874 ctx->cuparseinfo.CodecType = cudaVideoCodec_VC1;
878 av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");
882 if (avctx->codec->id == AV_CODEC_ID_H264 || avctx->codec->id == AV_CODEC_ID_HEVC) {
883 if (avctx->codec->id == AV_CODEC_ID_H264)
884 bsf = av_bsf_get_by_name("h264_mp4toannexb");
886 bsf = av_bsf_get_by_name("hevc_mp4toannexb");
889 ret = AVERROR_BSF_NOT_FOUND;
892 if (ret = av_bsf_alloc(bsf, &ctx->bsf)) {
895 if (((ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx)) < 0) || ((ret = av_bsf_init(ctx->bsf)) < 0)) {
896 av_bsf_free(&ctx->bsf);
900 ctx->cuparse_ext.format.seqhdr_data_length = ctx->bsf->par_out->extradata_size;
901 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
902 ctx->bsf->par_out->extradata,
903 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), ctx->bsf->par_out->extradata_size));
904 } else if (avctx->extradata_size > 0) {
905 ctx->cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;
906 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
908 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), avctx->extradata_size));
911 ctx->cuparseinfo.ulMaxNumDecodeSurfaces = ctx->nb_surfaces;
912 ctx->cuparseinfo.ulMaxDisplayDelay = 4;
913 ctx->cuparseinfo.pUserData = avctx;
914 ctx->cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;
915 ctx->cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;
916 ctx->cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;
918 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
922 ret = cuvid_test_dummy_decoder(avctx, &ctx->cuparseinfo,
928 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
932 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
933 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
935 if (seq_pkt.payload && seq_pkt.payload_size) {
936 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
941 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
945 ctx->prev_pts = INT64_MIN;
947 if (!avctx->pkt_timebase.num || !avctx->pkt_timebase.den)
948 av_log(avctx, AV_LOG_WARNING, "Invalid pkt_timebase, passing timestamps as-is.\n");
953 cuvid_decode_end(avctx);
957 static void cuvid_flush(AVCodecContext *avctx)
959 CuvidContext *ctx = avctx->priv_data;
960 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
961 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
962 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
963 CUVIDSOURCEDATAPACKET seq_pkt = { 0 };
966 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
970 av_fifo_freep(&ctx->frame_queue);
972 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
973 if (!ctx->frame_queue) {
974 av_log(avctx, AV_LOG_ERROR, "Failed to recreate frame queue on flush\n");
978 if (ctx->cudecoder) {
979 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
980 ctx->cudecoder = NULL;
984 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
985 ctx->cuparser = NULL;
988 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
992 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
993 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
995 if (seq_pkt.payload && seq_pkt.payload_size) {
996 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
1001 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
1005 ctx->prev_pts = INT64_MIN;
1006 ctx->decoder_flushing = 0;
1010 av_log(avctx, AV_LOG_ERROR, "CUDA reinit on flush failed\n");
1013 #define OFFSET(x) offsetof(CuvidContext, x)
1014 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1015 static const AVOption options[] = {
1016 { "deint", "Set deinterlacing mode", OFFSET(deint_mode), AV_OPT_TYPE_INT, { .i64 = cudaVideoDeinterlaceMode_Weave }, cudaVideoDeinterlaceMode_Weave, cudaVideoDeinterlaceMode_Adaptive, VD, "deint" },
1017 { "weave", "Weave deinterlacing (do nothing)", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Weave }, 0, 0, VD, "deint" },
1018 { "bob", "Bob deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Bob }, 0, 0, VD, "deint" },
1019 { "adaptive", "Adaptive deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Adaptive }, 0, 0, VD, "deint" },
1020 { "gpu", "GPU to be used for decoding", OFFSET(cu_gpu), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1021 { "surfaces", "Maximum surfaces to be used for decoding", OFFSET(nb_surfaces), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, INT_MAX, VD },
1022 { "drop_second_field", "Drop second field when deinterlacing", OFFSET(drop_second_field), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1023 { "crop", "Crop (top)x(bottom)x(left)x(right)", OFFSET(crop_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1024 { "resize", "Resize (width)x(height)", OFFSET(resize_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1028 #define DEFINE_CUVID_CODEC(x, X) \
1029 static const AVClass x##_cuvid_class = { \
1030 .class_name = #x "_cuvid", \
1031 .item_name = av_default_item_name, \
1032 .option = options, \
1033 .version = LIBAVUTIL_VERSION_INT, \
1035 AVHWAccel ff_##x##_cuvid_hwaccel = { \
1036 .name = #x "_cuvid", \
1037 .type = AVMEDIA_TYPE_VIDEO, \
1038 .id = AV_CODEC_ID_##X, \
1039 .pix_fmt = AV_PIX_FMT_CUDA, \
1041 AVCodec ff_##x##_cuvid_decoder = { \
1042 .name = #x "_cuvid", \
1043 .long_name = NULL_IF_CONFIG_SMALL("Nvidia CUVID " #X " decoder"), \
1044 .type = AVMEDIA_TYPE_VIDEO, \
1045 .id = AV_CODEC_ID_##X, \
1046 .priv_data_size = sizeof(CuvidContext), \
1047 .priv_class = &x##_cuvid_class, \
1048 .init = cuvid_decode_init, \
1049 .close = cuvid_decode_end, \
1050 .decode = cuvid_decode_frame, \
1051 .receive_frame = cuvid_output_frame, \
1052 .flush = cuvid_flush, \
1053 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING, \
1054 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_CUDA, \
1058 AV_PIX_FMT_NONE }, \
1061 #if CONFIG_HEVC_CUVID_DECODER
1062 DEFINE_CUVID_CODEC(hevc, HEVC)
1065 #if CONFIG_H264_CUVID_DECODER
1066 DEFINE_CUVID_CODEC(h264, H264)
1069 #if CONFIG_MJPEG_CUVID_DECODER
1070 DEFINE_CUVID_CODEC(mjpeg, MJPEG)
1073 #if CONFIG_MPEG1_CUVID_DECODER
1074 DEFINE_CUVID_CODEC(mpeg1, MPEG1VIDEO)
1077 #if CONFIG_MPEG2_CUVID_DECODER
1078 DEFINE_CUVID_CODEC(mpeg2, MPEG2VIDEO)
1081 #if CONFIG_MPEG4_CUVID_DECODER
1082 DEFINE_CUVID_CODEC(mpeg4, MPEG4)
1085 #if CONFIG_VP8_CUVID_DECODER
1086 DEFINE_CUVID_CODEC(vp8, VP8)
1089 #if CONFIG_VP9_CUVID_DECODER
1090 DEFINE_CUVID_CODEC(vp9, VP9)
1093 #if CONFIG_VC1_CUVID_DECODER
1094 DEFINE_CUVID_CODEC(vc1, VC1)