Line data Source code
1 : /*
2 : * Copyright (c) 2016 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 : #include "webrtc/modules/video_coding/utility/moving_average.h"
12 :
13 : #include <algorithm>
14 :
15 : namespace webrtc {
16 :
17 0 : MovingAverage::MovingAverage(size_t s) : sum_history_(s + 1, 0) {}
18 :
19 0 : void MovingAverage::AddSample(int sample) {
20 0 : count_++;
21 0 : sum_ += sample;
22 0 : sum_history_[count_ % sum_history_.size()] = sum_;
23 0 : }
24 :
25 0 : rtc::Optional<int> MovingAverage::GetAverage() const {
26 0 : return GetAverage(size());
27 : }
28 :
29 0 : rtc::Optional<int> MovingAverage::GetAverage(size_t num_samples) const {
30 0 : if (num_samples > size() || num_samples == 0)
31 0 : return rtc::Optional<int>();
32 0 : int sum = sum_ - sum_history_[(count_ - num_samples) % sum_history_.size()];
33 0 : return rtc::Optional<int>(sum / static_cast<int>(num_samples));
34 : }
35 :
36 0 : void MovingAverage::Reset() {
37 0 : count_ = 0;
38 0 : sum_ = 0;
39 0 : std::fill(sum_history_.begin(), sum_history_.end(), 0);
40 0 : }
41 :
42 0 : size_t MovingAverage::size() const {
43 0 : return std::min(count_, sum_history_.size() - 1);
44 : }
45 :
46 : } // namespace webrtc
|