blob: 8076f934766d58ba5342f92e820a95a4d30480c2 [file] [log] [blame]
kthelgason194f40a2016-09-14 02:14:58 -07001/*
2 * Copyright (c) 2016 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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/video_coding/utility/moving_average.h"
kthelgason194f40a2016-09-14 02:14:58 -070012
13#include <algorithm>
14
15namespace webrtc {
16
17MovingAverage::MovingAverage(size_t s) : sum_history_(s + 1, 0) {}
18
19void MovingAverage::AddSample(int sample) {
20 count_++;
21 sum_ += sample;
22 sum_history_[count_ % sum_history_.size()] = sum_;
23}
24
25rtc::Optional<int> MovingAverage::GetAverage() const {
26 return GetAverage(size());
27}
28
29rtc::Optional<int> MovingAverage::GetAverage(size_t num_samples) const {
30 if (num_samples > size() || num_samples == 0)
Oskar Sundbom6bd39022017-11-16 10:54:49 +010031 return rtc::nullopt;
kthelgason194f40a2016-09-14 02:14:58 -070032 int sum = sum_ - sum_history_[(count_ - num_samples) % sum_history_.size()];
Oskar Sundbom6bd39022017-11-16 10:54:49 +010033 return sum / static_cast<int>(num_samples);
kthelgason194f40a2016-09-14 02:14:58 -070034}
35
36void MovingAverage::Reset() {
37 count_ = 0;
38 sum_ = 0;
39 std::fill(sum_history_.begin(), sum_history_.end(), 0);
40}
41
42size_t MovingAverage::size() const {
43 return std::min(count_, sum_history_.size() - 1);
44}
45
46} // namespace webrtc