rtp_sender.cc revision 52b4e8871a7c43a12177cb9a717baff3fb2680c0
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 <cstdlib>  // srand
14
15#include "webrtc/modules/pacing/include/paced_sender.h"
16#include "webrtc/modules/rtp_rtcp/source/rtp_packet_history.h"
17#include "webrtc/modules/rtp_rtcp/source/rtp_sender_audio.h"
18#include "webrtc/modules/rtp_rtcp/source/rtp_sender_video.h"
19#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
20#include "webrtc/system_wrappers/interface/trace.h"
21#include "webrtc/system_wrappers/interface/trace_event.h"
22
23namespace webrtc {
24
25namespace {
26
27const char* FrameTypeToString(const FrameType frame_type) {
28  switch (frame_type) {
29    case kFrameEmpty: return "empty";
30    case kAudioFrameSpeech: return "audio_speech";
31    case kAudioFrameCN: return "audio_cn";
32    case kVideoFrameKey: return "video_key";
33    case kVideoFrameDelta: return "video_delta";
34    case kVideoFrameGolden: return "video_golden";
35    case kVideoFrameAltRef: return "video_altref";
36  }
37  return "";
38}
39
40}  // namespace
41
42RTPSender::RTPSender(const int32_t id, const bool audio, Clock *clock,
43                     Transport *transport, RtpAudioFeedback *audio_feedback,
44                     PacedSender *paced_sender)
45    : Bitrate(clock), id_(id), audio_configured_(audio), audio_(NULL),
46      video_(NULL), paced_sender_(paced_sender),
47      send_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
48      transport_(transport), sending_media_(true),  // Default to sending media.
49      max_payload_length_(IP_PACKET_SIZE - 28),     // Default is IP-v4/UDP.
50      target_send_bitrate_(0), packet_over_head_(28), payload_type_(-1),
51      payload_type_map_(), rtp_header_extension_map_(),
52      transmission_time_offset_(0),
53      // NACK.
54      nack_byte_count_times_(), nack_byte_count_(), nack_bitrate_(clock),
55      packet_history_(new RTPPacketHistory(clock)),
56      // Statistics
57      packets_sent_(0), payload_bytes_sent_(0), start_time_stamp_forced_(false),
58      start_time_stamp_(0), ssrc_db_(*SSRCDatabase::GetSSRCDatabase()),
59      remote_ssrc_(0), sequence_number_forced_(false), ssrc_forced_(false),
60      time_stamp_(0), csrcs_(0), csrc_(), include_csrcs_(true),
61      rtx_(kRtxOff), payload_type_rtx_(-1) {
62  memset(nack_byte_count_times_, 0, sizeof(nack_byte_count_times_));
63  memset(nack_byte_count_, 0, sizeof(nack_byte_count_));
64  memset(csrc_, 0, sizeof(csrc_));
65  // We need to seed the random generator.
66  srand(static_cast<uint32_t>(clock_->TimeInMilliseconds()));
67  ssrc_ = ssrc_db_.CreateSSRC();  // Can't be 0.
68  ssrc_rtx_ = ssrc_db_.CreateSSRC();  // Can't be 0.
69  // Random start, 16 bits. Can't be 0.
70  sequence_number_rtx_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;
71  sequence_number_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;
72
73  if (audio) {
74    audio_ = new RTPSenderAudio(id, clock_, this);
75    audio_->RegisterAudioCallback(audio_feedback);
76  } else {
77    video_ = new RTPSenderVideo(id, clock_, this);
78  }
79  WEBRTC_TRACE(kTraceMemory, kTraceRtpRtcp, id, "%s created", __FUNCTION__);
80}
81
82RTPSender::~RTPSender() {
83  if (remote_ssrc_ != 0) {
84    ssrc_db_.ReturnSSRC(remote_ssrc_);
85  }
86  ssrc_db_.ReturnSSRC(ssrc_);
87
88  SSRCDatabase::ReturnSSRCDatabase();
89  delete send_critsect_;
90  while (!payload_type_map_.empty()) {
91    std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
92        payload_type_map_.begin();
93    delete it->second;
94    payload_type_map_.erase(it);
95  }
96  delete packet_history_;
97  delete audio_;
98  delete video_;
99
100  WEBRTC_TRACE(kTraceMemory, kTraceRtpRtcp, id_, "%s deleted", __FUNCTION__);
101}
102
103void RTPSender::SetTargetSendBitrate(const uint32_t bits) {
104  target_send_bitrate_ = static_cast<uint16_t>(bits / 1000);
105}
106
107uint16_t RTPSender::ActualSendBitrateKbit() const {
108  return (uint16_t)(Bitrate::BitrateNow() / 1000);
109}
110
111uint32_t RTPSender::VideoBitrateSent() const {
112  if (video_) {
113    return video_->VideoBitrateSent();
114  }
115  return 0;
116}
117
118uint32_t RTPSender::FecOverheadRate() const {
119  if (video_) {
120    return video_->FecOverheadRate();
121  }
122  return 0;
123}
124
125uint32_t RTPSender::NackOverheadRate() const {
126  return nack_bitrate_.BitrateLast();
127}
128
129int32_t RTPSender::SetTransmissionTimeOffset(
130    const int32_t transmission_time_offset) {
131  if (transmission_time_offset > (0x800000 - 1) ||
132      transmission_time_offset < -(0x800000 - 1)) {  // Word24.
133    return -1;
134  }
135  CriticalSectionScoped cs(send_critsect_);
136  transmission_time_offset_ = transmission_time_offset;
137  return 0;
138}
139
140int32_t RTPSender::RegisterRtpHeaderExtension(const RTPExtensionType type,
141                                              const uint8_t id) {
142  CriticalSectionScoped cs(send_critsect_);
143  return rtp_header_extension_map_.Register(type, id);
144}
145
146int32_t RTPSender::DeregisterRtpHeaderExtension(
147    const RTPExtensionType type) {
148  CriticalSectionScoped cs(send_critsect_);
149  return rtp_header_extension_map_.Deregister(type);
150}
151
152uint16_t RTPSender::RtpHeaderExtensionTotalLength() const {
153  CriticalSectionScoped cs(send_critsect_);
154  return rtp_header_extension_map_.GetTotalLengthInBytes();
155}
156
157int32_t RTPSender::RegisterPayload(
158    const char payload_name[RTP_PAYLOAD_NAME_SIZE],
159    const int8_t payload_number, const uint32_t frequency,
160    const uint8_t channels, const uint32_t rate) {
161  assert(payload_name);
162  CriticalSectionScoped cs(send_critsect_);
163
164  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
165      payload_type_map_.find(payload_number);
166
167  if (payload_type_map_.end() != it) {
168    // We already use this payload type.
169    ModuleRTPUtility::Payload *payload = it->second;
170    assert(payload);
171
172    // Check if it's the same as we already have.
173    if (ModuleRTPUtility::StringCompare(payload->name, payload_name,
174                                        RTP_PAYLOAD_NAME_SIZE - 1)) {
175      if (audio_configured_ && payload->audio &&
176          payload->typeSpecific.Audio.frequency == frequency &&
177          (payload->typeSpecific.Audio.rate == rate ||
178           payload->typeSpecific.Audio.rate == 0 || rate == 0)) {
179        payload->typeSpecific.Audio.rate = rate;
180        // Ensure that we update the rate if new or old is zero.
181        return 0;
182      }
183      if (!audio_configured_ && !payload->audio) {
184        return 0;
185      }
186    }
187    return -1;
188  }
189  int32_t ret_val = -1;
190  ModuleRTPUtility::Payload *payload = NULL;
191  if (audio_configured_) {
192    ret_val = audio_->RegisterAudioPayload(payload_name, payload_number,
193                                           frequency, channels, rate, payload);
194  } else {
195    ret_val = video_->RegisterVideoPayload(payload_name, payload_number, rate,
196                                           payload);
197  }
198  if (payload) {
199    payload_type_map_[payload_number] = payload;
200  }
201  return ret_val;
202}
203
204int32_t RTPSender::DeRegisterSendPayload(
205    const int8_t payload_type) {
206  CriticalSectionScoped lock(send_critsect_);
207
208  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
209      payload_type_map_.find(payload_type);
210
211  if (payload_type_map_.end() == it) {
212    return -1;
213  }
214  ModuleRTPUtility::Payload *payload = it->second;
215  delete payload;
216  payload_type_map_.erase(it);
217  return 0;
218}
219
220int8_t RTPSender::SendPayloadType() const { return payload_type_; }
221
222int RTPSender::SendPayloadFrequency() const { return audio_->AudioFrequency(); }
223
224int32_t RTPSender::SetMaxPayloadLength(
225    const uint16_t max_payload_length,
226    const uint16_t packet_over_head) {
227  // Sanity check.
228  if (max_payload_length < 100 || max_payload_length > IP_PACKET_SIZE) {
229    WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_, "%s invalid argument",
230                 __FUNCTION__);
231    return -1;
232  }
233  CriticalSectionScoped cs(send_critsect_);
234  max_payload_length_ = max_payload_length;
235  packet_over_head_ = packet_over_head;
236
237  WEBRTC_TRACE(kTraceInfo, kTraceRtpRtcp, id_, "SetMaxPayloadLength to %d.",
238               max_payload_length);
239  return 0;
240}
241
242uint16_t RTPSender::MaxDataPayloadLength() const {
243  if (audio_configured_) {
244    return max_payload_length_ - RTPHeaderLength();
245  } else {
246    return max_payload_length_ - RTPHeaderLength() -
247           video_->FECPacketOverhead() - ((rtx_) ? 2 : 0);
248    // Include the FEC/ULP/RED overhead.
249  }
250}
251
252uint16_t RTPSender::MaxPayloadLength() const {
253  return max_payload_length_;
254}
255
256uint16_t RTPSender::PacketOverHead() const { return packet_over_head_; }
257
258void RTPSender::SetRTXStatus(RtxMode mode, bool set_ssrc, uint32_t ssrc) {
259  CriticalSectionScoped cs(send_critsect_);
260  rtx_ = mode;
261  if (rtx_ != kRtxOff) {
262    if (set_ssrc) {
263      ssrc_rtx_ = ssrc;
264    } else {
265      ssrc_rtx_ = ssrc_db_.CreateSSRC();  // Can't be 0.
266    }
267  }
268}
269
270void RTPSender::RTXStatus(RtxMode* mode, uint32_t* ssrc,
271                          int* payload_type) const {
272  CriticalSectionScoped cs(send_critsect_);
273  *mode = rtx_;
274  *ssrc = ssrc_rtx_;
275  *payload_type = payload_type_rtx_;
276}
277
278
279void RTPSender::SetRtxPayloadType(int payload_type) {
280  CriticalSectionScoped cs(send_critsect_);
281  payload_type_rtx_ = payload_type;
282}
283
284int32_t RTPSender::CheckPayloadType(const int8_t payload_type,
285                                    RtpVideoCodecTypes *video_type) {
286  CriticalSectionScoped cs(send_critsect_);
287
288  if (payload_type < 0) {
289    WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_, "\tinvalid payload_type (%d)",
290                 payload_type);
291    return -1;
292  }
293  if (audio_configured_) {
294    int8_t red_pl_type = -1;
295    if (audio_->RED(red_pl_type) == 0) {
296      // We have configured RED.
297      if (red_pl_type == payload_type) {
298        // And it's a match...
299        return 0;
300      }
301    }
302  }
303  if (payload_type_ == payload_type) {
304    if (!audio_configured_) {
305      *video_type = video_->VideoCodecType();
306    }
307    return 0;
308  }
309  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
310      payload_type_map_.find(payload_type);
311  if (it == payload_type_map_.end()) {
312    WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_,
313                 "\tpayloadType:%d not registered", payload_type);
314    return -1;
315  }
316  payload_type_ = payload_type;
317  ModuleRTPUtility::Payload *payload = it->second;
318  assert(payload);
319  if (!payload->audio && !audio_configured_) {
320    video_->SetVideoCodecType(payload->typeSpecific.Video.videoCodecType);
321    *video_type = payload->typeSpecific.Video.videoCodecType;
322    video_->SetMaxConfiguredBitrateVideo(payload->typeSpecific.Video.maxRate);
323  }
324  return 0;
325}
326
327int32_t RTPSender::SendOutgoingData(
328    const FrameType frame_type, const int8_t payload_type,
329    const uint32_t capture_timestamp, int64_t capture_time_ms,
330    const uint8_t *payload_data, const uint32_t payload_size,
331    const RTPFragmentationHeader *fragmentation,
332    VideoCodecInformation *codec_info, const RTPVideoTypeHeader *rtp_type_hdr) {
333  TRACE_EVENT2("webrtc_rtp", "RTPSender::SendOutgoingData",
334               "timestsamp", capture_timestamp,
335               "frame_type", FrameTypeToString(frame_type));
336  {
337    // Drop this packet if we're not sending media packets.
338    CriticalSectionScoped cs(send_critsect_);
339    if (!sending_media_) {
340      return 0;
341    }
342  }
343  RtpVideoCodecTypes video_type = kRtpGenericVideo;
344  if (CheckPayloadType(payload_type, &video_type) != 0) {
345    WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_,
346                 "%s invalid argument failed to find payload_type:%d",
347                 __FUNCTION__, payload_type);
348    return -1;
349  }
350
351  if (audio_configured_) {
352    assert(frame_type == kAudioFrameSpeech || frame_type == kAudioFrameCN ||
353           frame_type == kFrameEmpty);
354
355    return audio_->SendAudio(frame_type, payload_type, capture_timestamp,
356                             payload_data, payload_size, fragmentation);
357  } else {
358    assert(frame_type != kAudioFrameSpeech && frame_type != kAudioFrameCN);
359
360    if (frame_type == kFrameEmpty) {
361      return SendPaddingAccordingToBitrate(payload_type, capture_timestamp,
362                                           capture_time_ms);
363    }
364    return video_->SendVideo(video_type, frame_type, payload_type,
365                             capture_timestamp, capture_time_ms, payload_data,
366                             payload_size, fragmentation, codec_info,
367                             rtp_type_hdr);
368  }
369}
370
371int32_t RTPSender::SendPaddingAccordingToBitrate(
372    int8_t payload_type, uint32_t capture_timestamp,
373    int64_t capture_time_ms) {
374  // Current bitrate since last estimate(1 second) averaged with the
375  // estimate since then, to get the most up to date bitrate.
376  uint32_t current_bitrate = BitrateNow();
377  int bitrate_diff = target_send_bitrate_ * 1000 - current_bitrate;
378  if (bitrate_diff <= 0) {
379    return 0;
380  }
381  int bytes = 0;
382  if (current_bitrate == 0) {
383    // Start up phase. Send one 33.3 ms batch to start with.
384    bytes = (bitrate_diff / 8) / 30;
385  } else {
386    bytes = (bitrate_diff / 8);
387    // Cap at 200 ms of target send data.
388    int bytes_cap = target_send_bitrate_ * 25;  // 1000 / 8 / 5.
389    if (bytes > bytes_cap) {
390      bytes = bytes_cap;
391    }
392  }
393  return SendPadData(payload_type, capture_timestamp, capture_time_ms, bytes);
394}
395
396int32_t RTPSender::SendPadData(
397    int8_t payload_type, uint32_t capture_timestamp,
398    int64_t capture_time_ms, int32_t bytes) {
399  // Drop this packet if we're not sending media packets.
400  if (!sending_media_) {
401    return 0;
402  }
403  // Max in the RFC 3550 is 255 bytes, we limit it to be modulus 32 for SRTP.
404  int max_length = 224;
405  uint8_t data_buffer[IP_PACKET_SIZE];
406
407  for (; bytes > 0; bytes -= max_length) {
408    int padding_bytes_in_packet = max_length;
409    if (bytes < max_length) {
410      padding_bytes_in_packet = (bytes + 16) & 0xffe0;  // Keep our modulus 32.
411    }
412    if (padding_bytes_in_packet < 32) {
413      // Sanity don't send empty packets.
414      break;
415    }
416    // Correct seq num, timestamp and payload type.
417    int header_length = BuildRTPheader(
418                            data_buffer, payload_type, false,  // No markerbit.
419                            capture_timestamp, true,  // Timestamp provided.
420                            true);  // Increment sequence number.
421    data_buffer[0] |= 0x20;  // Set padding bit.
422    int32_t *data =
423        reinterpret_cast<int32_t *>(&(data_buffer[header_length]));
424
425    // Fill data buffer with random data.
426    for (int j = 0; j < (padding_bytes_in_packet >> 2); ++j) {
427      data[j] = rand();  // NOLINT
428    }
429    // Set number of padding bytes in the last byte of the packet.
430    data_buffer[header_length + padding_bytes_in_packet - 1] =
431        padding_bytes_in_packet;
432    // Send the packet.
433    if (0 > SendToNetwork(data_buffer, padding_bytes_in_packet, header_length,
434                          capture_time_ms, kDontRetransmit)) {
435      // Error sending the packet.
436      break;
437    }
438  }
439  if (bytes > 31) {  // 31 due to our modulus 32.
440    // We did not manage to send all bytes.
441    return -1;
442  }
443  return 0;
444}
445
446void RTPSender::SetStorePacketsStatus(const bool enable,
447                                      const uint16_t number_to_store) {
448  packet_history_->SetStorePacketsStatus(enable, number_to_store);
449}
450
451bool RTPSender::StorePackets() const {
452  return packet_history_->StorePackets();
453}
454
455int32_t RTPSender::ReSendPacket(uint16_t packet_id, uint32_t min_resend_time) {
456  uint16_t length = IP_PACKET_SIZE;
457  uint8_t data_buffer[IP_PACKET_SIZE];
458  uint8_t *buffer_to_send_ptr = data_buffer;
459  int64_t capture_time_ms;
460  StorageType type;
461  if (!packet_history_->GetRTPPacket(packet_id, min_resend_time, data_buffer,
462                                     &length, &capture_time_ms, &type)) {
463    // Packet not found.
464    return 0;
465  }
466  if (length == 0 || type == kDontRetransmit) {
467    // No bytes copied (packet recently resent, skip resending) or
468    // packet should not be retransmitted.
469    return 0;
470  }
471
472  uint8_t data_buffer_rtx[IP_PACKET_SIZE];
473  if (rtx_ != kRtxOff) {
474    BuildRtxPacket(data_buffer, &length, data_buffer_rtx);
475    buffer_to_send_ptr = data_buffer_rtx;
476  }
477
478  ModuleRTPUtility::RTPHeaderParser rtp_parser(data_buffer, length);
479  WebRtcRTPHeader rtp_header;
480  rtp_parser.Parse(rtp_header);
481
482  // Store the time when the packet was last sent or added to pacer.
483  packet_history_->UpdateResendTime(packet_id);
484
485  {
486    // Update send statistics prior to pacer.
487    CriticalSectionScoped cs(send_critsect_);
488    Bitrate::Update(length);
489    packets_sent_++;
490    // We on purpose don't add to payload_bytes_sent_ since this is a
491    // re-transmit and not new payload data.
492  }
493
494  TRACE_EVENT_INSTANT2("webrtc_rtp", "RTPSender::ReSendPacket",
495                       "timestamp", rtp_header.header.timestamp,
496                       "seqnum", rtp_header.header.sequenceNumber);
497
498  if (paced_sender_) {
499    if (!paced_sender_->SendPacket(PacedSender::kHighPriority,
500                                   rtp_header.header.ssrc,
501                                   rtp_header.header.sequenceNumber,
502                                   capture_time_ms,
503                                   length)) {
504      // We can't send the packet right now.
505      // We will be called when it is time.
506      return 0;
507    }
508  }
509
510  if (SendPacketToNetwork(buffer_to_send_ptr, length)) {
511    return 0;
512  }
513  return -1;
514}
515
516bool RTPSender::SendPacketToNetwork(const uint8_t *packet, uint32_t size) {
517  int bytes_sent = -1;
518  if (transport_) {
519    bytes_sent = transport_->SendPacket(id_, packet, size);
520  }
521  TRACE_EVENT_INSTANT2("webrtc_rtp", "RTPSender::SendPacketToNetwork",
522                       "size", size, "sent", bytes_sent);
523  // TODO(pwesin): Add a separate bitrate for sent bitrate after pacer.
524  if (bytes_sent <= 0) {
525    WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
526                 "Transport failed to send packet");
527    return false;
528  }
529  return true;
530}
531
532int RTPSender::SelectiveRetransmissions() const {
533  if (!video_)
534    return -1;
535  return video_->SelectiveRetransmissions();
536}
537
538int RTPSender::SetSelectiveRetransmissions(uint8_t settings) {
539  if (!video_)
540    return -1;
541  return video_->SetSelectiveRetransmissions(settings);
542}
543
544void RTPSender::OnReceivedNACK(
545    const std::list<uint16_t>& nack_sequence_numbers,
546    const uint16_t avg_rtt) {
547  TRACE_EVENT2("webrtc_rtp", "RTPSender::OnReceivedNACK",
548               "num_seqnum", nack_sequence_numbers.size(), "avg_rtt", avg_rtt);
549  const int64_t now = clock_->TimeInMilliseconds();
550  uint32_t bytes_re_sent = 0;
551
552  // Enough bandwidth to send NACK?
553  if (!ProcessNACKBitRate(now)) {
554    WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
555                 "NACK bitrate reached. Skip sending NACK response. Target %d",
556                 target_send_bitrate_);
557    return;
558  }
559
560  for (std::list<uint16_t>::const_iterator it = nack_sequence_numbers.begin();
561      it != nack_sequence_numbers.end(); ++it) {
562    const int32_t bytes_sent = ReSendPacket(*it, 5 + avg_rtt);
563    if (bytes_sent > 0) {
564      bytes_re_sent += bytes_sent;
565    } else if (bytes_sent == 0) {
566      // The packet has previously been resent.
567      // Try resending next packet in the list.
568      continue;
569    } else if (bytes_sent < 0) {
570      // Failed to send one Sequence number. Give up the rest in this nack.
571      WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
572                   "Failed resending RTP packet %d, Discard rest of packets",
573                   *it);
574      break;
575    }
576    // Delay bandwidth estimate (RTT * BW).
577    if (target_send_bitrate_ != 0 && avg_rtt) {
578      // kbits/s * ms = bits => bits/8 = bytes
579      uint32_t target_bytes =
580          (static_cast<uint32_t>(target_send_bitrate_) * avg_rtt) >> 3;
581      if (bytes_re_sent > target_bytes) {
582        break;  // Ignore the rest of the packets in the list.
583      }
584    }
585  }
586  if (bytes_re_sent > 0) {
587    // TODO(pwestin) consolidate these two methods.
588    UpdateNACKBitRate(bytes_re_sent, now);
589    nack_bitrate_.Update(bytes_re_sent);
590  }
591}
592
593bool RTPSender::ProcessNACKBitRate(const uint32_t now) {
594  uint32_t num = 0;
595  int32_t byte_count = 0;
596  const uint32_t avg_interval = 1000;
597
598  CriticalSectionScoped cs(send_critsect_);
599
600  if (target_send_bitrate_ == 0) {
601    return true;
602  }
603  for (num = 0; num < NACK_BYTECOUNT_SIZE; ++num) {
604    if ((now - nack_byte_count_times_[num]) > avg_interval) {
605      // Don't use data older than 1sec.
606      break;
607    } else {
608      byte_count += nack_byte_count_[num];
609    }
610  }
611  int32_t time_interval = avg_interval;
612  if (num == NACK_BYTECOUNT_SIZE) {
613    // More than NACK_BYTECOUNT_SIZE nack messages has been received
614    // during the last msg_interval.
615    time_interval = now - nack_byte_count_times_[num - 1];
616    if (time_interval < 0) {
617      time_interval = avg_interval;
618    }
619  }
620  return (byte_count * 8) < (target_send_bitrate_ * time_interval);
621}
622
623void RTPSender::UpdateNACKBitRate(const uint32_t bytes,
624                                  const uint32_t now) {
625  CriticalSectionScoped cs(send_critsect_);
626
627  // Save bitrate statistics.
628  if (bytes > 0) {
629    if (now == 0) {
630      // Add padding length.
631      nack_byte_count_[0] += bytes;
632    } else {
633      if (nack_byte_count_times_[0] == 0) {
634        // First no shift.
635      } else {
636        // Shift.
637        for (int i = (NACK_BYTECOUNT_SIZE - 2); i >= 0; i--) {
638          nack_byte_count_[i + 1] = nack_byte_count_[i];
639          nack_byte_count_times_[i + 1] = nack_byte_count_times_[i];
640        }
641      }
642      nack_byte_count_[0] = bytes;
643      nack_byte_count_times_[0] = now;
644    }
645  }
646}
647
648// Called from pacer when we can send the packet.
649void RTPSender::TimeToSendPacket(uint16_t sequence_number,
650                                 int64_t capture_time_ms) {
651  StorageType type;
652  uint16_t length = IP_PACKET_SIZE;
653  uint8_t data_buffer[IP_PACKET_SIZE];
654  int64_t stored_time_ms;
655
656  if (packet_history_ == NULL) {
657    return;
658  }
659  if (!packet_history_->GetRTPPacket(sequence_number, 0, data_buffer, &length,
660                                     &stored_time_ms, &type)) {
661    return;
662  }
663  assert(length > 0);
664
665  ModuleRTPUtility::RTPHeaderParser rtp_parser(data_buffer, length);
666  WebRtcRTPHeader rtp_header;
667  rtp_parser.Parse(rtp_header);
668  TRACE_EVENT_INSTANT2("webrtc_rtp", "RTPSender::TimeToSendPacket",
669                       "timestamp", rtp_header.header.timestamp,
670                       "seqnum", sequence_number);
671
672  int64_t diff_ms = clock_->TimeInMilliseconds() - capture_time_ms;
673  if (UpdateTransmissionTimeOffset(data_buffer, length, rtp_header, diff_ms)) {
674    // Update stored packet in case of receiving a re-transmission request.
675    packet_history_->ReplaceRTPHeader(data_buffer,
676                                      rtp_header.header.sequenceNumber,
677                                      rtp_header.header.headerLength);
678  }
679  SendPacketToNetwork(data_buffer, length);
680}
681
682// TODO(pwestin): send in the RTPHeaderParser to avoid parsing it again.
683int32_t RTPSender::SendToNetwork(
684    uint8_t *buffer, int payload_length, int rtp_header_length,
685    int64_t capture_time_ms, StorageType storage) {
686  ModuleRTPUtility::RTPHeaderParser rtp_parser(
687      buffer, payload_length + rtp_header_length);
688  WebRtcRTPHeader rtp_header;
689  rtp_parser.Parse(rtp_header);
690
691  // |capture_time_ms| <= 0 is considered invalid.
692  // TODO(holmer): This should be changed all over Video Engine so that negative
693  // time is consider invalid, while 0 is considered a valid time.
694  if (capture_time_ms > 0) {
695    int64_t time_now = clock_->TimeInMilliseconds();
696    UpdateTransmissionTimeOffset(buffer, payload_length + rtp_header_length,
697                                 rtp_header, time_now - capture_time_ms);
698  }
699  // Used for NACK and to spread out the transmission of packets.
700  if (packet_history_->PutRTPPacket(buffer, rtp_header_length + payload_length,
701                                    max_payload_length_, capture_time_ms,
702                                    storage) != 0) {
703    return -1;
704  }
705
706  // Create and send RTX Packet.
707  // TODO(pwesin): This should be moved to its own code path triggered by pacer.
708  bool rtx_sent = false;
709  if (rtx_ == kRtxAll && storage == kAllowRetransmission) {
710    uint16_t length_rtx = payload_length + rtp_header_length;
711    uint8_t data_buffer_rtx[IP_PACKET_SIZE];
712    BuildRtxPacket(buffer, &length_rtx, data_buffer_rtx);
713    if (!SendPacketToNetwork(data_buffer_rtx, length_rtx)) return -1;
714    rtx_sent = true;
715  }
716  {
717    // Update send statistics prior to pacer.
718    CriticalSectionScoped cs(send_critsect_);
719    Bitrate::Update(payload_length + rtp_header_length);
720    ++packets_sent_;
721    payload_bytes_sent_ += payload_length;
722    if (rtx_sent) {
723      // The RTX packet.
724      ++packets_sent_;
725      payload_bytes_sent_ += payload_length;
726    }
727  }
728
729  if (paced_sender_ && storage != kDontStore) {
730    if (!paced_sender_->SendPacket(
731        PacedSender::kNormalPriority, rtp_header.header.ssrc,
732        rtp_header.header.sequenceNumber, capture_time_ms,
733        payload_length + rtp_header_length)) {
734      // We can't send the packet right now.
735      // We will be called when it is time.
736      return 0;
737    }
738  }
739  if (SendPacketToNetwork(buffer, payload_length + rtp_header_length)) {
740    return 0;
741  }
742  return -1;
743}
744
745void RTPSender::ProcessBitrate() {
746  CriticalSectionScoped cs(send_critsect_);
747  Bitrate::Process();
748  nack_bitrate_.Process();
749  if (audio_configured_) {
750    return;
751  }
752  video_->ProcessBitrate();
753}
754
755uint16_t RTPSender::RTPHeaderLength() const {
756  uint16_t rtp_header_length = 12;
757  if (include_csrcs_) {
758    rtp_header_length += sizeof(uint32_t) * csrcs_;
759  }
760  rtp_header_length += RtpHeaderExtensionTotalLength();
761  return rtp_header_length;
762}
763
764uint16_t RTPSender::IncrementSequenceNumber() {
765  CriticalSectionScoped cs(send_critsect_);
766  return sequence_number_++;
767}
768
769void RTPSender::ResetDataCounters() {
770  packets_sent_ = 0;
771  payload_bytes_sent_ = 0;
772}
773
774uint32_t RTPSender::Packets() const {
775  // Don't use critsect to avoid potential deadlock.
776  return packets_sent_;
777}
778
779// Number of sent RTP bytes.
780// Don't use critsect to avoid potental deadlock.
781uint32_t RTPSender::Bytes() const {
782  return payload_bytes_sent_;
783}
784
785int32_t RTPSender::BuildRTPheader(
786    uint8_t *data_buffer, const int8_t payload_type,
787    const bool marker_bit, const uint32_t capture_time_stamp,
788    const bool time_stamp_provided, const bool inc_sequence_number) {
789  assert(payload_type >= 0);
790  CriticalSectionScoped cs(send_critsect_);
791
792  data_buffer[0] = static_cast<uint8_t>(0x80);  // version 2.
793  data_buffer[1] = static_cast<uint8_t>(payload_type);
794  if (marker_bit) {
795    data_buffer[1] |= kRtpMarkerBitMask;  // Marker bit is set.
796  }
797  if (time_stamp_provided) {
798    time_stamp_ = start_time_stamp_ + capture_time_stamp;
799  } else {
800    // Make a unique time stamp.
801    // We can't inc by the actual time, since then we increase the risk of back
802    // timing.
803    time_stamp_++;
804  }
805  ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer + 2, sequence_number_);
806  ModuleRTPUtility::AssignUWord32ToBuffer(data_buffer + 4, time_stamp_);
807  ModuleRTPUtility::AssignUWord32ToBuffer(data_buffer + 8, ssrc_);
808  int32_t rtp_header_length = 12;
809
810  // Add the CSRCs if any.
811  if (include_csrcs_ && csrcs_ > 0) {
812    if (csrcs_ > kRtpCsrcSize) {
813      // error
814      assert(false);
815      return -1;
816    }
817    uint8_t *ptr = &data_buffer[rtp_header_length];
818    for (uint32_t i = 0; i < csrcs_; ++i) {
819      ModuleRTPUtility::AssignUWord32ToBuffer(ptr, csrc_[i]);
820      ptr += 4;
821    }
822    data_buffer[0] = (data_buffer[0] & 0xf0) | csrcs_;
823
824    // Update length of header.
825    rtp_header_length += sizeof(uint32_t) * csrcs_;
826  }
827  sequence_number_++;  // Prepare for next packet.
828
829  uint16_t len = BuildRTPHeaderExtension(data_buffer + rtp_header_length);
830  if (len) {
831    data_buffer[0] |= 0x10;  // Set extension bit.
832    rtp_header_length += len;
833  }
834  return rtp_header_length;
835}
836
837uint16_t RTPSender::BuildRTPHeaderExtension(
838    uint8_t *data_buffer) const {
839  if (rtp_header_extension_map_.Size() <= 0) {
840    return 0;
841  }
842  // RTP header extension, RFC 3550.
843  //   0                   1                   2                   3
844  //   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
845  //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
846  //  |      defined by profile       |           length              |
847  //  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
848  //  |                        header extension                       |
849  //  |                             ....                              |
850  //
851  const uint32_t kPosLength = 2;
852  const uint32_t kHeaderLength = RTP_ONE_BYTE_HEADER_LENGTH_IN_BYTES;
853
854  // Add extension ID (0xBEDE).
855  ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer,
856                                          RTP_ONE_BYTE_HEADER_EXTENSION);
857
858  // Add extensions.
859  uint16_t total_block_length = 0;
860
861  RTPExtensionType type = rtp_header_extension_map_.First();
862  while (type != kRtpExtensionNone) {
863    uint8_t block_length = 0;
864    if (type == kRtpExtensionTransmissionTimeOffset) {
865      block_length = BuildTransmissionTimeOffsetExtension(
866                         data_buffer + kHeaderLength + total_block_length);
867    }
868    total_block_length += block_length;
869    type = rtp_header_extension_map_.Next(type);
870  }
871  if (total_block_length == 0) {
872    // No extension added.
873    return 0;
874  }
875  // Set header length (in number of Word32, header excluded).
876  assert(total_block_length % 4 == 0);
877  ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer + kPosLength,
878                                          total_block_length / 4);
879  // Total added length.
880  return kHeaderLength + total_block_length;
881}
882
883uint8_t RTPSender::BuildTransmissionTimeOffsetExtension(
884    uint8_t* data_buffer) const {
885  // From RFC 5450: Transmission Time Offsets in RTP Streams.
886  //
887  // The transmission time is signaled to the receiver in-band using the
888  // general mechanism for RTP header extensions [RFC5285]. The payload
889  // of this extension (the transmitted value) is a 24-bit signed integer.
890  // When added to the RTP timestamp of the packet, it represents the
891  // "effective" RTP transmission time of the packet, on the RTP
892  // timescale.
893  //
894  // The form of the transmission offset extension block:
895  //
896  //    0                   1                   2                   3
897  //    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
898  //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
899  //   |  ID   | len=2 |              transmission offset              |
900  //   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
901
902  // Get id defined by user.
903  uint8_t id;
904  if (rtp_header_extension_map_.GetId(kRtpExtensionTransmissionTimeOffset,
905                                      &id) != 0) {
906    // Not registered.
907    return 0;
908  }
909  int pos = 0;
910  const uint8_t len = 2;
911  data_buffer[pos++] = (id << 4) + len;
912  ModuleRTPUtility::AssignUWord24ToBuffer(data_buffer + pos,
913                                          transmission_time_offset_);
914  pos += 3;
915  assert(pos == TRANSMISSION_TIME_OFFSET_LENGTH_IN_BYTES);
916  return TRANSMISSION_TIME_OFFSET_LENGTH_IN_BYTES;
917}
918
919bool RTPSender::UpdateTransmissionTimeOffset(
920    uint8_t *rtp_packet, const uint16_t rtp_packet_length,
921    const WebRtcRTPHeader &rtp_header, const int64_t time_diff_ms) const {
922  CriticalSectionScoped cs(send_critsect_);
923
924  // Get length until start of transmission block.
925  int transmission_block_pos =
926      rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
927          kRtpExtensionTransmissionTimeOffset);
928  if (transmission_block_pos < 0) {
929    WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
930                 "Failed to update transmission time offset, not registered.");
931    return false;
932  }
933  int block_pos = 12 + rtp_header.header.numCSRCs + transmission_block_pos;
934  if (rtp_packet_length < block_pos + 4 ||
935      rtp_header.header.headerLength < block_pos + 4) {
936    WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
937                 "Failed to update transmission time offset, invalid length.");
938    return false;
939  }
940  // Verify that header contains extension.
941  if (!((rtp_packet[12 + rtp_header.header.numCSRCs] == 0xBE) &&
942        (rtp_packet[12 + rtp_header.header.numCSRCs + 1] == 0xDE))) {
943    WEBRTC_TRACE(
944        kTraceStream, kTraceRtpRtcp, id_,
945        "Failed to update transmission time offset, hdr extension not found.");
946    return false;
947  }
948  // Get id.
949  uint8_t id = 0;
950  if (rtp_header_extension_map_.GetId(kRtpExtensionTransmissionTimeOffset,
951                                      &id) != 0) {
952    WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
953                 "Failed to update transmission time offset, no id.");
954    return false;
955  }
956  // Verify first byte in block.
957  const uint8_t first_block_byte = (id << 4) + 2;
958  if (rtp_packet[block_pos] != first_block_byte) {
959    WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
960                 "Failed to update transmission time offset.");
961    return false;
962  }
963  // Update transmission offset field.
964  ModuleRTPUtility::AssignUWord24ToBuffer(rtp_packet + block_pos + 1,
965                                          time_diff_ms * 90);  // RTP timestamp.
966  return true;
967}
968
969void RTPSender::SetSendingStatus(const bool enabled) {
970  if (enabled) {
971    uint32_t frequency_hz;
972    if (audio_configured_) {
973      uint32_t frequency = audio_->AudioFrequency();
974
975      // sanity
976      switch (frequency) {
977      case 8000:
978      case 12000:
979      case 16000:
980      case 24000:
981      case 32000:
982        break;
983      default:
984        assert(false);
985        return;
986      }
987      frequency_hz = frequency;
988    } else {
989      frequency_hz = kDefaultVideoFrequency;
990    }
991    uint32_t RTPtime = ModuleRTPUtility::GetCurrentRTP(clock_, frequency_hz);
992
993    // Will be ignored if it's already configured via API.
994    SetStartTimestamp(RTPtime, false);
995  } else {
996    if (!ssrc_forced_) {
997      // Generate a new SSRC.
998      ssrc_db_.ReturnSSRC(ssrc_);
999      ssrc_ = ssrc_db_.CreateSSRC();  // Can't be 0.
1000    }
1001    // Don't initialize seq number if SSRC passed externally.
1002    if (!sequence_number_forced_ && !ssrc_forced_) {
1003      // Generate a new sequence number.
1004      sequence_number_ =
1005          rand() / (RAND_MAX / MAX_INIT_RTP_SEQ_NUMBER);  // NOLINT
1006    }
1007  }
1008}
1009
1010void RTPSender::SetSendingMediaStatus(const bool enabled) {
1011  CriticalSectionScoped cs(send_critsect_);
1012  sending_media_ = enabled;
1013}
1014
1015bool RTPSender::SendingMedia() const {
1016  CriticalSectionScoped cs(send_critsect_);
1017  return sending_media_;
1018}
1019
1020uint32_t RTPSender::Timestamp() const {
1021  CriticalSectionScoped cs(send_critsect_);
1022  return time_stamp_;
1023}
1024
1025void RTPSender::SetStartTimestamp(uint32_t timestamp, bool force) {
1026  CriticalSectionScoped cs(send_critsect_);
1027  if (force) {
1028    start_time_stamp_forced_ = force;
1029    start_time_stamp_ = timestamp;
1030  } else {
1031    if (!start_time_stamp_forced_) {
1032      start_time_stamp_ = timestamp;
1033    }
1034  }
1035}
1036
1037uint32_t RTPSender::StartTimestamp() const {
1038  CriticalSectionScoped cs(send_critsect_);
1039  return start_time_stamp_;
1040}
1041
1042uint32_t RTPSender::GenerateNewSSRC() {
1043  // If configured via API, return 0.
1044  CriticalSectionScoped cs(send_critsect_);
1045
1046  if (ssrc_forced_) {
1047    return 0;
1048  }
1049  ssrc_ = ssrc_db_.CreateSSRC();  // Can't be 0.
1050  return ssrc_;
1051}
1052
1053void RTPSender::SetSSRC(uint32_t ssrc) {
1054  // This is configured via the API.
1055  CriticalSectionScoped cs(send_critsect_);
1056
1057  if (ssrc_ == ssrc && ssrc_forced_) {
1058    return;  // Since it's same ssrc, don't reset anything.
1059  }
1060  ssrc_forced_ = true;
1061  ssrc_db_.ReturnSSRC(ssrc_);
1062  ssrc_db_.RegisterSSRC(ssrc);
1063  ssrc_ = ssrc;
1064  if (!sequence_number_forced_) {
1065    sequence_number_ =
1066        rand() / (RAND_MAX / MAX_INIT_RTP_SEQ_NUMBER);  // NOLINT
1067  }
1068}
1069
1070uint32_t RTPSender::SSRC() const {
1071  CriticalSectionScoped cs(send_critsect_);
1072  return ssrc_;
1073}
1074
1075void RTPSender::SetCSRCStatus(const bool include) {
1076  include_csrcs_ = include;
1077}
1078
1079void RTPSender::SetCSRCs(const uint32_t arr_of_csrc[kRtpCsrcSize],
1080                         const uint8_t arr_length) {
1081  assert(arr_length <= kRtpCsrcSize);
1082  CriticalSectionScoped cs(send_critsect_);
1083
1084  for (int i = 0; i < arr_length; i++) {
1085    csrc_[i] = arr_of_csrc[i];
1086  }
1087  csrcs_ = arr_length;
1088}
1089
1090int32_t RTPSender::CSRCs(uint32_t arr_of_csrc[kRtpCsrcSize]) const {
1091  assert(arr_of_csrc);
1092  CriticalSectionScoped cs(send_critsect_);
1093  for (int i = 0; i < csrcs_ && i < kRtpCsrcSize; i++) {
1094    arr_of_csrc[i] = csrc_[i];
1095  }
1096  return csrcs_;
1097}
1098
1099void RTPSender::SetSequenceNumber(uint16_t seq) {
1100  CriticalSectionScoped cs(send_critsect_);
1101  sequence_number_forced_ = true;
1102  sequence_number_ = seq;
1103}
1104
1105uint16_t RTPSender::SequenceNumber() const {
1106  CriticalSectionScoped cs(send_critsect_);
1107  return sequence_number_;
1108}
1109
1110// Audio.
1111int32_t RTPSender::SendTelephoneEvent(const uint8_t key,
1112                                      const uint16_t time_ms,
1113                                      const uint8_t level) {
1114  if (!audio_configured_) {
1115    return -1;
1116  }
1117  return audio_->SendTelephoneEvent(key, time_ms, level);
1118}
1119
1120bool RTPSender::SendTelephoneEventActive(int8_t *telephone_event) const {
1121  if (!audio_configured_) {
1122    return false;
1123  }
1124  return audio_->SendTelephoneEventActive(*telephone_event);
1125}
1126
1127int32_t RTPSender::SetAudioPacketSize(
1128    const uint16_t packet_size_samples) {
1129  if (!audio_configured_) {
1130    return -1;
1131  }
1132  return audio_->SetAudioPacketSize(packet_size_samples);
1133}
1134
1135int32_t RTPSender::SetAudioLevelIndicationStatus(const bool enable,
1136                                                 const uint8_t ID) {
1137  if (!audio_configured_) {
1138    return -1;
1139  }
1140  return audio_->SetAudioLevelIndicationStatus(enable, ID);
1141}
1142
1143int32_t RTPSender::AudioLevelIndicationStatus(bool *enable,
1144                                              uint8_t* id) const {
1145  return audio_->AudioLevelIndicationStatus(*enable, *id);
1146}
1147
1148int32_t RTPSender::SetAudioLevel(const uint8_t level_d_bov) {
1149  return audio_->SetAudioLevel(level_d_bov);
1150}
1151
1152int32_t RTPSender::SetRED(const int8_t payload_type) {
1153  if (!audio_configured_) {
1154    return -1;
1155  }
1156  return audio_->SetRED(payload_type);
1157}
1158
1159int32_t RTPSender::RED(int8_t *payload_type) const {
1160  if (!audio_configured_) {
1161    return -1;
1162  }
1163  return audio_->RED(*payload_type);
1164}
1165
1166// Video
1167VideoCodecInformation *RTPSender::CodecInformationVideo() {
1168  if (audio_configured_) {
1169    return NULL;
1170  }
1171  return video_->CodecInformationVideo();
1172}
1173
1174RtpVideoCodecTypes RTPSender::VideoCodecType() const {
1175  assert(!audio_configured_ && "Sender is an audio stream!");
1176  return video_->VideoCodecType();
1177}
1178
1179uint32_t RTPSender::MaxConfiguredBitrateVideo() const {
1180  if (audio_configured_) {
1181    return 0;
1182  }
1183  return video_->MaxConfiguredBitrateVideo();
1184}
1185
1186int32_t RTPSender::SendRTPIntraRequest() {
1187  if (audio_configured_) {
1188    return -1;
1189  }
1190  return video_->SendRTPIntraRequest();
1191}
1192
1193int32_t RTPSender::SetGenericFECStatus(
1194    const bool enable, const uint8_t payload_type_red,
1195    const uint8_t payload_type_fec) {
1196  if (audio_configured_) {
1197    return -1;
1198  }
1199  return video_->SetGenericFECStatus(enable, payload_type_red,
1200                                     payload_type_fec);
1201}
1202
1203int32_t RTPSender::GenericFECStatus(
1204    bool *enable, uint8_t *payload_type_red,
1205    uint8_t *payload_type_fec) const {
1206  if (audio_configured_) {
1207    return -1;
1208  }
1209  return video_->GenericFECStatus(
1210      *enable, *payload_type_red, *payload_type_fec);
1211}
1212
1213int32_t RTPSender::SetFecParameters(
1214    const FecProtectionParams *delta_params,
1215    const FecProtectionParams *key_params) {
1216  if (audio_configured_) {
1217    return -1;
1218  }
1219  return video_->SetFecParameters(delta_params, key_params);
1220}
1221
1222void RTPSender::BuildRtxPacket(uint8_t* buffer, uint16_t* length,
1223                               uint8_t* buffer_rtx) {
1224  CriticalSectionScoped cs(send_critsect_);
1225  uint8_t* data_buffer_rtx = buffer_rtx;
1226  // Add RTX header.
1227  ModuleRTPUtility::RTPHeaderParser rtp_parser(
1228      reinterpret_cast<const uint8_t *>(buffer), *length);
1229
1230  WebRtcRTPHeader rtp_header;
1231  rtp_parser.Parse(rtp_header);
1232
1233  // Add original RTP header.
1234  memcpy(data_buffer_rtx, buffer, rtp_header.header.headerLength);
1235
1236  // Replace payload type, if a specific type is set for RTX.
1237  if (payload_type_rtx_ != -1) {
1238    data_buffer_rtx[1] = static_cast<uint8_t>(payload_type_rtx_);
1239    if (rtp_header.header.markerBit)
1240      data_buffer_rtx[1] |= kRtpMarkerBitMask;
1241  }
1242
1243  // Replace sequence number.
1244  uint8_t *ptr = data_buffer_rtx + 2;
1245  ModuleRTPUtility::AssignUWord16ToBuffer(ptr, sequence_number_rtx_++);
1246
1247  // Replace SSRC.
1248  ptr += 6;
1249  ModuleRTPUtility::AssignUWord32ToBuffer(ptr, ssrc_rtx_);
1250
1251  // Add OSN (original sequence number).
1252  ptr = data_buffer_rtx + rtp_header.header.headerLength;
1253  ModuleRTPUtility::AssignUWord16ToBuffer(ptr,
1254                                          rtp_header.header.sequenceNumber);
1255  ptr += 2;
1256
1257  // Add original payload data.
1258  memcpy(ptr, buffer + rtp_header.header.headerLength,
1259         *length - rtp_header.header.headerLength);
1260  *length += 2;
1261}
1262
1263}  // namespace webrtc
1264