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