• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2018 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 "rtc_base/numerics/moving_average.h"
12 
13 #include <algorithm>
14 
15 #include "rtc_base/checks.h"
16 
17 namespace rtc {
18 
MovingAverage(size_t window_size)19 MovingAverage::MovingAverage(size_t window_size) : history_(window_size, 0) {
20   // Limit window size to avoid overflow.
21   RTC_DCHECK_LE(window_size, (int64_t{1} << 32) - 1);
22 }
23 MovingAverage::~MovingAverage() = default;
24 
AddSample(int sample)25 void MovingAverage::AddSample(int sample) {
26   count_++;
27   size_t index = count_ % history_.size();
28   if (count_ > history_.size())
29     sum_ -= history_[index];
30   sum_ += sample;
31   history_[index] = sample;
32 }
33 
GetAverageRoundedDown() const34 absl::optional<int> MovingAverage::GetAverageRoundedDown() const {
35   if (count_ == 0)
36     return absl::nullopt;
37   return sum_ / Size();
38 }
39 
GetAverageRoundedToClosest() const40 absl::optional<int> MovingAverage::GetAverageRoundedToClosest() const {
41   if (count_ == 0)
42     return absl::nullopt;
43   return (sum_ + Size() / 2) / Size();
44 }
45 
GetUnroundedAverage() const46 absl::optional<double> MovingAverage::GetUnroundedAverage() const {
47   if (count_ == 0)
48     return absl::nullopt;
49   return sum_ / static_cast<double>(Size());
50 }
51 
Reset()52 void MovingAverage::Reset() {
53   count_ = 0;
54   sum_ = 0;
55 }
56 
Size() const57 size_t MovingAverage::Size() const {
58   return std::min(count_, history_.size());
59 }
60 }  // namespace rtc
61