BlueGit

ict rusty-teams

Files

rusty-teams / vendor / webrtc-sys / src / jetson / h264_encoder_impl.cpp

h264_encoder_impl.cpp

h264_encoder_impl.cpp 14.3 KiB Download Raw
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 "h264_encoder_impl.h"
18
19#include <algorithm>
20#include <atomic>
21#include <cstdio>
22#include <cstdlib>
23#include <filesystem>
24#include <fstream>
25#include <limits>
26#include <string>
27
28#include "absl/strings/match.h"
29#include "absl/types/optional.h"
30#include "api/video/i420_buffer.h"
31#include "api/video/video_codec_constants.h"
32#include "api/video_codecs/scalability_mode.h"
33#include "common_video/h264/h264_common.h"
34#include "common_video/libyuv/include/webrtc_libyuv.h"
35#include "livekit/dmabuf_video_frame_buffer.h"
36#include "modules/video_coding/include/video_codec_interface.h"
37#include "modules/video_coding/include/video_error_codes.h"
38#include "modules/video_coding/svc/create_scalability_structure.h"
39#include "modules/video_coding/utility/simulcast_rate_allocator.h"
40#include "modules/video_coding/utility/simulcast_utility.h"
41#include "rtc_base/checks.h"
42#include "rtc_base/logging.h"
43#include "system_wrappers/include/metrics.h"
44#include "third_party/libyuv/include/libyuv/convert.h"
45
46namespace webrtc {
47
48// Used by histograms. Values of entries should not be changed.
49enum H264EncoderImplEvent {
50 kH264EncoderEventInit = 0,
51 kH264EncoderEventError = 1,
52 kH264EncoderEventMax = 16,
53};
54
55JetsonH264EncoderImpl::JetsonH264EncoderImpl(const webrtc::Environment& env,
56 const SdpVideoFormat& format)
57 : env_(env),
58 encoder_(livekit::JetsonCodec::kH264),
59 packetization_mode_(
60 H264EncoderSettings::Parse(format).packetization_mode),
61 format_(format) {
62 auto it = format_.parameters.find("profile-level-id");
63 if (it != format_.parameters.end()) {
64 std::optional<webrtc::H264ProfileLevelId> profile_level_id =
65 webrtc::ParseH264ProfileLevelId(it->second.c_str());
66 if (profile_level_id.has_value()) {
67 profile_ = profile_level_id->profile;
68 level_ = profile_level_id->level;
69 }
70 }
71}
72
73JetsonH264EncoderImpl::~JetsonH264EncoderImpl() {
74 Release();
75}
76
77void JetsonH264EncoderImpl::ReportInit() {
78 if (has_reported_init_) {
79 return;
80 }
81 RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H264EncoderImpl.Event",
82 kH264EncoderEventInit, kH264EncoderEventMax);
83 has_reported_init_ = true;
84}
85
86void JetsonH264EncoderImpl::ReportError() {
87 if (has_reported_error_) {
88 return;
89 }
90 RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.H264EncoderImpl.Event",
91 kH264EncoderEventError, kH264EncoderEventMax);
92 has_reported_error_ = true;
93}
94
95int32_t JetsonH264EncoderImpl::InitEncode(
96 const VideoCodec* inst,
97 const VideoEncoder::Settings& settings) {
98 (void)settings;
99
100 if (!inst || inst->codecType != kVideoCodecH264) {
101 ReportError();
102 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
103 }
104 if (inst->maxFramerate == 0) {
105 ReportError();
106 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
107 }
108 if (inst->width < 1 || inst->height < 1) {
109 ReportError();
110 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
111 }
112
113 int32_t release_ret = Release();
114 if (release_ret != WEBRTC_VIDEO_CODEC_OK) {
115 ReportError();
116 return release_ret;
117 }
118
119 codec_ = *inst;
120
121 if (codec_.numberOfSimulcastStreams == 0) {
122 codec_.simulcastStream[0].width = codec_.width;
123 codec_.simulcastStream[0].height = codec_.height;
124 }
125
126 const size_t new_capacity =
127 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
128 encoded_image_.SetEncodedData(EncodedImageBuffer::Create(new_capacity));
129 encoded_image_._encodedWidth = codec_.width;
130 encoded_image_._encodedHeight = codec_.height;
131 encoded_image_.set_size(0);
132
133 configuration_.sending = false;
134 configuration_.frame_dropping_on = codec_.GetFrameDropEnabled();
135 configuration_.key_frame_interval = codec_.H264()->keyFrameInterval;
136
137 configuration_.width = codec_.width;
138 configuration_.height = codec_.height;
139
140 configuration_.max_frame_rate = codec_.maxFramerate;
141 configuration_.target_bps = codec_.startBitrate * 1000;
142 configuration_.max_bps = codec_.maxBitrate * 1000;
143
144 if (!encoder_.IsInitialized()) {
145 // WebRTC will often leave keyFrameInterval at a very large default (e.g.
146 // 3000 frames). On Jetson MMAPI that can translate into "no usable video"
147 // for new subscribers until an IDR happens (unless FORCE_KEY_FRAME works
148 // reliably). Clamp to a sane WebRTC-friendly cadence.
149 //
150 // Default to ~2 seconds between keyframes, and cap at 10 seconds.
151 int key_frame_interval = codec_.H264()->keyFrameInterval;
152 const int fps = std::max<int>(1, static_cast<int>(codec_.maxFramerate));
153 const int default_interval = fps * 2;
154 const int max_interval = fps * 10;
155 if (key_frame_interval <= 0 || key_frame_interval > max_interval) {
156 key_frame_interval = default_interval;
157 }
158 if (!encoder_.Initialize(codec_.width, codec_.height, codec_.maxFramerate,
159 codec_.startBitrate * 1000, key_frame_interval)) {
160 RTC_LOG(LS_ERROR) << "Failed to initialize Jetson MMAPI encoder.";
161 ReportError();
162 return WEBRTC_VIDEO_CODEC_ERROR;
163 }
164 }
165
166 ReportInit();
167
168 SimulcastRateAllocator init_allocator(env_, codec_);
169 VideoBitrateAllocation allocation =
170 init_allocator.Allocate(VideoBitrateAllocationParameters(
171 DataRate::KilobitsPerSec(codec_.startBitrate), codec_.maxFramerate));
172 SetRates(RateControlParameters(allocation, codec_.maxFramerate));
173
174 return WEBRTC_VIDEO_CODEC_OK;
175}
176
177int32_t JetsonH264EncoderImpl::RegisterEncodeCompleteCallback(
178 EncodedImageCallback* callback) {
179 encoded_image_callback_ = callback;
180 return WEBRTC_VIDEO_CODEC_OK;
181}
182
183int32_t JetsonH264EncoderImpl::Release() {
184 if (encoder_.IsInitialized()) {
185 encoder_.Destroy();
186 }
187 return WEBRTC_VIDEO_CODEC_OK;
188}
189
190int32_t JetsonH264EncoderImpl::Encode(
191 const VideoFrame& input_frame,
192 const std::vector<VideoFrameType>* frame_types) {
193 static std::atomic<bool> logged_empty(false);
194
195 if (!encoder_.IsInitialized()) {
196 ReportError();
197 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
198 }
199 if (!encoded_image_callback_) {
200 RTC_LOG(LS_WARNING)
201 << "InitEncode() has been called, but a callback function "
202 "has not been set with RegisterEncodeCompleteCallback()";
203 ReportError();
204 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
205 }
206
207 bool is_keyframe_needed = false;
208 if (configuration_.key_frame_request && configuration_.sending) {
209 is_keyframe_needed = true;
210 }
211 if (frame_types && !frame_types->empty()) {
212 if ((*frame_types)[0] == VideoFrameType::kVideoFrameKey) {
213 is_keyframe_needed = true;
214 }
215 if ((*frame_types)[0] == VideoFrameType::kEmptyFrame) {
216 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
217 }
218 }
219
220 if (!configuration_.sending) {
221 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
222 }
223
224 std::vector<uint8_t> packet;
225 bool is_keyframe = false;
226
227 // Check for DmaBuf zero-copy path first.
228 auto* dmabuf = livekit::DmaBufVideoFrameBuffer::FromNative(
229 input_frame.video_frame_buffer().get());
230 if (dmabuf) {
231 if (!encoder_.EncodeDmaBuf(dmabuf->dmabuf_fd(), is_keyframe_needed,
232 &packet, &is_keyframe)) {
233 RTC_LOG(LS_ERROR) << "Failed to encode DmaBuf frame with Jetson MMAPI.";
234 return WEBRTC_VIDEO_CODEC_ERROR;
235 }
236 } else {
237 // Standard I420 path.
238 webrtc::scoped_refptr<I420BufferInterface> frame_buffer =
239 input_frame.video_frame_buffer()->ToI420();
240 if (!frame_buffer) {
241 RTC_LOG(LS_ERROR) << "Failed to convert frame to I420.";
242 return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
243 }
244
245 RTC_DCHECK_EQ(configuration_.width, frame_buffer->width());
246 RTC_DCHECK_EQ(configuration_.height, frame_buffer->height());
247
248 if (!encoder_.Encode(frame_buffer->DataY(), frame_buffer->StrideY(),
249 frame_buffer->DataU(), frame_buffer->StrideU(),
250 frame_buffer->DataV(), frame_buffer->StrideV(),
251 is_keyframe_needed, &packet, &is_keyframe)) {
252 RTC_LOG(LS_ERROR) << "Failed to encode frame with Jetson MMAPI encoder.";
253 return WEBRTC_VIDEO_CODEC_ERROR;
254 }
255 }
256 if (packet.empty()) {
257 if (!logged_empty.exchange(true)) {
258 RTC_LOG(LS_WARNING)
259 << "Jetson MMAPI encoder returned empty packet; "
260 "skipping output.";
261 }
262 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
263 }
264
265 if (is_keyframe_needed) {
266 configuration_.key_frame_request = false;
267 }
268
269 return ProcessEncodedFrame(packet, input_frame, is_keyframe);
270}
271
272int32_t JetsonH264EncoderImpl::ProcessEncodedFrame(
273 std::vector<uint8_t>& packet,
274 const ::webrtc::VideoFrame& input_frame,
275 bool is_keyframe) {
276 static std::atomic<bool> dumped(false);
277 static std::atomic<bool> logged_env(false);
278 if (!dumped.load(std::memory_order_relaxed)) {
279 const char* dump_path = std::getenv("LK_DUMP_H264");
280 if (!dump_path || dump_path[0] == '\0') {
281 if (!logged_env.exchange(true)) {
282 RTC_LOG(LS_INFO)
283 << "LK_DUMP_H264 not set; skipping H264 dump.";
284 }
285 } else if (packet.empty()) {
286 if (!logged_env.exchange(true)) {
287 RTC_LOG(LS_WARNING)
288 << "LK_DUMP_H264 set to " << dump_path
289 << " but encoded packet is empty.";
290 std::fprintf(stderr,
291 "LK_DUMP_H264 set to %s but packet is empty\n",
292 dump_path);
293 std::fflush(stderr);
294 }
295 } else {
296 std::error_code ec;
297 std::filesystem::path path(dump_path);
298 if (path.has_parent_path()) {
299 std::filesystem::create_directories(path.parent_path(), ec);
300 }
301 std::ofstream out(dump_path, std::ios::binary);
302 if (out.good()) {
303 out.write(reinterpret_cast<const char*>(packet.data()),
304 static_cast<std::streamsize>(packet.size()));
305 RTC_LOG(LS_INFO) << "Dumped H264 access unit to " << dump_path
306 << " (bytes=" << packet.size()
307 << ", keyframe=" << is_keyframe << ")";
308 std::fprintf(stderr,
309 "Dumped H264 access unit to %s (bytes=%zu, keyframe=%d)\n",
310 dump_path, packet.size(), is_keyframe ? 1 : 0);
311 std::fflush(stderr);
312 dumped.store(true, std::memory_order_relaxed);
313 } else {
314 RTC_LOG(LS_WARNING) << "Failed to open LK_DUMP_H264 path: "
315 << dump_path;
316 std::fprintf(stderr,
317 "Failed to open LK_DUMP_H264 path: %s\n",
318 dump_path);
319 std::fflush(stderr);
320 }
321 logged_env.store(true, std::memory_order_relaxed);
322 }
323 }
324 encoded_image_._encodedWidth = codec_.width;
325 encoded_image_._encodedHeight = codec_.height;
326 encoded_image_.SetRtpTimestamp(input_frame.rtp_timestamp());
327 encoded_image_.SetSimulcastIndex(0);
328 encoded_image_.ntp_time_ms_ = input_frame.ntp_time_ms();
329 encoded_image_.capture_time_ms_ = input_frame.render_time_ms();
330 encoded_image_.rotation_ = input_frame.rotation();
331 encoded_image_.content_type_ = VideoContentType::UNSPECIFIED;
332 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
333 encoded_image_._frameType =
334 is_keyframe ? VideoFrameType::kVideoFrameKey
335 : VideoFrameType::kVideoFrameDelta;
336 encoded_image_.SetColorSpace(input_frame.color_space());
337
338 std::vector<H264::NaluIndex> nalu_indices = H264::FindNaluIndices(packet);
339 for (uint32_t i = 0; i < nalu_indices.size(); i++) {
340 const H264::NaluType nalu_type =
341 H264::ParseNaluType(packet[nalu_indices[i].payload_start_offset]);
342 if (nalu_type == H264::kIdr) {
343 encoded_image_._frameType = VideoFrameType::kVideoFrameKey;
344 break;
345 }
346 }
347
348 encoded_image_.SetEncodedData(
349 EncodedImageBuffer::Create(packet.data(), packet.size()));
350 encoded_image_.set_size(packet.size());
351
352 h264_bitstream_parser_.ParseBitstream(encoded_image_);
353 encoded_image_.qp_ = h264_bitstream_parser_.GetLastSliceQp().value_or(-1);
354
355 CodecSpecificInfo codecInfo;
356 codecInfo.codecType = kVideoCodecH264;
357 codecInfo.codecSpecific.H264.packetization_mode =
358 H264PacketizationMode::NonInterleaved;
359
360 const auto result =
361 encoded_image_callback_->OnEncodedImage(encoded_image_, &codecInfo);
362 if (result.error != EncodedImageCallback::Result::OK) {
363 RTC_LOG(LS_ERROR) << "Encode m_encodedCompleteCallback failed "
364 << result.error;
365 return WEBRTC_VIDEO_CODEC_ERROR;
366 }
367 return WEBRTC_VIDEO_CODEC_OK;
368}
369
370VideoEncoder::EncoderInfo JetsonH264EncoderImpl::GetEncoderInfo() const {
371 EncoderInfo info;
372 info.supports_native_handle = true;
373 info.implementation_name = "Jetson MMAPI H264 Encoder";
374 info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
375 info.is_hardware_accelerated = true;
376 info.supports_simulcast = false;
377 info.preferred_pixel_formats = {VideoFrameBuffer::Type::kNative,
378 VideoFrameBuffer::Type::kI420};
379 return info;
380}
381
382void JetsonH264EncoderImpl::SetRates(
383 const RateControlParameters& parameters) {
384 if (!encoder_.IsInitialized()) {
385 RTC_LOG(LS_WARNING) << "SetRates() while uninitialized.";
386 return;
387 }
388
389 if (parameters.framerate_fps < 1.0) {
390 RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps;
391 return;
392 }
393
394 if (parameters.bitrate.get_sum_bps() == 0) {
395 configuration_.SetStreamState(false);
396 return;
397 }
398
399 codec_.maxFramerate = static_cast<uint32_t>(parameters.framerate_fps);
400 codec_.maxBitrate = parameters.bitrate.GetSpatialLayerSum(0);
401
402 configuration_.target_bps = parameters.bitrate.GetSpatialLayerSum(0);
403 configuration_.max_frame_rate = parameters.framerate_fps;
404
405 encoder_.SetRates(codec_.maxFramerate,
406 static_cast<int>(configuration_.target_bps));
407
408 if (configuration_.target_bps) {
409 configuration_.SetStreamState(true);
410 } else {
411 configuration_.SetStreamState(false);
412 }
413}
414
415void JetsonH264EncoderImpl::LayerConfig::SetStreamState(bool send_stream) {
416 if (send_stream && !sending) {
417 key_frame_request = true;
418 }
419 sending = send_stream;
420}
421
422} // namespace webrtc