<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/rtp_rtcp/source/rtp_sender.h"

#include <stdlib.h>  // srand

#include "webrtc/modules/rtp_rtcp/source/rtp_sender_audio.h"
#include "webrtc/modules/rtp_rtcp/source/rtp_sender_video.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/trace_event.h"

namespace webrtc {

// Max in the RFC 3550 is 255 bytes, we limit it to be modulus 32 for SRTP.
const int kMaxPaddingLength = 224;
const int kSendSideDelayWindowMs = 1000;

namespace {

const char* FrameTypeToString(const FrameType frame_type) {
  switch (frame_type) {
    case kFrameEmpty: return "empty";
    case kAudioFrameSpeech: return "audio_speech";
    case kAudioFrameCN: return "audio_cn";
    case kVideoFrameKey: return "video_key";
    case kVideoFrameDelta: return "video_delta";
  }
  return "";
}

}  // namespace

RTPSender::RTPSender(const int32_t id,
                     const bool audio,
                     Clock* clock,
                     Transport* transport,
                     RtpAudioFeedback* audio_feedback,
                     PacedSender* paced_sender)
    : clock_(clock),
      bitrate_sent_(clock, this),
      id_(id),
      audio_configured_(audio),
      audio_(NULL),
      video_(NULL),
      paced_sender_(paced_sender),
      send_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
      transport_(transport),
      sending_media_(true),                      // Default to sending media.
      max_payload_length_(IP_PACKET_SIZE - 28),  // Default is IP-v4/UDP.
      packet_over_head_(28),
      payload_type_(-1),
      payload_type_map_(),
      rtp_header_extension_map_(),
      transmission_time_offset_(0),
      absolute_send_time_(0),
      // NACK.
      nack_byte_count_times_(),
      nack_byte_count_(),
      nack_bitrate_(clock, NULL),
      packet_history_(clock),
      // Statistics
      statistics_crit_(CriticalSectionWrapper::CreateCriticalSection()),
      frame_count_observer_(NULL),
      rtp_stats_callback_(NULL),
      bitrate_callback_(NULL),
      // RTP variables
      start_time_stamp_forced_(false),
      start_time_stamp_(0),
      ssrc_db_(*SSRCDatabase::GetSSRCDatabase()),
      remote_ssrc_(0),
      sequence_number_forced_(false),
      ssrc_forced_(false),
      timestamp_(0),
      capture_time_ms_(0),
      last_timestamp_time_ms_(0),
      last_packet_marker_bit_(false),
      num_csrcs_(0),
      csrcs_(),
      include_csrcs_(true),
      rtx_(kRtxOff),
      payload_type_rtx_(-1),
      target_bitrate_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
      target_bitrate_(0) {
  memset(nack_byte_count_times_, 0, sizeof(nack_byte_count_times_));
  memset(nack_byte_count_, 0, sizeof(nack_byte_count_));
  memset(csrcs_, 0, sizeof(csrcs_));
  // We need to seed the random generator.
  srand(static_cast<uint32_t>(clock_->TimeInMilliseconds()));
  ssrc_ = ssrc_db_.CreateSSRC();  // Can't be 0.
  ssrc_rtx_ = ssrc_db_.CreateSSRC();  // Can't be 0.
  // Random start, 16 bits. Can't be 0.
  sequence_number_rtx_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;
  sequence_number_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;

  if (audio) {
    audio_ = new RTPSenderAudio(id, clock_, this);
    audio_->RegisterAudioCallback(audio_feedback);
  } else {
    video_ = new RTPSenderVideo(clock_, this);
  }
}

RTPSender::~RTPSender() {
  if (remote_ssrc_ != 0) {
    ssrc_db_.ReturnSSRC(remote_ssrc_);
  }
  ssrc_db_.ReturnSSRC(ssrc_);

  SSRCDatabase::ReturnSSRCDatabase();
  delete send_critsect_;
  while (!payload_type_map_.empty()) {
    std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
        payload_type_map_.begin();
    delete it->second;
    payload_type_map_.erase(it);
  }
  delete audio_;
  delete video_;
}

void RTPSender::SetTargetBitrate(uint32_t bitrate) {
  CriticalSectionScoped cs(target_bitrate_critsect_.get());
  target_bitrate_ = bitrate;
}

uint32_t RTPSender::GetTargetBitrate() {
  CriticalSectionScoped cs(target_bitrate_critsect_.get());
  return target_bitrate_;
}

uint16_t RTPSender::ActualSendBitrateKbit() const {
  return (uint16_t)(bitrate_sent_.BitrateNow() / 1000);
}

uint32_t RTPSender::VideoBitrateSent() const {
  if (video_) {
    return video_->VideoBitrateSent();
  }
  return 0;
}

uint32_t RTPSender::FecOverheadRate() const {
  if (video_) {
    return video_->FecOverheadRate();
  }
  return 0;
}

uint32_t RTPSender::NackOverheadRate() const {
  return nack_bitrate_.BitrateLast();
}

bool RTPSender::GetSendSideDelay(int* avg_send_delay_ms,
                                 int* max_send_delay_ms) const {
  if (!SendingMedia())
    return false;
  CriticalSectionScoped cs(statistics_crit_.get());
  SendDelayMap::const_iterator it = send_delays_.upper_bound(
      clock_->TimeInMilliseconds() - kSendSideDelayWindowMs);
  if (it == send_delays_.end())
    return false;
  int num_delays = 0;
  for (; it != send_delays_.end(); ++it) {
    *max_send_delay_ms = std::max(*max_send_delay_ms, it->second);
    *avg_send_delay_ms += it->second;
    ++num_delays;
  }
  *avg_send_delay_ms = (*avg_send_delay_ms + num_delays / 2) / num_delays;
  return true;
}

int32_t RTPSender::SetTransmissionTimeOffset(
    const int32_t transmission_time_offset) {
  if (transmission_time_offset > (0x800000 - 1) ||
      transmission_time_offset < -(0x800000 - 1)) {  // Word24.
    return -1;
  }
  CriticalSectionScoped cs(send_critsect_);
  transmission_time_offset_ = transmission_time_offset;
  return 0;
}

int32_t RTPSender::SetAbsoluteSendTime(
    const uint32_t absolute_send_time) {
  if (absolute_send_time > 0xffffff) {  // UWord24.
    return -1;
  }
  CriticalSectionScoped cs(send_critsect_);
  absolute_send_time_ = absolute_send_time;
  return 0;
}

int32_t RTPSender::RegisterRtpHeaderExtension(const RTPExtensionType type,
                                              const uint8_t id) {
  CriticalSectionScoped cs(send_critsect_);
  return rtp_header_extension_map_.Register(type, id);
}

int32_t RTPSender::DeregisterRtpHeaderExtension(
    const RTPExtensionType type) {
  CriticalSectionScoped cs(send_critsect_);
  return rtp_header_extension_map_.Deregister(type);
}

uint16_t RTPSender::RtpHeaderExtensionTotalLength() const {
  CriticalSectionScoped cs(send_critsect_);
  return rtp_header_extension_map_.GetTotalLengthInBytes();
}

int32_t RTPSender::RegisterPayload(
    const char payload_name[RTP_PAYLOAD_NAME_SIZE],
    const int8_t payload_number, const uint32_t frequency,
    const uint8_t channels, const uint32_t rate) {
  assert(payload_name);
  CriticalSectionScoped cs(send_critsect_);

  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
      payload_type_map_.find(payload_number);

  if (payload_type_map_.end() != it) {
    // We already use this payload type.
    ModuleRTPUtility::Payload *payload = it->second;
    assert(payload);

    // Check if it's the same as we already have.
    if (ModuleRTPUtility::StringCompare(payload->name, payload_name,
                                        RTP_PAYLOAD_NAME_SIZE - 1)) {
      if (audio_configured_ && payload->audio &&
          payload->typeSpecific.Audio.frequency == frequency &&
          (payload->typeSpecific.Audio.rate == rate ||
           payload->typeSpecific.Audio.rate == 0 || rate == 0)) {
        payload->typeSpecific.Audio.rate = rate;
        // Ensure that we update the rate if new or old is zero.
        return 0;
      }
      if (!audio_configured_ && !payload->audio) {
        return 0;
      }
    }
    return -1;
  }
  int32_t ret_val = -1;
  ModuleRTPUtility::Payload *payload = NULL;
  if (audio_configured_) {
    ret_val = audio_->RegisterAudioPayload(payload_name, payload_number,
                                           frequency, channels, rate, payload);
  } else {
    ret_val = video_->RegisterVideoPayload(payload_name, payload_number, rate,
                                           payload);
  }
  if (payload) {
    payload_type_map_[payload_number] = payload;
  }
  return ret_val;
}

int32_t RTPSender::DeRegisterSendPayload(
    const int8_t payload_type) {
  CriticalSectionScoped lock(send_critsect_);

  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
      payload_type_map_.find(payload_type);

  if (payload_type_map_.end() == it) {
    return -1;
  }
  ModuleRTPUtility::Payload *payload = it->second;
  delete payload;
  payload_type_map_.erase(it);
  return 0;
}

int8_t RTPSender::SendPayloadType() const {
  CriticalSectionScoped cs(send_critsect_);
  return payload_type_;
}

int RTPSender::SendPayloadFrequency() const {
  return audio_ != NULL ? audio_->AudioFrequency() : kVideoPayloadTypeFrequency;
}

int32_t RTPSender::SetMaxPayloadLength(
    const uint16_t max_payload_length,
    const uint16_t packet_over_head) {
  // Sanity check.
  if (max_payload_length < 100 || max_payload_length > IP_PACKET_SIZE) {
    LOG(LS_ERROR) << "Invalid max payload length: " << max_payload_length;
    return -1;
  }
  CriticalSectionScoped cs(send_critsect_);
  max_payload_length_ = max_payload_length;
  packet_over_head_ = packet_over_head;
  return 0;
}

uint16_t RTPSender::MaxDataPayloadLength() const {
  if (audio_configured_) {
    return max_payload_length_ - RTPHeaderLength();
  } else {
    return max_payload_length_ - RTPHeaderLength()  // RTP overhead.
           - video_->FECPacketOverhead()            // FEC/ULP/RED overhead.
           - ((rtx_) ? 2 : 0);                      // RTX overhead.
  }
}

uint16_t RTPSender::MaxPayloadLength() const {
  return max_payload_length_;
}

uint16_t RTPSender::PacketOverHead() const { return packet_over_head_; }

void RTPSender::SetRTXStatus(int mode) {
  CriticalSectionScoped cs(send_critsect_);
  rtx_ = mode;
}

void RTPSender::SetRtxSsrc(uint32_t ssrc) {
  CriticalSectionScoped cs(send_critsect_);
  ssrc_rtx_ = ssrc;
}

void RTPSender::RTXStatus(int* mode, uint32_t* ssrc,
                          int* payload_type) const {
  CriticalSectionScoped cs(send_critsect_);
  *mode = rtx_;
  *ssrc = ssrc_rtx_;
  *payload_type = payload_type_rtx_;
}

void RTPSender::SetRtxPayloadType(int payload_type) {
  CriticalSectionScoped cs(send_critsect_);
  payload_type_rtx_ = payload_type;
}

int32_t RTPSender::CheckPayloadType(const int8_t payload_type,
                                    RtpVideoCodecTypes *video_type) {
  CriticalSectionScoped cs(send_critsect_);

  if (payload_type < 0) {
    LOG(LS_ERROR) << "Invalid payload_type " << payload_type;
    return -1;
  }
  if (audio_configured_) {
    int8_t red_pl_type = -1;
    if (audio_->RED(red_pl_type) == 0) {
      // We have configured RED.
      if (red_pl_type == payload_type) {
        // And it's a match...
        return 0;
      }
    }
  }
  if (payload_type_ == payload_type) {
    if (!audio_configured_) {
      *video_type = video_->VideoCodecType();
    }
    return 0;
  }
  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
      payload_type_map_.find(payload_type);
  if (it == payload_type_map_.end()) {
    LOG(LS_WARNING) << "Payload type " << payload_type << " not registered.";
    return -1;
  }
  payload_type_ = payload_type;
  ModuleRTPUtility::Payload *payload = it->second;
  assert(payload);
  if (!payload->audio && !audio_configured_) {
    video_->SetVideoCodecType(payload->typeSpecific.Video.videoCodecType);
    *video_type = payload->typeSpecific.Video.videoCodecType;
    video_->SetMaxConfiguredBitrateVideo(payload->typeSpecific.Video.maxRate);
  }
  return 0;
}

int32_t RTPSender::SendOutgoingData(
    const FrameType frame_type, const int8_t payload_type,
    const uint32_t capture_timestamp, int64_t capture_time_ms,
    const uint8_t *payload_data, const uint32_t payload_size,
    const RTPFragmentationHeader *fragmentation,
    VideoCodecInformation *codec_info, const RTPVideoTypeHeader *rtp_type_hdr) {
  {
    // Drop this packet if we're not sending media packets.
    CriticalSectionScoped cs(send_critsect_);
    if (!sending_media_) {
      return 0;
    }
  }
  RtpVideoCodecTypes video_type = kRtpVideoGeneric;
  if (CheckPayloadType(payload_type, &video_type) != 0) {
    LOG(LS_ERROR) << "Don't send data with unknown payload type.";
    return -1;
  }

  uint32_t ret_val;
  if (audio_configured_) {
    TRACE_EVENT_ASYNC_STEP1("webrtc", "Audio", capture_timestamp,
                            "Send", "type", FrameTypeToString(frame_type));
    assert(frame_type == kAudioFrameSpeech || frame_type == kAudioFrameCN ||
           frame_type == kFrameEmpty);

    ret_val = audio_->SendAudio(frame_type, payload_type, capture_timestamp,
                                payload_data, payload_size, fragmentation);
  } else {
    TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", capture_time_ms,
                            "Send", "type", FrameTypeToString(frame_type));
    assert(frame_type != kAudioFrameSpeech && frame_type != kAudioFrameCN);

    if (frame_type == kFrameEmpty) {
      if (paced_sender_->Enabled()) {
        // Padding is driven by the pacer and not by the encoder.
        return 0;
      }
      return SendPaddingAccordingToBitrate(payload_type, capture_timestamp,
                                           capture_time_ms) ? 0 : -1;
    }
    ret_val = video_->SendVideo(video_type, frame_type, payload_type,
                                capture_timestamp, capture_time_ms,
                                payload_data, payload_size,
                                fragmentation, codec_info,
                                rtp_type_hdr);

  }

