sprang@webrtc.org | 7374da3 | 2013-12-03 10:31:59 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (c) 2013 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 | #include "webrtc/modules/remote_bitrate_estimator/rate_statistics.h" |
| 12 | |
| 13 | namespace webrtc { |
| 14 | |
| 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), |
| 19 | oldest_time_(0), |
| 20 | oldest_index_(0), |
| 21 | scale_(scale / (num_buckets_ - 1)) { |
| 22 | } |
| 23 | |
| 24 | RateStatistics::~RateStatistics() { |
| 25 | } |
| 26 | |
| 27 | void RateStatistics::Reset() { |
| 28 | accumulated_count_ = 0; |
| 29 | oldest_time_ = 0; |
| 30 | oldest_index_ = 0; |
| 31 | for (int i = 0; i < num_buckets_; i++) { |
| 32 | buckets_[i] = 0; |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | void RateStatistics::Update(uint32_t count, int64_t now_ms) { |
| 37 | if (now_ms < oldest_time_) { |
| 38 | // Too old data is ignored. |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | EraseOld(now_ms); |
| 43 | |
| 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_; |
| 49 | } |
| 50 | buckets_[index] += count; |
| 51 | accumulated_count_ += count; |
| 52 | } |
| 53 | |
| 54 | uint32_t RateStatistics::Rate(int64_t now_ms) { |
| 55 | EraseOld(now_ms); |
| 56 | return static_cast<uint32_t>(accumulated_count_ * scale_ + 0.5f); |
| 57 | } |
| 58 | |
| 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_) { |
| 62 | return; |
| 63 | } |
| 64 | |
| 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_) { |
| 71 | oldest_index_ = 0; |
| 72 | } |
| 73 | ++oldest_time_; |
| 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_|. |
| 77 | break; |
| 78 | } |
| 79 | } |
| 80 | oldest_time_ = new_oldest_time; |
| 81 | } |
| 82 | |
| 83 | } // namespace webrtc |