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