blob: 6ea3203c0021ddb2b322a732d40a017cf07c988d [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
11#include "webrtc/modules/audio_coding/neteq4/expand.h"
12
13#include <assert.h>
14
15#include <algorithm> // min, max
16#include <cstring> // memset
17
18#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
19#include "webrtc/modules/audio_coding/neteq4/background_noise.h"
20#include "webrtc/modules/audio_coding/neteq4/dsp_helper.h"
21#include "webrtc/modules/audio_coding/neteq4/random_vector.h"
22#include "webrtc/modules/audio_coding/neteq4/sync_buffer.h"
23
24namespace webrtc {
25
26void Expand::Reset() {
27 first_expand_ = true;
28 consecutive_expands_ = 0;
29 max_lag_ = 0;
30 for (size_t ix = 0; ix < num_channels_; ++ix) {
31 channel_parameters_[ix].expand_vector0.Clear();
32 channel_parameters_[ix].expand_vector1.Clear();
33 }
34}
35
36int Expand::Process(AudioMultiVector<int16_t>* output) {
37 int16_t random_vector[kMaxSampleRate / 8000 * 120 + 30];
38 int16_t scaled_random_vector[kMaxSampleRate / 8000 * 125];
39 static const int kTempDataSize = 3600;
40 int16_t temp_data[kTempDataSize]; // TODO(hlundin) Remove this.
41 int16_t* voiced_vector_storage = temp_data;
42 int16_t* voiced_vector = &voiced_vector_storage[overlap_length_];
43 static const int kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
44 int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
45 int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
46 int16_t* noise_vector = unvoiced_array_memory + kNoiseLpcOrder;
47
48 int fs_mult = fs_hz_ / 8000;
49
50 if (first_expand_) {
51 // Perform initial setup if this is the first expansion since last reset.
52 AnalyzeSignal(random_vector);
53 first_expand_ = false;
54 } else {
55 // This is not the first expansion, parameters are already estimated.
56 // Extract a noise segment.
57 int16_t rand_length = max_lag_;
58 // TODO(hlundin): This if-statement should not be needed. Should be just
59 // as good to generate all of the vector in one call in either case.
60 if (rand_length <= RandomVector::kRandomTableSize) {
61 random_vector_->IncreaseSeedIncrement(2);
62 random_vector_->Generate(rand_length, random_vector);
63 } else {
64 // This only applies to SWB where length could be larger than 256.
65 assert(rand_length <= kMaxSampleRate / 8000 * 120 + 30);
66 random_vector_->IncreaseSeedIncrement(2);
67 random_vector_->Generate(RandomVector::kRandomTableSize, random_vector);
68 random_vector_->IncreaseSeedIncrement(2);
69 random_vector_->Generate(rand_length - RandomVector::kRandomTableSize,
70 &random_vector[RandomVector::kRandomTableSize]);
71 }
72 }
73
74
75 // Generate signal.
76 UpdateLagIndex();
77
78 // Voiced part.
79 // Generate a weighted vector with the current lag.
80 size_t expansion_vector_length = max_lag_ + overlap_length_;
81 size_t current_lag = expand_lags_[current_lag_index_];
82 // Copy lag+overlap data.
83 size_t expansion_vector_position = expansion_vector_length - current_lag -
84 overlap_length_;
85 size_t temp_length = current_lag + overlap_length_;
86 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
87 ChannelParameters& parameters = channel_parameters_[channel_ix];
88 if (current_lag_index_ == 0) {
89 // Use only expand_vector0.
90 assert(expansion_vector_position + temp_length <=
91 parameters.expand_vector0.Size());
92 memcpy(voiced_vector_storage,
93 &parameters.expand_vector0[expansion_vector_position],
94 sizeof(int16_t) * temp_length);
95 } else if (current_lag_index_ == 1) {
96 // Mix 3/4 of expand_vector0 with 1/4 of expand_vector1.
97 WebRtcSpl_ScaleAndAddVectorsWithRound(
98 &parameters.expand_vector0[expansion_vector_position], 3,
99 &parameters.expand_vector1[expansion_vector_position], 1, 2,
100 voiced_vector_storage, temp_length);
101 } else if (current_lag_index_ == 2) {
102 // Mix 1/2 of expand_vector0 with 1/2 of expand_vector1.
103 assert(expansion_vector_position + temp_length <=
104 parameters.expand_vector0.Size());
105 assert(expansion_vector_position + temp_length <=
106 parameters.expand_vector1.Size());
107 WebRtcSpl_ScaleAndAddVectorsWithRound(
108 &parameters.expand_vector0[expansion_vector_position], 1,
109 &parameters.expand_vector1[expansion_vector_position], 1, 1,
110 voiced_vector_storage, temp_length);
111 }
112
113 // Get tapering window parameters. Values are in Q15.
114 int16_t muting_window, muting_window_increment;
115 int16_t unmuting_window, unmuting_window_increment;
116 if (fs_hz_ == 8000) {
117 muting_window = DspHelper::kMuteFactorStart8kHz;
118 muting_window_increment = DspHelper::kMuteFactorIncrement8kHz;
119 unmuting_window = DspHelper::kUnmuteFactorStart8kHz;
120 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement8kHz;
121 } else if (fs_hz_ == 16000) {
122 muting_window = DspHelper::kMuteFactorStart16kHz;
123 muting_window_increment = DspHelper::kMuteFactorIncrement16kHz;
124 unmuting_window = DspHelper::kUnmuteFactorStart16kHz;
125 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement16kHz;
126 } else if (fs_hz_ == 32000) {
127 muting_window = DspHelper::kMuteFactorStart32kHz;
128 muting_window_increment = DspHelper::kMuteFactorIncrement32kHz;
129 unmuting_window = DspHelper::kUnmuteFactorStart32kHz;
130 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement32kHz;
131 } else { // fs_ == 48000
132 muting_window = DspHelper::kMuteFactorStart48kHz;
133 muting_window_increment = DspHelper::kMuteFactorIncrement48kHz;
134 unmuting_window = DspHelper::kUnmuteFactorStart48kHz;
135 unmuting_window_increment = DspHelper::kUnmuteFactorIncrement48kHz;
136 }
137
138 // Smooth the expanded if it has not been muted to a low amplitude and
139 // |current_voice_mix_factor| is larger than 0.5.
140 if ((parameters.mute_factor > 819) &&
141 (parameters.current_voice_mix_factor > 8192)) {
142 size_t start_ix = sync_buffer_->Size() - overlap_length_;
143 for (size_t i = 0; i < overlap_length_; i++) {
144 // Do overlap add between new vector and overlap.
145 (*sync_buffer_)[channel_ix][start_ix + i] =
146 (((*sync_buffer_)[channel_ix][start_ix + i] * muting_window) +
147 (((parameters.mute_factor * voiced_vector_storage[i]) >> 14) *
148 unmuting_window) + 16384) >> 15;
149 muting_window += muting_window_increment;
150 unmuting_window += unmuting_window_increment;
151 }
152 } else if (parameters.mute_factor == 0) {
153 // The expanded signal will consist of only comfort noise if
154 // mute_factor = 0. Set the output length to 15 ms for best noise
155 // production.
156 // TODO(hlundin): This has been disabled since the length of
157 // parameters.expand_vector0 and parameters.expand_vector1 no longer
158 // match with expand_lags_, causing invalid reads and writes. Is it a good
159 // idea to enable this again, and solve the vector size problem?
160// max_lag_ = fs_mult * 120;
161// expand_lags_[0] = fs_mult * 120;
162// expand_lags_[1] = fs_mult * 120;
163// expand_lags_[2] = fs_mult * 120;
164 }
165
166 // Unvoiced part.
167 // Filter |scaled_random_vector| through |ar_filter_|.
168 memcpy(unvoiced_vector - kUnvoicedLpcOrder, parameters.ar_filter_state,
169 sizeof(int16_t) * kUnvoicedLpcOrder);
170 int32_t add_constant = 0;
171 if (parameters.ar_gain_scale > 0) {
172 add_constant = 1 << (parameters.ar_gain_scale - 1);
173 }
174 WebRtcSpl_AffineTransformVector(scaled_random_vector, random_vector,
175 parameters.ar_gain, add_constant,
176 parameters.ar_gain_scale, current_lag);
177 WebRtcSpl_FilterARFastQ12(scaled_random_vector, unvoiced_vector,
178 parameters.ar_filter,
179 kUnvoicedLpcOrder + 1, current_lag);
180 memcpy(parameters.ar_filter_state,
181 &(unvoiced_vector[current_lag - kUnvoicedLpcOrder]),
182 sizeof(int16_t) * kUnvoicedLpcOrder);
183
184 // Combine voiced and unvoiced contributions.
185
186 // Set a suitable cross-fading slope.
187 // For lag =
188 // <= 31 * fs_mult => go from 1 to 0 in about 8 ms;
189 // (>= 31 .. <= 63) * fs_mult => go from 1 to 0 in about 16 ms;
190 // >= 64 * fs_mult => go from 1 to 0 in about 32 ms.
191 // temp_shift = getbits(max_lag_) - 5.
192 int temp_shift = (31 - WebRtcSpl_NormW32(max_lag_)) - 5;
193 int16_t mix_factor_increment = 256 >> temp_shift;
194 if (stop_muting_) {
195 mix_factor_increment = 0;
196 }
197
198 // Create combined signal by shifting in more and more of unvoiced part.
199 temp_shift = 8 - temp_shift; // = getbits(mix_factor_increment).
200 size_t temp_lenght = (parameters.current_voice_mix_factor -
201 parameters.voice_mix_factor) >> temp_shift;
202 temp_lenght = std::min(temp_lenght, current_lag);
203 DspHelper::CrossFade(voiced_vector, unvoiced_vector, temp_lenght,
204 &parameters.current_voice_mix_factor,
205 mix_factor_increment, temp_data);
206
207 // End of cross-fading period was reached before end of expanded signal
208 // path. Mix the rest with a fixed mixing factor.
209 if (temp_lenght < current_lag) {
210 if (mix_factor_increment != 0) {
211 parameters.current_voice_mix_factor = parameters.voice_mix_factor;
212 }
213 int temp_scale = 16384 - parameters.current_voice_mix_factor;
214 WebRtcSpl_ScaleAndAddVectorsWithRound(
215 voiced_vector + temp_lenght, parameters.current_voice_mix_factor,
216 unvoiced_vector + temp_lenght, temp_scale, 14,
217 temp_data + temp_lenght, current_lag - temp_lenght);
218 }
219
220 // Select muting slope depending on how many consecutive expands we have
221 // done.
222 if (consecutive_expands_ == 3) {
223 // Let the mute factor decrease from 1.0 to 0.95 in 6.25 ms.
224 // mute_slope = 0.0010 / fs_mult in Q20.
225 parameters.mute_slope = std::max(parameters.mute_slope,
226 static_cast<int16_t>(1049 / fs_mult));
227 }
228 if (consecutive_expands_ == 7) {
229 // Let the mute factor decrease from 1.0 to 0.90 in 6.25 ms.
230 // mute_slope = 0.0020 / fs_mult in Q20.
231 parameters.mute_slope = std::max(parameters.mute_slope,
232 static_cast<int16_t>(2097 / fs_mult));
233 }
234
235 // Mute segment according to slope value.
236 if ((consecutive_expands_ != 0) || !parameters.onset) {
237 // Mute to the previous level, then continue with the muting.
238 WebRtcSpl_AffineTransformVector(temp_data, temp_data,
239 parameters.mute_factor, 8192,
240 14, current_lag);
241
242 if (!stop_muting_) {
243 DspHelper::MuteSignal(temp_data, parameters.mute_slope, current_lag);
244
245 // Shift by 6 to go from Q20 to Q14.
246 // TODO(hlundin): Adding 8192 before shifting 6 steps seems wrong.
247 // Legacy.
248 int16_t gain = 16384 -
249 (((current_lag * parameters.mute_slope) + 8192) >> 6);
250 gain = ((gain * parameters.mute_factor) + 8192) >> 14;
251
252 // Guard against getting stuck with very small (but sometimes audible)
253 // gain.
254 if ((consecutive_expands_ > 3) && (gain >= parameters.mute_factor)) {
255 parameters.mute_factor = 0;
256 } else {
257 parameters.mute_factor = gain;
258 }
259 }
260 }
261
262 // Background noise part.
263 // TODO(hlundin): Move to separate method? In BackgroundNoise class?
264 if (background_noise_->initialized()) {
265 // Use background noise parameters.
266 memcpy(noise_vector - kNoiseLpcOrder,
267 background_noise_->FilterState(channel_ix),
268 sizeof(int16_t) * kNoiseLpcOrder);
269
270 if (background_noise_->ScaleShift(channel_ix) > 1) {
271 add_constant = 1 << (background_noise_->ScaleShift(channel_ix) - 1);
272 } else {
273 add_constant = 0;
274 }
275
276 // Scale random vector to correct energy level.
277 WebRtcSpl_AffineTransformVector(
278 scaled_random_vector, random_vector,
279 background_noise_->Scale(channel_ix), add_constant,
280 background_noise_->ScaleShift(channel_ix), current_lag);
281
282 WebRtcSpl_FilterARFastQ12(scaled_random_vector, noise_vector,
283 background_noise_->Filter(channel_ix),
284 kNoiseLpcOrder + 1,
285 current_lag);
286
287 background_noise_->SetFilterState(
288 channel_ix,
289 &(noise_vector[current_lag - kNoiseLpcOrder]),
290 kNoiseLpcOrder);
291
292 // Unmute the background noise.
293 int16_t bgn_mute_factor = background_noise_->MuteFactor(channel_ix);
294 BackgroundNoise::BackgroundNoiseMode bgn_mode = background_noise_->mode();
295 if (bgn_mode == BackgroundNoise::kBgnFade &&
296 consecutive_expands_ >= kMaxConsecutiveExpands &&
297 bgn_mute_factor > 0) {
298 // Fade BGN to zero.
299 // Calculate muting slope, approximately -2^18 / fs_hz.
300 int16_t mute_slope;
301 if (fs_hz_ == 8000) {
302 mute_slope = -32;
303 } else if (fs_hz_ == 16000) {
304 mute_slope = -16;
305 } else if (fs_hz_ == 32000) {
306 mute_slope = -8;
307 } else {
308 mute_slope = -5;
309 }
310 // Use UnmuteSignal function with negative slope.
311 // |bgn_mute_factor| is in Q14. |mute_slope| is in Q20.
312 DspHelper::UnmuteSignal(noise_vector, current_lag, &bgn_mute_factor,
313 mute_slope, noise_vector);
314 } else if (bgn_mute_factor < 16384) {
315 // If mode is kBgnOff, or if kBgnFade has started fading,
316 // Use regular |mute_slope|.
317 if (!stop_muting_ && bgn_mode != BackgroundNoise::kBgnOff &&
318 !(bgn_mode == BackgroundNoise::kBgnFade &&
319 consecutive_expands_ >= kMaxConsecutiveExpands)) {
320 DspHelper::UnmuteSignal(noise_vector, current_lag, &bgn_mute_factor,
321 parameters.mute_slope, noise_vector);
322 } else {
323 // kBgnOn and stop muting, or
324 // kBgnOff (mute factor is always 0), or
325 // kBgnFade has reached 0.
326 WebRtcSpl_AffineTransformVector(noise_vector, noise_vector,
327 bgn_mute_factor, 8192, 14,
328 current_lag);
329 }
330 }
331 // Update mute_factor in BackgroundNoise class.
332 background_noise_->SetMuteFactor(channel_ix, bgn_mute_factor);
333 } else {
334 // BGN parameters have not been initialized; use zero noise.
335 memset(noise_vector, 0, sizeof(int16_t) * current_lag);
336 }
337
338 // Add background noise to the combined voiced-unvoiced signal.
339 for (size_t i = 0; i < current_lag; i++) {
340 temp_data[i] = temp_data[i] + noise_vector[i];
341 }
342 if (channel_ix == 0) {
343 output->AssertSize(current_lag);
344 } else {
345 assert(output->Size() == current_lag);
346 }
347 memcpy(&(*output)[channel_ix][0], temp_data,
348 sizeof(temp_data[0]) * current_lag);
349 }
350
351 // Increase call number and cap it.
352 ++consecutive_expands_;
353 if (consecutive_expands_ > kMaxConsecutiveExpands) {
354 consecutive_expands_ = kMaxConsecutiveExpands;
355 }
356
357 return 0;
358}
359
360void Expand::SetParametersForNormalAfterExpand() {
361 current_lag_index_ = 0;
362 lag_index_direction_ = 0;
363 stop_muting_ = true; // Do not mute signal any more.
364}
365
366void Expand::SetParametersForMergeAfterExpand() {
367 current_lag_index_ = -1; /* out of the 3 possible ones */
368 lag_index_direction_ = 1; /* make sure we get the "optimal" lag */
369 stop_muting_ = true;
370}
371
372void Expand::AnalyzeSignal(int16_t* random_vector) {
373 int32_t auto_correlation[kUnvoicedLpcOrder + 1];
374 int16_t reflection_coeff[kUnvoicedLpcOrder];
375 int16_t correlation_vector[kMaxSampleRate / 8000 * 102];
376 int best_correlation_index[kNumCorrelationCandidates];
377 int16_t best_correlation[kNumCorrelationCandidates];
378 int16_t best_distortion_index[kNumCorrelationCandidates];
379 int16_t best_distortion[kNumCorrelationCandidates];
380 int32_t correlation_vector2[(99 * kMaxSampleRate / 8000) + 1];
381 int32_t best_distortion_w32[kNumCorrelationCandidates];
382 static const int kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
383 int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
384 int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
385
386 int fs_mult = fs_hz_ / 8000;
387
388 // Pre-calculate common multiplications with fs_mult.
389 int fs_mult_4 = fs_mult * 4;
390 int fs_mult_20 = fs_mult * 20;
391 int fs_mult_120 = fs_mult * 120;
392 int fs_mult_dist_len = fs_mult * kDistortionLength;
393 int fs_mult_lpc_analysis_len = fs_mult * kLpcAnalysisLength;
394
395 const size_t signal_length = 256 * fs_mult;
396 const int16_t* audio_history =
397 &(*sync_buffer_)[0][sync_buffer_->Size() - signal_length];
398
399 // Initialize some member variables.
400 lag_index_direction_ = 1;
401 current_lag_index_ = -1;
402 stop_muting_ = false;
403 random_vector_->set_seed_increment(1);
404 consecutive_expands_ = 0;
405 for (size_t ix = 0; ix < num_channels_; ++ix) {
406 channel_parameters_[ix].current_voice_mix_factor = 16384; // 1.0 in Q14.
407 channel_parameters_[ix].mute_factor = 16384; // 1.0 in Q14.
408 // Start with 0 gain for background noise.
409 background_noise_->SetMuteFactor(ix, 0);
410 }
411
412 // Calculate correlation in downsampled domain (4 kHz sample rate).
413 int16_t correlation_scale;
414 int correlation_length = Correlation(audio_history, signal_length,
415 correlation_vector, &correlation_scale);
416 correlation_length = 51; // TODO(hlundin): Legacy bit-exactness.
417
418 // Find peaks in correlation vector.
419 DspHelper::PeakDetection(correlation_vector, correlation_length,
420 kNumCorrelationCandidates, fs_mult,
421 best_correlation_index, best_correlation);
422
423 // Adjust peak locations; cross-correlation lags start at 2.5 ms
424 // (20 * fs_mult samples).
425 best_correlation_index[0] += fs_mult_20;
426 best_correlation_index[1] += fs_mult_20;
427 best_correlation_index[2] += fs_mult_20;
428
429 // Calculate distortion around the |kNumCorrelationCandidates| best lags.
430 int distortion_scale = 0;
431 for (int i = 0; i < kNumCorrelationCandidates; i++) {
432 int16_t min_index = std::max(fs_mult_20,
433 best_correlation_index[i] - fs_mult_4);
434 int16_t max_index = std::min(fs_mult_120 - 1,
435 best_correlation_index[i] + fs_mult_4);
436 best_distortion_index[i] = DspHelper::MinDistortion(
437 &(audio_history[signal_length - fs_mult_dist_len]), min_index,
438 max_index, fs_mult_dist_len, &best_distortion_w32[i]);
439 distortion_scale = std::max(16 - WebRtcSpl_NormW32(best_distortion_w32[i]),
440 distortion_scale);
441 }
442 // Shift the distortion values to fit in 16 bits.
443 WebRtcSpl_VectorBitShiftW32ToW16(best_distortion, kNumCorrelationCandidates,
444 best_distortion_w32, distortion_scale);
445
446 // Find the maximizing index |i| of the cost function
447 // f[i] = best_correlation[i] / best_distortion[i].
448 int32_t best_ratio = -1;
449 int best_index = -1;
450 for (int i = 0; i < kNumCorrelationCandidates; ++i) {
451 int32_t ratio;
452 if (best_distortion[i] > 0) {
453 ratio = (best_correlation[i] << 16) / best_distortion[i];
454 } else {
455 assert(best_correlation[i] == 0); // If one is zero, both must be.
456 ratio = 0; // Divide zero by zero => set result to zero.
457 }
458 if (ratio > best_ratio) {
459 best_index = i;
460 best_ratio = ratio;
461 }
462 }
463
464 int distortion_lag = best_distortion_index[best_index];
465 int correlation_lag = best_correlation_index[best_index];
466 max_lag_ = std::max(distortion_lag, correlation_lag);
467
468 // Calculate the exact best correlation in the range between
469 // |correlation_lag| and |distortion_lag|.
470 correlation_length = distortion_lag + 10;
471 correlation_length = std::min(correlation_length, fs_mult_120);
472 correlation_length = std::max(correlation_length, 60 * fs_mult);
473
474 int start_index = std::min(distortion_lag, correlation_lag);
475 int correlation_lags = WEBRTC_SPL_ABS_W16((distortion_lag-correlation_lag))
476 + 1;
477 assert(correlation_lags <= 99 * fs_mult + 1); // Cannot be larger.
478
479 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
480 ChannelParameters& parameters = channel_parameters_[channel_ix];
481 // Calculate suitable scaling.
482 int16_t signal_max = WebRtcSpl_MaxAbsValueW16(
483 &audio_history[signal_length - correlation_length - start_index
484 - correlation_lags],
485 correlation_length + start_index + correlation_lags - 1);
486 correlation_scale = ((31 - WebRtcSpl_NormW32(signal_max * signal_max))
487 + (31 - WebRtcSpl_NormW32(correlation_length))) - 31;
488 correlation_scale = std::max(static_cast<int16_t>(0), correlation_scale);
489
490 // Calculate the correlation, store in |correlation_vector2|.
491 WebRtcSpl_CrossCorrelation(
492 correlation_vector2,
493 &(audio_history[signal_length - correlation_length]),
494 &(audio_history[signal_length - correlation_length - start_index]),
495 correlation_length, correlation_lags, correlation_scale, -1);
496
497 // Find maximizing index.
498 best_index = WebRtcSpl_MaxIndexW32(correlation_vector2, correlation_lags);
499 int32_t max_correlation = correlation_vector2[best_index];
500 // Compensate index with start offset.
501 best_index = best_index + start_index;
502
503 // Calculate energies.
504 int32_t energy1 = WebRtcSpl_DotProductWithScale(
505 &(audio_history[signal_length - correlation_length]),
506 &(audio_history[signal_length - correlation_length]),
507 correlation_length, correlation_scale);
508 int32_t energy2 = WebRtcSpl_DotProductWithScale(
509 &(audio_history[signal_length - correlation_length - best_index]),
510 &(audio_history[signal_length - correlation_length - best_index]),
511 correlation_length, correlation_scale);
512
513 // Calculate the correlation coefficient between the two portions of the
514 // signal.
515 int16_t corr_coefficient;
516 if ((energy1 > 0) && (energy2 > 0)) {
517 int energy1_scale = std::max(16 - WebRtcSpl_NormW32(energy1), 0);
518 int energy2_scale = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
519 // Make sure total scaling is even (to simplify scale factor after sqrt).
520 if ((energy1_scale + energy2_scale) & 1) {
521 // If sum is odd, add 1 to make it even.
522 energy1_scale += 1;
523 }
524 int16_t scaled_energy1 = energy1 >> energy1_scale;
525 int16_t scaled_energy2 = energy2 >> energy2_scale;
526 int16_t sqrt_energy_product = WebRtcSpl_SqrtFloor(
527 scaled_energy1 * scaled_energy2);
528 // Calculate max_correlation / sqrt(energy1 * energy2) in Q14.
529 int cc_shift = 14 - (energy1_scale + energy2_scale) / 2;
530 max_correlation = WEBRTC_SPL_SHIFT_W32(max_correlation, cc_shift);
531 corr_coefficient = WebRtcSpl_DivW32W16(max_correlation,
532 sqrt_energy_product);
533 corr_coefficient = std::min(static_cast<int16_t>(16384),
534 corr_coefficient); // Cap at 1.0 in Q14.
535 } else {
536 corr_coefficient = 0;
537 }
538
539 // Extract the two vectors expand_vector0 and expand_vector1 from
540 // |audio_history|.
541 int16_t expansion_length = max_lag_ + overlap_length_;
542 const int16_t* vector1 = &(audio_history[signal_length - expansion_length]);
543 const int16_t* vector2 = vector1 - distortion_lag;
544 // Normalize the second vector to the same energy as the first.
545 energy1 = WebRtcSpl_DotProductWithScale(vector1, vector1, expansion_length,
546 correlation_scale);
547 energy2 = WebRtcSpl_DotProductWithScale(vector2, vector2, expansion_length,
548 correlation_scale);
549 // Confirm that amplitude ratio sqrt(energy1 / energy2) is within 0.5 - 2.0,
550 // i.e., energy1 / energy1 is within 0.25 - 4.
551 int16_t amplitude_ratio;
552 if ((energy1 / 4 < energy2) && (energy1 > energy2 / 4)) {
553 // Energy constraint fulfilled. Use both vectors and scale them
554 // accordingly.
555 int16_t scaled_energy2 = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
556 int16_t scaled_energy1 = scaled_energy2 - 13;
557 // Calculate scaled_energy1 / scaled_energy2 in Q13.
558 int32_t energy_ratio = WebRtcSpl_DivW32W16(
559 WEBRTC_SPL_SHIFT_W32(energy1, -scaled_energy1),
560 WEBRTC_SPL_RSHIFT_W32(energy2, scaled_energy2));
561 // Calculate sqrt ratio in Q13 (sqrt of en1/en2 in Q26).
562 amplitude_ratio = WebRtcSpl_SqrtFloor(energy_ratio << 13);
563 // Copy the two vectors and give them the same energy.
564 parameters.expand_vector0.Clear();
565 parameters.expand_vector0.PushBack(vector1, expansion_length);
566 parameters.expand_vector1.Clear();
567 if (parameters.expand_vector1.Size() <
568 static_cast<size_t>(expansion_length)) {
569 parameters.expand_vector1.Extend(
570 expansion_length - parameters.expand_vector1.Size());
571 }
572 WebRtcSpl_AffineTransformVector(&parameters.expand_vector1[0],
573 const_cast<int16_t*>(vector2),
574 amplitude_ratio,
575 4096,
576 13,
577 expansion_length);
578 } else {
579 // Energy change constraint not fulfilled. Only use last vector.
580 parameters.expand_vector0.Clear();
581 parameters.expand_vector0.PushBack(vector1, expansion_length);
582 // Copy from expand_vector0 to expand_vector1.
583 parameters.expand_vector0.CopyFrom(&parameters.expand_vector1);
584 // Set the energy_ratio since it is used by muting slope.
585 if ((energy1 / 4 < energy2) || (energy2 == 0)) {
586 amplitude_ratio = 4096; // 0.5 in Q13.
587 } else {
588 amplitude_ratio = 16384; // 2.0 in Q13.
589 }
590 }
591
592 // Set the 3 lag values.
593 int lag_difference = distortion_lag - correlation_lag;
594 if (lag_difference == 0) {
595 // |distortion_lag| and |correlation_lag| are equal.
596 expand_lags_[0] = distortion_lag;
597 expand_lags_[1] = distortion_lag;
598 expand_lags_[2] = distortion_lag;
599 } else {
600 // |distortion_lag| and |correlation_lag| are not equal; use different
601 // combinations of the two.
602 // First lag is |distortion_lag| only.
603 expand_lags_[0] = distortion_lag;
604 // Second lag is the average of the two.
605 expand_lags_[1] = (distortion_lag + correlation_lag) / 2;
606 // Third lag is the average again, but rounding towards |correlation_lag|.
607 if (lag_difference > 0) {
608 expand_lags_[2] = (distortion_lag + correlation_lag - 1) / 2;
609 } else {
610 expand_lags_[2] = (distortion_lag + correlation_lag + 1) / 2;
611 }
612 }
613
614 // Calculate the LPC and the gain of the filters.
615 // Calculate scale value needed for auto-correlation.
616 correlation_scale = WebRtcSpl_MaxAbsValueW16(
617 &(audio_history[signal_length - fs_mult_lpc_analysis_len]),
618 fs_mult_lpc_analysis_len);
619
620 correlation_scale = std::min(16 - WebRtcSpl_NormW32(correlation_scale), 0);
621 correlation_scale = std::max(correlation_scale * 2 + 7, 0);
622
623 // Calculate kUnvoicedLpcOrder + 1 lags of the auto-correlation function.
624 size_t temp_index = signal_length - fs_mult_lpc_analysis_len -
625 kUnvoicedLpcOrder;
626 // Copy signal to temporary vector to be able to pad with leading zeros.
627 int16_t* temp_signal = new int16_t[fs_mult_lpc_analysis_len
628 + kUnvoicedLpcOrder];
629 memset(temp_signal, 0,
630 sizeof(int16_t) * (fs_mult_lpc_analysis_len + kUnvoicedLpcOrder));
631 memcpy(&temp_signal[kUnvoicedLpcOrder],
632 &audio_history[temp_index + kUnvoicedLpcOrder],
633 sizeof(int16_t) * fs_mult_lpc_analysis_len);
634 WebRtcSpl_CrossCorrelation(auto_correlation,
635 &temp_signal[kUnvoicedLpcOrder],
636 &temp_signal[kUnvoicedLpcOrder],
637 fs_mult_lpc_analysis_len, kUnvoicedLpcOrder + 1,
638 correlation_scale, -1);
639 delete [] temp_signal;
640
641 // Verify that variance is positive.
642 if (auto_correlation[0] > 0) {
643 // Estimate AR filter parameters using Levinson-Durbin algorithm;
644 // kUnvoicedLpcOrder + 1 filter coefficients.
645 int16_t stability = WebRtcSpl_LevinsonDurbin(auto_correlation,
646 parameters.ar_filter,
647 reflection_coeff,
648 kUnvoicedLpcOrder);
649
650 // Keep filter parameters only if filter is stable.
651 if (stability != 1) {
652 // Set first coefficient to 4096 (1.0 in Q12).
653 parameters.ar_filter[0] = 4096;
654 // Set remaining |kUnvoicedLpcOrder| coefficients to zero.
655 WebRtcSpl_MemSetW16(parameters.ar_filter + 1, 0, kUnvoicedLpcOrder);
656 }
657 }
658
659 if (channel_ix == 0) {
660 // Extract a noise segment.
661 int16_t noise_length;
662 if (distortion_lag < 40) {
663 noise_length = 2 * distortion_lag + 30;
664 } else {
665 noise_length = distortion_lag + 30;
666 }
667 if (noise_length <= RandomVector::kRandomTableSize) {
668 memcpy(random_vector, RandomVector::kRandomTable,
669 sizeof(int16_t) * noise_length);
670 } else {
671 // Only applies to SWB where length could be larger than
672 // |kRandomTableSize|.
673 memcpy(random_vector, RandomVector::kRandomTable,
674 sizeof(int16_t) * RandomVector::kRandomTableSize);
675 assert(noise_length <= kMaxSampleRate / 8000 * 120 + 30);
676 random_vector_->IncreaseSeedIncrement(2);
677 random_vector_->Generate(
678 noise_length - RandomVector::kRandomTableSize,
679 &random_vector[RandomVector::kRandomTableSize]);
680 }
681 }
682
683 // Set up state vector and calculate scale factor for unvoiced filtering.
684 memcpy(parameters.ar_filter_state,
685 &(audio_history[signal_length - kUnvoicedLpcOrder]),
686 sizeof(int16_t) * kUnvoicedLpcOrder);
687 memcpy(unvoiced_vector - kUnvoicedLpcOrder,
688 &(audio_history[signal_length - 128 - kUnvoicedLpcOrder]),
689 sizeof(int16_t) * kUnvoicedLpcOrder);
690 WebRtcSpl_FilterMAFastQ12(
691 const_cast<int16_t*>(&audio_history[signal_length - 128]),
692 unvoiced_vector, parameters.ar_filter, kUnvoicedLpcOrder + 1, 128);
693 int16_t unvoiced_prescale;
694 if (WebRtcSpl_MaxAbsValueW16(unvoiced_vector, 128) > 4000) {
695 unvoiced_prescale = 4;
696 } else {
697 unvoiced_prescale = 0;
698 }
699 int32_t unvoiced_energy = WebRtcSpl_DotProductWithScale(unvoiced_vector,
700 unvoiced_vector,
701 128,
702 unvoiced_prescale);
703
704 // Normalize |unvoiced_energy| to 28 or 29 bits to preserve sqrt() accuracy.
705 int16_t unvoiced_scale = WebRtcSpl_NormW32(unvoiced_energy) - 3;
706 // Make sure we do an odd number of shifts since we already have 7 shifts
707 // from dividing with 128 earlier. This will make the total scale factor
708 // even, which is suitable for the sqrt.
709 unvoiced_scale += ((unvoiced_scale & 0x1) ^ 0x1);
710 unvoiced_energy = WEBRTC_SPL_SHIFT_W32(unvoiced_energy, unvoiced_scale);
711 int32_t unvoiced_gain = WebRtcSpl_SqrtFloor(unvoiced_energy);
712 parameters.ar_gain_scale = 13
713 + (unvoiced_scale + 7 - unvoiced_prescale) / 2;
714 parameters.ar_gain = unvoiced_gain;
715
716 // Calculate voice_mix_factor from corr_coefficient.
717 // Let x = corr_coefficient. Then, we compute:
718 // if (x > 0.48)
719 // voice_mix_factor = (-5179 + 19931x - 16422x^2 + 5776x^3) / 4096;
720 // else
721 // voice_mix_factor = 0;
722 if (corr_coefficient > 7875) {
723 int16_t x1, x2, x3;
724 x1 = corr_coefficient; // |corr_coefficient| is in Q14.
725 x2 = (x1 * x1) >> 14; // Shift 14 to keep result in Q14.
726 x3 = (x1 * x2) >> 14;
727 static const int kCoefficients[4] = { -5179, 19931, -16422, 5776 };
728 int32_t temp_sum = kCoefficients[0] << 14;
729 temp_sum += kCoefficients[1] * x1;
730 temp_sum += kCoefficients[2] * x2;
731 temp_sum += kCoefficients[3] * x3;
732 parameters.voice_mix_factor = temp_sum / 4096;
733 parameters.voice_mix_factor = std::min(parameters.voice_mix_factor,
734 static_cast<int16_t>(16384));
735 parameters.voice_mix_factor = std::max(parameters.voice_mix_factor,
736 static_cast<int16_t>(0));
737 } else {
738 parameters.voice_mix_factor = 0;
739 }
740
741 // Calculate muting slope. Reuse value from earlier scaling of
742 // |expand_vector0| and |expand_vector1|.
743 int16_t slope = amplitude_ratio;
744 if (slope > 12288) {
745 // slope > 1.5.
746 // Calculate (1 - (1 / slope)) / distortion_lag =
747 // (slope - 1) / (distortion_lag * slope).
748 // |slope| is in Q13, so 1 corresponds to 8192. Shift up to Q25 before
749 // the division.
750 // Shift the denominator from Q13 to Q5 before the division. The result of
751 // the division will then be in Q20.
752 int16_t temp_ratio = WebRtcSpl_DivW32W16((slope - 8192) << 12,
753 (distortion_lag * slope) >> 8);
754 if (slope > 14746) {
755 // slope > 1.8.
756 // Divide by 2, with proper rounding.
757 parameters.mute_slope = (temp_ratio + 1) / 2;
758 } else {
759 // Divide by 8, with proper rounding.
760 parameters.mute_slope = (temp_ratio + 4) / 8;
761 }
762 parameters.onset = true;
763 } else {
764 // Calculate (1 - slope) / distortion_lag.
765 // Shift |slope| by 7 to Q20 before the division. The result is in Q20.
766 parameters.mute_slope = WebRtcSpl_DivW32W16((8192 - slope) << 7,
767 distortion_lag);
768 if (parameters.voice_mix_factor <= 13107) {
769 // Make sure the mute factor decreases from 1.0 to 0.9 in no more than
770 // 6.25 ms.
771 // mute_slope >= 0.005 / fs_mult in Q20.
772 parameters.mute_slope = std::max(static_cast<int16_t>(5243 / fs_mult),
773 parameters.mute_slope);
774 } else if (slope > 8028) {
775 parameters.mute_slope = 0;
776 }
777 parameters.onset = false;
778 }
779 }
780}
781
782int16_t Expand::Correlation(const int16_t* input, int16_t input_length,
783 int16_t* output, int16_t* output_scale) const {
784 // Set parameters depending on sample rate.
785 const int16_t* filter_coefficients;
786 int16_t num_coefficients;
787 int16_t downsampling_factor;
788 if (fs_hz_ == 8000) {
789 num_coefficients = 3;
790 downsampling_factor = 2;
791 filter_coefficients = DspHelper::kDownsample8kHzTbl;
792 } else if (fs_hz_ == 16000) {
793 num_coefficients = 5;
794 downsampling_factor = 4;
795 filter_coefficients = DspHelper::kDownsample16kHzTbl;
796 } else if (fs_hz_ == 32000) {
797 num_coefficients = 7;
798 downsampling_factor = 8;
799 filter_coefficients = DspHelper::kDownsample32kHzTbl;
800 } else { // fs_hz_ == 48000.
801 num_coefficients = 7;
802 downsampling_factor = 12;
803 filter_coefficients = DspHelper::kDownsample48kHzTbl;
804 }
805
806 // Correlate from lag 10 to lag 60 in downsampled domain.
807 // (Corresponds to 20-120 for narrow-band, 40-240 for wide-band, and so on.)
808 static const int kCorrelationStartLag = 10;
809 static const int kNumCorrelationLags = 54;
810 static const int kCorrelationLength = 60;
811 // Downsample to 4 kHz sample rate.
812 static const int kDownsampledLength = kCorrelationStartLag
813 + kNumCorrelationLags + kCorrelationLength;
814 int16_t downsampled_input[kDownsampledLength];
815 static const int kFilterDelay = 0;
816 WebRtcSpl_DownsampleFast(
817 input + input_length - kDownsampledLength * downsampling_factor,
818 kDownsampledLength * downsampling_factor, downsampled_input,
819 kDownsampledLength, filter_coefficients, num_coefficients,
820 downsampling_factor, kFilterDelay);
821
822 // Normalize |downsampled_input| to using all 16 bits.
823 int16_t max_value = WebRtcSpl_MaxAbsValueW16(downsampled_input,
824 kDownsampledLength);
825 int16_t norm_shift = 16 - WebRtcSpl_NormW32(max_value);
826 WebRtcSpl_VectorBitShiftW16(downsampled_input, kDownsampledLength,
827 downsampled_input, norm_shift);
828
829 int32_t correlation[kNumCorrelationLags];
830 static const int kCorrelationShift = 6;
831 WebRtcSpl_CrossCorrelation(
832 correlation,
833 &downsampled_input[kDownsampledLength - kCorrelationLength],
834 &downsampled_input[kDownsampledLength - kCorrelationLength
835 - kCorrelationStartLag],
836 kCorrelationLength, kNumCorrelationLags, kCorrelationShift, -1);
837
838 // Normalize and move data from 32-bit to 16-bit vector.
839 int32_t max_correlation = WebRtcSpl_MaxAbsValueW32(correlation,
840 kNumCorrelationLags);
841 int16_t norm_shift2 = std::max(18 - WebRtcSpl_NormW32(max_correlation), 0);
842 WebRtcSpl_VectorBitShiftW32ToW16(output, kNumCorrelationLags, correlation,
843 norm_shift2);
844 // Total scale factor (right shifts) of correlation value.
845 *output_scale = 2 * norm_shift + kCorrelationShift + norm_shift2;
846 return kNumCorrelationLags;
847}
848
849void Expand::UpdateLagIndex() {
850 current_lag_index_ = current_lag_index_ + lag_index_direction_;
851 // Change direction if needed.
852 if (current_lag_index_ <= 0) {
853 lag_index_direction_ = 1;
854 }
855 if (current_lag_index_ >= kNumLags - 1) {
856 lag_index_direction_ = -1;
857 }
858}
859
860} // namespace webrtc