blob: 5902886da49f81156767188c78799f609e389bd1 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
leozwang@webrtc.org39e96592012-03-01 18:22:48 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "video/rtp_video_stream_receiver.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
philipel7acc4a42019-09-26 11:25:52 +020013#include <algorithm>
14#include <limits>
philipelfd5a20f2016-11-15 00:57:57 -080015#include <utility>
ilnik04f4d122017-06-19 07:18:55 -070016#include <vector>
mflodman@webrtc.org4fd55272013-02-06 17:46:39 +000017
Steve Antonbd631a02019-03-28 10:51:27 -070018#include "absl/algorithm/container.h"
Niels Möller2ff1f2a2018-08-09 16:16:34 +020019#include "absl/memory/memory.h"
Steve Anton10542f22019-01-11 09:11:00 -080020#include "media/base/media_constants.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "modules/pacing/packet_router.h"
22#include "modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
23#include "modules/rtp_rtcp/include/receive_statistics.h"
24#include "modules/rtp_rtcp/include/rtp_cvo.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "modules/rtp_rtcp/include/rtp_rtcp.h"
26#include "modules/rtp_rtcp/include/ulpfec_receiver.h"
Niels Möller2ff1f2a2018-08-09 16:16:34 +020027#include "modules/rtp_rtcp/source/rtp_format.h"
philipelb3e42a42018-09-13 10:57:14 +020028#include "modules/rtp_rtcp/source/rtp_generic_frame_descriptor_extension.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
30#include "modules/rtp_rtcp/source/rtp_packet_received.h"
Niels Möller2ff1f2a2018-08-09 16:16:34 +020031#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
Niels Möllerfe407b72019-09-10 10:48:48 +020032#include "modules/utility/include/process_thread.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "modules/video_coding/frame_object.h"
34#include "modules/video_coding/h264_sprop_parameter_sets.h"
35#include "modules/video_coding/h264_sps_pps_tracker.h"
Ilya Nikolaevskiy8643b782018-06-07 16:15:40 +020036#include "modules/video_coding/nack_module.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "modules/video_coding/packet_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "rtc_base/checks.h"
39#include "rtc_base/location.h"
40#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020041#include "rtc_base/strings/string_builder.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010042#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "system_wrappers/include/field_trial.h"
44#include "system_wrappers/include/metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "video/receive_statistics_proxy.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000046
47namespace webrtc {
48
philipelfd5a20f2016-11-15 00:57:57 -080049namespace {
philipel3bf97cf2017-08-10 18:10:59 +020050// TODO(philipel): Change kPacketBufferStartSize back to 32 in M63 see:
51// crbug.com/752886
52constexpr int kPacketBufferStartSize = 512;
Johannes Kron201596f2018-10-22 14:33:39 +020053constexpr int kPacketBufferMaxSize = 2048;
Danil Chapovalovf7457e52019-09-20 17:57:15 +020054
55int PacketBufferMaxSize() {
56 // The group here must be a positive power of 2, in which case that is used as
57 // size. All other values shall result in the default value being used.
58 const std::string group_name =
59 webrtc::field_trial::FindFullName("WebRTC-PacketBufferMaxSize");
60 int packet_buffer_max_size = kPacketBufferMaxSize;
61 if (!group_name.empty() &&
62 (sscanf(group_name.c_str(), "%d", &packet_buffer_max_size) != 1 ||
63 packet_buffer_max_size <= 0 ||
64 // Verify that the number is a positive power of 2.
65 (packet_buffer_max_size & (packet_buffer_max_size - 1)) != 0)) {
66 RTC_LOG(LS_WARNING) << "Invalid packet buffer max size: " << group_name;
67 packet_buffer_max_size = kPacketBufferMaxSize;
68 }
69 return packet_buffer_max_size;
70}
71
Yves Gerey665174f2018-06-19 15:03:05 +020072} // namespace
philipelfd5a20f2016-11-15 00:57:57 -080073
mflodmanc0e58a32016-04-25 01:26:26 -070074std::unique_ptr<RtpRtcp> CreateRtpRtcpModule(
Sebastian Jansson8026d602019-03-04 19:39:01 +010075 Clock* clock,
mflodmanc0e58a32016-04-25 01:26:26 -070076 ReceiveStatistics* receive_statistics,
77 Transport* outgoing_transport,
78 RtcpRttStats* rtt_stats,
Erik Språnge3a10e12019-08-19 15:45:00 +020079 RtcpPacketTypeCounterObserver* rtcp_packet_type_counter_observer,
80 uint32_t local_ssrc) {
mflodmanc0e58a32016-04-25 01:26:26 -070081 RtpRtcp::Configuration configuration;
Sebastian Jansson8026d602019-03-04 19:39:01 +010082 configuration.clock = clock;
mflodmanc0e58a32016-04-25 01:26:26 -070083 configuration.audio = false;
84 configuration.receiver_only = true;
85 configuration.receive_statistics = receive_statistics;
86 configuration.outgoing_transport = outgoing_transport;
mflodmanc0e58a32016-04-25 01:26:26 -070087 configuration.rtt_stats = rtt_stats;
88 configuration.rtcp_packet_type_counter_observer =
89 rtcp_packet_type_counter_observer;
Erik Språng54d5d2c2019-08-20 17:22:36 +020090 configuration.local_media_ssrc = local_ssrc;
mflodmanc0e58a32016-04-25 01:26:26 -070091
Danil Chapovalovc44f6cc2019-03-06 11:31:09 +010092 std::unique_ptr<RtpRtcp> rtp_rtcp = RtpRtcp::Create(configuration);
mflodmanc0e58a32016-04-25 01:26:26 -070093 rtp_rtcp->SetRTCPStatus(RtcpMode::kCompound);
94
95 return rtp_rtcp;
96}
97
stefan@webrtc.orgeb24b042014-10-14 11:40:13 +000098static const int kPacketLogIntervalMs = 10000;
99
Elad Alonef09c5b2019-05-31 13:25:50 +0200100RtpVideoStreamReceiver::RtcpFeedbackBuffer::RtcpFeedbackBuffer(
101 KeyFrameRequestSender* key_frame_request_sender,
102 NackSender* nack_sender,
103 LossNotificationSender* loss_notification_sender)
104 : key_frame_request_sender_(key_frame_request_sender),
105 nack_sender_(nack_sender),
106 loss_notification_sender_(loss_notification_sender),
107 request_key_frame_(false) {
108 RTC_DCHECK(key_frame_request_sender_);
109 RTC_DCHECK(nack_sender_);
110 RTC_DCHECK(loss_notification_sender_);
111}
112
113void RtpVideoStreamReceiver::RtcpFeedbackBuffer::RequestKeyFrame() {
114 rtc::CritScope lock(&cs_);
115 request_key_frame_ = true;
116}
117
118void RtpVideoStreamReceiver::RtcpFeedbackBuffer::SendNack(
Elad Alonef09c5b2019-05-31 13:25:50 +0200119 const std::vector<uint16_t>& sequence_numbers,
120 bool buffering_allowed) {
121 RTC_DCHECK(!sequence_numbers.empty());
122 rtc::CritScope lock(&cs_);
123 nack_sequence_numbers_.insert(nack_sequence_numbers_.end(),
124 sequence_numbers.cbegin(),
125 sequence_numbers.cend());
126 if (!buffering_allowed) {
127 // Note that while *buffering* is not allowed, *batching* is, meaning that
128 // previously buffered messages may be sent along with the current message.
129 SendBufferedRtcpFeedback();
130 }
131}
132
133void RtpVideoStreamReceiver::RtcpFeedbackBuffer::SendLossNotification(
134 uint16_t last_decoded_seq_num,
135 uint16_t last_received_seq_num,
Elad Alone86af2c2019-06-03 14:37:50 +0200136 bool decodability_flag,
137 bool buffering_allowed) {
138 RTC_DCHECK(buffering_allowed);
Elad Alonef09c5b2019-05-31 13:25:50 +0200139 rtc::CritScope lock(&cs_);
Elad Alon36690cd2019-06-04 22:59:54 +0200140 RTC_DCHECK(!lntf_state_)
Elad Alonef09c5b2019-05-31 13:25:50 +0200141 << "SendLossNotification() called twice in a row with no call to "
142 "SendBufferedRtcpFeedback() in between.";
143 lntf_state_ = absl::make_optional<LossNotificationState>(
144 last_decoded_seq_num, last_received_seq_num, decodability_flag);
145}
146
Elad Alonef09c5b2019-05-31 13:25:50 +0200147void RtpVideoStreamReceiver::RtcpFeedbackBuffer::SendBufferedRtcpFeedback() {
148 bool request_key_frame = false;
149 std::vector<uint16_t> nack_sequence_numbers;
150 absl::optional<LossNotificationState> lntf_state;
151
152 {
153 rtc::CritScope lock(&cs_);
154 std::swap(request_key_frame, request_key_frame_);
155 std::swap(nack_sequence_numbers, nack_sequence_numbers_);
156 std::swap(lntf_state, lntf_state_);
157 }
158
Elad Alone86af2c2019-06-03 14:37:50 +0200159 if (lntf_state) {
160 // If either a NACK or a key frame request is sent, we should buffer
161 // the LNTF and wait for them (NACK or key frame request) to trigger
162 // the compound feedback message.
163 // Otherwise, the LNTF should be sent out immediately.
164 const bool buffering_allowed =
165 request_key_frame || !nack_sequence_numbers.empty();
166
167 loss_notification_sender_->SendLossNotification(
168 lntf_state->last_decoded_seq_num, lntf_state->last_received_seq_num,
169 lntf_state->decodability_flag, buffering_allowed);
170 }
171
Elad Alonef09c5b2019-05-31 13:25:50 +0200172 if (request_key_frame) {
173 key_frame_request_sender_->RequestKeyFrame();
174 } else if (!nack_sequence_numbers.empty()) {
175 nack_sender_->SendNack(nack_sequence_numbers, true);
176 }
Elad Alonef09c5b2019-05-31 13:25:50 +0200177}
178
nisseb1f2ff92017-06-09 04:01:55 -0700179RtpVideoStreamReceiver::RtpVideoStreamReceiver(
Sebastian Jansson8026d602019-03-04 19:39:01 +0100180 Clock* clock,
mflodmanfa666592016-04-28 23:15:33 -0700181 Transport* transport,
182 RtcpRttStats* rtt_stats,
mflodmancfc8e3b2016-05-03 21:22:04 -0700183 PacketRouter* packet_router,
Tommi733b5472016-06-10 17:58:01 +0200184 const VideoReceiveStream::Config* config,
nisseca5706d2017-09-11 02:32:16 -0700185 ReceiveStatistics* rtp_receive_statistics,
mflodmandc7d0d22016-05-06 05:32:22 -0700186 ReceiveStatisticsProxy* receive_stats_proxy,
Erik Språng737336d2016-07-29 12:59:36 +0200187 ProcessThread* process_thread,
philipelfd5a20f2016-11-15 00:57:57 -0800188 NackSender* nack_sender,
Niels Möller2f5554d2019-05-29 13:35:14 +0200189 KeyFrameRequestSender* keyframe_request_sender,
Benjamin Wright192eeec2018-10-17 17:27:25 -0700190 video_coding::OnCompleteFrameCallback* complete_frame_callback,
191 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor)
Sebastian Jansson8026d602019-03-04 19:39:01 +0100192 : clock_(clock),
Tommi733b5472016-06-10 17:58:01 +0200193 config_(*config),
mflodmanc0e58a32016-04-25 01:26:26 -0700194 packet_router_(packet_router),
mflodmandc7d0d22016-05-06 05:32:22 -0700195 process_thread_(process_thread),
Sebastian Jansson8026d602019-03-04 19:39:01 +0100196 ntp_estimator_(clock),
Niels Möllerb0573bc2017-09-25 10:47:00 +0200197 rtp_header_extensions_(config_.rtp.extensions),
nisseca5706d2017-09-11 02:32:16 -0700198 rtp_receive_statistics_(rtp_receive_statistics),
Ilya Nikolaevskiy2d821c32019-06-26 14:39:36 +0200199 ulpfec_receiver_(UlpfecReceiver::Create(config->rtp.remote_ssrc,
200 this,
201 config->rtp.extensions)),
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000202 receiving_(false),
mflodmanc0e58a32016-04-25 01:26:26 -0700203 last_packet_log_ms_(-1),
Niels Möller2f5554d2019-05-29 13:35:14 +0200204 rtp_rtcp_(CreateRtpRtcpModule(clock,
205 rtp_receive_statistics_,
206 transport,
207 rtt_stats,
Erik Språnge3a10e12019-08-19 15:45:00 +0200208 receive_stats_proxy,
209 config_.rtp.local_ssrc)),
philipelfd5a20f2016-11-15 00:57:57 -0800210 complete_frame_callback_(complete_frame_callback),
Niels Möller2f5554d2019-05-29 13:35:14 +0200211 keyframe_request_sender_(keyframe_request_sender),
Elad Alonef09c5b2019-05-31 13:25:50 +0200212 // TODO(bugs.webrtc.org/10336): Let |rtcp_feedback_buffer_| communicate
213 // directly with |rtp_rtcp_|.
214 rtcp_feedback_buffer_(this, nack_sender, this),
Danil Chapovalovce1ffcd2019-10-22 17:12:42 +0200215 packet_buffer_(clock_, kPacketBufferStartSize, PacketBufferMaxSize()),
Benjamin Wright52426ed2019-03-01 11:01:59 -0800216 has_received_frame_(false),
217 frames_decryptable_(false) {
eladalon822ff2b2017-08-01 06:30:28 -0700218 constexpr bool remb_candidate = true;
Niels Möller60f4e292019-05-20 11:06:33 +0200219 if (packet_router_)
220 packet_router_->AddReceiveRtpModule(rtp_rtcp_.get(), remb_candidate);
mflodmancfc8e3b2016-05-03 21:22:04 -0700221
Tommi733b5472016-06-10 17:58:01 +0200222 RTC_DCHECK(config_.rtp.rtcp_mode != RtcpMode::kOff)
mflodmancfc8e3b2016-05-03 21:22:04 -0700223 << "A stream should not be configured with RTCP disabled. This value is "
224 "reserved for internal usage.";
mflodmandc7d0d22016-05-06 05:32:22 -0700225 // TODO(pbos): What's an appropriate local_ssrc for receive-only streams?
226 RTC_DCHECK(config_.rtp.local_ssrc != 0);
227 RTC_DCHECK(config_.rtp.remote_ssrc != config_.rtp.local_ssrc);
228
Tommi733b5472016-06-10 17:58:01 +0200229 rtp_rtcp_->SetRTCPStatus(config_.rtp.rtcp_mode);
stefanb4ab3812017-06-09 06:12:11 -0700230 rtp_rtcp_->SetRemoteSSRC(config_.rtp.remote_ssrc);
mflodmandc7d0d22016-05-06 05:32:22 -0700231
mflodmancfc8e3b2016-05-03 21:22:04 -0700232 static const int kMaxPacketAgeToNack = 450;
Tommi733b5472016-06-10 17:58:01 +0200233 const int max_reordering_threshold = (config_.rtp.nack.rtp_history_ms > 0)
234 ? kMaxPacketAgeToNack
235 : kDefaultMaxReorderingThreshold;
Niels Möller87da1092019-05-24 14:04:28 +0200236 rtp_receive_statistics_->SetMaxReorderingThreshold(config_.rtp.remote_ssrc,
237 max_reordering_threshold);
238 // TODO(nisse): For historic reasons, we applied the above
239 // max_reordering_threshold also for RTX stats, which makes little sense since
240 // we don't NACK rtx packets. Consider deleting the below block, and rely on
241 // the default threshold.
242 if (config_.rtp.rtx_ssrc) {
243 rtp_receive_statistics_->SetMaxReorderingThreshold(
244 config_.rtp.rtx_ssrc, max_reordering_threshold);
245 }
Tommi733b5472016-06-10 17:58:01 +0200246 if (config_.rtp.rtcp_xr.receiver_reference_time_report)
mflodmandc7d0d22016-05-06 05:32:22 -0700247 rtp_rtcp_->SetRtcpXrRrtrStatus(true);
248
249 // Stats callback for CNAME changes.
Niels Möller4d7c4052019-08-05 12:45:19 +0200250 rtp_rtcp_->RegisterRtcpCnameCallback(receive_stats_proxy);
mflodmandc7d0d22016-05-06 05:32:22 -0700251
tommidea489f2017-03-03 03:20:24 -0800252 process_thread_->RegisterModule(rtp_rtcp_.get(), RTC_FROM_HERE);
philipelfd5a20f2016-11-15 00:57:57 -0800253
Elad Alonfadb1812019-05-24 13:40:02 +0200254 if (config_.rtp.lntf.enabled) {
Elad Alon7d6a4c02019-02-25 13:00:51 +0100255 loss_notification_controller_ =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200256 std::make_unique<LossNotificationController>(&rtcp_feedback_buffer_,
257 &rtcp_feedback_buffer_);
Elad Alonca2c4302019-05-27 22:43:10 +0200258 }
259
260 if (config_.rtp.nack.rtp_history_ms != 0) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200261 nack_module_ = std::make_unique<NackModule>(clock_, &rtcp_feedback_buffer_,
262 &rtcp_feedback_buffer_);
tommidea489f2017-03-03 03:20:24 -0800263 process_thread_->RegisterModule(nack_module_.get(), RTC_FROM_HERE);
tommif284b7f2017-02-27 01:59:36 -0800264 }
philipelfd5a20f2016-11-15 00:57:57 -0800265
Elad Alona8f54612018-11-06 11:21:25 +0100266 reference_finder_ =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200267 std::make_unique<video_coding::RtpFrameReferenceFinder>(this);
Benjamin Wrighta5564482019-04-03 10:44:18 -0700268
Benjamin Wright00765292018-11-30 16:18:26 -0800269 // Only construct the encrypted receiver if frame encryption is enabled.
Benjamin Wrighta5564482019-04-03 10:44:18 -0700270 if (config_.crypto_options.sframe.require_frame_encryption) {
Benjamin Wright00765292018-11-30 16:18:26 -0800271 buffered_frame_decryptor_ =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200272 std::make_unique<BufferedFrameDecryptor>(this, this);
Benjamin Wrighta5564482019-04-03 10:44:18 -0700273 if (frame_decryptor != nullptr) {
274 buffered_frame_decryptor_->SetFrameDecryptor(std::move(frame_decryptor));
275 }
Benjamin Wright00765292018-11-30 16:18:26 -0800276 }
mflodmanc0e58a32016-04-25 01:26:26 -0700277}
niklase@google.com470e71d2011-07-07 08:21:25 +0000278
nisseb1f2ff92017-06-09 04:01:55 -0700279RtpVideoStreamReceiver::~RtpVideoStreamReceiver() {
eladalonc0d481a2017-08-02 07:39:07 -0700280 RTC_DCHECK(secondary_sinks_.empty());
281
tommif284b7f2017-02-27 01:59:36 -0800282 if (nack_module_) {
283 process_thread_->DeRegisterModule(nack_module_.get());
284 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000285
tommif284b7f2017-02-27 01:59:36 -0800286 process_thread_->DeRegisterModule(rtp_rtcp_.get());
philipelfd5a20f2016-11-15 00:57:57 -0800287
Niels Möller60f4e292019-05-20 11:06:33 +0200288 if (packet_router_)
289 packet_router_->RemoveReceiveRtpModule(rtp_rtcp_.get());
mflodmandc7d0d22016-05-06 05:32:22 -0700290 UpdateHistograms();
asapersson@webrtc.org0800db72015-01-15 07:40:20 +0000291}
292
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200293void RtpVideoStreamReceiver::AddReceiveCodec(
philipel022b54e2016-12-20 04:15:59 -0800294 const VideoCodec& video_codec,
Mirta Dvornicicfe68daa2019-05-23 13:21:12 +0200295 const std::map<std::string, std::string>& codec_params,
296 bool raw_payload) {
297 absl::optional<VideoCodecType> video_type;
298 if (!raw_payload) {
299 video_type = video_codec.codecType;
300 }
301 payload_type_map_.emplace(video_codec.plType, video_type);
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200302 pt_codec_params_.emplace(video_codec.plType, codec_params);
wu@webrtc.org822fbd82013-08-15 23:38:54 +0000303}
304
Niels Möllerdf9e9ae2018-07-31 08:29:53 +0200305absl::optional<Syncable::Info> RtpVideoStreamReceiver::GetSyncInfo() const {
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200306 Syncable::Info info;
Niels Möllerdf9e9ae2018-07-31 08:29:53 +0200307 if (rtp_rtcp_->RemoteNTP(&info.capture_time_ntp_secs,
308 &info.capture_time_ntp_frac, nullptr, nullptr,
309 &info.capture_time_source_clock) != 0) {
310 return absl::nullopt;
311 }
Niels Möllerb0d4b412018-08-28 13:58:15 +0200312 {
Chen Xing90f3b892019-06-25 10:16:14 +0200313 rtc::CritScope lock(&sync_info_lock_);
Niels Möllerb0d4b412018-08-28 13:58:15 +0200314 if (!last_received_rtp_timestamp_ || !last_received_rtp_system_time_ms_) {
315 return absl::nullopt;
316 }
317 info.latest_received_capture_timestamp = *last_received_rtp_timestamp_;
318 info.latest_receive_time_ms = *last_received_rtp_system_time_ms_;
319 }
Niels Möllerdf9e9ae2018-07-31 08:29:53 +0200320
321 // Leaves info.current_delay_ms uninitialized.
322 return info;
wu@webrtc.org822fbd82013-08-15 23:38:54 +0000323}
324
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200325void RtpVideoStreamReceiver::OnReceivedPayloadData(
326 rtc::ArrayView<const uint8_t> codec_payload,
327 const RtpPacketReceived& rtp_packet,
328 const RTPVideoHeader& video) {
Danil Chapovalov09860e02019-10-30 14:12:24 +0100329 RTC_DCHECK_RUN_ON(&worker_task_checker_);
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200330 RTPHeader rtp_header;
331 rtp_packet.GetHeader(&rtp_header);
332 VCMPacket packet(codec_payload.data(), codec_payload.size(), rtp_header,
333 video, ntp_estimator_.Estimate(rtp_packet.Timestamp()),
Chen Xingf00bf422019-06-20 10:05:55 +0200334 clock_->TimeInMilliseconds());
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200335
336 RTPVideoHeader& video_header = packet.video_header;
337 video_header.rotation = kVideoRotation_0;
338 video_header.content_type = VideoContentType::UNSPECIFIED;
339 video_header.video_timing.flags = VideoSendTiming::kInvalid;
340 video_header.is_last_packet_in_frame |= rtp_packet.Marker();
341 video_header.frame_marking.temporal_id = kNoTemporalIdx;
342
343 if (const auto* vp9_header =
344 absl::get_if<RTPVideoHeaderVP9>(&video_header.video_type_header)) {
345 video_header.is_last_packet_in_frame |= vp9_header->end_of_frame;
346 video_header.is_first_packet_in_frame |= vp9_header->beginning_of_frame;
347 }
348
349 rtp_packet.GetExtension<VideoOrientation>(&video_header.rotation);
350 rtp_packet.GetExtension<VideoContentTypeExtension>(
351 &video_header.content_type);
352 rtp_packet.GetExtension<VideoTimingExtension>(&video_header.video_timing);
353 rtp_packet.GetExtension<PlayoutDelayLimits>(&video_header.playout_delay);
354 rtp_packet.GetExtension<FrameMarkingExtension>(&video_header.frame_marking);
355
356 RtpGenericFrameDescriptor& generic_descriptor =
357 packet.generic_descriptor.emplace();
358 if (rtp_packet.GetExtension<RtpGenericFrameDescriptorExtension01>(
359 &generic_descriptor)) {
360 if (rtp_packet.HasExtension<RtpGenericFrameDescriptorExtension00>()) {
361 RTC_LOG(LS_WARNING) << "RTP packet had two different GFD versions.";
362 return;
363 }
364 generic_descriptor.SetByteRepresentation(
365 rtp_packet.GetRawExtension<RtpGenericFrameDescriptorExtension01>());
366 } else if ((rtp_packet.GetExtension<RtpGenericFrameDescriptorExtension00>(
367 &generic_descriptor))) {
368 generic_descriptor.SetByteRepresentation(
369 rtp_packet.GetRawExtension<RtpGenericFrameDescriptorExtension00>());
370 } else {
371 packet.generic_descriptor = absl::nullopt;
372 }
373 if (packet.generic_descriptor != absl::nullopt) {
374 video_header.is_first_packet_in_frame =
375 packet.generic_descriptor->FirstPacketInSubFrame();
376 video_header.is_last_packet_in_frame =
377 rtp_packet.Marker() ||
378 packet.generic_descriptor->LastPacketInSubFrame();
379
380 if (packet.generic_descriptor->FirstPacketInSubFrame()) {
381 video_header.frame_type =
382 packet.generic_descriptor->FrameDependenciesDiffs().empty()
383 ? VideoFrameType::kVideoFrameKey
384 : VideoFrameType::kVideoFrameDelta;
385 }
386
387 video_header.width = packet.generic_descriptor->Width();
388 video_header.height = packet.generic_descriptor->Height();
389 }
390
391 // Color space should only be transmitted in the last packet of a frame,
392 // therefore, neglect it otherwise so that last_color_space_ is not reset by
393 // mistake.
394 if (video_header.is_last_packet_in_frame) {
395 video_header.color_space = rtp_packet.GetExtension<ColorSpaceExtension>();
396 if (video_header.color_space ||
397 video_header.frame_type == VideoFrameType::kVideoFrameKey) {
398 // Store color space since it's only transmitted when changed or for key
399 // frames. Color space will be cleared if a key frame is transmitted
400 // without color space information.
401 last_color_space_ = video_header.color_space;
402 } else if (last_color_space_) {
403 video_header.color_space = last_color_space_;
404 }
405 }
Elad Alon7d6a4c02019-02-25 13:00:51 +0100406
Elad Alonca2c4302019-05-27 22:43:10 +0200407 if (loss_notification_controller_) {
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200408 if (rtp_packet.recovered()) {
Elad Alonca2c4302019-05-27 22:43:10 +0200409 // TODO(bugs.webrtc.org/10336): Implement support for reordering.
Niels Möllera7401422019-09-13 14:18:58 +0200410 RTC_LOG(LS_INFO)
Elad Alonca2c4302019-05-27 22:43:10 +0200411 << "LossNotificationController does not support reordering.";
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200412 } else if (!packet.generic_descriptor) {
Niels Möllera7401422019-09-13 14:18:58 +0200413 RTC_LOG(LS_WARNING) << "LossNotificationController requires generic "
414 "frame descriptor, but it is missing.";
Elad Alonca2c4302019-05-27 22:43:10 +0200415 } else {
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200416 loss_notification_controller_->OnReceivedPacket(
417 rtp_packet.SequenceNumber(), *packet.generic_descriptor);
Elad Alonca2c4302019-05-27 22:43:10 +0200418 }
419 }
420
Niels Möller8dad9b42018-08-22 10:36:35 +0200421 if (nack_module_) {
Niels Möllerabbc50e2019-04-24 09:41:16 +0200422 const bool is_keyframe =
423 video_header.is_first_packet_in_frame &&
424 video_header.frame_type == VideoFrameType::kVideoFrameKey;
Niels Möller8dad9b42018-08-22 10:36:35 +0200425
426 packet.timesNacked = nack_module_->OnReceivedPacket(
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200427 rtp_packet.SequenceNumber(), is_keyframe, rtp_packet.recovered());
Niels Möller8dad9b42018-08-22 10:36:35 +0200428 } else {
429 packet.timesNacked = -1;
430 }
philipelfd5a20f2016-11-15 00:57:57 -0800431
philipel54ca9192017-03-21 05:45:18 -0700432 if (packet.sizeBytes == 0) {
Niels Möllerbc010472018-03-23 13:22:29 +0100433 NotifyReceiverOfEmptyPacket(packet.seqNum);
Elad Alonef09c5b2019-05-31 13:25:50 +0200434 rtcp_feedback_buffer_.SendBufferedRtcpFeedback();
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200435 return;
philipel54ca9192017-03-21 05:45:18 -0700436 }
437
Niels Möllerd5e02f02019-02-20 13:12:21 +0100438 if (packet.codec() == kVideoCodecH264) {
philipela45102f2017-02-22 05:30:39 -0800439 // Only when we start to receive packets will we know what payload type
440 // that will be used. When we know the payload type insert the correct
441 // sps/pps into the tracker.
442 if (packet.payloadType != last_payload_type_) {
443 last_payload_type_ = packet.payloadType;
444 InsertSpsPpsIntoTracker(packet.payloadType);
philipelfd5a20f2016-11-15 00:57:57 -0800445 }
446
Danil Chapovalovfbec2ec2019-10-28 13:27:05 +0100447 video_coding::H264SpsPpsTracker::FixedBitstream fixed =
448 tracker_.CopyAndFixBitstream(codec_payload, &packet.video_header);
449
450 switch (fixed.action) {
philipela45102f2017-02-22 05:30:39 -0800451 case video_coding::H264SpsPpsTracker::kRequestKeyframe:
Elad Alonef09c5b2019-05-31 13:25:50 +0200452 rtcp_feedback_buffer_.RequestKeyFrame();
453 rtcp_feedback_buffer_.SendBufferedRtcpFeedback();
Karl Wiberg80ba3332018-02-05 10:33:35 +0100454 RTC_FALLTHROUGH();
philipela45102f2017-02-22 05:30:39 -0800455 case video_coding::H264SpsPpsTracker::kDrop:
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200456 return;
philipela45102f2017-02-22 05:30:39 -0800457 case video_coding::H264SpsPpsTracker::kInsert:
Danil Chapovalovfbec2ec2019-10-28 13:27:05 +0100458 packet.dataPtr = fixed.data.release();
459 packet.sizeBytes = fixed.size;
philipela45102f2017-02-22 05:30:39 -0800460 break;
461 }
462
philipelfd5a20f2016-11-15 00:57:57 -0800463 } else {
philipela45102f2017-02-22 05:30:39 -0800464 uint8_t* data = new uint8_t[packet.sizeBytes];
465 memcpy(data, packet.dataPtr, packet.sizeBytes);
466 packet.dataPtr = data;
mflodman@webrtc.orgad4ee362011-11-28 22:39:24 +0000467 }
philipela45102f2017-02-22 05:30:39 -0800468
Elad Alonef09c5b2019-05-31 13:25:50 +0200469 rtcp_feedback_buffer_.SendBufferedRtcpFeedback();
Danil Chapovalov09860e02019-10-30 14:12:24 +0100470 frame_counter_.Add(packet.timestamp);
Danil Chapovalovce1ffcd2019-10-22 17:12:42 +0200471 OnInsertedPacket(packet_buffer_.InsertPacket(&packet));
niklase@google.com470e71d2011-07-07 08:21:25 +0000472}
473
nisseb1f2ff92017-06-09 04:01:55 -0700474void RtpVideoStreamReceiver::OnRecoveredPacket(const uint8_t* rtp_packet,
475 size_t rtp_packet_length) {
Niels Möllerb0573bc2017-09-25 10:47:00 +0200476 RtpPacketReceived packet;
477 if (!packet.Parse(rtp_packet, rtp_packet_length))
nisse30e89312017-05-29 08:16:37 -0700478 return;
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200479 if (packet.PayloadType() == config_.rtp.red_payload_type) {
480 RTC_LOG(LS_WARNING) << "Discarding recovered packet with RED encapsulation";
481 return;
482 }
483
Niels Möllerb0573bc2017-09-25 10:47:00 +0200484 packet.IdentifyExtensions(rtp_header_extensions_);
485 packet.set_payload_type_frequency(kVideoPayloadTypeFrequency);
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200486 // TODO(nisse): UlpfecReceiverImpl::ProcessReceivedFec passes both
487 // original (decapsulated) media packets and recovered packets to
488 // this callback. We need a way to distinguish, for setting
489 // packet.recovered() correctly. Ideally, move RED decapsulation out
490 // of the Ulpfec implementation.
Niels Möllerb0573bc2017-09-25 10:47:00 +0200491
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200492 ReceivePacket(packet);
wu@webrtc.org822fbd82013-08-15 23:38:54 +0000493}
494
nissed2ef3142017-05-11 08:00:58 -0700495// This method handles both regular RTP packets and packets recovered
496// via FlexFEC.
nisseb1f2ff92017-06-09 04:01:55 -0700497void RtpVideoStreamReceiver::OnRtpPacket(const RtpPacketReceived& packet) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200498 RTC_DCHECK_RUN_ON(&worker_task_checker_);
eladalonc0d481a2017-08-02 07:39:07 -0700499
eladalon8b073052017-08-25 00:49:08 -0700500 if (!receiving_) {
501 return;
502 }
solenberg@webrtc.orgfc320462014-02-11 15:27:49 +0000503
eladalon8b073052017-08-25 00:49:08 -0700504 if (!packet.recovered()) {
Jonas Oreland49ac5952018-09-26 16:04:32 +0200505 // TODO(nisse): Exclude out-of-order packets?
eladalon8b073052017-08-25 00:49:08 -0700506 int64_t now_ms = clock_->TimeInMilliseconds();
Niels Möllerb0d4b412018-08-28 13:58:15 +0200507 {
Chen Xing90f3b892019-06-25 10:16:14 +0200508 rtc::CritScope cs(&sync_info_lock_);
Niels Möllerb0d4b412018-08-28 13:58:15 +0200509 last_received_rtp_timestamp_ = packet.Timestamp();
510 last_received_rtp_system_time_ms_ = now_ms;
511 }
eladalon8b073052017-08-25 00:49:08 -0700512 // Periodically log the RTP header of incoming packets.
513 if (now_ms - last_packet_log_ms_ > kPacketLogIntervalMs) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200514 rtc::StringBuilder ss;
eladalon8b073052017-08-25 00:49:08 -0700515 ss << "Packet received on SSRC: " << packet.Ssrc()
516 << " with payload type: " << static_cast<int>(packet.PayloadType())
517 << ", timestamp: " << packet.Timestamp()
518 << ", sequence number: " << packet.SequenceNumber()
519 << ", arrival time: " << packet.arrival_time_ms();
520 int32_t time_offset;
521 if (packet.GetExtension<TransmissionOffset>(&time_offset)) {
522 ss << ", toffset: " << time_offset;
nisse38cc1d62017-02-13 05:59:46 -0800523 }
eladalon8b073052017-08-25 00:49:08 -0700524 uint32_t send_time;
525 if (packet.GetExtension<AbsoluteSendTime>(&send_time)) {
526 ss << ", abs send time: " << send_time;
527 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100528 RTC_LOG(LS_INFO) << ss.str();
eladalon8b073052017-08-25 00:49:08 -0700529 last_packet_log_ms_ = now_ms;
stefan@webrtc.orgeb24b042014-10-14 11:40:13 +0000530 }
531 }
wu@webrtc.orga9890802013-12-13 00:21:03 +0000532
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200533 ReceivePacket(packet);
nisse38cc1d62017-02-13 05:59:46 -0800534
asapersson@webrtc.org1457b472014-05-26 13:06:04 +0000535 // Update receive statistics after ReceivePacket.
536 // Receive statistics will be reset if the payload type changes (make sure
537 // that the first packet is included in the stats).
nissed2ef3142017-05-11 08:00:58 -0700538 if (!packet.recovered()) {
Niels Möller1f3206c2018-09-14 08:26:32 +0200539 rtp_receive_statistics_->OnRtpPacket(packet);
nissed2ef3142017-05-11 08:00:58 -0700540 }
eladalonc0d481a2017-08-02 07:39:07 -0700541
542 for (RtpPacketSinkInterface* secondary_sink : secondary_sinks_) {
543 secondary_sink->OnRtpPacket(packet);
544 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000545}
546
Niels Möller41684372019-03-25 15:51:03 +0100547void RtpVideoStreamReceiver::RequestKeyFrame() {
Elad Alonef09c5b2019-05-31 13:25:50 +0200548 // TODO(bugs.webrtc.org/10336): Allow the sender to ignore key frame requests
549 // issued by anything other than the LossNotificationController if it (the
550 // sender) is relying on LNTF alone.
Niels Möller2f5554d2019-05-29 13:35:14 +0200551 if (keyframe_request_sender_) {
552 keyframe_request_sender_->RequestKeyFrame();
553 } else {
Niels Möllerdd0094a2019-06-04 14:46:27 +0200554 rtp_rtcp_->SendPictureLossIndication();
Niels Möller2f5554d2019-05-29 13:35:14 +0200555 }
mflodmancfc8e3b2016-05-03 21:22:04 -0700556}
557
Elad Alon7d6a4c02019-02-25 13:00:51 +0100558void RtpVideoStreamReceiver::SendLossNotification(
559 uint16_t last_decoded_seq_num,
560 uint16_t last_received_seq_num,
Elad Alone86af2c2019-06-03 14:37:50 +0200561 bool decodability_flag,
562 bool buffering_allowed) {
Elad Alonfadb1812019-05-24 13:40:02 +0200563 RTC_DCHECK(config_.rtp.lntf.enabled);
Elad Alon7d6a4c02019-02-25 13:00:51 +0100564 rtp_rtcp_->SendLossNotification(last_decoded_seq_num, last_received_seq_num,
Elad Alone86af2c2019-06-03 14:37:50 +0200565 decodability_flag, buffering_allowed);
Elad Alon7d6a4c02019-02-25 13:00:51 +0100566}
567
nisseb1f2ff92017-06-09 04:01:55 -0700568bool RtpVideoStreamReceiver::IsUlpfecEnabled() const {
nisse3b3622f2017-09-26 02:49:21 -0700569 return config_.rtp.ulpfec_payload_type != -1;
brandtre6f98c72016-11-11 03:28:30 -0800570}
571
nisseb1f2ff92017-06-09 04:01:55 -0700572bool RtpVideoStreamReceiver::IsRetransmissionsEnabled() const {
mflodmandc7d0d22016-05-06 05:32:22 -0700573 return config_.rtp.nack.rtp_history_ms > 0;
574}
575
nisseb1f2ff92017-06-09 04:01:55 -0700576void RtpVideoStreamReceiver::RequestPacketRetransmit(
mflodmandc7d0d22016-05-06 05:32:22 -0700577 const std::vector<uint16_t>& sequence_numbers) {
578 rtp_rtcp_->SendNack(sequence_numbers);
579}
580
Benjamin Wright52426ed2019-03-01 11:01:59 -0800581bool RtpVideoStreamReceiver::IsDecryptable() const {
582 return frames_decryptable_.load();
583}
584
Danil Chapovalovce1ffcd2019-10-22 17:12:42 +0200585void RtpVideoStreamReceiver::OnInsertedPacket(
586 video_coding::PacketBuffer::InsertResult result) {
587 for (std::unique_ptr<video_coding::RtpFrameObject>& frame : result.frames) {
588 OnAssembledFrame(std::move(frame));
589 }
590 if (result.buffer_cleared) {
591 RequestKeyFrame();
592 }
593}
594
Elad Alonb4643ad2019-02-22 11:19:50 +0100595void RtpVideoStreamReceiver::OnAssembledFrame(
philipelfd5a20f2016-11-15 00:57:57 -0800596 std::unique_ptr<video_coding::RtpFrameObject> frame) {
Benjamin Wright00765292018-11-30 16:18:26 -0800597 RTC_DCHECK_RUN_ON(&network_tc_);
Elad Alon7d6a4c02019-02-25 13:00:51 +0100598 RTC_DCHECK(frame);
599
600 absl::optional<RtpGenericFrameDescriptor> descriptor =
601 frame->GetGenericFrameDescriptor();
602
603 if (loss_notification_controller_ && descriptor) {
604 loss_notification_controller_->OnAssembledFrame(
605 frame->first_seq_num(), descriptor->FrameId(),
606 descriptor->Discardable().value_or(false),
607 descriptor->FrameDependenciesDiffs());
Elad Alonca2c4302019-05-27 22:43:10 +0200608 }
609
Elad Alonef09c5b2019-05-31 13:25:50 +0200610 // If frames arrive before a key frame, they would not be decodable.
611 // In that case, request a key frame ASAP.
Elad Alonca2c4302019-05-27 22:43:10 +0200612 if (!has_received_frame_) {
Niels Möller8f7ce222019-03-21 15:43:58 +0100613 if (frame->FrameType() != VideoFrameType::kVideoFrameKey) {
Elad Alonef09c5b2019-05-31 13:25:50 +0200614 // |loss_notification_controller_|, if present, would have already
615 // requested a key frame when the first packet for the non-key frame
616 // had arrived, so no need to replicate the request.
617 if (!loss_notification_controller_) {
618 RequestKeyFrame();
619 }
Benjamin Wright39feabe2018-10-22 13:33:09 -0700620 }
Elad Alonef09c5b2019-05-31 13:25:50 +0200621 has_received_frame_ = true;
Benjamin Wright39feabe2018-10-22 13:33:09 -0700622 }
Elad Alon7d6a4c02019-02-25 13:00:51 +0100623
philipel7acc4a42019-09-26 11:25:52 +0200624 rtc::CritScope lock(&reference_finder_lock_);
625 // Reset |reference_finder_| if |frame| is new and the codec have changed.
626 if (current_codec_) {
627 bool frame_is_newer =
628 AheadOf(frame->Timestamp(), last_assembled_frame_rtp_timestamp_);
629
630 if (frame->codec_type() != current_codec_) {
631 if (frame_is_newer) {
632 // When we reset the |reference_finder_| we don't want new picture ids
633 // to overlap with old picture ids. To ensure that doesn't happen we
634 // start from the |last_completed_picture_id_| and add an offset in case
635 // of reordering.
636 reference_finder_ =
637 std::make_unique<video_coding::RtpFrameReferenceFinder>(
638 this, last_completed_picture_id_ +
639 std::numeric_limits<uint16_t>::max());
640 current_codec_ = frame->codec_type();
641 } else {
642 // Old frame from before the codec switch, discard it.
643 return;
644 }
645 }
646
647 if (frame_is_newer) {
648 last_assembled_frame_rtp_timestamp_ = frame->Timestamp();
649 }
650 } else {
651 current_codec_ = frame->codec_type();
652 last_assembled_frame_rtp_timestamp_ = frame->Timestamp();
653 }
654
Benjamin Wright00765292018-11-30 16:18:26 -0800655 if (buffered_frame_decryptor_ == nullptr) {
656 reference_finder_->ManageFrame(std::move(frame));
657 } else {
658 buffered_frame_decryptor_->ManageEncryptedFrame(std::move(frame));
Benjamin Wright192eeec2018-10-17 17:27:25 -0700659 }
philipelfd5a20f2016-11-15 00:57:57 -0800660}
661
nisseb1f2ff92017-06-09 04:01:55 -0700662void RtpVideoStreamReceiver::OnCompleteFrame(
philipele7c891f2018-02-22 14:35:06 +0100663 std::unique_ptr<video_coding::EncodedFrame> frame) {
philipelfd5a20f2016-11-15 00:57:57 -0800664 {
665 rtc::CritScope lock(&last_seq_num_cs_);
666 video_coding::RtpFrameObject* rtp_frame =
667 static_cast<video_coding::RtpFrameObject*>(frame.get());
philipel0fa82a62018-03-19 15:34:53 +0100668 last_seq_num_for_pic_id_[rtp_frame->id.picture_id] =
669 rtp_frame->last_seq_num();
philipelfd5a20f2016-11-15 00:57:57 -0800670 }
philipel7acc4a42019-09-26 11:25:52 +0200671 last_completed_picture_id_ =
672 std::max(last_completed_picture_id_, frame->id.picture_id);
philipelfd5a20f2016-11-15 00:57:57 -0800673 complete_frame_callback_->OnCompleteFrame(std::move(frame));
674}
675
Benjamin Wright00765292018-11-30 16:18:26 -0800676void RtpVideoStreamReceiver::OnDecryptedFrame(
677 std::unique_ptr<video_coding::RtpFrameObject> frame) {
philipel7acc4a42019-09-26 11:25:52 +0200678 rtc::CritScope lock(&reference_finder_lock_);
Benjamin Wright00765292018-11-30 16:18:26 -0800679 reference_finder_->ManageFrame(std::move(frame));
680}
681
Benjamin Wright2af5dcb2019-04-09 20:08:41 +0000682void RtpVideoStreamReceiver::OnDecryptionStatusChange(
683 FrameDecryptorInterface::Status status) {
684 frames_decryptable_.store(
685 (status == FrameDecryptorInterface::Status::kOk) ||
686 (status == FrameDecryptorInterface::Status::kRecoverable));
Benjamin Wright52426ed2019-03-01 11:01:59 -0800687}
688
Benjamin Wrighta5564482019-04-03 10:44:18 -0700689void RtpVideoStreamReceiver::SetFrameDecryptor(
690 rtc::scoped_refptr<FrameDecryptorInterface> frame_decryptor) {
691 RTC_DCHECK_RUN_ON(&network_tc_);
692 if (buffered_frame_decryptor_ == nullptr) {
693 buffered_frame_decryptor_ =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200694 std::make_unique<BufferedFrameDecryptor>(this, this);
Benjamin Wrighta5564482019-04-03 10:44:18 -0700695 }
696 buffered_frame_decryptor_->SetFrameDecryptor(std::move(frame_decryptor));
697}
698
Tommi81de14f2018-03-25 22:19:25 +0200699void RtpVideoStreamReceiver::UpdateRtt(int64_t max_rtt_ms) {
tommif284b7f2017-02-27 01:59:36 -0800700 if (nack_module_)
701 nack_module_->UpdateRtt(max_rtt_ms);
philipelfd5a20f2016-11-15 00:57:57 -0800702}
703
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200704absl::optional<int64_t> RtpVideoStreamReceiver::LastReceivedPacketMs() const {
Danil Chapovalovf7457e52019-09-20 17:57:15 +0200705 return packet_buffer_.LastReceivedPacketMs();
philipel3184f8e2017-05-18 08:08:53 -0700706}
707
Danil Chapovalovb9b146c2018-06-15 12:28:07 +0200708absl::optional<int64_t> RtpVideoStreamReceiver::LastReceivedKeyframePacketMs()
nisseb1f2ff92017-06-09 04:01:55 -0700709 const {
Danil Chapovalovf7457e52019-09-20 17:57:15 +0200710 return packet_buffer_.LastReceivedKeyframePacketMs();
philipel3184f8e2017-05-18 08:08:53 -0700711}
712
eladalonc0d481a2017-08-02 07:39:07 -0700713void RtpVideoStreamReceiver::AddSecondarySink(RtpPacketSinkInterface* sink) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200714 RTC_DCHECK_RUN_ON(&worker_task_checker_);
Steve Antonbd631a02019-03-28 10:51:27 -0700715 RTC_DCHECK(!absl::c_linear_search(secondary_sinks_, sink));
eladalonc0d481a2017-08-02 07:39:07 -0700716 secondary_sinks_.push_back(sink);
717}
718
719void RtpVideoStreamReceiver::RemoveSecondarySink(
720 const RtpPacketSinkInterface* sink) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200721 RTC_DCHECK_RUN_ON(&worker_task_checker_);
Steve Antonbd631a02019-03-28 10:51:27 -0700722 auto it = absl::c_find(secondary_sinks_, sink);
eladalonc0d481a2017-08-02 07:39:07 -0700723 if (it == secondary_sinks_.end()) {
724 // We might be rolling-back a call whose setup failed mid-way. In such a
725 // case, it's simpler to remove "everything" rather than remember what
726 // has already been added.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100727 RTC_LOG(LS_WARNING) << "Removal of unknown sink.";
eladalonc0d481a2017-08-02 07:39:07 -0700728 return;
729 }
730 secondary_sinks_.erase(it);
731}
732
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200733void RtpVideoStreamReceiver::ReceivePacket(const RtpPacketReceived& packet) {
734 if (packet.payload_size() == 0) {
Niels Möller0b926782018-08-21 17:49:24 +0200735 // Padding or keep-alive packet.
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200736 // TODO(nisse): Could drop empty packets earlier, but need to figure out how
737 // they should be counted in stats.
Niels Möller0b926782018-08-21 17:49:24 +0200738 NotifyReceiverOfEmptyPacket(packet.SequenceNumber());
nisse30e89312017-05-29 08:16:37 -0700739 return;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000740 }
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200741 if (packet.PayloadType() == config_.rtp.red_payload_type) {
Niels Möller1f3206c2018-09-14 08:26:32 +0200742 ParseAndHandleEncapsulatingHeader(packet);
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200743 return;
wu@webrtc.org822fbd82013-08-15 23:38:54 +0000744 }
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200745
Mirta Dvornicicfe68daa2019-05-23 13:21:12 +0200746 const auto type_it = payload_type_map_.find(packet.PayloadType());
747 if (type_it == payload_type_map_.end()) {
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200748 return;
749 }
750 auto depacketizer =
Mirta Dvornicicfe68daa2019-05-23 13:21:12 +0200751 absl::WrapUnique(RtpDepacketizer::Create(type_it->second));
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200752
753 if (!depacketizer) {
754 RTC_LOG(LS_ERROR) << "Failed to create depacketizer.";
755 return;
756 }
757 RtpDepacketizer::ParsedPayload parsed_payload;
758 if (!depacketizer->Parse(&parsed_payload, packet.payload().data(),
759 packet.payload().size())) {
760 RTC_LOG(LS_WARNING) << "Failed parsing payload.";
761 return;
762 }
763
Danil Chapovalovc71d85b2019-10-16 19:18:21 +0200764 OnReceivedPayloadData(
765 rtc::MakeArrayView(parsed_payload.payload, parsed_payload.payload_length),
766 packet, parsed_payload.video);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000767}
768
nisseb1f2ff92017-06-09 04:01:55 -0700769void RtpVideoStreamReceiver::ParseAndHandleEncapsulatingHeader(
Niels Möller1f3206c2018-09-14 08:26:32 +0200770 const RtpPacketReceived& packet) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200771 RTC_DCHECK_RUN_ON(&worker_task_checker_);
Niels Möller1f3206c2018-09-14 08:26:32 +0200772 if (packet.PayloadType() == config_.rtp.red_payload_type &&
773 packet.payload_size() > 0) {
774 if (packet.payload()[0] == config_.rtp.ulpfec_payload_type) {
Peter Boström0b250722016-04-22 18:23:15 +0200775 // Notify video_receiver about received FEC packets to avoid NACKing these
776 // packets.
Niels Möller1f3206c2018-09-14 08:26:32 +0200777 NotifyReceiverOfEmptyPacket(packet.SequenceNumber());
asapersson@webrtc.org37c05592015-01-28 13:58:27 +0000778 }
Danil Chapovalov04fd2152019-09-20 11:40:12 +0200779 if (!ulpfec_receiver_->AddReceivedRedPacket(
780 packet, config_.rtp.ulpfec_payload_type)) {
nisse30e89312017-05-29 08:16:37 -0700781 return;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000782 }
nisse30e89312017-05-29 08:16:37 -0700783 ulpfec_receiver_->ProcessReceivedFec();
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000784 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000785}
786
Niels Möllerbc010472018-03-23 13:22:29 +0100787// In the case of a video stream without picture ids and no rtx the
788// RtpFrameReferenceFinder will need to know about padding to
789// correctly calculate frame references.
790void RtpVideoStreamReceiver::NotifyReceiverOfEmptyPacket(uint16_t seq_num) {
philipel7acc4a42019-09-26 11:25:52 +0200791 {
792 rtc::CritScope lock(&reference_finder_lock_);
793 reference_finder_->PaddingReceived(seq_num);
794 }
Danil Chapovalovce1ffcd2019-10-22 17:12:42 +0200795 OnInsertedPacket(packet_buffer_.InsertPadding(seq_num));
Niels Möllerbc010472018-03-23 13:22:29 +0100796 if (nack_module_) {
Ying Wangb32bb952018-10-31 10:12:27 +0100797 nack_module_->OnReceivedPacket(seq_num, /* is_keyframe = */ false,
798 /* is _recovered = */ false);
asapersson@webrtc.org37c05592015-01-28 13:58:27 +0000799 }
Elad Alon7d6a4c02019-02-25 13:00:51 +0100800 if (loss_notification_controller_) {
Elad Alonca2c4302019-05-27 22:43:10 +0200801 // TODO(bugs.webrtc.org/10336): Handle empty packets.
Elad Alon7d6a4c02019-02-25 13:00:51 +0100802 RTC_LOG(LS_WARNING)
803 << "LossNotificationController does not expect empty packets.";
804 }
asapersson@webrtc.org37c05592015-01-28 13:58:27 +0000805}
806
nisseb1f2ff92017-06-09 04:01:55 -0700807bool RtpVideoStreamReceiver::DeliverRtcp(const uint8_t* rtcp_packet,
808 size_t rtcp_packet_length) {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200809 RTC_DCHECK_RUN_ON(&worker_task_checker_);
eladalon8b073052017-08-25 00:49:08 -0700810
811 if (!receiving_) {
812 return false;
Peter Boström4fa7eca2016-03-02 15:05:53 +0100813 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000814
Per83d09102016-04-15 14:59:13 +0200815 rtp_rtcp_->IncomingRtcpPacket(rtcp_packet, rtcp_packet_length);
wu@webrtc.orgcd701192014-04-24 22:10:24 +0000816
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000817 int64_t rtt = 0;
Niels Möller2ff1f2a2018-08-09 16:16:34 +0200818 rtp_rtcp_->RTT(config_.rtp.remote_ssrc, &rtt, nullptr, nullptr, nullptr);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +0000819 if (rtt == 0) {
820 // Waiting for valid rtt.
Peter Boströmd1d66ba2016-02-08 14:07:14 +0100821 return true;
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +0000822 }
823 uint32_t ntp_secs = 0;
824 uint32_t ntp_frac = 0;
825 uint32_t rtp_timestamp = 0;
Ilya Nikolaevskiy7172ea12017-10-30 11:17:34 +0100826 uint32_t recieved_ntp_secs = 0;
827 uint32_t recieved_ntp_frac = 0;
828 if (rtp_rtcp_->RemoteNTP(&ntp_secs, &ntp_frac, &recieved_ntp_secs,
829 &recieved_ntp_frac, &rtp_timestamp) != 0) {
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +0000830 // Waiting for RTCP.
Peter Boströmd1d66ba2016-02-08 14:07:14 +0100831 return true;
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +0000832 }
Ilya Nikolaevskiy7172ea12017-10-30 11:17:34 +0100833 NtpTime recieved_ntp(recieved_ntp_secs, recieved_ntp_frac);
834 int64_t time_since_recieved =
835 clock_->CurrentNtpInMilliseconds() - recieved_ntp.ToMs();
836 // Don't use old SRs to estimate time.
837 if (time_since_recieved <= 1) {
838 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
839 }
wu@webrtc.orgcd701192014-04-24 22:10:24 +0000840
Peter Boströmd1d66ba2016-02-08 14:07:14 +0100841 return true;
wu@webrtc.orgcd701192014-04-24 22:10:24 +0000842}
843
philipeld4fac692017-09-04 07:03:46 -0700844void RtpVideoStreamReceiver::FrameContinuous(int64_t picture_id) {
tommif284b7f2017-02-27 01:59:36 -0800845 if (!nack_module_)
846 return;
847
philipela45102f2017-02-22 05:30:39 -0800848 int seq_num = -1;
849 {
850 rtc::CritScope lock(&last_seq_num_cs_);
851 auto seq_num_it = last_seq_num_for_pic_id_.find(picture_id);
852 if (seq_num_it != last_seq_num_for_pic_id_.end())
853 seq_num = seq_num_it->second;
philipelfd5a20f2016-11-15 00:57:57 -0800854 }
philipela45102f2017-02-22 05:30:39 -0800855 if (seq_num != -1)
856 nack_module_->ClearUpTo(seq_num);
philipelfd5a20f2016-11-15 00:57:57 -0800857}
858
philipeld4fac692017-09-04 07:03:46 -0700859void RtpVideoStreamReceiver::FrameDecoded(int64_t picture_id) {
philipela45102f2017-02-22 05:30:39 -0800860 int seq_num = -1;
861 {
862 rtc::CritScope lock(&last_seq_num_cs_);
863 auto seq_num_it = last_seq_num_for_pic_id_.find(picture_id);
864 if (seq_num_it != last_seq_num_for_pic_id_.end()) {
865 seq_num = seq_num_it->second;
866 last_seq_num_for_pic_id_.erase(last_seq_num_for_pic_id_.begin(),
867 ++seq_num_it);
philipelfd5a20f2016-11-15 00:57:57 -0800868 }
philipela45102f2017-02-22 05:30:39 -0800869 }
870 if (seq_num != -1) {
Danil Chapovalovf7457e52019-09-20 17:57:15 +0200871 packet_buffer_.ClearTo(seq_num);
philipel7acc4a42019-09-26 11:25:52 +0200872 rtc::CritScope lock(&reference_finder_lock_);
philipela45102f2017-02-22 05:30:39 -0800873 reference_finder_->ClearTo(seq_num);
philipelfd5a20f2016-11-15 00:57:57 -0800874 }
875}
876
nisseb1f2ff92017-06-09 04:01:55 -0700877void RtpVideoStreamReceiver::SignalNetworkState(NetworkState state) {
mflodmandc7d0d22016-05-06 05:32:22 -0700878 rtp_rtcp_->SetRTCPStatus(state == kNetworkUp ? config_.rtp.rtcp_mode
879 : RtcpMode::kOff);
880}
881
nisseb1f2ff92017-06-09 04:01:55 -0700882void RtpVideoStreamReceiver::StartReceive() {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200883 RTC_DCHECK_RUN_ON(&worker_task_checker_);
mflodman@webrtc.orgad4ee362011-11-28 22:39:24 +0000884 receiving_ = true;
885}
886
nisseb1f2ff92017-06-09 04:01:55 -0700887void RtpVideoStreamReceiver::StopReceive() {
Sebastian Janssonb55015e2019-04-09 13:44:04 +0200888 RTC_DCHECK_RUN_ON(&worker_task_checker_);
mflodman@webrtc.orgad4ee362011-11-28 22:39:24 +0000889 receiving_ = false;
890}
891
nisseb1f2ff92017-06-09 04:01:55 -0700892void RtpVideoStreamReceiver::UpdateHistograms() {
brandtrd55c3f62016-10-31 04:51:33 -0700893 FecPacketCounter counter = ulpfec_receiver_->GetPacketCounter();
asapersson0c43f772016-11-30 01:42:26 -0800894 if (counter.first_packet_time_ms == -1)
895 return;
896
897 int64_t elapsed_sec =
898 (clock_->TimeInMilliseconds() - counter.first_packet_time_ms) / 1000;
899 if (elapsed_sec < metrics::kMinRunTimeInSeconds)
900 return;
901
mflodmandc7d0d22016-05-06 05:32:22 -0700902 if (counter.num_packets > 0) {
asapersson1d02d3e2016-09-09 22:40:25 -0700903 RTC_HISTOGRAM_PERCENTAGE(
mflodmandc7d0d22016-05-06 05:32:22 -0700904 "WebRTC.Video.ReceivedFecPacketsInPercent",
905 static_cast<int>(counter.num_fec_packets * 100 / counter.num_packets));
906 }
907 if (counter.num_fec_packets > 0) {
asapersson1d02d3e2016-09-09 22:40:25 -0700908 RTC_HISTOGRAM_PERCENTAGE("WebRTC.Video.RecoveredMediaPacketsInPercentOfFec",
909 static_cast<int>(counter.num_recovered_packets *
910 100 / counter.num_fec_packets));
mflodmandc7d0d22016-05-06 05:32:22 -0700911 }
Niels Möllercaef51e2019-08-27 09:19:49 +0200912 if (config_.rtp.ulpfec_payload_type != -1) {
913 RTC_HISTOGRAM_COUNTS_10000(
914 "WebRTC.Video.FecBitrateReceivedInKbps",
915 static_cast<int>(counter.num_bytes * 8 / elapsed_sec / 1000));
916 }
mflodmandc7d0d22016-05-06 05:32:22 -0700917}
918
nisseb1f2ff92017-06-09 04:01:55 -0700919void RtpVideoStreamReceiver::InsertSpsPpsIntoTracker(uint8_t payload_type) {
philipel022b54e2016-12-20 04:15:59 -0800920 auto codec_params_it = pt_codec_params_.find(payload_type);
921 if (codec_params_it == pt_codec_params_.end())
922 return;
923
Mirko Bonadei675513b2017-11-09 11:09:25 +0100924 RTC_LOG(LS_INFO) << "Found out of band supplied codec parameters for"
925 << " payload type: " << static_cast<int>(payload_type);
philipel022b54e2016-12-20 04:15:59 -0800926
927 H264SpropParameterSets sprop_decoder;
928 auto sprop_base64_it =
929 codec_params_it->second.find(cricket::kH264FmtpSpropParameterSets);
930
931 if (sprop_base64_it == codec_params_it->second.end())
932 return;
933
johan62d02c32017-01-24 04:38:27 -0800934 if (!sprop_decoder.DecodeSprop(sprop_base64_it->second.c_str()))
philipel022b54e2016-12-20 04:15:59 -0800935 return;
936
johand2b092f2017-01-24 02:38:17 -0800937 tracker_.InsertSpsPpsNalus(sprop_decoder.sps_nalu(),
938 sprop_decoder.pps_nalu());
philipel022b54e2016-12-20 04:15:59 -0800939}
940
mflodman@webrtc.orgad4ee362011-11-28 22:39:24 +0000941} // namespace webrtc