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