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