blob: 494bfd51fbc45630a3f1ce588f626ff5a9852990 [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 {
philipel5908c712015-12-21 08:23:20 -080019template <class T>
jackychen61b4d512015-04-21 15:30:11 -070020class 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
philipel5908c712015-12-21 08:23:20 -080033template <class T>
34MovingAverage<T>::MovingAverage()
35 : sum_(static_cast<T>(0)) {}
jackychen61b4d512015-04-21 15:30:11 -070036
philipel5908c712015-12-21 08:23:20 -080037template <class T>
jackychen61b4d512015-04-21 15:30:11 -070038void MovingAverage<T>::AddSample(T sample) {
39 samples_.push_back(sample);
40 sum_ += sample;
41}
42
philipel5908c712015-12-21 08:23:20 -080043template <class T>
jackychen61b4d512015-04-21 15:30:11 -070044bool 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
philipel5908c712015-12-21 08:23:20 -080058template <class T>
jackychen61b4d512015-04-21 15:30:11 -070059void MovingAverage<T>::Reset() {
60 sum_ = static_cast<T>(0);
61 samples_.clear();
62}
63
philipel5908c712015-12-21 08:23:20 -080064template <class T>
jackychen61b4d512015-04-21 15:30:11 -070065int 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_