blob: bde655917f47dc2f30b7727a680ec8b7316d0b5c [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
19#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000020#include "webrtc/modules/audio_coding/neteq/background_noise.h"
21#include "webrtc/modules/audio_coding/neteq/dsp_helper.h"
22#include "webrtc/modules/audio_coding/neteq/random_vector.h"
23#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000024
25namespace webrtc {
26
Karl Wiberg7f6c4d42015-04-09 15:44:22 +020027Expand::Expand(BackgroundNoise* background_noise,
28 SyncBuffer* sync_buffer,
29 RandomVector* random_vector,
30 int fs,
31 size_t num_channels)
32 : random_vector_(random_vector),
33 sync_buffer_(sync_buffer),
34 first_expand_(true),
35 fs_hz_(fs),
36 num_channels_(num_channels),
37 consecutive_expands_(0),
38 background_noise_(background_noise),
39 overlap_length_(5 * fs / 8000),
40 lag_index_direction_(0),
41 current_lag_index_(0),
42 stop_muting_(false),
43 channel_parameters_(new ChannelParameters[num_channels_]) {
44 assert(fs == 8000 || fs == 16000 || fs == 32000 || fs == 48000);
45 assert(fs <= kMaxSampleRate); // Should not be possible.
46 assert(num_channels_ > 0);
47 memset(expand_lags_, 0, sizeof(expand_lags_));
48 Reset();
49}
50
51Expand::~Expand() = default;
52
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000053void Expand::Reset() {
54 first_expand_ = true;
55 consecutive_expands_ = 0;
56 max_lag_ = 0;
57 for (size_t ix = 0; ix < num_channels_; ++ix) {
58 channel_parameters_[ix].expand_vector0.Clear();
59 channel_parameters_[ix].expand_vector1.Clear();
60 }
61}
62
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +000063int Expand::Process(AudioMultiVector* output) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000064 int16_t random_vector[kMaxSampleRate / 8000 * 120 + 30];
65 int16_t scaled_random_vector[kMaxSampleRate / 8000 * 125];
66 static const int kTempDataSize = 3600;
67 int16_t temp_data[kTempDataSize]; // TODO(hlundin) Remove this.
68 int16_t* voiced_vector_storage = temp_data;
69 int16_t* voiced_vector = &voiced_vector_storage[overlap_length_];
70 static const int kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
71 int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
72 int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
73 int16_t* noise_vector = unvoiced_array_memory + kNoiseLpcOrder;
74
75 int fs_mult = fs_hz_ / 8000;
76
77 if (first_expand_) {
78 // Perform initial setup if this is the first expansion since last reset.
79 AnalyzeSignal(random_vector);
80 first_expand_ = false;
81 } else {
82 // This is not the first expansion, parameters are already estimated.
83 // Extract a noise segment.
84 int16_t rand_length = max_lag_;
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000085 // This only applies to SWB where length could be larger than 256.
86 assert(rand_length <= kMaxSampleRate / 8000 * 120 + 30);
87 GenerateRandomVector(2, rand_length, random_vector);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000088 }
89
90
91 // Generate signal.
92 UpdateLagIndex();
93
94 // Voiced part.
95 // Generate a weighted vector with the current lag.
96 size_t expansion_vector_length = max_lag_ + overlap_length_;
97 size_t current_lag = expand_lags_[current_lag_index_];
98 // Copy lag+overlap data.
99 size_t expansion_vector_position = expansion_vector_length - current_lag -
100 overlap_length_;
101 size_t temp_length = current_lag + overlap_length_;
102 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
103 ChannelParameters& parameters = channel_parameters_[channel_ix];
104 if (current_lag_index_ == 0) {
105 // Use only expand_vector0.
106 assert(expansion_vector_position + temp_length <=
107 parameters.expand_vector0.Size());
108 memcpy(voiced_vector_storage,
109 &parameters.expand_vector0[expansion_vector_position],
110 sizeof(int16_t) * temp_length);
111 } else if (current_lag_index_ == 1) {
112 // Mix 3/4 of expand_vector0 with 1/4 of expand_vector1.
113 WebRtcSpl_ScaleAndAddVectorsWithRound(
114 &parameters.expand_vector0[expansion_vector_position], 3,
115 &parameters.expand_vector1[expansion_vector_position], 1, 2,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000116 voiced_vector_storage, static_cast<int>(temp_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117 } else if (current_lag_index_ == 2) {
118 // Mix 1/2 of expand_vector0 with 1/2 of expand_vector1.
119 assert(expansion_vector_position + temp_length <=
120 parameters.expand_vector0.Size());
121 assert(expansion_vector_position + temp_length <=
122 parameters.expand_vector1.Size());
123 WebRtcSpl_ScaleAndAddVectorsWithRound(
124 &parameters.expand_vector0[expansion_vector_position], 1,
125 &parameters.expand_vector1[expansion_vector_position], 1, 1,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000126 voiced_vector_storage, static_cast<int>(temp_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000127 }
128
129 // Get tapering window parameters. Values are in Q15.
130 int16_t muting_window, muting_window_increment;
131 int16_t unmuting_window, unmuting_window_increment;
132 if (fs_hz_ == 8000) {
133 muting_window = DspHelper::kMuteFactorStart8kHz;
134 muting_window_increment = DspHelper::kMuteFactorIncrement8kHz;
135 unmuting_window = DspHelper::kUnmuteFactorStart8kHz;
136 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement8kHz;
137 } else if (fs_hz_ == 16000) {
138 muting_window = DspHelper::kMuteFactorStart16kHz;
139 muting_window_increment = DspHelper::kMuteFactorIncrement16kHz;
140 unmuting_window = DspHelper::kUnmuteFactorStart16kHz;
141 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement16kHz;
142 } else if (fs_hz_ == 32000) {
143 muting_window = DspHelper::kMuteFactorStart32kHz;
144 muting_window_increment = DspHelper::kMuteFactorIncrement32kHz;
145 unmuting_window = DspHelper::kUnmuteFactorStart32kHz;
146 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement32kHz;
147 } else { // fs_ == 48000
148 muting_window = DspHelper::kMuteFactorStart48kHz;
149 muting_window_increment = DspHelper::kMuteFactorIncrement48kHz;
150 unmuting_window = DspHelper::kUnmuteFactorStart48kHz;
151 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement48kHz;
152 }
153
154 // Smooth the expanded if it has not been muted to a low amplitude and
155 // |current_voice_mix_factor| is larger than 0.5.
156 if ((parameters.mute_factor > 819) &&
157 (parameters.current_voice_mix_factor > 8192)) {
158 size_t start_ix = sync_buffer_->Size() - overlap_length_;
159 for (size_t i = 0; i < overlap_length_; i++) {
160 // Do overlap add between new vector and overlap.
161 (*sync_buffer_)[channel_ix][start_ix + i] =
162 (((*sync_buffer_)[channel_ix][start_ix + i] * muting_window) +
163 (((parameters.mute_factor * voiced_vector_storage[i]) >> 14) *
164 unmuting_window) + 16384) >> 15;
165 muting_window += muting_window_increment;
166 unmuting_window += unmuting_window_increment;
167 }
168 } else if (parameters.mute_factor == 0) {
169 // The expanded signal will consist of only comfort noise if
170 // mute_factor = 0. Set the output length to 15 ms for best noise
171 // production.
172 // TODO(hlundin): This has been disabled since the length of
173 // parameters.expand_vector0 and parameters.expand_vector1 no longer
174 // match with expand_lags_, causing invalid reads and writes. Is it a good
175 // idea to enable this again, and solve the vector size problem?
176// max_lag_ = fs_mult * 120;
177// expand_lags_[0] = fs_mult * 120;
178// expand_lags_[1] = fs_mult * 120;
179// expand_lags_[2] = fs_mult * 120;
180 }
181
182 // Unvoiced part.
183 // Filter |scaled_random_vector| through |ar_filter_|.
184 memcpy(unvoiced_vector - kUnvoicedLpcOrder, parameters.ar_filter_state,
185 sizeof(int16_t) * kUnvoicedLpcOrder);
186 int32_t add_constant = 0;
187 if (parameters.ar_gain_scale > 0) {
188 add_constant = 1 << (parameters.ar_gain_scale - 1);
189 }
190 WebRtcSpl_AffineTransformVector(scaled_random_vector, random_vector,
191 parameters.ar_gain, add_constant,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000192 parameters.ar_gain_scale,
193 static_cast<int>(current_lag));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000194 WebRtcSpl_FilterARFastQ12(scaled_random_vector, unvoiced_vector,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000195 parameters.ar_filter, kUnvoicedLpcOrder + 1,
196 static_cast<int>(current_lag));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000197 memcpy(parameters.ar_filter_state,
198 &(unvoiced_vector[current_lag - kUnvoicedLpcOrder]),
199 sizeof(int16_t) * kUnvoicedLpcOrder);
200
201 // Combine voiced and unvoiced contributions.
202
203 // Set a suitable cross-fading slope.
204 // For lag =
205 // <= 31 * fs_mult => go from 1 to 0 in about 8 ms;
206 // (>= 31 .. <= 63) * fs_mult => go from 1 to 0 in about 16 ms;
207 // >= 64 * fs_mult => go from 1 to 0 in about 32 ms.
208 // temp_shift = getbits(max_lag_) - 5.
209 int temp_shift = (31 - WebRtcSpl_NormW32(max_lag_)) - 5;
210 int16_t mix_factor_increment = 256 >> temp_shift;
211 if (stop_muting_) {
212 mix_factor_increment = 0;
213 }
214
215 // Create combined signal by shifting in more and more of unvoiced part.
216 temp_shift = 8 - temp_shift; // = getbits(mix_factor_increment).
Peter Kasting728d9032015-06-11 14:31:38 -0700217 size_t temp_length = (parameters.current_voice_mix_factor -
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000218 parameters.voice_mix_factor) >> temp_shift;
Peter Kasting728d9032015-06-11 14:31:38 -0700219 temp_length = std::min(temp_length, current_lag);
220 DspHelper::CrossFade(voiced_vector, unvoiced_vector, temp_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000221 &parameters.current_voice_mix_factor,
222 mix_factor_increment, temp_data);
223
224 // End of cross-fading period was reached before end of expanded signal
225 // path. Mix the rest with a fixed mixing factor.
Peter Kasting728d9032015-06-11 14:31:38 -0700226 if (temp_length < current_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000227 if (mix_factor_increment != 0) {
228 parameters.current_voice_mix_factor = parameters.voice_mix_factor;
229 }
Peter Kastingb7e50542015-06-11 12:55:50 -0700230 int16_t temp_scale = 16384 - parameters.current_voice_mix_factor;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000231 WebRtcSpl_ScaleAndAddVectorsWithRound(
Peter Kasting728d9032015-06-11 14:31:38 -0700232 voiced_vector + temp_length, parameters.current_voice_mix_factor,
233 unvoiced_vector + temp_length, temp_scale, 14,
234 temp_data + temp_length, static_cast<int>(current_lag - temp_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000235 }
236
237 // Select muting slope depending on how many consecutive expands we have
238 // done.
239 if (consecutive_expands_ == 3) {
240 // Let the mute factor decrease from 1.0 to 0.95 in 6.25 ms.
241 // mute_slope = 0.0010 / fs_mult in Q20.
Peter Kastingcb180972015-06-11 12:42:27 -0700242 parameters.mute_slope = std::max(parameters.mute_slope,
243 static_cast<int16_t>(1049 / fs_mult));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000244 }
245 if (consecutive_expands_ == 7) {
246 // Let the mute factor decrease from 1.0 to 0.90 in 6.25 ms.
247 // mute_slope = 0.0020 / fs_mult in Q20.
Peter Kastingcb180972015-06-11 12:42:27 -0700248 parameters.mute_slope = std::max(parameters.mute_slope,
249 static_cast<int16_t>(2097 / fs_mult));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 }
251
252 // Mute segment according to slope value.
253 if ((consecutive_expands_ != 0) || !parameters.onset) {
254 // Mute to the previous level, then continue with the muting.
255 WebRtcSpl_AffineTransformVector(temp_data, temp_data,
256 parameters.mute_factor, 8192,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000257 14, static_cast<int>(current_lag));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258
259 if (!stop_muting_) {
260 DspHelper::MuteSignal(temp_data, parameters.mute_slope, current_lag);
261
262 // Shift by 6 to go from Q20 to Q14.
263 // TODO(hlundin): Adding 8192 before shifting 6 steps seems wrong.
264 // Legacy.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000265 int16_t gain = static_cast<int16_t>(16384 -
266 (((current_lag * parameters.mute_slope) + 8192) >> 6));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000267 gain = ((gain * parameters.mute_factor) + 8192) >> 14;
268
269 // Guard against getting stuck with very small (but sometimes audible)
270 // gain.
271 if ((consecutive_expands_ > 3) && (gain >= parameters.mute_factor)) {
272 parameters.mute_factor = 0;
273 } else {
274 parameters.mute_factor = gain;
275 }
276 }
277 }
278
279 // Background noise part.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000280 GenerateBackgroundNoise(random_vector,
281 channel_ix,
282 channel_parameters_[channel_ix].mute_slope,
283 TooManyExpands(),
284 current_lag,
285 unvoiced_array_memory);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000286
287 // Add background noise to the combined voiced-unvoiced signal.
288 for (size_t i = 0; i < current_lag; i++) {
289 temp_data[i] = temp_data[i] + noise_vector[i];
290 }
291 if (channel_ix == 0) {
292 output->AssertSize(current_lag);
293 } else {
294 assert(output->Size() == current_lag);
295 }
296 memcpy(&(*output)[channel_ix][0], temp_data,
297 sizeof(temp_data[0]) * current_lag);
298 }
299
300 // Increase call number and cap it.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000301 consecutive_expands_ = consecutive_expands_ >= kMaxConsecutiveExpands ?
302 kMaxConsecutiveExpands : consecutive_expands_ + 1;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000303 return 0;
304}
305
306void Expand::SetParametersForNormalAfterExpand() {
307 current_lag_index_ = 0;
308 lag_index_direction_ = 0;
309 stop_muting_ = true; // Do not mute signal any more.
310}
311
312void Expand::SetParametersForMergeAfterExpand() {
313 current_lag_index_ = -1; /* out of the 3 possible ones */
314 lag_index_direction_ = 1; /* make sure we get the "optimal" lag */
315 stop_muting_ = true;
316}
317
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200318size_t Expand::overlap_length() const {
319 return overlap_length_;
320}
321
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000322void Expand::InitializeForAnExpandPeriod() {
323 lag_index_direction_ = 1;
324 current_lag_index_ = -1;
325 stop_muting_ = false;
326 random_vector_->set_seed_increment(1);
327 consecutive_expands_ = 0;
328 for (size_t ix = 0; ix < num_channels_; ++ix) {
329 channel_parameters_[ix].current_voice_mix_factor = 16384; // 1.0 in Q14.
330 channel_parameters_[ix].mute_factor = 16384; // 1.0 in Q14.
331 // Start with 0 gain for background noise.
332 background_noise_->SetMuteFactor(ix, 0);
333 }
334}
335
336bool Expand::TooManyExpands() {
337 return consecutive_expands_ >= kMaxConsecutiveExpands;
338}
339
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000340void Expand::AnalyzeSignal(int16_t* random_vector) {
341 int32_t auto_correlation[kUnvoicedLpcOrder + 1];
342 int16_t reflection_coeff[kUnvoicedLpcOrder];
343 int16_t correlation_vector[kMaxSampleRate / 8000 * 102];
344 int best_correlation_index[kNumCorrelationCandidates];
345 int16_t best_correlation[kNumCorrelationCandidates];
346 int16_t best_distortion_index[kNumCorrelationCandidates];
347 int16_t best_distortion[kNumCorrelationCandidates];
348 int32_t correlation_vector2[(99 * kMaxSampleRate / 8000) + 1];
349 int32_t best_distortion_w32[kNumCorrelationCandidates];
350 static const int kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
351 int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
352 int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
353
354 int fs_mult = fs_hz_ / 8000;
355
356 // Pre-calculate common multiplications with fs_mult.
357 int fs_mult_4 = fs_mult * 4;
358 int fs_mult_20 = fs_mult * 20;
359 int fs_mult_120 = fs_mult * 120;
360 int fs_mult_dist_len = fs_mult * kDistortionLength;
361 int fs_mult_lpc_analysis_len = fs_mult * kLpcAnalysisLength;
362
363 const size_t signal_length = 256 * fs_mult;
364 const int16_t* audio_history =
365 &(*sync_buffer_)[0][sync_buffer_->Size() - signal_length];
366
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000367 // Initialize.
368 InitializeForAnExpandPeriod();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369
370 // Calculate correlation in downsampled domain (4 kHz sample rate).
Peter Kastingcb180972015-06-11 12:42:27 -0700371 int16_t correlation_scale;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +0000372 int correlation_length = 51; // TODO(hlundin): Legacy bit-exactness.
373 // If it is decided to break bit-exactness |correlation_length| should be
374 // initialized to the return value of Correlation().
375 Correlation(audio_history, signal_length, correlation_vector,
376 &correlation_scale);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000377
378 // Find peaks in correlation vector.
379 DspHelper::PeakDetection(correlation_vector, correlation_length,
380 kNumCorrelationCandidates, fs_mult,
381 best_correlation_index, best_correlation);
382
383 // Adjust peak locations; cross-correlation lags start at 2.5 ms
384 // (20 * fs_mult samples).
385 best_correlation_index[0] += fs_mult_20;
386 best_correlation_index[1] += fs_mult_20;
387 best_correlation_index[2] += fs_mult_20;
388
389 // Calculate distortion around the |kNumCorrelationCandidates| best lags.
390 int distortion_scale = 0;
391 for (int i = 0; i < kNumCorrelationCandidates; i++) {
392 int16_t min_index = std::max(fs_mult_20,
393 best_correlation_index[i] - fs_mult_4);
394 int16_t max_index = std::min(fs_mult_120 - 1,
395 best_correlation_index[i] + fs_mult_4);
396 best_distortion_index[i] = DspHelper::MinDistortion(
397 &(audio_history[signal_length - fs_mult_dist_len]), min_index,
398 max_index, fs_mult_dist_len, &best_distortion_w32[i]);
399 distortion_scale = std::max(16 - WebRtcSpl_NormW32(best_distortion_w32[i]),
400 distortion_scale);
401 }
402 // Shift the distortion values to fit in 16 bits.
403 WebRtcSpl_VectorBitShiftW32ToW16(best_distortion, kNumCorrelationCandidates,
404 best_distortion_w32, distortion_scale);
405
406 // Find the maximizing index |i| of the cost function
407 // f[i] = best_correlation[i] / best_distortion[i].
turaj@webrtc.org58cd3162013-10-31 15:15:55 +0000408 int32_t best_ratio = std::numeric_limits<int32_t>::min();
Peter Kastingf045e4d2015-06-10 21:15:38 -0700409 int best_index = std::numeric_limits<int>::max();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000410 for (int i = 0; i < kNumCorrelationCandidates; ++i) {
411 int32_t ratio;
412 if (best_distortion[i] > 0) {
413 ratio = (best_correlation[i] << 16) / best_distortion[i];
turaj@webrtc.org7126b382013-07-31 16:05:09 +0000414 } else if (best_correlation[i] == 0) {
415 ratio = 0; // No correlation set result to zero.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000416 } else {
turaj@webrtc.org7126b382013-07-31 16:05:09 +0000417 ratio = std::numeric_limits<int32_t>::max(); // Denominator is zero.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000418 }
419 if (ratio > best_ratio) {
420 best_index = i;
421 best_ratio = ratio;
422 }
423 }
424
425 int distortion_lag = best_distortion_index[best_index];
426 int correlation_lag = best_correlation_index[best_index];
427 max_lag_ = std::max(distortion_lag, correlation_lag);
428
429 // Calculate the exact best correlation in the range between
430 // |correlation_lag| and |distortion_lag|.
Peter Kasting728d9032015-06-11 14:31:38 -0700431 correlation_length =
432 std::max(std::min(distortion_lag + 10, fs_mult_120), 60 * fs_mult);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000433
434 int start_index = std::min(distortion_lag, correlation_lag);
Peter Kasting728d9032015-06-11 14:31:38 -0700435 int correlation_lags =
436 WEBRTC_SPL_ABS_W16((distortion_lag-correlation_lag)) + 1;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000437 assert(correlation_lags <= 99 * fs_mult + 1); // Cannot be larger.
438
439 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
440 ChannelParameters& parameters = channel_parameters_[channel_ix];
441 // Calculate suitable scaling.
442 int16_t signal_max = WebRtcSpl_MaxAbsValueW16(
443 &audio_history[signal_length - correlation_length - start_index
444 - correlation_lags],
445 correlation_length + start_index + correlation_lags - 1);
446 correlation_scale = ((31 - WebRtcSpl_NormW32(signal_max * signal_max))
447 + (31 - WebRtcSpl_NormW32(correlation_length))) - 31;
Peter Kastingcb180972015-06-11 12:42:27 -0700448 correlation_scale = std::max(static_cast<int16_t>(0), correlation_scale);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000449
450 // Calculate the correlation, store in |correlation_vector2|.
451 WebRtcSpl_CrossCorrelation(
452 correlation_vector2,
453 &(audio_history[signal_length - correlation_length]),
454 &(audio_history[signal_length - correlation_length - start_index]),
455 correlation_length, correlation_lags, correlation_scale, -1);
456
457 // Find maximizing index.
458 best_index = WebRtcSpl_MaxIndexW32(correlation_vector2, correlation_lags);
459 int32_t max_correlation = correlation_vector2[best_index];
460 // Compensate index with start offset.
461 best_index = best_index + start_index;
462
463 // Calculate energies.
464 int32_t energy1 = WebRtcSpl_DotProductWithScale(
465 &(audio_history[signal_length - correlation_length]),
466 &(audio_history[signal_length - correlation_length]),
467 correlation_length, correlation_scale);
468 int32_t energy2 = WebRtcSpl_DotProductWithScale(
469 &(audio_history[signal_length - correlation_length - best_index]),
470 &(audio_history[signal_length - correlation_length - best_index]),
471 correlation_length, correlation_scale);
472
473 // Calculate the correlation coefficient between the two portions of the
474 // signal.
Peter Kastingcb180972015-06-11 12:42:27 -0700475 int16_t corr_coefficient;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000476 if ((energy1 > 0) && (energy2 > 0)) {
477 int energy1_scale = std::max(16 - WebRtcSpl_NormW32(energy1), 0);
478 int energy2_scale = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
479 // Make sure total scaling is even (to simplify scale factor after sqrt).
480 if ((energy1_scale + energy2_scale) & 1) {
481 // If sum is odd, add 1 to make it even.
482 energy1_scale += 1;
483 }
Peter Kastingcb180972015-06-11 12:42:27 -0700484 int16_t scaled_energy1 = energy1 >> energy1_scale;
485 int16_t scaled_energy2 = energy2 >> energy2_scale;
486 int16_t sqrt_energy_product = WebRtcSpl_SqrtFloor(
487 scaled_energy1 * scaled_energy2);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000488 // Calculate max_correlation / sqrt(energy1 * energy2) in Q14.
489 int cc_shift = 14 - (energy1_scale + energy2_scale) / 2;
490 max_correlation = WEBRTC_SPL_SHIFT_W32(max_correlation, cc_shift);
491 corr_coefficient = WebRtcSpl_DivW32W16(max_correlation,
492 sqrt_energy_product);
Peter Kastingcb180972015-06-11 12:42:27 -0700493 corr_coefficient = std::min(static_cast<int16_t>(16384),
494 corr_coefficient); // Cap at 1.0 in Q14.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000495 } else {
496 corr_coefficient = 0;
497 }
498
499 // Extract the two vectors expand_vector0 and expand_vector1 from
500 // |audio_history|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000501 int16_t expansion_length = static_cast<int16_t>(max_lag_ + overlap_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000502 const int16_t* vector1 = &(audio_history[signal_length - expansion_length]);
503 const int16_t* vector2 = vector1 - distortion_lag;
504 // Normalize the second vector to the same energy as the first.
505 energy1 = WebRtcSpl_DotProductWithScale(vector1, vector1, expansion_length,
506 correlation_scale);
507 energy2 = WebRtcSpl_DotProductWithScale(vector2, vector2, expansion_length,
508 correlation_scale);
509 // Confirm that amplitude ratio sqrt(energy1 / energy2) is within 0.5 - 2.0,
510 // i.e., energy1 / energy1 is within 0.25 - 4.
511 int16_t amplitude_ratio;
512 if ((energy1 / 4 < energy2) && (energy1 > energy2 / 4)) {
513 // Energy constraint fulfilled. Use both vectors and scale them
514 // accordingly.
Peter Kastingcb180972015-06-11 12:42:27 -0700515 int16_t scaled_energy2 = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
516 int16_t scaled_energy1 = scaled_energy2 - 13;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517 // Calculate scaled_energy1 / scaled_energy2 in Q13.
518 int32_t energy_ratio = WebRtcSpl_DivW32W16(
519 WEBRTC_SPL_SHIFT_W32(energy1, -scaled_energy1),
bjornv@webrtc.orga5ce7bb2014-10-20 08:24:54 +0000520 energy2 >> scaled_energy2);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521 // Calculate sqrt ratio in Q13 (sqrt of en1/en2 in Q26).
522 amplitude_ratio = WebRtcSpl_SqrtFloor(energy_ratio << 13);
523 // Copy the two vectors and give them the same energy.
524 parameters.expand_vector0.Clear();
525 parameters.expand_vector0.PushBack(vector1, expansion_length);
526 parameters.expand_vector1.Clear();
527 if (parameters.expand_vector1.Size() <
528 static_cast<size_t>(expansion_length)) {
529 parameters.expand_vector1.Extend(
530 expansion_length - parameters.expand_vector1.Size());
531 }
532 WebRtcSpl_AffineTransformVector(&parameters.expand_vector1[0],
533 const_cast<int16_t*>(vector2),
534 amplitude_ratio,
535 4096,
536 13,
537 expansion_length);
538 } else {
539 // Energy change constraint not fulfilled. Only use last vector.
540 parameters.expand_vector0.Clear();
541 parameters.expand_vector0.PushBack(vector1, expansion_length);
542 // Copy from expand_vector0 to expand_vector1.
henrik.lundin@webrtc.orgf6ab6f82014-09-04 10:58:43 +0000543 parameters.expand_vector0.CopyTo(&parameters.expand_vector1);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000544 // Set the energy_ratio since it is used by muting slope.
545 if ((energy1 / 4 < energy2) || (energy2 == 0)) {
546 amplitude_ratio = 4096; // 0.5 in Q13.
547 } else {
548 amplitude_ratio = 16384; // 2.0 in Q13.
549 }
550 }
551
552 // Set the 3 lag values.
Peter Kastingf045e4d2015-06-10 21:15:38 -0700553 if (distortion_lag == correlation_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000554 expand_lags_[0] = distortion_lag;
555 expand_lags_[1] = distortion_lag;
556 expand_lags_[2] = distortion_lag;
557 } else {
558 // |distortion_lag| and |correlation_lag| are not equal; use different
559 // combinations of the two.
560 // First lag is |distortion_lag| only.
561 expand_lags_[0] = distortion_lag;
562 // Second lag is the average of the two.
563 expand_lags_[1] = (distortion_lag + correlation_lag) / 2;
564 // Third lag is the average again, but rounding towards |correlation_lag|.
Peter Kastingf045e4d2015-06-10 21:15:38 -0700565 if (distortion_lag > correlation_lag) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000566 expand_lags_[2] = (distortion_lag + correlation_lag - 1) / 2;
567 } else {
568 expand_lags_[2] = (distortion_lag + correlation_lag + 1) / 2;
569 }
570 }
571
572 // Calculate the LPC and the gain of the filters.
573 // Calculate scale value needed for auto-correlation.
574 correlation_scale = WebRtcSpl_MaxAbsValueW16(
575 &(audio_history[signal_length - fs_mult_lpc_analysis_len]),
576 fs_mult_lpc_analysis_len);
577
578 correlation_scale = std::min(16 - WebRtcSpl_NormW32(correlation_scale), 0);
579 correlation_scale = std::max(correlation_scale * 2 + 7, 0);
580
581 // Calculate kUnvoicedLpcOrder + 1 lags of the auto-correlation function.
582 size_t temp_index = signal_length - fs_mult_lpc_analysis_len -
583 kUnvoicedLpcOrder;
584 // Copy signal to temporary vector to be able to pad with leading zeros.
585 int16_t* temp_signal = new int16_t[fs_mult_lpc_analysis_len
586 + kUnvoicedLpcOrder];
587 memset(temp_signal, 0,
588 sizeof(int16_t) * (fs_mult_lpc_analysis_len + kUnvoicedLpcOrder));
589 memcpy(&temp_signal[kUnvoicedLpcOrder],
590 &audio_history[temp_index + kUnvoicedLpcOrder],
591 sizeof(int16_t) * fs_mult_lpc_analysis_len);
592 WebRtcSpl_CrossCorrelation(auto_correlation,
593 &temp_signal[kUnvoicedLpcOrder],
594 &temp_signal[kUnvoicedLpcOrder],
595 fs_mult_lpc_analysis_len, kUnvoicedLpcOrder + 1,
596 correlation_scale, -1);
597 delete [] temp_signal;
598
599 // Verify that variance is positive.
600 if (auto_correlation[0] > 0) {
601 // Estimate AR filter parameters using Levinson-Durbin algorithm;
602 // kUnvoicedLpcOrder + 1 filter coefficients.
603 int16_t stability = WebRtcSpl_LevinsonDurbin(auto_correlation,
604 parameters.ar_filter,
605 reflection_coeff,
606 kUnvoicedLpcOrder);
607
608 // Keep filter parameters only if filter is stable.
609 if (stability != 1) {
610 // Set first coefficient to 4096 (1.0 in Q12).
611 parameters.ar_filter[0] = 4096;
612 // Set remaining |kUnvoicedLpcOrder| coefficients to zero.
613 WebRtcSpl_MemSetW16(parameters.ar_filter + 1, 0, kUnvoicedLpcOrder);
614 }
615 }
616
617 if (channel_ix == 0) {
618 // Extract a noise segment.
619 int16_t noise_length;
620 if (distortion_lag < 40) {
621 noise_length = 2 * distortion_lag + 30;
622 } else {
623 noise_length = distortion_lag + 30;
624 }
625 if (noise_length <= RandomVector::kRandomTableSize) {
626 memcpy(random_vector, RandomVector::kRandomTable,
627 sizeof(int16_t) * noise_length);
628 } else {
629 // Only applies to SWB where length could be larger than
630 // |kRandomTableSize|.
631 memcpy(random_vector, RandomVector::kRandomTable,
632 sizeof(int16_t) * RandomVector::kRandomTableSize);
633 assert(noise_length <= kMaxSampleRate / 8000 * 120 + 30);
634 random_vector_->IncreaseSeedIncrement(2);
635 random_vector_->Generate(
636 noise_length - RandomVector::kRandomTableSize,
637 &random_vector[RandomVector::kRandomTableSize]);
638 }
639 }
640
641 // Set up state vector and calculate scale factor for unvoiced filtering.
642 memcpy(parameters.ar_filter_state,
643 &(audio_history[signal_length - kUnvoicedLpcOrder]),
644 sizeof(int16_t) * kUnvoicedLpcOrder);
645 memcpy(unvoiced_vector - kUnvoicedLpcOrder,
646 &(audio_history[signal_length - 128 - kUnvoicedLpcOrder]),
647 sizeof(int16_t) * kUnvoicedLpcOrder);
bjornv@webrtc.orgc14e3572015-01-12 05:50:52 +0000648 WebRtcSpl_FilterMAFastQ12(&audio_history[signal_length - 128],
649 unvoiced_vector,
650 parameters.ar_filter,
651 kUnvoicedLpcOrder + 1,
652 128);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 int16_t unvoiced_prescale;
654 if (WebRtcSpl_MaxAbsValueW16(unvoiced_vector, 128) > 4000) {
655 unvoiced_prescale = 4;
656 } else {
657 unvoiced_prescale = 0;
658 }
659 int32_t unvoiced_energy = WebRtcSpl_DotProductWithScale(unvoiced_vector,
660 unvoiced_vector,
661 128,
662 unvoiced_prescale);
663
664 // Normalize |unvoiced_energy| to 28 or 29 bits to preserve sqrt() accuracy.
665 int16_t unvoiced_scale = WebRtcSpl_NormW32(unvoiced_energy) - 3;
666 // Make sure we do an odd number of shifts since we already have 7 shifts
667 // from dividing with 128 earlier. This will make the total scale factor
668 // even, which is suitable for the sqrt.
669 unvoiced_scale += ((unvoiced_scale & 0x1) ^ 0x1);
670 unvoiced_energy = WEBRTC_SPL_SHIFT_W32(unvoiced_energy, unvoiced_scale);
Peter Kastingb7e50542015-06-11 12:55:50 -0700671 int16_t unvoiced_gain =
672 static_cast<int16_t>(WebRtcSpl_SqrtFloor(unvoiced_energy));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000673 parameters.ar_gain_scale = 13
674 + (unvoiced_scale + 7 - unvoiced_prescale) / 2;
675 parameters.ar_gain = unvoiced_gain;
676
677 // Calculate voice_mix_factor from corr_coefficient.
678 // Let x = corr_coefficient. Then, we compute:
679 // if (x > 0.48)
680 // voice_mix_factor = (-5179 + 19931x - 16422x^2 + 5776x^3) / 4096;
681 // else
682 // voice_mix_factor = 0;
683 if (corr_coefficient > 7875) {
684 int16_t x1, x2, x3;
Peter Kastingcb180972015-06-11 12:42:27 -0700685 x1 = corr_coefficient; // |corr_coefficient| is in Q14.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000686 x2 = (x1 * x1) >> 14; // Shift 14 to keep result in Q14.
687 x3 = (x1 * x2) >> 14;
688 static const int kCoefficients[4] = { -5179, 19931, -16422, 5776 };
689 int32_t temp_sum = kCoefficients[0] << 14;
690 temp_sum += kCoefficients[1] * x1;
691 temp_sum += kCoefficients[2] * x2;
692 temp_sum += kCoefficients[3] * x3;
Peter Kastingf045e4d2015-06-10 21:15:38 -0700693 parameters.voice_mix_factor =
694 static_cast<int16_t>(std::min(temp_sum / 4096, 16384));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000695 parameters.voice_mix_factor = std::max(parameters.voice_mix_factor,
696 static_cast<int16_t>(0));
697 } else {
698 parameters.voice_mix_factor = 0;
699 }
700
701 // Calculate muting slope. Reuse value from earlier scaling of
702 // |expand_vector0| and |expand_vector1|.
703 int16_t slope = amplitude_ratio;
704 if (slope > 12288) {
705 // slope > 1.5.
706 // Calculate (1 - (1 / slope)) / distortion_lag =
707 // (slope - 1) / (distortion_lag * slope).
708 // |slope| is in Q13, so 1 corresponds to 8192. Shift up to Q25 before
709 // the division.
710 // Shift the denominator from Q13 to Q5 before the division. The result of
711 // the division will then be in Q20.
Peter Kastingb7e50542015-06-11 12:55:50 -0700712 int16_t temp_ratio = WebRtcSpl_DivW32W16(
713 (slope - 8192) << 12,
714 static_cast<int16_t>((distortion_lag * slope) >> 8));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000715 if (slope > 14746) {
716 // slope > 1.8.
717 // Divide by 2, with proper rounding.
718 parameters.mute_slope = (temp_ratio + 1) / 2;
719 } else {
720 // Divide by 8, with proper rounding.
721 parameters.mute_slope = (temp_ratio + 4) / 8;
722 }
723 parameters.onset = true;
724 } else {
725 // Calculate (1 - slope) / distortion_lag.
726 // Shift |slope| by 7 to Q20 before the division. The result is in Q20.
Peter Kastingb7e50542015-06-11 12:55:50 -0700727 parameters.mute_slope = WebRtcSpl_DivW32W16(
728 (8192 - slope) << 7, static_cast<int16_t>(distortion_lag));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000729 if (parameters.voice_mix_factor <= 13107) {
730 // Make sure the mute factor decreases from 1.0 to 0.9 in no more than
731 // 6.25 ms.
732 // mute_slope >= 0.005 / fs_mult in Q20.
Peter Kastingcb180972015-06-11 12:42:27 -0700733 parameters.mute_slope = std::max(static_cast<int16_t>(5243 / fs_mult),
734 parameters.mute_slope);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000735 } else if (slope > 8028) {
736 parameters.mute_slope = 0;
737 }
738 parameters.onset = false;
739 }
740 }
741}
742
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200743Expand::ChannelParameters::ChannelParameters()
744 : mute_factor(16384),
745 ar_gain(0),
746 ar_gain_scale(0),
747 voice_mix_factor(0),
748 current_voice_mix_factor(0),
749 onset(false),
750 mute_slope(0) {
751 memset(ar_filter, 0, sizeof(ar_filter));
752 memset(ar_filter_state, 0, sizeof(ar_filter_state));
753}
754
Peter Kasting728d9032015-06-11 14:31:38 -0700755void Expand::Correlation(const int16_t* input,
756 size_t input_length,
757 int16_t* output,
758 int16_t* output_scale) const {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000759 // Set parameters depending on sample rate.
760 const int16_t* filter_coefficients;
761 int16_t num_coefficients;
762 int16_t downsampling_factor;
763 if (fs_hz_ == 8000) {
764 num_coefficients = 3;
765 downsampling_factor = 2;
766 filter_coefficients = DspHelper::kDownsample8kHzTbl;
767 } else if (fs_hz_ == 16000) {
768 num_coefficients = 5;
769 downsampling_factor = 4;
770 filter_coefficients = DspHelper::kDownsample16kHzTbl;
771 } else if (fs_hz_ == 32000) {
772 num_coefficients = 7;
773 downsampling_factor = 8;
774 filter_coefficients = DspHelper::kDownsample32kHzTbl;
775 } else { // fs_hz_ == 48000.
776 num_coefficients = 7;
777 downsampling_factor = 12;
778 filter_coefficients = DspHelper::kDownsample48kHzTbl;
779 }
780
781 // Correlate from lag 10 to lag 60 in downsampled domain.
782 // (Corresponds to 20-120 for narrow-band, 40-240 for wide-band, and so on.)
783 static const int kCorrelationStartLag = 10;
784 static const int kNumCorrelationLags = 54;
785 static const int kCorrelationLength = 60;
786 // Downsample to 4 kHz sample rate.
787 static const int kDownsampledLength = kCorrelationStartLag
788 + kNumCorrelationLags + kCorrelationLength;
789 int16_t downsampled_input[kDownsampledLength];
790 static const int kFilterDelay = 0;
791 WebRtcSpl_DownsampleFast(
792 input + input_length - kDownsampledLength * downsampling_factor,
793 kDownsampledLength * downsampling_factor, downsampled_input,
794 kDownsampledLength, filter_coefficients, num_coefficients,
795 downsampling_factor, kFilterDelay);
796
797 // Normalize |downsampled_input| to using all 16 bits.
798 int16_t max_value = WebRtcSpl_MaxAbsValueW16(downsampled_input,
799 kDownsampledLength);
800 int16_t norm_shift = 16 - WebRtcSpl_NormW32(max_value);
801 WebRtcSpl_VectorBitShiftW16(downsampled_input, kDownsampledLength,
802 downsampled_input, norm_shift);
803
804 int32_t correlation[kNumCorrelationLags];
805 static const int kCorrelationShift = 6;
806 WebRtcSpl_CrossCorrelation(
807 correlation,
808 &downsampled_input[kDownsampledLength - kCorrelationLength],
809 &downsampled_input[kDownsampledLength - kCorrelationLength
810 - kCorrelationStartLag],
811 kCorrelationLength, kNumCorrelationLags, kCorrelationShift, -1);
812
813 // Normalize and move data from 32-bit to 16-bit vector.
814 int32_t max_correlation = WebRtcSpl_MaxAbsValueW32(correlation,
815 kNumCorrelationLags);
Peter Kastingb7e50542015-06-11 12:55:50 -0700816 int16_t norm_shift2 = static_cast<int16_t>(
817 std::max(18 - WebRtcSpl_NormW32(max_correlation), 0));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 WebRtcSpl_VectorBitShiftW32ToW16(output, kNumCorrelationLags, correlation,
819 norm_shift2);
820 // Total scale factor (right shifts) of correlation value.
821 *output_scale = 2 * norm_shift + kCorrelationShift + norm_shift2;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000822}
823
824void Expand::UpdateLagIndex() {
825 current_lag_index_ = current_lag_index_ + lag_index_direction_;
826 // Change direction if needed.
827 if (current_lag_index_ <= 0) {
828 lag_index_direction_ = 1;
829 }
830 if (current_lag_index_ >= kNumLags - 1) {
831 lag_index_direction_ = -1;
832 }
833}
834
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000835Expand* ExpandFactory::Create(BackgroundNoise* background_noise,
836 SyncBuffer* sync_buffer,
837 RandomVector* random_vector,
838 int fs,
839 size_t num_channels) const {
840 return new Expand(background_noise, sync_buffer, random_vector, fs,
841 num_channels);
842}
843
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000844// TODO(turajs): This can be moved to BackgroundNoise class.
845void Expand::GenerateBackgroundNoise(int16_t* random_vector,
846 size_t channel,
Peter Kastingcb180972015-06-11 12:42:27 -0700847 int16_t mute_slope,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000848 bool too_many_expands,
849 size_t num_noise_samples,
850 int16_t* buffer) {
851 static const int kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
852 int16_t scaled_random_vector[kMaxSampleRate / 8000 * 125];
Peter Kasting728d9032015-06-11 14:31:38 -0700853 assert(num_noise_samples <= static_cast<size_t>(kMaxSampleRate / 8000 * 125));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000854 int16_t* noise_samples = &buffer[kNoiseLpcOrder];
855 if (background_noise_->initialized()) {
856 // Use background noise parameters.
857 memcpy(noise_samples - kNoiseLpcOrder,
858 background_noise_->FilterState(channel),
859 sizeof(int16_t) * kNoiseLpcOrder);
860
861 int dc_offset = 0;
862 if (background_noise_->ScaleShift(channel) > 1) {
863 dc_offset = 1 << (background_noise_->ScaleShift(channel) - 1);
864 }
865
866 // Scale random vector to correct energy level.
867 WebRtcSpl_AffineTransformVector(
868 scaled_random_vector, random_vector,
869 background_noise_->Scale(channel), dc_offset,
870 background_noise_->ScaleShift(channel),
871 static_cast<int>(num_noise_samples));
872
873 WebRtcSpl_FilterARFastQ12(scaled_random_vector, noise_samples,
874 background_noise_->Filter(channel),
875 kNoiseLpcOrder + 1,
876 static_cast<int>(num_noise_samples));
877
878 background_noise_->SetFilterState(
879 channel,
880 &(noise_samples[num_noise_samples - kNoiseLpcOrder]),
881 kNoiseLpcOrder);
882
883 // Unmute the background noise.
884 int16_t bgn_mute_factor = background_noise_->MuteFactor(channel);
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000885 NetEq::BackgroundNoiseMode bgn_mode = background_noise_->mode();
886 if (bgn_mode == NetEq::kBgnFade && too_many_expands &&
887 bgn_mute_factor > 0) {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000888 // Fade BGN to zero.
889 // Calculate muting slope, approximately -2^18 / fs_hz.
Peter Kastingcb180972015-06-11 12:42:27 -0700890 int16_t mute_slope;
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000891 if (fs_hz_ == 8000) {
892 mute_slope = -32;
893 } else if (fs_hz_ == 16000) {
894 mute_slope = -16;
895 } else if (fs_hz_ == 32000) {
896 mute_slope = -8;
897 } else {
898 mute_slope = -5;
899 }
900 // Use UnmuteSignal function with negative slope.
901 // |bgn_mute_factor| is in Q14. |mute_slope| is in Q20.
902 DspHelper::UnmuteSignal(noise_samples,
903 num_noise_samples,
904 &bgn_mute_factor,
905 mute_slope,
906 noise_samples);
907 } else if (bgn_mute_factor < 16384) {
henrik.lundin@webrtc.org023f12f2014-08-13 09:45:40 +0000908 // If mode is kBgnOn, or if kBgnFade has started fading,
909 // use regular |mute_slope|.
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000910 if (!stop_muting_ && bgn_mode != NetEq::kBgnOff &&
911 !(bgn_mode == NetEq::kBgnFade && too_many_expands)) {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000912 DspHelper::UnmuteSignal(noise_samples,
913 static_cast<int>(num_noise_samples),
914 &bgn_mute_factor,
915 mute_slope,
916 noise_samples);
917 } else {
918 // kBgnOn and stop muting, or
919 // kBgnOff (mute factor is always 0), or
920 // kBgnFade has reached 0.
921 WebRtcSpl_AffineTransformVector(noise_samples, noise_samples,
922 bgn_mute_factor, 8192, 14,
923 static_cast<int>(num_noise_samples));
924 }
925 }
926 // Update mute_factor in BackgroundNoise class.
927 background_noise_->SetMuteFactor(channel, bgn_mute_factor);
928 } else {
929 // BGN parameters have not been initialized; use zero noise.
930 memset(noise_samples, 0, sizeof(int16_t) * num_noise_samples);
931 }
932}
933
Peter Kastingb7e50542015-06-11 12:55:50 -0700934void Expand::GenerateRandomVector(int16_t seed_increment,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000935 size_t length,
936 int16_t* random_vector) {
937 // TODO(turajs): According to hlundin The loop should not be needed. Should be
938 // just as good to generate all of the vector in one call.
939 size_t samples_generated = 0;
940 const size_t kMaxRandSamples = RandomVector::kRandomTableSize;
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000941 while (samples_generated < length) {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000942 size_t rand_length = std::min(length - samples_generated, kMaxRandSamples);
943 random_vector_->IncreaseSeedIncrement(seed_increment);
944 random_vector_->Generate(rand_length, &random_vector[samples_generated]);
945 samples_generated += rand_length;
946 }
947}
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +0000948
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000949} // namespace webrtc