23 #include "config_components.h"
27 #if CONFIG_AV1_NVENC_ENCODER
46 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
48 #define NVENC_CAP 0x30
50 #ifndef NVENC_NO_DEPRECATED_RC
51 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
52 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
53 rc == NV_ENC_PARAMS_RC_CBR_HQ)
55 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR)
64 #ifdef NVENC_HAVE_422_SUPPORT
95 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
96 pix_fmt == AV_PIX_FMT_P016 || \
97 pix_fmt == AV_PIX_FMT_P210 || \
98 pix_fmt == AV_PIX_FMT_P216 || \
99 pix_fmt == AV_PIX_FMT_YUV444P16 || \
100 pix_fmt == AV_PIX_FMT_X2RGB10 || \
101 pix_fmt == AV_PIX_FMT_X2BGR10 || \
102 pix_fmt == AV_PIX_FMT_GBRP16)
104 #define IS_RGB(pix_fmt) (pix_fmt == AV_PIX_FMT_0RGB32 || \
105 pix_fmt == AV_PIX_FMT_RGB32 || \
106 pix_fmt == AV_PIX_FMT_0BGR32 || \
107 pix_fmt == AV_PIX_FMT_BGR32 || \
108 pix_fmt == AV_PIX_FMT_X2RGB10 || \
109 pix_fmt == AV_PIX_FMT_X2BGR10)
111 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
112 pix_fmt == AV_PIX_FMT_YUV444P16 || \
113 pix_fmt == AV_PIX_FMT_GBRP || \
114 pix_fmt == AV_PIX_FMT_GBRP16 || \
115 (ctx->rgb_mode == NVENC_RGB_MODE_444 && IS_RGB(pix_fmt)))
117 #define IS_YUV422(pix_fmt) (pix_fmt == AV_PIX_FMT_NV16 || \
118 pix_fmt == AV_PIX_FMT_P210 || \
119 pix_fmt == AV_PIX_FMT_P216)
121 #define IS_GBRP(pix_fmt) (pix_fmt == AV_PIX_FMT_GBRP || \
122 pix_fmt == AV_PIX_FMT_GBRP16)
124 static const struct {
129 { NV_ENC_SUCCESS, 0,
"success" },
130 { NV_ENC_ERR_NO_ENCODE_DEVICE,
AVERROR(ENOENT),
"no encode device" },
131 { NV_ENC_ERR_UNSUPPORTED_DEVICE,
AVERROR(ENOSYS),
"unsupported device" },
132 { NV_ENC_ERR_INVALID_ENCODERDEVICE,
AVERROR(EINVAL),
"invalid encoder device" },
133 { NV_ENC_ERR_INVALID_DEVICE,
AVERROR(EINVAL),
"invalid device" },
134 { NV_ENC_ERR_DEVICE_NOT_EXIST,
AVERROR(EIO),
"device does not exist" },
135 { NV_ENC_ERR_INVALID_PTR,
AVERROR(EFAULT),
"invalid ptr" },
136 { NV_ENC_ERR_INVALID_EVENT,
AVERROR(EINVAL),
"invalid event" },
137 { NV_ENC_ERR_INVALID_PARAM,
AVERROR(EINVAL),
"invalid param" },
138 { NV_ENC_ERR_INVALID_CALL,
AVERROR(EINVAL),
"invalid call" },
139 { NV_ENC_ERR_OUT_OF_MEMORY,
AVERROR(ENOMEM),
"out of memory" },
140 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,
AVERROR(EINVAL),
"encoder not initialized" },
141 { NV_ENC_ERR_UNSUPPORTED_PARAM,
AVERROR(ENOSYS),
"unsupported param" },
142 { NV_ENC_ERR_LOCK_BUSY,
AVERROR(EAGAIN),
"lock busy" },
144 { NV_ENC_ERR_INVALID_VERSION,
AVERROR(EINVAL),
"invalid version" },
145 { NV_ENC_ERR_MAP_FAILED,
AVERROR(EIO),
"map failed" },
146 { NV_ENC_ERR_NEED_MORE_INPUT,
AVERROR(EAGAIN),
"need more input" },
147 { NV_ENC_ERR_ENCODER_BUSY,
AVERROR(EAGAIN),
"encoder busy" },
148 { NV_ENC_ERR_EVENT_NOT_REGISTERD,
AVERROR(EBADF),
"event not registered" },
150 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,
AVERROR(EINVAL),
"incompatible client key" },
151 { NV_ENC_ERR_UNIMPLEMENTED,
AVERROR(ENOSYS),
"unimplemented" },
152 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED,
AVERROR(EIO),
"resource register failed" },
153 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,
AVERROR(EBADF),
"resource not registered" },
154 { NV_ENC_ERR_RESOURCE_NOT_MAPPED,
AVERROR(EBADF),
"resource not mapped" },
168 *
desc =
"unknown error";
173 const char *error_string)
176 const char *details =
"(no details)";
179 #ifdef NVENC_HAVE_GETLASTERRORSTRING
181 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
183 if (p_nvenc &&
ctx->nvencoder)
184 details = p_nvenc->nvEncGetLastErrorString(
ctx->nvencoder);
197 #define PRESET_ALIAS(alias, name, ...) \
198 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
200 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
205 #ifdef NVENC_HAVE_NEW_PRESETS
244 ctx->init_encode_params.presetGUID = t->
guid;
247 #ifdef NVENC_HAVE_NEW_PRESETS
248 if (
ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
258 #if NVENCAPI_CHECK_VERSION(13, 1)
259 const char *minver =
"(unknown)";
260 #elif NVENCAPI_CHECK_VERSION(13, 0)
261 const char *minver =
"570.0";
262 #elif NVENCAPI_CHECK_VERSION(12, 2)
263 # if defined(_WIN32) || defined(__CYGWIN__)
264 const char *minver =
"551.76";
266 const char *minver =
"550.54.14";
268 #elif NVENCAPI_CHECK_VERSION(12, 1)
269 # if defined(_WIN32) || defined(__CYGWIN__)
270 const char *minver =
"531.61";
272 const char *minver =
"530.41.03";
274 #elif NVENCAPI_CHECK_VERSION(12, 0)
275 # if defined(_WIN32) || defined(__CYGWIN__)
276 const char *minver =
"522.25";
278 const char *minver =
"520.56.06";
280 #elif NVENCAPI_CHECK_VERSION(11, 1)
281 # if defined(_WIN32) || defined(__CYGWIN__)
282 const char *minver =
"471.41";
284 const char *minver =
"470.57.02";
286 #elif NVENCAPI_CHECK_VERSION(11, 0)
287 # if defined(_WIN32) || defined(__CYGWIN__)
288 const char *minver =
"456.71";
290 const char *minver =
"455.28";
292 #elif NVENCAPI_CHECK_VERSION(10, 0)
293 # if defined(_WIN32) || defined(__CYGWIN__)
294 const char *minver =
"450.51";
296 const char *minver =
"445.87";
298 #elif NVENCAPI_CHECK_VERSION(9, 1)
299 # if defined(_WIN32) || defined(__CYGWIN__)
300 const char *minver =
"436.15";
302 const char *minver =
"435.21";
304 #elif NVENCAPI_CHECK_VERSION(9, 0)
305 # if defined(_WIN32) || defined(__CYGWIN__)
306 const char *minver =
"418.81";
308 const char *minver =
"418.30";
310 #elif NVENCAPI_CHECK_VERSION(8, 2)
311 # if defined(_WIN32) || defined(__CYGWIN__)
312 const char *minver =
"397.93";
314 const char *minver =
"396.24";
316 #elif NVENCAPI_CHECK_VERSION(8, 1)
317 # if defined(_WIN32) || defined(__CYGWIN__)
318 const char *minver =
"390.77";
320 const char *minver =
"390.25";
323 # if defined(_WIN32) || defined(__CYGWIN__)
324 const char *minver =
"378.66";
326 const char *minver =
"378.13";
329 av_log(avctx,
level,
"The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
337 uint32_t nvenc_max_ver;
340 ret = cuda_load_functions(&dl_fn->
cuda_dl, avctx);
344 ret = nvenc_load_functions(&dl_fn->
nvenc_dl, avctx);
350 err = dl_fn->
nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
351 if (err != NV_ENC_SUCCESS)
356 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
357 av_log(avctx,
AV_LOG_ERROR,
"Driver does not support the required nvenc API version. "
358 "Required: %d.%d Found: %d.%d\n",
359 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
360 nvenc_max_ver >> 4, nvenc_max_ver & 0
xf);
365 dl_fn->
nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
368 if (err != NV_ENC_SUCCESS)
381 if (
ctx->d3d11_device)
393 if (
ctx->d3d11_device)
401 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
403 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
406 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
407 params.apiVersion = NVENCAPI_VERSION;
408 if (
ctx->d3d11_device) {
409 params.device =
ctx->d3d11_device;
410 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
412 params.device =
ctx->cu_context;
413 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
416 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &
ctx->nvencoder);
417 if (
ret != NV_ENC_SUCCESS) {
428 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
429 int i,
ret, count = 0;
432 ret = p_nvenc->nvEncGetEncodeGUIDCount(
ctx->nvencoder, &count);
434 if (
ret != NV_ENC_SUCCESS || !count)
441 ret = p_nvenc->nvEncGetEncodeGUIDs(
ctx->nvencoder, guids, count, &count);
442 if (
ret != NV_ENC_SUCCESS) {
448 for (
i = 0;
i < count;
i++) {
449 if (!memcmp(&guids[
i], &
ctx->init_encode_params.encodeGUID,
sizeof(*guids))) {
464 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
465 NV_ENC_CAPS_PARAM params = { 0 };
468 params.version = NV_ENC_CAPS_PARAM_VER;
469 params.capsToQuery = cap;
471 ret = p_nvenc->nvEncGetEncodeCaps(
ctx->nvencoder,
ctx->init_encode_params.encodeGUID, ¶ms, &
val);
473 if (
ret == NV_ENC_SUCCESS)
495 #ifdef NVENC_HAVE_422_SUPPORT
512 if (ret < avctx->
width) {
519 if (ret < avctx->
height) {
526 if (ret < avctx->max_b_frames) {
536 "Interlaced encoding is not supported. Supported level: %d\n",
548 if (
ctx->rc_lookahead > 0 &&
ret <= 0) {
554 if (
ctx->temporal_aq > 0 &&
ret <= 0) {
560 if (
ctx->weighted_pred > 0 &&
ret <= 0) {
566 if (
ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC &&
ret <= 0) {
571 #ifdef NVENC_HAVE_BFRAME_REF_MODE
572 tmp = (
ctx->b_ref_mode >= 0) ?
ctx->b_ref_mode : NV_ENC_BFRAME_REF_MODE_DISABLED;
574 if (
tmp == NV_ENC_BFRAME_REF_MODE_EACH &&
ret != 1 &&
ret != 3) {
577 }
else if (
tmp != NV_ENC_BFRAME_REF_MODE_DISABLED &&
ret == 0) {
582 tmp = (
ctx->b_ref_mode >= 0) ?
ctx->b_ref_mode : 0;
589 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
591 if(avctx->
refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT &&
ret <= 0) {
596 if(avctx->
refs != 0) {
602 #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
604 if(
ctx->single_slice_intra_refresh &&
ret <= 0) {
609 if(
ctx->single_slice_intra_refresh) {
616 if((
ctx->intra_refresh ||
ctx->single_slice_intra_refresh) &&
ret <= 0) {
621 #ifndef NVENC_HAVE_HEVC_CONSTRAINED_ENCODING
629 if(
ctx->constrained_encoding &&
ret <= 0) {
634 #if defined(NVENC_HAVE_TEMPORAL_FILTER) || defined(NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER)
636 if(
ctx->tf_level > 0 &&
ret <= 0) {
642 #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
644 if(
ctx->rc_lookahead > 0 &&
ctx->lookahead_level > 0 &&
645 ctx->lookahead_level != NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT &&
646 ctx->lookahead_level >
ret)
653 #ifdef NVENC_HAVE_UNIDIR_B
655 if(
ctx->unidir_b &&
ret <= 0) {
661 ctx->support_dyn_bitrate =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
670 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
671 char name[128] = { 0};
672 int major, minor,
ret;
691 av_log(avctx, loglevel,
"[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx,
name, major, minor);
692 if (((major << 4) | minor) <
NVENC_CAP) {
693 av_log(avctx, loglevel,
"does not support NVENC\n");
704 ctx->cu_context =
ctx->cu_context_internal;
716 av_log(avctx, loglevel,
"supports NVENC\n");
727 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
735 ctx->cu_context_internal =
NULL;
748 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
751 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
753 #if CONFIG_AV1_NVENC_ENCODER
755 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_AV1_GUID;
765 av_log(avctx,
AV_LOG_WARNING,
"The selected preset is deprecated. Use p1 to p7 + -tune or fast/medium/slow.\n");
789 cuda_device_hwctx = hwdev_ctx->
hwctx;
792 d3d11_device_hwctx = hwdev_ctx->
hwctx;
800 if (cuda_device_hwctx) {
802 ctx->cu_stream = cuda_device_hwctx->
stream;
805 else if (d3d11_device_hwctx) {
806 ctx->d3d11_device = d3d11_device_hwctx->
device;
807 ID3D11Device_AddRef(
ctx->d3d11_device);
817 av_log(avctx,
AV_LOG_FATAL,
"Provided device doesn't support required NVENC features\n");
821 int i, nb_devices = 0;
837 for (
i = 0;
i < nb_devices; ++
i) {
850 av_log(avctx,
AV_LOG_FATAL,
"Requested GPU %d, but only %d GPUs are available!\n",
ctx->device, nb_devices);
860 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
861 #if CONFIG_AV1_NVENC_ENCODER
867 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
869 if (
ctx->init_qp_p >= 0) {
870 rc->constQP.qpInterP =
ctx->init_qp_p;
871 if (
ctx->init_qp_i >= 0 &&
ctx->init_qp_b >= 0) {
872 rc->constQP.qpIntra =
ctx->init_qp_i;
873 rc->constQP.qpInterB =
ctx->init_qp_b;
877 rc->constQP.qpInterB =
av_clip(
880 rc->constQP.qpIntra = rc->constQP.qpInterP;
881 rc->constQP.qpInterB = rc->constQP.qpInterP;
883 }
else if (
ctx->cqp >= 0) {
884 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra =
ctx->cqp;
898 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
900 #if CONFIG_AV1_NVENC_ENCODER
906 if (avctx->
qmin >= 0 || avctx->
qmax >= 0)
907 av_log(avctx,
AV_LOG_WARNING,
"Passing qmin/qmax via global AVCodecContext options. Use encoder options instead.\n");
909 if (avctx->
qmin >= 0 &&
ctx->qmin < 0)
911 if (avctx->
qmax >= 0 &&
ctx->qmax < 0)
916 if (
ctx->qmin >= 0 &&
ctx->qmax >= 0) {
920 rc->minQP.qpInterB =
ctx->qmin;
921 rc->minQP.qpInterP =
ctx->qmin;
922 rc->minQP.qpIntra =
ctx->qmin;
924 rc->maxQP.qpInterB =
ctx->qmax;
925 rc->maxQP.qpInterP =
ctx->qmax;
926 rc->maxQP.qpIntra =
ctx->qmax;
928 qp_inter_p = (
ctx->qmax + 3 *
ctx->qmin) / 4;
929 }
else if (
ctx->qmin >= 0) {
932 rc->minQP.qpInterB =
ctx->qmin;
933 rc->minQP.qpInterP =
ctx->qmin;
934 rc->minQP.qpIntra =
ctx->qmin;
936 qp_inter_p =
ctx->qmin;
941 rc->enableInitialRCQP = 1;
943 if (
ctx->init_qp_p < 0) {
944 rc->initialRCQP.qpInterP = qp_inter_p;
946 rc->initialRCQP.qpInterP =
ctx->init_qp_p;
949 if (
ctx->init_qp_i < 0) {
951 rc->initialRCQP.qpIntra =
av_clip(
954 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
957 rc->initialRCQP.qpIntra =
ctx->init_qp_i;
960 if (
ctx->init_qp_b < 0) {
962 rc->initialRCQP.qpInterB =
av_clip(
965 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
968 rc->initialRCQP.qpInterB =
ctx->init_qp_b;
975 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
977 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
978 rc->constQP.qpInterB = 0;
979 rc->constQP.qpInterP = 0;
980 rc->constQP.qpIntra = 0;
989 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
992 case NV_ENC_PARAMS_RC_CONSTQP:
995 #ifndef NVENC_NO_DEPRECATED_RC
996 case NV_ENC_PARAMS_RC_VBR_MINQP:
997 if (avctx->
qmin < 0 &&
ctx->qmin < 0) {
999 "The variable bitrate rate-control requires "
1000 "the 'qmin' option set.\n");
1005 case NV_ENC_PARAMS_RC_VBR_HQ:
1007 case NV_ENC_PARAMS_RC_VBR:
1010 case NV_ENC_PARAMS_RC_CBR:
1011 #ifndef NVENC_NO_DEPRECATED_RC
1012 case NV_ENC_PARAMS_RC_CBR_HQ:
1013 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
1018 rc->rateControlMode =
ctx->rc;
1027 int nb_surfaces =
FFMAX(4,
ctx->encode_config.frameIntervalP * 2 * 2);
1030 if (
ctx->rc_lookahead > 0) {
1033 nb_surfaces =
FFMAX(1,
FFMAX(nb_surfaces,
ctx->rc_lookahead +
ctx->encode_config.frameIntervalP + 1 + 4));
1034 if (nb_surfaces >
ctx->nb_surfaces &&
ctx->nb_surfaces > 0)
1037 "Defined rc_lookahead requires more surfaces, "
1038 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
1040 ctx->nb_surfaces =
FFMAX(nb_surfaces,
ctx->nb_surfaces);
1042 if (
ctx->encode_config.frameIntervalP > 1 &&
ctx->nb_surfaces < nb_surfaces &&
ctx->nb_surfaces > 0)
1045 "Defined b-frame requires more surfaces, "
1046 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
1047 ctx->nb_surfaces =
FFMAX(
ctx->nb_surfaces, nb_surfaces);
1049 else if (
ctx->nb_surfaces <= 0)
1050 ctx->nb_surfaces = nb_surfaces;
1055 ctx->async_depth =
FFMIN(
ctx->async_depth,
ctx->nb_surfaces - 1);
1059 ctx->frame_data_array_nb =
FFMAX(
ctx->nb_surfaces,
ctx->nb_surfaces +
ctx->encode_config.frameIntervalP - 1);
1069 av_log(avctx,
AV_LOG_WARNING,
"Using global_quality with nvenc is deprecated. Use qp instead.\n");
1075 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate;
1076 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1077 ctx->encode_config.rcParams.maxBitRate =
ctx->encode_config.rcParams.averageBitRate;
1083 #ifdef NVENC_HAVE_MULTIPASS
1084 ctx->encode_config.rcParams.multiPass =
ctx->multipass;
1087 ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
1089 ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
1093 ctx->rc = NV_ENC_PARAMS_RC_CBR;
1094 }
else if (
ctx->cqp >= 0) {
1095 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
1096 }
else if (
ctx->quality >= 0.0f) {
1097 ctx->rc = NV_ENC_PARAMS_RC_VBR;
1107 if (
ctx->twopass < 0)
1112 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
1114 ctx->rc = NV_ENC_PARAMS_RC_CBR;
1116 }
else if (
ctx->cqp >= 0) {
1117 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
1118 }
else if (
ctx->twopass) {
1119 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
1120 }
else if ((avctx->
qmin >= 0 && avctx->
qmax >= 0) ||
1121 (
ctx->qmin >= 0 &&
ctx->qmax >= 0)) {
1122 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
1134 #ifdef NVENC_HAVE_QP_CHROMA_OFFSETS
1135 ctx->encode_config.rcParams.cbQPIndexOffset =
ctx->qp_cb_offset;
1136 ctx->encode_config.rcParams.crQPIndexOffset =
ctx->qp_cr_offset;
1138 if (
ctx->qp_cb_offset ||
ctx->qp_cr_offset)
1139 av_log(avctx,
AV_LOG_WARNING,
"Failed setting QP CB/CR offsets, SDK 11.1 or greater required at compile time.\n");
1142 #ifdef NVENC_HAVE_LDKFS
1144 ctx->encode_config.rcParams.lowDelayKeyFrameScale =
ctx->ldkfs;
1149 }
else if (
ctx->rc >= 0) {
1152 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
1158 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1159 avctx->
rc_buffer_size =
ctx->encode_config.rcParams.vbvBufferSize = 2 *
ctx->encode_config.rcParams.averageBitRate;
1163 ctx->encode_config.rcParams.enableAQ = 1;
1164 ctx->encode_config.rcParams.aqStrength =
ctx->aq_strength;
1168 if (
ctx->temporal_aq) {
1169 ctx->encode_config.rcParams.enableTemporalAQ = 1;
1173 if (
ctx->rc_lookahead > 0) {
1174 int lkd_bound =
FFMIN(
ctx->nb_surfaces,
ctx->async_depth) -
1175 ctx->encode_config.frameIntervalP - 4;
1177 if (lkd_bound < 0) {
1178 ctx->encode_config.rcParams.enableLookahead = 0;
1180 "Lookahead not enabled. Increase buffer delay (-delay).\n");
1182 ctx->encode_config.rcParams.enableLookahead = 1;
1183 ctx->encode_config.rcParams.lookaheadDepth =
av_clip(
ctx->rc_lookahead, 0, lkd_bound);
1184 ctx->encode_config.rcParams.disableIadapt =
ctx->no_scenecut;
1185 ctx->encode_config.rcParams.disableBadapt = !
ctx->b_adapt;
1187 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
1188 ctx->encode_config.rcParams.lookaheadDepth,
1189 ctx->encode_config.rcParams.disableIadapt ?
"disabled" :
"enabled",
1190 ctx->encode_config.rcParams.disableBadapt ?
"disabled" :
"enabled");
1191 if (
ctx->encode_config.rcParams.lookaheadDepth <
ctx->rc_lookahead)
1192 av_log(avctx,
AV_LOG_WARNING,
"Clipping lookahead depth to %d (from %d) due to lack of surfaces/delay",
1193 ctx->encode_config.rcParams.lookaheadDepth,
ctx->rc_lookahead);
1195 #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
1196 if (
ctx->lookahead_level >= 0) {
1197 switch (
ctx->lookahead_level) {
1198 case NV_ENC_LOOKAHEAD_LEVEL_0:
1199 case NV_ENC_LOOKAHEAD_LEVEL_1:
1200 case NV_ENC_LOOKAHEAD_LEVEL_2:
1201 case NV_ENC_LOOKAHEAD_LEVEL_3:
1202 case NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT:
1209 ctx->encode_config.rcParams.lookaheadLevel =
ctx->lookahead_level;
1215 if (
ctx->strict_gop) {
1216 ctx->encode_config.rcParams.strictGOPTarget = 1;
1221 ctx->encode_config.rcParams.enableNonRefP = 1;
1223 if (
ctx->zerolatency)
1224 ctx->encode_config.rcParams.zeroReorderDelay = 1;
1228 int tmp_quality = (int)(
ctx->quality * 256.0f);
1229 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1230 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1235 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate = 0;
1246 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1247 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1248 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1255 vui->transferCharacteristics = avctx->
color_trc;
1256 vui->videoFullRangeFlag = 0;
1260 vui->transferCharacteristics = avctx->
color_trc;
1265 vui->colourDescriptionPresentFlag =
1266 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1268 vui->videoSignalTypePresentFlag =
1269 (vui->colourDescriptionPresentFlag
1270 || vui->videoFormat != 5
1271 || vui->videoFullRangeFlag != 0);
1273 if (
ctx->max_slice_size > 0) {
1274 h264->sliceMode = 1;
1275 h264->sliceModeData =
ctx->max_slice_size;
1277 h264->sliceMode = 3;
1278 h264->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1281 if (
ctx->intra_refresh) {
1282 h264->enableIntraRefresh = 1;
1283 h264->intraRefreshPeriod = cc->gopLength;
1284 h264->intraRefreshCnt = cc->gopLength - 1;
1285 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1286 h264->outputRecoveryPointSEI = 1;
1287 #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
1288 h264->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1292 if (
ctx->constrained_encoding)
1293 h264->enableConstrainedEncoding = 1;
1297 h264->outputAUD =
ctx->aud;
1299 if (
ctx->dpb_size >= 0) {
1301 h264->maxNumRefFrames =
ctx->dpb_size;
1304 h264->idrPeriod = cc->gopLength;
1306 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1308 h264->outputBufferingPeriodSEI =
ctx->cbr_padding;
1310 #ifdef NVENC_HAVE_FILLER_DATA
1311 h264->enableFillerDataInsertion =
ctx->cbr_padding;
1315 h264->outputPictureTimingSEI = 1;
1317 #ifndef NVENC_NO_DEPRECATED_RC
1318 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1319 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1320 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1321 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1322 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1327 h264->qpPrimeYZeroTransformBypassFlag = 1;
1329 switch(
ctx->profile) {
1331 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1335 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1339 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1342 #ifdef NVENC_HAVE_H264_10BIT_SUPPORT
1343 case NV_ENC_H264_PROFILE_HIGH_10:
1344 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
1348 #ifdef NVENC_HAVE_422_SUPPORT
1349 case NV_ENC_H264_PROFILE_HIGH_422:
1350 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
1355 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1361 #ifdef NVENC_HAVE_H264_10BIT_SUPPORT
1364 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
1371 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1375 #ifdef NVENC_HAVE_422_SUPPORT
1378 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
1387 h264->level =
ctx->level;
1389 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1390 h264->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1391 h264->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1394 if (
ctx->coder >= 0)
1395 h264->entropyCodingMode =
ctx->coder;
1397 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1398 if (
ctx->b_ref_mode >= 0)
1399 h264->useBFramesAsRef =
ctx->b_ref_mode;
1402 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1403 h264->numRefL0 = avctx->
refs;
1404 h264->numRefL1 = avctx->
refs;
1407 #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
1408 if (
ctx->tf_level >= 0) {
1409 h264->tfLevel =
ctx->tf_level;
1411 switch (
ctx->tf_level)
1413 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1414 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1421 if (
ctx->encode_config.frameIntervalP < 5)
1426 #ifdef NVENC_HAVE_TIME_CODE
1428 h264->enableTimeCode = 1;
1437 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1438 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1439 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1446 vui->transferCharacteristics = avctx->
color_trc;
1447 vui->videoFullRangeFlag = 0;
1451 vui->transferCharacteristics = avctx->
color_trc;
1456 vui->colourDescriptionPresentFlag =
1457 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1459 vui->videoSignalTypePresentFlag =
1460 (vui->colourDescriptionPresentFlag
1461 || vui->videoFormat != 5
1462 || vui->videoFullRangeFlag != 0);
1464 if (
ctx->max_slice_size > 0) {
1465 hevc->sliceMode = 1;
1466 hevc->sliceModeData =
ctx->max_slice_size;
1468 hevc->sliceMode = 3;
1469 hevc->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1472 if (
ctx->intra_refresh) {
1473 hevc->enableIntraRefresh = 1;
1474 hevc->intraRefreshPeriod = cc->gopLength;
1475 hevc->intraRefreshCnt = cc->gopLength - 1;
1476 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1477 #ifdef NVENC_HAVE_HEVC_OUTPUT_RECOVERY_POINT_SEI
1478 hevc->outputRecoveryPointSEI = 1;
1480 #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
1481 hevc->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1485 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
1494 #ifdef NVENC_HAVE_HEVC_CONSTRAINED_ENCODING
1495 if (
ctx->constrained_encoding)
1496 hevc->enableConstrainedEncoding = 1;
1501 hevc->outputAUD =
ctx->aud;
1503 if (
ctx->dpb_size >= 0) {
1505 hevc->maxNumRefFramesInDPB =
ctx->dpb_size;
1508 hevc->idrPeriod = cc->gopLength;
1510 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1512 hevc->outputBufferingPeriodSEI =
ctx->cbr_padding;
1514 #ifdef NVENC_HAVE_FILLER_DATA
1515 hevc->enableFillerDataInsertion =
ctx->cbr_padding;
1519 hevc->outputPictureTimingSEI = 1;
1521 switch (
ctx->profile) {
1523 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1527 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1531 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1538 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1544 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1550 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1551 hevc->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1552 hevc->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1554 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1557 hevc->level =
ctx->level;
1559 hevc->tier =
ctx->tier;
1561 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1562 if (
ctx->b_ref_mode >= 0)
1563 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1566 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1567 hevc->numRefL0 = avctx->
refs;
1568 hevc->numRefL1 = avctx->
refs;
1571 #ifdef NVENC_HAVE_TEMPORAL_FILTER
1572 if (
ctx->tf_level >= 0) {
1573 hevc->tfLevel =
ctx->tf_level;
1575 switch (
ctx->tf_level)
1577 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1578 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1585 if (
ctx->encode_config.frameIntervalP < 5)
1593 #if CONFIG_AV1_NVENC_ENCODER
1597 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1598 NV_ENC_CONFIG_AV1 *av1 = &cc->encodeCodecConfig.av1Config;
1605 av1->transferCharacteristics = avctx->
color_trc;
1606 av1->colorRange = 0;
1610 av1->transferCharacteristics = avctx->
color_trc;
1616 av_log(avctx,
AV_LOG_ERROR,
"AV1 High Profile not supported, required for 4:4:4 encoding\n");
1619 cc->profileGUID = NV_ENC_AV1_PROFILE_MAIN_GUID;
1623 if (
ctx->dpb_size >= 0) {
1625 av1->maxNumRefFramesInDPB =
ctx->dpb_size;
1628 if (
ctx->intra_refresh) {
1629 av1->enableIntraRefresh = 1;
1630 av1->intraRefreshPeriod = cc->gopLength;
1631 av1->intraRefreshCnt = cc->gopLength - 1;
1632 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1635 av1->idrPeriod = cc->gopLength;
1637 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1638 av1->enableBitstreamPadding =
ctx->cbr_padding;
1641 if (
ctx->tile_cols >= 0)
1642 av1->numTileColumns =
ctx->tile_cols;
1643 if (
ctx->tile_rows >= 0)
1644 av1->numTileRows =
ctx->tile_rows;
1646 av1->outputAnnexBFormat = 0;
1648 av1->level =
ctx->level;
1649 av1->tier =
ctx->tier;
1651 av1->enableTimingInfo =
ctx->timing_info;
1654 av1->disableSeqHdr = 0;
1655 av1->repeatSeqHdr = 1;
1657 av1->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1659 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1660 av1->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1661 av1->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1663 av1->inputPixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1664 av1->pixelBitDepthMinus8 = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? 2 : 0;
1667 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
1676 if (
ctx->b_ref_mode >= 0)
1677 av1->useBFramesAsRef =
ctx->b_ref_mode;
1679 av1->numFwdRefs = avctx->
refs;
1680 av1->numBwdRefs = avctx->
refs;
1682 #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
1683 if (
ctx->tf_level >= 0) {
1684 av1->tfLevel =
ctx->tf_level;
1686 switch (
ctx->tf_level)
1688 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1689 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1696 if (
ctx->encode_config.frameIntervalP < 5)
1712 #if CONFIG_AV1_NVENC_ENCODER
1714 return nvenc_setup_av1_config(avctx);
1728 #if CONFIG_AV1_NVENC_ENCODER
1759 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1761 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1762 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1767 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1768 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1770 ctx->init_encode_params.encodeHeight = avctx->
height;
1771 ctx->init_encode_params.encodeWidth = avctx->
width;
1773 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1775 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1776 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1778 #ifdef NVENC_HAVE_NEW_PRESETS
1779 ctx->init_encode_params.tuningInfo =
ctx->tuning_info;
1782 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1784 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1786 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(
ctx->nvencoder,
1787 ctx->init_encode_params.encodeGUID,
1788 ctx->init_encode_params.presetGUID,
1789 ctx->init_encode_params.tuningInfo,
1792 nv_status = p_nvenc->nvEncGetEncodePresetConfig(
ctx->nvencoder,
1793 ctx->init_encode_params.encodeGUID,
1794 ctx->init_encode_params.presetGUID,
1797 if (nv_status != NV_ENC_SUCCESS)
1798 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1800 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1802 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1805 ctx->init_encode_params.darHeight = dh;
1806 ctx->init_encode_params.darWidth = dw;
1816 #ifdef NVENC_HAVE_UNIDIR_B
1817 ctx->init_encode_params.enableUniDirectionalB =
ctx->unidir_b;
1820 ctx->init_encode_params.enableEncodeAsync = 0;
1821 ctx->init_encode_params.enablePTD = 1;
1823 #ifdef NVENC_HAVE_NEW_PRESETS
1827 if (
ctx->rc_lookahead == 0 &&
ctx->encode_config.rcParams.enableLookahead)
1828 ctx->rc_lookahead =
ctx->encode_config.rcParams.lookaheadDepth;
1831 if (
ctx->weighted_pred == 1)
1832 ctx->init_encode_params.enableWeightedPrediction = 1;
1834 #ifdef NVENC_HAVE_SPLIT_FRAME_ENCODING
1835 ctx->init_encode_params.splitEncodeMode =
ctx->split_encode_mode;
1837 if (
ctx->split_encode_mode != NV_ENC_SPLIT_DISABLE_MODE) {
1839 av_log(avctx,
AV_LOG_WARNING,
"Split encoding not supported with weighted prediction enabled.\n");
1843 if (
ctx->bluray_compat) {
1852 ctx->level = NV_ENC_LEVEL_HEVC_51;
1853 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1862 ctx->encode_config.frameIntervalP = 0;
1863 ctx->encode_config.gopLength = 1;
1872 if(
ctx->single_slice_intra_refresh)
1873 ctx->intra_refresh = 1;
1882 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1884 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1895 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1896 if (nv_status != NV_ENC_SUCCESS) {
1901 #ifdef NVENC_HAVE_CUSTREAM_PTR
1902 if (
ctx->cu_context) {
1903 nv_status = p_nvenc->nvEncSetIOCudaStreams(
ctx->nvencoder, &
ctx->cu_stream, &
ctx->cu_stream);
1904 if (nv_status != NV_ENC_SUCCESS) {
1915 if (
ctx->encode_config.frameIntervalP > 1)
1918 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1919 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1926 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1935 return NV_ENC_BUFFER_FORMAT_YV12;
1937 return NV_ENC_BUFFER_FORMAT_NV12;
1940 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1943 return NV_ENC_BUFFER_FORMAT_YUV444;
1946 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1949 return NV_ENC_BUFFER_FORMAT_ARGB;
1952 return NV_ENC_BUFFER_FORMAT_ABGR;
1954 return NV_ENC_BUFFER_FORMAT_ARGB10;
1956 return NV_ENC_BUFFER_FORMAT_ABGR10;
1957 #ifdef NVENC_HAVE_422_SUPPORT
1959 return NV_ENC_BUFFER_FORMAT_NV16;
1962 return NV_ENC_BUFFER_FORMAT_P210;
1965 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1973 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1976 NVENCSTATUS nv_status;
1977 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1978 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1982 if (!
ctx->surfaces[idx].in_ref)
1985 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1988 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1994 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1995 allocSurf.width = avctx->
width;
1996 allocSurf.height = avctx->
height;
1997 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1999 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
2000 if (nv_status != NV_ENC_SUCCESS) {
2004 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
2005 ctx->surfaces[idx].width = allocSurf.width;
2006 ctx->surfaces[idx].height = allocSurf.height;
2009 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
2010 if (nv_status != NV_ENC_SUCCESS) {
2013 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
2018 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
2028 int i, res = 0, res2;
2034 ctx->frame_data_array =
av_calloc(
ctx->frame_data_array_nb,
sizeof(*
ctx->frame_data_array));
2035 if (!
ctx->frame_data_array)
2040 if (!
ctx->timestamp_list)
2044 if (!
ctx->unused_surface_queue)
2048 if (!
ctx->output_surface_queue)
2051 if (!
ctx->output_surface_ready_queue)
2058 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
2075 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2077 NVENCSTATUS nv_status;
2078 uint32_t outSize = 0;
2079 char tmpHeader[NV_MAX_SEQ_HDR_LEN];
2081 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
2082 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
2084 payload.spsppsBuffer = tmpHeader;
2085 payload.inBufferSize =
sizeof(tmpHeader);
2086 payload.outSPSPPSPayloadSize = &outSize;
2088 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
2089 if (nv_status != NV_ENC_SUCCESS) {
2100 memcpy(avctx->
extradata, tmpHeader, outSize);
2109 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2113 if (
ctx->nvencoder) {
2114 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
2115 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
2121 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, ¶ms);
2129 if (
ctx->frame_data_array) {
2130 for (
i = 0;
i <
ctx->frame_data_array_nb;
i++)
2136 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2137 if (
ctx->registered_frames[
i].mapped)
2138 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
2139 if (
ctx->registered_frames[
i].regptr)
2140 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2142 ctx->nb_registered_frames = 0;
2145 if (
ctx->surfaces) {
2146 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
2148 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
2150 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
2154 ctx->nb_surfaces = 0;
2160 if (
ctx->nvencoder) {
2161 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
2169 if (
ctx->cu_context_internal)
2171 ctx->cu_context =
ctx->cu_context_internal =
NULL;
2174 if (
ctx->d3d11_device) {
2175 ID3D11Device_Release(
ctx->d3d11_device);
2180 nvenc_free_functions(&dl_fn->
nvenc_dl);
2181 cuda_free_functions(&dl_fn->
cuda_dl);
2199 "hw_frames_ctx must be set when using GPU frames as input\n");
2205 "hw_frames_ctx must match the GPU frame type\n");
2254 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
2256 int dst_linesize[4] = {
2257 lock_buffer_params->pitch,
2258 lock_buffer_params->pitch,
2259 lock_buffer_params->pitch,
2260 lock_buffer_params->pitch
2262 uint8_t *dst_data[4];
2266 dst_linesize[1] = dst_linesize[2] >>= 1;
2269 lock_buffer_params->bufferDataPtr, dst_linesize);
2274 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
2287 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2288 NVENCSTATUS nv_status;
2293 for (first_round = 1; first_round >= 0; first_round--) {
2294 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2295 if (!
ctx->registered_frames[
i].mapped) {
2296 if (
ctx->registered_frames[
i].regptr) {
2299 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2300 if (nv_status != NV_ENC_SUCCESS)
2301 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
2302 ctx->registered_frames[
i].ptr =
NULL;
2303 ctx->registered_frames[
i].regptr =
NULL;
2310 return ctx->nb_registered_frames++;
2321 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2324 NV_ENC_REGISTER_RESOURCE reg = { 0 };
2327 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2338 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
2339 reg.width = frames_ctx->width;
2340 reg.height = frames_ctx->height;
2341 reg.pitch =
frame->linesize[0];
2342 reg.resourceToRegister =
frame->data[0];
2345 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
2348 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
2349 reg.subResourceIndex = (intptr_t)
frame->data[1];
2353 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
2359 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
2360 if (
ret != NV_ENC_SUCCESS) {
2365 ctx->registered_frames[idx].ptr =
frame->data[0];
2366 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
2367 ctx->registered_frames[idx].regptr = reg.registeredResource;
2376 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2379 NVENCSTATUS nv_status;
2392 if (!
ctx->registered_frames[reg_idx].mapped) {
2393 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
2394 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
2395 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
2396 if (nv_status != NV_ENC_SUCCESS) {
2402 ctx->registered_frames[reg_idx].mapped += 1;
2404 nvenc_frame->
reg_idx = reg_idx;
2405 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
2406 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
2411 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
2413 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
2416 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
2417 if (nv_status != NV_ENC_SUCCESS) {
2418 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
2421 nvenc_frame->
pitch = lockBufferParams.pitch;
2424 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
2425 if (nv_status != NV_ENC_SUCCESS) {
2433 #ifdef NVENC_HAVE_TIME_CODE
2439 uint32_t *tc = (uint32_t*)sd->
data;
2444 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2445 time_code->skipClockTimestampInsertion = 1;
2448 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME_DOUBLING;
2451 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME_TRIPLING;
2454 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2458 for (
int i = 0;
i < cnt;
i++) {
2459 unsigned hh, mm,
ss, ff, drop;
2462 time_code->clockTimestamp[
i].countingType = 0;
2463 time_code->clockTimestamp[
i].discontinuityFlag = 0;
2464 time_code->clockTimestamp[
i].cntDroppedFrames = drop;
2465 time_code->clockTimestamp[
i].nFrames = ff;
2466 time_code->clockTimestamp[
i].secondsValue =
ss;
2467 time_code->clockTimestamp[
i].minutesValue = mm;
2468 time_code->clockTimestamp[
i].hoursValue = hh;
2469 time_code->clockTimestamp[
i].timeOffset = 0;
2472 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2473 time_code->skipClockTimestampInsertion = 1;
2479 NV_ENC_PIC_PARAMS *params,
2480 NV_ENC_SEI_PAYLOAD *sei_data,
2487 params->codecPicParams.h264PicParams.sliceMode =
2488 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
2489 params->codecPicParams.h264PicParams.sliceModeData =
2490 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
2491 if (sei_count > 0) {
2492 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
2493 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
2496 #ifdef NVENC_HAVE_TIME_CODE
2498 nvenc_fill_time_code(avctx,
frame, ¶ms->codecPicParams.h264PicParams.timeCode);
2503 params->codecPicParams.hevcPicParams.sliceMode =
2504 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
2505 params->codecPicParams.hevcPicParams.sliceModeData =
2506 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
2507 if (sei_count > 0) {
2508 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
2509 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
2513 #if CONFIG_AV1_NVENC_ENCODER
2515 params->codecPicParams.av1PicParams.numTileColumns =
2516 ctx->encode_config.encodeCodecConfig.av1Config.numTileColumns;
2517 params->codecPicParams.av1PicParams.numTileRows =
2518 ctx->encode_config.encodeCodecConfig.av1Config.numTileRows;
2519 if (sei_count > 0) {
2520 params->codecPicParams.av1PicParams.obuPayloadArray = sei_data;
2521 params->codecPicParams.av1PicParams.obuPayloadArrayCnt = sei_count;
2552 NV_ENC_LOCK_BITSTREAM *params,
2559 pkt->
pts = params->outputTimeStamp;
2567 delay =
FFMAX(
ctx->encode_config.frameIntervalP - 1, 0);
2568 if (
ctx->output_frame_num >= delay) {
2570 ctx->output_frame_num++;
2574 delay_time =
ctx->initial_delay_time;
2582 delay_time = t1 - t2;
2587 delay_time = delay * (t3 - t2);
2591 ctx->initial_delay_time = delay_time;
2600 ctx->output_frame_num++;
2610 int idx =
ctx->frame_data_array_pos;
2625 ctx->frame_data_array_pos = (
ctx->frame_data_array_pos + 1) %
ctx->frame_data_array_nb;
2626 pic_params->inputDuration = idx;
2636 int idx = lock_params->outputDuration;
2656 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2658 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
2659 NVENCSTATUS nv_status;
2664 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
2666 lock_params.doNotWait = 0;
2669 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
2670 if (nv_status != NV_ENC_SUCCESS) {
2682 memcpy(
pkt->
data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
2684 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
2685 if (nv_status != NV_ENC_SUCCESS) {
2686 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
2692 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
2693 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
2694 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
2695 if (nv_status != NV_ENC_SUCCESS) {
2699 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
2709 switch (lock_params.pictureType) {
2710 case NV_ENC_PIC_TYPE_IDR:
2712 case NV_ENC_PIC_TYPE_I:
2715 case NV_ENC_PIC_TYPE_P:
2718 case NV_ENC_PIC_TYPE_B:
2721 case NV_ENC_PIC_TYPE_BI:
2725 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
2726 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
2754 int nb_ready, nb_pending;
2759 return nb_ready > 0;
2760 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
2770 void *a53_data =
NULL;
2771 size_t a53_size = 0;
2779 &
ctx->sei_data_size,
2780 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2787 ctx->sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2788 ctx->sei_data[sei_count].payload = (uint8_t*)a53_data;
2790 #if CONFIG_AV1_NVENC_ENCODER
2803 void *tc_data =
NULL;
2812 &
ctx->sei_data_size,
2813 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2820 ctx->sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2821 ctx->sei_data[sei_count].payload = (uint8_t*)tc_data;
2823 #if CONFIG_AV1_NVENC_ENCODER
2838 for (
i = 0;
i <
frame->nb_side_data;
i++) {
2846 &
ctx->sei_data_size,
2847 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2853 ctx->sei_data[sei_count].payloadSize = side_data->
size;
2857 if (!
ctx->sei_data[sei_count].payload) {
2869 for (
i = 0;
i < sei_count;
i++)
2878 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
2881 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2882 int needs_reconfig = 0;
2883 int needs_encode_config = 0;
2884 int reconfig_bitrate = 0, reconfig_dar = 0;
2887 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2888 params.reInitEncodeParams =
ctx->init_encode_params;
2891 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
2893 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2894 ctx->init_encode_params.darWidth,
2895 ctx->init_encode_params.darHeight, dw, dh);
2897 params.reInitEncodeParams.darHeight = dh;
2898 params.reInitEncodeParams.darWidth = dw;
2904 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
2905 if (avctx->
bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
2907 "avg bitrate change: %d -> %d\n",
2908 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2911 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
2912 reconfig_bitrate = 1;
2917 "max bitrate change: %d -> %d\n",
2918 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2921 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
2922 reconfig_bitrate = 1;
2927 "vbv buffer size change: %d -> %d\n",
2928 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2931 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->
rc_buffer_size;
2932 reconfig_bitrate = 1;
2935 if (reconfig_bitrate) {
2936 params.resetEncoder = 1;
2937 params.forceIDR = 1;
2939 needs_encode_config = 1;
2944 if (!needs_encode_config)
2945 params.reInitEncodeParams.encodeConfig =
NULL;
2947 if (needs_reconfig) {
2948 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, ¶ms);
2949 if (
ret != NV_ENC_SUCCESS) {
2953 ctx->init_encode_params.darHeight = dh;
2954 ctx->init_encode_params.darWidth = dw;
2957 if (reconfig_bitrate) {
2958 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2959 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2960 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2967 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
2969 MASTERING_DISPLAY_INFO *mastering_disp_info, CONTENT_LIGHT_LEVEL *content_light_level)
2973 if (
ctx->mdm ||
ctx->cll) {
3014 pic_params->codecPicParams.hevcPicParams.pMasteringDisplay = mastering_disp_info;
3016 pic_params->codecPicParams.av1PicParams.pMasteringDisplay = mastering_disp_info;
3023 content_light_level->maxContentLightLevel = cll->
MaxCLL;
3024 content_light_level->maxPicAverageLightLevel = cll->
MaxFALL;
3027 pic_params->codecPicParams.hevcPicParams.pMaxCll = content_light_level;
3029 pic_params->codecPicParams.av1PicParams.pMaxCll = content_light_level;
3041 NVENCSTATUS nv_status;
3046 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
3047 MASTERING_DISPLAY_INFO mastering_disp_info = { 0 };
3048 CONTENT_LIGHT_LEVEL content_light_level = { 0 };
3053 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
3055 NV_ENC_PIC_PARAMS pic_params = { 0 };
3056 pic_params.version = NV_ENC_PIC_PARAMS_VER;
3058 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
3082 pic_params.bufferFmt = in_surf->
format;
3083 pic_params.inputWidth = in_surf->
width;
3084 pic_params.inputHeight = in_surf->
height;
3085 pic_params.inputPitch = in_surf->
pitch;
3090 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
3092 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
3094 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
3098 pic_params.encodePicFlags =
3099 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
3101 pic_params.encodePicFlags = 0;
3104 pic_params.frameIdx =
ctx->frame_idx_counter++;
3105 pic_params.inputTimeStamp =
frame->pts;
3107 if (
ctx->extra_sei) {
3114 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
3115 res = nvenc_set_mastering_display_data(avctx,
frame, &pic_params, &mastering_disp_info, &content_light_level);
3126 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
3133 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
3135 for (
i = 0;
i < sei_count;
i++)
3142 if (nv_status != NV_ENC_SUCCESS &&
3143 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
3154 if (nv_status == NV_ENC_SUCCESS) {
3155 while (
av_fifo_read(
ctx->output_surface_queue, &tmp_out_surf, 1) >= 0)
3171 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
3174 if (!
frame->buf[0]) {
3219 ctx->output_frame_num = 0;
3220 ctx->initial_delay_time = 0;