• 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/rtcp_receiver.h"
12 
13 #include <string.h>
14 
15 #include <algorithm>
16 #include <limits>
17 #include <map>
18 #include <memory>
19 #include <utility>
20 #include <vector>
21 
22 #include "api/video/video_bitrate_allocation.h"
23 #include "api/video/video_bitrate_allocator.h"
24 #include "modules/rtp_rtcp/source/rtcp_packet/bye.h"
25 #include "modules/rtp_rtcp/source/rtcp_packet/common_header.h"
26 #include "modules/rtp_rtcp/source/rtcp_packet/compound_packet.h"
27 #include "modules/rtp_rtcp/source/rtcp_packet/extended_reports.h"
28 #include "modules/rtp_rtcp/source/rtcp_packet/fir.h"
29 #include "modules/rtp_rtcp/source/rtcp_packet/loss_notification.h"
30 #include "modules/rtp_rtcp/source/rtcp_packet/nack.h"
31 #include "modules/rtp_rtcp/source/rtcp_packet/pli.h"
32 #include "modules/rtp_rtcp/source/rtcp_packet/rapid_resync_request.h"
33 #include "modules/rtp_rtcp/source/rtcp_packet/receiver_report.h"
34 #include "modules/rtp_rtcp/source/rtcp_packet/remb.h"
35 #include "modules/rtp_rtcp/source/rtcp_packet/remote_estimate.h"
36 #include "modules/rtp_rtcp/source/rtcp_packet/sdes.h"
37 #include "modules/rtp_rtcp/source/rtcp_packet/sender_report.h"
38 #include "modules/rtp_rtcp/source/rtcp_packet/tmmbn.h"
39 #include "modules/rtp_rtcp/source/rtcp_packet/tmmbr.h"
40 #include "modules/rtp_rtcp/source/rtcp_packet/transport_feedback.h"
41 #include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
42 #include "modules/rtp_rtcp/source/time_util.h"
43 #include "modules/rtp_rtcp/source/tmmbr_help.h"
44 #include "rtc_base/checks.h"
45 #include "rtc_base/logging.h"
46 #include "rtc_base/time_utils.h"
47 #include "rtc_base/trace_event.h"
48 #include "system_wrappers/include/ntp_time.h"
49 
50 namespace webrtc {
51 namespace {
52 
53 using rtcp::CommonHeader;
54 using rtcp::ReportBlock;
55 
56 // The number of RTCP time intervals needed to trigger a timeout.
57 const int kRrTimeoutIntervals = 3;
58 
59 const int64_t kTmmbrTimeoutIntervalMs = 5 * 5000;
60 
61 const int64_t kMaxWarningLogIntervalMs = 10000;
62 const int64_t kRtcpMinFrameLengthMs = 17;
63 
64 // Maximum number of received RRTRs that will be stored.
65 const size_t kMaxNumberOfStoredRrtrs = 300;
66 
67 constexpr TimeDelta kDefaultVideoReportInterval = TimeDelta::Seconds(1);
68 constexpr TimeDelta kDefaultAudioReportInterval = TimeDelta::Seconds(5);
69 
GetRegisteredSsrcs(const RtpRtcpInterface::Configuration & config)70 std::set<uint32_t> GetRegisteredSsrcs(
71     const RtpRtcpInterface::Configuration& config) {
72   std::set<uint32_t> ssrcs;
73   ssrcs.insert(config.local_media_ssrc);
74   if (config.rtx_send_ssrc) {
75     ssrcs.insert(*config.rtx_send_ssrc);
76   }
77   if (config.fec_generator) {
78     absl::optional<uint32_t> flexfec_ssrc = config.fec_generator->FecSsrc();
79     if (flexfec_ssrc) {
80       ssrcs.insert(*flexfec_ssrc);
81     }
82   }
83   return ssrcs;
84 }
85 
86 // Returns true if the |timestamp| has exceeded the |interval *
87 // kRrTimeoutIntervals| period and was reset (set to PlusInfinity()). Returns
88 // false if the timer was either already reset or if it has not expired.
ResetTimestampIfExpired(const Timestamp now,Timestamp & timestamp,TimeDelta interval)89 bool ResetTimestampIfExpired(const Timestamp now,
90                              Timestamp& timestamp,
91                              TimeDelta interval) {
92   if (timestamp.IsInfinite() ||
93       now <= timestamp + interval * kRrTimeoutIntervals) {
94     return false;
95   }
96 
97   timestamp = Timestamp::PlusInfinity();
98   return true;
99 }
100 
101 }  // namespace
102 
103 struct RTCPReceiver::PacketInformation {
104   uint32_t packet_type_flags = 0;  // RTCPPacketTypeFlags bit field.
105 
106   uint32_t remote_ssrc = 0;
107   std::vector<uint16_t> nack_sequence_numbers;
108   // TODO(hbos): Remove |report_blocks| in favor of |report_block_datas|.
109   ReportBlockList report_blocks;
110   std::vector<ReportBlockData> report_block_datas;
111   int64_t rtt_ms = 0;
112   uint32_t receiver_estimated_max_bitrate_bps = 0;
113   std::unique_ptr<rtcp::TransportFeedback> transport_feedback;
114   absl::optional<VideoBitrateAllocation> target_bitrate_allocation;
115   absl::optional<NetworkStateEstimate> network_state_estimate;
116   std::unique_ptr<rtcp::LossNotification> loss_notification;
117 };
118 
119 // Structure for handing TMMBR and TMMBN rtcp messages (RFC5104, section 3.5.4).
120 struct RTCPReceiver::TmmbrInformation {
121   struct TimedTmmbrItem {
122     rtcp::TmmbItem tmmbr_item;
123     int64_t last_updated_ms;
124   };
125 
126   int64_t last_time_received_ms = 0;
127 
128   bool ready_for_delete = false;
129 
130   std::vector<rtcp::TmmbItem> tmmbn;
131   std::map<uint32_t, TimedTmmbrItem> tmmbr;
132 };
133 
134 // Structure for storing received RRTR RTCP messages (RFC3611, section 4.4).
135 struct RTCPReceiver::RrtrInformation {
RrtrInformationwebrtc::RTCPReceiver::RrtrInformation136   RrtrInformation(uint32_t ssrc,
137                   uint32_t received_remote_mid_ntp_time,
138                   uint32_t local_receive_mid_ntp_time)
139       : ssrc(ssrc),
140         received_remote_mid_ntp_time(received_remote_mid_ntp_time),
141         local_receive_mid_ntp_time(local_receive_mid_ntp_time) {}
142 
143   uint32_t ssrc;
144   // Received NTP timestamp in compact representation.
145   uint32_t received_remote_mid_ntp_time;
146   // NTP time when the report was received in compact representation.
147   uint32_t local_receive_mid_ntp_time;
148 };
149 
150 struct RTCPReceiver::LastFirStatus {
LastFirStatuswebrtc::RTCPReceiver::LastFirStatus151   LastFirStatus(int64_t now_ms, uint8_t sequence_number)
152       : request_ms(now_ms), sequence_number(sequence_number) {}
153   int64_t request_ms;
154   uint8_t sequence_number;
155 };
156 
RTCPReceiver(const RtpRtcpInterface::Configuration & config,ModuleRtpRtcp * owner)157 RTCPReceiver::RTCPReceiver(const RtpRtcpInterface::Configuration& config,
158                            ModuleRtpRtcp* owner)
159     : clock_(config.clock),
160       receiver_only_(config.receiver_only),
161       rtp_rtcp_(owner),
162       main_ssrc_(config.local_media_ssrc),
163       registered_ssrcs_(GetRegisteredSsrcs(config)),
164       rtcp_bandwidth_observer_(config.bandwidth_callback),
165       rtcp_intra_frame_observer_(config.intra_frame_callback),
166       rtcp_loss_notification_observer_(config.rtcp_loss_notification_observer),
167       network_state_estimate_observer_(config.network_state_estimate_observer),
168       transport_feedback_observer_(config.transport_feedback_callback),
169       bitrate_allocation_observer_(config.bitrate_allocation_observer),
170       report_interval_(config.rtcp_report_interval_ms > 0
171                            ? TimeDelta::Millis(config.rtcp_report_interval_ms)
172                            : (config.audio ? kDefaultAudioReportInterval
173                                            : kDefaultVideoReportInterval)),
174       // TODO(bugs.webrtc.org/10774): Remove fallback.
175       remote_ssrc_(0),
176       remote_sender_rtp_time_(0),
177       xr_rrtr_status_(false),
178       xr_rr_rtt_ms_(0),
179       oldest_tmmbr_info_ms_(0),
180       stats_callback_(config.rtcp_statistics_callback),
181       cname_callback_(config.rtcp_cname_callback),
182       report_block_data_observer_(config.report_block_data_observer),
183       packet_type_counter_observer_(config.rtcp_packet_type_counter_observer),
184       num_skipped_packets_(0),
185       last_skipped_packets_warning_ms_(clock_->TimeInMilliseconds()) {
186   RTC_DCHECK(owner);
187 }
188 
~RTCPReceiver()189 RTCPReceiver::~RTCPReceiver() {}
190 
IncomingPacket(rtc::ArrayView<const uint8_t> packet)191 void RTCPReceiver::IncomingPacket(rtc::ArrayView<const uint8_t> packet) {
192   if (packet.empty()) {
193     RTC_LOG(LS_WARNING) << "Incoming empty RTCP packet";
194     return;
195   }
196 
197   PacketInformation packet_information;
198   if (!ParseCompoundPacket(packet, &packet_information))
199     return;
200   TriggerCallbacksFromRtcpPacket(packet_information);
201 }
202 
203 // This method is only used by test and legacy code, so we should be able to
204 // remove it soon.
LastReceivedReportBlockMs() const205 int64_t RTCPReceiver::LastReceivedReportBlockMs() const {
206   MutexLock lock(&rtcp_receiver_lock_);
207   return last_received_rb_.IsFinite() ? last_received_rb_.ms() : 0;
208 }
209 
SetRemoteSSRC(uint32_t ssrc)210 void RTCPReceiver::SetRemoteSSRC(uint32_t ssrc) {
211   MutexLock lock(&rtcp_receiver_lock_);
212   // New SSRC reset old reports.
213   last_received_sr_ntp_.Reset();
214   remote_ssrc_ = ssrc;
215 }
216 
RemoteSSRC() const217 uint32_t RTCPReceiver::RemoteSSRC() const {
218   MutexLock lock(&rtcp_receiver_lock_);
219   return remote_ssrc_;
220 }
221 
RTT(uint32_t remote_ssrc,int64_t * last_rtt_ms,int64_t * avg_rtt_ms,int64_t * min_rtt_ms,int64_t * max_rtt_ms) const222 int32_t RTCPReceiver::RTT(uint32_t remote_ssrc,
223                           int64_t* last_rtt_ms,
224                           int64_t* avg_rtt_ms,
225                           int64_t* min_rtt_ms,
226                           int64_t* max_rtt_ms) const {
227   MutexLock lock(&rtcp_receiver_lock_);
228 
229   auto it = received_report_blocks_.find(main_ssrc_);
230   if (it == received_report_blocks_.end())
231     return -1;
232 
233   auto it_info = it->second.find(remote_ssrc);
234   if (it_info == it->second.end())
235     return -1;
236 
237   const ReportBlockData* report_block_data = &it_info->second;
238 
239   if (report_block_data->num_rtts() == 0)
240     return -1;
241 
242   if (last_rtt_ms)
243     *last_rtt_ms = report_block_data->last_rtt_ms();
244 
245   if (avg_rtt_ms) {
246     *avg_rtt_ms =
247         report_block_data->sum_rtt_ms() / report_block_data->num_rtts();
248   }
249 
250   if (min_rtt_ms)
251     *min_rtt_ms = report_block_data->min_rtt_ms();
252 
253   if (max_rtt_ms)
254     *max_rtt_ms = report_block_data->max_rtt_ms();
255 
256   return 0;
257 }
258 
SetRtcpXrRrtrStatus(bool enable)259 void RTCPReceiver::SetRtcpXrRrtrStatus(bool enable) {
260   MutexLock lock(&rtcp_receiver_lock_);
261   xr_rrtr_status_ = enable;
262 }
263 
GetAndResetXrRrRtt(int64_t * rtt_ms)264 bool RTCPReceiver::GetAndResetXrRrRtt(int64_t* rtt_ms) {
265   RTC_DCHECK(rtt_ms);
266   MutexLock lock(&rtcp_receiver_lock_);
267   if (xr_rr_rtt_ms_ == 0) {
268     return false;
269   }
270   *rtt_ms = xr_rr_rtt_ms_;
271   xr_rr_rtt_ms_ = 0;
272   return true;
273 }
274 
275 // Called regularly (1/sec) on the worker thread to do rtt  calculations.
OnPeriodicRttUpdate(Timestamp newer_than,bool sending)276 absl::optional<TimeDelta> RTCPReceiver::OnPeriodicRttUpdate(
277     Timestamp newer_than,
278     bool sending) {
279   // Running on the worker thread (same as construction thread).
280   absl::optional<TimeDelta> rtt;
281 
282   if (sending) {
283     // Check if we've received a report block within the last kRttUpdateInterval
284     // amount of time.
285     MutexLock lock(&rtcp_receiver_lock_);
286     if (last_received_rb_.IsInfinite() || last_received_rb_ > newer_than) {
287       // Stow away the report block for the main ssrc. We'll use the associated
288       // data map to look up each sender and check the last_rtt_ms().
289       auto main_report_it = received_report_blocks_.find(main_ssrc_);
290       if (main_report_it != received_report_blocks_.end()) {
291         const ReportBlockDataMap& main_data_map = main_report_it->second;
292         int64_t max_rtt = 0;
293         for (const auto& reports_per_receiver : received_report_blocks_) {
294           for (const auto& report : reports_per_receiver.second) {
295             const RTCPReportBlock& block = report.second.report_block();
296             auto it_info = main_data_map.find(block.sender_ssrc);
297             if (it_info != main_data_map.end()) {
298               const ReportBlockData* report_block_data = &it_info->second;
299               if (report_block_data->num_rtts() > 0) {
300                 max_rtt = std::max(report_block_data->last_rtt_ms(), max_rtt);
301               }
302             }
303           }
304         }
305         if (max_rtt)
306           rtt.emplace(TimeDelta::Millis(max_rtt));
307       }
308     }
309 
310     // Check for expired timers and if so, log and reset.
311     auto now = clock_->CurrentTime();
312     if (RtcpRrTimeoutLocked(now)) {
313       RTC_LOG_F(LS_WARNING) << "Timeout: No RTCP RR received.";
314     } else if (RtcpRrSequenceNumberTimeoutLocked(now)) {
315       RTC_LOG_F(LS_WARNING) << "Timeout: No increase in RTCP RR extended "
316                                "highest sequence number.";
317     }
318   } else {
319     // Report rtt from receiver.
320     int64_t rtt_ms;
321     if (GetAndResetXrRrRtt(&rtt_ms)) {
322       rtt.emplace(TimeDelta::Millis(rtt_ms));
323     }
324   }
325 
326   return rtt;
327 }
328 
NTP(uint32_t * received_ntp_secs,uint32_t * received_ntp_frac,uint32_t * rtcp_arrival_time_secs,uint32_t * rtcp_arrival_time_frac,uint32_t * rtcp_timestamp) const329 bool RTCPReceiver::NTP(uint32_t* received_ntp_secs,
330                        uint32_t* received_ntp_frac,
331                        uint32_t* rtcp_arrival_time_secs,
332                        uint32_t* rtcp_arrival_time_frac,
333                        uint32_t* rtcp_timestamp) const {
334   MutexLock lock(&rtcp_receiver_lock_);
335   if (!last_received_sr_ntp_.Valid())
336     return false;
337 
338   // NTP from incoming SenderReport.
339   if (received_ntp_secs)
340     *received_ntp_secs = remote_sender_ntp_time_.seconds();
341   if (received_ntp_frac)
342     *received_ntp_frac = remote_sender_ntp_time_.fractions();
343 
344   // Rtp time from incoming SenderReport.
345   if (rtcp_timestamp)
346     *rtcp_timestamp = remote_sender_rtp_time_;
347 
348   // Local NTP time when we received a RTCP packet with a send block.
349   if (rtcp_arrival_time_secs)
350     *rtcp_arrival_time_secs = last_received_sr_ntp_.seconds();
351   if (rtcp_arrival_time_frac)
352     *rtcp_arrival_time_frac = last_received_sr_ntp_.fractions();
353 
354   return true;
355 }
356 
357 std::vector<rtcp::ReceiveTimeInfo>
ConsumeReceivedXrReferenceTimeInfo()358 RTCPReceiver::ConsumeReceivedXrReferenceTimeInfo() {
359   MutexLock lock(&rtcp_receiver_lock_);
360 
361   const size_t last_xr_rtis_size = std::min(
362       received_rrtrs_.size(), rtcp::ExtendedReports::kMaxNumberOfDlrrItems);
363   std::vector<rtcp::ReceiveTimeInfo> last_xr_rtis;
364   last_xr_rtis.reserve(last_xr_rtis_size);
365 
366   const uint32_t now_ntp =
367       CompactNtp(TimeMicrosToNtp(clock_->TimeInMicroseconds()));
368 
369   for (size_t i = 0; i < last_xr_rtis_size; ++i) {
370     RrtrInformation& rrtr = received_rrtrs_.front();
371     last_xr_rtis.emplace_back(rrtr.ssrc, rrtr.received_remote_mid_ntp_time,
372                               now_ntp - rrtr.local_receive_mid_ntp_time);
373     received_rrtrs_ssrc_it_.erase(rrtr.ssrc);
374     received_rrtrs_.pop_front();
375   }
376 
377   return last_xr_rtis;
378 }
379 
380 // We can get multiple receive reports when we receive the report from a CE.
StatisticsReceived(std::vector<RTCPReportBlock> * receive_blocks) const381 int32_t RTCPReceiver::StatisticsReceived(
382     std::vector<RTCPReportBlock>* receive_blocks) const {
383   RTC_DCHECK(receive_blocks);
384   MutexLock lock(&rtcp_receiver_lock_);
385   for (const auto& reports_per_receiver : received_report_blocks_)
386     for (const auto& report : reports_per_receiver.second)
387       receive_blocks->push_back(report.second.report_block());
388   return 0;
389 }
390 
GetLatestReportBlockData() const391 std::vector<ReportBlockData> RTCPReceiver::GetLatestReportBlockData() const {
392   std::vector<ReportBlockData> result;
393   MutexLock lock(&rtcp_receiver_lock_);
394   for (const auto& reports_per_receiver : received_report_blocks_)
395     for (const auto& report : reports_per_receiver.second)
396       result.push_back(report.second);
397   return result;
398 }
399 
ParseCompoundPacket(rtc::ArrayView<const uint8_t> packet,PacketInformation * packet_information)400 bool RTCPReceiver::ParseCompoundPacket(rtc::ArrayView<const uint8_t> packet,
401                                        PacketInformation* packet_information) {
402   MutexLock lock(&rtcp_receiver_lock_);
403 
404   CommonHeader rtcp_block;
405   for (const uint8_t* next_block = packet.begin(); next_block != packet.end();
406        next_block = rtcp_block.NextPacket()) {
407     ptrdiff_t remaining_blocks_size = packet.end() - next_block;
408     RTC_DCHECK_GT(remaining_blocks_size, 0);
409     if (!rtcp_block.Parse(next_block, remaining_blocks_size)) {
410       if (next_block == packet.begin()) {
411         // Failed to parse 1st header, nothing was extracted from this packet.
412         RTC_LOG(LS_WARNING) << "Incoming invalid RTCP packet";
413         return false;
414       }
415       ++num_skipped_packets_;
416       break;
417     }
418 
419     if (packet_type_counter_.first_packet_time_ms == -1)
420       packet_type_counter_.first_packet_time_ms = clock_->TimeInMilliseconds();
421 
422     switch (rtcp_block.type()) {
423       case rtcp::SenderReport::kPacketType:
424         HandleSenderReport(rtcp_block, packet_information);
425         break;
426       case rtcp::ReceiverReport::kPacketType:
427         HandleReceiverReport(rtcp_block, packet_information);
428         break;
429       case rtcp::Sdes::kPacketType:
430         HandleSdes(rtcp_block, packet_information);
431         break;
432       case rtcp::ExtendedReports::kPacketType:
433         HandleXr(rtcp_block, packet_information);
434         break;
435       case rtcp::Bye::kPacketType:
436         HandleBye(rtcp_block);
437         break;
438       case rtcp::App::kPacketType:
439         HandleApp(rtcp_block, packet_information);
440         break;
441       case rtcp::Rtpfb::kPacketType:
442         switch (rtcp_block.fmt()) {
443           case rtcp::Nack::kFeedbackMessageType:
444             HandleNack(rtcp_block, packet_information);
445             break;
446           case rtcp::Tmmbr::kFeedbackMessageType:
447             HandleTmmbr(rtcp_block, packet_information);
448             break;
449           case rtcp::Tmmbn::kFeedbackMessageType:
450             HandleTmmbn(rtcp_block, packet_information);
451             break;
452           case rtcp::RapidResyncRequest::kFeedbackMessageType:
453             HandleSrReq(rtcp_block, packet_information);
454             break;
455           case rtcp::TransportFeedback::kFeedbackMessageType:
456             HandleTransportFeedback(rtcp_block, packet_information);
457             break;
458           default:
459             ++num_skipped_packets_;
460             break;
461         }
462         break;
463       case rtcp::Psfb::kPacketType:
464         switch (rtcp_block.fmt()) {
465           case rtcp::Pli::kFeedbackMessageType:
466             HandlePli(rtcp_block, packet_information);
467             break;
468           case rtcp::Fir::kFeedbackMessageType:
469             HandleFir(rtcp_block, packet_information);
470             break;
471           case rtcp::Psfb::kAfbMessageType:
472             HandlePsfbApp(rtcp_block, packet_information);
473             break;
474           default:
475             ++num_skipped_packets_;
476             break;
477         }
478         break;
479       default:
480         ++num_skipped_packets_;
481         break;
482     }
483   }
484 
485   if (packet_type_counter_observer_) {
486     packet_type_counter_observer_->RtcpPacketTypesCounterUpdated(
487         main_ssrc_, packet_type_counter_);
488   }
489 
490   if (num_skipped_packets_ > 0) {
491     const int64_t now_ms = clock_->TimeInMilliseconds();
492     if (now_ms - last_skipped_packets_warning_ms_ >= kMaxWarningLogIntervalMs) {
493       last_skipped_packets_warning_ms_ = now_ms;
494       RTC_LOG(LS_WARNING)
495           << num_skipped_packets_
496           << " RTCP blocks were skipped due to being malformed or of "
497              "unrecognized/unsupported type, during the past "
498           << (kMaxWarningLogIntervalMs / 1000) << " second period.";
499     }
500   }
501 
502   return true;
503 }
504 
HandleSenderReport(const CommonHeader & rtcp_block,PacketInformation * packet_information)505 void RTCPReceiver::HandleSenderReport(const CommonHeader& rtcp_block,
506                                       PacketInformation* packet_information) {
507   rtcp::SenderReport sender_report;
508   if (!sender_report.Parse(rtcp_block)) {
509     ++num_skipped_packets_;
510     return;
511   }
512 
513   const uint32_t remote_ssrc = sender_report.sender_ssrc();
514 
515   packet_information->remote_ssrc = remote_ssrc;
516 
517   UpdateTmmbrRemoteIsAlive(remote_ssrc);
518 
519   // Have I received RTP packets from this party?
520   if (remote_ssrc_ == remote_ssrc) {
521     // Only signal that we have received a SR when we accept one.
522     packet_information->packet_type_flags |= kRtcpSr;
523 
524     remote_sender_ntp_time_ = sender_report.ntp();
525     remote_sender_rtp_time_ = sender_report.rtp_timestamp();
526     last_received_sr_ntp_ = TimeMicrosToNtp(clock_->TimeInMicroseconds());
527   } else {
528     // We will only store the send report from one source, but
529     // we will store all the receive blocks.
530     packet_information->packet_type_flags |= kRtcpRr;
531   }
532 
533   for (const rtcp::ReportBlock& report_block : sender_report.report_blocks())
534     HandleReportBlock(report_block, packet_information, remote_ssrc);
535 }
536 
HandleReceiverReport(const CommonHeader & rtcp_block,PacketInformation * packet_information)537 void RTCPReceiver::HandleReceiverReport(const CommonHeader& rtcp_block,
538                                         PacketInformation* packet_information) {
539   rtcp::ReceiverReport receiver_report;
540   if (!receiver_report.Parse(rtcp_block)) {
541     ++num_skipped_packets_;
542     return;
543   }
544 
545   const uint32_t remote_ssrc = receiver_report.sender_ssrc();
546 
547   packet_information->remote_ssrc = remote_ssrc;
548 
549   UpdateTmmbrRemoteIsAlive(remote_ssrc);
550 
551   packet_information->packet_type_flags |= kRtcpRr;
552 
553   for (const ReportBlock& report_block : receiver_report.report_blocks())
554     HandleReportBlock(report_block, packet_information, remote_ssrc);
555 }
556 
HandleReportBlock(const ReportBlock & report_block,PacketInformation * packet_information,uint32_t remote_ssrc)557 void RTCPReceiver::HandleReportBlock(const ReportBlock& report_block,
558                                      PacketInformation* packet_information,
559                                      uint32_t remote_ssrc) {
560   // This will be called once per report block in the RTCP packet.
561   // We filter out all report blocks that are not for us.
562   // Each packet has max 31 RR blocks.
563   //
564   // We can calc RTT if we send a send report and get a report block back.
565 
566   // |report_block.source_ssrc()| is the SSRC identifier of the source to
567   // which the information in this reception report block pertains.
568 
569   // Filter out all report blocks that are not for us.
570   if (registered_ssrcs_.count(report_block.source_ssrc()) == 0)
571     return;
572 
573   last_received_rb_ = clock_->CurrentTime();
574 
575   ReportBlockData* report_block_data =
576       &received_report_blocks_[report_block.source_ssrc()][remote_ssrc];
577   RTCPReportBlock rtcp_report_block;
578   rtcp_report_block.sender_ssrc = remote_ssrc;
579   rtcp_report_block.source_ssrc = report_block.source_ssrc();
580   rtcp_report_block.fraction_lost = report_block.fraction_lost();
581   rtcp_report_block.packets_lost = report_block.cumulative_lost_signed();
582   if (report_block.extended_high_seq_num() >
583       report_block_data->report_block().extended_highest_sequence_number) {
584     // We have successfully delivered new RTP packets to the remote side after
585     // the last RR was sent from the remote side.
586     last_increased_sequence_number_ = last_received_rb_;
587   }
588   rtcp_report_block.extended_highest_sequence_number =
589       report_block.extended_high_seq_num();
590   rtcp_report_block.jitter = report_block.jitter();
591   rtcp_report_block.delay_since_last_sender_report =
592       report_block.delay_since_last_sr();
593   rtcp_report_block.last_sender_report_timestamp = report_block.last_sr();
594   report_block_data->SetReportBlock(rtcp_report_block, rtc::TimeUTCMicros());
595 
596   int64_t rtt_ms = 0;
597   uint32_t send_time_ntp = report_block.last_sr();
598   // RFC3550, section 6.4.1, LSR field discription states:
599   // If no SR has been received yet, the field is set to zero.
600   // Receiver rtp_rtcp module is not expected to calculate rtt using
601   // Sender Reports even if it accidentally can.
602 
603   // TODO(nisse): Use this way to determine the RTT only when |receiver_only_|
604   // is false. However, that currently breaks the tests of the
605   // googCaptureStartNtpTimeMs stat for audio receive streams. To fix, either
606   // delete all dependencies on RTT measurements for audio receive streams, or
607   // ensure that audio receive streams that need RTT and stats that depend on it
608   // are configured with an associated audio send stream.
609   if (send_time_ntp != 0) {
610     uint32_t delay_ntp = report_block.delay_since_last_sr();
611     // Local NTP time.
612     uint32_t receive_time_ntp =
613         CompactNtp(TimeMicrosToNtp(last_received_rb_.us()));
614 
615     // RTT in 1/(2^16) seconds.
616     uint32_t rtt_ntp = receive_time_ntp - delay_ntp - send_time_ntp;
617     // Convert to 1/1000 seconds (milliseconds).
618     rtt_ms = CompactNtpRttToMs(rtt_ntp);
619     report_block_data->AddRoundTripTimeSample(rtt_ms);
620 
621     packet_information->rtt_ms = rtt_ms;
622   }
623 
624   packet_information->report_blocks.push_back(
625       report_block_data->report_block());
626   packet_information->report_block_datas.push_back(*report_block_data);
627 }
628 
FindOrCreateTmmbrInfo(uint32_t remote_ssrc)629 RTCPReceiver::TmmbrInformation* RTCPReceiver::FindOrCreateTmmbrInfo(
630     uint32_t remote_ssrc) {
631   // Create or find receive information.
632   TmmbrInformation* tmmbr_info = &tmmbr_infos_[remote_ssrc];
633   // Update that this remote is alive.
634   tmmbr_info->last_time_received_ms = clock_->TimeInMilliseconds();
635   return tmmbr_info;
636 }
637 
UpdateTmmbrRemoteIsAlive(uint32_t remote_ssrc)638 void RTCPReceiver::UpdateTmmbrRemoteIsAlive(uint32_t remote_ssrc) {
639   auto tmmbr_it = tmmbr_infos_.find(remote_ssrc);
640   if (tmmbr_it != tmmbr_infos_.end())
641     tmmbr_it->second.last_time_received_ms = clock_->TimeInMilliseconds();
642 }
643 
GetTmmbrInformation(uint32_t remote_ssrc)644 RTCPReceiver::TmmbrInformation* RTCPReceiver::GetTmmbrInformation(
645     uint32_t remote_ssrc) {
646   auto it = tmmbr_infos_.find(remote_ssrc);
647   if (it == tmmbr_infos_.end())
648     return nullptr;
649   return &it->second;
650 }
651 
652 // These two methods (RtcpRrTimeout and RtcpRrSequenceNumberTimeout) only exist
653 // for tests and legacy code (rtp_rtcp_impl.cc). We should be able to to delete
654 // the methods and require that access to the locked variables only happens on
655 // the worker thread and thus no locking is needed.
RtcpRrTimeout()656 bool RTCPReceiver::RtcpRrTimeout() {
657   MutexLock lock(&rtcp_receiver_lock_);
658   return RtcpRrTimeoutLocked(clock_->CurrentTime());
659 }
660 
RtcpRrSequenceNumberTimeout()661 bool RTCPReceiver::RtcpRrSequenceNumberTimeout() {
662   MutexLock lock(&rtcp_receiver_lock_);
663   return RtcpRrSequenceNumberTimeoutLocked(clock_->CurrentTime());
664 }
665 
UpdateTmmbrTimers()666 bool RTCPReceiver::UpdateTmmbrTimers() {
667   MutexLock lock(&rtcp_receiver_lock_);
668 
669   int64_t now_ms = clock_->TimeInMilliseconds();
670   int64_t timeout_ms = now_ms - kTmmbrTimeoutIntervalMs;
671 
672   if (oldest_tmmbr_info_ms_ >= timeout_ms)
673     return false;
674 
675   bool update_bounding_set = false;
676   oldest_tmmbr_info_ms_ = -1;
677   for (auto tmmbr_it = tmmbr_infos_.begin(); tmmbr_it != tmmbr_infos_.end();) {
678     TmmbrInformation* tmmbr_info = &tmmbr_it->second;
679     if (tmmbr_info->last_time_received_ms > 0) {
680       if (tmmbr_info->last_time_received_ms < timeout_ms) {
681         // No rtcp packet for the last 5 regular intervals, reset limitations.
682         tmmbr_info->tmmbr.clear();
683         // Prevent that we call this over and over again.
684         tmmbr_info->last_time_received_ms = 0;
685         // Send new TMMBN to all channels using the default codec.
686         update_bounding_set = true;
687       } else if (oldest_tmmbr_info_ms_ == -1 ||
688                  tmmbr_info->last_time_received_ms < oldest_tmmbr_info_ms_) {
689         oldest_tmmbr_info_ms_ = tmmbr_info->last_time_received_ms;
690       }
691       ++tmmbr_it;
692     } else if (tmmbr_info->ready_for_delete) {
693       // When we dont have a last_time_received_ms and the object is marked
694       // ready_for_delete it's removed from the map.
695       tmmbr_it = tmmbr_infos_.erase(tmmbr_it);
696     } else {
697       ++tmmbr_it;
698     }
699   }
700   return update_bounding_set;
701 }
702 
BoundingSet(bool * tmmbr_owner)703 std::vector<rtcp::TmmbItem> RTCPReceiver::BoundingSet(bool* tmmbr_owner) {
704   MutexLock lock(&rtcp_receiver_lock_);
705   TmmbrInformation* tmmbr_info = GetTmmbrInformation(remote_ssrc_);
706   if (!tmmbr_info)
707     return std::vector<rtcp::TmmbItem>();
708 
709   *tmmbr_owner = TMMBRHelp::IsOwner(tmmbr_info->tmmbn, main_ssrc_);
710   return tmmbr_info->tmmbn;
711 }
712 
HandleSdes(const CommonHeader & rtcp_block,PacketInformation * packet_information)713 void RTCPReceiver::HandleSdes(const CommonHeader& rtcp_block,
714                               PacketInformation* packet_information) {
715   rtcp::Sdes sdes;
716   if (!sdes.Parse(rtcp_block)) {
717     ++num_skipped_packets_;
718     return;
719   }
720 
721   for (const rtcp::Sdes::Chunk& chunk : sdes.chunks()) {
722     received_cnames_[chunk.ssrc] = chunk.cname;
723     if (cname_callback_)
724       cname_callback_->OnCname(chunk.ssrc, chunk.cname);
725   }
726   packet_information->packet_type_flags |= kRtcpSdes;
727 }
728 
HandleNack(const CommonHeader & rtcp_block,PacketInformation * packet_information)729 void RTCPReceiver::HandleNack(const CommonHeader& rtcp_block,
730                               PacketInformation* packet_information) {
731   rtcp::Nack nack;
732   if (!nack.Parse(rtcp_block)) {
733     ++num_skipped_packets_;
734     return;
735   }
736 
737   if (receiver_only_ || main_ssrc_ != nack.media_ssrc())  // Not to us.
738     return;
739 
740   packet_information->nack_sequence_numbers.insert(
741       packet_information->nack_sequence_numbers.end(),
742       nack.packet_ids().begin(), nack.packet_ids().end());
743   for (uint16_t packet_id : nack.packet_ids())
744     nack_stats_.ReportRequest(packet_id);
745 
746   if (!nack.packet_ids().empty()) {
747     packet_information->packet_type_flags |= kRtcpNack;
748     ++packet_type_counter_.nack_packets;
749     packet_type_counter_.nack_requests = nack_stats_.requests();
750     packet_type_counter_.unique_nack_requests = nack_stats_.unique_requests();
751   }
752 }
753 
HandleApp(const rtcp::CommonHeader & rtcp_block,PacketInformation * packet_information)754 void RTCPReceiver::HandleApp(const rtcp::CommonHeader& rtcp_block,
755                              PacketInformation* packet_information) {
756   rtcp::App app;
757   if (app.Parse(rtcp_block)) {
758     if (app.name() == rtcp::RemoteEstimate::kName &&
759         app.sub_type() == rtcp::RemoteEstimate::kSubType) {
760       rtcp::RemoteEstimate estimate(std::move(app));
761       if (estimate.ParseData()) {
762         packet_information->network_state_estimate = estimate.estimate();
763         return;
764       }
765     }
766   }
767   ++num_skipped_packets_;
768 }
769 
HandleBye(const CommonHeader & rtcp_block)770 void RTCPReceiver::HandleBye(const CommonHeader& rtcp_block) {
771   rtcp::Bye bye;
772   if (!bye.Parse(rtcp_block)) {
773     ++num_skipped_packets_;
774     return;
775   }
776 
777   // Clear our lists.
778   for (auto& reports_per_receiver : received_report_blocks_)
779     reports_per_receiver.second.erase(bye.sender_ssrc());
780 
781   TmmbrInformation* tmmbr_info = GetTmmbrInformation(bye.sender_ssrc());
782   if (tmmbr_info)
783     tmmbr_info->ready_for_delete = true;
784 
785   last_fir_.erase(bye.sender_ssrc());
786   received_cnames_.erase(bye.sender_ssrc());
787   auto it = received_rrtrs_ssrc_it_.find(bye.sender_ssrc());
788   if (it != received_rrtrs_ssrc_it_.end()) {
789     received_rrtrs_.erase(it->second);
790     received_rrtrs_ssrc_it_.erase(it);
791   }
792   xr_rr_rtt_ms_ = 0;
793 }
794 
HandleXr(const CommonHeader & rtcp_block,PacketInformation * packet_information)795 void RTCPReceiver::HandleXr(const CommonHeader& rtcp_block,
796                             PacketInformation* packet_information) {
797   rtcp::ExtendedReports xr;
798   if (!xr.Parse(rtcp_block)) {
799     ++num_skipped_packets_;
800     return;
801   }
802 
803   if (xr.rrtr())
804     HandleXrReceiveReferenceTime(xr.sender_ssrc(), *xr.rrtr());
805 
806   for (const rtcp::ReceiveTimeInfo& time_info : xr.dlrr().sub_blocks())
807     HandleXrDlrrReportBlock(time_info);
808 
809   if (xr.target_bitrate()) {
810     HandleXrTargetBitrate(xr.sender_ssrc(), *xr.target_bitrate(),
811                           packet_information);
812   }
813 }
814 
HandleXrReceiveReferenceTime(uint32_t sender_ssrc,const rtcp::Rrtr & rrtr)815 void RTCPReceiver::HandleXrReceiveReferenceTime(uint32_t sender_ssrc,
816                                                 const rtcp::Rrtr& rrtr) {
817   uint32_t received_remote_mid_ntp_time = CompactNtp(rrtr.ntp());
818   uint32_t local_receive_mid_ntp_time =
819       CompactNtp(TimeMicrosToNtp(clock_->TimeInMicroseconds()));
820 
821   auto it = received_rrtrs_ssrc_it_.find(sender_ssrc);
822   if (it != received_rrtrs_ssrc_it_.end()) {
823     it->second->received_remote_mid_ntp_time = received_remote_mid_ntp_time;
824     it->second->local_receive_mid_ntp_time = local_receive_mid_ntp_time;
825   } else {
826     if (received_rrtrs_.size() < kMaxNumberOfStoredRrtrs) {
827       received_rrtrs_.emplace_back(sender_ssrc, received_remote_mid_ntp_time,
828                                    local_receive_mid_ntp_time);
829       received_rrtrs_ssrc_it_[sender_ssrc] = std::prev(received_rrtrs_.end());
830     } else {
831       RTC_LOG(LS_WARNING) << "Discarding received RRTR for ssrc " << sender_ssrc
832                           << ", reached maximum number of stored RRTRs.";
833     }
834   }
835 }
836 
HandleXrDlrrReportBlock(const rtcp::ReceiveTimeInfo & rti)837 void RTCPReceiver::HandleXrDlrrReportBlock(const rtcp::ReceiveTimeInfo& rti) {
838   if (registered_ssrcs_.count(rti.ssrc) == 0)  // Not to us.
839     return;
840 
841   // Caller should explicitly enable rtt calculation using extended reports.
842   if (!xr_rrtr_status_)
843     return;
844 
845   // The send_time and delay_rr fields are in units of 1/2^16 sec.
846   uint32_t send_time_ntp = rti.last_rr;
847   // RFC3611, section 4.5, LRR field discription states:
848   // If no such block has been received, the field is set to zero.
849   if (send_time_ntp == 0)
850     return;
851 
852   uint32_t delay_ntp = rti.delay_since_last_rr;
853   uint32_t now_ntp = CompactNtp(TimeMicrosToNtp(clock_->TimeInMicroseconds()));
854 
855   uint32_t rtt_ntp = now_ntp - delay_ntp - send_time_ntp;
856   xr_rr_rtt_ms_ = CompactNtpRttToMs(rtt_ntp);
857 }
858 
HandleXrTargetBitrate(uint32_t ssrc,const rtcp::TargetBitrate & target_bitrate,PacketInformation * packet_information)859 void RTCPReceiver::HandleXrTargetBitrate(
860     uint32_t ssrc,
861     const rtcp::TargetBitrate& target_bitrate,
862     PacketInformation* packet_information) {
863   if (ssrc != remote_ssrc_) {
864     return;  // Not for us.
865   }
866 
867   VideoBitrateAllocation bitrate_allocation;
868   for (const auto& item : target_bitrate.GetTargetBitrates()) {
869     if (item.spatial_layer >= kMaxSpatialLayers ||
870         item.temporal_layer >= kMaxTemporalStreams) {
871       RTC_LOG(LS_WARNING)
872           << "Invalid layer in XR target bitrate pack: spatial index "
873           << item.spatial_layer << ", temporal index " << item.temporal_layer
874           << ", dropping.";
875     } else {
876       bitrate_allocation.SetBitrate(item.spatial_layer, item.temporal_layer,
877                                     item.target_bitrate_kbps * 1000);
878     }
879   }
880   packet_information->target_bitrate_allocation.emplace(bitrate_allocation);
881 }
882 
HandlePli(const CommonHeader & rtcp_block,PacketInformation * packet_information)883 void RTCPReceiver::HandlePli(const CommonHeader& rtcp_block,
884                              PacketInformation* packet_information) {
885   rtcp::Pli pli;
886   if (!pli.Parse(rtcp_block)) {
887     ++num_skipped_packets_;
888     return;
889   }
890 
891   if (main_ssrc_ == pli.media_ssrc()) {
892     ++packet_type_counter_.pli_packets;
893     // Received a signal that we need to send a new key frame.
894     packet_information->packet_type_flags |= kRtcpPli;
895   }
896 }
897 
HandleTmmbr(const CommonHeader & rtcp_block,PacketInformation * packet_information)898 void RTCPReceiver::HandleTmmbr(const CommonHeader& rtcp_block,
899                                PacketInformation* packet_information) {
900   rtcp::Tmmbr tmmbr;
901   if (!tmmbr.Parse(rtcp_block)) {
902     ++num_skipped_packets_;
903     return;
904   }
905 
906   uint32_t sender_ssrc = tmmbr.sender_ssrc();
907   if (tmmbr.media_ssrc()) {
908     // media_ssrc() SHOULD be 0 if same as SenderSSRC.
909     // In relay mode this is a valid number.
910     sender_ssrc = tmmbr.media_ssrc();
911   }
912 
913   for (const rtcp::TmmbItem& request : tmmbr.requests()) {
914     if (main_ssrc_ != request.ssrc() || request.bitrate_bps() == 0)
915       continue;
916 
917     TmmbrInformation* tmmbr_info = FindOrCreateTmmbrInfo(tmmbr.sender_ssrc());
918     auto* entry = &tmmbr_info->tmmbr[sender_ssrc];
919     entry->tmmbr_item = rtcp::TmmbItem(sender_ssrc, request.bitrate_bps(),
920                                        request.packet_overhead());
921     // FindOrCreateTmmbrInfo always sets |last_time_received_ms| to
922     // |clock_->TimeInMilliseconds()|.
923     entry->last_updated_ms = tmmbr_info->last_time_received_ms;
924 
925     packet_information->packet_type_flags |= kRtcpTmmbr;
926     break;
927   }
928 }
929 
HandleTmmbn(const CommonHeader & rtcp_block,PacketInformation * packet_information)930 void RTCPReceiver::HandleTmmbn(const CommonHeader& rtcp_block,
931                                PacketInformation* packet_information) {
932   rtcp::Tmmbn tmmbn;
933   if (!tmmbn.Parse(rtcp_block)) {
934     ++num_skipped_packets_;
935     return;
936   }
937 
938   TmmbrInformation* tmmbr_info = FindOrCreateTmmbrInfo(tmmbn.sender_ssrc());
939 
940   packet_information->packet_type_flags |= kRtcpTmmbn;
941 
942   tmmbr_info->tmmbn = tmmbn.items();
943 }
944 
HandleSrReq(const CommonHeader & rtcp_block,PacketInformation * packet_information)945 void RTCPReceiver::HandleSrReq(const CommonHeader& rtcp_block,
946                                PacketInformation* packet_information) {
947   rtcp::RapidResyncRequest sr_req;
948   if (!sr_req.Parse(rtcp_block)) {
949     ++num_skipped_packets_;
950     return;
951   }
952 
953   packet_information->packet_type_flags |= kRtcpSrReq;
954 }
955 
HandlePsfbApp(const CommonHeader & rtcp_block,PacketInformation * packet_information)956 void RTCPReceiver::HandlePsfbApp(const CommonHeader& rtcp_block,
957                                  PacketInformation* packet_information) {
958   {
959     rtcp::Remb remb;
960     if (remb.Parse(rtcp_block)) {
961       packet_information->packet_type_flags |= kRtcpRemb;
962       packet_information->receiver_estimated_max_bitrate_bps =
963           remb.bitrate_bps();
964       return;
965     }
966   }
967 
968   {
969     auto loss_notification = std::make_unique<rtcp::LossNotification>();
970     if (loss_notification->Parse(rtcp_block)) {
971       packet_information->packet_type_flags |= kRtcpLossNotification;
972       packet_information->loss_notification = std::move(loss_notification);
973       return;
974     }
975   }
976 
977   RTC_LOG(LS_WARNING) << "Unknown PSFB-APP packet.";
978 
979   ++num_skipped_packets_;
980 }
981 
HandleFir(const CommonHeader & rtcp_block,PacketInformation * packet_information)982 void RTCPReceiver::HandleFir(const CommonHeader& rtcp_block,
983                              PacketInformation* packet_information) {
984   rtcp::Fir fir;
985   if (!fir.Parse(rtcp_block)) {
986     ++num_skipped_packets_;
987     return;
988   }
989 
990   if (fir.requests().empty())
991     return;
992 
993   const int64_t now_ms = clock_->TimeInMilliseconds();
994   for (const rtcp::Fir::Request& fir_request : fir.requests()) {
995     // Is it our sender that is requested to generate a new keyframe.
996     if (main_ssrc_ != fir_request.ssrc)
997       continue;
998 
999     ++packet_type_counter_.fir_packets;
1000 
1001     auto inserted = last_fir_.insert(std::make_pair(
1002         fir.sender_ssrc(), LastFirStatus(now_ms, fir_request.seq_nr)));
1003     if (!inserted.second) {  // There was already an entry.
1004       LastFirStatus* last_fir = &inserted.first->second;
1005 
1006       // Check if we have reported this FIRSequenceNumber before.
1007       if (fir_request.seq_nr == last_fir->sequence_number)
1008         continue;
1009 
1010       // Sanity: don't go crazy with the callbacks.
1011       if (now_ms - last_fir->request_ms < kRtcpMinFrameLengthMs)
1012         continue;
1013 
1014       last_fir->request_ms = now_ms;
1015       last_fir->sequence_number = fir_request.seq_nr;
1016     }
1017     // Received signal that we need to send a new key frame.
1018     packet_information->packet_type_flags |= kRtcpFir;
1019   }
1020 }
1021 
HandleTransportFeedback(const CommonHeader & rtcp_block,PacketInformation * packet_information)1022 void RTCPReceiver::HandleTransportFeedback(
1023     const CommonHeader& rtcp_block,
1024     PacketInformation* packet_information) {
1025   std::unique_ptr<rtcp::TransportFeedback> transport_feedback(
1026       new rtcp::TransportFeedback());
1027   if (!transport_feedback->Parse(rtcp_block)) {
1028     ++num_skipped_packets_;
1029     return;
1030   }
1031 
1032   packet_information->packet_type_flags |= kRtcpTransportFeedback;
1033   packet_information->transport_feedback = std::move(transport_feedback);
1034 }
1035 
NotifyTmmbrUpdated()1036 void RTCPReceiver::NotifyTmmbrUpdated() {
1037   // Find bounding set.
1038   std::vector<rtcp::TmmbItem> bounding =
1039       TMMBRHelp::FindBoundingSet(TmmbrReceived());
1040 
1041   if (!bounding.empty() && rtcp_bandwidth_observer_) {
1042     // We have a new bandwidth estimate on this channel.
1043     uint64_t bitrate_bps = TMMBRHelp::CalcMinBitrateBps(bounding);
1044     if (bitrate_bps <= std::numeric_limits<uint32_t>::max())
1045       rtcp_bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate_bps);
1046   }
1047 
1048   // Send tmmbn to inform remote clients about the new bandwidth.
1049   rtp_rtcp_->SetTmmbn(std::move(bounding));
1050 }
1051 
1052 // Holding no Critical section.
TriggerCallbacksFromRtcpPacket(const PacketInformation & packet_information)1053 void RTCPReceiver::TriggerCallbacksFromRtcpPacket(
1054     const PacketInformation& packet_information) {
1055   // Process TMMBR and REMB first to avoid multiple callbacks
1056   // to OnNetworkChanged.
1057   if (packet_information.packet_type_flags & kRtcpTmmbr) {
1058     // Might trigger a OnReceivedBandwidthEstimateUpdate.
1059     NotifyTmmbrUpdated();
1060   }
1061   uint32_t local_ssrc;
1062   std::set<uint32_t> registered_ssrcs;
1063   {
1064     // We don't want to hold this critsect when triggering the callbacks below.
1065     MutexLock lock(&rtcp_receiver_lock_);
1066     local_ssrc = main_ssrc_;
1067     registered_ssrcs = registered_ssrcs_;
1068   }
1069   if (!receiver_only_ && (packet_information.packet_type_flags & kRtcpSrReq)) {
1070     rtp_rtcp_->OnRequestSendReport();
1071   }
1072   if (!receiver_only_ && (packet_information.packet_type_flags & kRtcpNack)) {
1073     if (!packet_information.nack_sequence_numbers.empty()) {
1074       RTC_LOG(LS_VERBOSE) << "Incoming NACK length: "
1075                           << packet_information.nack_sequence_numbers.size();
1076       rtp_rtcp_->OnReceivedNack(packet_information.nack_sequence_numbers);
1077     }
1078   }
1079 
1080   // We need feedback that we have received a report block(s) so that we
1081   // can generate a new packet in a conference relay scenario, one received
1082   // report can generate several RTCP packets, based on number relayed/mixed
1083   // a send report block should go out to all receivers.
1084   if (rtcp_intra_frame_observer_) {
1085     RTC_DCHECK(!receiver_only_);
1086     if ((packet_information.packet_type_flags & kRtcpPli) ||
1087         (packet_information.packet_type_flags & kRtcpFir)) {
1088       if (packet_information.packet_type_flags & kRtcpPli) {
1089         RTC_LOG(LS_VERBOSE)
1090             << "Incoming PLI from SSRC " << packet_information.remote_ssrc;
1091       } else {
1092         RTC_LOG(LS_VERBOSE)
1093             << "Incoming FIR from SSRC " << packet_information.remote_ssrc;
1094       }
1095       rtcp_intra_frame_observer_->OnReceivedIntraFrameRequest(local_ssrc);
1096     }
1097   }
1098   if (rtcp_loss_notification_observer_ &&
1099       (packet_information.packet_type_flags & kRtcpLossNotification)) {
1100     rtcp::LossNotification* loss_notification =
1101         packet_information.loss_notification.get();
1102     RTC_DCHECK(loss_notification);
1103     if (loss_notification->media_ssrc() == local_ssrc) {
1104       rtcp_loss_notification_observer_->OnReceivedLossNotification(
1105           loss_notification->media_ssrc(), loss_notification->last_decoded(),
1106           loss_notification->last_received(),
1107           loss_notification->decodability_flag());
1108     }
1109   }
1110   if (rtcp_bandwidth_observer_) {
1111     RTC_DCHECK(!receiver_only_);
1112     if (packet_information.packet_type_flags & kRtcpRemb) {
1113       RTC_LOG(LS_VERBOSE)
1114           << "Incoming REMB: "
1115           << packet_information.receiver_estimated_max_bitrate_bps;
1116       rtcp_bandwidth_observer_->OnReceivedEstimatedBitrate(
1117           packet_information.receiver_estimated_max_bitrate_bps);
1118     }
1119     if ((packet_information.packet_type_flags & kRtcpSr) ||
1120         (packet_information.packet_type_flags & kRtcpRr)) {
1121       int64_t now_ms = clock_->TimeInMilliseconds();
1122       rtcp_bandwidth_observer_->OnReceivedRtcpReceiverReport(
1123           packet_information.report_blocks, packet_information.rtt_ms, now_ms);
1124     }
1125   }
1126   if ((packet_information.packet_type_flags & kRtcpSr) ||
1127       (packet_information.packet_type_flags & kRtcpRr)) {
1128     rtp_rtcp_->OnReceivedRtcpReportBlocks(packet_information.report_blocks);
1129   }
1130 
1131   if (transport_feedback_observer_ &&
1132       (packet_information.packet_type_flags & kRtcpTransportFeedback)) {
1133     uint32_t media_source_ssrc =
1134         packet_information.transport_feedback->media_ssrc();
1135     if (media_source_ssrc == local_ssrc ||
1136         registered_ssrcs.find(media_source_ssrc) != registered_ssrcs.end()) {
1137       transport_feedback_observer_->OnTransportFeedback(
1138           *packet_information.transport_feedback);
1139     }
1140   }
1141 
1142   if (network_state_estimate_observer_ &&
1143       packet_information.network_state_estimate) {
1144     network_state_estimate_observer_->OnRemoteNetworkEstimate(
1145         *packet_information.network_state_estimate);
1146   }
1147 
1148   if (bitrate_allocation_observer_ &&
1149       packet_information.target_bitrate_allocation) {
1150     bitrate_allocation_observer_->OnBitrateAllocationUpdated(
1151         *packet_information.target_bitrate_allocation);
1152   }
1153 
1154   if (!receiver_only_) {
1155     if (stats_callback_) {
1156       for (const auto& report_block : packet_information.report_blocks) {
1157         RtcpStatistics stats;
1158         stats.packets_lost = report_block.packets_lost;
1159         stats.extended_highest_sequence_number =
1160             report_block.extended_highest_sequence_number;
1161         stats.fraction_lost = report_block.fraction_lost;
1162         stats.jitter = report_block.jitter;
1163 
1164         stats_callback_->StatisticsUpdated(stats, report_block.source_ssrc);
1165       }
1166     }
1167     if (report_block_data_observer_) {
1168       for (const auto& report_block_data :
1169            packet_information.report_block_datas) {
1170         report_block_data_observer_->OnReportBlockDataUpdated(
1171             report_block_data);
1172       }
1173     }
1174   }
1175 }
1176 
CNAME(uint32_t remoteSSRC,char cName[RTCP_CNAME_SIZE]) const1177 int32_t RTCPReceiver::CNAME(uint32_t remoteSSRC,
1178                             char cName[RTCP_CNAME_SIZE]) const {
1179   RTC_DCHECK(cName);
1180 
1181   MutexLock lock(&rtcp_receiver_lock_);
1182   auto received_cname_it = received_cnames_.find(remoteSSRC);
1183   if (received_cname_it == received_cnames_.end())
1184     return -1;
1185 
1186   size_t length = received_cname_it->second.copy(cName, RTCP_CNAME_SIZE - 1);
1187   cName[length] = 0;
1188   return 0;
1189 }
1190 
TmmbrReceived()1191 std::vector<rtcp::TmmbItem> RTCPReceiver::TmmbrReceived() {
1192   MutexLock lock(&rtcp_receiver_lock_);
1193   std::vector<rtcp::TmmbItem> candidates;
1194 
1195   int64_t now_ms = clock_->TimeInMilliseconds();
1196   int64_t timeout_ms = now_ms - kTmmbrTimeoutIntervalMs;
1197 
1198   for (auto& kv : tmmbr_infos_) {
1199     for (auto it = kv.second.tmmbr.begin(); it != kv.second.tmmbr.end();) {
1200       if (it->second.last_updated_ms < timeout_ms) {
1201         // Erase timeout entries.
1202         it = kv.second.tmmbr.erase(it);
1203       } else {
1204         candidates.push_back(it->second.tmmbr_item);
1205         ++it;
1206       }
1207     }
1208   }
1209   return candidates;
1210 }
1211 
RtcpRrTimeoutLocked(Timestamp now)1212 bool RTCPReceiver::RtcpRrTimeoutLocked(Timestamp now) {
1213   return ResetTimestampIfExpired(now, last_received_rb_, report_interval_);
1214 }
1215 
RtcpRrSequenceNumberTimeoutLocked(Timestamp now)1216 bool RTCPReceiver::RtcpRrSequenceNumberTimeoutLocked(Timestamp now) {
1217   return ResetTimestampIfExpired(now, last_increased_sequence_number_,
1218                                  report_interval_);
1219 }
1220 
1221 }  // namespace webrtc
1222