BlueGit

ict rusty-teams

Files

rusty-teams / vendor / webrtc-sys / src / nvidia / h264_encoder_impl.cpp

h264_encoder_impl.cpp

h264_encoder_impl.cpp 15.8 KiB Download Raw
1#include "h264_encoder_impl.h"
2
3#include <algorithm>
4#include <cmath>
5#include <limits>
6#include <string>
7
8#include "i420_buffer_cuda.h"
9#include "absl/strings/match.h"
10#include "absl/types/optional.h"
11#include "api/video/video_codec_constants.h"
12#include "api/video_codecs/scalability_mode.h"
13#include <common_video/h264/h264_common.h>
14#include "common_video/libyuv/include/webrtc_libyuv.h"
15#include "modules/video_coding/include/video_codec_interface.h"
16#include "modules/video_coding/include/video_error_codes.h"
17#include "modules/video_coding/svc/create_scalability_structure.h"
18#include "modules/video_coding/utility/simulcast_rate_allocator.h"
19#include "modules/video_coding/utility/simulcast_utility.h"
20#include "rtc_base/checks.h"
21#include "rtc_base/logging.h"
22#include "rtc_base/time_utils.h"
23#include "system_wrappers/include/metrics.h"
24#include "third_party/libyuv/include/libyuv/convert.h"
25#include "third_party/libyuv/include/libyuv/scale.h"
26
27namespace webrtc {
28
29// Used by histograms. Values of entries should not be changed.
30enum H264EncoderImplEvent {
31 kH264EncoderEventInit = 0,
32 kH264EncoderEventError = 1,
33 kH264EncoderEventMax = 16,
34};
35
36
37NV_ENC_LEVEL H264LevelToNvEncLevel(webrtc::H264Level level) {
38 switch (level) {
39 case H264Level::kLevel1_b:
40 return NV_ENC_LEVEL_H264_1b;
41 case H264Level::kLevel1:
42 return NV_ENC_LEVEL_H264_1;
43 case H264Level::kLevel1_1:
44 return NV_ENC_LEVEL_H264_11;
45 case H264Level::kLevel1_2:
46 return NV_ENC_LEVEL_H264_12;
47 case H264Level::kLevel1_3:
48 return NV_ENC_LEVEL_H264_13;
49 case H264Level::kLevel2:
50 return NV_ENC_LEVEL_H264_2;
51 case H264Level::kLevel2_1:
52 return NV_ENC_LEVEL_H264_21;
53 case H264Level::kLevel2_2:
54 return NV_ENC_LEVEL_H264_22;
55 case H264Level::kLevel3:
56 return NV_ENC_LEVEL_H264_3;
57 case H264Level::kLevel3_1:
58 return NV_ENC_LEVEL_H264_31;
59 case H264Level::kLevel3_2:
60 return NV_ENC_LEVEL_H264_32;
61 case H264Level::kLevel4:
62 return NV_ENC_LEVEL_H264_4;
63 case H264Level::kLevel4_1:
64 return NV_ENC_LEVEL_H264_41;
65 case H264Level::kLevel4_2:
66 return NV_ENC_LEVEL_H264_42;
67 case H264Level::kLevel5:
68 return NV_ENC_LEVEL_H264_5;
69 case H264Level::kLevel5_1:
70 return NV_ENC_LEVEL_H264_51;
71 case H264Level::kLevel5_2:
72 return NV_ENC_LEVEL_H264_52;
73 }
74 return NV_ENC_LEVEL_AUTOSELECT; // Default value.
75}
76
77
78NvidiaH264EncoderImpl::NvidiaH264EncoderImpl(
79 const webrtc::Environment& env,
80 CUcontext context,
81 CUmemorytype memory_type,
82 NV_ENC_BUFFER_FORMAT nv_format,
83 const SdpVideoFormat& format)
84 : env_(env),
85 encoder_(nullptr),
86 cu_context_(context),
87 cu_memory_type_(memory_type),
88 cu_scaled_array_(nullptr),
89 nv_format_(nv_format),
90 packetization_mode_(
91 H264EncoderSettings::Parse(format).packetization_mode),
92 format_(format) {
93 std::string hexString = format_.parameters.at("profile-level-id");
94 std::optional<webrtc::H264ProfileLevelId> profile_level_id =
95 webrtc::ParseH264ProfileLevelId(hexString.c_str());
96 if (profile_level_id.has_value()) {
97 profile_ = profile_level_id->profile;
98 level_ = profile_level_id->level;
99 }
100
101 nv_enc_level_ = NV_ENC_LEVEL_AUTOSELECT;
102 if (level_ != H264Level::kLevel1_b) {
103 // Convert H264Level to NV_ENC_LEVEL.
104 nv_enc_level_ = webrtc::H264LevelToNvEncLevel(level_);
105 }
106
107 RTC_CHECK_NE(cu_memory_type_, CU_MEMORYTYPE_HOST);
108}
109
110NvidiaH264EncoderImpl::~NvidiaH264EncoderImpl() {
111 Release();
112}
113
114void NvidiaH264EncoderImpl::ReportInit() {
115 if (has_reported_init_)
116 return;
117 RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H264EncoderImpl.Event",
118 kH264EncoderEventInit, kH264EncoderEventMax);
119 has_reported_init_ = true;
120}
121
122void NvidiaH264EncoderImpl::ReportError() {
123 if (has_reported_error_)
124 return;
125 RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H264EncoderImpl.Event",
126 kH264EncoderEventError, kH264EncoderEventMax);
127 has_reported_error_ = true;
128}
129
130int32_t NvidiaH264EncoderImpl::InitEncode(
131 const VideoCodec* inst,
132 const VideoEncoder::Settings& settings) {
133 if (!inst || inst->codecType != kVideoCodecH264) {
134 ReportError();
135 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
136 }
137 if (inst->maxFramerate == 0) {
138 ReportError();
139 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
140 }
141 if (inst->width < 1 || inst->height < 1) {
142 ReportError();
143 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
144 }
145
146 int32_t release_ret = Release();
147 if (release_ret != WEBRTC_VIDEO_CODEC_OK) {
148 ReportError();
149 return release_ret;
150 }
151
152 codec_ = *inst;
153
154 // Code expects simulcastStream resolutions to be correct, make sure they are
155 // filled even when there are no simulcast layers.
156 if (codec_.numberOfSimulcastStreams == 0) {
157 codec_.simulcastStream[0].width = codec_.width;
158 codec_.simulcastStream[0].height = codec_.height;
159 }
160
161 // Initialize encoded image. Default buffer size: size of unencoded data.
162 const size_t new_capacity =
163 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
164 encoded_image_.SetEncodedData(EncodedImageBuffer::Create(new_capacity));
165 encoded_image_._encodedWidth = codec_.width;
166 encoded_image_._encodedHeight = codec_.height;
167 encoded_image_.set_size(0);
168
169 configuration_.sending = false;
170 configuration_.frame_dropping_on = codec_.GetFrameDropEnabled();
171 configuration_.key_frame_interval = codec_.H264()->keyFrameInterval;
172
173 configuration_.width = codec_.width;
174 configuration_.height = codec_.height;
175
176 configuration_.max_frame_rate = codec_.maxFramerate;
177 configuration_.target_bps = codec_.startBitrate * 1000;
178 configuration_.max_bps = codec_.maxBitrate * 1000;
179
180 const CUresult result = cuCtxSetCurrent(cu_context_);
181 if (result != CUDA_SUCCESS) {
182 return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
183 }
184
185 // Some NVIDIA GPUs have a limited Encode Session count.
186 // We can't get the Session count, so catching NvEncThrow to avoid the crash.
187 // refer:
188 // https://developer.nvidia.com/video-encode-and-decode-gpu-support-matrix-new
189 try {
190 if (cu_memory_type_ == CU_MEMORYTYPE_DEVICE) {
191 encoder_ = std::make_unique<NvEncoderCuda>(cu_context_, codec_.width,
192 codec_.height, nv_format_, 0);
193 } else {
194 RTC_DCHECK_NOTREACHED();
195 }
196 } catch (const NVENCException& e) {
197 // todo: If Encoder initialization fails, need to notify for Managed side.
198 RTC_LOG(LS_ERROR) << "Failed Initialize NvEncoder " << e.what();
199 return WEBRTC_VIDEO_CODEC_ERROR;
200 }
201
202 nv_initialize_params_.version = NV_ENC_INITIALIZE_PARAMS_VER;
203 nv_encode_config_.version = NV_ENC_CONFIG_VER;
204 nv_initialize_params_.encodeConfig = &nv_encode_config_;
205
206 GUID encodeGuid = NV_ENC_CODEC_H264_GUID;
207 GUID presetGuid = NV_ENC_PRESET_P4_GUID;
208
209 encoder_->CreateDefaultEncoderParams(&nv_initialize_params_, encodeGuid,
210 presetGuid,
211 NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY);
212
213 nv_initialize_params_.frameRateNum = std::max<uint32_t>(
214 1, static_cast<uint32_t>(std::round(configuration_.max_frame_rate)));
215 nv_initialize_params_.frameRateDen = 1;
216 nv_initialize_params_.bufferFormat = nv_format_;
217
218 nv_encode_config_.profileGUID = nv_profile_guid_;
219 nv_encode_config_.gopLength = NVENC_INFINITE_GOPLENGTH;
220 nv_encode_config_.frameIntervalP = 1;
221 nv_encode_config_.encodeCodecConfig.h264Config.level = nv_enc_level_;
222 nv_encode_config_.encodeCodecConfig.h264Config.idrPeriod =
223 NVENC_INFINITE_GOPLENGTH;
224 nv_encode_config_.rcParams.version = NV_ENC_RC_PARAMS_VER;
225 nv_encode_config_.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
226 nv_encode_config_.rcParams.averageBitRate = configuration_.target_bps;
227 nv_encode_config_.rcParams.vbvBufferSize =
228 (nv_encode_config_.rcParams.averageBitRate *
229 nv_initialize_params_.frameRateDen /
230 nv_initialize_params_.frameRateNum) *
231 5;
232 nv_encode_config_.rcParams.vbvInitialDelay =
233 nv_encode_config_.rcParams.vbvBufferSize;
234
235 try {
236 encoder_->CreateEncoder(&nv_initialize_params_);
237 } catch (const NVENCException& e) {
238 RTC_LOG(LS_ERROR) << "Failed Initialize NvEncoder " << e.what();
239 return WEBRTC_VIDEO_CODEC_ERROR;
240 }
241
242 RTC_LOG(LS_INFO) << "NVIDIA H264 NVENC initialized: "
243 << codec_.width << "x" << codec_.height
244 << " @ " << codec_.maxFramerate << "fps, target_bps="
245 << configuration_.target_bps;
246
247 SimulcastRateAllocator init_allocator(env_, codec_);
248 VideoBitrateAllocation allocation =
249 init_allocator.Allocate(VideoBitrateAllocationParameters(
250 DataRate::KilobitsPerSec(codec_.startBitrate), codec_.maxFramerate));
251 SetRates(RateControlParameters(allocation, codec_.maxFramerate));
252 return WEBRTC_VIDEO_CODEC_OK;
253}
254
255int32_t NvidiaH264EncoderImpl::RegisterEncodeCompleteCallback(
256 EncodedImageCallback* callback) {
257 encoded_image_callback_ = callback;
258 return WEBRTC_VIDEO_CODEC_OK;
259}
260
261int32_t NvidiaH264EncoderImpl::Release() {
262 if (encoder_) {
263 encoder_->DestroyEncoder();
264 encoder_ = nullptr;
265 }
266 if (cu_scaled_array_) {
267 cuArrayDestroy(cu_scaled_array_);
268 cu_scaled_array_ = nullptr;
269 }
270 return WEBRTC_VIDEO_CODEC_OK;
271}
272
273int32_t NvidiaH264EncoderImpl::Encode(
274 const VideoFrame& input_frame,
275 const std::vector<VideoFrameType>* frame_types) {
276 if (!encoder_) {
277 ReportError();
278 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
279 }
280 if (!encoded_image_callback_) {
281 RTC_LOG(LS_WARNING)
282 << "InitEncode() has been called, but a callback function "
283 "has not been set with RegisterEncodeCompleteCallback()";
284 ReportError();
285 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
286 }
287
288 webrtc::scoped_refptr<I420BufferInterface> frame_buffer =
289 input_frame.video_frame_buffer()->ToI420();
290 if (!frame_buffer) {
291 RTC_LOG(LS_ERROR) << "Failed to convert "
292 << VideoFrameBufferTypeToString(
293 input_frame.video_frame_buffer()->type())
294 << " image to I420. Can't encode frame.";
295 return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
296 }
297 RTC_CHECK(frame_buffer->type() == VideoFrameBuffer::Type::kI420);
298
299 bool is_keyframe_needed = false;
300 if (configuration_.key_frame_request && configuration_.sending) {
301 is_keyframe_needed = true;
302 }
303
304 bool send_key_frame =
305 is_keyframe_needed ||
306 (frame_types && (*frame_types)[0] == VideoFrameType::kVideoFrameKey);
307 if (send_key_frame) {
308 is_keyframe_needed = true;
309 configuration_.key_frame_request = false;
310 }
311
312 RTC_DCHECK_EQ(configuration_.width, frame_buffer->width());
313 RTC_DCHECK_EQ(configuration_.height, frame_buffer->height());
314
315 if (!configuration_.sending) {
316 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
317 }
318
319 if (frame_types != nullptr) {
320 // Skip frame?
321 if ((*frame_types)[0] == VideoFrameType::kEmptyFrame) {
322 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
323 }
324 }
325
326 try {
327 const NvEncInputFrame* nv_enc_input_frame = encoder_->GetNextInputFrame();
328
329 if (cu_memory_type_ == CU_MEMORYTYPE_DEVICE) {
330 CopyI420BufferToDeviceFrame(cu_context_, *frame_buffer,
331 *nv_enc_input_frame);
332 }
333
334 NV_ENC_PIC_PARAMS pic_params = NV_ENC_PIC_PARAMS();
335 pic_params.version = NV_ENC_PIC_PARAMS_VER;
336 pic_params.encodePicFlags = 0;
337 if (is_keyframe_needed) {
338 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_FORCEINTRA |
339 NV_ENC_PIC_FLAG_FORCEIDR |
340 NV_ENC_PIC_FLAG_OUTPUT_SPSPPS;
341 configuration_.key_frame_request = false;
342 }
343
344 std::vector<std::vector<uint8_t>> bit_stream;
345 encoder_->EncodeFrame(bit_stream, &pic_params);
346
347 for (std::vector<uint8_t>& packet : bit_stream) {
348 int32_t result = ProcessEncodedFrame(packet, input_frame);
349 if (result != WEBRTC_VIDEO_CODEC_OK) {
350 return result;
351 }
352 }
353 } catch (const NVENCException& e) {
354 RTC_LOG(LS_ERROR) << "Failed EncodeFrame NvEncoder " << e.what();
355 return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
356 }
357
358 return WEBRTC_VIDEO_CODEC_OK;
359}
360
361int32_t NvidiaH264EncoderImpl::ProcessEncodedFrame(
362 std::vector<uint8_t>& packet,
363 const ::webrtc::VideoFrame& inputFrame) {
364 encoded_image_._encodedWidth = encoder_->GetEncodeWidth();
365 encoded_image_._encodedHeight = encoder_->GetEncodeHeight();
366 encoded_image_.SetRtpTimestamp(inputFrame.rtp_timestamp());
367 encoded_image_.SetSimulcastIndex(0);
368 encoded_image_.ntp_time_ms_ = inputFrame.ntp_time_ms();
369 encoded_image_.capture_time_ms_ = inputFrame.render_time_ms();
370 encoded_image_.rotation_ = inputFrame.rotation();
371 encoded_image_.content_type_ = VideoContentType::UNSPECIFIED;
372 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
373 encoded_image_._frameType = VideoFrameType::kVideoFrameDelta;
374 encoded_image_.SetColorSpace(inputFrame.color_space());
375 std::vector<H264::NaluIndex> naluIndices = H264::FindNaluIndices(packet);
376 for (uint32_t i = 0; i < naluIndices.size(); i++) {
377 const H264::NaluType naluType =
378 H264::ParseNaluType(packet[naluIndices[i].payload_start_offset]);
379 if (naluType == H264::kIdr) {
380 encoded_image_._frameType = VideoFrameType::kVideoFrameKey;
381 break;
382 }
383 }
384
385 encoded_image_.SetEncodedData(
386 EncodedImageBuffer::Create(packet.data(), packet.size()));
387 encoded_image_.set_size(packet.size());
388
389 h264_bitstream_parser_.ParseBitstream(encoded_image_);
390 encoded_image_.qp_ = h264_bitstream_parser_.GetLastSliceQp().value_or(-1);
391
392 CodecSpecificInfo codecInfo;
393 codecInfo.codecType = kVideoCodecH264;
394 codecInfo.codecSpecific.H264.packetization_mode =
395 H264PacketizationMode::NonInterleaved;
396
397 const auto result =
398 encoded_image_callback_->OnEncodedImage(encoded_image_, &codecInfo);
399 if (result.error != EncodedImageCallback::Result::OK) {
400 RTC_LOG(LS_ERROR) << "Encode m_encodedCompleteCallback failed "
401 << result.error;
402 return WEBRTC_VIDEO_CODEC_ERROR;
403 }
404 return WEBRTC_VIDEO_CODEC_OK;
405}
406
407VideoEncoder::EncoderInfo NvidiaH264EncoderImpl::GetEncoderInfo() const {
408 EncoderInfo info;
409 info.supports_native_handle = false;
410 info.implementation_name = "NVIDIA H264 Encoder";
411 info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
412 info.is_hardware_accelerated = true;
413 info.supports_simulcast = false;
414 info.preferred_pixel_formats = {VideoFrameBuffer::Type::kI420};
415 return info;
416}
417
418void NvidiaH264EncoderImpl::SetRates(
419 const RateControlParameters& parameters) {
420 if (!encoder_) {
421 RTC_LOG(LS_WARNING) << "SetRates() while uninitialized.";
422 return;
423 }
424
425 if (!std::isfinite(parameters.framerate_fps) ||
426 parameters.framerate_fps < 1.0) {
427 RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps;
428 return;
429 }
430
431 const uint32_t target_bps = parameters.bitrate.get_sum_bps();
432 if (target_bps == 0) {
433 configuration_.SetStreamState(false);
434 return;
435 }
436
437 const uint32_t frame_rate = static_cast<uint32_t>(std::clamp(
438 std::round(parameters.framerate_fps), 1.0,
439 static_cast<double>(std::numeric_limits<uint32_t>::max())));
440 try {
441 if (!encoder_->SetRates(frame_rate, target_bps)) {
442 RTC_LOG(LS_WARNING) << "Failed to reconfigure NVENC rates: encoder is "
443 "not initialized.";
444 return;
445 }
446 } catch (const NVENCException& e) {
447 RTC_LOG(LS_WARNING) << "Failed to reconfigure NVENC rates to "
448 << target_bps << " bps @ " << frame_rate
449 << " fps: " << e.what();
450 return;
451 }
452
453 codec_.maxFramerate = frame_rate;
454 codec_.maxBitrate = target_bps / 1000;
455 configuration_.target_bps = target_bps;
456 configuration_.max_frame_rate = frame_rate;
457 configuration_.SetStreamState(true);
458}
459
460void NvidiaH264EncoderImpl::LayerConfig::SetStreamState(bool send_stream) {
461 if (send_stream && !sending) {
462 // Need a key frame if we have not sent this stream before.
463 key_frame_request = true;
464 }
465 sending = send_stream;
466}
467
468} // namespace webrtc