rtp_rtcp_impl.cc revision 2f44673d665899ca788ae44247a9a7f4764f5e2b
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 <string.h>
14#include <cassert>
15
16#include "webrtc/common_types.h"
17#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_audio.h"
18#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_video.h"
19#include "webrtc/system_wrappers/interface/logging.h"
20#include "webrtc/system_wrappers/interface/trace.h"
21
22#ifdef MATLAB
23#include "webrtc/modules/rtp_rtcp/test/BWEStandAlone/MatlabPlot.h"
24extern MatlabEngine eng;  // Global variable defined elsewhere.
25#endif
26
27// Local for this file.
28namespace {
29
30const float kFracMs = 4.294967296E6f;
31
32}  // namespace
33
34#ifdef _WIN32
35// Disable warning C4355: 'this' : used in base member initializer list.
36#pragma warning(disable : 4355)
37#endif
38
39namespace webrtc {
40
41static RtpData* NullObjectRtpData() {
42  static NullRtpData null_rtp_data;
43  return &null_rtp_data;
44}
45
46static RtpFeedback* NullObjectRtpFeedback() {
47  static NullRtpFeedback null_rtp_feedback;
48  return &null_rtp_feedback;
49}
50
51static RtpAudioFeedback* NullObjectRtpAudioFeedback() {
52  static NullRtpAudioFeedback null_rtp_audio_feedback;
53  return &null_rtp_audio_feedback;
54}
55
56RtpRtcp::Configuration::Configuration()
57    : id(-1),
58      audio(false),
59      clock(NULL),
60      default_module(NULL),
61      incoming_data(NullObjectRtpData()),
62      incoming_messages(NullObjectRtpFeedback()),
63      outgoing_transport(NULL),
64      rtcp_feedback(NULL),
65      intra_frame_callback(NULL),
66      bandwidth_callback(NULL),
67      rtt_observer(NULL),
68      audio_messages(NullObjectRtpAudioFeedback()),
69      remote_bitrate_estimator(NULL),
70      paced_sender(NULL) {
71}
72
73RtpRtcp* RtpRtcp::CreateRtpRtcp(const RtpRtcp::Configuration& configuration) {
74  if (configuration.clock) {
75    return new ModuleRtpRtcpImpl(configuration);
76  } else {
77    RtpRtcp::Configuration configuration_copy;
78    memcpy(&configuration_copy, &configuration,
79           sizeof(RtpRtcp::Configuration));
80    configuration_copy.clock = Clock::GetRealTimeClock();
81    ModuleRtpRtcpImpl* rtp_rtcp_instance =
82        new ModuleRtpRtcpImpl(configuration_copy);
83    return rtp_rtcp_instance;
84  }
85}
86
87ModuleRtpRtcpImpl::ModuleRtpRtcpImpl(const Configuration& configuration)
88    : rtp_payload_registry_(
89          configuration.id,
90          RTPPayloadStrategy::CreateStrategy(configuration.audio)),
91      rtp_sender_(configuration.id,
92                  configuration.audio,
93                  configuration.clock,
94                  configuration.outgoing_transport,
95                  configuration.audio_messages,
96                  configuration.paced_sender),
97      rtcp_sender_(configuration.id, configuration.audio, configuration.clock,
98                   this),
99      rtcp_receiver_(configuration.id, configuration.clock, this),
100      clock_(configuration.clock),
101      rtp_telephone_event_handler_(NULL),
102      id_(configuration.id),
103      audio_(configuration.audio),
104      collision_detected_(false),
105      last_process_time_(configuration.clock->TimeInMilliseconds()),
106      last_bitrate_process_time_(configuration.clock->TimeInMilliseconds()),
107      last_packet_timeout_process_time_(
108          configuration.clock->TimeInMilliseconds()),
109      last_rtt_process_time_(configuration.clock->TimeInMilliseconds()),
110      packet_overhead_(28),  // IPV4 UDP.
111      critical_section_module_ptrs_(
112          CriticalSectionWrapper::CreateCriticalSection()),
113      critical_section_module_ptrs_feedback_(
114          CriticalSectionWrapper::CreateCriticalSection()),
115      default_module_(
116          static_cast<ModuleRtpRtcpImpl*>(configuration.default_module)),
117      dead_or_alive_active_(false),
118      dead_or_alive_timeout_ms_(0),
119      dead_or_alive_last_timer_(0),
120      nack_method_(kNackOff),
121      nack_last_time_sent_full_(0),
122      nack_last_seq_number_sent_(0),
123      simulcast_(false),
124      key_frame_req_method_(kKeyFrameReqFirRtp),
125      remote_bitrate_(configuration.remote_bitrate_estimator),
126#ifdef MATLAB
127      , plot1_(NULL),
128#endif
129      rtt_observer_(configuration.rtt_observer) {
130  RTPReceiverStrategy* rtp_receiver_strategy;
131  if (configuration.audio) {
132    // If audio, we need to be able to handle telephone events too, so stash
133    // away the audio receiver for those situations.
134    rtp_telephone_event_handler_ =
135        new RTPReceiverAudio(configuration.id, configuration.incoming_data,
136                             configuration.audio_messages);
137    rtp_receiver_strategy = rtp_telephone_event_handler_;
138  } else {
139    rtp_receiver_strategy =
140        new RTPReceiverVideo(configuration.id, &rtp_payload_registry_,
141                             configuration.incoming_data);
142  }
143  rtp_receiver_.reset(new RTPReceiver(
144      configuration.id, configuration.clock, this,
145      configuration.audio_messages, configuration.incoming_data,
146      configuration.incoming_messages, rtp_receiver_strategy,
147      &rtp_payload_registry_));
148
149
150  send_video_codec_.codecType = kVideoCodecUnknown;
151
152  if (default_module_) {
153    default_module_->RegisterChildModule(this);
154  }
155  // TODO(pwestin) move to constructors of each rtp/rtcp sender/receiver object.
156  rtcp_receiver_.RegisterRtcpObservers(configuration.intra_frame_callback,
157                                       configuration.bandwidth_callback,
158                                       configuration.rtcp_feedback);
159  rtcp_sender_.RegisterSendTransport(configuration.outgoing_transport);
160
161  // Make sure that RTCP objects are aware of our SSRC
162  uint32_t SSRC = rtp_sender_.SSRC();
163  rtcp_sender_.SetSSRC(SSRC);
164  rtcp_receiver_.SetSSRC(SSRC);
165
166  WEBRTC_TRACE(kTraceMemory, kTraceRtpRtcp, id_, "%s created", __FUNCTION__);
167}
168
169ModuleRtpRtcpImpl::~ModuleRtpRtcpImpl() {
170  WEBRTC_TRACE(kTraceMemory, kTraceRtpRtcp, id_, "%s deleted", __FUNCTION__);
171
172  // All child modules MUST be deleted before deleting the default.
173  assert(child_modules_.empty());
174
175  // Deregister for the child modules.
176  // Will go in to the default and remove it self.
177  if (default_module_) {
178    default_module_->DeRegisterChildModule(this);
179  }
180#ifdef MATLAB
181  if (plot1_) {
182    eng.DeletePlot(plot1_);
183    plot1_ = NULL;
184  }
185#endif
186}
187
188void ModuleRtpRtcpImpl::RegisterChildModule(RtpRtcp* module) {
189  WEBRTC_TRACE(kTraceModuleCall,
190               kTraceRtpRtcp,
191               id_,
192               "RegisterChildModule(module:0x%x)",
193               module);
194
195  CriticalSectionScoped lock(
196      critical_section_module_ptrs_.get());
197  CriticalSectionScoped double_lock(
198      critical_section_module_ptrs_feedback_.get());
199
200  // We use two locks for protecting child_modules_, one
201  // (critical_section_module_ptrs_feedback_) for incoming
202  // messages (BitrateSent) and critical_section_module_ptrs_
203  // for all outgoing messages sending packets etc.
204  child_modules_.push_back(static_cast<ModuleRtpRtcpImpl*>(module));
205}
206
207void ModuleRtpRtcpImpl::DeRegisterChildModule(RtpRtcp* remove_module) {
208  WEBRTC_TRACE(kTraceModuleCall,
209               kTraceRtpRtcp,
210               id_,
211               "DeRegisterChildModule(module:0x%x)", remove_module);
212
213  CriticalSectionScoped lock(
214      critical_section_module_ptrs_.get());
215  CriticalSectionScoped double_lock(
216      critical_section_module_ptrs_feedback_.get());
217
218  std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
219  while (it != child_modules_.end()) {
220    RtpRtcp* module = *it;
221    if (module == remove_module) {
222      child_modules_.erase(it);
223      return;
224    }
225    it++;
226  }
227}
228
229// Returns the number of milliseconds until the module want a worker thread
230// to call Process.
231int32_t ModuleRtpRtcpImpl::TimeUntilNextProcess() {
232    const int64_t now = clock_->TimeInMilliseconds();
233  return kRtpRtcpMaxIdleTimeProcess - (now - last_process_time_);
234}
235
236// Process any pending tasks such as timeouts (non time critical events).
237int32_t ModuleRtpRtcpImpl::Process() {
238    const int64_t now = clock_->TimeInMilliseconds();
239  last_process_time_ = now;
240
241  if (now >=
242      last_packet_timeout_process_time_ + kRtpRtcpPacketTimeoutProcessTimeMs) {
243    rtp_receiver_->PacketTimeout();
244    rtcp_receiver_.PacketTimeout();
245    last_packet_timeout_process_time_ = now;
246  }
247
248  if (now >= last_bitrate_process_time_ + kRtpRtcpBitrateProcessTimeMs) {
249    rtp_sender_.ProcessBitrate();
250    rtp_receiver_->ProcessBitrate();
251    last_bitrate_process_time_ = now;
252  }
253
254  ProcessDeadOrAliveTimer();
255
256  const bool default_instance(child_modules_.empty() ? false : true);
257  if (!default_instance) {
258    if (rtcp_sender_.Sending()) {
259      // Process RTT if we have received a receiver report and we haven't
260      // processed RTT for at least |kRtpRtcpRttProcessTimeMs| milliseconds.
261      if (rtcp_receiver_.LastReceivedReceiverReport() >
262          last_rtt_process_time_ && now >= last_rtt_process_time_ +
263          kRtpRtcpRttProcessTimeMs) {
264        last_rtt_process_time_ = now;
265        std::vector<RTCPReportBlock> receive_blocks;
266        rtcp_receiver_.StatisticsReceived(&receive_blocks);
267        uint16_t max_rtt = 0;
268        for (std::vector<RTCPReportBlock>::iterator it = receive_blocks.begin();
269             it != receive_blocks.end(); ++it) {
270          uint16_t rtt = 0;
271          rtcp_receiver_.RTT(it->remoteSSRC, &rtt, NULL, NULL, NULL);
272          max_rtt = (rtt > max_rtt) ? rtt : max_rtt;
273        }
274        // Report the rtt.
275        if (rtt_observer_ && max_rtt != 0)
276          rtt_observer_->OnRttUpdate(max_rtt);
277      }
278
279      // Verify receiver reports are delivered and the reported sequence number
280      // is increasing.
281      int64_t rtcp_interval = RtcpReportInterval();
282      if (rtcp_receiver_.RtcpRrTimeout(rtcp_interval)) {
283        LOG_F(LS_WARNING) << "Timeout: No RTCP RR received.";
284      } else if (rtcp_receiver_.RtcpRrSequenceNumberTimeout(rtcp_interval)) {
285        LOG_F(LS_WARNING) <<
286            "Timeout: No increase in RTCP RR extended highest sequence number.";
287      }
288
289      if (remote_bitrate_ && TMMBR()) {
290        unsigned int target_bitrate = 0;
291        std::vector<unsigned int> ssrcs;
292        if (remote_bitrate_->LatestEstimate(&ssrcs, &target_bitrate)) {
293          if (!ssrcs.empty()) {
294            target_bitrate = target_bitrate / ssrcs.size();
295          }
296          rtcp_sender_.SetTargetBitrate(target_bitrate);
297        }
298      }
299    }
300    if (rtcp_sender_.TimeToSendRTCPReport())
301      rtcp_sender_.SendRTCP(kRtcpReport);
302  }
303
304  if (UpdateRTCPReceiveInformationTimers()) {
305    // A receiver has timed out
306    rtcp_receiver_.UpdateTMMBR();
307  }
308  return 0;
309}
310
311void ModuleRtpRtcpImpl::ProcessDeadOrAliveTimer() {
312  bool RTCPalive = false;
313  int64_t now = 0;
314  bool do_callback = false;
315
316  // Do operations on members under lock but avoid making the
317  // ProcessDeadOrAlive() callback under the same lock.
318  {
319    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
320    if (dead_or_alive_active_) {
321      now = clock_->TimeInMilliseconds();
322      if (now > dead_or_alive_timeout_ms_ + dead_or_alive_last_timer_) {
323        // RTCP is alive if we have received a report the last 12 seconds.
324        dead_or_alive_last_timer_ += dead_or_alive_timeout_ms_;
325
326        if (rtcp_receiver_.LastReceived() + 12000 > now)
327          RTCPalive = true;
328
329        do_callback = true;
330      }
331    }
332  }
333
334  if (do_callback)
335    rtp_receiver_->ProcessDeadOrAlive(RTCPalive, now);
336}
337
338int32_t ModuleRtpRtcpImpl::SetPeriodicDeadOrAliveStatus(
339    const bool enable,
340    const uint8_t sample_time_seconds) {
341  if (enable) {
342    WEBRTC_TRACE(kTraceModuleCall,
343                 kTraceRtpRtcp,
344                 id_,
345                 "SetPeriodicDeadOrAliveStatus(enable, %d)",
346                 sample_time_seconds);
347  } else {
348    WEBRTC_TRACE(kTraceModuleCall,
349                 kTraceRtpRtcp,
350                 id_,
351                 "SetPeriodicDeadOrAliveStatus(disable)");
352  }
353  if (sample_time_seconds == 0) {
354    return -1;
355  }
356  {
357    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
358    dead_or_alive_active_ = enable;
359    dead_or_alive_timeout_ms_ = sample_time_seconds * 1000;
360    // Trigger the first after one period.
361    dead_or_alive_last_timer_ = clock_->TimeInMilliseconds();
362  }
363  return 0;
364}
365
366int32_t ModuleRtpRtcpImpl::PeriodicDeadOrAliveStatus(
367    bool& enable,
368    uint8_t& sample_time_seconds) {
369  WEBRTC_TRACE(kTraceModuleCall,
370               kTraceRtpRtcp,
371               id_,
372               "PeriodicDeadOrAliveStatus()");
373
374  enable = dead_or_alive_active_;
375  sample_time_seconds =
376      static_cast<uint8_t>(dead_or_alive_timeout_ms_ / 1000);
377  return 0;
378}
379
380int32_t ModuleRtpRtcpImpl::SetPacketTimeout(
381    const uint32_t rtp_timeout_ms,
382    const uint32_t rtcp_timeout_ms) {
383  WEBRTC_TRACE(kTraceModuleCall,
384               kTraceRtpRtcp,
385               id_,
386               "SetPacketTimeout(%u,%u)",
387               rtp_timeout_ms,
388               rtcp_timeout_ms);
389
390  if (rtp_receiver_->SetPacketTimeout(rtp_timeout_ms) == 0) {
391    return rtcp_receiver_.SetPacketTimeout(rtcp_timeout_ms);
392  }
393  return -1;
394}
395
396int32_t ModuleRtpRtcpImpl::RegisterReceivePayload(
397    const CodecInst& voice_codec) {
398  WEBRTC_TRACE(kTraceModuleCall,
399               kTraceRtpRtcp,
400               id_,
401               "RegisterReceivePayload(voice_codec)");
402
403  return rtp_receiver_->RegisterReceivePayload(
404      voice_codec.plname,
405      voice_codec.pltype,
406      voice_codec.plfreq,
407      voice_codec.channels,
408      (voice_codec.rate < 0) ? 0 : voice_codec.rate);
409}
410
411int32_t ModuleRtpRtcpImpl::RegisterReceivePayload(
412    const VideoCodec& video_codec) {
413  WEBRTC_TRACE(kTraceModuleCall,
414               kTraceRtpRtcp,
415               id_,
416               "RegisterReceivePayload(video_codec)");
417
418  return rtp_receiver_->RegisterReceivePayload(video_codec.plName,
419                                               video_codec.plType,
420                                               90000,
421                                               0,
422                                               video_codec.maxBitrate);
423}
424
425int32_t ModuleRtpRtcpImpl::ReceivePayloadType(
426    const CodecInst& voice_codec,
427  int8_t* pl_type) {
428  WEBRTC_TRACE(kTraceModuleCall,
429               kTraceRtpRtcp,
430               id_,
431               "ReceivePayloadType(voice_codec)");
432
433  return rtp_receiver_->ReceivePayloadType(
434           voice_codec.plname,
435           voice_codec.plfreq,
436           voice_codec.channels,
437           (voice_codec.rate < 0) ? 0 : voice_codec.rate,
438           pl_type);
439}
440
441int32_t ModuleRtpRtcpImpl::ReceivePayloadType(
442    const VideoCodec& video_codec,
443  int8_t* pl_type) {
444  WEBRTC_TRACE(kTraceModuleCall,
445               kTraceRtpRtcp,
446               id_,
447               "ReceivePayloadType(video_codec)");
448
449  return rtp_receiver_->ReceivePayloadType(video_codec.plName,
450                                           90000,
451                                           0,
452                                           video_codec.maxBitrate,
453                                           pl_type);
454}
455
456int32_t ModuleRtpRtcpImpl::DeRegisterReceivePayload(
457    const int8_t payload_type) {
458  WEBRTC_TRACE(kTraceModuleCall,
459               kTraceRtpRtcp,
460               id_,
461               "DeRegisterReceivePayload(%d)",
462               payload_type);
463
464  return rtp_receiver_->DeRegisterReceivePayload(payload_type);
465}
466
467// Get the currently configured SSRC filter.
468int32_t ModuleRtpRtcpImpl::SSRCFilter(
469    uint32_t& allowed_ssrc) const {
470  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SSRCFilter()");
471
472  return rtp_receiver_->SSRCFilter(allowed_ssrc);
473}
474
475// Set a SSRC to be used as a filter for incoming RTP streams.
476int32_t ModuleRtpRtcpImpl::SetSSRCFilter(
477    const bool enable,
478    const uint32_t allowed_ssrc) {
479  if (enable) {
480    WEBRTC_TRACE(kTraceModuleCall,
481                 kTraceRtpRtcp,
482                 id_,
483                 "SetSSRCFilter(enable, 0x%x)",
484                 allowed_ssrc);
485  } else {
486    WEBRTC_TRACE(kTraceModuleCall,
487                 kTraceRtpRtcp,
488                 id_,
489                 "SetSSRCFilter(disable)");
490  }
491
492  return rtp_receiver_->SetSSRCFilter(enable, allowed_ssrc);
493}
494
495// Get last received remote timestamp.
496uint32_t ModuleRtpRtcpImpl::RemoteTimestamp() const {
497  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RemoteTimestamp()");
498
499  return rtp_receiver_->TimeStamp();
500}
501
502int64_t ModuleRtpRtcpImpl::LocalTimeOfRemoteTimeStamp() const {
503  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
504               "LocalTimeOfRemoteTimeStamp()");
505
506  return rtp_receiver_->LastReceivedTimeMs();
507}
508
509// Get the current estimated remote timestamp.
510int32_t ModuleRtpRtcpImpl::EstimatedRemoteTimeStamp(
511    uint32_t& timestamp) const {
512  WEBRTC_TRACE(kTraceModuleCall,
513               kTraceRtpRtcp,
514               id_,
515               "EstimatedRemoteTimeStamp()");
516
517  return rtp_receiver_->EstimatedRemoteTimeStamp(timestamp);
518}
519
520// Get incoming SSRC.
521uint32_t ModuleRtpRtcpImpl::RemoteSSRC() const {
522  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RemoteSSRC()");
523
524  return rtp_receiver_->SSRC();
525}
526
527// Get remote CSRC
528int32_t ModuleRtpRtcpImpl::RemoteCSRCs(
529    uint32_t arr_of_csrc[kRtpCsrcSize]) const {
530  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RemoteCSRCs()");
531
532  return rtp_receiver_->CSRCs(arr_of_csrc);
533}
534
535int32_t ModuleRtpRtcpImpl::SetRTXSendStatus(
536    const RtxMode mode,
537    const bool set_ssrc,
538    const uint32_t ssrc) {
539  rtp_sender_.SetRTXStatus(mode, set_ssrc, ssrc);
540  return 0;
541}
542
543int32_t ModuleRtpRtcpImpl::RTXSendStatus(RtxMode* mode, uint32_t* ssrc) const {
544  rtp_sender_.RTXStatus(mode, ssrc);
545  return 0;
546}
547
548int32_t ModuleRtpRtcpImpl::SetRTXReceiveStatus(
549    const bool enable,
550    const uint32_t ssrc) {
551  rtp_receiver_->SetRTXStatus(enable, ssrc);
552  return 0;
553}
554
555int32_t ModuleRtpRtcpImpl::RTXReceiveStatus(bool* enable,
556                                            uint32_t* ssrc) const {
557  rtp_receiver_->RTXStatus(enable, ssrc);
558  return 0;
559}
560
561// Called by the network module when we receive a packet.
562int32_t ModuleRtpRtcpImpl::IncomingPacket(
563    const uint8_t* incoming_packet,
564    const uint16_t incoming_packet_length) {
565  WEBRTC_TRACE(kTraceStream,
566               kTraceRtpRtcp,
567               id_,
568               "IncomingPacket(packet_length:%u)",
569               incoming_packet_length);
570  // Minimum RTP is 12 bytes.
571  // Minimum RTCP is 8 bytes (RTCP BYE).
572  if (incoming_packet_length < 8 || incoming_packet == NULL) {
573    WEBRTC_TRACE(kTraceDebug,
574                 kTraceRtpRtcp,
575                 id_,
576                 "IncomingPacket invalid buffer or length");
577    return -1;
578  }
579  // Check RTP version.
580  const uint8_t version = incoming_packet[0] >> 6;
581  if (version != 2) {
582    WEBRTC_TRACE(kTraceDebug,
583                 kTraceRtpRtcp,
584                 id_,
585                 "IncomingPacket invalid RTP version");
586    return -1;
587  }
588
589  ModuleRTPUtility::RTPHeaderParser rtp_parser(incoming_packet,
590                                               incoming_packet_length);
591
592  if (rtp_parser.RTCP()) {
593    // Allow receive of non-compound RTCP packets.
594    RTCPUtility::RTCPParserV2 rtcp_parser(incoming_packet,
595                                          incoming_packet_length,
596                                          true);
597
598    const bool valid_rtcpheader = rtcp_parser.IsValid();
599    if (!valid_rtcpheader) {
600      WEBRTC_TRACE(kTraceDebug,
601                   kTraceRtpRtcp,
602                   id_,
603                   "IncomingPacket invalid RTCP packet");
604      return -1;
605    }
606    RTCPHelp::RTCPPacketInformation rtcp_packet_information;
607    int32_t ret_val = rtcp_receiver_.IncomingRTCPPacket(
608        rtcp_packet_information, &rtcp_parser);
609    if (ret_val == 0) {
610      rtcp_receiver_.TriggerCallbacksFromRTCPPacket(rtcp_packet_information);
611    }
612    return ret_val;
613
614  } else {
615    WebRtcRTPHeader rtp_header;
616    memset(&rtp_header, 0, sizeof(rtp_header));
617
618    RtpHeaderExtensionMap map;
619    rtp_receiver_->GetHeaderExtensionMapCopy(&map);
620
621    const bool valid_rtpheader = rtp_parser.Parse(rtp_header, &map);
622    if (!valid_rtpheader) {
623      WEBRTC_TRACE(kTraceDebug,
624                   kTraceRtpRtcp,
625                   id_,
626                   "IncomingPacket invalid RTP header");
627      return -1;
628    }
629    return rtp_receiver_->IncomingRTPPacket(&rtp_header,
630                                            incoming_packet,
631                                            incoming_packet_length);
632  }
633}
634
635int32_t ModuleRtpRtcpImpl::RegisterSendPayload(
636    const CodecInst& voice_codec) {
637  WEBRTC_TRACE(kTraceModuleCall,
638               kTraceRtpRtcp,
639               id_,
640               "RegisterSendPayload(pl_name:%s pl_type:%d frequency:%u)",
641               voice_codec.plname,
642               voice_codec.pltype,
643               voice_codec.plfreq);
644
645  return rtp_sender_.RegisterPayload(
646           voice_codec.plname,
647           voice_codec.pltype,
648           voice_codec.plfreq,
649           voice_codec.channels,
650           (voice_codec.rate < 0) ? 0 : voice_codec.rate);
651}
652
653int32_t ModuleRtpRtcpImpl::RegisterSendPayload(
654    const VideoCodec& video_codec) {
655  WEBRTC_TRACE(kTraceModuleCall,
656               kTraceRtpRtcp,
657               id_,
658               "RegisterSendPayload(pl_name:%s pl_type:%d)",
659               video_codec.plName,
660               video_codec.plType);
661
662  send_video_codec_ = video_codec;
663  simulcast_ = (video_codec.numberOfSimulcastStreams > 1) ? true : false;
664  return rtp_sender_.RegisterPayload(video_codec.plName,
665                                     video_codec.plType,
666                                     90000,
667                                     0,
668                                     video_codec.maxBitrate);
669}
670
671int32_t ModuleRtpRtcpImpl::DeRegisterSendPayload(
672    const int8_t payload_type) {
673  WEBRTC_TRACE(kTraceModuleCall,
674               kTraceRtpRtcp,
675               id_,
676               "DeRegisterSendPayload(%d)", payload_type);
677
678  return rtp_sender_.DeRegisterSendPayload(payload_type);
679}
680
681int8_t ModuleRtpRtcpImpl::SendPayloadType() const {
682  return rtp_sender_.SendPayloadType();
683}
684
685uint32_t ModuleRtpRtcpImpl::StartTimestamp() const {
686  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "StartTimestamp()");
687
688  return rtp_sender_.StartTimestamp();
689}
690
691// Configure start timestamp, default is a random number.
692int32_t ModuleRtpRtcpImpl::SetStartTimestamp(
693    const uint32_t timestamp) {
694  WEBRTC_TRACE(kTraceModuleCall,
695               kTraceRtpRtcp,
696               id_,
697               "SetStartTimestamp(%d)",
698               timestamp);
699  rtcp_sender_.SetStartTimestamp(timestamp);
700  rtp_sender_.SetStartTimestamp(timestamp, true);
701  return 0;  // TODO(pwestin): change to void.
702}
703
704uint16_t ModuleRtpRtcpImpl::SequenceNumber() const {
705  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SequenceNumber()");
706
707  return rtp_sender_.SequenceNumber();
708}
709
710// Set SequenceNumber, default is a random number.
711int32_t ModuleRtpRtcpImpl::SetSequenceNumber(
712    const uint16_t seq_num) {
713  WEBRTC_TRACE(kTraceModuleCall,
714               kTraceRtpRtcp,
715               id_,
716               "SetSequenceNumber(%d)",
717               seq_num);
718
719  rtp_sender_.SetSequenceNumber(seq_num);
720  return 0;  // TODO(pwestin): change to void.
721}
722
723uint32_t ModuleRtpRtcpImpl::SSRC() const {
724  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SSRC()");
725
726  return rtp_sender_.SSRC();
727}
728
729// Configure SSRC, default is a random number.
730int32_t ModuleRtpRtcpImpl::SetSSRC(const uint32_t ssrc) {
731  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SetSSRC(%d)", ssrc);
732
733  rtp_sender_.SetSSRC(ssrc);
734  rtcp_receiver_.SetSSRC(ssrc);
735  rtcp_sender_.SetSSRC(ssrc);
736  return 0;  // TODO(pwestin): change to void.
737}
738
739int32_t ModuleRtpRtcpImpl::SetCSRCStatus(const bool include) {
740  rtcp_sender_.SetCSRCStatus(include);
741  rtp_sender_.SetCSRCStatus(include);
742  return 0;  // TODO(pwestin): change to void.
743}
744
745int32_t ModuleRtpRtcpImpl::CSRCs(
746  uint32_t arr_of_csrc[kRtpCsrcSize]) const {
747  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "CSRCs()");
748
749  return rtp_sender_.CSRCs(arr_of_csrc);
750}
751
752int32_t ModuleRtpRtcpImpl::SetCSRCs(
753    const uint32_t arr_of_csrc[kRtpCsrcSize],
754    const uint8_t arr_length) {
755  WEBRTC_TRACE(kTraceModuleCall,
756               kTraceRtpRtcp,
757               id_,
758               "SetCSRCs(arr_length:%d)",
759               arr_length);
760
761  const bool default_instance(child_modules_.empty() ? false : true);
762
763  if (default_instance) {
764    // For default we need to update all child modules too.
765    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
766
767    std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
768    while (it != child_modules_.end()) {
769      RtpRtcp* module = *it;
770      if (module) {
771        module->SetCSRCs(arr_of_csrc, arr_length);
772      }
773      it++;
774    }
775  } else {
776    for (int i = 0; i < arr_length; ++i) {
777      WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "\tidx:%d CSRC:%u", i,
778                   arr_of_csrc[i]);
779    }
780    rtcp_sender_.SetCSRCs(arr_of_csrc, arr_length);
781    rtp_sender_.SetCSRCs(arr_of_csrc, arr_length);
782  }
783  return 0;  // TODO(pwestin): change to void.
784}
785
786uint32_t ModuleRtpRtcpImpl::PacketCountSent() const {
787  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "PacketCountSent()");
788
789  return rtp_sender_.Packets();
790}
791
792uint32_t ModuleRtpRtcpImpl::ByteCountSent() const {
793  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "ByteCountSent()");
794
795  return rtp_sender_.Bytes();
796}
797
798int ModuleRtpRtcpImpl::CurrentSendFrequencyHz() const {
799  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
800               "CurrentSendFrequencyHz()");
801
802  return rtp_sender_.SendPayloadFrequency();
803}
804
805int32_t ModuleRtpRtcpImpl::SetSendingStatus(const bool sending) {
806  if (sending) {
807    WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
808                 "SetSendingStatus(sending)");
809  } else {
810    WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
811                 "SetSendingStatus(stopped)");
812  }
813  if (rtcp_sender_.Sending() != sending) {
814    // Sends RTCP BYE when going from true to false
815    if (rtcp_sender_.SetSendingStatus(sending) != 0) {
816      WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
817                   "Failed to send RTCP BYE");
818    }
819
820    collision_detected_ = false;
821
822    // Generate a new time_stamp if true and not configured via API
823    // Generate a new SSRC for the next "call" if false
824    rtp_sender_.SetSendingStatus(sending);
825    if (sending) {
826      // Make sure the RTCP sender has the same timestamp offset.
827      rtcp_sender_.SetStartTimestamp(rtp_sender_.StartTimestamp());
828    }
829
830    // Make sure that RTCP objects are aware of our SSRC (it could have changed
831    // Due to collision)
832    uint32_t SSRC = rtp_sender_.SSRC();
833    rtcp_receiver_.SetSSRC(SSRC);
834    rtcp_sender_.SetSSRC(SSRC);
835    return 0;
836  }
837  return 0;
838}
839
840bool ModuleRtpRtcpImpl::Sending() const {
841  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "Sending()");
842
843  return rtcp_sender_.Sending();
844}
845
846int32_t ModuleRtpRtcpImpl::SetSendingMediaStatus(const bool sending) {
847  if (sending) {
848    WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
849                 "SetSendingMediaStatus(sending)");
850  } else {
851    WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
852                 "SetSendingMediaStatus(stopped)");
853  }
854  rtp_sender_.SetSendingMediaStatus(sending);
855  return 0;
856}
857
858bool ModuleRtpRtcpImpl::SendingMedia() const {
859  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "Sending()");
860
861  const bool have_child_modules(child_modules_.empty() ? false : true);
862  if (!have_child_modules) {
863    return rtp_sender_.SendingMedia();
864  }
865
866  CriticalSectionScoped lock(critical_section_module_ptrs_.get());
867  std::list<ModuleRtpRtcpImpl*>::const_iterator it = child_modules_.begin();
868  while (it != child_modules_.end()) {
869    RTPSender& rtp_sender = (*it)->rtp_sender_;
870    if (rtp_sender.SendingMedia()) {
871      return true;
872    }
873    it++;
874  }
875  return false;
876}
877
878int32_t ModuleRtpRtcpImpl::SendOutgoingData(
879    FrameType frame_type,
880    int8_t payload_type,
881    uint32_t time_stamp,
882    int64_t capture_time_ms,
883    const uint8_t* payload_data,
884    uint32_t payload_size,
885    const RTPFragmentationHeader* fragmentation,
886    const RTPVideoHeader* rtp_video_hdr) {
887  WEBRTC_TRACE(
888    kTraceStream,
889    kTraceRtpRtcp,
890    id_,
891    "SendOutgoingData(frame_type:%d payload_type:%d time_stamp:%u size:%u)",
892    frame_type, payload_type, time_stamp, payload_size);
893
894  rtcp_sender_.SetLastRtpTime(time_stamp, capture_time_ms);
895
896  const bool have_child_modules(child_modules_.empty() ? false : true);
897  if (!have_child_modules) {
898    // Don't send RTCP from default module.
899    if (rtcp_sender_.TimeToSendRTCPReport(kVideoFrameKey == frame_type)) {
900      rtcp_sender_.SendRTCP(kRtcpReport);
901    }
902    return rtp_sender_.SendOutgoingData(frame_type,
903                                        payload_type,
904                                        time_stamp,
905                                        capture_time_ms,
906                                        payload_data,
907                                        payload_size,
908                                        fragmentation,
909                                        NULL,
910                                        &(rtp_video_hdr->codecHeader));
911  }
912  int32_t ret_val = -1;
913  if (simulcast_) {
914    if (rtp_video_hdr == NULL) {
915      return -1;
916    }
917    int idx = 0;
918    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
919    std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
920    for (; idx < rtp_video_hdr->simulcastIdx; ++it) {
921      if (it == child_modules_.end()) {
922        return -1;
923      }
924      if ((*it)->SendingMedia()) {
925        ++idx;
926      }
927    }
928    for (; it != child_modules_.end(); ++it) {
929      if ((*it)->SendingMedia()) {
930        break;
931      }
932      ++idx;
933    }
934    if (it == child_modules_.end()) {
935      return -1;
936    }
937    WEBRTC_TRACE(kTraceModuleCall,
938                 kTraceRtpRtcp,
939                 id_,
940                 "SendOutgoingData(SimulcastIdx:%u size:%u, ssrc:0x%x)",
941                 idx, payload_size, (*it)->rtp_sender_.SSRC());
942    return (*it)->SendOutgoingData(frame_type,
943                                   payload_type,
944                                   time_stamp,
945                                   capture_time_ms,
946                                   payload_data,
947                                   payload_size,
948                                   fragmentation,
949                                   rtp_video_hdr);
950  } else {
951    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
952
953    std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
954    if (it != child_modules_.end()) {
955      if ((*it)->SendingMedia()) {
956        ret_val = (*it)->SendOutgoingData(frame_type,
957                                          payload_type,
958                                          time_stamp,
959                                          capture_time_ms,
960                                          payload_data,
961                                          payload_size,
962                                          fragmentation,
963                                          rtp_video_hdr);
964      }
965      it++;
966    }
967    // Send to all remaining "child" modules
968    while (it != child_modules_.end()) {
969      if ((*it)->SendingMedia()) {
970        ret_val = (*it)->SendOutgoingData(frame_type,
971                                          payload_type,
972                                          time_stamp,
973                                          capture_time_ms,
974                                          payload_data,
975                                          payload_size,
976                                          fragmentation,
977                                          rtp_video_hdr);
978      }
979      it++;
980    }
981  }
982  return ret_val;
983}
984
985void ModuleRtpRtcpImpl::TimeToSendPacket(uint32_t ssrc,
986                                         uint16_t sequence_number,
987                                         int64_t capture_time_ms) {
988  WEBRTC_TRACE(
989    kTraceStream,
990    kTraceRtpRtcp,
991    id_,
992    "TimeToSendPacket(ssrc:0x%x sequence_number:%u capture_time_ms:%ll)",
993    ssrc, sequence_number, capture_time_ms);
994
995  if (simulcast_) {
996    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
997    std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
998    while (it != child_modules_.end()) {
999      if ((*it)->SendingMedia() && ssrc == (*it)->rtp_sender_.SSRC()) {
1000        (*it)->rtp_sender_.TimeToSendPacket(sequence_number, capture_time_ms);
1001        return;
1002      }
1003      ++it;
1004    }
1005  } else {
1006    bool have_child_modules = !child_modules_.empty();
1007    if (!have_child_modules) {
1008      // Don't send from default module.
1009      if (SendingMedia() && ssrc == rtp_sender_.SSRC()) {
1010        rtp_sender_.TimeToSendPacket(sequence_number, capture_time_ms);
1011      }
1012    } else {
1013      CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1014      std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1015      while (it != child_modules_.end()) {
1016        if ((*it)->SendingMedia() && ssrc == (*it)->rtp_sender_.SSRC()) {
1017          (*it)->rtp_sender_.TimeToSendPacket(sequence_number, capture_time_ms);
1018          return;
1019        }
1020        ++it;
1021      }
1022    }
1023  }
1024}
1025
1026uint16_t ModuleRtpRtcpImpl::MaxPayloadLength() const {
1027  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "MaxPayloadLength()");
1028
1029  return rtp_sender_.MaxPayloadLength();
1030}
1031
1032uint16_t ModuleRtpRtcpImpl::MaxDataPayloadLength() const {
1033  WEBRTC_TRACE(kTraceModuleCall,
1034               kTraceRtpRtcp,
1035               id_,
1036               "MaxDataPayloadLength()");
1037
1038  // Assuming IP/UDP.
1039  uint16_t min_data_payload_length = IP_PACKET_SIZE - 28;
1040
1041  const bool default_instance(child_modules_.empty() ? false : true);
1042  if (default_instance) {
1043    // For default we need to update all child modules too.
1044    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1045    std::list<ModuleRtpRtcpImpl*>::const_iterator it =
1046      child_modules_.begin();
1047    while (it != child_modules_.end()) {
1048      RtpRtcp* module = *it;
1049      if (module) {
1050        uint16_t data_payload_length =
1051          module->MaxDataPayloadLength();
1052        if (data_payload_length < min_data_payload_length) {
1053          min_data_payload_length = data_payload_length;
1054        }
1055      }
1056      it++;
1057    }
1058  }
1059
1060  uint16_t data_payload_length = rtp_sender_.MaxDataPayloadLength();
1061  if (data_payload_length < min_data_payload_length) {
1062    min_data_payload_length = data_payload_length;
1063  }
1064  return min_data_payload_length;
1065}
1066
1067int32_t ModuleRtpRtcpImpl::SetTransportOverhead(
1068    const bool tcp,
1069    const bool ipv6,
1070    const uint8_t authentication_overhead) {
1071  WEBRTC_TRACE(
1072    kTraceModuleCall,
1073    kTraceRtpRtcp,
1074    id_,
1075    "SetTransportOverhead(TCP:%d, IPV6:%d authentication_overhead:%u)",
1076    tcp, ipv6, authentication_overhead);
1077
1078  uint16_t packet_overhead = 0;
1079  if (ipv6) {
1080    packet_overhead = 40;
1081  } else {
1082    packet_overhead = 20;
1083  }
1084  if (tcp) {
1085    // TCP.
1086    packet_overhead += 20;
1087  } else {
1088    // UDP.
1089    packet_overhead += 8;
1090  }
1091  packet_overhead += authentication_overhead;
1092
1093  if (packet_overhead == packet_overhead_) {
1094    // Ok same as before.
1095    return 0;
1096  }
1097  // Calc diff.
1098  int16_t packet_over_head_diff = packet_overhead - packet_overhead_;
1099
1100  // Store new.
1101  packet_overhead_ = packet_overhead;
1102
1103  uint16_t length =
1104      rtp_sender_.MaxPayloadLength() - packet_over_head_diff;
1105  return rtp_sender_.SetMaxPayloadLength(length, packet_overhead_);
1106}
1107
1108int32_t ModuleRtpRtcpImpl::SetMaxTransferUnit(const uint16_t mtu) {
1109  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SetMaxTransferUnit(%u)",
1110               mtu);
1111
1112  if (mtu > IP_PACKET_SIZE) {
1113    WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
1114                 "Invalid in argument to SetMaxTransferUnit(%u)", mtu);
1115    return -1;
1116  }
1117  return rtp_sender_.SetMaxPayloadLength(mtu - packet_overhead_,
1118                                         packet_overhead_);
1119}
1120
1121RTCPMethod ModuleRtpRtcpImpl::RTCP() const {
1122  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RTCP()");
1123
1124  if (rtcp_sender_.Status() != kRtcpOff) {
1125    return rtcp_receiver_.Status();
1126  }
1127  return kRtcpOff;
1128}
1129
1130// Configure RTCP status i.e on/off.
1131int32_t ModuleRtpRtcpImpl::SetRTCPStatus(const RTCPMethod method) {
1132  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SetRTCPStatus(%d)",
1133               method);
1134
1135  if (rtcp_sender_.SetRTCPStatus(method) == 0) {
1136    return rtcp_receiver_.SetRTCPStatus(method);
1137  }
1138  return -1;
1139}
1140
1141// Only for internal test.
1142uint32_t ModuleRtpRtcpImpl::LastSendReport(
1143    uint32_t& last_rtcptime) {
1144  return rtcp_sender_.LastSendReport(last_rtcptime);
1145}
1146
1147int32_t ModuleRtpRtcpImpl::SetCNAME(const char c_name[RTCP_CNAME_SIZE]) {
1148  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SetCNAME(%s)", c_name);
1149  return rtcp_sender_.SetCNAME(c_name);
1150}
1151
1152int32_t ModuleRtpRtcpImpl::CNAME(char c_name[RTCP_CNAME_SIZE]) {
1153  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "CNAME()");
1154  return rtcp_sender_.CNAME(c_name);
1155}
1156
1157int32_t ModuleRtpRtcpImpl::AddMixedCNAME(
1158  const uint32_t ssrc,
1159  const char c_name[RTCP_CNAME_SIZE]) {
1160  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1161               "AddMixedCNAME(SSRC:%u)", ssrc);
1162
1163  return rtcp_sender_.AddMixedCNAME(ssrc, c_name);
1164}
1165
1166int32_t ModuleRtpRtcpImpl::RemoveMixedCNAME(const uint32_t ssrc) {
1167  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1168               "RemoveMixedCNAME(SSRC:%u)", ssrc);
1169  return rtcp_sender_.RemoveMixedCNAME(ssrc);
1170}
1171
1172int32_t ModuleRtpRtcpImpl::RemoteCNAME(
1173    const uint32_t remote_ssrc,
1174    char c_name[RTCP_CNAME_SIZE]) const {
1175  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1176               "RemoteCNAME(SSRC:%u)", remote_ssrc);
1177
1178  return rtcp_receiver_.CNAME(remote_ssrc, c_name);
1179}
1180
1181uint16_t ModuleRtpRtcpImpl::RemoteSequenceNumber() const {
1182  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RemoteSequenceNumber()");
1183
1184  return rtp_receiver_->SequenceNumber();
1185}
1186
1187int32_t ModuleRtpRtcpImpl::RemoteNTP(
1188    uint32_t* received_ntpsecs,
1189    uint32_t* received_ntpfrac,
1190    uint32_t* rtcp_arrival_time_secs,
1191    uint32_t* rtcp_arrival_time_frac,
1192    uint32_t* rtcp_timestamp) const {
1193  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RemoteNTP()");
1194
1195  return rtcp_receiver_.NTP(received_ntpsecs,
1196                            received_ntpfrac,
1197                            rtcp_arrival_time_secs,
1198                            rtcp_arrival_time_frac,
1199                            rtcp_timestamp);
1200}
1201
1202// Get RoundTripTime.
1203int32_t ModuleRtpRtcpImpl::RTT(const uint32_t remote_ssrc,
1204                               uint16_t* rtt,
1205                               uint16_t* avg_rtt,
1206                               uint16_t* min_rtt,
1207                               uint16_t* max_rtt) const {
1208  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RTT()");
1209
1210  return rtcp_receiver_.RTT(remote_ssrc, rtt, avg_rtt, min_rtt, max_rtt);
1211}
1212
1213// Reset RoundTripTime statistics.
1214int32_t ModuleRtpRtcpImpl::ResetRTT(const uint32_t remote_ssrc) {
1215  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "ResetRTT(SSRC:%u)",
1216               remote_ssrc);
1217
1218  return rtcp_receiver_.ResetRTT(remote_ssrc);
1219}
1220
1221void ModuleRtpRtcpImpl:: SetRtt(uint32_t rtt) {
1222  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SetRtt(rtt: %u)", rtt);
1223  rtcp_receiver_.SetRTT(static_cast<uint16_t>(rtt));
1224}
1225
1226// Reset RTP statistics.
1227int32_t ModuleRtpRtcpImpl::ResetStatisticsRTP() {
1228  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "ResetStatisticsRTP()");
1229
1230  return rtp_receiver_->ResetStatistics();
1231}
1232
1233// Reset RTP data counters for the receiving side.
1234int32_t ModuleRtpRtcpImpl::ResetReceiveDataCountersRTP() {
1235  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1236               "ResetReceiveDataCountersRTP()");
1237
1238  return rtp_receiver_->ResetDataCounters();
1239}
1240
1241// Reset RTP data counters for the sending side.
1242int32_t ModuleRtpRtcpImpl::ResetSendDataCountersRTP() {
1243  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1244               "ResetSendDataCountersRTP()");
1245
1246  rtp_sender_.ResetDataCounters();
1247  return 0;  // TODO(pwestin): change to void.
1248}
1249
1250// Force a send of an RTCP packet.
1251// Normal SR and RR are triggered via the process function.
1252int32_t ModuleRtpRtcpImpl::SendRTCP(uint32_t rtcp_packet_type) {
1253  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SendRTCP(0x%x)",
1254               rtcp_packet_type);
1255
1256  return  rtcp_sender_.SendRTCP(rtcp_packet_type);
1257}
1258
1259int32_t ModuleRtpRtcpImpl::SetRTCPApplicationSpecificData(
1260    const uint8_t sub_type,
1261    const uint32_t name,
1262    const uint8_t* data,
1263    const uint16_t length) {
1264  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1265               "SetRTCPApplicationSpecificData(sub_type:%d name:0x%x)",
1266               sub_type, name);
1267
1268  return  rtcp_sender_.SetApplicationSpecificData(sub_type, name, data, length);
1269}
1270
1271// (XR) VOIP metric.
1272int32_t ModuleRtpRtcpImpl::SetRTCPVoIPMetrics(
1273  const RTCPVoIPMetric* voip_metric) {
1274  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SetRTCPVoIPMetrics()");
1275
1276  return  rtcp_sender_.SetRTCPVoIPMetrics(voip_metric);
1277}
1278
1279// Our locally created statistics of the received RTP stream.
1280int32_t ModuleRtpRtcpImpl::StatisticsRTP(
1281    uint8_t*  fraction_lost,
1282    uint32_t* cum_lost,
1283    uint32_t* ext_max,
1284    uint32_t* jitter,
1285    uint32_t* max_jitter) const {
1286  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "StatisticsRTP()");
1287
1288  uint32_t jitter_transmission_time_offset = 0;
1289
1290  int32_t ret_val = rtp_receiver_->Statistics(
1291      fraction_lost, cum_lost, ext_max, jitter, max_jitter,
1292      &jitter_transmission_time_offset, (rtcp_sender_.Status() == kRtcpOff));
1293  if (ret_val == -1) {
1294    WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
1295                 "StatisticsRTP() no statistics available");
1296  }
1297  return ret_val;
1298}
1299
1300int32_t ModuleRtpRtcpImpl::DataCountersRTP(
1301    uint32_t* bytes_sent,
1302    uint32_t* packets_sent,
1303    uint32_t* bytes_received,
1304    uint32_t* packets_received) const {
1305  WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_, "DataCountersRTP()");
1306
1307  if (bytes_sent) {
1308    *bytes_sent = rtp_sender_.Bytes();
1309  }
1310  if (packets_sent) {
1311    *packets_sent = rtp_sender_.Packets();
1312  }
1313  return rtp_receiver_->DataCounters(bytes_received, packets_received);
1314}
1315
1316int32_t ModuleRtpRtcpImpl::ReportBlockStatistics(
1317    uint8_t* fraction_lost,
1318    uint32_t* cum_lost,
1319    uint32_t* ext_max,
1320    uint32_t* jitter,
1321    uint32_t* jitter_transmission_time_offset) {
1322  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "ReportBlockStatistics()");
1323  int32_t missing = 0;
1324  int32_t ret = rtp_receiver_->Statistics(fraction_lost,
1325                                          cum_lost,
1326                                          ext_max,
1327                                          jitter,
1328                                          NULL,
1329                                          jitter_transmission_time_offset,
1330                                          &missing,
1331                                                true);
1332
1333#ifdef MATLAB
1334  if (plot1_ == NULL) {
1335    plot1_ = eng.NewPlot(new MatlabPlot());
1336    plot1_->AddTimeLine(30, "b", "lost", clock_->TimeInMilliseconds());
1337  }
1338  plot1_->Append("lost", missing);
1339  plot1_->Plot();
1340#endif
1341
1342  return ret;
1343}
1344
1345int32_t ModuleRtpRtcpImpl::RemoteRTCPStat(RTCPSenderInfo* sender_info) {
1346  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RemoteRTCPStat()");
1347
1348  return rtcp_receiver_.SenderInfoReceived(sender_info);
1349}
1350
1351// Received RTCP report.
1352int32_t ModuleRtpRtcpImpl::RemoteRTCPStat(
1353    std::vector<RTCPReportBlock>* receive_blocks) const {
1354  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RemoteRTCPStat()");
1355
1356  return rtcp_receiver_.StatisticsReceived(receive_blocks);
1357}
1358
1359int32_t ModuleRtpRtcpImpl::AddRTCPReportBlock(
1360    const uint32_t ssrc,
1361    const RTCPReportBlock* report_block) {
1362  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "AddRTCPReportBlock()");
1363
1364  return rtcp_sender_.AddReportBlock(ssrc, report_block);
1365}
1366
1367int32_t ModuleRtpRtcpImpl::RemoveRTCPReportBlock(
1368  const uint32_t ssrc) {
1369  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "RemoveRTCPReportBlock()");
1370
1371  return rtcp_sender_.RemoveReportBlock(ssrc);
1372}
1373
1374// (REMB) Receiver Estimated Max Bitrate.
1375bool ModuleRtpRtcpImpl::REMB() const {
1376  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "REMB()");
1377
1378  return rtcp_sender_.REMB();
1379}
1380
1381int32_t ModuleRtpRtcpImpl::SetREMBStatus(const bool enable) {
1382  if (enable) {
1383    WEBRTC_TRACE(kTraceModuleCall,
1384                 kTraceRtpRtcp,
1385                 id_,
1386                 "SetREMBStatus(enable)");
1387  } else {
1388    WEBRTC_TRACE(kTraceModuleCall,
1389                 kTraceRtpRtcp,
1390                 id_,
1391                 "SetREMBStatus(disable)");
1392  }
1393  return rtcp_sender_.SetREMBStatus(enable);
1394}
1395
1396int32_t ModuleRtpRtcpImpl::SetREMBData(const uint32_t bitrate,
1397                                       const uint8_t number_of_ssrc,
1398                                       const uint32_t* ssrc) {
1399  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1400               "SetREMBData(bitrate:%d,?,?)", bitrate);
1401  return rtcp_sender_.SetREMBData(bitrate, number_of_ssrc, ssrc);
1402}
1403
1404// (IJ) Extended jitter report.
1405bool ModuleRtpRtcpImpl::IJ() const {
1406  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "IJ()");
1407
1408  return rtcp_sender_.IJ();
1409}
1410
1411int32_t ModuleRtpRtcpImpl::SetIJStatus(const bool enable) {
1412  WEBRTC_TRACE(kTraceModuleCall,
1413               kTraceRtpRtcp,
1414               id_,
1415               "SetIJStatus(%s)", enable ? "true" : "false");
1416
1417  return rtcp_sender_.SetIJStatus(enable);
1418}
1419
1420int32_t ModuleRtpRtcpImpl::RegisterSendRtpHeaderExtension(
1421    const RTPExtensionType type,
1422    const uint8_t id) {
1423  return rtp_sender_.RegisterRtpHeaderExtension(type, id);
1424}
1425
1426int32_t ModuleRtpRtcpImpl::DeregisterSendRtpHeaderExtension(
1427    const RTPExtensionType type) {
1428  return rtp_sender_.DeregisterRtpHeaderExtension(type);
1429}
1430
1431int32_t ModuleRtpRtcpImpl::RegisterReceiveRtpHeaderExtension(
1432    const RTPExtensionType type,
1433    const uint8_t id) {
1434  return rtp_receiver_->RegisterRtpHeaderExtension(type, id);
1435}
1436
1437int32_t ModuleRtpRtcpImpl::DeregisterReceiveRtpHeaderExtension(
1438  const RTPExtensionType type) {
1439  return rtp_receiver_->DeregisterRtpHeaderExtension(type);
1440}
1441
1442// (TMMBR) Temporary Max Media Bit Rate.
1443bool ModuleRtpRtcpImpl::TMMBR() const {
1444  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "TMMBR()");
1445
1446  return rtcp_sender_.TMMBR();
1447}
1448
1449int32_t ModuleRtpRtcpImpl::SetTMMBRStatus(const bool enable) {
1450  if (enable) {
1451    WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1452                 "SetTMMBRStatus(enable)");
1453  } else {
1454    WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1455                 "SetTMMBRStatus(disable)");
1456  }
1457  return rtcp_sender_.SetTMMBRStatus(enable);
1458}
1459
1460int32_t ModuleRtpRtcpImpl::SetTMMBN(const TMMBRSet* bounding_set) {
1461  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SetTMMBN()");
1462
1463  uint32_t max_bitrate_kbit =
1464      rtp_sender_.MaxConfiguredBitrateVideo() / 1000;
1465  return rtcp_sender_.SetTMMBN(bounding_set, max_bitrate_kbit);
1466}
1467
1468// (NACK) Negative acknowledgment.
1469
1470// Is Negative acknowledgment requests on/off?
1471NACKMethod ModuleRtpRtcpImpl::NACK() const {
1472  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "NACK()");
1473
1474  NACKMethod child_method = kNackOff;
1475  const bool default_instance(child_modules_.empty() ? false : true);
1476  if (default_instance) {
1477    // For default we need to check all child modules too.
1478    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1479    std::list<ModuleRtpRtcpImpl*>::const_iterator it =
1480      child_modules_.begin();
1481    while (it != child_modules_.end()) {
1482      RtpRtcp* module = *it;
1483      if (module) {
1484        NACKMethod nackMethod = module->NACK();
1485        if (nackMethod != kNackOff) {
1486          child_method = nackMethod;
1487          break;
1488        }
1489      }
1490      it++;
1491    }
1492  }
1493
1494  NACKMethod method = nack_method_;
1495  if (child_method != kNackOff) {
1496    method = child_method;
1497  }
1498  return method;
1499}
1500
1501// Turn negative acknowledgment requests on/off.
1502int32_t ModuleRtpRtcpImpl::SetNACKStatus(
1503    NACKMethod method, int max_reordering_threshold) {
1504  WEBRTC_TRACE(kTraceModuleCall,
1505               kTraceRtpRtcp,
1506               id_,
1507               "SetNACKStatus(%u)", method);
1508
1509  nack_method_ = method;
1510  rtp_receiver_->SetNACKStatus(method, max_reordering_threshold);
1511  return 0;
1512}
1513
1514// Returns the currently configured retransmission mode.
1515int ModuleRtpRtcpImpl::SelectiveRetransmissions() const {
1516  WEBRTC_TRACE(kTraceModuleCall,
1517               kTraceRtpRtcp,
1518               id_,
1519               "SelectiveRetransmissions()");
1520  return rtp_sender_.SelectiveRetransmissions();
1521}
1522
1523// Enable or disable a retransmission mode, which decides which packets will
1524// be retransmitted if NACKed.
1525int ModuleRtpRtcpImpl::SetSelectiveRetransmissions(uint8_t settings) {
1526  WEBRTC_TRACE(kTraceModuleCall,
1527               kTraceRtpRtcp,
1528               id_,
1529               "SetSelectiveRetransmissions(%u)",
1530               settings);
1531  return rtp_sender_.SetSelectiveRetransmissions(settings);
1532}
1533
1534// Send a Negative acknowledgment packet.
1535int32_t ModuleRtpRtcpImpl::SendNACK(const uint16_t* nack_list,
1536                                    const uint16_t size) {
1537  WEBRTC_TRACE(kTraceModuleCall,
1538               kTraceRtpRtcp,
1539               id_,
1540               "SendNACK(size:%u)", size);
1541
1542  uint16_t avg_rtt = 0;
1543  rtcp_receiver_.RTT(rtp_receiver_->SSRC(), NULL, &avg_rtt, NULL, NULL);
1544
1545  int64_t wait_time = 5 + ((avg_rtt * 3) >> 1);  // 5 + RTT * 1.5.
1546  if (wait_time == 5) {
1547    wait_time = 100;  // During startup we don't have an RTT.
1548  }
1549  const int64_t now = clock_->TimeInMilliseconds();
1550  const int64_t time_limit = now - wait_time;
1551  uint16_t nackLength = size;
1552  uint16_t start_id = 0;
1553
1554  if (nack_last_time_sent_full_ < time_limit) {
1555    // Send list. Set the timer to make sure we only send a full NACK list once
1556    // within every time_limit.
1557    nack_last_time_sent_full_ = now;
1558  } else {
1559    // Only send if extended list.
1560    if (nack_last_seq_number_sent_ == nack_list[size - 1]) {
1561      // Last seq num is the same don't send list.
1562      return 0;
1563    } else {
1564      // Send NACKs only for new sequence numbers to avoid re-sending
1565      // NACKs for sequences we have already sent.
1566      for (int i = 0; i < size; ++i)  {
1567        if (nack_last_seq_number_sent_ == nack_list[i]) {
1568          start_id = i + 1;
1569          break;
1570        }
1571      }
1572      nackLength = size - start_id;
1573    }
1574  }
1575  // Our RTCP NACK implementation is limited to kRtcpMaxNackFields sequence
1576  // numbers per RTCP packet.
1577  if (nackLength > kRtcpMaxNackFields) {
1578    nackLength = kRtcpMaxNackFields;
1579  }
1580  nack_last_seq_number_sent_ = nack_list[start_id + nackLength - 1];
1581
1582  switch (nack_method_) {
1583    case kNackRtcp:
1584      return rtcp_sender_.SendRTCP(kRtcpNack, nackLength, &nack_list[start_id]);
1585    case kNackOff:
1586      return -1;
1587  };
1588  return -1;
1589}
1590
1591// Store the sent packets, needed to answer to a Negative acknowledgment
1592// requests.
1593int32_t ModuleRtpRtcpImpl::SetStorePacketsStatus(
1594    const bool enable,
1595    const uint16_t number_to_store) {
1596  if (enable) {
1597    WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1598                 "SetStorePacketsStatus(enable, number_to_store:%d)",
1599                 number_to_store);
1600  } else {
1601    WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1602                 "SetStorePacketsStatus(disable)");
1603  }
1604  rtp_sender_.SetStorePacketsStatus(enable, number_to_store);
1605  return 0;  // TODO(pwestin): change to void.
1606}
1607
1608// Forward DTMFs to decoder for playout.
1609int ModuleRtpRtcpImpl::SetTelephoneEventForwardToDecoder(
1610    bool forward_to_decoder) {
1611  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1612               "SetTelephoneEventForwardToDecoder(forward_to_decoder:%d)",
1613               forward_to_decoder);
1614
1615  assert(audio_);
1616  assert(rtp_telephone_event_handler_);
1617  return rtp_telephone_event_handler_->SetTelephoneEventForwardToDecoder(
1618      forward_to_decoder);
1619}
1620
1621// Is forwarding of out-band telephone events turned on/off?
1622bool ModuleRtpRtcpImpl::TelephoneEventForwardToDecoder() const {
1623  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1624               "TelephoneEventForwardToDecoder()");
1625
1626  assert(audio_);
1627  assert(rtp_telephone_event_handler_);
1628  return rtp_telephone_event_handler_->TelephoneEventForwardToDecoder();
1629}
1630
1631// Send a TelephoneEvent tone using RFC 2833 (4733).
1632int32_t ModuleRtpRtcpImpl::SendTelephoneEventOutband(
1633    const uint8_t key,
1634    const uint16_t time_ms,
1635    const uint8_t level) {
1636  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1637               "SendTelephoneEventOutband(key:%u, time_ms:%u, level:%u)", key,
1638               time_ms, level);
1639
1640  return rtp_sender_.SendTelephoneEvent(key, time_ms, level);
1641}
1642
1643bool ModuleRtpRtcpImpl::SendTelephoneEventActive(
1644    int8_t& telephone_event) const {
1645
1646  WEBRTC_TRACE(kTraceModuleCall,
1647               kTraceRtpRtcp,
1648               id_,
1649               "SendTelephoneEventActive()");
1650
1651  return rtp_sender_.SendTelephoneEventActive(&telephone_event);
1652}
1653
1654// Set audio packet size, used to determine when it's time to send a DTMF
1655// packet in silence (CNG).
1656int32_t ModuleRtpRtcpImpl::SetAudioPacketSize(
1657    const uint16_t packet_size_samples) {
1658
1659  WEBRTC_TRACE(kTraceModuleCall,
1660               kTraceRtpRtcp,
1661               id_,
1662               "SetAudioPacketSize(%u)",
1663               packet_size_samples);
1664
1665  return rtp_sender_.SetAudioPacketSize(packet_size_samples);
1666}
1667
1668int32_t ModuleRtpRtcpImpl::SetRTPAudioLevelIndicationStatus(
1669    const bool enable,
1670    const uint8_t id) {
1671
1672  WEBRTC_TRACE(kTraceModuleCall,
1673               kTraceRtpRtcp,
1674               id_,
1675               "SetRTPAudioLevelIndicationStatus(enable=%d, ID=%u)",
1676               enable,
1677               id);
1678
1679  if (enable) {
1680    rtp_receiver_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel, id);
1681  } else {
1682    rtp_receiver_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
1683  }
1684  return rtp_sender_.SetAudioLevelIndicationStatus(enable, id);
1685}
1686
1687int32_t ModuleRtpRtcpImpl::GetRTPAudioLevelIndicationStatus(
1688    bool& enable,
1689    uint8_t& id) const {
1690
1691  WEBRTC_TRACE(kTraceModuleCall,
1692               kTraceRtpRtcp,
1693               id_,
1694               "GetRTPAudioLevelIndicationStatus()");
1695  return rtp_sender_.AudioLevelIndicationStatus(&enable, &id);
1696}
1697
1698int32_t ModuleRtpRtcpImpl::SetAudioLevel(
1699    const uint8_t level_d_bov) {
1700  WEBRTC_TRACE(kTraceModuleCall,
1701               kTraceRtpRtcp,
1702               id_,
1703               "SetAudioLevel(level_d_bov:%u)",
1704               level_d_bov);
1705  return rtp_sender_.SetAudioLevel(level_d_bov);
1706}
1707
1708// Set payload type for Redundant Audio Data RFC 2198.
1709int32_t ModuleRtpRtcpImpl::SetSendREDPayloadType(
1710    const int8_t payload_type) {
1711  WEBRTC_TRACE(kTraceModuleCall,
1712               kTraceRtpRtcp,
1713               id_,
1714               "SetSendREDPayloadType(%d)",
1715               payload_type);
1716
1717  return rtp_sender_.SetRED(payload_type);
1718}
1719
1720// Get payload type for Redundant Audio Data RFC 2198.
1721int32_t ModuleRtpRtcpImpl::SendREDPayloadType(
1722    int8_t& payload_type) const {
1723  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "SendREDPayloadType()");
1724
1725  return rtp_sender_.RED(&payload_type);
1726}
1727
1728RtpVideoCodecTypes ModuleRtpRtcpImpl::ReceivedVideoCodec() const {
1729  return rtp_receiver_->VideoCodecType();
1730}
1731
1732RtpVideoCodecTypes ModuleRtpRtcpImpl::SendVideoCodec() const {
1733  return rtp_sender_.VideoCodecType();
1734}
1735
1736void ModuleRtpRtcpImpl::SetTargetSendBitrate(const uint32_t bitrate) {
1737  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_,
1738               "SetTargetSendBitrate: %ubit", bitrate);
1739
1740  const bool have_child_modules(child_modules_.empty() ? false : true);
1741  if (have_child_modules) {
1742    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1743    if (simulcast_) {
1744      uint32_t bitrate_remainder = bitrate;
1745      std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1746      for (int i = 0; it != child_modules_.end() &&
1747           i < send_video_codec_.numberOfSimulcastStreams; ++it) {
1748        if ((*it)->SendingMedia()) {
1749          RTPSender& rtp_sender = (*it)->rtp_sender_;
1750          if (send_video_codec_.simulcastStream[i].maxBitrate * 1000 >
1751              bitrate_remainder) {
1752            rtp_sender.SetTargetSendBitrate(bitrate_remainder);
1753            bitrate_remainder = 0;
1754          } else {
1755            rtp_sender.SetTargetSendBitrate(
1756              send_video_codec_.simulcastStream[i].maxBitrate * 1000);
1757            bitrate_remainder -=
1758              send_video_codec_.simulcastStream[i].maxBitrate * 1000;
1759          }
1760          ++i;
1761        }
1762      }
1763    } else {
1764      std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1765      for (; it != child_modules_.end(); ++it) {
1766        RTPSender& rtp_sender = (*it)->rtp_sender_;
1767        rtp_sender.SetTargetSendBitrate(bitrate);
1768      }
1769    }
1770  } else {
1771    rtp_sender_.SetTargetSendBitrate(bitrate);
1772  }
1773}
1774
1775int32_t ModuleRtpRtcpImpl::SetKeyFrameRequestMethod(
1776    const KeyFrameRequestMethod method) {
1777  WEBRTC_TRACE(kTraceModuleCall,
1778               kTraceRtpRtcp,
1779               id_,
1780               "SetKeyFrameRequestMethod(method:%u)",
1781               method);
1782
1783  key_frame_req_method_ = method;
1784  return 0;
1785}
1786
1787int32_t ModuleRtpRtcpImpl::RequestKeyFrame() {
1788  WEBRTC_TRACE(kTraceModuleCall,
1789               kTraceRtpRtcp,
1790               id_,
1791               "RequestKeyFrame");
1792
1793  switch (key_frame_req_method_) {
1794    case kKeyFrameReqFirRtp:
1795      return rtp_sender_.SendRTPIntraRequest();
1796    case kKeyFrameReqPliRtcp:
1797      return rtcp_sender_.SendRTCP(kRtcpPli);
1798    case kKeyFrameReqFirRtcp:
1799      return rtcp_sender_.SendRTCP(kRtcpFir);
1800  }
1801  return -1;
1802}
1803
1804int32_t ModuleRtpRtcpImpl::SendRTCPSliceLossIndication(
1805    const uint8_t picture_id) {
1806  WEBRTC_TRACE(kTraceModuleCall,
1807               kTraceRtpRtcp,
1808               id_,
1809               "SendRTCPSliceLossIndication (picture_id:%d)",
1810               picture_id);
1811  return rtcp_sender_.SendRTCP(kRtcpSli, 0, 0, false, picture_id);
1812}
1813
1814int32_t ModuleRtpRtcpImpl::SetCameraDelay(const int32_t delay_ms) {
1815  WEBRTC_TRACE(kTraceModuleCall,
1816               kTraceRtpRtcp,
1817               id_,
1818               "SetCameraDelay(%d)",
1819               delay_ms);
1820  const bool default_instance(child_modules_.empty() ? false : true);
1821
1822  if (default_instance) {
1823    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1824
1825    std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1826    while (it != child_modules_.end()) {
1827      RtpRtcp* module = *it;
1828      if (module) {
1829        module->SetCameraDelay(delay_ms);
1830      }
1831      it++;
1832    }
1833    return 0;
1834  }
1835  return rtcp_sender_.SetCameraDelay(delay_ms);
1836}
1837
1838int32_t ModuleRtpRtcpImpl::SetGenericFECStatus(
1839    const bool enable,
1840    const uint8_t payload_type_red,
1841    const uint8_t payload_type_fec) {
1842  if (enable) {
1843    WEBRTC_TRACE(kTraceModuleCall,
1844                 kTraceRtpRtcp,
1845                 id_,
1846                 "SetGenericFECStatus(enable, %u)",
1847                 payload_type_red);
1848  } else {
1849    WEBRTC_TRACE(kTraceModuleCall,
1850                 kTraceRtpRtcp,
1851                 id_,
1852                 "SetGenericFECStatus(disable)");
1853  }
1854  return rtp_sender_.SetGenericFECStatus(enable,
1855                                         payload_type_red,
1856                                         payload_type_fec);
1857}
1858
1859int32_t ModuleRtpRtcpImpl::GenericFECStatus(
1860    bool& enable,
1861    uint8_t& payload_type_red,
1862    uint8_t& payload_type_fec) {
1863
1864  WEBRTC_TRACE(kTraceModuleCall, kTraceRtpRtcp, id_, "GenericFECStatus()");
1865
1866  bool child_enabled = false;
1867  const bool default_instance(child_modules_.empty() ? false : true);
1868  if (default_instance) {
1869    // For default we need to check all child modules too.
1870    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1871    std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1872    while (it != child_modules_.end()) {
1873      RtpRtcp* module = *it;
1874      if (module)  {
1875        bool enabled = false;
1876        uint8_t dummy_ptype_red = 0;
1877        uint8_t dummy_ptype_fec = 0;
1878        if (module->GenericFECStatus(enabled,
1879                                     dummy_ptype_red,
1880                                     dummy_ptype_fec) == 0 && enabled) {
1881          child_enabled = true;
1882          break;
1883        }
1884      }
1885      it++;
1886    }
1887  }
1888  int32_t ret_val = rtp_sender_.GenericFECStatus(&enable,
1889                                                 &payload_type_red,
1890                                                 &payload_type_fec);
1891  if (child_enabled) {
1892    // Returns true if enabled for any child module.
1893    enable = child_enabled;
1894  }
1895  return ret_val;
1896}
1897
1898int32_t ModuleRtpRtcpImpl::SetFecParameters(
1899    const FecProtectionParams* delta_params,
1900    const FecProtectionParams* key_params) {
1901  const bool default_instance(child_modules_.empty() ? false : true);
1902  if (default_instance)  {
1903    // For default we need to update all child modules too.
1904    CriticalSectionScoped lock(critical_section_module_ptrs_.get());
1905
1906    std::list<ModuleRtpRtcpImpl*>::iterator it = child_modules_.begin();
1907    while (it != child_modules_.end()) {
1908      RtpRtcp* module = *it;
1909      if (module) {
1910        module->SetFecParameters(delta_params, key_params);
1911      }
1912      it++;
1913    }
1914    return 0;
1915  }
1916  return rtp_sender_.SetFecParameters(delta_params, key_params);
1917}
1918
1919void ModuleRtpRtcpImpl::SetRemoteSSRC(const uint32_t ssrc) {
1920  // Inform about the incoming SSRC.
1921  rtcp_sender_.SetRemoteSSRC(ssrc);
1922  rtcp_receiver_.SetRemoteSSRC(ssrc);
1923
1924  // Check for a SSRC collision.
1925  if (rtp_sender_.SSRC() == ssrc && !collision_detected_) {
1926    // If we detect a collision change the SSRC but only once.
1927    collision_detected_ = true;
1928    uint32_t new_ssrc = rtp_sender_.GenerateNewSSRC();
1929    if (new_ssrc == 0) {
1930      // Configured via API ignore.
1931      return;
1932    }
1933    if (kRtcpOff != rtcp_sender_.Status()) {
1934      // Send RTCP bye on the current SSRC.
1935      rtcp_sender_.SendRTCP(kRtcpBye);
1936    }
1937    // Change local SSRC and inform all objects about the new SSRC.
1938    rtcp_sender_.SetSSRC(new_ssrc);
1939    rtcp_receiver_.SetSSRC(new_ssrc);
1940  }
1941}
1942
1943uint32_t ModuleRtpRtcpImpl::BitrateReceivedNow() const {
1944  return rtp_receiver_->BitrateNow();
1945}
1946
1947void ModuleRtpRtcpImpl::BitrateSent(uint32_t* total_rate,
1948                                    uint32_t* video_rate,
1949                                    uint32_t* fec_rate,
1950                                    uint32_t* nack_rate) const {
1951  const bool default_instance(child_modules_.empty() ? false : true);
1952
1953  if (default_instance) {
1954    // For default we need to update the send bitrate.
1955    CriticalSectionScoped lock(critical_section_module_ptrs_feedback_.get());
1956
1957    if (total_rate != NULL)
1958      *total_rate = 0;
1959    if (video_rate != NULL)
1960      *video_rate = 0;
1961    if (fec_rate != NULL)
1962      *fec_rate = 0;
1963    if (nack_rate != NULL)
1964      *nack_rate = 0;
1965
1966    std::list<ModuleRtpRtcpImpl*>::const_iterator it =
1967      child_modules_.begin();
1968    while (it != child_modules_.end()) {
1969      RtpRtcp* module = *it;
1970      if (module) {
1971        uint32_t child_total_rate = 0;
1972        uint32_t child_video_rate = 0;
1973        uint32_t child_fec_rate = 0;
1974        uint32_t child_nack_rate = 0;
1975        module->BitrateSent(&child_total_rate,
1976                            &child_video_rate,
1977                            &child_fec_rate,
1978                            &child_nack_rate);
1979        if (total_rate != NULL && child_total_rate > *total_rate)
1980          *total_rate = child_total_rate;
1981        if (video_rate != NULL && child_video_rate > *video_rate)
1982          *video_rate = child_video_rate;
1983        if (fec_rate != NULL && child_fec_rate > *fec_rate)
1984          *fec_rate = child_fec_rate;
1985        if (nack_rate != NULL && child_nack_rate > *nack_rate)
1986          *nack_rate = child_nack_rate;
1987      }
1988      it++;
1989    }
1990    return;
1991  }
1992  if (total_rate != NULL)
1993    *total_rate = rtp_sender_.BitrateLast();
1994  if (video_rate != NULL)
1995    *video_rate = rtp_sender_.VideoBitrateSent();
1996  if (fec_rate != NULL)
1997    *fec_rate = rtp_sender_.FecOverheadRate();
1998  if (nack_rate != NULL)
1999    *nack_rate = rtp_sender_.NackOverheadRate();
2000}
2001
2002// Bad state of RTP receiver request a keyframe.
2003void ModuleRtpRtcpImpl::OnRequestIntraFrame() {
2004  RequestKeyFrame();
2005}
2006
2007void ModuleRtpRtcpImpl::OnRequestSendReport() {
2008  rtcp_sender_.SendRTCP(kRtcpSr);
2009}
2010
2011int32_t ModuleRtpRtcpImpl::SendRTCPReferencePictureSelection(
2012    const uint64_t picture_id) {
2013  return rtcp_sender_.SendRTCP(kRtcpRpsi, 0, 0, false, picture_id);
2014}
2015
2016uint32_t ModuleRtpRtcpImpl::SendTimeOfSendReport(
2017    const uint32_t send_report) {
2018  return rtcp_sender_.SendTimeOfSendReport(send_report);
2019}
2020
2021void ModuleRtpRtcpImpl::OnReceivedNACK(
2022    const std::list<uint16_t>& nack_sequence_numbers) {
2023  if (!rtp_sender_.StorePackets() ||
2024      nack_sequence_numbers.size() == 0) {
2025    return;
2026  }
2027  uint16_t avg_rtt = 0;
2028  rtcp_receiver_.RTT(rtp_receiver_->SSRC(), NULL, &avg_rtt, NULL, NULL);
2029  rtp_sender_.OnReceivedNACK(nack_sequence_numbers, avg_rtt);
2030}
2031
2032int32_t ModuleRtpRtcpImpl::LastReceivedNTP(
2033    uint32_t& rtcp_arrival_time_secs,  // When we got the last report.
2034    uint32_t& rtcp_arrival_time_frac,
2035    uint32_t& remote_sr) {
2036  // Remote SR: NTP inside the last received (mid 16 bits from sec and frac).
2037  uint32_t ntp_secs = 0;
2038  uint32_t ntp_frac = 0;
2039
2040  if (-1 == rtcp_receiver_.NTP(&ntp_secs,
2041                               &ntp_frac,
2042                               &rtcp_arrival_time_secs,
2043                               &rtcp_arrival_time_frac,
2044                               NULL)) {
2045    return -1;
2046  }
2047  remote_sr = ((ntp_secs & 0x0000ffff) << 16) + ((ntp_frac & 0xffff0000) >> 16);
2048  return 0;
2049}
2050
2051bool ModuleRtpRtcpImpl::UpdateRTCPReceiveInformationTimers() {
2052  // If this returns true this channel has timed out.
2053  // Periodically check if this is true and if so call UpdateTMMBR.
2054  return rtcp_receiver_.UpdateRTCPReceiveInformationTimers();
2055}
2056
2057// Called from RTCPsender.
2058int32_t ModuleRtpRtcpImpl::BoundingSet(bool& tmmbr_owner,
2059                                       TMMBRSet*& bounding_set) {
2060  return rtcp_receiver_.BoundingSet(tmmbr_owner, bounding_set);
2061}
2062
2063int64_t ModuleRtpRtcpImpl::RtcpReportInterval() {
2064  if (audio_)
2065    return RTCP_INTERVAL_AUDIO_MS;
2066  else
2067    return RTCP_INTERVAL_VIDEO_MS;
2068}
2069}  // Namespace webrtc
2070