2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
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.
11 #include "webrtc/modules/rtp_rtcp/source/rtp_sender.h"
13 #include <stdlib.h> // srand
15 #include "webrtc/modules/rtp_rtcp/source/rtp_sender_audio.h"
16 #include "webrtc/modules/rtp_rtcp/source/rtp_sender_video.h"
17 #include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
18 #include "webrtc/system_wrappers/interface/trace.h"
19 #include "webrtc/system_wrappers/interface/trace_event.h"
23 // Max in the RFC 3550 is 255 bytes, we limit it to be modulus 32 for SRTP.
24 const int kMaxPaddingLength = 224;
25 const int kSendSideDelayWindowMs = 1000;
29 const char* FrameTypeToString(const FrameType frame_type) {
31 case kFrameEmpty: return "empty";
32 case kAudioFrameSpeech: return "audio_speech";
33 case kAudioFrameCN: return "audio_cn";
34 case kVideoFrameKey: return "video_key";
35 case kVideoFrameDelta: return "video_delta";
42 RTPSender::RTPSender(const int32_t id,
46 RtpAudioFeedback* audio_feedback,
47 PacedSender* paced_sender)
49 bitrate_sent_(clock, this),
51 audio_configured_(audio),
54 paced_sender_(paced_sender),
55 send_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
56 transport_(transport),
57 sending_media_(true), // Default to sending media.
58 max_payload_length_(IP_PACKET_SIZE - 28), // Default is IP-v4/UDP.
59 packet_over_head_(28),
62 rtp_header_extension_map_(),
63 transmission_time_offset_(0),
64 absolute_send_time_(0),
66 nack_byte_count_times_(),
68 nack_bitrate_(clock, NULL),
69 packet_history_(clock),
71 statistics_crit_(CriticalSectionWrapper::CreateCriticalSection()),
72 frame_count_observer_(NULL),
73 rtp_stats_callback_(NULL),
74 bitrate_callback_(NULL),
76 start_time_stamp_forced_(false),
78 ssrc_db_(*SSRCDatabase::GetSSRCDatabase()),
80 sequence_number_forced_(false),
84 last_timestamp_time_ms_(0),
85 last_packet_marker_bit_(false),
90 payload_type_rtx_(-1),
91 target_bitrate_critsect_(CriticalSectionWrapper::CreateCriticalSection()),
92 target_bitrate_kbps_(0) {
93 memset(nack_byte_count_times_, 0, sizeof(nack_byte_count_times_));
94 memset(nack_byte_count_, 0, sizeof(nack_byte_count_));
95 memset(csrcs_, 0, sizeof(csrcs_));
96 // We need to seed the random generator.
97 srand(static_cast<uint32_t>(clock_->TimeInMilliseconds()));
98 ssrc_ = ssrc_db_.CreateSSRC(); // Can't be 0.
99 ssrc_rtx_ = ssrc_db_.CreateSSRC(); // Can't be 0.
100 // Random start, 16 bits. Can't be 0.
101 sequence_number_rtx_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;
102 sequence_number_ = static_cast<uint16_t>(rand() + 1) & 0x7FFF;
105 audio_ = new RTPSenderAudio(id, clock_, this);
106 audio_->RegisterAudioCallback(audio_feedback);
108 video_ = new RTPSenderVideo(id, clock_, this);
110 WEBRTC_TRACE(kTraceMemory, kTraceRtpRtcp, id, "%s created", __FUNCTION__);
113 RTPSender::~RTPSender() {
114 if (remote_ssrc_ != 0) {
115 ssrc_db_.ReturnSSRC(remote_ssrc_);
117 ssrc_db_.ReturnSSRC(ssrc_);
119 SSRCDatabase::ReturnSSRCDatabase();
120 delete send_critsect_;
121 while (!payload_type_map_.empty()) {
122 std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
123 payload_type_map_.begin();
125 payload_type_map_.erase(it);
130 WEBRTC_TRACE(kTraceMemory, kTraceRtpRtcp, id_, "%s deleted", __FUNCTION__);
133 void RTPSender::SetTargetSendBitrate(const uint32_t bits) {
134 SetTargetBitrateKbps(static_cast<uint16_t>(bits / 1000));
137 uint16_t RTPSender::ActualSendBitrateKbit() const {
138 return (uint16_t)(bitrate_sent_.BitrateNow() / 1000);
141 uint32_t RTPSender::VideoBitrateSent() const {
143 return video_->VideoBitrateSent();
148 uint32_t RTPSender::FecOverheadRate() const {
150 return video_->FecOverheadRate();
155 uint32_t RTPSender::NackOverheadRate() const {
156 return nack_bitrate_.BitrateLast();
159 bool RTPSender::GetSendSideDelay(int* avg_send_delay_ms,
160 int* max_send_delay_ms) const {
163 CriticalSectionScoped cs(statistics_crit_.get());
164 SendDelayMap::const_iterator it = send_delays_.upper_bound(
165 clock_->TimeInMilliseconds() - kSendSideDelayWindowMs);
166 if (it == send_delays_.end())
169 for (; it != send_delays_.end(); ++it) {
170 *max_send_delay_ms = std::max(*max_send_delay_ms, it->second);
171 *avg_send_delay_ms += it->second;
174 *avg_send_delay_ms = (*avg_send_delay_ms + num_delays / 2) / num_delays;
178 int32_t RTPSender::SetTransmissionTimeOffset(
179 const int32_t transmission_time_offset) {
180 if (transmission_time_offset > (0x800000 - 1) ||
181 transmission_time_offset < -(0x800000 - 1)) { // Word24.
184 CriticalSectionScoped cs(send_critsect_);
185 transmission_time_offset_ = transmission_time_offset;
189 int32_t RTPSender::SetAbsoluteSendTime(
190 const uint32_t absolute_send_time) {
191 if (absolute_send_time > 0xffffff) { // UWord24.
194 CriticalSectionScoped cs(send_critsect_);
195 absolute_send_time_ = absolute_send_time;
199 int32_t RTPSender::RegisterRtpHeaderExtension(const RTPExtensionType type,
201 CriticalSectionScoped cs(send_critsect_);
202 return rtp_header_extension_map_.Register(type, id);
205 int32_t RTPSender::DeregisterRtpHeaderExtension(
206 const RTPExtensionType type) {
207 CriticalSectionScoped cs(send_critsect_);
208 return rtp_header_extension_map_.Deregister(type);
211 uint16_t RTPSender::RtpHeaderExtensionTotalLength() const {
212 CriticalSectionScoped cs(send_critsect_);
213 return rtp_header_extension_map_.GetTotalLengthInBytes();
216 int32_t RTPSender::RegisterPayload(
217 const char payload_name[RTP_PAYLOAD_NAME_SIZE],
218 const int8_t payload_number, const uint32_t frequency,
219 const uint8_t channels, const uint32_t rate) {
220 assert(payload_name);
221 CriticalSectionScoped cs(send_critsect_);
223 std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
224 payload_type_map_.find(payload_number);
226 if (payload_type_map_.end() != it) {
227 // We already use this payload type.
228 ModuleRTPUtility::Payload *payload = it->second;
231 // Check if it's the same as we already have.
232 if (ModuleRTPUtility::StringCompare(payload->name, payload_name,
233 RTP_PAYLOAD_NAME_SIZE - 1)) {
234 if (audio_configured_ && payload->audio &&
235 payload->typeSpecific.Audio.frequency == frequency &&
236 (payload->typeSpecific.Audio.rate == rate ||
237 payload->typeSpecific.Audio.rate == 0 || rate == 0)) {
238 payload->typeSpecific.Audio.rate = rate;
239 // Ensure that we update the rate if new or old is zero.
242 if (!audio_configured_ && !payload->audio) {
248 int32_t ret_val = -1;
249 ModuleRTPUtility::Payload *payload = NULL;
250 if (audio_configured_) {
251 ret_val = audio_->RegisterAudioPayload(payload_name, payload_number,
252 frequency, channels, rate, payload);
254 ret_val = video_->RegisterVideoPayload(payload_name, payload_number, rate,
258 payload_type_map_[payload_number] = payload;
263 int32_t RTPSender::DeRegisterSendPayload(
264 const int8_t payload_type) {
265 CriticalSectionScoped lock(send_critsect_);
267 std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
268 payload_type_map_.find(payload_type);
270 if (payload_type_map_.end() == it) {
273 ModuleRTPUtility::Payload *payload = it->second;
275 payload_type_map_.erase(it);
279 int8_t RTPSender::SendPayloadType() const {
280 CriticalSectionScoped cs(send_critsect_);
281 return payload_type_;
284 int RTPSender::SendPayloadFrequency() const {
285 return audio_ != NULL ? audio_->AudioFrequency() : kVideoPayloadTypeFrequency;
288 int32_t RTPSender::SetMaxPayloadLength(
289 const uint16_t max_payload_length,
290 const uint16_t packet_over_head) {
292 if (max_payload_length < 100 || max_payload_length > IP_PACKET_SIZE) {
293 WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_, "%s invalid argument",
297 CriticalSectionScoped cs(send_critsect_);
298 max_payload_length_ = max_payload_length;
299 packet_over_head_ = packet_over_head;
301 WEBRTC_TRACE(kTraceInfo, kTraceRtpRtcp, id_, "SetMaxPayloadLength to %d.",
306 uint16_t RTPSender::MaxDataPayloadLength() const {
307 if (audio_configured_) {
308 return max_payload_length_ - RTPHeaderLength();
310 return max_payload_length_ - RTPHeaderLength() // RTP overhead.
311 - video_->FECPacketOverhead() // FEC/ULP/RED overhead.
312 - ((rtx_) ? 2 : 0); // RTX overhead.
316 uint16_t RTPSender::MaxPayloadLength() const {
317 return max_payload_length_;
320 uint16_t RTPSender::PacketOverHead() const { return packet_over_head_; }
322 void RTPSender::SetRTXStatus(int mode, bool set_ssrc, uint32_t ssrc) {
323 CriticalSectionScoped cs(send_critsect_);
325 if (rtx_ != kRtxOff) {
329 ssrc_rtx_ = ssrc_db_.CreateSSRC(); // Can't be 0.
334 void RTPSender::RTXStatus(int* mode, uint32_t* ssrc,
335 int* payload_type) const {
336 CriticalSectionScoped cs(send_critsect_);
339 *payload_type = payload_type_rtx_;
343 void RTPSender::SetRtxPayloadType(int payload_type) {
344 CriticalSectionScoped cs(send_critsect_);
345 payload_type_rtx_ = payload_type;
348 int32_t RTPSender::CheckPayloadType(const int8_t payload_type,
349 RtpVideoCodecTypes *video_type) {
350 CriticalSectionScoped cs(send_critsect_);
352 if (payload_type < 0) {
353 WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_, "\tinvalid payload_type (%d)",
357 if (audio_configured_) {
358 int8_t red_pl_type = -1;
359 if (audio_->RED(red_pl_type) == 0) {
360 // We have configured RED.
361 if (red_pl_type == payload_type) {
362 // And it's a match...
367 if (payload_type_ == payload_type) {
368 if (!audio_configured_) {
369 *video_type = video_->VideoCodecType();
373 std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
374 payload_type_map_.find(payload_type);
375 if (it == payload_type_map_.end()) {
376 WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_,
377 "\tpayloadType:%d not registered", payload_type);
380 payload_type_ = payload_type;
381 ModuleRTPUtility::Payload *payload = it->second;
383 if (!payload->audio && !audio_configured_) {
384 video_->SetVideoCodecType(payload->typeSpecific.Video.videoCodecType);
385 *video_type = payload->typeSpecific.Video.videoCodecType;
386 video_->SetMaxConfiguredBitrateVideo(payload->typeSpecific.Video.maxRate);
391 int32_t RTPSender::SendOutgoingData(
392 const FrameType frame_type, const int8_t payload_type,
393 const uint32_t capture_timestamp, int64_t capture_time_ms,
394 const uint8_t *payload_data, const uint32_t payload_size,
395 const RTPFragmentationHeader *fragmentation,
396 VideoCodecInformation *codec_info, const RTPVideoTypeHeader *rtp_type_hdr) {
398 // Drop this packet if we're not sending media packets.
399 CriticalSectionScoped cs(send_critsect_);
400 if (!sending_media_) {
404 RtpVideoCodecTypes video_type = kRtpVideoGeneric;
405 if (CheckPayloadType(payload_type, &video_type) != 0) {
406 WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_,
407 "%s invalid argument failed to find payload_type:%d",
408 __FUNCTION__, payload_type);
413 if (audio_configured_) {
414 TRACE_EVENT_ASYNC_STEP1("webrtc", "Audio", capture_timestamp,
415 "Send", "type", FrameTypeToString(frame_type));
416 assert(frame_type == kAudioFrameSpeech || frame_type == kAudioFrameCN ||
417 frame_type == kFrameEmpty);
419 ret_val = audio_->SendAudio(frame_type, payload_type, capture_timestamp,
420 payload_data, payload_size, fragmentation);
422 TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", capture_time_ms,
423 "Send", "type", FrameTypeToString(frame_type));
424 assert(frame_type != kAudioFrameSpeech && frame_type != kAudioFrameCN);
426 if (frame_type == kFrameEmpty) {
427 if (paced_sender_->Enabled()) {
428 // Padding is driven by the pacer and not by the encoder.
431 return SendPaddingAccordingToBitrate(payload_type, capture_timestamp,
432 capture_time_ms) ? 0 : -1;
434 ret_val = video_->SendVideo(video_type, frame_type, payload_type,
435 capture_timestamp, capture_time_ms,
436 payload_data, payload_size,
437 fragmentation, codec_info,
442 CriticalSectionScoped cs(statistics_crit_.get());
443 uint32_t frame_count = ++frame_counts_[frame_type];
444 if (frame_count_observer_) {
445 frame_count_observer_->FrameCountUpdated(frame_type,
453 int RTPSender::SendRedundantPayloads(int payload_type, int bytes_to_send) {
454 if (!(rtx_ & kRtxRedundantPayloads))
456 uint8_t buffer[IP_PACKET_SIZE];
457 int bytes_left = bytes_to_send;
458 while (bytes_left > 0) {
459 uint16_t length = bytes_left;
460 int64_t capture_time_ms;
461 if (!packet_history_.GetBestFittingPacket(buffer, &length,
465 if (!PrepareAndSendPacket(buffer, length, capture_time_ms, true, false))
467 ModuleRTPUtility::RTPHeaderParser rtp_parser(buffer, length);
468 RTPHeader rtp_header;
469 rtp_parser.Parse(rtp_header);
470 bytes_left -= length - rtp_header.headerLength;
472 return bytes_to_send - bytes_left;
475 bool RTPSender::SendPaddingAccordingToBitrate(
476 int8_t payload_type, uint32_t capture_timestamp,
477 int64_t capture_time_ms) {
478 // Current bitrate since last estimate(1 second) averaged with the
479 // estimate since then, to get the most up to date bitrate.
480 uint32_t current_bitrate = bitrate_sent_.BitrateNow();
481 uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
482 int bitrate_diff = target_bitrate_kbps * 1000 - current_bitrate;
483 if (bitrate_diff <= 0) {
487 if (current_bitrate == 0) {
488 // Start up phase. Send one 33.3 ms batch to start with.
489 bytes = (bitrate_diff / 8) / 30;
491 bytes = (bitrate_diff / 8);
492 // Cap at 200 ms of target send data.
493 int bytes_cap = target_bitrate_kbps * 25; // 1000 / 8 / 5.
494 if (bytes > bytes_cap) {
500 CriticalSectionScoped cs(send_critsect_);
501 // Add the random RTP timestamp offset and store the capture time for
502 // later calculation of the send time offset.
503 timestamp = start_time_stamp_ + capture_timestamp;
504 timestamp_ = timestamp;
505 capture_time_ms_ = capture_time_ms;
506 last_timestamp_time_ms_ = clock_->TimeInMilliseconds();
508 int bytes_sent = SendPadData(payload_type, timestamp, capture_time_ms,
509 bytes, kDontRetransmit, false, false);
510 // We did not manage to send all bytes. Comparing with 31 due to modulus 32.
511 return bytes - bytes_sent < 31;
514 int RTPSender::BuildPaddingPacket(uint8_t* packet, int header_length,
516 int padding_bytes_in_packet = kMaxPaddingLength;
517 if (bytes < kMaxPaddingLength) {
518 padding_bytes_in_packet = bytes;
520 packet[0] |= 0x20; // Set padding bit.
522 reinterpret_cast<int32_t *>(&(packet[header_length]));
524 // Fill data buffer with random data.
525 for (int j = 0; j < (padding_bytes_in_packet >> 2); ++j) {
526 data[j] = rand(); // NOLINT
528 // Set number of padding bytes in the last byte of the packet.
529 packet[header_length + padding_bytes_in_packet - 1] = padding_bytes_in_packet;
530 return padding_bytes_in_packet;
533 int RTPSender::SendPadData(int payload_type, uint32_t timestamp,
534 int64_t capture_time_ms, int32_t bytes,
535 StorageType store, bool force_full_size_packets,
536 bool only_pad_after_markerbit) {
537 // Drop this packet if we're not sending media packets.
538 if (!SendingMedia()) {
541 int padding_bytes_in_packet = 0;
543 for (; bytes > 0; bytes -= padding_bytes_in_packet) {
544 // Always send full padding packets.
545 if (force_full_size_packets && bytes < kMaxPaddingLength)
546 bytes = kMaxPaddingLength;
547 if (bytes < kMaxPaddingLength) {
548 if (force_full_size_packets) {
549 bytes = kMaxPaddingLength;
551 // Round to the nearest multiple of 32.
552 bytes = (bytes + 16) & 0xffe0;
556 // Sanity don't send empty packets.
560 uint16_t sequence_number;
562 CriticalSectionScoped cs(send_critsect_);
563 // Only send padding packets following the last packet of a frame,
564 // indicated by the marker bit.
565 if (only_pad_after_markerbit && !last_packet_marker_bit_)
567 if (rtx_ == kRtxOff) {
569 sequence_number = sequence_number_;
573 sequence_number = sequence_number_rtx_;
574 ++sequence_number_rtx_;
577 uint8_t padding_packet[IP_PACKET_SIZE];
578 int header_length = CreateRTPHeader(padding_packet, payload_type, ssrc,
579 false, timestamp, sequence_number, NULL,
581 padding_bytes_in_packet = BuildPaddingPacket(padding_packet, header_length,
583 if (0 > SendToNetwork(padding_packet, padding_bytes_in_packet,
584 header_length, capture_time_ms, store,
585 PacedSender::kLowPriority)) {
586 // Error sending the packet.
589 bytes_sent += padding_bytes_in_packet;
594 void RTPSender::SetStorePacketsStatus(const bool enable,
595 const uint16_t number_to_store) {
596 packet_history_.SetStorePacketsStatus(enable, number_to_store);
599 bool RTPSender::StorePackets() const {
600 return packet_history_.StorePackets();
603 int32_t RTPSender::ReSendPacket(uint16_t packet_id, uint32_t min_resend_time) {
604 uint16_t length = IP_PACKET_SIZE;
605 uint8_t data_buffer[IP_PACKET_SIZE];
606 int64_t capture_time_ms;
607 if (!packet_history_.GetPacketAndSetSendTime(packet_id, min_resend_time, true,
608 data_buffer, &length,
615 ModuleRTPUtility::RTPHeaderParser rtp_parser(data_buffer, length);
617 if (!rtp_parser.Parse(header)) {
619 WEBRTC_TRACE(kTraceError, kTraceRtpRtcp, id_,
620 "Failed to parse RTP header of packet to be retransmitted.");
623 if (!paced_sender_->SendPacket(PacedSender::kHighPriority,
625 header.sequenceNumber,
627 length - header.headerLength,
629 // We can't send the packet right now.
630 // We will be called when it is time.
635 return PrepareAndSendPacket(data_buffer, length, capture_time_ms,
636 (rtx_ & kRtxRetransmitted) > 0, true) ?
640 bool RTPSender::SendPacketToNetwork(const uint8_t *packet, uint32_t size) {
643 bytes_sent = transport_->SendPacket(id_, packet, size);
645 TRACE_EVENT_INSTANT2("webrtc_rtp", "RTPSender::SendPacketToNetwork",
646 "size", size, "sent", bytes_sent);
647 // TODO(pwesin): Add a separate bitrate for sent bitrate after pacer.
648 if (bytes_sent <= 0) {
649 WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
650 "Transport failed to send packet");
656 int RTPSender::SelectiveRetransmissions() const {
659 return video_->SelectiveRetransmissions();
662 int RTPSender::SetSelectiveRetransmissions(uint8_t settings) {
665 return video_->SetSelectiveRetransmissions(settings);
668 void RTPSender::OnReceivedNACK(
669 const std::list<uint16_t>& nack_sequence_numbers,
670 const uint16_t avg_rtt) {
671 TRACE_EVENT2("webrtc_rtp", "RTPSender::OnReceivedNACK",
672 "num_seqnum", nack_sequence_numbers.size(), "avg_rtt", avg_rtt);
673 const int64_t now = clock_->TimeInMilliseconds();
674 uint32_t bytes_re_sent = 0;
675 uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
677 // Enough bandwidth to send NACK?
678 if (!ProcessNACKBitRate(now)) {
679 WEBRTC_TRACE(kTraceStream,
682 "NACK bitrate reached. Skip sending NACK response. Target %d",
683 target_bitrate_kbps);
687 for (std::list<uint16_t>::const_iterator it = nack_sequence_numbers.begin();
688 it != nack_sequence_numbers.end(); ++it) {
689 const int32_t bytes_sent = ReSendPacket(*it, 5 + avg_rtt);
690 if (bytes_sent > 0) {
691 bytes_re_sent += bytes_sent;
692 } else if (bytes_sent == 0) {
693 // The packet has previously been resent.
694 // Try resending next packet in the list.
696 } else if (bytes_sent < 0) {
697 // Failed to send one Sequence number. Give up the rest in this nack.
698 WEBRTC_TRACE(kTraceWarning, kTraceRtpRtcp, id_,
699 "Failed resending RTP packet %d, Discard rest of packets",
703 // Delay bandwidth estimate (RTT * BW).
704 if (target_bitrate_kbps != 0 && avg_rtt) {
705 // kbits/s * ms = bits => bits/8 = bytes
706 uint32_t target_bytes =
707 (static_cast<uint32_t>(target_bitrate_kbps) * avg_rtt) >> 3;
708 if (bytes_re_sent > target_bytes) {
709 break; // Ignore the rest of the packets in the list.
713 if (bytes_re_sent > 0) {
714 // TODO(pwestin) consolidate these two methods.
715 UpdateNACKBitRate(bytes_re_sent, now);
716 nack_bitrate_.Update(bytes_re_sent);
720 bool RTPSender::ProcessNACKBitRate(const uint32_t now) {
722 int32_t byte_count = 0;
723 const uint32_t avg_interval = 1000;
724 uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
726 CriticalSectionScoped cs(send_critsect_);
728 if (target_bitrate_kbps == 0) {
731 for (num = 0; num < NACK_BYTECOUNT_SIZE; ++num) {
732 if ((now - nack_byte_count_times_[num]) > avg_interval) {
733 // Don't use data older than 1sec.
736 byte_count += nack_byte_count_[num];
739 int32_t time_interval = avg_interval;
740 if (num == NACK_BYTECOUNT_SIZE) {
741 // More than NACK_BYTECOUNT_SIZE nack messages has been received
742 // during the last msg_interval.
743 time_interval = now - nack_byte_count_times_[num - 1];
744 if (time_interval < 0) {
745 time_interval = avg_interval;
748 return (byte_count * 8) < (target_bitrate_kbps * time_interval);
751 void RTPSender::UpdateNACKBitRate(const uint32_t bytes,
752 const uint32_t now) {
753 CriticalSectionScoped cs(send_critsect_);
755 // Save bitrate statistics.
758 // Add padding length.
759 nack_byte_count_[0] += bytes;
761 if (nack_byte_count_times_[0] == 0) {
765 for (int i = (NACK_BYTECOUNT_SIZE - 2); i >= 0; i--) {
766 nack_byte_count_[i + 1] = nack_byte_count_[i];
767 nack_byte_count_times_[i + 1] = nack_byte_count_times_[i];
770 nack_byte_count_[0] = bytes;
771 nack_byte_count_times_[0] = now;
776 // Called from pacer when we can send the packet.
777 bool RTPSender::TimeToSendPacket(uint16_t sequence_number,
778 int64_t capture_time_ms,
779 bool retransmission) {
780 uint16_t length = IP_PACKET_SIZE;
781 uint8_t data_buffer[IP_PACKET_SIZE];
782 int64_t stored_time_ms;
784 if (!packet_history_.GetPacketAndSetSendTime(sequence_number,
790 // Packet cannot be found. Allow sending to continue.
793 if (!retransmission && capture_time_ms > 0) {
794 UpdateDelayStatistics(capture_time_ms, clock_->TimeInMilliseconds());
796 return PrepareAndSendPacket(data_buffer, length, capture_time_ms,
797 retransmission && (rtx_ & kRtxRetransmitted) > 0,
801 bool RTPSender::PrepareAndSendPacket(uint8_t* buffer,
803 int64_t capture_time_ms,
805 bool is_retransmit) {
806 uint8_t *buffer_to_send_ptr = buffer;
808 ModuleRTPUtility::RTPHeaderParser rtp_parser(buffer, length);
809 RTPHeader rtp_header;
810 rtp_parser.Parse(rtp_header);
811 TRACE_EVENT_INSTANT2("webrtc_rtp", "PrepareAndSendPacket",
812 "timestamp", rtp_header.timestamp,
813 "seqnum", rtp_header.sequenceNumber);
815 uint8_t data_buffer_rtx[IP_PACKET_SIZE];
817 BuildRtxPacket(buffer, &length, data_buffer_rtx);
818 buffer_to_send_ptr = data_buffer_rtx;
821 int64_t now_ms = clock_->TimeInMilliseconds();
822 int64_t diff_ms = now_ms - capture_time_ms;
823 bool updated_transmission_time_offset =
824 UpdateTransmissionTimeOffset(buffer_to_send_ptr, length, rtp_header,
826 bool updated_abs_send_time =
827 UpdateAbsoluteSendTime(buffer_to_send_ptr, length, rtp_header, now_ms);
828 if (updated_transmission_time_offset || updated_abs_send_time) {
829 // Update stored packet in case of receiving a re-transmission request.
830 packet_history_.ReplaceRTPHeader(buffer_to_send_ptr,
831 rtp_header.sequenceNumber,
832 rtp_header.headerLength);
835 bool ret = SendPacketToNetwork(buffer_to_send_ptr, length);
836 UpdateRtpStats(buffer_to_send_ptr, length, rtp_header, send_over_rtx,
841 void RTPSender::UpdateRtpStats(const uint8_t* buffer,
843 const RTPHeader& header,
845 bool is_retransmit) {
846 StreamDataCounters* counters;
847 // Get ssrc before taking statistics_crit_ to avoid possible deadlock.
848 uint32_t ssrc = SSRC();
850 CriticalSectionScoped lock(statistics_crit_.get());
852 counters = &rtx_rtp_stats_;
855 counters = &rtp_stats_;
858 bitrate_sent_.Update(size);
860 if (IsFecPacket(buffer, header)) {
861 ++counters->fec_packets;
865 ++counters->retransmitted_packets;
867 counters->bytes += size - (header.headerLength + header.paddingLength);
868 counters->header_bytes += header.headerLength;
869 counters->padding_bytes += header.paddingLength;
872 if (rtp_stats_callback_) {
873 rtp_stats_callback_->DataCountersUpdated(*counters, ssrc);
877 bool RTPSender::IsFecPacket(const uint8_t* buffer,
878 const RTPHeader& header) const {
885 video_->GenericFECStatus(fec_enabled, pt_red, pt_fec);
886 return fec_enabled &&
887 header.payloadType == pt_red &&
888 buffer[header.headerLength] == pt_fec;
891 int RTPSender::TimeToSendPadding(int bytes) {
893 int64_t capture_time_ms;
896 CriticalSectionScoped cs(send_critsect_);
897 if (!sending_media_) {
900 payload_type = ((rtx_ & kRtxRedundantPayloads) > 0) ? payload_type_rtx_ :
902 timestamp = timestamp_;
903 capture_time_ms = capture_time_ms_;
904 if (last_timestamp_time_ms_ > 0) {
906 (clock_->TimeInMilliseconds() - last_timestamp_time_ms_) * 90;
908 (clock_->TimeInMilliseconds() - last_timestamp_time_ms_);
911 int bytes_sent = SendRedundantPayloads(payload_type, bytes);
914 int padding_sent = SendPadData(payload_type, timestamp, capture_time_ms,
915 bytes, kDontStore, true, true);
916 bytes_sent += padding_sent;
921 // TODO(pwestin): send in the RTPHeaderParser to avoid parsing it again.
922 int32_t RTPSender::SendToNetwork(
923 uint8_t *buffer, int payload_length, int rtp_header_length,
924 int64_t capture_time_ms, StorageType storage,
925 PacedSender::Priority priority) {
926 ModuleRTPUtility::RTPHeaderParser rtp_parser(
927 buffer, payload_length + rtp_header_length);
928 RTPHeader rtp_header;
929 rtp_parser.Parse(rtp_header);
931 int64_t now_ms = clock_->TimeInMilliseconds();
933 // |capture_time_ms| <= 0 is considered invalid.
934 // TODO(holmer): This should be changed all over Video Engine so that negative
935 // time is consider invalid, while 0 is considered a valid time.
936 if (capture_time_ms > 0) {
937 UpdateTransmissionTimeOffset(buffer, payload_length + rtp_header_length,
938 rtp_header, now_ms - capture_time_ms);
941 UpdateAbsoluteSendTime(buffer, payload_length + rtp_header_length,
944 // Used for NACK and to spread out the transmission of packets.
945 if (packet_history_.PutRTPPacket(buffer, rtp_header_length + payload_length,
946 max_payload_length_, capture_time_ms,
951 if (paced_sender_ && storage != kDontStore) {
952 if (!paced_sender_->SendPacket(priority, rtp_header.ssrc,
953 rtp_header.sequenceNumber, capture_time_ms,
954 payload_length, false)) {
955 // We can't send the packet right now.
956 // We will be called when it is time.
960 if (capture_time_ms > 0) {
961 UpdateDelayStatistics(capture_time_ms, now_ms);
963 uint32_t length = payload_length + rtp_header_length;
964 if (!SendPacketToNetwork(buffer, length))
966 UpdateRtpStats(buffer, length, rtp_header, false, false);
970 void RTPSender::UpdateDelayStatistics(int64_t capture_time_ms, int64_t now_ms) {
971 CriticalSectionScoped cs(statistics_crit_.get());
972 send_delays_[now_ms] = now_ms - capture_time_ms;
973 send_delays_.erase(send_delays_.begin(),
974 send_delays_.lower_bound(now_ms - kSendSideDelayWindowMs));
977 void RTPSender::ProcessBitrate() {
978 CriticalSectionScoped cs(send_critsect_);
979 bitrate_sent_.Process();
980 nack_bitrate_.Process();
981 if (audio_configured_) {
984 video_->ProcessBitrate();
987 uint16_t RTPSender::RTPHeaderLength() const {
988 uint16_t rtp_header_length = 12;
989 if (include_csrcs_) {
990 rtp_header_length += sizeof(uint32_t) * num_csrcs_;
992 rtp_header_length += RtpHeaderExtensionTotalLength();
993 return rtp_header_length;
996 uint16_t RTPSender::IncrementSequenceNumber() {
997 CriticalSectionScoped cs(send_critsect_);
998 return sequence_number_++;
1001 void RTPSender::ResetDataCounters() {
1002 CriticalSectionScoped lock(statistics_crit_.get());
1003 rtp_stats_ = StreamDataCounters();
1004 rtx_rtp_stats_ = StreamDataCounters();
1005 if (rtp_stats_callback_) {
1006 rtp_stats_callback_->DataCountersUpdated(rtp_stats_, ssrc_);
1007 rtp_stats_callback_->DataCountersUpdated(rtx_rtp_stats_, ssrc_rtx_);
1011 uint32_t RTPSender::Packets() const {
1012 CriticalSectionScoped lock(statistics_crit_.get());
1013 return rtp_stats_.packets + rtx_rtp_stats_.packets;
1016 // Number of sent RTP bytes.
1017 uint32_t RTPSender::Bytes() const {
1018 CriticalSectionScoped lock(statistics_crit_.get());
1019 return rtp_stats_.bytes + rtx_rtp_stats_.bytes;
1022 int RTPSender::CreateRTPHeader(
1023 uint8_t* header, int8_t payload_type, uint32_t ssrc, bool marker_bit,
1024 uint32_t timestamp, uint16_t sequence_number, const uint32_t* csrcs,
1025 uint8_t num_csrcs) const {
1026 header[0] = 0x80; // version 2.
1027 header[1] = static_cast<uint8_t>(payload_type);
1029 header[1] |= kRtpMarkerBitMask; // Marker bit is set.
1031 ModuleRTPUtility::AssignUWord16ToBuffer(header + 2, sequence_number);
1032 ModuleRTPUtility::AssignUWord32ToBuffer(header + 4, timestamp);
1033 ModuleRTPUtility::AssignUWord32ToBuffer(header + 8, ssrc);
1034 int32_t rtp_header_length = 12;
1036 // Add the CSRCs if any.
1037 if (num_csrcs > 0) {
1038 if (num_csrcs > kRtpCsrcSize) {
1043 uint8_t *ptr = &header[rtp_header_length];
1044 for (int i = 0; i < num_csrcs; ++i) {
1045 ModuleRTPUtility::AssignUWord32ToBuffer(ptr, csrcs[i]);
1048 header[0] = (header[0] & 0xf0) | num_csrcs;
1050 // Update length of header.
1051 rtp_header_length += sizeof(uint32_t) * num_csrcs;
1054 uint16_t len = BuildRTPHeaderExtension(header + rtp_header_length);
1056 header[0] |= 0x10; // Set extension bit.
1057 rtp_header_length += len;
1059 return rtp_header_length;
1062 int32_t RTPSender::BuildRTPheader(
1063 uint8_t *data_buffer, const int8_t payload_type,
1064 const bool marker_bit, const uint32_t capture_timestamp,
1065 int64_t capture_time_ms, const bool time_stamp_provided,
1066 const bool inc_sequence_number) {
1067 assert(payload_type >= 0);
1068 CriticalSectionScoped cs(send_critsect_);
1070 if (time_stamp_provided) {
1071 timestamp_ = start_time_stamp_ + capture_timestamp;
1073 // Make a unique time stamp.
1074 // We can't inc by the actual time, since then we increase the risk of back
1078 last_timestamp_time_ms_ = clock_->TimeInMilliseconds();
1079 uint32_t sequence_number = sequence_number_++;
1080 capture_time_ms_ = capture_time_ms;
1081 last_packet_marker_bit_ = marker_bit;
1082 int csrcs_length = 0;
1084 csrcs_length = num_csrcs_;
1085 return CreateRTPHeader(data_buffer, payload_type, ssrc_, marker_bit,
1086 timestamp_, sequence_number, csrcs_, csrcs_length);
1089 uint16_t RTPSender::BuildRTPHeaderExtension(uint8_t* data_buffer) const {
1090 if (rtp_header_extension_map_.Size() <= 0) {
1093 // RTP header extension, RFC 3550.
1095 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1096 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1097 // | defined by profile | length |
1098 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1099 // | header extension |
1102 const uint32_t kPosLength = 2;
1103 const uint32_t kHeaderLength = kRtpOneByteHeaderLength;
1105 // Add extension ID (0xBEDE).
1106 ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer,
1107 kRtpOneByteHeaderExtensionId);
1110 uint16_t total_block_length = 0;
1112 RTPExtensionType type = rtp_header_extension_map_.First();
1113 while (type != kRtpExtensionNone) {
1114 uint8_t block_length = 0;
1116 case kRtpExtensionTransmissionTimeOffset:
1117 block_length = BuildTransmissionTimeOffsetExtension(
1118 data_buffer + kHeaderLength + total_block_length);
1120 case kRtpExtensionAudioLevel:
1121 block_length = BuildAudioLevelExtension(
1122 data_buffer + kHeaderLength + total_block_length);
1124 case kRtpExtensionAbsoluteSendTime:
1125 block_length = BuildAbsoluteSendTimeExtension(
1126 data_buffer + kHeaderLength + total_block_length);
1131 total_block_length += block_length;
1132 type = rtp_header_extension_map_.Next(type);
1134 if (total_block_length == 0) {
1135 // No extension added.
1138 // Set header length (in number of Word32, header excluded).
1139 assert(total_block_length % 4 == 0);
1140 ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer + kPosLength,
1141 total_block_length / 4);
1142 // Total added length.
1143 return kHeaderLength + total_block_length;
1146 uint8_t RTPSender::BuildTransmissionTimeOffsetExtension(
1147 uint8_t* data_buffer) const {
1148 // From RFC 5450: Transmission Time Offsets in RTP Streams.
1150 // The transmission time is signaled to the receiver in-band using the
1151 // general mechanism for RTP header extensions [RFC5285]. The payload
1152 // of this extension (the transmitted value) is a 24-bit signed integer.
1153 // When added to the RTP timestamp of the packet, it represents the
1154 // "effective" RTP transmission time of the packet, on the RTP
1157 // The form of the transmission offset extension block:
1160 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1161 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1162 // | ID | len=2 | transmission offset |
1163 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1165 // Get id defined by user.
1167 if (rtp_header_extension_map_.GetId(kRtpExtensionTransmissionTimeOffset,
1173 const uint8_t len = 2;
1174 data_buffer[pos++] = (id << 4) + len;
1175 ModuleRTPUtility::AssignUWord24ToBuffer(data_buffer + pos,
1176 transmission_time_offset_);
1178 assert(pos == kTransmissionTimeOffsetLength);
1179 return kTransmissionTimeOffsetLength;
1182 uint8_t RTPSender::BuildAudioLevelExtension(uint8_t* data_buffer) const {
1183 // An RTP Header Extension for Client-to-Mixer Audio Level Indication
1185 // https://datatracker.ietf.org/doc/draft-lennox-avt-rtp-audio-level-exthdr/
1187 // The form of the audio level extension block:
1190 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1191 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1192 // | ID | len=0 |V| level | 0x00 | 0x00 |
1193 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1195 // Note that we always include 2 pad bytes, which will result in legal and
1196 // correctly parsed RTP, but may be a bit wasteful if more short extensions
1197 // are implemented. Right now the pad bytes would anyway be required at end
1198 // of the extension block, so it makes no difference.
1200 // Get id defined by user.
1202 if (rtp_header_extension_map_.GetId(kRtpExtensionAudioLevel, &id) != 0) {
1207 const uint8_t len = 0;
1208 data_buffer[pos++] = (id << 4) + len;
1209 data_buffer[pos++] = (1 << 7) + 0; // Voice, 0 dBov.
1210 data_buffer[pos++] = 0; // Padding.
1211 data_buffer[pos++] = 0; // Padding.
1212 // kAudioLevelLength is including pad bytes.
1213 assert(pos == kAudioLevelLength);
1214 return kAudioLevelLength;
1217 uint8_t RTPSender::BuildAbsoluteSendTimeExtension(uint8_t* data_buffer) const {
1218 // Absolute send time in RTP streams.
1220 // The absolute send time is signaled to the receiver in-band using the
1221 // general mechanism for RTP header extensions [RFC5285]. The payload
1222 // of this extension (the transmitted value) is a 24-bit unsigned integer
1223 // containing the sender's current time in seconds as a fixed point number
1224 // with 18 bits fractional part.
1226 // The form of the absolute send time extension block:
1229 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
1230 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1231 // | ID | len=2 | absolute send time |
1232 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1234 // Get id defined by user.
1236 if (rtp_header_extension_map_.GetId(kRtpExtensionAbsoluteSendTime,
1242 const uint8_t len = 2;
1243 data_buffer[pos++] = (id << 4) + len;
1244 ModuleRTPUtility::AssignUWord24ToBuffer(data_buffer + pos,
1245 absolute_send_time_);
1247 assert(pos == kAbsoluteSendTimeLength);
1248 return kAbsoluteSendTimeLength;
1251 bool RTPSender::UpdateTransmissionTimeOffset(
1252 uint8_t *rtp_packet, const uint16_t rtp_packet_length,
1253 const RTPHeader &rtp_header, const int64_t time_diff_ms) const {
1254 CriticalSectionScoped cs(send_critsect_);
1256 // Get length until start of header extension block.
1257 int extension_block_pos =
1258 rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1259 kRtpExtensionTransmissionTimeOffset);
1260 if (extension_block_pos < 0) {
1261 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1262 "Failed to update transmission time offset, not registered.");
1265 int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1266 if (rtp_packet_length < block_pos + kTransmissionTimeOffsetLength ||
1267 rtp_header.headerLength <
1268 block_pos + kTransmissionTimeOffsetLength) {
1269 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1270 "Failed to update transmission time offset, invalid length.");
1273 // Verify that header contains extension.
1274 if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1275 (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1277 kTraceStream, kTraceRtpRtcp, id_,
1278 "Failed to update transmission time offset, hdr extension not found.");
1283 if (rtp_header_extension_map_.GetId(kRtpExtensionTransmissionTimeOffset,
1285 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1286 "Failed to update transmission time offset, no id.");
1289 // Verify first byte in block.
1290 const uint8_t first_block_byte = (id << 4) + 2;
1291 if (rtp_packet[block_pos] != first_block_byte) {
1292 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1293 "Failed to update transmission time offset.");
1296 // Update transmission offset field (converting to a 90 kHz timestamp).
1297 ModuleRTPUtility::AssignUWord24ToBuffer(rtp_packet + block_pos + 1,
1298 time_diff_ms * 90); // RTP timestamp.
1302 bool RTPSender::UpdateAudioLevel(uint8_t *rtp_packet,
1303 const uint16_t rtp_packet_length,
1304 const RTPHeader &rtp_header,
1305 const bool is_voiced,
1306 const uint8_t dBov) const {
1307 CriticalSectionScoped cs(send_critsect_);
1309 // Get length until start of header extension block.
1310 int extension_block_pos =
1311 rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1312 kRtpExtensionAudioLevel);
1313 if (extension_block_pos < 0) {
1314 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1315 "Failed to update audio level, not registered.");
1318 int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1319 if (rtp_packet_length < block_pos + kAudioLevelLength ||
1320 rtp_header.headerLength < block_pos + kAudioLevelLength) {
1321 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1322 "Failed to update audio level, invalid length.");
1325 // Verify that header contains extension.
1326 if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1327 (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1329 kTraceStream, kTraceRtpRtcp, id_,
1330 "Failed to update audio level, hdr extension not found.");
1335 if (rtp_header_extension_map_.GetId(kRtpExtensionAudioLevel, &id) != 0) {
1336 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1337 "Failed to update audio level, no id.");
1340 // Verify first byte in block.
1341 const uint8_t first_block_byte = (id << 4) + 0;
1342 if (rtp_packet[block_pos] != first_block_byte) {
1343 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1344 "Failed to update audio level.");
1347 rtp_packet[block_pos + 1] = (is_voiced ? 0x80 : 0x00) + (dBov & 0x7f);
1351 bool RTPSender::UpdateAbsoluteSendTime(
1352 uint8_t *rtp_packet, const uint16_t rtp_packet_length,
1353 const RTPHeader &rtp_header, const int64_t now_ms) const {
1354 CriticalSectionScoped cs(send_critsect_);
1356 // Get length until start of header extension block.
1357 int extension_block_pos =
1358 rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1359 kRtpExtensionAbsoluteSendTime);
1360 if (extension_block_pos < 0) {
1361 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1362 "Failed to update absolute send time, not registered.");
1365 int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1366 if (rtp_packet_length < block_pos + kAbsoluteSendTimeLength ||
1367 rtp_header.headerLength < block_pos + kAbsoluteSendTimeLength) {
1368 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1369 "Failed to update absolute send time, invalid length.");
1372 // Verify that header contains extension.
1373 if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1374 (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1376 kTraceStream, kTraceRtpRtcp, id_,
1377 "Failed to update absolute send time, hdr extension not found.");
1382 if (rtp_header_extension_map_.GetId(kRtpExtensionAbsoluteSendTime,
1384 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1385 "Failed to update absolute send time, no id.");
1388 // Verify first byte in block.
1389 const uint8_t first_block_byte = (id << 4) + 2;
1390 if (rtp_packet[block_pos] != first_block_byte) {
1391 WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, id_,
1392 "Failed to update absolute send time.");
1395 // Update absolute send time field (convert ms to 24-bit unsigned with 18 bit
1396 // fractional part).
1397 ModuleRTPUtility::AssignUWord24ToBuffer(rtp_packet + block_pos + 1,
1398 ((now_ms << 18) / 1000) & 0x00ffffff);
1402 void RTPSender::SetSendingStatus(bool enabled) {
1404 uint32_t frequency_hz = SendPayloadFrequency();
1405 uint32_t RTPtime = ModuleRTPUtility::GetCurrentRTP(clock_, frequency_hz);
1407 // Will be ignored if it's already configured via API.
1408 SetStartTimestamp(RTPtime, false);
1410 if (!ssrc_forced_) {
1411 // Generate a new SSRC.
1412 ssrc_db_.ReturnSSRC(ssrc_);
1413 ssrc_ = ssrc_db_.CreateSSRC(); // Can't be 0.
1415 // Don't initialize seq number if SSRC passed externally.
1416 if (!sequence_number_forced_ && !ssrc_forced_) {
1417 // Generate a new sequence number.
1419 rand() / (RAND_MAX / MAX_INIT_RTP_SEQ_NUMBER); // NOLINT
1424 void RTPSender::SetSendingMediaStatus(const bool enabled) {
1425 CriticalSectionScoped cs(send_critsect_);
1426 sending_media_ = enabled;
1429 bool RTPSender::SendingMedia() const {
1430 CriticalSectionScoped cs(send_critsect_);
1431 return sending_media_;
1434 uint32_t RTPSender::Timestamp() const {
1435 CriticalSectionScoped cs(send_critsect_);
1439 void RTPSender::SetStartTimestamp(uint32_t timestamp, bool force) {
1440 CriticalSectionScoped cs(send_critsect_);
1442 start_time_stamp_forced_ = force;
1443 start_time_stamp_ = timestamp;
1445 if (!start_time_stamp_forced_) {
1446 start_time_stamp_ = timestamp;
1451 uint32_t RTPSender::StartTimestamp() const {
1452 CriticalSectionScoped cs(send_critsect_);
1453 return start_time_stamp_;
1456 uint32_t RTPSender::GenerateNewSSRC() {
1457 // If configured via API, return 0.
1458 CriticalSectionScoped cs(send_critsect_);
1463 ssrc_ = ssrc_db_.CreateSSRC(); // Can't be 0.
1467 void RTPSender::SetSSRC(uint32_t ssrc) {
1468 // This is configured via the API.
1469 CriticalSectionScoped cs(send_critsect_);
1471 if (ssrc_ == ssrc && ssrc_forced_) {
1472 return; // Since it's same ssrc, don't reset anything.
1474 ssrc_forced_ = true;
1475 ssrc_db_.ReturnSSRC(ssrc_);
1476 ssrc_db_.RegisterSSRC(ssrc);
1478 if (!sequence_number_forced_) {
1480 rand() / (RAND_MAX / MAX_INIT_RTP_SEQ_NUMBER); // NOLINT
1484 uint32_t RTPSender::SSRC() const {
1485 CriticalSectionScoped cs(send_critsect_);
1489 void RTPSender::SetCSRCStatus(const bool include) {
1490 include_csrcs_ = include;
1493 void RTPSender::SetCSRCs(const uint32_t arr_of_csrc[kRtpCsrcSize],
1494 const uint8_t arr_length) {
1495 assert(arr_length <= kRtpCsrcSize);
1496 CriticalSectionScoped cs(send_critsect_);
1498 for (int i = 0; i < arr_length; i++) {
1499 csrcs_[i] = arr_of_csrc[i];
1501 num_csrcs_ = arr_length;
1504 int32_t RTPSender::CSRCs(uint32_t arr_of_csrc[kRtpCsrcSize]) const {
1505 assert(arr_of_csrc);
1506 CriticalSectionScoped cs(send_critsect_);
1507 for (int i = 0; i < num_csrcs_ && i < kRtpCsrcSize; i++) {
1508 arr_of_csrc[i] = csrcs_[i];
1513 void RTPSender::SetSequenceNumber(uint16_t seq) {
1514 CriticalSectionScoped cs(send_critsect_);
1515 sequence_number_forced_ = true;
1516 sequence_number_ = seq;
1519 uint16_t RTPSender::SequenceNumber() const {
1520 CriticalSectionScoped cs(send_critsect_);
1521 return sequence_number_;
1525 int32_t RTPSender::SendTelephoneEvent(const uint8_t key,
1526 const uint16_t time_ms,
1527 const uint8_t level) {
1528 if (!audio_configured_) {
1531 return audio_->SendTelephoneEvent(key, time_ms, level);
1534 bool RTPSender::SendTelephoneEventActive(int8_t *telephone_event) const {
1535 if (!audio_configured_) {
1538 return audio_->SendTelephoneEventActive(*telephone_event);
1541 int32_t RTPSender::SetAudioPacketSize(
1542 const uint16_t packet_size_samples) {
1543 if (!audio_configured_) {
1546 return audio_->SetAudioPacketSize(packet_size_samples);
1549 int32_t RTPSender::SetAudioLevel(const uint8_t level_d_bov) {
1550 return audio_->SetAudioLevel(level_d_bov);
1553 int32_t RTPSender::SetRED(const int8_t payload_type) {
1554 if (!audio_configured_) {
1557 return audio_->SetRED(payload_type);
1560 int32_t RTPSender::RED(int8_t *payload_type) const {
1561 if (!audio_configured_) {
1564 return audio_->RED(*payload_type);
1568 VideoCodecInformation *RTPSender::CodecInformationVideo() {
1569 if (audio_configured_) {
1572 return video_->CodecInformationVideo();
1575 RtpVideoCodecTypes RTPSender::VideoCodecType() const {
1576 assert(!audio_configured_ && "Sender is an audio stream!");
1577 return video_->VideoCodecType();
1580 uint32_t RTPSender::MaxConfiguredBitrateVideo() const {
1581 if (audio_configured_) {
1584 return video_->MaxConfiguredBitrateVideo();
1587 int32_t RTPSender::SendRTPIntraRequest() {
1588 if (audio_configured_) {
1591 return video_->SendRTPIntraRequest();
1594 int32_t RTPSender::SetGenericFECStatus(
1595 const bool enable, const uint8_t payload_type_red,
1596 const uint8_t payload_type_fec) {
1597 if (audio_configured_) {
1600 return video_->SetGenericFECStatus(enable, payload_type_red,
1604 int32_t RTPSender::GenericFECStatus(
1605 bool *enable, uint8_t *payload_type_red,
1606 uint8_t *payload_type_fec) const {
1607 if (audio_configured_) {
1610 return video_->GenericFECStatus(
1611 *enable, *payload_type_red, *payload_type_fec);
1614 int32_t RTPSender::SetFecParameters(
1615 const FecProtectionParams *delta_params,
1616 const FecProtectionParams *key_params) {
1617 if (audio_configured_) {
1620 return video_->SetFecParameters(delta_params, key_params);
1623 void RTPSender::BuildRtxPacket(uint8_t* buffer, uint16_t* length,
1624 uint8_t* buffer_rtx) {
1625 CriticalSectionScoped cs(send_critsect_);
1626 uint8_t* data_buffer_rtx = buffer_rtx;
1628 ModuleRTPUtility::RTPHeaderParser rtp_parser(
1629 reinterpret_cast<const uint8_t *>(buffer), *length);
1631 RTPHeader rtp_header;
1632 rtp_parser.Parse(rtp_header);
1634 // Add original RTP header.
1635 memcpy(data_buffer_rtx, buffer, rtp_header.headerLength);
1637 // Replace payload type, if a specific type is set for RTX.
1638 if (payload_type_rtx_ != -1) {
1639 data_buffer_rtx[1] = static_cast<uint8_t>(payload_type_rtx_);
1640 if (rtp_header.markerBit)
1641 data_buffer_rtx[1] |= kRtpMarkerBitMask;
1644 // Replace sequence number.
1645 uint8_t *ptr = data_buffer_rtx + 2;
1646 ModuleRTPUtility::AssignUWord16ToBuffer(ptr, sequence_number_rtx_++);
1650 ModuleRTPUtility::AssignUWord32ToBuffer(ptr, ssrc_rtx_);
1652 // Add OSN (original sequence number).
1653 ptr = data_buffer_rtx + rtp_header.headerLength;
1654 ModuleRTPUtility::AssignUWord16ToBuffer(ptr, rtp_header.sequenceNumber);
1657 // Add original payload data.
1658 memcpy(ptr, buffer + rtp_header.headerLength,
1659 *length - rtp_header.headerLength);
1663 void RTPSender::RegisterFrameCountObserver(FrameCountObserver* observer) {
1664 CriticalSectionScoped cs(statistics_crit_.get());
1665 if (observer != NULL)
1666 assert(frame_count_observer_ == NULL);
1667 frame_count_observer_ = observer;
1670 FrameCountObserver* RTPSender::GetFrameCountObserver() const {
1671 CriticalSectionScoped cs(statistics_crit_.get());
1672 return frame_count_observer_;
1675 void RTPSender::RegisterRtpStatisticsCallback(
1676 StreamDataCountersCallback* callback) {
1677 CriticalSectionScoped cs(statistics_crit_.get());
1678 if (callback != NULL)
1679 assert(rtp_stats_callback_ == NULL);
1680 rtp_stats_callback_ = callback;
1683 StreamDataCountersCallback* RTPSender::GetRtpStatisticsCallback() const {
1684 CriticalSectionScoped cs(statistics_crit_.get());
1685 return rtp_stats_callback_;
1688 void RTPSender::RegisterBitrateObserver(BitrateStatisticsObserver* observer) {
1689 CriticalSectionScoped cs(statistics_crit_.get());
1690 if (observer != NULL)
1691 assert(bitrate_callback_ == NULL);
1692 bitrate_callback_ = observer;
1695 BitrateStatisticsObserver* RTPSender::GetBitrateObserver() const {
1696 CriticalSectionScoped cs(statistics_crit_.get());
1697 return bitrate_callback_;
1700 uint32_t RTPSender::BitrateSent() const { return bitrate_sent_.BitrateLast(); }
1702 void RTPSender::BitrateUpdated(const BitrateStatistics& stats) {
1703 CriticalSectionScoped cs(statistics_crit_.get());
1704 if (bitrate_callback_) {
1705 bitrate_callback_->Notify(stats, ssrc_);
1709 void RTPSender::SetTargetBitrateKbps(uint16_t bitrate_kbps) {
1710 CriticalSectionScoped cs(target_bitrate_critsect_.get());
1711 target_bitrate_kbps_ = bitrate_kbps;
1714 uint16_t RTPSender::GetTargetBitrateKbps() {
1715 CriticalSectionScoped cs(target_bitrate_critsect_.get());
1716 return target_bitrate_kbps_;
1718 } // namespace webrtc