blob: 94f6a8fdfebf4e274b94365e0b44f455ff43c39b [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
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/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
turaj@webrtc.org7126b382013-07-31 16:05:09 +000017#include <limits> // numeric_limits<T>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
Tommid44c0772016-03-11 17:12:32 -080019#include "webrtc/base/safe_conversions.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000020#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000021#include "webrtc/modules/audio_coding/neteq/background_noise.h"
minyue3d09dfd2016-04-27 15:06:10 -070022#include "webrtc/modules/audio_coding/neteq/cross_correlation.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000023#include "webrtc/modules/audio_coding/neteq/dsp_helper.h"
24#include "webrtc/modules/audio_coding/neteq/random_vector.h"
Henrik Lundinbef77e22015-08-18 14:58:09 +020025#include "webrtc/modules/audio_coding/neteq/statistics_calculator.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000026#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000027
28namespace webrtc {
29
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020030Expand::Expand(BackgroundNoise* background_noise,
31 SyncBuffer* sync_buffer,
32 RandomVector* random_vector,
Henrik Lundinbef77e22015-08-18 14:58:09 +020033 StatisticsCalculator* statistics,
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020034 int fs,
35 size_t num_channels)
36 : random_vector_(random_vector),
37 sync_buffer_(sync_buffer),
38 first_expand_(true),
39 fs_hz_(fs),
40 num_channels_(num_channels),
41 consecutive_expands_(0),
42 background_noise_(background_noise),
Henrik Lundinbef77e22015-08-18 14:58:09 +020043 statistics_(statistics),
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020044 overlap_length_(5 * fs / 8000),
45 lag_index_direction_(0),
46 current_lag_index_(0),
47 stop_muting_(false),
Henrik Lundinbef77e22015-08-18 14:58:09 +020048 expand_duration_samples_(0),
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020049 channel_parameters_(new ChannelParameters[num_channels_]) {
50 assert(fs == 8000 || fs == 16000 || fs == 32000 || fs == 48000);
Peter Kastingdce40cf2015-08-24 14:52:23 -070051 assert(fs <= static_cast<int>(kMaxSampleRate)); // Should not be possible.
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020052 assert(num_channels_ > 0);
53 memset(expand_lags_, 0, sizeof(expand_lags_));
54 Reset();
55}
56
57Expand::~Expand() = default;
58
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000059void Expand::Reset() {
60 first_expand_ = true;
61 consecutive_expands_ = 0;
62 max_lag_ = 0;
63 for (size_t ix = 0; ix < num_channels_; ++ix) {
64 channel_parameters_[ix].expand_vector0.Clear();
65 channel_parameters_[ix].expand_vector1.Clear();
66 }
67}
68
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +000069int Expand::Process(AudioMultiVector* output) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000070 int16_t random_vector[kMaxSampleRate / 8000 * 120 + 30];
71 int16_t scaled_random_vector[kMaxSampleRate / 8000 * 125];
72 static const int kTempDataSize = 3600;
73 int16_t temp_data[kTempDataSize]; // TODO(hlundin) Remove this.
74 int16_t* voiced_vector_storage = temp_data;
75 int16_t* voiced_vector = &voiced_vector_storage[overlap_length_];
Peter Kastingdce40cf2015-08-24 14:52:23 -070076 static const size_t kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000077 int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
78 int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
79 int16_t* noise_vector = unvoiced_array_memory + kNoiseLpcOrder;
80
81 int fs_mult = fs_hz_ / 8000;
82
83 if (first_expand_) {
84 // Perform initial setup if this is the first expansion since last reset.
85 AnalyzeSignal(random_vector);
86 first_expand_ = false;
Henrik Lundinbef77e22015-08-18 14:58:09 +020087 expand_duration_samples_ = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000088 } else {
89 // This is not the first expansion, parameters are already estimated.
90 // Extract a noise segment.
Peter Kastingdce40cf2015-08-24 14:52:23 -070091 size_t rand_length = max_lag_;
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000092 // This only applies to SWB where length could be larger than 256.
93 assert(rand_length <= kMaxSampleRate / 8000 * 120 + 30);
94 GenerateRandomVector(2, rand_length, random_vector);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 }
96
97
98 // Generate signal.
99 UpdateLagIndex();
100
101 // Voiced part.
102 // Generate a weighted vector with the current lag.
103 size_t expansion_vector_length = max_lag_ + overlap_length_;
104 size_t current_lag = expand_lags_[current_lag_index_];
105 // Copy lag+overlap data.
106 size_t expansion_vector_position = expansion_vector_length - current_lag -
107 overlap_length_;
108 size_t temp_length = current_lag + overlap_length_;
109 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
110 ChannelParameters& parameters = channel_parameters_[channel_ix];
111 if (current_lag_index_ == 0) {
112 // Use only expand_vector0.
113 assert(expansion_vector_position + temp_length <=
114 parameters.expand_vector0.Size());
115 memcpy(voiced_vector_storage,
116 &parameters.expand_vector0[expansion_vector_position],
117 sizeof(int16_t) * temp_length);
118 } else if (current_lag_index_ == 1) {
119 // Mix 3/4 of expand_vector0 with 1/4 of expand_vector1.
120 WebRtcSpl_ScaleAndAddVectorsWithRound(
121 &parameters.expand_vector0[expansion_vector_position], 3,
122 &parameters.expand_vector1[expansion_vector_position], 1, 2,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700123 voiced_vector_storage, temp_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 } else if (current_lag_index_ == 2) {
125 // Mix 1/2 of expand_vector0 with 1/2 of expand_vector1.
126 assert(expansion_vector_position + temp_length <=
127 parameters.expand_vector0.Size());
128 assert(expansion_vector_position + temp_length <=
129 parameters.expand_vector1.Size());
130 WebRtcSpl_ScaleAndAddVectorsWithRound(
131 &parameters.expand_vector0[expansion_vector_position], 1,
132 &parameters.expand_vector1[expansion_vector_position], 1, 1,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700133 voiced_vector_storage, temp_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000134 }
135
136 // Get tapering window parameters. Values are in Q15.
137 int16_t muting_window, muting_window_increment;
138 int16_t unmuting_window, unmuting_window_increment;
139 if (fs_hz_ == 8000) {
140 muting_window = DspHelper::kMuteFactorStart8kHz;
141 muting_window_increment = DspHelper::kMuteFactorIncrement8kHz;
142 unmuting_window = DspHelper::kUnmuteFactorStart8kHz;
143 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement8kHz;
144 } else if (fs_hz_ == 16000) {
145 muting_window = DspHelper::kMuteFactorStart16kHz;
146 muting_window_increment = DspHelper::kMuteFactorIncrement16kHz;
147 unmuting_window = DspHelper::kUnmuteFactorStart16kHz;
148 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement16kHz;
149 } else if (fs_hz_ == 32000) {
150 muting_window = DspHelper::kMuteFactorStart32kHz;
151 muting_window_increment = DspHelper::kMuteFactorIncrement32kHz;
152 unmuting_window = DspHelper::kUnmuteFactorStart32kHz;
153 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement32kHz;
154 } else { // fs_ == 48000
155 muting_window = DspHelper::kMuteFactorStart48kHz;
156 muting_window_increment = DspHelper::kMuteFactorIncrement48kHz;
157 unmuting_window = DspHelper::kUnmuteFactorStart48kHz;
158 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement48kHz;
159 }
160
161 // Smooth the expanded if it has not been muted to a low amplitude and
162 // |current_voice_mix_factor| is larger than 0.5.
163 if ((parameters.mute_factor > 819) &&
164 (parameters.current_voice_mix_factor > 8192)) {
165 size_t start_ix = sync_buffer_->Size() - overlap_length_;
166 for (size_t i = 0; i < overlap_length_; i++) {
167 // Do overlap add between new vector and overlap.
168 (*sync_buffer_)[channel_ix][start_ix + i] =
169 (((*sync_buffer_)[channel_ix][start_ix + i] * muting_window) +
170 (((parameters.mute_factor * voiced_vector_storage[i]) >> 14) *
171 unmuting_window) + 16384) >> 15;
172 muting_window += muting_window_increment;
173 unmuting_window += unmuting_window_increment;
174 }
175 } else if (parameters.mute_factor == 0) {
176 // The expanded signal will consist of only comfort noise if
177 // mute_factor = 0. Set the output length to 15 ms for best noise
178 // production.
179 // TODO(hlundin): This has been disabled since the length of
180 // parameters.expand_vector0 and parameters.expand_vector1 no longer
181 // match with expand_lags_, causing invalid reads and writes. Is it a good
182 // idea to enable this again, and solve the vector size problem?
183// max_lag_ = fs_mult * 120;
184// expand_lags_[0] = fs_mult * 120;
185// expand_lags_[1] = fs_mult * 120;
186// expand_lags_[2] = fs_mult * 120;
187 }
188
189 // Unvoiced part.
190 // Filter |scaled_random_vector| through |ar_filter_|.
191 memcpy(unvoiced_vector - kUnvoicedLpcOrder, parameters.ar_filter_state,
192 sizeof(int16_t) * kUnvoicedLpcOrder);
193 int32_t add_constant = 0;
194 if (parameters.ar_gain_scale > 0) {
195 add_constant = 1 << (parameters.ar_gain_scale - 1);
196 }
197 WebRtcSpl_AffineTransformVector(scaled_random_vector, random_vector,
198 parameters.ar_gain, add_constant,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000199 parameters.ar_gain_scale,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700200 current_lag);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000201 WebRtcSpl_FilterARFastQ12(scaled_random_vector, unvoiced_vector,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000202 parameters.ar_filter, kUnvoicedLpcOrder + 1,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700203 current_lag);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000204 memcpy(parameters.ar_filter_state,
205 &(unvoiced_vector[current_lag - kUnvoicedLpcOrder]),
206 sizeof(int16_t) * kUnvoicedLpcOrder);
207
208 // Combine voiced and unvoiced contributions.
209
210 // Set a suitable cross-fading slope.
211 // For lag =
212 // <= 31 * fs_mult => go from 1 to 0 in about 8 ms;
213 // (>= 31 .. <= 63) * fs_mult => go from 1 to 0 in about 16 ms;
214 // >= 64 * fs_mult => go from 1 to 0 in about 32 ms.
215 // temp_shift = getbits(max_lag_) - 5.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700216 int temp_shift =
217 (31 - WebRtcSpl_NormW32(rtc::checked_cast<int32_t>(max_lag_))) - 5;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000218 int16_t mix_factor_increment = 256 >> temp_shift;
219 if (stop_muting_) {
220 mix_factor_increment = 0;
221 }
222
223 // Create combined signal by shifting in more and more of unvoiced part.
224 temp_shift = 8 - temp_shift; // = getbits(mix_factor_increment).
Peter Kasting728d9032015-06-11 14:31:38 -0700225 size_t temp_length = (parameters.current_voice_mix_factor -
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000226 parameters.voice_mix_factor) >> temp_shift;
Peter Kasting728d9032015-06-11 14:31:38 -0700227 temp_length = std::min(temp_length, current_lag);
228 DspHelper::CrossFade(voiced_vector, unvoiced_vector, temp_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000229 &parameters.current_voice_mix_factor,
230 mix_factor_increment, temp_data);
231
232 // End of cross-fading period was reached before end of expanded signal
233 // path. Mix the rest with a fixed mixing factor.
Peter Kasting728d9032015-06-11 14:31:38 -0700234 if (temp_length < current_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000235 if (mix_factor_increment != 0) {
236 parameters.current_voice_mix_factor = parameters.voice_mix_factor;
237 }
Peter Kastingb7e50542015-06-11 12:55:50 -0700238 int16_t temp_scale = 16384 - parameters.current_voice_mix_factor;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000239 WebRtcSpl_ScaleAndAddVectorsWithRound(
Peter Kasting728d9032015-06-11 14:31:38 -0700240 voiced_vector + temp_length, parameters.current_voice_mix_factor,
241 unvoiced_vector + temp_length, temp_scale, 14,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700242 temp_data + temp_length, current_lag - temp_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000243 }
244
245 // Select muting slope depending on how many consecutive expands we have
246 // done.
247 if (consecutive_expands_ == 3) {
248 // Let the mute factor decrease from 1.0 to 0.95 in 6.25 ms.
249 // mute_slope = 0.0010 / fs_mult in Q20.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700250 parameters.mute_slope = std::max(parameters.mute_slope, 1049 / fs_mult);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000251 }
252 if (consecutive_expands_ == 7) {
253 // Let the mute factor decrease from 1.0 to 0.90 in 6.25 ms.
254 // mute_slope = 0.0020 / fs_mult in Q20.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700255 parameters.mute_slope = std::max(parameters.mute_slope, 2097 / fs_mult);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000256 }
257
258 // Mute segment according to slope value.
259 if ((consecutive_expands_ != 0) || !parameters.onset) {
260 // Mute to the previous level, then continue with the muting.
261 WebRtcSpl_AffineTransformVector(temp_data, temp_data,
262 parameters.mute_factor, 8192,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700263 14, current_lag);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000264
265 if (!stop_muting_) {
266 DspHelper::MuteSignal(temp_data, parameters.mute_slope, current_lag);
267
268 // Shift by 6 to go from Q20 to Q14.
269 // TODO(hlundin): Adding 8192 before shifting 6 steps seems wrong.
270 // Legacy.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000271 int16_t gain = static_cast<int16_t>(16384 -
272 (((current_lag * parameters.mute_slope) + 8192) >> 6));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000273 gain = ((gain * parameters.mute_factor) + 8192) >> 14;
274
275 // Guard against getting stuck with very small (but sometimes audible)
276 // gain.
277 if ((consecutive_expands_ > 3) && (gain >= parameters.mute_factor)) {
278 parameters.mute_factor = 0;
279 } else {
280 parameters.mute_factor = gain;
281 }
282 }
283 }
284
285 // Background noise part.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000286 GenerateBackgroundNoise(random_vector,
287 channel_ix,
288 channel_parameters_[channel_ix].mute_slope,
289 TooManyExpands(),
290 current_lag,
291 unvoiced_array_memory);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000292
293 // Add background noise to the combined voiced-unvoiced signal.
294 for (size_t i = 0; i < current_lag; i++) {
295 temp_data[i] = temp_data[i] + noise_vector[i];
296 }
297 if (channel_ix == 0) {
298 output->AssertSize(current_lag);
299 } else {
300 assert(output->Size() == current_lag);
301 }
302 memcpy(&(*output)[channel_ix][0], temp_data,
303 sizeof(temp_data[0]) * current_lag);
304 }
305
306 // Increase call number and cap it.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000307 consecutive_expands_ = consecutive_expands_ >= kMaxConsecutiveExpands ?
308 kMaxConsecutiveExpands : consecutive_expands_ + 1;
Henrik Lundinbef77e22015-08-18 14:58:09 +0200309 expand_duration_samples_ += output->Size();
310 // Clamp the duration counter at 2 seconds.
311 expand_duration_samples_ =
312 std::min(expand_duration_samples_, rtc::checked_cast<size_t>(fs_hz_ * 2));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000313 return 0;
314}
315
316void Expand::SetParametersForNormalAfterExpand() {
317 current_lag_index_ = 0;
318 lag_index_direction_ = 0;
319 stop_muting_ = true; // Do not mute signal any more.
Henrik Lundinbef77e22015-08-18 14:58:09 +0200320 statistics_->LogDelayedPacketOutageEvent(
321 rtc::checked_cast<int>(expand_duration_samples_) / (fs_hz_ / 1000));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322}
323
324void Expand::SetParametersForMergeAfterExpand() {
325 current_lag_index_ = -1; /* out of the 3 possible ones */
326 lag_index_direction_ = 1; /* make sure we get the "optimal" lag */
327 stop_muting_ = true;
328}
329
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200330size_t Expand::overlap_length() const {
331 return overlap_length_;
332}
333
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000334void Expand::InitializeForAnExpandPeriod() {
335 lag_index_direction_ = 1;
336 current_lag_index_ = -1;
337 stop_muting_ = false;
338 random_vector_->set_seed_increment(1);
339 consecutive_expands_ = 0;
340 for (size_t ix = 0; ix < num_channels_; ++ix) {
341 channel_parameters_[ix].current_voice_mix_factor = 16384; // 1.0 in Q14.
342 channel_parameters_[ix].mute_factor = 16384; // 1.0 in Q14.
343 // Start with 0 gain for background noise.
344 background_noise_->SetMuteFactor(ix, 0);
345 }
346}
347
348bool Expand::TooManyExpands() {
349 return consecutive_expands_ >= kMaxConsecutiveExpands;
350}
351
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000352void Expand::AnalyzeSignal(int16_t* random_vector) {
353 int32_t auto_correlation[kUnvoicedLpcOrder + 1];
354 int16_t reflection_coeff[kUnvoicedLpcOrder];
355 int16_t correlation_vector[kMaxSampleRate / 8000 * 102];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700356 size_t best_correlation_index[kNumCorrelationCandidates];
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357 int16_t best_correlation[kNumCorrelationCandidates];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700358 size_t best_distortion_index[kNumCorrelationCandidates];
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 int16_t best_distortion[kNumCorrelationCandidates];
360 int32_t correlation_vector2[(99 * kMaxSampleRate / 8000) + 1];
361 int32_t best_distortion_w32[kNumCorrelationCandidates];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700362 static const size_t kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000363 int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
364 int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
365
366 int fs_mult = fs_hz_ / 8000;
367
368 // Pre-calculate common multiplications with fs_mult.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700369 size_t fs_mult_4 = static_cast<size_t>(fs_mult * 4);
370 size_t fs_mult_20 = static_cast<size_t>(fs_mult * 20);
371 size_t fs_mult_120 = static_cast<size_t>(fs_mult * 120);
372 size_t fs_mult_dist_len = fs_mult * kDistortionLength;
373 size_t fs_mult_lpc_analysis_len = fs_mult * kLpcAnalysisLength;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374
Peter Kastingdce40cf2015-08-24 14:52:23 -0700375 const size_t signal_length = static_cast<size_t>(256 * fs_mult);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376 const int16_t* audio_history =
377 &(*sync_buffer_)[0][sync_buffer_->Size() - signal_length];
378
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000379 // Initialize.
380 InitializeForAnExpandPeriod();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000381
382 // Calculate correlation in downsampled domain (4 kHz sample rate).
Peter Kastingdce40cf2015-08-24 14:52:23 -0700383 size_t correlation_length = 51; // TODO(hlundin): Legacy bit-exactness.
turaj@webrtc.org58cd3162013-10-31 15:15:55 +0000384 // If it is decided to break bit-exactness |correlation_length| should be
385 // initialized to the return value of Correlation().
minyue3d09dfd2016-04-27 15:06:10 -0700386 Correlation(audio_history, signal_length, correlation_vector);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387
388 // Find peaks in correlation vector.
389 DspHelper::PeakDetection(correlation_vector, correlation_length,
390 kNumCorrelationCandidates, fs_mult,
391 best_correlation_index, best_correlation);
392
393 // Adjust peak locations; cross-correlation lags start at 2.5 ms
394 // (20 * fs_mult samples).
395 best_correlation_index[0] += fs_mult_20;
396 best_correlation_index[1] += fs_mult_20;
397 best_correlation_index[2] += fs_mult_20;
398
399 // Calculate distortion around the |kNumCorrelationCandidates| best lags.
400 int distortion_scale = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700401 for (size_t i = 0; i < kNumCorrelationCandidates; i++) {
402 size_t min_index = std::max(fs_mult_20,
403 best_correlation_index[i] - fs_mult_4);
404 size_t max_index = std::min(fs_mult_120 - 1,
405 best_correlation_index[i] + fs_mult_4);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000406 best_distortion_index[i] = DspHelper::MinDistortion(
407 &(audio_history[signal_length - fs_mult_dist_len]), min_index,
408 max_index, fs_mult_dist_len, &best_distortion_w32[i]);
409 distortion_scale = std::max(16 - WebRtcSpl_NormW32(best_distortion_w32[i]),
410 distortion_scale);
411 }
412 // Shift the distortion values to fit in 16 bits.
413 WebRtcSpl_VectorBitShiftW32ToW16(best_distortion, kNumCorrelationCandidates,
414 best_distortion_w32, distortion_scale);
415
416 // Find the maximizing index |i| of the cost function
417 // f[i] = best_correlation[i] / best_distortion[i].
turaj@webrtc.org58cd3162013-10-31 15:15:55 +0000418 int32_t best_ratio = std::numeric_limits<int32_t>::min();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700419 size_t best_index = std::numeric_limits<size_t>::max();
420 for (size_t i = 0; i < kNumCorrelationCandidates; ++i) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000421 int32_t ratio;
422 if (best_distortion[i] > 0) {
423 ratio = (best_correlation[i] << 16) / best_distortion[i];
turaj@webrtc.org7126b382013-07-31 16:05:09 +0000424 } else if (best_correlation[i] == 0) {
425 ratio = 0; // No correlation set result to zero.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000426 } else {
turaj@webrtc.org7126b382013-07-31 16:05:09 +0000427 ratio = std::numeric_limits<int32_t>::max(); // Denominator is zero.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428 }
429 if (ratio > best_ratio) {
430 best_index = i;
431 best_ratio = ratio;
432 }
433 }
434
Peter Kastingdce40cf2015-08-24 14:52:23 -0700435 size_t distortion_lag = best_distortion_index[best_index];
436 size_t correlation_lag = best_correlation_index[best_index];
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000437 max_lag_ = std::max(distortion_lag, correlation_lag);
438
439 // Calculate the exact best correlation in the range between
440 // |correlation_lag| and |distortion_lag|.
Peter Kasting728d9032015-06-11 14:31:38 -0700441 correlation_length =
Peter Kastingdce40cf2015-08-24 14:52:23 -0700442 std::max(std::min(distortion_lag + 10, fs_mult_120),
443 static_cast<size_t>(60 * fs_mult));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000444
Peter Kastingdce40cf2015-08-24 14:52:23 -0700445 size_t start_index = std::min(distortion_lag, correlation_lag);
446 size_t correlation_lags = static_cast<size_t>(
447 WEBRTC_SPL_ABS_W16((distortion_lag-correlation_lag)) + 1);
448 assert(correlation_lags <= static_cast<size_t>(99 * fs_mult + 1));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000449
450 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
451 ChannelParameters& parameters = channel_parameters_[channel_ix];
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000452
453 // Calculate the correlation, store in |correlation_vector2|.
minyue3d09dfd2016-04-27 15:06:10 -0700454 int correlation_scale = CrossCorrelationWithAutoShift(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000455 &(audio_history[signal_length - correlation_length]),
456 &(audio_history[signal_length - correlation_length - start_index]),
minyue3d09dfd2016-04-27 15:06:10 -0700457 correlation_length, correlation_lags, -1, correlation_vector2);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000458
459 // Find maximizing index.
Peter Kasting1380e262015-08-28 17:31:03 -0700460 best_index = WebRtcSpl_MaxIndexW32(correlation_vector2, correlation_lags);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000461 int32_t max_correlation = correlation_vector2[best_index];
462 // Compensate index with start offset.
463 best_index = best_index + start_index;
464
465 // Calculate energies.
466 int32_t energy1 = WebRtcSpl_DotProductWithScale(
467 &(audio_history[signal_length - correlation_length]),
468 &(audio_history[signal_length - correlation_length]),
469 correlation_length, correlation_scale);
470 int32_t energy2 = WebRtcSpl_DotProductWithScale(
471 &(audio_history[signal_length - correlation_length - best_index]),
472 &(audio_history[signal_length - correlation_length - best_index]),
473 correlation_length, correlation_scale);
474
475 // Calculate the correlation coefficient between the two portions of the
476 // signal.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700477 int32_t corr_coefficient;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000478 if ((energy1 > 0) && (energy2 > 0)) {
479 int energy1_scale = std::max(16 - WebRtcSpl_NormW32(energy1), 0);
480 int energy2_scale = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
481 // Make sure total scaling is even (to simplify scale factor after sqrt).
482 if ((energy1_scale + energy2_scale) & 1) {
483 // If sum is odd, add 1 to make it even.
484 energy1_scale += 1;
485 }
Peter Kasting36b7cc32015-06-11 19:57:18 -0700486 int32_t scaled_energy1 = energy1 >> energy1_scale;
487 int32_t scaled_energy2 = energy2 >> energy2_scale;
488 int16_t sqrt_energy_product = static_cast<int16_t>(
489 WebRtcSpl_SqrtFloor(scaled_energy1 * scaled_energy2));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490 // Calculate max_correlation / sqrt(energy1 * energy2) in Q14.
491 int cc_shift = 14 - (energy1_scale + energy2_scale) / 2;
492 max_correlation = WEBRTC_SPL_SHIFT_W32(max_correlation, cc_shift);
493 corr_coefficient = WebRtcSpl_DivW32W16(max_correlation,
494 sqrt_energy_product);
Peter Kasting36b7cc32015-06-11 19:57:18 -0700495 // Cap at 1.0 in Q14.
496 corr_coefficient = std::min(16384, corr_coefficient);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000497 } else {
498 corr_coefficient = 0;
499 }
500
501 // Extract the two vectors expand_vector0 and expand_vector1 from
502 // |audio_history|.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700503 size_t expansion_length = max_lag_ + overlap_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000504 const int16_t* vector1 = &(audio_history[signal_length - expansion_length]);
505 const int16_t* vector2 = vector1 - distortion_lag;
506 // Normalize the second vector to the same energy as the first.
507 energy1 = WebRtcSpl_DotProductWithScale(vector1, vector1, expansion_length,
508 correlation_scale);
509 energy2 = WebRtcSpl_DotProductWithScale(vector2, vector2, expansion_length,
510 correlation_scale);
511 // Confirm that amplitude ratio sqrt(energy1 / energy2) is within 0.5 - 2.0,
Henrik Lundine84e96e2016-01-12 16:36:13 +0100512 // i.e., energy1 / energy2 is within 0.25 - 4.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000513 int16_t amplitude_ratio;
514 if ((energy1 / 4 < energy2) && (energy1 > energy2 / 4)) {
515 // Energy constraint fulfilled. Use both vectors and scale them
516 // accordingly.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700517 int32_t scaled_energy2 = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
518 int32_t scaled_energy1 = scaled_energy2 - 13;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000519 // Calculate scaled_energy1 / scaled_energy2 in Q13.
520 int32_t energy_ratio = WebRtcSpl_DivW32W16(
521 WEBRTC_SPL_SHIFT_W32(energy1, -scaled_energy1),
Peter Kastingdce40cf2015-08-24 14:52:23 -0700522 static_cast<int16_t>(energy2 >> scaled_energy2));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000523 // Calculate sqrt ratio in Q13 (sqrt of en1/en2 in Q26).
Peter Kastingdce40cf2015-08-24 14:52:23 -0700524 amplitude_ratio =
525 static_cast<int16_t>(WebRtcSpl_SqrtFloor(energy_ratio << 13));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000526 // Copy the two vectors and give them the same energy.
527 parameters.expand_vector0.Clear();
528 parameters.expand_vector0.PushBack(vector1, expansion_length);
529 parameters.expand_vector1.Clear();
Peter Kastingdce40cf2015-08-24 14:52:23 -0700530 if (parameters.expand_vector1.Size() < expansion_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000531 parameters.expand_vector1.Extend(
532 expansion_length - parameters.expand_vector1.Size());
533 }
534 WebRtcSpl_AffineTransformVector(&parameters.expand_vector1[0],
535 const_cast<int16_t*>(vector2),
536 amplitude_ratio,
537 4096,
538 13,
539 expansion_length);
540 } else {
541 // Energy change constraint not fulfilled. Only use last vector.
542 parameters.expand_vector0.Clear();
543 parameters.expand_vector0.PushBack(vector1, expansion_length);
544 // Copy from expand_vector0 to expand_vector1.
henrik.lundin@webrtc.orgf6ab6f82014-09-04 10:58:43 +0000545 parameters.expand_vector0.CopyTo(&parameters.expand_vector1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000546 // Set the energy_ratio since it is used by muting slope.
547 if ((energy1 / 4 < energy2) || (energy2 == 0)) {
548 amplitude_ratio = 4096; // 0.5 in Q13.
549 } else {
550 amplitude_ratio = 16384; // 2.0 in Q13.
551 }
552 }
553
554 // Set the 3 lag values.
Peter Kastingf045e4d2015-06-10 21:15:38 -0700555 if (distortion_lag == correlation_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 expand_lags_[0] = distortion_lag;
557 expand_lags_[1] = distortion_lag;
558 expand_lags_[2] = distortion_lag;
559 } else {
560 // |distortion_lag| and |correlation_lag| are not equal; use different
561 // combinations of the two.
562 // First lag is |distortion_lag| only.
563 expand_lags_[0] = distortion_lag;
564 // Second lag is the average of the two.
565 expand_lags_[1] = (distortion_lag + correlation_lag) / 2;
566 // Third lag is the average again, but rounding towards |correlation_lag|.
Peter Kastingf045e4d2015-06-10 21:15:38 -0700567 if (distortion_lag > correlation_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568 expand_lags_[2] = (distortion_lag + correlation_lag - 1) / 2;
569 } else {
570 expand_lags_[2] = (distortion_lag + correlation_lag + 1) / 2;
571 }
572 }
573
574 // Calculate the LPC and the gain of the filters.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000575
576 // Calculate kUnvoicedLpcOrder + 1 lags of the auto-correlation function.
577 size_t temp_index = signal_length - fs_mult_lpc_analysis_len -
578 kUnvoicedLpcOrder;
579 // Copy signal to temporary vector to be able to pad with leading zeros.
580 int16_t* temp_signal = new int16_t[fs_mult_lpc_analysis_len
581 + kUnvoicedLpcOrder];
582 memset(temp_signal, 0,
583 sizeof(int16_t) * (fs_mult_lpc_analysis_len + kUnvoicedLpcOrder));
584 memcpy(&temp_signal[kUnvoicedLpcOrder],
585 &audio_history[temp_index + kUnvoicedLpcOrder],
586 sizeof(int16_t) * fs_mult_lpc_analysis_len);
minyue3d09dfd2016-04-27 15:06:10 -0700587 correlation_scale = CrossCorrelationWithAutoShift(
588 &temp_signal[kUnvoicedLpcOrder], &temp_signal[kUnvoicedLpcOrder],
589 fs_mult_lpc_analysis_len, kUnvoicedLpcOrder + 1, -1, auto_correlation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000590 delete [] temp_signal;
591
592 // Verify that variance is positive.
593 if (auto_correlation[0] > 0) {
594 // Estimate AR filter parameters using Levinson-Durbin algorithm;
595 // kUnvoicedLpcOrder + 1 filter coefficients.
596 int16_t stability = WebRtcSpl_LevinsonDurbin(auto_correlation,
597 parameters.ar_filter,
598 reflection_coeff,
599 kUnvoicedLpcOrder);
600
601 // Keep filter parameters only if filter is stable.
602 if (stability != 1) {
603 // Set first coefficient to 4096 (1.0 in Q12).
604 parameters.ar_filter[0] = 4096;
605 // Set remaining |kUnvoicedLpcOrder| coefficients to zero.
606 WebRtcSpl_MemSetW16(parameters.ar_filter + 1, 0, kUnvoicedLpcOrder);
607 }
608 }
609
610 if (channel_ix == 0) {
611 // Extract a noise segment.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700612 size_t noise_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000613 if (distortion_lag < 40) {
614 noise_length = 2 * distortion_lag + 30;
615 } else {
616 noise_length = distortion_lag + 30;
617 }
618 if (noise_length <= RandomVector::kRandomTableSize) {
619 memcpy(random_vector, RandomVector::kRandomTable,
620 sizeof(int16_t) * noise_length);
621 } else {
622 // Only applies to SWB where length could be larger than
623 // |kRandomTableSize|.
624 memcpy(random_vector, RandomVector::kRandomTable,
625 sizeof(int16_t) * RandomVector::kRandomTableSize);
626 assert(noise_length <= kMaxSampleRate / 8000 * 120 + 30);
627 random_vector_->IncreaseSeedIncrement(2);
628 random_vector_->Generate(
629 noise_length - RandomVector::kRandomTableSize,
630 &random_vector[RandomVector::kRandomTableSize]);
631 }
632 }
633
634 // Set up state vector and calculate scale factor for unvoiced filtering.
635 memcpy(parameters.ar_filter_state,
636 &(audio_history[signal_length - kUnvoicedLpcOrder]),
637 sizeof(int16_t) * kUnvoicedLpcOrder);
638 memcpy(unvoiced_vector - kUnvoicedLpcOrder,
639 &(audio_history[signal_length - 128 - kUnvoicedLpcOrder]),
640 sizeof(int16_t) * kUnvoicedLpcOrder);
bjornv@webrtc.orgc14e3572015-01-12 05:50:52 +0000641 WebRtcSpl_FilterMAFastQ12(&audio_history[signal_length - 128],
642 unvoiced_vector,
643 parameters.ar_filter,
644 kUnvoicedLpcOrder + 1,
645 128);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000646 int16_t unvoiced_prescale;
647 if (WebRtcSpl_MaxAbsValueW16(unvoiced_vector, 128) > 4000) {
648 unvoiced_prescale = 4;
649 } else {
650 unvoiced_prescale = 0;
651 }
652 int32_t unvoiced_energy = WebRtcSpl_DotProductWithScale(unvoiced_vector,
653 unvoiced_vector,
654 128,
655 unvoiced_prescale);
656
657 // Normalize |unvoiced_energy| to 28 or 29 bits to preserve sqrt() accuracy.
658 int16_t unvoiced_scale = WebRtcSpl_NormW32(unvoiced_energy) - 3;
659 // Make sure we do an odd number of shifts since we already have 7 shifts
660 // from dividing with 128 earlier. This will make the total scale factor
661 // even, which is suitable for the sqrt.
662 unvoiced_scale += ((unvoiced_scale & 0x1) ^ 0x1);
663 unvoiced_energy = WEBRTC_SPL_SHIFT_W32(unvoiced_energy, unvoiced_scale);
Peter Kastingb7e50542015-06-11 12:55:50 -0700664 int16_t unvoiced_gain =
665 static_cast<int16_t>(WebRtcSpl_SqrtFloor(unvoiced_energy));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000666 parameters.ar_gain_scale = 13
667 + (unvoiced_scale + 7 - unvoiced_prescale) / 2;
668 parameters.ar_gain = unvoiced_gain;
669
670 // Calculate voice_mix_factor from corr_coefficient.
671 // Let x = corr_coefficient. Then, we compute:
672 // if (x > 0.48)
673 // voice_mix_factor = (-5179 + 19931x - 16422x^2 + 5776x^3) / 4096;
674 // else
675 // voice_mix_factor = 0;
676 if (corr_coefficient > 7875) {
677 int16_t x1, x2, x3;
Peter Kasting36b7cc32015-06-11 19:57:18 -0700678 // |corr_coefficient| is in Q14.
679 x1 = static_cast<int16_t>(corr_coefficient);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000680 x2 = (x1 * x1) >> 14; // Shift 14 to keep result in Q14.
681 x3 = (x1 * x2) >> 14;
682 static const int kCoefficients[4] = { -5179, 19931, -16422, 5776 };
683 int32_t temp_sum = kCoefficients[0] << 14;
684 temp_sum += kCoefficients[1] * x1;
685 temp_sum += kCoefficients[2] * x2;
686 temp_sum += kCoefficients[3] * x3;
Peter Kastingf045e4d2015-06-10 21:15:38 -0700687 parameters.voice_mix_factor =
688 static_cast<int16_t>(std::min(temp_sum / 4096, 16384));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000689 parameters.voice_mix_factor = std::max(parameters.voice_mix_factor,
690 static_cast<int16_t>(0));
691 } else {
692 parameters.voice_mix_factor = 0;
693 }
694
695 // Calculate muting slope. Reuse value from earlier scaling of
696 // |expand_vector0| and |expand_vector1|.
697 int16_t slope = amplitude_ratio;
698 if (slope > 12288) {
699 // slope > 1.5.
700 // Calculate (1 - (1 / slope)) / distortion_lag =
701 // (slope - 1) / (distortion_lag * slope).
702 // |slope| is in Q13, so 1 corresponds to 8192. Shift up to Q25 before
703 // the division.
704 // Shift the denominator from Q13 to Q5 before the division. The result of
705 // the division will then be in Q20.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700706 int temp_ratio = WebRtcSpl_DivW32W16(
Peter Kastingb7e50542015-06-11 12:55:50 -0700707 (slope - 8192) << 12,
708 static_cast<int16_t>((distortion_lag * slope) >> 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709 if (slope > 14746) {
710 // slope > 1.8.
711 // Divide by 2, with proper rounding.
712 parameters.mute_slope = (temp_ratio + 1) / 2;
713 } else {
714 // Divide by 8, with proper rounding.
715 parameters.mute_slope = (temp_ratio + 4) / 8;
716 }
717 parameters.onset = true;
718 } else {
719 // Calculate (1 - slope) / distortion_lag.
720 // Shift |slope| by 7 to Q20 before the division. The result is in Q20.
Peter Kastingb7e50542015-06-11 12:55:50 -0700721 parameters.mute_slope = WebRtcSpl_DivW32W16(
722 (8192 - slope) << 7, static_cast<int16_t>(distortion_lag));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723 if (parameters.voice_mix_factor <= 13107) {
724 // Make sure the mute factor decreases from 1.0 to 0.9 in no more than
725 // 6.25 ms.
726 // mute_slope >= 0.005 / fs_mult in Q20.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700727 parameters.mute_slope = std::max(5243 / fs_mult, parameters.mute_slope);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000728 } else if (slope > 8028) {
729 parameters.mute_slope = 0;
730 }
731 parameters.onset = false;
732 }
733 }
734}
735
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200736Expand::ChannelParameters::ChannelParameters()
737 : mute_factor(16384),
738 ar_gain(0),
739 ar_gain_scale(0),
740 voice_mix_factor(0),
741 current_voice_mix_factor(0),
742 onset(false),
743 mute_slope(0) {
744 memset(ar_filter, 0, sizeof(ar_filter));
745 memset(ar_filter_state, 0, sizeof(ar_filter_state));
746}
747
Peter Kasting728d9032015-06-11 14:31:38 -0700748void Expand::Correlation(const int16_t* input,
749 size_t input_length,
minyue3d09dfd2016-04-27 15:06:10 -0700750 int16_t* output) const {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000751 // Set parameters depending on sample rate.
752 const int16_t* filter_coefficients;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700753 size_t num_coefficients;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754 int16_t downsampling_factor;
755 if (fs_hz_ == 8000) {
756 num_coefficients = 3;
757 downsampling_factor = 2;
758 filter_coefficients = DspHelper::kDownsample8kHzTbl;
759 } else if (fs_hz_ == 16000) {
760 num_coefficients = 5;
761 downsampling_factor = 4;
762 filter_coefficients = DspHelper::kDownsample16kHzTbl;
763 } else if (fs_hz_ == 32000) {
764 num_coefficients = 7;
765 downsampling_factor = 8;
766 filter_coefficients = DspHelper::kDownsample32kHzTbl;
767 } else { // fs_hz_ == 48000.
768 num_coefficients = 7;
769 downsampling_factor = 12;
770 filter_coefficients = DspHelper::kDownsample48kHzTbl;
771 }
772
773 // Correlate from lag 10 to lag 60 in downsampled domain.
774 // (Corresponds to 20-120 for narrow-band, 40-240 for wide-band, and so on.)
Peter Kastingdce40cf2015-08-24 14:52:23 -0700775 static const size_t kCorrelationStartLag = 10;
776 static const size_t kNumCorrelationLags = 54;
777 static const size_t kCorrelationLength = 60;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000778 // Downsample to 4 kHz sample rate.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700779 static const size_t kDownsampledLength = kCorrelationStartLag
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000780 + kNumCorrelationLags + kCorrelationLength;
781 int16_t downsampled_input[kDownsampledLength];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700782 static const size_t kFilterDelay = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000783 WebRtcSpl_DownsampleFast(
784 input + input_length - kDownsampledLength * downsampling_factor,
785 kDownsampledLength * downsampling_factor, downsampled_input,
786 kDownsampledLength, filter_coefficients, num_coefficients,
787 downsampling_factor, kFilterDelay);
788
789 // Normalize |downsampled_input| to using all 16 bits.
790 int16_t max_value = WebRtcSpl_MaxAbsValueW16(downsampled_input,
791 kDownsampledLength);
792 int16_t norm_shift = 16 - WebRtcSpl_NormW32(max_value);
793 WebRtcSpl_VectorBitShiftW16(downsampled_input, kDownsampledLength,
794 downsampled_input, norm_shift);
795
796 int32_t correlation[kNumCorrelationLags];
minyue3d09dfd2016-04-27 15:06:10 -0700797 CrossCorrelationWithAutoShift(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000798 &downsampled_input[kDownsampledLength - kCorrelationLength],
799 &downsampled_input[kDownsampledLength - kCorrelationLength
800 - kCorrelationStartLag],
minyue3d09dfd2016-04-27 15:06:10 -0700801 kCorrelationLength, kNumCorrelationLags, -1, correlation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000802
803 // Normalize and move data from 32-bit to 16-bit vector.
804 int32_t max_correlation = WebRtcSpl_MaxAbsValueW32(correlation,
805 kNumCorrelationLags);
Peter Kastingb7e50542015-06-11 12:55:50 -0700806 int16_t norm_shift2 = static_cast<int16_t>(
807 std::max(18 - WebRtcSpl_NormW32(max_correlation), 0));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 WebRtcSpl_VectorBitShiftW32ToW16(output, kNumCorrelationLags, correlation,
809 norm_shift2);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000810}
811
812void Expand::UpdateLagIndex() {
813 current_lag_index_ = current_lag_index_ + lag_index_direction_;
814 // Change direction if needed.
815 if (current_lag_index_ <= 0) {
816 lag_index_direction_ = 1;
817 }
818 if (current_lag_index_ >= kNumLags - 1) {
819 lag_index_direction_ = -1;
820 }
821}
822
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000823Expand* ExpandFactory::Create(BackgroundNoise* background_noise,
824 SyncBuffer* sync_buffer,
825 RandomVector* random_vector,
Henrik Lundinbef77e22015-08-18 14:58:09 +0200826 StatisticsCalculator* statistics,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000827 int fs,
828 size_t num_channels) const {
Henrik Lundinbef77e22015-08-18 14:58:09 +0200829 return new Expand(background_noise, sync_buffer, random_vector, statistics,
830 fs, num_channels);
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000831}
832
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000833// TODO(turajs): This can be moved to BackgroundNoise class.
834void Expand::GenerateBackgroundNoise(int16_t* random_vector,
835 size_t channel,
Peter Kasting36b7cc32015-06-11 19:57:18 -0700836 int mute_slope,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000837 bool too_many_expands,
838 size_t num_noise_samples,
839 int16_t* buffer) {
Peter Kastingdce40cf2015-08-24 14:52:23 -0700840 static const size_t kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000841 int16_t scaled_random_vector[kMaxSampleRate / 8000 * 125];
Peter Kastingdce40cf2015-08-24 14:52:23 -0700842 assert(num_noise_samples <= (kMaxSampleRate / 8000 * 125));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000843 int16_t* noise_samples = &buffer[kNoiseLpcOrder];
844 if (background_noise_->initialized()) {
845 // Use background noise parameters.
846 memcpy(noise_samples - kNoiseLpcOrder,
847 background_noise_->FilterState(channel),
848 sizeof(int16_t) * kNoiseLpcOrder);
849
850 int dc_offset = 0;
851 if (background_noise_->ScaleShift(channel) > 1) {
852 dc_offset = 1 << (background_noise_->ScaleShift(channel) - 1);
853 }
854
855 // Scale random vector to correct energy level.
856 WebRtcSpl_AffineTransformVector(
857 scaled_random_vector, random_vector,
858 background_noise_->Scale(channel), dc_offset,
859 background_noise_->ScaleShift(channel),
Peter Kastingdce40cf2015-08-24 14:52:23 -0700860 num_noise_samples);
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000861
862 WebRtcSpl_FilterARFastQ12(scaled_random_vector, noise_samples,
863 background_noise_->Filter(channel),
864 kNoiseLpcOrder + 1,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700865 num_noise_samples);
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000866
867 background_noise_->SetFilterState(
868 channel,
869 &(noise_samples[num_noise_samples - kNoiseLpcOrder]),
870 kNoiseLpcOrder);
871
872 // Unmute the background noise.
873 int16_t bgn_mute_factor = background_noise_->MuteFactor(channel);
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000874 NetEq::BackgroundNoiseMode bgn_mode = background_noise_->mode();
875 if (bgn_mode == NetEq::kBgnFade && too_many_expands &&
876 bgn_mute_factor > 0) {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000877 // Fade BGN to zero.
878 // Calculate muting slope, approximately -2^18 / fs_hz.
Peter Kasting36b7cc32015-06-11 19:57:18 -0700879 int mute_slope;
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000880 if (fs_hz_ == 8000) {
881 mute_slope = -32;
882 } else if (fs_hz_ == 16000) {
883 mute_slope = -16;
884 } else if (fs_hz_ == 32000) {
885 mute_slope = -8;
886 } else {
887 mute_slope = -5;
888 }
889 // Use UnmuteSignal function with negative slope.
890 // |bgn_mute_factor| is in Q14. |mute_slope| is in Q20.
891 DspHelper::UnmuteSignal(noise_samples,
892 num_noise_samples,
893 &bgn_mute_factor,
894 mute_slope,
895 noise_samples);
896 } else if (bgn_mute_factor < 16384) {
henrik.lundin@webrtc.org023f12f2014-08-13 09:45:40 +0000897 // If mode is kBgnOn, or if kBgnFade has started fading,
898 // use regular |mute_slope|.
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000899 if (!stop_muting_ && bgn_mode != NetEq::kBgnOff &&
900 !(bgn_mode == NetEq::kBgnFade && too_many_expands)) {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000901 DspHelper::UnmuteSignal(noise_samples,
902 static_cast<int>(num_noise_samples),
903 &bgn_mute_factor,
904 mute_slope,
905 noise_samples);
906 } else {
907 // kBgnOn and stop muting, or
908 // kBgnOff (mute factor is always 0), or
909 // kBgnFade has reached 0.
910 WebRtcSpl_AffineTransformVector(noise_samples, noise_samples,
911 bgn_mute_factor, 8192, 14,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700912 num_noise_samples);
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000913 }
914 }
915 // Update mute_factor in BackgroundNoise class.
916 background_noise_->SetMuteFactor(channel, bgn_mute_factor);
917 } else {
918 // BGN parameters have not been initialized; use zero noise.
919 memset(noise_samples, 0, sizeof(int16_t) * num_noise_samples);
920 }
921}
922
Peter Kastingb7e50542015-06-11 12:55:50 -0700923void Expand::GenerateRandomVector(int16_t seed_increment,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000924 size_t length,
925 int16_t* random_vector) {
926 // TODO(turajs): According to hlundin The loop should not be needed. Should be
927 // just as good to generate all of the vector in one call.
928 size_t samples_generated = 0;
929 const size_t kMaxRandSamples = RandomVector::kRandomTableSize;
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000930 while (samples_generated < length) {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000931 size_t rand_length = std::min(length - samples_generated, kMaxRandSamples);
932 random_vector_->IncreaseSeedIncrement(seed_increment);
933 random_vector_->Generate(rand_length, &random_vector[samples_generated]);
934 samples_generated += rand_length;
935 }
936}
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000937
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000938} // namespace webrtc