WebRTC源码分析--RateLimiter
RateLimiter
是webrtc中实现的限流工具,被用在诸如限制重传包数量等地方。它依赖于之前介绍的速率计算器RateStatistics
。
先看它的定义:
class RateLimiter {
public:
RateLimiter(Clock* clock, int64_t max_window_ms);
~RateLimiter();
// Try to use rate to send bytes. Returns true on success and if so updates
// current rate.
bool TryUseRate(size_t packet_size_bytes);
// Set the maximum bitrate, in bps, that this limiter allows to send.
void SetMaxRate(uint32_t max_rate_bps);
// Set the window size over which to measure the current bitrate.
// For example, irt retransmissions, this is typically the RTT.
// Returns true on success and false if window_size_ms is out of range.
bool SetWindowSize(int64_t window_size_ms);
private:
Clock* const clock_;
rtc::CriticalSection lock_;
RateStatistics current_rate_ RTC_GUARDED_BY(lock_);
int64_t window_size_ms_ RTC_GUARDED_BY(lock_);
uint32_t max_rate_bps_ RTC_GUARDED_BY(lock_);
RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(RateLimiter);
};
接口十分简单:
TryUseRate
: 尝试使用packet_size_bytes
字节的数据,该接口基于当前状态返回是否允许,这是主要的接口;SetMaxRate
: 设置允许的最大速率,即上限;SetWindowSize
:设置统计速率的时间窗口,也是设置RateStatistics
的窗口。
SetMaxRate
和SetWindowSize
都比较简单,只是设置参数:
void RateLimiter::SetMaxRate(uint32_t max_rate_bps) {
rtc::CritScope cs(&lock_);
max_rate_bps_ = max_rate_bps;
}
// Set the window size over which to measure the current bitrate.
// For retransmissions, this is typically the RTT.
bool RateLimiter::SetWindowSize(int64_t window_size_ms) {
rtc::CritScope cs(&lock_);
window_size_ms_ = window_size_ms;
return current_rate_.SetWindowSize(window_size_ms,
clock_->TimeInMilliseconds());
}
RateLimiter::TryUseRate
是核心,用于比较当前的使用速率和预设的最大速率之间的关系:
bool RateLimiter::TryUseRate(size_t packet_size_bytes) {
rtc::CritScope cs(&lock_);
int64_t now_ms = clock_->TimeInMilliseconds();
// 得到由RateStatistics计算得到的当前速率
absl::optional<uint32_t> current_rate = current_rate_.Rate(now_ms);
if (current_rate) {
// If there is a current rate, check if adding bytes would cause maximum
// bitrate target to be exceeded. If there is NOT a valid current rate,
// allow allocating rate even if target is exceeded. This prevents
// problems
// at very low rates, where for instance retransmissions would never be
// allowed due to too high bitrate caused by a single packet.
// 如果使用当前packet_size_bytes,计算它占用的速率,转换层bps
size_t bitrate_addition_bps =
(packet_size_bytes * 8 * 1000) / window_size_ms_;
// 判断是否超过预设值
if (*current_rate + bitrate_addition_bps > max_rate_bps_)
return false;
}
// 更新速率RateStatistics
current_rate_.Update(packet_size_bytes, now_ms);
return true;
}
- 通常
SetWindowSize
会被设置成一个rtt
,并限定在一个预设范围内; - 通常
SetMaxRate
会根据码率估计得到的值设置。