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;
45 int drop_second_field;
61 AVBufferRef *hwdevice;
66 AVFifoBuffer *frame_queue;
69 int deint_mode_current;
75 cudaVideoCodec codec_type;
76 cudaVideoChromaFormat chroma_format;
78 CUVIDPARSERPARAMS cuparseinfo;
79 CUVIDEOFORMATEX cuparse_ext;
85 typedef struct CuvidParsedFrame
87 CUVIDPARSERDISPINFO dispinfo;
92 static int check_cu(AVCodecContext *avctx, CUresult err, const char *func)
94 CuvidContext *ctx = avctx->priv_data;
96 const char *err_string;
98 av_log(avctx, AV_LOG_TRACE, "Calling %s\n", func);
100 if (err == CUDA_SUCCESS)
103 ctx->cudl->cuGetErrorName(err, &err_name);
104 ctx->cudl->cuGetErrorString(err, &err_string);
106 av_log(avctx, AV_LOG_ERROR, "%s failed", func);
107 if (err_name && err_string)
108 av_log(avctx, AV_LOG_ERROR, " -> %s: %s", err_name, err_string);
109 av_log(avctx, AV_LOG_ERROR, "\n");
111 return AVERROR_EXTERNAL;
114 #define CHECK_CU(x) check_cu(avctx, (x), #x)
116 static int CUDAAPI cuvid_handle_video_sequence(void *opaque, CUVIDEOFORMAT* format)
118 AVCodecContext *avctx = opaque;
119 CuvidContext *ctx = avctx->priv_data;
120 AVHWFramesContext *hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
121 CUVIDDECODECREATEINFO cuinfo;
124 int old_width = avctx->width;
125 int old_height = avctx->height;
127 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
128 AV_PIX_FMT_NONE, // Will be updated below
131 av_log(avctx, AV_LOG_TRACE, "pfnSequenceCallback, progressive_sequence=%d\n", format->progressive_sequence);
133 memset(&cuinfo, 0, sizeof(cuinfo));
135 ctx->internal_error = 0;
137 avctx->coded_width = cuinfo.ulWidth = format->coded_width;
138 avctx->coded_height = cuinfo.ulHeight = format->coded_height;
141 cuinfo.display_area.left = format->display_area.left + ctx->crop.left;
142 cuinfo.display_area.top = format->display_area.top + ctx->crop.top;
143 cuinfo.display_area.right = format->display_area.right - ctx->crop.right;
144 cuinfo.display_area.bottom = format->display_area.bottom - ctx->crop.bottom;
146 // width and height need to be set before calling ff_get_format
147 if (ctx->resize_expr) {
148 avctx->width = ctx->resize.width;
149 avctx->height = ctx->resize.height;
151 avctx->width = cuinfo.display_area.right - cuinfo.display_area.left;
152 avctx->height = cuinfo.display_area.bottom - cuinfo.display_area.top;
155 // target width/height need to be multiples of two
156 cuinfo.ulTargetWidth = avctx->width = (avctx->width + 1) & ~1;
157 cuinfo.ulTargetHeight = avctx->height = (avctx->height + 1) & ~1;
159 // aspect ratio conversion, 1:1, depends on scaled resolution
160 cuinfo.target_rect.left = 0;
161 cuinfo.target_rect.top = 0;
162 cuinfo.target_rect.right = cuinfo.ulTargetWidth;
163 cuinfo.target_rect.bottom = cuinfo.ulTargetHeight;
165 switch (format->bit_depth_luma_minus8) {
167 pix_fmts[1] = AV_PIX_FMT_NV12;
170 pix_fmts[1] = AV_PIX_FMT_P010;
173 pix_fmts[1] = AV_PIX_FMT_P016;
176 av_log(avctx, AV_LOG_ERROR, "unsupported bit depth: %d\n",
177 format->bit_depth_luma_minus8 + 8);
178 ctx->internal_error = AVERROR(EINVAL);
181 surface_fmt = ff_get_format(avctx, pix_fmts);
182 if (surface_fmt < 0) {
183 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", surface_fmt);
184 ctx->internal_error = AVERROR(EINVAL);
188 av_log(avctx, AV_LOG_VERBOSE, "Formats: Original: %s | HW: %s | SW: %s\n",
189 av_get_pix_fmt_name(avctx->pix_fmt),
190 av_get_pix_fmt_name(surface_fmt),
191 av_get_pix_fmt_name(avctx->sw_pix_fmt));
193 avctx->pix_fmt = surface_fmt;
195 // Update our hwframe ctx, as the get_format callback might have refreshed it!
196 if (avctx->hw_frames_ctx) {
197 av_buffer_unref(&ctx->hwframe);
199 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
201 ctx->internal_error = AVERROR(ENOMEM);
205 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
208 ff_set_sar(avctx, av_div_q(
209 (AVRational){ format->display_aspect_ratio.x, format->display_aspect_ratio.y },
210 (AVRational){ avctx->width, avctx->height }));
212 ctx->deint_mode_current = format->progressive_sequence
213 ? cudaVideoDeinterlaceMode_Weave
216 if (!format->progressive_sequence && ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave)
217 avctx->flags |= AV_CODEC_FLAG_INTERLACED_DCT;
219 avctx->flags &= ~AV_CODEC_FLAG_INTERLACED_DCT;
221 if (format->video_signal_description.video_full_range_flag)
222 avctx->color_range = AVCOL_RANGE_JPEG;
224 avctx->color_range = AVCOL_RANGE_MPEG;
226 avctx->color_primaries = format->video_signal_description.color_primaries;
227 avctx->color_trc = format->video_signal_description.transfer_characteristics;
228 avctx->colorspace = format->video_signal_description.matrix_coefficients;
231 avctx->bit_rate = format->bitrate;
233 if (format->frame_rate.numerator && format->frame_rate.denominator) {
234 avctx->framerate.num = format->frame_rate.numerator;
235 avctx->framerate.den = format->frame_rate.denominator;
239 && avctx->coded_width == format->coded_width
240 && avctx->coded_height == format->coded_height
241 && avctx->width == old_width
242 && avctx->height == old_height
243 && ctx->chroma_format == format->chroma_format
244 && ctx->codec_type == format->codec)
247 if (ctx->cudecoder) {
248 av_log(avctx, AV_LOG_TRACE, "Re-initializing decoder\n");
249 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder));
250 if (ctx->internal_error < 0)
252 ctx->cudecoder = NULL;
255 if (hwframe_ctx->pool && (
256 hwframe_ctx->width < avctx->width ||
257 hwframe_ctx->height < avctx->height ||
258 hwframe_ctx->format != AV_PIX_FMT_CUDA ||
259 hwframe_ctx->sw_format != avctx->sw_pix_fmt)) {
260 av_log(avctx, AV_LOG_ERROR, "AVHWFramesContext is already initialized with incompatible parameters\n");
261 av_log(avctx, AV_LOG_DEBUG, "width: %d <-> %d\n", hwframe_ctx->width, avctx->width);
262 av_log(avctx, AV_LOG_DEBUG, "height: %d <-> %d\n", hwframe_ctx->height, avctx->height);
263 av_log(avctx, AV_LOG_DEBUG, "format: %s <-> cuda\n", av_get_pix_fmt_name(hwframe_ctx->format));
264 av_log(avctx, AV_LOG_DEBUG, "sw_format: %s <-> %s\n",
265 av_get_pix_fmt_name(hwframe_ctx->sw_format), av_get_pix_fmt_name(avctx->sw_pix_fmt));
266 ctx->internal_error = AVERROR(EINVAL);
270 if (format->chroma_format != cudaVideoChromaFormat_420) {
271 av_log(avctx, AV_LOG_ERROR, "Chroma formats other than 420 are not supported\n");
272 ctx->internal_error = AVERROR(EINVAL);
276 ctx->chroma_format = format->chroma_format;
278 cuinfo.CodecType = ctx->codec_type = format->codec;
279 cuinfo.ChromaFormat = format->chroma_format;
281 switch (avctx->sw_pix_fmt) {
282 case AV_PIX_FMT_NV12:
283 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
285 case AV_PIX_FMT_P010:
286 case AV_PIX_FMT_P016:
287 cuinfo.OutputFormat = cudaVideoSurfaceFormat_P016;
290 av_log(avctx, AV_LOG_ERROR, "Output formats other than NV12, P010 or P016 are not supported\n");
291 ctx->internal_error = AVERROR(EINVAL);
295 cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
296 cuinfo.ulNumOutputSurfaces = 1;
297 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
298 cuinfo.bitDepthMinus8 = format->bit_depth_luma_minus8;
299 cuinfo.DeinterlaceMode = ctx->deint_mode_current;
301 if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave && !ctx->drop_second_field)
302 avctx->framerate = av_mul_q(avctx->framerate, (AVRational){2, 1});
304 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&ctx->cudecoder, &cuinfo));
305 if (ctx->internal_error < 0)
308 if (!hwframe_ctx->pool) {
309 hwframe_ctx->format = AV_PIX_FMT_CUDA;
310 hwframe_ctx->sw_format = avctx->sw_pix_fmt;
311 hwframe_ctx->width = avctx->width;
312 hwframe_ctx->height = avctx->height;
314 if ((ctx->internal_error = av_hwframe_ctx_init(ctx->hwframe)) < 0) {
315 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_init failed\n");
323 static int CUDAAPI cuvid_handle_picture_decode(void *opaque, CUVIDPICPARAMS* picparams)
325 AVCodecContext *avctx = opaque;
326 CuvidContext *ctx = avctx->priv_data;
328 av_log(avctx, AV_LOG_TRACE, "pfnDecodePicture\n");
330 ctx->internal_error = CHECK_CU(ctx->cvdl->cuvidDecodePicture(ctx->cudecoder, picparams));
331 if (ctx->internal_error < 0)
337 static int CUDAAPI cuvid_handle_picture_display(void *opaque, CUVIDPARSERDISPINFO* dispinfo)
339 AVCodecContext *avctx = opaque;
340 CuvidContext *ctx = avctx->priv_data;
341 CuvidParsedFrame parsed_frame = { { 0 } };
343 parsed_frame.dispinfo = *dispinfo;
344 ctx->internal_error = 0;
346 if (ctx->deint_mode_current == cudaVideoDeinterlaceMode_Weave) {
347 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
349 parsed_frame.is_deinterlacing = 1;
350 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
351 if (!ctx->drop_second_field) {
352 parsed_frame.second_field = 1;
353 av_fifo_generic_write(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
360 static int cuvid_decode_packet(AVCodecContext *avctx, const AVPacket *avpkt)
362 CuvidContext *ctx = avctx->priv_data;
363 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
364 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
365 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
366 CUVIDSOURCEDATAPACKET cupkt;
367 AVPacket filter_packet = { 0 };
368 AVPacket filtered_packet = { 0 };
369 int ret = 0, eret = 0, is_flush = ctx->decoder_flushing;
371 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_packet\n");
373 if (is_flush && avpkt && avpkt->size)
376 if ((av_fifo_size(ctx->frame_queue) / sizeof(CuvidParsedFrame)) + 2 > ctx->nb_surfaces && avpkt && avpkt->size)
377 return AVERROR(EAGAIN);
379 if (ctx->bsf && avpkt && avpkt->size) {
380 if ((ret = av_packet_ref(&filter_packet, avpkt)) < 0) {
381 av_log(avctx, AV_LOG_ERROR, "av_packet_ref failed\n");
385 if ((ret = av_bsf_send_packet(ctx->bsf, &filter_packet)) < 0) {
386 av_log(avctx, AV_LOG_ERROR, "av_bsf_send_packet failed\n");
387 av_packet_unref(&filter_packet);
391 if ((ret = av_bsf_receive_packet(ctx->bsf, &filtered_packet)) < 0) {
392 av_log(avctx, AV_LOG_ERROR, "av_bsf_receive_packet failed\n");
396 avpkt = &filtered_packet;
399 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
401 av_packet_unref(&filtered_packet);
405 memset(&cupkt, 0, sizeof(cupkt));
407 if (avpkt && avpkt->size) {
408 cupkt.payload_size = avpkt->size;
409 cupkt.payload = avpkt->data;
411 if (avpkt->pts != AV_NOPTS_VALUE) {
412 cupkt.flags = CUVID_PKT_TIMESTAMP;
413 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
414 cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000});
416 cupkt.timestamp = avpkt->pts;
419 cupkt.flags = CUVID_PKT_ENDOFSTREAM;
420 ctx->decoder_flushing = 1;
423 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &cupkt));
425 av_packet_unref(&filtered_packet);
430 // cuvidParseVideoData doesn't return an error just because stuff failed...
431 if (ctx->internal_error) {
432 av_log(avctx, AV_LOG_ERROR, "cuvid decode callback error\n");
433 ret = ctx->internal_error;
438 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
450 static int cuvid_output_frame(AVCodecContext *avctx, AVFrame *frame)
452 CuvidContext *ctx = avctx->priv_data;
453 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
454 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
455 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
456 CUdeviceptr mapped_frame = 0;
457 int ret = 0, eret = 0;
459 av_log(avctx, AV_LOG_TRACE, "cuvid_output_frame\n");
461 if (ctx->decoder_flushing) {
462 ret = cuvid_decode_packet(avctx, NULL);
463 if (ret < 0 && ret != AVERROR_EOF)
467 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
471 if (av_fifo_size(ctx->frame_queue)) {
472 CuvidParsedFrame parsed_frame;
473 CUVIDPROCPARAMS params;
474 unsigned int pitch = 0;
478 av_fifo_generic_read(ctx->frame_queue, &parsed_frame, sizeof(CuvidParsedFrame), NULL);
480 memset(¶ms, 0, sizeof(params));
481 params.progressive_frame = parsed_frame.dispinfo.progressive_frame;
482 params.second_field = parsed_frame.second_field;
483 params.top_field_first = parsed_frame.dispinfo.top_field_first;
485 ret = CHECK_CU(ctx->cvdl->cuvidMapVideoFrame(ctx->cudecoder, parsed_frame.dispinfo.picture_index, &mapped_frame, &pitch, ¶ms));
489 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
490 ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0);
492 av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n");
496 ret = ff_decode_frame_props(avctx, frame);
498 av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n");
502 for (i = 0; i < 2; i++) {
503 CUDA_MEMCPY2D cpy = {
504 .srcMemoryType = CU_MEMORYTYPE_DEVICE,
505 .dstMemoryType = CU_MEMORYTYPE_DEVICE,
506 .srcDevice = mapped_frame,
507 .dstDevice = (CUdeviceptr)frame->data[i],
509 .dstPitch = frame->linesize[i],
511 .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
512 .Height = avctx->height >> (i ? 1 : 0),
515 ret = CHECK_CU(ctx->cudl->cuMemcpy2D(&cpy));
519 offset += avctx->height;
521 } else if (avctx->pix_fmt == AV_PIX_FMT_NV12 ||
522 avctx->pix_fmt == AV_PIX_FMT_P010 ||
523 avctx->pix_fmt == AV_PIX_FMT_P016) {
524 AVFrame *tmp_frame = av_frame_alloc();
526 av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n");
527 ret = AVERROR(ENOMEM);
531 tmp_frame->format = AV_PIX_FMT_CUDA;
532 tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe);
533 tmp_frame->data[0] = (uint8_t*)mapped_frame;
534 tmp_frame->linesize[0] = pitch;
535 tmp_frame->data[1] = (uint8_t*)(mapped_frame + avctx->height * pitch);
536 tmp_frame->linesize[1] = pitch;
537 tmp_frame->width = avctx->width;
538 tmp_frame->height = avctx->height;
540 ret = ff_get_buffer(avctx, frame, 0);
542 av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n");
543 av_frame_free(&tmp_frame);
547 ret = av_hwframe_transfer_data(frame, tmp_frame, 0);
549 av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n");
550 av_frame_free(&tmp_frame);
553 av_frame_free(&tmp_frame);
559 frame->width = avctx->width;
560 frame->height = avctx->height;
561 if (avctx->pkt_timebase.num && avctx->pkt_timebase.den)
562 frame->pts = av_rescale_q(parsed_frame.dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase);
564 frame->pts = parsed_frame.dispinfo.timestamp;
566 if (parsed_frame.second_field) {
567 if (ctx->prev_pts == INT64_MIN) {
568 ctx->prev_pts = frame->pts;
569 frame->pts += (avctx->pkt_timebase.den * avctx->framerate.den) / (avctx->pkt_timebase.num * avctx->framerate.num);
571 int pts_diff = (frame->pts - ctx->prev_pts) / 2;
572 ctx->prev_pts = frame->pts;
573 frame->pts += pts_diff;
577 /* CUVIDs opaque reordering breaks the internal pkt logic.
578 * So set pkt_pts and clear all the other pkt_ fields.
581 FF_DISABLE_DEPRECATION_WARNINGS
582 frame->pkt_pts = frame->pts;
583 FF_ENABLE_DEPRECATION_WARNINGS
585 av_frame_set_pkt_pos(frame, -1);
586 av_frame_set_pkt_duration(frame, 0);
587 av_frame_set_pkt_size(frame, -1);
589 frame->interlaced_frame = !parsed_frame.is_deinterlacing && !parsed_frame.dispinfo.progressive_frame;
591 if (frame->interlaced_frame)
592 frame->top_field_first = parsed_frame.dispinfo.top_field_first;
593 } else if (ctx->decoder_flushing) {
596 ret = AVERROR(EAGAIN);
601 eret = CHECK_CU(ctx->cvdl->cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame));
603 eret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
611 static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
613 CuvidContext *ctx = avctx->priv_data;
614 AVFrame *frame = data;
617 av_log(avctx, AV_LOG_TRACE, "cuvid_decode_frame\n");
619 if (ctx->deint_mode_current != cudaVideoDeinterlaceMode_Weave) {
620 av_log(avctx, AV_LOG_ERROR, "Deinterlacing is not supported via the old API\n");
621 return AVERROR(EINVAL);
624 if (!ctx->decoder_flushing) {
625 ret = cuvid_decode_packet(avctx, avpkt);
630 ret = cuvid_output_frame(avctx, frame);
631 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
633 } else if (ret < 0) {
642 static av_cold int cuvid_decode_end(AVCodecContext *avctx)
644 CuvidContext *ctx = avctx->priv_data;
646 av_fifo_freep(&ctx->frame_queue);
649 av_bsf_free(&ctx->bsf);
652 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
655 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
659 av_buffer_unref(&ctx->hwframe);
660 av_buffer_unref(&ctx->hwdevice);
662 cuvid_free_functions(&ctx->cvdl);
667 static int cuvid_test_dummy_decoder(AVCodecContext *avctx,
668 const CUVIDPARSERPARAMS *cuparseinfo,
672 CuvidContext *ctx = avctx->priv_data;
673 CUVIDDECODECREATEINFO cuinfo;
674 CUvideodecoder cudec = 0;
677 memset(&cuinfo, 0, sizeof(cuinfo));
679 cuinfo.CodecType = cuparseinfo->CodecType;
680 cuinfo.ChromaFormat = cudaVideoChromaFormat_420;
681 cuinfo.OutputFormat = cudaVideoSurfaceFormat_NV12;
683 cuinfo.ulWidth = probed_width;
684 cuinfo.ulHeight = probed_height;
685 cuinfo.ulTargetWidth = cuinfo.ulWidth;
686 cuinfo.ulTargetHeight = cuinfo.ulHeight;
688 cuinfo.target_rect.left = 0;
689 cuinfo.target_rect.top = 0;
690 cuinfo.target_rect.right = cuinfo.ulWidth;
691 cuinfo.target_rect.bottom = cuinfo.ulHeight;
693 cuinfo.ulNumDecodeSurfaces = ctx->nb_surfaces;
694 cuinfo.ulNumOutputSurfaces = 1;
695 cuinfo.ulCreationFlags = cudaVideoCreate_PreferCUVID;
696 cuinfo.bitDepthMinus8 = 0;
698 cuinfo.DeinterlaceMode = cudaVideoDeinterlaceMode_Weave;
700 ret = CHECK_CU(ctx->cvdl->cuvidCreateDecoder(&cudec, &cuinfo));
704 ret = CHECK_CU(ctx->cvdl->cuvidDestroyDecoder(cudec));
711 static av_cold int cuvid_decode_init(AVCodecContext *avctx)
713 CuvidContext *ctx = avctx->priv_data;
714 AVCUDADeviceContext *device_hwctx;
715 AVHWDeviceContext *device_ctx;
716 AVHWFramesContext *hwframe_ctx;
717 CUVIDSOURCEDATAPACKET seq_pkt;
718 CUcontext cuda_ctx = NULL;
720 const AVBitStreamFilter *bsf;
723 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,
727 int probed_width = avctx->coded_width ? avctx->coded_width : 1280;
728 int probed_height = avctx->coded_height ? avctx->coded_height : 720;
730 // Accelerated transcoding scenarios with 'ffmpeg' require that the
731 // pix_fmt be set to AV_PIX_FMT_CUDA early. The sw_pix_fmt, and the
732 // pix_fmt for non-accelerated transcoding, do not need to be correct
733 // but need to be set to something. We arbitrarily pick NV12.
734 ret = ff_get_format(avctx, pix_fmts);
736 av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);
739 avctx->pix_fmt = ret;
741 if (ctx->resize_expr && sscanf(ctx->resize_expr, "%dx%d",
742 &ctx->resize.width, &ctx->resize.height) != 2) {
743 av_log(avctx, AV_LOG_ERROR, "Invalid resize expressions\n");
744 ret = AVERROR(EINVAL);
748 if (ctx->crop_expr && sscanf(ctx->crop_expr, "%dx%dx%dx%d",
749 &ctx->crop.top, &ctx->crop.bottom,
750 &ctx->crop.left, &ctx->crop.right) != 4) {
751 av_log(avctx, AV_LOG_ERROR, "Invalid cropping expressions\n");
752 ret = AVERROR(EINVAL);
756 ret = cuvid_load_functions(&ctx->cvdl);
758 av_log(avctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
762 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
763 if (!ctx->frame_queue) {
764 ret = AVERROR(ENOMEM);
768 if (avctx->hw_frames_ctx) {
769 ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);
771 ret = AVERROR(ENOMEM);
775 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
777 ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);
778 if (!ctx->hwdevice) {
779 ret = AVERROR(ENOMEM);
783 ret = av_hwdevice_ctx_create(&ctx->hwdevice, AV_HWDEVICE_TYPE_CUDA, ctx->cu_gpu, NULL, 0);
787 ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);
789 av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");
790 ret = AVERROR(ENOMEM);
794 hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;
797 device_ctx = hwframe_ctx->device_ctx;
798 device_hwctx = device_ctx->hwctx;
800 cuda_ctx = device_hwctx->cuda_ctx;
801 ctx->cudl = device_hwctx->internal->cuda_dl;
803 memset(&ctx->cuparseinfo, 0, sizeof(ctx->cuparseinfo));
804 memset(&ctx->cuparse_ext, 0, sizeof(ctx->cuparse_ext));
805 memset(&seq_pkt, 0, sizeof(seq_pkt));
807 ctx->cuparseinfo.pExtVideoInfo = &ctx->cuparse_ext;
809 switch (avctx->codec->id) {
810 #if CONFIG_H264_CUVID_DECODER
811 case AV_CODEC_ID_H264:
812 ctx->cuparseinfo.CodecType = cudaVideoCodec_H264;
815 #if CONFIG_HEVC_CUVID_DECODER
816 case AV_CODEC_ID_HEVC:
817 ctx->cuparseinfo.CodecType = cudaVideoCodec_HEVC;
820 #if CONFIG_MJPEG_CUVID_DECODER
821 case AV_CODEC_ID_MJPEG:
822 ctx->cuparseinfo.CodecType = cudaVideoCodec_JPEG;
825 #if CONFIG_MPEG1_CUVID_DECODER
826 case AV_CODEC_ID_MPEG1VIDEO:
827 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG1;
830 #if CONFIG_MPEG2_CUVID_DECODER
831 case AV_CODEC_ID_MPEG2VIDEO:
832 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG2;
835 #if CONFIG_MPEG4_CUVID_DECODER
836 case AV_CODEC_ID_MPEG4:
837 ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG4;
840 #if CONFIG_VP8_CUVID_DECODER
841 case AV_CODEC_ID_VP8:
842 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP8;
845 #if CONFIG_VP9_CUVID_DECODER
846 case AV_CODEC_ID_VP9:
847 ctx->cuparseinfo.CodecType = cudaVideoCodec_VP9;
850 #if CONFIG_VC1_CUVID_DECODER
851 case AV_CODEC_ID_VC1:
852 ctx->cuparseinfo.CodecType = cudaVideoCodec_VC1;
856 av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");
860 if (avctx->codec->id == AV_CODEC_ID_H264 || avctx->codec->id == AV_CODEC_ID_HEVC) {
861 if (avctx->codec->id == AV_CODEC_ID_H264)
862 bsf = av_bsf_get_by_name("h264_mp4toannexb");
864 bsf = av_bsf_get_by_name("hevc_mp4toannexb");
867 ret = AVERROR_BSF_NOT_FOUND;
870 if (ret = av_bsf_alloc(bsf, &ctx->bsf)) {
873 if (((ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx)) < 0) || ((ret = av_bsf_init(ctx->bsf)) < 0)) {
874 av_bsf_free(&ctx->bsf);
878 ctx->cuparse_ext.format.seqhdr_data_length = ctx->bsf->par_out->extradata_size;
879 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
880 ctx->bsf->par_out->extradata,
881 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), ctx->bsf->par_out->extradata_size));
882 } else if (avctx->extradata_size > 0) {
883 ctx->cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;
884 memcpy(ctx->cuparse_ext.raw_seqhdr_data,
886 FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), avctx->extradata_size));
889 ctx->cuparseinfo.ulMaxNumDecodeSurfaces = ctx->nb_surfaces;
890 ctx->cuparseinfo.ulMaxDisplayDelay = 4;
891 ctx->cuparseinfo.pUserData = avctx;
892 ctx->cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;
893 ctx->cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;
894 ctx->cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;
896 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
900 ret = cuvid_test_dummy_decoder(avctx, &ctx->cuparseinfo,
906 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
910 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
911 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
913 if (seq_pkt.payload && seq_pkt.payload_size) {
914 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
919 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
923 ctx->prev_pts = INT64_MIN;
925 if (!avctx->pkt_timebase.num || !avctx->pkt_timebase.den)
926 av_log(avctx, AV_LOG_WARNING, "Invalid pkt_timebase, passing timestamps as-is.\n");
931 cuvid_decode_end(avctx);
935 static void cuvid_flush(AVCodecContext *avctx)
937 CuvidContext *ctx = avctx->priv_data;
938 AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data;
939 AVCUDADeviceContext *device_hwctx = device_ctx->hwctx;
940 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
941 CUVIDSOURCEDATAPACKET seq_pkt = { 0 };
944 ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));
948 av_fifo_freep(&ctx->frame_queue);
950 ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));
951 if (!ctx->frame_queue) {
952 av_log(avctx, AV_LOG_ERROR, "Failed to recreate frame queue on flush\n");
956 if (ctx->cudecoder) {
957 ctx->cvdl->cuvidDestroyDecoder(ctx->cudecoder);
958 ctx->cudecoder = NULL;
962 ctx->cvdl->cuvidDestroyVideoParser(ctx->cuparser);
963 ctx->cuparser = NULL;
966 ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));
970 seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;
971 seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;
973 if (seq_pkt.payload && seq_pkt.payload_size) {
974 ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));
979 ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));
983 ctx->prev_pts = INT64_MIN;
984 ctx->decoder_flushing = 0;
988 av_log(avctx, AV_LOG_ERROR, "CUDA reinit on flush failed\n");
991 #define OFFSET(x) offsetof(CuvidContext, x)
992 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
993 static const AVOption options[] = {
994 { "deint", "Set deinterlacing mode", OFFSET(deint_mode), AV_OPT_TYPE_INT, { .i64 = cudaVideoDeinterlaceMode_Weave }, cudaVideoDeinterlaceMode_Weave, cudaVideoDeinterlaceMode_Adaptive, VD, "deint" },
995 { "weave", "Weave deinterlacing (do nothing)", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Weave }, 0, 0, VD, "deint" },
996 { "bob", "Bob deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Bob }, 0, 0, VD, "deint" },
997 { "adaptive", "Adaptive deinterlacing", 0, AV_OPT_TYPE_CONST, { .i64 = cudaVideoDeinterlaceMode_Adaptive }, 0, 0, VD, "deint" },
998 { "gpu", "GPU to be used for decoding", OFFSET(cu_gpu), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
999 { "surfaces", "Maximum surfaces to be used for decoding", OFFSET(nb_surfaces), AV_OPT_TYPE_INT, { .i64 = 25 }, 0, INT_MAX, VD },
1000 { "drop_second_field", "Drop second field when deinterlacing", OFFSET(drop_second_field), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
1001 { "crop", "Crop (top)x(bottom)x(left)x(right)", OFFSET(crop_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1002 { "resize", "Resize (width)x(height)", OFFSET(resize_expr), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VD },
1006 #define DEFINE_CUVID_CODEC(x, X) \
1007 static const AVClass x##_cuvid_class = { \
1008 .class_name = #x "_cuvid", \
1009 .item_name = av_default_item_name, \
1010 .option = options, \
1011 .version = LIBAVUTIL_VERSION_INT, \
1013 AVHWAccel ff_##x##_cuvid_hwaccel = { \
1014 .name = #x "_cuvid", \
1015 .type = AVMEDIA_TYPE_VIDEO, \
1016 .id = AV_CODEC_ID_##X, \
1017 .pix_fmt = AV_PIX_FMT_CUDA, \
1019 AVCodec ff_##x##_cuvid_decoder = { \
1020 .name = #x "_cuvid", \
1021 .long_name = NULL_IF_CONFIG_SMALL("Nvidia CUVID " #X " decoder"), \
1022 .type = AVMEDIA_TYPE_VIDEO, \
1023 .id = AV_CODEC_ID_##X, \
1024 .priv_data_size = sizeof(CuvidContext), \
1025 .priv_class = &x##_cuvid_class, \
1026 .init = cuvid_decode_init, \
1027 .close = cuvid_decode_end, \
1028 .decode = cuvid_decode_frame, \
1029 .send_packet = cuvid_decode_packet, \
1030 .receive_frame = cuvid_output_frame, \
1031 .flush = cuvid_flush, \
1032 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING, \
1033 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_CUDA, \
1037 AV_PIX_FMT_NONE }, \
1040 #if CONFIG_HEVC_CUVID_DECODER
1041 DEFINE_CUVID_CODEC(hevc, HEVC)
1044 #if CONFIG_H264_CUVID_DECODER
1045 DEFINE_CUVID_CODEC(h264, H264)
1048 #if CONFIG_MJPEG_CUVID_DECODER
1049 DEFINE_CUVID_CODEC(mjpeg, MJPEG)
1052 #if CONFIG_MPEG1_CUVID_DECODER
1053 DEFINE_CUVID_CODEC(mpeg1, MPEG1VIDEO)
1056 #if CONFIG_MPEG2_CUVID_DECODER
1057 DEFINE_CUVID_CODEC(mpeg2, MPEG2VIDEO)
1060 #if CONFIG_MPEG4_CUVID_DECODER
1061 DEFINE_CUVID_CODEC(mpeg4, MPEG4)
1064 #if CONFIG_VP8_CUVID_DECODER
1065 DEFINE_CUVID_CODEC(vp8, VP8)
1068 #if CONFIG_VP9_CUVID_DECODER
1069 DEFINE_CUVID_CODEC(vp9, VP9)
1072 #if CONFIG_VC1_CUVID_DECODER
1073 DEFINE_CUVID_CODEC(vc1, VC1)