| 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 "livekit/passthrough_video_encoder.h" |
| 18 | |
| 19 | #include <algorithm> |
| 20 | #include <map> |
| 21 | #include <memory> |
| 22 | #include <optional> |
| 23 | #include <string> |
| 24 | #include <utility> |
| 25 | #include <vector> |
| 26 | |
| 27 | #include "absl/container/inlined_vector.h" |
| 28 | #include "api/video/encoded_image.h" |
| 29 | #include "api/video/video_frame.h" |
| 30 | #include "api/video/video_codec_constants.h" |
| 31 | #include "api/video_codecs/scalability_mode.h" |
| 32 | #include "api/video_codecs/video_encoder.h" |
| 33 | #include "av1_bitstream.h" |
| 34 | #include "common_video/h264/h264_common.h" |
| 35 | #include "livekit/encoded_video_frame_buffer.h" |
| 36 | #include "media/base/media_constants.h" |
| 37 | #include "modules/video_coding/include/video_codec_interface.h" |
| 38 | #include "modules/video_coding/include/video_error_codes.h" |
| 39 | #include "modules/video_coding/svc/scalable_video_controller_no_layering.h" |
| 40 | #include "rtc_base/logging.h" |
| 41 | #include "rtc_base/synchronization/mutex.h" |
| 42 | |
| 43 | namespace livekit_ffi { |
| 44 | namespace { |
| 45 | |
| 46 | using livekit::EncodedVideoFrameBuffer; |
| 47 | using webrtc::CodecSpecificInfo; |
| 48 | using webrtc::EncodedImage; |
| 49 | using webrtc::EncodedImageBuffer; |
| 50 | using webrtc::EncodedImageCallback; |
| 51 | using webrtc::Environment; |
| 52 | using webrtc::H264PacketizationMode; |
| 53 | using webrtc::ScalabilityMode; |
| 54 | using webrtc::ScalableVideoController; |
| 55 | using webrtc::ScalableVideoControllerNoLayering; |
| 56 | using webrtc::SdpVideoFormat; |
| 57 | using webrtc::VideoCodec; |
| 58 | using webrtc::VideoCodecType; |
| 59 | using webrtc::VideoEncoder; |
| 60 | using webrtc::VideoFrame; |
| 61 | using webrtc::VideoFrameBuffer; |
| 62 | using webrtc::VideoFrameType; |
| 63 | |
| 64 | VideoCodecType CodecTypeFromFormat(const SdpVideoFormat& format) { |
| 65 | if (format.name == "H264") { |
| 66 | return webrtc::kVideoCodecH264; |
| 67 | } |
| 68 | if (format.name == "H265" || format.name == "HEVC") { |
| 69 | return webrtc::kVideoCodecH265; |
| 70 | } |
| 71 | if (format.name == "VP8") { |
| 72 | return webrtc::kVideoCodecVP8; |
| 73 | } |
| 74 | if (format.name == "VP9") { |
| 75 | return webrtc::kVideoCodecVP9; |
| 76 | } |
| 77 | if (format.name == "AV1") { |
| 78 | return webrtc::kVideoCodecAV1; |
| 79 | } |
| 80 | return webrtc::kVideoCodecGeneric; |
| 81 | } |
| 82 | |
| 83 | VideoCodecType CodecTypeFromBuffer(livekit::EncodedVideoCodec codec) { |
| 84 | switch (codec) { |
| 85 | case livekit::EncodedVideoCodec::kH264: |
| 86 | return webrtc::kVideoCodecH264; |
| 87 | case livekit::EncodedVideoCodec::kH265: |
| 88 | return webrtc::kVideoCodecH265; |
| 89 | case livekit::EncodedVideoCodec::kVP8: |
| 90 | return webrtc::kVideoCodecVP8; |
| 91 | case livekit::EncodedVideoCodec::kVP9: |
| 92 | return webrtc::kVideoCodecVP9; |
| 93 | case livekit::EncodedVideoCodec::kAV1: |
| 94 | return webrtc::kVideoCodecAV1; |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | VideoFrameType FrameTypeFromBuffer(livekit::EncodedFrameType frame_type) { |
| 99 | switch (frame_type) { |
| 100 | case livekit::EncodedFrameType::kKey: |
| 101 | return VideoFrameType::kVideoFrameKey; |
| 102 | case livekit::EncodedFrameType::kDelta: |
| 103 | return VideoFrameType::kVideoFrameDelta; |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | bool IsAv1Codec(VideoCodecType codec_type) { |
| 108 | return codec_type == webrtc::kVideoCodecAV1; |
| 109 | } |
| 110 | |
| 111 | bool IsKeyframe(livekit::EncodedFrameType frame_type) { |
| 112 | return frame_type == livekit::EncodedFrameType::kKey; |
| 113 | } |
| 114 | |
| 115 | // SDP profile parameters constrain real encoders, not a pass-through: the |
| 116 | // forwarded bytes are whatever the upstream encoder produced. Match formats |
| 117 | // by codec only (H265/HEVC are aliases via CodecTypeFromFormat). |
| 118 | bool IsSameCodecType(const SdpVideoFormat& a, const SdpVideoFormat& b) { |
| 119 | VideoCodecType type_a = CodecTypeFromFormat(a); |
| 120 | return type_a != webrtc::kVideoCodecGeneric && |
| 121 | type_a == CodecTypeFromFormat(b); |
| 122 | } |
| 123 | |
| 124 | void FillSingleLayerCodecSpecific( |
| 125 | CodecSpecificInfo* codec_info, |
| 126 | VideoCodecType codec_type, |
| 127 | int width, |
| 128 | int height, |
| 129 | bool keyframe, |
| 130 | ScalableVideoControllerNoLayering* av1_svc_controller) { |
| 131 | codec_info->codecType = codec_type; |
| 132 | codec_info->end_of_picture = true; |
| 133 | |
| 134 | switch (codec_type) { |
| 135 | case webrtc::kVideoCodecH264: |
| 136 | codec_info->codecSpecific.H264.packetization_mode = |
| 137 | H264PacketizationMode::NonInterleaved; |
| 138 | break; |
| 139 | case webrtc::kVideoCodecVP8: |
| 140 | codec_info->codecSpecific.VP8.nonReference = false; |
| 141 | codec_info->codecSpecific.VP8.temporalIdx = 0; |
| 142 | codec_info->codecSpecific.VP8.layerSync = false; |
| 143 | codec_info->codecSpecific.VP8.keyIdx = -1; |
| 144 | break; |
| 145 | case webrtc::kVideoCodecVP9: |
| 146 | codec_info->codecSpecific.VP9.first_frame_in_picture = true; |
| 147 | codec_info->codecSpecific.VP9.inter_pic_predicted = !keyframe; |
| 148 | codec_info->codecSpecific.VP9.flexible_mode = false; |
| 149 | codec_info->codecSpecific.VP9.ss_data_available = keyframe; |
| 150 | codec_info->codecSpecific.VP9.temporal_idx = 0; |
| 151 | codec_info->codecSpecific.VP9.temporal_up_switch = true; |
| 152 | codec_info->codecSpecific.VP9.inter_layer_predicted = false; |
| 153 | codec_info->codecSpecific.VP9.gof_idx = 0; |
| 154 | codec_info->codecSpecific.VP9.num_spatial_layers = 1; |
| 155 | codec_info->codecSpecific.VP9.first_active_layer = 0; |
| 156 | codec_info->codecSpecific.VP9.spatial_layer_resolution_present = keyframe; |
| 157 | codec_info->codecSpecific.VP9.width[0] = width; |
| 158 | codec_info->codecSpecific.VP9.height[0] = height; |
| 159 | codec_info->codecSpecific.VP9.gof.SetGofInfoVP9( |
| 160 | webrtc::kTemporalStructureMode1); |
| 161 | codec_info->codecSpecific.VP9.num_ref_pics = keyframe ? 0 : 1; |
| 162 | codec_info->codecSpecific.VP9.p_diff[0] = 1; |
| 163 | break; |
| 164 | case webrtc::kVideoCodecAV1: { |
| 165 | codec_info->scalability_mode = ScalabilityMode::kL1T1; |
| 166 | std::vector<ScalableVideoController::LayerFrameConfig> layer_frames = |
| 167 | av1_svc_controller->NextFrameConfig(/*restart=*/keyframe); |
| 168 | if (!layer_frames.empty()) { |
| 169 | const ScalableVideoController::LayerFrameConfig& layer_frame = |
| 170 | layer_frames.front(); |
| 171 | codec_info->generic_frame_info = |
| 172 | av1_svc_controller->OnEncodeDone(layer_frame); |
| 173 | if (layer_frame.IsKeyframe()) { |
| 174 | codec_info->template_structure = |
| 175 | av1_svc_controller->DependencyStructure(); |
| 176 | } |
| 177 | } |
| 178 | break; |
| 179 | } |
| 180 | default: |
| 181 | break; |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | class PassthroughVideoEncoder final : public VideoEncoder { |
| 186 | public: |
| 187 | PassthroughVideoEncoder(const Environment& env, const SdpVideoFormat& format) |
| 188 | : env_(env), format_(format), codec_type_(CodecTypeFromFormat(format)) {} |
| 189 | |
| 190 | int32_t InitEncode(const VideoCodec* codec_settings, |
| 191 | const Settings& /* settings */) override { |
| 192 | if (!codec_settings || codec_settings->codecType != codec_type_) { |
| 193 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 194 | } |
| 195 | codec_ = *codec_settings; |
| 196 | cached_sequence_header_obu_.clear(); |
| 197 | av1_svc_controller_ = ScalableVideoControllerNoLayering(); |
| 198 | if (IsAv1Codec(codec_type_) && !codec_.GetScalabilityMode().has_value()) { |
| 199 | codec_.SetScalabilityMode(ScalabilityMode::kL1T1); |
| 200 | } |
| 201 | return WEBRTC_VIDEO_CODEC_OK; |
| 202 | } |
| 203 | |
| 204 | int32_t RegisterEncodeCompleteCallback( |
| 205 | EncodedImageCallback* callback) override { |
| 206 | encoded_image_callback_ = callback; |
| 207 | return WEBRTC_VIDEO_CODEC_OK; |
| 208 | } |
| 209 | |
| 210 | int32_t Release() override { |
| 211 | encoded_image_callback_ = nullptr; |
| 212 | return WEBRTC_VIDEO_CODEC_OK; |
| 213 | } |
| 214 | |
| 215 | int32_t Encode(const VideoFrame& frame, |
| 216 | const std::vector<VideoFrameType>* frame_types) override { |
| 217 | if (!encoded_image_callback_) { |
| 218 | RTC_LOG(LS_ERROR) |
| 219 | << "PassthroughVideoEncoder callback is not registered"; |
| 220 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; |
| 221 | } |
| 222 | |
| 223 | webrtc::scoped_refptr<VideoFrameBuffer> frame_buffer = |
| 224 | frame.video_frame_buffer(); |
| 225 | EncodedVideoFrameBuffer* encoded_buffer = |
| 226 | EncodedVideoFrameBuffer::FromNative(frame_buffer.get()); |
| 227 | if (!encoded_buffer) { |
| 228 | RTC_LOG(LS_ERROR) |
| 229 | << "PassthroughVideoEncoder received a non-encoded frame buffer"; |
| 230 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 231 | } |
| 232 | |
| 233 | if (CodecTypeFromBuffer(encoded_buffer->codec()) != codec_type_) { |
| 234 | RTC_LOG(LS_ERROR) |
| 235 | << "PassthroughVideoEncoder frame codec does not match sender codec"; |
| 236 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 237 | } |
| 238 | ForwardPendingRateControl(encoded_buffer); |
| 239 | |
| 240 | const bool is_keyframe = IsKeyframe(encoded_buffer->frame_type()); |
| 241 | |
| 242 | // A pass-through cannot synthesize the keyframe the RTP layer wants |
| 243 | // (PLI/FIR, late subscriber, reconfiguration); forward the request to |
| 244 | // the capture source so the upstream encoder can produce an IDR. |
| 245 | const bool keyframe_requested = |
| 246 | frame_types != nullptr && |
| 247 | std::any_of(frame_types->begin(), frame_types->end(), |
| 248 | [](VideoFrameType type) { |
| 249 | return type == VideoFrameType::kVideoFrameKey; |
| 250 | }); |
| 251 | if (keyframe_requested && !is_keyframe) { |
| 252 | encoded_buffer->request_keyframe(); |
| 253 | } |
| 254 | |
| 255 | if (encoded_buffer->payload_size() == 0) { |
| 256 | RTC_LOG(LS_ERROR) << "PassthroughVideoEncoder received an empty frame"; |
| 257 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 258 | } |
| 259 | |
| 260 | // Non-AV1 payloads are forwarded without copying: the buffer already |
| 261 | // owns a webrtc::EncodedImageBuffer. AV1 needs RTP normalization, which |
| 262 | // may rewrite the bytes, so it works on a copy. |
| 263 | webrtc::scoped_refptr<webrtc::EncodedImageBufferInterface> encoded_data; |
| 264 | if (IsAv1Codec(codec_type_)) { |
| 265 | std::vector<uint8_t> payload( |
| 266 | encoded_buffer->payload_data(), |
| 267 | encoded_buffer->payload_data() + encoded_buffer->payload_size()); |
| 268 | livekit::av1::NormalizeForRtp(&payload); |
| 269 | |
| 270 | std::vector<uint8_t> sequence_header; |
| 271 | if (livekit::av1::ExtractSequenceHeaderObu( |
| 272 | payload.data(), payload.size(), &sequence_header)) { |
| 273 | cached_sequence_header_obu_ = std::move(sequence_header); |
| 274 | } else if (is_keyframe && !cached_sequence_header_obu_.empty()) { |
| 275 | livekit::av1::EnsureSequenceHeaderOnKeyframe( |
| 276 | &payload, cached_sequence_header_obu_); |
| 277 | } |
| 278 | if (payload.empty() || |
| 279 | !livekit::av1::IsWebRtcParseable(payload.data(), payload.size())) { |
| 280 | RTC_LOG(LS_ERROR) |
| 281 | << "PassthroughVideoEncoder received an AV1 frame that WebRTC " |
| 282 | "cannot packetize"; |
| 283 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; |
| 284 | } |
| 285 | encoded_data = EncodedImageBuffer::Create(payload.data(), payload.size()); |
| 286 | } else { |
| 287 | encoded_data = encoded_buffer->encoded_data(); |
| 288 | } |
| 289 | |
| 290 | EncodedImage encoded_image; |
| 291 | encoded_image._encodedWidth = encoded_buffer->width(); |
| 292 | encoded_image._encodedHeight = encoded_buffer->height(); |
| 293 | encoded_image.SetRtpTimestamp(frame.rtp_timestamp()); |
| 294 | encoded_image.SetSimulcastIndex(0); |
| 295 | encoded_image.ntp_time_ms_ = frame.ntp_time_ms(); |
| 296 | encoded_image.capture_time_ms_ = frame.render_time_ms(); |
| 297 | encoded_image.rotation_ = frame.rotation(); |
| 298 | encoded_image.content_type_ = webrtc::VideoContentType::UNSPECIFIED; |
| 299 | encoded_image.timing_.flags = webrtc::VideoSendTiming::kInvalid; |
| 300 | encoded_image._frameType = FrameTypeFromBuffer(encoded_buffer->frame_type()); |
| 301 | encoded_image.SetColorSpace(frame.color_space()); |
| 302 | const size_t encoded_size = encoded_data->size(); |
| 303 | encoded_image.SetEncodedData(std::move(encoded_data)); |
| 304 | encoded_image.set_size(encoded_size); |
| 305 | encoded_image.qp_ = -1; |
| 306 | |
| 307 | CodecSpecificInfo codec_info; |
| 308 | codec_info.codecSpecific = {}; |
| 309 | FillSingleLayerCodecSpecific(&codec_info, codec_type_, encoded_buffer->width(), |
| 310 | encoded_buffer->height(), is_keyframe, |
| 311 | &av1_svc_controller_); |
| 312 | |
| 313 | const auto result = |
| 314 | encoded_image_callback_->OnEncodedImage(encoded_image, &codec_info); |
| 315 | if (result.error != EncodedImageCallback::Result::OK) { |
| 316 | RTC_LOG(LS_ERROR) << "PassthroughVideoEncoder callback failed " |
| 317 | << result.error; |
| 318 | return WEBRTC_VIDEO_CODEC_ERROR; |
| 319 | } |
| 320 | return WEBRTC_VIDEO_CODEC_OK; |
| 321 | } |
| 322 | |
| 323 | void SetRates(const RateControlParameters& parameters) override { |
| 324 | webrtc::MutexLock lock(&rate_control_mutex_); |
| 325 | latest_rate_control_request_ = livekit::EncodedRateControlRequest{ |
| 326 | true, parameters.bitrate.get_sum_bps(), parameters.framerate_fps}; |
| 327 | } |
| 328 | |
| 329 | EncoderInfo GetEncoderInfo() const override { |
| 330 | EncoderInfo info; |
| 331 | info.supports_native_handle = true; |
| 332 | info.implementation_name = "LiveKit pre-encoded passthrough"; |
| 333 | info.scaling_settings = VideoEncoder::ScalingSettings::kOff; |
| 334 | info.is_hardware_accelerated = false; |
| 335 | info.supports_simulcast = false; |
| 336 | info.preferred_pixel_formats = {VideoFrameBuffer::Type::kNative}; |
| 337 | return info; |
| 338 | } |
| 339 | |
| 340 | private: |
| 341 | void ForwardPendingRateControl( |
| 342 | EncodedVideoFrameBuffer* encoded_buffer) { |
| 343 | std::optional<livekit::EncodedRateControlRequest> request; |
| 344 | { |
| 345 | webrtc::MutexLock lock(&rate_control_mutex_); |
| 346 | request = latest_rate_control_request_; |
| 347 | latest_rate_control_request_.reset(); |
| 348 | } |
| 349 | if (request.has_value()) { |
| 350 | encoded_buffer->set_rate_control_request(request->target_bitrate_bps, |
| 351 | request->framerate_fps); |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | Environment env_; |
| 356 | SdpVideoFormat format_; |
| 357 | VideoCodecType codec_type_; |
| 358 | VideoCodec codec_; |
| 359 | EncodedImageCallback* encoded_image_callback_ = nullptr; |
| 360 | ScalableVideoControllerNoLayering av1_svc_controller_; |
| 361 | std::vector<uint8_t> cached_sequence_header_obu_; |
| 362 | webrtc::Mutex rate_control_mutex_; |
| 363 | std::optional<livekit::EncodedRateControlRequest> latest_rate_control_request_; |
| 364 | }; |
| 365 | |
| 366 | } // namespace |
| 367 | |
| 368 | PassthroughVideoEncoderFactory::PassthroughVideoEncoderFactory() { |
| 369 | std::map<std::string, std::string> h264_parameters = { |
| 370 | {"profile-level-id", "42e01f"}, |
| 371 | {"level-asymmetry-allowed", "1"}, |
| 372 | {"packetization-mode", "1"}, |
| 373 | }; |
| 374 | absl::InlinedVector<ScalabilityMode, webrtc::kScalabilityModeCount> |
| 375 | scalability_modes; |
| 376 | scalability_modes.push_back(ScalabilityMode::kL1T1); |
| 377 | supported_formats_.push_back(SdpVideoFormat::VP8()); |
| 378 | supported_formats_.push_back(SdpVideoFormat::VP9Profile0()); |
| 379 | supported_formats_.push_back( |
| 380 | SdpVideoFormat(SdpVideoFormat::AV1Profile0(), scalability_modes)); |
| 381 | supported_formats_.push_back(SdpVideoFormat("H264", h264_parameters)); |
| 382 | supported_formats_.push_back(SdpVideoFormat("H265")); |
| 383 | supported_formats_.push_back(SdpVideoFormat("HEVC")); |
| 384 | } |
| 385 | |
| 386 | std::vector<SdpVideoFormat> |
| 387 | PassthroughVideoEncoderFactory::GetSupportedFormats() const { |
| 388 | return supported_formats_; |
| 389 | } |
| 390 | |
| 391 | std::vector<SdpVideoFormat> |
| 392 | PassthroughVideoEncoderFactory::GetImplementations() const { |
| 393 | return supported_formats_; |
| 394 | } |
| 395 | |
| 396 | PassthroughVideoEncoderFactory::CodecSupport |
| 397 | PassthroughVideoEncoderFactory::QueryCodecSupport( |
| 398 | const SdpVideoFormat& format, |
| 399 | std::optional<std::string> scalability_mode) const { |
| 400 | for (const auto& supported_format : supported_formats_) { |
| 401 | if (IsSameCodecType(format, supported_format)) { |
| 402 | if (format.name == "AV1" && scalability_mode.has_value() && |
| 403 | *scalability_mode != "L1T1") { |
| 404 | return {.is_supported = false, .is_power_efficient = false}; |
| 405 | } |
| 406 | return {.is_supported = true, .is_power_efficient = true}; |
| 407 | } |
| 408 | } |
| 409 | return {.is_supported = false, .is_power_efficient = false}; |
| 410 | } |
| 411 | |
| 412 | std::unique_ptr<VideoEncoder> PassthroughVideoEncoderFactory::Create( |
| 413 | const Environment& env, |
| 414 | const SdpVideoFormat& format) { |
| 415 | // Match by codec, not by exact profile: rejecting e.g. a High-profile |
| 416 | // H264 negotiation here would hand the session to a real encoder that |
| 417 | // cannot consume pre-encoded frames. |
| 418 | for (const auto& supported_format : supported_formats_) { |
| 419 | if (IsSameCodecType(format, supported_format)) { |
| 420 | return std::make_unique<PassthroughVideoEncoder>(env, format); |
| 421 | } |
| 422 | } |
| 423 | return nullptr; |
| 424 | } |
| 425 | |
| 426 | } // namespace livekit_ffi |