blob: ffaa4c74aa0d8305c8010a12cc5a4697e06f5b2c [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/expand.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> // memset
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000015
16#include <algorithm> // min, max
Yves Gerey665174f2018-06-19 15:03:05 +020017#include <limits> // numeric_limits<T>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "common_audio/signal_processing/include/signal_processing_library.h"
Yves Gerey988cc082018-10-23 12:03:01 +020020#include "modules/audio_coding/neteq/audio_multi_vector.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "modules/audio_coding/neteq/background_noise.h"
22#include "modules/audio_coding/neteq/cross_correlation.h"
23#include "modules/audio_coding/neteq/dsp_helper.h"
24#include "modules/audio_coding/neteq/random_vector.h"
25#include "modules/audio_coding/neteq/statistics_calculator.h"
26#include "modules/audio_coding/neteq/sync_buffer.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010027#include "rtc_base/numerics/safe_conversions.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000028
29namespace webrtc {
30
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020031Expand::Expand(BackgroundNoise* background_noise,
32 SyncBuffer* sync_buffer,
33 RandomVector* random_vector,
Henrik Lundinbef77e22015-08-18 14:58:09 +020034 StatisticsCalculator* statistics,
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020035 int fs,
36 size_t num_channels)
37 : random_vector_(random_vector),
38 sync_buffer_(sync_buffer),
39 first_expand_(true),
40 fs_hz_(fs),
41 num_channels_(num_channels),
42 consecutive_expands_(0),
43 background_noise_(background_noise),
Henrik Lundinbef77e22015-08-18 14:58:09 +020044 statistics_(statistics),
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020045 overlap_length_(5 * fs / 8000),
46 lag_index_direction_(0),
47 current_lag_index_(0),
48 stop_muting_(false),
Henrik Lundinbef77e22015-08-18 14:58:09 +020049 expand_duration_samples_(0),
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020050 channel_parameters_(new ChannelParameters[num_channels_]) {
Mirko Bonadei25ab3222021-07-08 20:08:20 +020051 RTC_DCHECK(fs == 8000 || fs == 16000 || fs == 32000 || fs == 48000);
52 RTC_DCHECK_LE(fs,
53 static_cast<int>(kMaxSampleRate)); // Should not be possible.
54 RTC_DCHECK_GT(num_channels_, 0);
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020055 memset(expand_lags_, 0, sizeof(expand_lags_));
56 Reset();
57}
58
59Expand::~Expand() = default;
60
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000061void Expand::Reset() {
62 first_expand_ = true;
63 consecutive_expands_ = 0;
64 max_lag_ = 0;
65 for (size_t ix = 0; ix < num_channels_; ++ix) {
66 channel_parameters_[ix].expand_vector0.Clear();
67 channel_parameters_[ix].expand_vector1.Clear();
68 }
69}
70
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +000071int Expand::Process(AudioMultiVector* output) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000072 int16_t random_vector[kMaxSampleRate / 8000 * 120 + 30];
73 int16_t scaled_random_vector[kMaxSampleRate / 8000 * 125];
74 static const int kTempDataSize = 3600;
75 int16_t temp_data[kTempDataSize]; // TODO(hlundin) Remove this.
76 int16_t* voiced_vector_storage = temp_data;
77 int16_t* voiced_vector = &voiced_vector_storage[overlap_length_];
Peter Kastingdce40cf2015-08-24 14:52:23 -070078 static const size_t kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000079 int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
80 int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
81 int16_t* noise_vector = unvoiced_array_memory + kNoiseLpcOrder;
82
83 int fs_mult = fs_hz_ / 8000;
84
85 if (first_expand_) {
86 // Perform initial setup if this is the first expansion since last reset.
87 AnalyzeSignal(random_vector);
88 first_expand_ = false;
Henrik Lundinbef77e22015-08-18 14:58:09 +020089 expand_duration_samples_ = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000090 } else {
91 // This is not the first expansion, parameters are already estimated.
92 // Extract a noise segment.
Peter Kastingdce40cf2015-08-24 14:52:23 -070093 size_t rand_length = max_lag_;
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000094 // This only applies to SWB where length could be larger than 256.
Mirko Bonadei25ab3222021-07-08 20:08:20 +020095 RTC_DCHECK_LE(rand_length, kMaxSampleRate / 8000 * 120 + 30);
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000096 GenerateRandomVector(2, rand_length, random_vector);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000097 }
98
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000099 // Generate signal.
100 UpdateLagIndex();
101
102 // Voiced part.
103 // Generate a weighted vector with the current lag.
104 size_t expansion_vector_length = max_lag_ + overlap_length_;
105 size_t current_lag = expand_lags_[current_lag_index_];
106 // Copy lag+overlap data.
Yves Gerey665174f2018-06-19 15:03:05 +0200107 size_t expansion_vector_position =
108 expansion_vector_length - current_lag - overlap_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000109 size_t temp_length = current_lag + overlap_length_;
110 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
111 ChannelParameters& parameters = channel_parameters_[channel_ix];
112 if (current_lag_index_ == 0) {
113 // Use only expand_vector0.
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200114 RTC_DCHECK_LE(expansion_vector_position + temp_length,
115 parameters.expand_vector0.Size());
minyue-webrtc79553cb2016-05-10 19:55:56 +0200116 parameters.expand_vector0.CopyTo(temp_length, expansion_vector_position,
117 voiced_vector_storage);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000118 } else if (current_lag_index_ == 1) {
minyue-webrtc79553cb2016-05-10 19:55:56 +0200119 std::unique_ptr<int16_t[]> temp_0(new int16_t[temp_length]);
120 parameters.expand_vector0.CopyTo(temp_length, expansion_vector_position,
121 temp_0.get());
122 std::unique_ptr<int16_t[]> temp_1(new int16_t[temp_length]);
123 parameters.expand_vector1.CopyTo(temp_length, expansion_vector_position,
124 temp_1.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 // Mix 3/4 of expand_vector0 with 1/4 of expand_vector1.
minyue-webrtc79553cb2016-05-10 19:55:56 +0200126 WebRtcSpl_ScaleAndAddVectorsWithRound(temp_0.get(), 3, temp_1.get(), 1, 2,
127 voiced_vector_storage, temp_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000128 } else if (current_lag_index_ == 2) {
129 // Mix 1/2 of expand_vector0 with 1/2 of expand_vector1.
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200130 RTC_DCHECK_LE(expansion_vector_position + temp_length,
131 parameters.expand_vector0.Size());
132 RTC_DCHECK_LE(expansion_vector_position + temp_length,
133 parameters.expand_vector1.Size());
minyue-webrtc79553cb2016-05-10 19:55:56 +0200134
135 std::unique_ptr<int16_t[]> temp_0(new int16_t[temp_length]);
136 parameters.expand_vector0.CopyTo(temp_length, expansion_vector_position,
137 temp_0.get());
138 std::unique_ptr<int16_t[]> temp_1(new int16_t[temp_length]);
139 parameters.expand_vector1.CopyTo(temp_length, expansion_vector_position,
140 temp_1.get());
141 WebRtcSpl_ScaleAndAddVectorsWithRound(temp_0.get(), 1, temp_1.get(), 1, 1,
142 voiced_vector_storage, temp_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000143 }
144
145 // Get tapering window parameters. Values are in Q15.
146 int16_t muting_window, muting_window_increment;
147 int16_t unmuting_window, unmuting_window_increment;
148 if (fs_hz_ == 8000) {
149 muting_window = DspHelper::kMuteFactorStart8kHz;
150 muting_window_increment = DspHelper::kMuteFactorIncrement8kHz;
151 unmuting_window = DspHelper::kUnmuteFactorStart8kHz;
152 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement8kHz;
153 } else if (fs_hz_ == 16000) {
154 muting_window = DspHelper::kMuteFactorStart16kHz;
155 muting_window_increment = DspHelper::kMuteFactorIncrement16kHz;
156 unmuting_window = DspHelper::kUnmuteFactorStart16kHz;
157 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement16kHz;
158 } else if (fs_hz_ == 32000) {
159 muting_window = DspHelper::kMuteFactorStart32kHz;
160 muting_window_increment = DspHelper::kMuteFactorIncrement32kHz;
161 unmuting_window = DspHelper::kUnmuteFactorStart32kHz;
162 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement32kHz;
163 } else { // fs_ == 48000
164 muting_window = DspHelper::kMuteFactorStart48kHz;
165 muting_window_increment = DspHelper::kMuteFactorIncrement48kHz;
166 unmuting_window = DspHelper::kUnmuteFactorStart48kHz;
167 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement48kHz;
168 }
169
170 // Smooth the expanded if it has not been muted to a low amplitude and
171 // |current_voice_mix_factor| is larger than 0.5.
172 if ((parameters.mute_factor > 819) &&
173 (parameters.current_voice_mix_factor > 8192)) {
174 size_t start_ix = sync_buffer_->Size() - overlap_length_;
175 for (size_t i = 0; i < overlap_length_; i++) {
176 // Do overlap add between new vector and overlap.
177 (*sync_buffer_)[channel_ix][start_ix + i] =
178 (((*sync_buffer_)[channel_ix][start_ix + i] * muting_window) +
Yves Gerey665174f2018-06-19 15:03:05 +0200179 (((parameters.mute_factor * voiced_vector_storage[i]) >> 14) *
180 unmuting_window) +
181 16384) >>
182 15;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 muting_window += muting_window_increment;
184 unmuting_window += unmuting_window_increment;
185 }
186 } else if (parameters.mute_factor == 0) {
187 // The expanded signal will consist of only comfort noise if
188 // mute_factor = 0. Set the output length to 15 ms for best noise
189 // production.
190 // TODO(hlundin): This has been disabled since the length of
191 // parameters.expand_vector0 and parameters.expand_vector1 no longer
192 // match with expand_lags_, causing invalid reads and writes. Is it a good
193 // idea to enable this again, and solve the vector size problem?
Yves Gerey665174f2018-06-19 15:03:05 +0200194 // max_lag_ = fs_mult * 120;
195 // expand_lags_[0] = fs_mult * 120;
196 // expand_lags_[1] = fs_mult * 120;
197 // expand_lags_[2] = fs_mult * 120;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000198 }
199
200 // Unvoiced part.
201 // Filter |scaled_random_vector| through |ar_filter_|.
202 memcpy(unvoiced_vector - kUnvoicedLpcOrder, parameters.ar_filter_state,
203 sizeof(int16_t) * kUnvoicedLpcOrder);
204 int32_t add_constant = 0;
205 if (parameters.ar_gain_scale > 0) {
206 add_constant = 1 << (parameters.ar_gain_scale - 1);
207 }
208 WebRtcSpl_AffineTransformVector(scaled_random_vector, random_vector,
209 parameters.ar_gain, add_constant,
Yves Gerey665174f2018-06-19 15:03:05 +0200210 parameters.ar_gain_scale, current_lag);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000211 WebRtcSpl_FilterARFastQ12(scaled_random_vector, unvoiced_vector,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000212 parameters.ar_filter, kUnvoicedLpcOrder + 1,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700213 current_lag);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000214 memcpy(parameters.ar_filter_state,
215 &(unvoiced_vector[current_lag - kUnvoicedLpcOrder]),
216 sizeof(int16_t) * kUnvoicedLpcOrder);
217
218 // Combine voiced and unvoiced contributions.
219
220 // Set a suitable cross-fading slope.
221 // For lag =
222 // <= 31 * fs_mult => go from 1 to 0 in about 8 ms;
223 // (>= 31 .. <= 63) * fs_mult => go from 1 to 0 in about 16 ms;
224 // >= 64 * fs_mult => go from 1 to 0 in about 32 ms.
225 // temp_shift = getbits(max_lag_) - 5.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700226 int temp_shift =
kwibergd3edd772017-03-01 18:52:48 -0800227 (31 - WebRtcSpl_NormW32(rtc::dchecked_cast<int32_t>(max_lag_))) - 5;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000228 int16_t mix_factor_increment = 256 >> temp_shift;
229 if (stop_muting_) {
230 mix_factor_increment = 0;
231 }
232
233 // Create combined signal by shifting in more and more of unvoiced part.
234 temp_shift = 8 - temp_shift; // = getbits(mix_factor_increment).
Yves Gerey665174f2018-06-19 15:03:05 +0200235 size_t temp_length =
236 (parameters.current_voice_mix_factor - parameters.voice_mix_factor) >>
237 temp_shift;
Peter Kasting728d9032015-06-11 14:31:38 -0700238 temp_length = std::min(temp_length, current_lag);
239 DspHelper::CrossFade(voiced_vector, unvoiced_vector, temp_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000240 &parameters.current_voice_mix_factor,
241 mix_factor_increment, temp_data);
242
243 // End of cross-fading period was reached before end of expanded signal
244 // path. Mix the rest with a fixed mixing factor.
Peter Kasting728d9032015-06-11 14:31:38 -0700245 if (temp_length < current_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000246 if (mix_factor_increment != 0) {
247 parameters.current_voice_mix_factor = parameters.voice_mix_factor;
248 }
Peter Kastingb7e50542015-06-11 12:55:50 -0700249 int16_t temp_scale = 16384 - parameters.current_voice_mix_factor;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 WebRtcSpl_ScaleAndAddVectorsWithRound(
Peter Kasting728d9032015-06-11 14:31:38 -0700251 voiced_vector + temp_length, parameters.current_voice_mix_factor,
252 unvoiced_vector + temp_length, temp_scale, 14,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700253 temp_data + temp_length, current_lag - temp_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000254 }
255
256 // Select muting slope depending on how many consecutive expands we have
257 // done.
258 if (consecutive_expands_ == 3) {
259 // Let the mute factor decrease from 1.0 to 0.95 in 6.25 ms.
260 // mute_slope = 0.0010 / fs_mult in Q20.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700261 parameters.mute_slope = std::max(parameters.mute_slope, 1049 / fs_mult);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000262 }
263 if (consecutive_expands_ == 7) {
264 // Let the mute factor decrease from 1.0 to 0.90 in 6.25 ms.
265 // mute_slope = 0.0020 / fs_mult in Q20.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700266 parameters.mute_slope = std::max(parameters.mute_slope, 2097 / fs_mult);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000267 }
268
269 // Mute segment according to slope value.
270 if ((consecutive_expands_ != 0) || !parameters.onset) {
271 // Mute to the previous level, then continue with the muting.
Yves Gerey665174f2018-06-19 15:03:05 +0200272 WebRtcSpl_AffineTransformVector(
273 temp_data, temp_data, parameters.mute_factor, 8192, 14, current_lag);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000274
275 if (!stop_muting_) {
276 DspHelper::MuteSignal(temp_data, parameters.mute_slope, current_lag);
277
278 // Shift by 6 to go from Q20 to Q14.
279 // TODO(hlundin): Adding 8192 before shifting 6 steps seems wrong.
280 // Legacy.
Yves Gerey665174f2018-06-19 15:03:05 +0200281 int16_t gain = static_cast<int16_t>(
282 16384 - (((current_lag * parameters.mute_slope) + 8192) >> 6));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000283 gain = ((gain * parameters.mute_factor) + 8192) >> 14;
284
285 // Guard against getting stuck with very small (but sometimes audible)
286 // gain.
287 if ((consecutive_expands_ > 3) && (gain >= parameters.mute_factor)) {
288 parameters.mute_factor = 0;
289 } else {
290 parameters.mute_factor = gain;
291 }
292 }
293 }
294
295 // Background noise part.
Alessio Bazzica7e53be02019-04-15 12:32:23 +0200296 background_noise_->GenerateBackgroundNoise(
Yves Gerey665174f2018-06-19 15:03:05 +0200297 random_vector, channel_ix, channel_parameters_[channel_ix].mute_slope,
298 TooManyExpands(), current_lag, unvoiced_array_memory);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299
300 // Add background noise to the combined voiced-unvoiced signal.
301 for (size_t i = 0; i < current_lag; i++) {
302 temp_data[i] = temp_data[i] + noise_vector[i];
303 }
304 if (channel_ix == 0) {
305 output->AssertSize(current_lag);
306 } else {
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200307 RTC_DCHECK_EQ(output->Size(), current_lag);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000308 }
minyue-webrtc79553cb2016-05-10 19:55:56 +0200309 (*output)[channel_ix].OverwriteAt(temp_data, current_lag, 0);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310 }
311
312 // Increase call number and cap it.
Yves Gerey665174f2018-06-19 15:03:05 +0200313 consecutive_expands_ = consecutive_expands_ >= kMaxConsecutiveExpands
314 ? kMaxConsecutiveExpands
315 : consecutive_expands_ + 1;
Henrik Lundinbef77e22015-08-18 14:58:09 +0200316 expand_duration_samples_ += output->Size();
317 // Clamp the duration counter at 2 seconds.
kwibergd3edd772017-03-01 18:52:48 -0800318 expand_duration_samples_ = std::min(expand_duration_samples_,
319 rtc::dchecked_cast<size_t>(fs_hz_ * 2));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000320 return 0;
321}
322
323void Expand::SetParametersForNormalAfterExpand() {
324 current_lag_index_ = 0;
325 lag_index_direction_ = 0;
326 stop_muting_ = true; // Do not mute signal any more.
Jakob Ivarsson352ce5c2018-11-27 12:52:16 +0100327 statistics_->LogDelayedPacketOutageEvent(expand_duration_samples_, fs_hz_);
Henrik Lundin2a8bd092019-04-26 09:47:07 +0200328 statistics_->EndExpandEvent(fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000329}
330
331void Expand::SetParametersForMergeAfterExpand() {
Yves Gerey665174f2018-06-19 15:03:05 +0200332 current_lag_index_ = -1; /* out of the 3 possible ones */
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000333 lag_index_direction_ = 1; /* make sure we get the "optimal" lag */
334 stop_muting_ = true;
Henrik Lundin2a8bd092019-04-26 09:47:07 +0200335 statistics_->EndExpandEvent(fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000336}
337
henrik.lundinf3995f72016-05-10 05:54:35 -0700338bool Expand::Muted() const {
339 if (first_expand_ || stop_muting_)
340 return false;
341 RTC_DCHECK(channel_parameters_);
342 for (size_t ch = 0; ch < num_channels_; ++ch) {
343 if (channel_parameters_[ch].mute_factor != 0)
344 return false;
345 }
346 return true;
347}
348
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200349size_t Expand::overlap_length() const {
350 return overlap_length_;
351}
352
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000353void Expand::InitializeForAnExpandPeriod() {
354 lag_index_direction_ = 1;
355 current_lag_index_ = -1;
356 stop_muting_ = false;
357 random_vector_->set_seed_increment(1);
358 consecutive_expands_ = 0;
359 for (size_t ix = 0; ix < num_channels_; ++ix) {
360 channel_parameters_[ix].current_voice_mix_factor = 16384; // 1.0 in Q14.
Yves Gerey665174f2018-06-19 15:03:05 +0200361 channel_parameters_[ix].mute_factor = 16384; // 1.0 in Q14.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000362 // Start with 0 gain for background noise.
363 background_noise_->SetMuteFactor(ix, 0);
364 }
365}
366
367bool Expand::TooManyExpands() {
368 return consecutive_expands_ >= kMaxConsecutiveExpands;
369}
370
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371void Expand::AnalyzeSignal(int16_t* random_vector) {
372 int32_t auto_correlation[kUnvoicedLpcOrder + 1];
373 int16_t reflection_coeff[kUnvoicedLpcOrder];
374 int16_t correlation_vector[kMaxSampleRate / 8000 * 102];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700375 size_t best_correlation_index[kNumCorrelationCandidates];
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376 int16_t best_correlation[kNumCorrelationCandidates];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700377 size_t best_distortion_index[kNumCorrelationCandidates];
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000378 int16_t best_distortion[kNumCorrelationCandidates];
379 int32_t correlation_vector2[(99 * kMaxSampleRate / 8000) + 1];
380 int32_t best_distortion_w32[kNumCorrelationCandidates];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700381 static const size_t kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000382 int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
383 int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
384
385 int fs_mult = fs_hz_ / 8000;
386
387 // Pre-calculate common multiplications with fs_mult.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700388 size_t fs_mult_4 = static_cast<size_t>(fs_mult * 4);
389 size_t fs_mult_20 = static_cast<size_t>(fs_mult * 20);
390 size_t fs_mult_120 = static_cast<size_t>(fs_mult * 120);
391 size_t fs_mult_dist_len = fs_mult * kDistortionLength;
392 size_t fs_mult_lpc_analysis_len = fs_mult * kLpcAnalysisLength;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393
Peter Kastingdce40cf2015-08-24 14:52:23 -0700394 const size_t signal_length = static_cast<size_t>(256 * fs_mult);
minyue-webrtc79553cb2016-05-10 19:55:56 +0200395
396 const size_t audio_history_position = sync_buffer_->Size() - signal_length;
397 std::unique_ptr<int16_t[]> audio_history(new int16_t[signal_length]);
398 (*sync_buffer_)[0].CopyTo(signal_length, audio_history_position,
399 audio_history.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000401 // Initialize.
402 InitializeForAnExpandPeriod();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000403
404 // Calculate correlation in downsampled domain (4 kHz sample rate).
Peter Kastingdce40cf2015-08-24 14:52:23 -0700405 size_t correlation_length = 51; // TODO(hlundin): Legacy bit-exactness.
turaj@webrtc.org58cd3162013-10-31 15:15:55 +0000406 // If it is decided to break bit-exactness |correlation_length| should be
407 // initialized to the return value of Correlation().
minyue-webrtc79553cb2016-05-10 19:55:56 +0200408 Correlation(audio_history.get(), signal_length, correlation_vector);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000409
410 // Find peaks in correlation vector.
411 DspHelper::PeakDetection(correlation_vector, correlation_length,
412 kNumCorrelationCandidates, fs_mult,
413 best_correlation_index, best_correlation);
414
415 // Adjust peak locations; cross-correlation lags start at 2.5 ms
416 // (20 * fs_mult samples).
417 best_correlation_index[0] += fs_mult_20;
418 best_correlation_index[1] += fs_mult_20;
419 best_correlation_index[2] += fs_mult_20;
420
421 // Calculate distortion around the |kNumCorrelationCandidates| best lags.
422 int distortion_scale = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700423 for (size_t i = 0; i < kNumCorrelationCandidates; i++) {
Yves Gerey665174f2018-06-19 15:03:05 +0200424 size_t min_index =
425 std::max(fs_mult_20, best_correlation_index[i] - fs_mult_4);
426 size_t max_index =
427 std::min(fs_mult_120 - 1, best_correlation_index[i] + fs_mult_4);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428 best_distortion_index[i] = DspHelper::MinDistortion(
429 &(audio_history[signal_length - fs_mult_dist_len]), min_index,
430 max_index, fs_mult_dist_len, &best_distortion_w32[i]);
431 distortion_scale = std::max(16 - WebRtcSpl_NormW32(best_distortion_w32[i]),
432 distortion_scale);
433 }
434 // Shift the distortion values to fit in 16 bits.
435 WebRtcSpl_VectorBitShiftW32ToW16(best_distortion, kNumCorrelationCandidates,
436 best_distortion_w32, distortion_scale);
437
438 // Find the maximizing index |i| of the cost function
439 // f[i] = best_correlation[i] / best_distortion[i].
turaj@webrtc.org58cd3162013-10-31 15:15:55 +0000440 int32_t best_ratio = std::numeric_limits<int32_t>::min();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700441 size_t best_index = std::numeric_limits<size_t>::max();
442 for (size_t i = 0; i < kNumCorrelationCandidates; ++i) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000443 int32_t ratio;
444 if (best_distortion[i] > 0) {
ivoc4843dd12017-01-09 08:31:42 -0800445 ratio = (best_correlation[i] * (1 << 16)) / best_distortion[i];
turaj@webrtc.org7126b382013-07-31 16:05:09 +0000446 } else if (best_correlation[i] == 0) {
447 ratio = 0; // No correlation set result to zero.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000448 } else {
turaj@webrtc.org7126b382013-07-31 16:05:09 +0000449 ratio = std::numeric_limits<int32_t>::max(); // Denominator is zero.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000450 }
451 if (ratio > best_ratio) {
452 best_index = i;
453 best_ratio = ratio;
454 }
455 }
456
Peter Kastingdce40cf2015-08-24 14:52:23 -0700457 size_t distortion_lag = best_distortion_index[best_index];
458 size_t correlation_lag = best_correlation_index[best_index];
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000459 max_lag_ = std::max(distortion_lag, correlation_lag);
460
461 // Calculate the exact best correlation in the range between
462 // |correlation_lag| and |distortion_lag|.
Yves Gerey665174f2018-06-19 15:03:05 +0200463 correlation_length = std::max(std::min(distortion_lag + 10, fs_mult_120),
464 static_cast<size_t>(60 * fs_mult));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000465
Peter Kastingdce40cf2015-08-24 14:52:23 -0700466 size_t start_index = std::min(distortion_lag, correlation_lag);
467 size_t correlation_lags = static_cast<size_t>(
Yves Gerey665174f2018-06-19 15:03:05 +0200468 WEBRTC_SPL_ABS_W16((distortion_lag - correlation_lag)) + 1);
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200469 RTC_DCHECK_LE(correlation_lags, static_cast<size_t>(99 * fs_mult + 1));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000470
471 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
472 ChannelParameters& parameters = channel_parameters_[channel_ix];
Henrik Lundin21021f02019-12-02 15:46:00 +0100473 if (channel_ix > 0) {
474 // When channel_ix == 0, audio_history contains the correct audio. For the
475 // other cases, we will have to copy the correct channel into
476 // audio_history.
477 (*sync_buffer_)[channel_ix].CopyTo(signal_length, audio_history_position,
478 audio_history.get());
479 }
480
minyue8c229622016-04-28 02:16:48 -0700481 // Calculate suitable scaling.
482 int16_t signal_max = WebRtcSpl_MaxAbsValueW16(
Yves Gerey665174f2018-06-19 15:03:05 +0200483 &audio_history[signal_length - correlation_length - start_index -
484 correlation_lags],
485 correlation_length + start_index + correlation_lags - 1);
486 int correlation_scale =
487 (31 - WebRtcSpl_NormW32(signal_max * signal_max)) +
minyue8c229622016-04-28 02:16:48 -0700488 (31 - WebRtcSpl_NormW32(static_cast<int32_t>(correlation_length))) - 31;
489 correlation_scale = std::max(0, correlation_scale);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490
491 // Calculate the correlation, store in |correlation_vector2|.
minyue8c229622016-04-28 02:16:48 -0700492 WebRtcSpl_CrossCorrelation(
493 correlation_vector2,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000494 &(audio_history[signal_length - correlation_length]),
495 &(audio_history[signal_length - correlation_length - start_index]),
minyue8c229622016-04-28 02:16:48 -0700496 correlation_length, correlation_lags, correlation_scale, -1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000497
498 // Find maximizing index.
Peter Kasting1380e262015-08-28 17:31:03 -0700499 best_index = WebRtcSpl_MaxIndexW32(correlation_vector2, correlation_lags);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000500 int32_t max_correlation = correlation_vector2[best_index];
501 // Compensate index with start offset.
502 best_index = best_index + start_index;
503
504 // Calculate energies.
505 int32_t energy1 = WebRtcSpl_DotProductWithScale(
506 &(audio_history[signal_length - correlation_length]),
507 &(audio_history[signal_length - correlation_length]),
508 correlation_length, correlation_scale);
509 int32_t energy2 = WebRtcSpl_DotProductWithScale(
510 &(audio_history[signal_length - correlation_length - best_index]),
511 &(audio_history[signal_length - correlation_length - best_index]),
512 correlation_length, correlation_scale);
513
514 // Calculate the correlation coefficient between the two portions of the
515 // signal.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700516 int32_t corr_coefficient;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517 if ((energy1 > 0) && (energy2 > 0)) {
518 int energy1_scale = std::max(16 - WebRtcSpl_NormW32(energy1), 0);
519 int energy2_scale = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
520 // Make sure total scaling is even (to simplify scale factor after sqrt).
521 if ((energy1_scale + energy2_scale) & 1) {
522 // If sum is odd, add 1 to make it even.
523 energy1_scale += 1;
524 }
Peter Kasting36b7cc32015-06-11 19:57:18 -0700525 int32_t scaled_energy1 = energy1 >> energy1_scale;
526 int32_t scaled_energy2 = energy2 >> energy2_scale;
527 int16_t sqrt_energy_product = static_cast<int16_t>(
528 WebRtcSpl_SqrtFloor(scaled_energy1 * scaled_energy2));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000529 // Calculate max_correlation / sqrt(energy1 * energy2) in Q14.
530 int cc_shift = 14 - (energy1_scale + energy2_scale) / 2;
531 max_correlation = WEBRTC_SPL_SHIFT_W32(max_correlation, cc_shift);
Yves Gerey665174f2018-06-19 15:03:05 +0200532 corr_coefficient =
533 WebRtcSpl_DivW32W16(max_correlation, sqrt_energy_product);
Peter Kasting36b7cc32015-06-11 19:57:18 -0700534 // Cap at 1.0 in Q14.
535 corr_coefficient = std::min(16384, corr_coefficient);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000536 } else {
537 corr_coefficient = 0;
538 }
539
540 // Extract the two vectors expand_vector0 and expand_vector1 from
541 // |audio_history|.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700542 size_t expansion_length = max_lag_ + overlap_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000543 const int16_t* vector1 = &(audio_history[signal_length - expansion_length]);
544 const int16_t* vector2 = vector1 - distortion_lag;
545 // Normalize the second vector to the same energy as the first.
546 energy1 = WebRtcSpl_DotProductWithScale(vector1, vector1, expansion_length,
547 correlation_scale);
548 energy2 = WebRtcSpl_DotProductWithScale(vector2, vector2, expansion_length,
549 correlation_scale);
550 // Confirm that amplitude ratio sqrt(energy1 / energy2) is within 0.5 - 2.0,
Henrik Lundine84e96e2016-01-12 16:36:13 +0100551 // i.e., energy1 / energy2 is within 0.25 - 4.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000552 int16_t amplitude_ratio;
553 if ((energy1 / 4 < energy2) && (energy1 > energy2 / 4)) {
554 // Energy constraint fulfilled. Use both vectors and scale them
555 // accordingly.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700556 int32_t scaled_energy2 = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
557 int32_t scaled_energy1 = scaled_energy2 - 13;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000558 // Calculate scaled_energy1 / scaled_energy2 in Q13.
Yves Gerey665174f2018-06-19 15:03:05 +0200559 int32_t energy_ratio =
560 WebRtcSpl_DivW32W16(WEBRTC_SPL_SHIFT_W32(energy1, -scaled_energy1),
561 static_cast<int16_t>(energy2 >> scaled_energy2));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000562 // Calculate sqrt ratio in Q13 (sqrt of en1/en2 in Q26).
Peter Kastingdce40cf2015-08-24 14:52:23 -0700563 amplitude_ratio =
564 static_cast<int16_t>(WebRtcSpl_SqrtFloor(energy_ratio << 13));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000565 // Copy the two vectors and give them the same energy.
566 parameters.expand_vector0.Clear();
567 parameters.expand_vector0.PushBack(vector1, expansion_length);
568 parameters.expand_vector1.Clear();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700569 if (parameters.expand_vector1.Size() < expansion_length) {
Yves Gerey665174f2018-06-19 15:03:05 +0200570 parameters.expand_vector1.Extend(expansion_length -
571 parameters.expand_vector1.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000572 }
minyue-webrtc79553cb2016-05-10 19:55:56 +0200573 std::unique_ptr<int16_t[]> temp_1(new int16_t[expansion_length]);
Yves Gerey665174f2018-06-19 15:03:05 +0200574 WebRtcSpl_AffineTransformVector(
575 temp_1.get(), const_cast<int16_t*>(vector2), amplitude_ratio, 4096,
576 13, expansion_length);
minyue-webrtc79553cb2016-05-10 19:55:56 +0200577 parameters.expand_vector1.OverwriteAt(temp_1.get(), expansion_length, 0);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000578 } else {
579 // Energy change constraint not fulfilled. Only use last vector.
580 parameters.expand_vector0.Clear();
581 parameters.expand_vector0.PushBack(vector1, expansion_length);
582 // Copy from expand_vector0 to expand_vector1.
henrik.lundin@webrtc.orgf6ab6f82014-09-04 10:58:43 +0000583 parameters.expand_vector0.CopyTo(&parameters.expand_vector1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000584 // Set the energy_ratio since it is used by muting slope.
585 if ((energy1 / 4 < energy2) || (energy2 == 0)) {
586 amplitude_ratio = 4096; // 0.5 in Q13.
587 } else {
588 amplitude_ratio = 16384; // 2.0 in Q13.
589 }
590 }
591
592 // Set the 3 lag values.
Peter Kastingf045e4d2015-06-10 21:15:38 -0700593 if (distortion_lag == correlation_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000594 expand_lags_[0] = distortion_lag;
595 expand_lags_[1] = distortion_lag;
596 expand_lags_[2] = distortion_lag;
597 } else {
598 // |distortion_lag| and |correlation_lag| are not equal; use different
599 // combinations of the two.
600 // First lag is |distortion_lag| only.
601 expand_lags_[0] = distortion_lag;
602 // Second lag is the average of the two.
603 expand_lags_[1] = (distortion_lag + correlation_lag) / 2;
604 // Third lag is the average again, but rounding towards |correlation_lag|.
Peter Kastingf045e4d2015-06-10 21:15:38 -0700605 if (distortion_lag > correlation_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000606 expand_lags_[2] = (distortion_lag + correlation_lag - 1) / 2;
607 } else {
608 expand_lags_[2] = (distortion_lag + correlation_lag + 1) / 2;
609 }
610 }
611
612 // Calculate the LPC and the gain of the filters.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000613
614 // Calculate kUnvoicedLpcOrder + 1 lags of the auto-correlation function.
Yves Gerey665174f2018-06-19 15:03:05 +0200615 size_t temp_index =
616 signal_length - fs_mult_lpc_analysis_len - kUnvoicedLpcOrder;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000617 // Copy signal to temporary vector to be able to pad with leading zeros.
Yves Gerey665174f2018-06-19 15:03:05 +0200618 int16_t* temp_signal =
619 new int16_t[fs_mult_lpc_analysis_len + kUnvoicedLpcOrder];
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000620 memset(temp_signal, 0,
621 sizeof(int16_t) * (fs_mult_lpc_analysis_len + kUnvoicedLpcOrder));
622 memcpy(&temp_signal[kUnvoicedLpcOrder],
623 &audio_history[temp_index + kUnvoicedLpcOrder],
624 sizeof(int16_t) * fs_mult_lpc_analysis_len);
minyue53ff70f2016-05-02 01:50:30 -0700625 CrossCorrelationWithAutoShift(
626 &temp_signal[kUnvoicedLpcOrder], &temp_signal[kUnvoicedLpcOrder],
627 fs_mult_lpc_analysis_len, kUnvoicedLpcOrder + 1, -1, auto_correlation);
Yves Gerey665174f2018-06-19 15:03:05 +0200628 delete[] temp_signal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000629
630 // Verify that variance is positive.
631 if (auto_correlation[0] > 0) {
632 // Estimate AR filter parameters using Levinson-Durbin algorithm;
633 // kUnvoicedLpcOrder + 1 filter coefficients.
Yves Gerey665174f2018-06-19 15:03:05 +0200634 int16_t stability =
635 WebRtcSpl_LevinsonDurbin(auto_correlation, parameters.ar_filter,
636 reflection_coeff, kUnvoicedLpcOrder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000637
638 // Keep filter parameters only if filter is stable.
639 if (stability != 1) {
640 // Set first coefficient to 4096 (1.0 in Q12).
641 parameters.ar_filter[0] = 4096;
642 // Set remaining |kUnvoicedLpcOrder| coefficients to zero.
643 WebRtcSpl_MemSetW16(parameters.ar_filter + 1, 0, kUnvoicedLpcOrder);
644 }
645 }
646
647 if (channel_ix == 0) {
648 // Extract a noise segment.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700649 size_t noise_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000650 if (distortion_lag < 40) {
651 noise_length = 2 * distortion_lag + 30;
652 } else {
653 noise_length = distortion_lag + 30;
654 }
655 if (noise_length <= RandomVector::kRandomTableSize) {
656 memcpy(random_vector, RandomVector::kRandomTable,
657 sizeof(int16_t) * noise_length);
658 } else {
659 // Only applies to SWB where length could be larger than
660 // |kRandomTableSize|.
661 memcpy(random_vector, RandomVector::kRandomTable,
662 sizeof(int16_t) * RandomVector::kRandomTableSize);
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200663 RTC_DCHECK_LE(noise_length, kMaxSampleRate / 8000 * 120 + 30);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000664 random_vector_->IncreaseSeedIncrement(2);
665 random_vector_->Generate(
666 noise_length - RandomVector::kRandomTableSize,
667 &random_vector[RandomVector::kRandomTableSize]);
668 }
669 }
670
671 // Set up state vector and calculate scale factor for unvoiced filtering.
672 memcpy(parameters.ar_filter_state,
673 &(audio_history[signal_length - kUnvoicedLpcOrder]),
674 sizeof(int16_t) * kUnvoicedLpcOrder);
675 memcpy(unvoiced_vector - kUnvoicedLpcOrder,
676 &(audio_history[signal_length - 128 - kUnvoicedLpcOrder]),
677 sizeof(int16_t) * kUnvoicedLpcOrder);
bjornv@webrtc.orgc14e3572015-01-12 05:50:52 +0000678 WebRtcSpl_FilterMAFastQ12(&audio_history[signal_length - 128],
Yves Gerey665174f2018-06-19 15:03:05 +0200679 unvoiced_vector, parameters.ar_filter,
680 kUnvoicedLpcOrder + 1, 128);
ivocffecbbf2016-12-16 05:51:49 -0800681 const int unvoiced_max_abs = [&] {
682 const int16_t max_abs = WebRtcSpl_MaxAbsValueW16(unvoiced_vector, 128);
683 // Since WebRtcSpl_MaxAbsValueW16 returns 2^15 - 1 when the input contains
684 // -2^15, we have to conservatively bump the return value by 1
685 // if it is 2^15 - 1.
686 return max_abs == WEBRTC_SPL_WORD16_MAX ? max_abs + 1 : max_abs;
687 }();
688 // Pick the smallest n such that 2^n > unvoiced_max_abs; then the maximum
689 // value of the dot product is less than 2^7 * 2^(2*n) = 2^(2*n + 7), so to
690 // prevent overflows we want 2n + 7 <= 31, which means we should shift by
691 // 2n + 7 - 31 bits, if this value is greater than zero.
692 int unvoiced_prescale =
693 std::max(0, 2 * WebRtcSpl_GetSizeInBits(unvoiced_max_abs) - 24);
694
Yves Gerey665174f2018-06-19 15:03:05 +0200695 int32_t unvoiced_energy = WebRtcSpl_DotProductWithScale(
696 unvoiced_vector, unvoiced_vector, 128, unvoiced_prescale);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000697
698 // Normalize |unvoiced_energy| to 28 or 29 bits to preserve sqrt() accuracy.
699 int16_t unvoiced_scale = WebRtcSpl_NormW32(unvoiced_energy) - 3;
700 // Make sure we do an odd number of shifts since we already have 7 shifts
701 // from dividing with 128 earlier. This will make the total scale factor
702 // even, which is suitable for the sqrt.
703 unvoiced_scale += ((unvoiced_scale & 0x1) ^ 0x1);
704 unvoiced_energy = WEBRTC_SPL_SHIFT_W32(unvoiced_energy, unvoiced_scale);
Peter Kastingb7e50542015-06-11 12:55:50 -0700705 int16_t unvoiced_gain =
706 static_cast<int16_t>(WebRtcSpl_SqrtFloor(unvoiced_energy));
Yves Gerey665174f2018-06-19 15:03:05 +0200707 parameters.ar_gain_scale =
708 13 + (unvoiced_scale + 7 - unvoiced_prescale) / 2;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709 parameters.ar_gain = unvoiced_gain;
710
711 // Calculate voice_mix_factor from corr_coefficient.
712 // Let x = corr_coefficient. Then, we compute:
713 // if (x > 0.48)
714 // voice_mix_factor = (-5179 + 19931x - 16422x^2 + 5776x^3) / 4096;
715 // else
716 // voice_mix_factor = 0;
717 if (corr_coefficient > 7875) {
718 int16_t x1, x2, x3;
Peter Kasting36b7cc32015-06-11 19:57:18 -0700719 // |corr_coefficient| is in Q14.
720 x1 = static_cast<int16_t>(corr_coefficient);
Yves Gerey665174f2018-06-19 15:03:05 +0200721 x2 = (x1 * x1) >> 14; // Shift 14 to keep result in Q14.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000722 x3 = (x1 * x2) >> 14;
Yves Gerey665174f2018-06-19 15:03:05 +0200723 static const int kCoefficients[4] = {-5179, 19931, -16422, 5776};
henrik.lundin79dfdad2016-11-15 01:45:53 -0800724 int32_t temp_sum = kCoefficients[0] * 16384;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000725 temp_sum += kCoefficients[1] * x1;
726 temp_sum += kCoefficients[2] * x2;
727 temp_sum += kCoefficients[3] * x3;
Peter Kastingf045e4d2015-06-10 21:15:38 -0700728 parameters.voice_mix_factor =
729 static_cast<int16_t>(std::min(temp_sum / 4096, 16384));
Yves Gerey665174f2018-06-19 15:03:05 +0200730 parameters.voice_mix_factor =
731 std::max(parameters.voice_mix_factor, static_cast<int16_t>(0));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000732 } else {
733 parameters.voice_mix_factor = 0;
734 }
735
736 // Calculate muting slope. Reuse value from earlier scaling of
737 // |expand_vector0| and |expand_vector1|.
738 int16_t slope = amplitude_ratio;
739 if (slope > 12288) {
740 // slope > 1.5.
741 // Calculate (1 - (1 / slope)) / distortion_lag =
742 // (slope - 1) / (distortion_lag * slope).
743 // |slope| is in Q13, so 1 corresponds to 8192. Shift up to Q25 before
744 // the division.
745 // Shift the denominator from Q13 to Q5 before the division. The result of
746 // the division will then be in Q20.
Henrik Lundin9024da82018-05-21 13:41:16 +0200747 int16_t denom =
748 rtc::saturated_cast<int16_t>((distortion_lag * slope) >> 8);
749 int temp_ratio = WebRtcSpl_DivW32W16((slope - 8192) << 12, denom);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 if (slope > 14746) {
751 // slope > 1.8.
752 // Divide by 2, with proper rounding.
753 parameters.mute_slope = (temp_ratio + 1) / 2;
754 } else {
755 // Divide by 8, with proper rounding.
756 parameters.mute_slope = (temp_ratio + 4) / 8;
757 }
758 parameters.onset = true;
759 } else {
760 // Calculate (1 - slope) / distortion_lag.
761 // Shift |slope| by 7 to Q20 before the division. The result is in Q20.
Peter Kastingb7e50542015-06-11 12:55:50 -0700762 parameters.mute_slope = WebRtcSpl_DivW32W16(
henrik.lundin79dfdad2016-11-15 01:45:53 -0800763 (8192 - slope) * 128, static_cast<int16_t>(distortion_lag));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764 if (parameters.voice_mix_factor <= 13107) {
765 // Make sure the mute factor decreases from 1.0 to 0.9 in no more than
766 // 6.25 ms.
767 // mute_slope >= 0.005 / fs_mult in Q20.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700768 parameters.mute_slope = std::max(5243 / fs_mult, parameters.mute_slope);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000769 } else if (slope > 8028) {
770 parameters.mute_slope = 0;
771 }
772 parameters.onset = false;
773 }
774 }
775}
776
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200777Expand::ChannelParameters::ChannelParameters()
778 : mute_factor(16384),
779 ar_gain(0),
780 ar_gain_scale(0),
781 voice_mix_factor(0),
782 current_voice_mix_factor(0),
783 onset(false),
784 mute_slope(0) {
785 memset(ar_filter, 0, sizeof(ar_filter));
786 memset(ar_filter_state, 0, sizeof(ar_filter_state));
787}
788
Peter Kasting728d9032015-06-11 14:31:38 -0700789void Expand::Correlation(const int16_t* input,
790 size_t input_length,
minyue53ff70f2016-05-02 01:50:30 -0700791 int16_t* output) const {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000792 // Set parameters depending on sample rate.
793 const int16_t* filter_coefficients;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700794 size_t num_coefficients;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 int16_t downsampling_factor;
796 if (fs_hz_ == 8000) {
797 num_coefficients = 3;
798 downsampling_factor = 2;
799 filter_coefficients = DspHelper::kDownsample8kHzTbl;
800 } else if (fs_hz_ == 16000) {
801 num_coefficients = 5;
802 downsampling_factor = 4;
803 filter_coefficients = DspHelper::kDownsample16kHzTbl;
804 } else if (fs_hz_ == 32000) {
805 num_coefficients = 7;
806 downsampling_factor = 8;
807 filter_coefficients = DspHelper::kDownsample32kHzTbl;
808 } else { // fs_hz_ == 48000.
809 num_coefficients = 7;
810 downsampling_factor = 12;
811 filter_coefficients = DspHelper::kDownsample48kHzTbl;
812 }
813
814 // Correlate from lag 10 to lag 60 in downsampled domain.
815 // (Corresponds to 20-120 for narrow-band, 40-240 for wide-band, and so on.)
Peter Kastingdce40cf2015-08-24 14:52:23 -0700816 static const size_t kCorrelationStartLag = 10;
817 static const size_t kNumCorrelationLags = 54;
818 static const size_t kCorrelationLength = 60;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000819 // Downsample to 4 kHz sample rate.
Yves Gerey665174f2018-06-19 15:03:05 +0200820 static const size_t kDownsampledLength =
821 kCorrelationStartLag + kNumCorrelationLags + kCorrelationLength;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000822 int16_t downsampled_input[kDownsampledLength];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700823 static const size_t kFilterDelay = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000824 WebRtcSpl_DownsampleFast(
825 input + input_length - kDownsampledLength * downsampling_factor,
826 kDownsampledLength * downsampling_factor, downsampled_input,
827 kDownsampledLength, filter_coefficients, num_coefficients,
828 downsampling_factor, kFilterDelay);
829
830 // Normalize |downsampled_input| to using all 16 bits.
Yves Gerey665174f2018-06-19 15:03:05 +0200831 int16_t max_value =
832 WebRtcSpl_MaxAbsValueW16(downsampled_input, kDownsampledLength);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000833 int16_t norm_shift = 16 - WebRtcSpl_NormW32(max_value);
834 WebRtcSpl_VectorBitShiftW16(downsampled_input, kDownsampledLength,
835 downsampled_input, norm_shift);
836
837 int32_t correlation[kNumCorrelationLags];
minyue53ff70f2016-05-02 01:50:30 -0700838 CrossCorrelationWithAutoShift(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000839 &downsampled_input[kDownsampledLength - kCorrelationLength],
Yves Gerey665174f2018-06-19 15:03:05 +0200840 &downsampled_input[kDownsampledLength - kCorrelationLength -
841 kCorrelationStartLag],
minyue53ff70f2016-05-02 01:50:30 -0700842 kCorrelationLength, kNumCorrelationLags, -1, correlation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000843
844 // Normalize and move data from 32-bit to 16-bit vector.
Yves Gerey665174f2018-06-19 15:03:05 +0200845 int32_t max_correlation =
846 WebRtcSpl_MaxAbsValueW32(correlation, kNumCorrelationLags);
Peter Kastingb7e50542015-06-11 12:55:50 -0700847 int16_t norm_shift2 = static_cast<int16_t>(
848 std::max(18 - WebRtcSpl_NormW32(max_correlation), 0));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000849 WebRtcSpl_VectorBitShiftW32ToW16(output, kNumCorrelationLags, correlation,
850 norm_shift2);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000851}
852
853void Expand::UpdateLagIndex() {
854 current_lag_index_ = current_lag_index_ + lag_index_direction_;
855 // Change direction if needed.
856 if (current_lag_index_ <= 0) {
857 lag_index_direction_ = 1;
858 }
859 if (current_lag_index_ >= kNumLags - 1) {
860 lag_index_direction_ = -1;
861 }
862}
863
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000864Expand* ExpandFactory::Create(BackgroundNoise* background_noise,
865 SyncBuffer* sync_buffer,
866 RandomVector* random_vector,
Henrik Lundinbef77e22015-08-18 14:58:09 +0200867 StatisticsCalculator* statistics,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000868 int fs,
869 size_t num_channels) const {
Henrik Lundinbef77e22015-08-18 14:58:09 +0200870 return new Expand(background_noise, sync_buffer, random_vector, statistics,
871 fs, num_channels);
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000872}
873
Peter Kastingb7e50542015-06-11 12:55:50 -0700874void Expand::GenerateRandomVector(int16_t seed_increment,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000875 size_t length,
876 int16_t* random_vector) {
877 // TODO(turajs): According to hlundin The loop should not be needed. Should be
878 // just as good to generate all of the vector in one call.
879 size_t samples_generated = 0;
880 const size_t kMaxRandSamples = RandomVector::kRandomTableSize;
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000881 while (samples_generated < length) {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000882 size_t rand_length = std::min(length - samples_generated, kMaxRandSamples);
883 random_vector_->IncreaseSeedIncrement(seed_increment);
884 random_vector_->Generate(rand_length, &random_vector[samples_generated]);
885 samples_generated += rand_length;
886 }
887}
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000888
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000889} // namespace webrtc