| 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 | #ifndef MODULES_PACING_PACING_CONTROLLER_H_ |
| 12 | #define MODULES_PACING_PACING_CONTROLLER_H_ |
| 13 |
| 14 | #include <stddef.h> |
| 15 | #include <stdint.h> |
| 16 |
| 17 | #include <array> |
| 18 | #include <atomic> |
| 19 | #include <memory> |
| 20 | #include <vector> |
| 21 |
| 22 | #include "absl/types/optional.h" |
| 23 | #include "api/field_trials_view.h" |
| 24 | #include "api/function_view.h" |
| 25 | #include "api/transport/field_trial_based_config.h" |
| 26 | #include "api/transport/network_types.h" |
| 27 | #include "api/units/data_size.h" |
| 28 | #include "api/units/time_delta.h" |
| 29 | #include "modules/pacing/bitrate_prober.h" |
| 30 | #include "modules/pacing/interval_budget.h" |
| 31 | #include "modules/pacing/prioritized_packet_queue.h" |
| 32 | #include "modules/pacing/rtp_packet_pacer.h" |
| 33 | #include "modules/rtp_rtcp/include/rtp_packet_sender.h" |
| 34 | #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" |
| 35 | #include "modules/rtp_rtcp/source/rtp_packet_to_send.h" |
| 36 | #include "rtc_base/experiments/field_trial_parser.h" |
| 37 | #include "rtc_base/thread_annotations.h" |
| 38 |
| 39 | namespace webrtc { |
| 40 |
| 41 | // This class implements a leaky-bucket packet pacing algorithm. It handles the |
| 42 | // logic of determining which packets to send when, but the actual timing of |
| 43 | // the processing is done externally (e.g. RtpPacketPacer). Furthermore, the |
| 44 | // forwarding of packets when they are ready to be sent is also handled |
| 45 | // externally, via the PacingController::PacketSender interface. |
| 46 | class PacingController { |
| 47 | public: |
| 48 | class PacketSender { |
| 49 | public: |
| 50 | virtual ~PacketSender() = default; |
| 51 | virtual void SendPacket(std::unique_ptr<RtpPacketToSend> packet, |
| 52 | const PacedPacketInfo& cluster_info) = 0; |
| 53 | // Should be called after each call to SendPacket(). |
| 54 | virtual std::vector<std::unique_ptr<RtpPacketToSend>> FetchFec() = 0; |
| 55 | virtual std::vector<std::unique_ptr<RtpPacketToSend>> GeneratePadding( |
| 56 | DataSize size) = 0; |
| 57 | // TODO(bugs.webrtc.org/1439830): Make pure virtual once subclasses adapt. |
| 58 | virtual void OnBatchComplete() {} |
| 59 |
| 60 | // TODO(bugs.webrtc.org/11340): Make pure virtual once downstream projects |
| 61 | // have been updated. |
| 62 | virtual void OnAbortedRetransmissions( |
| 63 | uint32_t ssrc, |
| 64 | rtc::ArrayView<const uint16_t> sequence_numbers) {} |
| 65 | virtual absl::optional<uint32_t> GetRtxSsrcForMedia(uint32_t ssrc) const { |
| 66 | return absl::nullopt; |
| 67 | } |
| 68 | }; |
| 69 |
| 70 | // If no media or paused, wake up at least every `kPausedProcessIntervalMs` in |
| 71 | // order to send a keep-alive packet so we don't get stuck in a bad state due |
| 72 | // to lack of feedback. |
| 73 | static const TimeDelta kPausedProcessInterval; |
| 74 | // The default minimum time that should elapse calls to `ProcessPackets()`. |
| 75 | static const TimeDelta kMinSleepTime; |
| 76 | // When padding should be generated, add packets to the buffer with a size |
| 77 | // corresponding to this duration times the current padding rate. |
| 78 | static const TimeDelta kTargetPaddingDuration; |
| 79 | // The maximum time that the pacer can use when "replaying" passed time where |
| 80 | // padding should have been generated. |
| 81 | static const TimeDelta kMaxPaddingReplayDuration; |
| 82 | // Allow probes to be processed slightly ahead of inteded send time. Currently |
| 83 | // set to 1ms as this is intended to allow times be rounded down to the |
| 84 | // nearest millisecond. |
| 85 | static const TimeDelta kMaxEarlyProbeProcessing; |
| 86 | // Max total size of packets expected to be sent in a burst in order to not |
| 87 | // risk loosing packets due to too small send socket buffers. It upper limits |
| 88 | // the send burst interval. |
| 89 | // Ex: max send burst interval = 63Kb / 10Mbit/s = 50ms. |
| 90 | static constexpr DataSize kMaxBurstSize = DataSize::Bytes(63 * 1000); |
| 91 |
| 92 | // Configuration default values. |
| 93 | static constexpr TimeDelta kDefaultBurstInterval = TimeDelta::Millis(40); |
| 94 | static constexpr TimeDelta kMaxExpectedQueueLength = TimeDelta::Millis(2000); |
| 95 |
| 96 | struct Configuration { |
| 97 | // If the pacer queue grows longer than the configured max queue limit, |
| 98 | // pacer sends at the minimum rate needed to keep the max queue limit and |
| 99 | // ignore the current bandwidth estimate. |
| 100 | bool drain_large_queues = true; |
| 101 | // Expected max pacer delay. If ExpectedQueueTime() is higher than |
| 102 | // this value, the packet producers should wait (eg drop frames rather than |
| 103 | // encoding them). Bitrate sent may temporarily exceed target set by |
| 104 | // SetPacingRates() so that this limit will be upheld if |
| 105 | // `drain_large_queues` is set. |
| 106 | TimeDelta queue_time_limit = kMaxExpectedQueueLength; |
| 107 | // If the first packet of a keyframe is enqueued on a RTP stream, pacer |
| 108 | // skips forward to that packet and drops other enqueued packets on that |
| 109 | // stream, unless a keyframe is already being paced. |
| 110 | bool keyframe_flushing = false; |
| 111 | // Audio retransmission is prioritized before video retransmission packets. |
| 112 | bool prioritize_audio_retransmission = false; |
| 113 | // Configure separate timeouts per priority. After a timeout, a packet of |
| 114 | // that sort will not be paced and instead dropped. |
| 115 | // Note: to set TTL on audio retransmission, |
| 116 | // `prioritize_audio_retransmission` must be true. |
| 117 | PacketQueueTTL packet_queue_ttl; |
| 118 | // The pacer is allowed to send enqueued packets in bursts and can build up |
| 119 | // a packet "debt" that correspond to approximately the send rate during the |
| 120 | // burst interval. |
| 121 | TimeDelta send_burst_interval = kDefaultBurstInterval; |
| 122 | }; |
| 123 |
| 124 | static Configuration DefaultConfiguration() { return Configuration{}; } |
| 125 |
| 126 | PacingController(Clock* clock, |
| 127 | PacketSender* packet_sender, |
| 128 | const FieldTrialsView& field_trials, |
| 129 | Configuration configuration = DefaultConfiguration()); |
| 130 |
| 131 | ~PacingController(); |
| 132 |
| 133 | // Adds the packet to the queue and calls PacketRouter::SendPacket() when |
| 134 | // it's time to send. |
| 135 | void EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet); |
| 136 |
| 137 | void CreateProbeClusters( |
| 138 | rtc::ArrayView<const ProbeClusterConfig> probe_cluster_configs); |
| 139 |
| 140 | void Pause(); // Temporarily pause all sending. |
| 141 | void Resume(); // Resume sending packets. |
| 142 | bool IsPaused() const; |
| 143 |
| 144 | void SetCongested(bool congested); |
| 145 |
| 146 | // Sets the pacing rates. Must be called once before packets can be sent. |
| 147 | void SetPacingRates(DataRate pacing_rate, DataRate padding_rate); |
| 148 | DataRate pacing_rate() const { return adjusted_media_rate_; } |
| 149 |
| 150 | // Currently audio traffic is not accounted by pacer and passed through. |
| 151 | // With the introduction of audio BWE audio traffic will be accounted for |
| 152 | // the pacer budget calculation. The audio traffic still will be injected |
| 153 | // at high priority. |
| 154 | void SetAccountForAudioPackets(bool account_for_audio); |
| 155 | void SetIncludeOverhead(); |
| 156 |
| 157 | void SetTransportOverhead(DataSize overhead_per_packet); |
| 158 | // The pacer is allowed to send enqued packets in bursts and can build up a |
| 159 | // packet "debt" that correspond to approximately the send rate during |
| 160 | // 'burst_interval'. |
| 161 | void SetSendBurstInterval(TimeDelta burst_interval); |
| 162 |
| 163 | // A probe may be sent without first waing for a media packet. |
| 164 | void SetAllowProbeWithoutMediaPacket(bool allow); |
| 165 |
| 166 | // Returns the time when the oldest packet was queued. |
| 167 | Timestamp OldestPacketEnqueueTime() const; |
| 168 |
| 169 | // Number of packets in the pacer queue. |
| 170 | size_t QueueSizePackets() const; |
| 171 | // Number of packets in the pacer queue per media type (RtpPacketMediaType |
| 172 | // values are used as lookup index). |
| 173 | const std::array<int, kNumMediaTypes>& SizeInPacketsPerRtpPacketMediaType() |
| 174 | const; |
| 175 | // Totals size of packets in the pacer queue. |
| 176 | DataSize QueueSizeData() const; |
| 177 |
| 178 | // Current buffer level, i.e. max of media and padding debt. |
| 179 | DataSize CurrentBufferLevel() const; |
| 180 |
| 181 | // Returns the time when the first packet was sent. |
| 182 | absl::optional<Timestamp> FirstSentPacketTime() const; |
| 183 |
| 184 | // Returns the number of milliseconds it will take to send the current |
| 185 | // packets in the queue, given the current size and bitrate, ignoring prio. |
| 186 | TimeDelta ExpectedQueueTime() const; |
| 187 |
| 188 | void SetQueueTimeLimit(TimeDelta limit); |
| 189 |
| 190 | // Enable bitrate probing. Enabled by default, mostly here to simplify |
| 191 | // testing. Must be called before any packets are being sent to have an |
| 192 | // effect. |
| 193 | void SetProbingEnabled(bool enabled); |
| 194 |
| 195 | // Returns the next time we expect ProcessPackets() to be called. |
| 196 | Timestamp NextSendTime() const; |
| 197 |
| 198 | // Check queue of pending packets and send them or padding packets, if budget |
| 199 | // is available. |
| 200 | void ProcessPackets(); |
| 201 |
| 202 | bool IsProbing() const; |
| 203 |
| 204 | // Note: Intended for debugging purposes only, will be removed. |
| 205 | // Sets the number of iterations of the main loop in `ProcessPackets()` that |
| 206 | // is considered erroneous to exceed. |
| 207 | void SetCircuitBreakerThreshold(int num_iterations); |
| 208 |
| 209 | // Remove any pending packets matching this SSRC from the packet queue. |
| 210 | void RemovePacketsForSsrc(uint32_t ssrc); |
| 211 |
| 212 | private: |
| 213 | TimeDelta UpdateTimeAndGetElapsed(Timestamp now); |
| 214 | bool ShouldSendKeepalive(Timestamp now) const; |
| 215 |
| 216 | // Updates the number of bytes that can be sent for the next time interval. |
| 217 | void UpdateBudgetWithElapsedTime(TimeDelta delta); |
| 218 | void UpdateBudgetWithSentData(DataSize size); |
| 219 | void UpdatePaddingBudgetWithSentData(DataSize size); |
| 220 |
| 221 | DataSize PaddingToAdd(DataSize recommended_probe_size, |
| 222 | DataSize data_sent) const; |
| 223 |
| 224 | std::unique_ptr<RtpPacketToSend> GetPendingPacket( |
| 225 | const PacedPacketInfo& pacing_info, |
| 226 | Timestamp target_send_time, |
| 227 | Timestamp now); |
| 228 | void OnPacketSent(RtpPacketMediaType packet_type, |
| 229 | DataSize packet_size, |
| 230 | Timestamp send_time); |
| 231 | void MaybeUpdateMediaRateDueToLongQueue(Timestamp now); |
| 232 |
| 233 | Timestamp CurrentTime() const; |
| 234 |
| 235 | // Helper methods for packet that may not be paced. Returns a finite Timestamp |
| 236 | // if a packet type is configured to not be paced and the packet queue has at |
| 237 | // least one packet of that type. Otherwise returns |
| 238 | // Timestamp::MinusInfinity(). |
| 239 | Timestamp NextUnpacedSendTime() const; |
| 240 |
| 241 | Clock* const clock_; |
| 242 | PacketSender* const packet_sender_; |
| 243 | const FieldTrialsView& field_trials_; |
| 244 |
| 245 | const bool drain_large_queues_; |
| 246 | const bool send_padding_if_silent_; |
| 247 | const bool pace_audio_; |
| 248 | const bool ignore_transport_overhead_; |
| 249 | const bool fast_retransmissions_; |
| 250 | const bool keyframe_flushing_; |
| 251 | DataRate max_rate = DataRate::BitsPerSec(100'000'000); |
| 252 | DataSize transport_overhead_per_packet_; |
| 253 | TimeDelta send_burst_interval_; |
| 254 |
| 255 | // TODO(webrtc:9716): Remove this when we are certain clocks are monotonic. |
| 256 | // The last millisecond timestamp returned by `clock_`. |
| 257 | mutable Timestamp last_timestamp_; |
| 258 | bool paused_; |
| 259 |
| 260 | // Amount of outstanding data for media and padding. |
| 261 | DataSize media_debt_; |
| 262 | DataSize padding_debt_; |
| 263 |
| 264 | // The target pacing rate, signaled via SetPacingRates(). |
| 265 | DataRate pacing_rate_; |
| 266 | // The media send rate, which might adjusted from pacing_rate_, e.g. if the |
| 267 | // pacing queue is growing too long. |
| 268 | DataRate adjusted_media_rate_; |
| 269 | // The padding target rate. We aim to fill up to this rate with padding what |
| 270 | // is not already used by media. |
| 271 | DataRate padding_rate_; |
| 272 |
| 273 | BitrateProber prober_; |
| 274 | bool probing_send_failure_; |
| 275 |
| 276 | Timestamp last_process_time_; |
| 277 | Timestamp last_send_time_; |
| 278 | absl::optional<Timestamp> first_sent_packet_time_; |
| 279 | bool seen_first_packet_; |
| 280 |
| 281 | PrioritizedPacketQueue packet_queue_; |
| 282 |
| 283 | bool congested_; |
| 284 |
| 285 | TimeDelta queue_time_limit_; |
| 286 | bool account_for_audio_; |
| 287 | bool include_overhead_; |
| 288 |
| 289 | int circuit_breaker_threshold_; |
| 290 | }; |
| 291 | } // namespace webrtc |
| 292 |
| 293 | #endif // MODULES_PACING_PACING_CONTROLLER_H_ |
| 294 |