OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * Copyright 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/audio_processing/utility/mean_calculator.h" |
| 12 |
| 13 namespace webrtc { |
| 14 |
| 15 MeanCalculator::MeanCalculator(size_t window_length) |
| 16 : window_length_(window_length), |
| 17 head_(0), |
| 18 full_(false), |
| 19 sum_(0.0f), |
| 20 compensation_(0.0f) { |
| 21 buffer_.resize(window_length); |
| 22 } |
| 23 |
| 24 // MeanCalculator::~MeanCalculator() = default; |
| 25 |
| 26 // Add one sample to the sequence. |
| 27 void MeanCalculator::AddSample(float sample) { |
| 28 rtc::CritScope cs(&crit_); |
| 29 if (full_) |
| 30 KahanSum(-buffer_[head_]); |
| 31 buffer_[head_] = sample; |
| 32 KahanSum(buffer_[head_]); |
| 33 head_ = (head_ + 1) % window_length_; |
| 34 if (!full_ && head_ == 0) |
| 35 full_ = true; |
| 36 } |
| 37 |
| 38 // Get the mean of the latest samples. Returns the mean if it is available, |
| 39 // otherwise null, which happens when the added samples have not fully filled |
| 40 // the window. |
| 41 rtc::Optional<float> MeanCalculator::GetMean() const { |
| 42 rtc::CritScope cs(&crit_); |
| 43 if (full_) { |
| 44 return rtc::Optional<float>(sum_ / window_length_); |
| 45 } else { |
| 46 return rtc::Optional<float>(); |
| 47 } |
| 48 } |
| 49 |
| 50 // Flush all samples added. |
| 51 void MeanCalculator::Clear() { |
| 52 rtc::CritScope cs(&crit_); |
| 53 head_ = 0; |
| 54 full_ = false; |
| 55 sum_ = 0.0f; |
| 56 compensation_ = 0.0f; |
| 57 } |
| 58 |
| 59 // Determines if the window is full. This is a quick way of checking if the |
| 60 // mean is ready. |
| 61 bool MeanCalculator::IsWindowFull() const { |
| 62 rtc::CritScope cs(&crit_); |
| 63 return full_; |
| 64 } |
| 65 |
| 66 void MeanCalculator::KahanSum(float sample) { |
| 67 rtc::CritScope cs(&crit_); |
| 68 const float compensated_sample = sample - compensation_; |
| 69 const float temp_sum = sum_ + compensated_sample; |
| 70 compensation_ = (temp_sum - sum_) - compensated_sample; |
| 71 sum_ = temp_sum; |
| 72 } |
| 73 |
| 74 } // namespace webrtc |
OLD | NEW |