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/audio_processing/level_controller/noise_level_estimator.h"
12 :
13 : #include <algorithm>
14 :
15 : #include "webrtc/modules/audio_processing/audio_buffer.h"
16 : #include "webrtc/modules/audio_processing/logging/apm_data_dumper.h"
17 :
18 : namespace webrtc {
19 :
20 0 : NoiseLevelEstimator::NoiseLevelEstimator() {
21 0 : Initialize(AudioProcessing::kSampleRate48kHz);
22 0 : }
23 :
24 0 : NoiseLevelEstimator::~NoiseLevelEstimator() {}
25 :
26 0 : void NoiseLevelEstimator::Initialize(int sample_rate_hz) {
27 0 : noise_energy_ = 1.f;
28 0 : first_update_ = true;
29 0 : min_noise_energy_ = sample_rate_hz * 2.f * 2.f / 100.f;
30 0 : noise_energy_hold_counter_ = 0;
31 0 : }
32 :
33 0 : float NoiseLevelEstimator::Analyze(SignalClassifier::SignalType signal_type,
34 : float frame_energy) {
35 0 : if (frame_energy <= 0.f) {
36 0 : return noise_energy_;
37 : }
38 :
39 0 : if (first_update_) {
40 : // Initialize the noise energy to the frame energy.
41 0 : first_update_ = false;
42 0 : return noise_energy_ = std::max(frame_energy, min_noise_energy_);
43 : }
44 :
45 : // Update the noise estimate in a minimum statistics-type manner.
46 0 : if (signal_type == SignalClassifier::SignalType::kStationary) {
47 0 : if (frame_energy > noise_energy_) {
48 : // Leak the estimate upwards towards the frame energy if no recent
49 : // downward update.
50 0 : noise_energy_hold_counter_ = std::max(noise_energy_hold_counter_ - 1, 0);
51 :
52 0 : if (noise_energy_hold_counter_ == 0) {
53 0 : noise_energy_ = std::min(noise_energy_ * 1.01f, frame_energy);
54 : }
55 : } else {
56 : // Update smoothly downwards with a limited maximum update magnitude.
57 0 : noise_energy_ =
58 0 : std::max(noise_energy_ * 0.9f,
59 0 : noise_energy_ + 0.05f * (frame_energy - noise_energy_));
60 0 : noise_energy_hold_counter_ = 1000;
61 : }
62 : } else {
63 : // For a non-stationary signal, leak the estimate downwards in order to
64 : // avoid estimate locking due to incorrect signal classification.
65 0 : noise_energy_ = noise_energy_ * 0.99f;
66 : }
67 :
68 : // Ensure a minimum of the estimate.
69 0 : return noise_energy_ = std::max(noise_energy_, min_noise_energy_);
70 : }
71 :
72 : } // namespace webrtc
|