| 1 | #include "h265_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/libyuv/include/webrtc_libyuv.h" |
| 14 | #include "modules/video_coding/include/video_codec_interface.h" |
| 15 | #include "modules/video_coding/include/video_error_codes.h" |
| 16 | #include "modules/video_coding/svc/create_scalability_structure.h" |
| 17 | #include "modules/video_coding/utility/simulcast_rate_allocator.h" |
| 18 | #include "modules/video_coding/utility/simulcast_utility.h" |
| 19 | #include "rtc_base/checks.h" |
| 20 | #include "rtc_base/logging.h" |
| 21 | #include "rtc_base/time_utils.h" |
| 22 | #include "system_wrappers/include/metrics.h" |
| 23 | #include "third_party/libyuv/include/libyuv/convert.h" |
| 24 | #include "third_party/libyuv/include/libyuv/scale.h" |
| 25 | |
| 26 | namespace webrtc { |
| 27 | |
| 28 | // Used by histograms. Values of entries should not be changed. |
| 29 | enum H265EncoderImplEvent { |
| 30 | kH265EncoderEventInit = 0, |
| 31 | kH265EncoderEventError = 1, |
| 32 | kH265EncoderEventMax = 16, |
| 33 | }; |
| 34 | |
| 35 | NvidiaH265EncoderImpl::NvidiaH265EncoderImpl( |
| 36 | const webrtc::Environment& env, |
| 37 | CUcontext context, |
| 38 | CUmemorytype memory_type, |
| 39 | NV_ENC_BUFFER_FORMAT nv_format, |
| 40 | const SdpVideoFormat& format) |
| 41 | : env_(env), |
| 42 | encoder_(nullptr), |
| 43 | cu_context_(context), |
| 44 | cu_memory_type_(memory_type), |
| 45 | cu_scaled_array_(nullptr), |
| 46 | nv_format_(nv_format), |
| 47 | format_(format) { |
| 48 | RTC_CHECK_NE(cu_memory_type_, CU_MEMORYTYPE_HOST); |
| 49 | } |
| 50 | |
| 51 | NvidiaH265EncoderImpl::~NvidiaH265EncoderImpl() { |
| 52 | Release(); |
| 53 | } |
| 54 | |
| 55 | void NvidiaH265EncoderImpl::ReportInit() { |
| 56 | if (has_reported_init_) |
| 57 | return; |
| 58 | RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H265EncoderImpl.Event", |
| 59 | kH265EncoderEventInit, kH265EncoderEventMax); |
| 60 | has_reported_init_ = true; |
| 61 | } |
| 62 | |
| 63 | void NvidiaH265EncoderImpl::ReportError() { |
| 64 | if (has_reported_error_) |
| 65 | return; |
| 66 | RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H265EncoderImpl.Event", |
| 67 | kH265EncoderEventError, kH265EncoderEventMax); |
| 68 | has_reported_error_ = true; |
| 69 | } |
| 70 | |
| 71 | int32_t NvidiaH265EncoderImpl::InitEncode( |
| 72 | const VideoCodec* inst, |
| 73 | const VideoEncoder::Settings& settings) { |
| 74 | if (!inst || inst->codecType != kVideoCodecH265) { |
| 75 | ReportError(); |
| 76 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 77 | } |
| 78 | if (inst->maxFramerate == 0) { |
| 79 | ReportError(); |
| 80 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 81 | } |
| 82 | if (inst->width < 1 || inst->height < 1) { |
| 83 | ReportError(); |
| 84 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 85 | } |
| 86 | |
| 87 | int32_t release_ret = Release(); |
| 88 | if (release_ret != WEBRTC_VIDEO_CODEC_OK) { |
| 89 | ReportError(); |
| 90 | return release_ret; |
| 91 | } |
| 92 | |
| 93 | codec_ = *inst; |
| 94 | |
| 95 | if (codec_.numberOfSimulcastStreams == 0) { |
| 96 | codec_.simulcastStream[0].width = codec_.width; |
| 97 | codec_.simulcastStream[0].height = codec_.height; |
| 98 | } |
| 99 | |
| 100 | const size_t new_capacity = |
| 101 | CalcBufferSize(VideoType::kI420, codec_.width, codec_.height); |
| 102 | encoded_image_.SetEncodedData(EncodedImageBuffer::Create(new_capacity)); |
| 103 | encoded_image_._encodedWidth = codec_.width; |
| 104 | encoded_image_._encodedHeight = codec_.height; |
| 105 | encoded_image_.set_size(0); |
| 106 | |
| 107 | configuration_.sending = false; |
| 108 | configuration_.frame_dropping_on = codec_.GetFrameDropEnabled(); |
| 109 | configuration_.key_frame_interval = 0; |
| 110 | |
| 111 | configuration_.width = codec_.width; |
| 112 | configuration_.height = codec_.height; |
| 113 | |
| 114 | configuration_.max_frame_rate = codec_.maxFramerate; |
| 115 | configuration_.target_bps = codec_.startBitrate * 1000; |
| 116 | configuration_.max_bps = codec_.maxBitrate * 1000; |
| 117 | |
| 118 | const CUresult result = cuCtxSetCurrent(cu_context_); |
| 119 | if (result != CUDA_SUCCESS) { |
| 120 | return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE; |
| 121 | } |
| 122 | |
| 123 | try { |
| 124 | if (cu_memory_type_ == CU_MEMORYTYPE_DEVICE) { |
| 125 | encoder_ = std::make_unique<NvEncoderCuda>(cu_context_, codec_.width, |
| 126 | codec_.height, nv_format_, 0); |
| 127 | } else { |
| 128 | RTC_DCHECK_NOTREACHED(); |
| 129 | } |
| 130 | } catch (const NVENCException& e) { |
| 131 | RTC_LOG(LS_ERROR) << "Failed Initialize NvEncoder " << e.what(); |
| 132 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 133 | } |
| 134 | |
| 135 | nv_initialize_params_.version = NV_ENC_INITIALIZE_PARAMS_VER; |
| 136 | nv_encode_config_.version = NV_ENC_CONFIG_VER; |
| 137 | nv_initialize_params_.encodeConfig = &nv_encode_config_; |
| 138 | |
| 139 | GUID encodeGuid = NV_ENC_CODEC_HEVC_GUID; |
| 140 | GUID presetGuid = NV_ENC_PRESET_P4_GUID; |
| 141 | |
| 142 | encoder_->CreateDefaultEncoderParams(&nv_initialize_params_, encodeGuid, |
| 143 | presetGuid, |
| 144 | NV_ENC_TUNING_INFO_ULTRA_LOW_LATENCY); |
| 145 | |
| 146 | nv_initialize_params_.frameRateNum = std::max<uint32_t>( |
| 147 | 1, static_cast<uint32_t>(std::round(configuration_.max_frame_rate))); |
| 148 | nv_initialize_params_.frameRateDen = 1; |
| 149 | nv_initialize_params_.bufferFormat = nv_format_; |
| 150 | |
| 151 | nv_encode_config_.profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID; |
| 152 | nv_encode_config_.gopLength = NVENC_INFINITE_GOPLENGTH; |
| 153 | nv_encode_config_.frameIntervalP = 1; |
| 154 | nv_encode_config_.rcParams.version = NV_ENC_RC_PARAMS_VER; |
| 155 | nv_encode_config_.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR; |
| 156 | nv_encode_config_.rcParams.averageBitRate = configuration_.target_bps; |
| 157 | nv_encode_config_.rcParams.vbvBufferSize = |
| 158 | (nv_encode_config_.rcParams.averageBitRate * |
| 159 | nv_initialize_params_.frameRateDen / |
| 160 | nv_initialize_params_.frameRateNum) * |
| 161 | 5; |
| 162 | nv_encode_config_.rcParams.vbvInitialDelay = |
| 163 | nv_encode_config_.rcParams.vbvBufferSize; |
| 164 | |
| 165 | try { |
| 166 | encoder_->CreateEncoder(&nv_initialize_params_); |
| 167 | } catch (const NVENCException& e) { |
| 168 | RTC_LOG(LS_ERROR) << "Failed Initialize NvEncoder " << e.what(); |
| 169 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 170 | } |
| 171 | |
| 172 | RTC_LOG(LS_INFO) << "NVIDIA H265/HEVC NVENC initialized: " |
| 173 | << codec_.width << "x" << codec_.height |
| 174 | << " @ " << codec_.maxFramerate << "fps, target_bps=" |
| 175 | << configuration_.target_bps; |
| 176 | |
| 177 | SimulcastRateAllocator init_allocator(env_, codec_); |
| 178 | VideoBitrateAllocation allocation = |
| 179 | init_allocator.Allocate(VideoBitrateAllocationParameters( |
| 180 | DataRate::KilobitsPerSec(codec_.startBitrate), codec_.maxFramerate)); |
| 181 | SetRates(RateControlParameters(allocation, codec_.maxFramerate)); |
| 182 | return WEBRTC_VIDEO_CODEC_OK; |
| 183 | } |
| 184 | |
| 185 | int32_t NvidiaH265EncoderImpl::RegisterEncodeCompleteCallback( |
| 186 | EncodedImageCallback* callback) { |
| 187 | encoded_image_callback_ = callback; |
| 188 | return WEBRTC_VIDEO_CODEC_OK; |
| 189 | } |
| 190 | |
| 191 | int32_t NvidiaH265EncoderImpl::Release() { |
| 192 | if (encoder_) { |
| 193 | encoder_->DestroyEncoder(); |
| 194 | encoder_ = nullptr; |
| 195 | } |
| 196 | if (cu_scaled_array_) { |
| 197 | cuArrayDestroy(cu_scaled_array_); |
| 198 | cu_scaled_array_ = nullptr; |
| 199 | } |
| 200 | return WEBRTC_VIDEO_CODEC_OK; |
| 201 | } |
| 202 | |
| 203 | int32_t NvidiaH265EncoderImpl::Encode( |
| 204 | const VideoFrame& input_frame, |
| 205 | const std::vector<VideoFrameType>* frame_types) { |
| 206 | if (!encoder_) { |
| 207 | ReportError(); |
| 208 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 209 | } |
| 210 | if (!encoded_image_callback_) { |
| 211 | RTC_LOG(LS_WARNING) |
| 212 | << "InitEncode() has been called, but a callback function " |
| 213 | "has not been set with RegisterEncodeCompleteCallback()"; |
| 214 | ReportError(); |
| 215 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 216 | } |
| 217 | |
| 218 | webrtc::scoped_refptr<I420BufferInterface> frame_buffer = |
| 219 | input_frame.video_frame_buffer()->ToI420(); |
| 220 | if (!frame_buffer) { |
| 221 | RTC_LOG(LS_ERROR) << "Failed to convert " |
| 222 | << VideoFrameBufferTypeToString( |
| 223 | input_frame.video_frame_buffer()->type()) |
| 224 | << " image to I420. Can't encode frame."; |
| 225 | return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE; |
| 226 | } |
| 227 | RTC_CHECK(frame_buffer->type() == VideoFrameBuffer::Type::kI420); |
| 228 | |
| 229 | bool is_keyframe_needed = false; |
| 230 | if (configuration_.key_frame_request && configuration_.sending) { |
| 231 | is_keyframe_needed = true; |
| 232 | } |
| 233 | |
| 234 | bool send_key_frame = |
| 235 | is_keyframe_needed || |
| 236 | (frame_types && (*frame_types)[0] == VideoFrameType::kVideoFrameKey); |
| 237 | if (send_key_frame) { |
| 238 | is_keyframe_needed = true; |
| 239 | configuration_.key_frame_request = false; |
| 240 | } |
| 241 | |
| 242 | RTC_DCHECK_EQ(configuration_.width, frame_buffer->width()); |
| 243 | RTC_DCHECK_EQ(configuration_.height, frame_buffer->height()); |
| 244 | |
| 245 | if (!configuration_.sending) { |
| 246 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 247 | } |
| 248 | |
| 249 | if (frame_types != nullptr) { |
| 250 | if ((*frame_types)[0] == VideoFrameType::kEmptyFrame) { |
| 251 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | try { |
| 256 | const NvEncInputFrame* nv_enc_input_frame = encoder_->GetNextInputFrame(); |
| 257 | |
| 258 | if (cu_memory_type_ == CU_MEMORYTYPE_DEVICE) { |
| 259 | CopyI420BufferToDeviceFrame(cu_context_, *frame_buffer, |
| 260 | *nv_enc_input_frame); |
| 261 | } |
| 262 | |
| 263 | NV_ENC_PIC_PARAMS pic_params = NV_ENC_PIC_PARAMS(); |
| 264 | pic_params.version = NV_ENC_PIC_PARAMS_VER; |
| 265 | pic_params.encodePicFlags = 0; |
| 266 | if (is_keyframe_needed) { |
| 267 | pic_params.encodePicFlags = NV_ENC_PIC_FLAG_FORCEINTRA | |
| 268 | NV_ENC_PIC_FLAG_FORCEIDR | |
| 269 | NV_ENC_PIC_FLAG_OUTPUT_SPSPPS; |
| 270 | configuration_.key_frame_request = false; |
| 271 | } |
| 272 | |
| 273 | current_encoding_is_keyframe_ = is_keyframe_needed; |
| 274 | |
| 275 | std::vector<std::vector<uint8_t>> bit_stream; |
| 276 | encoder_->EncodeFrame(bit_stream, &pic_params); |
| 277 | |
| 278 | for (std::vector<uint8_t>& packet : bit_stream) { |
| 279 | int32_t result = ProcessEncodedFrame(packet, input_frame); |
| 280 | if (result != WEBRTC_VIDEO_CODEC_OK) { |
| 281 | return result; |
| 282 | } |
| 283 | } |
| 284 | current_encoding_is_keyframe_ = false; |
| 285 | } catch (const NVENCException& e) { |
| 286 | RTC_LOG(LS_ERROR) << "Failed EncodeFrame NvEncoder " << e.what(); |
| 287 | return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE; |
| 288 | } |
| 289 | |
| 290 | return WEBRTC_VIDEO_CODEC_OK; |
| 291 | } |
| 292 | |
| 293 | int32_t NvidiaH265EncoderImpl::ProcessEncodedFrame( |
| 294 | std::vector<uint8_t>& packet, |
| 295 | const ::webrtc::VideoFrame& inputFrame) { |
| 296 | encoded_image_._encodedWidth = encoder_->GetEncodeWidth(); |
| 297 | encoded_image_._encodedHeight = encoder_->GetEncodeHeight(); |
| 298 | encoded_image_.SetRtpTimestamp(inputFrame.rtp_timestamp()); |
| 299 | encoded_image_.SetSimulcastIndex(0); |
| 300 | encoded_image_.ntp_time_ms_ = inputFrame.ntp_time_ms(); |
| 301 | encoded_image_.capture_time_ms_ = inputFrame.render_time_ms(); |
| 302 | encoded_image_.rotation_ = inputFrame.rotation(); |
| 303 | encoded_image_.content_type_ = VideoContentType::UNSPECIFIED; |
| 304 | encoded_image_.timing_.flags = VideoSendTiming::kInvalid; |
| 305 | encoded_image_._frameType = |
| 306 | current_encoding_is_keyframe_ ? VideoFrameType::kVideoFrameKey |
| 307 | : VideoFrameType::kVideoFrameDelta; |
| 308 | encoded_image_.SetColorSpace(inputFrame.color_space()); |
| 309 | |
| 310 | encoded_image_.SetEncodedData( |
| 311 | EncodedImageBuffer::Create(packet.data(), packet.size())); |
| 312 | encoded_image_.set_size(packet.size()); |
| 313 | |
| 314 | encoded_image_.qp_ = -1; |
| 315 | |
| 316 | CodecSpecificInfo codecInfo; |
| 317 | codecInfo.codecType = kVideoCodecH265; |
| 318 | |
| 319 | const auto result = |
| 320 | encoded_image_callback_->OnEncodedImage(encoded_image_, &codecInfo); |
| 321 | if (result.error != EncodedImageCallback::Result::OK) { |
| 322 | RTC_LOG(LS_ERROR) << "Encode m_encodedCompleteCallback failed " |
| 323 | << result.error; |
| 324 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 325 | } |
| 326 | return WEBRTC_VIDEO_CODEC_OK; |
| 327 | } |
| 328 | |
| 329 | VideoEncoder::EncoderInfo NvidiaH265EncoderImpl::GetEncoderInfo() const { |
| 330 | EncoderInfo info; |
| 331 | info.supports_native_handle = false; |
| 332 | info.implementation_name = "NVIDIA H265 Encoder"; |
| 333 | info.scaling_settings = VideoEncoder::ScalingSettings::kOff; |
| 334 | info.is_hardware_accelerated = true; |
| 335 | info.supports_simulcast = false; |
| 336 | info.preferred_pixel_formats = {VideoFrameBuffer::Type::kI420}; |
| 337 | return info; |
| 338 | } |
| 339 | |
| 340 | void NvidiaH265EncoderImpl::SetRates( |
| 341 | const RateControlParameters& parameters) { |
| 342 | if (!encoder_) { |
| 343 | RTC_LOG(LS_WARNING) << "SetRates() while uninitialized."; |
| 344 | return; |
| 345 | } |
| 346 | |
| 347 | if (!std::isfinite(parameters.framerate_fps) || |
| 348 | parameters.framerate_fps < 1.0) { |
| 349 | RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps; |
| 350 | return; |
| 351 | } |
| 352 | |
| 353 | const uint32_t target_bps = parameters.bitrate.get_sum_bps(); |
| 354 | if (target_bps == 0) { |
| 355 | configuration_.SetStreamState(false); |
| 356 | return; |
| 357 | } |
| 358 | |
| 359 | const uint32_t frame_rate = static_cast<uint32_t>(std::clamp( |
| 360 | std::round(parameters.framerate_fps), 1.0, |
| 361 | static_cast<double>(std::numeric_limits<uint32_t>::max()))); |
| 362 | try { |
| 363 | if (!encoder_->SetRates(frame_rate, target_bps)) { |
| 364 | RTC_LOG(LS_WARNING) << "Failed to reconfigure NVENC rates: encoder is " |
| 365 | "not initialized."; |
| 366 | return; |
| 367 | } |
| 368 | } catch (const NVENCException& e) { |
| 369 | RTC_LOG(LS_WARNING) << "Failed to reconfigure NVENC rates to " |
| 370 | << target_bps << " bps @ " << frame_rate |
| 371 | << " fps: " << e.what(); |
| 372 | return; |
| 373 | } |
| 374 | |
| 375 | codec_.maxFramerate = frame_rate; |
| 376 | codec_.maxBitrate = target_bps / 1000; |
| 377 | configuration_.target_bps = target_bps; |
| 378 | configuration_.max_frame_rate = frame_rate; |
| 379 | configuration_.SetStreamState(true); |
| 380 | } |
| 381 | |
| 382 | void NvidiaH265EncoderImpl::LayerConfig::SetStreamState(bool send_stream) { |
| 383 | if (send_stream && !sending) { |
| 384 | key_frame_request = true; |
| 385 | } |
| 386 | sending = send_stream; |
| 387 | } |
| 388 | |
| 389 | } // namespace webrtc |