| 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 "jetson_mmapi_encoder.h" |
| 18 | |
| 19 | #include "jetson_plane_layout.h" |
| 20 | #include "jetson_runtime_loader.h" |
| 21 | |
| 22 | #include <cerrno> |
| 23 | #include <linux/v4l2-controls.h> |
| 24 | #include <sys/stat.h> |
| 25 | #include <unistd.h> |
| 26 | |
| 27 | #include <algorithm> |
| 28 | #include <atomic> |
| 29 | #include <chrono> |
| 30 | #include <cstdio> |
| 31 | #include <cstdlib> |
| 32 | #include <cstring> |
| 33 | #include <filesystem> |
| 34 | #include <fstream> |
| 35 | #include <memory> |
| 36 | #include <thread> |
| 37 | #include <unordered_map> |
| 38 | |
| 39 | #include "NvBufSurface.h" |
| 40 | #include "NvBuffer.h" |
| 41 | #include "NvVideoEncoder.h" |
| 42 | #include "NvUtils.h" |
| 43 | #include "rtc_base/logging.h" |
| 44 | |
| 45 | namespace { |
| 46 | |
| 47 | constexpr int kDefaultOutputBufferCount = 4; |
| 48 | constexpr int kDefaultCaptureBufferCount = 4; |
| 49 | constexpr int kMinBitstreamBufferSize = 1024 * 1024; |
| 50 | |
| 51 | bool DeviceExists(const char* path) { |
| 52 | struct stat st = {}; |
| 53 | return stat(path, &st) == 0; |
| 54 | } |
| 55 | |
| 56 | void CopyPlane(uint8_t* dst, |
| 57 | int dst_stride, |
| 58 | const uint8_t* src, |
| 59 | int src_stride, |
| 60 | int width, |
| 61 | int height) { |
| 62 | for (int y = 0; y < height; ++y) { |
| 63 | std::memcpy(dst + y * dst_stride, src + y * src_stride, width); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Try to read the true per-plane pitch/height for an NvBuffer plane FD. |
| 68 | // This avoids relying on NvBufferGetParams/nvbuf_utils.h (not present on all |
| 69 | // JetPack images), and is more reliable than NvBufferPlane::fmt fields in MMAP |
| 70 | // mode. |
| 71 | bool GetPitchAndHeightFromNvBufSurfaceFd(int dmabuf_fd, |
| 72 | int plane_index, |
| 73 | uint32_t* out_pitch, |
| 74 | uint32_t* out_height, |
| 75 | uint32_t* out_num_planes) { |
| 76 | if (out_pitch) *out_pitch = 0; |
| 77 | if (out_height) *out_height = 0; |
| 78 | if (out_num_planes) *out_num_planes = 0; |
| 79 | if (dmabuf_fd < 0) { |
| 80 | return false; |
| 81 | } |
| 82 | if (plane_index < 0) { |
| 83 | return false; |
| 84 | } |
| 85 | |
| 86 | NvBufSurface* surface = nullptr; |
| 87 | int ret = NvBufSurfaceFromFd(dmabuf_fd, reinterpret_cast<void**>(&surface)); |
| 88 | if (ret != 0 || !surface) { |
| 89 | return false; |
| 90 | } |
| 91 | // Most MMAPI buffers are not batched; guard anyway. |
| 92 | if (surface->batchSize < 1) { |
| 93 | return false; |
| 94 | } |
| 95 | |
| 96 | const NvBufSurfaceParams& p = surface->surfaceList[0]; |
| 97 | if (out_num_planes) { |
| 98 | *out_num_planes = p.planeParams.num_planes; |
| 99 | } |
| 100 | if (p.planeParams.num_planes < 1) { |
| 101 | return false; |
| 102 | } |
| 103 | if (plane_index >= static_cast<int>(p.planeParams.num_planes)) { |
| 104 | return false; |
| 105 | } |
| 106 | |
| 107 | const uint32_t pitch = p.planeParams.pitch[plane_index]; |
| 108 | const uint32_t height = p.planeParams.height[plane_index]; |
| 109 | if (out_pitch) *out_pitch = pitch; |
| 110 | if (out_height) *out_height = height; |
| 111 | return pitch > 0 && height > 0; |
| 112 | } |
| 113 | |
| 114 | #ifndef V4L2_PIX_FMT_H265 |
| 115 | #define V4L2_PIX_FMT_H265 v4l2_fourcc('H', '2', '6', '5') |
| 116 | #endif |
| 117 | |
| 118 | #ifndef V4L2_PIX_FMT_AV1 |
| 119 | #define V4L2_PIX_FMT_AV1 v4l2_fourcc('A', 'V', '1', '0') |
| 120 | #endif |
| 121 | |
| 122 | #ifndef V4L2_CID_MPEG_VIDEOENC_AV1_HEADERS_WITH_FRAME |
| 123 | #define V4L2_CID_MPEG_VIDEOENC_AV1_HEADERS_WITH_FRAME (V4L2_CID_MPEG_BASE + 569) |
| 124 | #endif |
| 125 | |
| 126 | #ifndef V4L2_CID_MPEG_VIDEOENC_FORCE_INTRA_FRAME |
| 127 | #define V4L2_CID_MPEG_VIDEOENC_FORCE_INTRA_FRAME (V4L2_CID_MPEG_BASE + 566) |
| 128 | #endif |
| 129 | |
| 130 | #ifndef V4L2_CID_MPEG_VIDEOENC_FORCE_IDR_FRAME |
| 131 | #define V4L2_CID_MPEG_VIDEOENC_FORCE_IDR_FRAME (V4L2_CID_MPEG_BASE + 567) |
| 132 | #endif |
| 133 | |
| 134 | #ifndef V4L2_CID_MPEG_VIDEOENC_AV1_ENABLE_TILE_GROUPS |
| 135 | #define V4L2_CID_MPEG_VIDEOENC_AV1_ENABLE_TILE_GROUPS (V4L2_CID_MPEG_BASE + 598) |
| 136 | #endif |
| 137 | |
| 138 | bool SetEncoderControl(NvVideoEncoder* encoder, uint32_t id, int32_t value) { |
| 139 | v4l2_ext_control control = {}; |
| 140 | control.id = id; |
| 141 | control.value = value; |
| 142 | |
| 143 | v4l2_ext_controls controls = {}; |
| 144 | controls.count = 1; |
| 145 | controls.controls = &control; |
| 146 | return encoder->setExtControls(controls) == 0; |
| 147 | } |
| 148 | |
| 149 | } // namespace |
| 150 | |
| 151 | namespace livekit { |
| 152 | |
| 153 | JetsonMmapiEncoder::JetsonMmapiEncoder(JetsonCodec codec) : codec_(codec) {} |
| 154 | |
| 155 | JetsonMmapiEncoder::~JetsonMmapiEncoder() { |
| 156 | Destroy(); |
| 157 | } |
| 158 | |
| 159 | bool JetsonMmapiEncoder::IsSupported() { |
| 160 | return IsCodecSupported(JetsonCodec::kH264) || |
| 161 | IsCodecSupported(JetsonCodec::kH265) || |
| 162 | IsCodecSupported(JetsonCodec::kAV1); |
| 163 | } |
| 164 | |
| 165 | bool JetsonMmapiEncoder::IsCodecSupported(JetsonCodec codec) { |
| 166 | auto device = FindEncoderDevice(); |
| 167 | if (!device.has_value()) { |
| 168 | return false; |
| 169 | } |
| 170 | // The MMAPI/v4l2 symbols below are lazily bound and abort the process if |
| 171 | // invoked while the Jetson userspace libraries are absent, so the library |
| 172 | // probe must pass before any of them is called. |
| 173 | if (!lk_jetson_runtime_libs_available()) { |
| 174 | RTC_LOG(LS_WARNING) |
| 175 | << "Jetson encoder device exists, but the Jetson multimedia " |
| 176 | "libraries (libnvbufsurface/libv4l2) could not be loaded."; |
| 177 | return false; |
| 178 | } |
| 179 | std::unique_ptr<NvVideoEncoder> encoder( |
| 180 | NvVideoEncoder::createVideoEncoder("livekit-encoder")); |
| 181 | if (!encoder) { |
| 182 | return false; |
| 183 | } |
| 184 | const uint32_t pixfmt = CodecToV4L2PixFmt(codec); |
| 185 | if (encoder->setCapturePlaneFormat(pixfmt, 64, 64, |
| 186 | kMinBitstreamBufferSize) < 0) { |
| 187 | const uint32_t fallback_pixfmt = CodecToV4L2FallbackPixFmt(codec); |
| 188 | if (fallback_pixfmt == pixfmt || |
| 189 | encoder->setCapturePlaneFormat(fallback_pixfmt, 64, 64, |
| 190 | kMinBitstreamBufferSize) < 0) { |
| 191 | return false; |
| 192 | } |
| 193 | } |
| 194 | return true; |
| 195 | } |
| 196 | |
| 197 | std::optional<std::string> JetsonMmapiEncoder::FindEncoderDevice() { |
| 198 | if (DeviceExists("/dev/nvhost-msenc")) { |
| 199 | RTC_LOG(LS_INFO) << "Jetson MMAPI encoder device: /dev/nvhost-msenc"; |
| 200 | return std::string("/dev/nvhost-msenc"); |
| 201 | } |
| 202 | if (DeviceExists("/dev/v4l2-nvenc")) { |
| 203 | RTC_LOG(LS_INFO) << "Jetson MMAPI encoder device: /dev/v4l2-nvenc"; |
| 204 | return std::string("/dev/v4l2-nvenc"); |
| 205 | } |
| 206 | RTC_LOG(LS_WARNING) << "Jetson MMAPI encoder device not found."; |
| 207 | return std::nullopt; |
| 208 | } |
| 209 | |
| 210 | uint32_t JetsonMmapiEncoder::CodecToV4L2PixFmt(JetsonCodec codec) { |
| 211 | switch (codec) { |
| 212 | case JetsonCodec::kH264: |
| 213 | return V4L2_PIX_FMT_H264; |
| 214 | case JetsonCodec::kH265: |
| 215 | return V4L2_PIX_FMT_HEVC; |
| 216 | case JetsonCodec::kAV1: |
| 217 | return V4L2_PIX_FMT_AV1; |
| 218 | } |
| 219 | return V4L2_PIX_FMT_H264; |
| 220 | } |
| 221 | |
| 222 | uint32_t JetsonMmapiEncoder::CodecToV4L2FallbackPixFmt(JetsonCodec codec) { |
| 223 | if (codec == JetsonCodec::kH265) { |
| 224 | return V4L2_PIX_FMT_H265; |
| 225 | } |
| 226 | return CodecToV4L2PixFmt(codec); |
| 227 | } |
| 228 | |
| 229 | bool JetsonMmapiEncoder::Initialize(int width, |
| 230 | int height, |
| 231 | int framerate, |
| 232 | int bitrate_bps, |
| 233 | int keyframe_interval) { |
| 234 | if (initialized_) { |
| 235 | return true; |
| 236 | } |
| 237 | |
| 238 | width_ = width; |
| 239 | height_ = height; |
| 240 | framerate_ = framerate; |
| 241 | bitrate_bps_ = bitrate_bps; |
| 242 | keyframe_interval_ = keyframe_interval; |
| 243 | |
| 244 | auto device = FindEncoderDevice(); |
| 245 | if (!device.has_value()) { |
| 246 | RTC_LOG(LS_WARNING) << "Jetson MMAPI encoder device not found."; |
| 247 | return false; |
| 248 | } |
| 249 | |
| 250 | // Re-checked here rather than relying on the factory's IsSupported() gate: |
| 251 | // this is a public entry point, and an unresolved lazily-bound symbol |
| 252 | // aborts the process instead of returning an error. |
| 253 | if (!lk_jetson_runtime_libs_available()) { |
| 254 | RTC_LOG(LS_WARNING) |
| 255 | << "Jetson encoder device exists, but the Jetson multimedia " |
| 256 | "libraries (libnvbufsurface/libv4l2) could not be loaded."; |
| 257 | return false; |
| 258 | } |
| 259 | |
| 260 | if (!CreateEncoder()) { |
| 261 | return false; |
| 262 | } |
| 263 | |
| 264 | if (!ConfigureEncoder()) { |
| 265 | return false; |
| 266 | } |
| 267 | |
| 268 | if (!SetupPlanes()) { |
| 269 | return false; |
| 270 | } |
| 271 | |
| 272 | if (!QueueCaptureBuffers()) { |
| 273 | return false; |
| 274 | } |
| 275 | |
| 276 | if (!StartStreaming()) { |
| 277 | return false; |
| 278 | } |
| 279 | |
| 280 | initialized_ = true; |
| 281 | RTC_LOG(LS_INFO) << "Jetson MMAPI encoder initialized: " << width_ << "x" |
| 282 | << height_ << " @ " << framerate_ << " fps"; |
| 283 | return true; |
| 284 | } |
| 285 | |
| 286 | void JetsonMmapiEncoder::Destroy() { |
| 287 | StopStreaming(); |
| 288 | if (encoder_) { |
| 289 | delete encoder_; |
| 290 | encoder_ = nullptr; |
| 291 | } |
| 292 | initialized_ = false; |
| 293 | dmabuf_meta_cached_ = false; |
| 294 | dmabuf_planes_setup_ = false; |
| 295 | use_dmabuf_input_ = false; |
| 296 | mmap_sync_supported_ = true; |
| 297 | next_output_index_ = 0; |
| 298 | } |
| 299 | |
| 300 | bool JetsonMmapiEncoder::IsInitialized() const { |
| 301 | return initialized_; |
| 302 | } |
| 303 | |
| 304 | bool JetsonMmapiEncoder::Encode(const uint8_t* src_y, |
| 305 | int stride_y, |
| 306 | const uint8_t* src_u, |
| 307 | int stride_u, |
| 308 | const uint8_t* src_v, |
| 309 | int stride_v, |
| 310 | bool force_keyframe, |
| 311 | std::vector<uint8_t>* encoded, |
| 312 | bool* is_keyframe) { |
| 313 | if (!initialized_ || !encoder_) { |
| 314 | return false; |
| 315 | } |
| 316 | |
| 317 | if (force_keyframe && !ForceKeyframe()) { |
| 318 | RTC_LOG(LS_WARNING) << "Failed to request keyframe."; |
| 319 | } |
| 320 | |
| 321 | if (!QueueOutputBuffer(src_y, stride_y, src_u, stride_u, src_v, stride_v)) { |
| 322 | return false; |
| 323 | } |
| 324 | |
| 325 | if (!DequeueCaptureBuffer(encoded, is_keyframe)) { |
| 326 | return false; |
| 327 | } |
| 328 | |
| 329 | if (!DequeueOutputBuffer()) { |
| 330 | return false; |
| 331 | } |
| 332 | |
| 333 | return true; |
| 334 | } |
| 335 | |
| 336 | bool JetsonMmapiEncoder::EncodeNV12(const uint8_t* src_y, |
| 337 | int stride_y, |
| 338 | const uint8_t* src_uv, |
| 339 | int stride_uv, |
| 340 | bool force_keyframe, |
| 341 | std::vector<uint8_t>* encoded, |
| 342 | bool* is_keyframe) { |
| 343 | if (!initialized_ || !encoder_) { |
| 344 | return false; |
| 345 | } |
| 346 | |
| 347 | if (force_keyframe && !ForceKeyframe()) { |
| 348 | RTC_LOG(LS_WARNING) << "Failed to request keyframe."; |
| 349 | } |
| 350 | |
| 351 | if (!QueueOutputBufferNV12(src_y, stride_y, src_uv, stride_uv)) { |
| 352 | return false; |
| 353 | } |
| 354 | |
| 355 | if (!DequeueCaptureBuffer(encoded, is_keyframe)) { |
| 356 | return false; |
| 357 | } |
| 358 | |
| 359 | if (!DequeueOutputBuffer()) { |
| 360 | return false; |
| 361 | } |
| 362 | |
| 363 | return true; |
| 364 | } |
| 365 | |
| 366 | void JetsonMmapiEncoder::SetRates(int framerate, int bitrate_bps) { |
| 367 | framerate_ = framerate; |
| 368 | bitrate_bps_ = bitrate_bps; |
| 369 | if (!encoder_) { |
| 370 | return; |
| 371 | } |
| 372 | encoder_->setFrameRate(framerate_, 1); |
| 373 | encoder_->setBitrate(bitrate_bps_); |
| 374 | } |
| 375 | |
| 376 | void JetsonMmapiEncoder::SetKeyframeInterval(int keyframe_interval) { |
| 377 | keyframe_interval_ = keyframe_interval; |
| 378 | if (!encoder_) { |
| 379 | return; |
| 380 | } |
| 381 | if (codec_ != JetsonCodec::kAV1) { |
| 382 | encoder_->setIDRInterval(keyframe_interval_); |
| 383 | } |
| 384 | encoder_->setIFrameInterval(keyframe_interval_); |
| 385 | } |
| 386 | |
| 387 | bool JetsonMmapiEncoder::CreateEncoder() { |
| 388 | encoder_ = NvVideoEncoder::createVideoEncoder("livekit-encoder"); |
| 389 | if (!encoder_) { |
| 390 | RTC_LOG(LS_ERROR) << "Failed to create NvVideoEncoder."; |
| 391 | return false; |
| 392 | } |
| 393 | return true; |
| 394 | } |
| 395 | |
| 396 | void JetsonMmapiEncoder::ConfigureAv1HeadersWithFrame() { |
| 397 | // WebRTC expects raw low-overhead OBUs. NVIDIA documents this control as |
| 398 | // after both plane formats, but Jetson AV1 applies it before the output |
| 399 | // format is set; otherwise IVF headers can still be attached. |
| 400 | if (!SetEncoderControl(encoder_, |
| 401 | V4L2_CID_MPEG_VIDEOENC_AV1_HEADERS_WITH_FRAME, 0)) { |
| 402 | RTC_LOG(LS_WARNING) |
| 403 | << "Failed to disable AV1 IVF headers-with-frame on Jetson encoder; " |
| 404 | "using driver default."; |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | bool JetsonMmapiEncoder::ConfigureAv1Encoder() { |
| 409 | #ifdef V4L2_CID_MPEG_VIDEOENC_AV1_TILE_CONFIGURATION |
| 410 | v4l2_enc_av1_tile_config tile_config = {}; |
| 411 | tile_config.bEnableTile = 0; |
| 412 | tile_config.nLog2RowTiles = 0; |
| 413 | tile_config.nLog2ColTiles = 0; |
| 414 | if (encoder_->enableAV1Tile(tile_config) < 0) { |
| 415 | RTC_LOG(LS_WARNING) |
| 416 | << "Failed to configure AV1 single-tile mode; using driver default."; |
| 417 | } |
| 418 | #endif |
| 419 | |
| 420 | // v1 intentionally stays single-tile and does not emit tile groups. Keep the |
| 421 | // tile-group control best-effort because older JetPack drivers may not know |
| 422 | // the AV1 extension even when compiling with newer headers. |
| 423 | if (!SetEncoderControl(encoder_, |
| 424 | V4L2_CID_MPEG_VIDEOENC_AV1_ENABLE_TILE_GROUPS, 0)) { |
| 425 | RTC_LOG(LS_WARNING) |
| 426 | << "Failed to disable AV1 tile groups; using driver default."; |
| 427 | } |
| 428 | |
| 429 | return true; |
| 430 | } |
| 431 | |
| 432 | bool JetsonMmapiEncoder::ConfigureEncoder() { |
| 433 | const uint32_t codec_pixfmt = CodecToV4L2PixFmt(codec_); |
| 434 | const uint32_t bitstream_size = |
| 435 | std::max(kMinBitstreamBufferSize, width_ * height_); |
| 436 | |
| 437 | // Set capture plane (encoded bitstream) first so the driver knows codec. |
| 438 | int ret = encoder_->setCapturePlaneFormat(codec_pixfmt, width_, height_, |
| 439 | bitstream_size); |
| 440 | if (ret < 0) { |
| 441 | const uint32_t fallback_pixfmt = CodecToV4L2FallbackPixFmt(codec_); |
| 442 | int ret_fallback = ret; |
| 443 | if (fallback_pixfmt != codec_pixfmt) { |
| 444 | ret_fallback = encoder_->setCapturePlaneFormat( |
| 445 | fallback_pixfmt, width_, height_, bitstream_size); |
| 446 | } |
| 447 | if (fallback_pixfmt == codec_pixfmt || ret_fallback < 0) { |
| 448 | RTC_LOG(LS_ERROR) << "Failed to set capture plane format."; |
| 449 | return false; |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | if (codec_ == JetsonCodec::kAV1) { |
| 454 | ConfigureAv1HeadersWithFrame(); |
| 455 | } |
| 456 | |
| 457 | if (codec_ == JetsonCodec::kAV1) { |
| 458 | // Argus supplies NV12 DMA buffers. Prefer NV12 for AV1 up front so the |
| 459 | // DMABUF path does not change the output format after AV1 controls run. |
| 460 | output_is_nv12_ = true; |
| 461 | ret = encoder_->setOutputPlaneFormat(V4L2_PIX_FMT_NV12M, width_, height_); |
| 462 | if (ret < 0) { |
| 463 | ret = encoder_->setOutputPlaneFormat(V4L2_PIX_FMT_YUV420M, width_, |
| 464 | height_); |
| 465 | if (ret < 0) { |
| 466 | RTC_LOG(LS_ERROR) << "Failed to set AV1 output plane format."; |
| 467 | return false; |
| 468 | } |
| 469 | output_is_nv12_ = false; |
| 470 | } |
| 471 | } else { |
| 472 | // Prefer planar YUV420 (I420-style) for Jetson end-to-end. |
| 473 | // If that fails, fall back to NV12M. The I420 input path can still be used |
| 474 | // with NV12 by interleaving U/V into UV in QueueOutputBuffer(). |
| 475 | output_is_nv12_ = false; |
| 476 | ret = encoder_->setOutputPlaneFormat(V4L2_PIX_FMT_YUV420M, width_, |
| 477 | height_); |
| 478 | if (ret < 0) { |
| 479 | ret = encoder_->setOutputPlaneFormat(V4L2_PIX_FMT_NV12M, width_, |
| 480 | height_); |
| 481 | if (ret < 0) { |
| 482 | RTC_LOG(LS_ERROR) << "Failed to set output plane format."; |
| 483 | return false; |
| 484 | } |
| 485 | output_is_nv12_ = true; |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | if (codec_ == JetsonCodec::kAV1 && !ConfigureAv1Encoder()) { |
| 490 | return false; |
| 491 | } |
| 492 | |
| 493 | // These controls must be applied after both plane formats are set and before |
| 494 | // either plane requests buffers. Keep them best-effort so older JetPack/MMAPI |
| 495 | // versions can still encode if one low-latency knob is unavailable. |
| 496 | encoder_->setMaxPerfMode(1); |
| 497 | encoder_->setHWPresetType(V4L2_ENC_HW_PRESET_ULTRAFAST); |
| 498 | encoder_->setNumBFrames(0); |
| 499 | |
| 500 | if (codec_ == JetsonCodec::kH264) { |
| 501 | encoder_->setPocType(2); |
| 502 | } |
| 503 | |
| 504 | encoder_->setBitrate(bitrate_bps_); |
| 505 | encoder_->setFrameRate(framerate_, 1); |
| 506 | encoder_->setRateControlMode(V4L2_MPEG_VIDEO_BITRATE_MODE_CBR); |
| 507 | |
| 508 | if (codec_ != JetsonCodec::kAV1) { |
| 509 | encoder_->setIDRInterval(keyframe_interval_); |
| 510 | } |
| 511 | |
| 512 | encoder_->setIFrameInterval(keyframe_interval_); |
| 513 | |
| 514 | if (codec_ != JetsonCodec::kAV1) { |
| 515 | encoder_->setInsertSpsPpsAtIdrEnabled(true); |
| 516 | } |
| 517 | |
| 518 | if (codec_ == JetsonCodec::kH264) { |
| 519 | encoder_->setProfile(V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE); |
| 520 | // Match the factory-advertised SDP profile-level-id (42e01f == CBP L3.1) |
| 521 | // to avoid decoders rejecting due to an SPS level_idc higher than SDP. |
| 522 | encoder_->setLevel(V4L2_MPEG_VIDEO_H264_LEVEL_3_1); |
| 523 | } else if (codec_ == JetsonCodec::kH265) { |
| 524 | encoder_->setProfile(V4L2_MPEG_VIDEO_H265_PROFILE_MAIN); |
| 525 | } |
| 526 | |
| 527 | v4l2_format output_format = {}; |
| 528 | // Some MMAPI wrappers/driver paths require v4l2_format.type to be set before |
| 529 | // querying the current format, otherwise the returned struct can be zeroed. |
| 530 | output_format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; |
| 531 | ret = encoder_->output_plane.getFormat(output_format); |
| 532 | if (ret == 0) { |
| 533 | output_y_stride_ = output_format.fmt.pix_mp.plane_fmt[0].bytesperline; |
| 534 | if (output_is_nv12_) { |
| 535 | output_u_stride_ = output_format.fmt.pix_mp.plane_fmt[1].bytesperline; |
| 536 | output_v_stride_ = output_u_stride_; |
| 537 | } else { |
| 538 | output_u_stride_ = output_format.fmt.pix_mp.plane_fmt[1].bytesperline; |
| 539 | output_v_stride_ = output_format.fmt.pix_mp.plane_fmt[2].bytesperline; |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | if (output_y_stride_ == 0) { |
| 544 | output_y_stride_ = width_; |
| 545 | } |
| 546 | if (output_u_stride_ == 0) { |
| 547 | // For NV12, the chroma plane has full-width interleaved UV. |
| 548 | output_u_stride_ = output_is_nv12_ ? width_ : width_ / 2; |
| 549 | } |
| 550 | if (output_v_stride_ == 0) { |
| 551 | // For NV12, V is interleaved with U in plane[1]; keep v_stride equal to |
| 552 | // u_stride for logging only. |
| 553 | output_v_stride_ = output_is_nv12_ ? output_u_stride_ : width_ / 2; |
| 554 | } |
| 555 | |
| 556 | // Some Jetson drivers report incomplete/zero plane info via getFormat(). Clamp |
| 557 | // to sane minimums to avoid under-striding NV12 (which can lead to empty |
| 558 | // output or corruption). |
| 559 | if (output_is_nv12_ && output_u_stride_ < width_) { |
| 560 | output_u_stride_ = width_; |
| 561 | output_v_stride_ = width_; |
| 562 | } |
| 563 | if (!output_is_nv12_) { |
| 564 | const int min_chroma_stride = (width_ + 1) / 2; |
| 565 | if (output_u_stride_ < min_chroma_stride) { |
| 566 | output_u_stride_ = min_chroma_stride; |
| 567 | } |
| 568 | if (output_v_stride_ < min_chroma_stride) { |
| 569 | output_v_stride_ = min_chroma_stride; |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | return true; |
| 574 | } |
| 575 | |
| 576 | bool JetsonMmapiEncoder::SetupPlanes() { |
| 577 | output_buffer_count_ = kDefaultOutputBufferCount; |
| 578 | capture_buffer_count_ = kDefaultCaptureBufferCount; |
| 579 | |
| 580 | if (encoder_->output_plane.setupPlane(V4L2_MEMORY_MMAP, |
| 581 | output_buffer_count_, true, false) < |
| 582 | 0) { |
| 583 | RTC_LOG(LS_ERROR) << "Failed to setup output plane."; |
| 584 | return false; |
| 585 | } |
| 586 | if (encoder_->capture_plane.setupPlane(V4L2_MEMORY_MMAP, |
| 587 | capture_buffer_count_, true, false) < |
| 588 | 0) { |
| 589 | RTC_LOG(LS_ERROR) << "Failed to setup capture plane."; |
| 590 | return false; |
| 591 | } |
| 592 | return true; |
| 593 | } |
| 594 | |
| 595 | bool JetsonMmapiEncoder::QueueCaptureBuffers() { |
| 596 | for (int i = 0; i < capture_buffer_count_; ++i) { |
| 597 | v4l2_buffer v4l2_buf = {}; |
| 598 | v4l2_plane planes[VIDEO_MAX_PLANES] = {}; |
| 599 | v4l2_buf.index = i; |
| 600 | v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; |
| 601 | v4l2_buf.memory = V4L2_MEMORY_MMAP; |
| 602 | v4l2_buf.m.planes = planes; |
| 603 | v4l2_buf.length = encoder_->capture_plane.getNumPlanes(); |
| 604 | if (encoder_->capture_plane.qBuffer(v4l2_buf, nullptr) < 0) { |
| 605 | RTC_LOG(LS_ERROR) << "Failed to queue capture buffer " << i; |
| 606 | return false; |
| 607 | } |
| 608 | } |
| 609 | return true; |
| 610 | } |
| 611 | |
| 612 | bool JetsonMmapiEncoder::StartStreaming() { |
| 613 | if (streaming_) { |
| 614 | return true; |
| 615 | } |
| 616 | if (encoder_->output_plane.setStreamStatus(true) < 0) { |
| 617 | RTC_LOG(LS_ERROR) << "Failed to start output plane stream."; |
| 618 | return false; |
| 619 | } |
| 620 | if (encoder_->capture_plane.setStreamStatus(true) < 0) { |
| 621 | RTC_LOG(LS_ERROR) << "Failed to start capture plane stream."; |
| 622 | return false; |
| 623 | } |
| 624 | streaming_ = true; |
| 625 | return true; |
| 626 | } |
| 627 | |
| 628 | void JetsonMmapiEncoder::StopStreaming() { |
| 629 | if (!streaming_ || !encoder_) { |
| 630 | return; |
| 631 | } |
| 632 | encoder_->output_plane.setStreamStatus(false); |
| 633 | encoder_->capture_plane.setStreamStatus(false); |
| 634 | streaming_ = false; |
| 635 | } |
| 636 | |
| 637 | bool JetsonMmapiEncoder::QueueOutputBuffer(const uint8_t* src_y, |
| 638 | int stride_y, |
| 639 | const uint8_t* src_u, |
| 640 | int stride_u, |
| 641 | const uint8_t* src_v, |
| 642 | int stride_v) { |
| 643 | NvBuffer* buffer = encoder_->output_plane.getNthBuffer(next_output_index_); |
| 644 | if (!buffer) { |
| 645 | RTC_LOG(LS_ERROR) << "Failed to get output buffer."; |
| 646 | return false; |
| 647 | } |
| 648 | if (output_is_nv12_) { |
| 649 | if (buffer->n_planes < 2) { |
| 650 | RTC_LOG(LS_ERROR) << "Output plane format is NV12 but has <2 planes."; |
| 651 | return false; |
| 652 | } |
| 653 | } else { |
| 654 | if (buffer->n_planes < 3) { |
| 655 | RTC_LOG(LS_ERROR) << "Output plane format is YUV420M but has <3 planes."; |
| 656 | return false; |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | // IMPORTANT: The actual mapped destination pitch can differ from the |
| 661 | // V4L2 bytesperline returned by getFormat() due to alignment/pitch |
| 662 | // requirements. Using the wrong destination stride will produce |
| 663 | // "striped/shifted/green" output. |
| 664 | // |
| 665 | // On some Jetson/MMAPI combinations, NvBufferPlane::fmt.stride can be unset |
| 666 | // in MMAP mode. Also, NvBufferPlane::fmt.height may be misleading (e.g. UV |
| 667 | // plane reporting luma height), which can cause derived stride to be too |
| 668 | // small and result in green/corrupted output. |
| 669 | // |
| 670 | // Prefer NvBufSurfaceFromFd() plane pitch/height when available, and clamp |
| 671 | // derived strides to never under/over-stride the plane. |
| 672 | const int chroma_height = (height_ + 1) / 2; |
| 673 | const int chroma_width = (width_ + 1) / 2; |
| 674 | uint32_t y_pitch = 0, y_h = 0, y_np = 0; |
| 675 | uint32_t u_pitch = 0, u_h = 0, u_np = 0; |
| 676 | uint32_t v_pitch = 0, v_h = 0, v_np = 0; |
| 677 | // Only probe NvBufSurface plane metadata if the API works for MMAP fds. |
| 678 | // On JetPack versions where it doesn't, calling NvBufSurfaceFromFd |
| 679 | // produces noisy "Wrong buffer index" warnings on every frame. |
| 680 | const bool have_y = mmap_sync_supported_ && |
| 681 | GetPitchAndHeightFromNvBufSurfaceFd(buffer->planes[0].fd, 0, &y_pitch, &y_h, &y_np); |
| 682 | const bool have_u = mmap_sync_supported_ && |
| 683 | (buffer->n_planes > 1) && |
| 684 | GetPitchAndHeightFromNvBufSurfaceFd(buffer->planes[1].fd, 1, &u_pitch, &u_h, &u_np); |
| 685 | const bool have_v = mmap_sync_supported_ && |
| 686 | (!output_is_nv12_ && buffer->n_planes > 2) && |
| 687 | GetPitchAndHeightFromNvBufSurfaceFd(buffer->planes[2].fd, 2, &v_pitch, &v_h, &v_np); |
| 688 | |
| 689 | // Map the (sometimes unreliable) hardware metadata into plain-data hints so |
| 690 | // the stride/height resolution stays pure and unit-testable. See |
| 691 | // jetson_plane_layout.h. |
| 692 | auto hints_for = [](const NvBuffer::NvBufferPlane& plane, |
| 693 | bool have_probe, uint32_t probed_pitch) { |
| 694 | return PlaneLayoutHints{ |
| 695 | /*fmt_stride=*/static_cast<int>(plane.fmt.stride), |
| 696 | /*probed_pitch=*/have_probe ? static_cast<int>(probed_pitch) : 0, |
| 697 | /*plane_length=*/static_cast<int>(plane.length), |
| 698 | /*fmt_height=*/static_cast<int>(plane.fmt.height)}; |
| 699 | }; |
| 700 | |
| 701 | const int min_y_stride = width_; |
| 702 | const int min_uv_stride = output_is_nv12_ ? width_ : chroma_width; |
| 703 | const int dst_y_stride = ResolvePlaneStride( |
| 704 | hints_for(buffer->planes[0], have_y, y_pitch), height_, min_y_stride, |
| 705 | output_y_stride_); |
| 706 | const int dst_u_stride = ResolvePlaneStride( |
| 707 | hints_for(buffer->planes[1], have_u, u_pitch), chroma_height, |
| 708 | min_uv_stride, output_u_stride_); |
| 709 | const int dst_v_stride = |
| 710 | (!output_is_nv12_ && buffer->n_planes > 2) |
| 711 | ? ResolvePlaneStride(hints_for(buffer->planes[2], have_v, v_pitch), |
| 712 | chroma_height, chroma_width, output_v_stride_) |
| 713 | : dst_u_stride; |
| 714 | |
| 715 | uint8_t* dst_y = static_cast<uint8_t*>(buffer->planes[0].data); |
| 716 | const int plane_y_height = |
| 717 | ResolvePlaneHeight(have_y, static_cast<int>(y_h), height_); |
| 718 | const int plane_u_height = |
| 719 | ResolvePlaneHeight(have_u, static_cast<int>(u_h), chroma_height); |
| 720 | const int plane_v_height = |
| 721 | ResolvePlaneHeight(have_v, static_cast<int>(v_h), chroma_height); |
| 722 | auto ZeroPlaneRows = [](uint8_t* dst, int stride, int start_row, |
| 723 | int end_row) { |
| 724 | for (int y = start_row; y < end_row; ++y) { |
| 725 | std::memset(dst + y * stride, 0, static_cast<size_t>(stride)); |
| 726 | } |
| 727 | }; |
| 728 | CopyPlane(dst_y, dst_y_stride, src_y, stride_y, width_, height_); |
| 729 | if (plane_y_height > height_) { |
| 730 | ZeroPlaneRows(dst_y, dst_y_stride, height_, plane_y_height); |
| 731 | } |
| 732 | if (output_is_nv12_) { |
| 733 | uint8_t* dst_uv = static_cast<uint8_t*>(buffer->planes[1].data); |
| 734 | for (int y = 0; y < chroma_height; ++y) { |
| 735 | const uint8_t* src_u_row = src_u + y * stride_u; |
| 736 | const uint8_t* src_v_row = src_v + y * stride_v; |
| 737 | uint8_t* dst_row = dst_uv + y * dst_u_stride; |
| 738 | for (int x = 0; x < chroma_width; ++x) { |
| 739 | dst_row[x * 2] = src_u_row[x]; |
| 740 | dst_row[x * 2 + 1] = src_v_row[x]; |
| 741 | } |
| 742 | } |
| 743 | if (plane_u_height > chroma_height) { |
| 744 | ZeroPlaneRows(dst_uv, dst_u_stride, chroma_height, plane_u_height); |
| 745 | } |
| 746 | } else { |
| 747 | uint8_t* dst_u = static_cast<uint8_t*>(buffer->planes[1].data); |
| 748 | uint8_t* dst_v = static_cast<uint8_t*>(buffer->planes[2].data); |
| 749 | CopyPlane(dst_u, dst_u_stride, src_u, stride_u, chroma_width, |
| 750 | chroma_height); |
| 751 | CopyPlane(dst_v, dst_v_stride, src_v, stride_v, chroma_width, |
| 752 | chroma_height); |
| 753 | if (plane_u_height > chroma_height) { |
| 754 | ZeroPlaneRows(dst_u, dst_u_stride, chroma_height, plane_u_height); |
| 755 | } |
| 756 | if (plane_v_height > chroma_height) { |
| 757 | ZeroPlaneRows(dst_v, dst_v_stride, chroma_height, plane_v_height); |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | // IMPORTANT: In MMAP mode, the Jetson MMAPI wrapper can rely on NvBuffer's |
| 762 | // bytesused values (not only the v4l2_buffer's plane bytesused). If these |
| 763 | // are left at 0, the encoder may treat the input as empty and output black. |
| 764 | buffer->planes[0].bytesused = |
| 765 | dst_y_stride * static_cast<uint32_t>(plane_y_height); |
| 766 | buffer->planes[1].bytesused = |
| 767 | dst_u_stride * static_cast<uint32_t>(plane_u_height); |
| 768 | if (!output_is_nv12_ && buffer->n_planes > 2) { |
| 769 | buffer->planes[2].bytesused = |
| 770 | dst_v_stride * static_cast<uint32_t>(plane_v_height); |
| 771 | } |
| 772 | |
| 773 | // Best-effort sync of CPU-written pixel data to the device. On JetPack |
| 774 | // versions where NvBufSurfaceFromFd works for V4L2 MMAP plane fds this |
| 775 | // flushes CPU caches before the hardware encoder reads the buffer. On |
| 776 | // versions where it doesn't (producing "Wrong buffer index" warnings), |
| 777 | // we disable the sync after the first failure. V4L2 MMAP + qBuffer |
| 778 | // handles cache coherency on its own so skipping is safe. |
| 779 | if (mmap_sync_supported_) { |
| 780 | for (int plane = 0; plane < buffer->n_planes; ++plane) { |
| 781 | int fd = buffer->planes[plane].fd; |
| 782 | NvBufSurface* surface = nullptr; |
| 783 | int map_ret = |
| 784 | NvBufSurfaceFromFd(fd, reinterpret_cast<void**>(&surface)); |
| 785 | if (map_ret != 0 || !surface) { |
| 786 | mmap_sync_supported_ = false; |
| 787 | RTC_LOG(LS_WARNING) |
| 788 | << "NvBufSurfaceFromFd failed for MMAP fd; disabling explicit " |
| 789 | "device sync (V4L2 qBuffer handles coherency)."; |
| 790 | break; |
| 791 | } |
| 792 | int sync_ret = NvBufSurfaceSyncForDevice(surface, 0, -1); |
| 793 | if (sync_ret != 0) { |
| 794 | mmap_sync_supported_ = false; |
| 795 | RTC_LOG(LS_WARNING) |
| 796 | << "NvBufSurfaceSyncForDevice failed for MMAP fd; disabling " |
| 797 | "explicit device sync (V4L2 qBuffer handles coherency)."; |
| 798 | break; |
| 799 | } |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | v4l2_buffer v4l2_buf = {}; |
| 804 | v4l2_plane planes[VIDEO_MAX_PLANES] = {}; |
| 805 | v4l2_buf.index = next_output_index_; |
| 806 | v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; |
| 807 | v4l2_buf.memory = V4L2_MEMORY_MMAP; |
| 808 | v4l2_buf.m.planes = planes; |
| 809 | v4l2_buf.length = encoder_->output_plane.getNumPlanes(); |
| 810 | planes[0].bytesused = buffer->planes[0].bytesused; |
| 811 | planes[1].bytesused = buffer->planes[1].bytesused; |
| 812 | if (!output_is_nv12_) { |
| 813 | planes[2].bytesused = buffer->planes[2].bytesused; |
| 814 | } |
| 815 | |
| 816 | int qbuf_ret = encoder_->output_plane.qBuffer(v4l2_buf, nullptr); |
| 817 | if (qbuf_ret < 0) { |
| 818 | RTC_LOG(LS_ERROR) << "Failed to queue output buffer."; |
| 819 | return false; |
| 820 | } |
| 821 | |
| 822 | next_output_index_ = (next_output_index_ + 1) % output_buffer_count_; |
| 823 | return true; |
| 824 | } |
| 825 | |
| 826 | bool JetsonMmapiEncoder::QueueOutputBufferNV12(const uint8_t* src_y, |
| 827 | int stride_y, |
| 828 | const uint8_t* src_uv, |
| 829 | int stride_uv) { |
| 830 | if (!output_is_nv12_) { |
| 831 | RTC_LOG(LS_ERROR) << "QueueOutputBufferNV12 called but output is not NV12."; |
| 832 | return false; |
| 833 | } |
| 834 | |
| 835 | NvBuffer* buffer = encoder_->output_plane.getNthBuffer(next_output_index_); |
| 836 | if (!buffer) { |
| 837 | RTC_LOG(LS_ERROR) << "Failed to get output buffer."; |
| 838 | return false; |
| 839 | } |
| 840 | |
| 841 | const int chroma_height = (height_ + 1) / 2; |
| 842 | uint32_t y_pitch = 0, y_h = 0, y_np = 0; |
| 843 | uint32_t uv_pitch = 0, uv_h = 0, uv_np = 0; |
| 844 | const bool have_y = mmap_sync_supported_ && |
| 845 | GetPitchAndHeightFromNvBufSurfaceFd(buffer->planes[0].fd, 0, &y_pitch, &y_h, &y_np); |
| 846 | const bool have_uv = mmap_sync_supported_ && |
| 847 | (buffer->n_planes > 1) && |
| 848 | GetPitchAndHeightFromNvBufSurfaceFd(buffer->planes[1].fd, 1, &uv_pitch, &uv_h, &uv_np); |
| 849 | |
| 850 | // See QueueOutputBuffer: keep the layout decisions in pure, testable helpers. |
| 851 | auto hints_for = [](const NvBuffer::NvBufferPlane& plane, |
| 852 | bool have_probe, uint32_t probed_pitch) { |
| 853 | return PlaneLayoutHints{ |
| 854 | /*fmt_stride=*/static_cast<int>(plane.fmt.stride), |
| 855 | /*probed_pitch=*/have_probe ? static_cast<int>(probed_pitch) : 0, |
| 856 | /*plane_length=*/static_cast<int>(plane.length), |
| 857 | /*fmt_height=*/static_cast<int>(plane.fmt.height)}; |
| 858 | }; |
| 859 | |
| 860 | const int min_y_stride = width_; |
| 861 | const int min_uv_stride = width_; |
| 862 | const int dst_y_stride = ResolvePlaneStride( |
| 863 | hints_for(buffer->planes[0], have_y, y_pitch), height_, min_y_stride, |
| 864 | output_y_stride_); |
| 865 | const int dst_uv_stride = ResolvePlaneStride( |
| 866 | hints_for(buffer->planes[1], have_uv, uv_pitch), chroma_height, |
| 867 | min_uv_stride, output_u_stride_); |
| 868 | |
| 869 | uint8_t* dst_y = static_cast<uint8_t*>(buffer->planes[0].data); |
| 870 | uint8_t* dst_uv = static_cast<uint8_t*>(buffer->planes[1].data); |
| 871 | const int plane_y_height = |
| 872 | ResolvePlaneHeight(have_y, static_cast<int>(y_h), height_); |
| 873 | const int plane_uv_height = |
| 874 | ResolvePlaneHeight(have_uv, static_cast<int>(uv_h), chroma_height); |
| 875 | auto ZeroPlaneRows = [](uint8_t* dst, int stride, int start_row, |
| 876 | int end_row) { |
| 877 | for (int y = start_row; y < end_row; ++y) { |
| 878 | std::memset(dst + y * stride, 0, static_cast<size_t>(stride)); |
| 879 | } |
| 880 | }; |
| 881 | CopyPlane(dst_y, dst_y_stride, src_y, stride_y, width_, height_); |
| 882 | CopyPlane(dst_uv, dst_uv_stride, src_uv, stride_uv, width_, |
| 883 | (height_ + 1) / 2); |
| 884 | if (plane_y_height > height_) { |
| 885 | ZeroPlaneRows(dst_y, dst_y_stride, height_, plane_y_height); |
| 886 | } |
| 887 | if (plane_uv_height > chroma_height) { |
| 888 | ZeroPlaneRows(dst_uv, dst_uv_stride, chroma_height, plane_uv_height); |
| 889 | } |
| 890 | |
| 891 | // Keep NvBuffer bytesused in sync for MMAP. |
| 892 | buffer->planes[0].bytesused = |
| 893 | dst_y_stride * static_cast<uint32_t>(plane_y_height); |
| 894 | buffer->planes[1].bytesused = |
| 895 | dst_uv_stride * static_cast<uint32_t>(plane_uv_height); |
| 896 | |
| 897 | // Best-effort device sync (see QueueOutputBuffer for rationale). |
| 898 | if (mmap_sync_supported_) { |
| 899 | for (int plane = 0; plane < buffer->n_planes; ++plane) { |
| 900 | int fd = buffer->planes[plane].fd; |
| 901 | NvBufSurface* surface = nullptr; |
| 902 | int map_ret = |
| 903 | NvBufSurfaceFromFd(fd, reinterpret_cast<void**>(&surface)); |
| 904 | if (map_ret != 0 || !surface) { |
| 905 | mmap_sync_supported_ = false; |
| 906 | RTC_LOG(LS_WARNING) |
| 907 | << "NvBufSurfaceFromFd failed for MMAP fd; disabling explicit " |
| 908 | "device sync (V4L2 qBuffer handles coherency)."; |
| 909 | break; |
| 910 | } |
| 911 | int sync_ret = NvBufSurfaceSyncForDevice(surface, 0, -1); |
| 912 | if (sync_ret != 0) { |
| 913 | mmap_sync_supported_ = false; |
| 914 | RTC_LOG(LS_WARNING) |
| 915 | << "NvBufSurfaceSyncForDevice failed for MMAP fd; disabling " |
| 916 | "explicit device sync (V4L2 qBuffer handles coherency)."; |
| 917 | break; |
| 918 | } |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | v4l2_buffer v4l2_buf = {}; |
| 923 | v4l2_plane planes[VIDEO_MAX_PLANES] = {}; |
| 924 | v4l2_buf.index = next_output_index_; |
| 925 | v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; |
| 926 | v4l2_buf.memory = V4L2_MEMORY_MMAP; |
| 927 | v4l2_buf.m.planes = planes; |
| 928 | v4l2_buf.length = encoder_->output_plane.getNumPlanes(); |
| 929 | planes[0].bytesused = buffer->planes[0].bytesused; |
| 930 | planes[1].bytesused = buffer->planes[1].bytesused; |
| 931 | |
| 932 | int qbuf_ret = encoder_->output_plane.qBuffer(v4l2_buf, nullptr); |
| 933 | if (qbuf_ret < 0) { |
| 934 | RTC_LOG(LS_ERROR) << "Failed to queue output buffer."; |
| 935 | return false; |
| 936 | } |
| 937 | |
| 938 | next_output_index_ = (next_output_index_ + 1) % output_buffer_count_; |
| 939 | return true; |
| 940 | } |
| 941 | |
| 942 | bool JetsonMmapiEncoder::DequeueCaptureBuffer(std::vector<uint8_t>* encoded, |
| 943 | bool* is_keyframe) { |
| 944 | static std::atomic<bool> dumped(false); |
| 945 | static std::atomic<bool> logged_env(false); |
| 946 | static std::atomic<int> verbose_left(10); |
| 947 | const bool verbose = std::getenv("LK_DUMP_H264_VERBOSE") != nullptr; |
| 948 | constexpr int kMaxEmptyRetries = 5; |
| 949 | constexpr int kDequeueTimeoutMs = 1000; |
| 950 | v4l2_buffer v4l2_buf = {}; |
| 951 | v4l2_plane planes[VIDEO_MAX_PLANES] = {}; |
| 952 | NvBuffer* buffer = nullptr; |
| 953 | v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; |
| 954 | v4l2_buf.memory = V4L2_MEMORY_MMAP; |
| 955 | v4l2_buf.m.planes = planes; |
| 956 | v4l2_buf.length = encoder_->capture_plane.getNumPlanes(); |
| 957 | |
| 958 | size_t bytesused = 0; |
| 959 | int empty_retries = 0; |
| 960 | int backoff_ms = 1; |
| 961 | for (int attempt = 0; attempt < kMaxEmptyRetries; ++attempt) { |
| 962 | int dq_ret = encoder_->capture_plane.dqBuffer(v4l2_buf, &buffer, nullptr, |
| 963 | kDequeueTimeoutMs); |
| 964 | if (dq_ret < 0) { |
| 965 | RTC_LOG(LS_ERROR) << "Failed to dequeue capture buffer."; |
| 966 | return false; |
| 967 | } |
| 968 | bytesused = v4l2_buf.m.planes[0].bytesused; |
| 969 | if (bytesused > 0) { |
| 970 | break; |
| 971 | } |
| 972 | empty_retries++; |
| 973 | if (encoder_->capture_plane.qBuffer(v4l2_buf, nullptr) < 0) { |
| 974 | RTC_LOG(LS_ERROR) << "Failed to requeue empty capture buffer."; |
| 975 | return false; |
| 976 | } |
| 977 | std::this_thread::sleep_for(std::chrono::milliseconds(backoff_ms)); |
| 978 | backoff_ms = std::min(backoff_ms * 2, 8); |
| 979 | } |
| 980 | |
| 981 | if (bytesused == 0) { |
| 982 | RTC_LOG(LS_WARNING) << "All " << kMaxEmptyRetries |
| 983 | << " dequeue attempts returned an empty buffer."; |
| 984 | return false; |
| 985 | } |
| 986 | |
| 987 | encoded->assign(static_cast<uint8_t*>(buffer->planes[0].data), |
| 988 | static_cast<uint8_t*>(buffer->planes[0].data) + bytesused); |
| 989 | if (is_keyframe) { |
| 990 | *is_keyframe = (v4l2_buf.flags & V4L2_BUF_FLAG_KEYFRAME) != 0; |
| 991 | } |
| 992 | if (verbose && verbose_left.load(std::memory_order_relaxed) > 0) { |
| 993 | const int remaining = verbose_left.fetch_sub(1); |
| 994 | if (remaining > 0) { |
| 995 | std::fprintf(stderr, |
| 996 | "[MMAPI] capture dqBuffer: bytesused=%zu flags=0x%x " |
| 997 | "index=%d empty_retries=%d\n", |
| 998 | bytesused, v4l2_buf.flags, v4l2_buf.index, empty_retries); |
| 999 | std::fflush(stderr); |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | if (!dumped.load(std::memory_order_relaxed)) { |
| 1004 | const char* dump_path = std::getenv("LK_DUMP_H264"); |
| 1005 | if (!dump_path || dump_path[0] == '\0') { |
| 1006 | if (!logged_env.exchange(true)) { |
| 1007 | std::fprintf(stderr, |
| 1008 | "LK_DUMP_H264 not set; skipping H264 dump (MMAPI).\n"); |
| 1009 | std::fflush(stderr); |
| 1010 | } |
| 1011 | } else if (bytesused == 0) { |
| 1012 | if (!logged_env.exchange(true)) { |
| 1013 | std::error_code ec; |
| 1014 | std::filesystem::path path(dump_path); |
| 1015 | if (path.has_parent_path()) { |
| 1016 | std::filesystem::create_directories(path.parent_path(), ec); |
| 1017 | } |
| 1018 | |
| 1019 | // Create/truncate the file so it's obvious the env var was applied, |
| 1020 | // even if the first dequeued buffers are empty. |
| 1021 | std::ofstream out(dump_path, std::ios::binary); |
| 1022 | if (out.good()) { |
| 1023 | std::fprintf( |
| 1024 | stderr, |
| 1025 | "LK_DUMP_H264 set to %s but packet is empty (MMAPI); created " |
| 1026 | "empty dump file\n", |
| 1027 | dump_path); |
| 1028 | std::fflush(stderr); |
| 1029 | } else { |
| 1030 | std::fprintf(stderr, |
| 1031 | "Failed to open LK_DUMP_H264 path (MMAPI): %s\n", |
| 1032 | dump_path); |
| 1033 | std::fflush(stderr); |
| 1034 | } |
| 1035 | } |
| 1036 | } else { |
| 1037 | std::error_code ec; |
| 1038 | std::filesystem::path path(dump_path); |
| 1039 | if (path.has_parent_path()) { |
| 1040 | std::filesystem::create_directories(path.parent_path(), ec); |
| 1041 | } |
| 1042 | std::ofstream out(dump_path, std::ios::binary); |
| 1043 | if (out.good()) { |
| 1044 | out.write(reinterpret_cast<const char*>(encoded->data()), |
| 1045 | static_cast<std::streamsize>(encoded->size())); |
| 1046 | std::fprintf(stderr, |
| 1047 | "Dumped H264 access unit to %s (MMAPI, bytes=%zu, " |
| 1048 | "keyframe=%d)\n", |
| 1049 | dump_path, encoded->size(), |
| 1050 | is_keyframe ? (*is_keyframe ? 1 : 0) : -1); |
| 1051 | std::fflush(stderr); |
| 1052 | dumped.store(true, std::memory_order_relaxed); |
| 1053 | } else { |
| 1054 | std::fprintf(stderr, |
| 1055 | "Failed to open LK_DUMP_H264 path (MMAPI): %s\n", |
| 1056 | dump_path); |
| 1057 | std::fflush(stderr); |
| 1058 | } |
| 1059 | logged_env.store(true, std::memory_order_relaxed); |
| 1060 | } |
| 1061 | } |
| 1062 | |
| 1063 | int requeue_ret = encoder_->capture_plane.qBuffer(v4l2_buf, nullptr); |
| 1064 | if (requeue_ret < 0) { |
| 1065 | RTC_LOG(LS_ERROR) << "Failed to requeue capture buffer."; |
| 1066 | return false; |
| 1067 | } |
| 1068 | return true; |
| 1069 | } |
| 1070 | |
| 1071 | bool JetsonMmapiEncoder::DequeueOutputBuffer() { |
| 1072 | v4l2_buffer v4l2_buf = {}; |
| 1073 | v4l2_plane planes[VIDEO_MAX_PLANES] = {}; |
| 1074 | v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; |
| 1075 | v4l2_buf.memory = use_dmabuf_input_ ? V4L2_MEMORY_DMABUF : V4L2_MEMORY_MMAP; |
| 1076 | v4l2_buf.m.planes = planes; |
| 1077 | v4l2_buf.length = encoder_->output_plane.getNumPlanes(); |
| 1078 | if (encoder_->output_plane.dqBuffer(v4l2_buf, nullptr, nullptr, 0) < 0) { |
| 1079 | RTC_LOG(LS_ERROR) << "Failed to dequeue output buffer."; |
| 1080 | return false; |
| 1081 | } |
| 1082 | return true; |
| 1083 | } |
| 1084 | |
| 1085 | bool JetsonMmapiEncoder::EncodeDmaBuf(int dmabuf_fd, |
| 1086 | bool force_keyframe, |
| 1087 | std::vector<uint8_t>* encoded, |
| 1088 | bool* is_keyframe) { |
| 1089 | if (!initialized_ || !encoder_) { |
| 1090 | return false; |
| 1091 | } |
| 1092 | |
| 1093 | // On first DmaBuf encode, re-setup the output plane for V4L2_MEMORY_DMABUF. |
| 1094 | if (!dmabuf_planes_setup_) { |
| 1095 | // Stop streaming, reconfigure output plane, restart. |
| 1096 | StopStreaming(); |
| 1097 | if (!SetupPlanesDmaBuf()) { |
| 1098 | return false; |
| 1099 | } |
| 1100 | if (!QueueCaptureBuffers()) { |
| 1101 | return false; |
| 1102 | } |
| 1103 | if (!StartStreaming()) { |
| 1104 | return false; |
| 1105 | } |
| 1106 | dmabuf_planes_setup_ = true; |
| 1107 | use_dmabuf_input_ = true; |
| 1108 | next_output_index_ = 0; |
| 1109 | } |
| 1110 | |
| 1111 | if (force_keyframe && !ForceKeyframe()) { |
| 1112 | RTC_LOG(LS_WARNING) << "Failed to request keyframe."; |
| 1113 | } |
| 1114 | |
| 1115 | if (!QueueOutputBufferDmaBuf(dmabuf_fd)) { |
| 1116 | return false; |
| 1117 | } |
| 1118 | |
| 1119 | if (!DequeueCaptureBuffer(encoded, is_keyframe)) { |
| 1120 | return false; |
| 1121 | } |
| 1122 | |
| 1123 | if (!DequeueOutputBuffer()) { |
| 1124 | return false; |
| 1125 | } |
| 1126 | |
| 1127 | return true; |
| 1128 | } |
| 1129 | |
| 1130 | bool JetsonMmapiEncoder::SetupPlanesDmaBuf() { |
| 1131 | // The DMA buffers from Argus are NV12. If the encoder was initially |
| 1132 | // configured for YUV420M (3-plane I420), reconfigure to NV12M so the |
| 1133 | // plane count matches the DMA buffer layout. |
| 1134 | if (!output_is_nv12_) { |
| 1135 | int ret = encoder_->setOutputPlaneFormat(V4L2_PIX_FMT_NV12M, width_, height_); |
| 1136 | if (ret < 0) { |
| 1137 | RTC_LOG(LS_ERROR) |
| 1138 | << "SetupPlanesDmaBuf: failed to switch output plane to NV12M."; |
| 1139 | return false; |
| 1140 | } |
| 1141 | output_is_nv12_ = true; |
| 1142 | } |
| 1143 | |
| 1144 | // Output plane uses V4L2_MEMORY_DMABUF: we request buffers but don't |
| 1145 | // allocate backing memory -- the caller provides DMA fds at queue time. |
| 1146 | output_buffer_count_ = kDefaultOutputBufferCount; |
| 1147 | capture_buffer_count_ = kDefaultCaptureBufferCount; |
| 1148 | |
| 1149 | if (encoder_->output_plane.setupPlane(V4L2_MEMORY_DMABUF, |
| 1150 | output_buffer_count_, false, false) < |
| 1151 | 0) { |
| 1152 | RTC_LOG(LS_ERROR) << "Failed to setup output plane for DMABUF."; |
| 1153 | return false; |
| 1154 | } |
| 1155 | |
| 1156 | // Capture plane remains MMAP (encoded bitstream output). |
| 1157 | if (encoder_->capture_plane.setupPlane(V4L2_MEMORY_MMAP, |
| 1158 | capture_buffer_count_, true, false) < |
| 1159 | 0) { |
| 1160 | RTC_LOG(LS_ERROR) << "Failed to setup capture plane."; |
| 1161 | return false; |
| 1162 | } |
| 1163 | |
| 1164 | return true; |
| 1165 | } |
| 1166 | |
| 1167 | bool JetsonMmapiEncoder::QueueOutputBufferDmaBuf(int dmabuf_fd) { |
| 1168 | // Cache the NvBufSurface plane metadata after the first successful lookup. |
| 1169 | // All DMA buffers in the ring share the same dimensions and NV12 layout, |
| 1170 | // so the pitch/height/num_planes values are constant. Caching avoids |
| 1171 | // calling NvBufSurfaceFromFd on every frame, which on many JetPack |
| 1172 | // versions prints spurious "Wrong buffer index" warnings and adds latency. |
| 1173 | if (!dmabuf_meta_cached_) { |
| 1174 | NvBufSurface* surface = nullptr; |
| 1175 | int ret = NvBufSurfaceFromFd(dmabuf_fd, reinterpret_cast<void**>(&surface)); |
| 1176 | if (ret != 0 || !surface) { |
| 1177 | RTC_LOG(LS_ERROR) << "QueueOutputBufferDmaBuf: NvBufSurfaceFromFd failed " |
| 1178 | << "(fd=" << dmabuf_fd << ", ret=" << ret << ")"; |
| 1179 | return false; |
| 1180 | } |
| 1181 | const NvBufSurfaceParams& params = surface->surfaceList[0]; |
| 1182 | dmabuf_num_planes_ = params.planeParams.num_planes; |
| 1183 | for (uint32_t i = 0; i < dmabuf_num_planes_ && i < VIDEO_MAX_PLANES; ++i) { |
| 1184 | dmabuf_plane_bytesused_[i] = |
| 1185 | params.planeParams.pitch[i] * params.planeParams.height[i]; |
| 1186 | } |
| 1187 | dmabuf_meta_cached_ = true; |
| 1188 | } |
| 1189 | |
| 1190 | v4l2_buffer v4l2_buf = {}; |
| 1191 | v4l2_plane planes[VIDEO_MAX_PLANES] = {}; |
| 1192 | v4l2_buf.index = next_output_index_; |
| 1193 | v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; |
| 1194 | v4l2_buf.memory = V4L2_MEMORY_DMABUF; |
| 1195 | v4l2_buf.m.planes = planes; |
| 1196 | v4l2_buf.length = encoder_->output_plane.getNumPlanes(); |
| 1197 | |
| 1198 | for (uint32_t i = 0; i < v4l2_buf.length && i < dmabuf_num_planes_; ++i) { |
| 1199 | planes[i].m.fd = dmabuf_fd; |
| 1200 | planes[i].bytesused = dmabuf_plane_bytesused_[i]; |
| 1201 | } |
| 1202 | |
| 1203 | int qbuf_ret = encoder_->output_plane.qBuffer(v4l2_buf, nullptr); |
| 1204 | if (qbuf_ret < 0) { |
| 1205 | RTC_LOG(LS_ERROR) << "QueueOutputBufferDmaBuf: qBuffer failed " |
| 1206 | << "(index=" << next_output_index_ |
| 1207 | << ", errno=" << errno << ": " << strerror(errno) << ")"; |
| 1208 | return false; |
| 1209 | } |
| 1210 | |
| 1211 | next_output_index_ = (next_output_index_ + 1) % output_buffer_count_; |
| 1212 | return true; |
| 1213 | } |
| 1214 | |
| 1215 | bool JetsonMmapiEncoder::ForceKeyframe() { |
| 1216 | if (codec_ == JetsonCodec::kAV1) { |
| 1217 | // For AV1 the only control that actually forces an intra (key) frame on |
| 1218 | // this NVENC is V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE, which is what |
| 1219 | // NvVideoEncoder::forceIDR() drives. The H.264/H.265-oriented |
| 1220 | // FORCE_IDR_FRAME / FORCE_INTRA_FRAME controls return success but are |
| 1221 | // silently ignored by the AV1 encoder, so the requested keyframe is never |
| 1222 | // produced and a receiver that PLIs can never recover. |
| 1223 | return encoder_->forceIDR() == 0; |
| 1224 | } |
| 1225 | |
| 1226 | v4l2_ext_control control = {}; |
| 1227 | v4l2_ext_controls controls = {}; |
| 1228 | controls.count = 1; |
| 1229 | controls.controls = &control; |
| 1230 | control.value = 1; |
| 1231 | control.id = V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME; |
| 1232 | return encoder_->setExtControls(controls) == 0; |
| 1233 | } |
| 1234 | |
| 1235 | } // namespace livekit |