1 /*
2  *  Copyright (c) 2017 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/aec3/erl_estimator.h"
12 
13 #include <algorithm>
14 #include <numeric>
15 
16 namespace webrtc {
17 
18 namespace {
19 
20 constexpr float kMinErl = 0.01f;
21 constexpr float kMaxErl = 1000.f;
22 
23 }  // namespace
24 
ErlEstimator()25 ErlEstimator::ErlEstimator() {
26   erl_.fill(kMaxErl);
27   hold_counters_.fill(0);
28   erl_time_domain_ = kMaxErl;
29   hold_counter_time_domain_ = 0;
30 }
31 
32 ErlEstimator::~ErlEstimator() = default;
33 
Update(const std::array<float,kFftLengthBy2Plus1> & render_spectrum,const std::array<float,kFftLengthBy2Plus1> & capture_spectrum)34 void ErlEstimator::Update(
35     const std::array<float, kFftLengthBy2Plus1>& render_spectrum,
36     const std::array<float, kFftLengthBy2Plus1>& capture_spectrum) {
37   const auto& X2 = render_spectrum;
38   const auto& Y2 = capture_spectrum;
39 
40   // Corresponds to WGN of power -46 dBFS.
41   constexpr float kX2Min = 44015068.0f;
42 
43   // Update the estimates in a maximum statistics manner.
44   for (size_t k = 1; k < kFftLengthBy2; ++k) {
45     if (X2[k] > kX2Min) {
46       const float new_erl = Y2[k] / X2[k];
47       if (new_erl < erl_[k]) {
48         hold_counters_[k - 1] = 1000;
49         erl_[k] += 0.1f * (new_erl - erl_[k]);
50         erl_[k] = std::max(erl_[k], kMinErl);
51       }
52     }
53   }
54 
55   std::for_each(hold_counters_.begin(), hold_counters_.end(),
56                 [](int& a) { --a; });
57   std::transform(hold_counters_.begin(), hold_counters_.end(), erl_.begin() + 1,
58                  erl_.begin() + 1, [](int a, float b) {
59                    return a > 0 ? b : std::min(kMaxErl, 2.f * b);
60                  });
61 
62   erl_[0] = erl_[1];
63   erl_[kFftLengthBy2] = erl_[kFftLengthBy2 - 1];
64 
65   // Compute ERL over all frequency bins.
66   const float X2_sum = std::accumulate(X2.begin(), X2.end(), 0.0f);
67 
68   if (X2_sum > kX2Min * X2.size()) {
69     const float Y2_sum = std::accumulate(Y2.begin(), Y2.end(), 0.0f);
70     const float new_erl = Y2_sum / X2_sum;
71     if (new_erl < erl_time_domain_) {
72       hold_counter_time_domain_ = 1000;
73       erl_time_domain_ += 0.1f * (new_erl - erl_time_domain_);
74       erl_time_domain_ = std::max(erl_time_domain_, kMinErl);
75     }
76   }
77 
78   --hold_counter_time_domain_;
79   erl_time_domain_ = (hold_counter_time_domain_ > 0)
80                          ? erl_time_domain_
81                          : std::min(kMaxErl, 2.f * erl_time_domain_);
82 }
83 
84 }  // namespace webrtc
85