2 * H.264/HEVC hardware encoding using nvidia nvenc
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
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/imgutils.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/mem.h"
31 #include "libavutil/pixdesc.h"
34 #define NVENC_CAP 0x30
35 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
36 rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
37 rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
39 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
51 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
52 pix_fmt == AV_PIX_FMT_YUV444P16)
54 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
55 pix_fmt == AV_PIX_FMT_YUV444P16)
62 { NV_ENC_SUCCESS, 0, "success" },
63 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
64 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
65 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
66 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
67 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
68 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
69 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
70 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
71 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
72 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
73 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
74 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
75 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
76 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
77 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
78 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
79 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
80 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
81 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
82 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
83 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
84 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
85 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
86 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
87 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
90 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
93 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
94 if (nvenc_errors[i].nverr == err) {
96 *desc = nvenc_errors[i].desc;
97 return nvenc_errors[i].averr;
101 *desc = "unknown error";
102 return AVERROR_UNKNOWN;
105 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
106 const char *error_string)
110 ret = nvenc_map_error(err, &desc);
111 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
115 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
117 NvencContext *ctx = avctx->priv_data;
118 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
120 uint32_t nvenc_max_ver;
123 ret = cuda_load_functions(&dl_fn->cuda_dl);
127 ret = nvenc_load_functions(&dl_fn->nvenc_dl);
131 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
132 if (err != NV_ENC_SUCCESS)
133 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
135 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
137 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
138 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
139 "Required: %d.%d Found: %d.%d\n",
140 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
141 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
142 return AVERROR(ENOSYS);
145 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
147 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
148 if (err != NV_ENC_SUCCESS)
149 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
151 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
156 static av_cold int nvenc_open_session(AVCodecContext *avctx)
158 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
159 NvencContext *ctx = avctx->priv_data;
160 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
163 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
164 params.apiVersion = NVENCAPI_VERSION;
165 params.device = ctx->cu_context;
166 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
168 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
169 if (ret != NV_ENC_SUCCESS) {
170 ctx->nvencoder = NULL;
171 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
177 static int nvenc_check_codec_support(AVCodecContext *avctx)
179 NvencContext *ctx = avctx->priv_data;
180 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
181 int i, ret, count = 0;
184 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
186 if (ret != NV_ENC_SUCCESS || !count)
187 return AVERROR(ENOSYS);
189 guids = av_malloc(count * sizeof(GUID));
191 return AVERROR(ENOMEM);
193 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
194 if (ret != NV_ENC_SUCCESS) {
195 ret = AVERROR(ENOSYS);
199 ret = AVERROR(ENOSYS);
200 for (i = 0; i < count; i++) {
201 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
213 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
215 NvencContext *ctx = avctx->priv_data;
216 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
217 NV_ENC_CAPS_PARAM params = { 0 };
220 params.version = NV_ENC_CAPS_PARAM_VER;
221 params.capsToQuery = cap;
223 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
225 if (ret == NV_ENC_SUCCESS)
230 static int nvenc_check_capabilities(AVCodecContext *avctx)
232 NvencContext *ctx = avctx->priv_data;
235 ret = nvenc_check_codec_support(avctx);
237 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
241 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
242 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
243 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
244 return AVERROR(ENOSYS);
247 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
248 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
249 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
250 return AVERROR(ENOSYS);
253 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
254 if (ret < avctx->width) {
255 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
257 return AVERROR(ENOSYS);
260 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
261 if (ret < avctx->height) {
262 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
264 return AVERROR(ENOSYS);
267 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
268 if (ret < avctx->max_b_frames) {
269 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
270 avctx->max_b_frames, ret);
272 return AVERROR(ENOSYS);
275 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
276 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
277 av_log(avctx, AV_LOG_VERBOSE,
278 "Interlaced encoding is not supported. Supported level: %d\n",
280 return AVERROR(ENOSYS);
283 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
284 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
285 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
286 return AVERROR(ENOSYS);
289 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
290 if (ctx->rc_lookahead > 0 && ret <= 0) {
291 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
292 return AVERROR(ENOSYS);
295 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
296 if (ctx->temporal_aq > 0 && ret <= 0) {
297 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
298 return AVERROR(ENOSYS);
304 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
306 NvencContext *ctx = avctx->priv_data;
307 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
308 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
309 char name[128] = { 0};
310 int major, minor, ret;
314 int loglevel = AV_LOG_VERBOSE;
316 if (ctx->device == LIST_DEVICES)
317 loglevel = AV_LOG_INFO;
319 cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
320 if (cu_res != CUDA_SUCCESS) {
321 av_log(avctx, AV_LOG_ERROR,
322 "Cannot access the CUDA device %d\n",
327 cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
328 if (cu_res != CUDA_SUCCESS) {
329 av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
333 cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
334 if (cu_res != CUDA_SUCCESS) {
335 av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
339 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
340 if (((major << 4) | minor) < NVENC_CAP) {
341 av_log(avctx, loglevel, "does not support NVENC\n");
345 if (ctx->device != idx && ctx->device != ANY_DEVICE)
348 cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
349 if (cu_res != CUDA_SUCCESS) {
350 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
354 ctx->cu_context = ctx->cu_context_internal;
356 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
357 if (cu_res != CUDA_SUCCESS) {
358 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
362 if ((ret = nvenc_open_session(avctx)) < 0)
365 if ((ret = nvenc_check_capabilities(avctx)) < 0)
368 av_log(avctx, loglevel, "supports NVENC\n");
370 dl_fn->nvenc_device_count++;
372 if (ctx->device == idx || ctx->device == ANY_DEVICE)
376 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
377 ctx->nvencoder = NULL;
380 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
381 ctx->cu_context_internal = NULL;
384 return AVERROR(ENOSYS);
387 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
389 NvencContext *ctx = avctx->priv_data;
390 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
392 switch (avctx->codec->id) {
393 case AV_CODEC_ID_H264:
394 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
396 case AV_CODEC_ID_HEVC:
397 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
403 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
404 AVHWFramesContext *frames_ctx;
405 AVCUDADeviceContext *device_hwctx;
408 if (!avctx->hw_frames_ctx)
409 return AVERROR(EINVAL);
411 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
412 device_hwctx = frames_ctx->device_ctx->hwctx;
414 ctx->cu_context = device_hwctx->cuda_ctx;
416 ret = nvenc_open_session(avctx);
420 ret = nvenc_check_capabilities(avctx);
422 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
426 int i, nb_devices = 0;
428 if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
429 av_log(avctx, AV_LOG_ERROR,
430 "Cannot init CUDA\n");
431 return AVERROR_UNKNOWN;
434 if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
435 av_log(avctx, AV_LOG_ERROR,
436 "Cannot enumerate the CUDA devices\n");
437 return AVERROR_UNKNOWN;
441 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
442 return AVERROR_EXTERNAL;
445 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
447 dl_fn->nvenc_device_count = 0;
448 for (i = 0; i < nb_devices; ++i) {
449 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
453 if (ctx->device == LIST_DEVICES)
456 if (!dl_fn->nvenc_device_count) {
457 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
458 return AVERROR_EXTERNAL;
461 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
462 return AVERROR(EINVAL);
468 typedef struct GUIDTuple {
473 #define PRESET_ALIAS(alias, name, ...) \
474 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
476 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
478 static void nvenc_map_preset(NvencContext *ctx)
480 GUIDTuple presets[] = {
485 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
486 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
487 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
488 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
489 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
490 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
491 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
492 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
495 GUIDTuple *t = &presets[ctx->preset];
497 ctx->init_encode_params.presetGUID = t->guid;
498 ctx->flags = t->flags;
504 static av_cold void set_constqp(AVCodecContext *avctx)
506 NvencContext *ctx = avctx->priv_data;
507 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
509 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
510 rc->constQP.qpInterB = avctx->global_quality;
511 rc->constQP.qpInterP = avctx->global_quality;
512 rc->constQP.qpIntra = avctx->global_quality;
518 static av_cold void set_vbr(AVCodecContext *avctx)
520 NvencContext *ctx = avctx->priv_data;
521 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
524 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
528 rc->minQP.qpInterB = avctx->qmin;
529 rc->minQP.qpInterP = avctx->qmin;
530 rc->minQP.qpIntra = avctx->qmin;
532 rc->maxQP.qpInterB = avctx->qmax;
533 rc->maxQP.qpInterP = avctx->qmax;
534 rc->maxQP.qpIntra = avctx->qmax;
536 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
537 } else if (avctx->qmin >= 0) {
540 rc->minQP.qpInterB = avctx->qmin;
541 rc->minQP.qpInterP = avctx->qmin;
542 rc->minQP.qpIntra = avctx->qmin;
544 qp_inter_p = avctx->qmin;
546 qp_inter_p = 26; // default to 26
549 rc->enableInitialRCQP = 1;
550 rc->initialRCQP.qpInterP = qp_inter_p;
552 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
553 rc->initialRCQP.qpIntra = av_clip(
554 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
555 rc->initialRCQP.qpInterB = av_clip(
556 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
558 rc->initialRCQP.qpIntra = qp_inter_p;
559 rc->initialRCQP.qpInterB = qp_inter_p;
563 static av_cold void set_lossless(AVCodecContext *avctx)
565 NvencContext *ctx = avctx->priv_data;
566 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
568 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
569 rc->constQP.qpInterB = 0;
570 rc->constQP.qpInterP = 0;
571 rc->constQP.qpIntra = 0;
577 static void nvenc_override_rate_control(AVCodecContext *avctx)
579 NvencContext *ctx = avctx->priv_data;
580 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
583 case NV_ENC_PARAMS_RC_CONSTQP:
584 if (avctx->global_quality <= 0) {
585 av_log(avctx, AV_LOG_WARNING,
586 "The constant quality rate-control requires "
587 "the 'global_quality' option set.\n");
592 case NV_ENC_PARAMS_RC_2_PASS_VBR:
593 case NV_ENC_PARAMS_RC_VBR:
594 if (avctx->qmin < 0 && avctx->qmax < 0) {
595 av_log(avctx, AV_LOG_WARNING,
596 "The variable bitrate rate-control requires "
597 "the 'qmin' and/or 'qmax' option set.\n");
602 case NV_ENC_PARAMS_RC_VBR_MINQP:
603 if (avctx->qmin < 0) {
604 av_log(avctx, AV_LOG_WARNING,
605 "The variable bitrate rate-control requires "
606 "the 'qmin' option set.\n");
612 case NV_ENC_PARAMS_RC_CBR:
613 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
614 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
618 rc->rateControlMode = ctx->rc;
621 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
623 NvencContext *ctx = avctx->priv_data;
626 if (ctx->rc_lookahead > 0) {
627 nb_surfaces = ctx->rc_lookahead + ((ctx->encode_config.frameIntervalP > 0) ? ctx->encode_config.frameIntervalP : 0) + 1 + 4;
628 if (ctx->nb_surfaces < nb_surfaces) {
629 av_log(avctx, AV_LOG_WARNING,
630 "Defined rc_lookahead requires more surfaces, "
631 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
632 ctx->nb_surfaces = nb_surfaces;
636 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
637 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
642 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
644 NvencContext *ctx = avctx->priv_data;
646 if (avctx->bit_rate > 0) {
647 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
648 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
649 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
652 if (avctx->rc_max_rate > 0)
653 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
656 if (ctx->flags & NVENC_ONE_PASS)
658 if (ctx->flags & NVENC_TWO_PASSES)
661 if (ctx->twopass < 0)
662 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
666 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
668 ctx->rc = NV_ENC_PARAMS_RC_CBR;
670 } else if (avctx->global_quality > 0) {
671 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
672 } else if (ctx->twopass) {
673 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;
674 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
675 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
679 if (ctx->flags & NVENC_LOSSLESS) {
681 } else if (ctx->rc >= 0) {
682 nvenc_override_rate_control(avctx);
684 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
688 if (avctx->rc_buffer_size > 0) {
689 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
690 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
691 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
695 ctx->encode_config.rcParams.enableAQ = 1;
696 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
697 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
700 if (ctx->temporal_aq) {
701 ctx->encode_config.rcParams.enableTemporalAQ = 1;
702 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
705 if (ctx->rc_lookahead > 0) {
706 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
707 ctx->encode_config.frameIntervalP - 4;
710 av_log(avctx, AV_LOG_WARNING,
711 "Lookahead not enabled. Increase buffer delay (-delay).\n");
713 ctx->encode_config.rcParams.enableLookahead = 1;
714 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
715 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
716 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
717 av_log(avctx, AV_LOG_VERBOSE,
718 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
719 ctx->encode_config.rcParams.lookaheadDepth,
720 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
721 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
725 if (ctx->strict_gop) {
726 ctx->encode_config.rcParams.strictGOPTarget = 1;
727 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
731 ctx->encode_config.rcParams.enableNonRefP = 1;
733 if (ctx->zerolatency)
734 ctx->encode_config.rcParams.zeroReorderDelay = 1;
737 ctx->encode_config.rcParams.targetQuality = ctx->quality;
740 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
742 NvencContext *ctx = avctx->priv_data;
743 NV_ENC_CONFIG *cc = &ctx->encode_config;
744 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
745 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
747 vui->colourMatrix = avctx->colorspace;
748 vui->colourPrimaries = avctx->color_primaries;
749 vui->transferCharacteristics = avctx->color_trc;
750 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
751 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
753 vui->colourDescriptionPresentFlag =
754 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
756 vui->videoSignalTypePresentFlag =
757 (vui->colourDescriptionPresentFlag
758 || vui->videoFormat != 5
759 || vui->videoFullRangeFlag != 0);
762 h264->sliceModeData = 1;
764 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
765 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
766 h264->outputAUD = ctx->aud;
768 if (avctx->refs >= 0) {
769 /* 0 means "let the hardware decide" */
770 h264->maxNumRefFrames = avctx->refs;
772 if (avctx->gop_size >= 0) {
773 h264->idrPeriod = cc->gopLength;
776 if (IS_CBR(cc->rcParams.rateControlMode)) {
777 h264->outputBufferingPeriodSEI = 1;
778 h264->outputPictureTimingSEI = 1;
781 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||
782 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP ||
783 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_VBR) {
784 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
785 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
788 if (ctx->flags & NVENC_LOSSLESS) {
789 h264->qpPrimeYZeroTransformBypassFlag = 1;
791 switch(ctx->profile) {
792 case NV_ENC_H264_PROFILE_BASELINE:
793 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
794 avctx->profile = FF_PROFILE_H264_BASELINE;
796 case NV_ENC_H264_PROFILE_MAIN:
797 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
798 avctx->profile = FF_PROFILE_H264_MAIN;
800 case NV_ENC_H264_PROFILE_HIGH:
801 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
802 avctx->profile = FF_PROFILE_H264_HIGH;
804 case NV_ENC_H264_PROFILE_HIGH_444P:
805 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
806 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
811 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
812 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
813 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
814 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
817 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
819 h264->level = ctx->level;
824 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
826 NvencContext *ctx = avctx->priv_data;
827 NV_ENC_CONFIG *cc = &ctx->encode_config;
828 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
829 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
831 vui->colourMatrix = avctx->colorspace;
832 vui->colourPrimaries = avctx->color_primaries;
833 vui->transferCharacteristics = avctx->color_trc;
834 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
835 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
837 vui->colourDescriptionPresentFlag =
838 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
840 vui->videoSignalTypePresentFlag =
841 (vui->colourDescriptionPresentFlag
842 || vui->videoFormat != 5
843 || vui->videoFullRangeFlag != 0);
846 hevc->sliceModeData = 1;
848 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
849 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
850 hevc->outputAUD = ctx->aud;
852 if (avctx->refs >= 0) {
853 /* 0 means "let the hardware decide" */
854 hevc->maxNumRefFramesInDPB = avctx->refs;
856 if (avctx->gop_size >= 0) {
857 hevc->idrPeriod = cc->gopLength;
860 if (IS_CBR(cc->rcParams.rateControlMode)) {
861 hevc->outputBufferingPeriodSEI = 1;
862 hevc->outputPictureTimingSEI = 1;
865 switch(ctx->profile) {
866 case NV_ENC_HEVC_PROFILE_MAIN:
867 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
868 avctx->profile = FF_PROFILE_HEVC_MAIN;
870 case NV_ENC_HEVC_PROFILE_MAIN_10:
871 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
872 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
874 case NV_ENC_HEVC_PROFILE_REXT:
875 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
876 avctx->profile = FF_PROFILE_HEVC_REXT;
880 // force setting profile as main10 if input is 10 bit
881 if (IS_10BIT(ctx->data_pix_fmt)) {
882 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
883 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
886 // force setting profile as rext if input is yuv444
887 if (IS_YUV444(ctx->data_pix_fmt)) {
888 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
889 avctx->profile = FF_PROFILE_HEVC_REXT;
892 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
894 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
896 hevc->level = ctx->level;
898 hevc->tier = ctx->tier;
903 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
905 switch (avctx->codec->id) {
906 case AV_CODEC_ID_H264:
907 return nvenc_setup_h264_config(avctx);
908 case AV_CODEC_ID_HEVC:
909 return nvenc_setup_hevc_config(avctx);
910 /* Earlier switch/case will return if unknown codec is passed. */
916 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
918 NvencContext *ctx = avctx->priv_data;
919 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
920 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
922 NV_ENC_PRESET_CONFIG preset_config = { 0 };
923 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
924 AVCPBProperties *cpb_props;
928 ctx->encode_config.version = NV_ENC_CONFIG_VER;
929 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
931 ctx->init_encode_params.encodeHeight = avctx->height;
932 ctx->init_encode_params.encodeWidth = avctx->width;
934 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
936 nvenc_map_preset(ctx);
938 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
939 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
941 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
942 ctx->init_encode_params.encodeGUID,
943 ctx->init_encode_params.presetGUID,
945 if (nv_status != NV_ENC_SUCCESS)
946 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
948 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
950 ctx->encode_config.version = NV_ENC_CONFIG_VER;
954 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
955 dw*= avctx->sample_aspect_ratio.num;
956 dh*= avctx->sample_aspect_ratio.den;
958 av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
959 ctx->init_encode_params.darHeight = dh;
960 ctx->init_encode_params.darWidth = dw;
962 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
963 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
965 ctx->init_encode_params.enableEncodeAsync = 0;
966 ctx->init_encode_params.enablePTD = 1;
968 if (ctx->bluray_compat) {
970 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
971 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
972 switch (avctx->codec->id) {
973 case AV_CODEC_ID_H264:
974 /* maximum level depends on used resolution */
976 case AV_CODEC_ID_HEVC:
977 ctx->level = NV_ENC_LEVEL_HEVC_51;
978 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
983 if (avctx->gop_size > 0) {
984 if (avctx->max_b_frames >= 0) {
985 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
986 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
989 ctx->encode_config.gopLength = avctx->gop_size;
990 } else if (avctx->gop_size == 0) {
991 ctx->encode_config.frameIntervalP = 0;
992 ctx->encode_config.gopLength = 1;
995 ctx->initial_pts[0] = AV_NOPTS_VALUE;
996 ctx->initial_pts[1] = AV_NOPTS_VALUE;
998 nvenc_recalc_surfaces(avctx);
1000 nvenc_setup_rate_control(avctx);
1002 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1003 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1005 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1008 res = nvenc_setup_codec_config(avctx);
1012 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1013 if (nv_status != NV_ENC_SUCCESS) {
1014 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1017 if (ctx->encode_config.frameIntervalP > 1)
1018 avctx->has_b_frames = 2;
1020 if (ctx->encode_config.rcParams.averageBitRate > 0)
1021 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1023 cpb_props = ff_add_cpb_side_data(avctx);
1025 return AVERROR(ENOMEM);
1026 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1027 cpb_props->avg_bitrate = avctx->bit_rate;
1028 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1033 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1036 case AV_PIX_FMT_YUV420P:
1037 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1038 case AV_PIX_FMT_NV12:
1039 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1040 case AV_PIX_FMT_P010:
1041 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1042 case AV_PIX_FMT_YUV444P:
1043 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1044 case AV_PIX_FMT_YUV444P16:
1045 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1046 case AV_PIX_FMT_0RGB32:
1047 return NV_ENC_BUFFER_FORMAT_ARGB;
1048 case AV_PIX_FMT_0BGR32:
1049 return NV_ENC_BUFFER_FORMAT_ABGR;
1051 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1055 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1057 NvencContext *ctx = avctx->priv_data;
1058 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1059 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1061 NVENCSTATUS nv_status;
1062 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1063 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1065 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1066 ctx->surfaces[idx].in_ref = av_frame_alloc();
1067 if (!ctx->surfaces[idx].in_ref)
1068 return AVERROR(ENOMEM);
1070 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1072 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1073 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1074 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1075 av_get_pix_fmt_name(ctx->data_pix_fmt));
1076 return AVERROR(EINVAL);
1079 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1080 allocSurf.width = (avctx->width + 31) & ~31;
1081 allocSurf.height = (avctx->height + 31) & ~31;
1082 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1083 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1085 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1086 if (nv_status != NV_ENC_SUCCESS) {
1087 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1090 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1091 ctx->surfaces[idx].width = allocSurf.width;
1092 ctx->surfaces[idx].height = allocSurf.height;
1095 ctx->surfaces[idx].lockCount = 0;
1097 /* 1MB is large enough to hold most output frames.
1098 * NVENC increases this automaticaly if it is not enough. */
1099 allocOut.size = 1024 * 1024;
1101 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1103 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1104 if (nv_status != NV_ENC_SUCCESS) {
1105 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1106 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1107 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1108 av_frame_free(&ctx->surfaces[idx].in_ref);
1112 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1113 ctx->surfaces[idx].size = allocOut.size;
1118 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1120 NvencContext *ctx = avctx->priv_data;
1123 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1125 return AVERROR(ENOMEM);
1127 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1128 if (!ctx->timestamp_list)
1129 return AVERROR(ENOMEM);
1130 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1131 if (!ctx->output_surface_queue)
1132 return AVERROR(ENOMEM);
1133 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1134 if (!ctx->output_surface_ready_queue)
1135 return AVERROR(ENOMEM);
1137 for (i = 0; i < ctx->nb_surfaces; i++) {
1138 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1145 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1147 NvencContext *ctx = avctx->priv_data;
1148 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1149 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1151 NVENCSTATUS nv_status;
1152 uint32_t outSize = 0;
1153 char tmpHeader[256];
1154 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1155 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1157 payload.spsppsBuffer = tmpHeader;
1158 payload.inBufferSize = sizeof(tmpHeader);
1159 payload.outSPSPPSPayloadSize = &outSize;
1161 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1162 if (nv_status != NV_ENC_SUCCESS) {
1163 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1166 avctx->extradata_size = outSize;
1167 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1169 if (!avctx->extradata) {
1170 return AVERROR(ENOMEM);
1173 memcpy(avctx->extradata, tmpHeader, outSize);
1178 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1180 NvencContext *ctx = avctx->priv_data;
1181 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1182 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1185 /* the encoder has to be flushed before it can be closed */
1186 if (ctx->nvencoder) {
1187 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1188 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1190 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1193 av_fifo_freep(&ctx->timestamp_list);
1194 av_fifo_freep(&ctx->output_surface_ready_queue);
1195 av_fifo_freep(&ctx->output_surface_queue);
1197 if (ctx->surfaces && avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1198 for (i = 0; i < ctx->nb_surfaces; ++i) {
1199 if (ctx->surfaces[i].input_surface) {
1200 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1203 for (i = 0; i < ctx->nb_registered_frames; i++) {
1204 if (ctx->registered_frames[i].regptr)
1205 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1207 ctx->nb_registered_frames = 0;
1210 if (ctx->surfaces) {
1211 for (i = 0; i < ctx->nb_surfaces; ++i) {
1212 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1213 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1214 av_frame_free(&ctx->surfaces[i].in_ref);
1215 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1218 av_freep(&ctx->surfaces);
1219 ctx->nb_surfaces = 0;
1222 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1223 ctx->nvencoder = NULL;
1225 if (ctx->cu_context_internal)
1226 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
1227 ctx->cu_context = ctx->cu_context_internal = NULL;
1229 nvenc_free_functions(&dl_fn->nvenc_dl);
1230 cuda_free_functions(&dl_fn->cuda_dl);
1232 dl_fn->nvenc_device_count = 0;
1234 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1239 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1241 NvencContext *ctx = avctx->priv_data;
1244 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1245 AVHWFramesContext *frames_ctx;
1246 if (!avctx->hw_frames_ctx) {
1247 av_log(avctx, AV_LOG_ERROR,
1248 "hw_frames_ctx must be set when using GPU frames as input\n");
1249 return AVERROR(EINVAL);
1251 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1252 ctx->data_pix_fmt = frames_ctx->sw_format;
1254 ctx->data_pix_fmt = avctx->pix_fmt;
1257 if ((ret = nvenc_load_libraries(avctx)) < 0)
1260 if ((ret = nvenc_setup_device(avctx)) < 0)
1263 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1266 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1269 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1270 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1277 static NvencSurface *get_free_frame(NvencContext *ctx)
1281 for (i = 0; i < ctx->nb_surfaces; ++i) {
1282 if (!ctx->surfaces[i].lockCount) {
1283 ctx->surfaces[i].lockCount = 1;
1284 return &ctx->surfaces[i];
1291 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1292 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1294 int dst_linesize[4] = {
1295 lock_buffer_params->pitch,
1296 lock_buffer_params->pitch,
1297 lock_buffer_params->pitch,
1298 lock_buffer_params->pitch
1300 uint8_t *dst_data[4];
1303 if (frame->format == AV_PIX_FMT_YUV420P)
1304 dst_linesize[1] = dst_linesize[2] >>= 1;
1306 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1307 lock_buffer_params->bufferDataPtr, dst_linesize);
1311 if (frame->format == AV_PIX_FMT_YUV420P)
1312 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1314 av_image_copy(dst_data, dst_linesize,
1315 (const uint8_t**)frame->data, frame->linesize, frame->format,
1316 avctx->width, avctx->height);
1321 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1323 NvencContext *ctx = avctx->priv_data;
1324 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1325 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1329 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1330 for (i = 0; i < ctx->nb_registered_frames; i++) {
1331 if (!ctx->registered_frames[i].mapped) {
1332 if (ctx->registered_frames[i].regptr) {
1333 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1334 ctx->registered_frames[i].regptr);
1335 ctx->registered_frames[i].regptr = NULL;
1341 return ctx->nb_registered_frames++;
1344 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1345 return AVERROR(ENOMEM);
1348 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1350 NvencContext *ctx = avctx->priv_data;
1351 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1352 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1354 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1355 NV_ENC_REGISTER_RESOURCE reg;
1358 for (i = 0; i < ctx->nb_registered_frames; i++) {
1359 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1363 idx = nvenc_find_free_reg_resource(avctx);
1367 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1368 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1369 reg.width = frames_ctx->width;
1370 reg.height = frames_ctx->height;
1371 reg.pitch = frame->linesize[0];
1372 reg.resourceToRegister = frame->data[0];
1374 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1375 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1376 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1377 av_get_pix_fmt_name(frames_ctx->sw_format));
1378 return AVERROR(EINVAL);
1381 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1382 if (ret != NV_ENC_SUCCESS) {
1383 nvenc_print_error(avctx, ret, "Error registering an input resource");
1384 return AVERROR_UNKNOWN;
1387 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1388 ctx->registered_frames[idx].regptr = reg.registeredResource;
1392 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1393 NvencSurface *nvenc_frame)
1395 NvencContext *ctx = avctx->priv_data;
1396 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1397 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1400 NVENCSTATUS nv_status;
1402 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1403 int reg_idx = nvenc_register_frame(avctx, frame);
1405 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1409 res = av_frame_ref(nvenc_frame->in_ref, frame);
1413 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1414 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1415 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1416 if (nv_status != NV_ENC_SUCCESS) {
1417 av_frame_unref(nvenc_frame->in_ref);
1418 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1421 ctx->registered_frames[reg_idx].mapped = 1;
1422 nvenc_frame->reg_idx = reg_idx;
1423 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1424 nvenc_frame->pitch = frame->linesize[0];
1427 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1429 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1430 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1432 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1433 if (nv_status != NV_ENC_SUCCESS) {
1434 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1437 nvenc_frame->pitch = lockBufferParams.pitch;
1438 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1440 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1441 if (nv_status != NV_ENC_SUCCESS) {
1442 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1449 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1450 NV_ENC_PIC_PARAMS *params)
1452 NvencContext *ctx = avctx->priv_data;
1454 switch (avctx->codec->id) {
1455 case AV_CODEC_ID_H264:
1456 params->codecPicParams.h264PicParams.sliceMode =
1457 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1458 params->codecPicParams.h264PicParams.sliceModeData =
1459 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1461 case AV_CODEC_ID_HEVC:
1462 params->codecPicParams.hevcPicParams.sliceMode =
1463 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1464 params->codecPicParams.hevcPicParams.sliceModeData =
1465 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1470 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1472 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1475 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1477 int64_t timestamp = AV_NOPTS_VALUE;
1478 if (av_fifo_size(queue) > 0)
1479 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1484 static int nvenc_set_timestamp(AVCodecContext *avctx,
1485 NV_ENC_LOCK_BITSTREAM *params,
1488 NvencContext *ctx = avctx->priv_data;
1490 pkt->pts = params->outputTimeStamp;
1492 /* generate the first dts by linearly extrapolating the
1493 * first two pts values to the past */
1494 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1495 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1496 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1499 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1500 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1501 return AVERROR(ERANGE);
1504 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1505 (delta > 0 && ts0 < INT64_MIN + delta))
1506 return AVERROR(ERANGE);
1507 pkt->dts = ts0 - delta;
1509 ctx->first_packet_output = 1;
1513 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1518 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1520 NvencContext *ctx = avctx->priv_data;
1521 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1522 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1524 uint32_t slice_mode_data;
1525 uint32_t *slice_offsets = NULL;
1526 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1527 NVENCSTATUS nv_status;
1530 enum AVPictureType pict_type;
1532 switch (avctx->codec->id) {
1533 case AV_CODEC_ID_H264:
1534 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1536 case AV_CODEC_ID_H265:
1537 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1540 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1541 res = AVERROR(EINVAL);
1544 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1549 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1551 lock_params.doNotWait = 0;
1552 lock_params.outputBitstream = tmpoutsurf->output_surface;
1553 lock_params.sliceOffsets = slice_offsets;
1555 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1556 if (nv_status != NV_ENC_SUCCESS) {
1557 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1561 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1562 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1566 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1568 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1569 if (nv_status != NV_ENC_SUCCESS)
1570 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1573 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1574 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1575 av_frame_unref(tmpoutsurf->in_ref);
1576 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1578 tmpoutsurf->input_surface = NULL;
1581 switch (lock_params.pictureType) {
1582 case NV_ENC_PIC_TYPE_IDR:
1583 pkt->flags |= AV_PKT_FLAG_KEY;
1584 case NV_ENC_PIC_TYPE_I:
1585 pict_type = AV_PICTURE_TYPE_I;
1587 case NV_ENC_PIC_TYPE_P:
1588 pict_type = AV_PICTURE_TYPE_P;
1590 case NV_ENC_PIC_TYPE_B:
1591 pict_type = AV_PICTURE_TYPE_B;
1593 case NV_ENC_PIC_TYPE_BI:
1594 pict_type = AV_PICTURE_TYPE_BI;
1597 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1598 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1599 res = AVERROR_EXTERNAL;
1603 #if FF_API_CODED_FRAME
1604 FF_DISABLE_DEPRECATION_WARNINGS
1605 avctx->coded_frame->pict_type = pict_type;
1606 FF_ENABLE_DEPRECATION_WARNINGS
1609 ff_side_data_set_encoder_stats(pkt,
1610 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1612 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1616 av_free(slice_offsets);
1621 timestamp_queue_dequeue(ctx->timestamp_list);
1624 av_free(slice_offsets);
1629 static int output_ready(AVCodecContext *avctx, int flush)
1631 NvencContext *ctx = avctx->priv_data;
1632 int nb_ready, nb_pending;
1634 /* when B-frames are enabled, we wait for two initial timestamps to
1635 * calculate the first dts */
1636 if (!flush && avctx->max_b_frames > 0 &&
1637 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1640 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1641 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1643 return nb_ready > 0;
1644 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1647 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1648 const AVFrame *frame, int *got_packet)
1650 NVENCSTATUS nv_status;
1651 NvencSurface *tmpoutsurf, *inSurf;
1654 NvencContext *ctx = avctx->priv_data;
1655 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1656 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1658 NV_ENC_PIC_PARAMS pic_params = { 0 };
1659 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1662 inSurf = get_free_frame(ctx);
1664 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1668 res = nvenc_upload_frame(avctx, frame, inSurf);
1670 inSurf->lockCount = 0;
1674 pic_params.inputBuffer = inSurf->input_surface;
1675 pic_params.bufferFmt = inSurf->format;
1676 pic_params.inputWidth = avctx->width;
1677 pic_params.inputHeight = avctx->height;
1678 pic_params.inputPitch = inSurf->pitch;
1679 pic_params.outputBitstream = inSurf->output_surface;
1681 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1682 if (frame->top_field_first)
1683 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1685 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1687 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1690 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
1691 pic_params.encodePicFlags =
1692 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
1694 pic_params.encodePicFlags = 0;
1697 pic_params.inputTimeStamp = frame->pts;
1699 nvenc_codec_specific_pic_params(avctx, &pic_params);
1701 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1704 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1705 if (nv_status != NV_ENC_SUCCESS &&
1706 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1707 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1710 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1711 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1713 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1714 ctx->initial_pts[0] = frame->pts;
1715 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1716 ctx->initial_pts[1] = frame->pts;
1719 /* all the pending buffers are now ready for output */
1720 if (nv_status == NV_ENC_SUCCESS) {
1721 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1722 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1723 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1727 if (output_ready(avctx, !frame)) {
1728 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1730 res = process_output_surface(avctx, pkt, tmpoutsurf);
1735 av_assert0(tmpoutsurf->lockCount);
1736 tmpoutsurf->lockCount--;