  CriticalSectionScoped cs(statistics_crit_.get());
  uint32_t frame_count = ++frame_counts_[frame_type];
  if (frame_count_observer_) {
    frame_count_observer_->FrameCountUpdated(frame_type,
                                             frame_count,
                                             ssrc_);
  }

  return ret_val;
}

int RTPSender::SendRedundantPayloads(int payload_type, int bytes_to_send) {
  if (!(rtx_ & kRtxRedundantPayloads))
    return 0;
  uint8_t buffer[IP_PACKET_SIZE];
  int bytes_left = bytes_to_send;
  while (bytes_left > 0) {
    uint16_t length = bytes_left;
    int64_t capture_time_ms;
    if (!packet_history_.GetBestFittingPacket(buffer, &length,
                                              &capture_time_ms)) {
      break;
    }
    if (!PrepareAndSendPacket(buffer, length, capture_time_ms, true, false))
      return -1;
    ModuleRTPUtility::RTPHeaderParser rtp_parser(buffer, length);
    RTPHeader rtp_header;
    rtp_parser.Parse(rtp_header);
    bytes_left -= length - rtp_header.headerLength;
  }
  return bytes_to_send - bytes_left;
}

bool RTPSender::SendPaddingAccordingToBitrate(
    int8_t payload_type, uint32_t capture_timestamp,
    int64_t capture_time_ms) {
  // Current bitrate since last estimate(1 second) averaged with the
  // estimate since then, to get the most up to date bitrate.
  uint32_t current_bitrate = bitrate_sent_.BitrateNow();
  uint32_t target_bitrate = GetTargetBitrate();
  int bitrate_diff = target_bitrate - current_bitrate;
  if (bitrate_diff <= 0) {
    return true;
  }
  int bytes = 0;
  if (current_bitrate == 0) {
    // Start up phase. Send one 33.3 ms batch to start with.
    bytes = (bitrate_diff / 8) / 30;
  } else {
    bytes = (bitrate_diff / 8);
    // Cap at 200 ms of target send data.
    int bytes_cap = target_bitrate / 1000 * 25;  // 1000 / 8 / 5.
    if (bytes > bytes_cap) {
      bytes = bytes_cap;
    }
  }
  uint32_t timestamp;
  {
    CriticalSectionScoped cs(send_critsect_);
    // Add the random RTP timestamp offset and store the capture time for
    // later calculation of the send time offset.
    timestamp = start_time_stamp_ + capture_timestamp;
    timestamp_ = timestamp;
    capture_time_ms_ = capture_time_ms;
    last_timestamp_time_ms_ = clock_->TimeInMilliseconds();
  }
  int bytes_sent = SendPadData(payload_type, timestamp, capture_time_ms,
                               bytes, kDontRetransmit, false, false);
  // We did not manage to send all bytes. Comparing with 31 due to modulus 32.
  return bytes - bytes_sent < 31;
}

