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