blob: 18334e2a4afc6640fa1d13dccf37151ac2d121ad [file] [log] [blame]
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +00001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/pacing/paced_sender.h"
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +000012
jbauchd2a22962016-02-08 23:18:25 -080013#include <algorithm>
Sebastian Jansson916ae082018-10-26 13:10:23 +020014#include <utility>
Erik Språngf6468d22019-07-05 16:53:43 +020015#include <vector>
pbos@webrtc.org03c817e2014-07-07 10:20:35 +000016
Karl Wiberg918f50c2018-07-05 11:40:33 +020017#include "absl/memory/memory.h"
Yves Gerey988cc082018-10-23 12:03:01 +020018#include "logging/rtc_event_log/rtc_event_log.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "modules/pacing/bitrate_prober.h"
20#include "modules/pacing/interval_budget.h"
21#include "modules/utility/include/process_thread.h"
22#include "rtc_base/checks.h"
23#include "rtc_base/logging.h"
24#include "system_wrappers/include/clock.h"
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +000025
Per Kjellander7ef34f82019-02-22 13:09:32 +010026namespace webrtc {
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +000027namespace {
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +000028// Time limit in milliseconds between packet bursts.
Christoffer Rodbroe2e00002018-12-20 15:46:03 +010029const int64_t kDefaultMinPacketLimitMs = 5;
Sebastian Jansson45d9c1d2018-03-09 12:48:01 +010030const int64_t kCongestedPacketIntervalMs = 500;
31const int64_t kPausedProcessIntervalMs = kCongestedPacketIntervalMs;
Sebastian Janssone5d8c572018-02-28 08:53:06 +010032const int64_t kMaxElapsedTimeMs = 2000;
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +000033
34// Upper cap on process interval, in case process has not been called in a long
35// time.
pkasting@chromium.org0b1534c2014-12-15 22:09:40 +000036const int64_t kMaxIntervalTimeMs = 30;
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +000037
Per Kjellander7ef34f82019-02-22 13:09:32 +010038bool IsDisabled(const WebRtcKeyValueConfig& field_trials,
39 absl::string_view key) {
40 return field_trials.Lookup(key).find("Disabled") == 0;
41}
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +000042
Per Kjellander7ef34f82019-02-22 13:09:32 +010043bool IsEnabled(const WebRtcKeyValueConfig& field_trials,
44 absl::string_view key) {
45 return field_trials.Lookup(key).find("Enabled") == 0;
46}
47
Erik Språng58ee1872019-06-18 16:20:11 +020048int GetPriorityForType(RtpPacketToSend::Type type) {
49 switch (type) {
50 case RtpPacketToSend::Type::kAudio:
51 // Audio is always prioritized over other packet types.
52 return 0;
53 case RtpPacketToSend::Type::kRetransmission:
54 // Send retransmissions before new media.
55 return 1;
56 case RtpPacketToSend::Type::kVideo:
57 // Video has "normal" priority, in the old speak.
58 return 2;
59 case RtpPacketToSend::Type::kForwardErrorCorrection:
Erik Språng97b6c752019-07-25 09:16:34 +020060 // Send redundancy concurrently to video. If it is delayed it might have a
61 // lower chance of being useful.
62 return 2;
Erik Språng58ee1872019-06-18 16:20:11 +020063 case RtpPacketToSend::Type::kPadding:
64 // Packets that are in themselves likely useless, only sent to keep the
65 // BWE high.
Erik Språng97b6c752019-07-25 09:16:34 +020066 return 3;
Erik Språng58ee1872019-06-18 16:20:11 +020067 }
68}
69
Per Kjellander7ef34f82019-02-22 13:09:32 +010070} // namespace
sprang0a43fef2015-11-20 09:00:37 -080071const int64_t PacedSender::kMaxQueueLengthMs = 2000;
Sebastian Janssonea86bb72018-02-14 16:53:38 +000072const float PacedSender::kDefaultPaceMultiplier = 2.5f;
stefan@webrtc.org88e0dda2014-07-04 09:20:42 +000073
Sebastian Janssonaa01f272019-01-30 11:28:59 +010074PacedSender::PacedSender(Clock* clock,
Erik Språnge7942432019-06-12 13:30:02 +020075 PacketRouter* packet_router,
Per Kjellander7ef34f82019-02-22 13:09:32 +010076 RtcEventLog* event_log,
77 const WebRtcKeyValueConfig* field_trials)
stefan@webrtc.org88e0dda2014-07-04 09:20:42 +000078 : clock_(clock),
Erik Språnge7942432019-06-12 13:30:02 +020079 packet_router_(packet_router),
Per Kjellander5b698732019-04-15 12:36:33 +020080 fallback_field_trials_(
81 !field_trials ? absl::make_unique<FieldTrialBasedConfig>() : nullptr),
82 field_trials_(field_trials ? field_trials : fallback_field_trials_.get()),
Per Kjellander5b698732019-04-15 12:36:33 +020083 drain_large_queues_(
84 !IsDisabled(*field_trials_, "WebRTC-Pacer-DrainQueue")),
Sebastian Janssonc235a8d2018-06-15 14:46:11 +020085 send_padding_if_silent_(
Per Kjellander5b698732019-04-15 12:36:33 +020086 IsEnabled(*field_trials_, "WebRTC-Pacer-PadInSilence")),
87 pace_audio_(!IsDisabled(*field_trials_, "WebRTC-Pacer-BlockAudio")),
Christoffer Rodbroe2e00002018-12-20 15:46:03 +010088 min_packet_limit_ms_("", kDefaultMinPacketLimitMs),
Erik Språng96816752018-09-04 18:40:19 +020089 last_timestamp_ms_(clock_->TimeInMilliseconds()),
pwestin@webrtc.orgdb418562013-03-22 23:39:29 +000090 paused_(false),
Sebastian Jansson03914462018-10-11 20:22:03 +020091 media_budget_(0),
92 padding_budget_(0),
Per Kjellander5b698732019-04-15 12:36:33 +020093 prober_(*field_trials_),
philipelb61927c2017-02-28 07:05:23 -080094 probing_send_failure_(false),
perkjec81bcd2016-05-11 06:01:13 -070095 pacing_bitrate_kbps_(0),
Sebastian Janssona1630f82018-02-21 13:39:26 +010096 time_last_process_us_(clock->TimeInMicroseconds()),
97 last_send_time_us_(clock->TimeInMicroseconds()),
asaperssonfc5e81c2017-04-19 23:28:53 -070098 first_sent_packet_ms_(-1),
Sebastian Jansson2560e2e2018-10-11 20:17:22 +020099 packets_(clock->TimeInMicroseconds()),
sprang89c4a7e2017-06-30 13:27:40 -0700100 packet_counter_(0),
Alex Narest78609d52017-10-20 10:37:47 +0200101 queue_time_limit(kMaxQueueLengthMs),
Erik Språngf6468d22019-07-05 16:53:43 +0200102 account_for_audio_(false),
103 legacy_packet_referencing_(
Erik Språngc4f047d2019-07-19 13:34:11 +0200104 IsEnabled(*field_trials_, "WebRTC-Pacer-LegacyPacketReferencing")) {
Christoffer Rodbroe2e00002018-12-20 15:46:03 +0100105 if (!drain_large_queues_) {
Sebastian Jansson0601d682018-06-25 19:23:05 +0200106 RTC_LOG(LS_WARNING) << "Pacer queues will not be drained,"
107 "pushback experiment must be enabled.";
Christoffer Rodbroe2e00002018-12-20 15:46:03 +0100108 }
109 ParseFieldTrial({&min_packet_limit_ms_},
Per Kjellander5b698732019-04-15 12:36:33 +0200110 field_trials_->Lookup("WebRTC-Pacer-MinPacketLimitMs"));
Christoffer Rodbroe2e00002018-12-20 15:46:03 +0100111 UpdateBudgetWithElapsedTime(min_packet_limit_ms_);
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000112}
113
stefan@webrtc.org89fd1e82014-07-15 16:40:38 +0000114PacedSender::~PacedSender() {}
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000115
Piotr (Peter) Slatalac39f4622019-02-15 07:38:04 -0800116void PacedSender::CreateProbeCluster(int bitrate_bps, int cluster_id) {
kthelgason6bfe49c2017-03-30 01:14:41 -0700117 rtc::CritScope cs(&critsect_);
Piotr (Peter) Slatalac39f4622019-02-15 07:38:04 -0800118 prober_.CreateProbeCluster(bitrate_bps, TimeMilliseconds(), cluster_id);
philipeleb680ea2016-08-17 11:11:59 +0200119}
120
pwestin@webrtc.orgdb418562013-03-22 23:39:29 +0000121void PacedSender::Pause() {
tommi919dce22017-03-15 07:45:36 -0700122 {
kthelgason6bfe49c2017-03-30 01:14:41 -0700123 rtc::CritScope cs(&critsect_);
stefan9e117c5e12017-08-16 08:16:25 -0700124 if (!paused_)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100125 RTC_LOG(LS_INFO) << "PacedSender paused.";
tommi919dce22017-03-15 07:45:36 -0700126 paused_ = true;
Sebastian Jansson60570dc2018-09-13 17:11:06 +0200127 packets_.SetPauseState(true, TimeMilliseconds());
tommi919dce22017-03-15 07:45:36 -0700128 }
Sebastian Jansson439f0bc2018-02-20 10:46:39 +0100129 rtc::CritScope cs(&process_thread_lock_);
tommi919dce22017-03-15 07:45:36 -0700130 // Tell the process thread to call our TimeUntilNextProcess() method to get
131 // a new (longer) estimate for when to call Process().
132 if (process_thread_)
133 process_thread_->WakeUp(this);
pwestin@webrtc.orgdb418562013-03-22 23:39:29 +0000134}
135
136void PacedSender::Resume() {
tommi919dce22017-03-15 07:45:36 -0700137 {
kthelgason6bfe49c2017-03-30 01:14:41 -0700138 rtc::CritScope cs(&critsect_);
stefan9e117c5e12017-08-16 08:16:25 -0700139 if (paused_)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100140 RTC_LOG(LS_INFO) << "PacedSender resumed.";
tommi919dce22017-03-15 07:45:36 -0700141 paused_ = false;
Sebastian Jansson60570dc2018-09-13 17:11:06 +0200142 packets_.SetPauseState(false, TimeMilliseconds());
tommi919dce22017-03-15 07:45:36 -0700143 }
Sebastian Jansson439f0bc2018-02-20 10:46:39 +0100144 rtc::CritScope cs(&process_thread_lock_);
tommi919dce22017-03-15 07:45:36 -0700145 // Tell the process thread to call our TimeUntilNextProcess() method to
146 // refresh the estimate for when to call Process().
147 if (process_thread_)
148 process_thread_->WakeUp(this);
pwestin@webrtc.orgdb418562013-03-22 23:39:29 +0000149}
150
Sebastian Jansson45d9c1d2018-03-09 12:48:01 +0100151void PacedSender::SetCongestionWindow(int64_t congestion_window_bytes) {
152 rtc::CritScope cs(&critsect_);
153 congestion_window_bytes_ = congestion_window_bytes;
154}
155
156void PacedSender::UpdateOutstandingData(int64_t outstanding_bytes) {
157 rtc::CritScope cs(&critsect_);
158 outstanding_bytes_ = outstanding_bytes;
159}
160
161bool PacedSender::Congested() const {
162 if (congestion_window_bytes_ == kNoCongestionWindow)
163 return false;
164 return outstanding_bytes_ >= congestion_window_bytes_;
165}
166
Erik Språng96816752018-09-04 18:40:19 +0200167int64_t PacedSender::TimeMilliseconds() const {
168 int64_t time_ms = clock_->TimeInMilliseconds();
169 if (time_ms < last_timestamp_ms_) {
170 RTC_LOG(LS_WARNING)
171 << "Non-monotonic clock behavior observed. Previous timestamp: "
172 << last_timestamp_ms_ << ", new timestamp: " << time_ms;
173 RTC_DCHECK_GE(time_ms, last_timestamp_ms_);
174 time_ms = last_timestamp_ms_;
175 }
176 last_timestamp_ms_ = time_ms;
177 return time_ms;
178}
179
stefan@webrtc.orge9f0f592015-02-16 15:47:51 +0000180void PacedSender::SetProbingEnabled(bool enabled) {
kthelgason6bfe49c2017-03-30 01:14:41 -0700181 rtc::CritScope cs(&critsect_);
Elad Alon44b1fa42017-10-17 14:17:54 +0200182 RTC_CHECK_EQ(0, packet_counter_);
Sebastian Jansson03914462018-10-11 20:22:03 +0200183 prober_.SetEnabled(enabled);
stefan@webrtc.orge9f0f592015-02-16 15:47:51 +0000184}
185
Sebastian Jansson439f0bc2018-02-20 10:46:39 +0100186void PacedSender::SetPacingRates(uint32_t pacing_rate_bps,
187 uint32_t padding_rate_bps) {
188 rtc::CritScope cs(&critsect_);
189 RTC_DCHECK(pacing_rate_bps > 0);
190 pacing_bitrate_kbps_ = pacing_rate_bps / 1000;
Sebastian Jansson03914462018-10-11 20:22:03 +0200191 padding_budget_.set_target_rate_kbps(padding_rate_bps / 1000);
Evan Shrubsolefee13e82019-02-26 15:25:52 +0100192
193 RTC_LOG(LS_VERBOSE) << "bwe:pacer_updated pacing_kbps="
194 << pacing_bitrate_kbps_
195 << " padding_budget_kbps=" << padding_rate_bps / 1000;
Sebastian Jansson439f0bc2018-02-20 10:46:39 +0100196}
197
Peter Boströme23e7372015-10-08 11:44:14 +0200198void PacedSender::InsertPacket(RtpPacketSender::Priority priority,
199 uint32_t ssrc,
200 uint16_t sequence_number,
201 int64_t capture_time_ms,
202 size_t bytes,
203 bool retransmission) {
kthelgason6bfe49c2017-03-30 01:14:41 -0700204 rtc::CritScope cs(&critsect_);
Sebastian Jansson439f0bc2018-02-20 10:46:39 +0100205 RTC_DCHECK(pacing_bitrate_kbps_ > 0)
206 << "SetPacingRate must be called before InsertPacket.";
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000207
Erik Språng96816752018-09-04 18:40:19 +0200208 int64_t now_ms = TimeMilliseconds();
Sebastian Jansson03914462018-10-11 20:22:03 +0200209 prober_.OnIncomingPacket(bytes);
Peter Boström0453ef82016-02-16 16:23:08 +0100210
sprang0a43fef2015-11-20 09:00:37 -0800211 if (capture_time_ms < 0)
Erik Språngad113e52015-11-26 16:26:12 +0100212 capture_time_ms = now_ms;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000213
Erik Språng58ee1872019-06-18 16:20:11 +0200214 RtpPacketToSend::Type type;
215 switch (priority) {
Erik Språngaa59eca2019-07-24 14:52:55 +0200216 case RtpPacketSender::kHighPriority:
Erik Språng58ee1872019-06-18 16:20:11 +0200217 type = RtpPacketToSend::Type::kAudio;
218 break;
Erik Språngaa59eca2019-07-24 14:52:55 +0200219 case RtpPacketSender::kNormalPriority:
Erik Språng58ee1872019-06-18 16:20:11 +0200220 type = RtpPacketToSend::Type::kRetransmission;
221 break;
222 default:
223 type = RtpPacketToSend::Type::kVideo;
224 }
225 packets_.Push(GetPriorityForType(type), type, ssrc, sequence_number,
226 capture_time_ms, now_ms, bytes, retransmission,
227 packet_counter_++);
228}
229
230void PacedSender::EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet) {
231 rtc::CritScope cs(&critsect_);
232 RTC_DCHECK(pacing_bitrate_kbps_ > 0)
233 << "SetPacingRate must be called before InsertPacket.";
234
235 int64_t now_ms = TimeMilliseconds();
236 prober_.OnIncomingPacket(packet->payload_size());
237
238 if (packet->capture_time_ms() < 0) {
239 packet->set_capture_time_ms(now_ms);
240 }
241
242 RTC_CHECK(packet->packet_type());
243 int priority = GetPriorityForType(*packet->packet_type());
244 packets_.Push(priority, now_ms, packet_counter_++, std::move(packet));
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000245}
246
Alex Narest78609d52017-10-20 10:37:47 +0200247void PacedSender::SetAccountForAudioPackets(bool account_for_audio) {
248 rtc::CritScope cs(&critsect_);
249 account_for_audio_ = account_for_audio;
250}
251
pkasting@chromium.org2656bf82014-11-17 22:21:14 +0000252int64_t PacedSender::ExpectedQueueTimeMs() const {
kthelgason6bfe49c2017-03-30 01:14:41 -0700253 rtc::CritScope cs(&critsect_);
kwibergaf476c72016-11-28 15:21:39 -0800254 RTC_DCHECK_GT(pacing_bitrate_kbps_, 0);
Sebastian Jansson60570dc2018-09-13 17:11:06 +0200255 return static_cast<int64_t>(packets_.SizeInBytes() * 8 /
perkjec81bcd2016-05-11 06:01:13 -0700256 pacing_bitrate_kbps_);
stefan@webrtc.orgbfacda62013-03-27 16:36:01 +0000257}
258
stefan@webrtc.org82462aa2014-10-23 11:57:05 +0000259size_t PacedSender::QueueSizePackets() const {
kthelgason6bfe49c2017-03-30 01:14:41 -0700260 rtc::CritScope cs(&critsect_);
Sebastian Jansson60570dc2018-09-13 17:11:06 +0200261 return packets_.SizeInPackets();
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000262}
263
Christoffer Rodbroc610e262019-01-08 10:49:19 +0100264int64_t PacedSender::QueueSizeBytes() const {
265 rtc::CritScope cs(&critsect_);
266 return packets_.SizeInBytes();
267}
268
asaperssonfc5e81c2017-04-19 23:28:53 -0700269int64_t PacedSender::FirstSentPacketTimeMs() const {
270 rtc::CritScope cs(&critsect_);
271 return first_sent_packet_ms_;
272}
273
pkasting@chromium.org0b1534c2014-12-15 22:09:40 +0000274int64_t PacedSender::QueueInMs() const {
kthelgason6bfe49c2017-03-30 01:14:41 -0700275 rtc::CritScope cs(&critsect_);
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000276
Sebastian Jansson60570dc2018-09-13 17:11:06 +0200277 int64_t oldest_packet = packets_.OldestEnqueueTimeMs();
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000278 if (oldest_packet == 0)
279 return 0;
280
Erik Språng96816752018-09-04 18:40:19 +0200281 return TimeMilliseconds() - oldest_packet;
stefan@webrtc.org82462aa2014-10-23 11:57:05 +0000282}
283
pkasting@chromium.org0b1534c2014-12-15 22:09:40 +0000284int64_t PacedSender::TimeUntilNextProcess() {
kthelgason6bfe49c2017-03-30 01:14:41 -0700285 rtc::CritScope cs(&critsect_);
Sebastian Janssona1630f82018-02-21 13:39:26 +0100286 int64_t elapsed_time_us =
287 clock_->TimeInMicroseconds() - time_last_process_us_;
stefan9e117c5e12017-08-16 08:16:25 -0700288 int64_t elapsed_time_ms = (elapsed_time_us + 500) / 1000;
289 // When paused we wake up every 500 ms to send a padding packet to ensure
290 // we won't get stuck in the paused state due to no feedback being received.
tommi919dce22017-03-15 07:45:36 -0700291 if (paused_)
Sebastian Jansson45d9c1d2018-03-09 12:48:01 +0100292 return std::max<int64_t>(kPausedProcessIntervalMs - elapsed_time_ms, 0);
tommi919dce22017-03-15 07:45:36 -0700293
Sebastian Jansson03914462018-10-11 20:22:03 +0200294 if (prober_.IsProbing()) {
295 int64_t ret = prober_.TimeUntilNextProbe(TimeMilliseconds());
philipelb61927c2017-02-28 07:05:23 -0800296 if (ret > 0 || (ret == 0 && !probing_send_failure_))
stefan@webrtc.orge9f0f592015-02-16 15:47:51 +0000297 return ret;
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000298 }
Christoffer Rodbroe2e00002018-12-20 15:46:03 +0100299 return std::max<int64_t>(min_packet_limit_ms_ - elapsed_time_ms, 0);
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000300}
301
Sebastian Jansson916ae082018-10-26 13:10:23 +0200302int64_t PacedSender::UpdateTimeAndGetElapsedMs(int64_t now_us) {
Sebastian Janssonb544f6c2018-06-04 19:02:41 +0200303 int64_t elapsed_time_ms = (now_us - time_last_process_us_ + 500) / 1000;
Sebastian Janssona1630f82018-02-21 13:39:26 +0100304 time_last_process_us_ = now_us;
Sebastian Janssone5d8c572018-02-28 08:53:06 +0100305 if (elapsed_time_ms > kMaxElapsedTimeMs) {
306 RTC_LOG(LS_WARNING) << "Elapsed time (" << elapsed_time_ms
307 << " ms) longer than expected, limiting to "
308 << kMaxElapsedTimeMs << " ms";
309 elapsed_time_ms = kMaxElapsedTimeMs;
310 }
Sebastian Jansson916ae082018-10-26 13:10:23 +0200311 return elapsed_time_ms;
312}
313
314bool PacedSender::ShouldSendKeepalive(int64_t now_us) const {
Sebastian Janssonc235a8d2018-06-15 14:46:11 +0200315 if (send_padding_if_silent_ || paused_ || Congested()) {
316 // We send a padding packet every 500 ms to ensure we won't get stuck in
317 // congested state due to no feedback being received.
Sebastian Janssonb544f6c2018-06-04 19:02:41 +0200318 int64_t elapsed_since_last_send_us = now_us - last_send_time_us_;
319 if (elapsed_since_last_send_us >= kCongestedPacketIntervalMs * 1000) {
Sebastian Jansson682c6492018-04-12 13:08:22 +0200320 // We can not send padding unless a normal packet has first been sent. If
321 // we do, timestamps get messed up.
322 if (packet_counter_ > 0) {
Sebastian Jansson916ae082018-10-26 13:10:23 +0200323 return true;
Sebastian Jansson682c6492018-04-12 13:08:22 +0200324 }
Sebastian Janssona1630f82018-02-21 13:39:26 +0100325 }
stefan9e117c5e12017-08-16 08:16:25 -0700326 }
Sebastian Jansson916ae082018-10-26 13:10:23 +0200327 return false;
328}
329
330void PacedSender::Process() {
331 rtc::CritScope cs(&critsect_);
332 int64_t now_us = clock_->TimeInMicroseconds();
333 int64_t elapsed_time_ms = UpdateTimeAndGetElapsedMs(now_us);
334 if (ShouldSendKeepalive(now_us)) {
Erik Språngf6468d22019-07-05 16:53:43 +0200335 if (legacy_packet_referencing_) {
336 critsect_.Leave();
337 size_t bytes_sent =
338 packet_router_->TimeToSendPadding(1, PacedPacketInfo());
339 critsect_.Enter();
340 OnPaddingSent(bytes_sent);
341 } else {
Erik Språngb88fd312019-07-15 19:28:31 +0200342 size_t keepalive_bytes_sent = 0;
Erik Språngf6468d22019-07-05 16:53:43 +0200343 critsect_.Leave();
344 std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets =
345 packet_router_->GeneratePadding(1);
Erik Språngf6468d22019-07-05 16:53:43 +0200346 for (auto& packet : keepalive_packets) {
Erik Språngb88fd312019-07-15 19:28:31 +0200347 keepalive_bytes_sent += packet->payload_size() + packet->padding_size();
348 packet_router_->SendPacket(std::move(packet), PacedPacketInfo());
Erik Språngf6468d22019-07-05 16:53:43 +0200349 }
Erik Språngb88fd312019-07-15 19:28:31 +0200350 critsect_.Enter();
351 OnPaddingSent(keepalive_bytes_sent);
Erik Språngf6468d22019-07-05 16:53:43 +0200352 }
Sebastian Jansson916ae082018-10-26 13:10:23 +0200353 }
354
Sebastian Janssonc235a8d2018-06-15 14:46:11 +0200355 if (paused_)
356 return;
stefan9e117c5e12017-08-16 08:16:25 -0700357
358 if (elapsed_time_ms > 0) {
Sebastian Janssonc235a8d2018-06-15 14:46:11 +0200359 int target_bitrate_kbps = pacing_bitrate_kbps_;
Sebastian Jansson60570dc2018-09-13 17:11:06 +0200360 size_t queue_size_bytes = packets_.SizeInBytes();
sprang0a43fef2015-11-20 09:00:37 -0800361 if (queue_size_bytes > 0) {
362 // Assuming equal size packets and input/output rate, the average packet
363 // has avg_time_left_ms left to get queue_size_bytes out of the queue, if
364 // time constraint shall be met. Determine bitrate needed for that.
Sebastian Jansson60570dc2018-09-13 17:11:06 +0200365 packets_.UpdateQueueTime(TimeMilliseconds());
Sebastian Jansson0601d682018-06-25 19:23:05 +0200366 if (drain_large_queues_) {
367 int64_t avg_time_left_ms = std::max<int64_t>(
Sebastian Jansson60570dc2018-09-13 17:11:06 +0200368 1, queue_time_limit - packets_.AverageQueueTimeMs());
Sebastian Jansson0601d682018-06-25 19:23:05 +0200369 int min_bitrate_needed_kbps =
370 static_cast<int>(queue_size_bytes * 8 / avg_time_left_ms);
Evan Shrubsolefee13e82019-02-26 15:25:52 +0100371 if (min_bitrate_needed_kbps > target_bitrate_kbps) {
Sebastian Jansson0601d682018-06-25 19:23:05 +0200372 target_bitrate_kbps = min_bitrate_needed_kbps;
Evan Shrubsolefee13e82019-02-26 15:25:52 +0100373 RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps="
374 << target_bitrate_kbps;
375 }
Sebastian Jansson0601d682018-06-25 19:23:05 +0200376 }
sprang0a43fef2015-11-20 09:00:37 -0800377 }
378
Sebastian Jansson03914462018-10-11 20:22:03 +0200379 media_budget_.set_target_rate_kbps(target_bitrate_kbps);
isheriff31687812016-10-04 08:43:09 -0700380 UpdateBudgetWithElapsedTime(elapsed_time_ms);
stefan@webrtc.org80865fd2013-08-09 11:31:23 +0000381 }
philipela1ed0b32016-06-01 06:31:17 -0700382
Sebastian Jansson03914462018-10-11 20:22:03 +0200383 bool is_probing = prober_.IsProbing();
philipelc7bf32a2017-02-17 03:59:43 -0800384 PacedPacketInfo pacing_info;
Erik Språngf6468d22019-07-05 16:53:43 +0200385 absl::optional<size_t> recommended_probe_size;
isheriffcc5903e2016-10-04 08:29:38 -0700386 if (is_probing) {
Sebastian Jansson03914462018-10-11 20:22:03 +0200387 pacing_info = prober_.CurrentCluster();
388 recommended_probe_size = prober_.RecommendedMinProbeSize();
isheriffcc5903e2016-10-04 08:29:38 -0700389 }
Erik Språngf6468d22019-07-05 16:53:43 +0200390
391 size_t bytes_sent = 0;
Sebastian Jansson916ae082018-10-26 13:10:23 +0200392 // The paused state is checked in the loop since it leaves the critical
393 // section allowing the paused state to be changed from other code.
Erik Språngf6468d22019-07-05 16:53:43 +0200394 while (!paused_) {
Erik Språng58ee1872019-06-18 16:20:11 +0200395 auto* packet = GetPendingPacket(pacing_info);
Erik Språngf6468d22019-07-05 16:53:43 +0200396 if (packet == nullptr) {
397 // No packet available to send, check if we should send padding.
398 if (!legacy_packet_referencing_) {
399 size_t padding_bytes_to_add =
400 PaddingBytesToAdd(recommended_probe_size, bytes_sent);
401 if (padding_bytes_to_add > 0) {
402 critsect_.Leave();
403 std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets =
404 packet_router_->GeneratePadding(padding_bytes_to_add);
405 critsect_.Enter();
406 if (padding_packets.empty()) {
407 // No padding packets were generated, quite send loop.
408 break;
409 }
410 for (auto& packet : padding_packets) {
411 EnqueuePacket(std::move(packet));
412 }
413 // Continue loop to send the padding that was just added.
414 continue;
415 }
416 }
417
418 // Can't fetch new packet and no padding to send, exit send loop.
Sebastian Jansson916ae082018-10-26 13:10:23 +0200419 break;
Erik Språngf6468d22019-07-05 16:53:43 +0200420 }
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100421
Erik Språng58ee1872019-06-18 16:20:11 +0200422 std::unique_ptr<RtpPacketToSend> rtp_packet = packet->ReleasePacket();
423 const bool owned_rtp_packet = rtp_packet != nullptr;
Erik Språng58ee1872019-06-18 16:20:11 +0200424 RtpPacketSendResult success;
Erik Språngf6468d22019-07-05 16:53:43 +0200425
Erik Språng58ee1872019-06-18 16:20:11 +0200426 if (rtp_packet != nullptr) {
Erik Språngf6468d22019-07-05 16:53:43 +0200427 critsect_.Leave();
Erik Språng58ee1872019-06-18 16:20:11 +0200428 packet_router_->SendPacket(std::move(rtp_packet), pacing_info);
Erik Språngf6468d22019-07-05 16:53:43 +0200429 critsect_.Enter();
Erik Språng58ee1872019-06-18 16:20:11 +0200430 success = RtpPacketSendResult::kSuccess;
431 } else {
Erik Språngf6468d22019-07-05 16:53:43 +0200432 critsect_.Leave();
Erik Språng58ee1872019-06-18 16:20:11 +0200433 success = packet_router_->TimeToSendPacket(
434 packet->ssrc(), packet->sequence_number(), packet->capture_time_ms(),
435 packet->is_retransmission(), pacing_info);
Erik Språngf6468d22019-07-05 16:53:43 +0200436 critsect_.Enter();
Erik Språng58ee1872019-06-18 16:20:11 +0200437 }
438
Erik Språngd2879622019-05-10 08:29:01 -0700439 if (success == RtpPacketSendResult::kSuccess ||
440 success == RtpPacketSendResult::kPacketNotFound) {
441 // Packet sent or invalid packet, remove it from queue.
442 // TODO(webrtc:8052): Don't consume media budget on kInvalid.
Erik Språng58ee1872019-06-18 16:20:11 +0200443 bytes_sent += packet->size_in_bytes();
Sebastian Janssona1630f82018-02-21 13:39:26 +0100444 // Send succeeded, remove it from the queue.
Mirko Bonadei05cf6be2019-01-31 21:38:12 +0100445 OnPacketSent(packet);
Erik Språngf6468d22019-07-05 16:53:43 +0200446 if (recommended_probe_size && bytes_sent > *recommended_probe_size)
isheriffcc5903e2016-10-04 08:29:38 -0700447 break;
Erik Språng58ee1872019-06-18 16:20:11 +0200448 } else if (owned_rtp_packet) {
449 // Send failed, but we can't put it back in the queue, remove it without
450 // consuming budget.
451 packets_.FinalizePop();
452 break;
Peter Boströme23e7372015-10-08 11:44:14 +0200453 } else {
454 // Send failed, put it back into the queue.
Erik Språng58ee1872019-06-18 16:20:11 +0200455 packets_.CancelPop();
isheriffcc5903e2016-10-04 08:29:38 -0700456 break;
Peter Boströme23e7372015-10-08 11:44:14 +0200457 }
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000458 }
Peter Boströme23e7372015-10-08 11:44:14 +0200459
Erik Språngf6468d22019-07-05 16:53:43 +0200460 if (legacy_packet_referencing_ && packets_.Empty() && !Congested()) {
isheriffcc5903e2016-10-04 08:29:38 -0700461 // We can not send padding unless a normal packet has first been sent. If we
462 // do, timestamps get messed up.
463 if (packet_counter_ > 0) {
Erik Språngf6468d22019-07-05 16:53:43 +0200464 int padding_needed = static_cast<int>(
465 recommended_probe_size ? (*recommended_probe_size - bytes_sent)
466 : padding_budget_.bytes_remaining());
Sebastian Jansson439f0bc2018-02-20 10:46:39 +0100467 if (padding_needed > 0) {
Erik Språngf6468d22019-07-05 16:53:43 +0200468 size_t padding_sent = 0;
Sebastian Jansson916ae082018-10-26 13:10:23 +0200469 critsect_.Leave();
Erik Språngf6468d22019-07-05 16:53:43 +0200470 padding_sent =
Erik Språnge7942432019-06-12 13:30:02 +0200471 packet_router_->TimeToSendPadding(padding_needed, pacing_info);
Sebastian Jansson916ae082018-10-26 13:10:23 +0200472 critsect_.Enter();
473 bytes_sent += padding_sent;
474 OnPaddingSent(padding_sent);
Sebastian Jansson439f0bc2018-02-20 10:46:39 +0100475 }
isheriffcc5903e2016-10-04 08:29:38 -0700476 }
perkj71ee44c2016-06-15 00:47:53 -0700477 }
Erik Språngf6468d22019-07-05 16:53:43 +0200478
philipelb61927c2017-02-28 07:05:23 -0800479 if (is_probing) {
480 probing_send_failure_ = bytes_sent == 0;
481 if (!probing_send_failure_)
Sebastian Jansson03914462018-10-11 20:22:03 +0200482 prober_.ProbeSent(TimeMilliseconds(), bytes_sent);
philipelb61927c2017-02-28 07:05:23 -0800483 }
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000484}
485
tommi919dce22017-03-15 07:45:36 -0700486void PacedSender::ProcessThreadAttached(ProcessThread* process_thread) {
Karl Wiberg43432732018-05-23 11:13:31 +0200487 RTC_LOG(LS_INFO) << "ProcessThreadAttached 0x" << process_thread;
Sebastian Jansson439f0bc2018-02-20 10:46:39 +0100488 rtc::CritScope cs(&process_thread_lock_);
tommi919dce22017-03-15 07:45:36 -0700489 process_thread_ = process_thread;
490}
491
Erik Språngf6468d22019-07-05 16:53:43 +0200492size_t PacedSender::PaddingBytesToAdd(
493 absl::optional<size_t> recommended_probe_size,
494 size_t bytes_sent) {
495 if (!packets_.Empty()) {
496 // Actual payload available, no need to add padding.
497 return 0;
498 }
499
500 if (Congested()) {
501 // Don't add padding if congested, even if requested for probing.
502 return 0;
503 }
504
505 if (packet_counter_ == 0) {
506 // We can not send padding unless a normal packet has first been sent. If we
507 // do, timestamps get messed up.
508 return 0;
509 }
510
511 if (recommended_probe_size) {
512 if (*recommended_probe_size > bytes_sent) {
513 return *recommended_probe_size - bytes_sent;
514 }
515 return 0;
516 }
517
518 return padding_budget_.bytes_remaining();
519}
520
Erik Språng58ee1872019-06-18 16:20:11 +0200521RoundRobinPacketQueue::QueuedPacket* PacedSender::GetPendingPacket(
Sebastian Jansson916ae082018-10-26 13:10:23 +0200522 const PacedPacketInfo& pacing_info) {
Erik Språngf6468d22019-07-05 16:53:43 +0200523 if (packets_.Empty()) {
524 return nullptr;
525 }
526
Sebastian Jansson916ae082018-10-26 13:10:23 +0200527 // Since we need to release the lock in order to send, we first pop the
528 // element from the priority queue but keep it in storage, so that we can
529 // reinsert it if send fails.
Erik Språng58ee1872019-06-18 16:20:11 +0200530 RoundRobinPacketQueue::QueuedPacket* packet = packets_.BeginPop();
531 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
Sebastian Jansson470a5ea2019-01-23 12:37:49 +0100532 bool apply_pacing = !audio_packet || pace_audio_;
Sebastian Jansson03914462018-10-11 20:22:03 +0200533 if (apply_pacing && (Congested() || (media_budget_.bytes_remaining() == 0 &&
Sebastian Janssonce4829a2018-06-15 14:47:35 +0200534 pacing_info.probe_cluster_id ==
535 PacedPacketInfo::kNotAProbe))) {
Erik Språng58ee1872019-06-18 16:20:11 +0200536 packets_.CancelPop();
Sebastian Jansson916ae082018-10-26 13:10:23 +0200537 return nullptr;
terelius8b70faf2016-08-01 09:47:31 -0700538 }
Sebastian Jansson916ae082018-10-26 13:10:23 +0200539 return packet;
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000540}
541
Erik Språng58ee1872019-06-18 16:20:11 +0200542void PacedSender::OnPacketSent(RoundRobinPacketQueue::QueuedPacket* packet) {
Sebastian Jansson916ae082018-10-26 13:10:23 +0200543 if (first_sent_packet_ms_ == -1)
544 first_sent_packet_ms_ = TimeMilliseconds();
Erik Språng58ee1872019-06-18 16:20:11 +0200545 bool audio_packet = packet->type() == RtpPacketToSend::Type::kAudio;
Sebastian Jansson916ae082018-10-26 13:10:23 +0200546 if (!audio_packet || account_for_audio_) {
547 // Update media bytes sent.
Erik Språng58ee1872019-06-18 16:20:11 +0200548 UpdateBudgetWithBytesSent(packet->size_in_bytes());
Sebastian Jansson916ae082018-10-26 13:10:23 +0200549 last_send_time_us_ = clock_->TimeInMicroseconds();
550 }
551 // Send succeeded, remove it from the queue.
Erik Språng58ee1872019-06-18 16:20:11 +0200552 packets_.FinalizePop();
Sebastian Jansson916ae082018-10-26 13:10:23 +0200553}
sprang@webrtc.orgdcebf2d2014-11-04 16:27:16 +0000554
Sebastian Jansson916ae082018-10-26 13:10:23 +0200555void PacedSender::OnPaddingSent(size_t bytes_sent) {
Stefan Holmer01b48882015-05-05 10:21:24 +0200556 if (bytes_sent > 0) {
isheriff31687812016-10-04 08:43:09 -0700557 UpdateBudgetWithBytesSent(bytes_sent);
Stefan Holmer01b48882015-05-05 10:21:24 +0200558 }
Sebastian Janssonc235a8d2018-06-15 14:46:11 +0200559 last_send_time_us_ = clock_->TimeInMicroseconds();
stefan@webrtc.org19a40ff2013-11-27 14:16:20 +0000560}
561
isheriff31687812016-10-04 08:43:09 -0700562void PacedSender::UpdateBudgetWithElapsedTime(int64_t delta_time_ms) {
Sebastian Janssona1630f82018-02-21 13:39:26 +0100563 delta_time_ms = std::min(kMaxIntervalTimeMs, delta_time_ms);
Sebastian Jansson03914462018-10-11 20:22:03 +0200564 media_budget_.IncreaseBudget(delta_time_ms);
565 padding_budget_.IncreaseBudget(delta_time_ms);
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000566}
isheriff31687812016-10-04 08:43:09 -0700567
568void PacedSender::UpdateBudgetWithBytesSent(size_t bytes_sent) {
Sebastian Jansson45d9c1d2018-03-09 12:48:01 +0100569 outstanding_bytes_ += bytes_sent;
Sebastian Jansson03914462018-10-11 20:22:03 +0200570 media_budget_.UseBudget(bytes_sent);
571 padding_budget_.UseBudget(bytes_sent);
isheriff31687812016-10-04 08:43:09 -0700572}
sprang89c4a7e2017-06-30 13:27:40 -0700573
sprang89c4a7e2017-06-30 13:27:40 -0700574void PacedSender::SetQueueTimeLimit(int limit_ms) {
575 rtc::CritScope cs(&critsect_);
576 queue_time_limit = limit_ms;
577}
578
pwestin@webrtc.orgb5180172012-11-09 20:56:23 +0000579} // namespace webrtc