int RTPSender::BuildPaddingPacket(uint8_t* packet, int header_length,
                                  int32_t bytes) {
  int padding_bytes_in_packet = kMaxPaddingLength;
  if (bytes < kMaxPaddingLength) {
    padding_bytes_in_packet = bytes;
  }
  packet[0] |= 0x20;  // Set padding bit.
  int32_t *data =
      reinterpret_cast<int32_t *>(&(packet[header_length]));

  // Fill data buffer with random data.
  for (int j = 0; j < (padding_bytes_in_packet >> 2); ++j) {
    data[j] = rand();  // NOLINT
  }
  // Set number of padding bytes in the last byte of the packet.
  packet[header_length + padding_bytes_in_packet - 1] = padding_bytes_in_packet;
  return padding_bytes_in_packet;
}

int RTPSender::SendPadData(int payload_type, uint32_t timestamp,
                           int64_t capture_time_ms, int32_t bytes,
                           StorageType store, bool force_full_size_packets,
                           bool only_pad_after_markerbit) {
  // Drop this packet if we're not sending media packets.
  if (!SendingMedia()) {
    return bytes;
  }
  int padding_bytes_in_packet = 0;
  int bytes_sent = 0;
  for (; bytes > 0; bytes -= padding_bytes_in_packet) {
    // Always send full padding packets.
    if (force_full_size_packets && bytes < kMaxPaddingLength)
      bytes = kMaxPaddingLength;
    if (bytes < kMaxPaddingLength) {
      if (force_full_size_packets) {
        bytes = kMaxPaddingLength;
      } else {
        // Round to the nearest multiple of 32.
        bytes = (bytes + 16) & 0xffe0;
      }
    }
    if (bytes < 32) {
      // Sanity don't send empty packets.
      break;
    }
    uint32_t ssrc;
    uint16_t sequence_number;
    {
      CriticalSectionScoped cs(send_critsect_);
      // Only send padding packets following the last packet of a frame,
      // indicated by the marker bit.
      if (only_pad_after_markerbit && !last_packet_marker_bit_)
        return bytes_sent;
      if (rtx_ == kRtxOff) {
        ssrc = ssrc_;
        sequence_number = sequence_number_;
        ++sequence_number_;
      } else {
        ssrc = ssrc_rtx_;
        sequence_number = sequence_number_rtx_;
        ++sequence_number_rtx_;
      }
    }
    uint8_t padding_packet[IP_PACKET_SIZE];
    int header_length = CreateRTPHeader(padding_packet, payload_type, ssrc,
                                        false, timestamp, sequence_number, NULL,
                                        0);
    padding_bytes_in_packet = BuildPaddingPacket(padding_packet, header_length,
                                                 bytes);
    if (0 > SendToNetwork(padding_packet, padding_bytes_in_packet,
                          header_length, capture_time_ms, store,
                          PacedSender::kLowPriority)) {
      // Error sending the packet.
      break;
    }
    bytes_sent += padding_bytes_in_packet;
  }
  return bytes_sent;
}

