blob: eb23e3d92f3e6063eacdedfd8802a9ffa83d1c72 [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) {}
Paulina Hensmana680a6a2018-04-05 11:42:24 +020018MovingAverage::~MovingAverage() = default;
kthelgason194f40a2016-09-14 02:14:58 -070019
20void MovingAverage::AddSample(int sample) {
21 count_++;
22 sum_ += sample;
23 sum_history_[count_ % sum_history_.size()] = sum_;
24}
25
Danil Chapovalov0040b662018-06-18 10:48:16 +020026absl::optional<int> MovingAverage::GetAverage() const {
kthelgason194f40a2016-09-14 02:14:58 -070027 return GetAverage(size());
28}
29
Danil Chapovalov0040b662018-06-18 10:48:16 +020030absl::optional<int> MovingAverage::GetAverage(size_t num_samples) const {
kthelgason194f40a2016-09-14 02:14:58 -070031 if (num_samples > size() || num_samples == 0)
Danil Chapovalov0040b662018-06-18 10:48:16 +020032 return absl::nullopt;
kthelgason194f40a2016-09-14 02:14:58 -070033 int sum = sum_ - sum_history_[(count_ - num_samples) % sum_history_.size()];
Oskar Sundbom6bd39022017-11-16 10:54:49 +010034 return sum / static_cast<int>(num_samples);
kthelgason194f40a2016-09-14 02:14:58 -070035}
36
37void MovingAverage::Reset() {
38 count_ = 0;
39 sum_ = 0;
40 std::fill(sum_history_.begin(), sum_history_.end(), 0);
41}
42
43size_t MovingAverage::size() const {
44 return std::min(count_, sum_history_.size() - 1);
45}
46
47} // namespace webrtc