| 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/pacing/pacing_controller.h" |
| 12 |
| 13 | #include <algorithm> |
| 14 | #include <memory> |
| 15 | #include <utility> |
| 16 | #include <vector> |
| 17 |
| 18 | #include "absl/strings/match.h" |
| 19 | #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/experiments/field_trial_parser.h" |
| 24 | #include "rtc_base/logging.h" |
| 25 | #include "rtc_base/time_utils.h" |
| 26 | #include "system_wrappers/include/clock.h" |
| 27 |
| 28 | namespace webrtc { |
| 29 | namespace { |
| 30 | // Time limit in milliseconds between packet bursts. |
| 31 | constexpr TimeDelta kDefaultMinPacketLimit = TimeDelta::Millis(5); |
| 32 | constexpr TimeDelta kCongestedPacketInterval = TimeDelta::Millis(500); |
| 33 | // TODO(sprang): Consider dropping this limit. |
| 34 | // The maximum debt level, in terms of time, capped when sending packets. |
| 35 | constexpr TimeDelta kMaxDebtInTime = TimeDelta::Millis(500); |
| 36 | constexpr TimeDelta kMaxElapsedTime = TimeDelta::Seconds(2); |
| 37 |
| 38 | // Upper cap on process interval, in case process has not been called in a long |
| 39 | // time. Applies only to periodic mode. |
| 40 | constexpr TimeDelta kMaxProcessingInterval = TimeDelta::Millis(30); |
| 41 |
| 42 | // Allow probes to be processed slightly ahead of inteded send time. Currently |
| 43 | // set to 1ms as this is intended to allow times be rounded down to the nearest |
| 44 | // millisecond. |
| 45 | constexpr TimeDelta kMaxEarlyProbeProcessing = TimeDelta::Millis(1); |
| 46 |
| 47 | constexpr int kFirstPriority = 0; |
| 48 |
| 49 | bool IsDisabled(const WebRtcKeyValueConfig& field_trials, |
| 50 | absl::string_view key) { |
| 51 | return absl::StartsWith(field_trials.Lookup(key), "Disabled"); |
| 52 | } |
| 53 |
| 54 | bool IsEnabled(const WebRtcKeyValueConfig& field_trials, |
| 55 | absl::string_view key) { |
| 56 | return absl::StartsWith(field_trials.Lookup(key), "Enabled"); |
| 57 | } |
| 58 |
| 59 | TimeDelta GetDynamicPaddingTarget(const WebRtcKeyValueConfig& field_trials) { |
| 60 | FieldTrialParameter<TimeDelta> padding_target("timedelta", |
| 61 | TimeDelta::Millis(5)); |
| 62 | ParseFieldTrial({&padding_target}, |
| 63 | field_trials.Lookup("WebRTC-Pacer-DynamicPaddingTarget")); |
| 64 | return padding_target.Get(); |
| 65 | } |
| 66 |
| 67 | int GetPriorityForType(RtpPacketMediaType type) { |
| 68 | // Lower number takes priority over higher. |
| 69 | switch (type) { |
| 70 | case RtpPacketMediaType::kAudio: |
| 71 | // Audio is always prioritized over other packet types. |
| 72 | return kFirstPriority + 1; |
| 73 | case RtpPacketMediaType::kRetransmission: |
| 74 | // Send retransmissions before new media. |
| 75 | return kFirstPriority + 2; |
| 76 | case RtpPacketMediaType::kVideo: |
| 77 | case RtpPacketMediaType::kForwardErrorCorrection: |
| 78 | // Video has "normal" priority, in the old speak. |
| 79 | // Send redundancy concurrently to video. If it is delayed it might have a |
| 80 | // lower chance of being useful. |
| 81 | return kFirstPriority + 3; |
| 82 | case RtpPacketMediaType::kPadding: |
| 83 | // Packets that are in themselves likely useless, only sent to keep the |
| 84 | // BWE high. |
| 85 | return kFirstPriority + 4; |
| 86 | } |
| 87 | } |
| 88 |
| 89 | } // namespace |
| 90 |
| 91 | const TimeDelta PacingController::kMaxExpectedQueueLength = |
| 92 | TimeDelta::Millis(2000); |
| 93 | const float PacingController::kDefaultPaceMultiplier = 2.5f; |
| 94 | const TimeDelta PacingController::kPausedProcessInterval = |
| 95 | kCongestedPacketInterval; |
| 96 | const TimeDelta PacingController::kMinSleepTime = TimeDelta::Millis(1); |
| 97 |
| 98 | PacingController::PacingController(Clock* clock, |
| 99 | PacketSender* packet_sender, |
| 100 | RtcEventLog* event_log, |
| 101 | const WebRtcKeyValueConfig* field_trials, |
| 102 | ProcessMode mode) |
| 103 | : mode_(mode), |
| 104 | clock_(clock), |
| 105 | packet_sender_(packet_sender), |
| 106 | fallback_field_trials_( |
| 107 | !field_trials ? std::make_unique<FieldTrialBasedConfig>() : nullptr), |
| 108 | field_trials_(field_trials ? field_trials : fallback_field_trials_.get()), |
| 109 | drain_large_queues_( |
| 110 | !IsDisabled(*field_trials_, "WebRTC-Pacer-DrainQueue")), |
| 111 | send_padding_if_silent_( |
| 112 | IsEnabled(*field_trials_, "WebRTC-Pacer-PadInSilence")), |
| 113 | pace_audio_(IsEnabled(*field_trials_, "WebRTC-Pacer-BlockAudio")), |
| 114 | small_first_probe_packet_( |
| 115 | IsEnabled(*field_trials_, "WebRTC-Pacer-SmallFirstProbePacket")), |
| 116 | ignore_transport_overhead_( |
| 117 | IsEnabled(*field_trials_, "WebRTC-Pacer-IgnoreTransportOverhead")), |
| 118 | padding_target_duration_(GetDynamicPaddingTarget(*field_trials_)), |
| 119 | min_packet_limit_(kDefaultMinPacketLimit), |
| 120 | transport_overhead_per_packet_(DataSize::Zero()), |
| 121 | last_timestamp_(clock_->CurrentTime()), |
| 122 | paused_(false), |
| 123 | media_budget_(0), |
| 124 | padding_budget_(0), |
| 125 | media_debt_(DataSize::Zero()), |
| 126 | padding_debt_(DataSize::Zero()), |
| 127 | media_rate_(DataRate::Zero()), |
| 128 | padding_rate_(DataRate::Zero()), |
| 129 | prober_(*field_trials_), |
| 130 | probing_send_failure_(false), |
| 131 | pacing_bitrate_(DataRate::Zero()), |
| 132 | last_process_time_(clock->CurrentTime()), |
| 133 | last_send_time_(last_process_time_), |
| 134 | packet_queue_(last_process_time_, field_trials_), |
| 135 | packet_counter_(0), |
| 136 | congestion_window_size_(DataSize::PlusInfinity()), |
| 137 | outstanding_data_(DataSize::Zero()), |
| 138 | queue_time_limit(kMaxExpectedQueueLength), |
| 139 | account_for_audio_(false), |
| 140 | include_overhead_(false) { |
| 141 | if (!drain_large_queues_) { |
| 142 | RTC_LOG(LS_WARNING) << "Pacer queues will not be drained," |
| 143 | "pushback experiment must be enabled."; |
| 144 | } |
| 145 | FieldTrialParameter<int> min_packet_limit_ms("", min_packet_limit_.ms()); |
| 146 | ParseFieldTrial({&min_packet_limit_ms}, |
| 147 | field_trials_->Lookup("WebRTC-Pacer-MinPacketLimitMs")); |
| 148 | min_packet_limit_ = TimeDelta::Millis(min_packet_limit_ms.Get()); |
| 149 | UpdateBudgetWithElapsedTime(min_packet_limit_); |
| 150 | } |
| 151 |
| 152 | PacingController::~PacingController() = default; |
| 153 |
| 154 | void PacingController::CreateProbeCluster(DataRate bitrate, int cluster_id) { |
| 155 | prober_.CreateProbeCluster(bitrate, CurrentTime(), cluster_id); |
| 156 | } |
| 157 |
| 158 | void PacingController::Pause() { |
| 159 | if (!paused_) |
| 160 | RTC_LOG(LS_INFO) << "PacedSender paused."; |
| 161 | paused_ = true; |
| 162 | packet_queue_.SetPauseState(true, CurrentTime()); |
| 163 | } |
| 164 |
| 165 | void PacingController::Resume() { |
| 166 | if (paused_) |
| 167 | RTC_LOG(LS_INFO) << "PacedSender resumed."; |
| 168 | paused_ = false; |
| 169 | packet_queue_.SetPauseState(false, CurrentTime()); |
| 170 | } |
| 171 |
| 172 | bool PacingController::IsPaused() const { |
| 173 | return paused_; |
| 174 | } |
| 175 |
| 176 | void PacingController::SetCongestionWindow(DataSize congestion_window_size) { |
| 177 | const bool was_congested = Congested(); |
| 178 | congestion_window_size_ = congestion_window_size; |
| 179 | if (was_congested && !Congested()) { |
| 180 | TimeDelta elapsed_time = UpdateTimeAndGetElapsed(CurrentTime()); |
| 181 | UpdateBudgetWithElapsedTime(elapsed_time); |
| 182 | } |
| 183 | } |
| 184 |
| 185 | void PacingController::UpdateOutstandingData(DataSize outstanding_data) { |
| 186 | const bool was_congested = Congested(); |
| 187 | outstanding_data_ = outstanding_data; |
| 188 | if (was_congested && !Congested()) { |
| 189 | TimeDelta elapsed_time = UpdateTimeAndGetElapsed(CurrentTime()); |
| 190 | UpdateBudgetWithElapsedTime(elapsed_time); |
| 191 | } |
| 192 | } |
| 193 |
| 194 | bool PacingController::Congested() const { |
| 195 | if (congestion_window_size_.IsFinite()) { |
| 196 | return outstanding_data_ >= congestion_window_size_; |
| 197 | } |
| 198 | return false; |
| 199 | } |
| 200 |
| 201 | bool PacingController::IsProbing() const { |
| 202 | return prober_.is_probing(); |
| 203 | } |
| 204 |
| 205 | Timestamp PacingController::CurrentTime() const { |
| 206 | Timestamp time = clock_->CurrentTime(); |
| 207 | if (time < last_timestamp_) { |
| 208 | RTC_LOG(LS_WARNING) |
| 209 | << "Non-monotonic clock behavior observed. Previous timestamp: " |
| 210 | << last_timestamp_.ms() << ", new timestamp: " << time.ms(); |
| 211 | RTC_DCHECK_GE(time, last_timestamp_); |
| 212 | time = last_timestamp_; |
| 213 | } |
| 214 | last_timestamp_ = time; |
| 215 | return time; |
| 216 | } |
| 217 |
| 218 | void PacingController::SetProbingEnabled(bool enabled) { |
| 219 | RTC_CHECK_EQ(0, packet_counter_); |
| 220 | prober_.SetEnabled(enabled); |
| 221 | } |
| 222 |
| 223 | void PacingController::SetPacingRates(DataRate pacing_rate, |
| 224 | DataRate padding_rate) { |
| 225 | RTC_DCHECK_GT(pacing_rate, DataRate::Zero()); |
| 226 | media_rate_ = pacing_rate; |
| 227 | padding_rate_ = padding_rate; |
| 228 | pacing_bitrate_ = pacing_rate; |
| 229 | padding_budget_.set_target_rate_kbps(padding_rate.kbps()); |
| 230 |
| 231 | RTC_LOG(LS_VERBOSE) << "bwe:pacer_updated pacing_kbps=" |
| 232 | << pacing_bitrate_.kbps() |
| 233 | << " padding_budget_kbps=" << padding_rate.kbps(); |
| 234 | } |
| 235 |
| 236 | void PacingController::EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet) { |
| 237 | RTC_DCHECK(pacing_bitrate_ > DataRate::Zero()) |
| 238 | << "SetPacingRate must be called before InsertPacket."; |
| 239 | RTC_CHECK(packet->packet_type()); |
| 240 | // Get priority first and store in temporary, to avoid chance of object being |
| 241 | // moved before GetPriorityForType() being called. |
| 242 | const int priority = GetPriorityForType(*packet->packet_type()); |
| 243 | EnqueuePacketInternal(std::move(packet), priority); |
| 244 | } |
| 245 |
| 246 | void PacingController::SetAccountForAudioPackets(bool account_for_audio) { |
| 247 | account_for_audio_ = account_for_audio; |
| 248 | } |
| 249 |
| 250 | void PacingController::SetIncludeOverhead() { |
| 251 | include_overhead_ = true; |
| 252 | packet_queue_.SetIncludeOverhead(); |
| 253 | } |
| 254 |
| 255 | void PacingController::SetTransportOverhead(DataSize overhead_per_packet) { |
| 256 | if (ignore_transport_overhead_) |
| 257 | return; |
| 258 | transport_overhead_per_packet_ = overhead_per_packet; |
| 259 | packet_queue_.SetTransportOverhead(overhead_per_packet); |
| 260 | } |
| 261 |
| 262 | TimeDelta PacingController::ExpectedQueueTime() const { |
| 263 | RTC_DCHECK_GT(pacing_bitrate_, DataRate::Zero()); |
| 264 | return TimeDelta::Millis( |
| 265 | (QueueSizeData().bytes() * 8 * rtc::kNumMillisecsPerSec) / |
| 266 | pacing_bitrate_.bps()); |
| 267 | } |
| 268 |
| 269 | size_t PacingController::QueueSizePackets() const { |
| 270 | return packet_queue_.SizeInPackets(); |
| 271 | } |
| 272 |
| 273 | DataSize PacingController::QueueSizeData() const { |
| 274 | return packet_queue_.Size(); |
| 275 | } |
| 276 |
| 277 | DataSize PacingController::CurrentBufferLevel() const { |
| 278 | return std::max(media_debt_, padding_debt_); |
| 279 | } |
| 280 |
| 281 | absl::optional<Timestamp> PacingController::FirstSentPacketTime() const { |
| 282 | return first_sent_packet_time_; |
| 283 | } |
| 284 |
| 285 | TimeDelta PacingController::OldestPacketWaitTime() const { |
| 286 | Timestamp oldest_packet = packet_queue_.OldestEnqueueTime(); |
| 287 | if (oldest_packet.IsInfinite()) { |
| 288 | return TimeDelta::Zero(); |
| 289 | } |
| 290 |
| 291 | return CurrentTime() - oldest_packet; |
| 292 | } |
| 293 |
| 294 | void PacingController::EnqueuePacketInternal( |
| 295 | std::unique_ptr<RtpPacketToSend> packet, |
| 296 | int priority) { |
| 297 | prober_.OnIncomingPacket(DataSize::Bytes(packet->payload_size())); |
| 298 |
| 299 | // TODO(sprang): Make sure tests respect this, replace with DCHECK. |
| 300 | Timestamp now = CurrentTime(); |
| 301 | if (packet->capture_time_ms() < 0) { |
| 302 | packet->set_capture_time_ms(now.ms()); |
| 303 | } |
| 304 |
| 305 | if (mode_ == ProcessMode::kDynamic && packet_queue_.Empty() && |
| 306 | NextSendTime() <= now) { |
| 307 | TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now); |
| 308 | UpdateBudgetWithElapsedTime(elapsed_time); |
| 309 | } |
| 310 | packet_queue_.Push(priority, now, packet_counter_++, std::move(packet)); |
| 311 | } |
| 312 |
| 313 | TimeDelta PacingController::UpdateTimeAndGetElapsed(Timestamp now) { |
| 314 | // If no previous processing, or last process was "in the future" because of |
| 315 | // early probe processing, then there is no elapsed time to add budget for. |
| 316 | if (last_process_time_.IsMinusInfinity() || now < last_process_time_) { |
| 317 | return TimeDelta::Zero(); |
| 318 | } |
| 319 | RTC_DCHECK_GE(now, last_process_time_); |
| 320 | TimeDelta elapsed_time = now - last_process_time_; |
| 321 | last_process_time_ = now; |
| 322 | if (elapsed_time > kMaxElapsedTime) { |
| 323 | RTC_LOG(LS_WARNING) << "Elapsed time (" << elapsed_time.ms() |
| 324 | << " ms) longer than expected, limiting to " |
| 325 | << kMaxElapsedTime.ms(); |
| 326 | elapsed_time = kMaxElapsedTime; |
| 327 | } |
| 328 | return elapsed_time; |
| 329 | } |
| 330 |
| 331 | bool PacingController::ShouldSendKeepalive(Timestamp now) const { |
| 332 | if (send_padding_if_silent_ || paused_ || Congested() || |
| 333 | packet_counter_ == 0) { |
| 334 | // We send a padding packet every 500 ms to ensure we won't get stuck in |
| 335 | // congested state due to no feedback being received. |
| 336 | TimeDelta elapsed_since_last_send = now - last_send_time_; |
| 337 | if (elapsed_since_last_send >= kCongestedPacketInterval) { |
| 338 | return true; |
| 339 | } |
| 340 | } |
| 341 | return false; |
| 342 | } |
| 343 |
| 344 | Timestamp PacingController::NextSendTime() const { |
| 345 | const Timestamp now = CurrentTime(); |
| 346 |
| 347 | if (paused_) { |
| 348 | return last_send_time_ + kPausedProcessInterval; |
| 349 | } |
| 350 |
| 351 | // If probing is active, that always takes priority. |
| 352 | if (prober_.is_probing()) { |
| 353 | Timestamp probe_time = prober_.NextProbeTime(now); |
| 354 | // |probe_time| == PlusInfinity indicates no probe scheduled. |
| 355 | if (probe_time != Timestamp::PlusInfinity() && !probing_send_failure_) { |
| 356 | return probe_time; |
| 357 | } |
| 358 | } |
| 359 |
| 360 | if (mode_ == ProcessMode::kPeriodic) { |
| 361 | // In periodic non-probing mode, we just have a fixed interval. |
| 362 | return last_process_time_ + min_packet_limit_; |
| 363 | } |
| 364 |
| 365 | // In dynamic mode, figure out when the next packet should be sent, |
| 366 | // given the current conditions. |
| 367 |
| 368 | if (!pace_audio_) { |
| 369 | // Not pacing audio, if leading packet is audio its target send |
| 370 | // time is the time at which it was enqueued. |
| 371 | absl::optional<Timestamp> audio_enqueue_time = |
| 372 | packet_queue_.LeadingAudioPacketEnqueueTime(); |
| 373 | if (audio_enqueue_time.has_value()) { |
| 374 | return *audio_enqueue_time; |
| 375 | } |
| 376 | } |
| 377 |
| 378 | if (Congested() || packet_counter_ == 0) { |
| 379 | // We need to at least send keep-alive packets with some interval. |
| 380 | return last_send_time_ + kCongestedPacketInterval; |
| 381 | } |
| 382 |
| 383 | // Check how long until we can send the next media packet. |
| 384 | if (media_rate_ > DataRate::Zero() && !packet_queue_.Empty()) { |
| 385 | return std::min(last_send_time_ + kPausedProcessInterval, |
| 386 | last_process_time_ + media_debt_ / media_rate_); |
| 387 | } |
| 388 |
| 389 | // If we _don't_ have pending packets, check how long until we have |
| 390 | // bandwidth for padding packets. Both media and padding debts must |
| 391 | // have been drained to do this. |
| 392 | if (padding_rate_ > DataRate::Zero() && packet_queue_.Empty()) { |
| 393 | TimeDelta drain_time = |
| 394 | std::max(media_debt_ / media_rate_, padding_debt_ / padding_rate_); |
| 395 | return std::min(last_send_time_ + kPausedProcessInterval, |
| 396 | last_process_time_ + drain_time); |
| 397 | } |
| 398 |
| 399 | if (send_padding_if_silent_) { |
| 400 | return last_send_time_ + kPausedProcessInterval; |
| 401 | } |
| 402 | return last_process_time_ + kPausedProcessInterval; |
| 403 | } |
| 404 |
| 405 | void PacingController::ProcessPackets() { |
| 406 | Timestamp now = CurrentTime(); |
| 407 | Timestamp target_send_time = now; |
| 408 | if (mode_ == ProcessMode::kDynamic) { |
| 409 | target_send_time = NextSendTime(); |
| 410 | TimeDelta early_execute_margin = |
| 411 | prober_.is_probing() ? kMaxEarlyProbeProcessing : TimeDelta::Zero(); |
| 412 | if (target_send_time.IsMinusInfinity()) { |
| 413 | target_send_time = now; |
| 414 | } else if (now < target_send_time - early_execute_margin) { |
| 415 | // We are too early, but if queue is empty still allow draining some debt. |
| 416 | // Probing is allowed to be sent up to kMinSleepTime early. |
| 417 | TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now); |
| 418 | UpdateBudgetWithElapsedTime(elapsed_time); |
| 419 | return; |
| 420 | } |
| 421 |
| 422 | if (target_send_time < last_process_time_) { |
| 423 | // After the last process call, at time X, the target send time |
| 424 | // shifted to be earlier than X. This should normally not happen |
| 425 | // but we want to make sure rounding errors or erratic behavior |
| 426 | // of NextSendTime() does not cause issue. In particular, if the |
| 427 | // buffer reduction of |
| 428 | // rate * (target_send_time - previous_process_time) |
| 429 | // in the main loop doesn't clean up the existing debt we may not |
| 430 | // be able to send again. We don't want to check this reordering |
| 431 | // there as it is the normal exit condtion when the buffer is |
| 432 | // exhausted and there are packets in the queue. |
| 433 | UpdateBudgetWithElapsedTime(last_process_time_ - target_send_time); |
| 434 | target_send_time = last_process_time_; |
| 435 | } |
| 436 | } |
| 437 |
| 438 | Timestamp previous_process_time = last_process_time_; |
| 439 | TimeDelta elapsed_time = UpdateTimeAndGetElapsed(now); |
| 440 |
| 441 | if (ShouldSendKeepalive(now)) { |
| 442 | // We can not send padding unless a normal packet has first been sent. If |
| 443 | // we do, timestamps get messed up. |
| 444 | if (packet_counter_ == 0) { |
| 445 | last_send_time_ = now; |
| 446 | } else { |
| 447 | DataSize keepalive_data_sent = DataSize::Zero(); |
| 448 | std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets = |
| 449 | packet_sender_->GeneratePadding(DataSize::Bytes(1)); |
| 450 | for (auto& packet : keepalive_packets) { |
| 451 | keepalive_data_sent += |
| 452 | DataSize::Bytes(packet->payload_size() + packet->padding_size()); |
| 453 | packet_sender_->SendPacket(std::move(packet), PacedPacketInfo()); |
| 454 | for (auto& packet : packet_sender_->FetchFec()) { |
| 455 | EnqueuePacket(std::move(packet)); |
| 456 | } |
| 457 | } |
| 458 | OnPaddingSent(keepalive_data_sent); |
| 459 | } |
| 460 | } |
| 461 |
| 462 | if (paused_) { |
| 463 | return; |
| 464 | } |
| 465 |
| 466 | if (elapsed_time > TimeDelta::Zero()) { |
| 467 | DataRate target_rate = pacing_bitrate_; |
| 468 | DataSize queue_size_data = packet_queue_.Size(); |
| 469 | if (queue_size_data > DataSize::Zero()) { |
| 470 | // Assuming equal size packets and input/output rate, the average packet |
| 471 | // has avg_time_left_ms left to get queue_size_bytes out of the queue, if |
| 472 | // time constraint shall be met. Determine bitrate needed for that. |
| 473 | packet_queue_.UpdateQueueTime(now); |
| 474 | if (drain_large_queues_) { |
| 475 | TimeDelta avg_time_left = |
| 476 | std::max(TimeDelta::Millis(1), |
| 477 | queue_time_limit - packet_queue_.AverageQueueTime()); |
| 478 | DataRate min_rate_needed = queue_size_data / avg_time_left; |
| 479 | if (min_rate_needed > target_rate) { |
| 480 | target_rate = min_rate_needed; |
| 481 | RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps=" |
| 482 | << target_rate.kbps(); |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 |
| 487 | if (mode_ == ProcessMode::kPeriodic) { |
| 488 | // In periodic processing mode, the IntevalBudget allows positive budget |
| 489 | // up to (process interval duration) * (target rate), so we only need to |
| 490 | // update it once before the packet sending loop. |
| 491 | media_budget_.set_target_rate_kbps(target_rate.kbps()); |
| 492 | UpdateBudgetWithElapsedTime(elapsed_time); |
| 493 | } else { |
| 494 | media_rate_ = target_rate; |
| 495 | } |
| 496 | } |
| 497 |
| 498 | bool first_packet_in_probe = false; |
| 499 | PacedPacketInfo pacing_info; |
| 500 | DataSize recommended_probe_size = DataSize::Zero(); |
| 501 | bool is_probing = prober_.is_probing(); |
| 502 | if (is_probing) { |
| 503 | // Probe timing is sensitive, and handled explicitly by BitrateProber, so |
| 504 | // use actual send time rather than target. |
| 505 | pacing_info = prober_.CurrentCluster(now).value_or(PacedPacketInfo()); |
| 506 | if (pacing_info.probe_cluster_id != PacedPacketInfo::kNotAProbe) { |
| 507 | first_packet_in_probe = pacing_info.probe_cluster_bytes_sent == 0; |
| 508 | recommended_probe_size = prober_.RecommendedMinProbeSize(); |
| 509 | RTC_DCHECK_GT(recommended_probe_size, DataSize::Zero()); |
| 510 | } else { |
| 511 | // No valid probe cluster returned, probe might have timed out. |
| 512 | is_probing = false; |
| 513 | } |
| 514 | } |
| 515 |
| 516 | DataSize data_sent = DataSize::Zero(); |
| 517 |
| 518 | // The paused state is checked in the loop since it leaves the critical |
| 519 | // section allowing the paused state to be changed from other code. |
| 520 | while (!paused_) { |
| 521 | if (small_first_probe_packet_ && first_packet_in_probe) { |
| 522 | // If first packet in probe, insert a small padding packet so we have a |
| 523 | // more reliable start window for the rate estimation. |
| 524 | auto padding = packet_sender_->GeneratePadding(DataSize::Bytes(1)); |
| 525 | // If no RTP modules sending media are registered, we may not get a |
| 526 | // padding packet back. |
| 527 | if (!padding.empty()) { |
| 528 | // Insert with high priority so larger media packets don't preempt it. |
| 529 | EnqueuePacketInternal(std::move(padding[0]), kFirstPriority); |
| 530 | // We should never get more than one padding packets with a requested |
| 531 | // size of 1 byte. |
| 532 | RTC_DCHECK_EQ(padding.size(), 1u); |
| 533 | } |
| 534 | first_packet_in_probe = false; |
| 535 | } |
| 536 |
| 537 | if (mode_ == ProcessMode::kDynamic && |
| 538 | previous_process_time < target_send_time) { |
| 539 | // Reduce buffer levels with amount corresponding to time between last |
| 540 | // process and target send time for the next packet. |
| 541 | // If the process call is late, that may be the time between the optimal |
| 542 | // send times for two packets we should already have sent. |
| 543 | UpdateBudgetWithElapsedTime(target_send_time - previous_process_time); |
| 544 | previous_process_time = target_send_time; |
| 545 | } |
| 546 |
| 547 | // Fetch the next packet, so long as queue is not empty or budget is not |
| 548 | // exhausted. |
| 549 | std::unique_ptr<RtpPacketToSend> rtp_packet = |
| 550 | GetPendingPacket(pacing_info, target_send_time, now); |
| 551 |
| 552 | if (rtp_packet == nullptr) { |
| 553 | // No packet available to send, check if we should send padding. |
| 554 | DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent); |
| 555 | if (padding_to_add > DataSize::Zero()) { |
| 556 | std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets = |
| 557 | packet_sender_->GeneratePadding(padding_to_add); |
| 558 | if (padding_packets.empty()) { |
| 559 | // No padding packets were generated, quite send loop. |
| 560 | break; |
| 561 | } |
| 562 | for (auto& packet : padding_packets) { |
| 563 | EnqueuePacket(std::move(packet)); |
| 564 | } |
| 565 | // Continue loop to send the padding that was just added. |
| 566 | continue; |
| 567 | } |
| 568 |
| 569 | // Can't fetch new packet and no padding to send, exit send loop. |
| 570 | break; |
| 571 | } |
| 572 |
| 573 | RTC_DCHECK(rtp_packet); |
| 574 | RTC_DCHECK(rtp_packet->packet_type().has_value()); |
| 575 | const RtpPacketMediaType packet_type = *rtp_packet->packet_type(); |
| 576 | DataSize packet_size = DataSize::Bytes(rtp_packet->payload_size() + |
| 577 | rtp_packet->padding_size()); |
| 578 |
| 579 | if (include_overhead_) { |
| 580 | packet_size += DataSize::Bytes(rtp_packet->headers_size()) + |
| 581 | transport_overhead_per_packet_; |
| 582 | } |
| 583 |
| 584 | packet_sender_->SendPacket(std::move(rtp_packet), pacing_info); |
| 585 | for (auto& packet : packet_sender_->FetchFec()) { |
| 586 | EnqueuePacket(std::move(packet)); |
| 587 | } |
| 588 | data_sent += packet_size; |
| 589 |
| 590 | // Send done, update send/process time to the target send time. |
| 591 | OnPacketSent(packet_type, packet_size, target_send_time); |
| 592 |
| 593 | // If we are currently probing, we need to stop the send loop when we have |
| 594 | // reached the send target. |
| 595 | if (is_probing && data_sent >= recommended_probe_size) { |
| 596 | break; |
| 597 | } |
| 598 |
| 599 | if (mode_ == ProcessMode::kDynamic) { |
| 600 | // Update target send time in case that are more packets that we are late |
| 601 | // in processing. |
| 602 | Timestamp next_send_time = NextSendTime(); |
| 603 | if (next_send_time.IsMinusInfinity()) { |
| 604 | target_send_time = now; |
| 605 | } else { |
| 606 | target_send_time = std::min(now, next_send_time); |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 |
| 611 | last_process_time_ = std::max(last_process_time_, previous_process_time); |
| 612 |
| 613 | if (is_probing) { |
| 614 | probing_send_failure_ = data_sent == DataSize::Zero(); |
| 615 | if (!probing_send_failure_) { |
| 616 | prober_.ProbeSent(CurrentTime(), data_sent); |
| 617 | } |
| 618 | } |
| 619 | } |
| 620 |
| 621 | DataSize PacingController::PaddingToAdd(DataSize recommended_probe_size, |
| 622 | DataSize data_sent) const { |
| 623 | if (!packet_queue_.Empty()) { |
| 624 | // Actual payload available, no need to add padding. |
| 625 | return DataSize::Zero(); |
| 626 | } |
| 627 |
| 628 | if (Congested()) { |
| 629 | // Don't add padding if congested, even if requested for probing. |
| 630 | return DataSize::Zero(); |
| 631 | } |
| 632 |
| 633 | if (packet_counter_ == 0) { |
| 634 | // We can not send padding unless a normal packet has first been sent. If we |
| 635 | // do, timestamps get messed up. |
| 636 | return DataSize::Zero(); |
| 637 | } |
| 638 |
| 639 | if (!recommended_probe_size.IsZero()) { |
| 640 | if (recommended_probe_size > data_sent) { |
| 641 | return recommended_probe_size - data_sent; |
| 642 | } |
| 643 | return DataSize::Zero(); |
| 644 | } |
| 645 |
| 646 | if (mode_ == ProcessMode::kPeriodic) { |
| 647 | return DataSize::Bytes(padding_budget_.bytes_remaining()); |
| 648 | } else if (padding_rate_ > DataRate::Zero() && |
| 649 | padding_debt_ == DataSize::Zero()) { |
| 650 | return padding_target_duration_ * padding_rate_; |
| 651 | } |
| 652 | return DataSize::Zero(); |
| 653 | } |
| 654 |
| 655 | std::unique_ptr<RtpPacketToSend> PacingController::GetPendingPacket( |
| 656 | const PacedPacketInfo& pacing_info, |
| 657 | Timestamp target_send_time, |
| 658 | Timestamp now) { |
| 659 | if (packet_queue_.Empty()) { |
| 660 | return nullptr; |
| 661 | } |
| 662 |
| 663 | // First, check if there is any reason _not_ to send the next queued packet. |
| 664 |
| 665 | // Unpaced audio packets and probes are exempted from send checks. |
| 666 | bool unpaced_audio_packet = |
| 667 | !pace_audio_ && packet_queue_.LeadingAudioPacketEnqueueTime().has_value(); |
| 668 | bool is_probe = pacing_info.probe_cluster_id != PacedPacketInfo::kNotAProbe; |
| 669 | if (!unpaced_audio_packet && !is_probe) { |
| 670 | if (Congested()) { |
| 671 | // Don't send anything if congested. |
| 672 | return nullptr; |
| 673 | } |
| 674 |
| 675 | if (mode_ == ProcessMode::kPeriodic) { |
| 676 | if (media_budget_.bytes_remaining() <= 0) { |
| 677 | // Not enough budget. |
| 678 | return nullptr; |
| 679 | } |
| 680 | } else { |
| 681 | // Dynamic processing mode. |
| 682 | if (now <= target_send_time) { |
| 683 | // We allow sending slightly early if we think that we would actually |
| 684 | // had been able to, had we been right on time - i.e. the current debt |
| 685 | // is not more than would be reduced to zero at the target sent time. |
| 686 | TimeDelta flush_time = media_debt_ / media_rate_; |
| 687 | if (now + flush_time > target_send_time) { |
| 688 | return nullptr; |
| 689 | } |
| 690 | } |
| 691 | } |
| 692 | } |
| 693 |
| 694 | return packet_queue_.Pop(); |
| 695 | } |
| 696 |
| 697 | void PacingController::OnPacketSent(RtpPacketMediaType packet_type, |
| 698 | DataSize packet_size, |
| 699 | Timestamp send_time) { |
| 700 | if (!first_sent_packet_time_) { |
| 701 | first_sent_packet_time_ = send_time; |
| 702 | } |
| 703 | bool audio_packet = packet_type == RtpPacketMediaType::kAudio; |
| 704 | if (!audio_packet || account_for_audio_) { |
| 705 | // Update media bytes sent. |
| 706 | UpdateBudgetWithSentData(packet_size); |
| 707 | } |
| 708 | last_send_time_ = send_time; |
| 709 | last_process_time_ = send_time; |
| 710 | } |
| 711 |
| 712 | void PacingController::OnPaddingSent(DataSize data_sent) { |
| 713 | if (data_sent > DataSize::Zero()) { |
| 714 | UpdateBudgetWithSentData(data_sent); |
| 715 | } |
| 716 | Timestamp now = CurrentTime(); |
| 717 | last_send_time_ = now; |
| 718 | last_process_time_ = now; |
| 719 | } |
| 720 |
| 721 | void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) { |
| 722 | if (mode_ == ProcessMode::kPeriodic) { |
| 723 | delta = std::min(kMaxProcessingInterval, delta); |
| 724 | media_budget_.IncreaseBudget(delta.ms()); |
| 725 | padding_budget_.IncreaseBudget(delta.ms()); |
| 726 | } else { |
| 727 | media_debt_ -= std::min(media_debt_, media_rate_ * delta); |
| 728 | padding_debt_ -= std::min(padding_debt_, padding_rate_ * delta); |
| 729 | } |
| 730 | } |
| 731 |
| 732 | void PacingController::UpdateBudgetWithSentData(DataSize size) { |
| 733 | outstanding_data_ += size; |
| 734 | if (mode_ == ProcessMode::kPeriodic) { |
| 735 | media_budget_.UseBudget(size.bytes()); |
| 736 | padding_budget_.UseBudget(size.bytes()); |
| 737 | } else { |
| 738 | media_debt_ += size; |
| 739 | media_debt_ = std::min(media_debt_, media_rate_ * kMaxDebtInTime); |
| 740 | padding_debt_ += size; |
| 741 | padding_debt_ = std::min(padding_debt_, padding_rate_ * kMaxDebtInTime); |
| 742 | } |
| 743 | } |
| 744 |
| 745 | void PacingController::SetQueueTimeLimit(TimeDelta limit) { |
| 746 | queue_time_limit = limit; |
| 747 | } |
| 748 |
| 749 | } // namespace webrtc |
| 750 |