| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 |
| 11 | #include "video/video_receive_stream2.h" |
| 12 |
| 13 | #include <stdlib.h> |
| 14 | #include <string.h> |
| 15 |
| 16 | #include <algorithm> |
| 17 | #include <memory> |
| 18 | #include <set> |
| 19 | #include <string> |
| 20 | #include <utility> |
| 21 |
| 22 | #include "absl/algorithm/container.h" |
| 23 | #include "absl/types/optional.h" |
| 24 | #include "api/array_view.h" |
| 25 | #include "api/crypto/frame_decryptor_interface.h" |
| 26 | #include "api/scoped_refptr.h" |
| 27 | #include "api/sequence_checker.h" |
| 28 | #include "api/task_queue/pending_task_safety_flag.h" |
| 29 | #include "api/task_queue/task_queue_base.h" |
| 30 | #include "api/units/frequency.h" |
| 31 | #include "api/units/time_delta.h" |
| 32 | #include "api/units/timestamp.h" |
| 33 | #include "api/video/encoded_image.h" |
| 34 | #include "api/video_codecs/sdp_video_format.h" |
| 35 | #include "api/video_codecs/video_codec.h" |
| 36 | #include "api/video_codecs/video_decoder_factory.h" |
| 37 | #include "call/rtp_stream_receiver_controller_interface.h" |
| 38 | #include "call/rtx_receive_stream.h" |
| 39 | #include "modules/video_coding/include/video_codec_interface.h" |
| 40 | #include "modules/video_coding/include/video_coding_defines.h" |
| 41 | #include "modules/video_coding/include/video_error_codes.h" |
| 42 | #include "modules/video_coding/timing/timing.h" |
| 43 | #include "modules/video_coding/utility/vp8_header_parser.h" |
| 44 | #include "rtc_base/checks.h" |
| 45 | #include "rtc_base/event.h" |
| 46 | #include "rtc_base/logging.h" |
| 47 | #include "rtc_base/strings/string_builder.h" |
| 48 | #include "rtc_base/synchronization/mutex.h" |
| 49 | #include "rtc_base/thread_annotations.h" |
| 50 | #include "rtc_base/time_utils.h" |
| 51 | #include "rtc_base/trace_event.h" |
| 52 | #include "system_wrappers/include/clock.h" |
| 53 | #include "video/call_stats2.h" |
| 54 | #include "video/frame_dumping_decoder.h" |
| 55 | #include "video/receive_statistics_proxy.h" |
| 56 | #include "video/render/incoming_video_stream.h" |
| 57 | #include "video/task_queue_frame_decode_scheduler.h" |
| 58 |
| 59 | namespace webrtc { |
| 60 |
| 61 | namespace internal { |
| 62 |
| 63 | namespace { |
| 64 |
| 65 | // The default delay before re-requesting a key frame to be sent. |
| 66 | constexpr TimeDelta kMinBaseMinimumDelay = TimeDelta::Zero(); |
| 67 | constexpr TimeDelta kMaxBaseMinimumDelay = TimeDelta::Seconds(10); |
| 68 |
| 69 | // Concrete instance of RecordableEncodedFrame wrapping needed content |
| 70 | // from EncodedFrame. |
| 71 | class WebRtcRecordableEncodedFrame : public RecordableEncodedFrame { |
| 72 | public: |
| 73 | explicit WebRtcRecordableEncodedFrame( |
| 74 | const EncodedFrame& frame, |
| 75 | RecordableEncodedFrame::EncodedResolution resolution) |
| 76 | : buffer_(frame.GetEncodedData()), |
| 77 | render_time_ms_(frame.RenderTime()), |
| 78 | codec_(frame.CodecSpecific()->codecType), |
| 79 | is_key_frame_(frame.FrameType() == VideoFrameType::kVideoFrameKey), |
| 80 | resolution_(resolution) { |
| 81 | if (frame.ColorSpace()) { |
| 82 | color_space_ = *frame.ColorSpace(); |
| 83 | } |
| 84 | } |
| 85 |
| 86 | // VideoEncodedSinkInterface::FrameBuffer |
| 87 | rtc::scoped_refptr<const EncodedImageBufferInterface> encoded_buffer() |
| 88 | const override { |
| 89 | return buffer_; |
| 90 | } |
| 91 |
| 92 | absl::optional<webrtc::ColorSpace> color_space() const override { |
| 93 | return color_space_; |
| 94 | } |
| 95 |
| 96 | VideoCodecType codec() const override { return codec_; } |
| 97 |
| 98 | bool is_key_frame() const override { return is_key_frame_; } |
| 99 |
| 100 | EncodedResolution resolution() const override { return resolution_; } |
| 101 |
| 102 | Timestamp render_time() const override { |
| 103 | return Timestamp::Millis(render_time_ms_); |
| 104 | } |
| 105 |
| 106 | private: |
| 107 | rtc::scoped_refptr<EncodedImageBufferInterface> buffer_; |
| 108 | int64_t render_time_ms_; |
| 109 | VideoCodecType codec_; |
| 110 | bool is_key_frame_; |
| 111 | EncodedResolution resolution_; |
| 112 | absl::optional<webrtc::ColorSpace> color_space_; |
| 113 | }; |
| 114 |
| 115 | RenderResolution InitialDecoderResolution(const FieldTrialsView& field_trials) { |
| 116 | FieldTrialOptional<int> width("w"); |
| 117 | FieldTrialOptional<int> height("h"); |
| 118 | ParseFieldTrial({&width, &height}, |
| 119 | field_trials.Lookup("WebRTC-Video-InitialDecoderResolution")); |
| 120 | if (width && height) { |
| 121 | return RenderResolution(width.Value(), height.Value()); |
| 122 | } |
| 123 |
| 124 | return RenderResolution(320, 180); |
| 125 | } |
| 126 |
| 127 | // Video decoder class to be used for unknown codecs. Doesn't support decoding |
| 128 | // but logs messages to LS_ERROR. |
| 129 | class NullVideoDecoder : public webrtc::VideoDecoder { |
| 130 | public: |
| 131 | bool Configure(const Settings& settings) override { |
| 132 | RTC_LOG(LS_ERROR) << "Can't initialize NullVideoDecoder."; |
| 133 | return true; |
| 134 | } |
| 135 |
| 136 | int32_t Decode(const webrtc::EncodedImage& input_image, |
| 137 | int64_t render_time_ms) override { |
| 138 | RTC_LOG(LS_ERROR) << "The NullVideoDecoder doesn't support decoding."; |
| 139 | return WEBRTC_VIDEO_CODEC_OK; |
| 140 | } |
| 141 |
| 142 | int32_t RegisterDecodeCompleteCallback( |
| 143 | webrtc::DecodedImageCallback* callback) override { |
| 144 | RTC_LOG(LS_ERROR) |
| 145 | << "Can't register decode complete callback on NullVideoDecoder."; |
| 146 | return WEBRTC_VIDEO_CODEC_OK; |
| 147 | } |
| 148 |
| 149 | int32_t Release() override { return WEBRTC_VIDEO_CODEC_OK; } |
| 150 |
| 151 | const char* ImplementationName() const override { return "NullVideoDecoder"; } |
| 152 | }; |
| 153 |
| 154 | bool IsKeyFrameAndUnspecifiedResolution(const EncodedFrame& frame) { |
| 155 | return frame.FrameType() == VideoFrameType::kVideoFrameKey && |
| 156 | frame.EncodedImage()._encodedWidth == 0 && |
| 157 | frame.EncodedImage()._encodedHeight == 0; |
| 158 | } |
| 159 |
| 160 | std::string OptionalDelayToLogString(const absl::optional<TimeDelta> opt) { |
| 161 | return opt.has_value() ? ToLogString(*opt) : "<unset>"; |
| 162 | } |
| 163 |
| 164 | } // namespace |
| 165 |
| 166 | TimeDelta DetermineMaxWaitForFrame(TimeDelta rtp_history, bool is_keyframe) { |
| 167 | // A (arbitrary) conversion factor between the remotely signalled NACK buffer |
| 168 | // time (if not present defaults to 1000ms) and the maximum time we wait for a |
| 169 | // remote frame. Chosen to not change existing defaults when using not |
| 170 | // rtx-time. |
| 171 | const int conversion_factor = 3; |
| 172 | if (rtp_history > TimeDelta::Zero() && |
| 173 | conversion_factor * rtp_history < kMaxWaitForFrame) { |
| 174 | return is_keyframe ? rtp_history : conversion_factor * rtp_history; |
| 175 | } |
| 176 | return is_keyframe ? kMaxWaitForKeyFrame : kMaxWaitForFrame; |
| 177 | } |
| 178 |
| 179 | VideoReceiveStream2::VideoReceiveStream2( |
| 180 | const Environment& env, |
| 181 | Call* call, |
| 182 | int num_cpu_cores, |
| 183 | PacketRouter* packet_router, |
| 184 | VideoReceiveStreamInterface::Config config, |
| 185 | CallStats* call_stats, |
| 186 | std::unique_ptr<VCMTiming> timing, |
| 187 | NackPeriodicProcessor* nack_periodic_processor, |
| 188 | DecodeSynchronizer* decode_sync) |
| 189 | : env_(env), |
| 190 | packet_sequence_checker_(SequenceChecker::kDetached), |
| 191 | decode_sequence_checker_(SequenceChecker::kDetached), |
| 192 | transport_adapter_(config.rtcp_send_transport), |
| 193 | config_(std::move(config)), |
| 194 | num_cpu_cores_(num_cpu_cores), |
| 195 | call_(call), |
| 196 | call_stats_(call_stats), |
| 197 | source_tracker_(&env_.clock()), |
| 198 | stats_proxy_(remote_ssrc(), &env_.clock(), call->worker_thread()), |
| 199 | rtp_receive_statistics_(ReceiveStatistics::Create(&env_.clock())), |
| 200 | timing_(std::move(timing)), |
| 201 | video_receiver_(&env_.clock(), timing_.get(), env_.field_trials()), |
| 202 | rtp_video_stream_receiver_(call->worker_thread(), |
| 203 | &env_.clock(), |
| 204 | &transport_adapter_, |
| 205 | call_stats->AsRtcpRttStats(), |
| 206 | packet_router, |
| 207 | &config_, |
| 208 | rtp_receive_statistics_.get(), |
| 209 | &stats_proxy_, |
| 210 | &stats_proxy_, |
| 211 | nack_periodic_processor, |
| 212 | this, // OnCompleteFrameCallback |
| 213 | std::move(config_.frame_decryptor), |
| 214 | std::move(config_.frame_transformer), |
| 215 | env_.field_trials(), |
| 216 | &env_.event_log()), |
| 217 | rtp_stream_sync_(call->worker_thread(), this), |
| 218 | max_wait_for_keyframe_(DetermineMaxWaitForFrame( |
| 219 | TimeDelta::Millis(config_.rtp.nack.rtp_history_ms), |
| 220 | true)), |
| 221 | max_wait_for_frame_(DetermineMaxWaitForFrame( |
| 222 | TimeDelta::Millis(config_.rtp.nack.rtp_history_ms), |
| 223 | false)), |
| 224 | decode_queue_(env_.task_queue_factory().CreateTaskQueue( |
| 225 | "DecodingQueue", |
| 226 | TaskQueueFactory::Priority::HIGH)) { |
| 227 | RTC_LOG(LS_INFO) << "VideoReceiveStream2: " << config_.ToString(); |
| 228 |
| 229 | RTC_DCHECK(call_->worker_thread()); |
| 230 | RTC_DCHECK(config_.renderer); |
| 231 | RTC_DCHECK(call_stats_); |
| 232 |
| 233 | RTC_DCHECK(!config_.decoders.empty()); |
| 234 | RTC_CHECK(config_.decoder_factory); |
| 235 | std::set<int> decoder_payload_types; |
| 236 | for (const Decoder& decoder : config_.decoders) { |
| 237 | RTC_CHECK(decoder_payload_types.find(decoder.payload_type) == |
| 238 | decoder_payload_types.end()) |
| 239 | << "Duplicate payload type (" << decoder.payload_type |
| 240 | << ") for different decoders."; |
| 241 | decoder_payload_types.insert(decoder.payload_type); |
| 242 | } |
| 243 |
| 244 | timing_->set_render_delay(TimeDelta::Millis(config_.render_delay_ms)); |
| 245 |
| 246 | std::unique_ptr<FrameDecodeScheduler> scheduler = |
| 247 | decode_sync ? decode_sync->CreateSynchronizedFrameScheduler() |
| 248 | : std::make_unique<TaskQueueFrameDecodeScheduler>( |
| 249 | &env_.clock(), call_->worker_thread()); |
| 250 | buffer_ = std::make_unique<VideoStreamBufferController>( |
| 251 | &env_.clock(), call_->worker_thread(), timing_.get(), &stats_proxy_, this, |
| 252 | max_wait_for_keyframe_, max_wait_for_frame_, std::move(scheduler), |
| 253 | env_.field_trials()); |
| 254 |
| 255 | if (!config_.rtp.rtx_associated_payload_types.empty()) { |
| 256 | rtx_receive_stream_ = std::make_unique<RtxReceiveStream>( |
| 257 | &rtp_video_stream_receiver_, |
| 258 | std::move(config_.rtp.rtx_associated_payload_types), remote_ssrc(), |
| 259 | rtp_receive_statistics_.get()); |
| 260 | } else { |
| 261 | rtp_receive_statistics_->EnableRetransmitDetection(remote_ssrc(), true); |
| 262 | } |
| 263 | } |
| 264 |
| 265 | VideoReceiveStream2::~VideoReceiveStream2() { |
| 266 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 267 | RTC_LOG(LS_INFO) << "~VideoReceiveStream2: " << config_.ToString(); |
| 268 | RTC_DCHECK(!media_receiver_); |
| 269 | RTC_DCHECK(!rtx_receiver_); |
| 270 | Stop(); |
| 271 | } |
| 272 |
| 273 | void VideoReceiveStream2::RegisterWithTransport( |
| 274 | RtpStreamReceiverControllerInterface* receiver_controller) { |
| 275 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 276 | RTC_DCHECK(!media_receiver_); |
| 277 | RTC_DCHECK(!rtx_receiver_); |
| 278 | receiver_controller_ = receiver_controller; |
| 279 |
| 280 | // Register with RtpStreamReceiverController. |
| 281 | media_receiver_ = receiver_controller->CreateReceiver( |
| 282 | remote_ssrc(), &rtp_video_stream_receiver_); |
| 283 | if (rtx_ssrc()) { |
| 284 | RTC_DCHECK(rtx_receive_stream_); |
| 285 | rtx_receiver_ = receiver_controller->CreateReceiver( |
| 286 | rtx_ssrc(), rtx_receive_stream_.get()); |
| 287 | } |
| 288 | } |
| 289 |
| 290 | void VideoReceiveStream2::UnregisterFromTransport() { |
| 291 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 292 | media_receiver_.reset(); |
| 293 | rtx_receiver_.reset(); |
| 294 | receiver_controller_ = nullptr; |
| 295 | } |
| 296 |
| 297 | const std::string& VideoReceiveStream2::sync_group() const { |
| 298 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 299 | return config_.sync_group; |
| 300 | } |
| 301 |
| 302 | void VideoReceiveStream2::SignalNetworkState(NetworkState state) { |
| 303 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 304 | rtp_video_stream_receiver_.SignalNetworkState(state); |
| 305 | } |
| 306 |
| 307 | bool VideoReceiveStream2::DeliverRtcp(const uint8_t* packet, size_t length) { |
| 308 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 309 | return rtp_video_stream_receiver_.DeliverRtcp(packet, length); |
| 310 | } |
| 311 |
| 312 | void VideoReceiveStream2::SetSync(Syncable* audio_syncable) { |
| 313 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 314 | rtp_stream_sync_.ConfigureSync(audio_syncable); |
| 315 | } |
| 316 |
| 317 | void VideoReceiveStream2::SetLocalSsrc(uint32_t local_ssrc) { |
| 318 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 319 | if (config_.rtp.local_ssrc == local_ssrc) |
| 320 | return; |
| 321 |
| 322 | // TODO(tommi): Make sure we don't rely on local_ssrc via the config struct. |
| 323 | const_cast<uint32_t&>(config_.rtp.local_ssrc) = local_ssrc; |
| 324 | rtp_video_stream_receiver_.OnLocalSsrcChange(local_ssrc); |
| 325 | } |
| 326 |
| 327 | void VideoReceiveStream2::Start() { |
| 328 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 329 |
| 330 | if (decoder_running_) { |
| 331 | return; |
| 332 | } |
| 333 |
| 334 | const bool protected_by_fec = |
| 335 | config_.rtp.protected_by_flexfec || |
| 336 | rtp_video_stream_receiver_.ulpfec_payload_type() != -1; |
| 337 |
| 338 | if (config_.rtp.nack.rtp_history_ms > 0 && protected_by_fec) { |
| 339 | buffer_->SetProtectionMode(kProtectionNackFEC); |
| 340 | } |
| 341 |
| 342 | transport_adapter_.Enable(); |
| 343 | rtc::VideoSinkInterface<VideoFrame>* renderer = nullptr; |
| 344 | if (config_.enable_prerenderer_smoothing) { |
| 345 | incoming_video_stream_.reset(new IncomingVideoStream( |
| 346 | &env_.task_queue_factory(), config_.render_delay_ms, this)); |
| 347 | renderer = incoming_video_stream_.get(); |
| 348 | } else { |
| 349 | renderer = this; |
| 350 | } |
| 351 |
| 352 | for (const Decoder& decoder : config_.decoders) { |
| 353 | VideoDecoder::Settings settings; |
| 354 | settings.set_codec_type( |
| 355 | PayloadStringToCodecType(decoder.video_format.name)); |
| 356 | settings.set_max_render_resolution( |
| 357 | InitialDecoderResolution(env_.field_trials())); |
| 358 | settings.set_number_of_cores(num_cpu_cores_); |
| 359 |
| 360 | const bool raw_payload = |
| 361 | config_.rtp.raw_payload_types.count(decoder.payload_type) > 0; |
| 362 | { |
| 363 | // TODO(bugs.webrtc.org/11993): Make this call on the network thread. |
| 364 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 365 | rtp_video_stream_receiver_.AddReceiveCodec( |
| 366 | decoder.payload_type, settings.codec_type(), |
| 367 | decoder.video_format.parameters, raw_payload); |
| 368 | } |
| 369 | video_receiver_.RegisterReceiveCodec(decoder.payload_type, settings); |
| 370 | } |
| 371 |
| 372 | RTC_DCHECK(renderer != nullptr); |
| 373 | video_stream_decoder_.reset( |
| 374 | new VideoStreamDecoder(&video_receiver_, &stats_proxy_, renderer)); |
| 375 |
| 376 | // Make sure we register as a stats observer *after* we've prepared the |
| 377 | // `video_stream_decoder_`. |
| 378 | call_stats_->RegisterStatsObserver(this); |
| 379 |
| 380 | // Start decoding on task queue. |
| 381 | stats_proxy_.DecoderThreadStarting(); |
| 382 | decode_queue_->PostTask([this] { |
| 383 | RTC_DCHECK_RUN_ON(&decode_sequence_checker_); |
| 384 | decoder_stopped_ = false; |
| 385 | }); |
| 386 | buffer_->StartNextDecode(true); |
| 387 | decoder_running_ = true; |
| 388 |
| 389 | { |
| 390 | // TODO(bugs.webrtc.org/11993): Make this call on the network thread. |
| 391 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 392 | rtp_video_stream_receiver_.StartReceive(); |
| 393 | } |
| 394 | } |
| 395 |
| 396 | void VideoReceiveStream2::Stop() { |
| 397 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 398 |
| 399 | // TODO(bugs.webrtc.org/11993): Make this call on the network thread. |
| 400 | // Also call `GetUniqueFramesSeen()` at the same time (since it's a counter |
| 401 | // that's updated on the network thread). |
| 402 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 403 | rtp_video_stream_receiver_.StopReceive(); |
| 404 |
| 405 | stats_proxy_.OnUniqueFramesCounted( |
| 406 | rtp_video_stream_receiver_.GetUniqueFramesSeen()); |
| 407 |
| 408 | buffer_->Stop(); |
| 409 | call_stats_->DeregisterStatsObserver(this); |
| 410 |
| 411 | if (decoder_running_) { |
| 412 | rtc::Event done; |
| 413 | decode_queue_->PostTask([this, &done] { |
| 414 | RTC_DCHECK_RUN_ON(&decode_sequence_checker_); |
| 415 | // Set `decoder_stopped_` before deregistering all decoders. This means |
| 416 | // that any pending encoded frame will return early without trying to |
| 417 | // access the decoder database. |
| 418 | decoder_stopped_ = true; |
| 419 | for (const Decoder& decoder : config_.decoders) { |
| 420 | video_receiver_.RegisterExternalDecoder(nullptr, decoder.payload_type); |
| 421 | } |
| 422 | done.Set(); |
| 423 | }); |
| 424 | done.Wait(rtc::Event::kForever); |
| 425 |
| 426 | decoder_running_ = false; |
| 427 | stats_proxy_.DecoderThreadStopped(); |
| 428 |
| 429 | UpdateHistograms(); |
| 430 | } |
| 431 |
| 432 | // TODO(bugs.webrtc.org/11993): Make these calls on the network thread. |
| 433 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 434 | rtp_video_stream_receiver_.RemoveReceiveCodecs(); |
| 435 | video_receiver_.DeregisterReceiveCodecs(); |
| 436 |
| 437 | video_stream_decoder_.reset(); |
| 438 | incoming_video_stream_.reset(); |
| 439 | transport_adapter_.Disable(); |
| 440 | } |
| 441 |
| 442 | void VideoReceiveStream2::SetRtcpMode(RtcpMode mode) { |
| 443 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 444 | // TODO(tommi): Stop using the config struct for the internal state. |
| 445 | const_cast<RtcpMode&>(config_.rtp.rtcp_mode) = mode; |
| 446 | rtp_video_stream_receiver_.SetRtcpMode(mode); |
| 447 | } |
| 448 |
| 449 | void VideoReceiveStream2::SetFlexFecProtection( |
| 450 | RtpPacketSinkInterface* flexfec_sink) { |
| 451 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 452 | rtp_video_stream_receiver_.SetPacketSink(flexfec_sink); |
| 453 | // TODO(tommi): Stop using the config struct for the internal state. |
| 454 | const_cast<RtpPacketSinkInterface*&>(config_.rtp.packet_sink_) = flexfec_sink; |
| 455 | const_cast<bool&>(config_.rtp.protected_by_flexfec) = |
| 456 | (flexfec_sink != nullptr); |
| 457 | } |
| 458 |
| 459 | void VideoReceiveStream2::SetLossNotificationEnabled(bool enabled) { |
| 460 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 461 | // TODO(tommi): Stop using the config struct for the internal state. |
| 462 | const_cast<bool&>(config_.rtp.lntf.enabled) = enabled; |
| 463 | rtp_video_stream_receiver_.SetLossNotificationEnabled(enabled); |
| 464 | } |
| 465 |
| 466 | void VideoReceiveStream2::SetNackHistory(TimeDelta history) { |
| 467 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 468 | RTC_DCHECK_GE(history.ms(), 0); |
| 469 |
| 470 | if (config_.rtp.nack.rtp_history_ms == history.ms()) |
| 471 | return; |
| 472 |
| 473 | // TODO(tommi): Stop using the config struct for the internal state. |
| 474 | const_cast<int&>(config_.rtp.nack.rtp_history_ms) = history.ms(); |
| 475 |
| 476 | const bool protected_by_fec = |
| 477 | config_.rtp.protected_by_flexfec || |
| 478 | rtp_video_stream_receiver_.ulpfec_payload_type() != -1; |
| 479 |
| 480 | buffer_->SetProtectionMode(history.ms() > 0 && protected_by_fec |
| 481 | ? kProtectionNackFEC |
| 482 | : kProtectionNack); |
| 483 |
| 484 | rtp_video_stream_receiver_.SetNackHistory(history); |
| 485 | TimeDelta max_wait_for_keyframe = DetermineMaxWaitForFrame(history, true); |
| 486 | TimeDelta max_wait_for_frame = DetermineMaxWaitForFrame(history, false); |
| 487 |
| 488 | max_wait_for_keyframe_ = max_wait_for_keyframe; |
| 489 | max_wait_for_frame_ = max_wait_for_frame; |
| 490 |
| 491 | buffer_->SetMaxWaits(max_wait_for_keyframe, max_wait_for_frame); |
| 492 | } |
| 493 |
| 494 | void VideoReceiveStream2::SetProtectionPayloadTypes(int red_payload_type, |
| 495 | int ulpfec_payload_type) { |
| 496 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 497 | rtp_video_stream_receiver_.SetProtectionPayloadTypes(red_payload_type, |
| 498 | ulpfec_payload_type); |
| 499 | } |
| 500 |
| 501 | void VideoReceiveStream2::SetRtcpXr(Config::Rtp::RtcpXr rtcp_xr) { |
| 502 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 503 | rtp_video_stream_receiver_.SetReferenceTimeReport( |
| 504 | rtcp_xr.receiver_reference_time_report); |
| 505 | } |
| 506 |
| 507 | void VideoReceiveStream2::SetAssociatedPayloadTypes( |
| 508 | std::map<int, int> associated_payload_types) { |
| 509 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 510 | if (!rtx_receive_stream_) |
| 511 | return; |
| 512 |
| 513 | rtx_receive_stream_->SetAssociatedPayloadTypes( |
| 514 | std::move(associated_payload_types)); |
| 515 | } |
| 516 |
| 517 | void VideoReceiveStream2::CreateAndRegisterExternalDecoder( |
| 518 | const Decoder& decoder) { |
| 519 | TRACE_EVENT0("webrtc", |
| 520 | "VideoReceiveStream2::CreateAndRegisterExternalDecoder"); |
| 521 | std::unique_ptr<VideoDecoder> video_decoder = |
| 522 | config_.decoder_factory->Create(env_, decoder.video_format); |
| 523 | // If we still have no valid decoder, we have to create a "Null" decoder |
| 524 | // that ignores all calls. The reason we can get into this state is that the |
| 525 | // old decoder factory interface doesn't have a way to query supported |
| 526 | // codecs. |
| 527 | if (!video_decoder) { |
| 528 | video_decoder = std::make_unique<NullVideoDecoder>(); |
| 529 | } |
| 530 |
| 531 | std::string decoded_output_file = |
| 532 | env_.field_trials().Lookup("WebRTC-DecoderDataDumpDirectory"); |
| 533 | // Because '/' can't be used inside a field trial parameter, we use ';' |
| 534 | // instead. |
| 535 | // This is only relevant to WebRTC-DecoderDataDumpDirectory |
| 536 | // field trial. ';' is chosen arbitrary. Even though it's a legal character |
| 537 | // in some file systems, we can sacrifice ability to use it in the path to |
| 538 | // dumped video, since it's developers-only feature for debugging. |
| 539 | absl::c_replace(decoded_output_file, ';', '/'); |
| 540 | if (!decoded_output_file.empty()) { |
| 541 | char filename_buffer[256]; |
| 542 | rtc::SimpleStringBuilder ssb(filename_buffer); |
| 543 | ssb << decoded_output_file << "/webrtc_receive_stream_" << remote_ssrc() |
| 544 | << "-" << rtc::TimeMicros() << ".ivf"; |
| 545 | video_decoder = CreateFrameDumpingDecoderWrapper( |
| 546 | std::move(video_decoder), FileWrapper::OpenWriteOnly(ssb.str())); |
| 547 | } |
| 548 |
| 549 | video_receiver_.RegisterExternalDecoder(std::move(video_decoder), |
| 550 | decoder.payload_type); |
| 551 | } |
| 552 |
| 553 | VideoReceiveStreamInterface::Stats VideoReceiveStream2::GetStats() const { |
| 554 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 555 | VideoReceiveStream2::Stats stats = stats_proxy_.GetStats(); |
| 556 | stats.total_bitrate_bps = 0; |
| 557 | StreamStatistician* statistician = |
| 558 | rtp_receive_statistics_->GetStatistician(stats.ssrc); |
| 559 | if (statistician) { |
| 560 | stats.rtp_stats = statistician->GetStats(); |
| 561 | stats.total_bitrate_bps = statistician->BitrateReceived(); |
| 562 | } |
| 563 | if (rtx_ssrc()) { |
| 564 | StreamStatistician* rtx_statistician = |
| 565 | rtp_receive_statistics_->GetStatistician(rtx_ssrc()); |
| 566 | if (rtx_statistician) { |
| 567 | stats.total_bitrate_bps += rtx_statistician->BitrateReceived(); |
| 568 | stats.rtx_rtp_stats = rtx_statistician->GetStats(); |
| 569 | } |
| 570 | } |
| 571 | return stats; |
| 572 | } |
| 573 |
| 574 | void VideoReceiveStream2::UpdateHistograms() { |
| 575 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 576 | absl::optional<int> fraction_lost; |
| 577 | StreamDataCounters rtp_stats; |
| 578 | StreamStatistician* statistician = |
| 579 | rtp_receive_statistics_->GetStatistician(remote_ssrc()); |
| 580 | if (statistician) { |
| 581 | fraction_lost = statistician->GetFractionLostInPercent(); |
| 582 | rtp_stats = statistician->GetReceiveStreamDataCounters(); |
| 583 | } |
| 584 | if (rtx_ssrc()) { |
| 585 | StreamStatistician* rtx_statistician = |
| 586 | rtp_receive_statistics_->GetStatistician(rtx_ssrc()); |
| 587 | if (rtx_statistician) { |
| 588 | StreamDataCounters rtx_stats = |
| 589 | rtx_statistician->GetReceiveStreamDataCounters(); |
| 590 | stats_proxy_.UpdateHistograms(fraction_lost, rtp_stats, &rtx_stats); |
| 591 | return; |
| 592 | } |
| 593 | } |
| 594 | stats_proxy_.UpdateHistograms(fraction_lost, rtp_stats, nullptr); |
| 595 | } |
| 596 |
| 597 | bool VideoReceiveStream2::SetBaseMinimumPlayoutDelayMs(int delay_ms) { |
| 598 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 599 | TimeDelta delay = TimeDelta::Millis(delay_ms); |
| 600 | if (delay < kMinBaseMinimumDelay || delay > kMaxBaseMinimumDelay) { |
| 601 | return false; |
| 602 | } |
| 603 |
| 604 | base_minimum_playout_delay_ = delay; |
| 605 | UpdatePlayoutDelays(); |
| 606 | return true; |
| 607 | } |
| 608 |
| 609 | int VideoReceiveStream2::GetBaseMinimumPlayoutDelayMs() const { |
| 610 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 611 | constexpr TimeDelta kDefaultBaseMinPlayoutDelay = TimeDelta::Millis(-1); |
| 612 | // Unset must be -1. |
| 613 | static_assert(-1 == kDefaultBaseMinPlayoutDelay.ms(), ""); |
| 614 | return base_minimum_playout_delay_.value_or(kDefaultBaseMinPlayoutDelay).ms(); |
| 615 | } |
| 616 |
| 617 | void VideoReceiveStream2::OnFrame(const VideoFrame& video_frame) { |
| 618 | source_tracker_.OnFrameDelivered(video_frame.packet_infos()); |
| 619 | config_.renderer->OnFrame(video_frame); |
| 620 |
| 621 | // TODO(bugs.webrtc.org/10739): we should set local capture clock offset for |
| 622 | // `video_frame.packet_infos`. But VideoFrame is const qualified here. |
| 623 |
| 624 | // For frame delay metrics, calculated in `OnRenderedFrame`, to better reflect |
| 625 | // user experience measurements must be done as close as possible to frame |
| 626 | // rendering moment. Capture current time, which is used for calculation of |
| 627 | // delay metrics in `OnRenderedFrame`, right after frame is passed to |
| 628 | // renderer. Frame may or may be not rendered by this time. This results in |
| 629 | // inaccuracy but is still the best we can do in the absence of "frame |
| 630 | // rendered" callback from the renderer. |
| 631 | VideoFrameMetaData frame_meta(video_frame, env_.clock().CurrentTime()); |
| 632 | call_->worker_thread()->PostTask( |
| 633 | SafeTask(task_safety_.flag(), [frame_meta, this]() { |
| 634 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 635 | int64_t video_playout_ntp_ms; |
| 636 | int64_t sync_offset_ms; |
| 637 | double estimated_freq_khz; |
| 638 | if (rtp_stream_sync_.GetStreamSyncOffsetInMs( |
| 639 | frame_meta.rtp_timestamp, frame_meta.render_time_ms(), |
| 640 | &video_playout_ntp_ms, &sync_offset_ms, &estimated_freq_khz)) { |
| 641 | stats_proxy_.OnSyncOffsetUpdated(video_playout_ntp_ms, sync_offset_ms, |
| 642 | estimated_freq_khz); |
| 643 | } |
| 644 | stats_proxy_.OnRenderedFrame(frame_meta); |
| 645 | })); |
| 646 |
| 647 | webrtc::MutexLock lock(&pending_resolution_mutex_); |
| 648 | if (pending_resolution_.has_value()) { |
| 649 | if (!pending_resolution_->empty() && |
| 650 | (video_frame.width() != static_cast<int>(pending_resolution_->width) || |
| 651 | video_frame.height() != |
| 652 | static_cast<int>(pending_resolution_->height))) { |
| 653 | RTC_LOG(LS_WARNING) |
| 654 | << "Recordable encoded frame stream resolution was reported as " |
| 655 | << pending_resolution_->width << "x" << pending_resolution_->height |
| 656 | << " but the stream is now " << video_frame.width() |
| 657 | << video_frame.height(); |
| 658 | } |
| 659 | pending_resolution_ = RecordableEncodedFrame::EncodedResolution{ |
| 660 | static_cast<unsigned>(video_frame.width()), |
| 661 | static_cast<unsigned>(video_frame.height())}; |
| 662 | } |
| 663 | } |
| 664 |
| 665 | void VideoReceiveStream2::SetFrameDecryptor( |
| 666 | rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) { |
| 667 | rtp_video_stream_receiver_.SetFrameDecryptor(std::move(frame_decryptor)); |
| 668 | } |
| 669 |
| 670 | void VideoReceiveStream2::SetDepacketizerToDecoderFrameTransformer( |
| 671 | rtc::scoped_refptr<FrameTransformerInterface> frame_transformer) { |
| 672 | rtp_video_stream_receiver_.SetDepacketizerToDecoderFrameTransformer( |
| 673 | std::move(frame_transformer)); |
| 674 | } |
| 675 |
| 676 | void VideoReceiveStream2::RequestKeyFrame(Timestamp now) { |
| 677 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 678 | // Called from RtpVideoStreamReceiver (rtp_video_stream_receiver_ is |
| 679 | // ultimately responsible). |
| 680 | rtp_video_stream_receiver_.RequestKeyFrame(); |
| 681 | last_keyframe_request_ = now; |
| 682 | } |
| 683 |
| 684 | void VideoReceiveStream2::OnCompleteFrame(std::unique_ptr<EncodedFrame> frame) { |
| 685 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 686 |
| 687 | if (absl::optional<VideoPlayoutDelay> playout_delay = |
| 688 | frame->EncodedImage().PlayoutDelay()) { |
| 689 | frame_minimum_playout_delay_ = playout_delay->min(); |
| 690 | frame_maximum_playout_delay_ = playout_delay->max(); |
| 691 | UpdatePlayoutDelays(); |
| 692 | } |
| 693 |
| 694 | auto last_continuous_pid = buffer_->InsertFrame(std::move(frame)); |
| 695 | if (last_continuous_pid.has_value()) { |
| 696 | { |
| 697 | // TODO(bugs.webrtc.org/11993): Call on the network thread. |
| 698 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 699 | rtp_video_stream_receiver_.FrameContinuous(*last_continuous_pid); |
| 700 | } |
| 701 | } |
| 702 | } |
| 703 |
| 704 | void VideoReceiveStream2::OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) { |
| 705 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 706 | // TODO(bugs.webrtc.org/13757): Replace with TimeDelta. |
| 707 | buffer_->UpdateRtt(max_rtt_ms); |
| 708 | rtp_video_stream_receiver_.UpdateRtt(max_rtt_ms); |
| 709 | stats_proxy_.OnRttUpdate(avg_rtt_ms); |
| 710 | } |
| 711 |
| 712 | uint32_t VideoReceiveStream2::id() const { |
| 713 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 714 | return remote_ssrc(); |
| 715 | } |
| 716 |
| 717 | absl::optional<Syncable::Info> VideoReceiveStream2::GetInfo() const { |
| 718 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 719 | absl::optional<Syncable::Info> info = |
| 720 | rtp_video_stream_receiver_.GetSyncInfo(); |
| 721 |
| 722 | if (!info) |
| 723 | return absl::nullopt; |
| 724 |
| 725 | info->current_delay_ms = timing_->TargetVideoDelay().ms(); |
| 726 | return info; |
| 727 | } |
| 728 |
| 729 | bool VideoReceiveStream2::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp, |
| 730 | int64_t* time_ms) const { |
| 731 | RTC_DCHECK_NOTREACHED(); |
| 732 | return false; |
| 733 | } |
| 734 |
| 735 | void VideoReceiveStream2::SetEstimatedPlayoutNtpTimestampMs( |
| 736 | int64_t ntp_timestamp_ms, |
| 737 | int64_t time_ms) { |
| 738 | RTC_DCHECK_NOTREACHED(); |
| 739 | } |
| 740 |
| 741 | bool VideoReceiveStream2::SetMinimumPlayoutDelay(int delay_ms) { |
| 742 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 743 | syncable_minimum_playout_delay_ = TimeDelta::Millis(delay_ms); |
| 744 | UpdatePlayoutDelays(); |
| 745 | return true; |
| 746 | } |
| 747 |
| 748 | void VideoReceiveStream2::OnEncodedFrame(std::unique_ptr<EncodedFrame> frame) { |
| 749 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 750 | Timestamp now = env_.clock().CurrentTime(); |
| 751 | const bool keyframe_request_is_due = |
| 752 | !last_keyframe_request_ || |
| 753 | now >= (*last_keyframe_request_ + max_wait_for_keyframe_); |
| 754 | const bool received_frame_is_keyframe = |
| 755 | frame->FrameType() == VideoFrameType::kVideoFrameKey; |
| 756 |
| 757 | // Current OnPreDecode only cares about QP for VP8. |
| 758 | // TODO(brandtr): Move to stats_proxy_.OnDecodableFrame in VSBC, or deprecate. |
| 759 | int qp = -1; |
| 760 | if (frame->CodecSpecific()->codecType == kVideoCodecVP8) { |
| 761 | if (!vp8::GetQp(frame->data(), frame->size(), &qp)) { |
| 762 | RTC_LOG(LS_WARNING) << "Failed to extract QP from VP8 video frame"; |
| 763 | } |
| 764 | } |
| 765 | stats_proxy_.OnPreDecode(frame->CodecSpecific()->codecType, qp); |
| 766 |
| 767 | decode_queue_->PostTask([this, now, keyframe_request_is_due, |
| 768 | received_frame_is_keyframe, frame = std::move(frame), |
| 769 | keyframe_required = keyframe_required_]() mutable { |
| 770 | RTC_DCHECK_RUN_ON(&decode_sequence_checker_); |
| 771 | if (decoder_stopped_) |
| 772 | return; |
| 773 | DecodeFrameResult result = HandleEncodedFrameOnDecodeQueue( |
| 774 | std::move(frame), keyframe_request_is_due, keyframe_required); |
| 775 |
| 776 | // TODO(bugs.webrtc.org/11993): Make this PostTask to the network thread. |
| 777 | call_->worker_thread()->PostTask( |
| 778 | SafeTask(task_safety_.flag(), |
| 779 | [this, now, result = std::move(result), |
| 780 | received_frame_is_keyframe, keyframe_request_is_due]() { |
| 781 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 782 | keyframe_required_ = result.keyframe_required; |
| 783 |
| 784 | if (result.decoded_frame_picture_id) { |
| 785 | rtp_video_stream_receiver_.FrameDecoded( |
| 786 | *result.decoded_frame_picture_id); |
| 787 | } |
| 788 |
| 789 | HandleKeyFrameGeneration(received_frame_is_keyframe, now, |
| 790 | result.force_request_key_frame, |
| 791 | keyframe_request_is_due); |
| 792 | buffer_->StartNextDecode(keyframe_required_); |
| 793 | })); |
| 794 | }); |
| 795 | } |
| 796 |
| 797 | void VideoReceiveStream2::OnDecodableFrameTimeout(TimeDelta wait) { |
| 798 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 799 | Timestamp now = env_.clock().CurrentTime(); |
| 800 |
| 801 | absl::optional<int64_t> last_packet_ms = |
| 802 | rtp_video_stream_receiver_.LastReceivedPacketMs(); |
| 803 |
| 804 | // To avoid spamming keyframe requests for a stream that is not active we |
| 805 | // check if we have received a packet within the last 5 seconds. |
| 806 | constexpr TimeDelta kInactiveDuration = TimeDelta::Seconds(5); |
| 807 | const bool stream_is_active = |
| 808 | last_packet_ms && |
| 809 | now - Timestamp::Millis(*last_packet_ms) < kInactiveDuration; |
| 810 | if (!stream_is_active) |
| 811 | stats_proxy_.OnStreamInactive(); |
| 812 |
| 813 | if (stream_is_active && !IsReceivingKeyFrame(now) && |
| 814 | (!config_.crypto_options.sframe.require_frame_encryption || |
| 815 | rtp_video_stream_receiver_.IsDecryptable())) { |
| 816 | absl::optional<uint32_t> last_timestamp = |
| 817 | rtp_video_stream_receiver_.LastReceivedFrameRtpTimestamp(); |
| 818 | RTC_LOG(LS_WARNING) << "No decodable frame in " << wait |
| 819 | << " requesting keyframe. Last RTP timestamp " |
| 820 | << (last_timestamp ? rtc::ToString(*last_timestamp) |
| 821 | : "<not set>") |
| 822 | << "."; |
| 823 | RequestKeyFrame(now); |
| 824 | } |
| 825 |
| 826 | buffer_->StartNextDecode(keyframe_required_); |
| 827 | } |
| 828 |
| 829 | VideoReceiveStream2::DecodeFrameResult |
| 830 | VideoReceiveStream2::HandleEncodedFrameOnDecodeQueue( |
| 831 | std::unique_ptr<EncodedFrame> frame, |
| 832 | bool keyframe_request_is_due, |
| 833 | bool keyframe_required) { |
| 834 | RTC_DCHECK_RUN_ON(&decode_sequence_checker_); |
| 835 |
| 836 | bool force_request_key_frame = false; |
| 837 | absl::optional<int64_t> decoded_frame_picture_id; |
| 838 |
| 839 | if (!video_receiver_.IsExternalDecoderRegistered(frame->PayloadType())) { |
| 840 | // Look for the decoder with this payload type. |
| 841 | for (const Decoder& decoder : config_.decoders) { |
| 842 | if (decoder.payload_type == frame->PayloadType()) { |
| 843 | CreateAndRegisterExternalDecoder(decoder); |
| 844 | break; |
| 845 | } |
| 846 | } |
| 847 | } |
| 848 |
| 849 | int64_t frame_id = frame->Id(); |
| 850 | int decode_result = DecodeAndMaybeDispatchEncodedFrame(std::move(frame)); |
| 851 | if (decode_result == WEBRTC_VIDEO_CODEC_OK || |
| 852 | decode_result == WEBRTC_VIDEO_CODEC_OK_REQUEST_KEYFRAME) { |
| 853 | keyframe_required = false; |
| 854 | frame_decoded_ = true; |
| 855 |
| 856 | decoded_frame_picture_id = frame_id; |
| 857 |
| 858 | if (decode_result == WEBRTC_VIDEO_CODEC_OK_REQUEST_KEYFRAME) |
| 859 | force_request_key_frame = true; |
| 860 | } else if (!frame_decoded_ || !keyframe_required || keyframe_request_is_due) { |
| 861 | keyframe_required = true; |
| 862 | // TODO(philipel): Remove this keyframe request when downstream project |
| 863 | // has been fixed. |
| 864 | force_request_key_frame = true; |
| 865 | } |
| 866 |
| 867 | return DecodeFrameResult{ |
| 868 | .force_request_key_frame = force_request_key_frame, |
| 869 | .decoded_frame_picture_id = std::move(decoded_frame_picture_id), |
| 870 | .keyframe_required = keyframe_required, |
| 871 | }; |
| 872 | } |
| 873 |
| 874 | int VideoReceiveStream2::DecodeAndMaybeDispatchEncodedFrame( |
| 875 | std::unique_ptr<EncodedFrame> frame) { |
| 876 | RTC_DCHECK_RUN_ON(&decode_sequence_checker_); |
| 877 |
| 878 | // If `buffered_encoded_frames_` grows out of control (=60 queued frames), |
| 879 | // maybe due to a stuck decoder, we just halt the process here and log the |
| 880 | // error. |
| 881 | const bool encoded_frame_output_enabled = |
| 882 | encoded_frame_buffer_function_ != nullptr && |
| 883 | buffered_encoded_frames_.size() < kBufferedEncodedFramesMaxSize; |
| 884 | EncodedFrame* frame_ptr = frame.get(); |
| 885 | if (encoded_frame_output_enabled) { |
| 886 | // If we receive a key frame with unset resolution, hold on dispatching the |
| 887 | // frame and following ones until we know a resolution of the stream. |
| 888 | // NOTE: The code below has a race where it can report the wrong |
| 889 | // resolution for keyframes after an initial keyframe of other resolution. |
| 890 | // However, the only known consumer of this information is the W3C |
| 891 | // MediaRecorder and it will only use the resolution in the first encoded |
| 892 | // keyframe from WebRTC, so misreporting is fine. |
| 893 | buffered_encoded_frames_.push_back(std::move(frame)); |
| 894 | if (buffered_encoded_frames_.size() == kBufferedEncodedFramesMaxSize) |
| 895 | RTC_LOG(LS_ERROR) << "About to halt recordable encoded frame output due " |
| 896 | "to too many buffered frames."; |
| 897 |
| 898 | webrtc::MutexLock lock(&pending_resolution_mutex_); |
| 899 | if (IsKeyFrameAndUnspecifiedResolution(*frame_ptr) && |
| 900 | !pending_resolution_.has_value()) |
| 901 | pending_resolution_.emplace(); |
| 902 | } |
| 903 |
| 904 | int decode_result = video_receiver_.Decode(frame_ptr); |
| 905 | if (decode_result < WEBRTC_VIDEO_CODEC_OK) { |
| 906 | // Asynchronous decoders may delay error reporting, potentially resulting in |
| 907 | // error reports reflecting issues that occurred several frames back. |
| 908 | RTC_LOG(LS_WARNING) |
| 909 | << "Failed to decode frame. Return code: " << decode_result |
| 910 | << ", SSRC: " << remote_ssrc() |
| 911 | << ", frame RTP timestamp: " << frame_ptr->RtpTimestamp() |
| 912 | << ", type: " << VideoFrameTypeToString(frame_ptr->FrameType()) |
| 913 | << ", size: " << frame_ptr->size() |
| 914 | << ", width: " << frame_ptr->_encodedWidth |
| 915 | << ", height: " << frame_ptr->_encodedHeight |
| 916 | << ", spatial idx: " << frame_ptr->SpatialIndex().value_or(-1) |
| 917 | << ", temporal idx: " << frame_ptr->TemporalIndex().value_or(-1) |
| 918 | << ", id: " << frame_ptr->Id(); |
| 919 | } |
| 920 |
| 921 | if (encoded_frame_output_enabled) { |
| 922 | absl::optional<RecordableEncodedFrame::EncodedResolution> |
| 923 | pending_resolution; |
| 924 | { |
| 925 | // Fish out `pending_resolution_` to avoid taking the mutex on every lap |
| 926 | // or dispatching under the mutex in the flush loop. |
| 927 | webrtc::MutexLock lock(&pending_resolution_mutex_); |
| 928 | if (pending_resolution_.has_value()) |
| 929 | pending_resolution = *pending_resolution_; |
| 930 | } |
| 931 | if (!pending_resolution.has_value() || !pending_resolution->empty()) { |
| 932 | // Flush the buffered frames. |
| 933 | for (const auto& frame : buffered_encoded_frames_) { |
| 934 | RecordableEncodedFrame::EncodedResolution resolution{ |
| 935 | frame->EncodedImage()._encodedWidth, |
| 936 | frame->EncodedImage()._encodedHeight}; |
| 937 | if (IsKeyFrameAndUnspecifiedResolution(*frame)) { |
| 938 | RTC_DCHECK(!pending_resolution->empty()); |
| 939 | resolution = *pending_resolution; |
| 940 | } |
| 941 | encoded_frame_buffer_function_( |
| 942 | WebRtcRecordableEncodedFrame(*frame, resolution)); |
| 943 | } |
| 944 | buffered_encoded_frames_.clear(); |
| 945 | } |
| 946 | } |
| 947 | return decode_result; |
| 948 | } |
| 949 |
| 950 | void VideoReceiveStream2::HandleKeyFrameGeneration( |
| 951 | bool received_frame_is_keyframe, |
| 952 | Timestamp now, |
| 953 | bool always_request_key_frame, |
| 954 | bool keyframe_request_is_due) { |
| 955 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 956 | bool request_key_frame = always_request_key_frame; |
| 957 |
| 958 | // Repeat sending keyframe requests if we've requested a keyframe. |
| 959 | if (keyframe_generation_requested_) { |
| 960 | if (received_frame_is_keyframe) { |
| 961 | keyframe_generation_requested_ = false; |
| 962 | } else if (keyframe_request_is_due) { |
| 963 | if (!IsReceivingKeyFrame(now)) { |
| 964 | request_key_frame = true; |
| 965 | } |
| 966 | } else { |
| 967 | // It hasn't been long enough since the last keyframe request, do nothing. |
| 968 | } |
| 969 | } |
| 970 |
| 971 | if (request_key_frame) { |
| 972 | // HandleKeyFrameGeneration is initiated from the decode thread - |
| 973 | // RequestKeyFrame() triggers a call back to the decode thread. |
| 974 | // Perhaps there's a way to avoid that. |
| 975 | RequestKeyFrame(now); |
| 976 | } |
| 977 | } |
| 978 |
| 979 | bool VideoReceiveStream2::IsReceivingKeyFrame(Timestamp now) const { |
| 980 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 981 | absl::optional<int64_t> last_keyframe_packet_ms = |
| 982 | rtp_video_stream_receiver_.LastReceivedKeyframePacketMs(); |
| 983 |
| 984 | // If we recently have been receiving packets belonging to a keyframe then |
| 985 | // we assume a keyframe is currently being received. |
| 986 | bool receiving_keyframe = last_keyframe_packet_ms && |
| 987 | now - Timestamp::Millis(*last_keyframe_packet_ms) < |
| 988 | max_wait_for_keyframe_; |
| 989 | return receiving_keyframe; |
| 990 | } |
| 991 |
| 992 | void VideoReceiveStream2::UpdatePlayoutDelays() const { |
| 993 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 994 | const std::initializer_list<absl::optional<TimeDelta>> min_delays = { |
| 995 | frame_minimum_playout_delay_, base_minimum_playout_delay_, |
| 996 | syncable_minimum_playout_delay_}; |
| 997 |
| 998 | // Since nullopt < anything, this will return the largest of the minumum |
| 999 | // delays, or nullopt if all are nullopt. |
| 1000 | absl::optional<TimeDelta> minimum_delay = std::max(min_delays); |
| 1001 | if (minimum_delay) { |
| 1002 | auto num_playout_delays_set = |
| 1003 | absl::c_count_if(min_delays, [](auto opt) { return opt.has_value(); }); |
| 1004 | if (num_playout_delays_set > 1 && |
| 1005 | timing_->min_playout_delay() != minimum_delay) { |
| 1006 | RTC_LOG(LS_WARNING) |
| 1007 | << "Multiple playout delays set. Actual delay value set to " |
| 1008 | << *minimum_delay << " frame min delay=" |
| 1009 | << OptionalDelayToLogString(frame_minimum_playout_delay_) |
| 1010 | << " base min delay=" |
| 1011 | << OptionalDelayToLogString(base_minimum_playout_delay_) |
| 1012 | << " sync min delay=" |
| 1013 | << OptionalDelayToLogString(syncable_minimum_playout_delay_); |
| 1014 | } |
| 1015 | timing_->set_min_playout_delay(*minimum_delay); |
| 1016 | if (frame_minimum_playout_delay_ == TimeDelta::Zero() && |
| 1017 | frame_maximum_playout_delay_ > TimeDelta::Zero()) { |
| 1018 | // TODO(kron): Estimate frame rate from video stream. |
| 1019 | constexpr Frequency kFrameRate = Frequency::Hertz(60); |
| 1020 | // Convert playout delay in ms to number of frames. |
| 1021 | int max_composition_delay_in_frames = |
| 1022 | std::lrint(*frame_maximum_playout_delay_ * kFrameRate); |
| 1023 | // Subtract frames in buffer. |
| 1024 | max_composition_delay_in_frames = |
| 1025 | std::max(max_composition_delay_in_frames - buffer_->Size(), 0); |
| 1026 | timing_->SetMaxCompositionDelayInFrames(max_composition_delay_in_frames); |
| 1027 | } |
| 1028 | } |
| 1029 |
| 1030 | if (frame_maximum_playout_delay_) { |
| 1031 | timing_->set_max_playout_delay(*frame_maximum_playout_delay_); |
| 1032 | } |
| 1033 | } |
| 1034 |
| 1035 | std::vector<webrtc::RtpSource> VideoReceiveStream2::GetSources() const { |
| 1036 | return source_tracker_.GetSources(); |
| 1037 | } |
| 1038 |
| 1039 | VideoReceiveStream2::RecordingState |
| 1040 | VideoReceiveStream2::SetAndGetRecordingState(RecordingState state, |
| 1041 | bool generate_key_frame) { |
| 1042 | RTC_DCHECK_RUN_ON(&worker_sequence_checker_); |
| 1043 | rtc::Event event; |
| 1044 |
| 1045 | // Save old state, set the new state. |
| 1046 | RecordingState old_state; |
| 1047 |
| 1048 | absl::optional<Timestamp> last_keyframe_request; |
| 1049 | { |
| 1050 | // TODO(bugs.webrtc.org/11993): Post this to the network thread. |
| 1051 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 1052 | last_keyframe_request = last_keyframe_request_; |
| 1053 | last_keyframe_request_ = |
| 1054 | generate_key_frame |
| 1055 | ? env_.clock().CurrentTime() |
| 1056 | : Timestamp::Millis(state.last_keyframe_request_ms.value_or(0)); |
| 1057 | } |
| 1058 |
| 1059 | decode_queue_->PostTask( |
| 1060 | [this, &event, &old_state, callback = std::move(state.callback), |
| 1061 | last_keyframe_request = std::move(last_keyframe_request)] { |
| 1062 | RTC_DCHECK_RUN_ON(&decode_sequence_checker_); |
| 1063 | old_state.callback = std::move(encoded_frame_buffer_function_); |
| 1064 | encoded_frame_buffer_function_ = std::move(callback); |
| 1065 |
| 1066 | old_state.last_keyframe_request_ms = |
| 1067 | last_keyframe_request.value_or(Timestamp::Zero()).ms(); |
| 1068 |
| 1069 | event.Set(); |
| 1070 | }); |
| 1071 |
| 1072 | if (generate_key_frame) { |
| 1073 | rtp_video_stream_receiver_.RequestKeyFrame(); |
| 1074 | { |
| 1075 | // TODO(bugs.webrtc.org/11993): Post this to the network thread. |
| 1076 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 1077 | keyframe_generation_requested_ = true; |
| 1078 | } |
| 1079 | } |
| 1080 |
| 1081 | event.Wait(rtc::Event::kForever); |
| 1082 | return old_state; |
| 1083 | } |
| 1084 |
| 1085 | void VideoReceiveStream2::GenerateKeyFrame() { |
| 1086 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 1087 | RequestKeyFrame(env_.clock().CurrentTime()); |
| 1088 | keyframe_generation_requested_ = true; |
| 1089 | } |
| 1090 |
| 1091 | void VideoReceiveStream2::UpdateRtxSsrc(uint32_t ssrc) { |
| 1092 | RTC_DCHECK_RUN_ON(&packet_sequence_checker_); |
| 1093 | RTC_DCHECK(rtx_receive_stream_); |
| 1094 |
| 1095 | rtx_receiver_.reset(); |
| 1096 | updated_rtx_ssrc_ = ssrc; |
| 1097 | rtx_receiver_ = receiver_controller_->CreateReceiver( |
| 1098 | rtx_ssrc(), rtx_receive_stream_.get()); |
| 1099 | } |
| 1100 |
| 1101 | } // namespace internal |
| 1102 | } // namespace webrtc |
| 1103 |