• 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 "webrtc/modules/rtp_rtcp/source/rtp_rtcp_impl.h"
12 
13 #include <assert.h>
14 #include <string.h>
15 
16 #include "webrtc/common_types.h"
17 #include "webrtc/system_wrappers/interface/logging.h"
18 #include "webrtc/system_wrappers/interface/trace.h"
19 
20 #ifdef _WIN32
21 // Disable warning C4355: 'this' : used in base member initializer list.
22 #pragma warning(disable : 4355)
23 #endif
24 
25 namespace webrtc {
26 
Configuration()27 RtpRtcp::Configuration::Configuration()
28     : id(-1),
29       audio(false),
30       clock(NULL),
31       default_module(NULL),
32       receive_statistics(NullObjectReceiveStatistics()),
33       outgoing_transport(NULL),
34       rtcp_feedback(NULL),
35       intra_frame_callback(NULL),
36       bandwidth_callback(NULL),
37       rtt_stats(NULL),
38       audio_messages(NullObjectRtpAudioFeedback()),
39       remote_bitrate_estimator(NULL),
40       paced_sender(NULL) {
41 }
42 
CreateRtpRtcp(const RtpRtcp::Configuration & configuration)43 RtpRtcp* RtpRtcp::CreateRtpRtcp(const RtpRtcp::Configuration& configuration) {
44   if (configuration.clock) {
45     return new ModuleRtpRtcpImpl(configuration);
46   } else {
47     RtpRtcp::Configuration configuration_copy;
48     memcpy(&configuration_copy, &configuration,
49            sizeof(RtpRtcp::Configuration));
50     configuration_copy.clock = Clock::GetRealTimeClock();
51     ModuleRtpRtcpImpl* rtp_rtcp_instance =
52         new ModuleRtpRtcpImpl(configuration_copy);
53     return rtp_rtcp_instance;
54   }
55 }
56 
ModuleRtpRtcpImpl(const Configuration & configuration)57 ModuleRtpRtcpImpl::ModuleRtpRtcpImpl(const Configuration& configuration)
58     : rtp_sender_(configuration.id,
59                   configuration.audio,
60                   configuration.clock,
61                   configuration.outgoing_transport,
62                   configuration.audio_messages,
63                   configuration.paced_sender),
64       rtcp_sender_(configuration.id,
65                    configuration.audio,
66                    configuration.clock,
67                    configuration.receive_statistics),
68       rtcp_receiver_(configuration.id, configuration.clock, this),
69       clock_(configuration.clock),
70       id_(configuration.id),
71       audio_(configuration.audio),
72       collision_detected_(false),
73       last_process_time_(configuration.clock->TimeInMilliseconds()),
74       last_bitrate_process_time_(configuration.clock->TimeInMilliseconds()),
75       last_rtt_process_time_(configuration.clock->TimeInMilliseconds()),
76       packet_overhead_(28),  // IPV4 UDP.
77       critical_section_module_ptrs_(
78           CriticalSectionWrapper::CreateCriticalSection()),
79       critical_section_module_ptrs_feedback_(
80           CriticalSectionWrapper::CreateCriticalSection()),
81       default_module_(
82           static_cast<ModuleRtpRtcpImpl*>(configuration.default_module)),
83       padding_index_(-1),  // Start padding at the first child module.
84       nack_method_(kNackOff),
85       nack_last_time_sent_full_(0),
86       nack_last_seq_number_sent_(0),
87       simulcast_(false),
88       key_frame_req_method_(kKeyFrameReqFirRtp),
89       remote_bitrate_(configuration.remote_bitrate_estimator),
90       rtt_stats_(configuration.rtt_stats),
91       critical_section_rtt_(CriticalSectionWrapper::CreateCriticalSection()),
92       rtt_ms_(0) {
93   send_video_codec_.codecType = kVideoCodecUnknown;
94 
95   if (default_module_) {
96     default_module_->RegisterChildModule(this);
97   }
98   // TODO(pwestin) move to constructors of each rtp/rtcp sender/receiver object.
99   rtcp_receiver_.RegisterRtcpObservers(configuration.intra_frame_callback,
100                                        configuration.bandwidth_callback,
101                                        configuration.rtcp_feedback);
102   rtcp_sender_.RegisterSendTransport(configuration.outgoing_transport);
103 
104   // Make sure that RTCP objects are aware of our SSRC.
105   uint32_t SSRC = rtp_sender_.SSRC();
106   rtcp_sender_.SetSSRC(SSRC);
107   SetRtcpReceiverSsrcs(SSRC);
108 }
109 
~ModuleRtpRtcpImpl()110 ModuleRtpRtcpImpl::~ModuleRtpRtcpImpl() {
111   // All child modules MUST be deleted before deleting the default.
112   assert(child_modules_.empty());
113 
114   // Deregister for the child modules.
115   // Will go in to the default and remove it self.
116   if (default_module_) {
117     default_module_->DeRegisterChildModule(this);
118   }
119 }
120 
RegisterChildModule(RtpRtcp * module)121 void ModuleRtpRtcpImpl::RegisterChildModule(RtpRtcp* module) {
122   CriticalSectionScoped lock(
123       critical_section_module_ptrs_.get());
124   CriticalSectionScoped double_lock(
125       critical_section_module_ptrs_feedback_.get());
126 
127   // We use two locks for protecting child_modules_, one
128   // (critical_section_module_ptrs_feedback_) for incoming
129   // messages (BitrateSent) and critical_section_module_ptrs_
130   // for all outgoing messages sending packets etc.
131   child_modules_.push_back(static_cast<ModuleRtpRtcpImpl*>(module));
132 }
133 
DeRegisterChildModule(RtpRtcp * remove_module)134 void ModuleRtpRtcpImpl::DeRegisterChildModule(RtpRtcp* remove_module) {
135   CriticalSectionScoped lock(
136       critical_section_module_ptrs_.get());
137   CriticalSectionScoped double_lock(
138       critical_section_module_ptrs_feedback_.get());
139 
140   std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
141   while (it != child_modules_.end()) {
142     RtpRtcp* module = *it;
143     if (module == remove_module) {
144       child_modules_.erase(it);
145       return;
146     }
147     it++;
148   }
149 }
150 
151 // Returns the number of milliseconds until the module want a worker thread
152 // to call Process.
TimeUntilNextProcess()153 int32_t ModuleRtpRtcpImpl::TimeUntilNextProcess() {
154     const int64_t now = clock_->TimeInMilliseconds();
155   return kRtpRtcpMaxIdleTimeProcess - (now - last_process_time_);
156 }
157 
158 // Process any pending tasks such as timeouts (non time critical events).
Process()159 int32_t ModuleRtpRtcpImpl::Process() {
160   const int64_t now = clock_->TimeInMilliseconds();
161   last_process_time_ = now;
162 
163   if (now >= last_bitrate_process_time_ + kRtpRtcpBitrateProcessTimeMs) {
164     rtp_sender_.ProcessBitrate();
165     last_bitrate_process_time_ = now;
166   }
167 
168   if (!IsDefaultModule()) {
169     bool process_rtt = now >= last_rtt_process_time_ + kRtpRtcpRttProcessTimeMs;
170     if (rtcp_sender_.Sending()) {
171       // Process RTT if we have received a receiver report and we haven't
172       // processed RTT for at least |kRtpRtcpRttProcessTimeMs| milliseconds.
173       if (rtcp_receiver_.LastReceivedReceiverReport() >
174           last_rtt_process_time_ && process_rtt) {
175         std::vector<RTCPReportBlock> receive_blocks;
176         rtcp_receiver_.StatisticsReceived(&receive_blocks);
177         uint16_t max_rtt = 0;
178         for (std::vector<RTCPReportBlock>::iterator it = receive_blocks.begin();
179              it != receive_blocks.end(); ++it) {
180           uint16_t rtt = 0;
181           rtcp_receiver_.RTT(it->remoteSSRC, &rtt, NULL, NULL, NULL);
182           max_rtt = (rtt > max_rtt) ? rtt : max_rtt;
183         }
184         // Report the rtt.
185         if (rtt_stats_ && max_rtt != 0)
186           rtt_stats_->OnRttUpdate(max_rtt);
187       }
188 
189       // Verify receiver reports are delivered and the reported sequence number
190       // is increasing.
191       int64_t rtcp_interval = RtcpReportInterval();
192       if (rtcp_receiver_.RtcpRrTimeout(rtcp_interval)) {
193         LOG_F(LS_WARNING) << "Timeout: No RTCP RR received.";
194       } else if (rtcp_receiver_.RtcpRrSequenceNumberTimeout(rtcp_interval)) {
195         LOG_F(LS_WARNING) <<
196             "Timeout: No increase in RTCP RR extended highest sequence number.";
197       }
198 
199       if (remote_bitrate_ && rtcp_sender_.TMMBR()) {
200         unsigned int target_bitrate = 0;
201         std::vector<unsigned int> ssrcs;
202         if (remote_bitrate_->LatestEstimate(&ssrcs, &target_bitrate)) {
203           if (!ssrcs.empty()) {
204             target_bitrate = target_bitrate / ssrcs.size();
205           }
206           rtcp_sender_.SetTargetBitrate(target_bitrate);
207         }
208       }
209     } else {
210       // Report rtt from receiver.
211       if (process_rtt) {
212          uint16_t rtt_ms;
213          if (rtt_stats_ && rtcp_receiver_.GetAndResetXrRrRtt(&rtt_ms)) {
214            rtt_stats_->OnRttUpdate(rtt_ms);
215          }
216       }
217     }
218 
219     // Get processed rtt.
220     if (process_rtt) {
221       last_rtt_process_time_ = now;
222       if (rtt_stats_) {
223         set_rtt_ms(rtt_stats_->LastProcessedRtt());
224       }
225     }
226 
227     if (rtcp_sender_.TimeToSendRTCPReport()) {
228       RTCPSender::FeedbackState feedback_state(this);
229       rtcp_sender_.SendRTCP(feedback_state, kRtcpReport);
230     }
231   }
232 
233   if (UpdateRTCPReceiveInformationTimers()) {
234     // A receiver has timed out
235     rtcp_receiver_.UpdateTMMBR();
236   }
237   return 0;
238 }
239 
SetRTXSendStatus(int mode)240 void ModuleRtpRtcpImpl::SetRTXSendStatus(int mode) {
241   rtp_sender_.SetRTXStatus(mode);
242 }
243 
RTXSendStatus(int * mode,uint32_t * ssrc,int * payload_type) const244 void ModuleRtpRtcpImpl::RTXSendStatus(int* mode,
245                                       uint32_t* ssrc,
246                                       int* payload_type) const {
247   rtp_sender_.RTXStatus(mode, ssrc, payload_type);
248 }
249 
SetRtxSsrc(uint32_t ssrc)250 void ModuleRtpRtcpImpl::SetRtxSsrc(uint32_t ssrc) {
251   rtp_sender_.SetRtxSsrc(ssrc);
252 }
253 
SetRtxSendPayloadType(int payload_type)254 void ModuleRtpRtcpImpl::SetRtxSendPayloadType(int payload_type) {
255   rtp_sender_.SetRtxPayloadType(payload_type);
256 }
257 
IncomingRtcpPacket(const uint8_t * rtcp_packet,const uint16_t length)258 int32_t ModuleRtpRtcpImpl::IncomingRtcpPacket(
259     const uint8_t* rtcp_packet,
260     const uint16_t length) {
261   // Allow receive of non-compound RTCP packets.
262   RTCPUtility::RTCPParserV2 rtcp_parser(rtcp_packet, length, true);
263 
264   const bool valid_rtcpheader = rtcp_parser.IsValid();
265   if (!valid_rtcpheader) {
266     LOG(LS_WARNING) << "Incoming invalid RTCP packet";
267     return -1;
268   }
269   RTCPHelp::RTCPPacketInformation rtcp_packet_information;
270   int32_t ret_val = rtcp_receiver_.IncomingRTCPPacket(
271       rtcp_packet_information, &rtcp_parser);
272   if (ret_val == 0) {
273     rtcp_receiver_.TriggerCallbacksFromRTCPPacket(rtcp_packet_information);
274   }
275   return ret_val;
276 }
277 
RegisterSendPayload(const CodecInst & voice_codec)278 int32_t ModuleRtpRtcpImpl::RegisterSendPayload(
279     const CodecInst& voice_codec) {
280   return rtp_sender_.RegisterPayload(
281            voice_codec.plname,
282            voice_codec.pltype,
283            voice_codec.plfreq,
284            voice_codec.channels,
285            (voice_codec.rate < 0) ? 0 : voice_codec.rate);
286 }
287 
RegisterSendPayload(const VideoCodec & video_codec)288 int32_t ModuleRtpRtcpImpl::RegisterSendPayload(
289     const VideoCodec& video_codec) {
290   send_video_codec_ = video_codec;
291   {
292     // simulcast_ is accessed when accessing child_modules_, so this write needs
293     // to be protected by the same lock.
294     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
295     simulcast_ = video_codec.numberOfSimulcastStreams > 1;
296   }
297   return rtp_sender_.RegisterPayload(video_codec.plName,
298                                      video_codec.plType,
299                                      90000,
300                                      0,
301                                      video_codec.maxBitrate);
302 }
303 
DeRegisterSendPayload(const int8_t payload_type)304 int32_t ModuleRtpRtcpImpl::DeRegisterSendPayload(
305     const int8_t payload_type) {
306   return rtp_sender_.DeRegisterSendPayload(payload_type);
307 }
308 
SendPayloadType() const309 int8_t ModuleRtpRtcpImpl::SendPayloadType() const {
310   return rtp_sender_.SendPayloadType();
311 }
312 
StartTimestamp() const313 uint32_t ModuleRtpRtcpImpl::StartTimestamp() const {
314   return rtp_sender_.StartTimestamp();
315 }
316 
317 // Configure start timestamp, default is a random number.
SetStartTimestamp(const uint32_t timestamp)318 int32_t ModuleRtpRtcpImpl::SetStartTimestamp(
319     const uint32_t timestamp) {
320   rtcp_sender_.SetStartTimestamp(timestamp);
321   rtp_sender_.SetStartTimestamp(timestamp, true);
322   return 0;  // TODO(pwestin): change to void.
323 }
324 
SequenceNumber() const325 uint16_t ModuleRtpRtcpImpl::SequenceNumber() const {
326   return rtp_sender_.SequenceNumber();
327 }
328 
329 // Set SequenceNumber, default is a random number.
SetSequenceNumber(const uint16_t seq_num)330 int32_t ModuleRtpRtcpImpl::SetSequenceNumber(
331     const uint16_t seq_num) {
332   rtp_sender_.SetSequenceNumber(seq_num);
333   return 0;  // TODO(pwestin): change to void.
334 }
335 
SSRC() const336 uint32_t ModuleRtpRtcpImpl::SSRC() const {
337   return rtp_sender_.SSRC();
338 }
339 
340 // Configure SSRC, default is a random number.
SetSSRC(const uint32_t ssrc)341 void ModuleRtpRtcpImpl::SetSSRC(const uint32_t ssrc) {
342   rtp_sender_.SetSSRC(ssrc);
343   rtcp_sender_.SetSSRC(ssrc);
344   SetRtcpReceiverSsrcs(ssrc);
345 }
346 
SetCSRCStatus(const bool include)347 int32_t ModuleRtpRtcpImpl::SetCSRCStatus(const bool include) {
348   rtcp_sender_.SetCSRCStatus(include);
349   rtp_sender_.SetCSRCStatus(include);
350   return 0;  // TODO(pwestin): change to void.
351 }
352 
CSRCs(uint32_t arr_of_csrc[kRtpCsrcSize]) const353 int32_t ModuleRtpRtcpImpl::CSRCs(
354   uint32_t arr_of_csrc[kRtpCsrcSize]) const {
355   return rtp_sender_.CSRCs(arr_of_csrc);
356 }
357 
SetCSRCs(const uint32_t arr_of_csrc[kRtpCsrcSize],const uint8_t arr_length)358 int32_t ModuleRtpRtcpImpl::SetCSRCs(
359     const uint32_t arr_of_csrc[kRtpCsrcSize],
360     const uint8_t arr_length) {
361   if (IsDefaultModule()) {
362     // For default we need to update all child modules too.
363     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
364 
365     std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
366     while (it != child_modules_.end()) {
367       RtpRtcp* module = *it;
368       if (module) {
369         module->SetCSRCs(arr_of_csrc, arr_length);
370       }
371       it++;
372     }
373   } else {
374     rtcp_sender_.SetCSRCs(arr_of_csrc, arr_length);
375     rtp_sender_.SetCSRCs(arr_of_csrc, arr_length);
376   }
377   return 0;  // TODO(pwestin): change to void.
378 }
379 
PacketCountSent() const380 uint32_t ModuleRtpRtcpImpl::PacketCountSent() const {
381   return rtp_sender_.Packets();
382 }
383 
ByteCountSent() const384 uint32_t ModuleRtpRtcpImpl::ByteCountSent() const {
385   return rtp_sender_.Bytes();
386 }
387 
CurrentSendFrequencyHz() const388 int ModuleRtpRtcpImpl::CurrentSendFrequencyHz() const {
389   return rtp_sender_.SendPayloadFrequency();
390 }
391 
SetSendingStatus(const bool sending)392 int32_t ModuleRtpRtcpImpl::SetSendingStatus(const bool sending) {
393   if (rtcp_sender_.Sending() != sending) {
394     // Sends RTCP BYE when going from true to false
395     RTCPSender::FeedbackState feedback_state(this);
396     if (rtcp_sender_.SetSendingStatus(feedback_state, sending) != 0) {
397       LOG(LS_WARNING) << "Failed to send RTCP BYE";
398     }
399 
400     collision_detected_ = false;
401 
402     // Generate a new time_stamp if true and not configured via API
403     // Generate a new SSRC for the next "call" if false
404     rtp_sender_.SetSendingStatus(sending);
405     if (sending) {
406       // Make sure the RTCP sender has the same timestamp offset.
407       rtcp_sender_.SetStartTimestamp(rtp_sender_.StartTimestamp());
408     }
409 
410     // Make sure that RTCP objects are aware of our SSRC (it could have changed
411     // Due to collision)
412     uint32_t SSRC = rtp_sender_.SSRC();
413     rtcp_sender_.SetSSRC(SSRC);
414     SetRtcpReceiverSsrcs(SSRC);
415 
416     return 0;
417   }
418   return 0;
419 }
420 
Sending() const421 bool ModuleRtpRtcpImpl::Sending() const {
422   return rtcp_sender_.Sending();
423 }
424 
SetSendingMediaStatus(const bool sending)425 int32_t ModuleRtpRtcpImpl::SetSendingMediaStatus(const bool sending) {
426   rtp_sender_.SetSendingMediaStatus(sending);
427   return 0;
428 }
429 
SendingMedia() const430 bool ModuleRtpRtcpImpl::SendingMedia() const {
431   if (!IsDefaultModule()) {
432     return rtp_sender_.SendingMedia();
433   }
434 
435   CriticalSectionScoped lock(critical_section_module_ptrs_.get());
436   std::vector<ModuleRtpRtcpImpl*>::const_iterator it = child_modules_.begin();
437   while (it != child_modules_.end()) {
438     RTPSender& rtp_sender = (*it)->rtp_sender_;
439     if (rtp_sender.SendingMedia()) {
440       return true;
441     }
442     it++;
443   }
444   return false;
445 }
446 
SendOutgoingData(FrameType frame_type,int8_t payload_type,uint32_t time_stamp,int64_t capture_time_ms,const uint8_t * payload_data,uint32_t payload_size,const RTPFragmentationHeader * fragmentation,const RTPVideoHeader * rtp_video_hdr)447 int32_t ModuleRtpRtcpImpl::SendOutgoingData(
448     FrameType frame_type,
449     int8_t payload_type,
450     uint32_t time_stamp,
451     int64_t capture_time_ms,
452     const uint8_t* payload_data,
453     uint32_t payload_size,
454     const RTPFragmentationHeader* fragmentation,
455     const RTPVideoHeader* rtp_video_hdr) {
456   rtcp_sender_.SetLastRtpTime(time_stamp, capture_time_ms);
457 
458   if (!IsDefaultModule()) {
459     // Don't send RTCP from default module.
460     if (rtcp_sender_.TimeToSendRTCPReport(kVideoFrameKey == frame_type)) {
461       RTCPSender::FeedbackState feedback_state(this);
462       rtcp_sender_.SendRTCP(feedback_state, kRtcpReport);
463     }
464     return rtp_sender_.SendOutgoingData(frame_type,
465                                         payload_type,
466                                         time_stamp,
467                                         capture_time_ms,
468                                         payload_data,
469                                         payload_size,
470                                         fragmentation,
471                                         NULL,
472                                         &(rtp_video_hdr->codecHeader));
473   }
474   int32_t ret_val = -1;
475   CriticalSectionScoped lock(critical_section_module_ptrs_.get());
476   if (simulcast_) {
477     if (rtp_video_hdr == NULL) {
478       return -1;
479     }
480     int idx = 0;
481     std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
482     for (; idx < rtp_video_hdr->simulcastIdx; ++it) {
483       if (it == child_modules_.end()) {
484         return -1;
485       }
486       if ((*it)->SendingMedia()) {
487         ++idx;
488       }
489     }
490     for (; it != child_modules_.end(); ++it) {
491       if ((*it)->SendingMedia()) {
492         break;
493       }
494       ++idx;
495     }
496     if (it == child_modules_.end()) {
497       return -1;
498     }
499     return (*it)->SendOutgoingData(frame_type,
500                                    payload_type,
501                                    time_stamp,
502                                    capture_time_ms,
503                                    payload_data,
504                                    payload_size,
505                                    fragmentation,
506                                    rtp_video_hdr);
507   } else {
508     std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
509     // Send to all "child" modules
510     while (it != child_modules_.end()) {
511       if ((*it)->SendingMedia()) {
512         ret_val = (*it)->SendOutgoingData(frame_type,
513                                           payload_type,
514                                           time_stamp,
515                                           capture_time_ms,
516                                           payload_data,
517                                           payload_size,
518                                           fragmentation,
519                                           rtp_video_hdr);
520       }
521       it++;
522     }
523   }
524   return ret_val;
525 }
526 
TimeToSendPacket(uint32_t ssrc,uint16_t sequence_number,int64_t capture_time_ms,bool retransmission)527 bool ModuleRtpRtcpImpl::TimeToSendPacket(uint32_t ssrc,
528                                          uint16_t sequence_number,
529                                          int64_t capture_time_ms,
530                                          bool retransmission) {
531   if (!IsDefaultModule()) {
532     // Don't send from default module.
533     if (SendingMedia() && ssrc == rtp_sender_.SSRC()) {
534       return rtp_sender_.TimeToSendPacket(sequence_number, capture_time_ms,
535                                           retransmission);
536     }
537   } else {
538     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
539     std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
540     while (it != child_modules_.end()) {
541       if ((*it)->SendingMedia() && ssrc == (*it)->rtp_sender_.SSRC()) {
542         return (*it)->rtp_sender_.TimeToSendPacket(sequence_number,
543                                                    capture_time_ms,
544                                                    retransmission);
545       }
546       ++it;
547     }
548   }
549   // No RTP sender is interested in sending this packet.
550   return true;
551 }
552 
TimeToSendPadding(int bytes)553 int ModuleRtpRtcpImpl::TimeToSendPadding(int bytes) {
554   if (!IsDefaultModule()) {
555     // Don't send from default module.
556     if (SendingMedia()) {
557       return rtp_sender_.TimeToSendPadding(bytes);
558     }
559   } else {
560     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
561     for (size_t i = 0; i < child_modules_.size(); ++i) {
562       // Send padding on one of the modules sending media.
563       if (child_modules_[i]->SendingMedia()) {
564         return child_modules_[i]->rtp_sender_.TimeToSendPadding(bytes);
565       }
566     }
567   }
568   return 0;
569 }
570 
GetSendSideDelay(int * avg_send_delay_ms,int * max_send_delay_ms) const571 bool ModuleRtpRtcpImpl::GetSendSideDelay(int* avg_send_delay_ms,
572                                          int* max_send_delay_ms) const {
573   assert(avg_send_delay_ms);
574   assert(max_send_delay_ms);
575 
576   if (IsDefaultModule()) {
577     // This API is only supported for child modules.
578     return false;
579   }
580   return rtp_sender_.GetSendSideDelay(avg_send_delay_ms, max_send_delay_ms);
581 }
582 
MaxPayloadLength() const583 uint16_t ModuleRtpRtcpImpl::MaxPayloadLength() const {
584   return rtp_sender_.MaxPayloadLength();
585 }
586 
MaxDataPayloadLength() const587 uint16_t ModuleRtpRtcpImpl::MaxDataPayloadLength() const {
588   // Assuming IP/UDP.
589   uint16_t min_data_payload_length = IP_PACKET_SIZE - 28;
590 
591   if (IsDefaultModule()) {
592     // For default we need to update all child modules too.
593     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
594     std::vector<ModuleRtpRtcpImpl*>::const_iterator it = child_modules_.begin();
595     while (it != child_modules_.end()) {
596       RtpRtcp* module = *it;
597       if (module) {
598         uint16_t data_payload_length =
599           module->MaxDataPayloadLength();
600         if (data_payload_length < min_data_payload_length) {
601           min_data_payload_length = data_payload_length;
602         }
603       }
604       it++;
605     }
606   }
607 
608   uint16_t data_payload_length = rtp_sender_.MaxDataPayloadLength();
609   if (data_payload_length < min_data_payload_length) {
610     min_data_payload_length = data_payload_length;
611   }
612   return min_data_payload_length;
613 }
614 
SetTransportOverhead(const bool tcp,const bool ipv6,const uint8_t authentication_overhead)615 int32_t ModuleRtpRtcpImpl::SetTransportOverhead(
616     const bool tcp,
617     const bool ipv6,
618     const uint8_t authentication_overhead) {
619   uint16_t packet_overhead = 0;
620   if (ipv6) {
621     packet_overhead = 40;
622   } else {
623     packet_overhead = 20;
624   }
625   if (tcp) {
626     // TCP.
627     packet_overhead += 20;
628   } else {
629     // UDP.
630     packet_overhead += 8;
631   }
632   packet_overhead += authentication_overhead;
633 
634   if (packet_overhead == packet_overhead_) {
635     // Ok same as before.
636     return 0;
637   }
638   // Calc diff.
639   int16_t packet_over_head_diff = packet_overhead - packet_overhead_;
640 
641   // Store new.
642   packet_overhead_ = packet_overhead;
643 
644   uint16_t length =
645       rtp_sender_.MaxPayloadLength() - packet_over_head_diff;
646   return rtp_sender_.SetMaxPayloadLength(length, packet_overhead_);
647 }
648 
SetMaxTransferUnit(const uint16_t mtu)649 int32_t ModuleRtpRtcpImpl::SetMaxTransferUnit(const uint16_t mtu) {
650   if (mtu > IP_PACKET_SIZE) {
651     LOG(LS_ERROR) << "Invalid mtu: " << mtu;
652     return -1;
653   }
654   return rtp_sender_.SetMaxPayloadLength(mtu - packet_overhead_,
655                                          packet_overhead_);
656 }
657 
RTCP() const658 RTCPMethod ModuleRtpRtcpImpl::RTCP() const {
659   if (rtcp_sender_.Status() != kRtcpOff) {
660     return rtcp_receiver_.Status();
661   }
662   return kRtcpOff;
663 }
664 
665 // Configure RTCP status i.e on/off.
SetRTCPStatus(const RTCPMethod method)666 int32_t ModuleRtpRtcpImpl::SetRTCPStatus(const RTCPMethod method) {
667   if (rtcp_sender_.SetRTCPStatus(method) == 0) {
668     return rtcp_receiver_.SetRTCPStatus(method);
669   }
670   return -1;
671 }
672 
673 // Only for internal test.
LastSendReport(uint32_t & last_rtcptime)674 uint32_t ModuleRtpRtcpImpl::LastSendReport(
675     uint32_t& last_rtcptime) {
676   return rtcp_sender_.LastSendReport(last_rtcptime);
677 }
678 
SetCNAME(const char c_name[RTCP_CNAME_SIZE])679 int32_t ModuleRtpRtcpImpl::SetCNAME(const char c_name[RTCP_CNAME_SIZE]) {
680   return rtcp_sender_.SetCNAME(c_name);
681 }
682 
CNAME(char c_name[RTCP_CNAME_SIZE])683 int32_t ModuleRtpRtcpImpl::CNAME(char c_name[RTCP_CNAME_SIZE]) {
684   return rtcp_sender_.CNAME(c_name);
685 }
686 
AddMixedCNAME(const uint32_t ssrc,const char c_name[RTCP_CNAME_SIZE])687 int32_t ModuleRtpRtcpImpl::AddMixedCNAME(
688   const uint32_t ssrc,
689   const char c_name[RTCP_CNAME_SIZE]) {
690   return rtcp_sender_.AddMixedCNAME(ssrc, c_name);
691 }
692 
RemoveMixedCNAME(const uint32_t ssrc)693 int32_t ModuleRtpRtcpImpl::RemoveMixedCNAME(const uint32_t ssrc) {
694   return rtcp_sender_.RemoveMixedCNAME(ssrc);
695 }
696 
RemoteCNAME(const uint32_t remote_ssrc,char c_name[RTCP_CNAME_SIZE]) const697 int32_t ModuleRtpRtcpImpl::RemoteCNAME(
698     const uint32_t remote_ssrc,
699     char c_name[RTCP_CNAME_SIZE]) const {
700   return rtcp_receiver_.CNAME(remote_ssrc, c_name);
701 }
702 
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) const703 int32_t ModuleRtpRtcpImpl::RemoteNTP(
704     uint32_t* received_ntpsecs,
705     uint32_t* received_ntpfrac,
706     uint32_t* rtcp_arrival_time_secs,
707     uint32_t* rtcp_arrival_time_frac,
708     uint32_t* rtcp_timestamp) const {
709   return rtcp_receiver_.NTP(received_ntpsecs,
710                             received_ntpfrac,
711                             rtcp_arrival_time_secs,
712                             rtcp_arrival_time_frac,
713                             rtcp_timestamp);
714 }
715 
716 // Get RoundTripTime.
RTT(const uint32_t remote_ssrc,uint16_t * rtt,uint16_t * avg_rtt,uint16_t * min_rtt,uint16_t * max_rtt) const717 int32_t ModuleRtpRtcpImpl::RTT(const uint32_t remote_ssrc,
718                                uint16_t* rtt,
719                                uint16_t* avg_rtt,
720                                uint16_t* min_rtt,
721                                uint16_t* max_rtt) const {
722   int32_t ret = rtcp_receiver_.RTT(remote_ssrc, rtt, avg_rtt, min_rtt, max_rtt);
723   if (rtt && *rtt == 0) {
724     // Try to get RTT from RtcpRttStats class.
725     *rtt = static_cast<uint16_t>(rtt_ms());
726   }
727   return ret;
728 }
729 
730 // Reset RoundTripTime statistics.
ResetRTT(const uint32_t remote_ssrc)731 int32_t ModuleRtpRtcpImpl::ResetRTT(const uint32_t remote_ssrc) {
732   return rtcp_receiver_.ResetRTT(remote_ssrc);
733 }
734 
735 // Reset RTP data counters for the sending side.
ResetSendDataCountersRTP()736 int32_t ModuleRtpRtcpImpl::ResetSendDataCountersRTP() {
737   rtp_sender_.ResetDataCounters();
738   return 0;  // TODO(pwestin): change to void.
739 }
740 
741 // Force a send of an RTCP packet.
742 // Normal SR and RR are triggered via the process function.
SendRTCP(uint32_t rtcp_packet_type)743 int32_t ModuleRtpRtcpImpl::SendRTCP(uint32_t rtcp_packet_type) {
744   RTCPSender::FeedbackState feedback_state(this);
745   return rtcp_sender_.SendRTCP(feedback_state, rtcp_packet_type);
746 }
747 
SetRTCPApplicationSpecificData(const uint8_t sub_type,const uint32_t name,const uint8_t * data,const uint16_t length)748 int32_t ModuleRtpRtcpImpl::SetRTCPApplicationSpecificData(
749     const uint8_t sub_type,
750     const uint32_t name,
751     const uint8_t* data,
752     const uint16_t length) {
753   return  rtcp_sender_.SetApplicationSpecificData(sub_type, name, data, length);
754 }
755 
756 // (XR) VOIP metric.
SetRTCPVoIPMetrics(const RTCPVoIPMetric * voip_metric)757 int32_t ModuleRtpRtcpImpl::SetRTCPVoIPMetrics(
758   const RTCPVoIPMetric* voip_metric) {
759   return  rtcp_sender_.SetRTCPVoIPMetrics(voip_metric);
760 }
761 
SetRtcpXrRrtrStatus(bool enable)762 void ModuleRtpRtcpImpl::SetRtcpXrRrtrStatus(bool enable) {
763   return rtcp_sender_.SendRtcpXrReceiverReferenceTime(enable);
764 }
765 
RtcpXrRrtrStatus() const766 bool ModuleRtpRtcpImpl::RtcpXrRrtrStatus() const {
767   return rtcp_sender_.RtcpXrReceiverReferenceTime();
768 }
769 
DataCountersRTP(uint32_t * bytes_sent,uint32_t * packets_sent) const770 int32_t ModuleRtpRtcpImpl::DataCountersRTP(
771     uint32_t* bytes_sent,
772     uint32_t* packets_sent) const {
773   if (bytes_sent) {
774     *bytes_sent = rtp_sender_.Bytes();
775   }
776   if (packets_sent) {
777     *packets_sent = rtp_sender_.Packets();
778   }
779   return 0;
780 }
781 
RemoteRTCPStat(RTCPSenderInfo * sender_info)782 int32_t ModuleRtpRtcpImpl::RemoteRTCPStat(RTCPSenderInfo* sender_info) {
783   return rtcp_receiver_.SenderInfoReceived(sender_info);
784 }
785 
786 // Received RTCP report.
RemoteRTCPStat(std::vector<RTCPReportBlock> * receive_blocks) const787 int32_t ModuleRtpRtcpImpl::RemoteRTCPStat(
788     std::vector<RTCPReportBlock>* receive_blocks) const {
789   return rtcp_receiver_.StatisticsReceived(receive_blocks);
790 }
791 
AddRTCPReportBlock(const uint32_t ssrc,const RTCPReportBlock * report_block)792 int32_t ModuleRtpRtcpImpl::AddRTCPReportBlock(
793     const uint32_t ssrc,
794     const RTCPReportBlock* report_block) {
795   return rtcp_sender_.AddExternalReportBlock(ssrc, report_block);
796 }
797 
RemoveRTCPReportBlock(const uint32_t ssrc)798 int32_t ModuleRtpRtcpImpl::RemoveRTCPReportBlock(
799   const uint32_t ssrc) {
800   return rtcp_sender_.RemoveExternalReportBlock(ssrc);
801 }
802 
GetRtcpPacketTypeCounters(RtcpPacketTypeCounter * packets_sent,RtcpPacketTypeCounter * packets_received) const803 void ModuleRtpRtcpImpl::GetRtcpPacketTypeCounters(
804     RtcpPacketTypeCounter* packets_sent,
805     RtcpPacketTypeCounter* packets_received) const {
806   rtcp_sender_.GetPacketTypeCounter(packets_sent);
807   rtcp_receiver_.GetPacketTypeCounter(packets_received);
808 }
809 
810 // (REMB) Receiver Estimated Max Bitrate.
REMB() const811 bool ModuleRtpRtcpImpl::REMB() const {
812   return rtcp_sender_.REMB();
813 }
814 
SetREMBStatus(const bool enable)815 int32_t ModuleRtpRtcpImpl::SetREMBStatus(const bool enable) {
816   return rtcp_sender_.SetREMBStatus(enable);
817 }
818 
SetREMBData(const uint32_t bitrate,const uint8_t number_of_ssrc,const uint32_t * ssrc)819 int32_t ModuleRtpRtcpImpl::SetREMBData(const uint32_t bitrate,
820                                        const uint8_t number_of_ssrc,
821                                        const uint32_t* ssrc) {
822   return rtcp_sender_.SetREMBData(bitrate, number_of_ssrc, ssrc);
823 }
824 
825 // (IJ) Extended jitter report.
IJ() const826 bool ModuleRtpRtcpImpl::IJ() const {
827   return rtcp_sender_.IJ();
828 }
829 
SetIJStatus(const bool enable)830 int32_t ModuleRtpRtcpImpl::SetIJStatus(const bool enable) {
831   return rtcp_sender_.SetIJStatus(enable);
832 }
833 
RegisterSendRtpHeaderExtension(const RTPExtensionType type,const uint8_t id)834 int32_t ModuleRtpRtcpImpl::RegisterSendRtpHeaderExtension(
835     const RTPExtensionType type,
836     const uint8_t id) {
837   return rtp_sender_.RegisterRtpHeaderExtension(type, id);
838 }
839 
DeregisterSendRtpHeaderExtension(const RTPExtensionType type)840 int32_t ModuleRtpRtcpImpl::DeregisterSendRtpHeaderExtension(
841     const RTPExtensionType type) {
842   return rtp_sender_.DeregisterRtpHeaderExtension(type);
843 }
844 
845 // (TMMBR) Temporary Max Media Bit Rate.
TMMBR() const846 bool ModuleRtpRtcpImpl::TMMBR() const {
847   return rtcp_sender_.TMMBR();
848 }
849 
SetTMMBRStatus(const bool enable)850 int32_t ModuleRtpRtcpImpl::SetTMMBRStatus(const bool enable) {
851   return rtcp_sender_.SetTMMBRStatus(enable);
852 }
853 
SetTMMBN(const TMMBRSet * bounding_set)854 int32_t ModuleRtpRtcpImpl::SetTMMBN(const TMMBRSet* bounding_set) {
855   uint32_t max_bitrate_kbit =
856       rtp_sender_.MaxConfiguredBitrateVideo() / 1000;
857   return rtcp_sender_.SetTMMBN(bounding_set, max_bitrate_kbit);
858 }
859 
860 // Returns the currently configured retransmission mode.
SelectiveRetransmissions() const861 int ModuleRtpRtcpImpl::SelectiveRetransmissions() const {
862   return rtp_sender_.SelectiveRetransmissions();
863 }
864 
865 // Enable or disable a retransmission mode, which decides which packets will
866 // be retransmitted if NACKed.
SetSelectiveRetransmissions(uint8_t settings)867 int ModuleRtpRtcpImpl::SetSelectiveRetransmissions(uint8_t settings) {
868   return rtp_sender_.SetSelectiveRetransmissions(settings);
869 }
870 
871 // Send a Negative acknowledgment packet.
SendNACK(const uint16_t * nack_list,const uint16_t size)872 int32_t ModuleRtpRtcpImpl::SendNACK(const uint16_t* nack_list,
873                                     const uint16_t size) {
874   // Use RTT from RtcpRttStats class if provided.
875   uint16_t rtt = rtt_ms();
876   if (rtt == 0) {
877     rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
878   }
879 
880   int64_t wait_time = 5 + ((rtt * 3) >> 1);  // 5 + RTT * 1.5.
881   if (wait_time == 5) {
882     wait_time = 100;  // During startup we don't have an RTT.
883   }
884   const int64_t now = clock_->TimeInMilliseconds();
885   const int64_t time_limit = now - wait_time;
886   uint16_t nackLength = size;
887   uint16_t start_id = 0;
888 
889   if (nack_last_time_sent_full_ < time_limit) {
890     // Send list. Set the timer to make sure we only send a full NACK list once
891     // within every time_limit.
892     nack_last_time_sent_full_ = now;
893   } else {
894     // Only send if extended list.
895     if (nack_last_seq_number_sent_ == nack_list[size - 1]) {
896       // Last seq num is the same don't send list.
897       return 0;
898     } else {
899       // Send NACKs only for new sequence numbers to avoid re-sending
900       // NACKs for sequences we have already sent.
901       for (int i = 0; i < size; ++i)  {
902         if (nack_last_seq_number_sent_ == nack_list[i]) {
903           start_id = i + 1;
904           break;
905         }
906       }
907       nackLength = size - start_id;
908     }
909   }
910   // Our RTCP NACK implementation is limited to kRtcpMaxNackFields sequence
911   // numbers per RTCP packet.
912   if (nackLength > kRtcpMaxNackFields) {
913     nackLength = kRtcpMaxNackFields;
914   }
915   nack_last_seq_number_sent_ = nack_list[start_id + nackLength - 1];
916 
917   RTCPSender::FeedbackState feedback_state(this);
918   return rtcp_sender_.SendRTCP(
919       feedback_state, kRtcpNack, nackLength, &nack_list[start_id]);
920 }
921 
922 // Store the sent packets, needed to answer to a Negative acknowledgment
923 // requests.
SetStorePacketsStatus(const bool enable,const uint16_t number_to_store)924 int32_t ModuleRtpRtcpImpl::SetStorePacketsStatus(
925     const bool enable,
926     const uint16_t number_to_store) {
927   rtp_sender_.SetStorePacketsStatus(enable, number_to_store);
928   return 0;  // TODO(pwestin): change to void.
929 }
930 
StorePackets() const931 bool ModuleRtpRtcpImpl::StorePackets() const {
932   return rtp_sender_.StorePackets();
933 }
934 
RegisterSendChannelRtcpStatisticsCallback(RtcpStatisticsCallback * callback)935 void ModuleRtpRtcpImpl::RegisterSendChannelRtcpStatisticsCallback(
936     RtcpStatisticsCallback* callback) {
937   rtcp_receiver_.RegisterRtcpStatisticsCallback(callback);
938 }
939 
940 RtcpStatisticsCallback* ModuleRtpRtcpImpl::
GetSendChannelRtcpStatisticsCallback()941         GetSendChannelRtcpStatisticsCallback() {
942   return rtcp_receiver_.GetRtcpStatisticsCallback();
943 }
944 
945 // Send a TelephoneEvent tone using RFC 2833 (4733).
SendTelephoneEventOutband(const uint8_t key,const uint16_t time_ms,const uint8_t level)946 int32_t ModuleRtpRtcpImpl::SendTelephoneEventOutband(
947     const uint8_t key,
948     const uint16_t time_ms,
949     const uint8_t level) {
950   return rtp_sender_.SendTelephoneEvent(key, time_ms, level);
951 }
952 
SendTelephoneEventActive(int8_t & telephone_event) const953 bool ModuleRtpRtcpImpl::SendTelephoneEventActive(
954     int8_t& telephone_event) const {
955   return rtp_sender_.SendTelephoneEventActive(&telephone_event);
956 }
957 
958 // Set audio packet size, used to determine when it's time to send a DTMF
959 // packet in silence (CNG).
SetAudioPacketSize(const uint16_t packet_size_samples)960 int32_t ModuleRtpRtcpImpl::SetAudioPacketSize(
961     const uint16_t packet_size_samples) {
962   return rtp_sender_.SetAudioPacketSize(packet_size_samples);
963 }
964 
SetAudioLevel(const uint8_t level_d_bov)965 int32_t ModuleRtpRtcpImpl::SetAudioLevel(
966     const uint8_t level_d_bov) {
967   return rtp_sender_.SetAudioLevel(level_d_bov);
968 }
969 
970 // Set payload type for Redundant Audio Data RFC 2198.
SetSendREDPayloadType(const int8_t payload_type)971 int32_t ModuleRtpRtcpImpl::SetSendREDPayloadType(
972     const int8_t payload_type) {
973   return rtp_sender_.SetRED(payload_type);
974 }
975 
976 // Get payload type for Redundant Audio Data RFC 2198.
SendREDPayloadType(int8_t & payload_type) const977 int32_t ModuleRtpRtcpImpl::SendREDPayloadType(
978     int8_t& payload_type) const {
979   return rtp_sender_.RED(&payload_type);
980 }
981 
SendVideoCodec() const982 RtpVideoCodecTypes ModuleRtpRtcpImpl::SendVideoCodec() const {
983   return rtp_sender_.VideoCodecType();
984 }
985 
SetTargetSendBitrate(const std::vector<uint32_t> & stream_bitrates)986 void ModuleRtpRtcpImpl::SetTargetSendBitrate(
987     const std::vector<uint32_t>& stream_bitrates) {
988   if (IsDefaultModule()) {
989     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
990     if (simulcast_) {
991       std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
992       for (size_t i = 0;
993            it != child_modules_.end() && i < stream_bitrates.size(); ++it) {
994         if ((*it)->SendingMedia()) {
995           RTPSender& rtp_sender = (*it)->rtp_sender_;
996           rtp_sender.SetTargetBitrate(stream_bitrates[i]);
997           ++i;
998         }
999       }
1000     } else {
1001       if (stream_bitrates.size() > 1)
1002         return;
1003       std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1004       for (; it != child_modules_.end(); ++it) {
1005         RTPSender& rtp_sender = (*it)->rtp_sender_;
1006         rtp_sender.SetTargetBitrate(stream_bitrates[0]);
1007       }
1008     }
1009   } else {
1010     if (stream_bitrates.size() > 1)
1011       return;
1012     rtp_sender_.SetTargetBitrate(stream_bitrates[0]);
1013   }
1014 }
1015 
SetKeyFrameRequestMethod(const KeyFrameRequestMethod method)1016 int32_t ModuleRtpRtcpImpl::SetKeyFrameRequestMethod(
1017     const KeyFrameRequestMethod method) {
1018   key_frame_req_method_ = method;
1019   return 0;
1020 }
1021 
RequestKeyFrame()1022 int32_t ModuleRtpRtcpImpl::RequestKeyFrame() {
1023   switch (key_frame_req_method_) {
1024     case kKeyFrameReqFirRtp:
1025       return rtp_sender_.SendRTPIntraRequest();
1026     case kKeyFrameReqPliRtcp:
1027       return SendRTCP(kRtcpPli);
1028     case kKeyFrameReqFirRtcp:
1029       return SendRTCP(kRtcpFir);
1030   }
1031   return -1;
1032 }
1033 
SendRTCPSliceLossIndication(const uint8_t picture_id)1034 int32_t ModuleRtpRtcpImpl::SendRTCPSliceLossIndication(
1035     const uint8_t picture_id) {
1036   RTCPSender::FeedbackState feedback_state(this);
1037   return rtcp_sender_.SendRTCP(
1038       feedback_state, kRtcpSli, 0, 0, false, picture_id);
1039 }
1040 
SetCameraDelay(const int32_t delay_ms)1041 int32_t ModuleRtpRtcpImpl::SetCameraDelay(const int32_t delay_ms) {
1042   if (IsDefaultModule()) {
1043     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1044     std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1045     while (it != child_modules_.end()) {
1046       RtpRtcp* module = *it;
1047       if (module) {
1048         module->SetCameraDelay(delay_ms);
1049       }
1050       it++;
1051     }
1052     return 0;
1053   }
1054   return rtcp_sender_.SetCameraDelay(delay_ms);
1055 }
1056 
SetGenericFECStatus(const bool enable,const uint8_t payload_type_red,const uint8_t payload_type_fec)1057 int32_t ModuleRtpRtcpImpl::SetGenericFECStatus(
1058     const bool enable,
1059     const uint8_t payload_type_red,
1060     const uint8_t payload_type_fec) {
1061   return rtp_sender_.SetGenericFECStatus(enable,
1062                                          payload_type_red,
1063                                          payload_type_fec);
1064 }
1065 
GenericFECStatus(bool & enable,uint8_t & payload_type_red,uint8_t & payload_type_fec)1066 int32_t ModuleRtpRtcpImpl::GenericFECStatus(
1067     bool& enable,
1068     uint8_t& payload_type_red,
1069     uint8_t& payload_type_fec) {
1070   bool child_enabled = false;
1071   if (IsDefaultModule()) {
1072     // For default we need to check all child modules too.
1073     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1074     std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1075     while (it != child_modules_.end()) {
1076       RtpRtcp* module = *it;
1077       if (module)  {
1078         bool enabled = false;
1079         uint8_t dummy_ptype_red = 0;
1080         uint8_t dummy_ptype_fec = 0;
1081         if (module->GenericFECStatus(enabled,
1082                                      dummy_ptype_red,
1083                                      dummy_ptype_fec) == 0 && enabled) {
1084           child_enabled = true;
1085           break;
1086         }
1087       }
1088       it++;
1089     }
1090   }
1091   int32_t ret_val = rtp_sender_.GenericFECStatus(&enable,
1092                                                  &payload_type_red,
1093                                                  &payload_type_fec);
1094   if (child_enabled) {
1095     // Returns true if enabled for any child module.
1096     enable = child_enabled;
1097   }
1098   return ret_val;
1099 }
1100 
SetFecParameters(const FecProtectionParams * delta_params,const FecProtectionParams * key_params)1101 int32_t ModuleRtpRtcpImpl::SetFecParameters(
1102     const FecProtectionParams* delta_params,
1103     const FecProtectionParams* key_params) {
1104   if (IsDefaultModule())  {
1105     // For default we need to update all child modules too.
1106     CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1107 
1108     std::vector<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1109     while (it != child_modules_.end()) {
1110       RtpRtcp* module = *it;
1111       if (module) {
1112         module->SetFecParameters(delta_params, key_params);
1113       }
1114       it++;
1115     }
1116     return 0;
1117   }
1118   return rtp_sender_.SetFecParameters(delta_params, key_params);
1119 }
1120 
SetRemoteSSRC(const uint32_t ssrc)1121 void ModuleRtpRtcpImpl::SetRemoteSSRC(const uint32_t ssrc) {
1122   // Inform about the incoming SSRC.
1123   rtcp_sender_.SetRemoteSSRC(ssrc);
1124   rtcp_receiver_.SetRemoteSSRC(ssrc);
1125 
1126   // Check for a SSRC collision.
1127   if (rtp_sender_.SSRC() == ssrc && !collision_detected_) {
1128     // If we detect a collision change the SSRC but only once.
1129     collision_detected_ = true;
1130     uint32_t new_ssrc = rtp_sender_.GenerateNewSSRC();
1131     if (new_ssrc == 0) {
1132       // Configured via API ignore.
1133       return;
1134     }
1135     if (kRtcpOff != rtcp_sender_.Status()) {
1136       // Send RTCP bye on the current SSRC.
1137       SendRTCP(kRtcpBye);
1138     }
1139     // Change local SSRC and inform all objects about the new SSRC.
1140     rtcp_sender_.SetSSRC(new_ssrc);
1141     SetRtcpReceiverSsrcs(new_ssrc);
1142   }
1143 }
1144 
BitrateSent(uint32_t * total_rate,uint32_t * video_rate,uint32_t * fec_rate,uint32_t * nack_rate) const1145 void ModuleRtpRtcpImpl::BitrateSent(uint32_t* total_rate,
1146                                     uint32_t* video_rate,
1147                                     uint32_t* fec_rate,
1148                                     uint32_t* nack_rate) const {
1149   if (IsDefaultModule()) {
1150     // For default we need to update the send bitrate.
1151     CriticalSectionScoped lock(critical_section_module_ptrs_feedback_.get());
1152 
1153     if (total_rate != NULL)
1154       *total_rate = 0;
1155     if (video_rate != NULL)
1156       *video_rate = 0;
1157     if (fec_rate != NULL)
1158       *fec_rate = 0;
1159     if (nack_rate != NULL)
1160       *nack_rate = 0;
1161 
1162     std::vector<ModuleRtpRtcpImpl*>::const_iterator it = child_modules_.begin();
1163     while (it != child_modules_.end()) {
1164       RtpRtcp* module = *it;
1165       if (module) {
1166         uint32_t child_total_rate = 0;
1167         uint32_t child_video_rate = 0;
1168         uint32_t child_fec_rate = 0;
1169         uint32_t child_nack_rate = 0;
1170         module->BitrateSent(&child_total_rate,
1171                             &child_video_rate,
1172                             &child_fec_rate,
1173                             &child_nack_rate);
1174         if (total_rate != NULL && child_total_rate > *total_rate)
1175           *total_rate = child_total_rate;
1176         if (video_rate != NULL && child_video_rate > *video_rate)
1177           *video_rate = child_video_rate;
1178         if (fec_rate != NULL && child_fec_rate > *fec_rate)
1179           *fec_rate = child_fec_rate;
1180         if (nack_rate != NULL && child_nack_rate > *nack_rate)
1181           *nack_rate = child_nack_rate;
1182       }
1183       it++;
1184     }
1185     return;
1186   }
1187   if (total_rate != NULL)
1188     *total_rate = rtp_sender_.BitrateSent();
1189   if (video_rate != NULL)
1190     *video_rate = rtp_sender_.VideoBitrateSent();
1191   if (fec_rate != NULL)
1192     *fec_rate = rtp_sender_.FecOverheadRate();
1193   if (nack_rate != NULL)
1194     *nack_rate = rtp_sender_.NackOverheadRate();
1195 }
1196 
RegisterVideoBitrateObserver(BitrateStatisticsObserver * observer)1197 void ModuleRtpRtcpImpl::RegisterVideoBitrateObserver(
1198     BitrateStatisticsObserver* observer) {
1199   assert(!IsDefaultModule());
1200   rtp_sender_.RegisterBitrateObserver(observer);
1201 }
1202 
GetVideoBitrateObserver() const1203 BitrateStatisticsObserver* ModuleRtpRtcpImpl::GetVideoBitrateObserver() const {
1204   return rtp_sender_.GetBitrateObserver();
1205 }
1206 
OnRequestIntraFrame()1207 void ModuleRtpRtcpImpl::OnRequestIntraFrame() {
1208   RequestKeyFrame();
1209 }
1210 
OnRequestSendReport()1211 void ModuleRtpRtcpImpl::OnRequestSendReport() {
1212   SendRTCP(kRtcpSr);
1213 }
1214 
SendRTCPReferencePictureSelection(const uint64_t picture_id)1215 int32_t ModuleRtpRtcpImpl::SendRTCPReferencePictureSelection(
1216     const uint64_t picture_id) {
1217   RTCPSender::FeedbackState feedback_state(this);
1218   return rtcp_sender_.SendRTCP(
1219       feedback_state, kRtcpRpsi, 0, 0, false, picture_id);
1220 }
1221 
SendTimeOfSendReport(const uint32_t send_report)1222 uint32_t ModuleRtpRtcpImpl::SendTimeOfSendReport(
1223     const uint32_t send_report) {
1224   return rtcp_sender_.SendTimeOfSendReport(send_report);
1225 }
1226 
SendTimeOfXrRrReport(uint32_t mid_ntp,int64_t * time_ms) const1227 bool ModuleRtpRtcpImpl::SendTimeOfXrRrReport(
1228     uint32_t mid_ntp, int64_t* time_ms) const {
1229   return rtcp_sender_.SendTimeOfXrRrReport(mid_ntp, time_ms);
1230 }
1231 
OnReceivedNACK(const std::list<uint16_t> & nack_sequence_numbers)1232 void ModuleRtpRtcpImpl::OnReceivedNACK(
1233     const std::list<uint16_t>& nack_sequence_numbers) {
1234   if (!rtp_sender_.StorePackets() ||
1235       nack_sequence_numbers.size() == 0) {
1236     return;
1237   }
1238   // Use RTT from RtcpRttStats class if provided.
1239   uint16_t rtt = rtt_ms();
1240   if (rtt == 0) {
1241     rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
1242   }
1243   rtp_sender_.OnReceivedNACK(nack_sequence_numbers, rtt);
1244 }
1245 
LastReceivedNTP(uint32_t & rtcp_arrival_time_secs,uint32_t & rtcp_arrival_time_frac,uint32_t & remote_sr)1246 int32_t ModuleRtpRtcpImpl::LastReceivedNTP(
1247     uint32_t& rtcp_arrival_time_secs,  // When we got the last report.
1248     uint32_t& rtcp_arrival_time_frac,
1249     uint32_t& remote_sr) {
1250   // Remote SR: NTP inside the last received (mid 16 bits from sec and frac).
1251   uint32_t ntp_secs = 0;
1252   uint32_t ntp_frac = 0;
1253 
1254   if (-1 == rtcp_receiver_.NTP(&ntp_secs,
1255                                &ntp_frac,
1256                                &rtcp_arrival_time_secs,
1257                                &rtcp_arrival_time_frac,
1258                                NULL)) {
1259     return -1;
1260   }
1261   remote_sr = ((ntp_secs & 0x0000ffff) << 16) + ((ntp_frac & 0xffff0000) >> 16);
1262   return 0;
1263 }
1264 
LastReceivedXrReferenceTimeInfo(RtcpReceiveTimeInfo * info) const1265 bool ModuleRtpRtcpImpl::LastReceivedXrReferenceTimeInfo(
1266     RtcpReceiveTimeInfo* info) const {
1267   return rtcp_receiver_.LastReceivedXrReferenceTimeInfo(info);
1268 }
1269 
UpdateRTCPReceiveInformationTimers()1270 bool ModuleRtpRtcpImpl::UpdateRTCPReceiveInformationTimers() {
1271   // If this returns true this channel has timed out.
1272   // Periodically check if this is true and if so call UpdateTMMBR.
1273   return rtcp_receiver_.UpdateRTCPReceiveInformationTimers();
1274 }
1275 
1276 // Called from RTCPsender.
BoundingSet(bool & tmmbr_owner,TMMBRSet * & bounding_set)1277 int32_t ModuleRtpRtcpImpl::BoundingSet(bool& tmmbr_owner,
1278                                        TMMBRSet*& bounding_set) {
1279   return rtcp_receiver_.BoundingSet(tmmbr_owner, bounding_set);
1280 }
1281 
RtcpReportInterval()1282 int64_t ModuleRtpRtcpImpl::RtcpReportInterval() {
1283   if (audio_)
1284     return RTCP_INTERVAL_AUDIO_MS;
1285   else
1286     return RTCP_INTERVAL_VIDEO_MS;
1287 }
1288 
SetRtcpReceiverSsrcs(uint32_t main_ssrc)1289 void ModuleRtpRtcpImpl::SetRtcpReceiverSsrcs(uint32_t main_ssrc) {
1290   std::set<uint32_t> ssrcs;
1291   ssrcs.insert(main_ssrc);
1292   int rtx_mode = kRtxOff;
1293   uint32_t rtx_ssrc = 0;
1294   int rtx_payload_type = 0;
1295   rtp_sender_.RTXStatus(&rtx_mode, &rtx_ssrc, &rtx_payload_type);
1296   if (rtx_mode != kRtxOff)
1297     ssrcs.insert(rtx_ssrc);
1298   rtcp_receiver_.SetSsrcs(main_ssrc, ssrcs);
1299 }
1300 
set_rtt_ms(uint32_t rtt_ms)1301 void ModuleRtpRtcpImpl::set_rtt_ms(uint32_t rtt_ms) {
1302   CriticalSectionScoped cs(critical_section_rtt_.get());
1303   rtt_ms_ = rtt_ms;
1304 }
1305 
rtt_ms() const1306 uint32_t ModuleRtpRtcpImpl::rtt_ms() const {
1307   CriticalSectionScoped cs(critical_section_rtt_.get());
1308   return rtt_ms_;
1309 }
1310 
RegisterSendChannelRtpStatisticsCallback(StreamDataCountersCallback * callback)1311 void ModuleRtpRtcpImpl::RegisterSendChannelRtpStatisticsCallback(
1312     StreamDataCountersCallback* callback) {
1313   rtp_sender_.RegisterRtpStatisticsCallback(callback);
1314 }
1315 
1316 StreamDataCountersCallback*
GetSendChannelRtpStatisticsCallback() const1317     ModuleRtpRtcpImpl::GetSendChannelRtpStatisticsCallback() const {
1318   return rtp_sender_.GetRtpStatisticsCallback();
1319 }
1320 
RegisterSendFrameCountObserver(FrameCountObserver * observer)1321 void ModuleRtpRtcpImpl::RegisterSendFrameCountObserver(
1322     FrameCountObserver* observer) {
1323   rtp_sender_.RegisterFrameCountObserver(observer);
1324 }
1325 
GetSendFrameCountObserver() const1326 FrameCountObserver* ModuleRtpRtcpImpl::GetSendFrameCountObserver() const {
1327   return rtp_sender_.GetFrameCountObserver();
1328 }
1329 
IsDefaultModule() const1330 bool ModuleRtpRtcpImpl::IsDefaultModule() const {
1331   CriticalSectionScoped cs(critical_section_module_ptrs_.get());
1332   return !child_modules_.empty();
1333 }
1334 
1335 }  // Namespace webrtc
1336