• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "absl/strings/string_view.h"
23 #include "absl/types/optional.h"
24 #include "api/sequence_checker.h"
25 #include "api/transport/field_trial_based_config.h"
26 #include "api/units/time_delta.h"
27 #include "api/units/timestamp.h"
28 #include "modules/rtp_rtcp/source/rtcp_packet/dlrr.h"
29 #include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
30 #include "rtc_base/checks.h"
31 #include "rtc_base/logging.h"
32 #include "rtc_base/time_utils.h"
33 #include "system_wrappers/include/ntp_time.h"
34 
35 #ifdef _WIN32
36 // Disable warning C4355: 'this' : used in base member initializer list.
37 #pragma warning(disable : 4355)
38 #endif
39 
40 namespace webrtc {
41 namespace {
42 const int64_t kDefaultExpectedRetransmissionTimeMs = 125;
43 
44 constexpr TimeDelta kRttUpdateInterval = TimeDelta::Millis(1000);
45 
AddRtcpSendEvaluationCallback(RTCPSender::Configuration config,std::function<void (TimeDelta)> send_evaluation_callback)46 RTCPSender::Configuration AddRtcpSendEvaluationCallback(
47     RTCPSender::Configuration config,
48     std::function<void(TimeDelta)> send_evaluation_callback) {
49   config.schedule_next_rtcp_send_evaluation_function =
50       std::move(send_evaluation_callback);
51   return config;
52 }
53 
54 }  // namespace
55 
RtpSenderContext(const RtpRtcpInterface::Configuration & config)56 ModuleRtpRtcpImpl2::RtpSenderContext::RtpSenderContext(
57     const RtpRtcpInterface::Configuration& config)
58     : packet_history(config.clock, config.enable_rtx_padding_prioritization),
59       sequencer(config.local_media_ssrc,
60                 config.rtx_send_ssrc,
61                 /*require_marker_before_media_padding=*/!config.audio,
62                 config.clock),
63       packet_sender(config, &packet_history),
64       non_paced_sender(&packet_sender, &sequencer),
65       packet_generator(
66           config,
67           &packet_history,
68           config.paced_sender ? config.paced_sender : &non_paced_sender) {}
69 
ModuleRtpRtcpImpl2(const Configuration & configuration)70 ModuleRtpRtcpImpl2::ModuleRtpRtcpImpl2(const Configuration& configuration)
71     : worker_queue_(TaskQueueBase::Current()),
72       rtcp_sender_(AddRtcpSendEvaluationCallback(
73           RTCPSender::Configuration::FromRtpRtcpConfiguration(configuration),
74           [this](TimeDelta duration) {
75             ScheduleRtcpSendEvaluation(duration);
76           })),
77       rtcp_receiver_(configuration, this),
78       clock_(configuration.clock),
79       packet_overhead_(28),  // IPV4 UDP.
80       nack_last_time_sent_full_ms_(0),
81       nack_last_seq_number_sent_(0),
82       rtt_stats_(configuration.rtt_stats),
83       rtt_ms_(0) {
84   RTC_DCHECK(worker_queue_);
85   rtcp_thread_checker_.Detach();
86   if (!configuration.receiver_only) {
87     rtp_sender_ = std::make_unique<RtpSenderContext>(configuration);
88     rtp_sender_->sequencing_checker.Detach();
89     // Make sure rtcp sender use same timestamp offset as rtp sender.
90     rtcp_sender_.SetTimestampOffset(
91         rtp_sender_->packet_generator.TimestampOffset());
92     rtp_sender_->packet_sender.SetTimestampOffset(
93         rtp_sender_->packet_generator.TimestampOffset());
94   }
95 
96   // Set default packet size limit.
97   // TODO(nisse): Kind-of duplicates
98   // webrtc::VideoSendStream::Config::Rtp::kDefaultMaxPacketSize.
99   const size_t kTcpOverIpv4HeaderSize = 40;
100   SetMaxRtpPacketSize(IP_PACKET_SIZE - kTcpOverIpv4HeaderSize);
101   rtt_update_task_ = RepeatingTaskHandle::DelayedStart(
__anonaed80d960302() 102       worker_queue_, kRttUpdateInterval, [this]() {
103         PeriodicUpdate();
104         return kRttUpdateInterval;
105       });
106 }
107 
~ModuleRtpRtcpImpl2()108 ModuleRtpRtcpImpl2::~ModuleRtpRtcpImpl2() {
109   RTC_DCHECK_RUN_ON(worker_queue_);
110   rtt_update_task_.Stop();
111 }
112 
113 // static
Create(const Configuration & configuration)114 std::unique_ptr<ModuleRtpRtcpImpl2> ModuleRtpRtcpImpl2::Create(
115     const Configuration& configuration) {
116   RTC_DCHECK(configuration.clock);
117   RTC_DCHECK(TaskQueueBase::Current());
118   return std::make_unique<ModuleRtpRtcpImpl2>(configuration);
119 }
120 
SetRtxSendStatus(int mode)121 void ModuleRtpRtcpImpl2::SetRtxSendStatus(int mode) {
122   rtp_sender_->packet_generator.SetRtxStatus(mode);
123 }
124 
RtxSendStatus() const125 int ModuleRtpRtcpImpl2::RtxSendStatus() const {
126   return rtp_sender_ ? rtp_sender_->packet_generator.RtxStatus() : kRtxOff;
127 }
128 
SetRtxSendPayloadType(int payload_type,int associated_payload_type)129 void ModuleRtpRtcpImpl2::SetRtxSendPayloadType(int payload_type,
130                                                int associated_payload_type) {
131   rtp_sender_->packet_generator.SetRtxPayloadType(payload_type,
132                                                   associated_payload_type);
133 }
134 
RtxSsrc() const135 absl::optional<uint32_t> ModuleRtpRtcpImpl2::RtxSsrc() const {
136   return rtp_sender_ ? rtp_sender_->packet_generator.RtxSsrc() : absl::nullopt;
137 }
138 
FlexfecSsrc() const139 absl::optional<uint32_t> ModuleRtpRtcpImpl2::FlexfecSsrc() const {
140   if (rtp_sender_) {
141     return rtp_sender_->packet_generator.FlexfecSsrc();
142   }
143   return absl::nullopt;
144 }
145 
IncomingRtcpPacket(const uint8_t * rtcp_packet,const size_t length)146 void ModuleRtpRtcpImpl2::IncomingRtcpPacket(const uint8_t* rtcp_packet,
147                                             const size_t length) {
148   RTC_DCHECK_RUN_ON(&rtcp_thread_checker_);
149   rtcp_receiver_.IncomingPacket(rtcp_packet, length);
150 }
151 
RegisterSendPayloadFrequency(int payload_type,int payload_frequency)152 void ModuleRtpRtcpImpl2::RegisterSendPayloadFrequency(int payload_type,
153                                                       int payload_frequency) {
154   rtcp_sender_.SetRtpClockRate(payload_type, payload_frequency);
155 }
156 
DeRegisterSendPayload(const int8_t payload_type)157 int32_t ModuleRtpRtcpImpl2::DeRegisterSendPayload(const int8_t payload_type) {
158   return 0;
159 }
160 
StartTimestamp() const161 uint32_t ModuleRtpRtcpImpl2::StartTimestamp() const {
162   return rtp_sender_->packet_generator.TimestampOffset();
163 }
164 
165 // Configure start timestamp, default is a random number.
SetStartTimestamp(const uint32_t timestamp)166 void ModuleRtpRtcpImpl2::SetStartTimestamp(const uint32_t timestamp) {
167   rtcp_sender_.SetTimestampOffset(timestamp);
168   rtp_sender_->packet_generator.SetTimestampOffset(timestamp);
169   rtp_sender_->packet_sender.SetTimestampOffset(timestamp);
170 }
171 
SequenceNumber() const172 uint16_t ModuleRtpRtcpImpl2::SequenceNumber() const {
173   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
174   return rtp_sender_->sequencer.media_sequence_number();
175 }
176 
177 // Set SequenceNumber, default is a random number.
SetSequenceNumber(const uint16_t seq_num)178 void ModuleRtpRtcpImpl2::SetSequenceNumber(const uint16_t seq_num) {
179   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
180   if (rtp_sender_->sequencer.media_sequence_number() != seq_num) {
181     rtp_sender_->sequencer.set_media_sequence_number(seq_num);
182     rtp_sender_->packet_history.Clear();
183   }
184 }
185 
SetRtpState(const RtpState & rtp_state)186 void ModuleRtpRtcpImpl2::SetRtpState(const RtpState& rtp_state) {
187   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
188   rtp_sender_->packet_generator.SetRtpState(rtp_state);
189   rtp_sender_->sequencer.SetRtpState(rtp_state);
190   rtcp_sender_.SetTimestampOffset(rtp_state.start_timestamp);
191   rtp_sender_->packet_sender.SetTimestampOffset(rtp_state.start_timestamp);
192 }
193 
SetRtxState(const RtpState & rtp_state)194 void ModuleRtpRtcpImpl2::SetRtxState(const RtpState& rtp_state) {
195   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
196   rtp_sender_->packet_generator.SetRtxRtpState(rtp_state);
197   rtp_sender_->sequencer.set_rtx_sequence_number(rtp_state.sequence_number);
198 }
199 
GetRtpState() const200 RtpState ModuleRtpRtcpImpl2::GetRtpState() const {
201   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
202   RtpState state = rtp_sender_->packet_generator.GetRtpState();
203   rtp_sender_->sequencer.PopulateRtpState(state);
204   return state;
205 }
206 
GetRtxState() const207 RtpState ModuleRtpRtcpImpl2::GetRtxState() const {
208   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
209   RtpState state = rtp_sender_->packet_generator.GetRtxRtpState();
210   state.sequence_number = rtp_sender_->sequencer.rtx_sequence_number();
211   return state;
212 }
213 
SetNonSenderRttMeasurement(bool enabled)214 void ModuleRtpRtcpImpl2::SetNonSenderRttMeasurement(bool enabled) {
215   rtcp_sender_.SetNonSenderRttMeasurement(enabled);
216   rtcp_receiver_.SetNonSenderRttMeasurement(enabled);
217 }
218 
local_media_ssrc() const219 uint32_t ModuleRtpRtcpImpl2::local_media_ssrc() const {
220   RTC_DCHECK_RUN_ON(&rtcp_thread_checker_);
221   RTC_DCHECK_EQ(rtcp_receiver_.local_media_ssrc(), rtcp_sender_.SSRC());
222   return rtcp_receiver_.local_media_ssrc();
223 }
224 
SetMid(absl::string_view mid)225 void ModuleRtpRtcpImpl2::SetMid(absl::string_view mid) {
226   if (rtp_sender_) {
227     rtp_sender_->packet_generator.SetMid(mid);
228   }
229   // TODO(bugs.webrtc.org/4050): If we end up supporting the MID SDES item for
230   // RTCP, this will need to be passed down to the RTCPSender also.
231 }
232 
SetCsrcs(const std::vector<uint32_t> & csrcs)233 void ModuleRtpRtcpImpl2::SetCsrcs(const std::vector<uint32_t>& csrcs) {
234   rtcp_sender_.SetCsrcs(csrcs);
235   rtp_sender_->packet_generator.SetCsrcs(csrcs);
236 }
237 
238 // TODO(pbos): Handle media and RTX streams separately (separate RTCP
239 // feedbacks).
GetFeedbackState()240 RTCPSender::FeedbackState ModuleRtpRtcpImpl2::GetFeedbackState() {
241   // TODO(bugs.webrtc.org/11581): Called by potentially multiple threads.
242   // Mostly "Send*" methods. Make sure it's only called on the
243   // construction thread.
244 
245   RTCPSender::FeedbackState state;
246   // This is called also when receiver_only is true. Hence below
247   // checks that rtp_sender_ exists.
248   if (rtp_sender_) {
249     StreamDataCounters rtp_stats;
250     StreamDataCounters rtx_stats;
251     rtp_sender_->packet_sender.GetDataCounters(&rtp_stats, &rtx_stats);
252     state.packets_sent =
253         rtp_stats.transmitted.packets + rtx_stats.transmitted.packets;
254     state.media_bytes_sent = rtp_stats.transmitted.payload_bytes +
255                              rtx_stats.transmitted.payload_bytes;
256     state.send_bitrate =
257         rtp_sender_->packet_sender.GetSendRates().Sum().bps<uint32_t>();
258   }
259   state.receiver = &rtcp_receiver_;
260 
261   uint32_t received_ntp_secs = 0;
262   uint32_t received_ntp_frac = 0;
263   state.remote_sr = 0;
264   if (rtcp_receiver_.NTP(&received_ntp_secs, &received_ntp_frac,
265                          /*rtcp_arrival_time_secs=*/&state.last_rr_ntp_secs,
266                          /*rtcp_arrival_time_frac=*/&state.last_rr_ntp_frac,
267                          /*rtcp_timestamp=*/nullptr,
268                          /*remote_sender_packet_count=*/nullptr,
269                          /*remote_sender_octet_count=*/nullptr,
270                          /*remote_sender_reports_count=*/nullptr)) {
271     state.remote_sr = ((received_ntp_secs & 0x0000ffff) << 16) +
272                       ((received_ntp_frac & 0xffff0000) >> 16);
273   }
274 
275   state.last_xr_rtis = rtcp_receiver_.ConsumeReceivedXrReferenceTimeInfo();
276 
277   return state;
278 }
279 
SetSendingStatus(const bool sending)280 int32_t ModuleRtpRtcpImpl2::SetSendingStatus(const bool sending) {
281   if (rtcp_sender_.Sending() != sending) {
282     // Sends RTCP BYE when going from true to false
283     rtcp_sender_.SetSendingStatus(GetFeedbackState(), sending);
284   }
285   return 0;
286 }
287 
Sending() const288 bool ModuleRtpRtcpImpl2::Sending() const {
289   return rtcp_sender_.Sending();
290 }
291 
SetSendingMediaStatus(const bool sending)292 void ModuleRtpRtcpImpl2::SetSendingMediaStatus(const bool sending) {
293   rtp_sender_->packet_generator.SetSendingMediaStatus(sending);
294 }
295 
SendingMedia() const296 bool ModuleRtpRtcpImpl2::SendingMedia() const {
297   return rtp_sender_ ? rtp_sender_->packet_generator.SendingMedia() : false;
298 }
299 
IsAudioConfigured() const300 bool ModuleRtpRtcpImpl2::IsAudioConfigured() const {
301   return rtp_sender_ ? rtp_sender_->packet_generator.IsAudioConfigured()
302                      : false;
303 }
304 
SetAsPartOfAllocation(bool part_of_allocation)305 void ModuleRtpRtcpImpl2::SetAsPartOfAllocation(bool part_of_allocation) {
306   RTC_CHECK(rtp_sender_);
307   rtp_sender_->packet_sender.ForceIncludeSendPacketsInAllocation(
308       part_of_allocation);
309 }
310 
OnSendingRtpFrame(uint32_t timestamp,int64_t capture_time_ms,int payload_type,bool force_sender_report)311 bool ModuleRtpRtcpImpl2::OnSendingRtpFrame(uint32_t timestamp,
312                                            int64_t capture_time_ms,
313                                            int payload_type,
314                                            bool force_sender_report) {
315   if (!Sending())
316     return false;
317 
318   // TODO(bugs.webrtc.org/12873): Migrate this method and it's users to use
319   // optional Timestamps.
320   absl::optional<Timestamp> capture_time;
321   if (capture_time_ms > 0) {
322     capture_time = Timestamp::Millis(capture_time_ms);
323   }
324   absl::optional<int> payload_type_optional;
325   if (payload_type >= 0)
326     payload_type_optional = payload_type;
327   rtcp_sender_.SetLastRtpTime(timestamp, capture_time, payload_type_optional);
328   // Make sure an RTCP report isn't queued behind a key frame.
329   if (rtcp_sender_.TimeToSendRTCPReport(force_sender_report))
330     rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
331 
332   return true;
333 }
334 
TrySendPacket(RtpPacketToSend * packet,const PacedPacketInfo & pacing_info)335 bool ModuleRtpRtcpImpl2::TrySendPacket(RtpPacketToSend* packet,
336                                        const PacedPacketInfo& pacing_info) {
337   RTC_DCHECK(rtp_sender_);
338   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
339   if (!rtp_sender_->packet_generator.SendingMedia()) {
340     return false;
341   }
342   if (packet->packet_type() == RtpPacketMediaType::kPadding &&
343       packet->Ssrc() == rtp_sender_->packet_generator.SSRC() &&
344       !rtp_sender_->sequencer.CanSendPaddingOnMediaSsrc()) {
345     // New media packet preempted this generated padding packet, discard it.
346     return false;
347   }
348   bool is_flexfec =
349       packet->packet_type() == RtpPacketMediaType::kForwardErrorCorrection &&
350       packet->Ssrc() == rtp_sender_->packet_generator.FlexfecSsrc();
351   if (!is_flexfec) {
352     rtp_sender_->sequencer.Sequence(*packet);
353   }
354 
355   rtp_sender_->packet_sender.SendPacket(packet, pacing_info);
356   return true;
357 }
358 
SetFecProtectionParams(const FecProtectionParams & delta_params,const FecProtectionParams & key_params)359 void ModuleRtpRtcpImpl2::SetFecProtectionParams(
360     const FecProtectionParams& delta_params,
361     const FecProtectionParams& key_params) {
362   RTC_DCHECK(rtp_sender_);
363   rtp_sender_->packet_sender.SetFecProtectionParameters(delta_params,
364                                                         key_params);
365 }
366 
367 std::vector<std::unique_ptr<RtpPacketToSend>>
FetchFecPackets()368 ModuleRtpRtcpImpl2::FetchFecPackets() {
369   RTC_DCHECK(rtp_sender_);
370   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
371   return rtp_sender_->packet_sender.FetchFecPackets();
372 }
373 
OnAbortedRetransmissions(rtc::ArrayView<const uint16_t> sequence_numbers)374 void ModuleRtpRtcpImpl2::OnAbortedRetransmissions(
375     rtc::ArrayView<const uint16_t> sequence_numbers) {
376   RTC_DCHECK(rtp_sender_);
377   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
378   rtp_sender_->packet_sender.OnAbortedRetransmissions(sequence_numbers);
379 }
380 
OnPacketsAcknowledged(rtc::ArrayView<const uint16_t> sequence_numbers)381 void ModuleRtpRtcpImpl2::OnPacketsAcknowledged(
382     rtc::ArrayView<const uint16_t> sequence_numbers) {
383   RTC_DCHECK(rtp_sender_);
384   rtp_sender_->packet_history.CullAcknowledgedPackets(sequence_numbers);
385 }
386 
SupportsPadding() const387 bool ModuleRtpRtcpImpl2::SupportsPadding() const {
388   RTC_DCHECK(rtp_sender_);
389   return rtp_sender_->packet_generator.SupportsPadding();
390 }
391 
SupportsRtxPayloadPadding() const392 bool ModuleRtpRtcpImpl2::SupportsRtxPayloadPadding() const {
393   RTC_DCHECK(rtp_sender_);
394   return rtp_sender_->packet_generator.SupportsRtxPayloadPadding();
395 }
396 
397 std::vector<std::unique_ptr<RtpPacketToSend>>
GeneratePadding(size_t target_size_bytes)398 ModuleRtpRtcpImpl2::GeneratePadding(size_t target_size_bytes) {
399   RTC_DCHECK(rtp_sender_);
400   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
401 
402   return rtp_sender_->packet_generator.GeneratePadding(
403       target_size_bytes, rtp_sender_->packet_sender.MediaHasBeenSent(),
404       rtp_sender_->sequencer.CanSendPaddingOnMediaSsrc());
405 }
406 
407 std::vector<RtpSequenceNumberMap::Info>
GetSentRtpPacketInfos(rtc::ArrayView<const uint16_t> sequence_numbers) const408 ModuleRtpRtcpImpl2::GetSentRtpPacketInfos(
409     rtc::ArrayView<const uint16_t> sequence_numbers) const {
410   RTC_DCHECK(rtp_sender_);
411   return rtp_sender_->packet_sender.GetSentRtpPacketInfos(sequence_numbers);
412 }
413 
ExpectedPerPacketOverhead() const414 size_t ModuleRtpRtcpImpl2::ExpectedPerPacketOverhead() const {
415   if (!rtp_sender_) {
416     return 0;
417   }
418   return rtp_sender_->packet_generator.ExpectedPerPacketOverhead();
419 }
420 
OnPacketSendingThreadSwitched()421 void ModuleRtpRtcpImpl2::OnPacketSendingThreadSwitched() {
422   // Ownership of sequencing is being transferred to another thread.
423   rtp_sender_->sequencing_checker.Detach();
424 }
425 
MaxRtpPacketSize() const426 size_t ModuleRtpRtcpImpl2::MaxRtpPacketSize() const {
427   RTC_DCHECK(rtp_sender_);
428   return rtp_sender_->packet_generator.MaxRtpPacketSize();
429 }
430 
SetMaxRtpPacketSize(size_t rtp_packet_size)431 void ModuleRtpRtcpImpl2::SetMaxRtpPacketSize(size_t rtp_packet_size) {
432   RTC_DCHECK_LE(rtp_packet_size, IP_PACKET_SIZE)
433       << "rtp packet size too large: " << rtp_packet_size;
434   RTC_DCHECK_GT(rtp_packet_size, packet_overhead_)
435       << "rtp packet size too small: " << rtp_packet_size;
436 
437   rtcp_sender_.SetMaxRtpPacketSize(rtp_packet_size);
438   if (rtp_sender_) {
439     rtp_sender_->packet_generator.SetMaxRtpPacketSize(rtp_packet_size);
440   }
441 }
442 
RTCP() const443 RtcpMode ModuleRtpRtcpImpl2::RTCP() const {
444   return rtcp_sender_.Status();
445 }
446 
447 // Configure RTCP status i.e on/off.
SetRTCPStatus(const RtcpMode method)448 void ModuleRtpRtcpImpl2::SetRTCPStatus(const RtcpMode method) {
449   rtcp_sender_.SetRTCPStatus(method);
450 }
451 
SetCNAME(absl::string_view c_name)452 int32_t ModuleRtpRtcpImpl2::SetCNAME(absl::string_view c_name) {
453   return rtcp_sender_.SetCNAME(c_name);
454 }
455 
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) const456 int32_t ModuleRtpRtcpImpl2::RemoteNTP(uint32_t* received_ntpsecs,
457                                       uint32_t* received_ntpfrac,
458                                       uint32_t* rtcp_arrival_time_secs,
459                                       uint32_t* rtcp_arrival_time_frac,
460                                       uint32_t* rtcp_timestamp) const {
461   return rtcp_receiver_.NTP(received_ntpsecs, received_ntpfrac,
462                             rtcp_arrival_time_secs, rtcp_arrival_time_frac,
463                             rtcp_timestamp,
464                             /*remote_sender_packet_count=*/nullptr,
465                             /*remote_sender_octet_count=*/nullptr,
466                             /*remote_sender_reports_count=*/nullptr)
467              ? 0
468              : -1;
469 }
470 
471 // TODO(tommi): Check if `avg_rtt_ms`, `min_rtt_ms`, `max_rtt_ms` params are
472 // actually used in practice (some callers ask for it but don't use it). It
473 // could be that only `rtt` is needed and if so, then the fast path could be to
474 // 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) const475 int32_t ModuleRtpRtcpImpl2::RTT(const uint32_t remote_ssrc,
476                                 int64_t* rtt,
477                                 int64_t* avg_rtt,
478                                 int64_t* min_rtt,
479                                 int64_t* max_rtt) const {
480   int32_t ret = rtcp_receiver_.RTT(remote_ssrc, rtt, avg_rtt, min_rtt, max_rtt);
481   if (rtt && *rtt == 0) {
482     // Try to get RTT from RtcpRttStats class.
483     *rtt = rtt_ms();
484   }
485   return ret;
486 }
487 
ExpectedRetransmissionTimeMs() const488 int64_t ModuleRtpRtcpImpl2::ExpectedRetransmissionTimeMs() const {
489   int64_t expected_retransmission_time_ms = rtt_ms();
490   if (expected_retransmission_time_ms > 0) {
491     return expected_retransmission_time_ms;
492   }
493   // No rtt available (`kRttUpdateInterval` not yet passed?), so try to
494   // poll avg_rtt_ms directly from rtcp receiver.
495   if (rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), nullptr,
496                          &expected_retransmission_time_ms, nullptr,
497                          nullptr) == 0) {
498     return expected_retransmission_time_ms;
499   }
500   return kDefaultExpectedRetransmissionTimeMs;
501 }
502 
503 // Force a send of an RTCP packet.
504 // Normal SR and RR are triggered via the process function.
SendRTCP(RTCPPacketType packet_type)505 int32_t ModuleRtpRtcpImpl2::SendRTCP(RTCPPacketType packet_type) {
506   return rtcp_sender_.SendRTCP(GetFeedbackState(), packet_type);
507 }
508 
GetSendStreamDataCounters(StreamDataCounters * rtp_counters,StreamDataCounters * rtx_counters) const509 void ModuleRtpRtcpImpl2::GetSendStreamDataCounters(
510     StreamDataCounters* rtp_counters,
511     StreamDataCounters* rtx_counters) const {
512   rtp_sender_->packet_sender.GetDataCounters(rtp_counters, rtx_counters);
513 }
514 
515 // Received RTCP report.
GetLatestReportBlockData() const516 std::vector<ReportBlockData> ModuleRtpRtcpImpl2::GetLatestReportBlockData()
517     const {
518   return rtcp_receiver_.GetLatestReportBlockData();
519 }
520 
521 absl::optional<RtpRtcpInterface::SenderReportStats>
GetSenderReportStats() const522 ModuleRtpRtcpImpl2::GetSenderReportStats() const {
523   SenderReportStats stats;
524   uint32_t remote_timestamp_secs;
525   uint32_t remote_timestamp_frac;
526   uint32_t arrival_timestamp_secs;
527   uint32_t arrival_timestamp_frac;
528   if (rtcp_receiver_.NTP(&remote_timestamp_secs, &remote_timestamp_frac,
529                          &arrival_timestamp_secs, &arrival_timestamp_frac,
530                          /*rtcp_timestamp=*/nullptr, &stats.packets_sent,
531                          &stats.bytes_sent, &stats.reports_count)) {
532     stats.last_remote_timestamp.Set(remote_timestamp_secs,
533                                     remote_timestamp_frac);
534     stats.last_arrival_timestamp.Set(arrival_timestamp_secs,
535                                      arrival_timestamp_frac);
536     return stats;
537   }
538   return absl::nullopt;
539 }
540 
541 absl::optional<RtpRtcpInterface::NonSenderRttStats>
GetNonSenderRttStats() const542 ModuleRtpRtcpImpl2::GetNonSenderRttStats() const {
543   RTCPReceiver::NonSenderRttStats non_sender_rtt_stats =
544       rtcp_receiver_.GetNonSenderRTT();
545   return {{
546       non_sender_rtt_stats.round_trip_time(),
547       non_sender_rtt_stats.total_round_trip_time(),
548       non_sender_rtt_stats.round_trip_time_measurements(),
549   }};
550 }
551 
552 // (REMB) Receiver Estimated Max Bitrate.
SetRemb(int64_t bitrate_bps,std::vector<uint32_t> ssrcs)553 void ModuleRtpRtcpImpl2::SetRemb(int64_t bitrate_bps,
554                                  std::vector<uint32_t> ssrcs) {
555   rtcp_sender_.SetRemb(bitrate_bps, std::move(ssrcs));
556 }
557 
UnsetRemb()558 void ModuleRtpRtcpImpl2::UnsetRemb() {
559   rtcp_sender_.UnsetRemb();
560 }
561 
SetExtmapAllowMixed(bool extmap_allow_mixed)562 void ModuleRtpRtcpImpl2::SetExtmapAllowMixed(bool extmap_allow_mixed) {
563   rtp_sender_->packet_generator.SetExtmapAllowMixed(extmap_allow_mixed);
564 }
565 
RegisterRtpHeaderExtension(absl::string_view uri,int id)566 void ModuleRtpRtcpImpl2::RegisterRtpHeaderExtension(absl::string_view uri,
567                                                     int id) {
568   bool registered =
569       rtp_sender_->packet_generator.RegisterRtpHeaderExtension(uri, id);
570   RTC_CHECK(registered);
571 }
572 
DeregisterSendRtpHeaderExtension(absl::string_view uri)573 void ModuleRtpRtcpImpl2::DeregisterSendRtpHeaderExtension(
574     absl::string_view uri) {
575   rtp_sender_->packet_generator.DeregisterRtpHeaderExtension(uri);
576 }
577 
SetTmmbn(std::vector<rtcp::TmmbItem> bounding_set)578 void ModuleRtpRtcpImpl2::SetTmmbn(std::vector<rtcp::TmmbItem> bounding_set) {
579   rtcp_sender_.SetTmmbn(std::move(bounding_set));
580 }
581 
582 // Send a Negative acknowledgment packet.
SendNACK(const uint16_t * nack_list,const uint16_t size)583 int32_t ModuleRtpRtcpImpl2::SendNACK(const uint16_t* nack_list,
584                                      const uint16_t size) {
585   uint16_t nack_length = size;
586   uint16_t start_id = 0;
587   int64_t now_ms = clock_->TimeInMilliseconds();
588   if (TimeToSendFullNackList(now_ms)) {
589     nack_last_time_sent_full_ms_ = now_ms;
590   } else {
591     // Only send extended list.
592     if (nack_last_seq_number_sent_ == nack_list[size - 1]) {
593       // Last sequence number is the same, do not send list.
594       return 0;
595     }
596     // Send new sequence numbers.
597     for (int i = 0; i < size; ++i) {
598       if (nack_last_seq_number_sent_ == nack_list[i]) {
599         start_id = i + 1;
600         break;
601       }
602     }
603     nack_length = size - start_id;
604   }
605 
606   // Our RTCP NACK implementation is limited to kRtcpMaxNackFields sequence
607   // numbers per RTCP packet.
608   if (nack_length > kRtcpMaxNackFields) {
609     nack_length = kRtcpMaxNackFields;
610   }
611   nack_last_seq_number_sent_ = nack_list[start_id + nack_length - 1];
612 
613   return rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, nack_length,
614                                &nack_list[start_id]);
615 }
616 
SendNack(const std::vector<uint16_t> & sequence_numbers)617 void ModuleRtpRtcpImpl2::SendNack(
618     const std::vector<uint16_t>& sequence_numbers) {
619   rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, sequence_numbers.size(),
620                         sequence_numbers.data());
621 }
622 
TimeToSendFullNackList(int64_t now) const623 bool ModuleRtpRtcpImpl2::TimeToSendFullNackList(int64_t now) const {
624   // Use RTT from RtcpRttStats class if provided.
625   int64_t rtt = rtt_ms();
626   if (rtt == 0) {
627     rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
628   }
629 
630   const int64_t kStartUpRttMs = 100;
631   int64_t wait_time = 5 + ((rtt * 3) >> 1);  // 5 + RTT * 1.5.
632   if (rtt == 0) {
633     wait_time = kStartUpRttMs;
634   }
635 
636   // Send a full NACK list once within every `wait_time`.
637   return now - nack_last_time_sent_full_ms_ > wait_time;
638 }
639 
640 // Store the sent packets, needed to answer to Negative acknowledgment requests.
SetStorePacketsStatus(const bool enable,const uint16_t number_to_store)641 void ModuleRtpRtcpImpl2::SetStorePacketsStatus(const bool enable,
642                                                const uint16_t number_to_store) {
643   rtp_sender_->packet_history.SetStorePacketsStatus(
644       enable ? RtpPacketHistory::StorageMode::kStoreAndCull
645              : RtpPacketHistory::StorageMode::kDisabled,
646       number_to_store);
647 }
648 
StorePackets() const649 bool ModuleRtpRtcpImpl2::StorePackets() const {
650   return rtp_sender_->packet_history.GetStorageMode() !=
651          RtpPacketHistory::StorageMode::kDisabled;
652 }
653 
SendCombinedRtcpPacket(std::vector<std::unique_ptr<rtcp::RtcpPacket>> rtcp_packets)654 void ModuleRtpRtcpImpl2::SendCombinedRtcpPacket(
655     std::vector<std::unique_ptr<rtcp::RtcpPacket>> rtcp_packets) {
656   rtcp_sender_.SendCombinedRtcpPacket(std::move(rtcp_packets));
657 }
658 
SendLossNotification(uint16_t last_decoded_seq_num,uint16_t last_received_seq_num,bool decodability_flag,bool buffering_allowed)659 int32_t ModuleRtpRtcpImpl2::SendLossNotification(uint16_t last_decoded_seq_num,
660                                                  uint16_t last_received_seq_num,
661                                                  bool decodability_flag,
662                                                  bool buffering_allowed) {
663   return rtcp_sender_.SendLossNotification(
664       GetFeedbackState(), last_decoded_seq_num, last_received_seq_num,
665       decodability_flag, buffering_allowed);
666 }
667 
SetRemoteSSRC(const uint32_t ssrc)668 void ModuleRtpRtcpImpl2::SetRemoteSSRC(const uint32_t ssrc) {
669   // Inform about the incoming SSRC.
670   rtcp_sender_.SetRemoteSSRC(ssrc);
671   rtcp_receiver_.SetRemoteSSRC(ssrc);
672 }
673 
SetLocalSsrc(uint32_t local_ssrc)674 void ModuleRtpRtcpImpl2::SetLocalSsrc(uint32_t local_ssrc) {
675   RTC_DCHECK_RUN_ON(&rtcp_thread_checker_);
676   rtcp_receiver_.set_local_media_ssrc(local_ssrc);
677   rtcp_sender_.SetSsrc(local_ssrc);
678 }
679 
GetSendRates() const680 RtpSendRates ModuleRtpRtcpImpl2::GetSendRates() const {
681   // Typically called on the `rtp_transport_queue_` owned by an
682   // RtpTransportControllerSendInterface instance.
683   return rtp_sender_->packet_sender.GetSendRates();
684 }
685 
OnRequestSendReport()686 void ModuleRtpRtcpImpl2::OnRequestSendReport() {
687   SendRTCP(kRtcpSr);
688 }
689 
OnReceivedNack(const std::vector<uint16_t> & nack_sequence_numbers)690 void ModuleRtpRtcpImpl2::OnReceivedNack(
691     const std::vector<uint16_t>& nack_sequence_numbers) {
692   if (!rtp_sender_)
693     return;
694 
695   if (!StorePackets() || nack_sequence_numbers.empty()) {
696     return;
697   }
698   // Use RTT from RtcpRttStats class if provided.
699   int64_t rtt = rtt_ms();
700   if (rtt == 0) {
701     rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
702   }
703   rtp_sender_->packet_generator.OnReceivedNack(nack_sequence_numbers, rtt);
704 }
705 
OnReceivedRtcpReportBlocks(const ReportBlockList & report_blocks)706 void ModuleRtpRtcpImpl2::OnReceivedRtcpReportBlocks(
707     const ReportBlockList& report_blocks) {
708   if (rtp_sender_) {
709     uint32_t ssrc = SSRC();
710     absl::optional<uint32_t> rtx_ssrc;
711     if (rtp_sender_->packet_generator.RtxStatus() != kRtxOff) {
712       rtx_ssrc = rtp_sender_->packet_generator.RtxSsrc();
713     }
714 
715     for (const RTCPReportBlock& report_block : report_blocks) {
716       if (ssrc == report_block.source_ssrc) {
717         rtp_sender_->packet_generator.OnReceivedAckOnSsrc(
718             report_block.extended_highest_sequence_number);
719       } else if (rtx_ssrc && *rtx_ssrc == report_block.source_ssrc) {
720         rtp_sender_->packet_generator.OnReceivedAckOnRtxSsrc(
721             report_block.extended_highest_sequence_number);
722       }
723     }
724   }
725 }
726 
set_rtt_ms(int64_t rtt_ms)727 void ModuleRtpRtcpImpl2::set_rtt_ms(int64_t rtt_ms) {
728   RTC_DCHECK_RUN_ON(worker_queue_);
729   {
730     MutexLock lock(&mutex_rtt_);
731     rtt_ms_ = rtt_ms;
732   }
733   if (rtp_sender_) {
734     rtp_sender_->packet_history.SetRtt(TimeDelta::Millis(rtt_ms));
735   }
736 }
737 
rtt_ms() const738 int64_t ModuleRtpRtcpImpl2::rtt_ms() const {
739   MutexLock lock(&mutex_rtt_);
740   return rtt_ms_;
741 }
742 
SetVideoBitrateAllocation(const VideoBitrateAllocation & bitrate)743 void ModuleRtpRtcpImpl2::SetVideoBitrateAllocation(
744     const VideoBitrateAllocation& bitrate) {
745   rtcp_sender_.SetVideoBitrateAllocation(bitrate);
746 }
747 
RtpSender()748 RTPSender* ModuleRtpRtcpImpl2::RtpSender() {
749   return rtp_sender_ ? &rtp_sender_->packet_generator : nullptr;
750 }
751 
RtpSender() const752 const RTPSender* ModuleRtpRtcpImpl2::RtpSender() const {
753   return rtp_sender_ ? &rtp_sender_->packet_generator : nullptr;
754 }
755 
PeriodicUpdate()756 void ModuleRtpRtcpImpl2::PeriodicUpdate() {
757   RTC_DCHECK_RUN_ON(worker_queue_);
758 
759   Timestamp check_since = clock_->CurrentTime() - kRttUpdateInterval;
760   absl::optional<TimeDelta> rtt =
761       rtcp_receiver_.OnPeriodicRttUpdate(check_since, rtcp_sender_.Sending());
762   if (rtt) {
763     if (rtt_stats_) {
764       rtt_stats_->OnRttUpdate(rtt->ms());
765     }
766     set_rtt_ms(rtt->ms());
767   }
768 }
769 
MaybeSendRtcp()770 void ModuleRtpRtcpImpl2::MaybeSendRtcp() {
771   RTC_DCHECK_RUN_ON(worker_queue_);
772   if (rtcp_sender_.TimeToSendRTCPReport())
773     rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
774 }
775 
776 // TODO(bugs.webrtc.org/12889): Consider removing this function when the issue
777 // is resolved.
MaybeSendRtcpAtOrAfterTimestamp(Timestamp execution_time)778 void ModuleRtpRtcpImpl2::MaybeSendRtcpAtOrAfterTimestamp(
779     Timestamp execution_time) {
780   RTC_DCHECK_RUN_ON(worker_queue_);
781   Timestamp now = clock_->CurrentTime();
782   if (now >= execution_time) {
783     MaybeSendRtcp();
784     return;
785   }
786 
787   TimeDelta delta = execution_time - now;
788   // TaskQueue may run task 1ms earlier, so don't print warning if in this case.
789   if (delta > TimeDelta::Millis(1)) {
790     RTC_DLOG(LS_WARNING) << "BUGBUG: Task queue scheduled delayed call "
791                          << delta << " too early.";
792   }
793 
794   ScheduleMaybeSendRtcpAtOrAfterTimestamp(execution_time, delta);
795 }
796 
ScheduleRtcpSendEvaluation(TimeDelta duration)797 void ModuleRtpRtcpImpl2::ScheduleRtcpSendEvaluation(TimeDelta duration) {
798   // We end up here under various sequences including the worker queue, and
799   // the RTCPSender lock is held.
800   // We're assuming that the fact that RTCPSender executes under other sequences
801   // than the worker queue on which it's created on implies that external
802   // synchronization is present and removes this activity before destruction.
803   if (duration.IsZero()) {
804     worker_queue_->PostTask(SafeTask(task_safety_.flag(), [this] {
805       RTC_DCHECK_RUN_ON(worker_queue_);
806       MaybeSendRtcp();
807     }));
808   } else {
809     Timestamp execution_time = clock_->CurrentTime() + duration;
810     ScheduleMaybeSendRtcpAtOrAfterTimestamp(execution_time, duration);
811   }
812 }
813 
ScheduleMaybeSendRtcpAtOrAfterTimestamp(Timestamp execution_time,TimeDelta duration)814 void ModuleRtpRtcpImpl2::ScheduleMaybeSendRtcpAtOrAfterTimestamp(
815     Timestamp execution_time,
816     TimeDelta duration) {
817   // We end up here under various sequences including the worker queue, and
818   // the RTCPSender lock is held.
819   // See note in ScheduleRtcpSendEvaluation about why `worker_queue_` can be
820   // accessed.
821   worker_queue_->PostDelayedTask(
822       SafeTask(task_safety_.flag(),
823                [this, execution_time] {
824                  RTC_DCHECK_RUN_ON(worker_queue_);
825                  MaybeSendRtcpAtOrAfterTimestamp(execution_time);
826                }),
827       duration.RoundUpTo(TimeDelta::Millis(1)));
828 }
829 
830 }  // namespace webrtc
831