2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
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.
11 #include "webrtc/modules/remote_bitrate_estimator/rate_statistics.h"
15 RateStatistics::RateStatistics(uint32_t window_size_ms, float scale)
16 : num_buckets_(window_size_ms + 1), // N ms in (N+1) buckets.
17 buckets_(new uint32_t[num_buckets_]()),
18 accumulated_count_(0),
21 scale_(scale / (num_buckets_ - 1)) {
24 RateStatistics::~RateStatistics() {
27 void RateStatistics::Reset() {
28 accumulated_count_ = 0;
31 for (int i = 0; i < num_buckets_; i++) {
36 void RateStatistics::Update(uint32_t count, int64_t now_ms) {
37 if (now_ms < oldest_time_) {
38 // Too old data is ignored.
44 int now_offset = static_cast<int>(now_ms - oldest_time_);
45 assert(now_offset < num_buckets_);
46 int index = oldest_index_ + now_offset;
47 if (index >= num_buckets_) {
48 index -= num_buckets_;
50 buckets_[index] += count;
51 accumulated_count_ += count;
54 uint32_t RateStatistics::Rate(int64_t now_ms) {
56 return static_cast<uint32_t>(accumulated_count_ * scale_ + 0.5f);
59 void RateStatistics::EraseOld(int64_t now_ms) {
60 int64_t new_oldest_time = now_ms - num_buckets_ + 1;
61 if (new_oldest_time <= oldest_time_) {
65 while (oldest_time_ < new_oldest_time) {
66 uint32_t count_in_oldest_bucket = buckets_[oldest_index_];
67 assert(accumulated_count_ >= count_in_oldest_bucket);
68 accumulated_count_ -= count_in_oldest_bucket;
69 buckets_[oldest_index_] = 0;
70 if (++oldest_index_ >= num_buckets_) {
74 if (accumulated_count_ == 0) {
75 // This guarantees we go through all the buckets at most once, even if
76 // |new_oldest_time| is far greater than |oldest_time_|.
80 oldest_time_ = new_oldest_time;