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
15#include <set>
16
17#include "webrtc/base/checks.h"
18#include "webrtc/base/logging.h"
19#include "webrtc/common_types.h"
20#include "webrtc/system_wrappers/include/trace.h"
21
22#ifdef _WIN32
23// Disable warning C4355: 'this' : used in base member initializer list.
24#pragma warning(disable : 4355)
25#endif
26
27namespace webrtc {
28
29RtpRtcp::Configuration::Configuration()
30    : audio(false),
31      receiver_only(false),
32      clock(nullptr),
33      receive_statistics(NullObjectReceiveStatistics()),
34      outgoing_transport(nullptr),
35      intra_frame_callback(nullptr),
36      bandwidth_callback(nullptr),
37      transport_feedback_callback(nullptr),
38      rtt_stats(nullptr),
39      rtcp_packet_type_counter_observer(nullptr),
40      audio_messages(NullObjectRtpAudioFeedback()),
41      remote_bitrate_estimator(nullptr),
42      paced_sender(nullptr),
43      transport_sequence_number_allocator(nullptr),
44      send_bitrate_observer(nullptr),
45      send_frame_count_observer(nullptr),
46      send_side_delay_observer(nullptr) {}
47
48RtpRtcp* RtpRtcp::CreateRtpRtcp(const RtpRtcp::Configuration& configuration) {
49  if (configuration.clock) {
50    return new ModuleRtpRtcpImpl(configuration);
51  } else {
52    // No clock implementation provided, use default clock.
53    RtpRtcp::Configuration configuration_copy;
54    memcpy(&configuration_copy, &configuration,
55           sizeof(RtpRtcp::Configuration));
56    configuration_copy.clock = Clock::GetRealTimeClock();
57    return new ModuleRtpRtcpImpl(configuration_copy);
58  }
59}
60
61ModuleRtpRtcpImpl::ModuleRtpRtcpImpl(const Configuration& configuration)
62    : rtp_sender_(configuration.audio,
63                  configuration.clock,
64                  configuration.outgoing_transport,
65                  configuration.audio_messages,
66                  configuration.paced_sender,
67                  configuration.transport_sequence_number_allocator,
68                  configuration.transport_feedback_callback,
69                  configuration.send_bitrate_observer,
70                  configuration.send_frame_count_observer,
71                  configuration.send_side_delay_observer),
72      rtcp_sender_(configuration.audio,
73                   configuration.clock,
74                   configuration.receive_statistics,
75                   configuration.rtcp_packet_type_counter_observer,
76                   configuration.outgoing_transport),
77      rtcp_receiver_(configuration.clock,
78                     configuration.receiver_only,
79                     configuration.rtcp_packet_type_counter_observer,
80                     configuration.bandwidth_callback,
81                     configuration.intra_frame_callback,
82                     configuration.transport_feedback_callback,
83                     this),
84      clock_(configuration.clock),
85      audio_(configuration.audio),
86      collision_detected_(false),
87      last_process_time_(configuration.clock->TimeInMilliseconds()),
88      last_bitrate_process_time_(configuration.clock->TimeInMilliseconds()),
89      last_rtt_process_time_(configuration.clock->TimeInMilliseconds()),
90      packet_overhead_(28),                     // IPV4 UDP.
91      padding_index_(static_cast<size_t>(-1)),  // Start padding at first child.
92      nack_method_(kNackOff),
93      nack_last_time_sent_full_(0),
94      nack_last_time_sent_full_prev_(0),
95      nack_last_seq_number_sent_(0),
96      key_frame_req_method_(kKeyFrameReqPliRtcp),
97      remote_bitrate_(configuration.remote_bitrate_estimator),
98      rtt_stats_(configuration.rtt_stats),
99      critical_section_rtt_(CriticalSectionWrapper::CreateCriticalSection()),
100      rtt_ms_(0) {
101  send_video_codec_.codecType = kVideoCodecUnknown;
102
103  // Make sure that RTCP objects are aware of our SSRC.
104  uint32_t SSRC = rtp_sender_.SSRC();
105  rtcp_sender_.SetSSRC(SSRC);
106  SetRtcpReceiverSsrcs(SSRC);
107}
108
109// Returns the number of milliseconds until the module want a worker thread
110// to call Process.
111int64_t ModuleRtpRtcpImpl::TimeUntilNextProcess() {
112  const int64_t now = clock_->TimeInMilliseconds();
113  const int64_t kRtpRtcpMaxIdleTimeProcessMs = 5;
114  return kRtpRtcpMaxIdleTimeProcessMs - (now - last_process_time_);
115}
116
117// Process any pending tasks such as timeouts (non time critical events).
118int32_t ModuleRtpRtcpImpl::Process() {
119  const int64_t now = clock_->TimeInMilliseconds();
120  last_process_time_ = now;
121
122  const int64_t kRtpRtcpBitrateProcessTimeMs = 10;
123  if (now >= last_bitrate_process_time_ + kRtpRtcpBitrateProcessTimeMs) {
124    rtp_sender_.ProcessBitrate();
125    last_bitrate_process_time_ = now;
126  }
127
128  const int64_t kRtpRtcpRttProcessTimeMs = 1000;
129  bool process_rtt = now >= last_rtt_process_time_ + kRtpRtcpRttProcessTimeMs;
130  if (rtcp_sender_.Sending()) {
131    // Process RTT if we have received a receiver report and we haven't
132    // processed RTT for at least |kRtpRtcpRttProcessTimeMs| milliseconds.
133    if (rtcp_receiver_.LastReceivedReceiverReport() >
134        last_rtt_process_time_ && process_rtt) {
135      std::vector<RTCPReportBlock> receive_blocks;
136      rtcp_receiver_.StatisticsReceived(&receive_blocks);
137      int64_t max_rtt = 0;
138      for (std::vector<RTCPReportBlock>::iterator it = receive_blocks.begin();
139           it != receive_blocks.end(); ++it) {
140        int64_t rtt = 0;
141        rtcp_receiver_.RTT(it->remoteSSRC, &rtt, NULL, NULL, NULL);
142        max_rtt = (rtt > max_rtt) ? rtt : max_rtt;
143      }
144      // Report the rtt.
145      if (rtt_stats_ && max_rtt != 0)
146        rtt_stats_->OnRttUpdate(max_rtt);
147    }
148
149    // Verify receiver reports are delivered and the reported sequence number
150    // is increasing.
151    int64_t rtcp_interval = RtcpReportInterval();
152    if (rtcp_receiver_.RtcpRrTimeout(rtcp_interval)) {
153      LOG_F(LS_WARNING) << "Timeout: No RTCP RR received.";
154    } else if (rtcp_receiver_.RtcpRrSequenceNumberTimeout(rtcp_interval)) {
155      LOG_F(LS_WARNING) <<
156          "Timeout: No increase in RTCP RR extended highest sequence number.";
157    }
158
159    if (remote_bitrate_ && rtcp_sender_.TMMBR()) {
160      unsigned int target_bitrate = 0;
161      std::vector<unsigned int> ssrcs;
162      if (remote_bitrate_->LatestEstimate(&ssrcs, &target_bitrate)) {
163        if (!ssrcs.empty()) {
164          target_bitrate = target_bitrate / ssrcs.size();
165        }
166        rtcp_sender_.SetTargetBitrate(target_bitrate);
167      }
168    }
169  } else {
170    // Report rtt from receiver.
171    if (process_rtt) {
172       int64_t rtt_ms;
173       if (rtt_stats_ && rtcp_receiver_.GetAndResetXrRrRtt(&rtt_ms)) {
174         rtt_stats_->OnRttUpdate(rtt_ms);
175       }
176    }
177  }
178
179  // Get processed rtt.
180  if (process_rtt) {
181    last_rtt_process_time_ = now;
182    if (rtt_stats_)
183      set_rtt_ms(rtt_stats_->LastProcessedRtt());
184  }
185
186  // For sending streams, make sure to not send a SR before media has been sent.
187  if (rtcp_sender_.TimeToSendRTCPReport()) {
188    RTCPSender::FeedbackState state = GetFeedbackState();
189    // Prevent sending streams to send SR before any media has been sent.
190    if (!rtcp_sender_.Sending() || state.packets_sent > 0)
191      rtcp_sender_.SendRTCP(state, kRtcpReport);
192  }
193
194  if (UpdateRTCPReceiveInformationTimers()) {
195    // A receiver has timed out
196    rtcp_receiver_.UpdateTMMBR();
197  }
198  return 0;
199}
200
201void ModuleRtpRtcpImpl::SetRtxSendStatus(int mode) {
202  rtp_sender_.SetRtxStatus(mode);
203}
204
205int ModuleRtpRtcpImpl::RtxSendStatus() const {
206  return rtp_sender_.RtxStatus();
207}
208
209void ModuleRtpRtcpImpl::SetRtxSsrc(uint32_t ssrc) {
210  rtp_sender_.SetRtxSsrc(ssrc);
211}
212
213void ModuleRtpRtcpImpl::SetRtxSendPayloadType(int payload_type,
214                                              int associated_payload_type) {
215  rtp_sender_.SetRtxPayloadType(payload_type, associated_payload_type);
216}
217
218std::pair<int, int> ModuleRtpRtcpImpl::RtxSendPayloadType() const {
219  return rtp_sender_.RtxPayloadType();
220}
221
222int32_t ModuleRtpRtcpImpl::IncomingRtcpPacket(
223    const uint8_t* rtcp_packet,
224    const size_t length) {
225  // Allow receive of non-compound RTCP packets.
226  RTCPUtility::RTCPParserV2 rtcp_parser(rtcp_packet, length, true);
227
228  const bool valid_rtcpheader = rtcp_parser.IsValid();
229  if (!valid_rtcpheader) {
230    LOG(LS_WARNING) << "Incoming invalid RTCP packet";
231    return -1;
232  }
233  RTCPHelp::RTCPPacketInformation rtcp_packet_information;
234  int32_t ret_val = rtcp_receiver_.IncomingRTCPPacket(
235      rtcp_packet_information, &rtcp_parser);
236  if (ret_val == 0) {
237    rtcp_receiver_.TriggerCallbacksFromRTCPPacket(rtcp_packet_information);
238  }
239  return ret_val;
240}
241
242int32_t ModuleRtpRtcpImpl::RegisterSendPayload(
243    const CodecInst& voice_codec) {
244  return rtp_sender_.RegisterPayload(
245           voice_codec.plname,
246           voice_codec.pltype,
247           voice_codec.plfreq,
248           voice_codec.channels,
249           (voice_codec.rate < 0) ? 0 : voice_codec.rate);
250}
251
252int32_t ModuleRtpRtcpImpl::RegisterSendPayload(const VideoCodec& video_codec) {
253  send_video_codec_ = video_codec;
254  return rtp_sender_.RegisterPayload(video_codec.plName,
255                                     video_codec.plType,
256                                     90000,
257                                     0,
258                                     video_codec.maxBitrate);
259}
260
261int32_t ModuleRtpRtcpImpl::DeRegisterSendPayload(const int8_t payload_type) {
262  return rtp_sender_.DeRegisterSendPayload(payload_type);
263}
264
265int8_t ModuleRtpRtcpImpl::SendPayloadType() const {
266  return rtp_sender_.SendPayloadType();
267}
268
269uint32_t ModuleRtpRtcpImpl::StartTimestamp() const {
270  return rtp_sender_.StartTimestamp();
271}
272
273// Configure start timestamp, default is a random number.
274void ModuleRtpRtcpImpl::SetStartTimestamp(const uint32_t timestamp) {
275  rtcp_sender_.SetStartTimestamp(timestamp);
276  rtp_sender_.SetStartTimestamp(timestamp, true);
277}
278
279uint16_t ModuleRtpRtcpImpl::SequenceNumber() const {
280  return rtp_sender_.SequenceNumber();
281}
282
283// Set SequenceNumber, default is a random number.
284void ModuleRtpRtcpImpl::SetSequenceNumber(const uint16_t seq_num) {
285  rtp_sender_.SetSequenceNumber(seq_num);
286}
287
288bool ModuleRtpRtcpImpl::SetRtpStateForSsrc(uint32_t ssrc,
289                                           const RtpState& rtp_state) {
290  if (rtp_sender_.SSRC() == ssrc) {
291    rtp_sender_.SetRtpState(rtp_state);
292    return true;
293  }
294  if (rtp_sender_.RtxSsrc() == ssrc) {
295    rtp_sender_.SetRtxRtpState(rtp_state);
296    return true;
297  }
298  return false;
299}
300
301bool ModuleRtpRtcpImpl::GetRtpStateForSsrc(uint32_t ssrc, RtpState* rtp_state) {
302  if (rtp_sender_.SSRC() == ssrc) {
303    *rtp_state = rtp_sender_.GetRtpState();
304    return true;
305  }
306  if (rtp_sender_.RtxSsrc() == ssrc) {
307    *rtp_state = rtp_sender_.GetRtxRtpState();
308    return true;
309  }
310  return false;
311}
312
313uint32_t ModuleRtpRtcpImpl::SSRC() const {
314  return rtp_sender_.SSRC();
315}
316
317// Configure SSRC, default is a random number.
318void ModuleRtpRtcpImpl::SetSSRC(const uint32_t ssrc) {
319  rtp_sender_.SetSSRC(ssrc);
320  rtcp_sender_.SetSSRC(ssrc);
321  SetRtcpReceiverSsrcs(ssrc);
322}
323
324void ModuleRtpRtcpImpl::SetCsrcs(const std::vector<uint32_t>& csrcs) {
325  rtcp_sender_.SetCsrcs(csrcs);
326  rtp_sender_.SetCsrcs(csrcs);
327}
328
329// TODO(pbos): Handle media and RTX streams separately (separate RTCP
330// feedbacks).
331RTCPSender::FeedbackState ModuleRtpRtcpImpl::GetFeedbackState() {
332  StreamDataCounters rtp_stats;
333  StreamDataCounters rtx_stats;
334  rtp_sender_.GetDataCounters(&rtp_stats, &rtx_stats);
335
336  RTCPSender::FeedbackState state;
337  state.send_payload_type = SendPayloadType();
338  state.frequency_hz = CurrentSendFrequencyHz();
339  state.packets_sent = rtp_stats.transmitted.packets +
340                       rtx_stats.transmitted.packets;
341  state.media_bytes_sent = rtp_stats.transmitted.payload_bytes +
342                           rtx_stats.transmitted.payload_bytes;
343  state.module = this;
344
345  LastReceivedNTP(&state.last_rr_ntp_secs,
346                  &state.last_rr_ntp_frac,
347                  &state.remote_sr);
348
349  state.has_last_xr_rr = LastReceivedXrReferenceTimeInfo(&state.last_xr_rr);
350
351  uint32_t tmp;
352  BitrateSent(&state.send_bitrate, &tmp, &tmp, &tmp);
353  return state;
354}
355
356int ModuleRtpRtcpImpl::CurrentSendFrequencyHz() const {
357  return rtp_sender_.SendPayloadFrequency();
358}
359
360int32_t ModuleRtpRtcpImpl::SetSendingStatus(const bool sending) {
361  if (rtcp_sender_.Sending() != sending) {
362    // Sends RTCP BYE when going from true to false
363    if (rtcp_sender_.SetSendingStatus(GetFeedbackState(), sending) != 0) {
364      LOG(LS_WARNING) << "Failed to send RTCP BYE";
365    }
366
367    collision_detected_ = false;
368
369    // Generate a new time_stamp if true and not configured via API
370    // Generate a new SSRC for the next "call" if false
371    rtp_sender_.SetSendingStatus(sending);
372    if (sending) {
373      // Make sure the RTCP sender has the same timestamp offset.
374      rtcp_sender_.SetStartTimestamp(rtp_sender_.StartTimestamp());
375    }
376
377    // Make sure that RTCP objects are aware of our SSRC (it could have changed
378    // Due to collision)
379    uint32_t SSRC = rtp_sender_.SSRC();
380    rtcp_sender_.SetSSRC(SSRC);
381    SetRtcpReceiverSsrcs(SSRC);
382
383    return 0;
384  }
385  return 0;
386}
387
388bool ModuleRtpRtcpImpl::Sending() const {
389  return rtcp_sender_.Sending();
390}
391
392void ModuleRtpRtcpImpl::SetSendingMediaStatus(const bool sending) {
393  rtp_sender_.SetSendingMediaStatus(sending);
394}
395
396bool ModuleRtpRtcpImpl::SendingMedia() const {
397  return rtp_sender_.SendingMedia();
398}
399
400int32_t ModuleRtpRtcpImpl::SendOutgoingData(
401    FrameType frame_type,
402    int8_t payload_type,
403    uint32_t time_stamp,
404    int64_t capture_time_ms,
405    const uint8_t* payload_data,
406    size_t payload_size,
407    const RTPFragmentationHeader* fragmentation,
408    const RTPVideoHeader* rtp_video_hdr) {
409  rtcp_sender_.SetLastRtpTime(time_stamp, capture_time_ms);
410  // Make sure an RTCP report isn't queued behind a key frame.
411  if (rtcp_sender_.TimeToSendRTCPReport(kVideoFrameKey == frame_type)) {
412      rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
413  }
414  return rtp_sender_.SendOutgoingData(
415      frame_type, payload_type, time_stamp, capture_time_ms, payload_data,
416      payload_size, fragmentation, rtp_video_hdr);
417}
418
419bool ModuleRtpRtcpImpl::TimeToSendPacket(uint32_t ssrc,
420                                         uint16_t sequence_number,
421                                         int64_t capture_time_ms,
422                                         bool retransmission) {
423  if (SendingMedia() && ssrc == rtp_sender_.SSRC()) {
424    return rtp_sender_.TimeToSendPacket(
425        sequence_number, capture_time_ms, retransmission);
426  }
427  // No RTP sender is interested in sending this packet.
428  return true;
429}
430
431size_t ModuleRtpRtcpImpl::TimeToSendPadding(size_t bytes) {
432  return rtp_sender_.TimeToSendPadding(bytes);
433}
434
435uint16_t ModuleRtpRtcpImpl::MaxPayloadLength() const {
436  return rtp_sender_.MaxPayloadLength();
437}
438
439uint16_t ModuleRtpRtcpImpl::MaxDataPayloadLength() const {
440  return rtp_sender_.MaxDataPayloadLength();
441}
442
443int32_t ModuleRtpRtcpImpl::SetTransportOverhead(
444    const bool tcp,
445    const bool ipv6,
446    const uint8_t authentication_overhead) {
447  uint16_t packet_overhead = 0;
448  if (ipv6) {
449    packet_overhead = 40;
450  } else {
451    packet_overhead = 20;
452  }
453  if (tcp) {
454    // TCP.
455    packet_overhead += 20;
456  } else {
457    // UDP.
458    packet_overhead += 8;
459  }
460  packet_overhead += authentication_overhead;
461
462  if (packet_overhead == packet_overhead_) {
463    // Ok same as before.
464    return 0;
465  }
466  // Calc diff.
467  int16_t packet_over_head_diff = packet_overhead - packet_overhead_;
468
469  // Store new.
470  packet_overhead_ = packet_overhead;
471
472  uint16_t length =
473      rtp_sender_.MaxPayloadLength() - packet_over_head_diff;
474  return rtp_sender_.SetMaxPayloadLength(length, packet_overhead_);
475}
476
477int32_t ModuleRtpRtcpImpl::SetMaxTransferUnit(const uint16_t mtu) {
478  RTC_DCHECK_LE(mtu, IP_PACKET_SIZE) << "Invalid mtu: " << mtu;
479  return rtp_sender_.SetMaxPayloadLength(mtu - packet_overhead_,
480                                         packet_overhead_);
481}
482
483RtcpMode ModuleRtpRtcpImpl::RTCP() const {
484  if (rtcp_sender_.Status() != RtcpMode::kOff) {
485    return rtcp_receiver_.Status();
486  }
487  return RtcpMode::kOff;
488}
489
490// Configure RTCP status i.e on/off.
491void ModuleRtpRtcpImpl::SetRTCPStatus(const RtcpMode method) {
492  rtcp_sender_.SetRTCPStatus(method);
493  rtcp_receiver_.SetRTCPStatus(method);
494}
495
496int32_t ModuleRtpRtcpImpl::SetCNAME(const char* c_name) {
497  return rtcp_sender_.SetCNAME(c_name);
498}
499
500int32_t ModuleRtpRtcpImpl::AddMixedCNAME(uint32_t ssrc, const char* c_name) {
501  return rtcp_sender_.AddMixedCNAME(ssrc, c_name);
502}
503
504int32_t ModuleRtpRtcpImpl::RemoveMixedCNAME(const uint32_t ssrc) {
505  return rtcp_sender_.RemoveMixedCNAME(ssrc);
506}
507
508int32_t ModuleRtpRtcpImpl::RemoteCNAME(
509    const uint32_t remote_ssrc,
510    char c_name[RTCP_CNAME_SIZE]) const {
511  return rtcp_receiver_.CNAME(remote_ssrc, c_name);
512}
513
514int32_t ModuleRtpRtcpImpl::RemoteNTP(
515    uint32_t* received_ntpsecs,
516    uint32_t* received_ntpfrac,
517    uint32_t* rtcp_arrival_time_secs,
518    uint32_t* rtcp_arrival_time_frac,
519    uint32_t* rtcp_timestamp) const {
520  return rtcp_receiver_.NTP(received_ntpsecs,
521                            received_ntpfrac,
522                            rtcp_arrival_time_secs,
523                            rtcp_arrival_time_frac,
524                            rtcp_timestamp)
525             ? 0
526             : -1;
527}
528
529// Get RoundTripTime.
530int32_t ModuleRtpRtcpImpl::RTT(const uint32_t remote_ssrc,
531                               int64_t* rtt,
532                               int64_t* avg_rtt,
533                               int64_t* min_rtt,
534                               int64_t* max_rtt) const {
535  int32_t ret = rtcp_receiver_.RTT(remote_ssrc, rtt, avg_rtt, min_rtt, max_rtt);
536  if (rtt && *rtt == 0) {
537    // Try to get RTT from RtcpRttStats class.
538    *rtt = rtt_ms();
539  }
540  return ret;
541}
542
543// Force a send of an RTCP packet.
544// Normal SR and RR are triggered via the process function.
545int32_t ModuleRtpRtcpImpl::SendRTCP(RTCPPacketType packet_type) {
546  return rtcp_sender_.SendRTCP(GetFeedbackState(), packet_type);
547}
548
549// Force a send of an RTCP packet.
550// Normal SR and RR are triggered via the process function.
551int32_t ModuleRtpRtcpImpl::SendCompoundRTCP(
552    const std::set<RTCPPacketType>& packet_types) {
553  return rtcp_sender_.SendCompoundRTCP(GetFeedbackState(), packet_types);
554}
555
556int32_t ModuleRtpRtcpImpl::SetRTCPApplicationSpecificData(
557    const uint8_t sub_type,
558    const uint32_t name,
559    const uint8_t* data,
560    const uint16_t length) {
561  return  rtcp_sender_.SetApplicationSpecificData(sub_type, name, data, length);
562}
563
564// (XR) VOIP metric.
565int32_t ModuleRtpRtcpImpl::SetRTCPVoIPMetrics(
566  const RTCPVoIPMetric* voip_metric) {
567  return  rtcp_sender_.SetRTCPVoIPMetrics(voip_metric);
568}
569
570void ModuleRtpRtcpImpl::SetRtcpXrRrtrStatus(bool enable) {
571  return rtcp_sender_.SendRtcpXrReceiverReferenceTime(enable);
572}
573
574bool ModuleRtpRtcpImpl::RtcpXrRrtrStatus() const {
575  return rtcp_sender_.RtcpXrReceiverReferenceTime();
576}
577
578// TODO(asapersson): Replace this method with the one below.
579int32_t ModuleRtpRtcpImpl::DataCountersRTP(
580    size_t* bytes_sent,
581    uint32_t* packets_sent) const {
582  StreamDataCounters rtp_stats;
583  StreamDataCounters rtx_stats;
584  rtp_sender_.GetDataCounters(&rtp_stats, &rtx_stats);
585
586  if (bytes_sent) {
587    *bytes_sent = rtp_stats.transmitted.payload_bytes +
588                  rtp_stats.transmitted.padding_bytes +
589                  rtp_stats.transmitted.header_bytes +
590                  rtx_stats.transmitted.payload_bytes +
591                  rtx_stats.transmitted.padding_bytes +
592                  rtx_stats.transmitted.header_bytes;
593  }
594  if (packets_sent) {
595    *packets_sent = rtp_stats.transmitted.packets +
596                    rtx_stats.transmitted.packets;
597  }
598  return 0;
599}
600
601void ModuleRtpRtcpImpl::GetSendStreamDataCounters(
602    StreamDataCounters* rtp_counters,
603    StreamDataCounters* rtx_counters) const {
604  rtp_sender_.GetDataCounters(rtp_counters, rtx_counters);
605}
606
607void ModuleRtpRtcpImpl::GetRtpPacketLossStats(
608    bool outgoing,
609    uint32_t ssrc,
610    struct RtpPacketLossStats* loss_stats) const {
611  if (!loss_stats) return;
612  const PacketLossStats* stats_source = NULL;
613  if (outgoing) {
614    if (SSRC() == ssrc) {
615      stats_source = &send_loss_stats_;
616    }
617  } else {
618    if (rtcp_receiver_.RemoteSSRC() == ssrc) {
619      stats_source = &receive_loss_stats_;
620    }
621  }
622  if (stats_source) {
623    loss_stats->single_packet_loss_count =
624        stats_source->GetSingleLossCount();
625    loss_stats->multiple_packet_loss_event_count =
626        stats_source->GetMultipleLossEventCount();
627    loss_stats->multiple_packet_loss_packet_count =
628        stats_source->GetMultipleLossPacketCount();
629  }
630}
631
632int32_t ModuleRtpRtcpImpl::RemoteRTCPStat(RTCPSenderInfo* sender_info) {
633  return rtcp_receiver_.SenderInfoReceived(sender_info);
634}
635
636// Received RTCP report.
637int32_t ModuleRtpRtcpImpl::RemoteRTCPStat(
638    std::vector<RTCPReportBlock>* receive_blocks) const {
639  return rtcp_receiver_.StatisticsReceived(receive_blocks);
640}
641
642// (REMB) Receiver Estimated Max Bitrate.
643bool ModuleRtpRtcpImpl::REMB() const {
644  return rtcp_sender_.REMB();
645}
646
647void ModuleRtpRtcpImpl::SetREMBStatus(const bool enable) {
648  rtcp_sender_.SetREMBStatus(enable);
649}
650
651void ModuleRtpRtcpImpl::SetREMBData(const uint32_t bitrate,
652                                    const std::vector<uint32_t>& ssrcs) {
653  rtcp_sender_.SetREMBData(bitrate, ssrcs);
654}
655
656int32_t ModuleRtpRtcpImpl::RegisterSendRtpHeaderExtension(
657    const RTPExtensionType type,
658    const uint8_t id) {
659  return rtp_sender_.RegisterRtpHeaderExtension(type, id);
660}
661
662int32_t ModuleRtpRtcpImpl::DeregisterSendRtpHeaderExtension(
663    const RTPExtensionType type) {
664  return rtp_sender_.DeregisterRtpHeaderExtension(type);
665}
666
667// (TMMBR) Temporary Max Media Bit Rate.
668bool ModuleRtpRtcpImpl::TMMBR() const {
669  return rtcp_sender_.TMMBR();
670}
671
672void ModuleRtpRtcpImpl::SetTMMBRStatus(const bool enable) {
673  rtcp_sender_.SetTMMBRStatus(enable);
674}
675
676int32_t ModuleRtpRtcpImpl::SetTMMBN(const TMMBRSet* bounding_set) {
677  uint32_t max_bitrate_kbit =
678      rtp_sender_.MaxConfiguredBitrateVideo() / 1000;
679  return rtcp_sender_.SetTMMBN(bounding_set, max_bitrate_kbit);
680}
681
682// Returns the currently configured retransmission mode.
683int ModuleRtpRtcpImpl::SelectiveRetransmissions() const {
684  return rtp_sender_.SelectiveRetransmissions();
685}
686
687// Enable or disable a retransmission mode, which decides which packets will
688// be retransmitted if NACKed.
689int ModuleRtpRtcpImpl::SetSelectiveRetransmissions(uint8_t settings) {
690  return rtp_sender_.SetSelectiveRetransmissions(settings);
691}
692
693// Send a Negative acknowledgment packet.
694int32_t ModuleRtpRtcpImpl::SendNACK(const uint16_t* nack_list,
695                                    const uint16_t size) {
696  for (int i = 0; i < size; ++i) {
697    receive_loss_stats_.AddLostPacket(nack_list[i]);
698  }
699  uint16_t nack_length = size;
700  uint16_t start_id = 0;
701  int64_t now = clock_->TimeInMilliseconds();
702  if (TimeToSendFullNackList(now)) {
703    nack_last_time_sent_full_ = now;
704    nack_last_time_sent_full_prev_ = now;
705  } else {
706    // Only send extended list.
707    if (nack_last_seq_number_sent_ == nack_list[size - 1]) {
708      // Last sequence number is the same, do not send list.
709      return 0;
710    }
711    // Send new sequence numbers.
712    for (int i = 0; i < size; ++i) {
713      if (nack_last_seq_number_sent_ == nack_list[i]) {
714        start_id = i + 1;
715        break;
716      }
717    }
718    nack_length = size - start_id;
719  }
720
721  // Our RTCP NACK implementation is limited to kRtcpMaxNackFields sequence
722  // numbers per RTCP packet.
723  if (nack_length > kRtcpMaxNackFields) {
724    nack_length = kRtcpMaxNackFields;
725  }
726  nack_last_seq_number_sent_ = nack_list[start_id + nack_length - 1];
727
728  return rtcp_sender_.SendRTCP(
729      GetFeedbackState(), kRtcpNack, nack_length, &nack_list[start_id]);
730}
731
732bool ModuleRtpRtcpImpl::TimeToSendFullNackList(int64_t now) const {
733  // Use RTT from RtcpRttStats class if provided.
734  int64_t rtt = rtt_ms();
735  if (rtt == 0) {
736    rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
737  }
738
739  const int64_t kStartUpRttMs = 100;
740  int64_t wait_time = 5 + ((rtt * 3) >> 1);  // 5 + RTT * 1.5.
741  if (rtt == 0) {
742    wait_time = kStartUpRttMs;
743  }
744
745  // Send a full NACK list once within every |wait_time|.
746  if (rtt_stats_) {
747    return now - nack_last_time_sent_full_ > wait_time;
748  }
749  return now - nack_last_time_sent_full_prev_ > wait_time;
750}
751
752// Store the sent packets, needed to answer to Negative acknowledgment requests.
753void ModuleRtpRtcpImpl::SetStorePacketsStatus(const bool enable,
754                                              const uint16_t number_to_store) {
755  rtp_sender_.SetStorePacketsStatus(enable, number_to_store);
756}
757
758bool ModuleRtpRtcpImpl::StorePackets() const {
759  return rtp_sender_.StorePackets();
760}
761
762void ModuleRtpRtcpImpl::RegisterRtcpStatisticsCallback(
763    RtcpStatisticsCallback* callback) {
764  rtcp_receiver_.RegisterRtcpStatisticsCallback(callback);
765}
766
767RtcpStatisticsCallback* ModuleRtpRtcpImpl::GetRtcpStatisticsCallback() {
768  return rtcp_receiver_.GetRtcpStatisticsCallback();
769}
770
771bool ModuleRtpRtcpImpl::SendFeedbackPacket(
772    const rtcp::TransportFeedback& packet) {
773  return rtcp_sender_.SendFeedbackPacket(packet);
774}
775
776// Send a TelephoneEvent tone using RFC 2833 (4733).
777int32_t ModuleRtpRtcpImpl::SendTelephoneEventOutband(
778    const uint8_t key,
779    const uint16_t time_ms,
780    const uint8_t level) {
781  return rtp_sender_.SendTelephoneEvent(key, time_ms, level);
782}
783
784// Set audio packet size, used to determine when it's time to send a DTMF
785// packet in silence (CNG).
786int32_t ModuleRtpRtcpImpl::SetAudioPacketSize(
787    const uint16_t packet_size_samples) {
788  return rtp_sender_.SetAudioPacketSize(packet_size_samples);
789}
790
791int32_t ModuleRtpRtcpImpl::SetAudioLevel(
792    const uint8_t level_d_bov) {
793  return rtp_sender_.SetAudioLevel(level_d_bov);
794}
795
796// Set payload type for Redundant Audio Data RFC 2198.
797int32_t ModuleRtpRtcpImpl::SetSendREDPayloadType(
798    const int8_t payload_type) {
799  return rtp_sender_.SetRED(payload_type);
800}
801
802// Get payload type for Redundant Audio Data RFC 2198.
803int32_t ModuleRtpRtcpImpl::SendREDPayloadType(int8_t* payload_type) const {
804  return rtp_sender_.RED(payload_type);
805}
806
807void ModuleRtpRtcpImpl::SetTargetSendBitrate(uint32_t bitrate_bps) {
808  rtp_sender_.SetTargetBitrate(bitrate_bps);
809}
810
811int32_t ModuleRtpRtcpImpl::SetKeyFrameRequestMethod(
812    const KeyFrameRequestMethod method) {
813  key_frame_req_method_ = method;
814  return 0;
815}
816
817int32_t ModuleRtpRtcpImpl::RequestKeyFrame() {
818  switch (key_frame_req_method_) {
819    case kKeyFrameReqPliRtcp:
820      return SendRTCP(kRtcpPli);
821    case kKeyFrameReqFirRtcp:
822      return SendRTCP(kRtcpFir);
823  }
824  return -1;
825}
826
827int32_t ModuleRtpRtcpImpl::SendRTCPSliceLossIndication(
828    const uint8_t picture_id) {
829  return rtcp_sender_.SendRTCP(
830      GetFeedbackState(), kRtcpSli, 0, 0, false, picture_id);
831}
832
833void ModuleRtpRtcpImpl::SetGenericFECStatus(
834    const bool enable,
835    const uint8_t payload_type_red,
836    const uint8_t payload_type_fec) {
837  rtp_sender_.SetGenericFECStatus(enable, payload_type_red, payload_type_fec);
838}
839
840void ModuleRtpRtcpImpl::GenericFECStatus(bool* enable,
841                                         uint8_t* payload_type_red,
842                                         uint8_t* payload_type_fec) {
843  rtp_sender_.GenericFECStatus(enable, payload_type_red, payload_type_fec);
844}
845
846int32_t ModuleRtpRtcpImpl::SetFecParameters(
847    const FecProtectionParams* delta_params,
848    const FecProtectionParams* key_params) {
849  return rtp_sender_.SetFecParameters(delta_params, key_params);
850}
851
852void ModuleRtpRtcpImpl::SetRemoteSSRC(const uint32_t ssrc) {
853  // Inform about the incoming SSRC.
854  rtcp_sender_.SetRemoteSSRC(ssrc);
855  rtcp_receiver_.SetRemoteSSRC(ssrc);
856
857  // Check for a SSRC collision.
858  if (rtp_sender_.SSRC() == ssrc && !collision_detected_) {
859    // If we detect a collision change the SSRC but only once.
860    collision_detected_ = true;
861    uint32_t new_ssrc = rtp_sender_.GenerateNewSSRC();
862    if (new_ssrc == 0) {
863      // Configured via API ignore.
864      return;
865    }
866    if (RtcpMode::kOff != rtcp_sender_.Status()) {
867      // Send RTCP bye on the current SSRC.
868      SendRTCP(kRtcpBye);
869    }
870    // Change local SSRC and inform all objects about the new SSRC.
871    rtcp_sender_.SetSSRC(new_ssrc);
872    SetRtcpReceiverSsrcs(new_ssrc);
873  }
874}
875
876void ModuleRtpRtcpImpl::BitrateSent(uint32_t* total_rate,
877                                    uint32_t* video_rate,
878                                    uint32_t* fec_rate,
879                                    uint32_t* nack_rate) const {
880  *total_rate = rtp_sender_.BitrateSent();
881  *video_rate = rtp_sender_.VideoBitrateSent();
882  *fec_rate = rtp_sender_.FecOverheadRate();
883  *nack_rate = rtp_sender_.NackOverheadRate();
884}
885
886void ModuleRtpRtcpImpl::OnRequestIntraFrame() {
887  RequestKeyFrame();
888}
889
890void ModuleRtpRtcpImpl::OnRequestSendReport() {
891  SendRTCP(kRtcpSr);
892}
893
894int32_t ModuleRtpRtcpImpl::SendRTCPReferencePictureSelection(
895    const uint64_t picture_id) {
896  return rtcp_sender_.SendRTCP(
897      GetFeedbackState(), kRtcpRpsi, 0, 0, false, picture_id);
898}
899
900int64_t ModuleRtpRtcpImpl::SendTimeOfSendReport(
901    const uint32_t send_report) {
902  return rtcp_sender_.SendTimeOfSendReport(send_report);
903}
904
905bool ModuleRtpRtcpImpl::SendTimeOfXrRrReport(
906    uint32_t mid_ntp, int64_t* time_ms) const {
907  return rtcp_sender_.SendTimeOfXrRrReport(mid_ntp, time_ms);
908}
909
910void ModuleRtpRtcpImpl::OnReceivedNACK(
911    const std::list<uint16_t>& nack_sequence_numbers) {
912  for (uint16_t nack_sequence_number : nack_sequence_numbers) {
913    send_loss_stats_.AddLostPacket(nack_sequence_number);
914  }
915  if (!rtp_sender_.StorePackets() ||
916      nack_sequence_numbers.size() == 0) {
917    return;
918  }
919  // Use RTT from RtcpRttStats class if provided.
920  int64_t rtt = rtt_ms();
921  if (rtt == 0) {
922    rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
923  }
924  rtp_sender_.OnReceivedNACK(nack_sequence_numbers, rtt);
925}
926
927bool ModuleRtpRtcpImpl::LastReceivedNTP(
928    uint32_t* rtcp_arrival_time_secs,  // When we got the last report.
929    uint32_t* rtcp_arrival_time_frac,
930    uint32_t* remote_sr) const {
931  // Remote SR: NTP inside the last received (mid 16 bits from sec and frac).
932  uint32_t ntp_secs = 0;
933  uint32_t ntp_frac = 0;
934
935  if (!rtcp_receiver_.NTP(&ntp_secs,
936                          &ntp_frac,
937                          rtcp_arrival_time_secs,
938                          rtcp_arrival_time_frac,
939                          NULL)) {
940    return false;
941  }
942  *remote_sr =
943      ((ntp_secs & 0x0000ffff) << 16) + ((ntp_frac & 0xffff0000) >> 16);
944  return true;
945}
946
947bool ModuleRtpRtcpImpl::LastReceivedXrReferenceTimeInfo(
948    RtcpReceiveTimeInfo* info) const {
949  return rtcp_receiver_.LastReceivedXrReferenceTimeInfo(info);
950}
951
952bool ModuleRtpRtcpImpl::UpdateRTCPReceiveInformationTimers() {
953  // If this returns true this channel has timed out.
954  // Periodically check if this is true and if so call UpdateTMMBR.
955  return rtcp_receiver_.UpdateRTCPReceiveInformationTimers();
956}
957
958// Called from RTCPsender.
959int32_t ModuleRtpRtcpImpl::BoundingSet(bool* tmmbr_owner,
960                                       TMMBRSet* bounding_set) {
961  return rtcp_receiver_.BoundingSet(tmmbr_owner, bounding_set);
962}
963
964int64_t ModuleRtpRtcpImpl::RtcpReportInterval() {
965  if (audio_)
966    return RTCP_INTERVAL_AUDIO_MS;
967  else
968    return RTCP_INTERVAL_VIDEO_MS;
969}
970
971void ModuleRtpRtcpImpl::SetRtcpReceiverSsrcs(uint32_t main_ssrc) {
972  std::set<uint32_t> ssrcs;
973  ssrcs.insert(main_ssrc);
974  if (rtp_sender_.RtxStatus() != kRtxOff)
975    ssrcs.insert(rtp_sender_.RtxSsrc());
976  rtcp_receiver_.SetSsrcs(main_ssrc, ssrcs);
977}
978
979void ModuleRtpRtcpImpl::set_rtt_ms(int64_t rtt_ms) {
980  CriticalSectionScoped cs(critical_section_rtt_.get());
981  rtt_ms_ = rtt_ms;
982}
983
984int64_t ModuleRtpRtcpImpl::rtt_ms() const {
985  CriticalSectionScoped cs(critical_section_rtt_.get());
986  return rtt_ms_;
987}
988
989void ModuleRtpRtcpImpl::RegisterSendChannelRtpStatisticsCallback(
990    StreamDataCountersCallback* callback) {
991  rtp_sender_.RegisterRtpStatisticsCallback(callback);
992}
993
994StreamDataCountersCallback*
995    ModuleRtpRtcpImpl::GetSendChannelRtpStatisticsCallback() const {
996  return rtp_sender_.GetRtpStatisticsCallback();
997}
998}  // namespace webrtc
999