23 #include "config_components.h"
27 #if CONFIG_AV1_NVENC_ENCODER
47 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
49 #define NVENC_CAP 0x30
51 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR)
61 #ifdef NVENC_HAVE_422_SUPPORT
83 #ifdef NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
94 #ifdef NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
105 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
106 pix_fmt == AV_PIX_FMT_P012 || \
107 pix_fmt == AV_PIX_FMT_P016 || \
108 pix_fmt == AV_PIX_FMT_P210 || \
109 pix_fmt == AV_PIX_FMT_P212 || \
110 pix_fmt == AV_PIX_FMT_P216 || \
111 pix_fmt == AV_PIX_FMT_YUV444P10MSB || \
112 pix_fmt == AV_PIX_FMT_YUV444P12MSB || \
113 pix_fmt == AV_PIX_FMT_YUV444P16 || \
114 pix_fmt == AV_PIX_FMT_P410 || \
115 pix_fmt == AV_PIX_FMT_P412 || \
116 pix_fmt == AV_PIX_FMT_P416 || \
117 pix_fmt == AV_PIX_FMT_X2RGB10 || \
118 pix_fmt == AV_PIX_FMT_X2BGR10 || \
119 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
120 pix_fmt == AV_PIX_FMT_GBRP16)
122 #define IS_RGB(pix_fmt) (pix_fmt == AV_PIX_FMT_0RGB32 || \
123 pix_fmt == AV_PIX_FMT_RGB32 || \
124 pix_fmt == AV_PIX_FMT_0BGR32 || \
125 pix_fmt == AV_PIX_FMT_BGR32 || \
126 pix_fmt == AV_PIX_FMT_X2RGB10 || \
127 pix_fmt == AV_PIX_FMT_X2BGR10)
129 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
130 pix_fmt == AV_PIX_FMT_NV24 || \
131 pix_fmt == AV_PIX_FMT_YUV444P10MSB || \
132 pix_fmt == AV_PIX_FMT_YUV444P12MSB || \
133 pix_fmt == AV_PIX_FMT_YUV444P16 || \
134 pix_fmt == AV_PIX_FMT_P410 || \
135 pix_fmt == AV_PIX_FMT_P412 || \
136 pix_fmt == AV_PIX_FMT_P416 || \
137 pix_fmt == AV_PIX_FMT_GBRP || \
138 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
139 pix_fmt == AV_PIX_FMT_GBRP16 || \
140 (ctx->rgb_mode == NVENC_RGB_MODE_444 && IS_RGB(pix_fmt)))
142 #define IS_YUV422(pix_fmt) (pix_fmt == AV_PIX_FMT_NV16 || \
143 pix_fmt == AV_PIX_FMT_P210 || \
144 pix_fmt == AV_PIX_FMT_P212 || \
145 pix_fmt == AV_PIX_FMT_P216)
147 #define IS_HWACCEL(pix_fmt) (pix_fmt == AV_PIX_FMT_CUDA || \
148 pix_fmt == AV_PIX_FMT_CUARRAY || \
149 pix_fmt == AV_PIX_FMT_D3D11)
151 #define IS_GBRP(pix_fmt) (pix_fmt == AV_PIX_FMT_GBRP || \
152 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
153 pix_fmt == AV_PIX_FMT_GBRP16)
155 static const struct {
160 { NV_ENC_SUCCESS, 0,
"success" },
161 { NV_ENC_ERR_NO_ENCODE_DEVICE,
AVERROR(ENOENT),
"no encode device" },
162 { NV_ENC_ERR_UNSUPPORTED_DEVICE,
AVERROR(ENOSYS),
"unsupported device" },
163 { NV_ENC_ERR_INVALID_ENCODERDEVICE,
AVERROR(EINVAL),
"invalid encoder device" },
164 { NV_ENC_ERR_INVALID_DEVICE,
AVERROR(EINVAL),
"invalid device" },
165 { NV_ENC_ERR_DEVICE_NOT_EXIST,
AVERROR(EIO),
"device does not exist" },
166 { NV_ENC_ERR_INVALID_PTR,
AVERROR(EFAULT),
"invalid ptr" },
167 { NV_ENC_ERR_INVALID_EVENT,
AVERROR(EINVAL),
"invalid event" },
168 { NV_ENC_ERR_INVALID_PARAM,
AVERROR(EINVAL),
"invalid param" },
169 { NV_ENC_ERR_INVALID_CALL,
AVERROR(EINVAL),
"invalid call" },
170 { NV_ENC_ERR_OUT_OF_MEMORY,
AVERROR(ENOMEM),
"out of memory" },
171 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,
AVERROR(EINVAL),
"encoder not initialized" },
172 { NV_ENC_ERR_UNSUPPORTED_PARAM,
AVERROR(ENOSYS),
"unsupported param" },
173 { NV_ENC_ERR_LOCK_BUSY,
AVERROR(EAGAIN),
"lock busy" },
175 { NV_ENC_ERR_INVALID_VERSION,
AVERROR(EINVAL),
"invalid version" },
176 { NV_ENC_ERR_MAP_FAILED,
AVERROR(EIO),
"map failed" },
177 { NV_ENC_ERR_NEED_MORE_INPUT,
AVERROR(EAGAIN),
"need more input" },
178 { NV_ENC_ERR_ENCODER_BUSY,
AVERROR(EAGAIN),
"encoder busy" },
179 { NV_ENC_ERR_EVENT_NOT_REGISTERD,
AVERROR(EBADF),
"event not registered" },
181 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,
AVERROR(EINVAL),
"incompatible client key" },
182 { NV_ENC_ERR_UNIMPLEMENTED,
AVERROR(ENOSYS),
"unimplemented" },
183 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED,
AVERROR(EIO),
"resource register failed" },
184 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,
AVERROR(EBADF),
"resource not registered" },
185 { NV_ENC_ERR_RESOURCE_NOT_MAPPED,
AVERROR(EBADF),
"resource not mapped" },
199 *
desc =
"unknown error";
204 const char *error_string)
207 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
209 const char *details =
"(no details)";
212 if (p_nvenc &&
ctx->nvencoder)
213 details = p_nvenc->nvEncGetLastErrorString(
ctx->nvencoder);
225 #define PRESET_ALIAS(alias, name, ...) \
226 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
228 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
247 ctx->init_encode_params.presetGUID = t->
guid;
250 if (
ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
259 #if NVENCAPI_CHECK_VERSION(13, 2)
260 const char *minver =
"(unknown)";
261 #elif NVENCAPI_CHECK_VERSION(13, 1)
262 const char *minver =
"610.00";
263 #elif NVENCAPI_CHECK_VERSION(13, 0)
264 const char *minver =
"570.0";
265 #elif NVENCAPI_CHECK_VERSION(12, 2)
266 # if defined(_WIN32) || defined(__CYGWIN__)
267 const char *minver =
"551.76";
269 const char *minver =
"550.54.14";
271 #elif NVENCAPI_CHECK_VERSION(12, 1)
272 # if defined(_WIN32) || defined(__CYGWIN__)
273 const char *minver =
"531.61";
275 const char *minver =
"530.41.03";
277 #elif NVENCAPI_CHECK_VERSION(12, 0)
278 # if defined(_WIN32) || defined(__CYGWIN__)
279 const char *minver =
"522.25";
281 const char *minver =
"520.56.06";
284 # if defined(_WIN32) || defined(__CYGWIN__)
285 const char *minver =
"471.41";
287 const char *minver =
"470.57.02";
290 av_log(avctx,
level,
"The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
293 #if NVENCAPI_CHECK_VERSION(12, 0)
294 #define to_nv_color_matrix(n) (NV_ENC_VUI_MATRIX_COEFFS)(n)
295 #define to_nv_color_pri(n) (NV_ENC_VUI_COLOR_PRIMARIES)(n)
296 #define to_nv_color_trc(n) (NV_ENC_VUI_TRANSFER_CHARACTERISTIC)(n)
298 #define to_nv_color_matrix(n) (uint32_t)(n)
299 #define to_nv_color_pri(n) (uint32_t)(n)
300 #define to_nv_color_trc(n) (uint32_t)(n)
308 uint32_t nvenc_max_ver;
311 ret = cuda_load_functions(&dl_fn->
cuda_dl, avctx);
315 ret = nvenc_load_functions(&dl_fn->
nvenc_dl, avctx);
321 err = dl_fn->
nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
322 if (err != NV_ENC_SUCCESS)
327 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
328 av_log(avctx,
AV_LOG_ERROR,
"Driver does not support the required nvenc API version. "
329 "Required: %d.%d Found: %d.%d\n",
330 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
331 nvenc_max_ver >> 4, nvenc_max_ver & 0
xf);
336 dl_fn->
nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
339 if (err != NV_ENC_SUCCESS)
352 if (
ctx->d3d11_device)
364 if (
ctx->d3d11_device)
372 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS
params = { 0 };
374 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
377 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
378 params.apiVersion = NVENCAPI_VERSION;
379 if (
ctx->d3d11_device) {
381 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
384 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
387 ret = p_nvenc->nvEncOpenEncodeSessionEx(&
params, &
ctx->nvencoder);
388 if (
ret != NV_ENC_SUCCESS) {
399 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
400 int i,
ret, count = 0;
403 ret = p_nvenc->nvEncGetEncodeGUIDCount(
ctx->nvencoder, &count);
405 if (
ret != NV_ENC_SUCCESS || !count)
412 ret = p_nvenc->nvEncGetEncodeGUIDs(
ctx->nvencoder, guids, count, &count);
413 if (
ret != NV_ENC_SUCCESS) {
419 for (
i = 0;
i < count;
i++) {
420 if (!memcmp(&guids[
i], &
ctx->init_encode_params.encodeGUID,
sizeof(*guids))) {
435 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
436 NV_ENC_CAPS_PARAM
params = { 0 };
439 params.version = NV_ENC_CAPS_PARAM_VER;
442 ret = p_nvenc->nvEncGetEncodeCaps(
ctx->nvencoder,
ctx->init_encode_params.encodeGUID, &
params, &
val);
444 if (
ret == NV_ENC_SUCCESS)
466 #ifdef NVENC_HAVE_422_SUPPORT
483 if (ret < avctx->
width) {
490 if (ret < avctx->
height) {
497 if (ret < avctx->max_b_frames) {
507 "Interlaced encoding is not supported. Supported level: %d\n",
519 if (
ctx->rc_lookahead > 0 &&
ret <= 0) {
525 if (
ctx->temporal_aq > 0 &&
ret <= 0) {
531 if (
ctx->weighted_pred > 0 &&
ret <= 0) {
537 if (
ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC &&
ret <= 0) {
542 tmp = (
ctx->b_ref_mode >= 0) ?
ctx->b_ref_mode : NV_ENC_BFRAME_REF_MODE_DISABLED;
545 case NV_ENC_BFRAME_REF_MODE_DISABLED:
547 case NV_ENC_BFRAME_REF_MODE_EACH:
553 case NV_ENC_BFRAME_REF_MODE_MIDDLE:
559 #ifdef NVENC_HAVE_AV1_HGOP_SUPPORT
560 case NV_ENC_BFRAME_REF_MODE_HIERARCHICAL:
573 if(avctx->
refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT &&
ret <= 0) {
579 if(
ctx->single_slice_intra_refresh &&
ret <= 0) {
585 if((
ctx->intra_refresh ||
ctx->single_slice_intra_refresh) &&
ret <= 0) {
591 if(
ctx->constrained_encoding &&
ret <= 0) {
596 #if defined(NVENC_HAVE_TEMPORAL_FILTER) || defined(NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER)
598 if(
ctx->tf_level > 0 &&
ret <= 0) {
604 #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
606 if(
ctx->rc_lookahead > 0 &&
ctx->lookahead_level > 0 &&
607 ctx->lookahead_level != NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT &&
608 ctx->lookahead_level >
ret)
615 #ifdef NVENC_HAVE_UNIDIR_B
617 if(
ctx->unidir_b &&
ret <= 0) {
623 ctx->support_dyn_bitrate =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
625 #ifdef NVENC_HAVE_MVHEVC
626 ctx->multiview_supported =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MVHEVC_ENCODE) > 0;
628 ctx->profile == NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN &&
629 !
ctx->multiview_supported) {
642 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
643 char name[128] = { 0};
644 int major, minor,
ret;
663 av_log(avctx, loglevel,
"[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx,
name, major, minor);
664 if (((major << 4) | minor) <
NVENC_CAP) {
665 av_log(avctx, loglevel,
"does not support NVENC\n");
676 ctx->cu_context =
ctx->cu_context_internal;
688 av_log(avctx, loglevel,
"supports NVENC\n");
699 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
707 ctx->cu_context_internal =
NULL;
720 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
723 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
725 #if CONFIG_AV1_NVENC_ENCODER
727 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_AV1_GUID;
759 cuda_device_hwctx = hwdev_ctx->
hwctx;
762 d3d11_device_hwctx = hwdev_ctx->
hwctx;
770 if (cuda_device_hwctx) {
772 ctx->cu_stream = cuda_device_hwctx->
stream;
775 else if (d3d11_device_hwctx) {
776 ctx->d3d11_device = d3d11_device_hwctx->
device;
777 ID3D11Device_AddRef(
ctx->d3d11_device);
787 av_log(avctx,
AV_LOG_FATAL,
"Provided device doesn't support required NVENC features\n");
791 int i, nb_devices = 0;
807 for (
i = 0;
i < nb_devices; ++
i) {
820 av_log(avctx,
AV_LOG_FATAL,
"Requested GPU %d, but only %d GPUs are available!\n",
ctx->device, nb_devices);
830 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
831 #if CONFIG_AV1_NVENC_ENCODER
837 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
839 if (
ctx->init_qp_p >= 0) {
840 rc->constQP.qpInterP =
ctx->init_qp_p;
841 if (
ctx->init_qp_i >= 0 &&
ctx->init_qp_b >= 0) {
842 rc->constQP.qpIntra =
ctx->init_qp_i;
843 rc->constQP.qpInterB =
ctx->init_qp_b;
847 rc->constQP.qpInterB =
av_clip(
850 rc->constQP.qpIntra = rc->constQP.qpInterP;
851 rc->constQP.qpInterB = rc->constQP.qpInterP;
853 }
else if (
ctx->cqp >= 0) {
854 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra =
ctx->cqp;
868 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
870 #if CONFIG_AV1_NVENC_ENCODER
876 if (avctx->
qmin >= 0 || avctx->
qmax >= 0)
877 av_log(avctx,
AV_LOG_WARNING,
"Passing qmin/qmax via global AVCodecContext options. Use encoder options instead.\n");
879 if (avctx->
qmin >= 0 &&
ctx->qmin < 0)
881 if (avctx->
qmax >= 0 &&
ctx->qmax < 0)
886 if (
ctx->qmin >= 0 &&
ctx->qmax >= 0) {
890 rc->minQP.qpInterB =
ctx->qmin;
891 rc->minQP.qpInterP =
ctx->qmin;
892 rc->minQP.qpIntra =
ctx->qmin;
894 rc->maxQP.qpInterB =
ctx->qmax;
895 rc->maxQP.qpInterP =
ctx->qmax;
896 rc->maxQP.qpIntra =
ctx->qmax;
898 qp_inter_p = (
ctx->qmax + 3 *
ctx->qmin) / 4;
899 }
else if (
ctx->qmin >= 0) {
902 rc->minQP.qpInterB =
ctx->qmin;
903 rc->minQP.qpInterP =
ctx->qmin;
904 rc->minQP.qpIntra =
ctx->qmin;
906 qp_inter_p =
ctx->qmin;
911 rc->enableInitialRCQP = 1;
913 if (
ctx->init_qp_p < 0) {
914 rc->initialRCQP.qpInterP = qp_inter_p;
916 rc->initialRCQP.qpInterP =
ctx->init_qp_p;
919 if (
ctx->init_qp_i < 0) {
921 rc->initialRCQP.qpIntra =
av_clip(
924 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
927 rc->initialRCQP.qpIntra =
ctx->init_qp_i;
930 if (
ctx->init_qp_b < 0) {
932 rc->initialRCQP.qpInterB =
av_clip(
935 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
938 rc->initialRCQP.qpInterB =
ctx->init_qp_b;
945 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
947 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
948 rc->constQP.qpInterB = 0;
949 rc->constQP.qpInterP = 0;
950 rc->constQP.qpIntra = 0;
959 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
962 case NV_ENC_PARAMS_RC_CONSTQP:
965 case NV_ENC_PARAMS_RC_VBR:
968 case NV_ENC_PARAMS_RC_CBR:
972 rc->rateControlMode =
ctx->rc;
981 int nb_surfaces =
FFMAX(4,
ctx->encode_config.frameIntervalP * 2 * 2);
984 if (
ctx->rc_lookahead > 0) {
987 nb_surfaces =
FFMAX(1,
FFMAX(nb_surfaces,
ctx->rc_lookahead +
ctx->encode_config.frameIntervalP + 1 + 4));
988 if (nb_surfaces >
ctx->nb_surfaces &&
ctx->nb_surfaces > 0)
991 "Defined rc_lookahead requires more surfaces, "
992 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
994 ctx->nb_surfaces =
FFMAX(nb_surfaces,
ctx->nb_surfaces);
996 if (
ctx->encode_config.frameIntervalP > 1 &&
ctx->nb_surfaces < nb_surfaces &&
ctx->nb_surfaces > 0)
999 "Defined b-frame requires more surfaces, "
1000 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
1001 ctx->nb_surfaces =
FFMAX(
ctx->nb_surfaces, nb_surfaces);
1003 else if (
ctx->nb_surfaces <= 0)
1004 ctx->nb_surfaces = nb_surfaces;
1009 ctx->async_depth =
FFMIN(
ctx->async_depth,
ctx->nb_surfaces - 1);
1013 ctx->frame_data_array_nb =
FFMAX(
ctx->nb_surfaces,
ctx->nb_surfaces +
ctx->encode_config.frameIntervalP - 1);
1023 av_log(avctx,
AV_LOG_ERROR,
"Using global_quality with nvenc is not supported. Use qp instead.\n");
1028 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate;
1029 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1030 ctx->encode_config.rcParams.maxBitRate =
ctx->encode_config.rcParams.averageBitRate;
1036 ctx->encode_config.rcParams.multiPass =
ctx->multipass;
1039 ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
1041 ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
1044 if (
ctx->cqp >= 0) {
1045 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
1046 }
else if (
ctx->quality >= 0.0f) {
1047 ctx->rc = NV_ENC_PARAMS_RC_VBR;
1051 ctx->encode_config.rcParams.cbQPIndexOffset =
ctx->qp_cb_offset;
1052 ctx->encode_config.rcParams.crQPIndexOffset =
ctx->qp_cr_offset;
1055 ctx->qp_cr_offset !=
ctx->qp_cb_offset)
1057 "av1_nvenc: qp_cr_offset is currently ignored by the NVENC driver "
1058 "(deltaQ_v_ac is forced equal to deltaQ_u_ac); only qp_cb_offset "
1062 ctx->encode_config.rcParams.lowDelayKeyFrameScale =
ctx->ldkfs;
1066 }
else if (
ctx->rc >= 0) {
1069 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
1075 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1076 avctx->
rc_buffer_size =
ctx->encode_config.rcParams.vbvBufferSize = 2 *
ctx->encode_config.rcParams.averageBitRate;
1080 ctx->encode_config.rcParams.enableAQ = 1;
1081 ctx->encode_config.rcParams.aqStrength =
ctx->aq_strength;
1085 if (
ctx->temporal_aq) {
1086 ctx->encode_config.rcParams.enableTemporalAQ = 1;
1090 if (
ctx->rc_lookahead > 0) {
1091 int lkd_bound =
FFMIN(
ctx->nb_surfaces,
ctx->async_depth) -
1092 ctx->encode_config.frameIntervalP - 4;
1094 if (lkd_bound < 0) {
1095 ctx->encode_config.rcParams.enableLookahead = 0;
1097 "Lookahead not enabled. Increase buffer delay (-delay).\n");
1099 ctx->encode_config.rcParams.enableLookahead = 1;
1100 ctx->encode_config.rcParams.lookaheadDepth =
av_clip(
ctx->rc_lookahead, 0, lkd_bound);
1101 ctx->encode_config.rcParams.disableIadapt =
ctx->no_scenecut;
1102 ctx->encode_config.rcParams.disableBadapt = !
ctx->b_adapt;
1104 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
1105 ctx->encode_config.rcParams.lookaheadDepth,
1106 ctx->encode_config.rcParams.disableIadapt ?
"disabled" :
"enabled",
1107 ctx->encode_config.rcParams.disableBadapt ?
"disabled" :
"enabled");
1108 if (
ctx->encode_config.rcParams.lookaheadDepth <
ctx->rc_lookahead)
1109 av_log(avctx,
AV_LOG_WARNING,
"Clipping lookahead depth to %d (from %d) due to lack of surfaces/delay",
1110 ctx->encode_config.rcParams.lookaheadDepth,
ctx->rc_lookahead);
1112 #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
1113 if (
ctx->lookahead_level >= 0) {
1114 switch (
ctx->lookahead_level) {
1115 case NV_ENC_LOOKAHEAD_LEVEL_0:
1116 case NV_ENC_LOOKAHEAD_LEVEL_1:
1117 case NV_ENC_LOOKAHEAD_LEVEL_2:
1118 case NV_ENC_LOOKAHEAD_LEVEL_3:
1119 case NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT:
1126 ctx->encode_config.rcParams.lookaheadLevel =
ctx->lookahead_level;
1132 if (
ctx->strict_gop) {
1133 ctx->encode_config.rcParams.strictGOPTarget = 1;
1138 ctx->encode_config.rcParams.enableNonRefP = 1;
1140 if (
ctx->zerolatency)
1141 ctx->encode_config.rcParams.zeroReorderDelay = 1;
1145 int tmp_quality = (int)(
ctx->quality * 256.0f);
1146 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1147 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1152 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate = 0;
1163 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1164 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1165 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1173 vui->videoFullRangeFlag = 0;
1182 vui->colourDescriptionPresentFlag =
1183 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1185 vui->videoSignalTypePresentFlag =
1186 (vui->colourDescriptionPresentFlag
1187 || vui->videoFormat != 5
1188 || vui->videoFullRangeFlag != 0);
1190 if (
ctx->max_slice_size > 0) {
1191 h264->sliceMode = 1;
1192 h264->sliceModeData =
ctx->max_slice_size;
1194 h264->sliceMode = 3;
1195 h264->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1198 if (
ctx->intra_refresh) {
1199 h264->enableIntraRefresh = 1;
1200 h264->intraRefreshPeriod = cc->gopLength;
1201 h264->intraRefreshCnt = cc->gopLength - 1;
1202 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1203 h264->outputRecoveryPointSEI = 1;
1204 h264->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1207 if (
ctx->constrained_encoding)
1208 h264->enableConstrainedEncoding = 1;
1212 h264->outputAUD =
ctx->aud;
1214 if (
ctx->dpb_size >= 0) {
1216 h264->maxNumRefFrames =
ctx->dpb_size;
1219 h264->idrPeriod = cc->gopLength;
1221 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1223 h264->outputBufferingPeriodSEI =
ctx->cbr_padding;
1225 h264->enableFillerDataInsertion =
ctx->cbr_padding;
1228 h264->outputPictureTimingSEI = 1;
1231 h264->qpPrimeYZeroTransformBypassFlag = 1;
1233 switch(
ctx->profile) {
1235 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1237 if (cc->frameIntervalP > 1) {
1239 "B-frames are not supported by H.264 Baseline profile, disabling.\n");
1240 cc->frameIntervalP = 1;
1244 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1248 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1251 #ifdef NVENC_HAVE_H264_10BIT_SUPPORT
1252 case NV_ENC_H264_PROFILE_HIGH_10:
1253 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
1257 #ifdef NVENC_HAVE_422_SUPPORT
1258 case NV_ENC_H264_PROFILE_HIGH_422:
1259 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
1264 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1270 #ifdef NVENC_HAVE_H264_10BIT_SUPPORT
1273 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
1280 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1284 #ifdef NVENC_HAVE_422_SUPPORT
1287 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
1296 h264->level =
ctx->level;
1298 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1299 h264->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1300 h264->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1303 if (
ctx->coder >= 0)
1304 h264->entropyCodingMode =
ctx->coder;
1306 if (
ctx->b_ref_mode >= 0)
1307 h264->useBFramesAsRef =
ctx->b_ref_mode;
1309 h264->numRefL0 = avctx->
refs;
1310 h264->numRefL1 = avctx->
refs;
1312 #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
1313 if (
ctx->tf_level >= 0) {
1314 h264->tfLevel =
ctx->tf_level;
1316 switch (
ctx->tf_level)
1318 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1319 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1326 if (
ctx->encode_config.frameIntervalP < 5)
1331 #ifdef NVENC_HAVE_TIME_CODE
1333 h264->enableTimeCode = 1;
1342 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1343 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1344 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1352 vui->videoFullRangeFlag = 0;
1361 vui->colourDescriptionPresentFlag =
1362 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1364 vui->videoSignalTypePresentFlag =
1365 (vui->colourDescriptionPresentFlag
1366 || vui->videoFormat != 5
1367 || vui->videoFullRangeFlag != 0);
1369 if (
ctx->max_slice_size > 0) {
1370 hevc->sliceMode = 1;
1371 hevc->sliceModeData =
ctx->max_slice_size;
1373 hevc->sliceMode = 3;
1374 hevc->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1377 if (
ctx->intra_refresh) {
1378 hevc->enableIntraRefresh = 1;
1379 hevc->intraRefreshPeriod = cc->gopLength;
1380 hevc->intraRefreshCnt = cc->gopLength - 1;
1381 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1382 #ifdef NVENC_HAVE_HEVC_OUTPUT_RECOVERY_POINT_SEI
1383 hevc->outputRecoveryPointSEI = 1;
1385 hevc->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1388 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
1397 if (
ctx->constrained_encoding)
1398 hevc->enableConstrainedEncoding = 1;
1402 hevc->outputAUD =
ctx->aud;
1404 if (
ctx->dpb_size >= 0) {
1406 hevc->maxNumRefFramesInDPB =
ctx->dpb_size;
1409 hevc->idrPeriod = cc->gopLength;
1411 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1413 hevc->outputBufferingPeriodSEI =
ctx->cbr_padding;
1415 hevc->enableFillerDataInsertion =
ctx->cbr_padding;
1418 hevc->outputPictureTimingSEI = 1;
1420 #ifdef NVENC_HAVE_MVHEVC
1427 ctx->profile = NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN;
1429 if (
ctx->profile == NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN && stereo3d &&
1440 switch (
ctx->profile) {
1442 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1446 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1450 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1453 #ifdef NVENC_HAVE_MVHEVC
1454 case NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN:
1455 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1459 hevc->enableMVHEVC = 1;
1460 hevc->outputHevc3DReferenceDisplayInfo = 1;
1469 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1475 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1479 #ifdef NVENC_HAVE_MVHEVC
1481 av_log(avctx,
AV_LOG_ERROR,
"Multiview encoding only works for Main profile content.\n");
1488 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1489 hevc->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1490 hevc->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1492 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1495 hevc->level =
ctx->level;
1497 hevc->tier =
ctx->tier;
1499 if (
ctx->b_ref_mode >= 0)
1500 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1502 hevc->numRefL0 = avctx->
refs;
1503 hevc->numRefL1 = avctx->
refs;
1505 #ifdef NVENC_HAVE_TEMPORAL_FILTER
1506 if (
ctx->tf_level >= 0) {
1507 hevc->tfLevel =
ctx->tf_level;
1509 switch (
ctx->tf_level)
1511 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1512 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1519 if (
ctx->encode_config.frameIntervalP < 5)
1527 #if CONFIG_AV1_NVENC_ENCODER
1531 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1532 NV_ENC_CONFIG_AV1 *av1 = &cc->encodeCodecConfig.av1Config;
1540 av1->colorRange = 0;
1550 av_log(avctx,
AV_LOG_ERROR,
"AV1 High Profile not supported, required for 4:4:4 encoding\n");
1553 cc->profileGUID = NV_ENC_AV1_PROFILE_MAIN_GUID;
1557 if (
ctx->dpb_size >= 0) {
1559 av1->maxNumRefFramesInDPB =
ctx->dpb_size;
1562 if (
ctx->intra_refresh) {
1563 av1->enableIntraRefresh = 1;
1564 av1->intraRefreshPeriod = cc->gopLength;
1565 av1->intraRefreshCnt = cc->gopLength - 1;
1566 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1569 av1->idrPeriod = cc->gopLength;
1571 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1572 av1->enableBitstreamPadding =
ctx->cbr_padding;
1575 if (
ctx->tile_cols >= 0)
1576 av1->numTileColumns =
ctx->tile_cols;
1577 if (
ctx->tile_rows >= 0)
1578 av1->numTileRows =
ctx->tile_rows;
1580 av1->outputAnnexBFormat = 0;
1582 av1->level =
ctx->level;
1583 av1->tier =
ctx->tier;
1585 av1->enableTimingInfo =
ctx->timing_info;
1588 av1->disableSeqHdr = 0;
1589 av1->repeatSeqHdr = 1;
1591 av1->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1593 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1594 av1->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1595 av1->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1597 av1->inputPixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1598 av1->pixelBitDepthMinus8 = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? 2 : 0;
1601 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
1610 if (
ctx->b_ref_mode >= 0)
1611 av1->useBFramesAsRef =
ctx->b_ref_mode;
1613 av1->numFwdRefs = avctx->
refs;
1614 av1->numBwdRefs = avctx->
refs;
1616 #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
1617 if (
ctx->tf_level >= 0) {
1618 av1->tfLevel =
ctx->tf_level;
1620 switch (
ctx->tf_level)
1622 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1623 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1630 if (
ctx->encode_config.frameIntervalP < 5)
1646 #if CONFIG_AV1_NVENC_ENCODER
1648 return nvenc_setup_av1_config(avctx);
1662 #if CONFIG_AV1_NVENC_ENCODER
1693 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1695 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1696 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1701 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1702 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1704 ctx->init_encode_params.encodeHeight = avctx->
height;
1705 ctx->init_encode_params.encodeWidth = avctx->
width;
1707 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1709 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1710 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1712 ctx->init_encode_params.tuningInfo =
ctx->tuning_info;
1715 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1717 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1719 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(
ctx->nvencoder,
1720 ctx->init_encode_params.encodeGUID,
1721 ctx->init_encode_params.presetGUID,
1722 ctx->init_encode_params.tuningInfo,
1724 if (nv_status != NV_ENC_SUCCESS)
1725 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1727 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1729 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1732 ctx->init_encode_params.darHeight = dh;
1733 ctx->init_encode_params.darWidth = dw;
1743 #ifdef NVENC_HAVE_UNIDIR_B
1744 ctx->init_encode_params.enableUniDirectionalB =
ctx->unidir_b;
1747 ctx->init_encode_params.enableEncodeAsync = 0;
1748 ctx->init_encode_params.enablePTD = 1;
1753 if (
ctx->rc_lookahead == 0 &&
ctx->encode_config.rcParams.enableLookahead)
1754 ctx->rc_lookahead =
ctx->encode_config.rcParams.lookaheadDepth;
1756 if (
ctx->weighted_pred == 1)
1757 ctx->init_encode_params.enableWeightedPrediction = 1;
1759 #ifdef NVENC_HAVE_SPLIT_FRAME_ENCODING
1760 ctx->init_encode_params.splitEncodeMode =
ctx->split_encode_mode;
1762 if (
ctx->split_encode_mode != NV_ENC_SPLIT_DISABLE_MODE) {
1764 av_log(avctx,
AV_LOG_WARNING,
"Split encoding not supported with weighted prediction enabled.\n");
1768 if (
ctx->bluray_compat) {
1777 ctx->level = NV_ENC_LEVEL_HEVC_51;
1778 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1787 ctx->encode_config.frameIntervalP = 0;
1788 ctx->encode_config.gopLength = 1;
1797 if(
ctx->single_slice_intra_refresh)
1798 ctx->intra_refresh = 1;
1807 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1809 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1820 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1821 if (nv_status != NV_ENC_SUCCESS) {
1826 if (
ctx->cu_context) {
1827 nv_status = p_nvenc->nvEncSetIOCudaStreams(
ctx->nvencoder, &
ctx->cu_stream, &
ctx->cu_stream);
1828 if (nv_status != NV_ENC_SUCCESS) {
1838 if (
ctx->encode_config.frameIntervalP > 1)
1841 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1842 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1849 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1858 return NV_ENC_BUFFER_FORMAT_YV12;
1860 return NV_ENC_BUFFER_FORMAT_NV12;
1864 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1867 return NV_ENC_BUFFER_FORMAT_YUV444;
1873 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1876 return NV_ENC_BUFFER_FORMAT_ARGB;
1879 return NV_ENC_BUFFER_FORMAT_ABGR;
1881 return NV_ENC_BUFFER_FORMAT_ARGB10;
1883 return NV_ENC_BUFFER_FORMAT_ABGR10;
1884 #ifdef NVENC_HAVE_422_SUPPORT
1886 return NV_ENC_BUFFER_FORMAT_NV16;
1890 return NV_ENC_BUFFER_FORMAT_P210;
1893 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1901 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1904 NVENCSTATUS nv_status;
1905 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1906 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1910 if (!
ctx->surfaces[idx].in_ref)
1913 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1916 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1922 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1923 allocSurf.width = avctx->
width;
1924 allocSurf.height = avctx->
height;
1925 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1927 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
1928 if (nv_status != NV_ENC_SUCCESS) {
1932 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1933 ctx->surfaces[idx].width = allocSurf.width;
1934 ctx->surfaces[idx].height = allocSurf.height;
1937 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
1938 if (nv_status != NV_ENC_SUCCESS) {
1941 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
1946 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1956 int i, res = 0, res2;
1962 ctx->frame_data_array =
av_calloc(
ctx->frame_data_array_nb,
sizeof(*
ctx->frame_data_array));
1963 if (!
ctx->frame_data_array)
1968 if (!
ctx->timestamp_list)
1972 if (!
ctx->unused_surface_queue)
1976 if (!
ctx->output_surface_queue)
1979 if (!
ctx->output_surface_ready_queue)
1986 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
2003 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2005 NVENCSTATUS nv_status;
2006 uint32_t outSize = 0;
2007 char tmpHeader[NV_MAX_SEQ_HDR_LEN];
2009 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
2010 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
2012 payload.spsppsBuffer = tmpHeader;
2013 payload.inBufferSize =
sizeof(tmpHeader);
2014 payload.outSPSPPSPayloadSize = &outSize;
2016 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
2017 if (nv_status != NV_ENC_SUCCESS) {
2028 memcpy(avctx->
extradata, tmpHeader, outSize);
2037 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2041 if (
ctx->nvencoder) {
2042 NV_ENC_PIC_PARAMS
params = { .version = NV_ENC_PIC_PARAMS_VER,
2043 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
2049 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &
params);
2057 if (
ctx->frame_data_array) {
2058 for (
i = 0;
i <
ctx->frame_data_array_nb;
i++)
2064 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2065 if (
ctx->registered_frames[
i].mapped)
2066 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
2067 if (
ctx->registered_frames[
i].regptr)
2068 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2070 ctx->nb_registered_frames = 0;
2073 if (
ctx->surfaces) {
2074 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
2076 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
2078 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
2082 ctx->nb_surfaces = 0;
2088 if (
ctx->nvencoder) {
2089 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
2097 if (
ctx->cu_context_internal)
2099 ctx->cu_context =
ctx->cu_context_internal =
NULL;
2102 if (
ctx->d3d11_device) {
2103 ID3D11Device_Release(
ctx->d3d11_device);
2108 nvenc_free_functions(&dl_fn->
nvenc_dl);
2109 cuda_free_functions(&dl_fn->
cuda_dl);
2127 "hw_frames_ctx must be set when using GPU frames as input\n");
2133 "hw_frames_ctx must match the GPU frame type\n");
2182 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
2184 int dst_linesize[4] = {
2185 lock_buffer_params->pitch,
2186 lock_buffer_params->pitch,
2187 lock_buffer_params->pitch,
2188 lock_buffer_params->pitch
2190 uint8_t *dst_data[4];
2194 dst_linesize[1] = dst_linesize[2] >>= 1;
2197 lock_buffer_params->bufferDataPtr, dst_linesize);
2202 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
2215 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2216 NVENCSTATUS nv_status;
2221 for (first_round = 1; first_round >= 0; first_round--) {
2222 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2223 if (!
ctx->registered_frames[
i].mapped) {
2224 if (
ctx->registered_frames[
i].regptr) {
2227 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2228 if (nv_status != NV_ENC_SUCCESS)
2229 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
2230 ctx->registered_frames[
i].ptr =
NULL;
2231 ctx->registered_frames[
i].regptr =
NULL;
2238 return ctx->nb_registered_frames++;
2249 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2252 NV_ENC_REGISTER_RESOURCE reg = { 0 };
2255 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2258 ctx->registered_frames[
i].ptr ==
frame->data[0])
2268 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
2269 reg.width = frames_ctx->width;
2270 reg.height = frames_ctx->height;
2271 reg.pitch =
frame->linesize[0];
2272 reg.resourceToRegister =
frame->data[0];
2275 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
2276 #ifdef NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
2279 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDAARRAY;
2280 reg.pitch = frames_ctx->width * (
desc &&
desc->comp[0].depth > 8 ? 2 : 1);
2284 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
2285 reg.subResourceIndex = (intptr_t)
frame->data[1];
2289 #ifdef NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
2290 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED &&
2291 reg.resourceType == NV_ENC_INPUT_RESOURCE_TYPE_CUDAARRAY) {
2292 switch (frames_ctx->sw_format) {
2294 reg.bufferFormat = NV_ENC_BUFFER_FORMAT_YUV444;
2299 reg.bufferFormat = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
2306 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
2312 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
2313 if (
ret != NV_ENC_SUCCESS) {
2318 ctx->registered_frames[idx].ptr =
frame->data[0];
2319 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
2320 ctx->registered_frames[idx].regptr = reg.registeredResource;
2330 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2333 NVENCSTATUS nv_status;
2346 if (!
ctx->registered_frames[reg_idx].mapped) {
2347 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
2348 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
2349 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
2350 if (nv_status != NV_ENC_SUCCESS) {
2356 ctx->registered_frames[reg_idx].mapped += 1;
2358 nvenc_frame->
reg_idx = reg_idx;
2359 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
2360 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
2365 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
2367 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
2370 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
2371 if (nv_status != NV_ENC_SUCCESS) {
2372 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
2375 nvenc_frame->
pitch = lockBufferParams.pitch;
2378 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
2379 if (nv_status != NV_ENC_SUCCESS) {
2387 #ifdef NVENC_HAVE_TIME_CODE
2393 uint32_t *tc = (uint32_t*)sd->
data;
2398 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2399 time_code->skipClockTimestampInsertion = 1;
2402 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME_DOUBLING;
2405 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME_TRIPLING;
2408 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2412 for (
int i = 0;
i < cnt;
i++) {
2413 unsigned hh, mm,
ss, ff, drop;
2416 #ifdef NVENC_NEW_COUNTING_TYPE
2417 time_code->clockTimestamp[
i].countingTypeLSB = 0;
2418 time_code->clockTimestamp[
i].countingTypeMSB = 0;
2420 time_code->clockTimestamp[
i].countingType = 0;
2422 time_code->clockTimestamp[
i].discontinuityFlag = 0;
2423 time_code->clockTimestamp[
i].cntDroppedFrames = drop;
2424 time_code->clockTimestamp[
i].nFrames = ff;
2425 time_code->clockTimestamp[
i].secondsValue =
ss;
2426 time_code->clockTimestamp[
i].minutesValue = mm;
2427 time_code->clockTimestamp[
i].hoursValue = hh;
2428 time_code->clockTimestamp[
i].timeOffset = 0;
2431 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2432 time_code->skipClockTimestampInsertion = 1;
2438 NV_ENC_PIC_PARAMS *
params,
2439 NV_ENC_SEI_PAYLOAD *sei_data,
2446 params->codecPicParams.h264PicParams.sliceMode =
2447 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
2448 params->codecPicParams.h264PicParams.sliceModeData =
2449 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
2450 if (sei_count > 0) {
2451 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
2452 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
2455 #ifdef NVENC_HAVE_TIME_CODE
2457 nvenc_fill_time_code(avctx,
frame, &
params->codecPicParams.h264PicParams.timeCode);
2462 params->codecPicParams.hevcPicParams.sliceMode =
2463 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
2464 params->codecPicParams.hevcPicParams.sliceModeData =
2465 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
2466 if (sei_count > 0) {
2467 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
2468 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
2472 #if CONFIG_AV1_NVENC_ENCODER
2474 params->codecPicParams.av1PicParams.numTileColumns =
2475 ctx->encode_config.encodeCodecConfig.av1Config.numTileColumns;
2476 params->codecPicParams.av1PicParams.numTileRows =
2477 ctx->encode_config.encodeCodecConfig.av1Config.numTileRows;
2478 if (sei_count > 0) {
2479 params->codecPicParams.av1PicParams.obuPayloadArray = sei_data;
2480 params->codecPicParams.av1PicParams.obuPayloadArrayCnt = sei_count;
2511 NV_ENC_LOCK_BITSTREAM *
params,
2526 delay =
FFMAX(
ctx->encode_config.frameIntervalP - 1, 0);
2527 #ifdef NVENC_HAVE_MVHEVC
2528 delay *=
ctx->multiview ? 2 : 1;
2530 if (
ctx->output_frame_num >= delay) {
2532 ctx->output_frame_num++;
2536 delay_time =
ctx->initial_delay_time;
2544 delay_time = t1 - t2;
2549 delay_time = delay * (t3 - t2);
2553 ctx->initial_delay_time = delay_time;
2562 ctx->output_frame_num++;
2572 int idx =
ctx->frame_data_array_pos;
2587 ctx->frame_data_array_pos = (
ctx->frame_data_array_pos + 1) %
ctx->frame_data_array_nb;
2588 pic_params->inputDuration = idx;
2598 int idx = lock_params->outputDuration;
2618 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2620 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
2621 NVENCSTATUS nv_status;
2626 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
2628 lock_params.doNotWait = 0;
2631 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
2632 if (nv_status != NV_ENC_SUCCESS) {
2644 memcpy(
pkt->
data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
2646 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
2647 if (nv_status != NV_ENC_SUCCESS) {
2648 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
2654 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
2655 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
2656 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
2657 if (nv_status != NV_ENC_SUCCESS) {
2661 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
2671 switch (lock_params.pictureType) {
2672 case NV_ENC_PIC_TYPE_IDR:
2675 case NV_ENC_PIC_TYPE_I:
2678 case NV_ENC_PIC_TYPE_P:
2681 case NV_ENC_PIC_TYPE_B:
2684 case NV_ENC_PIC_TYPE_BI:
2688 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
2689 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
2717 int nb_ready, nb_pending;
2722 return nb_ready > 0;
2723 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
2733 void *a53_data =
NULL;
2734 size_t a53_size = 0;
2742 &
ctx->sei_data_size,
2743 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2750 ctx->sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2751 ctx->sei_data[sei_count].payload = (uint8_t*)a53_data;
2753 #if CONFIG_AV1_NVENC_ENCODER
2766 void *tc_data =
NULL;
2775 &
ctx->sei_data_size,
2776 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2783 ctx->sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2784 ctx->sei_data[sei_count].payload = (uint8_t*)tc_data;
2786 #if CONFIG_AV1_NVENC_ENCODER
2801 for (
i = 0;
i <
frame->nb_side_data;
i++) {
2809 &
ctx->sei_data_size,
2810 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2816 ctx->sei_data[sei_count].payloadSize = side_data->
size;
2820 if (!
ctx->sei_data[sei_count].payload) {
2832 for (
i = 0;
i < sei_count;
i++)
2841 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
2844 NV_ENC_RECONFIGURE_PARAMS
params = { 0 };
2845 int needs_reconfig = 0;
2846 int needs_encode_config = 0;
2847 int reconfig_bitrate = 0, reconfig_dar = 0;
2850 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2851 params.reInitEncodeParams =
ctx->init_encode_params;
2854 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
2856 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2857 ctx->init_encode_params.darWidth,
2858 ctx->init_encode_params.darHeight, dw, dh);
2860 params.reInitEncodeParams.darHeight = dh;
2861 params.reInitEncodeParams.darWidth = dw;
2867 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
2868 if (avctx->
bit_rate > 0 &&
params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
2870 "avg bitrate change: %d -> %d\n",
2871 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2874 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
2875 reconfig_bitrate = 1;
2880 "max bitrate change: %d -> %d\n",
2881 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2884 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
2885 reconfig_bitrate = 1;
2890 "vbv buffer size change: %d -> %d\n",
2891 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2895 reconfig_bitrate = 1;
2898 if (reconfig_bitrate) {
2902 needs_encode_config = 1;
2907 if (!needs_encode_config)
2908 params.reInitEncodeParams.encodeConfig =
NULL;
2910 if (needs_reconfig) {
2911 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, &
params);
2912 if (
ret != NV_ENC_SUCCESS) {
2916 ctx->init_encode_params.darHeight = dh;
2917 ctx->init_encode_params.darWidth = dw;
2920 if (reconfig_bitrate) {
2921 ctx->encode_config.rcParams.averageBitRate =
params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2922 ctx->encode_config.rcParams.maxBitRate =
params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2923 ctx->encode_config.rcParams.vbvBufferSize =
params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2930 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
2932 MASTERING_DISPLAY_INFO *mastering_disp_info, CONTENT_LIGHT_LEVEL *content_light_level)
2936 if (
ctx->mdm ||
ctx->cll) {
2977 pic_params->codecPicParams.hevcPicParams.pMasteringDisplay = mastering_disp_info;
2979 pic_params->codecPicParams.av1PicParams.pMasteringDisplay = mastering_disp_info;
2986 content_light_level->maxContentLightLevel = cll->
MaxCLL;
2987 content_light_level->maxPicAverageLightLevel = cll->
MaxFALL;
2990 pic_params->codecPicParams.hevcPicParams.pMaxCll = content_light_level;
2992 pic_params->codecPicParams.av1PicParams.pMaxCll = content_light_level;
3004 NVENCSTATUS nv_status;
3009 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
3010 MASTERING_DISPLAY_INFO mastering_disp_info = { 0 };
3011 CONTENT_LIGHT_LEVEL content_light_level = { 0 };
3013 #ifdef NVENC_HAVE_MVHEVC
3014 HEVC_3D_REFERENCE_DISPLAY_INFO ref_disp_info = { 0 };
3019 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
3021 NV_ENC_PIC_PARAMS pic_params = { 0 };
3022 pic_params.version = NV_ENC_PIC_PARAMS_VER;
3024 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
3048 pic_params.bufferFmt = in_surf->
format;
3049 pic_params.inputWidth = in_surf->
width;
3050 pic_params.inputHeight = in_surf->
height;
3051 pic_params.inputPitch = in_surf->
pitch;
3056 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
3058 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
3060 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
3064 pic_params.encodePicFlags =
3065 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
3067 pic_params.encodePicFlags = 0;
3070 pic_params.frameIdx =
ctx->frame_idx_counter++;
3071 pic_params.inputTimeStamp =
frame->pts;
3073 if (
ctx->extra_sei) {
3080 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
3081 res = nvenc_set_mastering_display_data(avctx,
frame, &pic_params, &mastering_disp_info, &content_light_level);
3086 #ifdef NVENC_HAVE_MVHEVC
3087 if (
ctx->multiview) {
3092 ctx->next_view_id = *(
int*)sd_view_id->
data;
3094 pic_params.codecPicParams.hevcPicParams.viewId =
ctx->next_view_id;
3118 pic_params.codecPicParams.hevcPicParams.p3DReferenceDisplayInfo = &ref_disp_info;
3119 ctx->display_sei_sent = 1;
3120 }
else if (!
ctx->display_sei_sent) {
3121 ref_disp_info.precRefDisplayWidth = 31;
3122 ref_disp_info.leftViewId[0] = 0;
3123 ref_disp_info.rightViewId[0] = 1;
3125 pic_params.codecPicParams.hevcPicParams.p3DReferenceDisplayInfo = &ref_disp_info;
3126 ctx->display_sei_sent = 1;
3129 ctx->next_view_id = !
ctx->next_view_id;
3139 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
3146 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
3148 for (
i = 0;
i < sei_count;
i++)
3155 if (nv_status != NV_ENC_SUCCESS &&
3156 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
3167 if (nv_status == NV_ENC_SUCCESS) {
3168 while (
av_fifo_read(
ctx->output_surface_queue, &tmp_out_surf, 1) >= 0)
3184 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
3187 if (!
frame->buf[0]) {
3232 ctx->output_frame_num = 0;
3233 ctx->initial_delay_time = 0;