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/logging.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(clock_, this);
112 RTPSender::~RTPSender() {
113 if (remote_ssrc_ != 0) {
114 ssrc_db_.ReturnSSRC(remote_ssrc_);
116 ssrc_db_.ReturnSSRC(ssrc_);
118 SSRCDatabase::ReturnSSRCDatabase();
119 delete send_critsect_;
120 while (!payload_type_map_.empty()) {
121 std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
122 payload_type_map_.begin();
124 payload_type_map_.erase(it);
130 void RTPSender::SetTargetSendBitrate(const uint32_t bits) {
131 SetTargetBitrateKbps(static_cast<uint16_t>(bits / 1000));
134 uint16_t RTPSender::ActualSendBitrateKbit() const {
135 return (uint16_t)(bitrate_sent_.BitrateNow() / 1000);
138 uint32_t RTPSender::VideoBitrateSent() const {
140 return video_->VideoBitrateSent();
145 uint32_t RTPSender::FecOverheadRate() const {
147 return video_->FecOverheadRate();
152 uint32_t RTPSender::NackOverheadRate() const {
153 return nack_bitrate_.BitrateLast();
156 bool RTPSender::GetSendSideDelay(int* avg_send_delay_ms,
157 int* max_send_delay_ms) const {
160 CriticalSectionScoped cs(statistics_crit_.get());
161 SendDelayMap::const_iterator it = send_delays_.upper_bound(
162 clock_->TimeInMilliseconds() - kSendSideDelayWindowMs);
163 if (it == send_delays_.end())
166 for (; it != send_delays_.end(); ++it) {
167 *max_send_delay_ms = std::max(*max_send_delay_ms, it->second);
168 *avg_send_delay_ms += it->second;
171 *avg_send_delay_ms = (*avg_send_delay_ms + num_delays / 2) / num_delays;
175 int32_t RTPSender::SetTransmissionTimeOffset(
176 const int32_t transmission_time_offset) {
177 if (transmission_time_offset > (0x800000 - 1) ||
178 transmission_time_offset < -(0x800000 - 1)) { // Word24.
181 CriticalSectionScoped cs(send_critsect_);
182 transmission_time_offset_ = transmission_time_offset;
186 int32_t RTPSender::SetAbsoluteSendTime(
187 const uint32_t absolute_send_time) {
188 if (absolute_send_time > 0xffffff) { // UWord24.
191 CriticalSectionScoped cs(send_critsect_);
192 absolute_send_time_ = absolute_send_time;
196 int32_t RTPSender::RegisterRtpHeaderExtension(const RTPExtensionType type,
198 CriticalSectionScoped cs(send_critsect_);
199 return rtp_header_extension_map_.Register(type, id);
202 int32_t RTPSender::DeregisterRtpHeaderExtension(
203 const RTPExtensionType type) {
204 CriticalSectionScoped cs(send_critsect_);
205 return rtp_header_extension_map_.Deregister(type);
208 uint16_t RTPSender::RtpHeaderExtensionTotalLength() const {
209 CriticalSectionScoped cs(send_critsect_);
210 return rtp_header_extension_map_.GetTotalLengthInBytes();
213 int32_t RTPSender::RegisterPayload(
214 const char payload_name[RTP_PAYLOAD_NAME_SIZE],
215 const int8_t payload_number, const uint32_t frequency,
216 const uint8_t channels, const uint32_t rate) {
217 assert(payload_name);
218 CriticalSectionScoped cs(send_critsect_);
220 std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
221 payload_type_map_.find(payload_number);
223 if (payload_type_map_.end() != it) {
224 // We already use this payload type.
225 ModuleRTPUtility::Payload *payload = it->second;
228 // Check if it's the same as we already have.
229 if (ModuleRTPUtility::StringCompare(payload->name, payload_name,
230 RTP_PAYLOAD_NAME_SIZE - 1)) {
231 if (audio_configured_ && payload->audio &&
232 payload->typeSpecific.Audio.frequency == frequency &&
233 (payload->typeSpecific.Audio.rate == rate ||
234 payload->typeSpecific.Audio.rate == 0 || rate == 0)) {
235 payload->typeSpecific.Audio.rate = rate;
236 // Ensure that we update the rate if new or old is zero.
239 if (!audio_configured_ && !payload->audio) {
245 int32_t ret_val = -1;
246 ModuleRTPUtility::Payload *payload = NULL;
247 if (audio_configured_) {
248 ret_val = audio_->RegisterAudioPayload(payload_name, payload_number,
249 frequency, channels, rate, payload);
251 ret_val = video_->RegisterVideoPayload(payload_name, payload_number, rate,
255 payload_type_map_[payload_number] = payload;
260 int32_t RTPSender::DeRegisterSendPayload(
261 const int8_t payload_type) {
262 CriticalSectionScoped lock(send_critsect_);
264 std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
265 payload_type_map_.find(payload_type);
267 if (payload_type_map_.end() == it) {
270 ModuleRTPUtility::Payload *payload = it->second;
272 payload_type_map_.erase(it);
276 int8_t RTPSender::SendPayloadType() const {
277 CriticalSectionScoped cs(send_critsect_);
278 return payload_type_;
281 int RTPSender::SendPayloadFrequency() const {
282 return audio_ != NULL ? audio_->AudioFrequency() : kVideoPayloadTypeFrequency;
285 int32_t RTPSender::SetMaxPayloadLength(
286 const uint16_t max_payload_length,
287 const uint16_t packet_over_head) {
289 if (max_payload_length < 100 || max_payload_length > IP_PACKET_SIZE) {
290 LOG(LS_ERROR) << "Invalid max payload length: " << max_payload_length;
293 CriticalSectionScoped cs(send_critsect_);
294 max_payload_length_ = max_payload_length;
295 packet_over_head_ = packet_over_head;
299 uint16_t RTPSender::MaxDataPayloadLength() const {
300 if (audio_configured_) {
301 return max_payload_length_ - RTPHeaderLength();
303 return max_payload_length_ - RTPHeaderLength() // RTP overhead.
304 - video_->FECPacketOverhead() // FEC/ULP/RED overhead.
305 - ((rtx_) ? 2 : 0); // RTX overhead.
309 uint16_t RTPSender::MaxPayloadLength() const {
310 return max_payload_length_;
313 uint16_t RTPSender::PacketOverHead() const { return packet_over_head_; }
315 void RTPSender::SetRTXStatus(int mode, bool set_ssrc, uint32_t ssrc) {
316 CriticalSectionScoped cs(send_critsect_);
318 if (rtx_ != kRtxOff) {
322 ssrc_rtx_ = ssrc_db_.CreateSSRC(); // Can't be 0.
327 void RTPSender::RTXStatus(int* mode, uint32_t* ssrc,
328 int* payload_type) const {
329 CriticalSectionScoped cs(send_critsect_);
332 *payload_type = payload_type_rtx_;
336 void RTPSender::SetRtxPayloadType(int payload_type) {
337 CriticalSectionScoped cs(send_critsect_);
338 payload_type_rtx_ = payload_type;
341 int32_t RTPSender::CheckPayloadType(const int8_t payload_type,
342 RtpVideoCodecTypes *video_type) {
343 CriticalSectionScoped cs(send_critsect_);
345 if (payload_type < 0) {
346 LOG(LS_ERROR) << "Invalid payload_type " << payload_type;
349 if (audio_configured_) {
350 int8_t red_pl_type = -1;
351 if (audio_->RED(red_pl_type) == 0) {
352 // We have configured RED.
353 if (red_pl_type == payload_type) {
354 // And it's a match...
359 if (payload_type_ == payload_type) {
360 if (!audio_configured_) {
361 *video_type = video_->VideoCodecType();
365 std::map<int8_t, ModuleRTPUtility::Payload *>::iterator it =
366 payload_type_map_.find(payload_type);
367 if (it == payload_type_map_.end()) {
368 LOG(LS_WARNING) << "Payload type " << payload_type << " not registered.";
371 payload_type_ = payload_type;
372 ModuleRTPUtility::Payload *payload = it->second;
374 if (!payload->audio && !audio_configured_) {
375 video_->SetVideoCodecType(payload->typeSpecific.Video.videoCodecType);
376 *video_type = payload->typeSpecific.Video.videoCodecType;
377 video_->SetMaxConfiguredBitrateVideo(payload->typeSpecific.Video.maxRate);
382 int32_t RTPSender::SendOutgoingData(
383 const FrameType frame_type, const int8_t payload_type,
384 const uint32_t capture_timestamp, int64_t capture_time_ms,
385 const uint8_t *payload_data, const uint32_t payload_size,
386 const RTPFragmentationHeader *fragmentation,
387 VideoCodecInformation *codec_info, const RTPVideoTypeHeader *rtp_type_hdr) {
389 // Drop this packet if we're not sending media packets.
390 CriticalSectionScoped cs(send_critsect_);
391 if (!sending_media_) {
395 RtpVideoCodecTypes video_type = kRtpVideoGeneric;
396 if (CheckPayloadType(payload_type, &video_type) != 0) {
397 LOG(LS_ERROR) << "Don't send data with unknown payload type.";
402 if (audio_configured_) {
403 TRACE_EVENT_ASYNC_STEP1("webrtc", "Audio", capture_timestamp,
404 "Send", "type", FrameTypeToString(frame_type));
405 assert(frame_type == kAudioFrameSpeech || frame_type == kAudioFrameCN ||
406 frame_type == kFrameEmpty);
408 ret_val = audio_->SendAudio(frame_type, payload_type, capture_timestamp,
409 payload_data, payload_size, fragmentation);
411 TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", capture_time_ms,
412 "Send", "type", FrameTypeToString(frame_type));
413 assert(frame_type != kAudioFrameSpeech && frame_type != kAudioFrameCN);
415 if (frame_type == kFrameEmpty) {
416 if (paced_sender_->Enabled()) {
417 // Padding is driven by the pacer and not by the encoder.
420 return SendPaddingAccordingToBitrate(payload_type, capture_timestamp,
421 capture_time_ms) ? 0 : -1;
423 ret_val = video_->SendVideo(video_type, frame_type, payload_type,
424 capture_timestamp, capture_time_ms,
425 payload_data, payload_size,
426 fragmentation, codec_info,
431 CriticalSectionScoped cs(statistics_crit_.get());
432 uint32_t frame_count = ++frame_counts_[frame_type];
433 if (frame_count_observer_) {
434 frame_count_observer_->FrameCountUpdated(frame_type,
442 int RTPSender::SendRedundantPayloads(int payload_type, int bytes_to_send) {
443 if (!(rtx_ & kRtxRedundantPayloads))
445 uint8_t buffer[IP_PACKET_SIZE];
446 int bytes_left = bytes_to_send;
447 while (bytes_left > 0) {
448 uint16_t length = bytes_left;
449 int64_t capture_time_ms;
450 if (!packet_history_.GetBestFittingPacket(buffer, &length,
454 if (!PrepareAndSendPacket(buffer, length, capture_time_ms, true, false))
456 ModuleRTPUtility::RTPHeaderParser rtp_parser(buffer, length);
457 RTPHeader rtp_header;
458 rtp_parser.Parse(rtp_header);
459 bytes_left -= length - rtp_header.headerLength;
461 return bytes_to_send - bytes_left;
464 bool RTPSender::SendPaddingAccordingToBitrate(
465 int8_t payload_type, uint32_t capture_timestamp,
466 int64_t capture_time_ms) {
467 // Current bitrate since last estimate(1 second) averaged with the
468 // estimate since then, to get the most up to date bitrate.
469 uint32_t current_bitrate = bitrate_sent_.BitrateNow();
470 uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
471 int bitrate_diff = target_bitrate_kbps * 1000 - current_bitrate;
472 if (bitrate_diff <= 0) {
476 if (current_bitrate == 0) {
477 // Start up phase. Send one 33.3 ms batch to start with.
478 bytes = (bitrate_diff / 8) / 30;
480 bytes = (bitrate_diff / 8);
481 // Cap at 200 ms of target send data.
482 int bytes_cap = target_bitrate_kbps * 25; // 1000 / 8 / 5.
483 if (bytes > bytes_cap) {
489 CriticalSectionScoped cs(send_critsect_);
490 // Add the random RTP timestamp offset and store the capture time for
491 // later calculation of the send time offset.
492 timestamp = start_time_stamp_ + capture_timestamp;
493 timestamp_ = timestamp;
494 capture_time_ms_ = capture_time_ms;
495 last_timestamp_time_ms_ = clock_->TimeInMilliseconds();
497 int bytes_sent = SendPadData(payload_type, timestamp, capture_time_ms,
498 bytes, kDontRetransmit, false, false);
499 // We did not manage to send all bytes. Comparing with 31 due to modulus 32.
500 return bytes - bytes_sent < 31;
503 int RTPSender::BuildPaddingPacket(uint8_t* packet, int header_length,
505 int padding_bytes_in_packet = kMaxPaddingLength;
506 if (bytes < kMaxPaddingLength) {
507 padding_bytes_in_packet = bytes;
509 packet[0] |= 0x20; // Set padding bit.
511 reinterpret_cast<int32_t *>(&(packet[header_length]));
513 // Fill data buffer with random data.
514 for (int j = 0; j < (padding_bytes_in_packet >> 2); ++j) {
515 data[j] = rand(); // NOLINT
517 // Set number of padding bytes in the last byte of the packet.
518 packet[header_length + padding_bytes_in_packet - 1] = padding_bytes_in_packet;
519 return padding_bytes_in_packet;
522 int RTPSender::SendPadData(int payload_type, uint32_t timestamp,
523 int64_t capture_time_ms, int32_t bytes,
524 StorageType store, bool force_full_size_packets,
525 bool only_pad_after_markerbit) {
526 // Drop this packet if we're not sending media packets.
527 if (!SendingMedia()) {
530 int padding_bytes_in_packet = 0;
532 for (; bytes > 0; bytes -= padding_bytes_in_packet) {
533 // Always send full padding packets.
534 if (force_full_size_packets && bytes < kMaxPaddingLength)
535 bytes = kMaxPaddingLength;
536 if (bytes < kMaxPaddingLength) {
537 if (force_full_size_packets) {
538 bytes = kMaxPaddingLength;
540 // Round to the nearest multiple of 32.
541 bytes = (bytes + 16) & 0xffe0;
545 // Sanity don't send empty packets.
549 uint16_t sequence_number;
551 CriticalSectionScoped cs(send_critsect_);
552 // Only send padding packets following the last packet of a frame,
553 // indicated by the marker bit.
554 if (only_pad_after_markerbit && !last_packet_marker_bit_)
556 if (rtx_ == kRtxOff) {
558 sequence_number = sequence_number_;
562 sequence_number = sequence_number_rtx_;
563 ++sequence_number_rtx_;
566 uint8_t padding_packet[IP_PACKET_SIZE];
567 int header_length = CreateRTPHeader(padding_packet, payload_type, ssrc,
568 false, timestamp, sequence_number, NULL,
570 padding_bytes_in_packet = BuildPaddingPacket(padding_packet, header_length,
572 if (0 > SendToNetwork(padding_packet, padding_bytes_in_packet,
573 header_length, capture_time_ms, store,
574 PacedSender::kLowPriority)) {
575 // Error sending the packet.
578 bytes_sent += padding_bytes_in_packet;
583 void RTPSender::SetStorePacketsStatus(const bool enable,
584 const uint16_t number_to_store) {
585 packet_history_.SetStorePacketsStatus(enable, number_to_store);
588 bool RTPSender::StorePackets() const {
589 return packet_history_.StorePackets();
592 int32_t RTPSender::ReSendPacket(uint16_t packet_id, uint32_t min_resend_time) {
593 uint16_t length = IP_PACKET_SIZE;
594 uint8_t data_buffer[IP_PACKET_SIZE];
595 int64_t capture_time_ms;
596 if (!packet_history_.GetPacketAndSetSendTime(packet_id, min_resend_time, true,
597 data_buffer, &length,
604 ModuleRTPUtility::RTPHeaderParser rtp_parser(data_buffer, length);
606 if (!rtp_parser.Parse(header)) {
610 if (!paced_sender_->SendPacket(PacedSender::kHighPriority,
612 header.sequenceNumber,
614 length - header.headerLength,
616 // We can't send the packet right now.
617 // We will be called when it is time.
622 return PrepareAndSendPacket(data_buffer, length, capture_time_ms,
623 (rtx_ & kRtxRetransmitted) > 0, true) ?
627 bool RTPSender::SendPacketToNetwork(const uint8_t *packet, uint32_t size) {
630 bytes_sent = transport_->SendPacket(id_, packet, size);
632 TRACE_EVENT_INSTANT2("webrtc_rtp", "RTPSender::SendPacketToNetwork",
633 "size", size, "sent", bytes_sent);
634 // TODO(pwestin): Add a separate bitrate for sent bitrate after pacer.
635 if (bytes_sent <= 0) {
636 LOG(LS_WARNING) << "Transport failed to send packet";
642 int RTPSender::SelectiveRetransmissions() const {
645 return video_->SelectiveRetransmissions();
648 int RTPSender::SetSelectiveRetransmissions(uint8_t settings) {
651 return video_->SetSelectiveRetransmissions(settings);
654 void RTPSender::OnReceivedNACK(
655 const std::list<uint16_t>& nack_sequence_numbers,
656 const uint16_t avg_rtt) {
657 TRACE_EVENT2("webrtc_rtp", "RTPSender::OnReceivedNACK",
658 "num_seqnum", nack_sequence_numbers.size(), "avg_rtt", avg_rtt);
659 const int64_t now = clock_->TimeInMilliseconds();
660 uint32_t bytes_re_sent = 0;
661 uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
663 // Enough bandwidth to send NACK?
664 if (!ProcessNACKBitRate(now)) {
665 LOG(LS_INFO) << "NACK bitrate reached. Skip sending NACK response. Target "
666 << target_bitrate_kbps;
670 for (std::list<uint16_t>::const_iterator it = nack_sequence_numbers.begin();
671 it != nack_sequence_numbers.end(); ++it) {
672 const int32_t bytes_sent = ReSendPacket(*it, 5 + avg_rtt);
673 if (bytes_sent > 0) {
674 bytes_re_sent += bytes_sent;
675 } else if (bytes_sent == 0) {
676 // The packet has previously been resent.
677 // Try resending next packet in the list.
679 } else if (bytes_sent < 0) {
680 // Failed to send one Sequence number. Give up the rest in this nack.
681 LOG(LS_WARNING) << "Failed resending RTP packet " << *it
682 << ", Discard rest of packets";
685 // Delay bandwidth estimate (RTT * BW).
686 if (target_bitrate_kbps != 0 && avg_rtt) {
687 // kbits/s * ms = bits => bits/8 = bytes
688 uint32_t target_bytes =
689 (static_cast<uint32_t>(target_bitrate_kbps) * avg_rtt) >> 3;
690 if (bytes_re_sent > target_bytes) {
691 break; // Ignore the rest of the packets in the list.
695 if (bytes_re_sent > 0) {
696 // TODO(pwestin) consolidate these two methods.
697 UpdateNACKBitRate(bytes_re_sent, now);
698 nack_bitrate_.Update(bytes_re_sent);
702 bool RTPSender::ProcessNACKBitRate(const uint32_t now) {
704 int32_t byte_count = 0;
705 const uint32_t avg_interval = 1000;
706 uint16_t target_bitrate_kbps = GetTargetBitrateKbps();
708 CriticalSectionScoped cs(send_critsect_);
710 if (target_bitrate_kbps == 0) {
713 for (num = 0; num < NACK_BYTECOUNT_SIZE; ++num) {
714 if ((now - nack_byte_count_times_[num]) > avg_interval) {
715 // Don't use data older than 1sec.
718 byte_count += nack_byte_count_[num];
721 int32_t time_interval = avg_interval;
722 if (num == NACK_BYTECOUNT_SIZE) {
723 // More than NACK_BYTECOUNT_SIZE nack messages has been received
724 // during the last msg_interval.
725 time_interval = now - nack_byte_count_times_[num - 1];
726 if (time_interval < 0) {
727 time_interval = avg_interval;
730 return (byte_count * 8) < (target_bitrate_kbps * time_interval);
733 void RTPSender::UpdateNACKBitRate(const uint32_t bytes,
734 const uint32_t now) {
735 CriticalSectionScoped cs(send_critsect_);
737 // Save bitrate statistics.
740 // Add padding length.
741 nack_byte_count_[0] += bytes;
743 if (nack_byte_count_times_[0] == 0) {
747 for (int i = (NACK_BYTECOUNT_SIZE - 2); i >= 0; i--) {
748 nack_byte_count_[i + 1] = nack_byte_count_[i];
749 nack_byte_count_times_[i + 1] = nack_byte_count_times_[i];
752 nack_byte_count_[0] = bytes;
753 nack_byte_count_times_[0] = now;
758 // Called from pacer when we can send the packet.
759 bool RTPSender::TimeToSendPacket(uint16_t sequence_number,
760 int64_t capture_time_ms,
761 bool retransmission) {
762 uint16_t length = IP_PACKET_SIZE;
763 uint8_t data_buffer[IP_PACKET_SIZE];
764 int64_t stored_time_ms;
766 if (!packet_history_.GetPacketAndSetSendTime(sequence_number,
772 // Packet cannot be found. Allow sending to continue.
775 if (!retransmission && capture_time_ms > 0) {
776 UpdateDelayStatistics(capture_time_ms, clock_->TimeInMilliseconds());
778 return PrepareAndSendPacket(data_buffer, length, capture_time_ms,
779 retransmission && (rtx_ & kRtxRetransmitted) > 0,
783 bool RTPSender::PrepareAndSendPacket(uint8_t* buffer,
785 int64_t capture_time_ms,
787 bool is_retransmit) {
788 uint8_t *buffer_to_send_ptr = buffer;
790 ModuleRTPUtility::RTPHeaderParser rtp_parser(buffer, length);
791 RTPHeader rtp_header;
792 rtp_parser.Parse(rtp_header);
793 TRACE_EVENT_INSTANT2("webrtc_rtp", "PrepareAndSendPacket",
794 "timestamp", rtp_header.timestamp,
795 "seqnum", rtp_header.sequenceNumber);
797 uint8_t data_buffer_rtx[IP_PACKET_SIZE];
799 BuildRtxPacket(buffer, &length, data_buffer_rtx);
800 buffer_to_send_ptr = data_buffer_rtx;
803 int64_t now_ms = clock_->TimeInMilliseconds();
804 int64_t diff_ms = now_ms - capture_time_ms;
805 bool updated_transmission_time_offset =
806 UpdateTransmissionTimeOffset(buffer_to_send_ptr, length, rtp_header,
808 bool updated_abs_send_time =
809 UpdateAbsoluteSendTime(buffer_to_send_ptr, length, rtp_header, now_ms);
810 if (updated_transmission_time_offset || updated_abs_send_time) {
811 // Update stored packet in case of receiving a re-transmission request.
812 packet_history_.ReplaceRTPHeader(buffer_to_send_ptr,
813 rtp_header.sequenceNumber,
814 rtp_header.headerLength);
817 bool ret = SendPacketToNetwork(buffer_to_send_ptr, length);
818 UpdateRtpStats(buffer_to_send_ptr, length, rtp_header, send_over_rtx,
823 void RTPSender::UpdateRtpStats(const uint8_t* buffer,
825 const RTPHeader& header,
827 bool is_retransmit) {
828 StreamDataCounters* counters;
829 // Get ssrc before taking statistics_crit_ to avoid possible deadlock.
830 uint32_t ssrc = SSRC();
832 CriticalSectionScoped lock(statistics_crit_.get());
834 counters = &rtx_rtp_stats_;
837 counters = &rtp_stats_;
840 bitrate_sent_.Update(size);
842 if (IsFecPacket(buffer, header)) {
843 ++counters->fec_packets;
847 ++counters->retransmitted_packets;
849 counters->bytes += size - (header.headerLength + header.paddingLength);
850 counters->header_bytes += header.headerLength;
851 counters->padding_bytes += header.paddingLength;
854 if (rtp_stats_callback_) {
855 rtp_stats_callback_->DataCountersUpdated(*counters, ssrc);
859 bool RTPSender::IsFecPacket(const uint8_t* buffer,
860 const RTPHeader& header) const {
867 video_->GenericFECStatus(fec_enabled, pt_red, pt_fec);
868 return fec_enabled &&
869 header.payloadType == pt_red &&
870 buffer[header.headerLength] == pt_fec;
873 int RTPSender::TimeToSendPadding(int bytes) {
875 int64_t capture_time_ms;
878 CriticalSectionScoped cs(send_critsect_);
879 if (!sending_media_) {
882 payload_type = ((rtx_ & kRtxRedundantPayloads) > 0) ? payload_type_rtx_ :
884 timestamp = timestamp_;
885 capture_time_ms = capture_time_ms_;
886 if (last_timestamp_time_ms_ > 0) {
888 (clock_->TimeInMilliseconds() - last_timestamp_time_ms_) * 90;
890 (clock_->TimeInMilliseconds() - last_timestamp_time_ms_);
893 int bytes_sent = SendRedundantPayloads(payload_type, bytes);
896 int padding_sent = SendPadData(payload_type, timestamp, capture_time_ms,
897 bytes, kDontStore, true, true);
898 bytes_sent += padding_sent;
903 // TODO(pwestin): send in the RTPHeaderParser to avoid parsing it again.
904 int32_t RTPSender::SendToNetwork(
905 uint8_t *buffer, int payload_length, int rtp_header_length,
906 int64_t capture_time_ms, StorageType storage,
907 PacedSender::Priority priority) {
908 ModuleRTPUtility::RTPHeaderParser rtp_parser(
909 buffer, payload_length + rtp_header_length);
910 RTPHeader rtp_header;
911 rtp_parser.Parse(rtp_header);
913 int64_t now_ms = clock_->TimeInMilliseconds();
915 // |capture_time_ms| <= 0 is considered invalid.
916 // TODO(holmer): This should be changed all over Video Engine so that negative
917 // time is consider invalid, while 0 is considered a valid time.
918 if (capture_time_ms > 0) {
919 UpdateTransmissionTimeOffset(buffer, payload_length + rtp_header_length,
920 rtp_header, now_ms - capture_time_ms);
923 UpdateAbsoluteSendTime(buffer, payload_length + rtp_header_length,
926 // Used for NACK and to spread out the transmission of packets.
927 if (packet_history_.PutRTPPacket(buffer, rtp_header_length + payload_length,
928 max_payload_length_, capture_time_ms,
933 if (paced_sender_ && storage != kDontStore) {
934 if (!paced_sender_->SendPacket(priority, rtp_header.ssrc,
935 rtp_header.sequenceNumber, capture_time_ms,
936 payload_length, false)) {
937 // We can't send the packet right now.
938 // We will be called when it is time.
942 if (capture_time_ms > 0) {
943 UpdateDelayStatistics(capture_time_ms, now_ms);
945 uint32_t length = payload_length + rtp_header_length;
946 if (!SendPacketToNetwork(buffer, length))
948 UpdateRtpStats(buffer, length, rtp_header, false, false);
952 void RTPSender::UpdateDelayStatistics(int64_t capture_time_ms, int64_t now_ms) {
953 CriticalSectionScoped cs(statistics_crit_.get());
954 send_delays_[now_ms] = now_ms - capture_time_ms;
955 send_delays_.erase(send_delays_.begin(),
956 send_delays_.lower_bound(now_ms - kSendSideDelayWindowMs));
959 void RTPSender::ProcessBitrate() {
960 CriticalSectionScoped cs(send_critsect_);
961 bitrate_sent_.Process();
962 nack_bitrate_.Process();
963 if (audio_configured_) {
966 video_->ProcessBitrate();
969 uint16_t RTPSender::RTPHeaderLength() const {
970 uint16_t rtp_header_length = 12;
971 if (include_csrcs_) {
972 rtp_header_length += sizeof(uint32_t) * num_csrcs_;
974 rtp_header_length += RtpHeaderExtensionTotalLength();
975 return rtp_header_length;
978 uint16_t RTPSender::IncrementSequenceNumber() {
979 CriticalSectionScoped cs(send_critsect_);
980 return sequence_number_++;
983 void RTPSender::ResetDataCounters() {
984 CriticalSectionScoped lock(statistics_crit_.get());
985 rtp_stats_ = StreamDataCounters();
986 rtx_rtp_stats_ = StreamDataCounters();
987 if (rtp_stats_callback_) {
988 rtp_stats_callback_->DataCountersUpdated(rtp_stats_, ssrc_);
989 rtp_stats_callback_->DataCountersUpdated(rtx_rtp_stats_, ssrc_rtx_);
993 uint32_t RTPSender::Packets() const {
994 CriticalSectionScoped lock(statistics_crit_.get());
995 return rtp_stats_.packets + rtx_rtp_stats_.packets;
998 // Number of sent RTP bytes.
999 uint32_t RTPSender::Bytes() const {
1000 CriticalSectionScoped lock(statistics_crit_.get());
1001 return rtp_stats_.bytes + rtx_rtp_stats_.bytes;
1004 int RTPSender::CreateRTPHeader(
1005 uint8_t* header, int8_t payload_type, uint32_t ssrc, bool marker_bit,
1006 uint32_t timestamp, uint16_t sequence_number, const uint32_t* csrcs,
1007 uint8_t num_csrcs) const {
1008 header[0] = 0x80; // version 2.
1009 header[1] = static_cast<uint8_t>(payload_type);
1011 header[1] |= kRtpMarkerBitMask; // Marker bit is set.
1013 ModuleRTPUtility::AssignUWord16ToBuffer(header + 2, sequence_number);
1014 ModuleRTPUtility::AssignUWord32ToBuffer(header + 4, timestamp);
1015 ModuleRTPUtility::AssignUWord32ToBuffer(header + 8, ssrc);
1016 int32_t rtp_header_length = 12;
1018 // Add the CSRCs if any.
1019 if (num_csrcs > 0) {
1020 if (num_csrcs > kRtpCsrcSize) {
1025 uint8_t *ptr = &header[rtp_header_length];
1026 for (int i = 0; i < num_csrcs; ++i) {
1027 ModuleRTPUtility::AssignUWord32ToBuffer(ptr, csrcs[i]);
1030 header[0] = (header[0] & 0xf0) | num_csrcs;
1032 // Update length of header.
1033 rtp_header_length += sizeof(uint32_t) * num_csrcs;
1036 uint16_t len = BuildRTPHeaderExtension(header + rtp_header_length);
1038 header[0] |= 0x10; // Set extension bit.
1039 rtp_header_length += len;
1041 return rtp_header_length;
1044 int32_t RTPSender::BuildRTPheader(
1045 uint8_t *data_buffer, const int8_t payload_type,
1046 const bool marker_bit, const uint32_t capture_timestamp,
1047 int64_t capture_time_ms, const bool time_stamp_provided,
1048 const bool inc_sequence_number) {
1049 assert(payload_type >= 0);
1050 CriticalSectionScoped cs(send_critsect_);
1052 if (time_stamp_provided) {
1053 timestamp_ = start_time_stamp_ + capture_timestamp;
1055 // Make a unique time stamp.
1056 // We can't inc by the actual time, since then we increase the risk of back
1060 last_timestamp_time_ms_ = clock_->TimeInMilliseconds();
1061 uint32_t sequence_number = sequence_number_++;
1062 capture_time_ms_ = capture_time_ms;
1063 last_packet_marker_bit_ = marker_bit;
1064 int csrcs_length = 0;
1066 csrcs_length = num_csrcs_;
1067 return CreateRTPHeader(data_buffer, payload_type, ssrc_, marker_bit,
1068 timestamp_, sequence_number, csrcs_, csrcs_length);
1071 uint16_t RTPSender::BuildRTPHeaderExtension(uint8_t* data_buffer) const {
1072 if (rtp_header_extension_map_.Size() <= 0) {
1075 // RTP header extension, RFC 3550.
1077 // 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
1078 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1079 // | defined by profile | length |
1080 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1081 // | header extension |
1084 const uint32_t kPosLength = 2;
1085 const uint32_t kHeaderLength = kRtpOneByteHeaderLength;
1087 // Add extension ID (0xBEDE).
1088 ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer,
1089 kRtpOneByteHeaderExtensionId);
1092 uint16_t total_block_length = 0;
1094 RTPExtensionType type = rtp_header_extension_map_.First();
1095 while (type != kRtpExtensionNone) {
1096 uint8_t block_length = 0;
1098 case kRtpExtensionTransmissionTimeOffset:
1099 block_length = BuildTransmissionTimeOffsetExtension(
1100 data_buffer + kHeaderLength + total_block_length);
1102 case kRtpExtensionAudioLevel:
1103 block_length = BuildAudioLevelExtension(
1104 data_buffer + kHeaderLength + total_block_length);
1106 case kRtpExtensionAbsoluteSendTime:
1107 block_length = BuildAbsoluteSendTimeExtension(
1108 data_buffer + kHeaderLength + total_block_length);
1113 total_block_length += block_length;
1114 type = rtp_header_extension_map_.Next(type);
1116 if (total_block_length == 0) {
1117 // No extension added.
1120 // Set header length (in number of Word32, header excluded).
1121 assert(total_block_length % 4 == 0);
1122 ModuleRTPUtility::AssignUWord16ToBuffer(data_buffer + kPosLength,
1123 total_block_length / 4);
1124 // Total added length.
1125 return kHeaderLength + total_block_length;
1128 uint8_t RTPSender::BuildTransmissionTimeOffsetExtension(
1129 uint8_t* data_buffer) const {
1130 // From RFC 5450: Transmission Time Offsets in RTP Streams.
1132 // The transmission time is signaled to the receiver in-band using the
1133 // general mechanism for RTP header extensions [RFC5285]. The payload
1134 // of this extension (the transmitted value) is a 24-bit signed integer.
1135 // When added to the RTP timestamp of the packet, it represents the
1136 // "effective" RTP transmission time of the packet, on the RTP
1139 // The form of the transmission offset extension block:
1142 // 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
1143 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1144 // | ID | len=2 | transmission offset |
1145 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1147 // Get id defined by user.
1149 if (rtp_header_extension_map_.GetId(kRtpExtensionTransmissionTimeOffset,
1155 const uint8_t len = 2;
1156 data_buffer[pos++] = (id << 4) + len;
1157 ModuleRTPUtility::AssignUWord24ToBuffer(data_buffer + pos,
1158 transmission_time_offset_);
1160 assert(pos == kTransmissionTimeOffsetLength);
1161 return kTransmissionTimeOffsetLength;
1164 uint8_t RTPSender::BuildAudioLevelExtension(uint8_t* data_buffer) const {
1165 // An RTP Header Extension for Client-to-Mixer Audio Level Indication
1167 // https://datatracker.ietf.org/doc/draft-lennox-avt-rtp-audio-level-exthdr/
1169 // The form of the audio level extension block:
1172 // 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
1173 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1174 // | ID | len=0 |V| level | 0x00 | 0x00 |
1175 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1177 // Note that we always include 2 pad bytes, which will result in legal and
1178 // correctly parsed RTP, but may be a bit wasteful if more short extensions
1179 // are implemented. Right now the pad bytes would anyway be required at end
1180 // of the extension block, so it makes no difference.
1182 // Get id defined by user.
1184 if (rtp_header_extension_map_.GetId(kRtpExtensionAudioLevel, &id) != 0) {
1189 const uint8_t len = 0;
1190 data_buffer[pos++] = (id << 4) + len;
1191 data_buffer[pos++] = (1 << 7) + 0; // Voice, 0 dBov.
1192 data_buffer[pos++] = 0; // Padding.
1193 data_buffer[pos++] = 0; // Padding.
1194 // kAudioLevelLength is including pad bytes.
1195 assert(pos == kAudioLevelLength);
1196 return kAudioLevelLength;
1199 uint8_t RTPSender::BuildAbsoluteSendTimeExtension(uint8_t* data_buffer) const {
1200 // Absolute send time in RTP streams.
1202 // The absolute send time is signaled to the receiver in-band using the
1203 // general mechanism for RTP header extensions [RFC5285]. The payload
1204 // of this extension (the transmitted value) is a 24-bit unsigned integer
1205 // containing the sender's current time in seconds as a fixed point number
1206 // with 18 bits fractional part.
1208 // The form of the absolute send time extension block:
1211 // 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
1212 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1213 // | ID | len=2 | absolute send time |
1214 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1216 // Get id defined by user.
1218 if (rtp_header_extension_map_.GetId(kRtpExtensionAbsoluteSendTime,
1224 const uint8_t len = 2;
1225 data_buffer[pos++] = (id << 4) + len;
1226 ModuleRTPUtility::AssignUWord24ToBuffer(data_buffer + pos,
1227 absolute_send_time_);
1229 assert(pos == kAbsoluteSendTimeLength);
1230 return kAbsoluteSendTimeLength;
1233 bool RTPSender::UpdateTransmissionTimeOffset(
1234 uint8_t *rtp_packet, const uint16_t rtp_packet_length,
1235 const RTPHeader &rtp_header, const int64_t time_diff_ms) const {
1236 CriticalSectionScoped cs(send_critsect_);
1239 if (rtp_header_extension_map_.GetId(kRtpExtensionTransmissionTimeOffset,
1244 // Get length until start of header extension block.
1245 int extension_block_pos =
1246 rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1247 kRtpExtensionTransmissionTimeOffset);
1248 if (extension_block_pos < 0) {
1250 << "Failed to update transmission time offset, not registered.";
1253 int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1254 if (rtp_packet_length < block_pos + kTransmissionTimeOffsetLength ||
1255 rtp_header.headerLength <
1256 block_pos + kTransmissionTimeOffsetLength) {
1258 << "Failed to update transmission time offset, invalid length.";
1261 // Verify that header contains extension.
1262 if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1263 (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1264 LOG(LS_WARNING) << "Failed to update transmission time offset, hdr "
1265 "extension not found.";
1268 // Verify first byte in block.
1269 const uint8_t first_block_byte = (id << 4) + 2;
1270 if (rtp_packet[block_pos] != first_block_byte) {
1271 LOG(LS_WARNING) << "Failed to update transmission time offset.";
1274 // Update transmission offset field (converting to a 90 kHz timestamp).
1275 ModuleRTPUtility::AssignUWord24ToBuffer(rtp_packet + block_pos + 1,
1276 time_diff_ms * 90); // RTP timestamp.
1280 bool RTPSender::UpdateAudioLevel(uint8_t *rtp_packet,
1281 const uint16_t rtp_packet_length,
1282 const RTPHeader &rtp_header,
1283 const bool is_voiced,
1284 const uint8_t dBov) const {
1285 CriticalSectionScoped cs(send_critsect_);
1289 if (rtp_header_extension_map_.GetId(kRtpExtensionAudioLevel, &id) != 0) {
1293 // Get length until start of header extension block.
1294 int extension_block_pos =
1295 rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1296 kRtpExtensionAudioLevel);
1297 if (extension_block_pos < 0) {
1298 // The feature is not enabled.
1301 int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1302 if (rtp_packet_length < block_pos + kAudioLevelLength ||
1303 rtp_header.headerLength < block_pos + kAudioLevelLength) {
1304 LOG(LS_WARNING) << "Failed to update audio level, invalid length.";
1307 // Verify that header contains extension.
1308 if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1309 (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1310 LOG(LS_WARNING) << "Failed to update audio level, hdr extension not found.";
1313 // Verify first byte in block.
1314 const uint8_t first_block_byte = (id << 4) + 0;
1315 if (rtp_packet[block_pos] != first_block_byte) {
1316 LOG(LS_WARNING) << "Failed to update audio level.";
1319 rtp_packet[block_pos + 1] = (is_voiced ? 0x80 : 0x00) + (dBov & 0x7f);
1323 bool RTPSender::UpdateAbsoluteSendTime(
1324 uint8_t *rtp_packet, const uint16_t rtp_packet_length,
1325 const RTPHeader &rtp_header, const int64_t now_ms) const {
1326 CriticalSectionScoped cs(send_critsect_);
1330 if (rtp_header_extension_map_.GetId(kRtpExtensionAbsoluteSendTime,
1335 // Get length until start of header extension block.
1336 int extension_block_pos =
1337 rtp_header_extension_map_.GetLengthUntilBlockStartInBytes(
1338 kRtpExtensionAbsoluteSendTime);
1339 if (extension_block_pos < 0) {
1340 // The feature is not enabled.
1343 int block_pos = 12 + rtp_header.numCSRCs + extension_block_pos;
1344 if (rtp_packet_length < block_pos + kAbsoluteSendTimeLength ||
1345 rtp_header.headerLength < block_pos + kAbsoluteSendTimeLength) {
1346 LOG(LS_WARNING) << "Failed to update absolute send time, invalid length.";
1349 // Verify that header contains extension.
1350 if (!((rtp_packet[12 + rtp_header.numCSRCs] == 0xBE) &&
1351 (rtp_packet[12 + rtp_header.numCSRCs + 1] == 0xDE))) {
1353 << "Failed to update absolute send time, hdr extension not found.";
1356 // Verify first byte in block.
1357 const uint8_t first_block_byte = (id << 4) + 2;
1358 if (rtp_packet[block_pos] != first_block_byte) {
1359 LOG(LS_WARNING) << "Failed to update absolute send time.";
1362 // Update absolute send time field (convert ms to 24-bit unsigned with 18 bit
1363 // fractional part).
1364 ModuleRTPUtility::AssignUWord24ToBuffer(rtp_packet + block_pos + 1,
1365 ((now_ms << 18) / 1000) & 0x00ffffff);
1369 void RTPSender::SetSendingStatus(bool enabled) {
1371 uint32_t frequency_hz = SendPayloadFrequency();
1372 uint32_t RTPtime = ModuleRTPUtility::GetCurrentRTP(clock_, frequency_hz);
1374 // Will be ignored if it's already configured via API.
1375 SetStartTimestamp(RTPtime, false);
1377 if (!ssrc_forced_) {
1378 // Generate a new SSRC.
1379 ssrc_db_.ReturnSSRC(ssrc_);
1380 ssrc_ = ssrc_db_.CreateSSRC(); // Can't be 0.
1382 // Don't initialize seq number if SSRC passed externally.
1383 if (!sequence_number_forced_ && !ssrc_forced_) {
1384 // Generate a new sequence number.
1386 rand() / (RAND_MAX / MAX_INIT_RTP_SEQ_NUMBER); // NOLINT
1391 void RTPSender::SetSendingMediaStatus(const bool enabled) {
1392 CriticalSectionScoped cs(send_critsect_);
1393 sending_media_ = enabled;
1396 bool RTPSender::SendingMedia() const {
1397 CriticalSectionScoped cs(send_critsect_);
1398 return sending_media_;
1401 uint32_t RTPSender::Timestamp() const {
1402 CriticalSectionScoped cs(send_critsect_);
1406 void RTPSender::SetStartTimestamp(uint32_t timestamp, bool force) {
1407 CriticalSectionScoped cs(send_critsect_);
1409 start_time_stamp_forced_ = force;
1410 start_time_stamp_ = timestamp;
1412 if (!start_time_stamp_forced_) {
1413 start_time_stamp_ = timestamp;
1418 uint32_t RTPSender::StartTimestamp() const {
1419 CriticalSectionScoped cs(send_critsect_);
1420 return start_time_stamp_;
1423 uint32_t RTPSender::GenerateNewSSRC() {
1424 // If configured via API, return 0.
1425 CriticalSectionScoped cs(send_critsect_);
1430 ssrc_ = ssrc_db_.CreateSSRC(); // Can't be 0.
1434 void RTPSender::SetSSRC(uint32_t ssrc) {
1435 // This is configured via the API.
1436 CriticalSectionScoped cs(send_critsect_);
1438 if (ssrc_ == ssrc && ssrc_forced_) {
1439 return; // Since it's same ssrc, don't reset anything.
1441 ssrc_forced_ = true;
1442 ssrc_db_.ReturnSSRC(ssrc_);
1443 ssrc_db_.RegisterSSRC(ssrc);
1445 if (!sequence_number_forced_) {
1447 rand() / (RAND_MAX / MAX_INIT_RTP_SEQ_NUMBER); // NOLINT
1451 uint32_t RTPSender::SSRC() const {
1452 CriticalSectionScoped cs(send_critsect_);
1456 void RTPSender::SetCSRCStatus(const bool include) {
1457 include_csrcs_ = include;
1460 void RTPSender::SetCSRCs(const uint32_t arr_of_csrc[kRtpCsrcSize],
1461 const uint8_t arr_length) {
1462 assert(arr_length <= kRtpCsrcSize);
1463 CriticalSectionScoped cs(send_critsect_);
1465 for (int i = 0; i < arr_length; i++) {
1466 csrcs_[i] = arr_of_csrc[i];
1468 num_csrcs_ = arr_length;
1471 int32_t RTPSender::CSRCs(uint32_t arr_of_csrc[kRtpCsrcSize]) const {
1472 assert(arr_of_csrc);
1473 CriticalSectionScoped cs(send_critsect_);
1474 for (int i = 0; i < num_csrcs_ && i < kRtpCsrcSize; i++) {
1475 arr_of_csrc[i] = csrcs_[i];
1480 void RTPSender::SetSequenceNumber(uint16_t seq) {
1481 CriticalSectionScoped cs(send_critsect_);
1482 sequence_number_forced_ = true;
1483 sequence_number_ = seq;
1486 uint16_t RTPSender::SequenceNumber() const {
1487 CriticalSectionScoped cs(send_critsect_);
1488 return sequence_number_;
1492 int32_t RTPSender::SendTelephoneEvent(const uint8_t key,
1493 const uint16_t time_ms,
1494 const uint8_t level) {
1495 if (!audio_configured_) {
1498 return audio_->SendTelephoneEvent(key, time_ms, level);
1501 bool RTPSender::SendTelephoneEventActive(int8_t *telephone_event) const {
1502 if (!audio_configured_) {
1505 return audio_->SendTelephoneEventActive(*telephone_event);
1508 int32_t RTPSender::SetAudioPacketSize(
1509 const uint16_t packet_size_samples) {
1510 if (!audio_configured_) {
1513 return audio_->SetAudioPacketSize(packet_size_samples);
1516 int32_t RTPSender::SetAudioLevel(const uint8_t level_d_bov) {
1517 return audio_->SetAudioLevel(level_d_bov);
1520 int32_t RTPSender::SetRED(const int8_t payload_type) {
1521 if (!audio_configured_) {
1524 return audio_->SetRED(payload_type);
1527 int32_t RTPSender::RED(int8_t *payload_type) const {
1528 if (!audio_configured_) {
1531 return audio_->RED(*payload_type);
1535 VideoCodecInformation *RTPSender::CodecInformationVideo() {
1536 if (audio_configured_) {
1539 return video_->CodecInformationVideo();
1542 RtpVideoCodecTypes RTPSender::VideoCodecType() const {
1543 assert(!audio_configured_ && "Sender is an audio stream!");
1544 return video_->VideoCodecType();
1547 uint32_t RTPSender::MaxConfiguredBitrateVideo() const {
1548 if (audio_configured_) {
1551 return video_->MaxConfiguredBitrateVideo();
1554 int32_t RTPSender::SendRTPIntraRequest() {
1555 if (audio_configured_) {
1558 return video_->SendRTPIntraRequest();
1561 int32_t RTPSender::SetGenericFECStatus(
1562 const bool enable, const uint8_t payload_type_red,
1563 const uint8_t payload_type_fec) {
1564 if (audio_configured_) {
1567 return video_->SetGenericFECStatus(enable, payload_type_red,
1571 int32_t RTPSender::GenericFECStatus(
1572 bool *enable, uint8_t *payload_type_red,
1573 uint8_t *payload_type_fec) const {
1574 if (audio_configured_) {
1577 return video_->GenericFECStatus(
1578 *enable, *payload_type_red, *payload_type_fec);
1581 int32_t RTPSender::SetFecParameters(
1582 const FecProtectionParams *delta_params,
1583 const FecProtectionParams *key_params) {
1584 if (audio_configured_) {
1587 return video_->SetFecParameters(delta_params, key_params);
1590 void RTPSender::BuildRtxPacket(uint8_t* buffer, uint16_t* length,
1591 uint8_t* buffer_rtx) {
1592 CriticalSectionScoped cs(send_critsect_);
1593 uint8_t* data_buffer_rtx = buffer_rtx;
1595 ModuleRTPUtility::RTPHeaderParser rtp_parser(
1596 reinterpret_cast<const uint8_t *>(buffer), *length);
1598 RTPHeader rtp_header;
1599 rtp_parser.Parse(rtp_header);
1601 // Add original RTP header.
1602 memcpy(data_buffer_rtx, buffer, rtp_header.headerLength);
1604 // Replace payload type, if a specific type is set for RTX.
1605 if (payload_type_rtx_ != -1) {
1606 data_buffer_rtx[1] = static_cast<uint8_t>(payload_type_rtx_);
1607 if (rtp_header.markerBit)
1608 data_buffer_rtx[1] |= kRtpMarkerBitMask;
1611 // Replace sequence number.
1612 uint8_t *ptr = data_buffer_rtx + 2;
1613 ModuleRTPUtility::AssignUWord16ToBuffer(ptr, sequence_number_rtx_++);
1617 ModuleRTPUtility::AssignUWord32ToBuffer(ptr, ssrc_rtx_);
1619 // Add OSN (original sequence number).
1620 ptr = data_buffer_rtx + rtp_header.headerLength;
1621 ModuleRTPUtility::AssignUWord16ToBuffer(ptr, rtp_header.sequenceNumber);
1624 // Add original payload data.
1625 memcpy(ptr, buffer + rtp_header.headerLength,
1626 *length - rtp_header.headerLength);
1630 void RTPSender::RegisterFrameCountObserver(FrameCountObserver* observer) {
1631 CriticalSectionScoped cs(statistics_crit_.get());
1632 if (observer != NULL)
1633 assert(frame_count_observer_ == NULL);
1634 frame_count_observer_ = observer;
1637 FrameCountObserver* RTPSender::GetFrameCountObserver() const {
1638 CriticalSectionScoped cs(statistics_crit_.get());
1639 return frame_count_observer_;
1642 void RTPSender::RegisterRtpStatisticsCallback(
1643 StreamDataCountersCallback* callback) {
1644 CriticalSectionScoped cs(statistics_crit_.get());
1645 if (callback != NULL)
1646 assert(rtp_stats_callback_ == NULL);
1647 rtp_stats_callback_ = callback;
1650 StreamDataCountersCallback* RTPSender::GetRtpStatisticsCallback() const {
1651 CriticalSectionScoped cs(statistics_crit_.get());
1652 return rtp_stats_callback_;
1655 void RTPSender::RegisterBitrateObserver(BitrateStatisticsObserver* observer) {
1656 CriticalSectionScoped cs(statistics_crit_.get());
1657 if (observer != NULL)
1658 assert(bitrate_callback_ == NULL);
1659 bitrate_callback_ = observer;
1662 BitrateStatisticsObserver* RTPSender::GetBitrateObserver() const {
1663 CriticalSectionScoped cs(statistics_crit_.get());
1664 return bitrate_callback_;
1667 uint32_t RTPSender::BitrateSent() const { return bitrate_sent_.BitrateLast(); }
1669 void RTPSender::BitrateUpdated(const BitrateStatistics& stats) {
1670 CriticalSectionScoped cs(statistics_crit_.get());
1671 if (bitrate_callback_) {
1672 bitrate_callback_->Notify(stats, ssrc_);
1676 void RTPSender::SetTargetBitrateKbps(uint16_t bitrate_kbps) {
1677 CriticalSectionScoped cs(target_bitrate_critsect_.get());
1678 target_bitrate_kbps_ = bitrate_kbps;
1681 uint16_t RTPSender::GetTargetBitrateKbps() {
1682 CriticalSectionScoped cs(target_bitrate_critsect_.get());
1683 return target_bitrate_kbps_;
1685 } // namespace webrtc