网络状态探测器,用于探测网络当前状态
一. 探测网络状态
- 过载了 网络负荷比较大,需要减少流量
- 正常状态
- 欠载 网络负荷比较小,可以加大流量
–
// ts_delta:2帧发送的相对延迟
// num_of_deltas: 计算offset的点的个数
// now_ms:当前时间点
BandwidthUsage Detect(double offset,double ts_delta,int num_of_deltas,
int64_t now_ms) {
// T 网络排队延迟,T>表示最近延迟在增加,《0 延迟在减小
// 点的个数 * 帧间的相对延迟
const double T = std::min(num_of_deltas, kMinNumDeltas) * offset;
if (T threshold_) {
if (time_over_using_ == -1) {
time_over_using_ = ts_delta / 2;
} else {
time_over_using_ += ts_delta;
}
overuse_counter_++;
//过载状态 已经持续了overusing_time_threshold_时长了,
// 网络相对延迟比上一次增加了 offset >= prev_offset_
if (time_over_using_ overusing_time_threshold_ && overuse_counter_ 1) {
if (offset >= prev_offset_) {
time_over_using_ = 0;
overuse_counter_ = 0;
hypothesis_ = kBwOverusing;
}
}
} else if (T < -threshold_) {
//网络相对延迟在减少中,已经达到阈值了
time_over_using_ = -1;
overuse_counter_ = 0;
hypothesis_ = kBwUnderusing;
} else {
//正常状态
time_over_using_ = -1;
overuse_counter_ = 0;
hypothesis_ = kBwNormal;
}
//记录上一次的相对延迟 ,更新阈值
prev_offset_ = offset;
UpdateThreshold(T, now_ms);
return hypothesis_;
}
二. 动态更新阈值
//modified_offset:延迟值
//now_ms :当前时间
void UpdateThreshold(double modified_offset, int64_t now_ms) {
if (!in_experiment_)
return;
if (last_update_ms_ == -1)
last_update_ms_ = now_ms;
//当延迟值异常过大的时候,当做异常值处理,不更新
if (fabs(modified_offset) > threshold_ + kMaxAdaptOffsetMs) {
// Avoid adapting the threshold to big latency spikes, caused e.g.,
// by a sudden capacity drop.
last_update_ms_ = now_ms;
return;
}
// k_up_(0.0087)
// k_down_(0.039)
// 当网络过载,欠载的时候,慢慢增大阈值 (k_up_),
// 网络正常的时候 快一点减少阈值 (k_down)
// -----欠载区域----|------正常区域--------|---过载区域----------------->
// -threshold_ threshold_
//
const double k = fabs(modified_offset) < threshold_ ? k_down_ : k_up_;
const int64_t kMaxTimeDeltaMs = 100;
int64_t time_delta_ms = std::min(now_ms - last_update_ms_, kMaxTimeDeltaMs);
threshold_ += k * (fabs(modified_offset) - threshold_) * time_delta_ms;
//保证阈值在一定区间内
const double kMinThreshold = 6;
const double kMaxThreshold = 600;
threshold_ = std::min(std::max(threshold_, kMinThreshold), kMaxThreshold);
last_update_ms_ = now_ms;
}