OLD | NEW |
| (Empty) |
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 <cmath> | |
12 | |
13 #include "webrtc/common_audio/smoothing_filter.h" | |
14 | |
15 namespace webrtc { | |
16 | |
17 SmoothingFilterImpl::SmoothingFilterImpl(int time_constant_ms, | |
18 const Clock* clock) | |
19 : time_constant_ms_(time_constant_ms), | |
20 clock_(clock), | |
21 first_sample_received_(false), | |
22 initialized_(false), | |
23 first_sample_time_ms_(0), | |
24 last_sample_time_ms_(0), | |
25 filter_(0.0) {} | |
26 | |
27 void SmoothingFilterImpl::AddSample(float sample) { | |
28 if (!first_sample_received_) { | |
29 last_sample_time_ms_ = first_sample_time_ms_ = clock_->TimeInMilliseconds(); | |
30 first_sample_received_ = true; | |
31 RTC_DCHECK_EQ(rtc::ExpFilter::kValueUndefined, filter_.filtered()); | |
32 | |
33 // Since this is first sample, any value for argument 1 should work. | |
34 filter_.Apply(0.0f, sample); | |
35 return; | |
36 } | |
37 | |
38 int64_t now_ms = clock_->TimeInMilliseconds(); | |
39 if (!initialized_) { | |
40 float duration = now_ms - first_sample_time_ms_; | |
41 if (duration < static_cast<int64_t>(time_constant_ms_)) { | |
42 filter_.UpdateBase(exp(1.0f / duration)); | |
43 } else { | |
44 initialized_ = true; | |
45 filter_.UpdateBase(exp(1.0f / time_constant_ms_)); | |
46 } | |
47 } | |
48 | |
49 // The filter will do the following: | |
50 // float alpha = pow(base, last_update_time_ms_ - now_ms); | |
51 // filtered_ = alpha * filtered_ + (1 - alpha) * sample; | |
52 filter_.Apply(static_cast<float>(last_sample_time_ms_ - now_ms), sample); | |
53 last_sample_time_ms_ = now_ms; | |
54 } | |
55 | |
56 rtc::Optional<float> SmoothingFilterImpl::GetAverage() const { | |
57 float value = filter_.filtered(); | |
58 return value == rtc::ExpFilter::kValueUndefined ? rtc::Optional<float>() | |
59 : rtc::Optional<float>(value); | |
60 } | |
61 | |
62 } // namespace webrtc | |
OLD | NEW |