blob: 770e47d86f8128fcf7774d4bc4509676975c62ac [file] [log] [blame]
Ilya Nikolaevskiy26341992018-11-05 12:55:18 +01001/*
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#ifndef RTC_BASE_NUMERICS_MOVING_AVERAGE_H_
12#define RTC_BASE_NUMERICS_MOVING_AVERAGE_H_
13
14#include <vector>
15
16#include "absl/types/optional.h"
17
18namespace rtc {
19
20// Calculates average over fixed size window. If there are less than window
21// size elements, calculates average of all inserted so far elements.
22//
23class MovingAverage {
24 public:
25 // Maximum supported window size is 2^32 - 1.
26 explicit MovingAverage(size_t window_size);
27 ~MovingAverage();
28 // MovingAverage is neither copyable nor movable.
29 MovingAverage(const MovingAverage&) = delete;
30 MovingAverage& operator=(const MovingAverage&) = delete;
31
32 // Adds new sample. If the window is full, the oldest element is pushed out.
33 void AddSample(int sample);
34
35 // Returns rounded down average of last |window_size| elements or all
36 // elements if there are not enough of them. Returns nullopt if there were
37 // no elements added.
38 absl::optional<int> GetAverageRoundedDown() const;
39
40 // Same as above but rounded to the closest integer.
41 absl::optional<int> GetAverageRoundedToClosest() const;
42
43 // Returns unrounded average over the window.
44 absl::optional<double> GetUnroundedAverage() const;
45
46 // Resets to the initial state before any elements were added.
47 void Reset();
48
49 // Returns number of elements in the window.
50 size_t Size() const;
51
52 private:
53 // Total number of samples added to the class since last reset.
54 size_t count_ = 0;
55 // Sum of the samples in the moving window.
56 int64_t sum_ = 0;
57 // Circular buffer for all the samples in the moving window.
58 // Size is always |window_size|
59 std::vector<int> history_;
60};
61
62} // namespace rtc
63#endif // RTC_BASE_NUMERICS_MOVING_AVERAGE_H_