blob: 8de1dd2a4377fb67e491316ede3173a4141f3b03 [file] [log] [blame]
jackychen61b4d512015-04-21 15:30:11 -07001/*
2 * Copyright (c) 2015 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 WEBRTC_MODULES_VIDEO_CODING_UTILITY_MOVING_AVERAGE_H_
12#define WEBRTC_MODULES_VIDEO_CODING_UTILITY_MOVING_AVERAGE_H_
13
14#include <list>
15
16#include "webrtc/typedefs.h"
17
18namespace webrtc {
19template<class T>
20class MovingAverage {
21 public:
22 MovingAverage();
23 void AddSample(T sample);
24 bool GetAverage(size_t num_samples, T* average);
25 void Reset();
26 int size();
27
28 private:
29 T sum_;
30 std::list<T> samples_;
31};
32
33template<class T>
34MovingAverage<T>::MovingAverage() : sum_(static_cast<T>(0)) {
35}
36
37template<class T>
38void MovingAverage<T>::AddSample(T sample) {
39 samples_.push_back(sample);
40 sum_ += sample;
41}
42
43template<class T>
44bool MovingAverage<T>::GetAverage(size_t num_samples, T* avg) {
45 if (num_samples > samples_.size())
46 return false;
47
48 // Remove old samples.
49 while (num_samples < samples_.size()) {
50 sum_ -= samples_.front();
51 samples_.pop_front();
52 }
53
54 *avg = sum_ / static_cast<T>(num_samples);
55 return true;
56}
57
58template<class T>
59void MovingAverage<T>::Reset() {
60 sum_ = static_cast<T>(0);
61 samples_.clear();
62}
63
64template<class T>
65int MovingAverage<T>::size() {
66 return samples_.size();
67}
68
69} // namespace webrtc
70
kjellander@webrtc.orgb7ce9642015-11-18 23:04:10 +010071#endif // WEBRTC_MODULES_VIDEO_CODING_UTILITY_MOVING_AVERAGE_H_