void RTPSender::SetStorePacketsStatus(const bool enable,
                                      const uint16_t number_to_store) {
  packet_history_.SetStorePacketsStatus(enable, number_to_store);
}

bool RTPSender::StorePackets() const {
  return packet_history_.StorePackets();
}

int32_t RTPSender::ReSendPacket(uint16_t packet_id, uint32_t min_resend_time) {
  uint16_t length = IP_PACKET_SIZE;
  uint8_t data_buffer[IP_PACKET_SIZE];
  int64_t capture_time_ms;
  if (!packet_history_.GetPacketAndSetSendTime(packet_id, min_resend_time, true,
                                               data_buffer, &length,
                                               &capture_time_ms)) {
    // Packet not found.
    return 0;
  }

  if (paced_sender_) {
    ModuleRTPUtility::RTPHeaderParser rtp_parser(data_buffer, length);
    RTPHeader header;
    if (!rtp_parser.Parse(header)) {
      assert(false);
      return -1;
    }
    if (!paced_sender_->SendPacket(PacedSender::kHighPriority,
                                   header.ssrc,
                                   header.sequenceNumber,
                                   capture_time_ms,
                                   length - header.headerLength,
                                   true)) {
      // We can't send the packet right now.
      // We will be called when it is time.
      return length;
    }
  }

  return PrepareAndSendPacket(data_buffer, length, capture_time_ms,
                              (rtx_ & kRtxRetransmitted) > 0, true) ?
      length : -1;
}

bool RTPSender::SendPacketToNetwork(const uint8_t *packet, uint32_t size) {
  int bytes_sent = -1;
  if (transport_) {
    bytes_sent = transport_->SendPacket(id_, packet, size);
  }
  TRACE_EVENT_INSTANT2("webrtc_rtp", "RTPSender::SendPacketToNetwork",
                       "size", size, "sent", bytes_sent);
  // TODO(pwestin): Add a separate bitrate for sent bitrate after pacer.
  if (bytes_sent <= 0) {
    LOG(LS_WARNING) << "Transport failed to send packet";
    return false;
  }
  return true;
}

int RTPSender::SelectiveRetransmissions() const {
  if (!video_)
    return -1;
  return video_->SelectiveRetransmissions();
}

int RTPSender::SetSelectiveRetransmissions(uint8_t settings) {
  if (!video_)
    return -1;
  return video_->SetSelectiveRetransmissions(settings);
}

void RTPSender::OnReceivedNACK(
    const std::list<uint16_t>& nack_sequence_numbers,
    const uint16_t avg_rtt) {
  TRACE_EVENT2("webrtc_rtp", "RTPSender::OnReceivedNACK",
               "num_seqnum", nack_sequence_numbers.size(), "avg_rtt", avg_rtt);
  const int64_t now = clock_->TimeInMilliseconds();
  uint32_t bytes_re_sent = 0;
  uint32_t target_bitrate = GetTargetBitrate();

  // Enough bandwidth to send NACK?
  if (!ProcessNACKBitRate(now)) {
    LOG(LS_INFO) << "NACK bitrate reached. Skip sending NACK response. Target "
                 << target_bitrate;
    return;
  }

  for (std::list<uint16_t>::const_iterator it = nack_sequence_numbers.begin();
      it != nack_sequence_numbers.end(); ++it) {
    const int32_t bytes_sent = ReSendPacket(*it, 5 + avg_rtt);
    if (bytes_sent > 0) {
      bytes_re_sent += bytes_sent;
    } else if (bytes_sent == 0) {
      // The packet has previously been resent.
      // Try resending next packet in the list.
      continue;
    } else if (bytes_sent < 0) {
      // Failed to send one Sequence number. Give up the rest in this nack.
      LOG(LS_WARNING) << "Failed resending RTP packet " << *it
                      << ", Discard rest of packets";
      break;
    }
    // Delay bandwidth estimate (RTT * BW).
    if (target_bitrate != 0 && avg_rtt) {
      // kbits/s * ms = bits => bits/8 = bytes
      uint32_t target_bytes =
          (static_cast<uint32_t>(target_bitrate / 1000) * avg_rtt) >> 3;
      if (bytes_re_sent > target_bytes) {
        break;  // Ignore the rest of the packets in the list.
      }
    }
  }
  if (bytes_re_sent > 0) {
    // TODO(pwestin) consolidate these two methods.
    UpdateNACKBitRate(bytes_re_sent, now);
    nack_bitrate_.Update(bytes_re_sent);
  }
}

bool RTPSender::ProcessNACKBitRate(const uint32_t now) {
  uint32_t num = 0;
  int byte_count = 0;
  const int kAvgIntervalMs = 1000;
  uint32_t target_bitrate = GetTargetBitrate();

  CriticalSectionScoped cs(send_critsect_);

  if (target_bitrate == 0) {
    return true;
  }
  for (num = 0; num < NACK_BYTECOUNT_SIZE; ++num) {
    if ((now - nack_byte_count_times_[num]) > kAvgIntervalMs) {
      // Don't use data older than 1sec.
      break;
    } else {
      byte_count += nack_byte_count_[num];
    }
  }
  int time_interval = kAvgIntervalMs;
  if (num == NACK_BYTECOUNT_SIZE) {
    // More than NACK_BYTECOUNT_SIZE nack messages has been received
    // during the last msg_interval.
    time_interval = now - nack_byte_count_times_[num - 1];
    if (time_interval < 0) {
      time_interval = kAvgIntervalMs;
    }
  }
  return (byte_count * 8) <
         static_cast<int>(target_bitrate / 1000 * time_interval);
}

