Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
nvenc_base.cpp
Go to the documentation of this file.
1
5// this include
6#include "nvenc_base.h"
7
8// standard includes
9#include <format>
10
11// local includes
12#include "src/config.h"
13#include "src/logging.h"
14#include "src/utility.h"
15
16#define MAKE_NVENC_VER(major, minor) ((major) | ((minor) << 24))
17
18// Make sure we check backwards compatibility when bumping the Video Codec SDK version
19// Things to look out for:
20// - NV_ENC_*_VER definitions where the value inside NVENCAPI_STRUCT_VERSION() was increased
21// - Incompatible struct changes in nvEncodeAPI.h (fields removed, semantics changed, etc.)
22// - Test both old and new drivers with all supported codecs
23#if NVENCAPI_VERSION != MAKE_NVENC_VER(12U, 0U)
24 #error Check and update NVENC code for backwards compatibility!
25#endif
26
27namespace {
28
29 GUID quality_preset_guid_from_number(unsigned number) {
30 if (number > 7) {
31 number = 7;
32 }
33
34 switch (number) {
35 case 1:
36 default:
37 return NV_ENC_PRESET_P1_GUID;
38
39 case 2:
40 return NV_ENC_PRESET_P2_GUID;
41
42 case 3:
43 return NV_ENC_PRESET_P3_GUID;
44
45 case 4:
46 return NV_ENC_PRESET_P4_GUID;
47
48 case 5:
49 return NV_ENC_PRESET_P5_GUID;
50
51 case 6:
52 return NV_ENC_PRESET_P6_GUID;
53
54 case 7:
55 return NV_ENC_PRESET_P7_GUID;
56 }
57 };
58
59 bool equal_guids(const GUID &guid1, const GUID &guid2) {
60 return std::memcmp(&guid1, &guid2, sizeof(GUID)) == 0;
61 }
62
63 auto quality_preset_string_from_guid(const GUID &guid) {
64 if (equal_guids(guid, NV_ENC_PRESET_P1_GUID)) {
65 return "P1";
66 }
67 if (equal_guids(guid, NV_ENC_PRESET_P2_GUID)) {
68 return "P2";
69 }
70 if (equal_guids(guid, NV_ENC_PRESET_P3_GUID)) {
71 return "P3";
72 }
73 if (equal_guids(guid, NV_ENC_PRESET_P4_GUID)) {
74 return "P4";
75 }
76 if (equal_guids(guid, NV_ENC_PRESET_P5_GUID)) {
77 return "P5";
78 }
79 if (equal_guids(guid, NV_ENC_PRESET_P6_GUID)) {
80 return "P6";
81 }
82 if (equal_guids(guid, NV_ENC_PRESET_P7_GUID)) {
83 return "P7";
84 }
85 return "Unknown";
86 }
87
88} // namespace
89
90namespace nvenc {
91
92 nvenc_base::nvenc_base(NV_ENC_DEVICE_TYPE device_type):
93 device_type(device_type) {
94 }
95
96 nvenc_base::~nvenc_base() {
97 // Use destroy_encoder() instead
98 }
99
100 bool nvenc_base::create_encoder(const nvenc_config &config, const video::config_t &client_config, const nvenc_colorspace_t &colorspace, NV_ENC_BUFFER_FORMAT buffer_format) {
101 // Pick the minimum NvEncode API version required to support the specified codec
102 // to maximize driver compatibility. AV1 was introduced in SDK v12.0.
103 minimum_api_version = (client_config.videoFormat <= 1) ? MAKE_NVENC_VER(11U, 0U) : MAKE_NVENC_VER(12U, 0U);
104
105 if (!nvenc && !init_library()) {
106 return false;
107 }
108
109 if (encoder) {
111 }
112 auto fail_guard = util::fail_guard([this] {
114 });
115
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;
120
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;
127 return false;
128 }
129
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;
133 return false;
134 };
135
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;
139 return false;
140 }
141
142 NV_ENC_INITIALIZE_PARAMS init_params = {min_struct_version(NV_ENC_INITIALIZE_PARAMS_VER)};
143
144 switch (client_config.videoFormat) {
145 case 0:
146 // H.264
147 init_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
148 break;
149
150 case 1:
151 // HEVC
152 init_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
153 break;
154
155 case 2:
156 // AV1
157 init_params.encodeGUID = NV_ENC_CODEC_AV1_GUID;
158 break;
159
160 default:
161 BOOST_LOG(error) << "NvEnc: unknown video format " << client_config.videoFormat;
162 return false;
163 }
164
165 {
166 auto search_predicate = [&](const GUID &guid) {
167 return equal_guids(init_params.encodeGUID, guid);
168 };
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";
171 return false;
172 }
173 }
174
175 auto get_encoder_cap = [&](NV_ENC_CAPS cap) {
176 NV_ENC_CAPS_PARAM param = {min_struct_version(NV_ENC_CAPS_PARAM_VER), cap};
177 int value = 0;
178 nvenc->nvEncGetEncodeCaps(encoder, init_params.encodeGUID, &param, &value);
179 return value;
180 };
181
182 auto buffer_is_10bit = [&]() {
183 return buffer_format == NV_ENC_BUFFER_FORMAT_YUV420_10BIT || buffer_format == NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
184 };
185
186 auto buffer_is_yuv444 = [&]() {
187 return buffer_format == NV_ENC_BUFFER_FORMAT_AYUV || buffer_format == NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
188 };
189
190 {
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;
195 return false;
196 }
197 }
198
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";
201 return false;
202 }
203
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";
206 return false;
207 }
208
209 if (async_event_handle && !get_encoder_cap(NV_ENC_CAPS_ASYNC_ENCODE_SUPPORT)) {
210 BOOST_LOG(warning) << "NvEnc: gpu doesn't support async encode";
211 async_event_handle = nullptr;
212 }
213
214 encoder_params.rfi = get_encoder_cap(NV_ENC_CAPS_SUPPORT_REF_PIC_INVALIDATION);
215
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;
219 init_params.enableEncodeAsync = async_event_handle ? 1 : 0;
220 init_params.enableWeightedPrediction = config.weighted_prediction && get_encoder_cap(NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
221
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;
228
229 NV_ENC_PRESET_CONFIG preset_config = {min_struct_version(NV_ENC_PRESET_CONFIG_VER), {min_struct_version(NV_ENC_CONFIG_VER, 7, 8)}};
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;
232 return false;
233 }
234
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;
243 enc_config.rcParams.multiPass = config.two_pass == nvenc_two_pass::quarter_resolution ? NV_ENC_TWO_PASS_QUARTER_RESOLUTION :
244 config.two_pass == nvenc_two_pass::full_resolution ? NV_ENC_TWO_PASS_FULL_RESOLUTION :
245 NV_ENC_MULTI_PASS_DISABLED;
246
247 enc_config.rcParams.enableAQ = config.adaptive_quantization;
248 enc_config.rcParams.averageBitRate = client_config.bitrate * 1000;
249
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;
254 }
255 }
256
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;
264 }
265 format_config.enableFillerDataInsertion = config.insert_filler_data;
266 };
267
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;
271 } else {
272 ref_frames_option = ref_frames_default;
273 }
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;
277 }
278 encoder_params.ref_frames_in_dpb = ref_frames_option;
279 // This limits ref frames any frame can use to 1, but allows larger buffer size for fallback if some frames are invalidated through rfi
280 L0_option = NV_ENC_NUM_REF_FRAMES_1;
281 };
282
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;
288 }
289 };
290
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;
302 };
303
304 switch (client_config.videoFormat) {
305 case 0:
306 {
307 // H.264
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;
313 } else {
314 format_config.entropyCodingMode = NV_ENC_H264_ENTROPY_CODING_MODE_CABAC;
315 }
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);
319 break;
320 }
321
322 case 1:
323 {
324 // HEVC
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;
329 }
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;
340 } else {
341 BOOST_LOG(warning) << "NvEnc: Single Slice Intra Refresh not supported";
342 }
343 } else {
344 BOOST_LOG(error) << "NvEnc: Client asked for intra-refresh but the encoder does not support intra-refresh";
345 }
346 }
347 break;
348 }
349
350 case 2:
351 {
352 // AV1
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;
358 }
359 format_config.enableBitstreamPadding = config.insert_filler_data;
360 if (buffer_is_10bit()) {
361 format_config.inputPixelBitDepthMinus8 = 2;
362 format_config.pixelBitDepthMinus8 = 2;
363 }
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);
371
372 if (client_config.slicesPerFrame > 1) {
373 // NVENC only supports slice counts that are powers of two, so we'll pick powers of two
374 // with bias to rows due to hopefully more similar macroblocks with a row vs a column.
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));
377 }
378 break;
379 }
380 }
381
382 init_params.encodeConfig = &enc_config;
383
384 if (nvenc_failed(nvenc->nvEncInitializeEncoder(encoder, &init_params))) {
385 BOOST_LOG(error) << "NvEnc: NvEncInitializeEncoder() failed: " << last_nvenc_error_string;
386 return false;
387 }
388
389 if (async_event_handle) {
390 NV_ENC_EVENT_PARAMS event_params = {min_struct_version(NV_ENC_EVENT_PARAMS_VER)};
391 event_params.completionEvent = async_event_handle;
392 if (nvenc_failed(nvenc->nvEncRegisterAsyncEvent(encoder, &event_params))) {
393 BOOST_LOG(error) << "NvEnc: NvEncRegisterAsyncEvent() failed: " << last_nvenc_error_string;
394 return false;
395 }
396 }
397
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;
401 return false;
402 }
403 output_bitstream = create_bitstream_buffer.bitstreamBuffer;
404
406 return false;
407 }
408
409 {
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";
412 }
413
414 {
415 auto video_format_string = client_config.videoFormat == 0 ? "H.264 " :
416 client_config.videoFormat == 1 ? "HEVC " :
417 client_config.videoFormat == 2 ? "AV1 " :
418 " ";
419 std::string extra;
420 if (init_params.enableEncodeAsync) {
421 extra += " async";
422 }
423 if (buffer_is_yuv444()) {
424 extra += " yuv444";
425 }
426 if (buffer_is_10bit()) {
427 extra += " 10-bit";
428 }
429 if (enc_config.rcParams.multiPass != NV_ENC_MULTI_PASS_DISABLED) {
430 extra += " two-pass";
431 }
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);
434 }
435 if (encoder_params.rfi) {
436 extra += " rfi";
437 }
438 if (init_params.enableWeightedPrediction) {
439 extra += " weighted-prediction";
440 }
441 if (enc_config.rcParams.enableAQ) {
442 extra += " spatial-aq";
443 }
444 if (enc_config.rcParams.enableMinQP) {
445 extra += std::format(" qpmin={}", enc_config.rcParams.minQP.qpInterP);
446 }
447 if (config.insert_filler_data) {
448 extra += " filler-data";
449 }
450
451 BOOST_LOG(info) << "NvEnc: created encoder " << video_format_string << quality_preset_string_from_guid(init_params.presetGUID) << extra;
452 }
453
454 encoder_state = {};
455 fail_guard.disable();
456 return true;
457 }
458
460 if (output_bitstream) {
461 if (nvenc_failed(nvenc->nvEncDestroyBitstreamBuffer(encoder, output_bitstream))) {
462 BOOST_LOG(error) << "NvEnc: NvEncDestroyBitstreamBuffer() failed: " << last_nvenc_error_string;
463 }
464 output_bitstream = nullptr;
465 }
466 if (encoder && async_event_handle) {
467 NV_ENC_EVENT_PARAMS event_params = {min_struct_version(NV_ENC_EVENT_PARAMS_VER)};
468 event_params.completionEvent = async_event_handle;
469 if (nvenc_failed(nvenc->nvEncUnregisterAsyncEvent(encoder, &event_params))) {
470 BOOST_LOG(error) << "NvEnc: NvEncUnregisterAsyncEvent() failed: " << last_nvenc_error_string;
471 }
472 }
474 if (nvenc_failed(nvenc->nvEncUnregisterResource(encoder, registered_input_buffer))) {
475 BOOST_LOG(error) << "NvEnc: NvEncUnregisterResource() failed: " << last_nvenc_error_string;
476 }
477 registered_input_buffer = nullptr;
478 }
479 if (encoder) {
480 if (nvenc_failed(nvenc->nvEncDestroyEncoder(encoder))) {
481 BOOST_LOG(error) << "NvEnc: NvEncDestroyEncoder() failed: " << last_nvenc_error_string;
482 }
483 encoder = nullptr;
484 }
485
486 encoder_state = {};
487 encoder_params = {};
488 }
489
490 nvenc_encoded_frame nvenc_base::encode_frame(uint64_t frame_index, bool force_idr) {
491 if (!encoder) {
492 return {};
493 }
494
496 assert(output_bitstream);
497
499 BOOST_LOG(error) << "NvEnc: failed to synchronize input buffer";
500 return {};
501 }
502
503 NV_ENC_MAP_INPUT_RESOURCE mapped_input_buffer = {min_struct_version(NV_ENC_MAP_INPUT_RESOURCE_VER)};
504 mapped_input_buffer.registeredResource = registered_input_buffer;
505
506 if (nvenc_failed(nvenc->nvEncMapInputResource(encoder, &mapped_input_buffer))) {
507 BOOST_LOG(error) << "NvEnc: NvEncMapInputResource() failed: " << last_nvenc_error_string;
508 return {};
509 }
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;
513 }
514 });
515
516 NV_ENC_PIC_PARAMS pic_params = {min_struct_version(NV_ENC_PIC_PARAMS_VER, 4, 6)};
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;
525 pic_params.completionEvent = async_event_handle;
526
527 if (nvenc_failed(nvenc->nvEncEncodePicture(encoder, &pic_params))) {
528 BOOST_LOG(error) << "NvEnc: NvEncEncodePicture() failed: " << last_nvenc_error_string;
529 return {};
530 }
531
532 NV_ENC_LOCK_BITSTREAM lock_bitstream = {min_struct_version(NV_ENC_LOCK_BITSTREAM_VER, 1, 2)};
533 lock_bitstream.outputBitstream = output_bitstream;
534 lock_bitstream.doNotWait = async_event_handle ? 1 : 0;
535
537 BOOST_LOG(error) << "NvEnc: frame " << frame_index << " encode wait timeout";
538 return {};
539 }
540
541 if (nvenc_failed(nvenc->nvEncLockBitstream(encoder, &lock_bitstream))) {
542 BOOST_LOG(error) << "NvEnc: NvEncLockBitstream() failed: " << last_nvenc_error_string;
543 return {};
544 }
545
546 auto data_pointer = (uint8_t *) lock_bitstream.bitstreamBufferPtr;
547 nvenc_encoded_frame encoded_frame {
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,
552 };
553
554 if (encoder_state.rfi_needs_confirmation) {
555 // Invalidation request has been fulfilled, and video network packet will be marked as such
556 encoder_state.rfi_needs_confirmation = false;
557 }
558
559 encoder_state.last_encoded_frame_index = frame_index;
560
561 if (encoded_frame.idr) {
562 BOOST_LOG(debug) << "NvEnc: idr frame " << encoded_frame.frame_index;
563 }
564
565 if (nvenc_failed(nvenc->nvEncUnlockBitstream(encoder, lock_bitstream.outputBitstream))) {
566 BOOST_LOG(error) << "NvEnc: NvEncUnlockBitstream() failed: " << last_nvenc_error_string;
567 }
568
569 encoder_state.frame_size_logger.collect_and_log(encoded_frame.data.size() / 1000.);
570
571 return encoded_frame;
572 }
573
574 bool nvenc_base::invalidate_ref_frames(uint64_t first_frame, uint64_t last_frame) {
575 if (!encoder || !encoder_params.rfi) {
576 return false;
577 }
578
579 if (first_frame >= encoder_state.last_rfi_range.first &&
580 last_frame <= encoder_state.last_rfi_range.second) {
581 BOOST_LOG(debug) << "NvEnc: rfi request " << first_frame << "-" << last_frame << " already done";
582 return true;
583 }
584
585 encoder_state.rfi_needs_confirmation = true;
586
587 if (last_frame < first_frame) {
588 BOOST_LOG(error) << "NvEnc: invaid rfi request " << first_frame << "-" << last_frame << ", generating IDR";
589 return false;
590 }
591
592 BOOST_LOG(debug) << "NvEnc: rfi request " << first_frame << "-" << last_frame << " expanding to last encoded frame " << encoder_state.last_encoded_frame_index;
593 last_frame = encoder_state.last_encoded_frame_index;
594
595 encoder_state.last_rfi_range = {first_frame, last_frame};
596
597 if (last_frame - first_frame + 1 >= encoder_params.ref_frames_in_dpb) {
598 BOOST_LOG(debug) << "NvEnc: rfi request too large, generating IDR";
599 return false;
600 }
601
602 for (auto i = first_frame; i <= last_frame; i++) {
603 if (nvenc_failed(nvenc->nvEncInvalidateRefFrames(encoder, i))) {
604 BOOST_LOG(error) << "NvEnc: NvEncInvalidateRefFrames() " << i << " failed: " << last_nvenc_error_string;
605 return false;
606 }
607 }
608
609 return true;
610 }
611
612 bool nvenc_base::nvenc_failed(NVENCSTATUS status) {
613 auto status_string = [](NVENCSTATUS status) -> std::string {
614 switch (status) {
615#define nvenc_status_case(x) \
616 case x: \
617 return #x;
618 nvenc_status_case(NV_ENC_SUCCESS);
619 nvenc_status_case(NV_ENC_ERR_NO_ENCODE_DEVICE);
620 nvenc_status_case(NV_ENC_ERR_UNSUPPORTED_DEVICE);
621 nvenc_status_case(NV_ENC_ERR_INVALID_ENCODERDEVICE);
622 nvenc_status_case(NV_ENC_ERR_INVALID_DEVICE);
623 nvenc_status_case(NV_ENC_ERR_DEVICE_NOT_EXIST);
624 nvenc_status_case(NV_ENC_ERR_INVALID_PTR);
625 nvenc_status_case(NV_ENC_ERR_INVALID_EVENT);
626 nvenc_status_case(NV_ENC_ERR_INVALID_PARAM);
627 nvenc_status_case(NV_ENC_ERR_INVALID_CALL);
628 nvenc_status_case(NV_ENC_ERR_OUT_OF_MEMORY);
629 nvenc_status_case(NV_ENC_ERR_ENCODER_NOT_INITIALIZED);
630 nvenc_status_case(NV_ENC_ERR_UNSUPPORTED_PARAM);
631 nvenc_status_case(NV_ENC_ERR_LOCK_BUSY);
632 nvenc_status_case(NV_ENC_ERR_NOT_ENOUGH_BUFFER);
633 nvenc_status_case(NV_ENC_ERR_INVALID_VERSION);
634 nvenc_status_case(NV_ENC_ERR_MAP_FAILED);
635 nvenc_status_case(NV_ENC_ERR_NEED_MORE_INPUT);
636 nvenc_status_case(NV_ENC_ERR_ENCODER_BUSY);
637 nvenc_status_case(NV_ENC_ERR_EVENT_NOT_REGISTERD);
638 nvenc_status_case(NV_ENC_ERR_GENERIC);
639 nvenc_status_case(NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY);
640 nvenc_status_case(NV_ENC_ERR_UNIMPLEMENTED);
641 nvenc_status_case(NV_ENC_ERR_RESOURCE_REGISTER_FAILED);
642 nvenc_status_case(NV_ENC_ERR_RESOURCE_NOT_REGISTERED);
643 nvenc_status_case(NV_ENC_ERR_RESOURCE_NOT_MAPPED);
644 // Newer versions of sdk may add more constants, look for them at the end of NVENCSTATUS enum
645#undef nvenc_status_case
646 default:
647 return std::to_string(status);
648 }
649 };
650
651 last_nvenc_error_string.clear();
652 if (status != NV_ENC_SUCCESS) {
653 /* This API function gives broken strings more often than not
654 if (nvenc && encoder) {
655 last_nvenc_error_string = nvenc->nvEncGetLastErrorString(encoder);
656 if (!last_nvenc_error_string.empty()) last_nvenc_error_string += " ";
657 }
658 */
659 last_nvenc_error_string += status_string(status);
660 return true;
661 }
662
663 return false;
664 }
665
666 uint32_t nvenc_base::min_struct_version(uint32_t version, uint32_t v11_struct_version, uint32_t v12_struct_version) {
667 assert(minimum_api_version);
668
669 // Mask off and replace the original NVENCAPI_VERSION
670 version &= ~NVENCAPI_VERSION;
671 version |= minimum_api_version;
672
673 // If there's a struct version override, apply that too
674 if (v11_struct_version || v12_struct_version) {
675 version &= ~(0xFFu << 16);
676 version |= (((minimum_api_version & 0xFF) >= 12) ? v12_struct_version : v11_struct_version) << 16;
677 }
678
679 return version;
680 }
681} // namespace nvenc
bool invalidate_ref_frames(uint64_t first_frame, uint64_t last_frame)
Perform reference frame invalidation (RFI) procedure.
nvenc_encoded_frame encode_frame(uint64_t frame_index, bool force_idr)
Encode the next frame using platform-specific input surface.
NV_ENC_REGISTERED_PTR registered_input_buffer
Definition nvenc_base.h:138
bool create_encoder(const nvenc_config &config, const video::config_t &client_config, const nvenc_colorspace_t &colorspace, NV_ENC_BUFFER_FORMAT buffer_format)
Create the encoder.
virtual bool create_and_register_input_buffer()=0
Required. Used for creating outside-facing input surface, registering this surface with nvenc->nvEncR...
uint32_t min_struct_version(uint32_t version, uint32_t v11_struct_version=0, uint32_t v12_struct_version=0)
This function returns the corresponding struct version for the minimum API required by the codec.
virtual bool wait_for_async_event(uint32_t timeout_ms)
Optional. Override if you want to create encoder in async mode. In this case must also set async_even...
Definition nvenc_base.h:103
void * async_event_handle
Definition nvenc_base.h:140
void destroy_encoder()
Destroy the encoder. Derived classes classes call it in the destructor.
virtual bool init_library()=0
Required. Used for loading NvEnc library and setting nvenc variable with NvEncodeAPICreateInstance()....
nvenc_base(NV_ENC_DEVICE_TYPE device_type)
virtual bool synchronize_input_buffer()
Optional. Override if you must perform additional operations on the registered input surface in the b...
Definition nvenc_base.h:93
Declarations for the configuration of Sunshine.
Declarations for logging related functions.
Standalone NVENC encoder.
@ full_resolution
Better overall statistics, slower and uses more extra vram.
@ quarter_resolution
Larger motion vectors being caught, faster and uses less extra vram.
Declarations for abstract platform-agnostic base of standalone NVENC encoder.
YUV colorspace and color range.
NVENC encoder configuration.
Declarations for utility functions.