BlueGit

ict rusty-teams

Files

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

av1_encoder_impl.cpp

av1_encoder_impl.cpp 16.0 KiB Download Raw
1#include "av1_encoder_impl.h"
2
3#include <algorithm>
4#include <cmath>
5#include <limits>
6#include <utility>
7
8#include "../av1_bitstream.h"
9#include "i420_buffer_cuda.h"
10#include "api/video/video_codec_constants.h"
11#include "common_video/libyuv/include/webrtc_libyuv.h"
12#include "modules/video_coding/include/video_codec_interface.h"
13#include "modules/video_coding/include/video_error_codes.h"
14#include "modules/video_coding/utility/simulcast_rate_allocator.h"
15#include "rtc_base/checks.h"
16#include "rtc_base/logging.h"
17#include "system_wrappers/include/metrics.h"
18
19namespace webrtc {
20
21// Used by histograms. Values of entries should not be changed.
22enum AV1EncoderImplEvent {
23 kAV1EncoderEventInit = 0,
24 kAV1EncoderEventError = 1,
25 kAV1EncoderEventMax = 16,
26};
27
28namespace {
29
30uint32_t ClampToUint32(uint64_t value) {
31 return static_cast<uint32_t>(
32 std::min<uint64_t>(value, std::numeric_limits<uint32_t>::max()));
33}
34
35} // namespace
36
37NvidiaAV1EncoderImpl::NvidiaAV1EncoderImpl(
38 const webrtc::Environment& env,
39 CUcontext context,
40 CUmemorytype memory_type,
41 NV_ENC_BUFFER_FORMAT nv_format,
42 const SdpVideoFormat& format)
43 : env_(env),
44 encoder_(nullptr),
45 cu_context_(context),
46 cu_memory_type_(memory_type),
47 cu_scaled_array_(nullptr),
48 nv_format_(nv_format),
49 format_(format) {
50 RTC_CHECK_NE(cu_memory_type_, CU_MEMORYTYPE_HOST);
51}
52
53NvidiaAV1EncoderImpl::~NvidiaAV1EncoderImpl() {
54 Release();
55}
56
57void NvidiaAV1EncoderImpl::ReportInit() {
58 if (has_reported_init_) {
59 return;
60 }
61 RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.AV1EncoderImpl.Event",
62 kAV1EncoderEventInit, kAV1EncoderEventMax);
63 has_reported_init_ = true;
64}
65
66void NvidiaAV1EncoderImpl::ReportError() {
67 if (has_reported_error_) {
68 return;
69 }
70 RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.AV1EncoderImpl.Event",
71 kAV1EncoderEventError, kAV1EncoderEventMax);
72 has_reported_error_ = true;
73}
74
75int32_t NvidiaAV1EncoderImpl::InitEncode(
76 const VideoCodec* inst,
77 const VideoEncoder::Settings& settings) {
78 (void)settings;
79 if (!inst || inst->codecType != kVideoCodecAV1) {
80 ReportError();
81 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
82 }
83 if (inst->maxFramerate == 0) {
84 ReportError();
85 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
86 }
87 if (inst->width < 1 || inst->height < 1) {
88 ReportError();
89 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
90 }
91 if (inst->numberOfSimulcastStreams > 1) {
92 ReportError();
93 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
94 }
95 const auto scalability_mode = inst->GetScalabilityMode();
96 if (scalability_mode.has_value() &&
97 *scalability_mode != ScalabilityMode::kL1T1) {
98 ReportError();
99 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
100 }
101
102 int32_t release_ret = Release();
103 if (release_ret != WEBRTC_VIDEO_CODEC_OK) {
104 ReportError();
105 return release_ret;
106 }
107
108 codec_ = *inst;
109 sent_decodable_keyframe_ = false;
110 cached_sequence_header_obu_.clear();
111 svc_controller_ = ScalableVideoControllerNoLayering();
112 if (!codec_.GetScalabilityMode().has_value()) {
113 codec_.SetScalabilityMode(ScalabilityMode::kL1T1);
114 }
115
116 if (codec_.numberOfSimulcastStreams == 0) {
117 codec_.simulcastStream[0].width = codec_.width;
118 codec_.simulcastStream[0].height = codec_.height;
119 }
120
121 const size_t new_capacity =
122 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
123 encoded_image_.SetEncodedData(EncodedImageBuffer::Create(new_capacity));
124 encoded_image_._encodedWidth = codec_.width;
125 encoded_image_._encodedHeight = codec_.height;
126 encoded_image_.set_size(0);
127
128 configuration_.sending = false;
129 configuration_.frame_dropping_on = codec_.GetFrameDropEnabled();
130 configuration_.key_frame_interval =
131 std::max<int>(1, static_cast<int>(codec_.maxFramerate)) * 2;
132
133 configuration_.width = codec_.width;
134 configuration_.height = codec_.height;
135
136 configuration_.max_frame_rate = codec_.maxFramerate;
137 configuration_.target_bps = codec_.startBitrate * 1000;
138 configuration_.max_bps = codec_.maxBitrate * 1000;
139
140 const CUresult result = cuCtxSetCurrent(cu_context_);
141 if (result != CUDA_SUCCESS) {
142 ReportError();
143 return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
144 }
145
146 try {
147 if (cu_memory_type_ == CU_MEMORYTYPE_DEVICE) {
148 encoder_ = std::make_unique<NvEncoderCuda>(cu_context_, codec_.width,
149 codec_.height, nv_format_, 0);
150 } else {
151 RTC_DCHECK_NOTREACHED();
152 }
153 } catch (const NVENCException& e) {
154 RTC_LOG(LS_ERROR) << "Failed Initialize NvEncoder " << e.what();
155 ReportError();
156 return WEBRTC_VIDEO_CODEC_ERROR;
157 }
158
159 nv_initialize_params_.version = NV_ENC_INITIALIZE_PARAMS_VER;
160 nv_encode_config_.version = NV_ENC_CONFIG_VER;
161 nv_initialize_params_.encodeConfig = &nv_encode_config_;
162
163 GUID encodeGuid = NV_ENC_CODEC_AV1_GUID;
164 GUID presetGuid = NV_ENC_PRESET_P4_GUID;
165
166 encoder_->CreateDefaultEncoderParams(&nv_initialize_params_, encodeGuid,
167 presetGuid,
168 NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY);
169
170 nv_initialize_params_.frameRateNum = std::max<uint32_t>(
171 1, static_cast<uint32_t>(std::round(configuration_.max_frame_rate)));
172 nv_initialize_params_.frameRateDen = 1;
173 nv_initialize_params_.bufferFormat = nv_format_;
174
175 nv_encode_config_.profileGUID = NV_ENC_AV1_PROFILE_MAIN_GUID;
176 nv_encode_config_.gopLength = NVENC_INFINITE_GOPLENGTH;
177 nv_encode_config_.frameIntervalP = 1;
178 nv_encode_config_.encodeCodecConfig.av1Config.level =
179 NV_ENC_LEVEL_AV1_AUTOSELECT;
180 nv_encode_config_.encodeCodecConfig.av1Config.tier = NV_ENC_TIER_AV1_0;
181 nv_encode_config_.encodeCodecConfig.av1Config.chromaFormatIDC = 1;
182 nv_encode_config_.encodeCodecConfig.av1Config.inputPixelBitDepthMinus8 = 0;
183 nv_encode_config_.encodeCodecConfig.av1Config.pixelBitDepthMinus8 = 0;
184 nv_encode_config_.encodeCodecConfig.av1Config.idrPeriod =
185 NVENC_INFINITE_GOPLENGTH;
186 nv_encode_config_.encodeCodecConfig.av1Config.repeatSeqHdr = 1;
187 nv_encode_config_.encodeCodecConfig.av1Config.maxTemporalLayersMinus1 = 0;
188 nv_encode_config_.rcParams.version = NV_ENC_RC_PARAMS_VER;
189 nv_encode_config_.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
190 nv_encode_config_.rcParams.averageBitRate = configuration_.target_bps;
191 const uint64_t vbv_buffer_size =
192 (static_cast<uint64_t>(nv_encode_config_.rcParams.averageBitRate) *
193 nv_initialize_params_.frameRateDen /
194 nv_initialize_params_.frameRateNum) *
195 5;
196 nv_encode_config_.rcParams.vbvBufferSize =
197 ClampToUint32(vbv_buffer_size);
198 nv_encode_config_.rcParams.vbvInitialDelay =
199 nv_encode_config_.rcParams.vbvBufferSize;
200
201 try {
202 encoder_->CreateEncoder(&nv_initialize_params_);
203 } catch (const NVENCException& e) {
204 RTC_LOG(LS_ERROR) << "Failed Initialize NvEncoder " << e.what();
205 ReportError();
206 return WEBRTC_VIDEO_CODEC_ERROR;
207 }
208
209 RTC_LOG(LS_INFO) << "NVIDIA AV1 NVENC initialized: " << codec_.width << "x"
210 << codec_.height << " @ " << codec_.maxFramerate
211 << "fps, target_bps=" << configuration_.target_bps;
212
213 ReportInit();
214
215 SimulcastRateAllocator init_allocator(env_, codec_);
216 VideoBitrateAllocation allocation =
217 init_allocator.Allocate(VideoBitrateAllocationParameters(
218 DataRate::KilobitsPerSec(codec_.startBitrate), codec_.maxFramerate));
219 SetRates(RateControlParameters(allocation, codec_.maxFramerate));
220 return WEBRTC_VIDEO_CODEC_OK;
221}
222
223int32_t NvidiaAV1EncoderImpl::RegisterEncodeCompleteCallback(
224 EncodedImageCallback* callback) {
225 encoded_image_callback_ = callback;
226 return WEBRTC_VIDEO_CODEC_OK;
227}
228
229int32_t NvidiaAV1EncoderImpl::Release() {
230 if (encoder_) {
231 encoder_->DestroyEncoder();
232 encoder_ = nullptr;
233 }
234 if (cu_scaled_array_) {
235 cuArrayDestroy(cu_scaled_array_);
236 cu_scaled_array_ = nullptr;
237 }
238 return WEBRTC_VIDEO_CODEC_OK;
239}
240
241int32_t NvidiaAV1EncoderImpl::Encode(
242 const VideoFrame& input_frame,
243 const std::vector<VideoFrameType>* frame_types) {
244 if (!encoder_) {
245 ReportError();
246 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
247 }
248 if (!encoded_image_callback_) {
249 RTC_LOG(LS_WARNING)
250 << "InitEncode() has been called, but a callback function "
251 "has not been set with RegisterEncodeCompleteCallback()";
252 ReportError();
253 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
254 }
255
256 webrtc::scoped_refptr<I420BufferInterface> frame_buffer =
257 input_frame.video_frame_buffer()->ToI420();
258 if (!frame_buffer) {
259 RTC_LOG(LS_ERROR) << "Failed to convert "
260 << VideoFrameBufferTypeToString(
261 input_frame.video_frame_buffer()->type())
262 << " image to I420. Can't encode frame.";
263 return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
264 }
265 RTC_CHECK(frame_buffer->type() == VideoFrameBuffer::Type::kI420);
266
267 bool is_keyframe_needed = false;
268 if (configuration_.key_frame_request && configuration_.sending) {
269 is_keyframe_needed = true;
270 }
271 if (frame_types && !frame_types->empty()) {
272 if ((*frame_types)[0] == VideoFrameType::kVideoFrameKey) {
273 is_keyframe_needed = true;
274 }
275 if ((*frame_types)[0] == VideoFrameType::kEmptyFrame) {
276 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
277 }
278 }
279
280 RTC_DCHECK_EQ(configuration_.width, frame_buffer->width());
281 RTC_DCHECK_EQ(configuration_.height, frame_buffer->height());
282
283 if (!configuration_.sending) {
284 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
285 }
286
287 if (!sent_decodable_keyframe_) {
288 is_keyframe_needed = true;
289 }
290
291 try {
292 const NvEncInputFrame* nv_enc_input_frame = encoder_->GetNextInputFrame();
293
294 if (cu_memory_type_ == CU_MEMORYTYPE_DEVICE) {
295 CopyI420BufferToDeviceFrame(cu_context_, *frame_buffer,
296 *nv_enc_input_frame);
297 }
298
299 NV_ENC_PIC_PARAMS pic_params = NV_ENC_PIC_PARAMS();
300 pic_params.version = NV_ENC_PIC_PARAMS_VER;
301 pic_params.encodePicFlags = 0;
302 if (is_keyframe_needed) {
303 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_FORCEINTRA |
304 NV_ENC_PIC_FLAG_FORCEIDR |
305 NV_ENC_PIC_FLAG_OUTPUT_SPSPPS;
306 }
307
308 std::vector<std::vector<uint8_t>> bit_stream;
309 encoder_->EncodeFrame(bit_stream, &pic_params);
310
311 for (std::vector<uint8_t>& packet : bit_stream) {
312 if (packet.empty()) {
313 RTC_LOG(LS_WARNING)
314 << "NVIDIA AV1 NVENC returned empty packet; skipping output.";
315 continue;
316 }
317
318 livekit::av1::NormalizeForRtp(&packet);
319 if (packet.empty()) {
320 RTC_LOG(LS_ERROR)
321 << "NVIDIA AV1 NVENC packet contained no transferable OBUs "
322 "after RTP normalization; skipping.";
323 continue;
324 }
325
326 std::vector<uint8_t> sequence_header;
327 if (livekit::av1::ExtractSequenceHeaderObu(
328 packet.data(), packet.size(), &sequence_header)) {
329 cached_sequence_header_obu_ = std::move(sequence_header);
330 }
331
332 const bool treat_as_keyframe = is_keyframe_needed;
333 if (treat_as_keyframe) {
334 livekit::av1::EnsureSequenceHeaderOnKeyframe(
335 &packet, cached_sequence_header_obu_);
336 }
337
338 if (!livekit::av1::IsWebRtcParseable(packet.data(), packet.size())) {
339 RTC_LOG(LS_ERROR)
340 << "NVIDIA AV1 NVENC bitstream is not parseable by WebRTC; "
341 "dropping frame (size="
342 << packet.size() << ").";
343 continue;
344 }
345
346 if (treat_as_keyframe &&
347 livekit::av1::HasSequenceHeaderObu(packet.data(), packet.size())) {
348 sent_decodable_keyframe_ = true;
349 configuration_.key_frame_request = false;
350 } else if (!sent_decodable_keyframe_) {
351 RTC_LOG(LS_WARNING)
352 << "NVIDIA AV1 NVENC keyframe missing sequence header OBU; "
353 "continuing to force keyframes.";
354 configuration_.key_frame_request = true;
355 } else if (is_keyframe_needed) {
356 configuration_.key_frame_request = false;
357 }
358
359 int32_t result =
360 ProcessEncodedFrame(packet, input_frame, treat_as_keyframe);
361 if (result != WEBRTC_VIDEO_CODEC_OK) {
362 return result;
363 }
364 }
365 } catch (const NVENCException& e) {
366 RTC_LOG(LS_ERROR) << "Failed EncodeFrame NvEncoder " << e.what();
367 return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
368 }
369
370 return WEBRTC_VIDEO_CODEC_OK;
371}
372
373int32_t NvidiaAV1EncoderImpl::ProcessEncodedFrame(
374 const std::vector<uint8_t>& packet,
375 const ::webrtc::VideoFrame& input_frame,
376 bool is_keyframe) {
377 encoded_image_._encodedWidth = encoder_->GetEncodeWidth();
378 encoded_image_._encodedHeight = encoder_->GetEncodeHeight();
379 encoded_image_.SetRtpTimestamp(input_frame.rtp_timestamp());
380 encoded_image_.SetSimulcastIndex(0);
381 encoded_image_.ntp_time_ms_ = input_frame.ntp_time_ms();
382 encoded_image_.capture_time_ms_ = input_frame.render_time_ms();
383 encoded_image_.rotation_ = input_frame.rotation();
384 encoded_image_.content_type_ = VideoContentType::UNSPECIFIED;
385 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
386 encoded_image_._frameType =
387 is_keyframe ? VideoFrameType::kVideoFrameKey
388 : VideoFrameType::kVideoFrameDelta;
389 encoded_image_.SetColorSpace(input_frame.color_space());
390
391 encoded_image_.SetEncodedData(
392 EncodedImageBuffer::Create(packet.data(), packet.size()));
393 encoded_image_.set_size(packet.size());
394
395 encoded_image_.qp_ = -1;
396
397 CodecSpecificInfo codecInfo;
398 codecInfo.codecType = kVideoCodecAV1;
399 codecInfo.end_of_picture = true;
400 codecInfo.scalability_mode = ScalabilityMode::kL1T1;
401
402 std::vector<ScalableVideoController::LayerFrameConfig> layer_frames =
403 svc_controller_.NextFrameConfig(/*restart=*/is_keyframe);
404 if (!layer_frames.empty()) {
405 const ScalableVideoController::LayerFrameConfig& layer_frame =
406 layer_frames.front();
407 codecInfo.generic_frame_info = svc_controller_.OnEncodeDone(layer_frame);
408 if (layer_frame.IsKeyframe()) {
409 codecInfo.template_structure = svc_controller_.DependencyStructure();
410 }
411 }
412
413 const auto result =
414 encoded_image_callback_->OnEncodedImage(encoded_image_, &codecInfo);
415 if (result.error != EncodedImageCallback::Result::OK) {
416 RTC_LOG(LS_ERROR) << "Encode m_encodedCompleteCallback failed "
417 << result.error;
418 return WEBRTC_VIDEO_CODEC_ERROR;
419 }
420 return WEBRTC_VIDEO_CODEC_OK;
421}
422
423VideoEncoder::EncoderInfo NvidiaAV1EncoderImpl::GetEncoderInfo() const {
424 EncoderInfo info;
425 info.supports_native_handle = false;
426 info.implementation_name = "NVIDIA AV1 Encoder";
427 info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
428 info.is_hardware_accelerated = true;
429 info.supports_simulcast = false;
430 info.preferred_pixel_formats = {VideoFrameBuffer::Type::kI420};
431 return info;
432}
433
434void NvidiaAV1EncoderImpl::SetRates(
435 const RateControlParameters& parameters) {
436 if (!encoder_) {
437 RTC_LOG(LS_WARNING) << "SetRates() while uninitialized.";
438 return;
439 }
440
441 if (!std::isfinite(parameters.framerate_fps) ||
442 parameters.framerate_fps < 1.0) {
443 RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps;
444 return;
445 }
446
447 const uint32_t target_bps = parameters.bitrate.get_sum_bps();
448 if (target_bps == 0) {
449 configuration_.SetStreamState(false);
450 return;
451 }
452
453 const uint32_t frame_rate = static_cast<uint32_t>(std::clamp(
454 std::round(parameters.framerate_fps), 1.0,
455 static_cast<double>(std::numeric_limits<uint32_t>::max())));
456 try {
457 if (!encoder_->SetRates(frame_rate, target_bps)) {
458 RTC_LOG(LS_WARNING) << "Failed to reconfigure NVENC rates: encoder is "
459 "not initialized.";
460 return;
461 }
462 } catch (const NVENCException& e) {
463 RTC_LOG(LS_WARNING) << "Failed to reconfigure NVENC rates to "
464 << target_bps << " bps @ " << frame_rate
465 << " fps: " << e.what();
466 return;
467 }
468
469 codec_.maxFramerate = frame_rate;
470 codec_.maxBitrate = target_bps / 1000;
471 configuration_.target_bps = target_bps;
472 configuration_.max_frame_rate = frame_rate;
473 configuration_.SetStreamState(true);
474}
475
476void NvidiaAV1EncoderImpl::LayerConfig::SetStreamState(bool send_stream) {
477 if (send_stream && !sending) {
478 key_frame_request = true;
479 }
480 sending = send_stream;
481}
482
483} // namespace webrtc