blob: ec42f6132ac0c992b01bf7e26c64c7ea096e36cf [file] [log] [blame]
Tommi3a5742c2020-05-20 09:32:51 +02001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
12
13#include <string.h>
14
15#include <algorithm>
16#include <cstdint>
17#include <memory>
18#include <set>
19#include <string>
20#include <utility>
21
Markus Handellc6b9ac72021-06-18 13:44:51 +020022#include "absl/types/optional.h"
Markus Handell885d5382021-06-21 18:57:36 +020023#include "api/sequence_checker.h"
Tommi3a5742c2020-05-20 09:32:51 +020024#include "api/transport/field_trial_based_config.h"
Markus Handell885d5382021-06-21 18:57:36 +020025#include "api/units/time_delta.h"
Markus Handellc6b9ac72021-06-18 13:44:51 +020026#include "api/units/timestamp.h"
Tommi3a5742c2020-05-20 09:32:51 +020027#include "modules/rtp_rtcp/source/rtcp_packet/dlrr.h"
28#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
29#include "rtc_base/checks.h"
30#include "rtc_base/logging.h"
Markus Handell885d5382021-06-21 18:57:36 +020031#include "rtc_base/task_utils/to_queued_task.h"
32#include "rtc_base/time_utils.h"
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +010033#include "system_wrappers/include/ntp_time.h"
Tommi3a5742c2020-05-20 09:32:51 +020034
35#ifdef _WIN32
36// Disable warning C4355: 'this' : used in base member initializer list.
37#pragma warning(disable : 4355)
38#endif
39
40namespace webrtc {
41namespace {
Tommi3a5742c2020-05-20 09:32:51 +020042const int64_t kDefaultExpectedRetransmissionTimeMs = 125;
Tomas Gunnarssonba0ba712020-07-01 08:53:21 +020043
44constexpr TimeDelta kRttUpdateInterval = TimeDelta::Millis(1000);
Markus Handell885d5382021-06-21 18:57:36 +020045
46RTCPSender::Configuration AddRtcpSendEvaluationCallback(
47 RTCPSender::Configuration config,
48 std::function<void(TimeDelta)> send_evaluation_callback) {
49 config.schedule_next_rtcp_send_evaluation_function =
50 std::move(send_evaluation_callback);
51 return config;
52}
53
54int DelayMillisForDuration(TimeDelta duration) {
55 // TimeDelta::ms() rounds downwards sometimes which leads to too little time
Artem Titov913cfa72021-07-28 23:57:33 +020056 // slept. Account for this, unless `duration` is exactly representable in
Markus Handell885d5382021-06-21 18:57:36 +020057 // millisecs.
58 return (duration.us() + rtc::kNumMillisecsPerSec - 1) /
59 rtc::kNumMicrosecsPerMillisec;
60}
Tommi3a5742c2020-05-20 09:32:51 +020061} // namespace
62
63ModuleRtpRtcpImpl2::RtpSenderContext::RtpSenderContext(
Tomas Gunnarssonf25761d2020-06-03 22:55:33 +020064 const RtpRtcpInterface::Configuration& config)
Tommi3a5742c2020-05-20 09:32:51 +020065 : packet_history(config.clock, config.enable_rtx_padding_prioritization),
Erik Språngbb904972021-08-06 13:10:11 +020066 deferred_sequencing_(config.use_deferred_sequencing),
Erik Språngbfcfe032021-08-04 14:45:32 +020067 sequencer_(config.local_media_ssrc,
68 config.rtx_send_ssrc,
69 /*require_marker_before_media_padding=*/!config.audio,
70 config.clock),
Tommi3a5742c2020-05-20 09:32:51 +020071 packet_sender(config, &packet_history),
Erik Språngbb904972021-08-06 13:10:11 +020072 non_paced_sender(&packet_sender, this, config.use_deferred_sequencing),
Tommi3a5742c2020-05-20 09:32:51 +020073 packet_generator(
74 config,
75 &packet_history,
Erik Språngbfcfe032021-08-04 14:45:32 +020076 config.paced_sender ? config.paced_sender : &non_paced_sender,
Erik Språngbb904972021-08-06 13:10:11 +020077 config.use_deferred_sequencing ? nullptr : &sequencer_) {}
Erik Språng1d50cb62020-07-02 17:41:32 +020078void ModuleRtpRtcpImpl2::RtpSenderContext::AssignSequenceNumber(
79 RtpPacketToSend* packet) {
Erik Språngbb904972021-08-06 13:10:11 +020080 if (deferred_sequencing_) {
Erik Språng6e2458d2021-08-11 13:34:59 +020081 MutexLock lock(&mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +020082 sequencer_.Sequence(*packet);
83 } else {
84 packet_generator.AssignSequenceNumber(packet);
85 }
Erik Språng1d50cb62020-07-02 17:41:32 +020086}
Tommi3a5742c2020-05-20 09:32:51 +020087
Tommi3a5742c2020-05-20 09:32:51 +020088ModuleRtpRtcpImpl2::ModuleRtpRtcpImpl2(const Configuration& configuration)
Niels Moller2accc7d2021-01-12 15:54:16 +000089 : worker_queue_(TaskQueueBase::Current()),
Markus Handell885d5382021-06-21 18:57:36 +020090 rtcp_sender_(AddRtcpSendEvaluationCallback(
91 RTCPSender::Configuration::FromRtpRtcpConfiguration(configuration),
92 [this](TimeDelta duration) {
93 ScheduleRtcpSendEvaluation(duration);
94 })),
Tommi3a5742c2020-05-20 09:32:51 +020095 rtcp_receiver_(configuration, this),
96 clock_(configuration.clock),
Tommi3a5742c2020-05-20 09:32:51 +020097 packet_overhead_(28), // IPV4 UDP.
98 nack_last_time_sent_full_ms_(0),
99 nack_last_seq_number_sent_(0),
100 remote_bitrate_(configuration.remote_bitrate_estimator),
101 rtt_stats_(configuration.rtt_stats),
102 rtt_ms_(0) {
Niels Moller2accc7d2021-01-12 15:54:16 +0000103 RTC_DCHECK(worker_queue_);
Tommi08be9ba2021-06-15 23:01:57 +0200104 packet_sequence_checker_.Detach();
Erik Språngbb904972021-08-06 13:10:11 +0200105 pacer_thread_checker_.Detach();
Tommi3a5742c2020-05-20 09:32:51 +0200106 if (!configuration.receiver_only) {
107 rtp_sender_ = std::make_unique<RtpSenderContext>(configuration);
108 // Make sure rtcp sender use same timestamp offset as rtp sender.
109 rtcp_sender_.SetTimestampOffset(
110 rtp_sender_->packet_generator.TimestampOffset());
111 }
112
113 // Set default packet size limit.
114 // TODO(nisse): Kind-of duplicates
115 // webrtc::VideoSendStream::Config::Rtp::kDefaultMaxPacketSize.
116 const size_t kTcpOverIpv4HeaderSize = 40;
117 SetMaxRtpPacketSize(IP_PACKET_SIZE - kTcpOverIpv4HeaderSize);
Ivo Creusen8c40d512021-07-13 12:53:22 +0000118 rtt_update_task_ = RepeatingTaskHandle::DelayedStart(
119 worker_queue_, kRttUpdateInterval, [this]() {
120 PeriodicUpdate();
121 return kRttUpdateInterval;
122 });
Tommi3a5742c2020-05-20 09:32:51 +0200123}
124
125ModuleRtpRtcpImpl2::~ModuleRtpRtcpImpl2() {
Niels Moller2accc7d2021-01-12 15:54:16 +0000126 RTC_DCHECK_RUN_ON(worker_queue_);
127 rtt_update_task_.Stop();
128}
129
130// static
131std::unique_ptr<ModuleRtpRtcpImpl2> ModuleRtpRtcpImpl2::Create(
132 const Configuration& configuration) {
133 RTC_DCHECK(configuration.clock);
134 RTC_DCHECK(TaskQueueBase::Current());
135 return std::make_unique<ModuleRtpRtcpImpl2>(configuration);
Tomas Gunnarssonfae05622020-06-03 08:54:39 +0200136}
137
Tommi3a5742c2020-05-20 09:32:51 +0200138void ModuleRtpRtcpImpl2::SetRtxSendStatus(int mode) {
139 rtp_sender_->packet_generator.SetRtxStatus(mode);
140}
141
142int ModuleRtpRtcpImpl2::RtxSendStatus() const {
143 return rtp_sender_ ? rtp_sender_->packet_generator.RtxStatus() : kRtxOff;
144}
145
146void ModuleRtpRtcpImpl2::SetRtxSendPayloadType(int payload_type,
147 int associated_payload_type) {
148 rtp_sender_->packet_generator.SetRtxPayloadType(payload_type,
149 associated_payload_type);
150}
151
152absl::optional<uint32_t> ModuleRtpRtcpImpl2::RtxSsrc() const {
153 return rtp_sender_ ? rtp_sender_->packet_generator.RtxSsrc() : absl::nullopt;
154}
155
156absl::optional<uint32_t> ModuleRtpRtcpImpl2::FlexfecSsrc() const {
157 if (rtp_sender_) {
158 return rtp_sender_->packet_generator.FlexfecSsrc();
159 }
160 return absl::nullopt;
161}
162
163void ModuleRtpRtcpImpl2::IncomingRtcpPacket(const uint8_t* rtcp_packet,
164 const size_t length) {
Tommi08be9ba2021-06-15 23:01:57 +0200165 RTC_DCHECK_RUN_ON(&packet_sequence_checker_);
Tommi3a5742c2020-05-20 09:32:51 +0200166 rtcp_receiver_.IncomingPacket(rtcp_packet, length);
167}
168
169void ModuleRtpRtcpImpl2::RegisterSendPayloadFrequency(int payload_type,
170 int payload_frequency) {
171 rtcp_sender_.SetRtpClockRate(payload_type, payload_frequency);
172}
173
174int32_t ModuleRtpRtcpImpl2::DeRegisterSendPayload(const int8_t payload_type) {
175 return 0;
176}
177
178uint32_t ModuleRtpRtcpImpl2::StartTimestamp() const {
179 return rtp_sender_->packet_generator.TimestampOffset();
180}
181
182// Configure start timestamp, default is a random number.
183void ModuleRtpRtcpImpl2::SetStartTimestamp(const uint32_t timestamp) {
184 rtcp_sender_.SetTimestampOffset(timestamp);
185 rtp_sender_->packet_generator.SetTimestampOffset(timestamp);
186 rtp_sender_->packet_sender.SetTimestampOffset(timestamp);
187}
188
189uint16_t ModuleRtpRtcpImpl2::SequenceNumber() const {
Erik Språngbb904972021-08-06 13:10:11 +0200190 if (rtp_sender_->deferred_sequencing_) {
Erik Språng6e2458d2021-08-11 13:34:59 +0200191 MutexLock lock(&rtp_sender_->mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +0200192 return rtp_sender_->sequencer_.media_sequence_number();
193 }
Tommi3a5742c2020-05-20 09:32:51 +0200194 return rtp_sender_->packet_generator.SequenceNumber();
195}
196
197// Set SequenceNumber, default is a random number.
198void ModuleRtpRtcpImpl2::SetSequenceNumber(const uint16_t seq_num) {
Erik Språngbb904972021-08-06 13:10:11 +0200199 if (rtp_sender_->deferred_sequencing_) {
200 RTC_DCHECK_RUN_ON(&pacer_thread_checker_);
Erik Språng6e2458d2021-08-11 13:34:59 +0200201 MutexLock lock(&rtp_sender_->mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +0200202 if (rtp_sender_->sequencer_.media_sequence_number() != seq_num) {
203 rtp_sender_->sequencer_.set_media_sequence_number(seq_num);
204 rtp_sender_->packet_history.Clear();
205 }
206 } else {
207 rtp_sender_->packet_generator.SetSequenceNumber(seq_num);
208 }
Tommi3a5742c2020-05-20 09:32:51 +0200209}
210
211void ModuleRtpRtcpImpl2::SetRtpState(const RtpState& rtp_state) {
212 rtp_sender_->packet_generator.SetRtpState(rtp_state);
Erik Språngbb904972021-08-06 13:10:11 +0200213 if (rtp_sender_->deferred_sequencing_) {
Erik Språng6e2458d2021-08-11 13:34:59 +0200214 MutexLock lock(&rtp_sender_->mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +0200215 rtp_sender_->sequencer_.SetRtpState(rtp_state);
216 }
Tommi3a5742c2020-05-20 09:32:51 +0200217 rtcp_sender_.SetTimestampOffset(rtp_state.start_timestamp);
218}
219
220void ModuleRtpRtcpImpl2::SetRtxState(const RtpState& rtp_state) {
221 rtp_sender_->packet_generator.SetRtxRtpState(rtp_state);
Erik Språngbb904972021-08-06 13:10:11 +0200222 if (rtp_sender_->deferred_sequencing_) {
Erik Språng6e2458d2021-08-11 13:34:59 +0200223 MutexLock lock(&rtp_sender_->mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +0200224 rtp_sender_->sequencer_.set_rtx_sequence_number(rtp_state.sequence_number);
225 }
Tommi3a5742c2020-05-20 09:32:51 +0200226}
227
228RtpState ModuleRtpRtcpImpl2::GetRtpState() const {
229 RtpState state = rtp_sender_->packet_generator.GetRtpState();
Erik Språngbb904972021-08-06 13:10:11 +0200230 if (rtp_sender_->deferred_sequencing_) {
Erik Språng6e2458d2021-08-11 13:34:59 +0200231 MutexLock lock(&rtp_sender_->mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +0200232 rtp_sender_->sequencer_.PopulateRtpState(state);
233 }
Tommi3a5742c2020-05-20 09:32:51 +0200234 return state;
235}
236
237RtpState ModuleRtpRtcpImpl2::GetRtxState() const {
Erik Språngbb904972021-08-06 13:10:11 +0200238 RtpState state = rtp_sender_->packet_generator.GetRtxRtpState();
239 if (rtp_sender_->deferred_sequencing_) {
Erik Språng6e2458d2021-08-11 13:34:59 +0200240 MutexLock lock(&rtp_sender_->mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +0200241 state.sequence_number = rtp_sender_->sequencer_.rtx_sequence_number();
242 }
243 return state;
Tommi3a5742c2020-05-20 09:32:51 +0200244}
245
Ivo Creusen8c40d512021-07-13 12:53:22 +0000246void ModuleRtpRtcpImpl2::SetNonSenderRttMeasurement(bool enabled) {
247 rtcp_sender_.SetNonSenderRttMeasurement(enabled);
248 rtcp_receiver_.SetNonSenderRttMeasurement(enabled);
249}
250
Tommi08be9ba2021-06-15 23:01:57 +0200251uint32_t ModuleRtpRtcpImpl2::local_media_ssrc() const {
252 RTC_DCHECK_RUN_ON(&packet_sequence_checker_);
253 RTC_DCHECK_EQ(rtcp_receiver_.local_media_ssrc(), rtcp_sender_.SSRC());
254 return rtcp_receiver_.local_media_ssrc();
255}
256
Tommi3a5742c2020-05-20 09:32:51 +0200257void ModuleRtpRtcpImpl2::SetRid(const std::string& rid) {
258 if (rtp_sender_) {
259 rtp_sender_->packet_generator.SetRid(rid);
260 }
261}
262
263void ModuleRtpRtcpImpl2::SetMid(const std::string& mid) {
264 if (rtp_sender_) {
265 rtp_sender_->packet_generator.SetMid(mid);
266 }
267 // TODO(bugs.webrtc.org/4050): If we end up supporting the MID SDES item for
268 // RTCP, this will need to be passed down to the RTCPSender also.
269}
270
271void ModuleRtpRtcpImpl2::SetCsrcs(const std::vector<uint32_t>& csrcs) {
272 rtcp_sender_.SetCsrcs(csrcs);
273 rtp_sender_->packet_generator.SetCsrcs(csrcs);
274}
275
276// TODO(pbos): Handle media and RTX streams separately (separate RTCP
277// feedbacks).
278RTCPSender::FeedbackState ModuleRtpRtcpImpl2::GetFeedbackState() {
Tomas Gunnarssona1163742020-06-29 17:41:22 +0200279 // TODO(bugs.webrtc.org/11581): Called by potentially multiple threads.
Tomas Gunnarssonba0ba712020-07-01 08:53:21 +0200280 // Mostly "Send*" methods. Make sure it's only called on the
Tomas Gunnarssona1163742020-06-29 17:41:22 +0200281 // construction thread.
282
Tommi3a5742c2020-05-20 09:32:51 +0200283 RTCPSender::FeedbackState state;
284 // This is called also when receiver_only is true. Hence below
285 // checks that rtp_sender_ exists.
286 if (rtp_sender_) {
287 StreamDataCounters rtp_stats;
288 StreamDataCounters rtx_stats;
289 rtp_sender_->packet_sender.GetDataCounters(&rtp_stats, &rtx_stats);
290 state.packets_sent =
291 rtp_stats.transmitted.packets + rtx_stats.transmitted.packets;
292 state.media_bytes_sent = rtp_stats.transmitted.payload_bytes +
293 rtx_stats.transmitted.payload_bytes;
294 state.send_bitrate =
295 rtp_sender_->packet_sender.GetSendRates().Sum().bps<uint32_t>();
296 }
297 state.receiver = &rtcp_receiver_;
298
Alessio Bazzica79011ef2021-03-10 14:52:35 +0100299 uint32_t received_ntp_secs = 0;
300 uint32_t received_ntp_frac = 0;
301 state.remote_sr = 0;
302 if (rtcp_receiver_.NTP(&received_ntp_secs, &received_ntp_frac,
303 /*rtcp_arrival_time_secs=*/&state.last_rr_ntp_secs,
304 /*rtcp_arrival_time_frac=*/&state.last_rr_ntp_frac,
Alessio Bazzica048adc72021-03-10 15:05:55 +0100305 /*rtcp_timestamp=*/nullptr,
306 /*remote_sender_packet_count=*/nullptr,
307 /*remote_sender_octet_count=*/nullptr,
308 /*remote_sender_reports_count=*/nullptr)) {
Alessio Bazzica79011ef2021-03-10 14:52:35 +0100309 state.remote_sr = ((received_ntp_secs & 0x0000ffff) << 16) +
310 ((received_ntp_frac & 0xffff0000) >> 16);
311 }
Tommi3a5742c2020-05-20 09:32:51 +0200312
313 state.last_xr_rtis = rtcp_receiver_.ConsumeReceivedXrReferenceTimeInfo();
314
315 return state;
316}
317
318// TODO(nisse): This method shouldn't be called for a receive-only
319// stream. Delete rtp_sender_ check as soon as all applications are
320// updated.
321int32_t ModuleRtpRtcpImpl2::SetSendingStatus(const bool sending) {
322 if (rtcp_sender_.Sending() != sending) {
323 // Sends RTCP BYE when going from true to false
Tomas Gunnarssondbcf5d32021-04-23 20:31:08 +0200324 rtcp_sender_.SetSendingStatus(GetFeedbackState(), sending);
Tommi3a5742c2020-05-20 09:32:51 +0200325 }
326 return 0;
327}
328
329bool ModuleRtpRtcpImpl2::Sending() const {
330 return rtcp_sender_.Sending();
331}
332
333// TODO(nisse): This method shouldn't be called for a receive-only
334// stream. Delete rtp_sender_ check as soon as all applications are
335// updated.
336void ModuleRtpRtcpImpl2::SetSendingMediaStatus(const bool sending) {
337 if (rtp_sender_) {
Erik Språngbb904972021-08-06 13:10:11 +0200338 // Turning on or off sending status indicates module being set
339 // up or torn down, detach thread checker since subsequent calls
340 // may be from a different thread.
341 if (rtp_sender_->packet_generator.SendingMedia() != sending) {
342 pacer_thread_checker_.Detach();
343 }
Tommi3a5742c2020-05-20 09:32:51 +0200344 rtp_sender_->packet_generator.SetSendingMediaStatus(sending);
345 } else {
346 RTC_DCHECK(!sending);
347 }
348}
349
350bool ModuleRtpRtcpImpl2::SendingMedia() const {
351 return rtp_sender_ ? rtp_sender_->packet_generator.SendingMedia() : false;
352}
353
354bool ModuleRtpRtcpImpl2::IsAudioConfigured() const {
355 return rtp_sender_ ? rtp_sender_->packet_generator.IsAudioConfigured()
356 : false;
357}
358
359void ModuleRtpRtcpImpl2::SetAsPartOfAllocation(bool part_of_allocation) {
360 RTC_CHECK(rtp_sender_);
361 rtp_sender_->packet_sender.ForceIncludeSendPacketsInAllocation(
362 part_of_allocation);
363}
364
365bool ModuleRtpRtcpImpl2::OnSendingRtpFrame(uint32_t timestamp,
366 int64_t capture_time_ms,
367 int payload_type,
368 bool force_sender_report) {
369 if (!Sending())
370 return false;
371
Markus Handellc6b9ac72021-06-18 13:44:51 +0200372 // TODO(bugs.webrtc.org/12873): Migrate this method and it's users to use
373 // optional Timestamps.
374 absl::optional<Timestamp> capture_time;
375 if (capture_time_ms > 0) {
376 capture_time = Timestamp::Millis(capture_time_ms);
377 }
378 absl::optional<int> payload_type_optional;
379 if (payload_type >= 0)
380 payload_type_optional = payload_type;
381 rtcp_sender_.SetLastRtpTime(timestamp, capture_time, payload_type_optional);
Tommi3a5742c2020-05-20 09:32:51 +0200382 // Make sure an RTCP report isn't queued behind a key frame.
383 if (rtcp_sender_.TimeToSendRTCPReport(force_sender_report))
384 rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
385
386 return true;
387}
388
389bool ModuleRtpRtcpImpl2::TrySendPacket(RtpPacketToSend* packet,
390 const PacedPacketInfo& pacing_info) {
391 RTC_DCHECK(rtp_sender_);
Erik Språngbb904972021-08-06 13:10:11 +0200392 RTC_DCHECK_RUN_ON(&pacer_thread_checker_);
393 if (rtp_sender_->deferred_sequencing_) {
Erik Språng2373bb92021-08-06 15:22:28 +0200394 if (!rtp_sender_->packet_generator.SendingMedia()) {
395 return false;
396 }
Erik Språng6e2458d2021-08-11 13:34:59 +0200397 MutexLock lock(&rtp_sender_->mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +0200398 if (packet->packet_type() == RtpPacketMediaType::kPadding &&
399 packet->Ssrc() == rtp_sender_->packet_generator.SSRC() &&
400 !rtp_sender_->sequencer_.CanSendPaddingOnMediaSsrc()) {
401 // New media packet preempted this generated padding packet, discard it.
402 return false;
403 }
404 bool is_flexfec =
405 packet->packet_type() == RtpPacketMediaType::kForwardErrorCorrection &&
406 packet->Ssrc() == rtp_sender_->packet_generator.FlexfecSsrc();
407 if (!is_flexfec) {
408 rtp_sender_->sequencer_.Sequence(*packet);
409 }
410 } else if (!rtp_sender_->packet_generator.SendingMedia()) {
Tommi3a5742c2020-05-20 09:32:51 +0200411 return false;
412 }
413 rtp_sender_->packet_sender.SendPacket(packet, pacing_info);
414 return true;
415}
416
Erik Språng1d50cb62020-07-02 17:41:32 +0200417void ModuleRtpRtcpImpl2::SetFecProtectionParams(
418 const FecProtectionParams& delta_params,
419 const FecProtectionParams& key_params) {
420 RTC_DCHECK(rtp_sender_);
421 rtp_sender_->packet_sender.SetFecProtectionParameters(delta_params,
422 key_params);
423}
424
425std::vector<std::unique_ptr<RtpPacketToSend>>
426ModuleRtpRtcpImpl2::FetchFecPackets() {
427 RTC_DCHECK(rtp_sender_);
Erik Språngbb904972021-08-06 13:10:11 +0200428 RTC_DCHECK_RUN_ON(&pacer_thread_checker_);
Erik Språng1d50cb62020-07-02 17:41:32 +0200429 auto fec_packets = rtp_sender_->packet_sender.FetchFecPackets();
Erik Språngbb904972021-08-06 13:10:11 +0200430 if (!fec_packets.empty() && !rtp_sender_->deferred_sequencing_) {
431 // Only assign sequence numbers for FEC packets in non-deferred mode, and
432 // never for FlexFEC which has as separate sequence number series.
Erik Språng1d50cb62020-07-02 17:41:32 +0200433 const bool generate_sequence_numbers =
434 !rtp_sender_->packet_sender.FlexFecSsrc().has_value();
435 if (generate_sequence_numbers) {
436 for (auto& fec_packet : fec_packets) {
437 rtp_sender_->packet_generator.AssignSequenceNumber(fec_packet.get());
438 }
439 }
440 }
441 return fec_packets;
442}
443
Tommi3a5742c2020-05-20 09:32:51 +0200444void ModuleRtpRtcpImpl2::OnPacketsAcknowledged(
445 rtc::ArrayView<const uint16_t> sequence_numbers) {
446 RTC_DCHECK(rtp_sender_);
447 rtp_sender_->packet_history.CullAcknowledgedPackets(sequence_numbers);
448}
449
450bool ModuleRtpRtcpImpl2::SupportsPadding() const {
451 RTC_DCHECK(rtp_sender_);
452 return rtp_sender_->packet_generator.SupportsPadding();
453}
454
455bool ModuleRtpRtcpImpl2::SupportsRtxPayloadPadding() const {
456 RTC_DCHECK(rtp_sender_);
457 return rtp_sender_->packet_generator.SupportsRtxPayloadPadding();
458}
459
460std::vector<std::unique_ptr<RtpPacketToSend>>
461ModuleRtpRtcpImpl2::GeneratePadding(size_t target_size_bytes) {
462 RTC_DCHECK(rtp_sender_);
Erik Språngbb904972021-08-06 13:10:11 +0200463 RTC_DCHECK_RUN_ON(&pacer_thread_checker_);
Erik Språng6e2458d2021-08-11 13:34:59 +0200464 MutexLock lock(&rtp_sender_->mutex_sequencer_);
Erik Språngbb904972021-08-06 13:10:11 +0200465
466 // `can_send_padding_on_media_ssrc` set to false when deferred sequencing
467 // is off. It will be ignored in that case, RTPSender will internally query
468 // `sequencer_` while holding the send lock instead.
Tommi3a5742c2020-05-20 09:32:51 +0200469 return rtp_sender_->packet_generator.GeneratePadding(
Erik Språngbfcfe032021-08-04 14:45:32 +0200470 target_size_bytes, rtp_sender_->packet_sender.MediaHasBeenSent(),
Erik Språngbb904972021-08-06 13:10:11 +0200471
472 rtp_sender_->deferred_sequencing_
473 ? rtp_sender_->sequencer_.CanSendPaddingOnMediaSsrc()
474 : false);
Tommi3a5742c2020-05-20 09:32:51 +0200475}
476
477std::vector<RtpSequenceNumberMap::Info>
478ModuleRtpRtcpImpl2::GetSentRtpPacketInfos(
479 rtc::ArrayView<const uint16_t> sequence_numbers) const {
480 RTC_DCHECK(rtp_sender_);
481 return rtp_sender_->packet_sender.GetSentRtpPacketInfos(sequence_numbers);
482}
483
484size_t ModuleRtpRtcpImpl2::ExpectedPerPacketOverhead() const {
485 if (!rtp_sender_) {
486 return 0;
487 }
488 return rtp_sender_->packet_generator.ExpectedPerPacketOverhead();
489}
490
491size_t ModuleRtpRtcpImpl2::MaxRtpPacketSize() const {
492 RTC_DCHECK(rtp_sender_);
493 return rtp_sender_->packet_generator.MaxRtpPacketSize();
494}
495
496void ModuleRtpRtcpImpl2::SetMaxRtpPacketSize(size_t rtp_packet_size) {
497 RTC_DCHECK_LE(rtp_packet_size, IP_PACKET_SIZE)
498 << "rtp packet size too large: " << rtp_packet_size;
499 RTC_DCHECK_GT(rtp_packet_size, packet_overhead_)
500 << "rtp packet size too small: " << rtp_packet_size;
501
502 rtcp_sender_.SetMaxRtpPacketSize(rtp_packet_size);
503 if (rtp_sender_) {
504 rtp_sender_->packet_generator.SetMaxRtpPacketSize(rtp_packet_size);
505 }
506}
507
508RtcpMode ModuleRtpRtcpImpl2::RTCP() const {
509 return rtcp_sender_.Status();
510}
511
512// Configure RTCP status i.e on/off.
513void ModuleRtpRtcpImpl2::SetRTCPStatus(const RtcpMode method) {
514 rtcp_sender_.SetRTCPStatus(method);
515}
516
517int32_t ModuleRtpRtcpImpl2::SetCNAME(const char* c_name) {
518 return rtcp_sender_.SetCNAME(c_name);
519}
520
Tommi3a5742c2020-05-20 09:32:51 +0200521int32_t ModuleRtpRtcpImpl2::RemoteNTP(uint32_t* received_ntpsecs,
522 uint32_t* received_ntpfrac,
523 uint32_t* rtcp_arrival_time_secs,
524 uint32_t* rtcp_arrival_time_frac,
525 uint32_t* rtcp_timestamp) const {
526 return rtcp_receiver_.NTP(received_ntpsecs, received_ntpfrac,
527 rtcp_arrival_time_secs, rtcp_arrival_time_frac,
Alessio Bazzica048adc72021-03-10 15:05:55 +0100528 rtcp_timestamp,
529 /*remote_sender_packet_count=*/nullptr,
530 /*remote_sender_octet_count=*/nullptr,
531 /*remote_sender_reports_count=*/nullptr)
Tommi3a5742c2020-05-20 09:32:51 +0200532 ? 0
533 : -1;
534}
535
Artem Titov913cfa72021-07-28 23:57:33 +0200536// TODO(tommi): Check if `avg_rtt_ms`, `min_rtt_ms`, `max_rtt_ms` params are
Tomas Gunnarssonba0ba712020-07-01 08:53:21 +0200537// actually used in practice (some callers ask for it but don't use it). It
Artem Titov913cfa72021-07-28 23:57:33 +0200538// could be that only `rtt` is needed and if so, then the fast path could be to
Tomas Gunnarssonba0ba712020-07-01 08:53:21 +0200539// just call rtt_ms() and rely on the calculation being done periodically.
Tommi3a5742c2020-05-20 09:32:51 +0200540int32_t ModuleRtpRtcpImpl2::RTT(const uint32_t remote_ssrc,
541 int64_t* rtt,
542 int64_t* avg_rtt,
543 int64_t* min_rtt,
544 int64_t* max_rtt) const {
545 int32_t ret = rtcp_receiver_.RTT(remote_ssrc, rtt, avg_rtt, min_rtt, max_rtt);
546 if (rtt && *rtt == 0) {
547 // Try to get RTT from RtcpRttStats class.
548 *rtt = rtt_ms();
549 }
550 return ret;
551}
552
553int64_t ModuleRtpRtcpImpl2::ExpectedRetransmissionTimeMs() const {
554 int64_t expected_retransmission_time_ms = rtt_ms();
555 if (expected_retransmission_time_ms > 0) {
556 return expected_retransmission_time_ms;
557 }
Artem Titov913cfa72021-07-28 23:57:33 +0200558 // No rtt available (`kRttUpdateInterval` not yet passed?), so try to
Tommi3a5742c2020-05-20 09:32:51 +0200559 // poll avg_rtt_ms directly from rtcp receiver.
560 if (rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), nullptr,
561 &expected_retransmission_time_ms, nullptr,
562 nullptr) == 0) {
563 return expected_retransmission_time_ms;
564 }
565 return kDefaultExpectedRetransmissionTimeMs;
566}
567
568// Force a send of an RTCP packet.
569// Normal SR and RR are triggered via the process function.
570int32_t ModuleRtpRtcpImpl2::SendRTCP(RTCPPacketType packet_type) {
571 return rtcp_sender_.SendRTCP(GetFeedbackState(), packet_type);
572}
573
Tommi3a5742c2020-05-20 09:32:51 +0200574void ModuleRtpRtcpImpl2::GetSendStreamDataCounters(
575 StreamDataCounters* rtp_counters,
576 StreamDataCounters* rtx_counters) const {
577 rtp_sender_->packet_sender.GetDataCounters(rtp_counters, rtx_counters);
578}
579
580// Received RTCP report.
Tommi3a5742c2020-05-20 09:32:51 +0200581std::vector<ReportBlockData> ModuleRtpRtcpImpl2::GetLatestReportBlockData()
582 const {
583 return rtcp_receiver_.GetLatestReportBlockData();
584}
585
Alessio Bazzicabc1c93d2021-03-12 17:45:26 +0100586absl::optional<RtpRtcpInterface::SenderReportStats>
587ModuleRtpRtcpImpl2::GetSenderReportStats() const {
588 SenderReportStats stats;
589 uint32_t remote_timestamp_secs;
590 uint32_t remote_timestamp_frac;
591 uint32_t arrival_timestamp_secs;
592 uint32_t arrival_timestamp_frac;
593 if (rtcp_receiver_.NTP(&remote_timestamp_secs, &remote_timestamp_frac,
594 &arrival_timestamp_secs, &arrival_timestamp_frac,
595 /*rtcp_timestamp=*/nullptr, &stats.packets_sent,
596 &stats.bytes_sent, &stats.reports_count)) {
597 stats.last_remote_timestamp.Set(remote_timestamp_secs,
598 remote_timestamp_frac);
599 stats.last_arrival_timestamp.Set(arrival_timestamp_secs,
600 arrival_timestamp_frac);
601 return stats;
602 }
603 return absl::nullopt;
604}
605
Tommi3a5742c2020-05-20 09:32:51 +0200606// (REMB) Receiver Estimated Max Bitrate.
607void ModuleRtpRtcpImpl2::SetRemb(int64_t bitrate_bps,
608 std::vector<uint32_t> ssrcs) {
609 rtcp_sender_.SetRemb(bitrate_bps, std::move(ssrcs));
610}
611
612void ModuleRtpRtcpImpl2::UnsetRemb() {
613 rtcp_sender_.UnsetRemb();
614}
615
616void ModuleRtpRtcpImpl2::SetExtmapAllowMixed(bool extmap_allow_mixed) {
617 rtp_sender_->packet_generator.SetExtmapAllowMixed(extmap_allow_mixed);
618}
619
Tommi3a5742c2020-05-20 09:32:51 +0200620void ModuleRtpRtcpImpl2::RegisterRtpHeaderExtension(absl::string_view uri,
621 int id) {
622 bool registered =
623 rtp_sender_->packet_generator.RegisterRtpHeaderExtension(uri, id);
624 RTC_CHECK(registered);
625}
626
627int32_t ModuleRtpRtcpImpl2::DeregisterSendRtpHeaderExtension(
628 const RTPExtensionType type) {
629 return rtp_sender_->packet_generator.DeregisterRtpHeaderExtension(type);
630}
631void ModuleRtpRtcpImpl2::DeregisterSendRtpHeaderExtension(
632 absl::string_view uri) {
633 rtp_sender_->packet_generator.DeregisterRtpHeaderExtension(uri);
634}
635
Tommi3a5742c2020-05-20 09:32:51 +0200636void ModuleRtpRtcpImpl2::SetTmmbn(std::vector<rtcp::TmmbItem> bounding_set) {
637 rtcp_sender_.SetTmmbn(std::move(bounding_set));
638}
639
640// Send a Negative acknowledgment packet.
641int32_t ModuleRtpRtcpImpl2::SendNACK(const uint16_t* nack_list,
642 const uint16_t size) {
643 uint16_t nack_length = size;
644 uint16_t start_id = 0;
645 int64_t now_ms = clock_->TimeInMilliseconds();
646 if (TimeToSendFullNackList(now_ms)) {
647 nack_last_time_sent_full_ms_ = now_ms;
648 } else {
649 // Only send extended list.
650 if (nack_last_seq_number_sent_ == nack_list[size - 1]) {
651 // Last sequence number is the same, do not send list.
652 return 0;
653 }
654 // Send new sequence numbers.
655 for (int i = 0; i < size; ++i) {
656 if (nack_last_seq_number_sent_ == nack_list[i]) {
657 start_id = i + 1;
658 break;
659 }
660 }
661 nack_length = size - start_id;
662 }
663
664 // Our RTCP NACK implementation is limited to kRtcpMaxNackFields sequence
665 // numbers per RTCP packet.
666 if (nack_length > kRtcpMaxNackFields) {
667 nack_length = kRtcpMaxNackFields;
668 }
669 nack_last_seq_number_sent_ = nack_list[start_id + nack_length - 1];
670
671 return rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, nack_length,
672 &nack_list[start_id]);
673}
674
675void ModuleRtpRtcpImpl2::SendNack(
676 const std::vector<uint16_t>& sequence_numbers) {
677 rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, sequence_numbers.size(),
678 sequence_numbers.data());
679}
680
681bool ModuleRtpRtcpImpl2::TimeToSendFullNackList(int64_t now) const {
682 // Use RTT from RtcpRttStats class if provided.
683 int64_t rtt = rtt_ms();
684 if (rtt == 0) {
685 rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
686 }
687
688 const int64_t kStartUpRttMs = 100;
689 int64_t wait_time = 5 + ((rtt * 3) >> 1); // 5 + RTT * 1.5.
690 if (rtt == 0) {
691 wait_time = kStartUpRttMs;
692 }
693
Artem Titov913cfa72021-07-28 23:57:33 +0200694 // Send a full NACK list once within every `wait_time`.
Tommi3a5742c2020-05-20 09:32:51 +0200695 return now - nack_last_time_sent_full_ms_ > wait_time;
696}
697
698// Store the sent packets, needed to answer to Negative acknowledgment requests.
699void ModuleRtpRtcpImpl2::SetStorePacketsStatus(const bool enable,
700 const uint16_t number_to_store) {
701 rtp_sender_->packet_history.SetStorePacketsStatus(
702 enable ? RtpPacketHistory::StorageMode::kStoreAndCull
703 : RtpPacketHistory::StorageMode::kDisabled,
704 number_to_store);
705}
706
707bool ModuleRtpRtcpImpl2::StorePackets() const {
708 return rtp_sender_->packet_history.GetStorageMode() !=
709 RtpPacketHistory::StorageMode::kDisabled;
710}
711
712void ModuleRtpRtcpImpl2::SendCombinedRtcpPacket(
713 std::vector<std::unique_ptr<rtcp::RtcpPacket>> rtcp_packets) {
714 rtcp_sender_.SendCombinedRtcpPacket(std::move(rtcp_packets));
715}
716
717int32_t ModuleRtpRtcpImpl2::SendLossNotification(uint16_t last_decoded_seq_num,
718 uint16_t last_received_seq_num,
719 bool decodability_flag,
720 bool buffering_allowed) {
721 return rtcp_sender_.SendLossNotification(
722 GetFeedbackState(), last_decoded_seq_num, last_received_seq_num,
723 decodability_flag, buffering_allowed);
724}
725
726void ModuleRtpRtcpImpl2::SetRemoteSSRC(const uint32_t ssrc) {
727 // Inform about the incoming SSRC.
728 rtcp_sender_.SetRemoteSSRC(ssrc);
729 rtcp_receiver_.SetRemoteSSRC(ssrc);
730}
731
Tommi08be9ba2021-06-15 23:01:57 +0200732void ModuleRtpRtcpImpl2::SetLocalSsrc(uint32_t local_ssrc) {
733 RTC_DCHECK_RUN_ON(&packet_sequence_checker_);
734 rtcp_receiver_.set_local_media_ssrc(local_ssrc);
735 rtcp_sender_.SetSsrc(local_ssrc);
736}
737
Tommi3a5742c2020-05-20 09:32:51 +0200738RtpSendRates ModuleRtpRtcpImpl2::GetSendRates() const {
Tommi1050fbc2021-06-03 17:58:28 +0200739 // Typically called on the `rtp_transport_queue_` owned by an
740 // RtpTransportControllerSendInterface instance.
Tommi3a5742c2020-05-20 09:32:51 +0200741 return rtp_sender_->packet_sender.GetSendRates();
742}
743
744void ModuleRtpRtcpImpl2::OnRequestSendReport() {
745 SendRTCP(kRtcpSr);
746}
747
748void ModuleRtpRtcpImpl2::OnReceivedNack(
749 const std::vector<uint16_t>& nack_sequence_numbers) {
750 if (!rtp_sender_)
751 return;
752
753 if (!StorePackets() || nack_sequence_numbers.empty()) {
754 return;
755 }
756 // Use RTT from RtcpRttStats class if provided.
757 int64_t rtt = rtt_ms();
758 if (rtt == 0) {
759 rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
760 }
761 rtp_sender_->packet_generator.OnReceivedNack(nack_sequence_numbers, rtt);
762}
763
764void ModuleRtpRtcpImpl2::OnReceivedRtcpReportBlocks(
765 const ReportBlockList& report_blocks) {
766 if (rtp_sender_) {
767 uint32_t ssrc = SSRC();
768 absl::optional<uint32_t> rtx_ssrc;
769 if (rtp_sender_->packet_generator.RtxStatus() != kRtxOff) {
770 rtx_ssrc = rtp_sender_->packet_generator.RtxSsrc();
771 }
772
773 for (const RTCPReportBlock& report_block : report_blocks) {
774 if (ssrc == report_block.source_ssrc) {
775 rtp_sender_->packet_generator.OnReceivedAckOnSsrc(
776 report_block.extended_highest_sequence_number);
777 } else if (rtx_ssrc && *rtx_ssrc == report_block.source_ssrc) {
778 rtp_sender_->packet_generator.OnReceivedAckOnRtxSsrc(
779 report_block.extended_highest_sequence_number);
780 }
781 }
782 }
783}
784
Tommi3a5742c2020-05-20 09:32:51 +0200785void ModuleRtpRtcpImpl2::set_rtt_ms(int64_t rtt_ms) {
Tomas Gunnarssonba0ba712020-07-01 08:53:21 +0200786 RTC_DCHECK_RUN_ON(worker_queue_);
Tommi3a5742c2020-05-20 09:32:51 +0200787 {
Markus Handellf7303e62020-07-09 01:34:42 +0200788 MutexLock lock(&mutex_rtt_);
Tommi3a5742c2020-05-20 09:32:51 +0200789 rtt_ms_ = rtt_ms;
790 }
791 if (rtp_sender_) {
792 rtp_sender_->packet_history.SetRtt(rtt_ms);
793 }
794}
795
796int64_t ModuleRtpRtcpImpl2::rtt_ms() const {
Markus Handellf7303e62020-07-09 01:34:42 +0200797 MutexLock lock(&mutex_rtt_);
Tommi3a5742c2020-05-20 09:32:51 +0200798 return rtt_ms_;
799}
800
801void ModuleRtpRtcpImpl2::SetVideoBitrateAllocation(
802 const VideoBitrateAllocation& bitrate) {
803 rtcp_sender_.SetVideoBitrateAllocation(bitrate);
804}
805
806RTPSender* ModuleRtpRtcpImpl2::RtpSender() {
807 return rtp_sender_ ? &rtp_sender_->packet_generator : nullptr;
808}
809
810const RTPSender* ModuleRtpRtcpImpl2::RtpSender() const {
811 return rtp_sender_ ? &rtp_sender_->packet_generator : nullptr;
812}
813
Tomas Gunnarssonba0ba712020-07-01 08:53:21 +0200814void ModuleRtpRtcpImpl2::PeriodicUpdate() {
815 RTC_DCHECK_RUN_ON(worker_queue_);
816
817 Timestamp check_since = clock_->CurrentTime() - kRttUpdateInterval;
818 absl::optional<TimeDelta> rtt =
819 rtcp_receiver_.OnPeriodicRttUpdate(check_since, rtcp_sender_.Sending());
820 if (rtt) {
Ivo Creusen8c40d512021-07-13 12:53:22 +0000821 if (rtt_stats_) {
822 rtt_stats_->OnRttUpdate(rtt->ms());
823 }
Tomas Gunnarssonba0ba712020-07-01 08:53:21 +0200824 set_rtt_ms(rtt->ms());
825 }
Tomas Gunnarssonba0ba712020-07-01 08:53:21 +0200826}
827
Markus Handell885d5382021-06-21 18:57:36 +0200828// RTC_RUN_ON(worker_queue_);
829void ModuleRtpRtcpImpl2::MaybeSendRtcp() {
830 if (rtcp_sender_.TimeToSendRTCPReport())
831 rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
832}
833
834// TODO(bugs.webrtc.org/12889): Consider removing this function when the issue
835// is resolved.
836// RTC_RUN_ON(worker_queue_);
837void ModuleRtpRtcpImpl2::MaybeSendRtcpAtOrAfterTimestamp(
838 Timestamp execution_time) {
839 Timestamp now = clock_->CurrentTime();
840 if (now >= execution_time) {
841 MaybeSendRtcp();
842 return;
843 }
844
845 RTC_DLOG(LS_WARNING)
846 << "BUGBUG: Task queue scheduled delayed call too early.";
847
848 ScheduleMaybeSendRtcpAtOrAfterTimestamp(execution_time, execution_time - now);
849}
850
851void ModuleRtpRtcpImpl2::ScheduleRtcpSendEvaluation(TimeDelta duration) {
852 // We end up here under various sequences including the worker queue, and
853 // the RTCPSender lock is held.
854 // We're assuming that the fact that RTCPSender executes under other sequences
855 // than the worker queue on which it's created on implies that external
856 // synchronization is present and removes this activity before destruction.
857 if (duration.IsZero()) {
858 worker_queue_->PostTask(ToQueuedTask(task_safety_, [this] {
859 RTC_DCHECK_RUN_ON(worker_queue_);
860 MaybeSendRtcp();
861 }));
862 } else {
863 Timestamp execution_time = clock_->CurrentTime() + duration;
864 ScheduleMaybeSendRtcpAtOrAfterTimestamp(execution_time, duration);
865 }
866}
867
868void ModuleRtpRtcpImpl2::ScheduleMaybeSendRtcpAtOrAfterTimestamp(
869 Timestamp execution_time,
870 TimeDelta duration) {
871 // We end up here under various sequences including the worker queue, and
872 // the RTCPSender lock is held.
Artem Titov913cfa72021-07-28 23:57:33 +0200873 // See note in ScheduleRtcpSendEvaluation about why `worker_queue_` can be
Markus Handell885d5382021-06-21 18:57:36 +0200874 // accessed.
875 worker_queue_->PostDelayedTask(
876 ToQueuedTask(task_safety_,
877 [this, execution_time] {
878 RTC_DCHECK_RUN_ON(worker_queue_);
879 MaybeSendRtcpAtOrAfterTimestamp(execution_time);
880 }),
881 DelayMillisForDuration(duration));
882}
883
Tommi3a5742c2020-05-20 09:32:51 +0200884} // namespace webrtc