1 /*
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 
18 namespace webrtc {
19 template <class T>
20 class 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 
33 template <class T>
MovingAverage()34 MovingAverage<T>::MovingAverage()
35     : sum_(static_cast<T>(0)) {}
36 
37 template <class T>
AddSample(T sample)38 void MovingAverage<T>::AddSample(T sample) {
39   samples_.push_back(sample);
40   sum_ += sample;
41 }
42 
43 template <class T>
GetAverage(size_t num_samples,T * avg)44 bool 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 
58 template <class T>
Reset()59 void MovingAverage<T>::Reset() {
60   sum_ = static_cast<T>(0);
61   samples_.clear();
62 }
63 
64 template <class T>
size()65 int MovingAverage<T>::size() {
66   return samples_.size();
67 }
68 
69 }  // namespace webrtc
70 
71 #endif  // WEBRTC_MODULES_VIDEO_CODING_UTILITY_MOVING_AVERAGE_H_
72