| 1 | #include "h264_encoder_impl.h" |
| 2 | |
| 3 | #include <algorithm> |
| 4 | #include <limits> |
| 5 | #include <string> |
| 6 | |
| 7 | #include "absl/strings/match.h" |
| 8 | #include "absl/types/optional.h" |
| 9 | #include "api/video/video_codec_constants.h" |
| 10 | #include "api/video_codecs/scalability_mode.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/svc/create_scalability_structure.h" |
| 15 | #include "modules/video_coding/utility/simulcast_rate_allocator.h" |
| 16 | #include "modules/video_coding/utility/simulcast_utility.h" |
| 17 | #include "rtc_base/checks.h" |
| 18 | #include "rtc_base/logging.h" |
| 19 | #include "rtc_base/time_utils.h" |
| 20 | #include "system_wrappers/include/metrics.h" |
| 21 | #include "third_party/libyuv/include/libyuv/convert.h" |
| 22 | #include "third_party/libyuv/include/libyuv/scale.h" |
| 23 | |
| 24 | #define VA_FOURCC_I420 0x30323449 // I420 |
| 25 | |
| 26 | namespace webrtc { |
| 27 | |
| 28 | // Used by histograms. Values of entries should not be changed. |
| 29 | enum H264EncoderImplEvent { |
| 30 | kH264EncoderEventInit = 0, |
| 31 | kH264EncoderEventError = 1, |
| 32 | kH264EncoderEventMax = 16, |
| 33 | }; |
| 34 | |
| 35 | VAAPIH264EncoderWrapper::VAAPIH264EncoderWrapper(const webrtc::Environment& env, |
| 36 | const SdpVideoFormat& format) |
| 37 | : env_(env), |
| 38 | encoder_(new livekit_ffi::VaapiH264EncoderWrapper()), |
| 39 | packetization_mode_( |
| 40 | H264EncoderSettings::Parse(format).packetization_mode), |
| 41 | format_(format) { |
| 42 | std::string hexString = format_.parameters.at("profile-level-id"); |
| 43 | std::optional<webrtc::H264ProfileLevelId> profile_level_id = |
| 44 | webrtc::ParseH264ProfileLevelId(hexString.c_str()); |
| 45 | if (profile_level_id.has_value()) { |
| 46 | profile_ = profile_level_id->profile; |
| 47 | level_ = profile_level_id->level; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | VAProfile VAAPIH264EncoderWrapper::GetVAProfile() const { |
| 52 | switch (profile_) { |
| 53 | case H264Profile::kProfileConstrainedBaseline: |
| 54 | case H264Profile::kProfileBaseline: |
| 55 | return VAProfileH264ConstrainedBaseline; |
| 56 | |
| 57 | case H264Profile::kProfileMain: |
| 58 | return VAProfileH264Main; |
| 59 | |
| 60 | case H264Profile::kProfileConstrainedHigh: |
| 61 | case H264Profile::kProfileHigh: |
| 62 | return VAProfileH264High; |
| 63 | } |
| 64 | return VAProfileNone; |
| 65 | } |
| 66 | |
| 67 | VAAPIH264EncoderWrapper::~VAAPIH264EncoderWrapper() { |
| 68 | Release(); |
| 69 | } |
| 70 | |
| 71 | void VAAPIH264EncoderWrapper::ReportInit() { |
| 72 | if (has_reported_init_) |
| 73 | return; |
| 74 | RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H264EncoderImpl.Event", |
| 75 | kH264EncoderEventInit, kH264EncoderEventMax); |
| 76 | has_reported_init_ = true; |
| 77 | } |
| 78 | |
| 79 | void VAAPIH264EncoderWrapper::ReportError() { |
| 80 | if (has_reported_error_) |
| 81 | return; |
| 82 | RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H264EncoderImpl.Event", |
| 83 | kH264EncoderEventError, kH264EncoderEventMax); |
| 84 | has_reported_error_ = true; |
| 85 | } |
| 86 | |
| 87 | int32_t VAAPIH264EncoderWrapper::InitEncode( |
| 88 | const VideoCodec* inst, |
| 89 | const VideoEncoder::Settings& settings) { |
| 90 | if (!inst || inst->codecType != kVideoCodecH264) { |
| 91 | ReportError(); |
| 92 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 93 | } |
| 94 | if (inst->maxFramerate == 0) { |
| 95 | ReportError(); |
| 96 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 97 | } |
| 98 | if (inst->width < 1 || inst->height < 1) { |
| 99 | ReportError(); |
| 100 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 101 | } |
| 102 | |
| 103 | int32_t release_ret = Release(); |
| 104 | if (release_ret != WEBRTC_VIDEO_CODEC_OK) { |
| 105 | ReportError(); |
| 106 | return release_ret; |
| 107 | } |
| 108 | |
| 109 | codec_ = *inst; |
| 110 | |
| 111 | // Code expects simulcastStream resolutions to be correct, make sure they are |
| 112 | // filled even when there are no simulcast layers. |
| 113 | if (codec_.numberOfSimulcastStreams == 0) { |
| 114 | codec_.simulcastStream[0].width = codec_.width; |
| 115 | codec_.simulcastStream[0].height = codec_.height; |
| 116 | } |
| 117 | |
| 118 | // Initialize encoded image. Default buffer size: size of unencoded data. |
| 119 | const size_t new_capacity = |
| 120 | CalcBufferSize(VideoType::kI420, codec_.width, codec_.height); |
| 121 | encoded_image_.SetEncodedData(EncodedImageBuffer::Create(new_capacity)); |
| 122 | encoded_image_._encodedWidth = codec_.width; |
| 123 | encoded_image_._encodedHeight = codec_.height; |
| 124 | encoded_image_.set_size(0); |
| 125 | |
| 126 | configuration_.sending = false; |
| 127 | configuration_.frame_dropping_on = codec_.GetFrameDropEnabled(); |
| 128 | configuration_.key_frame_interval = codec_.H264()->keyFrameInterval; |
| 129 | |
| 130 | configuration_.width = codec_.width; |
| 131 | configuration_.height = codec_.height; |
| 132 | |
| 133 | configuration_.max_frame_rate = codec_.maxFramerate; |
| 134 | configuration_.target_bps = codec_.startBitrate * 1000; |
| 135 | configuration_.max_bps = codec_.maxBitrate * 1000; |
| 136 | |
| 137 | if (!encoder_->IsInitialized()) { |
| 138 | // Initialize encoder. |
| 139 | int keyFrameInterval = 60; |
| 140 | if (codec_.maxFramerate > 0) { |
| 141 | keyFrameInterval = codec_.maxFramerate * 5; |
| 142 | } |
| 143 | auto va_profile = GetVAProfile(); |
| 144 | if (va_profile == VAProfileNone) { |
| 145 | RTC_LOG(LS_ERROR) << "Unsupported H264 profile: " |
| 146 | << static_cast<int>(profile_); |
| 147 | ReportError(); |
| 148 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 149 | } |
| 150 | if (!encoder_->Initialize(codec_.width, codec_.height, |
| 151 | codec_.startBitrate * 1000, keyFrameInterval, |
| 152 | keyFrameInterval, 1, codec_.maxFramerate, |
| 153 | va_profile, VA_RC_CBR)) { |
| 154 | RTC_LOG(LS_ERROR) << "Failed to initialize VAAPI H264 encoder"; |
| 155 | ReportError(); |
| 156 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | SimulcastRateAllocator init_allocator(env_, codec_); |
| 161 | VideoBitrateAllocation allocation = |
| 162 | init_allocator.Allocate(VideoBitrateAllocationParameters( |
| 163 | DataRate::KilobitsPerSec(codec_.startBitrate), codec_.maxFramerate)); |
| 164 | SetRates(RateControlParameters(allocation, codec_.maxFramerate)); |
| 165 | return WEBRTC_VIDEO_CODEC_OK; |
| 166 | } |
| 167 | |
| 168 | int32_t VAAPIH264EncoderWrapper::RegisterEncodeCompleteCallback( |
| 169 | EncodedImageCallback* callback) { |
| 170 | encoded_image_callback_ = callback; |
| 171 | return WEBRTC_VIDEO_CODEC_OK; |
| 172 | } |
| 173 | |
| 174 | int32_t VAAPIH264EncoderWrapper::Release() { |
| 175 | if (encoder_->IsInitialized()) { |
| 176 | encoder_->Destroy(); |
| 177 | } |
| 178 | return WEBRTC_VIDEO_CODEC_OK; |
| 179 | } |
| 180 | |
| 181 | int32_t VAAPIH264EncoderWrapper::Encode( |
| 182 | const VideoFrame& input_frame, |
| 183 | const std::vector<VideoFrameType>* frame_types) { |
| 184 | if (!encoder_) { |
| 185 | ReportError(); |
| 186 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 187 | } |
| 188 | if (!encoded_image_callback_) { |
| 189 | RTC_LOG(LS_WARNING) |
| 190 | << "InitEncode() has been called, but a callback function " |
| 191 | "has not been set with RegisterEncodeCompleteCallback()"; |
| 192 | ReportError(); |
| 193 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 194 | } |
| 195 | |
| 196 | webrtc::scoped_refptr<I420BufferInterface> frame_buffer = |
| 197 | input_frame.video_frame_buffer()->ToI420(); |
| 198 | if (!frame_buffer) { |
| 199 | RTC_LOG(LS_ERROR) << "Failed to convert " |
| 200 | << VideoFrameBufferTypeToString( |
| 201 | input_frame.video_frame_buffer()->type()) |
| 202 | << " image to I420. Can't encode frame."; |
| 203 | return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE; |
| 204 | } |
| 205 | RTC_CHECK(frame_buffer->type() == VideoFrameBuffer::Type::kI420 || |
| 206 | frame_buffer->type() == VideoFrameBuffer::Type::kI420A); |
| 207 | |
| 208 | bool is_keyframe_needed = false; |
| 209 | if (configuration_.key_frame_request && configuration_.sending) { |
| 210 | is_keyframe_needed = true; |
| 211 | } |
| 212 | |
| 213 | bool send_key_frame = |
| 214 | is_keyframe_needed || |
| 215 | (frame_types && (*frame_types)[0] == VideoFrameType::kVideoFrameKey); |
| 216 | if (send_key_frame) { |
| 217 | is_keyframe_needed = true; |
| 218 | configuration_.key_frame_request = false; |
| 219 | } |
| 220 | |
| 221 | RTC_DCHECK_EQ(configuration_.width, frame_buffer->width()); |
| 222 | RTC_DCHECK_EQ(configuration_.height, frame_buffer->height()); |
| 223 | |
| 224 | if (!configuration_.sending) { |
| 225 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 226 | } |
| 227 | |
| 228 | if (frame_types != nullptr) { |
| 229 | // Skip frame? |
| 230 | if ((*frame_types)[0] == VideoFrameType::kEmptyFrame) { |
| 231 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | std::vector<uint8_t> output; |
| 236 | encoder_->Encode(VA_FOURCC_I420, frame_buffer->DataY(), frame_buffer->DataU(), |
| 237 | frame_buffer->DataV(), send_key_frame, output); |
| 238 | |
| 239 | if (output.empty()) { |
| 240 | RTC_LOG(LS_ERROR) << "Failed to encode frame."; |
| 241 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 242 | } |
| 243 | |
| 244 | encoded_image_.SetEncodedData( |
| 245 | EncodedImageBuffer::Create(output.data(), output.size())); |
| 246 | |
| 247 | h264_bitstream_parser_.ParseBitstream(encoded_image_); |
| 248 | |
| 249 | encoded_image_.qp_ = h264_bitstream_parser_.GetLastSliceQp().value_or(-1); |
| 250 | |
| 251 | encoded_image_._encodedWidth = configuration_.width; |
| 252 | encoded_image_._encodedHeight = configuration_.height; |
| 253 | encoded_image_.SetRtpTimestamp(input_frame.rtp_timestamp()); |
| 254 | encoded_image_.SetColorSpace(input_frame.color_space()); |
| 255 | encoded_image_._frameType = send_key_frame ? VideoFrameType::kVideoFrameKey |
| 256 | : VideoFrameType::kVideoFrameDelta; |
| 257 | CodecSpecificInfo codec_specific; |
| 258 | codec_specific.codecType = kVideoCodecH264; |
| 259 | codec_specific.codecSpecific.H264.packetization_mode = packetization_mode_; |
| 260 | codec_specific.codecSpecific.H264.temporal_idx = kNoTemporalIdx; |
| 261 | codec_specific.codecSpecific.H264.base_layer_sync = false; |
| 262 | codec_specific.codecSpecific.H264.idr_frame = send_key_frame; |
| 263 | encoded_image_callback_->OnEncodedImage(encoded_image_, &codec_specific); |
| 264 | |
| 265 | return WEBRTC_VIDEO_CODEC_OK; |
| 266 | } |
| 267 | |
| 268 | VideoEncoder::EncoderInfo VAAPIH264EncoderWrapper::GetEncoderInfo() const { |
| 269 | EncoderInfo info; |
| 270 | info.supports_native_handle = false; |
| 271 | info.implementation_name = "VAAPI H264 Encoder"; |
| 272 | info.scaling_settings = VideoEncoder::ScalingSettings::kOff; |
| 273 | info.is_hardware_accelerated = true; |
| 274 | info.supports_simulcast = false; |
| 275 | info.preferred_pixel_formats = {VideoFrameBuffer::Type::kI420}; |
| 276 | return info; |
| 277 | } |
| 278 | |
| 279 | void VAAPIH264EncoderWrapper::SetRates( |
| 280 | const RateControlParameters& parameters) { |
| 281 | if (!encoder_) { |
| 282 | RTC_LOG(LS_WARNING) << "SetRates() while uninitialized."; |
| 283 | return; |
| 284 | } |
| 285 | |
| 286 | if (parameters.framerate_fps < 1.0) { |
| 287 | RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps; |
| 288 | return; |
| 289 | } |
| 290 | |
| 291 | if (parameters.bitrate.get_sum_bps() == 0) { |
| 292 | configuration_.SetStreamState(false); |
| 293 | return; |
| 294 | } |
| 295 | |
| 296 | codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps); |
| 297 | |
| 298 | configuration_.target_bps = parameters.bitrate.GetSpatialLayerSum(0); |
| 299 | configuration_.max_frame_rate = parameters.framerate_fps; |
| 300 | |
| 301 | if (configuration_.target_bps) { |
| 302 | configuration_.SetStreamState(true); |
| 303 | // Update max_frame_rate/target_bitrate for vaapi encoder. |
| 304 | encoder_->UpdateRates(configuration_.max_frame_rate, |
| 305 | configuration_.target_bps); |
| 306 | } else { |
| 307 | configuration_.SetStreamState(false); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | void VAAPIH264EncoderWrapper::LayerConfig::SetStreamState(bool send_stream) { |
| 312 | if (send_stream && !sending) { |
| 313 | // Need a key frame if we have not sent this stream before. |
| 314 | key_frame_request = true; |
| 315 | } |
| 316 | sending = send_stream; |
| 317 | } |
| 318 | |
| 319 | } // namespace webrtc |