blob: 5bb9d7e0264b21a199a75071edc117348b1f28f8 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/neteq/background_noise.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
pbos@webrtc.org12dc1a32013-08-05 16:22:53 +000014#include <string.h> // memcpy
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000015
16#include <algorithm> // min, max
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "common_audio/signal_processing/include/signal_processing_library.h"
19#include "modules/audio_coding/neteq/audio_multi_vector.h"
20#include "modules/audio_coding/neteq/cross_correlation.h"
21#include "modules/audio_coding/neteq/post_decode_vad.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000022
23namespace webrtc {
Alessio Bazzica7e53be02019-04-15 12:32:23 +020024namespace {
25
26constexpr size_t kMaxSampleRate = 48000;
27
28} // namespace
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000029
Peter Kastingdce40cf2015-08-24 14:52:23 -070030// static
Alessio Bazzica7e53be02019-04-15 12:32:23 +020031constexpr size_t BackgroundNoise::kMaxLpcOrder;
Peter Kastingdce40cf2015-08-24 14:52:23 -070032
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000033BackgroundNoise::BackgroundNoise(size_t num_channels)
34 : num_channels_(num_channels),
Henrik Lundin67190172018-04-20 15:34:48 +020035 channel_parameters_(new ChannelParameters[num_channels_]) {
pbos@webrtc.org2d1a55c2013-07-31 15:54:00 +000036 Reset();
37}
38
39BackgroundNoise::~BackgroundNoise() {}
40
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000041void BackgroundNoise::Reset() {
42 initialized_ = false;
43 for (size_t channel = 0; channel < num_channels_; ++channel) {
44 channel_parameters_[channel].Reset();
45 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000046}
47
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +000048void BackgroundNoise::Update(const AudioMultiVector& input,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000049 const PostDecodeVad& vad) {
50 if (vad.running() && vad.active_speech()) {
51 // Do not update the background noise parameters if we know that the signal
52 // is active speech.
53 return;
54 }
55
56 int32_t auto_correlation[kMaxLpcOrder + 1];
57 int16_t fiter_output[kMaxLpcOrder + kResidualLength];
58 int16_t reflection_coefficients[kMaxLpcOrder];
59 int16_t lpc_coefficients[kMaxLpcOrder + 1];
60
61 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
62 ChannelParameters& parameters = channel_parameters_[channel_ix];
63 int16_t temp_signal_array[kVecLen + kMaxLpcOrder] = {0};
64 int16_t* temp_signal = &temp_signal_array[kMaxLpcOrder];
minyue-webrtc79553cb2016-05-10 19:55:56 +020065 input[channel_ix].CopyTo(kVecLen, input.Size() - kVecLen, temp_signal);
Yves Gerey665174f2018-06-19 15:03:05 +020066 int32_t sample_energy =
67 CalculateAutoCorrelation(temp_signal, kVecLen, auto_correlation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000068
69 if ((!vad.running() &&
Yves Gerey665174f2018-06-19 15:03:05 +020070 sample_energy < parameters.energy_update_threshold) ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000071 (vad.running() && !vad.active_speech())) {
72 // Generate LPC coefficients.
73 if (auto_correlation[0] > 0) {
74 // Regardless of whether the filter is actually updated or not,
75 // update energy threshold levels, since we have in fact observed
76 // a low energy signal.
77 if (sample_energy < parameters.energy_update_threshold) {
78 // Never go under 1.0 in average sample energy.
79 parameters.energy_update_threshold = std::max(sample_energy, 1);
80 parameters.low_energy_update_threshold = 0;
81 }
82
83 // Only update BGN if filter is stable, i.e., if return value from
84 // Levinson-Durbin function is 1.
85 if (WebRtcSpl_LevinsonDurbin(auto_correlation, lpc_coefficients,
86 reflection_coefficients,
87 kMaxLpcOrder) != 1) {
88 return;
89 }
90 } else {
91 // Center value in auto-correlation is not positive. Do not update.
92 return;
93 }
94
95 // Generate the CNG gain factor by looking at the energy of the residual.
96 WebRtcSpl_FilterMAFastQ12(temp_signal + kVecLen - kResidualLength,
97 fiter_output, lpc_coefficients,
98 kMaxLpcOrder + 1, kResidualLength);
Yves Gerey665174f2018-06-19 15:03:05 +020099 int32_t residual_energy = WebRtcSpl_DotProductWithScale(
100 fiter_output, fiter_output, kResidualLength, 0);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000101
102 // Check spectral flatness.
103 // Comparing the residual variance with the input signal variance tells
104 // if the spectrum is flat or not.
henrik.lundina67e5f52017-03-01 03:06:50 -0800105 // If 5 * residual_energy >= 16 * sample_energy, the spectrum is flat
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000106 // enough. Also ensure that the energy is non-zero.
henrik.lundina67e5f52017-03-01 03:06:50 -0800107 if ((sample_energy > 0) &&
108 (int64_t{5} * residual_energy >= int64_t{16} * sample_energy)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000109 // Spectrum is flat enough; save filter parameters.
110 // |temp_signal| + |kVecLen| - |kMaxLpcOrder| points at the first of the
111 // |kMaxLpcOrder| samples in the residual signal, which will form the
112 // filter state for the next noise generation.
113 SaveParameters(channel_ix, lpc_coefficients,
114 temp_signal + kVecLen - kMaxLpcOrder, sample_energy,
115 residual_energy);
116 }
117 } else {
118 // Will only happen if post-decode VAD is disabled and |sample_energy| is
119 // not low enough. Increase the threshold for update so that it increases
120 // by a factor 4 in 4 seconds.
121 IncrementEnergyThreshold(channel_ix, sample_energy);
122 }
123 }
124 return;
125}
126
Alessio Bazzica7e53be02019-04-15 12:32:23 +0200127void BackgroundNoise::GenerateBackgroundNoise(
128 rtc::ArrayView<const int16_t> random_vector,
129 size_t channel,
130 int mute_slope,
131 bool too_many_expands,
132 size_t num_noise_samples,
133 int16_t* buffer) {
134 constexpr size_t kNoiseLpcOrder = kMaxLpcOrder;
135 int16_t scaled_random_vector[kMaxSampleRate / 8000 * 125];
136 assert(num_noise_samples <= (kMaxSampleRate / 8000 * 125));
137 RTC_DCHECK_GE(random_vector.size(), num_noise_samples);
138 int16_t* noise_samples = &buffer[kNoiseLpcOrder];
139 if (initialized()) {
140 // Use background noise parameters.
141 memcpy(noise_samples - kNoiseLpcOrder, FilterState(channel),
142 sizeof(int16_t) * kNoiseLpcOrder);
143
144 int dc_offset = 0;
145 if (ScaleShift(channel) > 1) {
146 dc_offset = 1 << (ScaleShift(channel) - 1);
147 }
148
149 // Scale random vector to correct energy level.
150 WebRtcSpl_AffineTransformVector(scaled_random_vector, random_vector.data(),
151 Scale(channel), dc_offset,
152 ScaleShift(channel), num_noise_samples);
153
154 WebRtcSpl_FilterARFastQ12(scaled_random_vector, noise_samples,
155 Filter(channel), kNoiseLpcOrder + 1,
156 num_noise_samples);
157
158 SetFilterState(
159 channel,
160 {&(noise_samples[num_noise_samples - kNoiseLpcOrder]), kNoiseLpcOrder});
161
162 // Unmute the background noise.
163 int16_t bgn_mute_factor = MuteFactor(channel);
164 if (bgn_mute_factor < 16384) {
165 WebRtcSpl_AffineTransformVector(noise_samples, noise_samples,
166 bgn_mute_factor, 8192, 14,
167 num_noise_samples);
168 }
169 // Update mute_factor in BackgroundNoise class.
170 SetMuteFactor(channel, bgn_mute_factor);
171 } else {
172 // BGN parameters have not been initialized; use zero noise.
173 memset(noise_samples, 0, sizeof(int16_t) * num_noise_samples);
174 }
175}
176
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000177int32_t BackgroundNoise::Energy(size_t channel) const {
178 assert(channel < num_channels_);
179 return channel_parameters_[channel].energy;
180}
181
182void BackgroundNoise::SetMuteFactor(size_t channel, int16_t value) {
183 assert(channel < num_channels_);
184 channel_parameters_[channel].mute_factor = value;
185}
186
187int16_t BackgroundNoise::MuteFactor(size_t channel) const {
188 assert(channel < num_channels_);
189 return channel_parameters_[channel].mute_factor;
190}
191
192const int16_t* BackgroundNoise::Filter(size_t channel) const {
193 assert(channel < num_channels_);
194 return channel_parameters_[channel].filter;
195}
196
197const int16_t* BackgroundNoise::FilterState(size_t channel) const {
198 assert(channel < num_channels_);
199 return channel_parameters_[channel].filter_state;
200}
201
Yves Gerey665174f2018-06-19 15:03:05 +0200202void BackgroundNoise::SetFilterState(size_t channel,
Alessio Bazzica7e53be02019-04-15 12:32:23 +0200203 rtc::ArrayView<const int16_t> input) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000204 assert(channel < num_channels_);
Alessio Bazzica7e53be02019-04-15 12:32:23 +0200205 size_t length = std::min(input.size(), kMaxLpcOrder);
206 memcpy(channel_parameters_[channel].filter_state, input.data(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000207 length * sizeof(int16_t));
208}
209
210int16_t BackgroundNoise::Scale(size_t channel) const {
211 assert(channel < num_channels_);
212 return channel_parameters_[channel].scale;
213}
214int16_t BackgroundNoise::ScaleShift(size_t channel) const {
215 assert(channel < num_channels_);
216 return channel_parameters_[channel].scale_shift;
217}
218
219int32_t BackgroundNoise::CalculateAutoCorrelation(
Yves Gerey665174f2018-06-19 15:03:05 +0200220 const int16_t* signal,
221 size_t length,
222 int32_t* auto_correlation) const {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 static const int kCorrelationStep = -1;
minyue53ff70f2016-05-02 01:50:30 -0700224 const int correlation_scale =
225 CrossCorrelationWithAutoShift(signal, signal, length, kMaxLpcOrder + 1,
226 kCorrelationStep, auto_correlation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000227
228 // Number of shifts to normalize energy to energy/sample.
229 int energy_sample_shift = kLogVecLen - correlation_scale;
230 return auto_correlation[0] >> energy_sample_shift;
231}
232
233void BackgroundNoise::IncrementEnergyThreshold(size_t channel,
234 int32_t sample_energy) {
235 // TODO(hlundin): Simplify the below threshold update. What this code
236 // does is simply "threshold += (increment * threshold) >> 16", but due
237 // to the limited-width operations, it is not exactly the same. The
238 // difference should be inaudible, but bit-exactness would not be
239 // maintained.
240 assert(channel < num_channels_);
241 ChannelParameters& parameters = channel_parameters_[channel];
242 int32_t temp_energy =
Yves Gerey665174f2018-06-19 15:03:05 +0200243 (kThresholdIncrement * parameters.low_energy_update_threshold) >> 16;
244 temp_energy +=
245 kThresholdIncrement * (parameters.energy_update_threshold & 0xFF);
246 temp_energy +=
247 (kThresholdIncrement * ((parameters.energy_update_threshold >> 8) & 0xFF))
248 << 8;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000249 parameters.low_energy_update_threshold += temp_energy;
250
Yves Gerey665174f2018-06-19 15:03:05 +0200251 parameters.energy_update_threshold +=
252 kThresholdIncrement * (parameters.energy_update_threshold >> 16);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000253 parameters.energy_update_threshold +=
254 parameters.low_energy_update_threshold >> 16;
255 parameters.low_energy_update_threshold =
256 parameters.low_energy_update_threshold & 0x0FFFF;
257
258 // Update maximum energy.
259 // Decrease by a factor 1/1024 each time.
Yves Gerey665174f2018-06-19 15:03:05 +0200260 parameters.max_energy = parameters.max_energy - (parameters.max_energy >> 10);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 if (sample_energy > parameters.max_energy) {
262 parameters.max_energy = sample_energy;
263 }
264
265 // Set |energy_update_threshold| to no less than 60 dB lower than
266 // |max_energy_|. Adding 524288 assures proper rounding.
267 int32_t energy_update_threshold = (parameters.max_energy + 524288) >> 20;
268 if (energy_update_threshold > parameters.energy_update_threshold) {
269 parameters.energy_update_threshold = energy_update_threshold;
270 }
271}
272
273void BackgroundNoise::SaveParameters(size_t channel,
274 const int16_t* lpc_coefficients,
275 const int16_t* filter_state,
276 int32_t sample_energy,
277 int32_t residual_energy) {
278 assert(channel < num_channels_);
279 ChannelParameters& parameters = channel_parameters_[channel];
280 memcpy(parameters.filter, lpc_coefficients,
Yves Gerey665174f2018-06-19 15:03:05 +0200281 (kMaxLpcOrder + 1) * sizeof(int16_t));
282 memcpy(parameters.filter_state, filter_state, kMaxLpcOrder * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000283 // Save energy level and update energy threshold levels.
284 // Never get under 1.0 in average sample energy.
285 parameters.energy = std::max(sample_energy, 1);
286 parameters.energy_update_threshold = parameters.energy;
287 parameters.low_energy_update_threshold = 0;
288
289 // Normalize residual_energy to 29 or 30 bits before sqrt.
Peter Kastingb7e50542015-06-11 12:55:50 -0700290 int16_t norm_shift = WebRtcSpl_NormW32(residual_energy) - 1;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 if (norm_shift & 0x1) {
292 norm_shift -= 1; // Even number of shifts required.
293 }
Henrik Lundin3c4ef292015-08-31 10:18:28 +0200294 residual_energy = WEBRTC_SPL_SHIFT_W32(residual_energy, norm_shift);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000295
296 // Calculate scale and shift factor.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700297 parameters.scale = static_cast<int16_t>(WebRtcSpl_SqrtFloor(residual_energy));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000298 // Add 13 to the |scale_shift_|, since the random numbers table is in
299 // Q13.
300 // TODO(hlundin): Move the "13" to where the |scale_shift_| is used?
Peter Kastingb7e50542015-06-11 12:55:50 -0700301 parameters.scale_shift =
302 static_cast<int16_t>(13 + ((kLogResidualLength + norm_shift) / 2));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000303
304 initialized_ = true;
305}
306
307} // namespace webrtc