23 #include "config_components.h"
27 #if CONFIG_AV1_NVENC_ENCODER
44 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
46 #define NVENC_CAP 0x30
48 #ifndef NVENC_NO_DEPRECATED_RC
49 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
50 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
51 rc == NV_ENC_PARAMS_RC_CBR_HQ)
53 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR)
88 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
89 pix_fmt == AV_PIX_FMT_P016 || \
90 pix_fmt == AV_PIX_FMT_YUV444P16 || \
91 pix_fmt == AV_PIX_FMT_X2RGB10 || \
92 pix_fmt == AV_PIX_FMT_X2BGR10 || \
93 pix_fmt == AV_PIX_FMT_GBRP16)
95 #define IS_RGB(pix_fmt) (pix_fmt == AV_PIX_FMT_0RGB32 || \
96 pix_fmt == AV_PIX_FMT_RGB32 || \
97 pix_fmt == AV_PIX_FMT_0BGR32 || \
98 pix_fmt == AV_PIX_FMT_BGR32 || \
99 pix_fmt == AV_PIX_FMT_X2RGB10 || \
100 pix_fmt == AV_PIX_FMT_X2BGR10)
102 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
103 pix_fmt == AV_PIX_FMT_YUV444P16 || \
104 pix_fmt == AV_PIX_FMT_GBRP || \
105 pix_fmt == AV_PIX_FMT_GBRP16 || \
106 (ctx->rgb_mode == NVENC_RGB_MODE_444 && IS_RGB(pix_fmt)))
108 #define IS_GBRP(pix_fmt) (pix_fmt == AV_PIX_FMT_GBRP || \
109 pix_fmt == AV_PIX_FMT_GBRP16)
111 static const struct {
116 { NV_ENC_SUCCESS, 0,
"success" },
117 { NV_ENC_ERR_NO_ENCODE_DEVICE,
AVERROR(ENOENT),
"no encode device" },
118 { NV_ENC_ERR_UNSUPPORTED_DEVICE,
AVERROR(ENOSYS),
"unsupported device" },
119 { NV_ENC_ERR_INVALID_ENCODERDEVICE,
AVERROR(EINVAL),
"invalid encoder device" },
120 { NV_ENC_ERR_INVALID_DEVICE,
AVERROR(EINVAL),
"invalid device" },
121 { NV_ENC_ERR_DEVICE_NOT_EXIST,
AVERROR(EIO),
"device does not exist" },
122 { NV_ENC_ERR_INVALID_PTR,
AVERROR(EFAULT),
"invalid ptr" },
123 { NV_ENC_ERR_INVALID_EVENT,
AVERROR(EINVAL),
"invalid event" },
124 { NV_ENC_ERR_INVALID_PARAM,
AVERROR(EINVAL),
"invalid param" },
125 { NV_ENC_ERR_INVALID_CALL,
AVERROR(EINVAL),
"invalid call" },
126 { NV_ENC_ERR_OUT_OF_MEMORY,
AVERROR(ENOMEM),
"out of memory" },
127 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,
AVERROR(EINVAL),
"encoder not initialized" },
128 { NV_ENC_ERR_UNSUPPORTED_PARAM,
AVERROR(ENOSYS),
"unsupported param" },
129 { NV_ENC_ERR_LOCK_BUSY,
AVERROR(EAGAIN),
"lock busy" },
131 { NV_ENC_ERR_INVALID_VERSION,
AVERROR(EINVAL),
"invalid version" },
132 { NV_ENC_ERR_MAP_FAILED,
AVERROR(EIO),
"map failed" },
133 { NV_ENC_ERR_NEED_MORE_INPUT,
AVERROR(EAGAIN),
"need more input" },
134 { NV_ENC_ERR_ENCODER_BUSY,
AVERROR(EAGAIN),
"encoder busy" },
135 { NV_ENC_ERR_EVENT_NOT_REGISTERD,
AVERROR(EBADF),
"event not registered" },
137 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,
AVERROR(EINVAL),
"incompatible client key" },
138 { NV_ENC_ERR_UNIMPLEMENTED,
AVERROR(ENOSYS),
"unimplemented" },
139 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED,
AVERROR(EIO),
"resource register failed" },
140 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,
AVERROR(EBADF),
"resource not registered" },
141 { NV_ENC_ERR_RESOURCE_NOT_MAPPED,
AVERROR(EBADF),
"resource not mapped" },
155 *
desc =
"unknown error";
160 const char *error_string)
163 const char *details =
"(no details)";
166 #ifdef NVENC_HAVE_GETLASTERRORSTRING
168 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
170 if (p_nvenc &&
ctx->nvencoder)
171 details = p_nvenc->nvEncGetLastErrorString(
ctx->nvencoder);
184 #define PRESET_ALIAS(alias, name, ...) \
185 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
187 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
192 #ifdef NVENC_HAVE_NEW_PRESETS
231 ctx->init_encode_params.presetGUID = t->
guid;
234 #ifdef NVENC_HAVE_NEW_PRESETS
235 if (
ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
245 #if NVENCAPI_CHECK_VERSION(12, 3)
246 const char *minver =
"(unknown)";
247 #elif NVENCAPI_CHECK_VERSION(12, 2)
248 # if defined(_WIN32) || defined(__CYGWIN__)
249 const char *minver =
"551.76";
251 const char *minver =
"550.54.14";
253 #elif NVENCAPI_CHECK_VERSION(12, 1)
254 # if defined(_WIN32) || defined(__CYGWIN__)
255 const char *minver =
"531.61";
257 const char *minver =
"530.41.03";
259 #elif NVENCAPI_CHECK_VERSION(12, 0)
260 # if defined(_WIN32) || defined(__CYGWIN__)
261 const char *minver =
"522.25";
263 const char *minver =
"520.56.06";
265 #elif NVENCAPI_CHECK_VERSION(11, 1)
266 # if defined(_WIN32) || defined(__CYGWIN__)
267 const char *minver =
"471.41";
269 const char *minver =
"470.57.02";
271 #elif NVENCAPI_CHECK_VERSION(11, 0)
272 # if defined(_WIN32) || defined(__CYGWIN__)
273 const char *minver =
"456.71";
275 const char *minver =
"455.28";
277 #elif NVENCAPI_CHECK_VERSION(10, 0)
278 # if defined(_WIN32) || defined(__CYGWIN__)
279 const char *minver =
"450.51";
281 const char *minver =
"445.87";
283 #elif NVENCAPI_CHECK_VERSION(9, 1)
284 # if defined(_WIN32) || defined(__CYGWIN__)
285 const char *minver =
"436.15";
287 const char *minver =
"435.21";
289 #elif NVENCAPI_CHECK_VERSION(9, 0)
290 # if defined(_WIN32) || defined(__CYGWIN__)
291 const char *minver =
"418.81";
293 const char *minver =
"418.30";
295 #elif NVENCAPI_CHECK_VERSION(8, 2)
296 # if defined(_WIN32) || defined(__CYGWIN__)
297 const char *minver =
"397.93";
299 const char *minver =
"396.24";
301 #elif NVENCAPI_CHECK_VERSION(8, 1)
302 # if defined(_WIN32) || defined(__CYGWIN__)
303 const char *minver =
"390.77";
305 const char *minver =
"390.25";
308 # if defined(_WIN32) || defined(__CYGWIN__)
309 const char *minver =
"378.66";
311 const char *minver =
"378.13";
314 av_log(avctx,
level,
"The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
322 uint32_t nvenc_max_ver;
325 ret = cuda_load_functions(&dl_fn->
cuda_dl, avctx);
329 ret = nvenc_load_functions(&dl_fn->
nvenc_dl, avctx);
335 err = dl_fn->
nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
336 if (err != NV_ENC_SUCCESS)
341 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
342 av_log(avctx,
AV_LOG_ERROR,
"Driver does not support the required nvenc API version. "
343 "Required: %d.%d Found: %d.%d\n",
344 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
345 nvenc_max_ver >> 4, nvenc_max_ver & 0
xf);
350 dl_fn->
nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
353 if (err != NV_ENC_SUCCESS)
366 if (
ctx->d3d11_device)
378 if (
ctx->d3d11_device)
386 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
388 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
391 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
392 params.apiVersion = NVENCAPI_VERSION;
393 if (
ctx->d3d11_device) {
394 params.device =
ctx->d3d11_device;
395 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
397 params.device =
ctx->cu_context;
398 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
401 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &
ctx->nvencoder);
402 if (
ret != NV_ENC_SUCCESS) {
413 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
414 int i,
ret, count = 0;
417 ret = p_nvenc->nvEncGetEncodeGUIDCount(
ctx->nvencoder, &count);
419 if (
ret != NV_ENC_SUCCESS || !count)
426 ret = p_nvenc->nvEncGetEncodeGUIDs(
ctx->nvencoder, guids, count, &count);
427 if (
ret != NV_ENC_SUCCESS) {
433 for (
i = 0;
i < count;
i++) {
434 if (!memcmp(&guids[
i], &
ctx->init_encode_params.encodeGUID,
sizeof(*guids))) {
449 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
450 NV_ENC_CAPS_PARAM params = { 0 };
453 params.version = NV_ENC_CAPS_PARAM_VER;
454 params.capsToQuery = cap;
456 ret = p_nvenc->nvEncGetEncodeCaps(
ctx->nvencoder,
ctx->init_encode_params.encodeGUID, ¶ms, &
val);
458 if (
ret == NV_ENC_SUCCESS)
487 if (ret < avctx->
width) {
494 if (ret < avctx->
height) {
501 if (ret < avctx->max_b_frames) {
511 "Interlaced encoding is not supported. Supported level: %d\n",
523 if (
ctx->rc_lookahead > 0 &&
ret <= 0) {
529 if (
ctx->temporal_aq > 0 &&
ret <= 0) {
535 if (
ctx->weighted_pred > 0 &&
ret <= 0) {
541 if (
ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC &&
ret <= 0) {
546 #ifdef NVENC_HAVE_BFRAME_REF_MODE
547 tmp = (
ctx->b_ref_mode >= 0) ?
ctx->b_ref_mode : NV_ENC_BFRAME_REF_MODE_DISABLED;
549 if (
tmp == NV_ENC_BFRAME_REF_MODE_EACH &&
ret != 1 &&
ret != 3) {
552 }
else if (
tmp != NV_ENC_BFRAME_REF_MODE_DISABLED &&
ret == 0) {
557 tmp = (
ctx->b_ref_mode >= 0) ?
ctx->b_ref_mode : 0;
564 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
566 if(avctx->
refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT &&
ret <= 0) {
571 if(avctx->
refs != 0) {
577 #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
579 if(
ctx->single_slice_intra_refresh &&
ret <= 0) {
584 if(
ctx->single_slice_intra_refresh) {
591 if((
ctx->intra_refresh ||
ctx->single_slice_intra_refresh) &&
ret <= 0) {
596 #ifndef NVENC_HAVE_HEVC_CONSTRAINED_ENCODING
604 if(
ctx->constrained_encoding &&
ret <= 0) {
609 #ifdef NVENC_HAVE_TEMPORAL_FILTER
611 if(
ctx->tf_level > 0 &&
ret <= 0) {
617 #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
619 if(
ctx->rc_lookahead > 0 &&
ctx->lookahead_level > 0 &&
620 ctx->lookahead_level != NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT &&
621 ctx->lookahead_level >
ret)
628 #ifdef NVENC_HAVE_UNIDIR_B
630 if(
ctx->unidir_b &&
ret <= 0) {
636 ctx->support_dyn_bitrate =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
645 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
646 char name[128] = { 0};
647 int major, minor,
ret;
666 av_log(avctx, loglevel,
"[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx,
name, major, minor);
667 if (((major << 4) | minor) <
NVENC_CAP) {
668 av_log(avctx, loglevel,
"does not support NVENC\n");
679 ctx->cu_context =
ctx->cu_context_internal;
691 av_log(avctx, loglevel,
"supports NVENC\n");
702 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
710 ctx->cu_context_internal =
NULL;
723 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
726 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
728 #if CONFIG_AV1_NVENC_ENCODER
730 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_AV1_GUID;
740 av_log(avctx,
AV_LOG_WARNING,
"The selected preset is deprecated. Use p1 to p7 + -tune or fast/medium/slow.\n");
764 cuda_device_hwctx = hwdev_ctx->
hwctx;
767 d3d11_device_hwctx = hwdev_ctx->
hwctx;
775 if (cuda_device_hwctx) {
777 ctx->cu_stream = cuda_device_hwctx->
stream;
780 else if (d3d11_device_hwctx) {
781 ctx->d3d11_device = d3d11_device_hwctx->
device;
782 ID3D11Device_AddRef(
ctx->d3d11_device);
792 av_log(avctx,
AV_LOG_FATAL,
"Provided device doesn't support required NVENC features\n");
796 int i, nb_devices = 0;
812 for (
i = 0;
i < nb_devices; ++
i) {
825 av_log(avctx,
AV_LOG_FATAL,
"Requested GPU %d, but only %d GPUs are available!\n",
ctx->device, nb_devices);
835 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
836 #if CONFIG_AV1_NVENC_ENCODER
842 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
844 if (
ctx->init_qp_p >= 0) {
845 rc->constQP.qpInterP =
ctx->init_qp_p;
846 if (
ctx->init_qp_i >= 0 &&
ctx->init_qp_b >= 0) {
847 rc->constQP.qpIntra =
ctx->init_qp_i;
848 rc->constQP.qpInterB =
ctx->init_qp_b;
852 rc->constQP.qpInterB =
av_clip(
855 rc->constQP.qpIntra = rc->constQP.qpInterP;
856 rc->constQP.qpInterB = rc->constQP.qpInterP;
858 }
else if (
ctx->cqp >= 0) {
859 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra =
ctx->cqp;
873 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
875 #if CONFIG_AV1_NVENC_ENCODER
881 if (avctx->
qmin >= 0 && avctx->
qmax >= 0) {
885 rc->minQP.qpInterB = avctx->
qmin;
886 rc->minQP.qpInterP = avctx->
qmin;
887 rc->minQP.qpIntra = avctx->
qmin;
889 rc->maxQP.qpInterB = avctx->
qmax;
890 rc->maxQP.qpInterP = avctx->
qmax;
891 rc->maxQP.qpIntra = avctx->
qmax;
893 qp_inter_p = (avctx->
qmax + 3 * avctx->
qmin) / 4;
894 }
else if (avctx->
qmin >= 0) {
897 rc->minQP.qpInterB = avctx->
qmin;
898 rc->minQP.qpInterP = avctx->
qmin;
899 rc->minQP.qpIntra = avctx->
qmin;
901 qp_inter_p = avctx->
qmin;
906 rc->enableInitialRCQP = 1;
908 if (
ctx->init_qp_p < 0) {
909 rc->initialRCQP.qpInterP = qp_inter_p;
911 rc->initialRCQP.qpInterP =
ctx->init_qp_p;
914 if (
ctx->init_qp_i < 0) {
916 rc->initialRCQP.qpIntra =
av_clip(
919 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
922 rc->initialRCQP.qpIntra =
ctx->init_qp_i;
925 if (
ctx->init_qp_b < 0) {
927 rc->initialRCQP.qpInterB =
av_clip(
930 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
933 rc->initialRCQP.qpInterB =
ctx->init_qp_b;
940 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
942 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
943 rc->constQP.qpInterB = 0;
944 rc->constQP.qpInterP = 0;
945 rc->constQP.qpIntra = 0;
954 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
957 case NV_ENC_PARAMS_RC_CONSTQP:
960 #ifndef NVENC_NO_DEPRECATED_RC
961 case NV_ENC_PARAMS_RC_VBR_MINQP:
962 if (avctx->
qmin < 0) {
964 "The variable bitrate rate-control requires "
965 "the 'qmin' option set.\n");
970 case NV_ENC_PARAMS_RC_VBR_HQ:
972 case NV_ENC_PARAMS_RC_VBR:
975 case NV_ENC_PARAMS_RC_CBR:
976 #ifndef NVENC_NO_DEPRECATED_RC
977 case NV_ENC_PARAMS_RC_CBR_HQ:
978 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
983 rc->rateControlMode =
ctx->rc;
992 int nb_surfaces =
FFMAX(4,
ctx->encode_config.frameIntervalP * 2 * 2);
995 if (
ctx->rc_lookahead > 0) {
998 nb_surfaces =
FFMAX(1,
FFMAX(nb_surfaces,
ctx->rc_lookahead +
ctx->encode_config.frameIntervalP + 1 + 4));
999 if (nb_surfaces >
ctx->nb_surfaces &&
ctx->nb_surfaces > 0)
1002 "Defined rc_lookahead requires more surfaces, "
1003 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
1005 ctx->nb_surfaces =
FFMAX(nb_surfaces,
ctx->nb_surfaces);
1007 if (
ctx->encode_config.frameIntervalP > 1 &&
ctx->nb_surfaces < nb_surfaces &&
ctx->nb_surfaces > 0)
1010 "Defined b-frame requires more surfaces, "
1011 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
1012 ctx->nb_surfaces =
FFMAX(
ctx->nb_surfaces, nb_surfaces);
1014 else if (
ctx->nb_surfaces <= 0)
1015 ctx->nb_surfaces = nb_surfaces;
1020 ctx->async_depth =
FFMIN(
ctx->async_depth,
ctx->nb_surfaces - 1);
1024 ctx->frame_data_array_nb =
FFMAX(
ctx->nb_surfaces,
ctx->nb_surfaces +
ctx->encode_config.frameIntervalP - 1);
1034 av_log(avctx,
AV_LOG_WARNING,
"Using global_quality with nvenc is deprecated. Use qp instead.\n");
1040 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate;
1041 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1042 ctx->encode_config.rcParams.maxBitRate =
ctx->encode_config.rcParams.averageBitRate;
1048 #ifdef NVENC_HAVE_MULTIPASS
1049 ctx->encode_config.rcParams.multiPass =
ctx->multipass;
1052 ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
1054 ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
1058 ctx->rc = NV_ENC_PARAMS_RC_CBR;
1059 }
else if (
ctx->cqp >= 0) {
1060 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
1061 }
else if (
ctx->quality >= 0.0f) {
1062 ctx->rc = NV_ENC_PARAMS_RC_VBR;
1072 if (
ctx->twopass < 0)
1077 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
1079 ctx->rc = NV_ENC_PARAMS_RC_CBR;
1081 }
else if (
ctx->cqp >= 0) {
1082 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
1083 }
else if (
ctx->twopass) {
1084 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
1085 }
else if (avctx->
qmin >= 0 && avctx->
qmax >= 0) {
1086 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
1098 #ifdef NVENC_HAVE_QP_CHROMA_OFFSETS
1099 ctx->encode_config.rcParams.cbQPIndexOffset =
ctx->qp_cb_offset;
1100 ctx->encode_config.rcParams.crQPIndexOffset =
ctx->qp_cr_offset;
1102 if (
ctx->qp_cb_offset ||
ctx->qp_cr_offset)
1103 av_log(avctx,
AV_LOG_WARNING,
"Failed setting QP CB/CR offsets, SDK 11.1 or greater required at compile time.\n");
1106 #ifdef NVENC_HAVE_LDKFS
1108 ctx->encode_config.rcParams.lowDelayKeyFrameScale =
ctx->ldkfs;
1113 }
else if (
ctx->rc >= 0) {
1116 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
1122 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1123 avctx->
rc_buffer_size =
ctx->encode_config.rcParams.vbvBufferSize = 2 *
ctx->encode_config.rcParams.averageBitRate;
1127 ctx->encode_config.rcParams.enableAQ = 1;
1128 ctx->encode_config.rcParams.aqStrength =
ctx->aq_strength;
1132 if (
ctx->temporal_aq) {
1133 ctx->encode_config.rcParams.enableTemporalAQ = 1;
1137 if (
ctx->rc_lookahead > 0) {
1138 int lkd_bound =
FFMIN(
ctx->nb_surfaces,
ctx->async_depth) -
1139 ctx->encode_config.frameIntervalP - 4;
1141 if (lkd_bound < 0) {
1142 ctx->encode_config.rcParams.enableLookahead = 0;
1144 "Lookahead not enabled. Increase buffer delay (-delay).\n");
1146 ctx->encode_config.rcParams.enableLookahead = 1;
1147 ctx->encode_config.rcParams.lookaheadDepth =
av_clip(
ctx->rc_lookahead, 0, lkd_bound);
1148 ctx->encode_config.rcParams.disableIadapt =
ctx->no_scenecut;
1149 ctx->encode_config.rcParams.disableBadapt = !
ctx->b_adapt;
1151 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
1152 ctx->encode_config.rcParams.lookaheadDepth,
1153 ctx->encode_config.rcParams.disableIadapt ?
"disabled" :
"enabled",
1154 ctx->encode_config.rcParams.disableBadapt ?
"disabled" :
"enabled");
1155 if (
ctx->encode_config.rcParams.lookaheadDepth <
ctx->rc_lookahead)
1156 av_log(avctx,
AV_LOG_WARNING,
"Clipping lookahead depth to %d (from %d) due to lack of surfaces/delay",
1157 ctx->encode_config.rcParams.lookaheadDepth,
ctx->rc_lookahead);
1159 #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
1160 if (
ctx->lookahead_level >= 0) {
1161 switch (
ctx->lookahead_level) {
1162 case NV_ENC_LOOKAHEAD_LEVEL_0:
1163 case NV_ENC_LOOKAHEAD_LEVEL_1:
1164 case NV_ENC_LOOKAHEAD_LEVEL_2:
1165 case NV_ENC_LOOKAHEAD_LEVEL_3:
1166 case NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT:
1173 ctx->encode_config.rcParams.lookaheadLevel =
ctx->lookahead_level;
1179 if (
ctx->strict_gop) {
1180 ctx->encode_config.rcParams.strictGOPTarget = 1;
1185 ctx->encode_config.rcParams.enableNonRefP = 1;
1187 if (
ctx->zerolatency)
1188 ctx->encode_config.rcParams.zeroReorderDelay = 1;
1192 int tmp_quality = (int)(
ctx->quality * 256.0f);
1193 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1194 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1199 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate = 0;
1210 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1211 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1212 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1219 vui->transferCharacteristics = avctx->
color_trc;
1220 vui->videoFullRangeFlag = 0;
1224 vui->transferCharacteristics = avctx->
color_trc;
1229 vui->colourDescriptionPresentFlag =
1230 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1232 vui->videoSignalTypePresentFlag =
1233 (vui->colourDescriptionPresentFlag
1234 || vui->videoFormat != 5
1235 || vui->videoFullRangeFlag != 0);
1237 if (
ctx->max_slice_size > 0) {
1238 h264->sliceMode = 1;
1239 h264->sliceModeData =
ctx->max_slice_size;
1241 h264->sliceMode = 3;
1242 h264->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1245 if (
ctx->intra_refresh) {
1246 h264->enableIntraRefresh = 1;
1247 h264->intraRefreshPeriod = cc->gopLength;
1248 h264->intraRefreshCnt = cc->gopLength - 1;
1249 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1250 #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
1251 h264->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1255 if (
ctx->constrained_encoding)
1256 h264->enableConstrainedEncoding = 1;
1260 h264->outputAUD =
ctx->aud;
1262 if (
ctx->dpb_size >= 0) {
1264 h264->maxNumRefFrames =
ctx->dpb_size;
1267 h264->idrPeriod = cc->gopLength;
1269 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1270 h264->outputBufferingPeriodSEI = 1;
1273 h264->outputPictureTimingSEI = 1;
1275 #ifndef NVENC_NO_DEPRECATED_RC
1276 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1277 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1278 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1279 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1280 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1285 h264->qpPrimeYZeroTransformBypassFlag = 1;
1287 switch(
ctx->profile) {
1289 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1293 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1297 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1301 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1309 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1315 h264->level =
ctx->level;
1317 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1318 h264->inputBitDepth = h264->outputBitDepth =
1319 IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1322 if (
ctx->coder >= 0)
1323 h264->entropyCodingMode =
ctx->coder;
1325 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1326 if (
ctx->b_ref_mode >= 0)
1327 h264->useBFramesAsRef =
ctx->b_ref_mode;
1330 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1331 h264->numRefL0 = avctx->
refs;
1332 h264->numRefL1 = avctx->
refs;
1341 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1342 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1343 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1350 vui->transferCharacteristics = avctx->
color_trc;
1351 vui->videoFullRangeFlag = 0;
1355 vui->transferCharacteristics = avctx->
color_trc;
1360 vui->colourDescriptionPresentFlag =
1361 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1363 vui->videoSignalTypePresentFlag =
1364 (vui->colourDescriptionPresentFlag
1365 || vui->videoFormat != 5
1366 || vui->videoFullRangeFlag != 0);
1368 if (
ctx->max_slice_size > 0) {
1369 hevc->sliceMode = 1;
1370 hevc->sliceModeData =
ctx->max_slice_size;
1372 hevc->sliceMode = 3;
1373 hevc->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1376 if (
ctx->intra_refresh) {
1377 hevc->enableIntraRefresh = 1;
1378 hevc->intraRefreshPeriod = cc->gopLength;
1379 hevc->intraRefreshCnt = cc->gopLength - 1;
1380 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1381 #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
1382 hevc->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1386 #ifdef NVENC_HAVE_HEVC_CONSTRAINED_ENCODING
1387 if (
ctx->constrained_encoding)
1388 hevc->enableConstrainedEncoding = 1;
1393 hevc->outputAUD =
ctx->aud;
1395 if (
ctx->dpb_size >= 0) {
1397 hevc->maxNumRefFramesInDPB =
ctx->dpb_size;
1400 hevc->idrPeriod = cc->gopLength;
1402 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1403 hevc->outputBufferingPeriodSEI = 1;
1406 hevc->outputPictureTimingSEI = 1;
1408 switch (
ctx->profile) {
1410 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1414 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1418 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1425 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1431 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1435 hevc->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1437 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1438 hevc->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1439 hevc->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1441 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1444 hevc->level =
ctx->level;
1446 hevc->tier =
ctx->tier;
1448 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1449 if (
ctx->b_ref_mode >= 0)
1450 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1453 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1454 hevc->numRefL0 = avctx->
refs;
1455 hevc->numRefL1 = avctx->
refs;
1458 #ifdef NVENC_HAVE_TEMPORAL_FILTER
1459 if (
ctx->tf_level >= 0) {
1460 hevc->tfLevel =
ctx->tf_level;
1462 switch (
ctx->tf_level)
1464 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1465 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1472 if (
ctx->encode_config.frameIntervalP < 5)
1480 #if CONFIG_AV1_NVENC_ENCODER
1484 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1485 NV_ENC_CONFIG_AV1 *av1 = &cc->encodeCodecConfig.av1Config;
1492 av1->transferCharacteristics = avctx->
color_trc;
1493 av1->colorRange = 0;
1497 av1->transferCharacteristics = avctx->
color_trc;
1503 av_log(avctx,
AV_LOG_ERROR,
"AV1 High Profile not supported, required for 4:4:4 encoding\n");
1506 cc->profileGUID = NV_ENC_AV1_PROFILE_MAIN_GUID;
1510 if (
ctx->dpb_size >= 0) {
1512 av1->maxNumRefFramesInDPB =
ctx->dpb_size;
1515 if (
ctx->intra_refresh) {
1516 av1->enableIntraRefresh = 1;
1517 av1->intraRefreshPeriod = cc->gopLength;
1518 av1->intraRefreshCnt = cc->gopLength - 1;
1519 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1522 av1->idrPeriod = cc->gopLength;
1524 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1525 av1->enableBitstreamPadding = 1;
1528 if (
ctx->tile_cols >= 0)
1529 av1->numTileColumns =
ctx->tile_cols;
1530 if (
ctx->tile_rows >= 0)
1531 av1->numTileRows =
ctx->tile_rows;
1533 av1->outputAnnexBFormat = 0;
1535 av1->level =
ctx->level;
1536 av1->tier =
ctx->tier;
1538 av1->enableTimingInfo =
ctx->timing_info;
1541 av1->disableSeqHdr = 0;
1542 av1->repeatSeqHdr = 1;
1544 av1->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1546 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1547 av1->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1548 av1->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1550 av1->inputPixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1551 av1->pixelBitDepthMinus8 = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? 2 : 0;
1554 if (
ctx->b_ref_mode >= 0)
1555 av1->useBFramesAsRef =
ctx->b_ref_mode;
1557 av1->numFwdRefs = avctx->
refs;
1558 av1->numBwdRefs = avctx->
refs;
1571 #if CONFIG_AV1_NVENC_ENCODER
1573 return nvenc_setup_av1_config(avctx);
1587 #if CONFIG_AV1_NVENC_ENCODER
1618 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1620 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1621 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1626 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1627 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1629 ctx->init_encode_params.encodeHeight = avctx->
height;
1630 ctx->init_encode_params.encodeWidth = avctx->
width;
1632 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1634 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1635 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1637 #ifdef NVENC_HAVE_NEW_PRESETS
1638 ctx->init_encode_params.tuningInfo =
ctx->tuning_info;
1641 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1643 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1645 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(
ctx->nvencoder,
1646 ctx->init_encode_params.encodeGUID,
1647 ctx->init_encode_params.presetGUID,
1648 ctx->init_encode_params.tuningInfo,
1651 nv_status = p_nvenc->nvEncGetEncodePresetConfig(
ctx->nvencoder,
1652 ctx->init_encode_params.encodeGUID,
1653 ctx->init_encode_params.presetGUID,
1656 if (nv_status != NV_ENC_SUCCESS)
1657 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1659 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1661 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1664 ctx->init_encode_params.darHeight = dh;
1665 ctx->init_encode_params.darWidth = dw;
1674 #if FF_API_TICKS_PER_FRAME
1681 #ifdef NVENC_HAVE_UNIDIR_B
1682 ctx->init_encode_params.enableUniDirectionalB =
ctx->unidir_b;
1685 ctx->init_encode_params.enableEncodeAsync = 0;
1686 ctx->init_encode_params.enablePTD = 1;
1688 #ifdef NVENC_HAVE_NEW_PRESETS
1692 if (
ctx->rc_lookahead == 0 &&
ctx->encode_config.rcParams.enableLookahead)
1693 ctx->rc_lookahead =
ctx->encode_config.rcParams.lookaheadDepth;
1696 if (
ctx->weighted_pred == 1)
1697 ctx->init_encode_params.enableWeightedPrediction = 1;
1699 #ifdef NVENC_HAVE_SPLIT_FRAME_ENCODING
1700 ctx->init_encode_params.splitEncodeMode =
ctx->split_encode_mode;
1702 if (
ctx->split_encode_mode != NV_ENC_SPLIT_DISABLE_MODE) {
1704 av_log(avctx,
AV_LOG_WARNING,
"Split encoding not supported with weighted prediction enabled.\n");
1708 if (
ctx->bluray_compat) {
1717 ctx->level = NV_ENC_LEVEL_HEVC_51;
1718 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1727 ctx->encode_config.frameIntervalP = 0;
1728 ctx->encode_config.gopLength = 1;
1737 if(
ctx->single_slice_intra_refresh)
1738 ctx->intra_refresh = 1;
1747 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1749 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1760 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1761 if (nv_status != NV_ENC_SUCCESS) {
1766 #ifdef NVENC_HAVE_CUSTREAM_PTR
1767 if (
ctx->cu_context) {
1768 nv_status = p_nvenc->nvEncSetIOCudaStreams(
ctx->nvencoder, &
ctx->cu_stream, &
ctx->cu_stream);
1769 if (nv_status != NV_ENC_SUCCESS) {
1780 if (
ctx->encode_config.frameIntervalP > 1)
1783 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1784 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1791 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1800 return NV_ENC_BUFFER_FORMAT_YV12;
1802 return NV_ENC_BUFFER_FORMAT_NV12;
1805 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1808 return NV_ENC_BUFFER_FORMAT_YUV444;
1811 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1814 return NV_ENC_BUFFER_FORMAT_ARGB;
1817 return NV_ENC_BUFFER_FORMAT_ABGR;
1819 return NV_ENC_BUFFER_FORMAT_ARGB10;
1821 return NV_ENC_BUFFER_FORMAT_ABGR10;
1823 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1831 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1834 NVENCSTATUS nv_status;
1835 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1836 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1840 if (!
ctx->surfaces[idx].in_ref)
1843 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1846 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1852 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1853 allocSurf.width = avctx->
width;
1854 allocSurf.height = avctx->
height;
1855 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1857 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
1858 if (nv_status != NV_ENC_SUCCESS) {
1862 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1863 ctx->surfaces[idx].width = allocSurf.width;
1864 ctx->surfaces[idx].height = allocSurf.height;
1867 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
1868 if (nv_status != NV_ENC_SUCCESS) {
1871 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
1876 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1886 int i, res = 0, res2;
1892 ctx->frame_data_array =
av_calloc(
ctx->frame_data_array_nb,
sizeof(*
ctx->frame_data_array));
1893 if (!
ctx->frame_data_array)
1898 if (!
ctx->timestamp_list)
1902 if (!
ctx->unused_surface_queue)
1906 if (!
ctx->output_surface_queue)
1909 if (!
ctx->output_surface_ready_queue)
1916 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
1933 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1935 NVENCSTATUS nv_status;
1936 uint32_t outSize = 0;
1937 char tmpHeader[NV_MAX_SEQ_HDR_LEN];
1939 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1940 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1942 payload.spsppsBuffer = tmpHeader;
1943 payload.inBufferSize =
sizeof(tmpHeader);
1944 payload.outSPSPPSPayloadSize = &outSize;
1946 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
1947 if (nv_status != NV_ENC_SUCCESS) {
1958 memcpy(avctx->
extradata, tmpHeader, outSize);
1967 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1971 if (
ctx->nvencoder) {
1972 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1973 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1979 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, ¶ms);
1987 if (
ctx->frame_data_array) {
1988 for (
i = 0;
i <
ctx->frame_data_array_nb;
i++)
1994 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1995 if (
ctx->registered_frames[
i].mapped)
1996 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
1997 if (
ctx->registered_frames[
i].regptr)
1998 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2000 ctx->nb_registered_frames = 0;
2003 if (
ctx->surfaces) {
2004 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
2006 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
2008 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
2012 ctx->nb_surfaces = 0;
2018 if (
ctx->nvencoder) {
2019 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
2027 if (
ctx->cu_context_internal)
2029 ctx->cu_context =
ctx->cu_context_internal =
NULL;
2032 if (
ctx->d3d11_device) {
2033 ID3D11Device_Release(
ctx->d3d11_device);
2038 nvenc_free_functions(&dl_fn->
nvenc_dl);
2039 cuda_free_functions(&dl_fn->
cuda_dl);
2057 "hw_frames_ctx must be set when using GPU frames as input\n");
2063 "hw_frames_ctx must match the GPU frame type\n");
2112 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
2114 int dst_linesize[4] = {
2115 lock_buffer_params->pitch,
2116 lock_buffer_params->pitch,
2117 lock_buffer_params->pitch,
2118 lock_buffer_params->pitch
2120 uint8_t *dst_data[4];
2124 dst_linesize[1] = dst_linesize[2] >>= 1;
2127 lock_buffer_params->bufferDataPtr, dst_linesize);
2132 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
2145 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2146 NVENCSTATUS nv_status;
2151 for (first_round = 1; first_round >= 0; first_round--) {
2152 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2153 if (!
ctx->registered_frames[
i].mapped) {
2154 if (
ctx->registered_frames[
i].regptr) {
2157 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2158 if (nv_status != NV_ENC_SUCCESS)
2159 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
2160 ctx->registered_frames[
i].ptr =
NULL;
2161 ctx->registered_frames[
i].regptr =
NULL;
2168 return ctx->nb_registered_frames++;
2179 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2182 NV_ENC_REGISTER_RESOURCE reg = { 0 };
2185 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2196 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
2197 reg.width = frames_ctx->width;
2198 reg.height = frames_ctx->height;
2199 reg.pitch =
frame->linesize[0];
2200 reg.resourceToRegister =
frame->data[0];
2203 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
2206 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
2207 reg.subResourceIndex = (intptr_t)
frame->data[1];
2211 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
2217 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
2218 if (
ret != NV_ENC_SUCCESS) {
2223 ctx->registered_frames[idx].ptr =
frame->data[0];
2224 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
2225 ctx->registered_frames[idx].regptr = reg.registeredResource;
2234 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2237 NVENCSTATUS nv_status;
2250 if (!
ctx->registered_frames[reg_idx].mapped) {
2251 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
2252 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
2253 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
2254 if (nv_status != NV_ENC_SUCCESS) {
2260 ctx->registered_frames[reg_idx].mapped += 1;
2262 nvenc_frame->
reg_idx = reg_idx;
2263 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
2264 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
2269 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
2271 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
2274 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
2275 if (nv_status != NV_ENC_SUCCESS) {
2276 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
2279 nvenc_frame->
pitch = lockBufferParams.pitch;
2282 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
2283 if (nv_status != NV_ENC_SUCCESS) {
2292 NV_ENC_PIC_PARAMS *params,
2293 NV_ENC_SEI_PAYLOAD *sei_data,
2300 params->codecPicParams.h264PicParams.sliceMode =
2301 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
2302 params->codecPicParams.h264PicParams.sliceModeData =
2303 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
2304 if (sei_count > 0) {
2305 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
2306 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
2311 params->codecPicParams.hevcPicParams.sliceMode =
2312 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
2313 params->codecPicParams.hevcPicParams.sliceModeData =
2314 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
2315 if (sei_count > 0) {
2316 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
2317 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
2321 #if CONFIG_AV1_NVENC_ENCODER
2323 params->codecPicParams.av1PicParams.numTileColumns =
2324 ctx->encode_config.encodeCodecConfig.av1Config.numTileColumns;
2325 params->codecPicParams.av1PicParams.numTileRows =
2326 ctx->encode_config.encodeCodecConfig.av1Config.numTileRows;
2327 if (sei_count > 0) {
2328 params->codecPicParams.av1PicParams.obuPayloadArray = sei_data;
2329 params->codecPicParams.av1PicParams.obuPayloadArrayCnt = sei_count;
2360 NV_ENC_LOCK_BITSTREAM *params,
2367 pkt->
pts = params->outputTimeStamp;
2375 delay =
FFMAX(
ctx->encode_config.frameIntervalP - 1, 0);
2376 if (
ctx->output_frame_num >= delay) {
2378 ctx->output_frame_num++;
2382 delay_time =
ctx->initial_delay_time;
2390 delay_time = t1 - t2;
2395 delay_time = delay * (t3 - t2);
2399 ctx->initial_delay_time = delay_time;
2408 ctx->output_frame_num++;
2418 int idx =
ctx->frame_data_array_pos;
2433 ctx->frame_data_array_pos = (
ctx->frame_data_array_pos + 1) %
ctx->frame_data_array_nb;
2434 pic_params->inputDuration = idx;
2444 int idx = lock_params->outputDuration;
2464 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2466 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
2467 NVENCSTATUS nv_status;
2472 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
2474 lock_params.doNotWait = 0;
2477 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
2478 if (nv_status != NV_ENC_SUCCESS) {
2490 memcpy(
pkt->
data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
2492 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
2493 if (nv_status != NV_ENC_SUCCESS) {
2494 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
2500 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
2501 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
2502 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
2503 if (nv_status != NV_ENC_SUCCESS) {
2507 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
2517 switch (lock_params.pictureType) {
2518 case NV_ENC_PIC_TYPE_IDR:
2520 case NV_ENC_PIC_TYPE_I:
2523 case NV_ENC_PIC_TYPE_P:
2526 case NV_ENC_PIC_TYPE_B:
2529 case NV_ENC_PIC_TYPE_BI:
2533 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
2534 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
2562 int nb_ready, nb_pending;
2567 return nb_ready > 0;
2568 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
2578 void *a53_data =
NULL;
2579 size_t a53_size = 0;
2587 &
ctx->sei_data_size,
2588 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2595 ctx->sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2596 ctx->sei_data[sei_count].payload = (uint8_t*)a53_data;
2598 #if CONFIG_AV1_NVENC_ENCODER
2611 void *tc_data =
NULL;
2620 &
ctx->sei_data_size,
2621 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2628 ctx->sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2629 ctx->sei_data[sei_count].payload = (uint8_t*)tc_data;
2631 #if CONFIG_AV1_NVENC_ENCODER
2646 for (
i = 0;
i <
frame->nb_side_data;
i++) {
2654 &
ctx->sei_data_size,
2655 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2661 ctx->sei_data[sei_count].payloadSize = side_data->
size;
2665 if (!
ctx->sei_data[sei_count].payload) {
2677 for (
i = 0;
i < sei_count;
i++)
2686 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
2689 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2690 int needs_reconfig = 0;
2691 int needs_encode_config = 0;
2692 int reconfig_bitrate = 0, reconfig_dar = 0;
2695 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2696 params.reInitEncodeParams =
ctx->init_encode_params;
2699 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
2701 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2702 ctx->init_encode_params.darWidth,
2703 ctx->init_encode_params.darHeight, dw, dh);
2705 params.reInitEncodeParams.darHeight = dh;
2706 params.reInitEncodeParams.darWidth = dw;
2712 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
2713 if (avctx->
bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
2715 "avg bitrate change: %d -> %d\n",
2716 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2719 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
2720 reconfig_bitrate = 1;
2725 "max bitrate change: %d -> %d\n",
2726 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2729 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
2730 reconfig_bitrate = 1;
2735 "vbv buffer size change: %d -> %d\n",
2736 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2739 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->
rc_buffer_size;
2740 reconfig_bitrate = 1;
2743 if (reconfig_bitrate) {
2744 params.resetEncoder = 1;
2745 params.forceIDR = 1;
2747 needs_encode_config = 1;
2752 if (!needs_encode_config)
2753 params.reInitEncodeParams.encodeConfig =
NULL;
2755 if (needs_reconfig) {
2756 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, ¶ms);
2757 if (
ret != NV_ENC_SUCCESS) {
2761 ctx->init_encode_params.darHeight = dh;
2762 ctx->init_encode_params.darWidth = dw;
2765 if (reconfig_bitrate) {
2766 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2767 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2768 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2777 NVENCSTATUS nv_status;
2785 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2787 NV_ENC_PIC_PARAMS pic_params = { 0 };
2788 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2790 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2814 pic_params.bufferFmt = in_surf->
format;
2815 pic_params.inputWidth = in_surf->
width;
2816 pic_params.inputHeight = in_surf->
height;
2817 pic_params.inputPitch = in_surf->
pitch;
2822 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2824 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2826 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2830 pic_params.encodePicFlags =
2831 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2833 pic_params.encodePicFlags = 0;
2836 pic_params.frameIdx =
ctx->frame_idx_counter++;
2837 pic_params.inputTimeStamp =
frame->pts;
2839 if (
ctx->extra_sei) {
2852 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2859 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
2861 for (
i = 0;
i < sei_count;
i++)
2868 if (nv_status != NV_ENC_SUCCESS &&
2869 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2880 if (nv_status == NV_ENC_SUCCESS) {
2881 while (
av_fifo_read(
ctx->output_surface_queue, &tmp_out_surf, 1) >= 0)
2897 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2900 if (!
frame->buf[0]) {
2945 ctx->output_frame_num = 0;
2946 ctx->initial_delay_time = 0;