Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / third_party / webrtc / modules / rtp_rtcp / source / rtp_sender.cc
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_sender.h"
12
13 #include <stdlib.h>  // srand
14
15 #include "webrtc/modules/rtp_rtcp/source/rtp_sender_audio.h"
16 #include "webrtc/modules/rtp_rtcp/source/rtp_sender_video.h"
17 #include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
18 #include "webrtc/system_wrappers/interface/trace.h"
19 #include "webrtc/system_wrappers/interface/trace_event.h"
20
21 namespace webrtc {
22
23 // Max in the RFC 3550 is 255 bytes, we limit it to be modulus 32 for SRTP.
24 const int kMaxPaddingLength = 224;
25 const int kSendSideDelayWindowMs = 1000;
26
27 namespace {
28
29 const char* FrameTypeToString(const FrameType frame_type) {
30   switch (frame_type) {
31     case kFrameEmpty: return "empty";
32     case kAudioFrameSpeech: return "audio_speech";
33     case kAudioFrameCN: return "audio_cn";
34     case kVideoFrameKey: return "video_key";
35     case kVideoFrameDelta: return "video_delta";
36   }
37   return "";
38 }
39
40 }  // namespace
41
42 RTPSender::RTPSender(const int32_t id,
43                      const bool audio,
44                      Clock* clock,
45                      Transport* transport,
46                      RtpAudioFeedback* audio_feedback,
47                      PacedSender* paced_sender)
48     : clock_(clock),
49       bitrate_sent_(clock, this),
50       id_(id),
51       audio_configured_(audio),
52       audio_(NULL),
53       video_(NULL),
54       paced_sender_(paced_sender),
55       send_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
56       transport_(transport),
57       sending_media_(true),                      // Default to sending media.
58       max_payload_length_(IP_PACKET_SIZE - 28),  // Default is IP-v4/UDP.
59       packet_over_head_(28),
60       payload_type_(-1),
61       payload_type_map_(),
62       rtp_header_extension_map_(),
63       transmission_time_offset_(0),
64       absolute_send_time_(0),
65       // NACK.
66       nack_byte_count_times_(),
67       nack_byte_count_(),
68       nack_bitrate_(clock, NULL),
69       packet_history_(clock),
70       // Statistics
71       statistics_crit_(CriticalSectionWrapper::CreateCriticalSection()),
72       frame_count_observer_(NULL),
73       rtp_stats_callback_(NULL),
74       bitrate_callback_(NULL),
75       // RTP variables
76       start_time_stamp_forced_(false),
77       start_time_stamp_(0),
78       ssrc_db_(*SSRCDatabase::GetSSRCDatabase()),
79       remote_ssrc_(0),
80       sequence_number_forced_(false),
81       ssrc_forced_(false),
82       timestamp_(0),
83       capture_time_ms_(0),
84       last_timestamp_time_ms_(0),
85       last_packet_marker_bit_(false),
86       num_csrcs_(0),
87       csrcs_(),
88       include_csrcs_(true),
89       rtx_(kRtxOff),
90       payload_type_rtx_(-1),
91       target_bitrate_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
92       target_bitrate_kbps_(0) {
93   memset(nack_byte_count_times_, 0, sizeof(nack_byte_count_times_));
94   memset(nack_byte_count_, 0, sizeof(nack_byte_count_));
95   memset(csrcs_, 0, sizeof(csrcs_));
96   // We need to seed the random generator.
97   srand(static_cast<uint32_t>(clock_->TimeInMilliseconds()));
98   ssrc_ = ssrc_db_.CreateSSRC();  // Can't be 0.
99   ssrc_rtx_ = ssrc_db_.CreateSSRC();  // Can't be 0.
100   // Random start, 16 bits. Can't be 0.
101   sequence_number_rtx_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;
102   sequence_number_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;
103
104   if (audio) {
105     audio_ = new RTPSenderAudio(id, clock_, this);
106     audio_->RegisterAudioCallback(audio_feedback);
107   } else {
108     video_ = new RTPSenderVideo(id, clock_, this);
109   }
110   WEBRTC_TRACE(kTraceMemory, kTraceRtpRtcp, id, "%s created", __FUNCTION__);
111 }
112
113 RTPSender::~RTPSender() {
114   if (remote_ssrc_ != 0) {
115     ssrc_db_.ReturnSSRC(remote_ssrc_);
116   }
117   ssrc_db_.ReturnSSRC(ssrc_);
118
119   SSRCDatabase::ReturnSSRCDatabase();
120   delete send_critsect_;
121   while (!payload_type_map_.empty()) {
122     std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
123         payload_type_map_.begin();
124     delete it->second;
125     payload_type_map_.erase(it);
126   }
127   delete audio_;
128   delete video_;
129
130   WEBRTC_TRACE(kTraceMemory, kTraceRtpRtcp, id_, "%s deleted", __FUNCTION__);
131 }
132
133 void RTPSender::SetTargetSendBitrate(const uint32_t bits) {
134   SetTargetBitrateKbps(static_cast<uint16_t>(bits / 1000));
135 }
136
137 uint16_t RTPSender::ActualSendBitrateKbit() const {
138   return (uint16_t)(bitrate_sent_.BitrateNow() / 1000);
139 }
140
141 uint32_t RTPSender::VideoBitrateSent() const {
142   if (video_) {
143     return video_->VideoBitrateSent();
144   }
145   return 0;
146 }
147
148 uint32_t RTPSender::FecOverheadRate() const {
149   if (video_) {
150     return video_->FecOverheadRate();
151   }
152   return 0;
153 }
154
155 uint32_t RTPSender::NackOverheadRate() const {
156   return nack_bitrate_.BitrateLast();
157 }
158
159 bool RTPSender::GetSendSideDelay(int* avg_send_delay_ms,
160                                  int* max_send_delay_ms) const {
161   if (!SendingMedia())
162     return false;
163   CriticalSectionScoped cs(statistics_crit_.get());
164   SendDelayMap::const_iterator it = send_delays_.upper_bound(
165       clock_->TimeInMilliseconds() - kSendSideDelayWindowMs);
166   if (it == send_delays_.end())
167     return false;
168   int num_delays = 0;
169   for (; it != send_delays_.end(); ++it) {
170     *max_send_delay_ms = std::max(*max_send_delay_ms, it->second);
171     *avg_send_delay_ms += it->second;
172     ++num_delays;
173   }
174   *avg_send_delay_ms = (*avg_send_delay_ms + num_delays / 2) / num_delays;
175   return true;
176 }
177
178 int32_t RTPSender::SetTransmissionTimeOffset(
179     const int32_t transmission_time_offset) {
180   if (transmission_time_offset > (0x800000 - 1) ||
181       transmission_time_offset < -(0x800000 - 1)) {  // Word24.
182     return -1;
183   }
184   CriticalSectionScoped cs(send_critsect_);
185   transmission_time_offset_ = transmission_time_offset;
186   return 0;
187 }
188
189 int32_t RTPSender::SetAbsoluteSendTime(
190     const uint32_t absolute_send_time) {
191   if (absolute_send_time > 0xffffff) {  // UWord24.
192     return -1;
193   }
194   CriticalSectionScoped cs(send_critsect_);
195   absolute_send_time_ = absolute_send_time;
196   return 0;
197 }
198
199 int32_t RTPSender::RegisterRtpHeaderExtension(const RTPExtensionType type,
200                                               const uint8_t id) {
201   CriticalSectionScoped cs(send_critsect_);
202   return rtp_header_extension_map_.Register(type, id);
203 }
204
205 int32_t RTPSender::DeregisterRtpHeaderExtension(
206     const RTPExtensionType type) {
207   CriticalSectionScoped cs(send_critsect_);
208   return rtp_header_extension_map_.Deregister(type);
209 }
210
211 uint16_t RTPSender::RtpHeaderExtensionTotalLength() const {
212   CriticalSectionScoped cs(send_critsect_);
213   return rtp_header_extension_map_.GetTotalLengthInBytes();
214 }
215
216 int32_t RTPSender::RegisterPayload(
217     const char payload_name[RTP_PAYLOAD_NAME_SIZE],
218     const int8_t payload_number, const uint32_t frequency,
219     const uint8_t channels, const uint32_t rate) {
220   assert(payload_name);
221   CriticalSectionScoped cs(send_critsect_);
222
223   std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
224       payload_type_map_.find(payload_number);
225
226   if (payload_type_map_.end() != it) {
227     // We already use this payload type.
228     ModuleRTPUtility::Payload *payload = it->second;
229     assert(payload);
230
231     // Check if it's the same as we already have.
232     if (ModuleRTPUtility::StringCompare(payload->name, payload_name,
233                                         RTP_PAYLOAD_NAME_SIZE - 1)) {
234       if (audio_configured_ && payload->audio &&
235           payload->typeSpecific.Audio.frequency == frequency &&
236           (payload->typeSpecific.Audio.rate == rate ||
237            payload->typeSpecific.Audio.rate == 0 || rate == 0)) {
238         payload->typeSpecific.Audio.rate = rate;
239         // Ensure that we update the rate if new or old is zero.
240         return 0;
241       }
242       if (!audio_configured_ && !payload->audio) {
243         return 0;
244       }
245     }
246     return -1;
247   }
248   int32_t ret_val = -1;
249   ModuleRTPUtility::Payload *payload = NULL;
250   if (audio_configured_) {
251     ret_val = audio_->RegisterAudioPayload(payload_name, payload_number,
252                                            frequency, channels, rate, payload);
253   } else {
254     ret_val = video_->RegisterVideoPayload(payload_name, payload_number, rate,
255                                            payload);
256   }
257   if (payload) {
258     payload_type_map_[payload_number] = payload;
259   }
260   return ret_val;
261 }
262
263 int32_t RTPSender::DeRegisterSendPayload(
264     const int8_t payload_type) {
265   CriticalSectionScoped lock(send_critsect_);
266
267   std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
268       payload_type_map_.find(payload_type);
269
270   if (payload_type_map_.end() == it) {
271     return -1;
272   }
273   ModuleRTPUtility::Payload *payload = it->second;
274   delete payload;
275   payload_type_map_.erase(it);
276   return 0;
277 }
278
279 int8_t RTPSender::SendPayloadType() const {
280   CriticalSectionScoped cs(send_critsect_);
281   return payload_type_;
282 }
283
284 int RTPSender::SendPayloadFrequency() const {
285   return audio_ != NULL ? audio_->AudioFrequency() : kVideoPayloadTypeFrequency;
286 }
287
288 int32_t RTPSender::SetMaxPayloadLength(
289     const uint16_t max_payload_length,
290     const uint16_t packet_over_head) {
291   // Sanity check.
292   if (max_payload_length < 100 || max_payload_length > IP_PACKET_SIZE) {
293     WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_, "%s invalid argument",
294                  __FUNCTION__);
295     return -1;
296   }
297   CriticalSectionScoped cs(send_critsect_);
298   max_payload_length_ = max_payload_length;
299   packet_over_head_ = packet_over_head;
300
301   WEBRTC_TRACE(kTraceInfo, kTraceRtpRtcp, id_, "SetMaxPayloadLength to %d.",
302                max_payload_length);
303   return 0;
304 }
305
306 uint16_t RTPSender::MaxDataPayloadLength() const {
307   if (audio_configured_) {
308     return max_payload_length_ - RTPHeaderLength();
309   } else {
310     return max_payload_length_ - RTPHeaderLength()  // RTP overhead.
311            - video_->FECPacketOverhead()            // FEC/ULP/RED overhead.
312            - ((rtx_) ? 2 : 0);                      // RTX overhead.
313   }
314 }
315
316 uint16_t RTPSender::MaxPayloadLength() const {
317   return max_payload_length_;
318 }
319
320 uint16_t RTPSender::PacketOverHead() const { return packet_over_head_; }
321
322 void RTPSender::SetRTXStatus(int mode, bool set_ssrc, uint32_t ssrc) {
323   CriticalSectionScoped cs(send_critsect_);
324   rtx_ = mode;
325   if (rtx_ != kRtxOff) {
326     if (set_ssrc) {
327       ssrc_rtx_ = ssrc;
328     } else {
329       ssrc_rtx_ = ssrc_db_.CreateSSRC();  // Can't be 0.
330     }
331   }
332 }
333
334 void RTPSender::RTXStatus(int* mode, uint32_t* ssrc,
335                           int* payload_type) const {
336   CriticalSectionScoped cs(send_critsect_);
337   *mode = rtx_;
338   *ssrc = ssrc_rtx_;
339   *payload_type = payload_type_rtx_;
340 }
341
342
343 void RTPSender::SetRtxPayloadType(int payload_type) {
344   CriticalSectionScoped cs(send_critsect_);
345   payload_type_rtx_ = payload_type;
346 }
347
348 int32_t RTPSender::CheckPayloadType(const int8_t payload_type,
349                                     RtpVideoCodecTypes *video_type) {
350   CriticalSectionScoped cs(send_critsect_);
351
352   if (payload_type < 0) {
353     WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_, "\tinvalid payload_type (%d)",
354                  payload_type);
355     return -1;
356   }
357   if (audio_configured_) {
358     int8_t red_pl_type = -1;
359     if (audio_->RED(red_pl_type) == 0) {
360       // We have configured RED.
361       if (red_pl_type == payload_type) {
362         // And it's a match...
363         return 0;
364       }
365     }
366   }
367   if (payload_type_ == payload_type) {
368     if (!audio_configured_) {
369       *video_type = video_->VideoCodecType();
370     }
371     return 0;
372   }
373   std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
374       payload_type_map_.find(payload_type);
375   if (it == payload_type_map_.end()) {
376     WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_,
377                  "\tpayloadType:%d not registered", payload_type);
378     return -1;
379   }
380   payload_type_ = payload_type;
381   ModuleRTPUtility::Payload *payload = it->second;
382   assert(payload);
383   if (!payload->audio && !audio_configured_) {
384     video_->SetVideoCodecType(payload->typeSpecific.Video.videoCodecType);
385     *video_type = payload->typeSpecific.Video.videoCodecType;
386     video_->SetMaxConfiguredBitrateVideo(payload->typeSpecific.Video.maxRate);
387   }
388   return 0;
389 }
390
391 int32_t RTPSender::SendOutgoingData(
392     const FrameType frame_type, const int8_t payload_type,
393     const uint32_t capture_timestamp, int64_t capture_time_ms,
394     const uint8_t *payload_data, const uint32_t payload_size,
395     const RTPFragmentationHeader *fragmentation,
396     VideoCodecInformation *codec_info, const RTPVideoTypeHeader *rtp_type_hdr) {
397   {
398     // Drop this packet if we're not sending media packets.
399     CriticalSectionScoped cs(send_critsect_);
400     if (!sending_media_) {
401       return 0;
402     }
403   }
404   RtpVideoCodecTypes video_type = kRtpVideoGeneric;
405   if (CheckPayloadType(payload_type, &video_type) != 0) {
406     WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_,
407                  "%s invalid argument failed to find payload_type:%d",
408                  __FUNCTION__, payload_type);
409     return -1;
410   }
411
412   uint32_t ret_val;
413   if (audio_configured_) {
414     TRACE_EVENT_ASYNC_STEP1("webrtc", "Audio", capture_timestamp,
415                             "Send", "type", FrameTypeToString(frame_type));
416     assert(frame_type == kAudioFrameSpeech || frame_type == kAudioFrameCN ||
417            frame_type == kFrameEmpty);
418
419     ret_val = audio_->SendAudio(frame_type, payload_type, capture_timestamp,
420                                 payload_data, payload_size, fragmentation);
421   } else {
422     TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", capture_time_ms,
423                             "Send", "type", FrameTypeToString(frame_type));
424     assert(frame_type != kAudioFrameSpeech && frame_type != kAudioFrameCN);
425
426     if (frame_type == kFrameEmpty) {
427       if (paced_sender_->Enabled()) {
428         // Padding is driven by the pacer and not by the encoder.
429         return 0;
430       }
431       return SendPaddingAccordingToBitrate(payload_type, capture_timestamp,
432                                            capture_time_ms) ? 0 : -1;
433     }
434     ret_val = video_->SendVideo(video_type, frame_type, payload_type,
435                                 capture_timestamp, capture_time_ms,
436                                 payload_data, payload_size,
437                                 fragmentation, codec_info,
438                                 rtp_type_hdr);
439
440   }
441
442   CriticalSectionScoped cs(statistics_crit_.get());
443   uint32_t frame_count = ++frame_counts_[frame_type];
444   if (frame_count_observer_) {
445     frame_count_observer_->FrameCountUpdated(frame_type,
446                                              frame_count,
447                                              ssrc_);
448   }
449
450   return ret_val;
451 }
452
453 int RTPSender::SendRedundantPayloads(int payload_type, int bytes_to_send) {
454   if (!(rtx_ & kRtxRedundantPayloads))
455     return 0;
456   uint8_t buffer[IP_PACKET_SIZE];
457   int bytes_left = bytes_to_send;
458   while (bytes_left > 0) {
459     uint16_t length = bytes_left;
460     int64_t capture_time_ms;
461     if (!packet_history_.GetBestFittingPacket(buffer, &length,
462                                               &capture_time_ms)) {
463       break;
464     }
465     if (!PrepareAndSendPacket(buffer, length, capture_time_ms, true, false))
466       return -1;
467     ModuleRTPUtility::RTPHeaderParser rtp_parser(buffer, length);
468     RTPHeader rtp_header;
469     rtp_parser.Parse(rtp_header);
470     bytes_left -= length - rtp_header.headerLength;
471   }
472   return bytes_to_send - bytes_left;
473 }
474
475 bool RTPSender::SendPaddingAccordingToBitrate(
476     int8_t payload_type, uint32_t capture_timestamp,
477     int64_t capture_time_ms) {
478   // Current bitrate since last estimate(1 second) averaged with the
479   // estimate since then, to get the most up to date bitrate.
480   uint32_t current_bitrate = bitrate_sent_.BitrateNow();
481   uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
482   int bitrate_diff = target_bitrate_kbps * 1000 - current_bitrate;
483   if (bitrate_diff <= 0) {
484     return true;
485   }
486   int bytes = 0;
487   if (current_bitrate == 0) {
488     // Start up phase. Send one 33.3 ms batch to start with.
489     bytes = (bitrate_diff / 8) / 30;
490   } else {
491     bytes = (bitrate_diff / 8);
492     // Cap at 200 ms of target send data.
493     int bytes_cap = target_bitrate_kbps * 25;  // 1000 / 8 / 5.
494     if (bytes > bytes_cap) {
495       bytes = bytes_cap;
496     }
497   }
498   uint32_t timestamp;
499   {
500     CriticalSectionScoped cs(send_critsect_);
501     // Add the random RTP timestamp offset and store the capture time for
502     // later calculation of the send time offset.
503     timestamp = start_time_stamp_ + capture_timestamp;
504     timestamp_ = timestamp;
505     capture_time_ms_ = capture_time_ms;
506     last_timestamp_time_ms_ = clock_->TimeInMilliseconds();
507   }
508   int bytes_sent = SendPadData(payload_type, timestamp, capture_time_ms,
509                                bytes, kDontRetransmit, false, false);
510   // We did not manage to send all bytes. Comparing with 31 due to modulus 32.
511   return bytes - bytes_sent < 31;
512 }
513
514 int RTPSender::BuildPaddingPacket(uint8_t* packet, int header_length,
515                                   int32_t bytes) {
516   int padding_bytes_in_packet = kMaxPaddingLength;
517   if (bytes < kMaxPaddingLength) {
518     padding_bytes_in_packet = bytes;
519   }
520   packet[0] |= 0x20;  // Set padding bit.
521   int32_t *data =
522       reinterpret_cast<int32_t *>(&(packet[header_length]));
523
524   // Fill data buffer with random data.
525   for (int j = 0; j < (padding_bytes_in_packet >> 2); ++j) {
526     data[j] = rand();  // NOLINT
527   }
528   // Set number of padding bytes in the last byte of the packet.
529   packet[header_length + padding_bytes_in_packet - 1] = padding_bytes_in_packet;
530   return padding_bytes_in_packet;
531 }
532
533 int RTPSender::SendPadData(int payload_type, uint32_t timestamp,
534                            int64_t capture_time_ms, int32_t bytes,
535                            StorageType store, bool force_full_size_packets,
536                            bool only_pad_after_markerbit) {
537   // Drop this packet if we're not sending media packets.
538   if (!SendingMedia()) {
539     return bytes;
540   }
541   int padding_bytes_in_packet = 0;
542   int bytes_sent = 0;
543   for (; bytes > 0; bytes -= padding_bytes_in_packet) {
544     // Always send full padding packets.
545     if (force_full_size_packets && bytes < kMaxPaddingLength)
546       bytes = kMaxPaddingLength;
547     if (bytes < kMaxPaddingLength) {
548       if (force_full_size_packets) {
549         bytes = kMaxPaddingLength;
550       } else {
551         // Round to the nearest multiple of 32.
552         bytes = (bytes + 16) & 0xffe0;
553       }
554     }
555     if (bytes < 32) {
556       // Sanity don't send empty packets.
557       break;
558     }
559     uint32_t ssrc;
560     uint16_t sequence_number;
561     {
562       CriticalSectionScoped cs(send_critsect_);
563       // Only send padding packets following the last packet of a frame,
564       // indicated by the marker bit.
565       if (only_pad_after_markerbit && !last_packet_marker_bit_)
566         return bytes_sent;
567       if (rtx_ == kRtxOff) {
568         ssrc = ssrc_;
569         sequence_number = sequence_number_;
570         ++sequence_number_;
571       } else {
572         ssrc = ssrc_rtx_;
573         sequence_number = sequence_number_rtx_;
574         ++sequence_number_rtx_;
575       }
576     }
577     uint8_t padding_packet[IP_PACKET_SIZE];
578     int header_length = CreateRTPHeader(padding_packet, payload_type, ssrc,
579                                         false, timestamp, sequence_number, NULL,
580                                         0);
581     padding_bytes_in_packet = BuildPaddingPacket(padding_packet, header_length,
582                                                  bytes);
583     if (0 > SendToNetwork(padding_packet, padding_bytes_in_packet,
584                           header_length, capture_time_ms, store,
585                           PacedSender::kLowPriority)) {
586       // Error sending the packet.
587       break;
588     }
589     bytes_sent += padding_bytes_in_packet;
590   }
591   return bytes_sent;
592 }
593
594 void RTPSender::SetStorePacketsStatus(const bool enable,
595                                       const uint16_t number_to_store) {
596   packet_history_.SetStorePacketsStatus(enable, number_to_store);
597 }
598
599 bool RTPSender::StorePackets() const {
600   return packet_history_.StorePackets();
601 }
602
603 int32_t RTPSender::ReSendPacket(uint16_t packet_id, uint32_t min_resend_time) {
604   uint16_t length = IP_PACKET_SIZE;
605   uint8_t data_buffer[IP_PACKET_SIZE];
606   int64_t capture_time_ms;
607   if (!packet_history_.GetPacketAndSetSendTime(packet_id, min_resend_time, true,
608                                                data_buffer, &length,
609                                                &capture_time_ms)) {
610     // Packet not found.
611     return 0;
612   }
613
614   if (paced_sender_) {
615     ModuleRTPUtility::RTPHeaderParser rtp_parser(data_buffer, length);
616     RTPHeader header;
617     if (!rtp_parser.Parse(header)) {
618       assert(false);
619       WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_,
620                    "Failed to parse RTP header of packet to be retransmitted.");
621       return -1;
622     }
623     if (!paced_sender_->SendPacket(PacedSender::kHighPriority,
624                                    header.ssrc,
625                                    header.sequenceNumber,
626                                    capture_time_ms,
627                                    length - header.headerLength,
628                                    true)) {
629       // We can't send the packet right now.
630       // We will be called when it is time.
631       return length;
632     }
633   }
634
635   return PrepareAndSendPacket(data_buffer, length, capture_time_ms,
636                               (rtx_ & kRtxRetransmitted) > 0, true) ?
637       length : -1;
638 }
639
640 bool RTPSender::SendPacketToNetwork(const uint8_t *packet, uint32_t size) {
641   int bytes_sent = -1;
642   if (transport_) {
643     bytes_sent = transport_->SendPacket(id_, packet, size);
644   }
645   TRACE_EVENT_INSTANT2("webrtc_rtp", "RTPSender::SendPacketToNetwork",
646                        "size", size, "sent", bytes_sent);
647   // TODO(pwesin): Add a separate bitrate for sent bitrate after pacer.
648   if (bytes_sent <= 0) {
649     WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
650                  "Transport failed to send packet");
651     return false;
652   }
653   return true;
654 }
655
656 int RTPSender::SelectiveRetransmissions() const {
657   if (!video_)
658     return -1;
659   return video_->SelectiveRetransmissions();
660 }
661
662 int RTPSender::SetSelectiveRetransmissions(uint8_t settings) {
663   if (!video_)
664     return -1;
665   return video_->SetSelectiveRetransmissions(settings);
666 }
667
668 void RTPSender::OnReceivedNACK(
669     const std::list<uint16_t>& nack_sequence_numbers,
670     const uint16_t avg_rtt) {
671   TRACE_EVENT2("webrtc_rtp", "RTPSender::OnReceivedNACK",
672                "num_seqnum", nack_sequence_numbers.size(), "avg_rtt", avg_rtt);
673   const int64_t now = clock_->TimeInMilliseconds();
674   uint32_t bytes_re_sent = 0;
675   uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
676
677   // Enough bandwidth to send NACK?
678   if (!ProcessNACKBitRate(now)) {
679     WEBRTC_TRACE(kTraceStream,
680                  kTraceRtpRtcp,
681                  id_,
682                  "NACK bitrate reached. Skip sending NACK response. Target %d",
683                  target_bitrate_kbps);
684     return;
685   }
686
687   for (std::list<uint16_t>::const_iterator it = nack_sequence_numbers.begin();
688       it != nack_sequence_numbers.end(); ++it) {
689     const int32_t bytes_sent = ReSendPacket(*it, 5 + avg_rtt);
690     if (bytes_sent > 0) {
691       bytes_re_sent += bytes_sent;
692     } else if (bytes_sent == 0) {
693       // The packet has previously been resent.
694       // Try resending next packet in the list.
695       continue;
696     } else if (bytes_sent < 0) {
697       // Failed to send one Sequence number. Give up the rest in this nack.
698       WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
699                    "Failed resending RTP packet %d, Discard rest of packets",
700                    *it);
701       break;
702     }
703     // Delay bandwidth estimate (RTT * BW).
704     if (target_bitrate_kbps != 0 && avg_rtt) {
705       // kbits/s * ms = bits => bits/8 = bytes
706       uint32_t target_bytes =
707           (static_cast<uint32_t>(target_bitrate_kbps) * avg_rtt) >> 3;
708       if (bytes_re_sent > target_bytes) {
709         break;  // Ignore the rest of the packets in the list.
710       }
711     }
712   }
713   if (bytes_re_sent > 0) {
714     // TODO(pwestin) consolidate these two methods.
715     UpdateNACKBitRate(bytes_re_sent, now);
716     nack_bitrate_.Update(bytes_re_sent);
717   }
718 }
719
720 bool RTPSender::ProcessNACKBitRate(const uint32_t now) {
721   uint32_t num = 0;
722   int32_t byte_count = 0;
723   const uint32_t avg_interval = 1000;
724   uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
725
726   CriticalSectionScoped cs(send_critsect_);
727
728   if (target_bitrate_kbps == 0) {
729     return true;
730   }
731   for (num = 0; num < NACK_BYTECOUNT_SIZE; ++num) {
732     if ((now - nack_byte_count_times_[num]) > avg_interval) {
733       // Don't use data older than 1sec.
734       break;
735     } else {
736       byte_count += nack_byte_count_[num];
737     }
738   }
739   int32_t time_interval = avg_interval;
740   if (num == NACK_BYTECOUNT_SIZE) {
741     // More than NACK_BYTECOUNT_SIZE nack messages has been received
742     // during the last msg_interval.
743     time_interval = now - nack_byte_count_times_[num - 1];
744     if (time_interval < 0) {
745       time_interval = avg_interval;
746     }
747   }
748   return (byte_count * 8) < (target_bitrate_kbps * time_interval);
749 }
750
751 void RTPSender::UpdateNACKBitRate(const uint32_t bytes,
752                                   const uint32_t now) {
753   CriticalSectionScoped cs(send_critsect_);
754
755   // Save bitrate statistics.
756   if (bytes > 0) {
757     if (now == 0) {
758       // Add padding length.
759       nack_byte_count_[0] += bytes;
760     } else {
761       if (nack_byte_count_times_[0] == 0) {
762         // First no shift.
763       } else {
764         // Shift.
765         for (int i = (NACK_BYTECOUNT_SIZE - 2); i >= 0; i--) {
766           nack_byte_count_[i + 1] = nack_byte_count_[i];
767           nack_byte_count_times_[i + 1] = nack_byte_count_times_[i];
768         }
769       }
770       nack_byte_count_[0] = bytes;
771       nack_byte_count_times_[0] = now;
772     }
773   }
774 }
775
776 // Called from pacer when we can send the packet.
777 bool RTPSender::TimeToSendPacket(uint16_t sequence_number,
778                                  int64_t capture_time_ms,
779                                  bool retransmission) {
780   uint16_t length = IP_PACKET_SIZE;
781   uint8_t data_buffer[IP_PACKET_SIZE];
782   int64_t stored_time_ms;
783
784   if (!packet_history_.GetPacketAndSetSendTime(sequence_number,
785                                                0,
786                                                retransmission,
787                                                data_buffer,
788                                                &length,
789                                                &stored_time_ms)) {
790     // Packet cannot be found. Allow sending to continue.
791     return true;
792   }
793   if (!retransmission && capture_time_ms > 0) {
794     UpdateDelayStatistics(capture_time_ms, clock_->TimeInMilliseconds());
795   }
796   return PrepareAndSendPacket(data_buffer, length, capture_time_ms,
797                               retransmission && (rtx_ & kRtxRetransmitted) > 0,
798                               retransmission);
799 }
800
801 bool RTPSender::PrepareAndSendPacket(uint8_t* buffer,
802                                      uint16_t length,
803                                      int64_t capture_time_ms,
804                                      bool send_over_rtx,
805                                      bool is_retransmit) {
806   uint8_t *buffer_to_send_ptr = buffer;
807
808   ModuleRTPUtility::RTPHeaderParser rtp_parser(buffer, length);
809   RTPHeader rtp_header;
810   rtp_parser.Parse(rtp_header);
811   TRACE_EVENT_INSTANT2("webrtc_rtp", "PrepareAndSendPacket",
812                        "timestamp", rtp_header.timestamp,
813                        "seqnum", rtp_header.sequenceNumber);
814
815   uint8_t data_buffer_rtx[IP_PACKET_SIZE];
816   if (send_over_rtx) {
817     BuildRtxPacket(buffer, &length, data_buffer_rtx);
818     buffer_to_send_ptr = data_buffer_rtx;
819   }
820
821   int64_t now_ms = clock_->TimeInMilliseconds();
822   int64_t diff_ms = now_ms - capture_time_ms;
823   bool updated_transmission_time_offset =
824       UpdateTransmissionTimeOffset(buffer_to_send_ptr, length, rtp_header,
825                                    diff_ms);
826   bool updated_abs_send_time =
827       UpdateAbsoluteSendTime(buffer_to_send_ptr, length, rtp_header, now_ms);
828   if (updated_transmission_time_offset || updated_abs_send_time) {
829     // Update stored packet in case of receiving a re-transmission request.
830     packet_history_.ReplaceRTPHeader(buffer_to_send_ptr,
831                                      rtp_header.sequenceNumber,
832                                      rtp_header.headerLength);
833   }
834
835   bool ret = SendPacketToNetwork(buffer_to_send_ptr, length);
836   UpdateRtpStats(buffer_to_send_ptr, length, rtp_header, send_over_rtx,
837                  is_retransmit);
838   return ret;
839 }
840
841 void RTPSender::UpdateRtpStats(const uint8_t* buffer,
842                                uint32_t size,
843                                const RTPHeader& header,
844                                bool is_rtx,
845                                bool is_retransmit) {
846   StreamDataCounters* counters;
847   // Get ssrc before taking statistics_crit_ to avoid possible deadlock.
848   uint32_t ssrc = SSRC();
849
850   CriticalSectionScoped lock(statistics_crit_.get());
851   if (is_rtx) {
852     counters = &rtx_rtp_stats_;
853     ssrc = ssrc_rtx_;
854   } else {
855     counters = &rtp_stats_;
856   }
857
858   bitrate_sent_.Update(size);
859   ++counters->packets;
860   if (IsFecPacket(buffer, header)) {
861     ++counters->fec_packets;
862   }
863
864   if (is_retransmit) {
865     ++counters->retransmitted_packets;
866   } else {
867     counters->bytes += size - (header.headerLength + header.paddingLength);
868     counters->header_bytes += header.headerLength;
869     counters->padding_bytes += header.paddingLength;
870   }
871
872   if (rtp_stats_callback_) {
873     rtp_stats_callback_->DataCountersUpdated(*counters, ssrc);
874   }
875 }
876
877 bool RTPSender::IsFecPacket(const uint8_t* buffer,
878                             const RTPHeader& header) const {
879   if (!video_) {
880     return false;
881   }
882   bool fec_enabled;
883   uint8_t pt_red;
884   uint8_t pt_fec;
885   video_->GenericFECStatus(fec_enabled, pt_red, pt_fec);
886   return fec_enabled &&
887       header.payloadType == pt_red &&
888       buffer[header.headerLength] == pt_fec;
889 }
890
891 int RTPSender::TimeToSendPadding(int bytes) {
892   int payload_type;
893   int64_t capture_time_ms;
894   uint32_t timestamp;
895   {
896     CriticalSectionScoped cs(send_critsect_);
897     if (!sending_media_) {
898       return 0;
899     }
900     payload_type = ((rtx_ & kRtxRedundantPayloads) > 0) ? payload_type_rtx_ :
901         payload_type_;
902     timestamp = timestamp_;
903     capture_time_ms = capture_time_ms_;
904     if (last_timestamp_time_ms_ > 0) {
905       timestamp +=
906           (clock_->TimeInMilliseconds() - last_timestamp_time_ms_) * 90;
907       capture_time_ms +=
908           (clock_->TimeInMilliseconds() - last_timestamp_time_ms_);
909     }
910   }
911   int bytes_sent = SendRedundantPayloads(payload_type, bytes);
912   bytes -= bytes_sent;
913   if (bytes > 0) {
914     int padding_sent = SendPadData(payload_type, timestamp, capture_time_ms,
915                                    bytes, kDontStore, true, true);
916     bytes_sent += padding_sent;
917   }
918   return bytes_sent;
919 }
920
921 // TODO(pwestin): send in the RTPHeaderParser to avoid parsing it again.
922 int32_t RTPSender::SendToNetwork(
923     uint8_t *buffer, int payload_length, int rtp_header_length,
924     int64_t capture_time_ms, StorageType storage,
925     PacedSender::Priority priority) {
926   ModuleRTPUtility::RTPHeaderParser rtp_parser(
927       buffer, payload_length + rtp_header_length);
928   RTPHeader rtp_header;
929   rtp_parser.Parse(rtp_header);
930
931   int64_t now_ms = clock_->TimeInMilliseconds();
932
933   // |capture_time_ms| <= 0 is considered invalid.
934   // TODO(holmer): This should be changed all over Video Engine so that negative
935   // time is consider invalid, while 0 is considered a valid time.
936   if (capture_time_ms > 0) {
937     UpdateTransmissionTimeOffset(buffer, payload_length + rtp_header_length,
938                                  rtp_header, now_ms - capture_time_ms);
939   }
940
941   UpdateAbsoluteSendTime(buffer, payload_length + rtp_header_length,
942                          rtp_header, now_ms);
943
944   // Used for NACK and to spread out the transmission of packets.
945   if (packet_history_.PutRTPPacket(buffer, rtp_header_length + payload_length,
946                                    max_payload_length_, capture_time_ms,
947                                    storage) != 0) {
948     return -1;
949   }
950
951   if (paced_sender_ && storage != kDontStore) {
952     if (!paced_sender_->SendPacket(priority, rtp_header.ssrc,
953                                    rtp_header.sequenceNumber, capture_time_ms,
954                                    payload_length, false)) {
955       // We can't send the packet right now.
956       // We will be called when it is time.
957       return 0;
958     }
959   }
960   if (capture_time_ms > 0) {
961     UpdateDelayStatistics(capture_time_ms, now_ms);
962   }
963   uint32_t length = payload_length + rtp_header_length;
964   if (!SendPacketToNetwork(buffer, length))
965     return -1;
966   UpdateRtpStats(buffer, length, rtp_header, false, false);
967   return 0;
968 }
969
970 void RTPSender::UpdateDelayStatistics(int64_t capture_time_ms, int64_t now_ms) {
971   CriticalSectionScoped cs(statistics_crit_.get());
972   send_delays_[now_ms] = now_ms - capture_time_ms;
973   send_delays_.erase(send_delays_.begin(),
974                      send_delays_.lower_bound(now_ms - kSendSideDelayWindowMs));
975 }
976
977 void RTPSender::ProcessBitrate() {
978   CriticalSectionScoped cs(send_critsect_);
979   bitrate_sent_.Process();
980   nack_bitrate_.Process();
981   if (audio_configured_) {
982     return;
983   }
984   video_->ProcessBitrate();
985 }
986
987 uint16_t RTPSender::RTPHeaderLength() const {
988   uint16_t rtp_header_length = 12;
989   if (include_csrcs_) {
990     rtp_header_length += sizeof(uint32_t) * num_csrcs_;
991   }
992   rtp_header_length += RtpHeaderExtensionTotalLength();
993   return rtp_header_length;
994 }
995
996 uint16_t RTPSender::IncrementSequenceNumber() {
997   CriticalSectionScoped cs(send_critsect_);
998   return sequence_number_++;
999 }
1000
1001 void RTPSender::ResetDataCounters() {
1002   CriticalSectionScoped lock(statistics_crit_.get());
1003   rtp_stats_ = StreamDataCounters();
1004   rtx_rtp_stats_ = StreamDataCounters();
1005   if (rtp_stats_callback_) {
1006     rtp_stats_callback_->DataCountersUpdated(rtp_stats_, ssrc_);
1007     rtp_stats_callback_->DataCountersUpdated(rtx_rtp_stats_, ssrc_rtx_);
1008   }
1009 }
1010
1011 uint32_t RTPSender::Packets() const {
1012   CriticalSectionScoped lock(statistics_crit_.get());
1013   return rtp_stats_.packets + rtx_rtp_stats_.packets;
1014 }
1015
1016 // Number of sent RTP bytes.
1017 uint32_t RTPSender::Bytes() const {
1018   CriticalSectionScoped lock(statistics_crit_.get());
1019   return rtp_stats_.bytes + rtx_rtp_stats_.bytes;
1020 }
1021
1022 int RTPSender::CreateRTPHeader(
1023     uint8_t* header, int8_t payload_type, uint32_t ssrc, bool marker_bit,
1024     uint32_t timestamp, uint16_t sequence_number, const uint32_t* csrcs,
1025     uint8_t num_csrcs) const {
1026   header[0] = 0x80;  // version 2.
1027   header[1] = static_cast<uint8_t>(payload_type);
1028   if (marker_bit) {
1029     header[1] |= kRtpMarkerBitMask;  // Marker bit is set.
1030   }
1031   ModuleRTPUtility::AssignUWord16ToBuffer(header + 2, sequence_number);
1032   ModuleRTPUtility::AssignUWord32ToBuffer(header + 4, timestamp);
1033   ModuleRTPUtility::AssignUWord32ToBuffer(header + 8, ssrc);
1034   int32_t rtp_header_length = 12;
1035
1036   // Add the CSRCs if any.
1037   if (num_csrcs > 0) {
1038     if (num_csrcs > kRtpCsrcSize) {
1039       // error
1040       assert(false);
1041       return -1;
1042     }
1043     uint8_t *ptr = &header[rtp_header_length];
1044     for (int i = 0; i < num_csrcs; ++i) {
1045       ModuleRTPUtility::AssignUWord32ToBuffer(ptr, csrcs[i]);
1046       ptr += 4;
1047     }
1048     header[0] = (header[0] & 0xf0) | num_csrcs;
1049
1050     // Update length of header.
1051     rtp_header_length += sizeof(uint32_t) * num_csrcs;
1052   }
1053
1054   uint16_t len = BuildRTPHeaderExtension(header + rtp_header_length);
1055   if (len > 0) {
1056     header[0] |= 0x10;  // Set extension bit.
1057     rtp_header_length += len;
1058   }
1059   return rtp_header_length;
1060 }
1061
1062 int32_t RTPSender::BuildRTPheader(
1063     uint8_t *data_buffer, const int8_t payload_type,
1064     const bool marker_bit, const uint32_t capture_timestamp,
1065     int64_t capture_time_ms, const bool time_stamp_provided,
1066     const bool inc_sequence_number) {
1067   assert(payload_type >= 0);
1068   CriticalSectionScoped cs(send_critsect_);
1069
1070   if (time_stamp_provided) {
1071     timestamp_ = start_time_stamp_ + capture_timestamp;
1072   } else {
1073     // Make a unique time stamp.
1074     // We can't inc by the actual time, since then we increase the risk of back
1075     // timing.
1076     timestamp_++;
1077   }
1078   last_timestamp_time_ms_ = clock_->TimeInMilliseconds();
1079   uint32_t sequence_number = sequence_number_++;
1080   capture_time_ms_ = capture_time_ms;
1081   last_packet_marker_bit_ = marker_bit;
1082   int csrcs_length = 0;
1083   if (include_csrcs_)
1084     csrcs_length = num_csrcs_;
1085   return CreateRTPHeader(data_buffer, payload_type, ssrc_, marker_bit,
1086                          timestamp_, sequence_number, csrcs_, csrcs_length);
1087 }
1088
1089 uint16_t RTPSender::BuildRTPHeaderExtension(uint8_t* data_buffer) const {
1090   if (rtp_header_extension_map_.Size() <= 0) {
1091     return 0;
1092   }
1093   // RTP header extension, RFC 3550.
1094   //   0                   1                   2                   3
1095   //   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1096   //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1097   //  |      defined by profile       |           length              |
1098   //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1099   //  |                        header extension                       |
1100   //  |                             ....                              |
1101   //
1102   const uint32_t kPosLength = 2;
1103   const uint32_t kHeaderLength = kRtpOneByteHeaderLength;
1104
1105   // Add extension ID (0xBEDE).
1106   ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer,
1107                                           kRtpOneByteHeaderExtensionId);
1108
1109   // Add extensions.
1110   uint16_t total_block_length = 0;
1111
1112   RTPExtensionType type = rtp_header_extension_map_.First();
1113   while (type != kRtpExtensionNone) {
1114     uint8_t block_length = 0;
1115     switch (type) {
1116       case kRtpExtensionTransmissionTimeOffset:
1117         block_length = BuildTransmissionTimeOffsetExtension(
1118             data_buffer + kHeaderLength + total_block_length);
1119         break;
1120       case kRtpExtensionAudioLevel:
1121         block_length = BuildAudioLevelExtension(
1122             data_buffer + kHeaderLength + total_block_length);
1123         break;
1124       case kRtpExtensionAbsoluteSendTime:
1125         block_length = BuildAbsoluteSendTimeExtension(
1126             data_buffer + kHeaderLength + total_block_length);
1127         break;
1128       default:
1129         assert(false);
1130     }
1131     total_block_length += block_length;
1132     type = rtp_header_extension_map_.Next(type);
1133   }
1134   if (total_block_length == 0) {
1135     // No extension added.
1136     return 0;
1137   }
1138   // Set header length (in number of Word32, header excluded).
1139   assert(total_block_length % 4 == 0);
1140   ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer + kPosLength,
1141                                           total_block_length / 4);
1142   // Total added length.
1143   return kHeaderLength + total_block_length;
1144 }
1145
1146 uint8_t RTPSender::BuildTransmissionTimeOffsetExtension(
1147     uint8_t* data_buffer) const {
1148   // From RFC 5450: Transmission Time Offsets in RTP Streams.
1149   //
1150   // The transmission time is signaled to the receiver in-band using the
1151   // general mechanism for RTP header extensions [RFC5285]. The payload
1152   // of this extension (the transmitted value) is a 24-bit signed integer.
1153   // When added to the RTP timestamp of the packet, it represents the
1154   // "effective" RTP transmission time of the packet, on the RTP
1155   // timescale.
1156   //
1157   // The form of the transmission offset extension block:
1158   //
1159   //    0                   1                   2                   3
1160   //    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1161   //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1162   //   |  ID   | len=2 |              transmission offset              |
1163   //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1164
1165   // Get id defined by user.
1166   uint8_t id;
1167   if (rtp_header_extension_map_.GetId(kRtpExtensionTransmissionTimeOffset,
1168                                       &id) != 0) {
1169     // Not registered.
1170     return 0;
1171   }
1172   size_t pos = 0;
1173   const uint8_t len = 2;
1174   data_buffer[pos++] = (id << 4) + len;
1175   ModuleRTPUtility::AssignUWord24ToBuffer(data_buffer + pos,
1176                                           transmission_time_offset_);
1177   pos += 3;
1178   assert(pos == kTransmissionTimeOffsetLength);
1179   return kTransmissionTimeOffsetLength;
1180 }
1181
1182 uint8_t RTPSender::BuildAudioLevelExtension(uint8_t* data_buffer) const {
1183   // An RTP Header Extension for Client-to-Mixer Audio Level Indication
1184   //
1185   // https://datatracker.ietf.org/doc/draft-lennox-avt-rtp-audio-level-exthdr/
1186   //
1187   // The form of the audio level extension block:
1188   //
1189   //    0                   1                   2                   3
1190   //    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1191   //    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1192   //    |  ID   | len=0 |V|   level     |      0x00     |      0x00     |
1193   //    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1194   //
1195   // Note that we always include 2 pad bytes, which will result in legal and
1196   // correctly parsed RTP, but may be a bit wasteful if more short extensions
1197   // are implemented. Right now the pad bytes would anyway be required at end
1198   // of the extension block, so it makes no difference.
1199
1200   // Get id defined by user.
1201   uint8_t id;
1202   if (rtp_header_extension_map_.GetId(kRtpExtensionAudioLevel, &id) != 0) {
1203     // Not registered.
1204     return 0;
1205   }
1206   size_t pos = 0;
1207   const uint8_t len = 0;
1208   data_buffer[pos++] = (id << 4) + len;
1209   data_buffer[pos++] = (1 << 7) + 0;     // Voice, 0 dBov.
1210   data_buffer[pos++] = 0;                // Padding.
1211   data_buffer[pos++] = 0;                // Padding.
1212   // kAudioLevelLength is including pad bytes.
1213   assert(pos == kAudioLevelLength);
1214   return kAudioLevelLength;
1215 }
1216
1217 uint8_t RTPSender::BuildAbsoluteSendTimeExtension(uint8_t* data_buffer) const {
1218   // Absolute send time in RTP streams.
1219   //
1220   // The absolute send time is signaled to the receiver in-band using the
1221   // general mechanism for RTP header extensions [RFC5285]. The payload
1222   // of this extension (the transmitted value) is a 24-bit unsigned integer
1223   // containing the sender's current time in seconds as a fixed point number
1224   // with 18 bits fractional part.
1225   //
1226   // The form of the absolute send time extension block:
1227   //
1228   //    0                   1                   2                   3
1229   //    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1230   //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1231   //   |  ID   | len=2 |              absolute send time               |
1232   //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1233
1234   // Get id defined by user.
1235   uint8_t id;
1236   if (rtp_header_extension_map_.GetId(kRtpExtensionAbsoluteSendTime,
1237                                       &id) != 0) {
1238     // Not registered.
1239     return 0;
1240   }
1241   size_t pos = 0;
1242   const uint8_t len = 2;
1243   data_buffer[pos++] = (id << 4) + len;
1244   ModuleRTPUtility::AssignUWord24ToBuffer(data_buffer + pos,
1245                                           absolute_send_time_);
1246   pos += 3;
1247   assert(pos == kAbsoluteSendTimeLength);
1248   return kAbsoluteSendTimeLength;
1249 }
1250
1251 bool RTPSender::UpdateTransmissionTimeOffset(
1252     uint8_t *rtp_packet, const uint16_t rtp_packet_length,
1253     const RTPHeader &rtp_header, const int64_t time_diff_ms) const {
1254   CriticalSectionScoped cs(send_critsect_);
1255
1256   // Get length until start of header extension block.
1257   int extension_block_pos =
1258       rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1259           kRtpExtensionTransmissionTimeOffset);
1260   if (extension_block_pos < 0) {
1261     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1262                  "Failed to update transmission time offset, not registered.");
1263     return false;
1264   }
1265   int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1266   if (rtp_packet_length < block_pos + kTransmissionTimeOffsetLength ||
1267       rtp_header.headerLength <
1268           block_pos + kTransmissionTimeOffsetLength) {
1269     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1270                  "Failed to update transmission time offset, invalid length.");
1271     return false;
1272   }
1273   // Verify that header contains extension.
1274   if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1275         (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1276     WEBRTC_TRACE(
1277         kTraceStream, kTraceRtpRtcp, id_,
1278         "Failed to update transmission time offset, hdr extension not found.");
1279     return false;
1280   }
1281   // Get id.
1282   uint8_t id = 0;
1283   if (rtp_header_extension_map_.GetId(kRtpExtensionTransmissionTimeOffset,
1284                                       &id) != 0) {
1285     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1286                  "Failed to update transmission time offset, no id.");
1287     return false;
1288   }
1289   // Verify first byte in block.
1290   const uint8_t first_block_byte = (id << 4) + 2;
1291   if (rtp_packet[block_pos] != first_block_byte) {
1292     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1293                  "Failed to update transmission time offset.");
1294     return false;
1295   }
1296   // Update transmission offset field (converting to a 90 kHz timestamp).
1297   ModuleRTPUtility::AssignUWord24ToBuffer(rtp_packet + block_pos + 1,
1298                                           time_diff_ms * 90);  // RTP timestamp.
1299   return true;
1300 }
1301
1302 bool RTPSender::UpdateAudioLevel(uint8_t *rtp_packet,
1303                                  const uint16_t rtp_packet_length,
1304                                  const RTPHeader &rtp_header,
1305                                  const bool is_voiced,
1306                                  const uint8_t dBov) const {
1307   CriticalSectionScoped cs(send_critsect_);
1308
1309   // Get length until start of header extension block.
1310   int extension_block_pos =
1311       rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1312           kRtpExtensionAudioLevel);
1313   if (extension_block_pos < 0) {
1314     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1315                  "Failed to update audio level, not registered.");
1316     return false;
1317   }
1318   int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1319   if (rtp_packet_length < block_pos + kAudioLevelLength ||
1320       rtp_header.headerLength < block_pos + kAudioLevelLength) {
1321     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1322                  "Failed to update audio level, invalid length.");
1323     return false;
1324   }
1325   // Verify that header contains extension.
1326   if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1327         (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1328     WEBRTC_TRACE(
1329         kTraceStream, kTraceRtpRtcp, id_,
1330         "Failed to update audio level, hdr extension not found.");
1331     return false;
1332   }
1333   // Get id.
1334   uint8_t id = 0;
1335   if (rtp_header_extension_map_.GetId(kRtpExtensionAudioLevel, &id) != 0) {
1336     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1337                  "Failed to update audio level, no id.");
1338     return false;
1339   }
1340   // Verify first byte in block.
1341   const uint8_t first_block_byte = (id << 4) + 0;
1342   if (rtp_packet[block_pos] != first_block_byte) {
1343     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1344                  "Failed to update audio level.");
1345     return false;
1346   }
1347   rtp_packet[block_pos + 1] = (is_voiced ? 0x80 : 0x00) + (dBov & 0x7f);
1348   return true;
1349 }
1350
1351 bool RTPSender::UpdateAbsoluteSendTime(
1352     uint8_t *rtp_packet, const uint16_t rtp_packet_length,
1353     const RTPHeader &rtp_header, const int64_t now_ms) const {
1354   CriticalSectionScoped cs(send_critsect_);
1355
1356   // Get length until start of header extension block.
1357   int extension_block_pos =
1358       rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1359           kRtpExtensionAbsoluteSendTime);
1360   if (extension_block_pos < 0) {
1361     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1362                  "Failed to update absolute send time, not registered.");
1363     return false;
1364   }
1365   int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1366   if (rtp_packet_length < block_pos + kAbsoluteSendTimeLength ||
1367       rtp_header.headerLength < block_pos + kAbsoluteSendTimeLength) {
1368     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1369                  "Failed to update absolute send time, invalid length.");
1370     return false;
1371   }
1372   // Verify that header contains extension.
1373   if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1374         (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1375     WEBRTC_TRACE(
1376         kTraceStream, kTraceRtpRtcp, id_,
1377         "Failed to update absolute send time, hdr extension not found.");
1378     return false;
1379   }
1380   // Get id.
1381   uint8_t id = 0;
1382   if (rtp_header_extension_map_.GetId(kRtpExtensionAbsoluteSendTime,
1383                                       &id) != 0) {
1384     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1385                  "Failed to update absolute send time, no id.");
1386     return false;
1387   }
1388   // Verify first byte in block.
1389   const uint8_t first_block_byte = (id << 4) + 2;
1390   if (rtp_packet[block_pos] != first_block_byte) {
1391     WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1392                  "Failed to update absolute send time.");
1393     return false;
1394   }
1395   // Update absolute send time field (convert ms to 24-bit unsigned with 18 bit
1396   // fractional part).
1397   ModuleRTPUtility::AssignUWord24ToBuffer(rtp_packet + block_pos + 1,
1398                                           ((now_ms << 18) / 1000) & 0x00ffffff);
1399   return true;
1400 }
1401
1402 void RTPSender::SetSendingStatus(bool enabled) {
1403   if (enabled) {
1404     uint32_t frequency_hz = SendPayloadFrequency();
1405     uint32_t RTPtime = ModuleRTPUtility::GetCurrentRTP(clock_, frequency_hz);
1406
1407     // Will be ignored if it's already configured via API.
1408     SetStartTimestamp(RTPtime, false);
1409   } else {
1410     if (!ssrc_forced_) {
1411       // Generate a new SSRC.
1412       ssrc_db_.ReturnSSRC(ssrc_);
1413       ssrc_ = ssrc_db_.CreateSSRC();  // Can't be 0.
1414     }
1415     // Don't initialize seq number if SSRC passed externally.
1416     if (!sequence_number_forced_ && !ssrc_forced_) {
1417       // Generate a new sequence number.
1418       sequence_number_ =
1419           rand() / (RAND_MAX / MAX_INIT_RTP_SEQ_NUMBER);  // NOLINT
1420     }
1421   }
1422 }
1423
1424 void RTPSender::SetSendingMediaStatus(const bool enabled) {
1425   CriticalSectionScoped cs(send_critsect_);
1426   sending_media_ = enabled;
1427 }
1428
1429 bool RTPSender::SendingMedia() const {
1430   CriticalSectionScoped cs(send_critsect_);
1431   return sending_media_;
1432 }
1433
1434 uint32_t RTPSender::Timestamp() const {
1435   CriticalSectionScoped cs(send_critsect_);
1436   return timestamp_;
1437 }
1438
1439 void RTPSender::SetStartTimestamp(uint32_t timestamp, bool force) {
1440   CriticalSectionScoped cs(send_critsect_);
1441   if (force) {
1442     start_time_stamp_forced_ = force;
1443     start_time_stamp_ = timestamp;
1444   } else {
1445     if (!start_time_stamp_forced_) {
1446       start_time_stamp_ = timestamp;
1447     }
1448   }
1449 }
1450
1451 uint32_t RTPSender::StartTimestamp() const {
1452   CriticalSectionScoped cs(send_critsect_);
1453   return start_time_stamp_;
1454 }
1455
1456 uint32_t RTPSender::GenerateNewSSRC() {
1457   // If configured via API, return 0.
1458   CriticalSectionScoped cs(send_critsect_);
1459
1460   if (ssrc_forced_) {
1461     return 0;
1462   }
1463   ssrc_ = ssrc_db_.CreateSSRC();  // Can't be 0.
1464   return ssrc_;
1465 }
1466
1467 void RTPSender::SetSSRC(uint32_t ssrc) {
1468   // This is configured via the API.
1469   CriticalSectionScoped cs(send_critsect_);
1470
1471   if (ssrc_ == ssrc && ssrc_forced_) {
1472     return;  // Since it's same ssrc, don't reset anything.
1473   }
1474   ssrc_forced_ = true;
1475   ssrc_db_.ReturnSSRC(ssrc_);
1476   ssrc_db_.RegisterSSRC(ssrc);
1477   ssrc_ = ssrc;
1478   if (!sequence_number_forced_) {
1479     sequence_number_ =
1480         rand() / (RAND_MAX / MAX_INIT_RTP_SEQ_NUMBER);  // NOLINT
1481   }
1482 }
1483
1484 uint32_t RTPSender::SSRC() const {
1485   CriticalSectionScoped cs(send_critsect_);
1486   return ssrc_;
1487 }
1488
1489 void RTPSender::SetCSRCStatus(const bool include) {
1490   include_csrcs_ = include;
1491 }
1492
1493 void RTPSender::SetCSRCs(const uint32_t arr_of_csrc[kRtpCsrcSize],
1494                          const uint8_t arr_length) {
1495   assert(arr_length <= kRtpCsrcSize);
1496   CriticalSectionScoped cs(send_critsect_);
1497
1498   for (int i = 0; i < arr_length; i++) {
1499     csrcs_[i] = arr_of_csrc[i];
1500   }
1501   num_csrcs_ = arr_length;
1502 }
1503
1504 int32_t RTPSender::CSRCs(uint32_t arr_of_csrc[kRtpCsrcSize]) const {
1505   assert(arr_of_csrc);
1506   CriticalSectionScoped cs(send_critsect_);
1507   for (int i = 0; i < num_csrcs_ && i < kRtpCsrcSize; i++) {
1508     arr_of_csrc[i] = csrcs_[i];
1509   }
1510   return num_csrcs_;
1511 }
1512
1513 void RTPSender::SetSequenceNumber(uint16_t seq) {
1514   CriticalSectionScoped cs(send_critsect_);
1515   sequence_number_forced_ = true;
1516   sequence_number_ = seq;
1517 }
1518
1519 uint16_t RTPSender::SequenceNumber() const {
1520   CriticalSectionScoped cs(send_critsect_);
1521   return sequence_number_;
1522 }
1523
1524 // Audio.
1525 int32_t RTPSender::SendTelephoneEvent(const uint8_t key,
1526                                       const uint16_t time_ms,
1527                                       const uint8_t level) {
1528   if (!audio_configured_) {
1529     return -1;
1530   }
1531   return audio_->SendTelephoneEvent(key, time_ms, level);
1532 }
1533
1534 bool RTPSender::SendTelephoneEventActive(int8_t *telephone_event) const {
1535   if (!audio_configured_) {
1536     return false;
1537   }
1538   return audio_->SendTelephoneEventActive(*telephone_event);
1539 }
1540
1541 int32_t RTPSender::SetAudioPacketSize(
1542     const uint16_t packet_size_samples) {
1543   if (!audio_configured_) {
1544     return -1;
1545   }
1546   return audio_->SetAudioPacketSize(packet_size_samples);
1547 }
1548
1549 int32_t RTPSender::SetAudioLevel(const uint8_t level_d_bov) {
1550   return audio_->SetAudioLevel(level_d_bov);
1551 }
1552
1553 int32_t RTPSender::SetRED(const int8_t payload_type) {
1554   if (!audio_configured_) {
1555     return -1;
1556   }
1557   return audio_->SetRED(payload_type);
1558 }
1559
1560 int32_t RTPSender::RED(int8_t *payload_type) const {
1561   if (!audio_configured_) {
1562     return -1;
1563   }
1564   return audio_->RED(*payload_type);
1565 }
1566
1567 // Video
1568 VideoCodecInformation *RTPSender::CodecInformationVideo() {
1569   if (audio_configured_) {
1570     return NULL;
1571   }
1572   return video_->CodecInformationVideo();
1573 }
1574
1575 RtpVideoCodecTypes RTPSender::VideoCodecType() const {
1576   assert(!audio_configured_ && "Sender is an audio stream!");
1577   return video_->VideoCodecType();
1578 }
1579
1580 uint32_t RTPSender::MaxConfiguredBitrateVideo() const {
1581   if (audio_configured_) {
1582     return 0;
1583   }
1584   return video_->MaxConfiguredBitrateVideo();
1585 }
1586
1587 int32_t RTPSender::SendRTPIntraRequest() {
1588   if (audio_configured_) {
1589     return -1;
1590   }
1591   return video_->SendRTPIntraRequest();
1592 }
1593
1594 int32_t RTPSender::SetGenericFECStatus(
1595     const bool enable, const uint8_t payload_type_red,
1596     const uint8_t payload_type_fec) {
1597   if (audio_configured_) {
1598     return -1;
1599   }
1600   return video_->SetGenericFECStatus(enable, payload_type_red,
1601                                      payload_type_fec);
1602 }
1603
1604 int32_t RTPSender::GenericFECStatus(
1605     bool *enable, uint8_t *payload_type_red,
1606     uint8_t *payload_type_fec) const {
1607   if (audio_configured_) {
1608     return -1;
1609   }
1610   return video_->GenericFECStatus(
1611       *enable, *payload_type_red, *payload_type_fec);
1612 }
1613
1614 int32_t RTPSender::SetFecParameters(
1615     const FecProtectionParams *delta_params,
1616     const FecProtectionParams *key_params) {
1617   if (audio_configured_) {
1618     return -1;
1619   }
1620   return video_->SetFecParameters(delta_params, key_params);
1621 }
1622
1623 void RTPSender::BuildRtxPacket(uint8_t* buffer, uint16_t* length,
1624                                uint8_t* buffer_rtx) {
1625   CriticalSectionScoped cs(send_critsect_);
1626   uint8_t* data_buffer_rtx = buffer_rtx;
1627   // Add RTX header.
1628   ModuleRTPUtility::RTPHeaderParser rtp_parser(
1629       reinterpret_cast<const uint8_t *>(buffer), *length);
1630
1631   RTPHeader rtp_header;
1632   rtp_parser.Parse(rtp_header);
1633
1634   // Add original RTP header.
1635   memcpy(data_buffer_rtx, buffer, rtp_header.headerLength);
1636
1637   // Replace payload type, if a specific type is set for RTX.
1638   if (payload_type_rtx_ != -1) {
1639     data_buffer_rtx[1] = static_cast<uint8_t>(payload_type_rtx_);
1640     if (rtp_header.markerBit)
1641       data_buffer_rtx[1] |= kRtpMarkerBitMask;
1642   }
1643
1644   // Replace sequence number.
1645   uint8_t *ptr = data_buffer_rtx + 2;
1646   ModuleRTPUtility::AssignUWord16ToBuffer(ptr, sequence_number_rtx_++);
1647
1648   // Replace SSRC.
1649   ptr += 6;
1650   ModuleRTPUtility::AssignUWord32ToBuffer(ptr, ssrc_rtx_);
1651
1652   // Add OSN (original sequence number).
1653   ptr = data_buffer_rtx + rtp_header.headerLength;
1654   ModuleRTPUtility::AssignUWord16ToBuffer(ptr, rtp_header.sequenceNumber);
1655   ptr += 2;
1656
1657   // Add original payload data.
1658   memcpy(ptr, buffer + rtp_header.headerLength,
1659          *length - rtp_header.headerLength);
1660   *length += 2;
1661 }
1662
1663 void RTPSender::RegisterFrameCountObserver(FrameCountObserver* observer) {
1664   CriticalSectionScoped cs(statistics_crit_.get());
1665   if (observer != NULL)
1666     assert(frame_count_observer_ == NULL);
1667   frame_count_observer_ = observer;
1668 }
1669
1670 FrameCountObserver* RTPSender::GetFrameCountObserver() const {
1671   CriticalSectionScoped cs(statistics_crit_.get());
1672   return frame_count_observer_;
1673 }
1674
1675 void RTPSender::RegisterRtpStatisticsCallback(
1676     StreamDataCountersCallback* callback) {
1677   CriticalSectionScoped cs(statistics_crit_.get());
1678   if (callback != NULL)
1679     assert(rtp_stats_callback_ == NULL);
1680   rtp_stats_callback_ = callback;
1681 }
1682
1683 StreamDataCountersCallback* RTPSender::GetRtpStatisticsCallback() const {
1684   CriticalSectionScoped cs(statistics_crit_.get());
1685   return rtp_stats_callback_;
1686 }
1687
1688 void RTPSender::RegisterBitrateObserver(BitrateStatisticsObserver* observer) {
1689   CriticalSectionScoped cs(statistics_crit_.get());
1690   if (observer != NULL)
1691     assert(bitrate_callback_ == NULL);
1692   bitrate_callback_ = observer;
1693 }
1694
1695 BitrateStatisticsObserver* RTPSender::GetBitrateObserver() const {
1696   CriticalSectionScoped cs(statistics_crit_.get());
1697   return bitrate_callback_;
1698 }
1699
1700 uint32_t RTPSender::BitrateSent() const { return bitrate_sent_.BitrateLast(); }
1701
1702 void RTPSender::BitrateUpdated(const BitrateStatistics& stats) {
1703   CriticalSectionScoped cs(statistics_crit_.get());
1704   if (bitrate_callback_) {
1705     bitrate_callback_->Notify(stats, ssrc_);
1706   }
1707 }
1708
1709 void RTPSender::SetTargetBitrateKbps(uint16_t bitrate_kbps) {
1710   CriticalSectionScoped cs(target_bitrate_critsect_.get());
1711   target_bitrate_kbps_ = bitrate_kbps;
1712 }
1713
1714 uint16_t RTPSender::GetTargetBitrateKbps() {
1715   CriticalSectionScoped cs(target_bitrate_critsect_.get());
1716   return target_bitrate_kbps_;
1717 }
1718 }  // namespace webrtc