blob: b7854a0c9de3ec474ce5541a9fa8b22442f95dcf [file] [log] [blame]
Sam Zackrisson52f81882018-03-06 11:54:08 +00001/*
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/level_controller.h"
12
13#include <math.h>
14#include <algorithm>
15#include <numeric>
16
17#include "api/array_view.h"
18#include "modules/audio_processing/audio_buffer.h"
19#include "modules/audio_processing/level_controller/gain_applier.h"
20#include "modules/audio_processing/level_controller/gain_selector.h"
21#include "modules/audio_processing/level_controller/noise_level_estimator.h"
22#include "modules/audio_processing/level_controller/peak_level_estimator.h"
23#include "modules/audio_processing/level_controller/saturating_gain_estimator.h"
24#include "modules/audio_processing/level_controller/signal_classifier.h"
25#include "modules/audio_processing/logging/apm_data_dumper.h"
26#include "rtc_base/arraysize.h"
27#include "rtc_base/checks.h"
28#include "rtc_base/logging.h"
29#include "system_wrappers/include/metrics.h"
30
31namespace webrtc {
32namespace {
33
34void UpdateAndRemoveDcLevel(float forgetting_factor,
35 float* dc_level,
36 rtc::ArrayView<float> x) {
37 RTC_DCHECK(!x.empty());
38 float mean =
39 std::accumulate(x.begin(), x.end(), 0.0f) / static_cast<float>(x.size());
40 *dc_level += forgetting_factor * (mean - *dc_level);
41
42 for (float& v : x) {
43 v -= *dc_level;
44 }
45}
46
47float FrameEnergy(const AudioBuffer& audio) {
48 float energy = 0.f;
49 for (size_t k = 0; k < audio.num_channels(); ++k) {
50 float channel_energy =
51 std::accumulate(audio.channels_const_f()[k],
52 audio.channels_const_f()[k] + audio.num_frames(), 0.f,
53 [](float a, float b) -> float { return a + b * b; });
54 energy = std::max(channel_energy, energy);
55 }
56 return energy;
57}
58
59float PeakLevel(const AudioBuffer& audio) {
60 float peak_level = 0.f;
61 for (size_t k = 0; k < audio.num_channels(); ++k) {
62 auto* channel_peak_level = std::max_element(
63 audio.channels_const_f()[k],
64 audio.channels_const_f()[k] + audio.num_frames(),
65 [](float a, float b) { return std::abs(a) < std::abs(b); });
66 peak_level = std::max(*channel_peak_level, peak_level);
67 }
68 return peak_level;
69}
70
71const int kMetricsFrameInterval = 1000;
72
73} // namespace
74
75int LevelController::instance_count_ = 0;
76
77void LevelController::Metrics::Initialize(int sample_rate_hz) {
78 RTC_DCHECK(sample_rate_hz == AudioProcessing::kSampleRate8kHz ||
79 sample_rate_hz == AudioProcessing::kSampleRate16kHz ||
80 sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
81 sample_rate_hz == AudioProcessing::kSampleRate48kHz);
82
83 Reset();
84 frame_length_ = rtc::CheckedDivExact(sample_rate_hz, 100);
85}
86
87void LevelController::Metrics::Reset() {
88 metrics_frame_counter_ = 0;
89 gain_sum_ = 0.f;
90 peak_level_sum_ = 0.f;
91 noise_energy_sum_ = 0.f;
92 max_gain_ = 0.f;
93 max_peak_level_ = 0.f;
94 max_noise_energy_ = 0.f;
95}
96
97void LevelController::Metrics::Update(float long_term_peak_level,
98 float noise_energy,
99 float gain,
100 float frame_peak_level) {
101 const float kdBFSOffset = 90.3090f;
102 gain_sum_ += gain;
103 peak_level_sum_ += long_term_peak_level;
104 noise_energy_sum_ += noise_energy;
105 max_gain_ = std::max(max_gain_, gain);
106 max_peak_level_ = std::max(max_peak_level_, long_term_peak_level);
107 max_noise_energy_ = std::max(max_noise_energy_, noise_energy);
108
109 ++metrics_frame_counter_;
110 if (metrics_frame_counter_ == kMetricsFrameInterval) {
111 RTC_DCHECK_LT(0, frame_length_);
112 RTC_DCHECK_LT(0, kMetricsFrameInterval);
113
114 const int max_noise_power_dbfs = static_cast<int>(
115 10 * log10(max_noise_energy_ / frame_length_ + 1e-10f) - kdBFSOffset);
116 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.LevelControl.MaxNoisePower",
117 max_noise_power_dbfs, -90, 0, 50);
118
119 const int average_noise_power_dbfs = static_cast<int>(
120 10 * log10(noise_energy_sum_ / (frame_length_ * kMetricsFrameInterval) +
121 1e-10f) -
122 kdBFSOffset);
123 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.LevelControl.AverageNoisePower",
124 average_noise_power_dbfs, -90, 0, 50);
125
126 const int max_peak_level_dbfs = static_cast<int>(
127 10 * log10(max_peak_level_ * max_peak_level_ + 1e-10f) - kdBFSOffset);
128 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.LevelControl.MaxPeakLevel",
129 max_peak_level_dbfs, -90, 0, 50);
130
131 const int average_peak_level_dbfs = static_cast<int>(
132 10 * log10(peak_level_sum_ * peak_level_sum_ /
133 (kMetricsFrameInterval * kMetricsFrameInterval) +
134 1e-10f) -
135 kdBFSOffset);
136 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.LevelControl.AveragePeakLevel",
137 average_peak_level_dbfs, -90, 0, 50);
138
139 RTC_DCHECK_LE(1.f, max_gain_);
140 RTC_DCHECK_LE(1.f, gain_sum_ / kMetricsFrameInterval);
141
142 const int max_gain_db = static_cast<int>(10 * log10(max_gain_ * max_gain_));
143 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.LevelControl.MaxGain", max_gain_db, 0,
144 33, 30);
145
146 const int average_gain_db = static_cast<int>(
147 10 * log10(gain_sum_ * gain_sum_ /
148 (kMetricsFrameInterval * kMetricsFrameInterval)));
149 RTC_HISTOGRAM_COUNTS("WebRTC.Audio.LevelControl.AverageGain",
150 average_gain_db, 0, 33, 30);
151
152 const int long_term_peak_level_dbfs = static_cast<int>(
153 10 * log10(long_term_peak_level * long_term_peak_level + 1e-10f) -
154 kdBFSOffset);
155
156 const int frame_peak_level_dbfs = static_cast<int>(
157 10 * log10(frame_peak_level * frame_peak_level + 1e-10f) - kdBFSOffset);
158
159 RTC_LOG(LS_INFO) << "Level Controller metrics: {Max noise power: "
160 << max_noise_power_dbfs
161 << " dBFS, Average noise power: "
162 << average_noise_power_dbfs
163 << " dBFS, Max long term peak level: "
164 << max_peak_level_dbfs
165 << " dBFS, Average long term peak level: "
166 << average_peak_level_dbfs
167 << " dBFS, Max gain: "
168 << max_gain_db
169 << " dB, Average gain: "
170 << average_gain_db
171 << " dB, Long term peak level: "
172 << long_term_peak_level_dbfs
173 << " dBFS, Last frame peak level: "
174 << frame_peak_level_dbfs
175 << " dBFS}";
176
177 Reset();
178 }
179}
180
181LevelController::LevelController()
182 : data_dumper_(new ApmDataDumper(instance_count_)),
183 gain_applier_(data_dumper_.get()),
184 signal_classifier_(data_dumper_.get()),
185 peak_level_estimator_(kTargetLcPeakLeveldBFS) {
186 Initialize(AudioProcessing::kSampleRate48kHz);
187 ++instance_count_;
188}
189
190LevelController::~LevelController() {}
191
192void LevelController::Initialize(int sample_rate_hz) {
193 RTC_DCHECK(sample_rate_hz == AudioProcessing::kSampleRate8kHz ||
194 sample_rate_hz == AudioProcessing::kSampleRate16kHz ||
195 sample_rate_hz == AudioProcessing::kSampleRate32kHz ||
196 sample_rate_hz == AudioProcessing::kSampleRate48kHz);
197 data_dumper_->InitiateNewSetOfRecordings();
198 gain_selector_.Initialize(sample_rate_hz);
199 gain_applier_.Initialize(sample_rate_hz);
200 signal_classifier_.Initialize(sample_rate_hz);
201 noise_level_estimator_.Initialize(sample_rate_hz);
202 peak_level_estimator_.Initialize(config_.initial_peak_level_dbfs);
203 saturating_gain_estimator_.Initialize();
204 metrics_.Initialize(sample_rate_hz);
205
206 last_gain_ = 1.0f;
207 sample_rate_hz_ = sample_rate_hz;
208 dc_forgetting_factor_ = 0.01f * sample_rate_hz / 48000.f;
209 std::fill(dc_level_, dc_level_ + arraysize(dc_level_), 0.f);
210}
211
212void LevelController::Process(AudioBuffer* audio) {
213 RTC_DCHECK_LT(0, audio->num_channels());
214 RTC_DCHECK_GE(2, audio->num_channels());
215 RTC_DCHECK_NE(0.f, dc_forgetting_factor_);
216 RTC_DCHECK(sample_rate_hz_);
217 data_dumper_->DumpWav("lc_input", audio->num_frames(),
218 audio->channels_const_f()[0], *sample_rate_hz_, 1);
219
220 // Remove DC level.
221 for (size_t k = 0; k < audio->num_channels(); ++k) {
222 UpdateAndRemoveDcLevel(
223 dc_forgetting_factor_, &dc_level_[k],
224 rtc::ArrayView<float>(audio->channels_f()[k], audio->num_frames()));
225 }
226
227 SignalClassifier::SignalType signal_type;
228 signal_classifier_.Analyze(*audio, &signal_type);
229 int tmp = static_cast<int>(signal_type);
230 data_dumper_->DumpRaw("lc_signal_type", 1, &tmp);
231
232 // Estimate the noise energy.
233 float noise_energy =
234 noise_level_estimator_.Analyze(signal_type, FrameEnergy(*audio));
235
236 // Estimate the overall signal peak level.
237 const float frame_peak_level = PeakLevel(*audio);
238 const float long_term_peak_level =
239 peak_level_estimator_.Analyze(signal_type, frame_peak_level);
240
241 float saturating_gain = saturating_gain_estimator_.GetGain();
242
243 // Compute the new gain to apply.
244 last_gain_ =
245 gain_selector_.GetNewGain(long_term_peak_level, noise_energy,
246 saturating_gain, gain_jumpstart_, signal_type);
247
248 // Unflag the jumpstart of the gain as it should only happen once.
249 gain_jumpstart_ = false;
250
251 // Apply the gain to the signal.
252 int num_saturations = gain_applier_.Process(last_gain_, audio);
253
254 // Estimate the gain that saturates the overall signal.
255 saturating_gain_estimator_.Update(last_gain_, num_saturations);
256
257 // Update the metrics.
258 metrics_.Update(long_term_peak_level, noise_energy, last_gain_,
259 frame_peak_level);
260
261 data_dumper_->DumpRaw("lc_selected_gain", 1, &last_gain_);
262 data_dumper_->DumpRaw("lc_noise_energy", 1, &noise_energy);
263 data_dumper_->DumpRaw("lc_peak_level", 1, &long_term_peak_level);
264 data_dumper_->DumpRaw("lc_saturating_gain", 1, &saturating_gain);
265
266 data_dumper_->DumpWav("lc_output", audio->num_frames(),
267 audio->channels_f()[0], *sample_rate_hz_, 1);
268}
269
270void LevelController::ApplyConfig(
271 const AudioProcessing::Config::LevelController& config) {
272 RTC_DCHECK(Validate(config));
273 config_ = config;
274 peak_level_estimator_.Initialize(config_.initial_peak_level_dbfs);
275 gain_jumpstart_ = true;
276}
277
278std::string LevelController::ToString(
279 const AudioProcessing::Config::LevelController& config) {
280 std::stringstream ss;
281 ss << "{"
282 << "enabled: " << (config.enabled ? "true" : "false") << ", "
283 << "initial_peak_level_dbfs: " << config.initial_peak_level_dbfs << "}";
284 return ss.str();
285}
286
287bool LevelController::Validate(
288 const AudioProcessing::Config::LevelController& config) {
289 return (config.initial_peak_level_dbfs <
290 std::numeric_limits<float>::epsilon() &&
291 config.initial_peak_level_dbfs >
292 -(100.f + std::numeric_limits<float>::epsilon()));
293}
294
295} // namespace webrtc