Repository navigation
Expand file tree
/
Copy pathVideoEncoder.cpp
More file actions
442 lines (379 loc) · 14.3 KB
/
Copy pathVideoEncoder.cpp
File metadata and controls
442 lines (379 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#include "warpr_includes.h"
#include "VideoEncoder.h"
#include "Graphics/GraphicsDevice.h"
using namespace Axodox::Infrastructure;
using namespace DirectX;
using namespace Warpr::Graphics;
using namespace std;
using namespace winrt;
namespace
{
void check_nvenc(NVENCSTATUS status)
{
if (status != NV_ENC_SUCCESS)
{
throw runtime_error("NVEnc call failed.");
}
}
GUID get_codec_guid(Warpr::Encoder::VideoCodec codec)
{
switch (codec)
{
case Warpr::Encoder::VideoCodec::H264:
return NV_ENC_CODEC_H264_GUID;
case Warpr::Encoder::VideoCodec::H265:
return NV_ENC_CODEC_HEVC_GUID;
default:
throw logic_error("Unsupported video codec.");
}
}
}
namespace Warpr::Encoder
{
VideoEncoder::VideoEncoder(Axodox::Infrastructure::dependency_container* container)
{
_logger.log(log_severity::information, "Initializing NVEnc API...");
//Check API support
{
uint32_t version = 0;
uint32_t currentVersion = (NVENCAPI_MAJOR_VERSION << 4) | NVENCAPI_MINOR_VERSION;
check_nvenc(NvEncodeAPIGetMaxSupportedVersion(&version));
if (currentVersion > version)
{
_logger.log(log_severity::error, "Current Driver Version does not support this NvEncodeAPI version, please upgrade driver.");
throw runtime_error("Outdated driver encountered.");
}
}
//Initialize API
{
_nvenc = { NV_ENCODE_API_FUNCTION_LIST_VER };
check_nvenc(NvEncodeAPICreateInstance(&_nvenc));
if (!_nvenc.nvEncOpenEncodeSession)
{
_logger.log(log_severity::error, "EncodeAPI is not supported on this machine.");
throw runtime_error("EncodeAPI is not supported.");
}
}
_logger.log(log_severity::information, "NVEnc API ready.");
_device = container->resolve<GraphicsDevice>()->Device();
QuerySupportedCodecs();
}
void VideoEncoder::QuerySupportedCodecs()
{
_logger.log(log_severity::information, "Querying supported codecs...");
//Open a temporary session, codec support can only be queried from one
void* encoder = nullptr;
NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encodeSessionExParams = {
.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER,
.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX,
.device = _device.get(),
.apiVersion = NVENCAPI_VERSION
};
check_nvenc(_nvenc.nvEncOpenEncodeSessionEx(&encodeSessionExParams, &encoder));
try
{
uint32_t guidCount = 0;
check_nvenc(_nvenc.nvEncGetEncodeGUIDCount(encoder, &guidCount));
vector<GUID> guids(guidCount);
check_nvenc(_nvenc.nvEncGetEncodeGUIDs(encoder, guids.data(), guidCount, &guidCount));
guids.resize(guidCount);
for (auto codec : { VideoCodec::H264, VideoCodec::H265 })
{
if (ranges::find(guids, get_codec_guid(codec)) == guids.end()) continue;
_supportedCodecs.emplace(codec);
_logger.log(log_severity::information, "{} encoding is supported.", codec);
}
_nvenc.nvEncDestroyEncoder(encoder);
}
catch (...)
{
_nvenc.nvEncDestroyEncoder(encoder);
throw;
}
if (_supportedCodecs.empty())
{
_logger.log(log_severity::error, "No supported video codec found.");
throw runtime_error("No supported video codec found.");
}
}
const std::vector<VideoCodec>& VideoEncoder::CodecPreference() const
{
return _codecPreference;
}
void VideoEncoder::CodecPreference(const std::vector<VideoCodec>& value)
{
_codecPreference = value;
}
VideoCodec VideoEncoder::SelectCodec() const
{
for (auto codec : _codecPreference)
{
if (_supportedCodecs.contains(codec)) return codec;
}
//No overlap with the client, fall back to the best codec the GPU supports
return *_supportedCodecs.rbegin();
}
VideoEncoder::~VideoEncoder()
{
ReleaseResources();
}
uint32_t VideoEncoder::Bitrate() const
{
return _bitrate;
}
void VideoEncoder::Bitrate(uint32_t value)
{
_bitrate = value;
}
EncodedFrame VideoEncoder::EncodeFrame(const Capture::Frame& frame, bool forceIdrFrame)
{
Stopwatch watch{ "Frame encode" };
//Ensure session
auto encoderProperties = GetEncoderProperties(frame);
EnsureEncoder(encoderProperties);
//Register input
RegisterFrame(frame);
//Map input
void* mappedResource;
NV_ENC_BUFFER_FORMAT mappedFormat;
{
NV_ENC_MAP_INPUT_RESOURCE description{
.version = NV_ENC_MAP_INPUT_RESOURCE_VER,
.subResourceIndex = 0,
.inputResource = 0,
.registeredResource = _inputResource,
.mappedResource = nullptr,
.mappedBufferFmt = NV_ENC_BUFFER_FORMAT_UNDEFINED,
.reserved1 = {},
.reserved2 = {}
};
check_nvenc(_nvenc.nvEncMapInputResource(_encoder, &description));
mappedResource = description.mappedResource;
mappedFormat = description.mappedBufferFmt;
}
//Encode frame
{
NV_ENC_PIC_PARAMS description{
.version = NV_ENC_PIC_PARAMS_VER,
.inputWidth = _encoderProperties.Width,
.inputHeight = _encoderProperties.Height,
.inputPitch = 0,
.encodePicFlags = forceIdrFrame ? NV_ENC_PIC_FLAG_FORCEIDR : 0u,
.frameIdx = _frameIndex++,
.inputTimeStamp = 0,
.inputDuration = 0,
.inputBuffer = mappedResource,
.outputBitstream = _outputBuffer,
.completionEvent = nullptr, //for later
.bufferFmt = mappedFormat,
.pictureStruct = NV_ENC_PIC_STRUCT_FRAME,
.pictureType = NV_ENC_PIC_TYPE_P
};
check_nvenc(_nvenc.nvEncEncodePicture(_encoder, &description));
}
//Unmap input
{
check_nvenc(_nvenc.nvEncUnmapInputResource(_encoder, mappedResource));
}
//Get output
EncodedFrame result;
{
result.Slices.resize(2048);
NV_ENC_LOCK_BITSTREAM description{
.version = NV_ENC_LOCK_BITSTREAM_VER,
.doNotWait = false,
.outputBitstream = _outputBuffer,
.sliceOffsets = result.Slices.data()
};
check_nvenc(_nvenc.nvEncLockBitstream(_encoder, &description));
if (description.bitstreamBufferPtr)
{
result.Bytes.resize(description.bitstreamSizeInBytes);
memcpy(result.Bytes.data(), description.bitstreamBufferPtr, result.Bytes.size());
}
result.Slices.resize(description.numSlices);
result.Index = description.frameIdx;
result.Type = description.pictureType == NV_ENC_PIC_TYPE_IDR ? FrameType::Key : FrameType::Delta;
result.Width = _encoderProperties.Width;
result.Height = _encoderProperties.Height;
result.Codec = _encoderProperties.Codec;
check_nvenc(_nvenc.nvEncUnlockBitstream(_encoder, _outputBuffer));
}
//Return result
return result;
}
VideoEncoder::EncoderProperties VideoEncoder::GetEncoderProperties(const Capture::Frame& frame)
{
D3D11_TEXTURE2D_DESC description;
frame->GetDesc(&description);
return {
.Width = description.Width,
.Height = description.Height,
.Bitrate = _bitrate,
.Codec = SelectCodec()
};
}
void VideoEncoder::EnsureEncoder(const EncoderProperties& encoderProperties)
{
if (_encoderProperties == encoderProperties) return;
_encoderProperties = encoderProperties;
_logger.log(log_severity::information, "Encoder property change detected.");
//Release resources
ReleaseResources();
//Open encode session
{
_logger.log(log_severity::information, "Opening encode session...");
NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encodeSessionExParams = {
.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER,
.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX,
.device = _device.get(),
.apiVersion = NVENCAPI_VERSION
};
check_nvenc(_nvenc.nvEncOpenEncodeSessionEx(&encodeSessionExParams, &_encoder));
_logger.log(log_severity::information, "Encode session ready.");
}
//Initialize encoder
{
_logger.log(log_severity::information, "Initializing {} encoder...", encoderProperties.Codec);
auto codecGuid = get_codec_guid(encoderProperties.Codec);
NV_ENC_PRESET_CONFIG presetConfig = { NV_ENC_PRESET_CONFIG_VER, 0, { NV_ENC_CONFIG_VER } };
check_nvenc(_nvenc.nvEncGetEncodePresetConfigEx(_encoder, codecGuid, NV_ENC_PRESET_P1_GUID, NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY, &presetConfig));
NV_ENC_CONFIG encodeConfig = presetConfig.presetCfg;
encodeConfig.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
encodeConfig.rcParams.zeroReorderDelay = 1;
encodeConfig.rcParams.averageBitRate = encoderProperties.Bitrate;
//encodeConfig.rcParams.vbvBufferSize = 0;
//encodeConfig.rcParams.vbvInitialDelay = 0;
//encodeConfig.rcParams.maxBitRate = 2500;
//encodeConfig.gopLength = 120; //Key frame interval
encodeConfig.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
switch (encoderProperties.Codec)
{
case VideoCodec::H264:
encodeConfig.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
encodeConfig.encodeCodecConfig.h264Config.enableIntraRefresh = 1;
encodeConfig.encodeCodecConfig.h264Config.intraRefreshPeriod = 120;
encodeConfig.encodeCodecConfig.h264Config.intraRefreshCnt = 120;
encodeConfig.encodeCodecConfig.h264Config.chromaFormatIDC = 1;
encodeConfig.encodeCodecConfig.h264Config.idrPeriod = encodeConfig.gopLength;
encodeConfig.encodeCodecConfig.h264Config.sliceMode = 3;
encodeConfig.encodeCodecConfig.h264Config.sliceModeData = 2048;
encodeConfig.encodeCodecConfig.h264Config.repeatSPSPPS = 1;
encodeConfig.encodeCodecConfig.h264Config.h264VUIParameters.bitstreamRestrictionFlag = 1; //Signals no frame reordering, so decoders output frames without buffering
break;
case VideoCodec::H265:
encodeConfig.encodeCodecConfig.hevcConfig.enableIntraRefresh = 1;
encodeConfig.encodeCodecConfig.hevcConfig.intraRefreshPeriod = 120;
encodeConfig.encodeCodecConfig.hevcConfig.intraRefreshCnt = 120;
encodeConfig.encodeCodecConfig.hevcConfig.inputBitDepth = NV_ENC_BIT_DEPTH_8;
encodeConfig.encodeCodecConfig.hevcConfig.outputBitDepth = NV_ENC_BIT_DEPTH_8;
encodeConfig.encodeCodecConfig.hevcConfig.chromaFormatIDC = 1;
encodeConfig.encodeCodecConfig.hevcConfig.idrPeriod = encodeConfig.gopLength;
encodeConfig.encodeCodecConfig.hevcConfig.sliceMode = 3;
encodeConfig.encodeCodecConfig.hevcConfig.sliceModeData = 2048;
encodeConfig.encodeCodecConfig.hevcConfig.repeatSPSPPS = 1;
break;
}
encodeConfig.frameIntervalP = 1;
NV_ENC_INITIALIZE_PARAMS description{
.version = NV_ENC_INITIALIZE_PARAMS_VER,
.encodeGUID = codecGuid,
.presetGUID = NV_ENC_PRESET_P1_GUID,
.encodeWidth = _encoderProperties.Width,
.encodeHeight = _encoderProperties.Height,
.darWidth = _encoderProperties.Width,
.darHeight = _encoderProperties.Height,
.frameRateNum = 60,
.frameRateDen = 1,
.enableEncodeAsync = 0,
.enablePTD = 1,
.reportSliceOffsets = 1, //Slice offsets could be useful for frame splitting
.enableSubFrameWrite = 0,
.enableExternalMEHints = 0, //Maybe we could use motion vectors from rendering later
.enableMEOnlyMode = 0,
.enableWeightedPrediction = 0,
.splitEncodeMode = 0,
.enableOutputInVidmem = 0,
.enableReconFrameOutput = 0,
.enableOutputStats = 0,
.enableUniDirectionalB = 0,
.reservedBitFields = 0,
.privDataSize = 0,
.reserved = 0,
.privData = nullptr,
.encodeConfig = &encodeConfig,
.maxEncodeWidth = _encoderProperties.Width,
.maxEncodeHeight = _encoderProperties.Height,
.maxMEHintCountsPerBlock = { 0, 0 },
.tuningInfo = NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY,
.bufferFormat = NV_ENC_BUFFER_FORMAT_UNDEFINED,
.numStateBuffers = 0,
.outputStatsLevel = NV_ENC_OUTPUT_STATS_NONE,
.reserved1 = {},
.reserved2 = {}
};
check_nvenc(_nvenc.nvEncInitializeEncoder(_encoder, &description));
_logger.log(log_severity::information, "Encoder initialized.");
}
//Create output buffer
{
_logger.log(log_severity::information, "Allocating output buffer...");
NV_ENC_CREATE_BITSTREAM_BUFFER description = { NV_ENC_CREATE_BITSTREAM_BUFFER_VER };
check_nvenc(_nvenc.nvEncCreateBitstreamBuffer(_encoder, &description));
_outputBuffer = description.bitstreamBuffer;
_logger.log(log_severity::information, "Output buffer allocated.");
}
//Reset data
{
_frameIndex = 0u;
}
}
void VideoEncoder::RegisterFrame(const Capture::Frame& frame)
{
if (frame.get() == _frameResource) return;
_frameResource = frame.get();
if (_inputResource) check_nvenc(_nvenc.nvEncUnregisterResource(_encoder, _inputResource));
_logger.log(log_severity::information, "Registering input resource...");
NV_ENC_REGISTER_RESOURCE description{
.version = NV_ENC_REGISTER_RESOURCE_VER,
.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX,
.width = _encoderProperties.Width,
.height = _encoderProperties.Height,
.pitch = 0,
.subResourceIndex = 0,
.resourceToRegister = frame.get(),
.registeredResource = nullptr,
.bufferFormat = NV_ENC_BUFFER_FORMAT_NV12,
.bufferUsage = NV_ENC_INPUT_IMAGE,
.pInputFencePoint = nullptr,
.chromaOffset = { 0, 0 },
.reserved1 = {},
.reserved2 = {}
};
check_nvenc(_nvenc.nvEncRegisterResource(_encoder, &description));
_inputResource = description.registeredResource;
_logger.log(log_severity::information, "Input resource registered.");
}
void VideoEncoder::ReleaseResources()
{
_logger.log(log_severity::information, "Releasing resources...");
if (_inputResource)
{
_nvenc.nvEncUnregisterResource(_encoder, _inputResource);
_inputResource = nullptr;
}
//The frame must be registered again with the new encoder, even if the texture is the same
_frameResource = nullptr;
if (_outputBuffer)
{
_nvenc.nvEncDestroyBitstreamBuffer(_encoder, _outputBuffer);
_outputBuffer = nullptr;
}
if (_encoder)
{
_nvenc.nvEncDestroyEncoder(_encoder);
_encoder = nullptr;
}
_logger.log(log_severity::information, "Resources released.");
}
}