void RTPSender::UpdateNACKBitRate(const uint32_t bytes,
                                  const uint32_t now) {
  CriticalSectionScoped cs(send_critsect_);

  // Save bitrate statistics.
  if (bytes > 0) {
    if (now == 0) {
      // Add padding length.
      nack_byte_count_[0] += bytes;
    } else {<commit_msg>fix after r6472 in rtp_sender, comparison between signed and unsigned integer expressions.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/rtp_rtcp/source/rtp_sender.h"

#include <stdlib.h>  // srand

#include "webrtc/modules/rtp_rtcp/source/rtp_sender_audio.h"
#include "webrtc/modules/rtp_rtcp/source/rtp_sender_video.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/trace_event.h"

namespace webrtc {

// Max in the RFC 3550 is 255 bytes, we limit it to be modulus 32 for SRTP.
const int kMaxPaddingLength = 224;
const int kSendSideDelayWindowMs = 1000;

namespace {

const char* FrameTypeToString(const FrameType frame_type) {
  switch (frame_type) {
    case kFrameEmpty: return "empty";
    case kAudioFrameSpeech: return "audio_speech";
    case kAudioFrameCN: return "audio_cn";
    case kVideoFrameKey: return "video_key";
    case kVideoFrameDelta: return "video_delta";
  }
  return "";
}

}  // namespace

RTPSender::RTPSender(const int32_t id,
                     const bool audio,
                     Clock* clock,
                     Transport* transport,
                     RtpAudioFeedback* audio_feedback,
                     PacedSender* paced_sender)
    : clock_(clock),
      bitrate_sent_(clock, this),
      id_(id),
      audio_configured_(audio),
      audio_(NULL),
      video_(NULL),
      paced_sender_(paced_sender),
      send_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
      transport_(transport),
      sending_media_(true),                      // Default to sending media.
      max_payload_length_(IP_PACKET_SIZE - 28),  // Default is IP-v4/UDP.
      packet_over_head_(28),
      payload_type_(-1),
      payload_type_map_(),
      rtp_header_extension_map_(),
      transmission_time_offset_(0),
      absolute_send_time_(0),
      // NACK.
      nack_byte_count_times_(),
      nack_byte_count_(),
      nack_bitrate_(clock, NULL),
      packet_history_(clock),
      // Statistics
      statistics_crit_(CriticalSectionWrapper::CreateCriticalSection()),
      frame_count_observer_(NULL),
      rtp_stats_callback_(NULL),
      bitrate_callback_(NULL),
      // RTP variables
      start_time_stamp_forced_(false),
      start_time_stamp_(0),
      ssrc_db_(*SSRCDatabase::GetSSRCDatabase()),
      remote_ssrc_(0),
      sequence_number_forced_(false),
      ssrc_forced_(false),
      timestamp_(0),
      capture_time_ms_(0),
      last_timestamp_time_ms_(0),
      last_packet_marker_bit_(false),
      num_csrcs_(0),
      csrcs_(),
      include_csrcs_(true),
      rtx_(kRtxOff),
      payload_type_rtx_(-1),
      target_bitrate_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
      target_bitrate_(0) {
  memset(nack_byte_count_times_, 0, sizeof(nack_byte_count_times_));
  memset(nack_byte_count_, 0, sizeof(nack_byte_count_));
  memset(csrcs_, 0, sizeof(csrcs_));
  // We need to seed the random generator.
  srand(static_cast<uint32_t>(clock_->TimeInMilliseconds()));
  ssrc_ = ssrc_db_.CreateSSRC();  // Can't be 0.
  ssrc_rtx_ = ssrc_db_.CreateSSRC();  // Can't be 0.
  // Random start, 16 bits. Can't be 0.
  sequence_number_rtx_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;
  sequence_number_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;

  if (audio) {
    audio_ = new RTPSenderAudio(id, clock_, this);
    audio_->RegisterAudioCallback(audio_feedback);
  } else {
    video_ = new RTPSenderVideo(clock_, this);
  }
}

RTPSender::~RTPSender() {
  if (remote_ssrc_ != 0) {
    ssrc_db_.ReturnSSRC(remote_ssrc_);
  }
  ssrc_db_.ReturnSSRC(ssrc_);

  SSRCDatabase::ReturnSSRCDatabase();
  delete send_critsect_;
  while (!payload_type_map_.empty()) {
    std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
        payload_type_map_.begin();
    delete it->second;
    payload_type_map_.erase(it);
  }
  delete audio_;
  delete video_;
}

void RTPSender::SetTargetBitrate(uint32_t bitrate) {
  CriticalSectionScoped cs(target_bitrate_critsect_.get());
  target_bitrate_ = bitrate;
}

uint32_t RTPSender::GetTargetBitrate() {
  CriticalSectionScoped cs(target_bitrate_critsect_.get());
  return target_bitrate_;
}

uint16_t RTPSender::ActualSendBitrateKbit() const {
  return (uint16_t)(bitrate_sent_.BitrateNow() / 1000);
}

uint32_t RTPSender::VideoBitrateSent() const {
  if (video_) {
    return video_->VideoBitrateSent();
  }
  return 0;
}

uint32_t RTPSender::FecOverheadRate() const {
  if (video_) {
    return video_->FecOverheadRate();
  }
  return 0;
}

uint32_t RTPSender::NackOverheadRate() const {
  return nack_bitrate_.BitrateLast();
}

bool RTPSender::GetSendSideDelay(int* avg_send_delay_ms,
                                 int* max_send_delay_ms) const {
  if (!SendingMedia())
    return false;
  CriticalSectionScoped cs(statistics_crit_.get());
  SendDelayMap::const_iterator it = send_delays_.upper_bound(
      clock_->TimeInMilliseconds() - kSendSideDelayWindowMs);
  if (it == send_delays_.end())
    return false;
  int num_delays = 0;
  for (; it != send_delays_.end(); ++it) {
    *max_send_delay_ms = std::max(*max_send_delay_ms, it->second);
    *avg_send_delay_ms += it->second;
    ++num_delays;
  }
  *avg_send_delay_ms = (*avg_send_delay_ms + num_delays / 2) / num_delays;
  return true;
}

int32_t RTPSender::SetTransmissionTimeOffset(
    const int32_t transmission_time_offset) {
  if (transmission_time_offset > (0x800000 - 1) ||
      transmission_time_offset < -(0x800000 - 1)) {  // Word24.
    return -1;
  }
  CriticalSectionScoped cs(send_critsect_);
  transmission_time_offset_ = transmission_time_offset;
  return 0;
}

int32_t RTPSender::SetAbsoluteSendTime(
    const uint32_t absolute_send_time) {
  if (absolute_send_time > 0xffffff) {  // UWord24.
    return -1;
  }
  CriticalSectionScoped cs(send_critsect_);
  absolute_send_time_ = absolute_send_time;
  return 0;
}

int32_t RTPSender::RegisterRtpHeaderExtension(const RTPExtensionType type,
                                              const uint8_t id) {
  CriticalSectionScoped cs(send_critsect_);
  return rtp_header_extension_map_.Register(type, id);
}

int32_t RTPSender::DeregisterRtpHeaderExtension(
    const RTPExtensionType type) {
  CriticalSectionScoped cs(send_critsect_);
  return rtp_header_extension_map_.Deregister(type);
}

uint16_t RTPSender::RtpHeaderExtensionTotalLength() const {
  CriticalSectionScoped cs(send_critsect_);
  return rtp_header_extension_map_.GetTotalLengthInBytes();
}

int32_t RTPSender::RegisterPayload(
    const char payload_name[RTP_PAYLOAD_NAME_SIZE],
    const int8_t payload_number, const uint32_t frequency,
    const uint8_t channels, const uint32_t rate) {
  assert(payload_name);
  CriticalSectionScoped cs(send_critsect_);

  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
      payload_type_map_.find(payload_number);

  if (payload_type_map_.end() != it) {
    // We already use this payload type.
    ModuleRTPUtility::Payload *payload = it->second;
    assert(payload);

    // Check if it's the same as we already have.
    if (ModuleRTPUtility::StringCompare(payload->name, payload_name,
                                        RTP_PAYLOAD_NAME_SIZE - 1)) {
      if (audio_configured_ && payload->audio &&
          payload->typeSpecific.Audio.frequency == frequency &&
          (payload->typeSpecific.Audio.rate == rate ||
           payload->typeSpecific.Audio.rate == 0 || rate == 0)) {
        payload->typeSpecific.Audio.rate = rate;
        // Ensure that we update the rate if new or old is zero.
        return 0;
      }
      if (!audio_configured_ && !payload->audio) {
        return 0;
      }
    }
    return -1;
  }
  int32_t ret_val = -1;
  ModuleRTPUtility::Payload *payload = NULL;
  if (audio_configured_) {
    ret_val = audio_->RegisterAudioPayload(payload_name, payload_number,
                                           frequency, channels, rate, payload);
  } else {
    ret_val = video_->RegisterVideoPayload(payload_name, payload_number, rate,
                                           payload);
  }
  if (payload) {
    payload_type_map_[payload_number] = payload;
  }
  return ret_val;
}

int32_t RTPSender::DeRegisterSendPayload(
    const int8_t payload_type) {
  CriticalSectionScoped lock(send_critsect_);

  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
      payload_type_map_.find(payload_type);

  if (payload_type_map_.end() == it) {
    return -1;
  }
  ModuleRTPUtility::Payload *payload = it->second;
  delete payload;
  payload_type_map_.erase(it);
  return 0;
}

int8_t RTPSender::SendPayloadType() const {
  CriticalSectionScoped cs(send_critsect_);
  return payload_type_;
}

int RTPSender::SendPayloadFrequency() const {
  return audio_ != NULL ? audio_->AudioFrequency() : kVideoPayloadTypeFrequency;
}

int32_t RTPSender::SetMaxPayloadLength(
    const uint16_t max_payload_length,
    const uint16_t packet_over_head) {
  // Sanity check.
  if (max_payload_length < 100 || max_payload_length > IP_PACKET_SIZE) {
    LOG(LS_ERROR) << "Invalid max payload length: " << max_payload_length;
    return -1;
  }
  CriticalSectionScoped cs(send_critsect_);
  max_payload_length_ = max_payload_length;
  packet_over_head_ = packet_over_head;
  return 0;
}

uint16_t RTPSender::MaxDataPayloadLength() const {
  if (audio_configured_) {
    return max_payload_length_ - RTPHeaderLength();
  } else {
    return max_payload_length_ - RTPHeaderLength()  // RTP overhead.
           - video_->FECPacketOverhead()            // FEC/ULP/RED overhead.
           - ((rtx_) ? 2 : 0);                      // RTX overhead.
  }
}

uint16_t RTPSender::MaxPayloadLength() const {
  return max_payload_length_;
}

uint16_t RTPSender::PacketOverHead() const { return packet_over_head_; }

void RTPSender::SetRTXStatus(int mode) {
  CriticalSectionScoped cs(send_critsect_);
  rtx_ = mode;
}

void RTPSender::SetRtxSsrc(uint32_t ssrc) {
  CriticalSectionScoped cs(send_critsect_);
  ssrc_rtx_ = ssrc;
}

void RTPSender::RTXStatus(int* mode, uint32_t* ssrc,
                          int* payload_type) const {
  CriticalSectionScoped cs(send_critsect_);
  *mode = rtx_;
  *ssrc = ssrc_rtx_;
  *payload_type = payload_type_rtx_;
}

void RTPSender::SetRtxPayloadType(int payload_type) {
  CriticalSectionScoped cs(send_critsect_);
  payload_type_rtx_ = payload_type;
}

int32_t RTPSender::CheckPayloadType(const int8_t payload_type,
                                    RtpVideoCodecTypes *video_type) {
  CriticalSectionScoped cs(send_critsect_);

  if (payload_type < 0) {
    LOG(LS_ERROR) << "Invalid payload_type " << payload_type;
    return -1;
  }
  if (audio_configured_) {
    int8_t red_pl_type = -1;
    if (audio_->RED(red_pl_type) == 0) {
      // We have configured RED.
      if (red_pl_type == payload_type) {
        // And it's a match...
        return 0;
      }
    }
  }
  if (payload_type_ == payload_type) {
    if (!audio_configured_) {
      *video_type = video_->VideoCodecType();
    }
    return 0;
  }
  std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
      payload_type_map_.find(payload_type);
  if (it == payload_type_map_.end()) {
    LOG(LS_WARNING) << "Payload type " << payload_type << " not registered.";
    return -1;
  }
  payload_type_ = payload_type;
  ModuleRTPUtility::Payload *payload = it->second;
  assert(payload);
  if (!payload->audio && !audio_configured_) {
    video_->SetVideoCodecType(payload->typeSpecific.Video.videoCodecType);
    *video_type = payload->typeSpecific.Video.videoCodecType;
    video_->SetMaxConfiguredBitrateVideo(payload->typeSpecific.Video.maxRate);
  }
  return 0;
}

int32_t RTPSender::SendOutgoingData(
    const FrameType frame_type, const int8_t payload_type,
    const uint32_t capture_timestamp, int64_t capture_time_ms,
    const uint8_t *payload_data, const uint32_t payload_size,
    const RTPFragmentationHeader *fragmentation,
    VideoCodecInformation *codec_info, const RTPVideoTypeHeader *rtp_type_hdr) {
  {
    // Drop this packet if we're not sending media packets.
    CriticalSectionScoped cs(send_critsect_);
    if (!sending_media_) {
      return 0;
    }
  }
  RtpVideoCodecTypes video_type = kRtpVideoGeneric;
  if (CheckPayloadType(payload_type, &video_type) != 0) {
    LOG(LS_ERROR) << "Don't send data with unknown payload type.";
    return -1;
  }

  uint32_t ret_val;
  if (audio_configured_) {
    TRACE_EVENT_ASYNC_STEP1("webrtc", "Audio", capture_timestamp,
                            "Send", "type", FrameTypeToString(frame_type));
    assert(frame_type == kAudioFrameSpeech || frame_type == kAudioFrameCN ||
           frame_type == kFrameEmpty);

    ret_val = audio_->SendAudio(frame_type, payload_type, capture_timestamp,
                                payload_data, payload_size, fragmentation);
  } else {
    TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", capture_time_ms,
                            "Send", "type", FrameTypeToString(frame_type));
    assert(frame_type != kAudioFrameSpeech && frame_type != kAudioFrameCN);

    if (frame_type == kFrameEmpty) {
      if (paced_sender_->Enabled()) {
        // Padding is driven by the pacer and not by the encoder.
        return 0;
      }
      return SendPaddingAccordingToBitrate(payload_type, capture_timestamp,
                                           capture_time_ms) ? 0 : -1;
    }
    ret_val = video_->SendVideo(video_type, frame_type, payload_type,
                                capture_timestamp, capture_time_ms,
                                payload_data, payload_size,
                                fragmentation, codec_info,
                                rtp_type_hdr);

  }

  CriticalSectionScoped cs(statistics_crit_.get());
  uint32_t frame_count = ++frame_counts_[frame_type];
  if (frame_count_observer_) {
    frame_count_observer_->FrameCountUpdated(frame_type,
                                             frame_count,
                                             ssrc_);
  }

  return ret_val;
}

int RTPSender::SendRedundantPayloads(int payload_type, int bytes_to_send) {
  if (!(rtx_ & kRtxRedundantPayloads))
    return 0;
  uint8_t buffer[IP_PACKET_SIZE];
  int bytes_left = bytes_to_send;
  while (bytes_left > 0) {
    uint16_t length = bytes_left;
    int64_t capture_time_ms;
    if (!packet_history_.GetBestFittingPacket(buffer, &length,
                                              &capture_time_ms)) {
      break;
    }
    if (!PrepareAndSendPacket(buffer, length, capture_time_ms, true, false))
      return -1;
    ModuleRTPUtility::RTPHeaderParser rtp_parser(buffer, length);
    RTPHeader rtp_header;
    rtp_parser.Parse(rtp_header);
    bytes_left -= length - rtp_header.headerLength;
  }
  return bytes_to_send - bytes_left;
}

bool RTPSender::SendPaddingAccordingToBitrate(
    int8_t payload_type, uint32_t capture_timestamp,
    int64_t capture_time_ms) {
  // Current bitrate since last estimate(1 second) averaged with the
  // estimate since then, to get the most up to date bitrate.
  uint32_t current_bitrate = bitrate_sent_.BitrateNow();
  uint32_t target_bitrate = GetTargetBitrate();
  int bitrate_diff = target_bitrate - current_bitrate;
  if (bitrate_diff <= 0) {
    return true;
  }
  int bytes = 0;
  if (current_bitrate == 0) {
    // Start up phase. Send one 33.3 ms batch to start with.
    bytes = (bitrate_diff / 8) / 30;
  } else {
    bytes = (bitrate_diff / 8);
    // Cap at 200 ms of target send data.
    int bytes_cap = target_bitrate / 1000 * 25;  // 1000 / 8 / 5.
    if (bytes > bytes_cap) {
      bytes = bytes_cap;
    }
  }
  uint32_t timestamp;
  {
    CriticalSectionScoped cs(send_critsect_);
    // Add the random RTP timestamp offset and store the capture time for
    // later calculation of the send time offset.
    timestamp = start_time_stamp_ + capture_timestamp;
    timestamp_ = timestamp;
    capture_time_ms_ = capture_time_ms;
    last_timestamp_time_ms_ = clock_->TimeInMilliseconds();
  }
  int bytes_sent = SendPadData(payload_type, timestamp, capture_time_ms,
                               bytes, kDontRetransmit, false, false);
  // We did not manage to send all bytes. Comparing with 31 due to modulus 32.
  return bytes - bytes_sent < 31;
}

int RTPSender::BuildPaddingPacket(uint8_t* packet, int header_length,
                                  int32_t bytes) {
  int padding_bytes_in_packet = kMaxPaddingLength;
  if (bytes < kMaxPaddingLength) {
    padding_bytes_in_packet = bytes;
  }
  packet[0] |= 0x20;  // Set padding bit.
  int32_t *data =
      reinterpret_cast<int32_t *>(&(packet[header_length]));

  // Fill data buffer with random data.
  for (int j = 0; j < (padding_bytes_in_packet >> 2); ++j) {
    data[j] = rand();  // NOLINT
  }
  // Set number of padding bytes in the last byte of the packet.
  packet[header_length + padding_bytes_in_packet - 1] = padding_bytes_in_packet;
  return padding_bytes_in_packet;
}

int RTPSender::SendPadData(int payload_type, uint32_t timestamp,
                           int64_t capture_time_ms, int32_t bytes,
                           StorageType store, bool force_full_size_packets,
                           bool only_pad_after_markerbit) {
  // Drop this packet if we're not sending media packets.
  if (!SendingMedia()) {
    return bytes;
  }
  int padding_bytes_in_packet = 0;
  int bytes_sent = 0;
  for (; bytes > 0; bytes -= padding_bytes_in_packet) {
    // Always send full padding packets.
    if (force_full_size_packets && bytes < kMaxPaddingLength)
      bytes = kMaxPaddingLength;
    if (bytes < kMaxPaddingLength) {
      if (force_full_size_packets) {
        bytes = kMaxPaddingLength;
      } else {
        // Round to the nearest multiple of 32.
        bytes = (bytes + 16) & 0xffe0;
      }
    }
    if (bytes < 32) {
      // Sanity don't send empty packets.
      break;
    }
    uint32_t ssrc;
    uint16_t sequence_number;
    {
      CriticalSectionScoped cs(send_critsect_);
      // Only send padding packets following the last packet of a frame,
      // indicated by the marker bit.
      if (only_pad_after_markerbit && !last_packet_marker_bit_)
        return bytes_sent;
      if (rtx_ == kRtxOff) {
        ssrc = ssrc_;
        sequence_number = sequence_number_;
        ++sequence_number_;
      } else {
        ssrc = ssrc_rtx_;
        sequence_number = sequence_number_rtx_;
        ++sequence_number_rtx_;
      }
    }
    uint8_t padding_packet[IP_PACKET_SIZE];
    int header_length = CreateRTPHeader(padding_packet, payload_type, ssrc,
                                        false, timestamp, sequence_number, NULL,
                                        0);
    padding_bytes_in_packet = BuildPaddingPacket(padding_packet, header_length,
                                                 bytes);
    if (0 > SendToNetwork(padding_packet, padding_bytes_in_packet,
                          header_length, capture_time_ms, store,
                          PacedSender::kLowPriority)) {
      // Error sending the packet.
      break;
    }
    bytes_sent += padding_bytes_in_packet;
  }
  return bytes_sent;
}

void RTPSender::SetStorePacketsStatus(const bool enable,
                                      const uint16_t number_to_store) {
  packet_history_.SetStorePacketsStatus(enable, number_to_store);
}

bool RTPSender::StorePackets() const {
  return packet_history_.StorePackets();
}

int32_t RTPSender::ReSendPacket(uint16_t packet_id, uint32_t min_resend_time) {
  uint16_t length = IP_PACKET_SIZE;
  uint8_t data_buffer[IP_PACKET_SIZE];
  int64_t capture_time_ms;
  if (!packet_history_.GetPacketAndSetSendTime(packet_id, min_resend_time, true,
                                               data_buffer, &length,
                                               &capture_time_ms)) {
    // Packet not found.
    return 0;
  }

  if (paced_sender_) {
    ModuleRTPUtility::RTPHeaderParser rtp_parser(data_buffer, length);
    RTPHeader header;
    if (!rtp_parser.Parse(header)) {
      assert(false);
      return -1;
    }
    if (!paced_sender_->SendPacket(PacedSender::kHighPriority,
                                   header.ssrc,
                                   header.sequenceNumber,
                                   capture_time_ms,
                                   length - header.headerLength,
                                   true)) {
      // We can't send the packet right now.
      // We will be called when it is time.
      return length;
    }
  }

  return PrepareAndSendPacket(data_buffer, length, capture_time_ms,
                              (rtx_ & kRtxRetransmitted) > 0, true) ?
      length : -1;
}

bool RTPSender::SendPacketToNetwork(const uint8_t *packet, uint32_t size) {
  int bytes_sent = -1;
  if (transport_) {
    bytes_sent = transport_->SendPacket(id_, packet, size);
  }
  TRACE_EVENT_INSTANT2("webrtc_rtp", "RTPSender::SendPacketToNetwork",
                       "size", size, "sent", bytes_sent);
  // TODO(pwestin): Add a separate bitrate for sent bitrate after pacer.
  if (bytes_sent <= 0) {
    LOG(LS_WARNING) << "Transport failed to send packet";
    return false;
  }
  return true;
}

int RTPSender::SelectiveRetransmissions() const {
  if (!video_)
    return -1;
  return video_->SelectiveRetransmissions();
}

int RTPSender::SetSelectiveRetransmissions(uint8_t settings) {
  if (!video_)
    return -1;
  return video_->SetSelectiveRetransmissions(settings);
}

void RTPSender::OnReceivedNACK(
    const std::list<uint16_t>& nack_sequence_numbers,
    const uint16_t avg_rtt) {
  TRACE_EVENT2("webrtc_rtp", "RTPSender::OnReceivedNACK",
               "num_seqnum", nack_sequence_numbers.size(), "avg_rtt", avg_rtt);
  const int64_t now = clock_->TimeInMilliseconds();
  uint32_t bytes_re_sent = 0;
  uint32_t target_bitrate = GetTargetBitrate();

  // Enough bandwidth to send NACK?
  if (!ProcessNACKBitRate(now)) {
    LOG(LS_INFO) << "NACK bitrate reached. Skip sending NACK response. Target "
                 << target_bitrate;
    return;
  }

  for (std::list<uint16_t>::const_iterator it = nack_sequence_numbers.begin();
      it != nack_sequence_numbers.end(); ++it) {
    const int32_t bytes_sent = ReSendPacket(*it, 5 + avg_rtt);
    if (bytes_sent > 0) {
      bytes_re_sent += bytes_sent;
    } else if (bytes_sent == 0) {
      // The packet has previously been resent.
      // Try resending next packet in the list.
      continue;
    } else if (bytes_sent < 0) {
      // Failed to send one Sequence number. Give up the rest in this nack.
      LOG(LS_WARNING) << "Failed resending RTP packet " << *it
                      << ", Discard rest of packets";
      break;
    }
    // Delay bandwidth estimate (RTT * BW).
    if (target_bitrate != 0 && avg_rtt) {
      // kbits/s * ms = bits => bits/8 = bytes
      uint32_t target_bytes =
          (static_cast<uint32_t>(target_bitrate / 1000) * avg_rtt) >> 3;
      if (bytes_re_sent > target_bytes) {
        break;  // Ignore the rest of the packets in the list.
      }
    }
  }
  if (bytes_re_sent > 0) {
    // TODO(pwestin) consolidate these two methods.
    UpdateNACKBitRate(bytes_re_sent, now);
    nack_bitrate_.Update(bytes_re_sent);
  }
}

bool RTPSender::ProcessNACKBitRate(const uint32_t now) {
  uint32_t num = 0;
  int byte_count = 0;
  const uint32_t kAvgIntervalMs = 1000;
  uint32_t target_bitrate = GetTargetBitrate();

  CriticalSectionScoped cs(send_critsect_);

  if (target_bitrate == 0) {
    return true;
  }
  for (num = 0; num < NACK_BYTECOUNT_SIZE; ++num) {
    if ((now - nack_byte_count_times_[num]) > kAvgIntervalMs) {
      // Don't use data older than 1sec.
      break;
    } else {
      byte_count += nack_byte_count_[num];
    }
  }
  uint32_t time_interval = kAvgIntervalMs;
  if (num == NACK_BYTECOUNT_SIZE) {
    // More than NACK_BYTECOUNT_SIZE nack messages has been received
    // during the last msg_interval.
    if (nack_byte_count_times_[num - 1] <= now) {
      time_interval = now - nack_byte_count_times_[num - 1];
    }
  }
  return (byte_count * 8) <
         static_cast<int>(target_bitrate / 1000 * time_interval);
}

void RTPSender::UpdateNACKBitRate(const uint32_t bytes,
                                  const uint32_t now) {
  CriticalSectionScoped cs(send_critsect_);

  // Save bitrate statistics.
  if (bytes > 0) {
    if (now == 0) {
      // Add padding length.
      nack_byte_count_[0] += bytes;
    } else {
{'fraction_non_alphanumeric': 0.09895728491485165, 'fraction_numerical': 0.015499818833286364, 'mean_word_length': 2.9237816918094937, 'pattern_counts': {'":': 0, '<': 115, '<?xml version=': 0, '>': 145, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 68, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5386266', 'n_tokens_mistral': 16634, 'n_tokens_neox': 15915, 'n_words': 3440}