36 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
38 #define NVENC_CAP 0x30
39 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
40 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
41 rc == NV_ENC_PARAMS_RC_CBR_HQ)
69 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
70 pix_fmt == AV_PIX_FMT_P016 || \
71 pix_fmt == AV_PIX_FMT_YUV444P16)
73 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
74 pix_fmt == AV_PIX_FMT_YUV444P16)
81 { NV_ENC_SUCCESS, 0,
"success" },
82 { NV_ENC_ERR_NO_ENCODE_DEVICE,
AVERROR(ENOENT),
"no encode device" },
83 { NV_ENC_ERR_UNSUPPORTED_DEVICE,
AVERROR(ENOSYS),
"unsupported device" },
84 { NV_ENC_ERR_INVALID_ENCODERDEVICE,
AVERROR(EINVAL),
"invalid encoder device" },
85 { NV_ENC_ERR_INVALID_DEVICE,
AVERROR(EINVAL),
"invalid device" },
86 { NV_ENC_ERR_DEVICE_NOT_EXIST,
AVERROR(EIO),
"device does not exist" },
87 { NV_ENC_ERR_INVALID_PTR,
AVERROR(EFAULT),
"invalid ptr" },
88 { NV_ENC_ERR_INVALID_EVENT,
AVERROR(EINVAL),
"invalid event" },
89 { NV_ENC_ERR_INVALID_PARAM,
AVERROR(EINVAL),
"invalid param" },
90 { NV_ENC_ERR_INVALID_CALL,
AVERROR(EINVAL),
"invalid call" },
91 { NV_ENC_ERR_OUT_OF_MEMORY,
AVERROR(ENOMEM),
"out of memory" },
92 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,
AVERROR(EINVAL),
"encoder not initialized" },
93 { NV_ENC_ERR_UNSUPPORTED_PARAM,
AVERROR(ENOSYS),
"unsupported param" },
94 { NV_ENC_ERR_LOCK_BUSY,
AVERROR(EAGAIN),
"lock busy" },
96 { NV_ENC_ERR_INVALID_VERSION,
AVERROR(EINVAL),
"invalid version" },
97 { NV_ENC_ERR_MAP_FAILED,
AVERROR(EIO),
"map failed" },
98 { NV_ENC_ERR_NEED_MORE_INPUT,
AVERROR(EAGAIN),
"need more input" },
99 { NV_ENC_ERR_ENCODER_BUSY,
AVERROR(EAGAIN),
"encoder busy" },
100 { NV_ENC_ERR_EVENT_NOT_REGISTERD,
AVERROR(EBADF),
"event not registered" },
102 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,
AVERROR(EINVAL),
"incompatible client key" },
103 { NV_ENC_ERR_UNIMPLEMENTED,
AVERROR(ENOSYS),
"unimplemented" },
104 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED,
AVERROR(EIO),
"resource register failed" },
105 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,
AVERROR(EBADF),
"resource not registered" },
106 { NV_ENC_ERR_RESOURCE_NOT_MAPPED,
AVERROR(EBADF),
"resource not mapped" },
120 *
desc =
"unknown error";
125 const char *error_string)
128 const char *details =
"(no details)";
131 #ifdef NVENC_HAVE_GETLASTERRORSTRING
133 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
135 if (p_nvenc &&
ctx->nvencoder)
136 details = p_nvenc->nvEncGetLastErrorString(
ctx->nvencoder);
146 #if NVENCAPI_CHECK_VERSION(9, 2)
147 const char *minver =
"(unknown)";
148 #elif NVENCAPI_CHECK_VERSION(9, 1)
149 # if defined(_WIN32) || defined(__CYGWIN__)
150 const char *minver =
"436.15";
152 const char *minver =
"435.21";
154 #elif NVENCAPI_CHECK_VERSION(9, 0)
155 # if defined(_WIN32) || defined(__CYGWIN__)
156 const char *minver =
"418.81";
158 const char *minver =
"418.30";
160 #elif NVENCAPI_CHECK_VERSION(8, 2)
161 # if defined(_WIN32) || defined(__CYGWIN__)
162 const char *minver =
"397.93";
164 const char *minver =
"396.24";
166 #elif NVENCAPI_CHECK_VERSION(8, 1)
167 # if defined(_WIN32) || defined(__CYGWIN__)
168 const char *minver =
"390.77";
170 const char *minver =
"390.25";
173 # if defined(_WIN32) || defined(__CYGWIN__)
174 const char *minver =
"378.66";
176 const char *minver =
"378.13";
179 av_log(avctx,
level,
"The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
187 uint32_t nvenc_max_ver;
190 ret = cuda_load_functions(&dl_fn->
cuda_dl, avctx);
194 ret = nvenc_load_functions(&dl_fn->
nvenc_dl, avctx);
200 err = dl_fn->
nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
201 if (err != NV_ENC_SUCCESS)
206 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
207 av_log(avctx,
AV_LOG_ERROR,
"Driver does not support the required nvenc API version. "
208 "Required: %d.%d Found: %d.%d\n",
209 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
210 nvenc_max_ver >> 4, nvenc_max_ver & 0
xf);
215 dl_fn->
nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
218 if (err != NV_ENC_SUCCESS)
231 if (
ctx->d3d11_device)
243 if (
ctx->d3d11_device)
251 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
253 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
256 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
257 params.apiVersion = NVENCAPI_VERSION;
258 if (
ctx->d3d11_device) {
259 params.device =
ctx->d3d11_device;
260 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
262 params.device =
ctx->cu_context;
263 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
266 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &
ctx->nvencoder);
267 if (
ret != NV_ENC_SUCCESS) {
278 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
279 int i,
ret, count = 0;
282 ret = p_nvenc->nvEncGetEncodeGUIDCount(
ctx->nvencoder, &count);
284 if (
ret != NV_ENC_SUCCESS || !count)
291 ret = p_nvenc->nvEncGetEncodeGUIDs(
ctx->nvencoder, guids, count, &count);
292 if (
ret != NV_ENC_SUCCESS) {
298 for (
i = 0;
i < count;
i++) {
299 if (!memcmp(&guids[
i], &
ctx->init_encode_params.encodeGUID,
sizeof(*guids))) {
314 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
315 NV_ENC_CAPS_PARAM params = { 0 };
318 params.version = NV_ENC_CAPS_PARAM_VER;
319 params.capsToQuery = cap;
321 ret = p_nvenc->nvEncGetEncodeCaps(
ctx->nvencoder,
ctx->init_encode_params.encodeGUID, ¶ms, &
val);
323 if (
ret == NV_ENC_SUCCESS)
352 if (ret < avctx->
width) {
359 if (ret < avctx->
height) {
366 if (ret < avctx->max_b_frames) {
376 "Interlaced encoding is not supported. Supported level: %d\n",
388 if (
ctx->rc_lookahead > 0 &&
ret <= 0) {
394 if (
ctx->temporal_aq > 0 &&
ret <= 0) {
400 if (
ctx->weighted_pred > 0 &&
ret <= 0) {
406 if (
ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC &&
ret <= 0) {
411 #ifdef NVENC_HAVE_BFRAME_REF_MODE
413 if (
ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH &&
ret != 1) {
416 }
else if (
ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED &&
ret == 0) {
421 if (
ctx->b_ref_mode != 0) {
427 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
429 if(avctx->
refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT &&
ret <= 0) {
434 if(avctx->
refs != 0) {
440 ctx->support_dyn_bitrate =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
449 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
450 char name[128] = { 0};
470 av_log(avctx, loglevel,
"[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx,
name,
major,
minor);
472 av_log(avctx, loglevel,
"does not support NVENC\n");
483 ctx->cu_context =
ctx->cu_context_internal;
495 av_log(avctx, loglevel,
"supports NVENC\n");
506 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
514 ctx->cu_context_internal =
NULL;
527 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
530 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
558 cuda_device_hwctx = hwdev_ctx->
hwctx;
561 d3d11_device_hwctx = hwdev_ctx->
hwctx;
569 if (cuda_device_hwctx) {
571 ctx->cu_stream = cuda_device_hwctx->
stream;
574 else if (d3d11_device_hwctx) {
575 ctx->d3d11_device = d3d11_device_hwctx->
device;
576 ID3D11Device_AddRef(
ctx->d3d11_device);
586 av_log(avctx,
AV_LOG_FATAL,
"Provided device doesn't support required NVENC features\n");
590 int i, nb_devices = 0;
606 for (
i = 0;
i < nb_devices; ++
i) {
619 av_log(avctx,
AV_LOG_FATAL,
"Requested GPU %d, but only %d GPUs are available!\n",
ctx->device, nb_devices);
631 #define PRESET_ALIAS(alias, name, ...) \
632 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
634 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
655 ctx->init_encode_params.presetGUID = t->
guid;
665 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
667 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
669 if (
ctx->init_qp_p >= 0) {
670 rc->constQP.qpInterP =
ctx->init_qp_p;
671 if (
ctx->init_qp_i >= 0 &&
ctx->init_qp_b >= 0) {
672 rc->constQP.qpIntra =
ctx->init_qp_i;
673 rc->constQP.qpInterB =
ctx->init_qp_b;
675 rc->constQP.qpIntra = av_clip(
677 rc->constQP.qpInterB = av_clip(
680 rc->constQP.qpIntra = rc->constQP.qpInterP;
681 rc->constQP.qpInterB = rc->constQP.qpInterP;
683 }
else if (
ctx->cqp >= 0) {
684 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra =
ctx->cqp;
698 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
701 if (avctx->
qmin >= 0 && avctx->
qmax >= 0) {
705 rc->minQP.qpInterB = avctx->
qmin;
706 rc->minQP.qpInterP = avctx->
qmin;
707 rc->minQP.qpIntra = avctx->
qmin;
709 rc->maxQP.qpInterB = avctx->
qmax;
710 rc->maxQP.qpInterP = avctx->
qmax;
711 rc->maxQP.qpIntra = avctx->
qmax;
713 qp_inter_p = (avctx->
qmax + 3 * avctx->
qmin) / 4;
714 }
else if (avctx->
qmin >= 0) {
717 rc->minQP.qpInterB = avctx->
qmin;
718 rc->minQP.qpInterP = avctx->
qmin;
719 rc->minQP.qpIntra = avctx->
qmin;
721 qp_inter_p = avctx->
qmin;
726 rc->enableInitialRCQP = 1;
728 if (
ctx->init_qp_p < 0) {
729 rc->initialRCQP.qpInterP = qp_inter_p;
731 rc->initialRCQP.qpInterP =
ctx->init_qp_p;
734 if (
ctx->init_qp_i < 0) {
736 rc->initialRCQP.qpIntra = av_clip(
739 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
742 rc->initialRCQP.qpIntra =
ctx->init_qp_i;
745 if (
ctx->init_qp_b < 0) {
747 rc->initialRCQP.qpInterB = av_clip(
750 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
753 rc->initialRCQP.qpInterB =
ctx->init_qp_b;
760 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
762 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
763 rc->constQP.qpInterB = 0;
764 rc->constQP.qpInterP = 0;
765 rc->constQP.qpIntra = 0;
774 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
777 case NV_ENC_PARAMS_RC_CONSTQP:
780 case NV_ENC_PARAMS_RC_VBR_MINQP:
781 if (avctx->
qmin < 0) {
783 "The variable bitrate rate-control requires "
784 "the 'qmin' option set.\n");
789 case NV_ENC_PARAMS_RC_VBR_HQ:
790 case NV_ENC_PARAMS_RC_VBR:
793 case NV_ENC_PARAMS_RC_CBR:
794 case NV_ENC_PARAMS_RC_CBR_HQ:
795 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
799 rc->rateControlMode =
ctx->rc;
808 int nb_surfaces =
FFMAX(4,
ctx->encode_config.frameIntervalP * 2 * 2);
811 if (
ctx->rc_lookahead > 0) {
814 nb_surfaces =
FFMAX(1,
FFMAX(nb_surfaces,
ctx->rc_lookahead +
ctx->encode_config.frameIntervalP + 1 + 4));
815 if (nb_surfaces >
ctx->nb_surfaces &&
ctx->nb_surfaces > 0)
818 "Defined rc_lookahead requires more surfaces, "
819 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
821 ctx->nb_surfaces =
FFMAX(nb_surfaces,
ctx->nb_surfaces);
823 if (
ctx->encode_config.frameIntervalP > 1 &&
ctx->nb_surfaces < nb_surfaces &&
ctx->nb_surfaces > 0)
826 "Defined b-frame requires more surfaces, "
827 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
828 ctx->nb_surfaces =
FFMAX(
ctx->nb_surfaces, nb_surfaces);
830 else if (
ctx->nb_surfaces <= 0)
831 ctx->nb_surfaces = nb_surfaces;
846 av_log(avctx,
AV_LOG_WARNING,
"Using global_quality with nvenc is deprecated. Use qp instead.\n");
852 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate;
853 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
854 ctx->encode_config.rcParams.maxBitRate =
ctx->encode_config.rcParams.averageBitRate;
866 if (
ctx->twopass < 0)
871 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
873 ctx->rc = NV_ENC_PARAMS_RC_CBR;
875 }
else if (
ctx->cqp >= 0) {
876 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
877 }
else if (
ctx->twopass) {
878 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
879 }
else if (avctx->
qmin >= 0 && avctx->
qmax >= 0) {
880 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
896 }
else if (
ctx->rc >= 0) {
899 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
905 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
906 avctx->
rc_buffer_size =
ctx->encode_config.rcParams.vbvBufferSize = 2 *
ctx->encode_config.rcParams.averageBitRate;
910 ctx->encode_config.rcParams.enableAQ = 1;
911 ctx->encode_config.rcParams.aqStrength =
ctx->aq_strength;
915 if (
ctx->temporal_aq) {
916 ctx->encode_config.rcParams.enableTemporalAQ = 1;
920 if (
ctx->rc_lookahead > 0) {
921 int lkd_bound =
FFMIN(
ctx->nb_surfaces,
ctx->async_depth) -
922 ctx->encode_config.frameIntervalP - 4;
926 "Lookahead not enabled. Increase buffer delay (-delay).\n");
928 ctx->encode_config.rcParams.enableLookahead = 1;
929 ctx->encode_config.rcParams.lookaheadDepth = av_clip(
ctx->rc_lookahead, 0, lkd_bound);
930 ctx->encode_config.rcParams.disableIadapt =
ctx->no_scenecut;
931 ctx->encode_config.rcParams.disableBadapt = !
ctx->b_adapt;
933 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
934 ctx->encode_config.rcParams.lookaheadDepth,
935 ctx->encode_config.rcParams.disableIadapt ?
"disabled" :
"enabled",
936 ctx->encode_config.rcParams.disableBadapt ?
"disabled" :
"enabled");
940 if (
ctx->strict_gop) {
941 ctx->encode_config.rcParams.strictGOPTarget = 1;
946 ctx->encode_config.rcParams.enableNonRefP = 1;
948 if (
ctx->zerolatency)
949 ctx->encode_config.rcParams.zeroReorderDelay = 1;
953 int tmp_quality = (
int)(
ctx->quality * 256.0f);
954 ctx->encode_config.rcParams.targetQuality = (
uint8_t)(tmp_quality >> 8);
955 ctx->encode_config.rcParams.targetQualityLSB = (
uint8_t)(tmp_quality & 0xff);
960 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate = 0;
968 NV_ENC_CONFIG *cc = &
ctx->encode_config;
969 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
970 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
974 vui->transferCharacteristics = avctx->
color_trc;
978 vui->colourDescriptionPresentFlag =
981 vui->videoSignalTypePresentFlag =
982 (vui->colourDescriptionPresentFlag
983 || vui->videoFormat != 5
984 || vui->videoFullRangeFlag != 0);
987 h264->sliceModeData = 1;
991 h264->outputAUD =
ctx->aud;
993 if (
ctx->dpb_size >= 0) {
995 h264->maxNumRefFrames =
ctx->dpb_size;
998 h264->idrPeriod = cc->gopLength;
1001 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1002 h264->outputBufferingPeriodSEI = 1;
1005 h264->outputPictureTimingSEI = 1;
1007 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1008 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1009 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1010 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1011 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1015 h264->qpPrimeYZeroTransformBypassFlag = 1;
1017 switch(
ctx->profile) {
1019 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1023 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1027 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1031 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1039 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1045 h264->level =
ctx->level;
1047 if (
ctx->coder >= 0)
1048 h264->entropyCodingMode =
ctx->coder;
1050 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1051 h264->useBFramesAsRef =
ctx->b_ref_mode;
1054 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1055 h264->numRefL0 = avctx->
refs;
1056 h264->numRefL1 = avctx->
refs;
1065 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1066 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1067 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1071 vui->transferCharacteristics = avctx->
color_trc;
1075 vui->colourDescriptionPresentFlag =
1078 vui->videoSignalTypePresentFlag =
1079 (vui->colourDescriptionPresentFlag
1080 || vui->videoFormat != 5
1081 || vui->videoFullRangeFlag != 0);
1083 hevc->sliceMode = 3;
1084 hevc->sliceModeData = 1;
1088 hevc->outputAUD =
ctx->aud;
1090 if (
ctx->dpb_size >= 0) {
1092 hevc->maxNumRefFramesInDPB =
ctx->dpb_size;
1095 hevc->idrPeriod = cc->gopLength;
1098 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1099 hevc->outputBufferingPeriodSEI = 1;
1102 hevc->outputPictureTimingSEI = 1;
1104 switch (
ctx->profile) {
1106 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1110 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1114 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1121 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1127 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1131 hevc->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1133 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1135 hevc->level =
ctx->level;
1137 hevc->tier =
ctx->tier;
1139 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1140 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1143 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1144 hevc->numRefL0 = avctx->
refs;
1145 hevc->numRefL1 = avctx->
refs;
1182 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1184 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1185 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1190 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1191 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1193 ctx->init_encode_params.encodeHeight = avctx->
height;
1194 ctx->init_encode_params.encodeWidth = avctx->
width;
1196 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1200 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1201 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1203 nv_status = p_nvenc->nvEncGetEncodePresetConfig(
ctx->nvencoder,
1204 ctx->init_encode_params.encodeGUID,
1205 ctx->init_encode_params.presetGUID,
1207 if (nv_status != NV_ENC_SUCCESS)
1208 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1210 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1212 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1215 ctx->init_encode_params.darHeight = dh;
1216 ctx->init_encode_params.darWidth = dw;
1226 ctx->init_encode_params.enableEncodeAsync = 0;
1227 ctx->init_encode_params.enablePTD = 1;
1229 if (
ctx->weighted_pred == 1)
1230 ctx->init_encode_params.enableWeightedPrediction = 1;
1232 if (
ctx->bluray_compat) {
1241 ctx->level = NV_ENC_LEVEL_HEVC_51;
1242 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1255 ctx->encode_config.frameIntervalP = 0;
1256 ctx->encode_config.gopLength = 1;
1264 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1266 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1277 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1278 if (nv_status != NV_ENC_SUCCESS) {
1283 #ifdef NVENC_HAVE_CUSTREAM_PTR
1284 if (
ctx->cu_context) {
1285 nv_status = p_nvenc->nvEncSetIOCudaStreams(
ctx->nvencoder, &
ctx->cu_stream, &
ctx->cu_stream);
1286 if (nv_status != NV_ENC_SUCCESS) {
1297 if (
ctx->encode_config.frameIntervalP > 1)
1300 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1301 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1308 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1317 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1319 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1322 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1324 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1326 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1328 return NV_ENC_BUFFER_FORMAT_ARGB;
1330 return NV_ENC_BUFFER_FORMAT_ABGR;
1332 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1340 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1343 NVENCSTATUS nv_status;
1344 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1345 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1349 if (!
ctx->surfaces[idx].in_ref)
1352 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1355 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1361 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1362 allocSurf.width = avctx->
width;
1363 allocSurf.height = avctx->
height;
1364 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1366 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
1367 if (nv_status != NV_ENC_SUCCESS) {
1371 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1372 ctx->surfaces[idx].width = allocSurf.width;
1373 ctx->surfaces[idx].height = allocSurf.height;
1376 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
1377 if (nv_status != NV_ENC_SUCCESS) {
1380 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
1385 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1386 ctx->surfaces[idx].size = allocOut.size;
1396 int i, res = 0, res2;
1403 if (!
ctx->timestamp_list)
1407 if (!
ctx->unused_surface_queue)
1411 if (!
ctx->output_surface_queue)
1414 if (!
ctx->output_surface_ready_queue)
1421 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
1438 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1440 NVENCSTATUS nv_status;
1441 uint32_t outSize = 0;
1442 char tmpHeader[256];
1443 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1444 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1446 payload.spsppsBuffer = tmpHeader;
1447 payload.inBufferSize =
sizeof(tmpHeader);
1448 payload.outSPSPPSPayloadSize = &outSize;
1450 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
1451 if (nv_status != NV_ENC_SUCCESS) {
1462 memcpy(avctx->
extradata, tmpHeader, outSize);
1471 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1475 if (
ctx->nvencoder) {
1476 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1477 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1483 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, ¶ms);
1492 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1493 if (
ctx->registered_frames[
i].mapped)
1494 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
1495 if (
ctx->registered_frames[
i].regptr)
1496 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
1498 ctx->nb_registered_frames = 0;
1501 if (
ctx->surfaces) {
1502 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
1504 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
1506 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
1510 ctx->nb_surfaces = 0;
1512 if (
ctx->nvencoder) {
1513 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
1521 if (
ctx->cu_context_internal)
1523 ctx->cu_context =
ctx->cu_context_internal =
NULL;
1526 if (
ctx->d3d11_device) {
1527 ID3D11Device_Release(
ctx->d3d11_device);
1532 nvenc_free_functions(&dl_fn->
nvenc_dl);
1533 cuda_free_functions(&dl_fn->
cuda_dl);
1551 "hw_frames_ctx must be set when using GPU frames as input\n");
1557 "hw_frames_ctx must match the GPU frame type\n");
1598 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
1600 int dst_linesize[4] = {
1601 lock_buffer_params->pitch,
1602 lock_buffer_params->pitch,
1603 lock_buffer_params->pitch,
1604 lock_buffer_params->pitch
1610 dst_linesize[1] = dst_linesize[2] >>= 1;
1613 lock_buffer_params->bufferDataPtr, dst_linesize);
1631 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1632 NVENCSTATUS nv_status;
1637 for (first_round = 1; first_round >= 0; first_round--) {
1638 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1639 if (!
ctx->registered_frames[
i].mapped) {
1640 if (
ctx->registered_frames[
i].regptr) {
1643 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
1644 if (nv_status != NV_ENC_SUCCESS)
1645 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
1646 ctx->registered_frames[
i].ptr =
NULL;
1647 ctx->registered_frames[
i].regptr =
NULL;
1654 return ctx->nb_registered_frames++;
1665 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1668 NV_ENC_REGISTER_RESOURCE reg;
1671 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1682 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1683 reg.width = frames_ctx->
width;
1684 reg.height = frames_ctx->
height;
1685 reg.pitch =
frame->linesize[0];
1686 reg.resourceToRegister =
frame->data[0];
1689 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1692 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1693 reg.subResourceIndex = (intptr_t)
frame->data[1];
1697 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1703 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
1704 if (
ret != NV_ENC_SUCCESS) {
1709 ctx->registered_frames[idx].ptr =
frame->data[0];
1710 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1711 ctx->registered_frames[idx].regptr = reg.registeredResource;
1720 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1723 NVENCSTATUS nv_status;
1736 if (!
ctx->registered_frames[reg_idx].mapped) {
1737 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1738 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
1739 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
1740 if (nv_status != NV_ENC_SUCCESS) {
1746 ctx->registered_frames[reg_idx].mapped += 1;
1748 nvenc_frame->
reg_idx = reg_idx;
1749 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
1750 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1755 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1757 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1760 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
1761 if (nv_status != NV_ENC_SUCCESS) {
1762 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
1765 nvenc_frame->
pitch = lockBufferParams.pitch;
1768 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
1769 if (nv_status != NV_ENC_SUCCESS) {
1778 NV_ENC_PIC_PARAMS *params,
1779 NV_ENC_SEI_PAYLOAD *sei_data)
1785 params->codecPicParams.h264PicParams.sliceMode =
1786 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1787 params->codecPicParams.h264PicParams.sliceModeData =
1788 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1790 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1791 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1796 params->codecPicParams.hevcPicParams.sliceMode =
1797 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1798 params->codecPicParams.hevcPicParams.sliceModeData =
1799 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1801 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1802 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1824 NV_ENC_LOCK_BITSTREAM *params,
1829 pkt->
pts = params->outputTimeStamp;
1841 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1843 uint32_t slice_mode_data;
1844 uint32_t *slice_offsets =
NULL;
1845 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1846 NVENCSTATUS nv_status;
1853 slice_mode_data =
ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1856 slice_mode_data =
ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1863 slice_offsets =
av_mallocz(slice_mode_data *
sizeof(*slice_offsets));
1865 if (!slice_offsets) {
1870 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1872 lock_params.doNotWait = 0;
1874 lock_params.sliceOffsets = slice_offsets;
1876 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
1877 if (nv_status != NV_ENC_SUCCESS) {
1883 ff_alloc_packet2(avctx,
pkt, lock_params.bitstreamSizeInBytes, lock_params.bitstreamSizeInBytes) :
1891 memcpy(
pkt->
data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1893 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
1894 if (nv_status != NV_ENC_SUCCESS) {
1895 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
1901 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
1902 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
1903 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
1904 if (nv_status != NV_ENC_SUCCESS) {
1908 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
1918 switch (lock_params.pictureType) {
1919 case NV_ENC_PIC_TYPE_IDR:
1921 case NV_ENC_PIC_TYPE_I:
1924 case NV_ENC_PIC_TYPE_P:
1927 case NV_ENC_PIC_TYPE_B:
1930 case NV_ENC_PIC_TYPE_BI:
1934 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
1935 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
1940 #if FF_API_CODED_FRAME
1969 int nb_ready, nb_pending;
1974 return nb_ready > 0;
1975 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
1981 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
1984 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1985 int needs_reconfig = 0;
1986 int needs_encode_config = 0;
1987 int reconfig_bitrate = 0, reconfig_dar = 0;
1990 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1991 params.reInitEncodeParams =
ctx->init_encode_params;
1994 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
1996 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
1997 ctx->init_encode_params.darWidth,
1998 ctx->init_encode_params.darHeight, dw, dh);
2000 params.reInitEncodeParams.darHeight = dh;
2001 params.reInitEncodeParams.darWidth = dw;
2007 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
2008 if (avctx->
bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
2010 "avg bitrate change: %d -> %d\n",
2011 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2014 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
2015 reconfig_bitrate = 1;
2020 "max bitrate change: %d -> %d\n",
2021 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2024 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
2025 reconfig_bitrate = 1;
2030 "vbv buffer size change: %d -> %d\n",
2031 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2034 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->
rc_buffer_size;
2035 reconfig_bitrate = 1;
2038 if (reconfig_bitrate) {
2039 params.resetEncoder = 1;
2040 params.forceIDR = 1;
2042 needs_encode_config = 1;
2047 if (!needs_encode_config)
2048 params.reInitEncodeParams.encodeConfig =
NULL;
2050 if (needs_reconfig) {
2051 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, ¶ms);
2052 if (
ret != NV_ENC_SUCCESS) {
2056 ctx->init_encode_params.darHeight = dh;
2057 ctx->init_encode_params.darWidth = dw;
2060 if (reconfig_bitrate) {
2061 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2062 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2063 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2072 NVENCSTATUS nv_status;
2075 NV_ENC_SEI_PAYLOAD *sei_data =
NULL;
2080 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2082 NV_ENC_PIC_PARAMS pic_params = { 0 };
2083 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2085 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2088 if (
ctx->encoder_flushing) {
2092 ctx->encoder_flushing = 0;
2117 pic_params.bufferFmt = in_surf->
format;
2118 pic_params.inputWidth = in_surf->
width;
2119 pic_params.inputHeight = in_surf->
height;
2120 pic_params.inputPitch = in_surf->
pitch;
2124 if (
frame->top_field_first)
2125 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2127 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2129 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2133 pic_params.encodePicFlags =
2134 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2136 pic_params.encodePicFlags = 0;
2139 pic_params.inputTimeStamp =
frame->pts;
2147 sei_data->payloadSize = (uint32_t)sei_size;
2148 sei_data->payloadType = 4;
2149 sei_data->payload = (
uint8_t*)(sei_data + 1);
2155 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2156 ctx->encoder_flushing = 1;
2163 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
2170 if (nv_status != NV_ENC_SUCCESS &&
2171 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2180 if (nv_status == NV_ENC_SUCCESS) {
2197 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2217 }
else if (
ctx->encoder_flushing) {
2232 if (!
ctx->encoder_flushing) {
2241 }
else if (res < 0) {