| 1 | /* |
| 2 | * Copyright 2026 LiveKit, Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include "h265_encoder_impl.h" |
| 18 | |
| 19 | #include <algorithm> |
| 20 | #include <limits> |
| 21 | #include <string> |
| 22 | |
| 23 | #include "absl/strings/match.h" |
| 24 | #include "absl/types/optional.h" |
| 25 | #include "api/video/video_codec_constants.h" |
| 26 | #include "api/video_codecs/scalability_mode.h" |
| 27 | #include "common_video/libyuv/include/webrtc_libyuv.h" |
| 28 | #include "livekit/dmabuf_video_frame_buffer.h" |
| 29 | #include "modules/video_coding/include/video_codec_interface.h" |
| 30 | #include "modules/video_coding/include/video_error_codes.h" |
| 31 | #include "modules/video_coding/svc/create_scalability_structure.h" |
| 32 | #include "modules/video_coding/utility/simulcast_rate_allocator.h" |
| 33 | #include "modules/video_coding/utility/simulcast_utility.h" |
| 34 | #include "rtc_base/checks.h" |
| 35 | #include "rtc_base/logging.h" |
| 36 | #include "system_wrappers/include/metrics.h" |
| 37 | #include "third_party/libyuv/include/libyuv/convert.h" |
| 38 | |
| 39 | namespace webrtc { |
| 40 | |
| 41 | // Used by histograms. Values of entries should not be changed. |
| 42 | enum H265EncoderImplEvent { |
| 43 | kH265EncoderEventInit = 0, |
| 44 | kH265EncoderEventError = 1, |
| 45 | kH265EncoderEventMax = 16, |
| 46 | }; |
| 47 | |
| 48 | JetsonH265EncoderImpl::JetsonH265EncoderImpl(const webrtc::Environment& env, |
| 49 | const SdpVideoFormat& format) |
| 50 | : env_(env), encoder_(livekit::JetsonCodec::kH265), format_(format) {} |
| 51 | |
| 52 | JetsonH265EncoderImpl::~JetsonH265EncoderImpl() { |
| 53 | Release(); |
| 54 | } |
| 55 | |
| 56 | void JetsonH265EncoderImpl::ReportInit() { |
| 57 | if (has_reported_init_) { |
| 58 | return; |
| 59 | } |
| 60 | RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H265EncoderImpl.Event", |
| 61 | kH265EncoderEventInit, kH265EncoderEventMax); |
| 62 | has_reported_init_ = true; |
| 63 | } |
| 64 | |
| 65 | void JetsonH265EncoderImpl::ReportError() { |
| 66 | if (has_reported_error_) { |
| 67 | return; |
| 68 | } |
| 69 | RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H265EncoderImpl.Event", |
| 70 | kH265EncoderEventError, kH265EncoderEventMax); |
| 71 | has_reported_error_ = true; |
| 72 | } |
| 73 | |
| 74 | int32_t JetsonH265EncoderImpl::InitEncode( |
| 75 | const VideoCodec* inst, |
| 76 | const VideoEncoder::Settings& settings) { |
| 77 | (void)settings; |
| 78 | if (!inst || inst->codecType != kVideoCodecH265) { |
| 79 | ReportError(); |
| 80 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 81 | } |
| 82 | if (inst->maxFramerate == 0) { |
| 83 | ReportError(); |
| 84 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 85 | } |
| 86 | if (inst->width < 1 || inst->height < 1) { |
| 87 | ReportError(); |
| 88 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 89 | } |
| 90 | |
| 91 | int32_t release_ret = Release(); |
| 92 | if (release_ret != WEBRTC_VIDEO_CODEC_OK) { |
| 93 | ReportError(); |
| 94 | return release_ret; |
| 95 | } |
| 96 | |
| 97 | codec_ = *inst; |
| 98 | |
| 99 | if (codec_.numberOfSimulcastStreams == 0) { |
| 100 | codec_.simulcastStream[0].width = codec_.width; |
| 101 | codec_.simulcastStream[0].height = codec_.height; |
| 102 | } |
| 103 | |
| 104 | const size_t new_capacity = |
| 105 | CalcBufferSize(VideoType::kI420, codec_.width, codec_.height); |
| 106 | encoded_image_.SetEncodedData(EncodedImageBuffer::Create(new_capacity)); |
| 107 | encoded_image_._encodedWidth = codec_.width; |
| 108 | encoded_image_._encodedHeight = codec_.height; |
| 109 | encoded_image_.set_size(0); |
| 110 | |
| 111 | configuration_.sending = false; |
| 112 | configuration_.frame_dropping_on = codec_.GetFrameDropEnabled(); |
| 113 | configuration_.key_frame_interval = 0; |
| 114 | |
| 115 | configuration_.width = codec_.width; |
| 116 | configuration_.height = codec_.height; |
| 117 | |
| 118 | configuration_.max_frame_rate = codec_.maxFramerate; |
| 119 | configuration_.target_bps = codec_.startBitrate * 1000; |
| 120 | configuration_.max_bps = codec_.maxBitrate * 1000; |
| 121 | |
| 122 | if (!encoder_.IsInitialized()) { |
| 123 | int key_frame_interval = codec_.maxFramerate * 5; |
| 124 | if (!encoder_.Initialize(codec_.width, codec_.height, codec_.maxFramerate, |
| 125 | codec_.startBitrate * 1000, key_frame_interval)) { |
| 126 | RTC_LOG(LS_ERROR) << "Failed to initialize Jetson MMAPI encoder."; |
| 127 | ReportError(); |
| 128 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | ReportInit(); |
| 133 | |
| 134 | SimulcastRateAllocator init_allocator(env_, codec_); |
| 135 | VideoBitrateAllocation allocation = |
| 136 | init_allocator.Allocate(VideoBitrateAllocationParameters( |
| 137 | DataRate::KilobitsPerSec(codec_.startBitrate), codec_.maxFramerate)); |
| 138 | SetRates(RateControlParameters(allocation, codec_.maxFramerate)); |
| 139 | return WEBRTC_VIDEO_CODEC_OK; |
| 140 | } |
| 141 | |
| 142 | int32_t JetsonH265EncoderImpl::RegisterEncodeCompleteCallback( |
| 143 | EncodedImageCallback* callback) { |
| 144 | encoded_image_callback_ = callback; |
| 145 | return WEBRTC_VIDEO_CODEC_OK; |
| 146 | } |
| 147 | |
| 148 | int32_t JetsonH265EncoderImpl::Release() { |
| 149 | if (encoder_.IsInitialized()) { |
| 150 | encoder_.Destroy(); |
| 151 | } |
| 152 | return WEBRTC_VIDEO_CODEC_OK; |
| 153 | } |
| 154 | |
| 155 | int32_t JetsonH265EncoderImpl::Encode( |
| 156 | const VideoFrame& input_frame, |
| 157 | const std::vector<VideoFrameType>* frame_types) { |
| 158 | if (!encoder_.IsInitialized()) { |
| 159 | ReportError(); |
| 160 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 161 | } |
| 162 | if (!encoded_image_callback_) { |
| 163 | RTC_LOG(LS_WARNING) |
| 164 | << "InitEncode() has been called, but a callback function " |
| 165 | "has not been set with RegisterEncodeCompleteCallback()"; |
| 166 | ReportError(); |
| 167 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 168 | } |
| 169 | |
| 170 | bool is_keyframe_needed = false; |
| 171 | if (configuration_.key_frame_request && configuration_.sending) { |
| 172 | is_keyframe_needed = true; |
| 173 | } |
| 174 | if (frame_types && !frame_types->empty()) { |
| 175 | if ((*frame_types)[0] == VideoFrameType::kVideoFrameKey) { |
| 176 | is_keyframe_needed = true; |
| 177 | } |
| 178 | if ((*frame_types)[0] == VideoFrameType::kEmptyFrame) { |
| 179 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | if (!configuration_.sending) { |
| 184 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 185 | } |
| 186 | |
| 187 | std::vector<uint8_t> packet; |
| 188 | bool is_keyframe = false; |
| 189 | |
| 190 | // Check for DmaBuf zero-copy path first. |
| 191 | auto* dmabuf = livekit::DmaBufVideoFrameBuffer::FromNative( |
| 192 | input_frame.video_frame_buffer().get()); |
| 193 | if (dmabuf) { |
| 194 | if (!encoder_.EncodeDmaBuf(dmabuf->dmabuf_fd(), is_keyframe_needed, |
| 195 | &packet, &is_keyframe)) { |
| 196 | RTC_LOG(LS_ERROR) << "Failed to encode DmaBuf frame with Jetson MMAPI."; |
| 197 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 198 | } |
| 199 | } else { |
| 200 | // Standard I420 path. |
| 201 | webrtc::scoped_refptr<I420BufferInterface> frame_buffer = |
| 202 | input_frame.video_frame_buffer()->ToI420(); |
| 203 | if (!frame_buffer) { |
| 204 | RTC_LOG(LS_ERROR) << "Failed to convert frame to I420."; |
| 205 | return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE; |
| 206 | } |
| 207 | |
| 208 | RTC_DCHECK_EQ(configuration_.width, frame_buffer->width()); |
| 209 | RTC_DCHECK_EQ(configuration_.height, frame_buffer->height()); |
| 210 | |
| 211 | if (!encoder_.Encode(frame_buffer->DataY(), frame_buffer->StrideY(), |
| 212 | frame_buffer->DataU(), frame_buffer->StrideU(), |
| 213 | frame_buffer->DataV(), frame_buffer->StrideV(), |
| 214 | is_keyframe_needed, &packet, &is_keyframe)) { |
| 215 | RTC_LOG(LS_ERROR) << "Failed to encode frame with Jetson MMAPI encoder."; |
| 216 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | if (packet.empty()) { |
| 221 | RTC_LOG(LS_WARNING) << "Jetson MMAPI encoder returned empty packet; " |
| 222 | "skipping output."; |
| 223 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 224 | } |
| 225 | |
| 226 | if (is_keyframe_needed) { |
| 227 | configuration_.key_frame_request = false; |
| 228 | } |
| 229 | |
| 230 | return ProcessEncodedFrame(packet, input_frame, is_keyframe); |
| 231 | } |
| 232 | |
| 233 | int32_t JetsonH265EncoderImpl::ProcessEncodedFrame( |
| 234 | std::vector<uint8_t>& packet, |
| 235 | const ::webrtc::VideoFrame& input_frame, |
| 236 | bool is_keyframe) { |
| 237 | encoded_image_._encodedWidth = codec_.width; |
| 238 | encoded_image_._encodedHeight = codec_.height; |
| 239 | encoded_image_.SetRtpTimestamp(input_frame.rtp_timestamp()); |
| 240 | encoded_image_.SetSimulcastIndex(0); |
| 241 | encoded_image_.ntp_time_ms_ = input_frame.ntp_time_ms(); |
| 242 | encoded_image_.capture_time_ms_ = input_frame.render_time_ms(); |
| 243 | encoded_image_.rotation_ = input_frame.rotation(); |
| 244 | encoded_image_.content_type_ = VideoContentType::UNSPECIFIED; |
| 245 | encoded_image_.timing_.flags = VideoSendTiming::kInvalid; |
| 246 | encoded_image_._frameType = |
| 247 | is_keyframe ? VideoFrameType::kVideoFrameKey |
| 248 | : VideoFrameType::kVideoFrameDelta; |
| 249 | encoded_image_.SetColorSpace(input_frame.color_space()); |
| 250 | |
| 251 | encoded_image_.SetEncodedData( |
| 252 | EncodedImageBuffer::Create(packet.data(), packet.size())); |
| 253 | encoded_image_.set_size(packet.size()); |
| 254 | |
| 255 | encoded_image_.qp_ = -1; |
| 256 | |
| 257 | CodecSpecificInfo codecInfo; |
| 258 | codecInfo.codecType = kVideoCodecH265; |
| 259 | |
| 260 | const auto result = |
| 261 | encoded_image_callback_->OnEncodedImage(encoded_image_, &codecInfo); |
| 262 | if (result.error != EncodedImageCallback::Result::OK) { |
| 263 | RTC_LOG(LS_ERROR) << "Encode m_encodedCompleteCallback failed " |
| 264 | << result.error; |
| 265 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 266 | } |
| 267 | return WEBRTC_VIDEO_CODEC_OK; |
| 268 | } |
| 269 | |
| 270 | VideoEncoder::EncoderInfo JetsonH265EncoderImpl::GetEncoderInfo() const { |
| 271 | EncoderInfo info; |
| 272 | info.supports_native_handle = true; |
| 273 | info.implementation_name = "Jetson MMAPI H265 Encoder"; |
| 274 | info.scaling_settings = VideoEncoder::ScalingSettings::kOff; |
| 275 | info.is_hardware_accelerated = true; |
| 276 | info.supports_simulcast = false; |
| 277 | info.preferred_pixel_formats = {VideoFrameBuffer::Type::kNative, |
| 278 | VideoFrameBuffer::Type::kI420}; |
| 279 | return info; |
| 280 | } |
| 281 | |
| 282 | void JetsonH265EncoderImpl::SetRates( |
| 283 | const RateControlParameters& parameters) { |
| 284 | if (!encoder_.IsInitialized()) { |
| 285 | RTC_LOG(LS_WARNING) << "SetRates() while uninitialized."; |
| 286 | return; |
| 287 | } |
| 288 | |
| 289 | if (parameters.framerate_fps < 1.0) { |
| 290 | RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps; |
| 291 | return; |
| 292 | } |
| 293 | |
| 294 | if (parameters.bitrate.get_sum_bps() == 0) { |
| 295 | configuration_.SetStreamState(false); |
| 296 | return; |
| 297 | } |
| 298 | |
| 299 | codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps); |
| 300 | codec_.maxBitrate = parameters.bitrate.GetSpatialLayerSum(0); |
| 301 | |
| 302 | configuration_.target_bps = parameters.bitrate.GetSpatialLayerSum(0); |
| 303 | configuration_.max_frame_rate = parameters.framerate_fps; |
| 304 | |
| 305 | encoder_.SetRates(codec_.maxFramerate, |
| 306 | static_cast<int>(configuration_.target_bps)); |
| 307 | |
| 308 | if (configuration_.target_bps) { |
| 309 | configuration_.SetStreamState(true); |
| 310 | } else { |
| 311 | configuration_.SetStreamState(false); |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | void JetsonH265EncoderImpl::LayerConfig::SetStreamState(bool send_stream) { |
| 316 | if (send_stream && !sending) { |
| 317 | key_frame_request = true; |
| 318 | } |
| 319 | sending = send_stream; |
| 320 | } |
| 321 | |
| 322 | } // namespace webrtc |