1 /*
2  *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
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_stream.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/video/encoded_image.h"
27 #include "api/video_codecs/sdp_video_format.h"
28 #include "api/video_codecs/video_codec.h"
29 #include "api/video_codecs/video_decoder_factory.h"
30 #include "api/video_codecs/video_encoder.h"
31 #include "call/rtp_stream_receiver_controller_interface.h"
32 #include "call/rtx_receive_stream.h"
33 #include "common_video/include/incoming_video_stream.h"
34 #include "media/base/h264_profile_level_id.h"
35 #include "modules/utility/include/process_thread.h"
36 #include "modules/video_coding/include/video_codec_interface.h"
37 #include "modules/video_coding/include/video_coding_defines.h"
38 #include "modules/video_coding/include/video_error_codes.h"
39 #include "modules/video_coding/timing.h"
40 #include "modules/video_coding/utility/vp8_header_parser.h"
41 #include "rtc_base/checks.h"
42 #include "rtc_base/experiments/keyframe_interval_settings.h"
43 #include "rtc_base/location.h"
44 #include "rtc_base/logging.h"
45 #include "rtc_base/strings/string_builder.h"
46 #include "rtc_base/system/thread_registry.h"
47 #include "rtc_base/time_utils.h"
48 #include "rtc_base/trace_event.h"
49 #include "system_wrappers/include/clock.h"
50 #include "system_wrappers/include/field_trial.h"
51 #include "video/call_stats.h"
52 #include "video/frame_dumping_decoder.h"
53 #include "video/receive_statistics_proxy.h"
54 
55 namespace webrtc {
56 
57 namespace internal {
58 constexpr int VideoReceiveStream::kMaxWaitForKeyFrameMs;
59 }  // namespace internal
60 
61 namespace {
62 
63 using video_coding::EncodedFrame;
64 using ReturnReason = video_coding::FrameBuffer::ReturnReason;
65 
66 constexpr int kMinBaseMinimumDelayMs = 0;
67 constexpr int kMaxBaseMinimumDelayMs = 10000;
68 
69 constexpr int kMaxWaitForFrameMs = 3000;
70 
71 // Concrete instance of RecordableEncodedFrame wrapping needed content
72 // from video_coding::EncodedFrame.
73 class WebRtcRecordableEncodedFrame : public RecordableEncodedFrame {
74  public:
WebRtcRecordableEncodedFrame(const EncodedFrame & frame)75   explicit WebRtcRecordableEncodedFrame(const EncodedFrame& frame)
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_{frame.EncodedImage()._encodedWidth,
81                     frame.EncodedImage()._encodedHeight} {
82     if (frame.ColorSpace()) {
83       color_space_ = *frame.ColorSpace();
84     }
85   }
86 
87   // VideoEncodedSinkInterface::FrameBuffer
encoded_buffer() const88   rtc::scoped_refptr<const EncodedImageBufferInterface> encoded_buffer()
89       const override {
90     return buffer_;
91   }
92 
color_space() const93   absl::optional<webrtc::ColorSpace> color_space() const override {
94     return color_space_;
95   }
96 
codec() const97   VideoCodecType codec() const override { return codec_; }
98 
is_key_frame() const99   bool is_key_frame() const override { return is_key_frame_; }
100 
resolution() const101   EncodedResolution resolution() const override { return resolution_; }
102 
render_time() const103   Timestamp render_time() const override {
104     return Timestamp::Millis(render_time_ms_);
105   }
106 
107  private:
108   rtc::scoped_refptr<EncodedImageBufferInterface> buffer_;
109   int64_t render_time_ms_;
110   VideoCodecType codec_;
111   bool is_key_frame_;
112   EncodedResolution resolution_;
113   absl::optional<webrtc::ColorSpace> color_space_;
114 };
115 
CreateDecoderVideoCodec(const VideoReceiveStream::Decoder & decoder)116 VideoCodec CreateDecoderVideoCodec(const VideoReceiveStream::Decoder& decoder) {
117   VideoCodec codec;
118   memset(&codec, 0, sizeof(codec));
119 
120   codec.codecType = PayloadStringToCodecType(decoder.video_format.name);
121 
122   if (codec.codecType == kVideoCodecVP8) {
123     *(codec.VP8()) = VideoEncoder::GetDefaultVp8Settings();
124   } else if (codec.codecType == kVideoCodecVP9) {
125     *(codec.VP9()) = VideoEncoder::GetDefaultVp9Settings();
126   } else if (codec.codecType == kVideoCodecH264) {
127     *(codec.H264()) = VideoEncoder::GetDefaultH264Settings();
128   } else if (codec.codecType == kVideoCodecMultiplex) {
129     VideoReceiveStream::Decoder associated_decoder = decoder;
130     associated_decoder.video_format =
131         SdpVideoFormat(CodecTypeToPayloadString(kVideoCodecVP9));
132     VideoCodec associated_codec = CreateDecoderVideoCodec(associated_decoder);
133     associated_codec.codecType = kVideoCodecMultiplex;
134     return associated_codec;
135   }
136 
137   codec.width = 320;
138   codec.height = 180;
139   const int kDefaultStartBitrate = 300;
140   codec.startBitrate = codec.minBitrate = codec.maxBitrate =
141       kDefaultStartBitrate;
142 
143   return codec;
144 }
145 
146 // Video decoder class to be used for unknown codecs. Doesn't support decoding
147 // but logs messages to LS_ERROR.
148 class NullVideoDecoder : public webrtc::VideoDecoder {
149  public:
InitDecode(const webrtc::VideoCodec * codec_settings,int32_t number_of_cores)150   int32_t InitDecode(const webrtc::VideoCodec* codec_settings,
151                      int32_t number_of_cores) override {
152     RTC_LOG(LS_ERROR) << "Can't initialize NullVideoDecoder.";
153     return WEBRTC_VIDEO_CODEC_OK;
154   }
155 
Decode(const webrtc::EncodedImage & input_image,bool missing_frames,int64_t render_time_ms)156   int32_t Decode(const webrtc::EncodedImage& input_image,
157                  bool missing_frames,
158                  int64_t render_time_ms) override {
159     RTC_LOG(LS_ERROR) << "The NullVideoDecoder doesn't support decoding.";
160     return WEBRTC_VIDEO_CODEC_OK;
161   }
162 
RegisterDecodeCompleteCallback(webrtc::DecodedImageCallback * callback)163   int32_t RegisterDecodeCompleteCallback(
164       webrtc::DecodedImageCallback* callback) override {
165     RTC_LOG(LS_ERROR)
166         << "Can't register decode complete callback on NullVideoDecoder.";
167     return WEBRTC_VIDEO_CODEC_OK;
168   }
169 
Release()170   int32_t Release() override { return WEBRTC_VIDEO_CODEC_OK; }
171 
ImplementationName() const172   const char* ImplementationName() const override { return "NullVideoDecoder"; }
173 };
174 
175 // TODO(https://bugs.webrtc.org/9974): Consider removing this workaround.
176 // Maximum time between frames before resetting the FrameBuffer to avoid RTP
177 // timestamps wraparound to affect FrameBuffer.
178 constexpr int kInactiveStreamThresholdMs = 600000;  //  10 minutes.
179 
180 }  // namespace
181 
182 namespace internal {
183 
VideoReceiveStream(TaskQueueFactory * task_queue_factory,RtpStreamReceiverControllerInterface * receiver_controller,int num_cpu_cores,PacketRouter * packet_router,VideoReceiveStream::Config config,ProcessThread * process_thread,CallStats * call_stats,Clock * clock,VCMTiming * timing)184 VideoReceiveStream::VideoReceiveStream(
185     TaskQueueFactory* task_queue_factory,
186     RtpStreamReceiverControllerInterface* receiver_controller,
187     int num_cpu_cores,
188     PacketRouter* packet_router,
189     VideoReceiveStream::Config config,
190     ProcessThread* process_thread,
191     CallStats* call_stats,
192     Clock* clock,
193     VCMTiming* timing)
194     : task_queue_factory_(task_queue_factory),
195       transport_adapter_(config.rtcp_send_transport),
196       config_(std::move(config)),
197       num_cpu_cores_(num_cpu_cores),
198       process_thread_(process_thread),
199       clock_(clock),
200       call_stats_(call_stats),
201       source_tracker_(clock_),
202       stats_proxy_(&config_, clock_),
203       rtp_receive_statistics_(ReceiveStatistics::Create(clock_)),
204       timing_(timing),
205       video_receiver_(clock_, timing_.get()),
206       rtp_video_stream_receiver_(clock_,
207                                  &transport_adapter_,
208                                  call_stats,
209                                  packet_router,
210                                  &config_,
211                                  rtp_receive_statistics_.get(),
212                                  &stats_proxy_,
213                                  &stats_proxy_,
214                                  process_thread_,
215                                  this,     // NackSender
216                                  nullptr,  // Use default KeyFrameRequestSender
217                                  this,     // OnCompleteFrameCallback
218                                  config_.frame_decryptor,
219                                  config_.frame_transformer),
220       rtp_stream_sync_(this),
221       max_wait_for_keyframe_ms_(KeyframeIntervalSettings::ParseFromFieldTrials()
222                                     .MaxWaitForKeyframeMs()
223                                     .value_or(kMaxWaitForKeyFrameMs)),
224       max_wait_for_frame_ms_(KeyframeIntervalSettings::ParseFromFieldTrials()
225                                  .MaxWaitForFrameMs()
226                                  .value_or(kMaxWaitForFrameMs)),
227       decode_queue_(task_queue_factory_->CreateTaskQueue(
228           "DecodingQueue",
229           TaskQueueFactory::Priority::HIGH)) {
230   RTC_LOG(LS_INFO) << "VideoReceiveStream: " << config_.ToString();
231 
232   RTC_DCHECK(config_.renderer);
233   RTC_DCHECK(process_thread_);
234   RTC_DCHECK(call_stats_);
235 
236   module_process_sequence_checker_.Detach();
237   network_sequence_checker_.Detach();
238 
239   RTC_DCHECK(!config_.decoders.empty());
240   RTC_CHECK(config_.decoder_factory);
241   std::set<int> decoder_payload_types;
242   for (const Decoder& decoder : config_.decoders) {
243     RTC_CHECK(decoder_payload_types.find(decoder.payload_type) ==
244               decoder_payload_types.end())
245         << "Duplicate payload type (" << decoder.payload_type
246         << ") for different decoders.";
247     decoder_payload_types.insert(decoder.payload_type);
248   }
249 
250   timing_->set_render_delay(config_.render_delay_ms);
251 
252   frame_buffer_.reset(
253       new video_coding::FrameBuffer(clock_, timing_.get(), &stats_proxy_));
254 
255   process_thread_->RegisterModule(&rtp_stream_sync_, RTC_FROM_HERE);
256   // Register with RtpStreamReceiverController.
257   media_receiver_ = receiver_controller->CreateReceiver(
258       config_.rtp.remote_ssrc, &rtp_video_stream_receiver_);
259   if (config_.rtp.rtx_ssrc) {
260     rtx_receive_stream_ = std::make_unique<RtxReceiveStream>(
261         &rtp_video_stream_receiver_, config.rtp.rtx_associated_payload_types,
262         config_.rtp.remote_ssrc, rtp_receive_statistics_.get());
263     rtx_receiver_ = receiver_controller->CreateReceiver(
264         config_.rtp.rtx_ssrc, rtx_receive_stream_.get());
265   } else {
266     rtp_receive_statistics_->EnableRetransmitDetection(config.rtp.remote_ssrc,
267                                                        true);
268   }
269 }
270 
VideoReceiveStream(TaskQueueFactory * task_queue_factory,RtpStreamReceiverControllerInterface * receiver_controller,int num_cpu_cores,PacketRouter * packet_router,VideoReceiveStream::Config config,ProcessThread * process_thread,CallStats * call_stats,Clock * clock)271 VideoReceiveStream::VideoReceiveStream(
272     TaskQueueFactory* task_queue_factory,
273     RtpStreamReceiverControllerInterface* receiver_controller,
274     int num_cpu_cores,
275     PacketRouter* packet_router,
276     VideoReceiveStream::Config config,
277     ProcessThread* process_thread,
278     CallStats* call_stats,
279     Clock* clock)
280     : VideoReceiveStream(task_queue_factory,
281                          receiver_controller,
282                          num_cpu_cores,
283                          packet_router,
284                          std::move(config),
285                          process_thread,
286                          call_stats,
287                          clock,
288                          new VCMTiming(clock)) {}
289 
~VideoReceiveStream()290 VideoReceiveStream::~VideoReceiveStream() {
291   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
292   RTC_LOG(LS_INFO) << "~VideoReceiveStream: " << config_.ToString();
293   Stop();
294   process_thread_->DeRegisterModule(&rtp_stream_sync_);
295 }
296 
SignalNetworkState(NetworkState state)297 void VideoReceiveStream::SignalNetworkState(NetworkState state) {
298   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
299   rtp_video_stream_receiver_.SignalNetworkState(state);
300 }
301 
DeliverRtcp(const uint8_t * packet,size_t length)302 bool VideoReceiveStream::DeliverRtcp(const uint8_t* packet, size_t length) {
303   return rtp_video_stream_receiver_.DeliverRtcp(packet, length);
304 }
305 
SetSync(Syncable * audio_syncable)306 void VideoReceiveStream::SetSync(Syncable* audio_syncable) {
307   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
308   rtp_stream_sync_.ConfigureSync(audio_syncable);
309 }
310 
Start()311 void VideoReceiveStream::Start() {
312   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
313 
314   if (decoder_running_) {
315     return;
316   }
317 
318   const bool protected_by_fec = config_.rtp.protected_by_flexfec ||
319                                 rtp_video_stream_receiver_.IsUlpfecEnabled();
320 
321   if (rtp_video_stream_receiver_.IsRetransmissionsEnabled() &&
322       protected_by_fec) {
323     frame_buffer_->SetProtectionMode(kProtectionNackFEC);
324   }
325 
326   transport_adapter_.Enable();
327   rtc::VideoSinkInterface<VideoFrame>* renderer = nullptr;
328   if (config_.enable_prerenderer_smoothing) {
329     incoming_video_stream_.reset(new IncomingVideoStream(
330         task_queue_factory_, config_.render_delay_ms, this));
331     renderer = incoming_video_stream_.get();
332   } else {
333     renderer = this;
334   }
335 
336   for (const Decoder& decoder : config_.decoders) {
337     std::unique_ptr<VideoDecoder> video_decoder =
338         config_.decoder_factory->LegacyCreateVideoDecoder(decoder.video_format,
339                                                           config_.stream_id);
340     // If we still have no valid decoder, we have to create a "Null" decoder
341     // that ignores all calls. The reason we can get into this state is that the
342     // old decoder factory interface doesn't have a way to query supported
343     // codecs.
344     if (!video_decoder) {
345       video_decoder = std::make_unique<NullVideoDecoder>();
346     }
347 
348     std::string decoded_output_file =
349         field_trial::FindFullName("WebRTC-DecoderDataDumpDirectory");
350     // Because '/' can't be used inside a field trial parameter, we use ';'
351     // instead.
352     // This is only relevant to WebRTC-DecoderDataDumpDirectory
353     // field trial. ';' is chosen arbitrary. Even though it's a legal character
354     // in some file systems, we can sacrifice ability to use it in the path to
355     // dumped video, since it's developers-only feature for debugging.
356     absl::c_replace(decoded_output_file, ';', '/');
357     if (!decoded_output_file.empty()) {
358       char filename_buffer[256];
359       rtc::SimpleStringBuilder ssb(filename_buffer);
360       ssb << decoded_output_file << "/webrtc_receive_stream_"
361           << this->config_.rtp.remote_ssrc << "-" << rtc::TimeMicros()
362           << ".ivf";
363       video_decoder = CreateFrameDumpingDecoderWrapper(
364           std::move(video_decoder), FileWrapper::OpenWriteOnly(ssb.str()));
365     }
366 
367     video_decoders_.push_back(std::move(video_decoder));
368 
369     video_receiver_.RegisterExternalDecoder(video_decoders_.back().get(),
370                                             decoder.payload_type);
371     VideoCodec codec = CreateDecoderVideoCodec(decoder);
372 
373     const bool raw_payload =
374         config_.rtp.raw_payload_types.count(decoder.payload_type) > 0;
375     rtp_video_stream_receiver_.AddReceiveCodec(decoder.payload_type, codec,
376                                                decoder.video_format.parameters,
377                                                raw_payload);
378     RTC_CHECK_EQ(VCM_OK, video_receiver_.RegisterReceiveCodec(
379                              decoder.payload_type, &codec, num_cpu_cores_));
380   }
381 
382   RTC_DCHECK(renderer != nullptr);
383   video_stream_decoder_.reset(
384       new VideoStreamDecoder(&video_receiver_, &stats_proxy_, renderer));
385 
386   // Make sure we register as a stats observer *after* we've prepared the
387   // |video_stream_decoder_|.
388   call_stats_->RegisterStatsObserver(this);
389 
390   // Start decoding on task queue.
391   video_receiver_.DecoderThreadStarting();
392   stats_proxy_.DecoderThreadStarting();
393   decode_queue_.PostTask([this] {
394     RTC_DCHECK_RUN_ON(&decode_queue_);
395     decoder_stopped_ = false;
396     StartNextDecode();
397   });
398   decoder_running_ = true;
399   rtp_video_stream_receiver_.StartReceive();
400 }
401 
Stop()402 void VideoReceiveStream::Stop() {
403   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
404   rtp_video_stream_receiver_.StopReceive();
405 
406   stats_proxy_.OnUniqueFramesCounted(
407       rtp_video_stream_receiver_.GetUniqueFramesSeen());
408 
409   decode_queue_.PostTask([this] { frame_buffer_->Stop(); });
410 
411   call_stats_->DeregisterStatsObserver(this);
412 
413   if (decoder_running_) {
414     rtc::Event done;
415     decode_queue_.PostTask([this, &done] {
416       RTC_DCHECK_RUN_ON(&decode_queue_);
417       decoder_stopped_ = true;
418       done.Set();
419     });
420     done.Wait(rtc::Event::kForever);
421 
422     decoder_running_ = false;
423     video_receiver_.DecoderThreadStopped();
424     stats_proxy_.DecoderThreadStopped();
425     // Deregister external decoders so they are no longer running during
426     // destruction. This effectively stops the VCM since the decoder thread is
427     // stopped, the VCM is deregistered and no asynchronous decoder threads are
428     // running.
429     for (const Decoder& decoder : config_.decoders)
430       video_receiver_.RegisterExternalDecoder(nullptr, decoder.payload_type);
431 
432     UpdateHistograms();
433   }
434 
435   video_stream_decoder_.reset();
436   incoming_video_stream_.reset();
437   transport_adapter_.Disable();
438 }
439 
GetStats() const440 VideoReceiveStream::Stats VideoReceiveStream::GetStats() const {
441   VideoReceiveStream::Stats stats = stats_proxy_.GetStats();
442   stats.total_bitrate_bps = 0;
443   stats.rtcp_sender_packets_sent = 0;
444   stats.rtcp_sender_octets_sent = 0;
445   stats.rtcp_sender_ntp_timestamp_ms = 0;
446   stats.rtcp_sender_remote_ntp_timestamp_ms = 0;
447   StreamStatistician* statistician =
448       rtp_receive_statistics_->GetStatistician(stats.ssrc);
449   if (statistician) {
450     stats.rtp_stats = statistician->GetStats();
451     stats.total_bitrate_bps = statistician->BitrateReceived();
452   }
453   if (config_.rtp.rtx_ssrc) {
454     StreamStatistician* rtx_statistician =
455         rtp_receive_statistics_->GetStatistician(config_.rtp.rtx_ssrc);
456     if (rtx_statistician)
457       stats.total_bitrate_bps += rtx_statistician->BitrateReceived();
458   }
459   RtpRtcp* rtp_rtcp = rtp_video_stream_receiver_.rtp_rtcp();
460   if (rtp_rtcp) {
461     rtp_rtcp->RemoteRTCPSenderInfo(&stats.rtcp_sender_packets_sent,
462                                    &stats.rtcp_sender_octets_sent,
463                                    &stats.rtcp_sender_ntp_timestamp_ms,
464                                    &stats.rtcp_sender_remote_ntp_timestamp_ms);
465   }
466 
467   return stats;
468 }
469 
UpdateHistograms()470 void VideoReceiveStream::UpdateHistograms() {
471   absl::optional<int> fraction_lost;
472   StreamDataCounters rtp_stats;
473   StreamStatistician* statistician =
474       rtp_receive_statistics_->GetStatistician(config_.rtp.remote_ssrc);
475   if (statistician) {
476     fraction_lost = statistician->GetFractionLostInPercent();
477     rtp_stats = statistician->GetReceiveStreamDataCounters();
478   }
479   if (config_.rtp.rtx_ssrc) {
480     StreamStatistician* rtx_statistician =
481         rtp_receive_statistics_->GetStatistician(config_.rtp.rtx_ssrc);
482     if (rtx_statistician) {
483       StreamDataCounters rtx_stats =
484           rtx_statistician->GetReceiveStreamDataCounters();
485       stats_proxy_.UpdateHistograms(fraction_lost, rtp_stats, &rtx_stats);
486       return;
487     }
488   }
489   stats_proxy_.UpdateHistograms(fraction_lost, rtp_stats, nullptr);
490 }
491 
AddSecondarySink(RtpPacketSinkInterface * sink)492 void VideoReceiveStream::AddSecondarySink(RtpPacketSinkInterface* sink) {
493   rtp_video_stream_receiver_.AddSecondarySink(sink);
494 }
495 
RemoveSecondarySink(const RtpPacketSinkInterface * sink)496 void VideoReceiveStream::RemoveSecondarySink(
497     const RtpPacketSinkInterface* sink) {
498   rtp_video_stream_receiver_.RemoveSecondarySink(sink);
499 }
500 
SetBaseMinimumPlayoutDelayMs(int delay_ms)501 bool VideoReceiveStream::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
502   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
503   if (delay_ms < kMinBaseMinimumDelayMs || delay_ms > kMaxBaseMinimumDelayMs) {
504     return false;
505   }
506 
507   MutexLock lock(&playout_delay_lock_);
508   base_minimum_playout_delay_ms_ = delay_ms;
509   UpdatePlayoutDelays();
510   return true;
511 }
512 
GetBaseMinimumPlayoutDelayMs() const513 int VideoReceiveStream::GetBaseMinimumPlayoutDelayMs() const {
514   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
515 
516   MutexLock lock(&playout_delay_lock_);
517   return base_minimum_playout_delay_ms_;
518 }
519 
520 // TODO(tommi): This method grabs a lock 6 times.
OnFrame(const VideoFrame & video_frame)521 void VideoReceiveStream::OnFrame(const VideoFrame& video_frame) {
522   int64_t video_playout_ntp_ms;
523   int64_t sync_offset_ms;
524   double estimated_freq_khz;
525   // TODO(tommi): GetStreamSyncOffsetInMs grabs three locks.  One inside the
526   // function itself, another in GetChannel() and a third in
527   // GetPlayoutTimestamp.  Seems excessive.  Anyhow, I'm assuming the function
528   // succeeds most of the time, which leads to grabbing a fourth lock.
529   if (rtp_stream_sync_.GetStreamSyncOffsetInMs(
530           video_frame.timestamp(), video_frame.render_time_ms(),
531           &video_playout_ntp_ms, &sync_offset_ms, &estimated_freq_khz)) {
532     // TODO(tommi): OnSyncOffsetUpdated grabs a lock.
533     stats_proxy_.OnSyncOffsetUpdated(video_playout_ntp_ms, sync_offset_ms,
534                                      estimated_freq_khz);
535   }
536   source_tracker_.OnFrameDelivered(video_frame.packet_infos());
537 
538   config_.renderer->OnFrame(video_frame);
539 
540   // TODO(tommi): OnRenderFrame grabs a lock too.
541   stats_proxy_.OnRenderedFrame(video_frame);
542 }
543 
SetFrameDecryptor(rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor)544 void VideoReceiveStream::SetFrameDecryptor(
545     rtc::scoped_refptr<webrtc::FrameDecryptorInterface> frame_decryptor) {
546   rtp_video_stream_receiver_.SetFrameDecryptor(std::move(frame_decryptor));
547 }
548 
SetDepacketizerToDecoderFrameTransformer(rtc::scoped_refptr<FrameTransformerInterface> frame_transformer)549 void VideoReceiveStream::SetDepacketizerToDecoderFrameTransformer(
550     rtc::scoped_refptr<FrameTransformerInterface> frame_transformer) {
551   rtp_video_stream_receiver_.SetDepacketizerToDecoderFrameTransformer(
552       std::move(frame_transformer));
553 }
554 
SendNack(const std::vector<uint16_t> & sequence_numbers,bool buffering_allowed)555 void VideoReceiveStream::SendNack(const std::vector<uint16_t>& sequence_numbers,
556                                   bool buffering_allowed) {
557   RTC_DCHECK(buffering_allowed);
558   rtp_video_stream_receiver_.RequestPacketRetransmit(sequence_numbers);
559 }
560 
RequestKeyFrame(int64_t timestamp_ms)561 void VideoReceiveStream::RequestKeyFrame(int64_t timestamp_ms) {
562   rtp_video_stream_receiver_.RequestKeyFrame();
563   last_keyframe_request_ms_ = timestamp_ms;
564 }
565 
OnCompleteFrame(std::unique_ptr<video_coding::EncodedFrame> frame)566 void VideoReceiveStream::OnCompleteFrame(
567     std::unique_ptr<video_coding::EncodedFrame> frame) {
568   RTC_DCHECK_RUN_ON(&network_sequence_checker_);
569   // TODO(https://bugs.webrtc.org/9974): Consider removing this workaround.
570   int64_t time_now_ms = clock_->TimeInMilliseconds();
571   if (last_complete_frame_time_ms_ > 0 &&
572       time_now_ms - last_complete_frame_time_ms_ > kInactiveStreamThresholdMs) {
573     frame_buffer_->Clear();
574   }
575   last_complete_frame_time_ms_ = time_now_ms;
576 
577   const VideoPlayoutDelay& playout_delay = frame->EncodedImage().playout_delay_;
578   if (playout_delay.min_ms >= 0) {
579     MutexLock lock(&playout_delay_lock_);
580     frame_minimum_playout_delay_ms_ = playout_delay.min_ms;
581     UpdatePlayoutDelays();
582   }
583 
584   if (playout_delay.max_ms >= 0) {
585     MutexLock lock(&playout_delay_lock_);
586     frame_maximum_playout_delay_ms_ = playout_delay.max_ms;
587     UpdatePlayoutDelays();
588   }
589 
590   int64_t last_continuous_pid = frame_buffer_->InsertFrame(std::move(frame));
591   if (last_continuous_pid != -1)
592     rtp_video_stream_receiver_.FrameContinuous(last_continuous_pid);
593 }
594 
OnRttUpdate(int64_t avg_rtt_ms,int64_t max_rtt_ms)595 void VideoReceiveStream::OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) {
596   RTC_DCHECK_RUN_ON(&module_process_sequence_checker_);
597   frame_buffer_->UpdateRtt(max_rtt_ms);
598   rtp_video_stream_receiver_.UpdateRtt(max_rtt_ms);
599 }
600 
id() const601 uint32_t VideoReceiveStream::id() const {
602   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
603   return config_.rtp.remote_ssrc;
604 }
605 
GetInfo() const606 absl::optional<Syncable::Info> VideoReceiveStream::GetInfo() const {
607   RTC_DCHECK_RUN_ON(&module_process_sequence_checker_);
608   absl::optional<Syncable::Info> info =
609       rtp_video_stream_receiver_.GetSyncInfo();
610 
611   if (!info)
612     return absl::nullopt;
613 
614   info->current_delay_ms = timing_->TargetVideoDelay();
615   return info;
616 }
617 
GetPlayoutRtpTimestamp(uint32_t * rtp_timestamp,int64_t * time_ms) const618 bool VideoReceiveStream::GetPlayoutRtpTimestamp(uint32_t* rtp_timestamp,
619                                                 int64_t* time_ms) const {
620   RTC_NOTREACHED();
621   return 0;
622 }
623 
SetEstimatedPlayoutNtpTimestampMs(int64_t ntp_timestamp_ms,int64_t time_ms)624 void VideoReceiveStream::SetEstimatedPlayoutNtpTimestampMs(
625     int64_t ntp_timestamp_ms,
626     int64_t time_ms) {
627   RTC_NOTREACHED();
628 }
629 
SetMinimumPlayoutDelay(int delay_ms)630 bool VideoReceiveStream::SetMinimumPlayoutDelay(int delay_ms) {
631   RTC_DCHECK_RUN_ON(&module_process_sequence_checker_);
632   MutexLock lock(&playout_delay_lock_);
633   syncable_minimum_playout_delay_ms_ = delay_ms;
634   UpdatePlayoutDelays();
635   return true;
636 }
637 
GetWaitMs() const638 int64_t VideoReceiveStream::GetWaitMs() const {
639   return keyframe_required_ ? max_wait_for_keyframe_ms_
640                             : max_wait_for_frame_ms_;
641 }
642 
StartNextDecode()643 void VideoReceiveStream::StartNextDecode() {
644   TRACE_EVENT0("webrtc", "VideoReceiveStream::StartNextDecode");
645   frame_buffer_->NextFrame(
646       GetWaitMs(), keyframe_required_, &decode_queue_,
647       /* encoded frame handler */
648       [this](std::unique_ptr<EncodedFrame> frame, ReturnReason res) {
649         RTC_DCHECK_EQ(frame == nullptr, res == ReturnReason::kTimeout);
650         RTC_DCHECK_EQ(frame != nullptr, res == ReturnReason::kFrameFound);
651         decode_queue_.PostTask([this, frame = std::move(frame)]() mutable {
652           RTC_DCHECK_RUN_ON(&decode_queue_);
653           if (decoder_stopped_)
654             return;
655           if (frame) {
656             HandleEncodedFrame(std::move(frame));
657           } else {
658             HandleFrameBufferTimeout();
659           }
660           StartNextDecode();
661         });
662       });
663 }
664 
HandleEncodedFrame(std::unique_ptr<EncodedFrame> frame)665 void VideoReceiveStream::HandleEncodedFrame(
666     std::unique_ptr<EncodedFrame> frame) {
667   int64_t now_ms = clock_->TimeInMilliseconds();
668 
669   // Current OnPreDecode only cares about QP for VP8.
670   int qp = -1;
671   if (frame->CodecSpecific()->codecType == kVideoCodecVP8) {
672     if (!vp8::GetQp(frame->data(), frame->size(), &qp)) {
673       RTC_LOG(LS_WARNING) << "Failed to extract QP from VP8 video frame";
674     }
675   }
676   stats_proxy_.OnPreDecode(frame->CodecSpecific()->codecType, qp);
677   HandleKeyFrameGeneration(frame->FrameType() == VideoFrameType::kVideoFrameKey,
678                            now_ms);
679   int decode_result = video_receiver_.Decode(frame.get());
680   if (decode_result == WEBRTC_VIDEO_CODEC_OK ||
681       decode_result == WEBRTC_VIDEO_CODEC_OK_REQUEST_KEYFRAME) {
682     keyframe_required_ = false;
683     frame_decoded_ = true;
684     rtp_video_stream_receiver_.FrameDecoded(frame->id.picture_id);
685 
686     if (decode_result == WEBRTC_VIDEO_CODEC_OK_REQUEST_KEYFRAME)
687       RequestKeyFrame(now_ms);
688   } else if (!frame_decoded_ || !keyframe_required_ ||
689              (last_keyframe_request_ms_ + max_wait_for_keyframe_ms_ < now_ms)) {
690     keyframe_required_ = true;
691     // TODO(philipel): Remove this keyframe request when downstream project
692     //                 has been fixed.
693     RequestKeyFrame(now_ms);
694   }
695 
696   if (encoded_frame_buffer_function_) {
697     frame->Retain();
698     encoded_frame_buffer_function_(WebRtcRecordableEncodedFrame(*frame));
699   }
700 }
701 
HandleKeyFrameGeneration(bool received_frame_is_keyframe,int64_t now_ms)702 void VideoReceiveStream::HandleKeyFrameGeneration(
703     bool received_frame_is_keyframe,
704     int64_t now_ms) {
705   // Repeat sending keyframe requests if we've requested a keyframe.
706   if (!keyframe_generation_requested_) {
707     return;
708   }
709   if (received_frame_is_keyframe) {
710     keyframe_generation_requested_ = false;
711   } else if (last_keyframe_request_ms_ + max_wait_for_keyframe_ms_ <= now_ms) {
712     if (!IsReceivingKeyFrame(now_ms)) {
713       RequestKeyFrame(now_ms);
714     }
715   } else {
716     // It hasn't been long enough since the last keyframe request, do nothing.
717   }
718 }
719 
HandleFrameBufferTimeout()720 void VideoReceiveStream::HandleFrameBufferTimeout() {
721   int64_t now_ms = clock_->TimeInMilliseconds();
722   absl::optional<int64_t> last_packet_ms =
723       rtp_video_stream_receiver_.LastReceivedPacketMs();
724 
725   // To avoid spamming keyframe requests for a stream that is not active we
726   // check if we have received a packet within the last 5 seconds.
727   bool stream_is_active = last_packet_ms && now_ms - *last_packet_ms < 5000;
728   if (!stream_is_active)
729     stats_proxy_.OnStreamInactive();
730 
731   if (stream_is_active && !IsReceivingKeyFrame(now_ms) &&
732       (!config_.crypto_options.sframe.require_frame_encryption ||
733        rtp_video_stream_receiver_.IsDecryptable())) {
734     RTC_LOG(LS_WARNING) << "No decodable frame in " << GetWaitMs()
735                         << " ms, requesting keyframe.";
736     RequestKeyFrame(now_ms);
737   }
738 }
739 
IsReceivingKeyFrame(int64_t timestamp_ms) const740 bool VideoReceiveStream::IsReceivingKeyFrame(int64_t timestamp_ms) const {
741   absl::optional<int64_t> last_keyframe_packet_ms =
742       rtp_video_stream_receiver_.LastReceivedKeyframePacketMs();
743 
744   // If we recently have been receiving packets belonging to a keyframe then
745   // we assume a keyframe is currently being received.
746   bool receiving_keyframe =
747       last_keyframe_packet_ms &&
748       timestamp_ms - *last_keyframe_packet_ms < max_wait_for_keyframe_ms_;
749   return receiving_keyframe;
750 }
751 
UpdatePlayoutDelays() const752 void VideoReceiveStream::UpdatePlayoutDelays() const {
753   const int minimum_delay_ms =
754       std::max({frame_minimum_playout_delay_ms_, base_minimum_playout_delay_ms_,
755                 syncable_minimum_playout_delay_ms_});
756   if (minimum_delay_ms >= 0) {
757     timing_->set_min_playout_delay(minimum_delay_ms);
758   }
759 
760   const int maximum_delay_ms = frame_maximum_playout_delay_ms_;
761   if (maximum_delay_ms >= 0) {
762     timing_->set_max_playout_delay(maximum_delay_ms);
763   }
764 }
765 
GetSources() const766 std::vector<webrtc::RtpSource> VideoReceiveStream::GetSources() const {
767   return source_tracker_.GetSources();
768 }
769 
SetAndGetRecordingState(RecordingState state,bool generate_key_frame)770 VideoReceiveStream::RecordingState VideoReceiveStream::SetAndGetRecordingState(
771     RecordingState state,
772     bool generate_key_frame) {
773   RTC_DCHECK_RUN_ON(&worker_sequence_checker_);
774   rtc::Event event;
775   RecordingState old_state;
776   decode_queue_.PostTask([this, &event, &old_state, generate_key_frame,
777                           state = std::move(state)] {
778     RTC_DCHECK_RUN_ON(&decode_queue_);
779     // Save old state.
780     old_state.callback = std::move(encoded_frame_buffer_function_);
781     old_state.keyframe_needed = keyframe_generation_requested_;
782     old_state.last_keyframe_request_ms = last_keyframe_request_ms_;
783 
784     // Set new state.
785     encoded_frame_buffer_function_ = std::move(state.callback);
786     if (generate_key_frame) {
787       RequestKeyFrame(clock_->TimeInMilliseconds());
788       keyframe_generation_requested_ = true;
789     } else {
790       keyframe_generation_requested_ = state.keyframe_needed;
791       last_keyframe_request_ms_ = state.last_keyframe_request_ms.value_or(0);
792     }
793     event.Set();
794   });
795   event.Wait(rtc::Event::kForever);
796   return old_state;
797 }
798 
GenerateKeyFrame()799 void VideoReceiveStream::GenerateKeyFrame() {
800   decode_queue_.PostTask([this]() {
801     RTC_DCHECK_RUN_ON(&decode_queue_);
802     RequestKeyFrame(clock_->TimeInMilliseconds());
803     keyframe_generation_requested_ = true;
804   });
805 }
806 }  // namespace internal
807 }  // namespace webrtc
808