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)
60 #ifdef NVENC_HAVE_422_SUPPORT
95 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
96 pix_fmt == AV_PIX_FMT_P012 || \
97 pix_fmt == AV_PIX_FMT_P016 || \
98 pix_fmt == AV_PIX_FMT_P210 || \
99 pix_fmt == AV_PIX_FMT_P212 || \
100 pix_fmt == AV_PIX_FMT_P216 || \
101 pix_fmt == AV_PIX_FMT_YUV444P10MSB || \
102 pix_fmt == AV_PIX_FMT_YUV444P12MSB || \
103 pix_fmt == AV_PIX_FMT_YUV444P16 || \
104 pix_fmt == AV_PIX_FMT_X2RGB10 || \
105 pix_fmt == AV_PIX_FMT_X2BGR10 || \
106 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
107 pix_fmt == AV_PIX_FMT_GBRP16)
109 #define IS_RGB(pix_fmt) (pix_fmt == AV_PIX_FMT_0RGB32 || \
110 pix_fmt == AV_PIX_FMT_RGB32 || \
111 pix_fmt == AV_PIX_FMT_0BGR32 || \
112 pix_fmt == AV_PIX_FMT_BGR32 || \
113 pix_fmt == AV_PIX_FMT_X2RGB10 || \
114 pix_fmt == AV_PIX_FMT_X2BGR10)
116 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
117 pix_fmt == AV_PIX_FMT_YUV444P10MSB || \
118 pix_fmt == AV_PIX_FMT_YUV444P12MSB || \
119 pix_fmt == AV_PIX_FMT_YUV444P16 || \
120 pix_fmt == AV_PIX_FMT_GBRP || \
121 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
122 pix_fmt == AV_PIX_FMT_GBRP16 || \
123 (ctx->rgb_mode == NVENC_RGB_MODE_444 && IS_RGB(pix_fmt)))
125 #define IS_YUV422(pix_fmt) (pix_fmt == AV_PIX_FMT_NV16 || \
126 pix_fmt == AV_PIX_FMT_P210 || \
127 pix_fmt == AV_PIX_FMT_P212 || \
128 pix_fmt == AV_PIX_FMT_P216)
130 #define IS_GBRP(pix_fmt) (pix_fmt == AV_PIX_FMT_GBRP || \
131 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
132 pix_fmt == AV_PIX_FMT_GBRP16)
134 static const struct {
139 { NV_ENC_SUCCESS, 0,
"success" },
140 { NV_ENC_ERR_NO_ENCODE_DEVICE,
AVERROR(ENOENT),
"no encode device" },
141 { NV_ENC_ERR_UNSUPPORTED_DEVICE,
AVERROR(ENOSYS),
"unsupported device" },
142 { NV_ENC_ERR_INVALID_ENCODERDEVICE,
AVERROR(EINVAL),
"invalid encoder device" },
143 { NV_ENC_ERR_INVALID_DEVICE,
AVERROR(EINVAL),
"invalid device" },
144 { NV_ENC_ERR_DEVICE_NOT_EXIST,
AVERROR(EIO),
"device does not exist" },
145 { NV_ENC_ERR_INVALID_PTR,
AVERROR(EFAULT),
"invalid ptr" },
146 { NV_ENC_ERR_INVALID_EVENT,
AVERROR(EINVAL),
"invalid event" },
147 { NV_ENC_ERR_INVALID_PARAM,
AVERROR(EINVAL),
"invalid param" },
148 { NV_ENC_ERR_INVALID_CALL,
AVERROR(EINVAL),
"invalid call" },
149 { NV_ENC_ERR_OUT_OF_MEMORY,
AVERROR(ENOMEM),
"out of memory" },
150 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,
AVERROR(EINVAL),
"encoder not initialized" },
151 { NV_ENC_ERR_UNSUPPORTED_PARAM,
AVERROR(ENOSYS),
"unsupported param" },
152 { NV_ENC_ERR_LOCK_BUSY,
AVERROR(EAGAIN),
"lock busy" },
154 { NV_ENC_ERR_INVALID_VERSION,
AVERROR(EINVAL),
"invalid version" },
155 { NV_ENC_ERR_MAP_FAILED,
AVERROR(EIO),
"map failed" },
156 { NV_ENC_ERR_NEED_MORE_INPUT,
AVERROR(EAGAIN),
"need more input" },
157 { NV_ENC_ERR_ENCODER_BUSY,
AVERROR(EAGAIN),
"encoder busy" },
158 { NV_ENC_ERR_EVENT_NOT_REGISTERD,
AVERROR(EBADF),
"event not registered" },
160 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,
AVERROR(EINVAL),
"incompatible client key" },
161 { NV_ENC_ERR_UNIMPLEMENTED,
AVERROR(ENOSYS),
"unimplemented" },
162 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED,
AVERROR(EIO),
"resource register failed" },
163 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,
AVERROR(EBADF),
"resource not registered" },
164 { NV_ENC_ERR_RESOURCE_NOT_MAPPED,
AVERROR(EBADF),
"resource not mapped" },
178 *
desc =
"unknown error";
183 const char *error_string)
186 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
188 const char *details =
"(no details)";
191 if (p_nvenc &&
ctx->nvencoder)
192 details = p_nvenc->nvEncGetLastErrorString(
ctx->nvencoder);
204 #define PRESET_ALIAS(alias, name, ...) \
205 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
207 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
226 ctx->init_encode_params.presetGUID = t->
guid;
229 if (
ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
238 #if NVENCAPI_CHECK_VERSION(13, 2)
239 const char *minver =
"(unknown)";
240 #elif NVENCAPI_CHECK_VERSION(13, 1)
241 const char *minver =
"610.00";
242 #elif NVENCAPI_CHECK_VERSION(13, 0)
243 const char *minver =
"570.0";
244 #elif NVENCAPI_CHECK_VERSION(12, 2)
245 # if defined(_WIN32) || defined(__CYGWIN__)
246 const char *minver =
"551.76";
248 const char *minver =
"550.54.14";
250 #elif NVENCAPI_CHECK_VERSION(12, 1)
251 # if defined(_WIN32) || defined(__CYGWIN__)
252 const char *minver =
"531.61";
254 const char *minver =
"530.41.03";
256 #elif NVENCAPI_CHECK_VERSION(12, 0)
257 # if defined(_WIN32) || defined(__CYGWIN__)
258 const char *minver =
"522.25";
260 const char *minver =
"520.56.06";
263 # if defined(_WIN32) || defined(__CYGWIN__)
264 const char *minver =
"471.41";
266 const char *minver =
"470.57.02";
269 av_log(avctx,
level,
"The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
272 #if NVENCAPI_CHECK_VERSION(12, 0)
273 #define to_nv_color_matrix(n) (NV_ENC_VUI_MATRIX_COEFFS)(n)
274 #define to_nv_color_pri(n) (NV_ENC_VUI_COLOR_PRIMARIES)(n)
275 #define to_nv_color_trc(n) (NV_ENC_VUI_TRANSFER_CHARACTERISTIC)(n)
277 #define to_nv_color_matrix(n) (uint32_t)(n)
278 #define to_nv_color_pri(n) (uint32_t)(n)
279 #define to_nv_color_trc(n) (uint32_t)(n)
287 uint32_t nvenc_max_ver;
290 ret = cuda_load_functions(&dl_fn->
cuda_dl, avctx);
294 ret = nvenc_load_functions(&dl_fn->
nvenc_dl, avctx);
300 err = dl_fn->
nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
301 if (err != NV_ENC_SUCCESS)
306 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
307 av_log(avctx,
AV_LOG_ERROR,
"Driver does not support the required nvenc API version. "
308 "Required: %d.%d Found: %d.%d\n",
309 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
310 nvenc_max_ver >> 4, nvenc_max_ver & 0
xf);
315 dl_fn->
nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
318 if (err != NV_ENC_SUCCESS)
331 if (
ctx->d3d11_device)
343 if (
ctx->d3d11_device)
351 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
353 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
356 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
357 params.apiVersion = NVENCAPI_VERSION;
358 if (
ctx->d3d11_device) {
359 params.device =
ctx->d3d11_device;
360 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
362 params.device =
ctx->cu_context;
363 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
366 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &
ctx->nvencoder);
367 if (
ret != NV_ENC_SUCCESS) {
378 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
379 int i,
ret, count = 0;
382 ret = p_nvenc->nvEncGetEncodeGUIDCount(
ctx->nvencoder, &count);
384 if (
ret != NV_ENC_SUCCESS || !count)
391 ret = p_nvenc->nvEncGetEncodeGUIDs(
ctx->nvencoder, guids, count, &count);
392 if (
ret != NV_ENC_SUCCESS) {
398 for (
i = 0;
i < count;
i++) {
399 if (!memcmp(&guids[
i], &
ctx->init_encode_params.encodeGUID,
sizeof(*guids))) {
414 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
415 NV_ENC_CAPS_PARAM params = { 0 };
418 params.version = NV_ENC_CAPS_PARAM_VER;
419 params.capsToQuery = cap;
421 ret = p_nvenc->nvEncGetEncodeCaps(
ctx->nvencoder,
ctx->init_encode_params.encodeGUID, ¶ms, &
val);
423 if (
ret == NV_ENC_SUCCESS)
445 #ifdef NVENC_HAVE_422_SUPPORT
462 if (ret < avctx->
width) {
469 if (ret < avctx->
height) {
476 if (ret < avctx->max_b_frames) {
486 "Interlaced encoding is not supported. Supported level: %d\n",
498 if (
ctx->rc_lookahead > 0 &&
ret <= 0) {
504 if (
ctx->temporal_aq > 0 &&
ret <= 0) {
510 if (
ctx->weighted_pred > 0 &&
ret <= 0) {
516 if (
ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC &&
ret <= 0) {
521 tmp = (
ctx->b_ref_mode >= 0) ?
ctx->b_ref_mode : NV_ENC_BFRAME_REF_MODE_DISABLED;
524 case NV_ENC_BFRAME_REF_MODE_DISABLED:
526 case NV_ENC_BFRAME_REF_MODE_EACH:
532 case NV_ENC_BFRAME_REF_MODE_MIDDLE:
538 #ifdef NVENC_HAVE_AV1_HGOP_SUPPORT
539 case NV_ENC_BFRAME_REF_MODE_HIERARCHICAL:
552 if(avctx->
refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT &&
ret <= 0) {
558 if(
ctx->single_slice_intra_refresh &&
ret <= 0) {
564 if((
ctx->intra_refresh ||
ctx->single_slice_intra_refresh) &&
ret <= 0) {
570 if(
ctx->constrained_encoding &&
ret <= 0) {
575 #if defined(NVENC_HAVE_TEMPORAL_FILTER) || defined(NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER)
577 if(
ctx->tf_level > 0 &&
ret <= 0) {
583 #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
585 if(
ctx->rc_lookahead > 0 &&
ctx->lookahead_level > 0 &&
586 ctx->lookahead_level != NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT &&
587 ctx->lookahead_level >
ret)
594 #ifdef NVENC_HAVE_UNIDIR_B
596 if(
ctx->unidir_b &&
ret <= 0) {
602 ctx->support_dyn_bitrate =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
604 #ifdef NVENC_HAVE_MVHEVC
605 ctx->multiview_supported =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MVHEVC_ENCODE) > 0;
607 ctx->profile == NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN &&
608 !
ctx->multiview_supported) {
621 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
622 char name[128] = { 0};
623 int major, minor,
ret;
642 av_log(avctx, loglevel,
"[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx,
name, major, minor);
643 if (((major << 4) | minor) <
NVENC_CAP) {
644 av_log(avctx, loglevel,
"does not support NVENC\n");
655 ctx->cu_context =
ctx->cu_context_internal;
667 av_log(avctx, loglevel,
"supports NVENC\n");
678 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
686 ctx->cu_context_internal =
NULL;
699 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
702 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
704 #if CONFIG_AV1_NVENC_ENCODER
706 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_AV1_GUID;
737 cuda_device_hwctx = hwdev_ctx->
hwctx;
740 d3d11_device_hwctx = hwdev_ctx->
hwctx;
748 if (cuda_device_hwctx) {
750 ctx->cu_stream = cuda_device_hwctx->
stream;
753 else if (d3d11_device_hwctx) {
754 ctx->d3d11_device = d3d11_device_hwctx->
device;
755 ID3D11Device_AddRef(
ctx->d3d11_device);
765 av_log(avctx,
AV_LOG_FATAL,
"Provided device doesn't support required NVENC features\n");
769 int i, nb_devices = 0;
785 for (
i = 0;
i < nb_devices; ++
i) {
798 av_log(avctx,
AV_LOG_FATAL,
"Requested GPU %d, but only %d GPUs are available!\n",
ctx->device, nb_devices);
808 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
809 #if CONFIG_AV1_NVENC_ENCODER
815 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
817 if (
ctx->init_qp_p >= 0) {
818 rc->constQP.qpInterP =
ctx->init_qp_p;
819 if (
ctx->init_qp_i >= 0 &&
ctx->init_qp_b >= 0) {
820 rc->constQP.qpIntra =
ctx->init_qp_i;
821 rc->constQP.qpInterB =
ctx->init_qp_b;
825 rc->constQP.qpInterB =
av_clip(
828 rc->constQP.qpIntra = rc->constQP.qpInterP;
829 rc->constQP.qpInterB = rc->constQP.qpInterP;
831 }
else if (
ctx->cqp >= 0) {
832 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra =
ctx->cqp;
846 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
848 #if CONFIG_AV1_NVENC_ENCODER
854 if (avctx->
qmin >= 0 || avctx->
qmax >= 0)
855 av_log(avctx,
AV_LOG_WARNING,
"Passing qmin/qmax via global AVCodecContext options. Use encoder options instead.\n");
857 if (avctx->
qmin >= 0 &&
ctx->qmin < 0)
859 if (avctx->
qmax >= 0 &&
ctx->qmax < 0)
864 if (
ctx->qmin >= 0 &&
ctx->qmax >= 0) {
868 rc->minQP.qpInterB =
ctx->qmin;
869 rc->minQP.qpInterP =
ctx->qmin;
870 rc->minQP.qpIntra =
ctx->qmin;
872 rc->maxQP.qpInterB =
ctx->qmax;
873 rc->maxQP.qpInterP =
ctx->qmax;
874 rc->maxQP.qpIntra =
ctx->qmax;
876 qp_inter_p = (
ctx->qmax + 3 *
ctx->qmin) / 4;
877 }
else if (
ctx->qmin >= 0) {
880 rc->minQP.qpInterB =
ctx->qmin;
881 rc->minQP.qpInterP =
ctx->qmin;
882 rc->minQP.qpIntra =
ctx->qmin;
884 qp_inter_p =
ctx->qmin;
889 rc->enableInitialRCQP = 1;
891 if (
ctx->init_qp_p < 0) {
892 rc->initialRCQP.qpInterP = qp_inter_p;
894 rc->initialRCQP.qpInterP =
ctx->init_qp_p;
897 if (
ctx->init_qp_i < 0) {
899 rc->initialRCQP.qpIntra =
av_clip(
902 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
905 rc->initialRCQP.qpIntra =
ctx->init_qp_i;
908 if (
ctx->init_qp_b < 0) {
910 rc->initialRCQP.qpInterB =
av_clip(
913 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
916 rc->initialRCQP.qpInterB =
ctx->init_qp_b;
923 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
925 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
926 rc->constQP.qpInterB = 0;
927 rc->constQP.qpInterP = 0;
928 rc->constQP.qpIntra = 0;
937 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
940 case NV_ENC_PARAMS_RC_CONSTQP:
943 case NV_ENC_PARAMS_RC_VBR:
946 case NV_ENC_PARAMS_RC_CBR:
950 rc->rateControlMode =
ctx->rc;
959 int nb_surfaces =
FFMAX(4,
ctx->encode_config.frameIntervalP * 2 * 2);
962 if (
ctx->rc_lookahead > 0) {
965 nb_surfaces =
FFMAX(1,
FFMAX(nb_surfaces,
ctx->rc_lookahead +
ctx->encode_config.frameIntervalP + 1 + 4));
966 if (nb_surfaces >
ctx->nb_surfaces &&
ctx->nb_surfaces > 0)
969 "Defined rc_lookahead requires more surfaces, "
970 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
972 ctx->nb_surfaces =
FFMAX(nb_surfaces,
ctx->nb_surfaces);
974 if (
ctx->encode_config.frameIntervalP > 1 &&
ctx->nb_surfaces < nb_surfaces &&
ctx->nb_surfaces > 0)
977 "Defined b-frame requires more surfaces, "
978 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
979 ctx->nb_surfaces =
FFMAX(
ctx->nb_surfaces, nb_surfaces);
981 else if (
ctx->nb_surfaces <= 0)
982 ctx->nb_surfaces = nb_surfaces;
991 ctx->frame_data_array_nb =
FFMAX(
ctx->nb_surfaces,
ctx->nb_surfaces +
ctx->encode_config.frameIntervalP - 1);
1001 av_log(avctx,
AV_LOG_ERROR,
"Using global_quality with nvenc is not supported. Use qp instead.\n");
1006 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate;
1007 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1008 ctx->encode_config.rcParams.maxBitRate =
ctx->encode_config.rcParams.averageBitRate;
1014 ctx->encode_config.rcParams.multiPass =
ctx->multipass;
1017 ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
1019 ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
1022 if (
ctx->cqp >= 0) {
1023 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
1024 }
else if (
ctx->quality >= 0.0f) {
1025 ctx->rc = NV_ENC_PARAMS_RC_VBR;
1029 ctx->encode_config.rcParams.cbQPIndexOffset =
ctx->qp_cb_offset;
1030 ctx->encode_config.rcParams.crQPIndexOffset =
ctx->qp_cr_offset;
1033 ctx->qp_cr_offset !=
ctx->qp_cb_offset)
1035 "av1_nvenc: qp_cr_offset is currently ignored by the NVENC driver "
1036 "(deltaQ_v_ac is forced equal to deltaQ_u_ac); only qp_cb_offset "
1040 ctx->encode_config.rcParams.lowDelayKeyFrameScale =
ctx->ldkfs;
1044 }
else if (
ctx->rc >= 0) {
1047 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
1053 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1054 avctx->
rc_buffer_size =
ctx->encode_config.rcParams.vbvBufferSize = 2 *
ctx->encode_config.rcParams.averageBitRate;
1058 ctx->encode_config.rcParams.enableAQ = 1;
1059 ctx->encode_config.rcParams.aqStrength =
ctx->aq_strength;
1063 if (
ctx->temporal_aq) {
1064 ctx->encode_config.rcParams.enableTemporalAQ = 1;
1068 if (
ctx->rc_lookahead > 0) {
1069 int lkd_bound =
FFMIN(
ctx->nb_surfaces,
ctx->async_depth) -
1070 ctx->encode_config.frameIntervalP - 4;
1072 if (lkd_bound < 0) {
1073 ctx->encode_config.rcParams.enableLookahead = 0;
1075 "Lookahead not enabled. Increase buffer delay (-delay).\n");
1077 ctx->encode_config.rcParams.enableLookahead = 1;
1078 ctx->encode_config.rcParams.lookaheadDepth =
av_clip(
ctx->rc_lookahead, 0, lkd_bound);
1079 ctx->encode_config.rcParams.disableIadapt =
ctx->no_scenecut;
1080 ctx->encode_config.rcParams.disableBadapt = !
ctx->b_adapt;
1082 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
1083 ctx->encode_config.rcParams.lookaheadDepth,
1084 ctx->encode_config.rcParams.disableIadapt ?
"disabled" :
"enabled",
1085 ctx->encode_config.rcParams.disableBadapt ?
"disabled" :
"enabled");
1086 if (
ctx->encode_config.rcParams.lookaheadDepth <
ctx->rc_lookahead)
1087 av_log(avctx,
AV_LOG_WARNING,
"Clipping lookahead depth to %d (from %d) due to lack of surfaces/delay",
1088 ctx->encode_config.rcParams.lookaheadDepth,
ctx->rc_lookahead);
1090 #ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
1091 if (
ctx->lookahead_level >= 0) {
1092 switch (
ctx->lookahead_level) {
1093 case NV_ENC_LOOKAHEAD_LEVEL_0:
1094 case NV_ENC_LOOKAHEAD_LEVEL_1:
1095 case NV_ENC_LOOKAHEAD_LEVEL_2:
1096 case NV_ENC_LOOKAHEAD_LEVEL_3:
1097 case NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT:
1104 ctx->encode_config.rcParams.lookaheadLevel =
ctx->lookahead_level;
1110 if (
ctx->strict_gop) {
1111 ctx->encode_config.rcParams.strictGOPTarget = 1;
1116 ctx->encode_config.rcParams.enableNonRefP = 1;
1118 if (
ctx->zerolatency)
1119 ctx->encode_config.rcParams.zeroReorderDelay = 1;
1123 int tmp_quality = (int)(
ctx->quality * 256.0f);
1124 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1125 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1130 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate = 0;
1141 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1142 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1143 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1151 vui->videoFullRangeFlag = 0;
1160 vui->colourDescriptionPresentFlag =
1161 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1163 vui->videoSignalTypePresentFlag =
1164 (vui->colourDescriptionPresentFlag
1165 || vui->videoFormat != 5
1166 || vui->videoFullRangeFlag != 0);
1168 if (
ctx->max_slice_size > 0) {
1169 h264->sliceMode = 1;
1170 h264->sliceModeData =
ctx->max_slice_size;
1172 h264->sliceMode = 3;
1173 h264->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1176 if (
ctx->intra_refresh) {
1177 h264->enableIntraRefresh = 1;
1178 h264->intraRefreshPeriod = cc->gopLength;
1179 h264->intraRefreshCnt = cc->gopLength - 1;
1180 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1181 h264->outputRecoveryPointSEI = 1;
1182 h264->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1185 if (
ctx->constrained_encoding)
1186 h264->enableConstrainedEncoding = 1;
1190 h264->outputAUD =
ctx->aud;
1192 if (
ctx->dpb_size >= 0) {
1194 h264->maxNumRefFrames =
ctx->dpb_size;
1197 h264->idrPeriod = cc->gopLength;
1199 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1201 h264->outputBufferingPeriodSEI =
ctx->cbr_padding;
1203 h264->enableFillerDataInsertion =
ctx->cbr_padding;
1206 h264->outputPictureTimingSEI = 1;
1209 h264->qpPrimeYZeroTransformBypassFlag = 1;
1211 switch(
ctx->profile) {
1213 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1215 if (cc->frameIntervalP > 1) {
1217 "B-frames are not supported by H.264 Baseline profile, disabling.\n");
1218 cc->frameIntervalP = 1;
1222 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1226 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1229 #ifdef NVENC_HAVE_H264_10BIT_SUPPORT
1230 case NV_ENC_H264_PROFILE_HIGH_10:
1231 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
1235 #ifdef NVENC_HAVE_422_SUPPORT
1236 case NV_ENC_H264_PROFILE_HIGH_422:
1237 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
1242 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1248 #ifdef NVENC_HAVE_H264_10BIT_SUPPORT
1251 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
1258 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1262 #ifdef NVENC_HAVE_422_SUPPORT
1265 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
1274 h264->level =
ctx->level;
1276 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1277 h264->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1278 h264->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1281 if (
ctx->coder >= 0)
1282 h264->entropyCodingMode =
ctx->coder;
1284 if (
ctx->b_ref_mode >= 0)
1285 h264->useBFramesAsRef =
ctx->b_ref_mode;
1287 h264->numRefL0 = avctx->
refs;
1288 h264->numRefL1 = avctx->
refs;
1290 #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
1291 if (
ctx->tf_level >= 0) {
1292 h264->tfLevel =
ctx->tf_level;
1294 switch (
ctx->tf_level)
1296 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1297 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1304 if (
ctx->encode_config.frameIntervalP < 5)
1309 #ifdef NVENC_HAVE_TIME_CODE
1311 h264->enableTimeCode = 1;
1320 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1321 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1322 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1330 vui->videoFullRangeFlag = 0;
1339 vui->colourDescriptionPresentFlag =
1340 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1342 vui->videoSignalTypePresentFlag =
1343 (vui->colourDescriptionPresentFlag
1344 || vui->videoFormat != 5
1345 || vui->videoFullRangeFlag != 0);
1347 if (
ctx->max_slice_size > 0) {
1348 hevc->sliceMode = 1;
1349 hevc->sliceModeData =
ctx->max_slice_size;
1351 hevc->sliceMode = 3;
1352 hevc->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1355 if (
ctx->intra_refresh) {
1356 hevc->enableIntraRefresh = 1;
1357 hevc->intraRefreshPeriod = cc->gopLength;
1358 hevc->intraRefreshCnt = cc->gopLength - 1;
1359 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1360 #ifdef NVENC_HAVE_HEVC_OUTPUT_RECOVERY_POINT_SEI
1361 hevc->outputRecoveryPointSEI = 1;
1363 hevc->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1366 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
1375 if (
ctx->constrained_encoding)
1376 hevc->enableConstrainedEncoding = 1;
1380 hevc->outputAUD =
ctx->aud;
1382 if (
ctx->dpb_size >= 0) {
1384 hevc->maxNumRefFramesInDPB =
ctx->dpb_size;
1387 hevc->idrPeriod = cc->gopLength;
1389 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1391 hevc->outputBufferingPeriodSEI =
ctx->cbr_padding;
1393 hevc->enableFillerDataInsertion =
ctx->cbr_padding;
1396 hevc->outputPictureTimingSEI = 1;
1398 #ifdef NVENC_HAVE_MVHEVC
1405 ctx->profile = NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN;
1407 if (
ctx->profile == NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN && stereo3d &&
1418 switch (
ctx->profile) {
1420 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1424 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1428 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1431 #ifdef NVENC_HAVE_MVHEVC
1432 case NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN:
1433 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1437 hevc->enableMVHEVC = 1;
1438 hevc->outputHevc3DReferenceDisplayInfo = 1;
1447 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1453 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1457 #ifdef NVENC_HAVE_MVHEVC
1459 av_log(avctx,
AV_LOG_ERROR,
"Multiview encoding only works for Main profile content.\n");
1466 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1467 hevc->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1468 hevc->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1470 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1473 hevc->level =
ctx->level;
1475 hevc->tier =
ctx->tier;
1477 if (
ctx->b_ref_mode >= 0)
1478 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1480 hevc->numRefL0 = avctx->
refs;
1481 hevc->numRefL1 = avctx->
refs;
1483 #ifdef NVENC_HAVE_TEMPORAL_FILTER
1484 if (
ctx->tf_level >= 0) {
1485 hevc->tfLevel =
ctx->tf_level;
1487 switch (
ctx->tf_level)
1489 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1490 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1497 if (
ctx->encode_config.frameIntervalP < 5)
1505 #if CONFIG_AV1_NVENC_ENCODER
1509 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1510 NV_ENC_CONFIG_AV1 *av1 = &cc->encodeCodecConfig.av1Config;
1518 av1->colorRange = 0;
1528 av_log(avctx,
AV_LOG_ERROR,
"AV1 High Profile not supported, required for 4:4:4 encoding\n");
1531 cc->profileGUID = NV_ENC_AV1_PROFILE_MAIN_GUID;
1535 if (
ctx->dpb_size >= 0) {
1537 av1->maxNumRefFramesInDPB =
ctx->dpb_size;
1540 if (
ctx->intra_refresh) {
1541 av1->enableIntraRefresh = 1;
1542 av1->intraRefreshPeriod = cc->gopLength;
1543 av1->intraRefreshCnt = cc->gopLength - 1;
1544 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1547 av1->idrPeriod = cc->gopLength;
1549 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1550 av1->enableBitstreamPadding =
ctx->cbr_padding;
1553 if (
ctx->tile_cols >= 0)
1554 av1->numTileColumns =
ctx->tile_cols;
1555 if (
ctx->tile_rows >= 0)
1556 av1->numTileRows =
ctx->tile_rows;
1558 av1->outputAnnexBFormat = 0;
1560 av1->level =
ctx->level;
1561 av1->tier =
ctx->tier;
1563 av1->enableTimingInfo =
ctx->timing_info;
1566 av1->disableSeqHdr = 0;
1567 av1->repeatSeqHdr = 1;
1569 av1->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1571 #ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1572 av1->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1573 av1->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1575 av1->inputPixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1576 av1->pixelBitDepthMinus8 = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? 2 : 0;
1579 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
1588 if (
ctx->b_ref_mode >= 0)
1589 av1->useBFramesAsRef =
ctx->b_ref_mode;
1591 av1->numFwdRefs = avctx->
refs;
1592 av1->numBwdRefs = avctx->
refs;
1594 #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
1595 if (
ctx->tf_level >= 0) {
1596 av1->tfLevel =
ctx->tf_level;
1598 switch (
ctx->tf_level)
1600 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1601 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1608 if (
ctx->encode_config.frameIntervalP < 5)
1624 #if CONFIG_AV1_NVENC_ENCODER
1626 return nvenc_setup_av1_config(avctx);
1640 #if CONFIG_AV1_NVENC_ENCODER
1671 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1673 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1674 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1679 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1680 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1682 ctx->init_encode_params.encodeHeight = avctx->
height;
1683 ctx->init_encode_params.encodeWidth = avctx->
width;
1685 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1687 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1688 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1690 ctx->init_encode_params.tuningInfo =
ctx->tuning_info;
1693 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1695 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1697 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(
ctx->nvencoder,
1698 ctx->init_encode_params.encodeGUID,
1699 ctx->init_encode_params.presetGUID,
1700 ctx->init_encode_params.tuningInfo,
1702 if (nv_status != NV_ENC_SUCCESS)
1703 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1705 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1707 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1710 ctx->init_encode_params.darHeight = dh;
1711 ctx->init_encode_params.darWidth = dw;
1721 #ifdef NVENC_HAVE_UNIDIR_B
1722 ctx->init_encode_params.enableUniDirectionalB =
ctx->unidir_b;
1725 ctx->init_encode_params.enableEncodeAsync = 0;
1726 ctx->init_encode_params.enablePTD = 1;
1731 if (
ctx->rc_lookahead == 0 &&
ctx->encode_config.rcParams.enableLookahead)
1732 ctx->rc_lookahead =
ctx->encode_config.rcParams.lookaheadDepth;
1734 if (
ctx->weighted_pred == 1)
1735 ctx->init_encode_params.enableWeightedPrediction = 1;
1737 #ifdef NVENC_HAVE_SPLIT_FRAME_ENCODING
1738 ctx->init_encode_params.splitEncodeMode =
ctx->split_encode_mode;
1740 if (
ctx->split_encode_mode != NV_ENC_SPLIT_DISABLE_MODE) {
1742 av_log(avctx,
AV_LOG_WARNING,
"Split encoding not supported with weighted prediction enabled.\n");
1746 if (
ctx->bluray_compat) {
1755 ctx->level = NV_ENC_LEVEL_HEVC_51;
1756 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1765 ctx->encode_config.frameIntervalP = 0;
1766 ctx->encode_config.gopLength = 1;
1775 if(
ctx->single_slice_intra_refresh)
1776 ctx->intra_refresh = 1;
1785 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1787 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1798 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1799 if (nv_status != NV_ENC_SUCCESS) {
1804 if (
ctx->cu_context) {
1805 nv_status = p_nvenc->nvEncSetIOCudaStreams(
ctx->nvencoder, &
ctx->cu_stream, &
ctx->cu_stream);
1806 if (nv_status != NV_ENC_SUCCESS) {
1816 if (
ctx->encode_config.frameIntervalP > 1)
1819 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1820 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1827 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1836 return NV_ENC_BUFFER_FORMAT_YV12;
1838 return NV_ENC_BUFFER_FORMAT_NV12;
1842 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1845 return NV_ENC_BUFFER_FORMAT_YUV444;
1851 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1854 return NV_ENC_BUFFER_FORMAT_ARGB;
1857 return NV_ENC_BUFFER_FORMAT_ABGR;
1859 return NV_ENC_BUFFER_FORMAT_ARGB10;
1861 return NV_ENC_BUFFER_FORMAT_ABGR10;
1862 #ifdef NVENC_HAVE_422_SUPPORT
1864 return NV_ENC_BUFFER_FORMAT_NV16;
1868 return NV_ENC_BUFFER_FORMAT_P210;
1871 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1879 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1882 NVENCSTATUS nv_status;
1883 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1884 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1888 if (!
ctx->surfaces[idx].in_ref)
1891 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1894 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1900 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1901 allocSurf.width = avctx->
width;
1902 allocSurf.height = avctx->
height;
1903 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1905 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
1906 if (nv_status != NV_ENC_SUCCESS) {
1910 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1911 ctx->surfaces[idx].width = allocSurf.width;
1912 ctx->surfaces[idx].height = allocSurf.height;
1915 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
1916 if (nv_status != NV_ENC_SUCCESS) {
1919 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
1924 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1934 int i, res = 0, res2;
1940 ctx->frame_data_array =
av_calloc(
ctx->frame_data_array_nb,
sizeof(*
ctx->frame_data_array));
1941 if (!
ctx->frame_data_array)
1946 if (!
ctx->timestamp_list)
1950 if (!
ctx->unused_surface_queue)
1954 if (!
ctx->output_surface_queue)
1957 if (!
ctx->output_surface_ready_queue)
1964 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
1981 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1983 NVENCSTATUS nv_status;
1984 uint32_t outSize = 0;
1985 char tmpHeader[NV_MAX_SEQ_HDR_LEN];
1987 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1988 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1990 payload.spsppsBuffer = tmpHeader;
1991 payload.inBufferSize =
sizeof(tmpHeader);
1992 payload.outSPSPPSPayloadSize = &outSize;
1994 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
1995 if (nv_status != NV_ENC_SUCCESS) {
2006 memcpy(avctx->
extradata, tmpHeader, outSize);
2015 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2019 if (
ctx->nvencoder) {
2020 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
2021 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
2027 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, ¶ms);
2035 if (
ctx->frame_data_array) {
2036 for (
i = 0;
i <
ctx->frame_data_array_nb;
i++)
2042 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2043 if (
ctx->registered_frames[
i].mapped)
2044 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
2045 if (
ctx->registered_frames[
i].regptr)
2046 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2048 ctx->nb_registered_frames = 0;
2051 if (
ctx->surfaces) {
2052 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
2054 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
2056 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
2060 ctx->nb_surfaces = 0;
2066 if (
ctx->nvencoder) {
2067 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
2075 if (
ctx->cu_context_internal)
2077 ctx->cu_context =
ctx->cu_context_internal =
NULL;
2080 if (
ctx->d3d11_device) {
2081 ID3D11Device_Release(
ctx->d3d11_device);
2086 nvenc_free_functions(&dl_fn->
nvenc_dl);
2087 cuda_free_functions(&dl_fn->
cuda_dl);
2105 "hw_frames_ctx must be set when using GPU frames as input\n");
2111 "hw_frames_ctx must match the GPU frame type\n");
2160 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
2162 int dst_linesize[4] = {
2163 lock_buffer_params->pitch,
2164 lock_buffer_params->pitch,
2165 lock_buffer_params->pitch,
2166 lock_buffer_params->pitch
2168 uint8_t *dst_data[4];
2172 dst_linesize[1] = dst_linesize[2] >>= 1;
2175 lock_buffer_params->bufferDataPtr, dst_linesize);
2180 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
2193 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2194 NVENCSTATUS nv_status;
2199 for (first_round = 1; first_round >= 0; first_round--) {
2200 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2201 if (!
ctx->registered_frames[
i].mapped) {
2202 if (
ctx->registered_frames[
i].regptr) {
2205 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2206 if (nv_status != NV_ENC_SUCCESS)
2207 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
2208 ctx->registered_frames[
i].ptr =
NULL;
2209 ctx->registered_frames[
i].regptr =
NULL;
2216 return ctx->nb_registered_frames++;
2227 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2230 NV_ENC_REGISTER_RESOURCE reg = { 0 };
2233 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2244 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
2245 reg.width = frames_ctx->width;
2246 reg.height = frames_ctx->height;
2247 reg.pitch =
frame->linesize[0];
2248 reg.resourceToRegister =
frame->data[0];
2251 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
2254 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
2255 reg.subResourceIndex = (intptr_t)
frame->data[1];
2259 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
2265 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
2266 if (
ret != NV_ENC_SUCCESS) {
2271 ctx->registered_frames[idx].ptr =
frame->data[0];
2272 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
2273 ctx->registered_frames[idx].regptr = reg.registeredResource;
2282 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2285 NVENCSTATUS nv_status;
2298 if (!
ctx->registered_frames[reg_idx].mapped) {
2299 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
2300 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
2301 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
2302 if (nv_status != NV_ENC_SUCCESS) {
2308 ctx->registered_frames[reg_idx].mapped += 1;
2310 nvenc_frame->
reg_idx = reg_idx;
2311 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
2312 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
2317 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
2319 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
2322 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
2323 if (nv_status != NV_ENC_SUCCESS) {
2324 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
2327 nvenc_frame->
pitch = lockBufferParams.pitch;
2330 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
2331 if (nv_status != NV_ENC_SUCCESS) {
2339 #ifdef NVENC_HAVE_TIME_CODE
2345 uint32_t *tc = (uint32_t*)sd->
data;
2350 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2351 time_code->skipClockTimestampInsertion = 1;
2354 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME_DOUBLING;
2357 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME_TRIPLING;
2360 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2364 for (
int i = 0;
i < cnt;
i++) {
2365 unsigned hh, mm,
ss, ff, drop;
2368 #ifdef NVENC_NEW_COUNTING_TYPE
2369 time_code->clockTimestamp[
i].countingTypeLSB = 0;
2370 time_code->clockTimestamp[
i].countingTypeMSB = 0;
2372 time_code->clockTimestamp[
i].countingType = 0;
2374 time_code->clockTimestamp[
i].discontinuityFlag = 0;
2375 time_code->clockTimestamp[
i].cntDroppedFrames = drop;
2376 time_code->clockTimestamp[
i].nFrames = ff;
2377 time_code->clockTimestamp[
i].secondsValue =
ss;
2378 time_code->clockTimestamp[
i].minutesValue = mm;
2379 time_code->clockTimestamp[
i].hoursValue = hh;
2380 time_code->clockTimestamp[
i].timeOffset = 0;
2383 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2384 time_code->skipClockTimestampInsertion = 1;
2390 NV_ENC_PIC_PARAMS *params,
2391 NV_ENC_SEI_PAYLOAD *sei_data,
2398 params->codecPicParams.h264PicParams.sliceMode =
2399 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
2400 params->codecPicParams.h264PicParams.sliceModeData =
2401 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
2402 if (sei_count > 0) {
2403 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
2404 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
2407 #ifdef NVENC_HAVE_TIME_CODE
2409 nvenc_fill_time_code(avctx,
frame, ¶ms->codecPicParams.h264PicParams.timeCode);
2414 params->codecPicParams.hevcPicParams.sliceMode =
2415 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
2416 params->codecPicParams.hevcPicParams.sliceModeData =
2417 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
2418 if (sei_count > 0) {
2419 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
2420 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
2424 #if CONFIG_AV1_NVENC_ENCODER
2426 params->codecPicParams.av1PicParams.numTileColumns =
2427 ctx->encode_config.encodeCodecConfig.av1Config.numTileColumns;
2428 params->codecPicParams.av1PicParams.numTileRows =
2429 ctx->encode_config.encodeCodecConfig.av1Config.numTileRows;
2430 if (sei_count > 0) {
2431 params->codecPicParams.av1PicParams.obuPayloadArray = sei_data;
2432 params->codecPicParams.av1PicParams.obuPayloadArrayCnt = sei_count;
2463 NV_ENC_LOCK_BITSTREAM *params,
2470 pkt->
pts = params->outputTimeStamp;
2478 delay =
FFMAX(
ctx->encode_config.frameIntervalP - 1, 0);
2479 #ifdef NVENC_HAVE_MVHEVC
2480 delay *=
ctx->multiview ? 2 : 1;
2482 if (
ctx->output_frame_num >= delay) {
2484 ctx->output_frame_num++;
2488 delay_time =
ctx->initial_delay_time;
2496 delay_time = t1 - t2;
2501 delay_time = delay * (t3 - t2);
2505 ctx->initial_delay_time = delay_time;
2514 ctx->output_frame_num++;
2524 int idx =
ctx->frame_data_array_pos;
2539 ctx->frame_data_array_pos = (
ctx->frame_data_array_pos + 1) %
ctx->frame_data_array_nb;
2540 pic_params->inputDuration = idx;
2550 int idx = lock_params->outputDuration;
2570 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2572 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
2573 NVENCSTATUS nv_status;
2578 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
2580 lock_params.doNotWait = 0;
2583 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
2584 if (nv_status != NV_ENC_SUCCESS) {
2596 memcpy(
pkt->
data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
2598 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
2599 if (nv_status != NV_ENC_SUCCESS) {
2600 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
2606 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
2607 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
2608 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
2609 if (nv_status != NV_ENC_SUCCESS) {
2613 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
2623 switch (lock_params.pictureType) {
2624 case NV_ENC_PIC_TYPE_IDR:
2627 case NV_ENC_PIC_TYPE_I:
2630 case NV_ENC_PIC_TYPE_P:
2633 case NV_ENC_PIC_TYPE_B:
2636 case NV_ENC_PIC_TYPE_BI:
2640 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
2641 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
2669 int nb_ready, nb_pending;
2674 return nb_ready > 0;
2675 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
2685 void *a53_data =
NULL;
2686 size_t a53_size = 0;
2694 &
ctx->sei_data_size,
2695 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2702 ctx->sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2703 ctx->sei_data[sei_count].payload = (uint8_t*)a53_data;
2705 #if CONFIG_AV1_NVENC_ENCODER
2718 void *tc_data =
NULL;
2727 &
ctx->sei_data_size,
2728 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2735 ctx->sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2736 ctx->sei_data[sei_count].payload = (uint8_t*)tc_data;
2738 #if CONFIG_AV1_NVENC_ENCODER
2753 for (
i = 0;
i <
frame->nb_side_data;
i++) {
2761 &
ctx->sei_data_size,
2762 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2768 ctx->sei_data[sei_count].payloadSize = side_data->
size;
2772 if (!
ctx->sei_data[sei_count].payload) {
2784 for (
i = 0;
i < sei_count;
i++)
2793 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
2796 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2797 int needs_reconfig = 0;
2798 int needs_encode_config = 0;
2799 int reconfig_bitrate = 0, reconfig_dar = 0;
2802 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2803 params.reInitEncodeParams =
ctx->init_encode_params;
2806 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
2808 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2809 ctx->init_encode_params.darWidth,
2810 ctx->init_encode_params.darHeight, dw, dh);
2812 params.reInitEncodeParams.darHeight = dh;
2813 params.reInitEncodeParams.darWidth = dw;
2819 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
2820 if (avctx->
bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
2822 "avg bitrate change: %d -> %d\n",
2823 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2826 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
2827 reconfig_bitrate = 1;
2832 "max bitrate change: %d -> %d\n",
2833 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2836 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
2837 reconfig_bitrate = 1;
2842 "vbv buffer size change: %d -> %d\n",
2843 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2846 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->
rc_buffer_size;
2847 reconfig_bitrate = 1;
2850 if (reconfig_bitrate) {
2851 params.resetEncoder = 1;
2852 params.forceIDR = 1;
2854 needs_encode_config = 1;
2859 if (!needs_encode_config)
2860 params.reInitEncodeParams.encodeConfig =
NULL;
2862 if (needs_reconfig) {
2863 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, ¶ms);
2864 if (
ret != NV_ENC_SUCCESS) {
2868 ctx->init_encode_params.darHeight = dh;
2869 ctx->init_encode_params.darWidth = dw;
2872 if (reconfig_bitrate) {
2873 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2874 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2875 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2882 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
2884 MASTERING_DISPLAY_INFO *mastering_disp_info, CONTENT_LIGHT_LEVEL *content_light_level)
2888 if (
ctx->mdm ||
ctx->cll) {
2929 pic_params->codecPicParams.hevcPicParams.pMasteringDisplay = mastering_disp_info;
2931 pic_params->codecPicParams.av1PicParams.pMasteringDisplay = mastering_disp_info;
2938 content_light_level->maxContentLightLevel = cll->
MaxCLL;
2939 content_light_level->maxPicAverageLightLevel = cll->
MaxFALL;
2942 pic_params->codecPicParams.hevcPicParams.pMaxCll = content_light_level;
2944 pic_params->codecPicParams.av1PicParams.pMaxCll = content_light_level;
2956 NVENCSTATUS nv_status;
2961 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
2962 MASTERING_DISPLAY_INFO mastering_disp_info = { 0 };
2963 CONTENT_LIGHT_LEVEL content_light_level = { 0 };
2965 #ifdef NVENC_HAVE_MVHEVC
2966 HEVC_3D_REFERENCE_DISPLAY_INFO ref_disp_info = { 0 };
2971 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2973 NV_ENC_PIC_PARAMS pic_params = { 0 };
2974 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2976 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
3000 pic_params.bufferFmt = in_surf->
format;
3001 pic_params.inputWidth = in_surf->
width;
3002 pic_params.inputHeight = in_surf->
height;
3003 pic_params.inputPitch = in_surf->
pitch;
3008 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
3010 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
3012 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
3016 pic_params.encodePicFlags =
3017 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
3019 pic_params.encodePicFlags = 0;
3022 pic_params.frameIdx =
ctx->frame_idx_counter++;
3023 pic_params.inputTimeStamp =
frame->pts;
3025 if (
ctx->extra_sei) {
3032 #ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
3033 res = nvenc_set_mastering_display_data(avctx,
frame, &pic_params, &mastering_disp_info, &content_light_level);
3038 #ifdef NVENC_HAVE_MVHEVC
3039 if (
ctx->multiview) {
3044 ctx->next_view_id = *(
int*)sd_view_id->
data;
3046 pic_params.codecPicParams.hevcPicParams.viewId =
ctx->next_view_id;
3070 pic_params.codecPicParams.hevcPicParams.p3DReferenceDisplayInfo = &ref_disp_info;
3071 ctx->display_sei_sent = 1;
3072 }
else if (!
ctx->display_sei_sent) {
3073 ref_disp_info.precRefDisplayWidth = 31;
3074 ref_disp_info.leftViewId[0] = 0;
3075 ref_disp_info.rightViewId[0] = 1;
3077 pic_params.codecPicParams.hevcPicParams.p3DReferenceDisplayInfo = &ref_disp_info;
3078 ctx->display_sei_sent = 1;
3081 ctx->next_view_id = !
ctx->next_view_id;
3091 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
3098 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
3100 for (
i = 0;
i < sei_count;
i++)
3107 if (nv_status != NV_ENC_SUCCESS &&
3108 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
3119 if (nv_status == NV_ENC_SUCCESS) {
3120 while (
av_fifo_read(
ctx->output_surface_queue, &tmp_out_surf, 1) >= 0)
3136 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
3139 if (!
frame->buf[0]) {
3184 ctx->output_frame_num = 0;
3185 ctx->initial_delay_time = 0;