| 1 | /* |
| 2 | * Copyright 2025 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/video_track.h" |
| 18 | |
| 19 | #include <algorithm> |
| 20 | #include <iostream> |
| 21 | #include <memory> |
| 22 | |
| 23 | #include "api/media_stream_interface.h" |
| 24 | #include "api/video/video_frame.h" |
| 25 | #include "api/video/video_rotation.h" |
| 26 | #include "audio/remix_resample.h" |
| 27 | #include "common_audio/include/audio_util.h" |
| 28 | #include "livekit/encoded_video_frame_buffer.h" |
| 29 | #include "livekit/media_stream.h" |
| 30 | #include "livekit/packet_trailer.h" |
| 31 | #include "livekit/video_track.h" |
| 32 | #include "rtc_base/logging.h" |
| 33 | #include "rtc_base/ref_counted_object.h" |
| 34 | #include "rtc_base/synchronization/mutex.h" |
| 35 | #include "rtc_base/time_utils.h" |
| 36 | #include "webrtc-sys/src/packet_trailer.rs.h" |
| 37 | #include "webrtc-sys/src/video_track.rs.h" |
| 38 | |
| 39 | namespace livekit_ffi { |
| 40 | namespace { |
| 41 | |
| 42 | livekit::EncodedVideoCodec ToNativeEncodedCodec(EncodedVideoCodec codec) { |
| 43 | switch (codec) { |
| 44 | case EncodedVideoCodec::H264: |
| 45 | return livekit::EncodedVideoCodec::kH264; |
| 46 | case EncodedVideoCodec::H265: |
| 47 | return livekit::EncodedVideoCodec::kH265; |
| 48 | case EncodedVideoCodec::VP8: |
| 49 | return livekit::EncodedVideoCodec::kVP8; |
| 50 | case EncodedVideoCodec::VP9: |
| 51 | return livekit::EncodedVideoCodec::kVP9; |
| 52 | case EncodedVideoCodec::AV1: |
| 53 | return livekit::EncodedVideoCodec::kAV1; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | livekit::EncodedFrameType ToNativeEncodedFrameType(EncodedFrameType frame_type) { |
| 58 | switch (frame_type) { |
| 59 | case EncodedFrameType::Key: |
| 60 | return livekit::EncodedFrameType::kKey; |
| 61 | case EncodedFrameType::Delta: |
| 62 | return livekit::EncodedFrameType::kDelta; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | } // namespace |
| 67 | |
| 68 | VideoTrack::VideoTrack(std::shared_ptr<RtcRuntime> rtc_runtime, |
| 69 | webrtc::scoped_refptr<webrtc::VideoTrackInterface> track) |
| 70 | : MediaStreamTrack(rtc_runtime, std::move(track)) {} |
| 71 | |
| 72 | VideoTrack::~VideoTrack() { |
| 73 | webrtc::MutexLock lock(&mutex_); |
| 74 | for (auto& sink : sinks_) { |
| 75 | track()->RemoveSink(sink.get()); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | void VideoTrack::add_sink(const std::shared_ptr<NativeVideoSink>& sink) const { |
| 80 | webrtc::MutexLock lock(&mutex_); |
| 81 | track()->AddOrUpdateSink(sink.get(), |
| 82 | webrtc::VideoSinkWants()); // TODO(theomonnom): Expose |
| 83 | // VideoSinkWants to Rust? |
| 84 | sinks_.push_back(sink); |
| 85 | } |
| 86 | |
| 87 | void VideoTrack::remove_sink( |
| 88 | const std::shared_ptr<NativeVideoSink>& sink) const { |
| 89 | webrtc::MutexLock lock(&mutex_); |
| 90 | track()->RemoveSink(sink.get()); |
| 91 | sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end()); |
| 92 | } |
| 93 | |
| 94 | void VideoTrack::set_should_receive(bool should_receive) const { |
| 95 | track()->set_should_receive(should_receive); |
| 96 | } |
| 97 | |
| 98 | bool VideoTrack::should_receive() const { |
| 99 | return track()->should_receive(); |
| 100 | } |
| 101 | |
| 102 | ContentHint VideoTrack::content_hint() const { |
| 103 | return static_cast<ContentHint>(track()->content_hint()); |
| 104 | } |
| 105 | |
| 106 | void VideoTrack::set_content_hint(ContentHint hint) const { |
| 107 | track()->set_content_hint( |
| 108 | static_cast<webrtc::VideoTrackInterface::ContentHint>(hint)); |
| 109 | } |
| 110 | |
| 111 | NativeVideoSink::NativeVideoSink(rust::Box<VideoSinkWrapper> observer) |
| 112 | : observer_(std::move(observer)) {} |
| 113 | |
| 114 | void NativeVideoSink::OnFrame(const webrtc::VideoFrame& frame) { |
| 115 | observer_->on_frame(std::make_unique<VideoFrame>(frame)); |
| 116 | } |
| 117 | |
| 118 | void NativeVideoSink::OnDiscardedFrame() { |
| 119 | observer_->on_discarded_frame(); |
| 120 | } |
| 121 | |
| 122 | void NativeVideoSink::OnConstraintsChanged( |
| 123 | const webrtc::VideoTrackSourceConstraints& constraints) { |
| 124 | VideoTrackSourceConstraints cst; |
| 125 | cst.has_min_fps = constraints.min_fps.has_value(); |
| 126 | cst.min_fps = constraints.min_fps.value_or(0); |
| 127 | cst.has_max_fps = constraints.max_fps.has_value(); |
| 128 | cst.max_fps = constraints.max_fps.value_or(0); |
| 129 | observer_->on_constraints_changed(cst); |
| 130 | } |
| 131 | |
| 132 | std::shared_ptr<NativeVideoSink> new_native_video_sink( |
| 133 | rust::Box<VideoSinkWrapper> observer) { |
| 134 | return std::make_shared<NativeVideoSink>(std::move(observer)); |
| 135 | } |
| 136 | |
| 137 | VideoTrackSource::InternalSource::InternalSource( |
| 138 | const VideoResolution& resolution, bool is_screencast) |
| 139 | : webrtc::AdaptedVideoTrackSource(4), resolution_(resolution), is_screencast_(is_screencast) {} |
| 140 | |
| 141 | VideoTrackSource::InternalSource::~InternalSource() {} |
| 142 | |
| 143 | bool VideoTrackSource::InternalSource::is_screencast() const { |
| 144 | return is_screencast_; |
| 145 | } |
| 146 | |
| 147 | std::optional<bool> VideoTrackSource::InternalSource::needs_denoising() const { |
| 148 | return false; |
| 149 | } |
| 150 | |
| 151 | webrtc::MediaSourceInterface::SourceState |
| 152 | VideoTrackSource::InternalSource::state() const { |
| 153 | return SourceState::kLive; |
| 154 | } |
| 155 | |
| 156 | bool VideoTrackSource::InternalSource::remote() const { |
| 157 | return false; |
| 158 | } |
| 159 | |
| 160 | VideoResolution VideoTrackSource::InternalSource::video_resolution() const { |
| 161 | webrtc::MutexLock lock(&mutex_); |
| 162 | return resolution_; |
| 163 | } |
| 164 | |
| 165 | bool VideoTrackSource::InternalSource::on_captured_frame( |
| 166 | const webrtc::VideoFrame& frame, |
| 167 | const FrameMetadata& frame_metadata) { |
| 168 | webrtc::MutexLock lock(&mutex_); |
| 169 | |
| 170 | int64_t aligned_timestamp_us = timestamp_aligner_.TranslateTimestamp( |
| 171 | frame.timestamp_us(), webrtc::TimeMicros()); |
| 172 | |
| 173 | // If a packet trailer was provided on this frame and we have a handler, |
| 174 | // store the mapping keyed by the aligned timestamp. This is the value |
| 175 | // that CaptureTime() will return in TransformSend, so the lookup will |
| 176 | // succeed. |
| 177 | if (frame_metadata.has_packet_trailer && packet_trailer_handler_) { |
| 178 | packet_trailer_handler_->store_frame_metadata( |
| 179 | aligned_timestamp_us, frame_metadata.user_timestamp, |
| 180 | frame_metadata.frame_id, |
| 181 | rust::Slice<const uint8_t>(frame_metadata.user_data.data(), |
| 182 | frame_metadata.user_data.size())); |
| 183 | } |
| 184 | |
| 185 | webrtc::scoped_refptr<webrtc::VideoFrameBuffer> buffer = |
| 186 | frame.video_frame_buffer(); |
| 187 | |
| 188 | if (resolution_.height == 0 || resolution_.width == 0) { |
| 189 | resolution_ = VideoResolution{static_cast<uint32_t>(buffer->width()), |
| 190 | static_cast<uint32_t>(buffer->height())}; |
| 191 | } |
| 192 | |
| 193 | // Pre-encoded access units bypass the adapter entirely: frame-rate and |
| 194 | // resolution adaptation operate on raw frames, and dropping or scaling an |
| 195 | // encoded delta frame would corrupt the bitstream for every receiver. |
| 196 | if (livekit::EncodedVideoFrameBuffer::FromNative(buffer.get())) { |
| 197 | if (packet_trailer_handler_) { |
| 198 | packet_trailer_handler_->emit_publish_timing( |
| 199 | VideoPublishTimingStage::EncoderUpload, |
| 200 | frame_metadata.has_packet_trailer ? frame_metadata.user_timestamp |
| 201 | : 0, |
| 202 | frame_metadata.has_packet_trailer ? frame_metadata.frame_id : 0); |
| 203 | } |
| 204 | OnFrame(webrtc::VideoFrame::Builder() |
| 205 | .set_video_frame_buffer(buffer) |
| 206 | .set_rotation(frame.rotation()) |
| 207 | .set_timestamp_us(aligned_timestamp_us) |
| 208 | .build()); |
| 209 | return true; |
| 210 | } |
| 211 | |
| 212 | int adapted_width, adapted_height, crop_width, crop_height, crop_x, crop_y; |
| 213 | if (!AdaptFrame(buffer->width(), buffer->height(), aligned_timestamp_us, |
| 214 | &adapted_width, &adapted_height, &crop_width, &crop_height, |
| 215 | &crop_x, &crop_y)) { |
| 216 | return false; |
| 217 | } |
| 218 | |
| 219 | if (adapted_width != frame.width() || adapted_height != frame.height()) { |
| 220 | buffer = buffer->CropAndScale(crop_x, crop_y, crop_width, crop_height, |
| 221 | adapted_width, adapted_height); |
| 222 | } |
| 223 | |
| 224 | webrtc::VideoRotation rotation = frame.rotation(); |
| 225 | if (apply_rotation() && rotation != webrtc::kVideoRotation_0) { |
| 226 | // If the buffer is I420, webrtc::AdaptedVideoTrackSource will handle the |
| 227 | // rotation for us. |
| 228 | buffer = buffer->ToI420(); |
| 229 | } |
| 230 | |
| 231 | if (packet_trailer_handler_) { |
| 232 | packet_trailer_handler_->emit_publish_timing( |
| 233 | VideoPublishTimingStage::EncoderUpload, |
| 234 | frame_metadata.has_packet_trailer ? frame_metadata.user_timestamp : 0, |
| 235 | frame_metadata.has_packet_trailer ? frame_metadata.frame_id : 0); |
| 236 | } |
| 237 | |
| 238 | OnFrame(webrtc::VideoFrame::Builder() |
| 239 | .set_video_frame_buffer(buffer) |
| 240 | .set_rotation(rotation) |
| 241 | .set_timestamp_us(aligned_timestamp_us) |
| 242 | .build()); |
| 243 | |
| 244 | return true; |
| 245 | } |
| 246 | |
| 247 | void VideoTrackSource::InternalSource::set_packet_trailer_handler( |
| 248 | std::shared_ptr<PacketTrailerHandler> handler) { |
| 249 | webrtc::MutexLock lock(&mutex_); |
| 250 | packet_trailer_handler_ = std::move(handler); |
| 251 | } |
| 252 | |
| 253 | VideoTrackSource::VideoTrackSource(const VideoResolution& resolution, bool is_screencast) { |
| 254 | source_ = webrtc::make_ref_counted<InternalSource>(resolution, is_screencast); |
| 255 | } |
| 256 | |
| 257 | VideoResolution VideoTrackSource::video_resolution() const { |
| 258 | return source_->video_resolution(); |
| 259 | } |
| 260 | |
| 261 | bool VideoTrackSource::on_captured_frame( |
| 262 | const std::unique_ptr<VideoFrame>& frame, |
| 263 | const FrameMetadata& frame_metadata) const { |
| 264 | auto rtc_frame = frame->get(); |
| 265 | return source_->on_captured_frame(rtc_frame, frame_metadata); |
| 266 | } |
| 267 | |
| 268 | bool VideoTrackSource::capture_encoded_frame( |
| 269 | int width, |
| 270 | int height, |
| 271 | const EncodedVideoFrameData& encoded_frame, |
| 272 | rust::Slice<const uint8_t> payload, |
| 273 | const FrameMetadata& frame_metadata) const { |
| 274 | // The single unavoidable copy on this path: the Rust payload only lives |
| 275 | // for the duration of this call, while the EncodedImageBuffer is shared |
| 276 | // (uncopied) with the pass-through encoder downstream. |
| 277 | auto buffer = webrtc::make_ref_counted<livekit::EncodedVideoFrameBuffer>( |
| 278 | width, height, ToNativeEncodedCodec(encoded_frame.codec), |
| 279 | ToNativeEncodedFrameType(encoded_frame.frame_type), |
| 280 | webrtc::EncodedImageBuffer::Create(payload.data(), payload.size()), |
| 281 | source_->keyframe_request_flag(), source_->rate_control_state()); |
| 282 | |
| 283 | auto frame = webrtc::VideoFrame::Builder() |
| 284 | .set_video_frame_buffer(std::move(buffer)) |
| 285 | .set_rotation(webrtc::kVideoRotation_0) |
| 286 | .set_timestamp_us(encoded_frame.timestamp_us) |
| 287 | .build(); |
| 288 | |
| 289 | return source_->on_captured_frame(frame, frame_metadata); |
| 290 | } |
| 291 | |
| 292 | bool VideoTrackSource::take_keyframe_request() const { |
| 293 | return source_->keyframe_request_flag()->exchange(false, |
| 294 | std::memory_order_relaxed); |
| 295 | } |
| 296 | |
| 297 | EncodedRateControlRequest VideoTrackSource::take_rate_control_request() const { |
| 298 | auto request = source_->rate_control_state()->Take(); |
| 299 | return EncodedRateControlRequest{request.has_request, |
| 300 | request.target_bitrate_bps, |
| 301 | request.framerate_fps}; |
| 302 | } |
| 303 | |
| 304 | void VideoTrackSource::set_packet_trailer_handler( |
| 305 | std::shared_ptr<PacketTrailerHandler> handler) const { |
| 306 | source_->set_packet_trailer_handler(std::move(handler)); |
| 307 | } |
| 308 | |
| 309 | webrtc::scoped_refptr<VideoTrackSource::InternalSource> VideoTrackSource::get() |
| 310 | const { |
| 311 | return source_; |
| 312 | } |
| 313 | |
| 314 | std::shared_ptr<VideoTrackSource> new_video_track_source( |
| 315 | const VideoResolution& resolution, bool is_screencast) { |
| 316 | return std::make_shared<VideoTrackSource>(resolution, is_screencast); |
| 317 | } |
| 318 | |
| 319 | } // namespace livekit_ffi |