35 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
37 #define NVENC_CAP 0x30
38 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
39 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
40 rc == NV_ENC_PARAMS_RC_CBR_HQ)
58 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
59 pix_fmt == AV_PIX_FMT_P016 || \
60 pix_fmt == AV_PIX_FMT_YUV444P16)
62 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
63 pix_fmt == AV_PIX_FMT_YUV444P16)
70 { NV_ENC_SUCCESS, 0,
"success" },
71 { NV_ENC_ERR_NO_ENCODE_DEVICE,
AVERROR(ENOENT),
"no encode device" },
72 { NV_ENC_ERR_UNSUPPORTED_DEVICE,
AVERROR(ENOSYS),
"unsupported device" },
73 { NV_ENC_ERR_INVALID_ENCODERDEVICE,
AVERROR(EINVAL),
"invalid encoder device" },
74 { NV_ENC_ERR_INVALID_DEVICE,
AVERROR(EINVAL),
"invalid device" },
75 { NV_ENC_ERR_DEVICE_NOT_EXIST,
AVERROR(EIO),
"device does not exist" },
76 { NV_ENC_ERR_INVALID_PTR,
AVERROR(EFAULT),
"invalid ptr" },
77 { NV_ENC_ERR_INVALID_EVENT,
AVERROR(EINVAL),
"invalid event" },
78 { NV_ENC_ERR_INVALID_PARAM,
AVERROR(EINVAL),
"invalid param" },
79 { NV_ENC_ERR_INVALID_CALL,
AVERROR(EINVAL),
"invalid call" },
80 { NV_ENC_ERR_OUT_OF_MEMORY,
AVERROR(ENOMEM),
"out of memory" },
81 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,
AVERROR(EINVAL),
"encoder not initialized" },
82 { NV_ENC_ERR_UNSUPPORTED_PARAM,
AVERROR(ENOSYS),
"unsupported param" },
83 { NV_ENC_ERR_LOCK_BUSY,
AVERROR(EAGAIN),
"lock busy" },
85 { NV_ENC_ERR_INVALID_VERSION,
AVERROR(EINVAL),
"invalid version" },
86 { NV_ENC_ERR_MAP_FAILED,
AVERROR(EIO),
"map failed" },
87 { NV_ENC_ERR_NEED_MORE_INPUT,
AVERROR(EAGAIN),
"need more input" },
88 { NV_ENC_ERR_ENCODER_BUSY,
AVERROR(EAGAIN),
"encoder busy" },
89 { NV_ENC_ERR_EVENT_NOT_REGISTERD,
AVERROR(EBADF),
"event not registered" },
91 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,
AVERROR(EINVAL),
"incompatible client key" },
92 { NV_ENC_ERR_UNIMPLEMENTED,
AVERROR(ENOSYS),
"unimplemented" },
93 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED,
AVERROR(EIO),
"resource register failed" },
94 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,
AVERROR(EBADF),
"resource not registered" },
95 { NV_ENC_ERR_RESOURCE_NOT_MAPPED,
AVERROR(EBADF),
"resource not mapped" },
109 *
desc =
"unknown error";
114 const char *error_string)
125 #if NVENCAPI_CHECK_VERSION(9, 2)
126 const char *minver =
"(unknown)";
127 #elif NVENCAPI_CHECK_VERSION(9, 1)
128 # if defined(_WIN32) || defined(__CYGWIN__)
129 const char *minver =
"436.15";
131 const char *minver =
"435.21";
133 #elif NVENCAPI_CHECK_VERSION(9, 0)
134 # if defined(_WIN32) || defined(__CYGWIN__)
135 const char *minver =
"418.81";
137 const char *minver =
"418.30";
139 #elif NVENCAPI_CHECK_VERSION(8, 2)
140 # if defined(_WIN32) || defined(__CYGWIN__)
141 const char *minver =
"397.93";
143 const char *minver =
"396.24";
145 #elif NVENCAPI_CHECK_VERSION(8, 1)
146 # if defined(_WIN32) || defined(__CYGWIN__)
147 const char *minver =
"390.77";
149 const char *minver =
"390.25";
152 # if defined(_WIN32) || defined(__CYGWIN__)
153 const char *minver =
"378.66";
155 const char *minver =
"378.13";
158 av_log(avctx,
level,
"The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
166 uint32_t nvenc_max_ver;
169 ret = cuda_load_functions(&dl_fn->
cuda_dl, avctx);
173 ret = nvenc_load_functions(&dl_fn->
nvenc_dl, avctx);
179 err = dl_fn->
nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
180 if (err != NV_ENC_SUCCESS)
185 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
186 av_log(avctx,
AV_LOG_ERROR,
"Driver does not support the required nvenc API version. "
187 "Required: %d.%d Found: %d.%d\n",
188 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
189 nvenc_max_ver >> 4, nvenc_max_ver & 0
xf);
194 dl_fn->
nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
197 if (err != NV_ENC_SUCCESS)
210 if (
ctx->d3d11_device)
222 if (
ctx->d3d11_device)
230 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS
params = { 0 };
232 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
235 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
236 params.apiVersion = NVENCAPI_VERSION;
237 if (
ctx->d3d11_device) {
239 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
242 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
245 ret = p_nvenc->nvEncOpenEncodeSessionEx(&
params, &
ctx->nvencoder);
246 if (
ret != NV_ENC_SUCCESS) {
257 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
261 ret = p_nvenc->nvEncGetEncodeGUIDCount(
ctx->nvencoder, &
count);
263 if (
ret != NV_ENC_SUCCESS || !
count)
271 if (
ret != NV_ENC_SUCCESS) {
278 if (!memcmp(&guids[
i], &
ctx->init_encode_params.encodeGUID,
sizeof(*guids))) {
293 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
294 NV_ENC_CAPS_PARAM
params = { 0 };
297 params.version = NV_ENC_CAPS_PARAM_VER;
300 ret = p_nvenc->nvEncGetEncodeCaps(
ctx->nvencoder,
ctx->init_encode_params.encodeGUID, &
params, &
val);
302 if (
ret == NV_ENC_SUCCESS)
331 if (ret < avctx->
width) {
338 if (ret < avctx->
height) {
345 if (ret < avctx->max_b_frames) {
355 "Interlaced encoding is not supported. Supported level: %d\n",
367 if (
ctx->rc_lookahead > 0 &&
ret <= 0) {
373 if (
ctx->temporal_aq > 0 &&
ret <= 0) {
379 if (
ctx->weighted_pred > 0 &&
ret <= 0) {
385 if (
ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC &&
ret <= 0) {
390 #ifdef NVENC_HAVE_BFRAME_REF_MODE
392 if (
ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH &&
ret != 1) {
395 }
else if (
ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED &&
ret == 0) {
400 if (
ctx->b_ref_mode != 0) {
406 ctx->support_dyn_bitrate =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
415 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
416 char name[128] = { 0};
417 int major, minor,
ret;
436 av_log(avctx, loglevel,
"[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx,
name, major, minor);
437 if (((major << 4) | minor) <
NVENC_CAP) {
438 av_log(avctx, loglevel,
"does not support NVENC\n");
449 ctx->cu_context =
ctx->cu_context_internal;
460 av_log(avctx, loglevel,
"supports NVENC\n");
471 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
479 ctx->cu_context_internal =
NULL;
492 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
495 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
523 cuda_device_hwctx = hwdev_ctx->
hwctx;
526 d3d11_device_hwctx = hwdev_ctx->
hwctx;
534 if (cuda_device_hwctx) {
538 else if (d3d11_device_hwctx) {
539 ctx->d3d11_device = d3d11_device_hwctx->
device;
540 ID3D11Device_AddRef(
ctx->d3d11_device);
550 av_log(avctx,
AV_LOG_FATAL,
"Provided device doesn't support required NVENC features\n");
554 int i, nb_devices = 0;
570 for (
i = 0;
i < nb_devices; ++
i) {
583 av_log(avctx,
AV_LOG_FATAL,
"Requested GPU %d, but only %d GPUs are available!\n",
ctx->device, nb_devices);
595 #define PRESET_ALIAS(alias, name, ...) \
596 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
598 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
619 ctx->init_encode_params.presetGUID = t->
guid;
629 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
631 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
633 if (
ctx->init_qp_p >= 0) {
634 rc->constQP.qpInterP =
ctx->init_qp_p;
635 if (
ctx->init_qp_i >= 0 &&
ctx->init_qp_b >= 0) {
636 rc->constQP.qpIntra =
ctx->init_qp_i;
637 rc->constQP.qpInterB =
ctx->init_qp_b;
639 rc->constQP.qpIntra = av_clip(
641 rc->constQP.qpInterB = av_clip(
644 rc->constQP.qpIntra = rc->constQP.qpInterP;
645 rc->constQP.qpInterB = rc->constQP.qpInterP;
647 }
else if (
ctx->cqp >= 0) {
648 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra =
ctx->cqp;
662 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
665 if (avctx->
qmin >= 0 && avctx->
qmax >= 0) {
669 rc->minQP.qpInterB = avctx->
qmin;
670 rc->minQP.qpInterP = avctx->
qmin;
671 rc->minQP.qpIntra = avctx->
qmin;
673 rc->maxQP.qpInterB = avctx->
qmax;
674 rc->maxQP.qpInterP = avctx->
qmax;
675 rc->maxQP.qpIntra = avctx->
qmax;
677 qp_inter_p = (avctx->
qmax + 3 * avctx->
qmin) / 4;
678 }
else if (avctx->
qmin >= 0) {
681 rc->minQP.qpInterB = avctx->
qmin;
682 rc->minQP.qpInterP = avctx->
qmin;
683 rc->minQP.qpIntra = avctx->
qmin;
685 qp_inter_p = avctx->
qmin;
690 rc->enableInitialRCQP = 1;
692 if (
ctx->init_qp_p < 0) {
693 rc->initialRCQP.qpInterP = qp_inter_p;
695 rc->initialRCQP.qpInterP =
ctx->init_qp_p;
698 if (
ctx->init_qp_i < 0) {
700 rc->initialRCQP.qpIntra = av_clip(
703 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
706 rc->initialRCQP.qpIntra =
ctx->init_qp_i;
709 if (
ctx->init_qp_b < 0) {
711 rc->initialRCQP.qpInterB = av_clip(
714 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
717 rc->initialRCQP.qpInterB =
ctx->init_qp_b;
724 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
726 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
727 rc->constQP.qpInterB = 0;
728 rc->constQP.qpInterP = 0;
729 rc->constQP.qpIntra = 0;
738 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
741 case NV_ENC_PARAMS_RC_CONSTQP:
744 case NV_ENC_PARAMS_RC_VBR_MINQP:
745 if (avctx->
qmin < 0) {
747 "The variable bitrate rate-control requires "
748 "the 'qmin' option set.\n");
753 case NV_ENC_PARAMS_RC_VBR_HQ:
754 case NV_ENC_PARAMS_RC_VBR:
757 case NV_ENC_PARAMS_RC_CBR:
758 case NV_ENC_PARAMS_RC_CBR_HQ:
759 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
763 rc->rateControlMode =
ctx->rc;
772 int nb_surfaces =
FFMAX(4,
ctx->encode_config.frameIntervalP * 2 * 2);
775 if (
ctx->rc_lookahead > 0) {
778 nb_surfaces =
FFMAX(1,
FFMAX(nb_surfaces,
ctx->rc_lookahead +
ctx->encode_config.frameIntervalP + 1 + 4));
779 if (nb_surfaces >
ctx->nb_surfaces &&
ctx->nb_surfaces > 0)
782 "Defined rc_lookahead requires more surfaces, "
783 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
785 ctx->nb_surfaces =
FFMAX(nb_surfaces,
ctx->nb_surfaces);
787 if (
ctx->encode_config.frameIntervalP > 1 &&
ctx->nb_surfaces < nb_surfaces &&
ctx->nb_surfaces > 0)
790 "Defined b-frame requires more surfaces, "
791 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
792 ctx->nb_surfaces =
FFMAX(
ctx->nb_surfaces, nb_surfaces);
794 else if (
ctx->nb_surfaces <= 0)
795 ctx->nb_surfaces = nb_surfaces;
810 av_log(avctx,
AV_LOG_WARNING,
"Using global_quality with nvenc is deprecated. Use qp instead.\n");
816 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate;
817 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
818 ctx->encode_config.rcParams.maxBitRate =
ctx->encode_config.rcParams.averageBitRate;
830 if (
ctx->twopass < 0)
835 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
837 ctx->rc = NV_ENC_PARAMS_RC_CBR;
839 }
else if (
ctx->cqp >= 0) {
840 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
841 }
else if (
ctx->twopass) {
842 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
843 }
else if (avctx->
qmin >= 0 && avctx->
qmax >= 0) {
844 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
860 }
else if (
ctx->rc >= 0) {
863 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
869 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
870 avctx->
rc_buffer_size =
ctx->encode_config.rcParams.vbvBufferSize = 2 *
ctx->encode_config.rcParams.averageBitRate;
874 ctx->encode_config.rcParams.enableAQ = 1;
875 ctx->encode_config.rcParams.aqStrength =
ctx->aq_strength;
879 if (
ctx->temporal_aq) {
880 ctx->encode_config.rcParams.enableTemporalAQ = 1;
884 if (
ctx->rc_lookahead > 0) {
885 int lkd_bound =
FFMIN(
ctx->nb_surfaces,
ctx->async_depth) -
886 ctx->encode_config.frameIntervalP - 4;
890 "Lookahead not enabled. Increase buffer delay (-delay).\n");
892 ctx->encode_config.rcParams.enableLookahead = 1;
893 ctx->encode_config.rcParams.lookaheadDepth = av_clip(
ctx->rc_lookahead, 0, lkd_bound);
894 ctx->encode_config.rcParams.disableIadapt =
ctx->no_scenecut;
895 ctx->encode_config.rcParams.disableBadapt = !
ctx->b_adapt;
897 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
898 ctx->encode_config.rcParams.lookaheadDepth,
899 ctx->encode_config.rcParams.disableIadapt ?
"disabled" :
"enabled",
900 ctx->encode_config.rcParams.disableBadapt ?
"disabled" :
"enabled");
904 if (
ctx->strict_gop) {
905 ctx->encode_config.rcParams.strictGOPTarget = 1;
910 ctx->encode_config.rcParams.enableNonRefP = 1;
912 if (
ctx->zerolatency)
913 ctx->encode_config.rcParams.zeroReorderDelay = 1;
917 int tmp_quality = (
int)(
ctx->quality * 256.0f);
918 ctx->encode_config.rcParams.targetQuality = (
uint8_t)(tmp_quality >> 8);
919 ctx->encode_config.rcParams.targetQualityLSB = (
uint8_t)(tmp_quality & 0xff);
924 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate = 0;
932 NV_ENC_CONFIG *cc = &
ctx->encode_config;
933 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
934 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
938 vui->transferCharacteristics = avctx->
color_trc;
942 vui->colourDescriptionPresentFlag =
945 vui->videoSignalTypePresentFlag =
946 (vui->colourDescriptionPresentFlag
947 || vui->videoFormat != 5
948 || vui->videoFullRangeFlag != 0);
951 h264->sliceModeData = 1;
955 h264->outputAUD =
ctx->aud;
957 if (avctx->
refs >= 0) {
959 h264->maxNumRefFrames = avctx->
refs;
962 h264->idrPeriod = cc->gopLength;
965 if (
IS_CBR(cc->rcParams.rateControlMode)) {
966 h264->outputBufferingPeriodSEI = 1;
969 h264->outputPictureTimingSEI = 1;
971 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
972 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
973 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
974 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
975 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
979 h264->qpPrimeYZeroTransformBypassFlag = 1;
981 switch(
ctx->profile) {
983 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
987 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
991 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
995 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1003 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1009 h264->level =
ctx->level;
1011 if (
ctx->coder >= 0)
1012 h264->entropyCodingMode =
ctx->coder;
1014 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1015 h264->useBFramesAsRef =
ctx->b_ref_mode;
1024 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1025 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1026 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1030 vui->transferCharacteristics = avctx->
color_trc;
1034 vui->colourDescriptionPresentFlag =
1037 vui->videoSignalTypePresentFlag =
1038 (vui->colourDescriptionPresentFlag
1039 || vui->videoFormat != 5
1040 || vui->videoFullRangeFlag != 0);
1042 hevc->sliceMode = 3;
1043 hevc->sliceModeData = 1;
1047 hevc->outputAUD =
ctx->aud;
1049 if (avctx->
refs >= 0) {
1051 hevc->maxNumRefFramesInDPB = avctx->
refs;
1054 hevc->idrPeriod = cc->gopLength;
1057 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1058 hevc->outputBufferingPeriodSEI = 1;
1061 hevc->outputPictureTimingSEI = 1;
1063 switch (
ctx->profile) {
1065 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1069 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1073 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1080 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1086 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1090 hevc->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1092 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1094 hevc->level =
ctx->level;
1096 hevc->tier =
ctx->tier;
1098 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1099 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1136 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1138 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1139 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1144 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1145 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1147 ctx->init_encode_params.encodeHeight = avctx->
height;
1148 ctx->init_encode_params.encodeWidth = avctx->
width;
1150 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1154 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1155 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1157 nv_status = p_nvenc->nvEncGetEncodePresetConfig(
ctx->nvencoder,
1158 ctx->init_encode_params.encodeGUID,
1159 ctx->init_encode_params.presetGUID,
1161 if (nv_status != NV_ENC_SUCCESS)
1162 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1164 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1166 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1169 ctx->init_encode_params.darHeight = dh;
1170 ctx->init_encode_params.darWidth = dw;
1180 ctx->init_encode_params.enableEncodeAsync = 0;
1181 ctx->init_encode_params.enablePTD = 1;
1183 if (
ctx->weighted_pred == 1)
1184 ctx->init_encode_params.enableWeightedPrediction = 1;
1186 if (
ctx->bluray_compat) {
1195 ctx->level = NV_ENC_LEVEL_HEVC_51;
1196 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1209 ctx->encode_config.frameIntervalP = 0;
1210 ctx->encode_config.gopLength = 1;
1221 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1223 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1234 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1240 if (nv_status != NV_ENC_SUCCESS) {
1244 if (
ctx->encode_config.frameIntervalP > 1)
1247 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1248 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1255 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1264 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1266 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1269 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1271 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1273 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1275 return NV_ENC_BUFFER_FORMAT_ARGB;
1277 return NV_ENC_BUFFER_FORMAT_ABGR;
1279 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1287 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1290 NVENCSTATUS nv_status;
1291 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1292 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1296 if (!
ctx->surfaces[idx].in_ref)
1299 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1302 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1308 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1309 allocSurf.width = avctx->
width;
1310 allocSurf.height = avctx->
height;
1311 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1313 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
1314 if (nv_status != NV_ENC_SUCCESS) {
1318 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1319 ctx->surfaces[idx].width = allocSurf.width;
1320 ctx->surfaces[idx].height = allocSurf.height;
1323 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
1324 if (nv_status != NV_ENC_SUCCESS) {
1327 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
1332 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1333 ctx->surfaces[idx].size = allocOut.size;
1343 int i, res = 0, res2;
1350 if (!
ctx->timestamp_list)
1354 if (!
ctx->unused_surface_queue)
1358 if (!
ctx->output_surface_queue)
1361 if (!
ctx->output_surface_ready_queue)
1368 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
1385 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1387 NVENCSTATUS nv_status;
1388 uint32_t outSize = 0;
1389 char tmpHeader[256];
1390 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1391 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1393 payload.spsppsBuffer = tmpHeader;
1394 payload.inBufferSize =
sizeof(tmpHeader);
1395 payload.outSPSPPSPayloadSize = &outSize;
1397 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
1398 if (nv_status != NV_ENC_SUCCESS) {
1409 memcpy(avctx->
extradata, tmpHeader, outSize);
1418 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1422 if (
ctx->nvencoder) {
1423 NV_ENC_PIC_PARAMS
params = { .version = NV_ENC_PIC_PARAMS_VER,
1424 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1430 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &
params);
1439 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1440 if (
ctx->registered_frames[
i].mapped)
1441 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
1442 if (
ctx->registered_frames[
i].regptr)
1443 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
1445 ctx->nb_registered_frames = 0;
1448 if (
ctx->surfaces) {
1449 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
1451 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
1453 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
1457 ctx->nb_surfaces = 0;
1459 if (
ctx->nvencoder) {
1460 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
1468 if (
ctx->cu_context_internal)
1470 ctx->cu_context =
ctx->cu_context_internal =
NULL;
1473 if (
ctx->d3d11_device) {
1474 ID3D11Device_Release(
ctx->d3d11_device);
1479 nvenc_free_functions(&dl_fn->
nvenc_dl);
1480 cuda_free_functions(&dl_fn->
cuda_dl);
1498 "hw_frames_ctx must be set when using GPU frames as input\n");
1504 "hw_frames_ctx must match the GPU frame type\n");
1545 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
1547 int dst_linesize[4] = {
1548 lock_buffer_params->pitch,
1549 lock_buffer_params->pitch,
1550 lock_buffer_params->pitch,
1551 lock_buffer_params->pitch
1557 dst_linesize[1] = dst_linesize[2] >>= 1;
1560 lock_buffer_params->bufferDataPtr, dst_linesize);
1578 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1579 NVENCSTATUS nv_status;
1584 for (first_round = 1; first_round >= 0; first_round--) {
1585 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1586 if (!
ctx->registered_frames[
i].mapped) {
1587 if (
ctx->registered_frames[
i].regptr) {
1590 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
1591 if (nv_status != NV_ENC_SUCCESS)
1592 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
1593 ctx->registered_frames[
i].ptr =
NULL;
1594 ctx->registered_frames[
i].regptr =
NULL;
1601 return ctx->nb_registered_frames++;
1612 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1615 NV_ENC_REGISTER_RESOURCE reg;
1618 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1629 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1630 reg.width = frames_ctx->
width;
1631 reg.height = frames_ctx->
height;
1632 reg.pitch =
frame->linesize[0];
1633 reg.resourceToRegister =
frame->data[0];
1636 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1639 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1640 reg.subResourceIndex = (intptr_t)
frame->data[1];
1644 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1650 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
1651 if (
ret != NV_ENC_SUCCESS) {
1656 ctx->registered_frames[idx].ptr =
frame->data[0];
1657 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1658 ctx->registered_frames[idx].regptr = reg.registeredResource;
1667 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1670 NVENCSTATUS nv_status;
1683 if (!
ctx->registered_frames[reg_idx].mapped) {
1684 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1685 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
1686 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
1687 if (nv_status != NV_ENC_SUCCESS) {
1693 ctx->registered_frames[reg_idx].mapped += 1;
1695 nvenc_frame->
reg_idx = reg_idx;
1696 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
1697 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1702 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1704 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1707 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
1708 if (nv_status != NV_ENC_SUCCESS) {
1709 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
1712 nvenc_frame->
pitch = lockBufferParams.pitch;
1715 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
1716 if (nv_status != NV_ENC_SUCCESS) {
1725 NV_ENC_PIC_PARAMS *
params,
1726 NV_ENC_SEI_PAYLOAD *sei_data)
1732 params->codecPicParams.h264PicParams.sliceMode =
1733 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1734 params->codecPicParams.h264PicParams.sliceModeData =
1735 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1737 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1738 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1743 params->codecPicParams.hevcPicParams.sliceMode =
1744 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1745 params->codecPicParams.hevcPicParams.sliceModeData =
1746 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1748 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1749 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1771 NV_ENC_LOCK_BITSTREAM *
params,
1782 int64_t ts0 =
ctx->initial_pts[0], ts1 =
ctx->initial_pts[1];
1785 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1786 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1790 if ((delta < 0 && ts0 > INT64_MAX +
delta) ||
1795 ctx->first_packet_output = 1;
1809 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1811 uint32_t slice_mode_data;
1812 uint32_t *slice_offsets =
NULL;
1813 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1814 NVENCSTATUS nv_status;
1821 slice_mode_data =
ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1824 slice_mode_data =
ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1831 slice_offsets =
av_mallocz(slice_mode_data *
sizeof(*slice_offsets));
1833 if (!slice_offsets) {
1838 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1840 lock_params.doNotWait = 0;
1842 lock_params.sliceOffsets = slice_offsets;
1844 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
1845 if (nv_status != NV_ENC_SUCCESS) {
1851 ff_alloc_packet2(avctx,
pkt, lock_params.bitstreamSizeInBytes, lock_params.bitstreamSizeInBytes) :
1859 memcpy(
pkt->
data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1861 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
1862 if (nv_status != NV_ENC_SUCCESS) {
1863 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
1869 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
1870 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
1871 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
1872 if (nv_status != NV_ENC_SUCCESS) {
1876 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
1886 switch (lock_params.pictureType) {
1887 case NV_ENC_PIC_TYPE_IDR:
1889 case NV_ENC_PIC_TYPE_I:
1892 case NV_ENC_PIC_TYPE_P:
1895 case NV_ENC_PIC_TYPE_B:
1898 case NV_ENC_PIC_TYPE_BI:
1902 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
1903 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
1908 #if FF_API_CODED_FRAME
1937 int nb_ready, nb_pending;
1948 return nb_ready > 0;
1949 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
1955 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
1958 NV_ENC_RECONFIGURE_PARAMS
params = { 0 };
1959 int needs_reconfig = 0;
1960 int needs_encode_config = 0;
1961 int reconfig_bitrate = 0, reconfig_dar = 0;
1964 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1965 params.reInitEncodeParams =
ctx->init_encode_params;
1968 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
1970 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
1971 ctx->init_encode_params.darWidth,
1972 ctx->init_encode_params.darHeight, dw, dh);
1974 params.reInitEncodeParams.darHeight = dh;
1975 params.reInitEncodeParams.darWidth = dw;
1981 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
1982 if (avctx->
bit_rate > 0 &&
params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
1984 "avg bitrate change: %d -> %d\n",
1985 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
1988 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
1989 reconfig_bitrate = 1;
1994 "max bitrate change: %d -> %d\n",
1995 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
1998 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
1999 reconfig_bitrate = 1;
2004 "vbv buffer size change: %d -> %d\n",
2005 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2009 reconfig_bitrate = 1;
2012 if (reconfig_bitrate) {
2016 needs_encode_config = 1;
2021 if (!needs_encode_config)
2022 params.reInitEncodeParams.encodeConfig =
NULL;
2024 if (needs_reconfig) {
2025 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, &
params);
2026 if (
ret != NV_ENC_SUCCESS) {
2030 ctx->init_encode_params.darHeight = dh;
2031 ctx->init_encode_params.darWidth = dw;
2034 if (reconfig_bitrate) {
2035 ctx->encode_config.rcParams.averageBitRate =
params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2036 ctx->encode_config.rcParams.maxBitRate =
params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2037 ctx->encode_config.rcParams.vbvBufferSize =
params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2046 NVENCSTATUS nv_status;
2049 NV_ENC_SEI_PAYLOAD *sei_data =
NULL;
2054 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2056 NV_ENC_PIC_PARAMS pic_params = { 0 };
2057 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2059 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2062 if (
ctx->encoder_flushing) {
2066 ctx->encoder_flushing = 0;
2067 ctx->first_packet_output = 0;
2094 pic_params.bufferFmt = in_surf->
format;
2095 pic_params.inputWidth = in_surf->
width;
2096 pic_params.inputHeight = in_surf->
height;
2097 pic_params.inputPitch = in_surf->
pitch;
2101 if (
frame->top_field_first)
2102 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2104 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2106 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2110 pic_params.encodePicFlags =
2111 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2113 pic_params.encodePicFlags = 0;
2116 pic_params.inputTimeStamp =
frame->pts;
2124 sei_data->payloadSize = (uint32_t)sei_size;
2125 sei_data->payloadType = 4;
2126 sei_data->payload = (
uint8_t*)(sei_data + 1);
2132 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2133 ctx->encoder_flushing = 1;
2140 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
2147 if (nv_status != NV_ENC_SUCCESS &&
2148 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2162 if (nv_status == NV_ENC_SUCCESS) {
2179 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2199 }
else if (
ctx->encoder_flushing) {
2214 if (!
ctx->encoder_flushing) {
2223 }
else if (res < 0) {