39 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
41 #define NVENC_CAP 0x30
43 #ifndef NVENC_NO_DEPRECATED_RC
44 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
45 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
46 rc == NV_ENC_PARAMS_RC_CBR_HQ)
48 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR)
77 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
78 pix_fmt == AV_PIX_FMT_P016 || \
79 pix_fmt == AV_PIX_FMT_YUV444P16)
81 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
82 pix_fmt == AV_PIX_FMT_YUV444P16)
89 { NV_ENC_SUCCESS, 0,
"success" },
90 { NV_ENC_ERR_NO_ENCODE_DEVICE,
AVERROR(ENOENT),
"no encode device" },
91 { NV_ENC_ERR_UNSUPPORTED_DEVICE,
AVERROR(ENOSYS),
"unsupported device" },
92 { NV_ENC_ERR_INVALID_ENCODERDEVICE,
AVERROR(EINVAL),
"invalid encoder device" },
93 { NV_ENC_ERR_INVALID_DEVICE,
AVERROR(EINVAL),
"invalid device" },
94 { NV_ENC_ERR_DEVICE_NOT_EXIST,
AVERROR(EIO),
"device does not exist" },
95 { NV_ENC_ERR_INVALID_PTR,
AVERROR(EFAULT),
"invalid ptr" },
96 { NV_ENC_ERR_INVALID_EVENT,
AVERROR(EINVAL),
"invalid event" },
97 { NV_ENC_ERR_INVALID_PARAM,
AVERROR(EINVAL),
"invalid param" },
98 { NV_ENC_ERR_INVALID_CALL,
AVERROR(EINVAL),
"invalid call" },
99 { NV_ENC_ERR_OUT_OF_MEMORY,
AVERROR(ENOMEM),
"out of memory" },
100 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,
AVERROR(EINVAL),
"encoder not initialized" },
101 { NV_ENC_ERR_UNSUPPORTED_PARAM,
AVERROR(ENOSYS),
"unsupported param" },
102 { NV_ENC_ERR_LOCK_BUSY,
AVERROR(EAGAIN),
"lock busy" },
104 { NV_ENC_ERR_INVALID_VERSION,
AVERROR(EINVAL),
"invalid version" },
105 { NV_ENC_ERR_MAP_FAILED,
AVERROR(EIO),
"map failed" },
106 { NV_ENC_ERR_NEED_MORE_INPUT,
AVERROR(EAGAIN),
"need more input" },
107 { NV_ENC_ERR_ENCODER_BUSY,
AVERROR(EAGAIN),
"encoder busy" },
108 { NV_ENC_ERR_EVENT_NOT_REGISTERD,
AVERROR(EBADF),
"event not registered" },
110 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,
AVERROR(EINVAL),
"incompatible client key" },
111 { NV_ENC_ERR_UNIMPLEMENTED,
AVERROR(ENOSYS),
"unimplemented" },
112 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED,
AVERROR(EIO),
"resource register failed" },
113 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,
AVERROR(EBADF),
"resource not registered" },
114 { NV_ENC_ERR_RESOURCE_NOT_MAPPED,
AVERROR(EBADF),
"resource not mapped" },
128 *
desc =
"unknown error";
133 const char *error_string)
136 const char *details =
"(no details)";
139 #ifdef NVENC_HAVE_GETLASTERRORSTRING
141 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
143 if (p_nvenc &&
ctx->nvencoder)
144 details = p_nvenc->nvEncGetLastErrorString(
ctx->nvencoder);
157 #define PRESET_ALIAS(alias, name, ...) \
158 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
160 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
165 #ifdef NVENC_HAVE_NEW_PRESETS
204 ctx->init_encode_params.presetGUID = t->
guid;
207 #ifdef NVENC_HAVE_NEW_PRESETS
208 if (
ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
218 #if NVENCAPI_CHECK_VERSION(11, 1)
219 const char *minver =
"(unknown)";
220 #elif NVENCAPI_CHECK_VERSION(11, 0)
221 # if defined(_WIN32) || defined(__CYGWIN__)
222 const char *minver =
"456.71";
224 const char *minver =
"455.28";
226 #elif NVENCAPI_CHECK_VERSION(10, 0)
227 # if defined(_WIN32) || defined(__CYGWIN__)
228 const char *minver =
"450.51";
230 const char *minver =
"445.87";
232 #elif NVENCAPI_CHECK_VERSION(9, 1)
233 # if defined(_WIN32) || defined(__CYGWIN__)
234 const char *minver =
"436.15";
236 const char *minver =
"435.21";
238 #elif NVENCAPI_CHECK_VERSION(9, 0)
239 # if defined(_WIN32) || defined(__CYGWIN__)
240 const char *minver =
"418.81";
242 const char *minver =
"418.30";
244 #elif NVENCAPI_CHECK_VERSION(8, 2)
245 # if defined(_WIN32) || defined(__CYGWIN__)
246 const char *minver =
"397.93";
248 const char *minver =
"396.24";
250 #elif NVENCAPI_CHECK_VERSION(8, 1)
251 # if defined(_WIN32) || defined(__CYGWIN__)
252 const char *minver =
"390.77";
254 const char *minver =
"390.25";
257 # if defined(_WIN32) || defined(__CYGWIN__)
258 const char *minver =
"378.66";
260 const char *minver =
"378.13";
263 av_log(avctx,
level,
"The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
271 uint32_t nvenc_max_ver;
274 ret = cuda_load_functions(&dl_fn->
cuda_dl, avctx);
278 ret = nvenc_load_functions(&dl_fn->
nvenc_dl, avctx);
284 err = dl_fn->
nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
285 if (err != NV_ENC_SUCCESS)
288 av_log(avctx,
AV_LOG_VERBOSE,
"Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
290 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
291 av_log(avctx,
AV_LOG_ERROR,
"Driver does not support the required nvenc API version. "
292 "Required: %d.%d Found: %d.%d\n",
293 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
294 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
299 dl_fn->
nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
302 if (err != NV_ENC_SUCCESS)
315 if (
ctx->d3d11_device)
327 if (
ctx->d3d11_device)
335 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
337 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
340 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
341 params.apiVersion = NVENCAPI_VERSION;
342 if (
ctx->d3d11_device) {
343 params.device =
ctx->d3d11_device;
344 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
346 params.device =
ctx->cu_context;
347 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
350 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &
ctx->nvencoder);
351 if (ret != NV_ENC_SUCCESS) {
362 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
363 int i, ret, count = 0;
366 ret = p_nvenc->nvEncGetEncodeGUIDCount(
ctx->nvencoder, &count);
368 if (ret != NV_ENC_SUCCESS || !count)
375 ret = p_nvenc->nvEncGetEncodeGUIDs(
ctx->nvencoder, guids, count, &count);
376 if (ret != NV_ENC_SUCCESS) {
382 for (
i = 0;
i < count;
i++) {
383 if (!memcmp(&guids[
i], &
ctx->init_encode_params.encodeGUID,
sizeof(*guids))) {
398 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
399 NV_ENC_CAPS_PARAM params = { 0 };
402 params.version = NV_ENC_CAPS_PARAM_VER;
403 params.capsToQuery = cap;
405 ret = p_nvenc->nvEncGetEncodeCaps(
ctx->nvencoder,
ctx->init_encode_params.encodeGUID, ¶ms, &
val);
407 if (ret == NV_ENC_SUCCESS)
436 if (ret < avctx->
width) {
443 if (ret < avctx->
height) {
450 if (ret < avctx->max_b_frames) {
460 "Interlaced encoding is not supported. Supported level: %d\n",
472 if (
ctx->rc_lookahead > 0 && ret <= 0) {
478 if (
ctx->temporal_aq > 0 && ret <= 0) {
484 if (
ctx->weighted_pred > 0 && ret <= 0) {
490 if (
ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
495 #ifdef NVENC_HAVE_BFRAME_REF_MODE
497 if (
ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1 && ret != 3) {
500 }
else if (
ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
505 if (
ctx->b_ref_mode != 0) {
511 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
513 if(avctx->
refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
518 if(avctx->
refs != 0) {
524 ctx->support_dyn_bitrate =
nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
533 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
534 char name[128] = { 0};
554 av_log(avctx, loglevel,
"[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx,
name,
major,
minor);
556 av_log(avctx, loglevel,
"does not support NVENC\n");
567 ctx->cu_context =
ctx->cu_context_internal;
579 av_log(avctx, loglevel,
"supports NVENC\n");
590 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
598 ctx->cu_context_internal =
NULL;
611 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
614 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
623 av_log(avctx,
AV_LOG_WARNING,
"The selected preset is deprecated. Use p1 to p7 + -tune or fast/medium/slow.\n");
647 cuda_device_hwctx = hwdev_ctx->
hwctx;
650 d3d11_device_hwctx = hwdev_ctx->
hwctx;
658 if (cuda_device_hwctx) {
660 ctx->cu_stream = cuda_device_hwctx->
stream;
663 else if (d3d11_device_hwctx) {
664 ctx->d3d11_device = d3d11_device_hwctx->
device;
665 ID3D11Device_AddRef(
ctx->d3d11_device);
675 av_log(avctx,
AV_LOG_FATAL,
"Provided device doesn't support required NVENC features\n");
679 int i, nb_devices = 0;
695 for (
i = 0;
i < nb_devices; ++
i) {
708 av_log(avctx,
AV_LOG_FATAL,
"Requested GPU %d, but only %d GPUs are available!\n",
ctx->device, nb_devices);
718 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
720 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
722 if (
ctx->init_qp_p >= 0) {
723 rc->constQP.qpInterP =
ctx->init_qp_p;
724 if (
ctx->init_qp_i >= 0 &&
ctx->init_qp_b >= 0) {
725 rc->constQP.qpIntra =
ctx->init_qp_i;
726 rc->constQP.qpInterB =
ctx->init_qp_b;
730 rc->constQP.qpInterB =
av_clip(
733 rc->constQP.qpIntra = rc->constQP.qpInterP;
734 rc->constQP.qpInterB = rc->constQP.qpInterP;
736 }
else if (
ctx->cqp >= 0) {
737 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra =
ctx->cqp;
751 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
754 if (avctx->
qmin >= 0 && avctx->
qmax >= 0) {
758 rc->minQP.qpInterB = avctx->
qmin;
759 rc->minQP.qpInterP = avctx->
qmin;
760 rc->minQP.qpIntra = avctx->
qmin;
762 rc->maxQP.qpInterB = avctx->
qmax;
763 rc->maxQP.qpInterP = avctx->
qmax;
764 rc->maxQP.qpIntra = avctx->
qmax;
766 qp_inter_p = (avctx->
qmax + 3 * avctx->
qmin) / 4;
767 }
else if (avctx->
qmin >= 0) {
770 rc->minQP.qpInterB = avctx->
qmin;
771 rc->minQP.qpInterP = avctx->
qmin;
772 rc->minQP.qpIntra = avctx->
qmin;
774 qp_inter_p = avctx->
qmin;
779 rc->enableInitialRCQP = 1;
781 if (
ctx->init_qp_p < 0) {
782 rc->initialRCQP.qpInterP = qp_inter_p;
784 rc->initialRCQP.qpInterP =
ctx->init_qp_p;
787 if (
ctx->init_qp_i < 0) {
789 rc->initialRCQP.qpIntra =
av_clip(
792 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
795 rc->initialRCQP.qpIntra =
ctx->init_qp_i;
798 if (
ctx->init_qp_b < 0) {
800 rc->initialRCQP.qpInterB =
av_clip(
803 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
806 rc->initialRCQP.qpInterB =
ctx->init_qp_b;
813 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
815 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
816 rc->constQP.qpInterB = 0;
817 rc->constQP.qpInterP = 0;
818 rc->constQP.qpIntra = 0;
827 NV_ENC_RC_PARAMS *rc = &
ctx->encode_config.rcParams;
830 case NV_ENC_PARAMS_RC_CONSTQP:
833 #ifndef NVENC_NO_DEPRECATED_RC
834 case NV_ENC_PARAMS_RC_VBR_MINQP:
835 if (avctx->
qmin < 0) {
837 "The variable bitrate rate-control requires "
838 "the 'qmin' option set.\n");
843 case NV_ENC_PARAMS_RC_VBR_HQ:
845 case NV_ENC_PARAMS_RC_VBR:
848 case NV_ENC_PARAMS_RC_CBR:
849 #ifndef NVENC_NO_DEPRECATED_RC
850 case NV_ENC_PARAMS_RC_CBR_HQ:
851 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
856 rc->rateControlMode =
ctx->rc;
865 int nb_surfaces =
FFMAX(4,
ctx->encode_config.frameIntervalP * 2 * 2);
868 if (
ctx->rc_lookahead > 0) {
871 nb_surfaces =
FFMAX(1,
FFMAX(nb_surfaces,
ctx->rc_lookahead +
ctx->encode_config.frameIntervalP + 1 + 4));
872 if (nb_surfaces >
ctx->nb_surfaces &&
ctx->nb_surfaces > 0)
875 "Defined rc_lookahead requires more surfaces, "
876 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
878 ctx->nb_surfaces =
FFMAX(nb_surfaces,
ctx->nb_surfaces);
880 if (
ctx->encode_config.frameIntervalP > 1 &&
ctx->nb_surfaces < nb_surfaces &&
ctx->nb_surfaces > 0)
883 "Defined b-frame requires more surfaces, "
884 "increasing used surfaces %d -> %d\n",
ctx->nb_surfaces, nb_surfaces);
885 ctx->nb_surfaces =
FFMAX(
ctx->nb_surfaces, nb_surfaces);
887 else if (
ctx->nb_surfaces <= 0)
888 ctx->nb_surfaces = nb_surfaces;
903 av_log(avctx,
AV_LOG_WARNING,
"Using global_quality with nvenc is deprecated. Use qp instead.\n");
909 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate;
910 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
911 ctx->encode_config.rcParams.maxBitRate =
ctx->encode_config.rcParams.averageBitRate;
917 #ifdef NVENC_HAVE_MULTIPASS
918 ctx->encode_config.rcParams.multiPass =
ctx->multipass;
921 ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
923 ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
927 ctx->rc = NV_ENC_PARAMS_RC_CBR;
928 }
else if (
ctx->cqp >= 0) {
929 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
930 }
else if (
ctx->quality >= 0.0f) {
931 ctx->rc = NV_ENC_PARAMS_RC_VBR;
941 if (
ctx->twopass < 0)
946 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
948 ctx->rc = NV_ENC_PARAMS_RC_CBR;
950 }
else if (
ctx->cqp >= 0) {
951 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
952 }
else if (
ctx->twopass) {
953 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
954 }
else if (avctx->
qmin >= 0 && avctx->
qmax >= 0) {
955 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
967 #ifdef NVENC_HAVE_LDKFS
969 ctx->encode_config.rcParams.lowDelayKeyFrameScale =
ctx->ldkfs;
974 }
else if (
ctx->rc >= 0) {
977 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
983 }
else if (
ctx->encode_config.rcParams.averageBitRate > 0) {
984 avctx->
rc_buffer_size =
ctx->encode_config.rcParams.vbvBufferSize = 2 *
ctx->encode_config.rcParams.averageBitRate;
988 ctx->encode_config.rcParams.enableAQ = 1;
989 ctx->encode_config.rcParams.aqStrength =
ctx->aq_strength;
993 if (
ctx->temporal_aq) {
994 ctx->encode_config.rcParams.enableTemporalAQ = 1;
998 if (
ctx->rc_lookahead > 0) {
999 int lkd_bound =
FFMIN(
ctx->nb_surfaces,
ctx->async_depth) -
1000 ctx->encode_config.frameIntervalP - 4;
1002 if (lkd_bound < 0) {
1004 "Lookahead not enabled. Increase buffer delay (-delay).\n");
1006 ctx->encode_config.rcParams.enableLookahead = 1;
1007 ctx->encode_config.rcParams.lookaheadDepth =
av_clip(
ctx->rc_lookahead, 0, lkd_bound);
1008 ctx->encode_config.rcParams.disableIadapt =
ctx->no_scenecut;
1009 ctx->encode_config.rcParams.disableBadapt = !
ctx->b_adapt;
1011 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
1012 ctx->encode_config.rcParams.lookaheadDepth,
1013 ctx->encode_config.rcParams.disableIadapt ?
"disabled" :
"enabled",
1014 ctx->encode_config.rcParams.disableBadapt ?
"disabled" :
"enabled");
1018 if (
ctx->strict_gop) {
1019 ctx->encode_config.rcParams.strictGOPTarget = 1;
1024 ctx->encode_config.rcParams.enableNonRefP = 1;
1026 if (
ctx->zerolatency)
1027 ctx->encode_config.rcParams.zeroReorderDelay = 1;
1031 int tmp_quality = (
int)(
ctx->quality * 256.0f);
1032 ctx->encode_config.rcParams.targetQuality = (
uint8_t)(tmp_quality >> 8);
1033 ctx->encode_config.rcParams.targetQualityLSB = (
uint8_t)(tmp_quality & 0xff);
1038 ctx->encode_config.rcParams.averageBitRate = avctx->
bit_rate = 0;
1047 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1048 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1049 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1053 vui->transferCharacteristics = avctx->
color_trc;
1057 vui->colourDescriptionPresentFlag =
1060 vui->videoSignalTypePresentFlag =
1061 (vui->colourDescriptionPresentFlag
1062 || vui->videoFormat != 5
1063 || vui->videoFullRangeFlag != 0);
1065 h264->sliceMode = 3;
1066 h264->sliceModeData = 1;
1070 h264->outputAUD =
ctx->aud;
1072 if (
ctx->dpb_size >= 0) {
1074 h264->maxNumRefFrames =
ctx->dpb_size;
1077 h264->idrPeriod = cc->gopLength;
1080 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1081 h264->outputBufferingPeriodSEI = 1;
1084 h264->outputPictureTimingSEI = 1;
1086 #ifndef NVENC_NO_DEPRECATED_RC
1087 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1088 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1089 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1090 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1091 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1096 h264->qpPrimeYZeroTransformBypassFlag = 1;
1098 switch(
ctx->profile) {
1100 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1104 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1108 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1112 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1120 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1126 h264->level =
ctx->level;
1128 if (
ctx->coder >= 0)
1129 h264->entropyCodingMode =
ctx->coder;
1131 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1132 h264->useBFramesAsRef =
ctx->b_ref_mode;
1135 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1136 h264->numRefL0 = avctx->
refs;
1137 h264->numRefL1 = avctx->
refs;
1146 NV_ENC_CONFIG *cc = &
ctx->encode_config;
1147 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1148 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1152 vui->transferCharacteristics = avctx->
color_trc;
1156 vui->colourDescriptionPresentFlag =
1159 vui->videoSignalTypePresentFlag =
1160 (vui->colourDescriptionPresentFlag
1161 || vui->videoFormat != 5
1162 || vui->videoFullRangeFlag != 0);
1164 hevc->sliceMode = 3;
1165 hevc->sliceModeData = 1;
1169 hevc->outputAUD =
ctx->aud;
1171 if (
ctx->dpb_size >= 0) {
1173 hevc->maxNumRefFramesInDPB =
ctx->dpb_size;
1176 hevc->idrPeriod = cc->gopLength;
1179 if (
IS_CBR(cc->rcParams.rateControlMode)) {
1180 hevc->outputBufferingPeriodSEI = 1;
1183 hevc->outputPictureTimingSEI = 1;
1185 switch (
ctx->profile) {
1187 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1191 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1195 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1202 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1208 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1212 hevc->chromaFormatIDC =
IS_YUV444(
ctx->data_pix_fmt) ? 3 : 1;
1214 hevc->pixelBitDepthMinus8 =
IS_10BIT(
ctx->data_pix_fmt) ? 2 : 0;
1216 hevc->level =
ctx->level;
1218 hevc->tier =
ctx->tier;
1220 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1221 hevc->useBFramesAsRef =
ctx->b_ref_mode;
1224 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1225 hevc->numRefL0 = avctx->
refs;
1226 hevc->numRefL1 = avctx->
refs;
1263 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1265 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1266 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1271 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1272 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1274 ctx->init_encode_params.encodeHeight = avctx->
height;
1275 ctx->init_encode_params.encodeWidth = avctx->
width;
1277 ctx->init_encode_params.encodeConfig = &
ctx->encode_config;
1279 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1280 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1282 #ifdef NVENC_HAVE_NEW_PRESETS
1283 ctx->init_encode_params.tuningInfo =
ctx->tuning_info;
1286 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1288 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1290 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(
ctx->nvencoder,
1291 ctx->init_encode_params.encodeGUID,
1292 ctx->init_encode_params.presetGUID,
1293 ctx->init_encode_params.tuningInfo,
1296 nv_status = p_nvenc->nvEncGetEncodePresetConfig(
ctx->nvencoder,
1297 ctx->init_encode_params.encodeGUID,
1298 ctx->init_encode_params.presetGUID,
1301 if (nv_status != NV_ENC_SUCCESS)
1302 return nvenc_print_error(avctx, nv_status,
"Cannot get the preset configuration");
1304 memcpy(&
ctx->encode_config, &preset_config.presetCfg,
sizeof(
ctx->encode_config));
1306 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1309 ctx->init_encode_params.darHeight = dh;
1310 ctx->init_encode_params.darWidth = dw;
1320 ctx->init_encode_params.enableEncodeAsync = 0;
1321 ctx->init_encode_params.enablePTD = 1;
1323 #ifdef NVENC_HAVE_NEW_PRESETS
1327 if (
ctx->rc_lookahead == 0 &&
ctx->encode_config.rcParams.enableLookahead)
1328 ctx->rc_lookahead =
ctx->encode_config.rcParams.lookaheadDepth;
1331 if (
ctx->weighted_pred == 1)
1332 ctx->init_encode_params.enableWeightedPrediction = 1;
1334 if (
ctx->bluray_compat) {
1343 ctx->level = NV_ENC_LEVEL_HEVC_51;
1344 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1357 ctx->encode_config.frameIntervalP = 0;
1358 ctx->encode_config.gopLength = 1;
1366 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1368 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1379 nv_status = p_nvenc->nvEncInitializeEncoder(
ctx->nvencoder, &
ctx->init_encode_params);
1380 if (nv_status != NV_ENC_SUCCESS) {
1385 #ifdef NVENC_HAVE_CUSTREAM_PTR
1386 if (
ctx->cu_context) {
1387 nv_status = p_nvenc->nvEncSetIOCudaStreams(
ctx->nvencoder, &
ctx->cu_stream, &
ctx->cu_stream);
1388 if (nv_status != NV_ENC_SUCCESS) {
1399 if (
ctx->encode_config.frameIntervalP > 1)
1402 if (
ctx->encode_config.rcParams.averageBitRate > 0)
1403 avctx->
bit_rate =
ctx->encode_config.rcParams.averageBitRate;
1410 cpb_props->
buffer_size =
ctx->encode_config.rcParams.vbvBufferSize;
1419 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1421 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1424 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1426 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1428 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1430 return NV_ENC_BUFFER_FORMAT_ARGB;
1432 return NV_ENC_BUFFER_FORMAT_ABGR;
1434 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1442 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1445 NVENCSTATUS nv_status;
1446 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1447 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1451 if (!
ctx->surfaces[idx].in_ref)
1454 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1457 if (
ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1463 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1464 allocSurf.width = avctx->
width;
1465 allocSurf.height = avctx->
height;
1466 allocSurf.bufferFmt =
ctx->surfaces[idx].format;
1468 nv_status = p_nvenc->nvEncCreateInputBuffer(
ctx->nvencoder, &allocSurf);
1469 if (nv_status != NV_ENC_SUCCESS) {
1473 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1474 ctx->surfaces[idx].width = allocSurf.width;
1475 ctx->surfaces[idx].height = allocSurf.height;
1478 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(
ctx->nvencoder, &allocOut);
1479 if (nv_status != NV_ENC_SUCCESS) {
1482 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[idx].input_surface);
1487 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1497 int i, res = 0, res2;
1504 if (!
ctx->timestamp_list)
1508 if (!
ctx->unused_surface_queue)
1512 if (!
ctx->output_surface_queue)
1515 if (!
ctx->output_surface_ready_queue)
1522 for (
i = 0;
i <
ctx->nb_surfaces;
i++) {
1539 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1541 NVENCSTATUS nv_status;
1542 uint32_t outSize = 0;
1543 char tmpHeader[256];
1544 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1545 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1547 payload.spsppsBuffer = tmpHeader;
1548 payload.inBufferSize =
sizeof(tmpHeader);
1549 payload.outSPSPPSPayloadSize = &outSize;
1551 nv_status = p_nvenc->nvEncGetSequenceParams(
ctx->nvencoder, &payload);
1552 if (nv_status != NV_ENC_SUCCESS) {
1563 memcpy(avctx->
extradata, tmpHeader, outSize);
1572 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1576 if (
ctx->nvencoder) {
1577 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1578 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1584 p_nvenc->nvEncEncodePicture(
ctx->nvencoder, ¶ms);
1593 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1594 if (
ctx->registered_frames[
i].mapped)
1595 p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[
i].in_map.mappedResource);
1596 if (
ctx->registered_frames[
i].regptr)
1597 p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
1599 ctx->nb_registered_frames = 0;
1602 if (
ctx->surfaces) {
1603 for (
i = 0;
i <
ctx->nb_surfaces; ++
i) {
1605 p_nvenc->nvEncDestroyInputBuffer(
ctx->nvencoder,
ctx->surfaces[
i].input_surface);
1607 p_nvenc->nvEncDestroyBitstreamBuffer(
ctx->nvencoder,
ctx->surfaces[
i].output_surface);
1611 ctx->nb_surfaces = 0;
1615 if (
ctx->nvencoder) {
1616 p_nvenc->nvEncDestroyEncoder(
ctx->nvencoder);
1624 if (
ctx->cu_context_internal)
1626 ctx->cu_context =
ctx->cu_context_internal =
NULL;
1629 if (
ctx->d3d11_device) {
1630 ID3D11Device_Release(
ctx->d3d11_device);
1635 nvenc_free_functions(&dl_fn->
nvenc_dl);
1636 cuda_free_functions(&dl_fn->
cuda_dl);
1654 "hw_frames_ctx must be set when using GPU frames as input\n");
1660 "hw_frames_ctx must match the GPU frame type\n");
1705 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params,
const AVFrame *
frame)
1707 int dst_linesize[4] = {
1708 lock_buffer_params->pitch,
1709 lock_buffer_params->pitch,
1710 lock_buffer_params->pitch,
1711 lock_buffer_params->pitch
1717 dst_linesize[1] = dst_linesize[2] >>= 1;
1720 lock_buffer_params->bufferDataPtr, dst_linesize);
1738 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1739 NVENCSTATUS nv_status;
1744 for (first_round = 1; first_round >= 0; first_round--) {
1745 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1746 if (!
ctx->registered_frames[
i].mapped) {
1747 if (
ctx->registered_frames[
i].regptr) {
1750 nv_status = p_nvenc->nvEncUnregisterResource(
ctx->nvencoder,
ctx->registered_frames[
i].regptr);
1751 if (nv_status != NV_ENC_SUCCESS)
1752 return nvenc_print_error(avctx, nv_status,
"Failed unregistering unused input resource");
1753 ctx->registered_frames[
i].ptr =
NULL;
1754 ctx->registered_frames[
i].regptr =
NULL;
1761 return ctx->nb_registered_frames++;
1772 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1775 NV_ENC_REGISTER_RESOURCE reg = { 0 };
1778 for (
i = 0;
i <
ctx->nb_registered_frames;
i++) {
1789 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1790 reg.width = frames_ctx->width;
1791 reg.height = frames_ctx->height;
1793 reg.resourceToRegister =
frame->
data[0];
1796 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1799 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1800 reg.subResourceIndex = (intptr_t)
frame->
data[1];
1804 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1810 ret = p_nvenc->nvEncRegisterResource(
ctx->nvencoder, ®);
1811 if (ret != NV_ENC_SUCCESS) {
1817 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1818 ctx->registered_frames[idx].regptr = reg.registeredResource;
1827 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1830 NVENCSTATUS nv_status;
1843 if (!
ctx->registered_frames[reg_idx].mapped) {
1844 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1845 ctx->registered_frames[reg_idx].in_map.registeredResource =
ctx->registered_frames[reg_idx].regptr;
1846 nv_status = p_nvenc->nvEncMapInputResource(
ctx->nvencoder, &
ctx->registered_frames[reg_idx].in_map);
1847 if (nv_status != NV_ENC_SUCCESS) {
1853 ctx->registered_frames[reg_idx].mapped += 1;
1855 nvenc_frame->
reg_idx = reg_idx;
1856 nvenc_frame->
input_surface =
ctx->registered_frames[reg_idx].in_map.mappedResource;
1857 nvenc_frame->
format =
ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1862 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1864 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1867 nv_status = p_nvenc->nvEncLockInputBuffer(
ctx->nvencoder, &lockBufferParams);
1868 if (nv_status != NV_ENC_SUCCESS) {
1869 return nvenc_print_error(avctx, nv_status,
"Failed locking nvenc input buffer");
1872 nvenc_frame->
pitch = lockBufferParams.pitch;
1875 nv_status = p_nvenc->nvEncUnlockInputBuffer(
ctx->nvencoder, nvenc_frame->
input_surface);
1876 if (nv_status != NV_ENC_SUCCESS) {
1885 NV_ENC_PIC_PARAMS *params,
1886 NV_ENC_SEI_PAYLOAD *sei_data,
1893 params->codecPicParams.h264PicParams.sliceMode =
1894 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1895 params->codecPicParams.h264PicParams.sliceModeData =
1896 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1897 if (sei_count > 0) {
1898 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1899 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
1904 params->codecPicParams.hevcPicParams.sliceMode =
1905 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1906 params->codecPicParams.hevcPicParams.sliceModeData =
1907 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1908 if (sei_count > 0) {
1909 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1910 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
1932 NV_ENC_LOCK_BITSTREAM *params,
1937 pkt->
pts = params->outputTimeStamp;
1949 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
1951 uint32_t slice_mode_data;
1952 uint32_t *slice_offsets =
NULL;
1953 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1954 NVENCSTATUS nv_status;
1961 slice_mode_data =
ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1964 slice_mode_data =
ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1971 slice_offsets =
av_mallocz(slice_mode_data *
sizeof(*slice_offsets));
1973 if (!slice_offsets) {
1978 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1980 lock_params.doNotWait = 0;
1982 lock_params.sliceOffsets = slice_offsets;
1984 nv_status = p_nvenc->nvEncLockBitstream(
ctx->nvencoder, &lock_params);
1985 if (nv_status != NV_ENC_SUCCESS) {
1997 memcpy(
pkt->
data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1999 nv_status = p_nvenc->nvEncUnlockBitstream(
ctx->nvencoder, tmpoutsurf->
output_surface);
2000 if (nv_status != NV_ENC_SUCCESS) {
2001 res =
nvenc_print_error(avctx, nv_status,
"Failed unlocking bitstream buffer, expect the gates of mordor to open");
2007 ctx->registered_frames[tmpoutsurf->
reg_idx].mapped -= 1;
2008 if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped == 0) {
2009 nv_status = p_nvenc->nvEncUnmapInputResource(
ctx->nvencoder,
ctx->registered_frames[tmpoutsurf->
reg_idx].in_map.mappedResource);
2010 if (nv_status != NV_ENC_SUCCESS) {
2014 }
else if (
ctx->registered_frames[tmpoutsurf->
reg_idx].mapped < 0) {
2024 switch (lock_params.pictureType) {
2025 case NV_ENC_PIC_TYPE_IDR:
2027 case NV_ENC_PIC_TYPE_I:
2030 case NV_ENC_PIC_TYPE_P:
2033 case NV_ENC_PIC_TYPE_B:
2036 case NV_ENC_PIC_TYPE_BI:
2040 av_log(avctx,
AV_LOG_ERROR,
"Unknown picture type encountered, expect the output to be broken.\n");
2041 av_log(avctx,
AV_LOG_ERROR,
"Please report this error and include as much information on how to reproduce it as possible.\n");
2046 #if FF_API_CODED_FRAME
2075 int nb_ready, nb_pending;
2080 return nb_ready > 0;
2081 return (nb_ready > 0) && (nb_ready + nb_pending >=
ctx->async_depth);
2087 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &
ctx->nvenc_dload_funcs.nvenc_funcs;
2090 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2091 int needs_reconfig = 0;
2092 int needs_encode_config = 0;
2093 int reconfig_bitrate = 0, reconfig_dar = 0;
2096 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2097 params.reInitEncodeParams =
ctx->init_encode_params;
2100 if (dw !=
ctx->init_encode_params.darWidth || dh !=
ctx->init_encode_params.darHeight) {
2102 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2103 ctx->init_encode_params.darWidth,
2104 ctx->init_encode_params.darHeight, dw, dh);
2106 params.reInitEncodeParams.darHeight = dh;
2107 params.reInitEncodeParams.darWidth = dw;
2113 if (
ctx->rc != NV_ENC_PARAMS_RC_CONSTQP &&
ctx->support_dyn_bitrate) {
2114 if (avctx->
bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->
bit_rate) {
2116 "avg bitrate change: %d -> %d\n",
2117 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2120 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->
bit_rate;
2121 reconfig_bitrate = 1;
2126 "max bitrate change: %d -> %d\n",
2127 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2130 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->
rc_max_rate;
2131 reconfig_bitrate = 1;
2136 "vbv buffer size change: %d -> %d\n",
2137 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2140 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->
rc_buffer_size;
2141 reconfig_bitrate = 1;
2144 if (reconfig_bitrate) {
2145 params.resetEncoder = 1;
2146 params.forceIDR = 1;
2148 needs_encode_config = 1;
2153 if (!needs_encode_config)
2154 params.reInitEncodeParams.encodeConfig =
NULL;
2156 if (needs_reconfig) {
2157 ret = p_nvenc->nvEncReconfigureEncoder(
ctx->nvencoder, ¶ms);
2158 if (ret != NV_ENC_SUCCESS) {
2162 ctx->init_encode_params.darHeight = dh;
2163 ctx->init_encode_params.darWidth = dw;
2166 if (reconfig_bitrate) {
2167 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2168 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2169 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2178 NVENCSTATUS nv_status;
2181 NV_ENC_SEI_PAYLOAD sei_data[8];
2187 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->
nvenc_funcs;
2189 NV_ENC_PIC_PARAMS pic_params = { 0 };
2190 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2192 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
2216 pic_params.bufferFmt = in_surf->
format;
2217 pic_params.inputWidth = in_surf->
width;
2218 pic_params.inputHeight = in_surf->
height;
2219 pic_params.inputPitch = in_surf->
pitch;
2224 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2226 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2228 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2232 pic_params.encodePicFlags =
2233 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2235 pic_params.encodePicFlags = 0;
2238 pic_params.inputTimeStamp =
frame->
pts;
2241 void *a53_data =
NULL;
2242 size_t a53_size = 0;
2249 sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2250 sei_data[sei_count].payloadType = 4;
2251 sei_data[sei_count].payload = (
uint8_t*)a53_data;
2257 void *tc_data =
NULL;
2265 sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2267 sei_data[sei_count].payload = (
uint8_t*)tc_data;
2274 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2281 nv_status = p_nvenc->nvEncEncodePicture(
ctx->nvencoder, &pic_params);
2283 for (
i = 0;
i < sei_count;
i++)
2290 if (nv_status != NV_ENC_SUCCESS &&
2291 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2300 if (nv_status == NV_ENC_SUCCESS) {
2319 if ((!
ctx->cu_context && !
ctx->d3d11_device) || !
ctx->nvencoder)
static void flush(AVCodecContext *avctx)
static double val(void *priv, double ch)
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.
simple assert() macros that are a bit more flexible than ISO C assert().
#define FF_PROFILE_H264_HIGH
#define FF_PROFILE_H264_MAIN
#define FF_PROFILE_HEVC_MAIN_10
#define FF_PROFILE_H264_HIGH_444_PREDICTIVE
#define FF_PROFILE_H264_BASELINE
#define FF_PROFILE_HEVC_REXT
#define FF_PROFILE_HEVC_MAIN
int ff_side_data_set_encoder_stats(AVPacket *pkt, int quality, int64_t *error, int error_count, int pict_type)
#define flags(name, subs,...)
#define FFSWAP(type, a, b)
static __device__ float fabs(float a)
static enum AVPixelFormat pix_fmt
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.
#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_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.
#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.
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
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.
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
@ AV_FRAME_DATA_S12M_TIMECODE
Timecode which conforms to SMPTE ST 12-1.
#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.
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
void * av_mallocz_array(size_t nmemb, size_t size)
Allocate a memory block for an array with av_mallocz().
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.
void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height)
Copy image in src_data to dst_data.
@ 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.
#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.
AVCPBProperties * ff_add_cpb_side_data(AVCodecContext *avctx)
Add a CPB properties side data to an encoding context.
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 av_fifo_reset(AVFifoBuffer *f)
Reset the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied.
void av_fifo_freep(AVFifoBuffer **f)
Free an AVFifoBuffer and reset pointer to NULL.
int av_fifo_size(const AVFifoBuffer *f)
Return the amount of data in bytes in the AVFifoBuffer, that is the amount of data you can read from ...
int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void(*func)(void *, void *, int))
Feed data from an AVFifoBuffer to a user-supplied callback.
AVFifoBuffer * av_fifo_alloc(unsigned int size)
Initialize an AVFifoBuffer.
int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int(*func)(void *, void *, int))
Feed data from a user-supplied callback to an AVFifoBuffer.
common internal API header
#define FF_DISABLE_DEPRECATION_WARNINGS
#define FF_ENABLE_DEPRECATION_WARNINGS
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 av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
static const struct @102 nvenc_errors[]
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 nvenc_codec_specific_pic_params(AVCodecContext *avctx, NV_ENC_PIC_PARAMS *params, NV_ENC_SEI_PAYLOAD *sei_data, int sei_count)
static void timestamp_queue_enqueue(AVFifoBuffer *queue, int64_t timestamp)
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)
static int nvenc_map_error(NVENCSTATUS err, const char **desc)
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 int64_t timestamp_queue_dequeue(AVFifoBuffer *queue)
static void nvenc_map_preset(NvencContext *ctx)
#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 int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame, NvencSurface *nvenc_frame)
static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
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 av_cold int nvenc_setup_device(AVCodecContext *avctx)
static int output_ready(AVCodecContext *avctx, int flush)
static NvencSurface * get_free_frame(NvencContext *ctx)
static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
@ NVENC_DEPRECATED_PRESET
@ 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 RC_MODE_DEPRECATED
#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.
#define AV_PIX_FMT_0RGB32
@ AVCOL_RANGE_JPEG
Full range content.
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_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_YUVJ422P
planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting col...
@ 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_YUV444P16
#define AV_PIX_FMT_0BGR32
#define FF_ARRAY_ELEMS(a)
uint8_t * data
The data buffer.
This structure describes the bitrate properties of an encoded bitstream.
int avg_bitrate
Average bitrate of the stream, in bits per second.
int buffer_size
The size of the buffer to which the ratecontrol is applied, in bits.
int max_bitrate
Maximum bitrate of the stream, in bits per second.
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.
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.
attribute_deprecated AVFrame * coded_frame
the picture in the bitstream
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
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_*.
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
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 draining
checks API usage: after codec draining, flush is required to resume operation
This struct is allocated as AVHWDeviceContext.hwctx.
ID3D11Device * device
Device used for texture creation and access.
int flags
Flags modifying the (de)muxer behaviour.
This structure describes decoded (raw) audio or video data.
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
AVBufferRef * hw_frames_ctx
For hwaccel-format frames, this should be a reference to the AVHWFramesContext describing the frame.
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
int top_field_first
If the content is interlaced, is top field displayed first.
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
enum AVPictureType pict_type
Picture type of the frame.
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.
AVHWDeviceContext * device_ctx
The parent AVHWDeviceContext.
This structure stores compressed data.
int flags
A combination of AV_PKT_FLAG values.
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
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[]