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)
51#define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR)
61#ifdef NVENC_HAVE_422_SUPPORT
83#ifdef NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
94#ifdef NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
105#define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
106 pix_fmt == AV_PIX_FMT_P012 || \
107 pix_fmt == AV_PIX_FMT_P016 || \
108 pix_fmt == AV_PIX_FMT_P210 || \
109 pix_fmt == AV_PIX_FMT_P212 || \
110 pix_fmt == AV_PIX_FMT_P216 || \
111 pix_fmt == AV_PIX_FMT_YUV444P10MSB || \
112 pix_fmt == AV_PIX_FMT_YUV444P12MSB || \
113 pix_fmt == AV_PIX_FMT_YUV444P16 || \
114 pix_fmt == AV_PIX_FMT_P410 || \
115 pix_fmt == AV_PIX_FMT_P412 || \
116 pix_fmt == AV_PIX_FMT_P416 || \
117 pix_fmt == AV_PIX_FMT_X2RGB10 || \
118 pix_fmt == AV_PIX_FMT_X2BGR10 || \
119 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
120 pix_fmt == AV_PIX_FMT_GBRP16)
122#define IS_RGB(pix_fmt) (pix_fmt == AV_PIX_FMT_0RGB32 || \
123 pix_fmt == AV_PIX_FMT_RGB32 || \
124 pix_fmt == AV_PIX_FMT_0BGR32 || \
125 pix_fmt == AV_PIX_FMT_BGR32 || \
126 pix_fmt == AV_PIX_FMT_X2RGB10 || \
127 pix_fmt == AV_PIX_FMT_X2BGR10)
129#define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
130 pix_fmt == AV_PIX_FMT_NV24 || \
131 pix_fmt == AV_PIX_FMT_YUV444P10MSB || \
132 pix_fmt == AV_PIX_FMT_YUV444P12MSB || \
133 pix_fmt == AV_PIX_FMT_YUV444P16 || \
134 pix_fmt == AV_PIX_FMT_P410 || \
135 pix_fmt == AV_PIX_FMT_P412 || \
136 pix_fmt == AV_PIX_FMT_P416 || \
137 pix_fmt == AV_PIX_FMT_GBRP || \
138 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
139 pix_fmt == AV_PIX_FMT_GBRP16 || \
140 (ctx->rgb_mode == NVENC_RGB_MODE_444 && IS_RGB(pix_fmt)))
142#define IS_YUV422(pix_fmt) (pix_fmt == AV_PIX_FMT_NV16 || \
143 pix_fmt == AV_PIX_FMT_P210 || \
144 pix_fmt == AV_PIX_FMT_P212 || \
145 pix_fmt == AV_PIX_FMT_P216)
147#define IS_HWACCEL(pix_fmt) (pix_fmt == AV_PIX_FMT_CUDA || \
148 pix_fmt == AV_PIX_FMT_CUARRAY || \
149 pix_fmt == AV_PIX_FMT_D3D11)
151#define IS_GBRP(pix_fmt) (pix_fmt == AV_PIX_FMT_GBRP || \
152 pix_fmt == AV_PIX_FMT_GBRP10MSB || \
153 pix_fmt == AV_PIX_FMT_GBRP16)
160 { NV_ENC_SUCCESS, 0,
"success" },
161 { NV_ENC_ERR_NO_ENCODE_DEVICE,
AVERROR(ENOENT),
"no encode device" },
162 { NV_ENC_ERR_UNSUPPORTED_DEVICE,
AVERROR(ENOSYS),
"unsupported device" },
163 { NV_ENC_ERR_INVALID_ENCODERDEVICE,
AVERROR(EINVAL),
"invalid encoder device" },
164 { NV_ENC_ERR_INVALID_DEVICE,
AVERROR(EINVAL),
"invalid device" },
165 { NV_ENC_ERR_DEVICE_NOT_EXIST,
AVERROR(EIO),
"device does not exist" },
166 { NV_ENC_ERR_INVALID_PTR,
AVERROR(EFAULT),
"invalid ptr" },
167 { NV_ENC_ERR_INVALID_EVENT,
AVERROR(EINVAL),
"invalid event" },
168 { NV_ENC_ERR_INVALID_PARAM,
AVERROR(EINVAL),
"invalid param" },
169 { NV_ENC_ERR_INVALID_CALL,
AVERROR(EINVAL),
"invalid call" },
170 { NV_ENC_ERR_OUT_OF_MEMORY,
AVERROR(ENOMEM),
"out of memory" },
171 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,
AVERROR(EINVAL),
"encoder not initialized" },
172 { NV_ENC_ERR_UNSUPPORTED_PARAM,
AVERROR(ENOSYS),
"unsupported param" },
173 { NV_ENC_ERR_LOCK_BUSY,
AVERROR(EAGAIN),
"lock busy" },
175 { NV_ENC_ERR_INVALID_VERSION,
AVERROR(EINVAL),
"invalid version" },
176 { NV_ENC_ERR_MAP_FAILED,
AVERROR(EIO),
"map failed" },
177 { NV_ENC_ERR_NEED_MORE_INPUT,
AVERROR(EAGAIN),
"need more input" },
178 { NV_ENC_ERR_ENCODER_BUSY,
AVERROR(EAGAIN),
"encoder busy" },
179 { NV_ENC_ERR_EVENT_NOT_REGISTERD,
AVERROR(EBADF),
"event not registered" },
181 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,
AVERROR(EINVAL),
"incompatible client key" },
182 { NV_ENC_ERR_UNIMPLEMENTED,
AVERROR(ENOSYS),
"unimplemented" },
183 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED,
AVERROR(EIO),
"resource register failed" },
184 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,
AVERROR(EBADF),
"resource not registered" },
185 { NV_ENC_ERR_RESOURCE_NOT_MAPPED,
AVERROR(EBADF),
"resource not mapped" },
199 *
desc =
"unknown error";
204 const char *error_string)
207 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
209 const char *details =
"(no details)";
212 if (p_nvenc &&
ctx->nvencoder)
213 details = p_nvenc->nvEncGetLastErrorString(
ctx->nvencoder);
225#define PRESET_ALIAS(alias, name, ...) \
226 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
228#define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
247 ctx->init_encode_params.presetGUID = t->
guid;
250 if (
ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
259#if NVENCAPI_CHECK_VERSION(13, 2)
260 const char *minver =
"(unknown)";
261#elif NVENCAPI_CHECK_VERSION(13, 1)
262 const char *minver =
"610.00";
263#elif NVENCAPI_CHECK_VERSION(13, 0)
264 const char *minver =
"570.0";
265#elif NVENCAPI_CHECK_VERSION(12, 2)
266# if defined(_WIN32) || defined(__CYGWIN__)
267 const char *minver =
"551.76";
269 const char *minver =
"550.54.14";
271#elif NVENCAPI_CHECK_VERSION(12, 1)
272# if defined(_WIN32) || defined(__CYGWIN__)
273 const char *minver =
"531.61";
275 const char *minver =
"530.41.03";
277#elif NVENCAPI_CHECK_VERSION(12, 0)
278# if defined(_WIN32) || defined(__CYGWIN__)
279 const char *minver =
"522.25";
281 const char *minver =
"520.56.06";
284# if defined(_WIN32) || defined(__CYGWIN__)
285 const char *minver =
"471.41";
287 const char *minver =
"470.57.02";
290 av_log(avctx,
level,
"The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
293#if NVENCAPI_CHECK_VERSION(12, 0)
294#define to_nv_color_matrix(n) (NV_ENC_VUI_MATRIX_COEFFS)(n)
295#define to_nv_color_pri(n) (NV_ENC_VUI_COLOR_PRIMARIES)(n)
296#define to_nv_color_trc(n) (NV_ENC_VUI_TRANSFER_CHARACTERISTIC)(n)
298#define to_nv_color_matrix(n) (uint32_t)(n)
299#define to_nv_color_pri(n) (uint32_t)(n)
300#define to_nv_color_trc(n) (uint32_t)(n)
308 uint32_t nvenc_max_ver;
311 ret = cuda_load_functions(&dl_fn->
cuda_dl, avctx);
315 ret = nvenc_load_functions(&dl_fn->
nvenc_dl, avctx);
321 err = dl_fn->
nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
322 if (err != NV_ENC_SUCCESS)
325 av_log(avctx,
AV_LOG_VERBOSE,
"Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
327 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
328 av_log(avctx,
AV_LOG_ERROR,
"Driver does not support the required nvenc API version. "
329 "Required: %d.%d Found: %d.%d\n",
330 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
331 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
336 dl_fn->
nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
339 if (err != NV_ENC_SUCCESS)
352 if (
ctx->d3d11_device)
364 if (
ctx->d3d11_device)
372 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS
params = { 0 };
374 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
377 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
378 params.apiVersion = NVENCAPI_VERSION;
379 if (
ctx->d3d11_device) {
381 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
384 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
387 ret = p_nvenc->nvEncOpenEncodeSessionEx(&
params, &
ctx->nvencoder);
388 if (ret != NV_ENC_SUCCESS) {
399 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
400 int i, ret, count = 0;
403 ret = p_nvenc->nvEncGetEncodeGUIDCount(
ctx->nvencoder, &count);
405 if (ret != NV_ENC_SUCCESS || !count)
412 ret = p_nvenc->nvEncGetEncodeGUIDs(
ctx->nvencoder, guids, count, &count);
413 if (ret != NV_ENC_SUCCESS) {
419 for (
i = 0;
i < count;
i++) {
420 if (!memcmp(&guids[
i], &
ctx->init_encode_params.encodeGUID,
sizeof(*guids))) {
435 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
436 NV_ENC_CAPS_PARAM
params = { 0 };
439 params.version = NV_ENC_CAPS_PARAM_VER;
442 ret = p_nvenc->nvEncGetEncodeCaps(
ctx->nvencoder,
ctx->init_encode_params.encodeGUID, &
params, &
val);
444 if (ret == NV_ENC_SUCCESS)
466#ifdef NVENC_HAVE_422_SUPPORT
483 if (ret < avctx->
width) {
490 if (ret < avctx->
height) {
497 if (ret < avctx->max_b_frames) {
507 "Interlaced encoding is not supported. Supported level: %d\n",
513 if ((
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) && ret <= 0) {
519 if (
ctx->rc_lookahead > 0 && ret <= 0) {
525 if (
ctx->temporal_aq > 0 && ret <= 0) {
531 if (
ctx->weighted_pred > 0 && ret <= 0) {
537 if (
ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
542 tmp = (
ctx->b_ref_mode >= 0) ?
ctx->b_ref_mode : NV_ENC_BFRAME_REF_MODE_DISABLED;
545 case NV_ENC_BFRAME_REF_MODE_DISABLED:
547 case NV_ENC_BFRAME_REF_MODE_EACH:
553 case NV_ENC_BFRAME_REF_MODE_MIDDLE:
559#ifdef NVENC_HAVE_AV1_HGOP_SUPPORT
560 case NV_ENC_BFRAME_REF_MODE_HIERARCHICAL:
573 if(avctx->
refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
579 if(
ctx->single_slice_intra_refresh && ret <= 0) {
585 if((
ctx->intra_refresh ||
ctx->single_slice_intra_refresh) && ret <= 0) {
590 ret =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CONSTRAINED_ENCODING);
591 if(
ctx->constrained_encoding && ret <= 0) {
596#if defined(NVENC_HAVE_TEMPORAL_FILTER) || defined(NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER)
598 if(
ctx->tf_level > 0 && ret <= 0) {
604#ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
606 if(
ctx->rc_lookahead > 0 &&
ctx->lookahead_level > 0 &&
607 ctx->lookahead_level != NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT &&
608 ctx->lookahead_level > ret)
615#ifdef NVENC_HAVE_UNIDIR_B
617 if(
ctx->unidir_b && ret <= 0) {
623 ctx->support_dyn_bitrate =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
625#ifdef NVENC_HAVE_MVHEVC
626 ctx->multiview_supported =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MVHEVC_ENCODE) > 0;
628 ctx->profile == NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN &&
629 !
ctx->multiview_supported) {
642 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
643 char name[128] = { 0};
644 int major, minor, ret;
659 ret =
CHECK_CU(dl_fn->
cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
663 av_log(avctx, loglevel,
"[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx,
name, major, minor);
664 if (((major << 4) | minor) <
NVENC_CAP) {
665 av_log(avctx, loglevel,
"does not support NVENC\n");
676 ctx->cu_context =
ctx->cu_context_internal;
688 av_log(avctx, loglevel,
"supports NVENC\n");
699 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
707 ctx->cu_context_internal =
NULL;
720 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
723 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
725#if CONFIG_AV1_NVENC_ENCODER
727 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_AV1_GUID;
759 cuda_device_hwctx = hwdev_ctx->
hwctx;
762 d3d11_device_hwctx = hwdev_ctx->
hwctx;
770 if (cuda_device_hwctx) {
772 ctx->cu_stream = cuda_device_hwctx->
stream;
775 else if (d3d11_device_hwctx) {
776 ctx->d3d11_device = d3d11_device_hwctx->
device;
777 ID3D11Device_AddRef(
ctx->d3d11_device);
787 av_log(avctx,
AV_LOG_FATAL,
"Provided device doesn't support required NVENC features\n");
791 int i, nb_devices = 0;
807 for (
i = 0;
i < nb_devices; ++
i) {
820 av_log(avctx,
AV_LOG_FATAL,
"Requested GPU %d, but only %d GPUs are available!\n",
ctx->device, nb_devices);
830 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
831#if CONFIG_AV1_NVENC_ENCODER
837 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
839 if (
ctx->init_qp_p >= 0) {
840 rc->constQP.qpInterP =
ctx->init_qp_p;
841 if (
ctx->init_qp_i >= 0 &&
ctx->init_qp_b >= 0) {
842 rc->constQP.qpIntra =
ctx->init_qp_i;
843 rc->constQP.qpInterB =
ctx->init_qp_b;
847 rc->constQP.qpInterB =
av_clip(
850 rc->constQP.qpIntra = rc->constQP.qpInterP;
851 rc->constQP.qpInterB = rc->constQP.qpInterP;
853 }
else if (
ctx->cqp >= 0) {
854 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra =
ctx->cqp;
868 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
870#if CONFIG_AV1_NVENC_ENCODER
876 if (avctx->
qmin >= 0 || avctx->
qmax >= 0)
877 av_log(avctx,
AV_LOG_WARNING,
"Passing qmin/qmax via global AVCodecContext options. Use encoder options instead.\n");
879 if (avctx->
qmin >= 0 &&
ctx->qmin < 0)
881 if (avctx->
qmax >= 0 &&
ctx->qmax < 0)
886 if (
ctx->qmin >= 0 &&
ctx->qmax >= 0) {
890 rc->minQP.qpInterB =
ctx->qmin;
891 rc->minQP.qpInterP =
ctx->qmin;
892 rc->minQP.qpIntra =
ctx->qmin;
894 rc->maxQP.qpInterB =
ctx->qmax;
895 rc->maxQP.qpInterP =
ctx->qmax;
896 rc->maxQP.qpIntra =
ctx->qmax;
898 qp_inter_p = (
ctx->qmax + 3 *
ctx->qmin) / 4;
899 }
else if (
ctx->qmin >= 0) {
902 rc->minQP.qpInterB =
ctx->qmin;
903 rc->minQP.qpInterP =
ctx->qmin;
904 rc->minQP.qpIntra =
ctx->qmin;
906 qp_inter_p =
ctx->qmin;
911 rc->enableInitialRCQP = 1;
913 if (
ctx->init_qp_p < 0) {
914 rc->initialRCQP.qpInterP = qp_inter_p;
916 rc->initialRCQP.qpInterP =
ctx->init_qp_p;
919 if (
ctx->init_qp_i < 0) {
921 rc->initialRCQP.qpIntra =
av_clip(
924 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
927 rc->initialRCQP.qpIntra =
ctx->init_qp_i;
930 if (
ctx->init_qp_b < 0) {
932 rc->initialRCQP.qpInterB =
av_clip(
935 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
938 rc->initialRCQP.qpInterB =
ctx->init_qp_b;
945 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
947 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
948 rc->constQP.qpInterB = 0;
949 rc->constQP.qpInterP = 0;
950 rc->constQP.qpIntra = 0;
959 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
962 case NV_ENC_PARAMS_RC_CONSTQP:
965 case NV_ENC_PARAMS_RC_VBR:
968 case NV_ENC_PARAMS_RC_CBR:
972 rc->rateControlMode =
ctx->rc;
981 int nb_surfaces =
FFMAX(4,
ctx->encode_config.frameIntervalP * 2 * 2);
984 if (
ctx->rc_lookahead > 0) {
987 nb_surfaces =
FFMAX(1,
FFMAX(nb_surfaces,
ctx->rc_lookahead +
ctx->encode_config.frameIntervalP + 1 + 4));
988 if (nb_surfaces >
ctx->nb_surfaces &&
ctx->nb_surfaces > 0)
991 "Defined rc_lookahead requires more surfaces, "
992 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
994 ctx->nb_surfaces =
FFMAX(nb_surfaces,
ctx->nb_surfaces);
996 if (
ctx->encode_config.frameIntervalP > 1 &&
ctx->nb_surfaces < nb_surfaces &&
ctx->nb_surfaces > 0)
999 "Defined b-frame requires more surfaces, "
1000 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
1001 ctx->nb_surfaces =
FFMAX(
ctx->nb_surfaces, nb_surfaces);
1003 else if (
ctx->nb_surfaces <= 0)
1004 ctx->nb_surfaces = nb_surfaces;
1009 ctx->async_depth =
FFMIN(
ctx->async_depth,
ctx->nb_surfaces - 1);
1013 ctx->frame_data_array_nb =
FFMAX(
ctx->nb_surfaces,
ctx->nb_surfaces +
ctx->encode_config.frameIntervalP - 1);
1023 av_log(avctx,
AV_LOG_ERROR,
"Using global_quality with nvenc is not supported. Use qp instead.\n");
1028 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate;
1029 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1030 ctx->encode_config.rcParams.maxBitRate =
ctx->encode_config.rcParams.averageBitRate;
1036 ctx->encode_config.rcParams.multiPass =
ctx->multipass;
1039 ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
1041 ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
1044 if (
ctx->cqp >= 0) {
1045 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
1046 }
else if (
ctx->quality >= 0.0f) {
1047 ctx->rc = NV_ENC_PARAMS_RC_VBR;
1051 ctx->encode_config.rcParams.cbQPIndexOffset =
ctx->qp_cb_offset;
1052 ctx->encode_config.rcParams.crQPIndexOffset =
ctx->qp_cr_offset;
1055 ctx->qp_cr_offset !=
ctx->qp_cb_offset)
1057 "av1_nvenc: qp_cr_offset is currently ignored by the NVENC driver "
1058 "(deltaQ_v_ac is forced equal to deltaQ_u_ac); only qp_cb_offset "
1062 ctx->encode_config.rcParams.lowDelayKeyFrameScale =
ctx->ldkfs;
1066 }
else if (
ctx->rc >= 0) {
1069 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
1075 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
1076 avctx->
rc_buffer_size =
ctx->encode_config.rcParams.vbvBufferSize = 2 *
ctx->encode_config.rcParams.averageBitRate;
1080 ctx->encode_config.rcParams.enableAQ = 1;
1081 ctx->encode_config.rcParams.aqStrength =
ctx->aq_strength;
1085 if (
ctx->temporal_aq) {
1086 ctx->encode_config.rcParams.enableTemporalAQ = 1;
1090 if (
ctx->rc_lookahead > 0) {
1091 int lkd_bound =
FFMIN(
ctx->nb_surfaces,
ctx->async_depth) -
1092 ctx->encode_config.frameIntervalP - 4;
1094 if (lkd_bound < 0) {
1095 ctx->encode_config.rcParams.enableLookahead = 0;
1097 "Lookahead not enabled. Increase buffer delay (-delay).\n");
1099 ctx->encode_config.rcParams.enableLookahead = 1;
1100 ctx->encode_config.rcParams.lookaheadDepth =
av_clip(
ctx->rc_lookahead, 0, lkd_bound);
1101 ctx->encode_config.rcParams.disableIadapt =
ctx->no_scenecut;
1102 ctx->encode_config.rcParams.disableBadapt = !
ctx->b_adapt;
1104 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
1105 ctx->encode_config.rcParams.lookaheadDepth,
1106 ctx->encode_config.rcParams.disableIadapt ?
"disabled" :
"enabled",
1107 ctx->encode_config.rcParams.disableBadapt ?
"disabled" :
"enabled");
1108 if (
ctx->encode_config.rcParams.lookaheadDepth <
ctx->rc_lookahead)
1109 av_log(avctx,
AV_LOG_WARNING,
"Clipping lookahead depth to %d (from %d) due to lack of surfaces/delay",
1110 ctx->encode_config.rcParams.lookaheadDepth,
ctx->rc_lookahead);
1112#ifdef NVENC_HAVE_LOOKAHEAD_LEVEL
1113 if (
ctx->lookahead_level >= 0) {
1114 switch (
ctx->lookahead_level) {
1115 case NV_ENC_LOOKAHEAD_LEVEL_0:
1116 case NV_ENC_LOOKAHEAD_LEVEL_1:
1117 case NV_ENC_LOOKAHEAD_LEVEL_2:
1118 case NV_ENC_LOOKAHEAD_LEVEL_3:
1119 case NV_ENC_LOOKAHEAD_LEVEL_AUTOSELECT:
1126 ctx->encode_config.rcParams.lookaheadLevel =
ctx->lookahead_level;
1132 if (
ctx->strict_gop) {
1133 ctx->encode_config.rcParams.strictGOPTarget = 1;
1138 ctx->encode_config.rcParams.enableNonRefP = 1;
1140 if (
ctx->zerolatency)
1141 ctx->encode_config.rcParams.zeroReorderDelay = 1;
1145 int tmp_quality = (int)(
ctx->quality * 256.0f);
1146 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1147 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1152 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate = 0;
1163 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1164 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1165 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1173 vui->videoFullRangeFlag = 0;
1182 vui->colourDescriptionPresentFlag =
1183 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1185 vui->videoSignalTypePresentFlag =
1186 (vui->colourDescriptionPresentFlag
1187 || vui->videoFormat != 5
1188 || vui->videoFullRangeFlag != 0);
1190 if (
ctx->max_slice_size > 0) {
1191 h264->sliceMode = 1;
1192 h264->sliceModeData =
ctx->max_slice_size;
1194 h264->sliceMode = 3;
1195 h264->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1198 if (
ctx->intra_refresh) {
1199 h264->enableIntraRefresh = 1;
1200 h264->intraRefreshPeriod = cc->gopLength;
1201 h264->intraRefreshCnt = cc->gopLength - 1;
1202 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1203 h264->outputRecoveryPointSEI = 1;
1204 h264->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1207 if (
ctx->constrained_encoding)
1208 h264->enableConstrainedEncoding = 1;
1212 h264->outputAUD =
ctx->aud;
1214 if (
ctx->dpb_size >= 0) {
1216 h264->maxNumRefFrames =
ctx->dpb_size;
1219 h264->idrPeriod = cc->gopLength;
1221 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1223 h264->outputBufferingPeriodSEI =
ctx->cbr_padding;
1225 h264->enableFillerDataInsertion =
ctx->cbr_padding;
1228 h264->outputPictureTimingSEI = 1;
1231 h264->qpPrimeYZeroTransformBypassFlag = 1;
1233 switch(
ctx->profile) {
1235 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1237 if (cc->frameIntervalP > 1) {
1239 "B-frames are not supported by H.264 Baseline profile, disabling.\n");
1240 cc->frameIntervalP = 1;
1244 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1248 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1251#ifdef NVENC_HAVE_H264_10BIT_SUPPORT
1252 case NV_ENC_H264_PROFILE_HIGH_10:
1253 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
1257#ifdef NVENC_HAVE_422_SUPPORT
1258 case NV_ENC_H264_PROFILE_HIGH_422:
1259 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
1264 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1270#ifdef NVENC_HAVE_H264_10BIT_SUPPORT
1273 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_10_GUID;
1280 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1284#ifdef NVENC_HAVE_422_SUPPORT
1287 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_422_GUID;
1296 h264->level =
ctx->level;
1298#ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1299 h264->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1300 h264->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1303 if (
ctx->coder >= 0)
1304 h264->entropyCodingMode =
ctx->coder;
1306 if (
ctx->b_ref_mode >= 0)
1307 h264->useBFramesAsRef =
ctx->b_ref_mode;
1309 h264->numRefL0 = avctx->
refs;
1310 h264->numRefL1 = avctx->
refs;
1312#ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
1313 if (
ctx->tf_level >= 0) {
1314 h264->tfLevel =
ctx->tf_level;
1316 switch (
ctx->tf_level)
1318 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1319 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1326 if (
ctx->encode_config.frameIntervalP < 5)
1331#ifdef NVENC_HAVE_TIME_CODE
1333 h264->enableTimeCode = 1;
1342 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1343 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1344 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1352 vui->videoFullRangeFlag = 0;
1361 vui->colourDescriptionPresentFlag =
1362 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1364 vui->videoSignalTypePresentFlag =
1365 (vui->colourDescriptionPresentFlag
1366 || vui->videoFormat != 5
1367 || vui->videoFullRangeFlag != 0);
1369 if (
ctx->max_slice_size > 0) {
1370 hevc->sliceMode = 1;
1371 hevc->sliceModeData =
ctx->max_slice_size;
1373 hevc->sliceMode = 3;
1374 hevc->sliceModeData = avctx->
slices > 0 ? avctx->
slices : 1;
1377 if (
ctx->intra_refresh) {
1378 hevc->enableIntraRefresh = 1;
1379 hevc->intraRefreshPeriod = cc->gopLength;
1380 hevc->intraRefreshCnt = cc->gopLength - 1;
1381 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1382#ifdef NVENC_HAVE_HEVC_OUTPUT_RECOVERY_POINT_SEI
1383 hevc->outputRecoveryPointSEI = 1;
1385 hevc->singleSliceIntraRefresh =
ctx->single_slice_intra_refresh;
1388#ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
1397 if (
ctx->constrained_encoding)
1398 hevc->enableConstrainedEncoding = 1;
1402 hevc->outputAUD =
ctx->aud;
1404 if (
ctx->dpb_size >= 0) {
1406 hevc->maxNumRefFramesInDPB =
ctx->dpb_size;
1409 hevc->idrPeriod = cc->gopLength;
1411 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1413 hevc->outputBufferingPeriodSEI =
ctx->cbr_padding;
1415 hevc->enableFillerDataInsertion =
ctx->cbr_padding;
1418 hevc->outputPictureTimingSEI = 1;
1420#ifdef NVENC_HAVE_MVHEVC
1427 ctx->profile = NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN;
1429 if (
ctx->profile == NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN && stereo3d &&
1440 switch (
ctx->profile) {
1442 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1446 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1450 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1453#ifdef NVENC_HAVE_MVHEVC
1454 case NV_ENC_HEVC_PROFILE_MULTIVIEW_MAIN:
1455 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1459 hevc->enableMVHEVC = 1;
1460 hevc->outputHevc3DReferenceDisplayInfo = 1;
1469 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1475 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1479#ifdef NVENC_HAVE_MVHEVC
1481 av_log(avctx,
AV_LOG_ERROR,
"Multiview encoding only works for Main profile content.\n");
1488#ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1489 hevc->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1490 hevc->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1492 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1495 hevc->level =
ctx->level;
1497 hevc->tier =
ctx->tier;
1499 if (
ctx->b_ref_mode >= 0)
1500 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1502 hevc->numRefL0 = avctx->
refs;
1503 hevc->numRefL1 = avctx->
refs;
1505#ifdef NVENC_HAVE_TEMPORAL_FILTER
1506 if (
ctx->tf_level >= 0) {
1507 hevc->tfLevel =
ctx->tf_level;
1509 switch (
ctx->tf_level)
1511 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1512 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1519 if (
ctx->encode_config.frameIntervalP < 5)
1527#if CONFIG_AV1_NVENC_ENCODER
1531 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1532 NV_ENC_CONFIG_AV1 *av1 = &cc->encodeCodecConfig.av1Config;
1540 av1->colorRange = 0;
1550 av_log(avctx,
AV_LOG_ERROR,
"AV1 High Profile not supported, required for 4:4:4 encoding\n");
1553 cc->profileGUID = NV_ENC_AV1_PROFILE_MAIN_GUID;
1557 if (
ctx->dpb_size >= 0) {
1559 av1->maxNumRefFramesInDPB =
ctx->dpb_size;
1562 if (
ctx->intra_refresh) {
1563 av1->enableIntraRefresh = 1;
1564 av1->intraRefreshPeriod = cc->gopLength;
1565 av1->intraRefreshCnt = cc->gopLength - 1;
1566 cc->gopLength = NVENC_INFINITE_GOPLENGTH;
1569 av1->idrPeriod = cc->gopLength;
1571 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1572 av1->enableBitstreamPadding =
ctx->cbr_padding;
1575 if (
ctx->tile_cols >= 0)
1576 av1->numTileColumns =
ctx->tile_cols;
1577 if (
ctx->tile_rows >= 0)
1578 av1->numTileRows =
ctx->tile_rows;
1580 av1->outputAnnexBFormat = 0;
1582 av1->level =
ctx->level;
1583 av1->tier =
ctx->tier;
1585 av1->enableTimingInfo =
ctx->timing_info;
1588 av1->disableSeqHdr = 0;
1589 av1->repeatSeqHdr = 1;
1591 av1->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1593#ifdef NVENC_HAVE_NEW_BIT_DEPTH_API
1594 av1->inputBitDepth =
IS_10BIT(
ctx->data_pix_fmt) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1595 av1->outputBitDepth = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8;
1597 av1->inputPixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1598 av1->pixelBitDepthMinus8 = (
IS_10BIT(
ctx->data_pix_fmt) ||
ctx->highbitdepth) ? 2 : 0;
1601#ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
1610 if (
ctx->b_ref_mode >= 0)
1611 av1->useBFramesAsRef =
ctx->b_ref_mode;
1613 av1->numFwdRefs = avctx->
refs;
1614 av1->numBwdRefs = avctx->
refs;
1616#ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
1617 if (
ctx->tf_level >= 0) {
1618 av1->tfLevel =
ctx->tf_level;
1620 switch (
ctx->tf_level)
1622 case NV_ENC_TEMPORAL_FILTER_LEVEL_0:
1623 case NV_ENC_TEMPORAL_FILTER_LEVEL_4:
1630 if (
ctx->encode_config.frameIntervalP < 5)
1646#if CONFIG_AV1_NVENC_ENCODER
1648 return nvenc_setup_av1_config(avctx);
1662#if CONFIG_AV1_NVENC_ENCODER
1693 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1695 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1696 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1701 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1702 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1704 ctx->init_encode_params.encodeHeight = avctx->
height;
1705 ctx->init_encode_params.encodeWidth = avctx->
width;
1707 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1709 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1710 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1712 ctx->init_encode_params.tuningInfo =
ctx->tuning_info;
1715 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1717 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1719 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(
ctx->nvencoder,
1720 ctx->init_encode_params.encodeGUID,
1721 ctx->init_encode_params.presetGUID,
1722 ctx->init_encode_params.tuningInfo,
1724 if (nv_status != NV_ENC_SUCCESS)
1725 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1727 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1729 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1732 ctx->init_encode_params.darHeight = dh;
1733 ctx->init_encode_params.darWidth = dw;
1743#ifdef NVENC_HAVE_UNIDIR_B
1744 ctx->init_encode_params.enableUniDirectionalB =
ctx->unidir_b;
1747 ctx->init_encode_params.enableEncodeAsync = 0;
1748 ctx->init_encode_params.enablePTD = 1;
1753 if (
ctx->rc_lookahead == 0 &&
ctx->encode_config.rcParams.enableLookahead)
1754 ctx->rc_lookahead =
ctx->encode_config.rcParams.lookaheadDepth;
1756 if (
ctx->weighted_pred == 1)
1757 ctx->init_encode_params.enableWeightedPrediction = 1;
1759#ifdef NVENC_HAVE_SPLIT_FRAME_ENCODING
1760 ctx->init_encode_params.splitEncodeMode =
ctx->split_encode_mode;
1762 if (
ctx->split_encode_mode != NV_ENC_SPLIT_DISABLE_MODE) {
1764 av_log(avctx,
AV_LOG_WARNING,
"Split encoding not supported with weighted prediction enabled.\n");
1768 if (
ctx->bluray_compat) {
1777 ctx->level = NV_ENC_LEVEL_HEVC_51;
1778 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1787 ctx->encode_config.frameIntervalP = 0;
1788 ctx->encode_config.gopLength = 1;
1797 if(
ctx->single_slice_intra_refresh)
1798 ctx->intra_refresh = 1;
1807 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1809 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1820 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1821 if (nv_status != NV_ENC_SUCCESS) {
1826 if (
ctx->cu_context) {
1827 nv_status = p_nvenc->nvEncSetIOCudaStreams(
ctx->nvencoder, &
ctx->cu_stream, &
ctx->cu_stream);
1828 if (nv_status != NV_ENC_SUCCESS) {
1838 if (
ctx->encode_config.frameIntervalP > 1)
1841 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1842 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1849 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1858 return NV_ENC_BUFFER_FORMAT_YV12;
1860 return NV_ENC_BUFFER_FORMAT_NV12;
1864 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1867 return NV_ENC_BUFFER_FORMAT_YUV444;
1873 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1876 return NV_ENC_BUFFER_FORMAT_ARGB;
1879 return NV_ENC_BUFFER_FORMAT_ABGR;
1881 return NV_ENC_BUFFER_FORMAT_ARGB10;
1883 return NV_ENC_BUFFER_FORMAT_ABGR10;
1884#ifdef NVENC_HAVE_422_SUPPORT
1886 return NV_ENC_BUFFER_FORMAT_NV16;
1890 return NV_ENC_BUFFER_FORMAT_P210;
1893 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1901 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1904 NVENCSTATUS nv_status;
1905 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1906 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1910 if (!
ctx->surfaces[idx].in_ref)
1913 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1916 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1922 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1923 allocSurf.width = avctx->
width;
1924 allocSurf.height = avctx->
height;
1925 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1927 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
1928 if (nv_status != NV_ENC_SUCCESS) {
1932 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1933 ctx->surfaces[idx].width = allocSurf.width;
1934 ctx->surfaces[idx].height = allocSurf.height;
1937 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
1938 if (nv_status != NV_ENC_SUCCESS) {
1941 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
1942 ctx->surfaces[idx].input_surface =
NULL;
1948 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1958 int i, res = 0, res2;
1964 ctx->frame_data_array =
av_calloc(
ctx->frame_data_array_nb,
sizeof(*
ctx->frame_data_array));
1965 if (!
ctx->frame_data_array)
1970 if (!
ctx->timestamp_list)
1974 if (!
ctx->unused_surface_queue)
1978 if (!
ctx->output_surface_queue)
1981 if (!
ctx->output_surface_ready_queue)
1988 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
2005 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2007 NVENCSTATUS nv_status;
2008 uint32_t outSize = 0;
2009 char tmpHeader[NV_MAX_SEQ_HDR_LEN];
2011 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
2012 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
2014 payload.spsppsBuffer = tmpHeader;
2015 payload.inBufferSize =
sizeof(tmpHeader);
2016 payload.outSPSPPSPayloadSize = &outSize;
2018 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
2019 if (nv_status != NV_ENC_SUCCESS) {
2030 memcpy(avctx->
extradata, tmpHeader, outSize);
2039 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2043 if (
ctx->nvencoder) {
2044 NV_ENC_PIC_PARAMS
params = { .version = NV_ENC_PIC_PARAMS_VER,
2045 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
2051 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &
params);
2059 if (
ctx->frame_data_array) {
2060 for (
i = 0;
i <
ctx->frame_data_array_nb;
i++)
2066 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2067 if (
ctx->registered_frames[
i].mapped)
2068 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
2069 if (
ctx->registered_frames[
i].regptr)
2070 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2072 ctx->nb_registered_frames = 0;
2075 if (
ctx->surfaces) {
2076 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
2078 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
2080 if (
ctx->surfaces[
i].output_surface)
2081 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
2085 ctx->nb_surfaces = 0;
2091 if (
ctx->nvencoder) {
2092 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
2100 if (
ctx->cu_context_internal)
2102 ctx->cu_context =
ctx->cu_context_internal =
NULL;
2105 if (
ctx->d3d11_device) {
2106 ID3D11Device_Release(
ctx->d3d11_device);
2111 nvenc_free_functions(&dl_fn->
nvenc_dl);
2112 cuda_free_functions(&dl_fn->
cuda_dl);
2130 "hw_frames_ctx must be set when using GPU frames as input\n");
2136 "hw_frames_ctx must match the GPU frame type\n");
2185 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
2187 int dst_linesize[4] = {
2188 lock_buffer_params->pitch,
2189 lock_buffer_params->pitch,
2190 lock_buffer_params->pitch,
2191 lock_buffer_params->pitch
2193 uint8_t *dst_data[4];
2197 dst_linesize[1] = dst_linesize[2] >>= 1;
2200 lock_buffer_params->bufferDataPtr, dst_linesize);
2205 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
2218 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2219 NVENCSTATUS nv_status;
2224 for (first_round = 1; first_round >= 0; first_round--) {
2225 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2226 if (!
ctx->registered_frames[
i].mapped) {
2227 if (
ctx->registered_frames[
i].regptr) {
2230 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
2231 if (nv_status != NV_ENC_SUCCESS)
2232 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
2233 ctx->registered_frames[
i].ptr =
NULL;
2234 ctx->registered_frames[
i].regptr =
NULL;
2241 return ctx->nb_registered_frames++;
2252 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2255 NV_ENC_REGISTER_RESOURCE reg = { 0 };
2258 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
2261 ctx->registered_frames[
i].ptr ==
frame->data[0])
2271 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
2272 reg.width = frames_ctx->
width;
2273 reg.height = frames_ctx->
height;
2274 reg.pitch =
frame->linesize[0];
2275 reg.resourceToRegister =
frame->data[0];
2278 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
2279#ifdef NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
2282 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDAARRAY;
2283 reg.pitch = frames_ctx->
width * (
desc &&
desc->comp[0].depth > 8 ? 2 : 1);
2287 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
2288 reg.subResourceIndex = (intptr_t)
frame->data[1];
2292#ifdef NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
2293 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED &&
2294 reg.resourceType == NV_ENC_INPUT_RESOURCE_TYPE_CUDAARRAY) {
2297 reg.bufferFormat = NV_ENC_BUFFER_FORMAT_YUV444;
2302 reg.bufferFormat = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
2309 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
2315 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
2316 if (ret != NV_ENC_SUCCESS) {
2321 ctx->registered_frames[idx].ptr =
frame->data[0];
2322 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
2323 ctx->registered_frames[idx].regptr = reg.registeredResource;
2333 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2336 NVENCSTATUS nv_status;
2349 if (!
ctx->registered_frames[reg_idx].mapped) {
2350 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
2351 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
2352 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
2353 if (nv_status != NV_ENC_SUCCESS) {
2359 ctx->registered_frames[reg_idx].mapped += 1;
2361 nvenc_frame->
reg_idx = reg_idx;
2362 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
2363 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
2368 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
2370 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
2373 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
2374 if (nv_status != NV_ENC_SUCCESS) {
2375 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
2378 nvenc_frame->
pitch = lockBufferParams.pitch;
2381 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
2382 if (nv_status != NV_ENC_SUCCESS) {
2390#ifdef NVENC_HAVE_TIME_CODE
2396 uint32_t *tc = (uint32_t*)sd->
data;
2401 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2402 time_code->skipClockTimestampInsertion = 1;
2405 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME_DOUBLING;
2408 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME_TRIPLING;
2411 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2415 for (
int i = 0;
i < cnt;
i++) {
2416 unsigned hh, mm,
ss, ff, drop;
2419#ifdef NVENC_NEW_COUNTING_TYPE
2420 time_code->clockTimestamp[
i].countingTypeLSB = 0;
2421 time_code->clockTimestamp[
i].countingTypeMSB = 0;
2423 time_code->clockTimestamp[
i].countingType = 0;
2425 time_code->clockTimestamp[
i].discontinuityFlag = 0;
2426 time_code->clockTimestamp[
i].cntDroppedFrames = drop;
2427 time_code->clockTimestamp[
i].nFrames = ff;
2428 time_code->clockTimestamp[
i].secondsValue =
ss;
2429 time_code->clockTimestamp[
i].minutesValue = mm;
2430 time_code->clockTimestamp[
i].hoursValue = hh;
2431 time_code->clockTimestamp[
i].timeOffset = 0;
2434 time_code->displayPicStruct = NV_ENC_PIC_STRUCT_DISPLAY_FRAME;
2435 time_code->skipClockTimestampInsertion = 1;
2441 NV_ENC_PIC_PARAMS *
params,
2442 NV_ENC_SEI_PAYLOAD *sei_data,
2449 params->codecPicParams.h264PicParams.sliceMode =
2450 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
2451 params->codecPicParams.h264PicParams.sliceModeData =
2452 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
2453 if (sei_count > 0) {
2454 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
2455 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
2458#ifdef NVENC_HAVE_TIME_CODE
2460 nvenc_fill_time_code(avctx,
frame, &
params->codecPicParams.h264PicParams.timeCode);
2465 params->codecPicParams.hevcPicParams.sliceMode =
2466 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
2467 params->codecPicParams.hevcPicParams.sliceModeData =
2468 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
2469 if (sei_count > 0) {
2470 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
2471 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
2475#if CONFIG_AV1_NVENC_ENCODER
2477 params->codecPicParams.av1PicParams.numTileColumns =
2478 ctx->encode_config.encodeCodecConfig.av1Config.numTileColumns;
2479 params->codecPicParams.av1PicParams.numTileRows =
2480 ctx->encode_config.encodeCodecConfig.av1Config.numTileRows;
2481 if (sei_count > 0) {
2482 params->codecPicParams.av1PicParams.obuPayloadArray = sei_data;
2483 params->codecPicParams.av1PicParams.obuPayloadArrayCnt = sei_count;
2514 NV_ENC_LOCK_BITSTREAM *
params,
2529 delay =
FFMAX(
ctx->encode_config.frameIntervalP - 1, 0);
2530#ifdef NVENC_HAVE_MVHEVC
2531 delay *=
ctx->multiview ? 2 : 1;
2533 if (
ctx->output_frame_num >= delay) {
2535 ctx->output_frame_num++;
2539 delay_time =
ctx->initial_delay_time;
2547 delay_time = t1 - t2;
2552 delay_time = delay * (t3 - t2);
2556 ctx->initial_delay_time = delay_time;
2565 ctx->output_frame_num++;
2575 int idx =
ctx->frame_data_array_pos;
2590 ctx->frame_data_array_pos = (
ctx->frame_data_array_pos + 1) %
ctx->frame_data_array_nb;
2591 pic_params->inputDuration = idx;
2601 int idx = lock_params->outputDuration;
2621 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2623 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
2624 NVENCSTATUS nv_status;
2629 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
2631 lock_params.doNotWait = 0;
2634 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
2635 if (nv_status != NV_ENC_SUCCESS) {
2647 memcpy(
pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
2649 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
2650 if (nv_status != NV_ENC_SUCCESS) {
2651 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
2657 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
2658 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
2659 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
2660 if (nv_status != NV_ENC_SUCCESS) {
2664 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
2674 switch (lock_params.pictureType) {
2675 case NV_ENC_PIC_TYPE_IDR:
2678 case NV_ENC_PIC_TYPE_I:
2681 case NV_ENC_PIC_TYPE_P:
2684 case NV_ENC_PIC_TYPE_B:
2687 case NV_ENC_PIC_TYPE_BI:
2691 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
2692 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
2720 int nb_ready, nb_pending;
2725 return nb_ready > 0;
2726 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
2736 void *a53_data =
NULL;
2737 size_t a53_size = 0;
2745 &
ctx->sei_data_size,
2746 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2753 ctx->sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2754 ctx->sei_data[sei_count].payload = (uint8_t*)a53_data;
2756#if CONFIG_AV1_NVENC_ENCODER
2769 void *tc_data =
NULL;
2780 &
ctx->sei_data_size,
2781 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2788 ctx->sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2789 ctx->sei_data[sei_count].payload = (uint8_t*)tc_data;
2791#if CONFIG_AV1_NVENC_ENCODER
2806 for (
i = 0;
i <
frame->nb_side_data;
i++) {
2814 &
ctx->sei_data_size,
2815 (sei_count + 1) *
sizeof(*
ctx->sei_data));
2821 ctx->sei_data[sei_count].payloadSize = side_data->
size;
2825 if (!
ctx->sei_data[sei_count].payload) {
2837 for (
i = 0;
i < sei_count;
i++)
2846 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
2849 NV_ENC_RECONFIGURE_PARAMS
params = { 0 };
2850 int needs_reconfig = 0;
2851 int needs_encode_config = 0;
2852 int reconfig_bitrate = 0, reconfig_dar = 0;
2855 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2856 params.reInitEncodeParams =
ctx->init_encode_params;
2859 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
2861 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2862 ctx->init_encode_params.darWidth,
2863 ctx->init_encode_params.darHeight, dw, dh);
2865 params.reInitEncodeParams.darHeight = dh;
2866 params.reInitEncodeParams.darWidth = dw;
2872 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
2873 if (avctx->
bit_rate > 0 &&
params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
2875 "avg bitrate change: %d -> %d\n",
2876 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2879 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
2880 reconfig_bitrate = 1;
2885 "max bitrate change: %d -> %d\n",
2886 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2889 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
2890 reconfig_bitrate = 1;
2895 "vbv buffer size change: %d -> %d\n",
2896 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2900 reconfig_bitrate = 1;
2903 if (reconfig_bitrate) {
2907 needs_encode_config = 1;
2912 if (!needs_encode_config)
2913 params.reInitEncodeParams.encodeConfig =
NULL;
2915 if (needs_reconfig) {
2916 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, &
params);
2917 if (ret != NV_ENC_SUCCESS) {
2921 ctx->init_encode_params.darHeight = dh;
2922 ctx->init_encode_params.darWidth = dw;
2925 if (reconfig_bitrate) {
2926 ctx->encode_config.rcParams.averageBitRate =
params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2927 ctx->encode_config.rcParams.maxBitRate =
params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2928 ctx->encode_config.rcParams.vbvBufferSize =
params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2935#ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
2937 MASTERING_DISPLAY_INFO *mastering_disp_info, CONTENT_LIGHT_LEVEL *content_light_level)
2941 if (
ctx->mdm ||
ctx->cll) {
2960 mastering_disp_info->r.x =
av_rescale(mdm->display_primaries[0][0].num, chroma_den,
2961 mdm->display_primaries[0][0].den);
2962 mastering_disp_info->r.y =
av_rescale(mdm->display_primaries[0][1].num, chroma_den,
2963 mdm->display_primaries[0][1].den);
2964 mastering_disp_info->g.x =
av_rescale(mdm->display_primaries[1][0].num, chroma_den,
2965 mdm->display_primaries[1][0].den);
2966 mastering_disp_info->g.y =
av_rescale(mdm->display_primaries[1][1].num, chroma_den,
2967 mdm->display_primaries[1][1].den);
2968 mastering_disp_info->b.x =
av_rescale(mdm->display_primaries[2][0].num, chroma_den,
2969 mdm->display_primaries[2][0].den);
2970 mastering_disp_info->b.y =
av_rescale(mdm->display_primaries[2][1].num, chroma_den,
2971 mdm->display_primaries[2][1].den);
2972 mastering_disp_info->whitePoint.x =
av_rescale(mdm->white_point[0].num, chroma_den,
2973 mdm->white_point[0].den);
2974 mastering_disp_info->whitePoint.y =
av_rescale(mdm->white_point[1].num, chroma_den,
2975 mdm->white_point[1].den);
2976 mastering_disp_info->maxLuma =
av_rescale(mdm->max_luminance.num, max_luma_den,
2977 mdm->max_luminance.den);
2978 mastering_disp_info->minLuma =
av_rescale(mdm->min_luminance.num, min_luma_den,
2979 mdm->min_luminance.den);
2982 pic_params->codecPicParams.hevcPicParams.pMasteringDisplay = mastering_disp_info;
2984 pic_params->codecPicParams.av1PicParams.pMasteringDisplay = mastering_disp_info;
2991 content_light_level->maxContentLightLevel = cll->MaxCLL;
2992 content_light_level->maxPicAverageLightLevel = cll->MaxFALL;
2995 pic_params->codecPicParams.hevcPicParams.pMaxCll = content_light_level;
2997 pic_params->codecPicParams.av1PicParams.pMaxCll = content_light_level;
3009 NVENCSTATUS nv_status;
3014#ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
3015 MASTERING_DISPLAY_INFO mastering_disp_info = { 0 };
3016 CONTENT_LIGHT_LEVEL content_light_level = { 0 };
3018#ifdef NVENC_HAVE_MVHEVC
3019 HEVC_3D_REFERENCE_DISPLAY_INFO ref_disp_info = { 0 };
3024 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
3026 NV_ENC_PIC_PARAMS pic_params = { 0 };
3027 pic_params.version = NV_ENC_PIC_PARAMS_VER;
3029 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
3053 pic_params.bufferFmt = in_surf->
format;
3054 pic_params.inputWidth = in_surf->
width;
3055 pic_params.inputHeight = in_surf->
height;
3056 pic_params.inputPitch = in_surf->
pitch;
3061 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
3063 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
3065 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
3069 pic_params.encodePicFlags =
3070 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
3072 pic_params.encodePicFlags = 0;
3075 pic_params.frameIdx =
ctx->frame_idx_counter++;
3076 pic_params.inputTimeStamp =
frame->pts;
3078 if (
ctx->extra_sei) {
3085#ifdef NVENC_HAVE_HEVC_AND_AV1_MASTERING_METADATA
3086 res = nvenc_set_mastering_display_data(avctx,
frame, &pic_params, &mastering_disp_info, &content_light_level);
3091#ifdef NVENC_HAVE_MVHEVC
3092 if (
ctx->multiview) {
3097 ctx->next_view_id = *(
int*)sd_view_id->
data;
3099 pic_params.codecPicParams.hevcPicParams.viewId =
ctx->next_view_id;
3123 pic_params.codecPicParams.hevcPicParams.p3DReferenceDisplayInfo = &ref_disp_info;
3124 ctx->display_sei_sent = 1;
3125 }
else if (!
ctx->display_sei_sent) {
3126 ref_disp_info.precRefDisplayWidth = 31;
3127 ref_disp_info.leftViewId[0] = 0;
3128 ref_disp_info.rightViewId[0] = 1;
3130 pic_params.codecPicParams.hevcPicParams.p3DReferenceDisplayInfo = &ref_disp_info;
3131 ctx->display_sei_sent = 1;
3134 ctx->next_view_id = !
ctx->next_view_id;
3144 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
3151 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
3153 for (
i = 0;
i < sei_count;
i++)
3160 if (nv_status != NV_ENC_SUCCESS &&
3161 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
3172 if (nv_status == NV_ENC_SUCCESS) {
3173 while (
av_fifo_read(
ctx->output_surface_queue, &tmp_out_surf, 1) >= 0)
3189 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
3192 if (!
frame->buf[0]) {
3237 ctx->output_frame_num = 0;
3238 ctx->initial_delay_time = 0;
SwsAArch64OpImplParams params
static double val(void *priv, double ch)
static AVFormatContext * ctx
int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len, void **data, size_t *sei_size)
Check AVFrame for A53 side data and allocate and fill SEI message with A53 info.
#define flags(name, subs,...)
#define i(width, name, range_min, range_max)
#define ss(width, name, subs,...)
static __device__ float fabs(float a)
#define AV_PROFILE_HEVC_MULTIVIEW_MAIN
#define AV_PROFILE_H264_MAIN
#define AV_PROFILE_H264_HIGH_444_PREDICTIVE
#define AV_PROFILE_HEVC_REXT
#define AV_PROFILE_HEVC_MAIN
#define AV_PROFILE_HEVC_MAIN_10
#define AV_PROFILE_H264_HIGH
#define AV_PROFILE_H264_HIGH_10
#define AV_PROFILE_AV1_MAIN
#define AV_PROFILE_H264_HIGH_422
#define AV_PROFILE_H264_BASELINE
static enum AVPixelFormat pix_fmt
void(* flush)(AVBSFContext *ctx)
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
Get a buffer for a packet.
int ff_encode_get_frame(AVCodecContext *avctx, AVFrame *frame)
Called by encoders to get the next frame for encoding.
AVCPBProperties * ff_encode_add_cpb_side_data(AVCodecContext *avctx)
Add a CPB properties side data to an encoding context.
int ff_encode_add_stats_side_data(AVPacket *pkt, int quality, const int64_t error[], int error_count, enum AVPictureType pict_type)
FrameData * frame_data(AVFrame *frame)
Get our axiliary frame data attached to the frame, allocating it if needed.
#define AV_CODEC_FLAG_INTERLACED_DCT
Use interlaced DCT.
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
#define AV_CODEC_FLAG_COPY_OPAQUE
#define AV_CODEC_PROP_REORDER
Codec supports frame reordering.
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
#define AVERROR_EXTERNAL
Generic error in an external library.
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
#define AVERROR_EOF
End of file.
AVFifo * av_fifo_alloc2(size_t nb_elems, size_t elem_size, unsigned int flags)
Allocate and initialize an AVFifo with a given element size.
void av_fifo_freep2(AVFifo **f)
Free an AVFifo and reset pointer to NULL.
void av_fifo_reset2(AVFifo *f)
size_t av_fifo_can_read(const AVFifo *f)
int av_fifo_peek(const AVFifo *f, void *buf, size_t nb_elems, size_t offset)
Read data from a FIFO without modifying FIFO state.
int av_fifo_write(AVFifo *f, const void *buf, size_t nb_elems)
Write data into a FIFO.
int av_fifo_read(AVFifo *f, void *buf, size_t nb_elems)
Read data from a FIFO.
#define AV_FRAME_FLAG_TOP_FIELD_FIRST
A flag to mark frames where the top field is displayed first if the content is interlaced.
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
int av_frame_ref(AVFrame *dst, const AVFrame *src)
Set up a new reference to the data described by the source frame.
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
static const AVFrameSideData * av_frame_side_data_get(AVFrameSideData *const *sd, const int nb_sd, enum AVFrameSideDataType type)
Wrapper around av_frame_side_data_get_c() to workaround the limitation that for any type T the conver...
@ AV_FRAME_DATA_VIEW_ID
This side data must be associated with a video frame.
@ AV_FRAME_DATA_CONTENT_LIGHT_LEVEL
Content light level (based on CTA-861.3).
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
@ AV_FRAME_DATA_SEI_UNREGISTERED
User data unregistered metadata associated with a video frame.
@ AV_FRAME_DATA_MASTERING_DISPLAY_METADATA
Mastering display metadata associated with a video frame.
@ AV_FRAME_DATA_3D_REFERENCE_DISPLAYS
This side data contains information about the reference display width(s) and reference viewing distan...
@ AV_FRAME_DATA_S12M_TIMECODE
Timecode which conforms to SMPTE ST 12-1.
@ AV_FRAME_DATA_STEREO3D
Stereoscopic 3d metadata.
#define AV_LOG_WARNING
Something somehow does not look correct.
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
#define AV_LOG_VERBOSE
Detailed information.
#define AV_LOG_INFO
Standard information.
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height, uint8_t *ptr, const int linesizes[4])
Fill plane data pointers for an image with pixel format pix_fmt and height height.
static void av_image_copy2(uint8_t *const dst_data[4], const int dst_linesizes[4], uint8_t *const src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height)
Wrapper around av_image_copy() to workaround the limitation that the conversion from uint8_t * const ...
@ AV_PICTURE_TYPE_I
Intra.
@ AV_PICTURE_TYPE_BI
BI type.
@ AV_PICTURE_TYPE_P
Predicted.
@ AV_PICTURE_TYPE_B
Bi-dir predicted.
#define AV_NOPTS_VALUE
Undefined timestamp value.
static av_always_inline AV3DReferenceDisplay * av_tdrdi_get_display(AV3DReferenceDisplaysInfo *tdrdi, unsigned int idx)
@ AV_STEREO3D_2D
Video is not stereoscopic (and metadata has to be there).
@ AV_STEREO3D_UNSPEC
Video is stereoscopic but the packing is unspecified.
@ AV_STEREO3D_FRAMESEQUENCE
Views are alternated temporally.
#define HW_CONFIG_ENCODER_DEVICE(format, device_type_)
#define HW_CONFIG_ENCODER_FRAMES(format, device_type_)
@ AV_HWDEVICE_TYPE_D3D11VA
An API-specific header for AV_HWDEVICE_TYPE_CUDA.
@ AV1_METADATA_TYPE_TIMECODE
@ AV1_METADATA_TYPE_ITUT_T35
common internal api header.
int ff_alloc_timecode_metadata_av1(const AVFrame *frame, AVRational rate, void **data, size_t *size)
int ff_alloc_timecode_sei(const AVFrame *frame, AVRational rate, size_t prefix_len, void **data, size_t *sei_size)
Check AVFrame for S12M timecode side data and allocate and fill TC SEI message with timecode info.
void ff_timecode_set_smpte(unsigned *drop, unsigned *hh, unsigned *mm, unsigned *ss, unsigned *ff, AVRational rate, uint32_t tcsmpte, int prevent_df, int skip_field)
Convert SMPTE 12M binary representation to sei info.
#define FFSWAP(type, a, b)
void * av_calloc(size_t nmemb, size_t size)
Memory handling functions.
static void nvenc_override_rate_control(AVCodecContext *avctx)
static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
static av_cold void set_constqp(AVCodecContext *avctx)
static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
static int nvenc_push_context(AVCodecContext *avctx)
av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
static NvencSurface * get_free_frame(NvencContext *ctx)
#define to_nv_color_trc(n)
static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
#define to_nv_color_matrix(n)
int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
static void nvenc_codec_specific_pic_params(AVCodecContext *avctx, const AVFrame *frame, NV_ENC_PIC_PARAMS *params, NV_ENC_SEI_PAYLOAD *sei_data, int sei_count)
static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
static int nvenc_check_capabilities(AVCodecContext *avctx)
#define IS_YUV444(pix_fmt)
const AVCodecHWConfigInternal *const ff_nvenc_hw_configs[]
static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
static void timestamp_queue_enqueue(AVFifo *queue, int64_t timestamp)
static av_cold int nvenc_setup_rate_control(AVCodecContext *avctx)
static int nvenc_set_timestamp(AVCodecContext *avctx, NV_ENC_LOCK_BITSTREAM *params, AVPacket *pkt)
#define PRESET_ALIAS(alias, name,...)
static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
enum AVPixelFormat ff_nvenc_pix_fmts[]
static void compute_dar(AVCodecContext *avctx, int *dw, int *dh)
#define IS_YUV422(pix_fmt)
static int nvenc_map_error(NVENCSTATUS err, const char **desc)
static const struct @221142305270013126041350255341237163020260275372 nvenc_errors[]
static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err, const char *error_string)
static av_cold int nvenc_open_session(AVCodecContext *avctx)
static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
static void nvenc_map_preset(NvencContext *ctx)
static int nvenc_store_frame_data(AVCodecContext *avctx, NV_ENC_PIC_PARAMS *pic_params, const AVFrame *frame)
#define to_nv_color_pri(n)
#define IS_10BIT(pix_fmt)
static av_cold void set_lossless(AVCodecContext *avctx)
static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
static int64_t timestamp_queue_peek(AVFifo *queue, size_t index)
static int nvenc_retrieve_frame_data(AVCodecContext *avctx, NV_ENC_LOCK_BITSTREAM *lock_params, AVPacket *pkt)
static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame, NvencSurface *nvenc_frame)
av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
static int nvenc_check_codec_support(AVCodecContext *avctx)
static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface, NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
static int nvenc_pop_context(AVCodecContext *avctx)
static av_cold void set_vbr(AVCodecContext *avctx)
static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
static int64_t timestamp_queue_dequeue(AVFifo *queue)
static av_cold int nvenc_setup_device(AVCodecContext *avctx)
static int output_ready(AVCodecContext *avctx, int flush)
static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
#define IS_HWACCEL(pix_fmt)
av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
static int prepare_sei_data_array(AVCodecContext *avctx, const AVFrame *frame)
@ NVENC_RGB_MODE_DISABLED
@ NV_ENC_H264_PROFILE_MAIN
@ NV_ENC_H264_PROFILE_HIGH
@ NV_ENC_H264_PROFILE_HIGH_444P
@ NV_ENC_H264_PROFILE_BASELINE
@ NV_ENC_HEVC_PROFILE_REXT
@ NV_ENC_HEVC_PROFILE_MAIN
@ NV_ENC_HEVC_PROFILE_MAIN_10
#define MAX_REGISTERED_FRAMES
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
#define AV_PIX_FMT_FLAG_RGB
The pixel format contains RGB-like data (as opposed to YUV/grayscale).
#define AV_PIX_FMT_0RGB32
@ AVCOL_RANGE_JPEG
Full range content.
#define AV_PIX_FMT_YUV444P12MSB
#define AV_PIX_FMT_X2RGB10
AVPixelFormat
Pixel format.
@ AV_PIX_FMT_NV12
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
@ AV_PIX_FMT_CUDA
HW acceleration through CUDA.
@ AV_PIX_FMT_NV24
planar YUV 4:4:4, 24bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
@ AV_PIX_FMT_NV16
interleaved chroma YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
@ AV_PIX_FMT_YUV444P
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
@ AV_PIX_FMT_D3D11
Hardware surfaces for Direct3D11.
@ AV_PIX_FMT_CUARRAY
hardware decoding through openharmony
@ AV_PIX_FMT_YUVJ422P
planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting col...
@ AV_PIX_FMT_GBRP
planar GBR 4:4:4 24bpp
@ AV_PIX_FMT_YUVJ444P
planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting col...
@ AV_PIX_FMT_YUVJ420P
planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting col...
#define AV_PIX_FMT_X2BGR10
#define AV_PIX_FMT_GBRP16
#define AV_PIX_FMT_GBRP10MSB
#define AV_PIX_FMT_YUV444P16
#define AV_PIX_FMT_YUV444P10MSB
#define AV_PIX_FMT_0BGR32
@ AVCOL_SPC_BT470BG
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
@ AVCOL_SPC_RGB
order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB), YZX and ST 428-1
@ SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35
@ SEI_TYPE_USER_DATA_UNREGISTERED
#define FF_ARRAY_ELEMS(a)
Data structure for single deference display information.
uint8_t additional_shift_present_flag
An array of flags to indicates that the information about additional horizontal shift of the left and...
uint8_t mantissa_ref_viewing_distance
The mantissa part of the reference viewing distance of the n-th reference display.
uint16_t left_view_id
The ViewId of the left view of a stereo pair corresponding to the n-th reference display.
int16_t num_sample_shift
The recommended additional horizontal shift for a stereo pair corresponding to the n-th reference bas...
uint8_t mantissa_ref_display_width
The mantissa part of the reference display width of the n-th reference display.
uint8_t exponent_ref_display_width
The exponent part of the reference display width of the n-th reference display.
uint16_t right_view_id
The ViewId of the left view of a stereo pair corresponding to the n-th reference display.
uint8_t exponent_ref_viewing_distance
The exponent part of the reference viewing distance of the n-th reference display.
This structure describes information about the reference display width(s) and reference viewing dista...
uint8_t prec_ref_viewing_dist
The exponent of the maximum allowable truncation error for {exponent,mantissa}_ref_viewing_distance a...
uint8_t prec_ref_display_width
The exponent of the maximum allowable truncation error for {exponent,mantissa}_ref_display_width as g...
uint8_t ref_viewing_distance_flag
A flag to indicate the presence of reference viewing distance.
uint8_t num_ref_displays
The number of reference displays that are signalled in this struct.
uint8_t * data
The data buffer.
This structure describes the bitrate properties of an encoded bitstream.
int64_t avg_bitrate
Average bitrate of the stream, in bits per second.
int64_t max_bitrate
Maximum bitrate of the stream, in bits per second.
int64_t buffer_size
The size of the buffer to which the ratecontrol is applied, in bits.
This struct is allocated as AVHWDeviceContext.hwctx.
main external API structure.
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
int width
picture width / height.
const struct AVCodecDescriptor * codec_descriptor
AVCodecDescriptor.
int rc_buffer_size
decoder bitstream buffer size
int global_quality
Global quality for codecs which cannot change it per frame.
enum AVColorRange color_range
MPEG vs JPEG YUV range.
float b_quant_offset
qscale offset between IP and B-frames
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames.
int max_b_frames
maximum number of B-frames between non-B-frames Note: The output will be delayed by max_b_frames+1 re...
int qmin
minimum quantizer
float b_quant_factor
qscale factor between IP and B-frames If > 0 then the last P-frame quantizer will be used (q= lastp_q...
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
int has_b_frames
Size of the frame reordering buffer in the decoder.
int64_t bit_rate
the average bitrate
const struct AVCodec * codec
enum AVColorSpace colorspace
YUV colorspace type.
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
int refs
number of reference frames
int64_t rc_max_rate
maximum bitrate
int qmax
maximum quantizer
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
int flags
AV_CODEC_FLAG_*.
AVFrameSideData ** decoded_side_data
Array containing static side data, such as HDR10 CLL / MDCV structures.
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
AVBufferRef * hw_device_ctx
A reference to the AVHWDeviceContext describing the device which will be used by a hardware encoder/d...
float i_quant_factor
qscale factor between P- and I-frames If > 0 then the last P-frame quantizer will be used (q = lastp_...
struct AVCodecInternal * internal
Private context used for internal data.
float i_quant_offset
qscale offset between P and I-frames
int slices
Number of slices.
int props
Codec properties, a combination of AV_CODEC_PROP_* flags.
int draining
decoding: AVERROR_EOF has been returned from ff_decode_get_packet(); must not be used by decoders tha...
Content light level needed by to transmit HDR over HDMI (CTA-861.3).
This struct is allocated as AVHWDeviceContext.hwctx.
ID3D11Device * device
Device used for texture creation and access.
Structure to hold side data for an AVFrame.
enum AVFrameSideDataType type
This structure describes decoded (raw) audio or video data.
This struct aggregates all the (hardware/vendor-specific) "high-level" state, i.e.
void * hwctx
The format-specific data, allocated and freed by libavutil along with this context.
enum AVHWDeviceType type
This field identifies the underlying API used for hardware access.
This struct describes a set or pool of "hardware" frames (i.e.
enum AVPixelFormat format
The pixel format identifying the underlying HW surface type.
enum AVPixelFormat sw_format
The pixel format identifying the actual data layout of the hardware frames.
int width
The allocated dimensions of the frames in this pool.
AVHWDeviceContext * device_ctx
The parent AVHWDeviceContext.
This structure stores compressed data.
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
uint64_t flags
Combination of AV_PIX_FMT_FLAG_... flags.
Rational number (pair of numerator and denominator).
Stereo 3D type: this structure describes how two videos are packed within a single video surface,...
enum AVStereo3DType type
How views are packed within the video.
NvencFunctions * nvenc_dl
NV_ENCODE_API_FUNCTION_LIST nvenc_funcs
NV_ENC_OUTPUT_PTR output_surface
NV_ENC_BUFFER_FORMAT format
NV_ENC_INPUT_PTR input_surface
static void error(const char *err)
static const Preset presets[]