| 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/cleanup/cleanup.h" |
| 19 | #include "absl/strings/match.h" |
| 20 | #include "api/units/data_size.h" |
| 21 | #include "api/units/time_delta.h" |
| 22 | #include "api/units/timestamp.h" |
| 23 | #include "modules/pacing/bitrate_prober.h" |
| 24 | #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" |
| 25 | #include "rtc_base/checks.h" |
| 26 | #include "rtc_base/logging.h" |
| 27 | #include "system_wrappers/include/clock.h" |
| 28 |
| 29 | namespace webrtc { |
| 30 | namespace { |
| 31 | constexpr TimeDelta kCongestedPacketInterval = TimeDelta::Millis(500); |
| 32 | // TODO(sprang): Consider dropping this limit. |
| 33 | // The maximum debt level, in terms of time, capped when sending packets. |
| 34 | constexpr TimeDelta kMaxDebtInTime = TimeDelta::Millis(500); |
| 35 | constexpr TimeDelta kMaxElapsedTime = TimeDelta::Seconds(2); |
| 36 |
| 37 | bool IsDisabled(const FieldTrialsView& field_trials, absl::string_view key) { |
| 38 | return absl::StartsWith(field_trials.Lookup(key), "Disabled"); |
| 39 | } |
| 40 |
| 41 | bool IsEnabled(const FieldTrialsView& field_trials, absl::string_view key) { |
| 42 | return absl::StartsWith(field_trials.Lookup(key), "Enabled"); |
| 43 | } |
| 44 |
| 45 | } // namespace |
| 46 |
| 47 | const TimeDelta PacingController::kPausedProcessInterval = |
| 48 | kCongestedPacketInterval; |
| 49 | const TimeDelta PacingController::kMinSleepTime = TimeDelta::Millis(1); |
| 50 | const TimeDelta PacingController::kTargetPaddingDuration = TimeDelta::Millis(5); |
| 51 | const TimeDelta PacingController::kMaxPaddingReplayDuration = |
| 52 | TimeDelta::Millis(50); |
| 53 | const TimeDelta PacingController::kMaxEarlyProbeProcessing = |
| 54 | TimeDelta::Millis(1); |
| 55 |
| 56 | PacingController::PacingController(Clock* clock, |
| 57 | PacketSender* packet_sender, |
| 58 | const FieldTrialsView& field_trials, |
| 59 | Configuration configuration) |
| 60 | : clock_(clock), |
| 61 | packet_sender_(packet_sender), |
| 62 | field_trials_(field_trials), |
| 63 | drain_large_queues_( |
| 64 | configuration.drain_large_queues && |
| 65 | !IsDisabled(field_trials_, "WebRTC-Pacer-DrainQueue")), |
| 66 | send_padding_if_silent_( |
| 67 | IsEnabled(field_trials_, "WebRTC-Pacer-PadInSilence")), |
| 68 | pace_audio_(IsEnabled(field_trials_, "WebRTC-Pacer-BlockAudio")), |
| 69 | ignore_transport_overhead_( |
| 70 | IsEnabled(field_trials_, "WebRTC-Pacer-IgnoreTransportOverhead")), |
| 71 | fast_retransmissions_( |
| 72 | IsEnabled(field_trials_, "WebRTC-Pacer-FastRetransmissions")), |
| 73 | keyframe_flushing_( |
| 74 | configuration.keyframe_flushing || |
| 75 | IsEnabled(field_trials_, "WebRTC-Pacer-KeyframeFlushing")), |
| 76 | transport_overhead_per_packet_(DataSize::Zero()), |
| 77 | send_burst_interval_(configuration.send_burst_interval), |
| 78 | last_timestamp_(clock_->CurrentTime()), |
| 79 | paused_(false), |
| 80 | media_debt_(DataSize::Zero()), |
| 81 | padding_debt_(DataSize::Zero()), |
| 82 | pacing_rate_(DataRate::Zero()), |
| 83 | adjusted_media_rate_(DataRate::Zero()), |
| 84 | padding_rate_(DataRate::Zero()), |
| 85 | prober_(field_trials_), |
| 86 | probing_send_failure_(false), |
| 87 | last_process_time_(clock->CurrentTime()), |
| 88 | last_send_time_(last_process_time_), |
| 89 | seen_first_packet_(false), |
| 90 | packet_queue_(/*creation_time=*/last_process_time_, |
| 91 | configuration.prioritize_audio_retransmission, |
| 92 | configuration.packet_queue_ttl), |
| 93 | congested_(false), |
| 94 | queue_time_limit_(configuration.queue_time_limit), |
| 95 | account_for_audio_(false), |
| 96 | include_overhead_(false), |
| 97 | circuit_breaker_threshold_(1 << 16) { |
| 98 | if (!drain_large_queues_) { |
| 99 | RTC_LOG(LS_WARNING) << "Pacer queues will not be drained," |
| 100 | "pushback experiment must be enabled."; |
| 101 | } |
| 102 | } |
| 103 |
| 104 | PacingController::~PacingController() = default; |
| 105 |
| 106 | void PacingController::CreateProbeClusters( |
| 107 | rtc::ArrayView<const ProbeClusterConfig> probe_cluster_configs) { |
| 108 | for (const ProbeClusterConfig probe_cluster_config : probe_cluster_configs) { |
| 109 | prober_.CreateProbeCluster(probe_cluster_config); |
| 110 | } |
| 111 | } |
| 112 |
| 113 | void PacingController::Pause() { |
| 114 | if (!paused_) |
| 115 | RTC_LOG(LS_INFO) << "PacedSender paused."; |
| 116 | paused_ = true; |
| 117 | packet_queue_.SetPauseState(true, CurrentTime()); |
| 118 | } |
| 119 |
| 120 | void PacingController::Resume() { |
| 121 | if (paused_) |
| 122 | RTC_LOG(LS_INFO) << "PacedSender resumed."; |
| 123 | paused_ = false; |
| 124 | packet_queue_.SetPauseState(false, CurrentTime()); |
| 125 | } |
| 126 |
| 127 | bool PacingController::IsPaused() const { |
| 128 | return paused_; |
| 129 | } |
| 130 |
| 131 | void PacingController::SetCongested(bool congested) { |
| 132 | if (congested_ && !congested) { |
| 133 | UpdateBudgetWithElapsedTime(UpdateTimeAndGetElapsed(CurrentTime())); |
| 134 | } |
| 135 | congested_ = congested; |
| 136 | } |
| 137 |
| 138 | void PacingController::SetCircuitBreakerThreshold(int num_iterations) { |
| 139 | circuit_breaker_threshold_ = num_iterations; |
| 140 | } |
| 141 |
| 142 | void PacingController::RemovePacketsForSsrc(uint32_t ssrc) { |
| 143 | packet_queue_.RemovePacketsForSsrc(ssrc); |
| 144 | } |
| 145 |
| 146 | bool PacingController::IsProbing() const { |
| 147 | return prober_.is_probing(); |
| 148 | } |
| 149 |
| 150 | Timestamp PacingController::CurrentTime() const { |
| 151 | Timestamp time = clock_->CurrentTime(); |
| 152 | if (time < last_timestamp_) { |
| 153 | RTC_LOG(LS_WARNING) |
| 154 | << "Non-monotonic clock behavior observed. Previous timestamp: " |
| 155 | << last_timestamp_.ms() << ", new timestamp: " << time.ms(); |
| 156 | RTC_DCHECK_GE(time, last_timestamp_); |
| 157 | time = last_timestamp_; |
| 158 | } |
| 159 | last_timestamp_ = time; |
| 160 | return time; |
| 161 | } |
| 162 |
| 163 | void PacingController::SetProbingEnabled(bool enabled) { |
| 164 | RTC_CHECK(!seen_first_packet_); |
| 165 | prober_.SetEnabled(enabled); |
| 166 | } |
| 167 |
| 168 | void PacingController::SetPacingRates(DataRate pacing_rate, |
| 169 | DataRate padding_rate) { |
| 170 | RTC_CHECK_GT(pacing_rate, DataRate::Zero()); |
| 171 | RTC_CHECK_GE(padding_rate, DataRate::Zero()); |
| 172 | if (padding_rate > pacing_rate) { |
| 173 | RTC_LOG(LS_WARNING) << "Padding rate " << padding_rate.kbps() |
| 174 | << "kbps is higher than the pacing rate " |
| 175 | << pacing_rate.kbps() << "kbps, capping."; |
| 176 | padding_rate = pacing_rate; |
| 177 | } |
| 178 |
| 179 | if (pacing_rate > max_rate || padding_rate > max_rate) { |
| 180 | RTC_LOG(LS_WARNING) << "Very high pacing rates ( > " << max_rate.kbps() |
| 181 | << " kbps) configured: pacing = " << pacing_rate.kbps() |
| 182 | << " kbps, padding = " << padding_rate.kbps() |
| 183 | << " kbps."; |
| 184 | max_rate = std::max(pacing_rate, padding_rate) * 1.1; |
| 185 | } |
| 186 | pacing_rate_ = pacing_rate; |
| 187 | padding_rate_ = padding_rate; |
| 188 | MaybeUpdateMediaRateDueToLongQueue(CurrentTime()); |
| 189 |
| 190 | RTC_LOG(LS_VERBOSE) << "bwe:pacer_updated pacing_kbps=" << pacing_rate_.kbps() |
| 191 | << " padding_budget_kbps=" << padding_rate.kbps(); |
| 192 | } |
| 193 |
| 194 | void PacingController::EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet) { |
| 195 | RTC_DCHECK(pacing_rate_ > DataRate::Zero()) |
| 196 | << "SetPacingRate must be called before InsertPacket."; |
| 197 | RTC_CHECK(packet->packet_type()); |
| 198 |
| 199 | if (keyframe_flushing_ && |
| 200 | packet->packet_type() == RtpPacketMediaType::kVideo && |
| 201 | packet->is_key_frame() && packet->is_first_packet_of_frame() && |
| 202 | !packet_queue_.HasKeyframePackets(packet->Ssrc())) { |
| 203 | // First packet of a keyframe (and no keyframe packets currently in the |
| 204 | // queue). Flush any pending packets currently in the queue for that stream |
| 205 | // in order to get the new keyframe out as quickly as possible. |
| 206 | packet_queue_.RemovePacketsForSsrc(packet->Ssrc()); |
| 207 | absl::optional<uint32_t> rtx_ssrc = |
| 208 | packet_sender_->GetRtxSsrcForMedia(packet->Ssrc()); |
| 209 | if (rtx_ssrc) { |
| 210 | packet_queue_.RemovePacketsForSsrc(*rtx_ssrc); |
| 211 | } |
| 212 | } |
| 213 |
| 214 | prober_.OnIncomingPacket(DataSize::Bytes(packet->payload_size())); |
| 215 |
| 216 | const Timestamp now = CurrentTime(); |
| 217 | if (packet_queue_.Empty()) { |
| 218 | // If queue is empty, we need to "fast-forward" the last process time, |
| 219 | // so that we don't use passed time as budget for sending the first new |
| 220 | // packet. |
| 221 | Timestamp target_process_time = now; |
| 222 | Timestamp next_send_time = NextSendTime(); |
| 223 | if (next_send_time.IsFinite()) { |
| 224 | // There was already a valid planned send time, such as a keep-alive. |
| 225 | // Use that as last process time only if it's prior to now. |
| 226 | target_process_time = std::min(now, next_send_time); |
| 227 | } |
| 228 | UpdateBudgetWithElapsedTime(UpdateTimeAndGetElapsed(target_process_time)); |
| 229 | } |
| 230 | packet_queue_.Push(now, std::move(packet)); |
| 231 | seen_first_packet_ = true; |
| 232 |
| 233 | // Queue length has increased, check if we need to change the pacing rate. |
| 234 | MaybeUpdateMediaRateDueToLongQueue(now); |
| 235 | } |
| 236 |
| 237 | void PacingController::SetAccountForAudioPackets(bool account_for_audio) { |
| 238 | account_for_audio_ = account_for_audio; |
| 239 | } |
| 240 |
| 241 | void PacingController::SetIncludeOverhead() { |
| 242 | include_overhead_ = true; |
| 243 | } |
| 244 |
| 245 | void PacingController::SetTransportOverhead(DataSize overhead_per_packet) { |
| 246 | if (ignore_transport_overhead_) |
| 247 | return; |
| 248 | transport_overhead_per_packet_ = overhead_per_packet; |
| 249 | } |
| 250 |
| 251 | void PacingController::SetSendBurstInterval(TimeDelta burst_interval) { |
| 252 | send_burst_interval_ = burst_interval; |
| 253 | } |
| 254 |
| 255 | void PacingController::SetAllowProbeWithoutMediaPacket(bool allow) { |
| 256 | prober_.SetAllowProbeWithoutMediaPacket(allow); |
| 257 | } |
| 258 |
| 259 | TimeDelta PacingController::ExpectedQueueTime() const { |
| 260 | RTC_DCHECK_GT(adjusted_media_rate_, DataRate::Zero()); |
| 261 | return QueueSizeData() / adjusted_media_rate_; |
| 262 | } |
| 263 |
| 264 | size_t PacingController::QueueSizePackets() const { |
| 265 | return rtc::checked_cast<size_t>(packet_queue_.SizeInPackets()); |
| 266 | } |
| 267 |
| 268 | const std::array<int, kNumMediaTypes>& |
| 269 | PacingController::SizeInPacketsPerRtpPacketMediaType() const { |
| 270 | return packet_queue_.SizeInPacketsPerRtpPacketMediaType(); |
| 271 | } |
| 272 |
| 273 | DataSize PacingController::QueueSizeData() const { |
| 274 | DataSize size = packet_queue_.SizeInPayloadBytes(); |
| 275 | if (include_overhead_) { |
| 276 | size += static_cast<int64_t>(packet_queue_.SizeInPackets()) * |
| 277 | transport_overhead_per_packet_; |
| 278 | } |
| 279 | return size; |
| 280 | } |
| 281 |
| 282 | DataSize PacingController::CurrentBufferLevel() const { |
| 283 | return std::max(media_debt_, padding_debt_); |
| 284 | } |
| 285 |
| 286 | absl::optional<Timestamp> PacingController::FirstSentPacketTime() const { |
| 287 | return first_sent_packet_time_; |
| 288 | } |
| 289 |
| 290 | Timestamp PacingController::OldestPacketEnqueueTime() const { |
| 291 | return packet_queue_.OldestEnqueueTime(); |
| 292 | } |
| 293 |
| 294 | TimeDelta PacingController::UpdateTimeAndGetElapsed(Timestamp now) { |
| 295 | // If no previous processing, or last process was "in the future" because of |
| 296 | // early probe processing, then there is no elapsed time to add budget for. |
| 297 | if (last_process_time_.IsMinusInfinity() || now < last_process_time_) { |
| 298 | return TimeDelta::Zero(); |
| 299 | } |
| 300 | TimeDelta elapsed_time = now - last_process_time_; |
| 301 | last_process_time_ = now; |
| 302 | if (elapsed_time > kMaxElapsedTime) { |
| 303 | RTC_LOG(LS_WARNING) << "Elapsed time (" << ToLogString(elapsed_time) |
| 304 | << ") longer than expected, limiting to " |
| 305 | << ToLogString(kMaxElapsedTime); |
| 306 | elapsed_time = kMaxElapsedTime; |
| 307 | } |
| 308 | return elapsed_time; |
| 309 | } |
| 310 |
| 311 | bool PacingController::ShouldSendKeepalive(Timestamp now) const { |
| 312 | if (send_padding_if_silent_ || paused_ || congested_ || !seen_first_packet_) { |
| 313 | // We send a padding packet every 500 ms to ensure we won't get stuck in |
| 314 | // congested state due to no feedback being received. |
| 315 | if (now - last_send_time_ >= kCongestedPacketInterval) { |
| 316 | return true; |
| 317 | } |
| 318 | } |
| 319 | return false; |
| 320 | } |
| 321 |
| 322 | Timestamp PacingController::NextSendTime() const { |
| 323 | const Timestamp now = CurrentTime(); |
| 324 | Timestamp next_send_time = Timestamp::PlusInfinity(); |
| 325 |
| 326 | if (paused_) { |
| 327 | return last_send_time_ + kPausedProcessInterval; |
| 328 | } |
| 329 |
| 330 | // If probing is active, that always takes priority. |
| 331 | if (prober_.is_probing() && !probing_send_failure_) { |
| 332 | Timestamp probe_time = prober_.NextProbeTime(now); |
| 333 | if (!probe_time.IsPlusInfinity()) { |
| 334 | return probe_time.IsMinusInfinity() ? now : probe_time; |
| 335 | } |
| 336 | } |
| 337 |
| 338 | // If queue contains a packet which should not be paced, its target send time |
| 339 | // is the time at which it was enqueued. |
| 340 | Timestamp unpaced_send_time = NextUnpacedSendTime(); |
| 341 | if (unpaced_send_time.IsFinite()) { |
| 342 | return unpaced_send_time; |
| 343 | } |
| 344 |
| 345 | if (congested_ || !seen_first_packet_) { |
| 346 | // We need to at least send keep-alive packets with some interval. |
| 347 | return last_send_time_ + kCongestedPacketInterval; |
| 348 | } |
| 349 |
| 350 | if (adjusted_media_rate_ > DataRate::Zero() && !packet_queue_.Empty()) { |
| 351 | // If packets are allowed to be sent in a burst, the |
| 352 | // debt is allowed to grow up to one packet more than what can be sent |
| 353 | // during 'send_burst_period_'. |
| 354 | TimeDelta drain_time = media_debt_ / adjusted_media_rate_; |
| 355 | // Ensure that a burst of sent packet is not larger than kMaxBurstSize in |
| 356 | // order to not risk overfilling socket buffers at high bitrate. |
| 357 | TimeDelta send_burst_interval = |
| 358 | std::min(send_burst_interval_, kMaxBurstSize / adjusted_media_rate_); |
| 359 | next_send_time = |
| 360 | last_process_time_ + |
| 361 | ((send_burst_interval > drain_time) ? TimeDelta::Zero() : drain_time); |
| 362 | } else if (padding_rate_ > DataRate::Zero() && packet_queue_.Empty()) { |
| 363 | // If we _don't_ have pending packets, check how long until we have |
| 364 | // bandwidth for padding packets. Both media and padding debts must |
| 365 | // have been drained to do this. |
| 366 | RTC_DCHECK_GT(adjusted_media_rate_, DataRate::Zero()); |
| 367 | TimeDelta drain_time = std::max(media_debt_ / adjusted_media_rate_, |
| 368 | padding_debt_ / padding_rate_); |
| 369 |
| 370 | if (drain_time.IsZero() && |
| 371 | (!media_debt_.IsZero() || !padding_debt_.IsZero())) { |
| 372 | // We have a non-zero debt, but drain time is smaller than tick size of |
| 373 | // TimeDelta, round it up to the smallest possible non-zero delta. |
| 374 | drain_time = TimeDelta::Micros(1); |
| 375 | } |
| 376 | next_send_time = last_process_time_ + drain_time; |
| 377 | } else { |
| 378 | // Nothing to do. |
| 379 | next_send_time = last_process_time_ + kPausedProcessInterval; |
| 380 | } |
| 381 |
| 382 | if (send_padding_if_silent_) { |
| 383 | next_send_time = |
| 384 | std::min(next_send_time, last_send_time_ + kPausedProcessInterval); |
| 385 | } |
| 386 |
| 387 | return next_send_time; |
| 388 | } |
| 389 |
| 390 | void PacingController::ProcessPackets() { |
| 391 | absl::Cleanup cleanup = [packet_sender = packet_sender_] { |
| 392 | packet_sender->OnBatchComplete(); |
| 393 | }; |
| 394 | const Timestamp now = CurrentTime(); |
| 395 | Timestamp target_send_time = now; |
| 396 |
| 397 | if (ShouldSendKeepalive(now)) { |
| 398 | DataSize keepalive_data_sent = DataSize::Zero(); |
| 399 | // We can not send padding unless a normal packet has first been sent. If |
| 400 | // we do, timestamps get messed up. |
| 401 | if (seen_first_packet_) { |
| 402 | std::vector<std::unique_ptr<RtpPacketToSend>> keepalive_packets = |
| 403 | packet_sender_->GeneratePadding(DataSize::Bytes(1)); |
| 404 | for (auto& packet : keepalive_packets) { |
| 405 | keepalive_data_sent += |
| 406 | DataSize::Bytes(packet->payload_size() + packet->padding_size()); |
| 407 | packet_sender_->SendPacket(std::move(packet), PacedPacketInfo()); |
| 408 | for (auto& packet : packet_sender_->FetchFec()) { |
| 409 | EnqueuePacket(std::move(packet)); |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | OnPacketSent(RtpPacketMediaType::kPadding, keepalive_data_sent, now); |
| 414 | } |
| 415 |
| 416 | if (paused_) { |
| 417 | return; |
| 418 | } |
| 419 |
| 420 | TimeDelta early_execute_margin = |
| 421 | prober_.is_probing() ? kMaxEarlyProbeProcessing : TimeDelta::Zero(); |
| 422 |
| 423 | target_send_time = NextSendTime(); |
| 424 | if (now + early_execute_margin < target_send_time) { |
| 425 | // We are too early, but if queue is empty still allow draining some debt. |
| 426 | // Probing is allowed to be sent up to kMinSleepTime early. |
| 427 | UpdateBudgetWithElapsedTime(UpdateTimeAndGetElapsed(now)); |
| 428 | return; |
| 429 | } |
| 430 |
| 431 | TimeDelta elapsed_time = UpdateTimeAndGetElapsed(target_send_time); |
| 432 |
| 433 | if (elapsed_time > TimeDelta::Zero()) { |
| 434 | UpdateBudgetWithElapsedTime(elapsed_time); |
| 435 | } |
| 436 |
| 437 | PacedPacketInfo pacing_info; |
| 438 | DataSize recommended_probe_size = DataSize::Zero(); |
| 439 | bool is_probing = prober_.is_probing(); |
| 440 | if (is_probing) { |
| 441 | // Probe timing is sensitive, and handled explicitly by BitrateProber, so |
| 442 | // use actual send time rather than target. |
| 443 | pacing_info = prober_.CurrentCluster(now).value_or(PacedPacketInfo()); |
| 444 | if (pacing_info.probe_cluster_id != PacedPacketInfo::kNotAProbe) { |
| 445 | recommended_probe_size = prober_.RecommendedMinProbeSize(); |
| 446 | RTC_DCHECK_GT(recommended_probe_size, DataSize::Zero()); |
| 447 | } else { |
| 448 | // No valid probe cluster returned, probe might have timed out. |
| 449 | is_probing = false; |
| 450 | } |
| 451 | } |
| 452 |
| 453 | DataSize data_sent = DataSize::Zero(); |
| 454 | int iteration = 0; |
| 455 | int packets_sent = 0; |
| 456 | int padding_packets_generated = 0; |
| 457 | for (; iteration < circuit_breaker_threshold_; ++iteration) { |
| 458 | // Fetch packet, so long as queue is not empty or budget is not |
| 459 | // exhausted. |
| 460 | std::unique_ptr<RtpPacketToSend> rtp_packet = |
| 461 | GetPendingPacket(pacing_info, target_send_time, now); |
| 462 | if (rtp_packet == nullptr) { |
| 463 | // No packet available to send, check if we should send padding. |
| 464 | if (now - target_send_time > kMaxPaddingReplayDuration) { |
| 465 | // The target send time is more than `kMaxPaddingReplayDuration` behind |
| 466 | // the real-time clock. This can happen if the clock is adjusted forward |
| 467 | // without `ProcessPackets()` having been called at the expected times. |
| 468 | target_send_time = now - kMaxPaddingReplayDuration; |
| 469 | last_process_time_ = std::max(last_process_time_, target_send_time); |
| 470 | } |
| 471 |
| 472 | DataSize padding_to_add = PaddingToAdd(recommended_probe_size, data_sent); |
| 473 | if (padding_to_add > DataSize::Zero()) { |
| 474 | std::vector<std::unique_ptr<RtpPacketToSend>> padding_packets = |
| 475 | packet_sender_->GeneratePadding(padding_to_add); |
| 476 | if (!padding_packets.empty()) { |
| 477 | padding_packets_generated += padding_packets.size(); |
| 478 | for (auto& packet : padding_packets) { |
| 479 | EnqueuePacket(std::move(packet)); |
| 480 | } |
| 481 | // Continue loop to send the padding that was just added. |
| 482 | continue; |
| 483 | } else { |
| 484 | // Can't generate padding, still update padding budget for next send |
| 485 | // time. |
| 486 | UpdatePaddingBudgetWithSentData(padding_to_add); |
| 487 | } |
| 488 | } |
| 489 | // Can't fetch new packet and no padding to send, exit send loop. |
| 490 | break; |
| 491 | } else { |
| 492 | RTC_DCHECK(rtp_packet); |
| 493 | RTC_DCHECK(rtp_packet->packet_type().has_value()); |
| 494 | const RtpPacketMediaType packet_type = *rtp_packet->packet_type(); |
| 495 | DataSize packet_size = DataSize::Bytes(rtp_packet->payload_size() + |
| 496 | rtp_packet->padding_size()); |
| 497 |
| 498 | if (include_overhead_) { |
| 499 | packet_size += DataSize::Bytes(rtp_packet->headers_size()) + |
| 500 | transport_overhead_per_packet_; |
| 501 | } |
| 502 |
| 503 | packet_sender_->SendPacket(std::move(rtp_packet), pacing_info); |
| 504 | for (auto& packet : packet_sender_->FetchFec()) { |
| 505 | EnqueuePacket(std::move(packet)); |
| 506 | } |
| 507 | data_sent += packet_size; |
| 508 | ++packets_sent; |
| 509 |
| 510 | // Send done, update send time. |
| 511 | OnPacketSent(packet_type, packet_size, now); |
| 512 |
| 513 | if (is_probing) { |
| 514 | pacing_info.probe_cluster_bytes_sent += packet_size.bytes(); |
| 515 | // If we are currently probing, we need to stop the send loop when we |
| 516 | // have reached the send target. |
| 517 | if (data_sent >= recommended_probe_size) { |
| 518 | break; |
| 519 | } |
| 520 | } |
| 521 |
| 522 | // Update target send time in case that are more packets that we are late |
| 523 | // in processing. |
| 524 | target_send_time = NextSendTime(); |
| 525 | if (target_send_time > now) { |
| 526 | // Exit loop if not probing. |
| 527 | if (!is_probing) { |
| 528 | break; |
| 529 | } |
| 530 | target_send_time = now; |
| 531 | } |
| 532 | UpdateBudgetWithElapsedTime(UpdateTimeAndGetElapsed(target_send_time)); |
| 533 | } |
| 534 | } |
| 535 |
| 536 | if (iteration >= circuit_breaker_threshold_) { |
| 537 | // Circuit break activated. Log warning, adjust send time and return. |
| 538 | // TODO(sprang): Consider completely clearing state. |
| 539 | RTC_LOG(LS_ERROR) |
| 540 | << "PacingController exceeded max iterations in " |
| 541 | "send-loop. Debug info: " |
| 542 | << " packets sent = " << packets_sent |
| 543 | << ", padding packets generated = " << padding_packets_generated |
| 544 | << ", bytes sent = " << data_sent.bytes() |
| 545 | << ", probing = " << (is_probing ? "true" : "false") |
| 546 | << ", recommended_probe_size = " << recommended_probe_size.bytes() |
| 547 | << ", now = " << now.us() |
| 548 | << ", target_send_time = " << target_send_time.us() |
| 549 | << ", last_process_time = " << last_process_time_.us() |
| 550 | << ", last_send_time = " << last_send_time_.us() |
| 551 | << ", paused = " << (paused_ ? "true" : "false") |
| 552 | << ", media_debt = " << media_debt_.bytes() |
| 553 | << ", padding_debt = " << padding_debt_.bytes() |
| 554 | << ", pacing_rate = " << pacing_rate_.bps() |
| 555 | << ", adjusted_media_rate = " << adjusted_media_rate_.bps() |
| 556 | << ", padding_rate = " << padding_rate_.bps() |
| 557 | << ", queue size (packets) = " << packet_queue_.SizeInPackets() |
| 558 | << ", queue size (payload bytes) = " |
| 559 | << packet_queue_.SizeInPayloadBytes(); |
| 560 | last_send_time_ = now; |
| 561 | last_process_time_ = now; |
| 562 | return; |
| 563 | } |
| 564 |
| 565 | if (is_probing) { |
| 566 | probing_send_failure_ = data_sent == DataSize::Zero(); |
| 567 | if (!probing_send_failure_) { |
| 568 | prober_.ProbeSent(CurrentTime(), data_sent); |
| 569 | } |
| 570 | } |
| 571 |
| 572 | // Queue length has probably decreased, check if pacing rate needs to updated. |
| 573 | // Poll the time again, since we might have enqueued new fec/padding packets |
| 574 | // with a later timestamp than `now`. |
| 575 | MaybeUpdateMediaRateDueToLongQueue(CurrentTime()); |
| 576 | } |
| 577 |
| 578 | DataSize PacingController::PaddingToAdd(DataSize recommended_probe_size, |
| 579 | DataSize data_sent) const { |
| 580 | if (!packet_queue_.Empty()) { |
| 581 | // Actual payload available, no need to add padding. |
| 582 | return DataSize::Zero(); |
| 583 | } |
| 584 |
| 585 | if (congested_) { |
| 586 | // Don't add padding if congested, even if requested for probing. |
| 587 | return DataSize::Zero(); |
| 588 | } |
| 589 |
| 590 | if (!recommended_probe_size.IsZero()) { |
| 591 | if (recommended_probe_size > data_sent) { |
| 592 | return recommended_probe_size - data_sent; |
| 593 | } |
| 594 | return DataSize::Zero(); |
| 595 | } |
| 596 |
| 597 | if (padding_rate_ > DataRate::Zero() && padding_debt_ == DataSize::Zero()) { |
| 598 | return kTargetPaddingDuration * padding_rate_; |
| 599 | } |
| 600 | return DataSize::Zero(); |
| 601 | } |
| 602 |
| 603 | std::unique_ptr<RtpPacketToSend> PacingController::GetPendingPacket( |
| 604 | const PacedPacketInfo& pacing_info, |
| 605 | Timestamp target_send_time, |
| 606 | Timestamp now) { |
| 607 | const bool is_probe = |
| 608 | pacing_info.probe_cluster_id != PacedPacketInfo::kNotAProbe; |
| 609 | // If first packet in probe, insert a small padding packet so we have a |
| 610 | // more reliable start window for the rate estimation. |
| 611 | if (is_probe && pacing_info.probe_cluster_bytes_sent == 0) { |
| 612 | auto padding = packet_sender_->GeneratePadding(DataSize::Bytes(1)); |
| 613 | // If no RTP modules sending media are registered, we may not get a |
| 614 | // padding packet back. |
| 615 | if (!padding.empty()) { |
| 616 | // We should never get more than one padding packets with a requested |
| 617 | // size of 1 byte. |
| 618 | RTC_DCHECK_EQ(padding.size(), 1u); |
| 619 | return std::move(padding[0]); |
| 620 | } |
| 621 | } |
| 622 |
| 623 | if (packet_queue_.Empty()) { |
| 624 | return nullptr; |
| 625 | } |
| 626 |
| 627 | // First, check if there is any reason _not_ to send the next queued packet. |
| 628 | // Unpaced packets and probes are exempted from send checks. |
| 629 | if (NextUnpacedSendTime().IsInfinite() && !is_probe) { |
| 630 | if (congested_) { |
| 631 | // Don't send anything if congested. |
| 632 | return nullptr; |
| 633 | } |
| 634 |
| 635 | if (now <= target_send_time && send_burst_interval_.IsZero()) { |
| 636 | // We allow sending slightly early if we think that we would actually |
| 637 | // had been able to, had we been right on time - i.e. the current debt |
| 638 | // is not more than would be reduced to zero at the target sent time. |
| 639 | // If we allow packets to be sent in a burst, packet are allowed to be |
| 640 | // sent early. |
| 641 | TimeDelta flush_time = media_debt_ / adjusted_media_rate_; |
| 642 | if (now + flush_time > target_send_time) { |
| 643 | return nullptr; |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 |
| 648 | return packet_queue_.Pop(); |
| 649 | } |
| 650 |
| 651 | void PacingController::OnPacketSent(RtpPacketMediaType packet_type, |
| 652 | DataSize packet_size, |
| 653 | Timestamp send_time) { |
| 654 | if (!first_sent_packet_time_ && packet_type != RtpPacketMediaType::kPadding) { |
| 655 | first_sent_packet_time_ = send_time; |
| 656 | } |
| 657 |
| 658 | bool audio_packet = packet_type == RtpPacketMediaType::kAudio; |
| 659 | if ((!audio_packet || account_for_audio_) && packet_size > DataSize::Zero()) { |
| 660 | UpdateBudgetWithSentData(packet_size); |
| 661 | } |
| 662 |
| 663 | last_send_time_ = send_time; |
| 664 | } |
| 665 |
| 666 | void PacingController::UpdateBudgetWithElapsedTime(TimeDelta delta) { |
| 667 | media_debt_ -= std::min(media_debt_, adjusted_media_rate_ * delta); |
| 668 | padding_debt_ -= std::min(padding_debt_, padding_rate_ * delta); |
| 669 | } |
| 670 |
| 671 | void PacingController::UpdateBudgetWithSentData(DataSize size) { |
| 672 | media_debt_ += size; |
| 673 | media_debt_ = std::min(media_debt_, adjusted_media_rate_ * kMaxDebtInTime); |
| 674 | UpdatePaddingBudgetWithSentData(size); |
| 675 | } |
| 676 |
| 677 | void PacingController::UpdatePaddingBudgetWithSentData(DataSize size) { |
| 678 | padding_debt_ += size; |
| 679 | padding_debt_ = std::min(padding_debt_, padding_rate_ * kMaxDebtInTime); |
| 680 | } |
| 681 |
| 682 | void PacingController::SetQueueTimeLimit(TimeDelta limit) { |
| 683 | queue_time_limit_ = limit; |
| 684 | } |
| 685 |
| 686 | void PacingController::MaybeUpdateMediaRateDueToLongQueue(Timestamp now) { |
| 687 | adjusted_media_rate_ = pacing_rate_; |
| 688 | if (!drain_large_queues_) { |
| 689 | return; |
| 690 | } |
| 691 |
| 692 | DataSize queue_size_data = QueueSizeData(); |
| 693 | if (queue_size_data > DataSize::Zero()) { |
| 694 | // Assuming equal size packets and input/output rate, the average packet |
| 695 | // has avg_time_left_ms left to get queue_size_bytes out of the queue, if |
| 696 | // time constraint shall be met. Determine bitrate needed for that. |
| 697 | packet_queue_.UpdateAverageQueueTime(now); |
| 698 | TimeDelta avg_time_left = |
| 699 | std::max(TimeDelta::Millis(1), |
| 700 | queue_time_limit_ - packet_queue_.AverageQueueTime()); |
| 701 | DataRate min_rate_needed = queue_size_data / avg_time_left; |
| 702 | if (min_rate_needed > pacing_rate_) { |
| 703 | adjusted_media_rate_ = min_rate_needed; |
| 704 | RTC_LOG(LS_VERBOSE) << "bwe:large_pacing_queue pacing_rate_kbps=" |
| 705 | << pacing_rate_.kbps(); |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 |
| 710 | Timestamp PacingController::NextUnpacedSendTime() const { |
| 711 | if (!pace_audio_) { |
| 712 | Timestamp leading_audio_send_time = |
| 713 | packet_queue_.LeadingPacketEnqueueTime(RtpPacketMediaType::kAudio); |
| 714 | if (leading_audio_send_time.IsFinite()) { |
| 715 | return leading_audio_send_time; |
| 716 | } |
| 717 | } |
| 718 | if (fast_retransmissions_) { |
| 719 | Timestamp leading_retransmission_send_time = |
| 720 | packet_queue_.LeadingPacketEnqueueTimeForRetransmission(); |
| 721 | if (leading_retransmission_send_time.IsFinite()) { |
| 722 | return leading_retransmission_send_time; |
| 723 | } |
| 724 | } |
| 725 | return Timestamp::MinusInfinity(); |
| 726 | } |
| 727 |
| 728 | } // namespace webrtc |
| 729 |