103 minimum_api_version = (client_config.videoFormat <= 1) ? MAKE_NVENC_VER(11U, 0U) : MAKE_NVENC_VER(12U, 0U);
112 auto fail_guard = util::fail_guard([
this] {
116 encoder_params.width = client_config.width;
117 encoder_params.height = client_config.height;
118 encoder_params.buffer_format = buffer_format;
119 encoder_params.rfi =
true;
121 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS session_params = {
min_struct_version(NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER)};
122 session_params.device =
device;
123 session_params.deviceType = device_type;
124 session_params.apiVersion = minimum_api_version;
125 if (nvenc_failed(
nvenc->nvEncOpenEncodeSessionEx(&session_params, &encoder))) {
126 BOOST_LOG(error) <<
"NvEnc: NvEncOpenEncodeSessionEx() failed: " << last_nvenc_error_string;
130 uint32_t encode_guid_count = 0;
131 if (nvenc_failed(
nvenc->nvEncGetEncodeGUIDCount(encoder, &encode_guid_count))) {
132 BOOST_LOG(error) <<
"NvEnc: NvEncGetEncodeGUIDCount() failed: " << last_nvenc_error_string;
136 std::vector<GUID> encode_guids(encode_guid_count);
137 if (nvenc_failed(
nvenc->nvEncGetEncodeGUIDs(encoder, encode_guids.data(), encode_guids.size(), &encode_guid_count))) {
138 BOOST_LOG(error) <<
"NvEnc: NvEncGetEncodeGUIDs() failed: " << last_nvenc_error_string;
142 NV_ENC_INITIALIZE_PARAMS init_params = {
min_struct_version(NV_ENC_INITIALIZE_PARAMS_VER)};
144 switch (client_config.videoFormat) {
147 init_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
152 init_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
157 init_params.encodeGUID = NV_ENC_CODEC_AV1_GUID;
161 BOOST_LOG(error) <<
"NvEnc: unknown video format " << client_config.videoFormat;
166 auto search_predicate = [&](
const GUID &guid) {
167 return equal_guids(init_params.encodeGUID, guid);
169 if (std::find_if(encode_guids.begin(), encode_guids.end(), search_predicate) == encode_guids.end()) {
170 BOOST_LOG(error) <<
"NvEnc: encoding format is not supported by the gpu";
175 auto get_encoder_cap = [&](NV_ENC_CAPS cap) {
178 nvenc->nvEncGetEncodeCaps(encoder, init_params.encodeGUID, ¶m, &value);
182 auto buffer_is_10bit = [&]() {
183 return buffer_format == NV_ENC_BUFFER_FORMAT_YUV420_10BIT || buffer_format == NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
186 auto buffer_is_yuv444 = [&]() {
187 return buffer_format == NV_ENC_BUFFER_FORMAT_AYUV || buffer_format == NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
191 auto supported_width = get_encoder_cap(NV_ENC_CAPS_WIDTH_MAX);
192 auto supported_height = get_encoder_cap(NV_ENC_CAPS_HEIGHT_MAX);
193 if (encoder_params.width > supported_width || encoder_params.height > supported_height) {
194 BOOST_LOG(error) <<
"NvEnc: gpu max encode resolution " << supported_width <<
"x" << supported_height <<
", requested " << encoder_params.width <<
"x" << encoder_params.height;
199 if (buffer_is_10bit() && !get_encoder_cap(NV_ENC_CAPS_SUPPORT_10BIT_ENCODE)) {
200 BOOST_LOG(error) <<
"NvEnc: gpu doesn't support 10-bit encode";
204 if (buffer_is_yuv444() && !get_encoder_cap(NV_ENC_CAPS_SUPPORT_YUV444_ENCODE)) {
205 BOOST_LOG(error) <<
"NvEnc: gpu doesn't support YUV444 encode";
210 BOOST_LOG(warning) <<
"NvEnc: gpu doesn't support async encode";
214 encoder_params.rfi = get_encoder_cap(NV_ENC_CAPS_SUPPORT_REF_PIC_INVALIDATION);
216 init_params.presetGUID = quality_preset_guid_from_number(config.quality_preset);
217 init_params.tuningInfo = NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY;
218 init_params.enablePTD = 1;
220 init_params.enableWeightedPrediction = config.weighted_prediction && get_encoder_cap(NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
222 init_params.encodeWidth = encoder_params.width;
223 init_params.darWidth = encoder_params.width;
224 init_params.encodeHeight = encoder_params.height;
225 init_params.darHeight = encoder_params.height;
226 init_params.frameRateNum = client_config.framerate;
227 init_params.frameRateDen = 1;
230 if (nvenc_failed(
nvenc->nvEncGetEncodePresetConfigEx(encoder, init_params.encodeGUID, init_params.presetGUID, init_params.tuningInfo, &preset_config))) {
231 BOOST_LOG(error) <<
"NvEnc: NvEncGetEncodePresetConfigEx() failed: " << last_nvenc_error_string;
235 NV_ENC_CONFIG enc_config = preset_config.presetCfg;
236 enc_config.profileGUID = NV_ENC_CODEC_PROFILE_AUTOSELECT_GUID;
237 enc_config.gopLength = NVENC_INFINITE_GOPLENGTH;
238 enc_config.frameIntervalP = 1;
239 enc_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
240 enc_config.rcParams.zeroReorderDelay = 1;
241 enc_config.rcParams.enableLookahead = 0;
242 enc_config.rcParams.lowDelayKeyFrameScale = 1;
245 NV_ENC_MULTI_PASS_DISABLED;
247 enc_config.rcParams.enableAQ = config.adaptive_quantization;
248 enc_config.rcParams.averageBitRate = client_config.bitrate * 1000;
250 if (get_encoder_cap(NV_ENC_CAPS_SUPPORT_CUSTOM_VBV_BUF_SIZE)) {
251 enc_config.rcParams.vbvBufferSize = client_config.bitrate * 1000 / client_config.framerate;
252 if (config.vbv_percentage_increase > 0) {
253 enc_config.rcParams.vbvBufferSize += enc_config.rcParams.vbvBufferSize * config.vbv_percentage_increase / 100;
257 auto set_h264_hevc_common_format_config = [&](
auto &format_config) {
258 format_config.repeatSPSPPS = 1;
259 format_config.idrPeriod = NVENC_INFINITE_GOPLENGTH;
260 format_config.sliceMode = 3;
261 format_config.sliceModeData = client_config.slicesPerFrame;
262 if (buffer_is_yuv444()) {
263 format_config.chromaFormatIDC = 3;
265 format_config.enableFillerDataInsertion = config.insert_filler_data;
268 auto set_ref_frames = [&](uint32_t &ref_frames_option, NV_ENC_NUM_REF_FRAMES &L0_option, uint32_t ref_frames_default) {
269 if (client_config.numRefFrames > 0) {
270 ref_frames_option = client_config.numRefFrames;
272 ref_frames_option = ref_frames_default;
274 if (ref_frames_option > 0 && !get_encoder_cap(NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES)) {
275 ref_frames_option = 1;
276 encoder_params.rfi =
false;
278 encoder_params.ref_frames_in_dpb = ref_frames_option;
280 L0_option = NV_ENC_NUM_REF_FRAMES_1;
283 auto set_minqp_if_enabled = [&](
int value) {
284 if (config.enable_min_qp) {
285 enc_config.rcParams.enableMinQP = 1;
286 enc_config.rcParams.minQP.qpInterP = value;
287 enc_config.rcParams.minQP.qpIntra = value;
291 auto fill_h264_hevc_vui = [&](
auto &vui_config) {
292 vui_config.videoSignalTypePresentFlag = 1;
293 vui_config.videoFormat = NV_ENC_VUI_VIDEO_FORMAT_UNSPECIFIED;
294 vui_config.videoFullRangeFlag = colorspace.full_range;
295 vui_config.colourDescriptionPresentFlag = 1;
296 vui_config.colourPrimaries = colorspace.primaries;
297 vui_config.transferCharacteristics = colorspace.tranfer_function;
298 vui_config.colourMatrix = colorspace.matrix;
299 vui_config.chromaSampleLocationFlag = buffer_is_yuv444() ? 0 : 1;
300 vui_config.chromaSampleLocationTop = 0;
301 vui_config.chromaSampleLocationBot = 0;
304 switch (client_config.videoFormat) {
308 enc_config.profileGUID = buffer_is_yuv444() ? NV_ENC_H264_PROFILE_HIGH_444_GUID : NV_ENC_H264_PROFILE_HIGH_GUID;
309 auto &format_config = enc_config.encodeCodecConfig.h264Config;
310 set_h264_hevc_common_format_config(format_config);
311 if (config.h264_cavlc || !get_encoder_cap(NV_ENC_CAPS_SUPPORT_CABAC)) {
312 format_config.entropyCodingMode = NV_ENC_H264_ENTROPY_CODING_MODE_CAVLC;
314 format_config.entropyCodingMode = NV_ENC_H264_ENTROPY_CODING_MODE_CABAC;
316 set_ref_frames(format_config.maxNumRefFrames, format_config.numRefL0, 5);
317 set_minqp_if_enabled(config.min_qp_h264);
318 fill_h264_hevc_vui(format_config.h264VUIParameters);
325 auto &format_config = enc_config.encodeCodecConfig.hevcConfig;
326 set_h264_hevc_common_format_config(format_config);
327 if (buffer_is_10bit()) {
328 format_config.pixelBitDepthMinus8 = 2;
330 set_ref_frames(format_config.maxNumRefFramesInDPB, format_config.numRefL0, 5);
331 set_minqp_if_enabled(config.min_qp_hevc);
332 fill_h264_hevc_vui(format_config.hevcVUIParameters);
333 if (client_config.enableIntraRefresh == 1) {
334 if (get_encoder_cap(NV_ENC_CAPS_SUPPORT_INTRA_REFRESH)) {
335 format_config.enableIntraRefresh = 1;
336 format_config.intraRefreshPeriod = 300;
337 format_config.intraRefreshCnt = 299;
338 if (get_encoder_cap(NV_ENC_CAPS_SINGLE_SLICE_INTRA_REFRESH)) {
339 format_config.singleSliceIntraRefresh = 1;
341 BOOST_LOG(warning) <<
"NvEnc: Single Slice Intra Refresh not supported";
344 BOOST_LOG(error) <<
"NvEnc: Client asked for intra-refresh but the encoder does not support intra-refresh";
353 auto &format_config = enc_config.encodeCodecConfig.av1Config;
354 format_config.repeatSeqHdr = 1;
355 format_config.idrPeriod = NVENC_INFINITE_GOPLENGTH;
356 if (buffer_is_yuv444()) {
357 format_config.chromaFormatIDC = 3;
359 format_config.enableBitstreamPadding = config.insert_filler_data;
360 if (buffer_is_10bit()) {
361 format_config.inputPixelBitDepthMinus8 = 2;
362 format_config.pixelBitDepthMinus8 = 2;
364 format_config.colorPrimaries = colorspace.primaries;
365 format_config.transferCharacteristics = colorspace.tranfer_function;
366 format_config.matrixCoefficients = colorspace.matrix;
367 format_config.colorRange = colorspace.full_range;
368 format_config.chromaSamplePosition = buffer_is_yuv444() ? 0 : 1;
369 set_ref_frames(format_config.maxNumRefFramesInDPB, format_config.numFwdRefs, 8);
370 set_minqp_if_enabled(config.min_qp_av1);
372 if (client_config.slicesPerFrame > 1) {
375 format_config.numTileRows = std::pow(2, std::ceil(std::log2(client_config.slicesPerFrame) / 2));
376 format_config.numTileColumns = std::pow(2, std::floor(std::log2(client_config.slicesPerFrame) / 2));
382 init_params.encodeConfig = &enc_config;
384 if (nvenc_failed(
nvenc->nvEncInitializeEncoder(encoder, &init_params))) {
385 BOOST_LOG(error) <<
"NvEnc: NvEncInitializeEncoder() failed: " << last_nvenc_error_string;
392 if (nvenc_failed(
nvenc->nvEncRegisterAsyncEvent(encoder, &event_params))) {
393 BOOST_LOG(error) <<
"NvEnc: NvEncRegisterAsyncEvent() failed: " << last_nvenc_error_string;
398 NV_ENC_CREATE_BITSTREAM_BUFFER create_bitstream_buffer = {
min_struct_version(NV_ENC_CREATE_BITSTREAM_BUFFER_VER)};
399 if (nvenc_failed(
nvenc->nvEncCreateBitstreamBuffer(encoder, &create_bitstream_buffer))) {
400 BOOST_LOG(error) <<
"NvEnc: NvEncCreateBitstreamBuffer() failed: " << last_nvenc_error_string;
403 output_bitstream = create_bitstream_buffer.bitstreamBuffer;
410 auto f = stat_trackers::two_digits_after_decimal();
411 BOOST_LOG(debug) <<
"NvEnc: requested encoded frame size " << f % (client_config.bitrate / 8. / client_config.framerate) <<
" kB";
415 auto video_format_string = client_config.videoFormat == 0 ?
"H.264 " :
416 client_config.videoFormat == 1 ?
"HEVC " :
417 client_config.videoFormat == 2 ?
"AV1 " :
420 if (init_params.enableEncodeAsync) {
423 if (buffer_is_yuv444()) {
426 if (buffer_is_10bit()) {
429 if (enc_config.rcParams.multiPass != NV_ENC_MULTI_PASS_DISABLED) {
430 extra +=
" two-pass";
432 if (config.vbv_percentage_increase > 0 && get_encoder_cap(NV_ENC_CAPS_SUPPORT_CUSTOM_VBV_BUF_SIZE)) {
433 extra += std::format(
" vbv+{}", config.vbv_percentage_increase);
435 if (encoder_params.rfi) {
438 if (init_params.enableWeightedPrediction) {
439 extra +=
" weighted-prediction";
441 if (enc_config.rcParams.enableAQ) {
442 extra +=
" spatial-aq";
444 if (enc_config.rcParams.enableMinQP) {
445 extra += std::format(
" qpmin={}", enc_config.rcParams.minQP.qpInterP);
447 if (config.insert_filler_data) {
448 extra +=
" filler-data";
451 BOOST_LOG(info) <<
"NvEnc: created encoder " << video_format_string << quality_preset_string_from_guid(init_params.presetGUID) << extra;
455 fail_guard.disable();
496 assert(output_bitstream);
499 BOOST_LOG(error) <<
"NvEnc: failed to synchronize input buffer";
503 NV_ENC_MAP_INPUT_RESOURCE mapped_input_buffer = {
min_struct_version(NV_ENC_MAP_INPUT_RESOURCE_VER)};
506 if (nvenc_failed(
nvenc->nvEncMapInputResource(encoder, &mapped_input_buffer))) {
507 BOOST_LOG(error) <<
"NvEnc: NvEncMapInputResource() failed: " << last_nvenc_error_string;
510 auto unmap_guard = util::fail_guard([&] {
511 if (nvenc_failed(
nvenc->nvEncUnmapInputResource(encoder, mapped_input_buffer.mappedResource))) {
512 BOOST_LOG(error) <<
"NvEnc: NvEncUnmapInputResource() failed: " << last_nvenc_error_string;
517 pic_params.inputWidth = encoder_params.width;
518 pic_params.inputHeight = encoder_params.height;
519 pic_params.encodePicFlags = force_idr ? NV_ENC_PIC_FLAG_FORCEIDR : 0;
520 pic_params.inputTimeStamp = frame_index;
521 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
522 pic_params.inputBuffer = mapped_input_buffer.mappedResource;
523 pic_params.bufferFmt = mapped_input_buffer.mappedBufferFmt;
524 pic_params.outputBitstream = output_bitstream;
527 if (nvenc_failed(
nvenc->nvEncEncodePicture(encoder, &pic_params))) {
528 BOOST_LOG(error) <<
"NvEnc: NvEncEncodePicture() failed: " << last_nvenc_error_string;
532 NV_ENC_LOCK_BITSTREAM lock_bitstream = {
min_struct_version(NV_ENC_LOCK_BITSTREAM_VER, 1, 2)};
533 lock_bitstream.outputBitstream = output_bitstream;
537 BOOST_LOG(error) <<
"NvEnc: frame " << frame_index <<
" encode wait timeout";
541 if (nvenc_failed(
nvenc->nvEncLockBitstream(encoder, &lock_bitstream))) {
542 BOOST_LOG(error) <<
"NvEnc: NvEncLockBitstream() failed: " << last_nvenc_error_string;
546 auto data_pointer = (uint8_t *) lock_bitstream.bitstreamBufferPtr;
548 {data_pointer, data_pointer + lock_bitstream.bitstreamSizeInBytes},
549 lock_bitstream.outputTimeStamp,
550 lock_bitstream.pictureType == NV_ENC_PIC_TYPE_IDR,
551 encoder_state.rfi_needs_confirmation,
554 if (encoder_state.rfi_needs_confirmation) {
556 encoder_state.rfi_needs_confirmation =
false;
559 encoder_state.last_encoded_frame_index = frame_index;
561 if (encoded_frame.idr) {
562 BOOST_LOG(debug) <<
"NvEnc: idr frame " << encoded_frame.frame_index;
565 if (nvenc_failed(
nvenc->nvEncUnlockBitstream(encoder, lock_bitstream.outputBitstream))) {
566 BOOST_LOG(error) <<
"NvEnc: NvEncUnlockBitstream() failed: " << last_nvenc_error_string;
569 encoder_state.frame_size_logger.collect_and_log(encoded_frame.data.size() / 1000.);
571 return encoded_frame;