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