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;
1317 h264->level =
ctx->level;
1319 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1320 h264->inputBitDepth = h264->outputBitDepth =
1321 IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1324 if (
ctx->coder >= 0)
1325 h264->entropyCodingMode =
ctx->coder;
1327 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1328 if (
ctx->b_ref_mode >= 0)
1329 h264->useBFramesAsRef =
ctx->b_ref_mode;
1332 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1333 h264->numRefL0 = avctx->
refs;
1334 h264->numRefL1 = avctx->
refs;
1343 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1344 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1345 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1352 vui->transferCharacteristics = avctx->
color_trc;
1353 vui->videoFullRangeFlag = 0;
1357 vui->transferCharacteristics = avctx->
color_trc;
1362 vui->colourDescriptionPresentFlag =
1363 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1365 vui->videoSignalTypePresentFlag =
1366 (vui->colourDescriptionPresentFlag
1367 || vui->videoFormat != 5
1368 || vui->videoFullRangeFlag != 0);
1370 if (
ctx->max_slice_size > 0) {
1371 hevc->sliceMode = 1;
1372 hevc->sliceModeData =
ctx->max_slice_size;
1374 hevc->sliceMode = 3;
1375 hevc->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1378 if (
ctx->intra_refresh) {
1379 hevc->enableIntraRefresh = 1;
1380 hevc->intraRefreshPeriod = cc->gopLength;
1381 hevc->intraRefreshCnt = cc->gopLength - 1;
1382 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1383 #ifdef NVENC_HAVE_SINGLE_SLICE_INTRA_REFRESH
1384 hevc->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1388 #ifdef NVENC_HAVE_HEVC_CONSTRAINED_ENCODING
1389 if (
ctx->constrained_encoding)
1390 hevc->enableConstrainedEncoding = 1;
1395 hevc->outputAUD =
ctx->aud;
1397 if (
ctx->dpb_size >= 0) {
1399 hevc->maxNumRefFramesInDPB =
ctx->dpb_size;
1402 hevc->idrPeriod = cc->gopLength;
1404 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1405 hevc->outputBufferingPeriodSEI = 1;
1408 hevc->outputPictureTimingSEI = 1;
1410 switch (
ctx->profile) {
1412 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1416 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1420 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1427 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1433 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1437 hevc->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1439 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1440 hevc->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1441 hevc->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1443 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1446 hevc->level =
ctx->level;
1448 hevc->tier =
ctx->tier;
1450 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1451 if (
ctx->b_ref_mode >= 0)
1452 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1455 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1456 hevc->numRefL0 = avctx->
refs;
1457 hevc->numRefL1 = avctx->
refs;
1460 #ifdef NVENC_HAVE_TEMPORAL_FILTER
1461 if (
ctx->tf_level >= 0) {
1462 hevc->tfLevel =
ctx->tf_level;
1464 switch (
ctx->tf_level)
1466 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1467 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1474 if (
ctx->encode_config.frameIntervalP < 5)
1482 #if CONFIG_AV1_NVENC_ENCODER
1486 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1487 NV_ENC_CONFIG_AV1 *av1 = &cc->encodeCodecConfig.av1Config;
1494 av1->transferCharacteristics = avctx->
color_trc;
1495 av1->colorRange = 0;
1499 av1->transferCharacteristics = avctx->
color_trc;
1505 av_log(avctx,
AV_LOG_ERROR,
"AV1 High Profile not supported, required for 4:4:4 encoding\n");
1508 cc->profileGUID = NV_ENC_AV1_PROFILE_MAIN_GUID;
1512 if (
ctx->dpb_size >= 0) {
1514 av1->maxNumRefFramesInDPB =
ctx->dpb_size;
1517 if (
ctx->intra_refresh) {
1518 av1->enableIntraRefresh = 1;
1519 av1->intraRefreshPeriod = cc->gopLength;
1520 av1->intraRefreshCnt = cc->gopLength - 1;
1521 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1524 av1->idrPeriod = cc->gopLength;
1526 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1527 av1->enableBitstreamPadding = 1;
1530 if (
ctx->tile_cols >= 0)
1531 av1->numTileColumns =
ctx->tile_cols;
1532 if (
ctx->tile_rows >= 0)
1533 av1->numTileRows =
ctx->tile_rows;
1535 av1->outputAnnexBFormat = 0;
1537 av1->level =
ctx->level;
1538 av1->tier =
ctx->tier;
1540 av1->enableTimingInfo =
ctx->timing_info;
1543 av1->disableSeqHdr = 0;
1544 av1->repeatSeqHdr = 1;
1546 av1->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1548 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1549 av1->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1550 av1->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1552 av1->inputPixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1553 av1->pixelBitDepthMinus8 = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? 2 : 0;
1556 if (
ctx->b_ref_mode >= 0)
1557 av1->useBFramesAsRef =
ctx->b_ref_mode;
1559 av1->numFwdRefs = avctx->
refs;
1560 av1->numBwdRefs = avctx->
refs;
1573 #if CONFIG_AV1_NVENC_ENCODER
1575 return nvenc_setup_av1_config(avctx);
1589 #if CONFIG_AV1_NVENC_ENCODER
1620 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1622 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1623 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1628 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1629 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1631 ctx->init_encode_params.encodeHeight = avctx->
height;
1632 ctx->init_encode_params.encodeWidth = avctx->
width;
1634 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1636 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1637 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1639 #ifdef NVENC_HAVE_NEW_PRESETS
1640 ctx->init_encode_params.tuningInfo =
ctx->tuning_info;
1643 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1645 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1647 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(
ctx->nvencoder,
1648 ctx->init_encode_params.encodeGUID,
1649 ctx->init_encode_params.presetGUID,
1650 ctx->init_encode_params.tuningInfo,
1653 nv_status = p_nvenc->nvEncGetEncodePresetConfig(
ctx->nvencoder,
1654 ctx->init_encode_params.encodeGUID,
1655 ctx->init_encode_params.presetGUID,
1658 if (nv_status != NV_ENC_SUCCESS)
1659 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1661 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1663 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1666 ctx->init_encode_params.darHeight = dh;
1667 ctx->init_encode_params.darWidth = dw;
1676 #if FF_API_TICKS_PER_FRAME
1683 #ifdef NVENC_HAVE_UNIDIR_B
1684 ctx->init_encode_params.enableUniDirectionalB =
ctx->unidir_b;
1687 ctx->init_encode_params.enableEncodeAsync = 0;
1688 ctx->init_encode_params.enablePTD = 1;
1690 #ifdef NVENC_HAVE_NEW_PRESETS
1694 if (
ctx->rc_lookahead == 0 &&
ctx->encode_config.rcParams.enableLookahead)
1695 ctx->rc_lookahead =
ctx->encode_config.rcParams.lookaheadDepth;
1698 if (
ctx->weighted_pred == 1)
1699 ctx->init_encode_params.enableWeightedPrediction = 1;
1701 #ifdef NVENC_HAVE_SPLIT_FRAME_ENCODING
1702 ctx->init_encode_params.splitEncodeMode =
ctx->split_encode_mode;
1704 if (
ctx->split_encode_mode != NV_ENC_SPLIT_DISABLE_MODE) {
1706 av_log(avctx,
AV_LOG_WARNING,
"Split encoding not supported with weighted prediction enabled.\n");
1710 if (
ctx->bluray_compat) {
1719 ctx->level = NV_ENC_LEVEL_HEVC_51;
1720 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1729 ctx->encode_config.frameIntervalP = 0;
1730 ctx->encode_config.gopLength = 1;
1739 if(
ctx->single_slice_intra_refresh)
1740 ctx->intra_refresh = 1;
1749 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1751 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1762 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1763 if (nv_status != NV_ENC_SUCCESS) {
1768 #ifdef NVENC_HAVE_CUSTREAM_PTR
1769 if (
ctx->cu_context) {
1770 nv_status = p_nvenc->nvEncSetIOCudaStreams(
ctx->nvencoder, &
ctx->cu_stream, &
ctx->cu_stream);
1771 if (nv_status != NV_ENC_SUCCESS) {
1782 if (
ctx->encode_config.frameIntervalP > 1)
1785 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1786 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1793 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1802 return NV_ENC_BUFFER_FORMAT_YV12;
1804 return NV_ENC_BUFFER_FORMAT_NV12;
1807 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1810 return NV_ENC_BUFFER_FORMAT_YUV444;
1813 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1816 return NV_ENC_BUFFER_FORMAT_ARGB;
1819 return NV_ENC_BUFFER_FORMAT_ABGR;
1821 return NV_ENC_BUFFER_FORMAT_ARGB10;
1823 return NV_ENC_BUFFER_FORMAT_ABGR10;
1825 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1833 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1836 NVENCSTATUS nv_status;
1837 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1838 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1842 if (!
ctx->surfaces[idx].in_ref)
1845 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1848 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1854 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1855 allocSurf.width = avctx->
width;
1856 allocSurf.height = avctx->
height;
1857 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1859 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
1860 if (nv_status != NV_ENC_SUCCESS) {
1864 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1865 ctx->surfaces[idx].width = allocSurf.width;
1866 ctx->surfaces[idx].height = allocSurf.height;
1869 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
1870 if (nv_status != NV_ENC_SUCCESS) {
1873 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
1878 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1888 int i, res = 0, res2;
1894 ctx->frame_data_array =
av_calloc(
ctx->frame_data_array_nb,
sizeof(*
ctx->frame_data_array));
1895 if (!
ctx->frame_data_array)
1900 if (!
ctx->timestamp_list)
1904 if (!
ctx->unused_surface_queue)
1908 if (!
ctx->output_surface_queue)
1911 if (!
ctx->output_surface_ready_queue)
1918 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
1935 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1937 NVENCSTATUS nv_status;
1938 uint32_t outSize = 0;
1939 char tmpHeader[NV_MAX_SEQ_HDR_LEN];
1941 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1942 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1944 payload.spsppsBuffer = tmpHeader;
1945 payload.inBufferSize =
sizeof(tmpHeader);
1946 payload.outSPSPPSPayloadSize = &outSize;
1948 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
1949 if (nv_status != NV_ENC_SUCCESS) {
1960 memcpy(avctx->
extradata, tmpHeader, outSize);
1969 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1973 if (
ctx->nvencoder) {
1974 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1975 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1981 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, ¶ms);
1989 if (
ctx->frame_data_array) {
1990 for (
i = 0;
i <
ctx->frame_data_array_nb;
i++)
1996 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1997 if (
ctx->registered_frames[
i].mapped)
1998 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
1999 if (
ctx->registered_frames[
i].regptr)
2000 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2002 ctx->nb_registered_frames = 0;
2005 if (
ctx->surfaces) {
2006 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
2008 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
2010 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
2014 ctx->nb_surfaces = 0;
2020 if (
ctx->nvencoder) {
2021 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
2029 if (
ctx->cu_context_internal)
2031 ctx->cu_context =
ctx->cu_context_internal =
NULL;
2034 if (
ctx->d3d11_device) {
2035 ID3D11Device_Release(
ctx->d3d11_device);
2040 nvenc_free_functions(&dl_fn->
nvenc_dl);
2041 cuda_free_functions(&dl_fn->
cuda_dl);
2059 "hw_frames_ctx must be set when using GPU frames as input\n");
2065 "hw_frames_ctx must match the GPU frame type\n");
2114 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
2116 int dst_linesize[4] = {
2117 lock_buffer_params->pitch,
2118 lock_buffer_params->pitch,
2119 lock_buffer_params->pitch,
2120 lock_buffer_params->pitch
2122 uint8_t *dst_data[4];
2126 dst_linesize[1] = dst_linesize[2] >>= 1;
2129 lock_buffer_params->bufferDataPtr, dst_linesize);
2134 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
2147 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2148 NVENCSTATUS nv_status;
2153 for (first_round = 1; first_round >= 0; first_round--) {
2154 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2155 if (!
ctx->registered_frames[
i].mapped) {
2156 if (
ctx->registered_frames[
i].regptr) {
2159 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2160 if (nv_status != NV_ENC_SUCCESS)
2161 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
2162 ctx->registered_frames[
i].ptr =
NULL;
2163 ctx->registered_frames[
i].regptr =
NULL;
2170 return ctx->nb_registered_frames++;
2181 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2184 NV_ENC_REGISTER_RESOURCE reg = { 0 };
2187 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2198 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
2199 reg.width = frames_ctx->width;
2200 reg.height = frames_ctx->height;
2201 reg.pitch =
frame->linesize[0];
2202 reg.resourceToRegister =
frame->data[0];
2205 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
2208 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
2209 reg.subResourceIndex = (intptr_t)
frame->data[1];
2213 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
2219 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
2220 if (
ret != NV_ENC_SUCCESS) {
2225 ctx->registered_frames[idx].ptr =
frame->data[0];
2226 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
2227 ctx->registered_frames[idx].regptr = reg.registeredResource;
2236 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2239 NVENCSTATUS nv_status;
2252 if (!
ctx->registered_frames[reg_idx].mapped) {
2253 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
2254 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
2255 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
2256 if (nv_status != NV_ENC_SUCCESS) {
2262 ctx->registered_frames[reg_idx].mapped += 1;
2264 nvenc_frame->
reg_idx = reg_idx;
2265 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
2266 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
2271 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
2273 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
2276 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
2277 if (nv_status != NV_ENC_SUCCESS) {
2278 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
2281 nvenc_frame->
pitch = lockBufferParams.pitch;
2284 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
2285 if (nv_status != NV_ENC_SUCCESS) {
2294 NV_ENC_PIC_PARAMS *params,
2295 NV_ENC_SEI_PAYLOAD *sei_data,
2302 params->codecPicParams.h264PicParams.sliceMode =
2303 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
2304 params->codecPicParams.h264PicParams.sliceModeData =
2305 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
2306 if (sei_count > 0) {
2307 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
2308 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
2313 params->codecPicParams.hevcPicParams.sliceMode =
2314 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
2315 params->codecPicParams.hevcPicParams.sliceModeData =
2316 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
2317 if (sei_count > 0) {
2318 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
2319 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
2323 #if CONFIG_AV1_NVENC_ENCODER
2325 params->codecPicParams.av1PicParams.numTileColumns =
2326 ctx->encode_config.encodeCodecConfig.av1Config.numTileColumns;
2327 params->codecPicParams.av1PicParams.numTileRows =
2328 ctx->encode_config.encodeCodecConfig.av1Config.numTileRows;
2329 if (sei_count > 0) {
2330 params->codecPicParams.av1PicParams.obuPayloadArray = sei_data;
2331 params->codecPicParams.av1PicParams.obuPayloadArrayCnt = sei_count;
2362 NV_ENC_LOCK_BITSTREAM *params,
2369 pkt->
pts = params->outputTimeStamp;
2377 delay =
FFMAX(
ctx->encode_config.frameIntervalP - 1, 0);
2378 if (
ctx->output_frame_num >= delay) {
2380 ctx->output_frame_num++;
2384 delay_time =
ctx->initial_delay_time;
2392 delay_time = t1 - t2;
2397 delay_time = delay * (t3 - t2);
2401 ctx->initial_delay_time = delay_time;
2410 ctx->output_frame_num++;
2420 int idx =
ctx->frame_data_array_pos;
2435 ctx->frame_data_array_pos = (
ctx->frame_data_array_pos + 1) %
ctx->frame_data_array_nb;
2436 pic_params->inputDuration = idx;
2446 int idx = lock_params->outputDuration;
2466 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2468 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
2469 NVENCSTATUS nv_status;
2474 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
2476 lock_params.doNotWait = 0;
2479 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
2480 if (nv_status != NV_ENC_SUCCESS) {
2492 memcpy(
pkt->
data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
2494 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
2495 if (nv_status != NV_ENC_SUCCESS) {
2496 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
2502 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
2503 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
2504 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
2505 if (nv_status != NV_ENC_SUCCESS) {
2509 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
2519 switch (lock_params.pictureType) {
2520 case NV_ENC_PIC_TYPE_IDR:
2522 case NV_ENC_PIC_TYPE_I:
2525 case NV_ENC_PIC_TYPE_P:
2528 case NV_ENC_PIC_TYPE_B:
2531 case NV_ENC_PIC_TYPE_BI:
2535 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
2536 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
2564 int nb_ready, nb_pending;
2569 return nb_ready > 0;
2570 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
2580 void *a53_data =
NULL;
2581 size_t a53_size = 0;
2589 &
ctx->sei_data_size,
2590 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2597 ctx->sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2598 ctx->sei_data[sei_count].payload = (uint8_t*)a53_data;
2600 #if CONFIG_AV1_NVENC_ENCODER
2613 void *tc_data =
NULL;
2622 &
ctx->sei_data_size,
2623 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2630 ctx->sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2631 ctx->sei_data[sei_count].payload = (uint8_t*)tc_data;
2633 #if CONFIG_AV1_NVENC_ENCODER
2648 for (
i = 0;
i <
frame->nb_side_data;
i++) {
2656 &
ctx->sei_data_size,
2657 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2663 ctx->sei_data[sei_count].payloadSize = side_data->
size;
2667 if (!
ctx->sei_data[sei_count].payload) {
2679 for (
i = 0;
i < sei_count;
i++)
2688 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
2691 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2692 int needs_reconfig = 0;
2693 int needs_encode_config = 0;
2694 int reconfig_bitrate = 0, reconfig_dar = 0;
2697 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2698 params.reInitEncodeParams =
ctx->init_encode_params;
2701 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
2703 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2704 ctx->init_encode_params.darWidth,
2705 ctx->init_encode_params.darHeight, dw, dh);
2707 params.reInitEncodeParams.darHeight = dh;
2708 params.reInitEncodeParams.darWidth = dw;
2714 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
2715 if (avctx->
bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
2717 "avg bitrate change: %d -> %d\n",
2718 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2721 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
2722 reconfig_bitrate = 1;
2727 "max bitrate change: %d -> %d\n",
2728 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2731 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
2732 reconfig_bitrate = 1;
2737 "vbv buffer size change: %d -> %d\n",
2738 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2741 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->
rc_buffer_size;
2742 reconfig_bitrate = 1;
2745 if (reconfig_bitrate) {
2746 params.resetEncoder = 1;
2747 params.forceIDR = 1;
2749 needs_encode_config = 1;
2754 if (!needs_encode_config)
2755 params.reInitEncodeParams.encodeConfig =
NULL;
2757 if (needs_reconfig) {
2758 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, ¶ms);
2759 if (
ret != NV_ENC_SUCCESS) {
2763 ctx->init_encode_params.darHeight = dh;
2764 ctx->init_encode_params.darWidth = dw;
2767 if (reconfig_bitrate) {
2768 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2769 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2770 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2779 NVENCSTATUS nv_status;
2787 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2789 NV_ENC_PIC_PARAMS pic_params = { 0 };
2790 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2792 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2816 pic_params.bufferFmt = in_surf->
format;
2817 pic_params.inputWidth = in_surf->
width;
2818 pic_params.inputHeight = in_surf->
height;
2819 pic_params.inputPitch = in_surf->
pitch;
2824 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2826 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2828 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2832 pic_params.encodePicFlags =
2833 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2835 pic_params.encodePicFlags = 0;
2838 pic_params.frameIdx =
ctx->frame_idx_counter++;
2839 pic_params.inputTimeStamp =
frame->pts;
2841 if (
ctx->extra_sei) {
2854 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2861 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
2863 for (
i = 0;
i < sei_count;
i++)
2870 if (nv_status != NV_ENC_SUCCESS &&
2871 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2882 if (nv_status == NV_ENC_SUCCESS) {
2883 while (
av_fifo_read(
ctx->output_surface_queue, &tmp_out_surf, 1) >= 0)
2899 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2902 if (!
frame->buf[0]) {
2947 ctx->output_frame_num = 0;
2948 ctx->initial_delay_time = 0;