1 /*
2 * Copyright (c) 2012 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 "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
12
13 #include <string.h>
14
15 #include <algorithm>
16 #include <cstdint>
17 #include <memory>
18 #include <set>
19 #include <string>
20 #include <utility>
21
22 #include "api/transport/field_trial_based_config.h"
23 #include "modules/rtp_rtcp/source/rtcp_packet/dlrr.h"
24 #include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
25 #include "rtc_base/checks.h"
26 #include "rtc_base/logging.h"
27
28 #ifdef _WIN32
29 // Disable warning C4355: 'this' : used in base member initializer list.
30 #pragma warning(disable : 4355)
31 #endif
32
33 namespace webrtc {
34 namespace {
35 const int64_t kRtpRtcpMaxIdleTimeProcessMs = 5;
36 const int64_t kDefaultExpectedRetransmissionTimeMs = 125;
37
38 constexpr TimeDelta kRttUpdateInterval = TimeDelta::Millis(1000);
39 } // namespace
40
RtpSenderContext(const RtpRtcpInterface::Configuration & config)41 ModuleRtpRtcpImpl2::RtpSenderContext::RtpSenderContext(
42 const RtpRtcpInterface::Configuration& config)
43 : packet_history(config.clock, config.enable_rtx_padding_prioritization),
44 packet_sender(config, &packet_history),
45 non_paced_sender(&packet_sender, this),
46 packet_generator(
47 config,
48 &packet_history,
49 config.paced_sender ? config.paced_sender : &non_paced_sender) {}
AssignSequenceNumber(RtpPacketToSend * packet)50 void ModuleRtpRtcpImpl2::RtpSenderContext::AssignSequenceNumber(
51 RtpPacketToSend* packet) {
52 packet_generator.AssignSequenceNumber(packet);
53 }
54
ModuleRtpRtcpImpl2(const Configuration & configuration)55 ModuleRtpRtcpImpl2::ModuleRtpRtcpImpl2(const Configuration& configuration)
56 : worker_queue_(TaskQueueBase::Current()),
57 rtcp_sender_(configuration),
58 rtcp_receiver_(configuration, this),
59 clock_(configuration.clock),
60 last_rtt_process_time_(clock_->TimeInMilliseconds()),
61 next_process_time_(clock_->TimeInMilliseconds() +
62 kRtpRtcpMaxIdleTimeProcessMs),
63 packet_overhead_(28), // IPV4 UDP.
64 nack_last_time_sent_full_ms_(0),
65 nack_last_seq_number_sent_(0),
66 remote_bitrate_(configuration.remote_bitrate_estimator),
67 rtt_stats_(configuration.rtt_stats),
68 rtt_ms_(0) {
69 RTC_DCHECK(worker_queue_);
70 process_thread_checker_.Detach();
71 if (!configuration.receiver_only) {
72 rtp_sender_ = std::make_unique<RtpSenderContext>(configuration);
73 // Make sure rtcp sender use same timestamp offset as rtp sender.
74 rtcp_sender_.SetTimestampOffset(
75 rtp_sender_->packet_generator.TimestampOffset());
76 }
77
78 // Set default packet size limit.
79 // TODO(nisse): Kind-of duplicates
80 // webrtc::VideoSendStream::Config::Rtp::kDefaultMaxPacketSize.
81 const size_t kTcpOverIpv4HeaderSize = 40;
82 SetMaxRtpPacketSize(IP_PACKET_SIZE - kTcpOverIpv4HeaderSize);
83
84 if (rtt_stats_) {
85 rtt_update_task_ = RepeatingTaskHandle::DelayedStart(
86 worker_queue_, kRttUpdateInterval, [this]() {
87 PeriodicUpdate();
88 return kRttUpdateInterval;
89 });
90 }
91 }
92
~ModuleRtpRtcpImpl2()93 ModuleRtpRtcpImpl2::~ModuleRtpRtcpImpl2() {
94 RTC_DCHECK_RUN_ON(worker_queue_);
95 rtt_update_task_.Stop();
96 }
97
98 // static
Create(const Configuration & configuration)99 std::unique_ptr<ModuleRtpRtcpImpl2> ModuleRtpRtcpImpl2::Create(
100 const Configuration& configuration) {
101 RTC_DCHECK(configuration.clock);
102 RTC_DCHECK(TaskQueueBase::Current());
103 return std::make_unique<ModuleRtpRtcpImpl2>(configuration);
104 }
105
106 // Returns the number of milliseconds until the module want a worker thread
107 // to call Process.
TimeUntilNextProcess()108 int64_t ModuleRtpRtcpImpl2::TimeUntilNextProcess() {
109 RTC_DCHECK_RUN_ON(&process_thread_checker_);
110 return std::max<int64_t>(0,
111 next_process_time_ - clock_->TimeInMilliseconds());
112 }
113
114 // Process any pending tasks such as timeouts (non time critical events).
Process()115 void ModuleRtpRtcpImpl2::Process() {
116 RTC_DCHECK_RUN_ON(&process_thread_checker_);
117
118 const Timestamp now = clock_->CurrentTime();
119
120 // TODO(bugs.webrtc.org/11581): Figure out why we need to call Process() 200
121 // times a second.
122 next_process_time_ = now.ms() + kRtpRtcpMaxIdleTimeProcessMs;
123
124 // TODO(bugs.webrtc.org/11581): once we don't use Process() to trigger
125 // calls to SendRTCP(), the only remaining timer will require remote_bitrate_
126 // to be not null. In that case, we can disable the timer when it is null.
127 if (remote_bitrate_ && rtcp_sender_.Sending() && rtcp_sender_.TMMBR()) {
128 unsigned int target_bitrate = 0;
129 std::vector<unsigned int> ssrcs;
130 if (remote_bitrate_->LatestEstimate(&ssrcs, &target_bitrate)) {
131 if (!ssrcs.empty()) {
132 target_bitrate = target_bitrate / ssrcs.size();
133 }
134 rtcp_sender_.SetTargetBitrate(target_bitrate);
135 }
136 }
137
138 // TODO(bugs.webrtc.org/11581): Run this on a separate set of delayed tasks
139 // based off of next_time_to_send_rtcp_ in RTCPSender.
140 if (rtcp_sender_.TimeToSendRTCPReport())
141 rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
142 }
143
SetRtxSendStatus(int mode)144 void ModuleRtpRtcpImpl2::SetRtxSendStatus(int mode) {
145 rtp_sender_->packet_generator.SetRtxStatus(mode);
146 }
147
RtxSendStatus() const148 int ModuleRtpRtcpImpl2::RtxSendStatus() const {
149 return rtp_sender_ ? rtp_sender_->packet_generator.RtxStatus() : kRtxOff;
150 }
151
SetRtxSendPayloadType(int payload_type,int associated_payload_type)152 void ModuleRtpRtcpImpl2::SetRtxSendPayloadType(int payload_type,
153 int associated_payload_type) {
154 rtp_sender_->packet_generator.SetRtxPayloadType(payload_type,
155 associated_payload_type);
156 }
157
RtxSsrc() const158 absl::optional<uint32_t> ModuleRtpRtcpImpl2::RtxSsrc() const {
159 return rtp_sender_ ? rtp_sender_->packet_generator.RtxSsrc() : absl::nullopt;
160 }
161
FlexfecSsrc() const162 absl::optional<uint32_t> ModuleRtpRtcpImpl2::FlexfecSsrc() const {
163 if (rtp_sender_) {
164 return rtp_sender_->packet_generator.FlexfecSsrc();
165 }
166 return absl::nullopt;
167 }
168
IncomingRtcpPacket(const uint8_t * rtcp_packet,const size_t length)169 void ModuleRtpRtcpImpl2::IncomingRtcpPacket(const uint8_t* rtcp_packet,
170 const size_t length) {
171 rtcp_receiver_.IncomingPacket(rtcp_packet, length);
172 }
173
RegisterSendPayloadFrequency(int payload_type,int payload_frequency)174 void ModuleRtpRtcpImpl2::RegisterSendPayloadFrequency(int payload_type,
175 int payload_frequency) {
176 rtcp_sender_.SetRtpClockRate(payload_type, payload_frequency);
177 }
178
DeRegisterSendPayload(const int8_t payload_type)179 int32_t ModuleRtpRtcpImpl2::DeRegisterSendPayload(const int8_t payload_type) {
180 return 0;
181 }
182
StartTimestamp() const183 uint32_t ModuleRtpRtcpImpl2::StartTimestamp() const {
184 return rtp_sender_->packet_generator.TimestampOffset();
185 }
186
187 // Configure start timestamp, default is a random number.
SetStartTimestamp(const uint32_t timestamp)188 void ModuleRtpRtcpImpl2::SetStartTimestamp(const uint32_t timestamp) {
189 rtcp_sender_.SetTimestampOffset(timestamp);
190 rtp_sender_->packet_generator.SetTimestampOffset(timestamp);
191 rtp_sender_->packet_sender.SetTimestampOffset(timestamp);
192 }
193
SequenceNumber() const194 uint16_t ModuleRtpRtcpImpl2::SequenceNumber() const {
195 return rtp_sender_->packet_generator.SequenceNumber();
196 }
197
198 // Set SequenceNumber, default is a random number.
SetSequenceNumber(const uint16_t seq_num)199 void ModuleRtpRtcpImpl2::SetSequenceNumber(const uint16_t seq_num) {
200 rtp_sender_->packet_generator.SetSequenceNumber(seq_num);
201 }
202
SetRtpState(const RtpState & rtp_state)203 void ModuleRtpRtcpImpl2::SetRtpState(const RtpState& rtp_state) {
204 rtp_sender_->packet_generator.SetRtpState(rtp_state);
205 rtcp_sender_.SetTimestampOffset(rtp_state.start_timestamp);
206 }
207
SetRtxState(const RtpState & rtp_state)208 void ModuleRtpRtcpImpl2::SetRtxState(const RtpState& rtp_state) {
209 rtp_sender_->packet_generator.SetRtxRtpState(rtp_state);
210 }
211
GetRtpState() const212 RtpState ModuleRtpRtcpImpl2::GetRtpState() const {
213 RtpState state = rtp_sender_->packet_generator.GetRtpState();
214 return state;
215 }
216
GetRtxState() const217 RtpState ModuleRtpRtcpImpl2::GetRtxState() const {
218 return rtp_sender_->packet_generator.GetRtxRtpState();
219 }
220
SetRid(const std::string & rid)221 void ModuleRtpRtcpImpl2::SetRid(const std::string& rid) {
222 if (rtp_sender_) {
223 rtp_sender_->packet_generator.SetRid(rid);
224 }
225 }
226
SetMid(const std::string & mid)227 void ModuleRtpRtcpImpl2::SetMid(const std::string& mid) {
228 if (rtp_sender_) {
229 rtp_sender_->packet_generator.SetMid(mid);
230 }
231 // TODO(bugs.webrtc.org/4050): If we end up supporting the MID SDES item for
232 // RTCP, this will need to be passed down to the RTCPSender also.
233 }
234
SetCsrcs(const std::vector<uint32_t> & csrcs)235 void ModuleRtpRtcpImpl2::SetCsrcs(const std::vector<uint32_t>& csrcs) {
236 rtcp_sender_.SetCsrcs(csrcs);
237 rtp_sender_->packet_generator.SetCsrcs(csrcs);
238 }
239
240 // TODO(pbos): Handle media and RTX streams separately (separate RTCP
241 // feedbacks).
GetFeedbackState()242 RTCPSender::FeedbackState ModuleRtpRtcpImpl2::GetFeedbackState() {
243 // TODO(bugs.webrtc.org/11581): Called by potentially multiple threads.
244 // Mostly "Send*" methods. Make sure it's only called on the
245 // construction thread.
246
247 RTCPSender::FeedbackState state;
248 // This is called also when receiver_only is true. Hence below
249 // checks that rtp_sender_ exists.
250 if (rtp_sender_) {
251 StreamDataCounters rtp_stats;
252 StreamDataCounters rtx_stats;
253 rtp_sender_->packet_sender.GetDataCounters(&rtp_stats, &rtx_stats);
254 state.packets_sent =
255 rtp_stats.transmitted.packets + rtx_stats.transmitted.packets;
256 state.media_bytes_sent = rtp_stats.transmitted.payload_bytes +
257 rtx_stats.transmitted.payload_bytes;
258 state.send_bitrate =
259 rtp_sender_->packet_sender.GetSendRates().Sum().bps<uint32_t>();
260 }
261 state.receiver = &rtcp_receiver_;
262
263 LastReceivedNTP(&state.last_rr_ntp_secs, &state.last_rr_ntp_frac,
264 &state.remote_sr);
265
266 state.last_xr_rtis = rtcp_receiver_.ConsumeReceivedXrReferenceTimeInfo();
267
268 return state;
269 }
270
271 // TODO(nisse): This method shouldn't be called for a receive-only
272 // stream. Delete rtp_sender_ check as soon as all applications are
273 // updated.
SetSendingStatus(const bool sending)274 int32_t ModuleRtpRtcpImpl2::SetSendingStatus(const bool sending) {
275 if (rtcp_sender_.Sending() != sending) {
276 // Sends RTCP BYE when going from true to false
277 if (rtcp_sender_.SetSendingStatus(GetFeedbackState(), sending) != 0) {
278 RTC_LOG(LS_WARNING) << "Failed to send RTCP BYE";
279 }
280 }
281 return 0;
282 }
283
Sending() const284 bool ModuleRtpRtcpImpl2::Sending() const {
285 return rtcp_sender_.Sending();
286 }
287
288 // TODO(nisse): This method shouldn't be called for a receive-only
289 // stream. Delete rtp_sender_ check as soon as all applications are
290 // updated.
SetSendingMediaStatus(const bool sending)291 void ModuleRtpRtcpImpl2::SetSendingMediaStatus(const bool sending) {
292 if (rtp_sender_) {
293 rtp_sender_->packet_generator.SetSendingMediaStatus(sending);
294 } else {
295 RTC_DCHECK(!sending);
296 }
297 }
298
SendingMedia() const299 bool ModuleRtpRtcpImpl2::SendingMedia() const {
300 return rtp_sender_ ? rtp_sender_->packet_generator.SendingMedia() : false;
301 }
302
IsAudioConfigured() const303 bool ModuleRtpRtcpImpl2::IsAudioConfigured() const {
304 return rtp_sender_ ? rtp_sender_->packet_generator.IsAudioConfigured()
305 : false;
306 }
307
SetAsPartOfAllocation(bool part_of_allocation)308 void ModuleRtpRtcpImpl2::SetAsPartOfAllocation(bool part_of_allocation) {
309 RTC_CHECK(rtp_sender_);
310 rtp_sender_->packet_sender.ForceIncludeSendPacketsInAllocation(
311 part_of_allocation);
312 }
313
OnSendingRtpFrame(uint32_t timestamp,int64_t capture_time_ms,int payload_type,bool force_sender_report)314 bool ModuleRtpRtcpImpl2::OnSendingRtpFrame(uint32_t timestamp,
315 int64_t capture_time_ms,
316 int payload_type,
317 bool force_sender_report) {
318 if (!Sending())
319 return false;
320
321 rtcp_sender_.SetLastRtpTime(timestamp, capture_time_ms, payload_type);
322 // Make sure an RTCP report isn't queued behind a key frame.
323 if (rtcp_sender_.TimeToSendRTCPReport(force_sender_report))
324 rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
325
326 return true;
327 }
328
TrySendPacket(RtpPacketToSend * packet,const PacedPacketInfo & pacing_info)329 bool ModuleRtpRtcpImpl2::TrySendPacket(RtpPacketToSend* packet,
330 const PacedPacketInfo& pacing_info) {
331 RTC_DCHECK(rtp_sender_);
332 // TODO(sprang): Consider if we can remove this check.
333 if (!rtp_sender_->packet_generator.SendingMedia()) {
334 return false;
335 }
336 rtp_sender_->packet_sender.SendPacket(packet, pacing_info);
337 return true;
338 }
339
SetFecProtectionParams(const FecProtectionParams & delta_params,const FecProtectionParams & key_params)340 void ModuleRtpRtcpImpl2::SetFecProtectionParams(
341 const FecProtectionParams& delta_params,
342 const FecProtectionParams& key_params) {
343 RTC_DCHECK(rtp_sender_);
344 rtp_sender_->packet_sender.SetFecProtectionParameters(delta_params,
345 key_params);
346 }
347
348 std::vector<std::unique_ptr<RtpPacketToSend>>
FetchFecPackets()349 ModuleRtpRtcpImpl2::FetchFecPackets() {
350 RTC_DCHECK(rtp_sender_);
351 auto fec_packets = rtp_sender_->packet_sender.FetchFecPackets();
352 if (!fec_packets.empty()) {
353 // Don't assign sequence numbers for FlexFEC packets.
354 const bool generate_sequence_numbers =
355 !rtp_sender_->packet_sender.FlexFecSsrc().has_value();
356 if (generate_sequence_numbers) {
357 for (auto& fec_packet : fec_packets) {
358 rtp_sender_->packet_generator.AssignSequenceNumber(fec_packet.get());
359 }
360 }
361 }
362 return fec_packets;
363 }
364
OnPacketsAcknowledged(rtc::ArrayView<const uint16_t> sequence_numbers)365 void ModuleRtpRtcpImpl2::OnPacketsAcknowledged(
366 rtc::ArrayView<const uint16_t> sequence_numbers) {
367 RTC_DCHECK(rtp_sender_);
368 rtp_sender_->packet_history.CullAcknowledgedPackets(sequence_numbers);
369 }
370
SupportsPadding() const371 bool ModuleRtpRtcpImpl2::SupportsPadding() const {
372 RTC_DCHECK(rtp_sender_);
373 return rtp_sender_->packet_generator.SupportsPadding();
374 }
375
SupportsRtxPayloadPadding() const376 bool ModuleRtpRtcpImpl2::SupportsRtxPayloadPadding() const {
377 RTC_DCHECK(rtp_sender_);
378 return rtp_sender_->packet_generator.SupportsRtxPayloadPadding();
379 }
380
381 std::vector<std::unique_ptr<RtpPacketToSend>>
GeneratePadding(size_t target_size_bytes)382 ModuleRtpRtcpImpl2::GeneratePadding(size_t target_size_bytes) {
383 RTC_DCHECK(rtp_sender_);
384 return rtp_sender_->packet_generator.GeneratePadding(
385 target_size_bytes, rtp_sender_->packet_sender.MediaHasBeenSent());
386 }
387
388 std::vector<RtpSequenceNumberMap::Info>
GetSentRtpPacketInfos(rtc::ArrayView<const uint16_t> sequence_numbers) const389 ModuleRtpRtcpImpl2::GetSentRtpPacketInfos(
390 rtc::ArrayView<const uint16_t> sequence_numbers) const {
391 RTC_DCHECK(rtp_sender_);
392 return rtp_sender_->packet_sender.GetSentRtpPacketInfos(sequence_numbers);
393 }
394
ExpectedPerPacketOverhead() const395 size_t ModuleRtpRtcpImpl2::ExpectedPerPacketOverhead() const {
396 if (!rtp_sender_) {
397 return 0;
398 }
399 return rtp_sender_->packet_generator.ExpectedPerPacketOverhead();
400 }
401
MaxRtpPacketSize() const402 size_t ModuleRtpRtcpImpl2::MaxRtpPacketSize() const {
403 RTC_DCHECK(rtp_sender_);
404 return rtp_sender_->packet_generator.MaxRtpPacketSize();
405 }
406
SetMaxRtpPacketSize(size_t rtp_packet_size)407 void ModuleRtpRtcpImpl2::SetMaxRtpPacketSize(size_t rtp_packet_size) {
408 RTC_DCHECK_LE(rtp_packet_size, IP_PACKET_SIZE)
409 << "rtp packet size too large: " << rtp_packet_size;
410 RTC_DCHECK_GT(rtp_packet_size, packet_overhead_)
411 << "rtp packet size too small: " << rtp_packet_size;
412
413 rtcp_sender_.SetMaxRtpPacketSize(rtp_packet_size);
414 if (rtp_sender_) {
415 rtp_sender_->packet_generator.SetMaxRtpPacketSize(rtp_packet_size);
416 }
417 }
418
RTCP() const419 RtcpMode ModuleRtpRtcpImpl2::RTCP() const {
420 return rtcp_sender_.Status();
421 }
422
423 // Configure RTCP status i.e on/off.
SetRTCPStatus(const RtcpMode method)424 void ModuleRtpRtcpImpl2::SetRTCPStatus(const RtcpMode method) {
425 rtcp_sender_.SetRTCPStatus(method);
426 }
427
SetCNAME(const char * c_name)428 int32_t ModuleRtpRtcpImpl2::SetCNAME(const char* c_name) {
429 return rtcp_sender_.SetCNAME(c_name);
430 }
431
RemoteNTP(uint32_t * received_ntpsecs,uint32_t * received_ntpfrac,uint32_t * rtcp_arrival_time_secs,uint32_t * rtcp_arrival_time_frac,uint32_t * rtcp_timestamp) const432 int32_t ModuleRtpRtcpImpl2::RemoteNTP(uint32_t* received_ntpsecs,
433 uint32_t* received_ntpfrac,
434 uint32_t* rtcp_arrival_time_secs,
435 uint32_t* rtcp_arrival_time_frac,
436 uint32_t* rtcp_timestamp) const {
437 return rtcp_receiver_.NTP(received_ntpsecs, received_ntpfrac,
438 rtcp_arrival_time_secs, rtcp_arrival_time_frac,
439 rtcp_timestamp)
440 ? 0
441 : -1;
442 }
443
444 // TODO(tommi): Check if |avg_rtt_ms|, |min_rtt_ms|, |max_rtt_ms| params are
445 // actually used in practice (some callers ask for it but don't use it). It
446 // could be that only |rtt| is needed and if so, then the fast path could be to
447 // just call rtt_ms() and rely on the calculation being done periodically.
RTT(const uint32_t remote_ssrc,int64_t * rtt,int64_t * avg_rtt,int64_t * min_rtt,int64_t * max_rtt) const448 int32_t ModuleRtpRtcpImpl2::RTT(const uint32_t remote_ssrc,
449 int64_t* rtt,
450 int64_t* avg_rtt,
451 int64_t* min_rtt,
452 int64_t* max_rtt) const {
453 int32_t ret = rtcp_receiver_.RTT(remote_ssrc, rtt, avg_rtt, min_rtt, max_rtt);
454 if (rtt && *rtt == 0) {
455 // Try to get RTT from RtcpRttStats class.
456 *rtt = rtt_ms();
457 }
458 return ret;
459 }
460
ExpectedRetransmissionTimeMs() const461 int64_t ModuleRtpRtcpImpl2::ExpectedRetransmissionTimeMs() const {
462 int64_t expected_retransmission_time_ms = rtt_ms();
463 if (expected_retransmission_time_ms > 0) {
464 return expected_retransmission_time_ms;
465 }
466 // No rtt available (|kRttUpdateInterval| not yet passed?), so try to
467 // poll avg_rtt_ms directly from rtcp receiver.
468 if (rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), nullptr,
469 &expected_retransmission_time_ms, nullptr,
470 nullptr) == 0) {
471 return expected_retransmission_time_ms;
472 }
473 return kDefaultExpectedRetransmissionTimeMs;
474 }
475
476 // Force a send of an RTCP packet.
477 // Normal SR and RR are triggered via the process function.
SendRTCP(RTCPPacketType packet_type)478 int32_t ModuleRtpRtcpImpl2::SendRTCP(RTCPPacketType packet_type) {
479 return rtcp_sender_.SendRTCP(GetFeedbackState(), packet_type);
480 }
481
SetRtcpXrRrtrStatus(bool enable)482 void ModuleRtpRtcpImpl2::SetRtcpXrRrtrStatus(bool enable) {
483 rtcp_receiver_.SetRtcpXrRrtrStatus(enable);
484 rtcp_sender_.SendRtcpXrReceiverReferenceTime(enable);
485 }
486
RtcpXrRrtrStatus() const487 bool ModuleRtpRtcpImpl2::RtcpXrRrtrStatus() const {
488 return rtcp_sender_.RtcpXrReceiverReferenceTime();
489 }
490
GetSendStreamDataCounters(StreamDataCounters * rtp_counters,StreamDataCounters * rtx_counters) const491 void ModuleRtpRtcpImpl2::GetSendStreamDataCounters(
492 StreamDataCounters* rtp_counters,
493 StreamDataCounters* rtx_counters) const {
494 rtp_sender_->packet_sender.GetDataCounters(rtp_counters, rtx_counters);
495 }
496
497 // Received RTCP report.
RemoteRTCPStat(std::vector<RTCPReportBlock> * receive_blocks) const498 int32_t ModuleRtpRtcpImpl2::RemoteRTCPStat(
499 std::vector<RTCPReportBlock>* receive_blocks) const {
500 return rtcp_receiver_.StatisticsReceived(receive_blocks);
501 }
502
GetLatestReportBlockData() const503 std::vector<ReportBlockData> ModuleRtpRtcpImpl2::GetLatestReportBlockData()
504 const {
505 return rtcp_receiver_.GetLatestReportBlockData();
506 }
507
508 // (REMB) Receiver Estimated Max Bitrate.
SetRemb(int64_t bitrate_bps,std::vector<uint32_t> ssrcs)509 void ModuleRtpRtcpImpl2::SetRemb(int64_t bitrate_bps,
510 std::vector<uint32_t> ssrcs) {
511 rtcp_sender_.SetRemb(bitrate_bps, std::move(ssrcs));
512 }
513
UnsetRemb()514 void ModuleRtpRtcpImpl2::UnsetRemb() {
515 rtcp_sender_.UnsetRemb();
516 }
517
SetExtmapAllowMixed(bool extmap_allow_mixed)518 void ModuleRtpRtcpImpl2::SetExtmapAllowMixed(bool extmap_allow_mixed) {
519 rtp_sender_->packet_generator.SetExtmapAllowMixed(extmap_allow_mixed);
520 }
521
RegisterRtpHeaderExtension(absl::string_view uri,int id)522 void ModuleRtpRtcpImpl2::RegisterRtpHeaderExtension(absl::string_view uri,
523 int id) {
524 bool registered =
525 rtp_sender_->packet_generator.RegisterRtpHeaderExtension(uri, id);
526 RTC_CHECK(registered);
527 }
528
DeregisterSendRtpHeaderExtension(const RTPExtensionType type)529 int32_t ModuleRtpRtcpImpl2::DeregisterSendRtpHeaderExtension(
530 const RTPExtensionType type) {
531 return rtp_sender_->packet_generator.DeregisterRtpHeaderExtension(type);
532 }
DeregisterSendRtpHeaderExtension(absl::string_view uri)533 void ModuleRtpRtcpImpl2::DeregisterSendRtpHeaderExtension(
534 absl::string_view uri) {
535 rtp_sender_->packet_generator.DeregisterRtpHeaderExtension(uri);
536 }
537
SetTmmbn(std::vector<rtcp::TmmbItem> bounding_set)538 void ModuleRtpRtcpImpl2::SetTmmbn(std::vector<rtcp::TmmbItem> bounding_set) {
539 rtcp_sender_.SetTmmbn(std::move(bounding_set));
540 }
541
542 // Send a Negative acknowledgment packet.
SendNACK(const uint16_t * nack_list,const uint16_t size)543 int32_t ModuleRtpRtcpImpl2::SendNACK(const uint16_t* nack_list,
544 const uint16_t size) {
545 uint16_t nack_length = size;
546 uint16_t start_id = 0;
547 int64_t now_ms = clock_->TimeInMilliseconds();
548 if (TimeToSendFullNackList(now_ms)) {
549 nack_last_time_sent_full_ms_ = now_ms;
550 } else {
551 // Only send extended list.
552 if (nack_last_seq_number_sent_ == nack_list[size - 1]) {
553 // Last sequence number is the same, do not send list.
554 return 0;
555 }
556 // Send new sequence numbers.
557 for (int i = 0; i < size; ++i) {
558 if (nack_last_seq_number_sent_ == nack_list[i]) {
559 start_id = i + 1;
560 break;
561 }
562 }
563 nack_length = size - start_id;
564 }
565
566 // Our RTCP NACK implementation is limited to kRtcpMaxNackFields sequence
567 // numbers per RTCP packet.
568 if (nack_length > kRtcpMaxNackFields) {
569 nack_length = kRtcpMaxNackFields;
570 }
571 nack_last_seq_number_sent_ = nack_list[start_id + nack_length - 1];
572
573 return rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, nack_length,
574 &nack_list[start_id]);
575 }
576
SendNack(const std::vector<uint16_t> & sequence_numbers)577 void ModuleRtpRtcpImpl2::SendNack(
578 const std::vector<uint16_t>& sequence_numbers) {
579 rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, sequence_numbers.size(),
580 sequence_numbers.data());
581 }
582
TimeToSendFullNackList(int64_t now) const583 bool ModuleRtpRtcpImpl2::TimeToSendFullNackList(int64_t now) const {
584 // Use RTT from RtcpRttStats class if provided.
585 int64_t rtt = rtt_ms();
586 if (rtt == 0) {
587 rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
588 }
589
590 const int64_t kStartUpRttMs = 100;
591 int64_t wait_time = 5 + ((rtt * 3) >> 1); // 5 + RTT * 1.5.
592 if (rtt == 0) {
593 wait_time = kStartUpRttMs;
594 }
595
596 // Send a full NACK list once within every |wait_time|.
597 return now - nack_last_time_sent_full_ms_ > wait_time;
598 }
599
600 // Store the sent packets, needed to answer to Negative acknowledgment requests.
SetStorePacketsStatus(const bool enable,const uint16_t number_to_store)601 void ModuleRtpRtcpImpl2::SetStorePacketsStatus(const bool enable,
602 const uint16_t number_to_store) {
603 rtp_sender_->packet_history.SetStorePacketsStatus(
604 enable ? RtpPacketHistory::StorageMode::kStoreAndCull
605 : RtpPacketHistory::StorageMode::kDisabled,
606 number_to_store);
607 }
608
StorePackets() const609 bool ModuleRtpRtcpImpl2::StorePackets() const {
610 return rtp_sender_->packet_history.GetStorageMode() !=
611 RtpPacketHistory::StorageMode::kDisabled;
612 }
613
SendCombinedRtcpPacket(std::vector<std::unique_ptr<rtcp::RtcpPacket>> rtcp_packets)614 void ModuleRtpRtcpImpl2::SendCombinedRtcpPacket(
615 std::vector<std::unique_ptr<rtcp::RtcpPacket>> rtcp_packets) {
616 rtcp_sender_.SendCombinedRtcpPacket(std::move(rtcp_packets));
617 }
618
SendLossNotification(uint16_t last_decoded_seq_num,uint16_t last_received_seq_num,bool decodability_flag,bool buffering_allowed)619 int32_t ModuleRtpRtcpImpl2::SendLossNotification(uint16_t last_decoded_seq_num,
620 uint16_t last_received_seq_num,
621 bool decodability_flag,
622 bool buffering_allowed) {
623 return rtcp_sender_.SendLossNotification(
624 GetFeedbackState(), last_decoded_seq_num, last_received_seq_num,
625 decodability_flag, buffering_allowed);
626 }
627
SetRemoteSSRC(const uint32_t ssrc)628 void ModuleRtpRtcpImpl2::SetRemoteSSRC(const uint32_t ssrc) {
629 // Inform about the incoming SSRC.
630 rtcp_sender_.SetRemoteSSRC(ssrc);
631 rtcp_receiver_.SetRemoteSSRC(ssrc);
632 }
633
634 // TODO(nisse): Delete video_rate amd fec_rate arguments.
BitrateSent(uint32_t * total_rate,uint32_t * video_rate,uint32_t * fec_rate,uint32_t * nack_rate) const635 void ModuleRtpRtcpImpl2::BitrateSent(uint32_t* total_rate,
636 uint32_t* video_rate,
637 uint32_t* fec_rate,
638 uint32_t* nack_rate) const {
639 RTC_DCHECK_RUN_ON(worker_queue_);
640 RtpSendRates send_rates = rtp_sender_->packet_sender.GetSendRates();
641 *total_rate = send_rates.Sum().bps<uint32_t>();
642 if (video_rate)
643 *video_rate = 0;
644 if (fec_rate)
645 *fec_rate = 0;
646 *nack_rate = send_rates[RtpPacketMediaType::kRetransmission].bps<uint32_t>();
647 }
648
GetSendRates() const649 RtpSendRates ModuleRtpRtcpImpl2::GetSendRates() const {
650 RTC_DCHECK_RUN_ON(worker_queue_);
651 return rtp_sender_->packet_sender.GetSendRates();
652 }
653
OnRequestSendReport()654 void ModuleRtpRtcpImpl2::OnRequestSendReport() {
655 SendRTCP(kRtcpSr);
656 }
657
OnReceivedNack(const std::vector<uint16_t> & nack_sequence_numbers)658 void ModuleRtpRtcpImpl2::OnReceivedNack(
659 const std::vector<uint16_t>& nack_sequence_numbers) {
660 if (!rtp_sender_)
661 return;
662
663 if (!StorePackets() || nack_sequence_numbers.empty()) {
664 return;
665 }
666 // Use RTT from RtcpRttStats class if provided.
667 int64_t rtt = rtt_ms();
668 if (rtt == 0) {
669 rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
670 }
671 rtp_sender_->packet_generator.OnReceivedNack(nack_sequence_numbers, rtt);
672 }
673
OnReceivedRtcpReportBlocks(const ReportBlockList & report_blocks)674 void ModuleRtpRtcpImpl2::OnReceivedRtcpReportBlocks(
675 const ReportBlockList& report_blocks) {
676 if (rtp_sender_) {
677 uint32_t ssrc = SSRC();
678 absl::optional<uint32_t> rtx_ssrc;
679 if (rtp_sender_->packet_generator.RtxStatus() != kRtxOff) {
680 rtx_ssrc = rtp_sender_->packet_generator.RtxSsrc();
681 }
682
683 for (const RTCPReportBlock& report_block : report_blocks) {
684 if (ssrc == report_block.source_ssrc) {
685 rtp_sender_->packet_generator.OnReceivedAckOnSsrc(
686 report_block.extended_highest_sequence_number);
687 } else if (rtx_ssrc && *rtx_ssrc == report_block.source_ssrc) {
688 rtp_sender_->packet_generator.OnReceivedAckOnRtxSsrc(
689 report_block.extended_highest_sequence_number);
690 }
691 }
692 }
693 }
694
LastReceivedNTP(uint32_t * rtcp_arrival_time_secs,uint32_t * rtcp_arrival_time_frac,uint32_t * remote_sr) const695 bool ModuleRtpRtcpImpl2::LastReceivedNTP(
696 uint32_t* rtcp_arrival_time_secs, // When we got the last report.
697 uint32_t* rtcp_arrival_time_frac,
698 uint32_t* remote_sr) const {
699 // Remote SR: NTP inside the last received (mid 16 bits from sec and frac).
700 uint32_t ntp_secs = 0;
701 uint32_t ntp_frac = 0;
702
703 if (!rtcp_receiver_.NTP(&ntp_secs, &ntp_frac, rtcp_arrival_time_secs,
704 rtcp_arrival_time_frac, NULL)) {
705 return false;
706 }
707 *remote_sr =
708 ((ntp_secs & 0x0000ffff) << 16) + ((ntp_frac & 0xffff0000) >> 16);
709 return true;
710 }
711
set_rtt_ms(int64_t rtt_ms)712 void ModuleRtpRtcpImpl2::set_rtt_ms(int64_t rtt_ms) {
713 RTC_DCHECK_RUN_ON(worker_queue_);
714 {
715 MutexLock lock(&mutex_rtt_);
716 rtt_ms_ = rtt_ms;
717 }
718 if (rtp_sender_) {
719 rtp_sender_->packet_history.SetRtt(rtt_ms);
720 }
721 }
722
rtt_ms() const723 int64_t ModuleRtpRtcpImpl2::rtt_ms() const {
724 MutexLock lock(&mutex_rtt_);
725 return rtt_ms_;
726 }
727
SetVideoBitrateAllocation(const VideoBitrateAllocation & bitrate)728 void ModuleRtpRtcpImpl2::SetVideoBitrateAllocation(
729 const VideoBitrateAllocation& bitrate) {
730 rtcp_sender_.SetVideoBitrateAllocation(bitrate);
731 }
732
RtpSender()733 RTPSender* ModuleRtpRtcpImpl2::RtpSender() {
734 return rtp_sender_ ? &rtp_sender_->packet_generator : nullptr;
735 }
736
RtpSender() const737 const RTPSender* ModuleRtpRtcpImpl2::RtpSender() const {
738 return rtp_sender_ ? &rtp_sender_->packet_generator : nullptr;
739 }
740
PeriodicUpdate()741 void ModuleRtpRtcpImpl2::PeriodicUpdate() {
742 RTC_DCHECK_RUN_ON(worker_queue_);
743
744 Timestamp check_since = clock_->CurrentTime() - kRttUpdateInterval;
745 absl::optional<TimeDelta> rtt =
746 rtcp_receiver_.OnPeriodicRttUpdate(check_since, rtcp_sender_.Sending());
747 if (rtt) {
748 rtt_stats_->OnRttUpdate(rtt->ms());
749 set_rtt_ms(rtt->ms());
750 }
751
752 // kTmmbrTimeoutIntervalMs is 25 seconds, so an order of seconds.
753 // Instead of this polling approach, consider having an optional timer in the
754 // RTCPReceiver class that is started/stopped based on the state of
755 // rtcp_sender_.TMMBR().
756 if (rtcp_sender_.TMMBR() && rtcp_receiver_.UpdateTmmbrTimers())
757 rtcp_receiver_.NotifyTmmbrUpdated();
758 }
759
760 } // namespace webrtc
761