| 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 "av1_encoder_impl.h" |
| 18 | |
| 19 | #include <algorithm> |
| 20 | #include <atomic> |
| 21 | #include <cstdio> |
| 22 | #include <cstdlib> |
| 23 | #include <filesystem> |
| 24 | #include <fstream> |
| 25 | |
| 26 | #include "api/video/video_codec_constants.h" |
| 27 | #include "api/video_codecs/scalability_mode.h" |
| 28 | #include "common_video/libyuv/include/webrtc_libyuv.h" |
| 29 | #include "../av1_bitstream.h" |
| 30 | #include "livekit/dmabuf_video_frame_buffer.h" |
| 31 | #include "modules/video_coding/include/video_codec_interface.h" |
| 32 | #include "modules/video_coding/include/video_error_codes.h" |
| 33 | #include "modules/video_coding/utility/simulcast_rate_allocator.h" |
| 34 | #include "rtc_base/checks.h" |
| 35 | #include "rtc_base/logging.h" |
| 36 | #include "system_wrappers/include/metrics.h" |
| 37 | |
| 38 | namespace webrtc { |
| 39 | |
| 40 | // Used by histograms. Values of entries should not be changed. |
| 41 | enum AV1EncoderImplEvent { |
| 42 | kAV1EncoderEventInit = 0, |
| 43 | kAV1EncoderEventError = 1, |
| 44 | kAV1EncoderEventMax = 16, |
| 45 | }; |
| 46 | |
| 47 | namespace { |
| 48 | |
| 49 | void DumpAv1PacketIfRequested(const std::vector<uint8_t>& packet, |
| 50 | bool keyframe) { |
| 51 | static std::atomic<bool> dumped(false); |
| 52 | if (dumped.load(std::memory_order_relaxed)) { |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | const char* dump_path = std::getenv("LK_DUMP_AV1"); |
| 57 | if (!dump_path || dump_path[0] == '\0') { |
| 58 | return; |
| 59 | } |
| 60 | |
| 61 | std::error_code ec; |
| 62 | std::filesystem::path path(dump_path); |
| 63 | if (path.has_parent_path()) { |
| 64 | std::filesystem::create_directories(path.parent_path(), ec); |
| 65 | } |
| 66 | std::ofstream out(dump_path, std::ios::binary); |
| 67 | if (!out.good()) { |
| 68 | std::fprintf(stderr, "[AV1] Failed to open LK_DUMP_AV1 path: %s\n", |
| 69 | dump_path); |
| 70 | std::fflush(stderr); |
| 71 | return; |
| 72 | } |
| 73 | |
| 74 | out.write(reinterpret_cast<const char*>(packet.data()), |
| 75 | static_cast<std::streamsize>(packet.size())); |
| 76 | dumped.store(true, std::memory_order_relaxed); |
| 77 | std::fprintf(stderr, "[AV1] Dumped normalized access unit to %s (bytes=%zu, " |
| 78 | "keyframe=%d)\n", |
| 79 | dump_path, packet.size(), keyframe ? 1 : 0); |
| 80 | std::fflush(stderr); |
| 81 | } |
| 82 | |
| 83 | } // namespace |
| 84 | |
| 85 | JetsonAV1EncoderImpl::JetsonAV1EncoderImpl(const webrtc::Environment& env, |
| 86 | const SdpVideoFormat& format) |
| 87 | : env_(env), encoder_(livekit::JetsonCodec::kAV1), format_(format) {} |
| 88 | |
| 89 | JetsonAV1EncoderImpl::~JetsonAV1EncoderImpl() { |
| 90 | Release(); |
| 91 | } |
| 92 | |
| 93 | void JetsonAV1EncoderImpl::ReportInit() { |
| 94 | if (has_reported_init_) { |
| 95 | return; |
| 96 | } |
| 97 | RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.AV1EncoderImpl.Event", |
| 98 | kAV1EncoderEventInit, kAV1EncoderEventMax); |
| 99 | has_reported_init_ = true; |
| 100 | } |
| 101 | |
| 102 | void JetsonAV1EncoderImpl::ReportError() { |
| 103 | if (has_reported_error_) { |
| 104 | return; |
| 105 | } |
| 106 | RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.AV1EncoderImpl.Event", |
| 107 | kAV1EncoderEventError, kAV1EncoderEventMax); |
| 108 | has_reported_error_ = true; |
| 109 | } |
| 110 | |
| 111 | int32_t JetsonAV1EncoderImpl::InitEncode( |
| 112 | const VideoCodec* inst, |
| 113 | const VideoEncoder::Settings& settings) { |
| 114 | (void)settings; |
| 115 | if (!inst || inst->codecType != kVideoCodecAV1) { |
| 116 | ReportError(); |
| 117 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 118 | } |
| 119 | if (inst->maxFramerate == 0) { |
| 120 | ReportError(); |
| 121 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 122 | } |
| 123 | if (inst->width < 1 || inst->height < 1) { |
| 124 | ReportError(); |
| 125 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 126 | } |
| 127 | if (inst->numberOfSimulcastStreams > 1) { |
| 128 | ReportError(); |
| 129 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 130 | } |
| 131 | const auto scalability_mode = inst->GetScalabilityMode(); |
| 132 | if (scalability_mode.has_value() && |
| 133 | *scalability_mode != ScalabilityMode::kL1T1) { |
| 134 | ReportError(); |
| 135 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 136 | } |
| 137 | |
| 138 | int32_t release_ret = Release(); |
| 139 | if (release_ret != WEBRTC_VIDEO_CODEC_OK) { |
| 140 | ReportError(); |
| 141 | return release_ret; |
| 142 | } |
| 143 | |
| 144 | codec_ = *inst; |
| 145 | sent_decodable_keyframe_ = false; |
| 146 | cached_sequence_header_obu_.clear(); |
| 147 | // Reset the dependency-descriptor controller so the first encoded frame of |
| 148 | // the new session is emitted as a keyframe with a fresh template structure. |
| 149 | svc_controller_ = ScalableVideoControllerNoLayering(); |
| 150 | if (!codec_.GetScalabilityMode().has_value()) { |
| 151 | codec_.SetScalabilityMode(ScalabilityMode::kL1T1); |
| 152 | } |
| 153 | |
| 154 | if (codec_.numberOfSimulcastStreams == 0) { |
| 155 | codec_.simulcastStream[0].width = codec_.width; |
| 156 | codec_.simulcastStream[0].height = codec_.height; |
| 157 | } |
| 158 | |
| 159 | const size_t new_capacity = |
| 160 | CalcBufferSize(VideoType::kI420, codec_.width, codec_.height); |
| 161 | encoded_image_.SetEncodedData(EncodedImageBuffer::Create(new_capacity)); |
| 162 | encoded_image_._encodedWidth = codec_.width; |
| 163 | encoded_image_._encodedHeight = codec_.height; |
| 164 | encoded_image_.set_size(0); |
| 165 | |
| 166 | configuration_.sending = false; |
| 167 | configuration_.frame_dropping_on = codec_.GetFrameDropEnabled(); |
| 168 | configuration_.key_frame_interval = |
| 169 | std::max<int>(1, static_cast<int>(codec_.maxFramerate)) * 2; |
| 170 | |
| 171 | configuration_.width = codec_.width; |
| 172 | configuration_.height = codec_.height; |
| 173 | |
| 174 | configuration_.max_frame_rate = codec_.maxFramerate; |
| 175 | configuration_.target_bps = codec_.startBitrate * 1000; |
| 176 | configuration_.max_bps = codec_.maxBitrate * 1000; |
| 177 | |
| 178 | if (!encoder_.IsInitialized()) { |
| 179 | if (!encoder_.Initialize(codec_.width, codec_.height, codec_.maxFramerate, |
| 180 | codec_.startBitrate * 1000, |
| 181 | configuration_.key_frame_interval)) { |
| 182 | RTC_LOG(LS_ERROR) << "Failed to initialize Jetson MMAPI AV1 encoder."; |
| 183 | ReportError(); |
| 184 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | ReportInit(); |
| 189 | |
| 190 | SimulcastRateAllocator init_allocator(env_, codec_); |
| 191 | VideoBitrateAllocation allocation = |
| 192 | init_allocator.Allocate(VideoBitrateAllocationParameters( |
| 193 | DataRate::KilobitsPerSec(codec_.startBitrate), codec_.maxFramerate)); |
| 194 | SetRates(RateControlParameters(allocation, codec_.maxFramerate)); |
| 195 | return WEBRTC_VIDEO_CODEC_OK; |
| 196 | } |
| 197 | |
| 198 | int32_t JetsonAV1EncoderImpl::RegisterEncodeCompleteCallback( |
| 199 | EncodedImageCallback* callback) { |
| 200 | encoded_image_callback_ = callback; |
| 201 | return WEBRTC_VIDEO_CODEC_OK; |
| 202 | } |
| 203 | |
| 204 | int32_t JetsonAV1EncoderImpl::Release() { |
| 205 | if (encoder_.IsInitialized()) { |
| 206 | encoder_.Destroy(); |
| 207 | } |
| 208 | return WEBRTC_VIDEO_CODEC_OK; |
| 209 | } |
| 210 | |
| 211 | int32_t JetsonAV1EncoderImpl::Encode( |
| 212 | const VideoFrame& input_frame, |
| 213 | const std::vector<VideoFrameType>* frame_types) { |
| 214 | if (!encoder_.IsInitialized()) { |
| 215 | ReportError(); |
| 216 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 217 | } |
| 218 | if (!encoded_image_callback_) { |
| 219 | RTC_LOG(LS_WARNING) |
| 220 | << "InitEncode() has been called, but a callback function " |
| 221 | "has not been set with RegisterEncodeCompleteCallback()"; |
| 222 | ReportError(); |
| 223 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 224 | } |
| 225 | |
| 226 | bool is_keyframe_needed = false; |
| 227 | if (configuration_.key_frame_request && configuration_.sending) { |
| 228 | is_keyframe_needed = true; |
| 229 | } |
| 230 | if (frame_types && !frame_types->empty()) { |
| 231 | if ((*frame_types)[0] == VideoFrameType::kVideoFrameKey) { |
| 232 | is_keyframe_needed = true; |
| 233 | } |
| 234 | if ((*frame_types)[0] == VideoFrameType::kEmptyFrame) { |
| 235 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | if (!configuration_.sending) { |
| 240 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 241 | } |
| 242 | |
| 243 | if (!sent_decodable_keyframe_) { |
| 244 | is_keyframe_needed = true; |
| 245 | } |
| 246 | |
| 247 | std::vector<uint8_t> packet; |
| 248 | bool is_keyframe = false; |
| 249 | |
| 250 | auto* dmabuf = livekit::DmaBufVideoFrameBuffer::FromNative( |
| 251 | input_frame.video_frame_buffer().get()); |
| 252 | if (dmabuf) { |
| 253 | if (!encoder_.EncodeDmaBuf(dmabuf->dmabuf_fd(), is_keyframe_needed, |
| 254 | &packet, &is_keyframe)) { |
| 255 | RTC_LOG(LS_ERROR) |
| 256 | << "Failed to encode DmaBuf frame with Jetson MMAPI AV1."; |
| 257 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 258 | } |
| 259 | } else { |
| 260 | webrtc::scoped_refptr<I420BufferInterface> frame_buffer = |
| 261 | input_frame.video_frame_buffer()->ToI420(); |
| 262 | if (!frame_buffer) { |
| 263 | RTC_LOG(LS_ERROR) << "Failed to convert frame to I420."; |
| 264 | return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE; |
| 265 | } |
| 266 | |
| 267 | RTC_DCHECK_EQ(configuration_.width, frame_buffer->width()); |
| 268 | RTC_DCHECK_EQ(configuration_.height, frame_buffer->height()); |
| 269 | |
| 270 | if (!encoder_.Encode(frame_buffer->DataY(), frame_buffer->StrideY(), |
| 271 | frame_buffer->DataU(), frame_buffer->StrideU(), |
| 272 | frame_buffer->DataV(), frame_buffer->StrideV(), |
| 273 | is_keyframe_needed, &packet, &is_keyframe)) { |
| 274 | RTC_LOG(LS_ERROR) |
| 275 | << "Failed to encode frame with Jetson MMAPI AV1 encoder."; |
| 276 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | if (packet.empty()) { |
| 281 | RTC_LOG(LS_WARNING) << "Jetson MMAPI AV1 encoder returned empty packet; " |
| 282 | "skipping output."; |
| 283 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 284 | } |
| 285 | |
| 286 | livekit::av1::NormalizeForRtp(&packet); |
| 287 | if (packet.empty()) { |
| 288 | RTC_LOG(LS_ERROR) << "Jetson MMAPI AV1 packet contained no transferable " |
| 289 | "OBUs after RTP normalization; skipping."; |
| 290 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 291 | } |
| 292 | |
| 293 | std::vector<uint8_t> sequence_header; |
| 294 | if (livekit::av1::ExtractSequenceHeaderObu(packet.data(), packet.size(), |
| 295 | &sequence_header)) { |
| 296 | cached_sequence_header_obu_ = std::move(sequence_header); |
| 297 | } |
| 298 | |
| 299 | const bool treat_as_keyframe = is_keyframe_needed || is_keyframe; |
| 300 | if (treat_as_keyframe) { |
| 301 | livekit::av1::EnsureSequenceHeaderOnKeyframe(&packet, |
| 302 | cached_sequence_header_obu_); |
| 303 | } |
| 304 | |
| 305 | if (!livekit::av1::IsWebRtcParseable(packet.data(), packet.size())) { |
| 306 | RTC_LOG(LS_ERROR) |
| 307 | << "Jetson MMAPI AV1 bitstream is not parseable by WebRTC; " |
| 308 | "dropping frame (size=" << packet.size() << ")."; |
| 309 | return WEBRTC_VIDEO_CODEC_NO_OUTPUT; |
| 310 | } |
| 311 | |
| 312 | DumpAv1PacketIfRequested(packet, treat_as_keyframe); |
| 313 | |
| 314 | if (treat_as_keyframe && |
| 315 | livekit::av1::HasSequenceHeaderObu(packet.data(), packet.size())) { |
| 316 | sent_decodable_keyframe_ = true; |
| 317 | configuration_.key_frame_request = false; |
| 318 | } else if (!sent_decodable_keyframe_) { |
| 319 | RTC_LOG(LS_WARNING) |
| 320 | << "Jetson MMAPI AV1 keyframe still missing sequence header OBU; " |
| 321 | "continuing to force keyframes."; |
| 322 | configuration_.key_frame_request = true; |
| 323 | } else if (is_keyframe_needed) { |
| 324 | configuration_.key_frame_request = false; |
| 325 | } |
| 326 | |
| 327 | return ProcessEncodedFrame(packet, input_frame, treat_as_keyframe); |
| 328 | } |
| 329 | |
| 330 | int32_t JetsonAV1EncoderImpl::ProcessEncodedFrame( |
| 331 | std::vector<uint8_t>& packet, |
| 332 | const ::webrtc::VideoFrame& input_frame, |
| 333 | bool is_keyframe) { |
| 334 | encoded_image_._encodedWidth = codec_.width; |
| 335 | encoded_image_._encodedHeight = codec_.height; |
| 336 | encoded_image_.SetRtpTimestamp(input_frame.rtp_timestamp()); |
| 337 | encoded_image_.SetSimulcastIndex(0); |
| 338 | encoded_image_.ntp_time_ms_ = input_frame.ntp_time_ms(); |
| 339 | encoded_image_.capture_time_ms_ = input_frame.render_time_ms(); |
| 340 | encoded_image_.rotation_ = input_frame.rotation(); |
| 341 | encoded_image_.content_type_ = VideoContentType::UNSPECIFIED; |
| 342 | encoded_image_.timing_.flags = VideoSendTiming::kInvalid; |
| 343 | encoded_image_._frameType = |
| 344 | is_keyframe ? VideoFrameType::kVideoFrameKey |
| 345 | : VideoFrameType::kVideoFrameDelta; |
| 346 | encoded_image_.SetColorSpace(input_frame.color_space()); |
| 347 | |
| 348 | encoded_image_.SetEncodedData( |
| 349 | EncodedImageBuffer::Create(packet.data(), packet.size())); |
| 350 | encoded_image_.set_size(packet.size()); |
| 351 | |
| 352 | encoded_image_.qp_ = -1; |
| 353 | |
| 354 | CodecSpecificInfo codecInfo; |
| 355 | codecInfo.codecSpecific = {}; |
| 356 | codecInfo.codecType = kVideoCodecAV1; |
| 357 | codecInfo.end_of_picture = true; |
| 358 | codecInfo.scalability_mode = ScalabilityMode::kL1T1; |
| 359 | |
| 360 | // Attach the AV1 dependency-descriptor metadata. The hardware encoder only |
| 361 | // produces an OBU bitstream, so we drive WebRTC's no-layering scalability |
| 362 | // controller to generate the GenericFrameInfo for every frame (and the |
| 363 | // FrameDependencyStructure on keyframes). This is required for the RTP layer |
| 364 | // to packetize/send AV1 and for the SFU to forward it; without it the encoder |
| 365 | // produces frames but no RTP packets are ever emitted. NextFrameConfig() is |
| 366 | // called exactly once per emitted frame (after all drop checks) so the |
| 367 | // dependency chain stays consistent with what is actually sent. |
| 368 | std::vector<ScalableVideoController::LayerFrameConfig> layer_frames = |
| 369 | svc_controller_.NextFrameConfig(/*restart=*/is_keyframe); |
| 370 | if (!layer_frames.empty()) { |
| 371 | const ScalableVideoController::LayerFrameConfig& layer_frame = |
| 372 | layer_frames.front(); |
| 373 | codecInfo.generic_frame_info = svc_controller_.OnEncodeDone(layer_frame); |
| 374 | if (layer_frame.IsKeyframe()) { |
| 375 | codecInfo.template_structure = svc_controller_.DependencyStructure(); |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | const auto result = |
| 380 | encoded_image_callback_->OnEncodedImage(encoded_image_, &codecInfo); |
| 381 | if (result.error != EncodedImageCallback::Result::OK) { |
| 382 | RTC_LOG(LS_ERROR) << "Encode m_encodedCompleteCallback failed " |
| 383 | << result.error; |
| 384 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 385 | } |
| 386 | return WEBRTC_VIDEO_CODEC_OK; |
| 387 | } |
| 388 | |
| 389 | VideoEncoder::EncoderInfo JetsonAV1EncoderImpl::GetEncoderInfo() const { |
| 390 | EncoderInfo info; |
| 391 | info.supports_native_handle = true; |
| 392 | info.implementation_name = "Jetson MMAPI AV1 Encoder"; |
| 393 | info.scaling_settings = VideoEncoder::ScalingSettings::kOff; |
| 394 | info.is_hardware_accelerated = true; |
| 395 | info.supports_simulcast = false; |
| 396 | info.preferred_pixel_formats = {VideoFrameBuffer::Type::kNative, |
| 397 | VideoFrameBuffer::Type::kI420}; |
| 398 | return info; |
| 399 | } |
| 400 | |
| 401 | void JetsonAV1EncoderImpl::SetRates(const RateControlParameters& parameters) { |
| 402 | if (!encoder_.IsInitialized()) { |
| 403 | RTC_LOG(LS_WARNING) << "SetRates() while uninitialized."; |
| 404 | return; |
| 405 | } |
| 406 | |
| 407 | if (parameters.framerate_fps < 1.0) { |
| 408 | RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps; |
| 409 | return; |
| 410 | } |
| 411 | |
| 412 | if (parameters.bitrate.get_sum_bps() == 0) { |
| 413 | configuration_.SetStreamState(false); |
| 414 | return; |
| 415 | } |
| 416 | |
| 417 | codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps); |
| 418 | codec_.maxBitrate = parameters.bitrate.GetSpatialLayerSum(0); |
| 419 | |
| 420 | configuration_.target_bps = parameters.bitrate.GetSpatialLayerSum(0); |
| 421 | configuration_.max_frame_rate = parameters.framerate_fps; |
| 422 | |
| 423 | encoder_.SetRates(codec_.maxFramerate, |
| 424 | static_cast<int>(configuration_.target_bps)); |
| 425 | |
| 426 | if (configuration_.target_bps) { |
| 427 | configuration_.SetStreamState(true); |
| 428 | } else { |
| 429 | configuration_.SetStreamState(false); |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | void JetsonAV1EncoderImpl::LayerConfig::SetStreamState(bool send_stream) { |
| 434 | if (send_stream && !sending) { |
| 435 | key_frame_request = true; |
| 436 | } |
| 437 | sending = send_stream; |
| 438 | } |
| 439 | |
| 440 | } // namespace webrtc |