blob: 0948616919137a4ef15ab247ea4c1da06025a6b1 [file] [log] [blame]
Erik Språngd05edec2019-08-14 10:43:47 +02001/*
2 * Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#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 <atomic>
18#include <memory>
19#include <vector>
20
21#include "absl/types/optional.h"
22#include "api/function_view.h"
23#include "api/rtc_event_log/rtc_event_log.h"
24#include "api/transport/field_trial_based_config.h"
25#include "api/transport/network_types.h"
26#include "api/transport/webrtc_key_value_config.h"
27#include "modules/pacing/bitrate_prober.h"
28#include "modules/pacing/interval_budget.h"
29#include "modules/pacing/round_robin_packet_queue.h"
30#include "modules/pacing/rtp_packet_pacer.h"
31#include "modules/rtp_rtcp/include/rtp_packet_sender.h"
32#include "modules/rtp_rtcp/source/rtp_packet_to_send.h"
33#include "rtc_base/critical_section.h"
34#include "rtc_base/experiments/field_trial_parser.h"
35#include "rtc_base/thread_annotations.h"
36
37namespace webrtc {
38
39// This class implements a leaky-buck packet pacing algorithm. It handles the
40// logic of determining which packets to send when, but the actual timing of
41// the processing is done externally (e.g. PacedSender). Furthermore, the
42// forwarding of packets when they are ready to be sent is also handled
43// externally, via the PacedSendingController::PacketSender interface.
44//
45class PacingController {
46 public:
47 class PacketSender {
48 public:
49 virtual ~PacketSender() = default;
50 virtual void SendRtpPacket(std::unique_ptr<RtpPacketToSend> packet,
51 const PacedPacketInfo& cluster_info) = 0;
52 virtual std::vector<std::unique_ptr<RtpPacketToSend>> GeneratePadding(
53 DataSize size) = 0;
54
55 // TODO(bugs.webrtc.org/10633): Remove these when old code path is gone.
56 virtual RtpPacketSendResult TimeToSendPacket(
57 uint32_t ssrc,
58 uint16_t sequence_number,
59 int64_t capture_timestamp,
60 bool retransmission,
61 const PacedPacketInfo& packet_info) = 0;
62 virtual DataSize TimeToSendPadding(DataSize size,
63 const PacedPacketInfo& pacing_info) = 0;
64 };
65
66 // Expected max pacer delay. If ExpectedQueueTime() is higher than
67 // this value, the packet producers should wait (eg drop frames rather than
68 // encoding them). Bitrate sent may temporarily exceed target set by
69 // UpdateBitrate() so that this limit will be upheld.
70 static const TimeDelta kMaxExpectedQueueLength;
71 // Pacing-rate relative to our target send rate.
72 // Multiplicative factor that is applied to the target bitrate to calculate
73 // the number of bytes that can be transmitted per interval.
74 // Increasing this factor will result in lower delays in cases of bitrate
75 // overshoots from the encoder.
76 static const float kDefaultPaceMultiplier;
77 // If no media or paused, wake up at least every |kPausedProcessIntervalMs| in
78 // order to send a keep-alive packet so we don't get stuck in a bad state due
79 // to lack of feedback.
80 static const TimeDelta kPausedProcessInterval;
81
82 PacingController(Clock* clock,
83 PacketSender* packet_sender,
84 RtcEventLog* event_log,
85 const WebRtcKeyValueConfig* field_trials);
86
87 ~PacingController();
88
89 // Adds the packet information to the queue and calls TimeToSendPacket
90 // when it's time to send.
91 void InsertPacket(RtpPacketSender::Priority priority,
92 uint32_t ssrc,
93 uint16_t sequence_number,
94 int64_t capture_time_ms,
95 size_t bytes,
96 bool retransmission);
97 // Adds the packet to the queue and calls PacketRouter::SendPacket() when
98 // it's time to send.
99 void EnqueuePacket(std::unique_ptr<RtpPacketToSend> packet);
100
101 void CreateProbeCluster(DataRate bitrate, int cluster_id);
102
103 void Pause(); // Temporarily pause all sending.
104 void Resume(); // Resume sending packets.
105 bool IsPaused() const;
106
107 void SetCongestionWindow(DataSize congestion_window_size);
108 void UpdateOutstandingData(DataSize outstanding_data);
109
110 // Sets the pacing rates. Must be called once before packets can be sent.
111 void SetPacingRates(DataRate pacing_rate, DataRate padding_rate);
112
113 // Currently audio traffic is not accounted by pacer and passed through.
114 // With the introduction of audio BWE audio traffic will be accounted for
115 // the pacer budget calculation. The audio traffic still will be injected
116 // at high priority.
117 void SetAccountForAudioPackets(bool account_for_audio);
118
119 // Returns the time since the oldest queued packet was enqueued.
120 TimeDelta OldestPacketWaitTime() const;
121
122 size_t QueueSizePackets() const;
123 DataSize QueueSizeData() const;
124
125 // Returns the time when the first packet was sent;
126 absl::optional<Timestamp> FirstSentPacketTime() const;
127
128 // Returns the number of milliseconds it will take to send the current
129 // packets in the queue, given the current size and bitrate, ignoring prio.
130 TimeDelta ExpectedQueueTime() const;
131
132 void SetQueueTimeLimit(TimeDelta limit);
133
134 // Enable bitrate probing. Enabled by default, mostly here to simplify
135 // testing. Must be called before any packets are being sent to have an
136 // effect.
137 void SetProbingEnabled(bool enabled);
138
139 // Time until next probe should be sent. If this value is set, it should be
140 // respected - i.e. don't call ProcessPackets() before this specified time as
141 // that can have unintended side effects.
142 absl::optional<TimeDelta> TimeUntilNextProbe();
143
144 // Time since ProcessPackets() was last executed.
145 TimeDelta TimeElapsedSinceLastProcess() const;
146
147 TimeDelta TimeUntilAvailableBudget() const;
148
149 // Check queue of pending packets and send them or padding packets, if budget
150 // is available.
151 void ProcessPackets();
152
153 bool Congested() const;
154
155 private:
156 TimeDelta UpdateTimeAndGetElapsed(Timestamp now);
157 bool ShouldSendKeepalive(Timestamp now) const;
158
159 // Updates the number of bytes that can be sent for the next time interval.
160 void UpdateBudgetWithElapsedTime(TimeDelta delta);
161 void UpdateBudgetWithSentData(DataSize size);
162
163 DataSize PaddingToAdd(absl::optional<DataSize> recommended_probe_size,
164 DataSize data_sent);
165
166 RoundRobinPacketQueue::QueuedPacket* GetPendingPacket(
167 const PacedPacketInfo& pacing_info);
168 void OnPacketSent(RoundRobinPacketQueue::QueuedPacket* packet);
169 void OnPaddingSent(DataSize padding_sent);
170
171 Timestamp CurrentTime() const;
172
173 Clock* const clock_;
174 PacketSender* const packet_sender_;
175 const std::unique_ptr<FieldTrialBasedConfig> fallback_field_trials_;
176 const WebRtcKeyValueConfig* field_trials_;
177
178 const bool drain_large_queues_;
179 const bool send_padding_if_silent_;
180 const bool pace_audio_;
181 TimeDelta min_packet_limit_;
182
183 // TODO(webrtc:9716): Remove this when we are certain clocks are monotonic.
184 // The last millisecond timestamp returned by |clock_|.
185 mutable Timestamp last_timestamp_;
186 bool paused_;
187 // This is the media budget, keeping track of how many bits of media
188 // we can pace out during the current interval.
189 IntervalBudget media_budget_;
190 // This is the padding budget, keeping track of how many bits of padding we're
191 // allowed to send out during the current interval. This budget will be
192 // utilized when there's no media to send.
193 IntervalBudget padding_budget_;
194
195 BitrateProber prober_;
196 bool probing_send_failure_;
197 bool padding_failure_state_;
198
199 DataRate pacing_bitrate_;
200
201 Timestamp time_last_process_;
202 Timestamp last_send_time_;
203 absl::optional<Timestamp> first_sent_packet_time_;
204
205 RoundRobinPacketQueue packet_queue_;
206 uint64_t packet_counter_;
207
208 DataSize congestion_window_size_;
209 DataSize outstanding_data_;
210
211 TimeDelta queue_time_limit;
212 bool account_for_audio_;
213
214 // If true, PacedSender should only reference packets as in legacy mode.
215 // If false, PacedSender may have direct ownership of RtpPacketToSend objects.
216 // Defaults to true, will be changed to default false soon.
217 const bool legacy_packet_referencing_;
218};
219} // namespace webrtc
220
221#endif // MODULES_PACING_PACING_CONTROLLER_H_