blob: 73f2ef85a562e9221183a60fdbccd1737fbdc538 [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
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +000037int Expand::Process(AudioMultiVector* output) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000038 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);
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000297 NetEqBackgroundNoiseMode bgn_mode = background_noise_->mode();
298 if (bgn_mode == kBgnFade &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299 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|.
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000320 if (!stop_muting_ && bgn_mode != kBgnOff &&
321 !(bgn_mode == kBgnFade &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322 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;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +0000418 int correlation_length = 51; // TODO(hlundin): Legacy bit-exactness.
419 // If it is decided to break bit-exactness |correlation_length| should be
420 // initialized to the return value of Correlation().
421 Correlation(audio_history, signal_length, correlation_vector,
422 &correlation_scale);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000423
424 // Find peaks in correlation vector.
425 DspHelper::PeakDetection(correlation_vector, correlation_length,
426 kNumCorrelationCandidates, fs_mult,
427 best_correlation_index, best_correlation);
428
429 // Adjust peak locations; cross-correlation lags start at 2.5 ms
430 // (20 * fs_mult samples).
431 best_correlation_index[0] += fs_mult_20;
432 best_correlation_index[1] += fs_mult_20;
433 best_correlation_index[2] += fs_mult_20;
434
435 // Calculate distortion around the |kNumCorrelationCandidates| best lags.
436 int distortion_scale = 0;
437 for (int i = 0; i < kNumCorrelationCandidates; i++) {
438 int16_t min_index = std::max(fs_mult_20,
439 best_correlation_index[i] - fs_mult_4);
440 int16_t max_index = std::min(fs_mult_120 - 1,
441 best_correlation_index[i] + fs_mult_4);
442 best_distortion_index[i] = DspHelper::MinDistortion(
443 &(audio_history[signal_length - fs_mult_dist_len]), min_index,
444 max_index, fs_mult_dist_len, &best_distortion_w32[i]);
445 distortion_scale = std::max(16 - WebRtcSpl_NormW32(best_distortion_w32[i]),
446 distortion_scale);
447 }
448 // Shift the distortion values to fit in 16 bits.
449 WebRtcSpl_VectorBitShiftW32ToW16(best_distortion, kNumCorrelationCandidates,
450 best_distortion_w32, distortion_scale);
451
452 // Find the maximizing index |i| of the cost function
453 // f[i] = best_correlation[i] / best_distortion[i].
turaj@webrtc.org58cd3162013-10-31 15:15:55 +0000454 int32_t best_ratio = std::numeric_limits<int32_t>::min();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000455 int best_index = -1;
456 for (int i = 0; i < kNumCorrelationCandidates; ++i) {
457 int32_t ratio;
458 if (best_distortion[i] > 0) {
459 ratio = (best_correlation[i] << 16) / best_distortion[i];
turaj@webrtc.org7126b382013-07-31 16:05:09 +0000460 } else if (best_correlation[i] == 0) {
461 ratio = 0; // No correlation set result to zero.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000462 } else {
turaj@webrtc.org7126b382013-07-31 16:05:09 +0000463 ratio = std::numeric_limits<int32_t>::max(); // Denominator is zero.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000464 }
465 if (ratio > best_ratio) {
466 best_index = i;
467 best_ratio = ratio;
468 }
469 }
470
471 int distortion_lag = best_distortion_index[best_index];
472 int correlation_lag = best_correlation_index[best_index];
473 max_lag_ = std::max(distortion_lag, correlation_lag);
474
475 // Calculate the exact best correlation in the range between
476 // |correlation_lag| and |distortion_lag|.
477 correlation_length = distortion_lag + 10;
478 correlation_length = std::min(correlation_length, fs_mult_120);
479 correlation_length = std::max(correlation_length, 60 * fs_mult);
480
481 int start_index = std::min(distortion_lag, correlation_lag);
482 int correlation_lags = WEBRTC_SPL_ABS_W16((distortion_lag-correlation_lag))
483 + 1;
484 assert(correlation_lags <= 99 * fs_mult + 1); // Cannot be larger.
485
486 for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
487 ChannelParameters& parameters = channel_parameters_[channel_ix];
488 // Calculate suitable scaling.
489 int16_t signal_max = WebRtcSpl_MaxAbsValueW16(
490 &audio_history[signal_length - correlation_length - start_index
491 - correlation_lags],
492 correlation_length + start_index + correlation_lags - 1);
493 correlation_scale = ((31 - WebRtcSpl_NormW32(signal_max * signal_max))
494 + (31 - WebRtcSpl_NormW32(correlation_length))) - 31;
495 correlation_scale = std::max(static_cast<int16_t>(0), correlation_scale);
496
497 // Calculate the correlation, store in |correlation_vector2|.
498 WebRtcSpl_CrossCorrelation(
499 correlation_vector2,
500 &(audio_history[signal_length - correlation_length]),
501 &(audio_history[signal_length - correlation_length - start_index]),
502 correlation_length, correlation_lags, correlation_scale, -1);
503
504 // Find maximizing index.
505 best_index = WebRtcSpl_MaxIndexW32(correlation_vector2, correlation_lags);
506 int32_t max_correlation = correlation_vector2[best_index];
507 // Compensate index with start offset.
508 best_index = best_index + start_index;
509
510 // Calculate energies.
511 int32_t energy1 = WebRtcSpl_DotProductWithScale(
512 &(audio_history[signal_length - correlation_length]),
513 &(audio_history[signal_length - correlation_length]),
514 correlation_length, correlation_scale);
515 int32_t energy2 = WebRtcSpl_DotProductWithScale(
516 &(audio_history[signal_length - correlation_length - best_index]),
517 &(audio_history[signal_length - correlation_length - best_index]),
518 correlation_length, correlation_scale);
519
520 // Calculate the correlation coefficient between the two portions of the
521 // signal.
522 int16_t corr_coefficient;
523 if ((energy1 > 0) && (energy2 > 0)) {
524 int energy1_scale = std::max(16 - WebRtcSpl_NormW32(energy1), 0);
525 int energy2_scale = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
526 // Make sure total scaling is even (to simplify scale factor after sqrt).
527 if ((energy1_scale + energy2_scale) & 1) {
528 // If sum is odd, add 1 to make it even.
529 energy1_scale += 1;
530 }
531 int16_t scaled_energy1 = energy1 >> energy1_scale;
532 int16_t scaled_energy2 = energy2 >> energy2_scale;
533 int16_t sqrt_energy_product = WebRtcSpl_SqrtFloor(
534 scaled_energy1 * scaled_energy2);
535 // Calculate max_correlation / sqrt(energy1 * energy2) in Q14.
536 int cc_shift = 14 - (energy1_scale + energy2_scale) / 2;
537 max_correlation = WEBRTC_SPL_SHIFT_W32(max_correlation, cc_shift);
538 corr_coefficient = WebRtcSpl_DivW32W16(max_correlation,
539 sqrt_energy_product);
540 corr_coefficient = std::min(static_cast<int16_t>(16384),
541 corr_coefficient); // Cap at 1.0 in Q14.
542 } else {
543 corr_coefficient = 0;
544 }
545
546 // Extract the two vectors expand_vector0 and expand_vector1 from
547 // |audio_history|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000548 int16_t expansion_length = static_cast<int16_t>(max_lag_ + overlap_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000549 const int16_t* vector1 = &(audio_history[signal_length - expansion_length]);
550 const int16_t* vector2 = vector1 - distortion_lag;
551 // Normalize the second vector to the same energy as the first.
552 energy1 = WebRtcSpl_DotProductWithScale(vector1, vector1, expansion_length,
553 correlation_scale);
554 energy2 = WebRtcSpl_DotProductWithScale(vector2, vector2, expansion_length,
555 correlation_scale);
556 // Confirm that amplitude ratio sqrt(energy1 / energy2) is within 0.5 - 2.0,
557 // i.e., energy1 / energy1 is within 0.25 - 4.
558 int16_t amplitude_ratio;
559 if ((energy1 / 4 < energy2) && (energy1 > energy2 / 4)) {
560 // Energy constraint fulfilled. Use both vectors and scale them
561 // accordingly.
562 int16_t scaled_energy2 = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
563 int16_t scaled_energy1 = scaled_energy2 - 13;
564 // Calculate scaled_energy1 / scaled_energy2 in Q13.
565 int32_t energy_ratio = WebRtcSpl_DivW32W16(
566 WEBRTC_SPL_SHIFT_W32(energy1, -scaled_energy1),
567 WEBRTC_SPL_RSHIFT_W32(energy2, scaled_energy2));
568 // Calculate sqrt ratio in Q13 (sqrt of en1/en2 in Q26).
569 amplitude_ratio = WebRtcSpl_SqrtFloor(energy_ratio << 13);
570 // Copy the two vectors and give them the same energy.
571 parameters.expand_vector0.Clear();
572 parameters.expand_vector0.PushBack(vector1, expansion_length);
573 parameters.expand_vector1.Clear();
574 if (parameters.expand_vector1.Size() <
575 static_cast<size_t>(expansion_length)) {
576 parameters.expand_vector1.Extend(
577 expansion_length - parameters.expand_vector1.Size());
578 }
579 WebRtcSpl_AffineTransformVector(&parameters.expand_vector1[0],
580 const_cast<int16_t*>(vector2),
581 amplitude_ratio,
582 4096,
583 13,
584 expansion_length);
585 } else {
586 // Energy change constraint not fulfilled. Only use last vector.
587 parameters.expand_vector0.Clear();
588 parameters.expand_vector0.PushBack(vector1, expansion_length);
589 // Copy from expand_vector0 to expand_vector1.
590 parameters.expand_vector0.CopyFrom(&parameters.expand_vector1);
591 // Set the energy_ratio since it is used by muting slope.
592 if ((energy1 / 4 < energy2) || (energy2 == 0)) {
593 amplitude_ratio = 4096; // 0.5 in Q13.
594 } else {
595 amplitude_ratio = 16384; // 2.0 in Q13.
596 }
597 }
598
599 // Set the 3 lag values.
600 int lag_difference = distortion_lag - correlation_lag;
601 if (lag_difference == 0) {
602 // |distortion_lag| and |correlation_lag| are equal.
603 expand_lags_[0] = distortion_lag;
604 expand_lags_[1] = distortion_lag;
605 expand_lags_[2] = distortion_lag;
606 } else {
607 // |distortion_lag| and |correlation_lag| are not equal; use different
608 // combinations of the two.
609 // First lag is |distortion_lag| only.
610 expand_lags_[0] = distortion_lag;
611 // Second lag is the average of the two.
612 expand_lags_[1] = (distortion_lag + correlation_lag) / 2;
613 // Third lag is the average again, but rounding towards |correlation_lag|.
614 if (lag_difference > 0) {
615 expand_lags_[2] = (distortion_lag + correlation_lag - 1) / 2;
616 } else {
617 expand_lags_[2] = (distortion_lag + correlation_lag + 1) / 2;
618 }
619 }
620
621 // Calculate the LPC and the gain of the filters.
622 // Calculate scale value needed for auto-correlation.
623 correlation_scale = WebRtcSpl_MaxAbsValueW16(
624 &(audio_history[signal_length - fs_mult_lpc_analysis_len]),
625 fs_mult_lpc_analysis_len);
626
627 correlation_scale = std::min(16 - WebRtcSpl_NormW32(correlation_scale), 0);
628 correlation_scale = std::max(correlation_scale * 2 + 7, 0);
629
630 // Calculate kUnvoicedLpcOrder + 1 lags of the auto-correlation function.
631 size_t temp_index = signal_length - fs_mult_lpc_analysis_len -
632 kUnvoicedLpcOrder;
633 // Copy signal to temporary vector to be able to pad with leading zeros.
634 int16_t* temp_signal = new int16_t[fs_mult_lpc_analysis_len
635 + kUnvoicedLpcOrder];
636 memset(temp_signal, 0,
637 sizeof(int16_t) * (fs_mult_lpc_analysis_len + kUnvoicedLpcOrder));
638 memcpy(&temp_signal[kUnvoicedLpcOrder],
639 &audio_history[temp_index + kUnvoicedLpcOrder],
640 sizeof(int16_t) * fs_mult_lpc_analysis_len);
641 WebRtcSpl_CrossCorrelation(auto_correlation,
642 &temp_signal[kUnvoicedLpcOrder],
643 &temp_signal[kUnvoicedLpcOrder],
644 fs_mult_lpc_analysis_len, kUnvoicedLpcOrder + 1,
645 correlation_scale, -1);
646 delete [] temp_signal;
647
648 // Verify that variance is positive.
649 if (auto_correlation[0] > 0) {
650 // Estimate AR filter parameters using Levinson-Durbin algorithm;
651 // kUnvoicedLpcOrder + 1 filter coefficients.
652 int16_t stability = WebRtcSpl_LevinsonDurbin(auto_correlation,
653 parameters.ar_filter,
654 reflection_coeff,
655 kUnvoicedLpcOrder);
656
657 // Keep filter parameters only if filter is stable.
658 if (stability != 1) {
659 // Set first coefficient to 4096 (1.0 in Q12).
660 parameters.ar_filter[0] = 4096;
661 // Set remaining |kUnvoicedLpcOrder| coefficients to zero.
662 WebRtcSpl_MemSetW16(parameters.ar_filter + 1, 0, kUnvoicedLpcOrder);
663 }
664 }
665
666 if (channel_ix == 0) {
667 // Extract a noise segment.
668 int16_t noise_length;
669 if (distortion_lag < 40) {
670 noise_length = 2 * distortion_lag + 30;
671 } else {
672 noise_length = distortion_lag + 30;
673 }
674 if (noise_length <= RandomVector::kRandomTableSize) {
675 memcpy(random_vector, RandomVector::kRandomTable,
676 sizeof(int16_t) * noise_length);
677 } else {
678 // Only applies to SWB where length could be larger than
679 // |kRandomTableSize|.
680 memcpy(random_vector, RandomVector::kRandomTable,
681 sizeof(int16_t) * RandomVector::kRandomTableSize);
682 assert(noise_length <= kMaxSampleRate / 8000 * 120 + 30);
683 random_vector_->IncreaseSeedIncrement(2);
684 random_vector_->Generate(
685 noise_length - RandomVector::kRandomTableSize,
686 &random_vector[RandomVector::kRandomTableSize]);
687 }
688 }
689
690 // Set up state vector and calculate scale factor for unvoiced filtering.
691 memcpy(parameters.ar_filter_state,
692 &(audio_history[signal_length - kUnvoicedLpcOrder]),
693 sizeof(int16_t) * kUnvoicedLpcOrder);
694 memcpy(unvoiced_vector - kUnvoicedLpcOrder,
695 &(audio_history[signal_length - 128 - kUnvoicedLpcOrder]),
696 sizeof(int16_t) * kUnvoicedLpcOrder);
697 WebRtcSpl_FilterMAFastQ12(
698 const_cast<int16_t*>(&audio_history[signal_length - 128]),
699 unvoiced_vector, parameters.ar_filter, kUnvoicedLpcOrder + 1, 128);
700 int16_t unvoiced_prescale;
701 if (WebRtcSpl_MaxAbsValueW16(unvoiced_vector, 128) > 4000) {
702 unvoiced_prescale = 4;
703 } else {
704 unvoiced_prescale = 0;
705 }
706 int32_t unvoiced_energy = WebRtcSpl_DotProductWithScale(unvoiced_vector,
707 unvoiced_vector,
708 128,
709 unvoiced_prescale);
710
711 // Normalize |unvoiced_energy| to 28 or 29 bits to preserve sqrt() accuracy.
712 int16_t unvoiced_scale = WebRtcSpl_NormW32(unvoiced_energy) - 3;
713 // Make sure we do an odd number of shifts since we already have 7 shifts
714 // from dividing with 128 earlier. This will make the total scale factor
715 // even, which is suitable for the sqrt.
716 unvoiced_scale += ((unvoiced_scale & 0x1) ^ 0x1);
717 unvoiced_energy = WEBRTC_SPL_SHIFT_W32(unvoiced_energy, unvoiced_scale);
718 int32_t unvoiced_gain = WebRtcSpl_SqrtFloor(unvoiced_energy);
719 parameters.ar_gain_scale = 13
720 + (unvoiced_scale + 7 - unvoiced_prescale) / 2;
721 parameters.ar_gain = unvoiced_gain;
722
723 // Calculate voice_mix_factor from corr_coefficient.
724 // Let x = corr_coefficient. Then, we compute:
725 // if (x > 0.48)
726 // voice_mix_factor = (-5179 + 19931x - 16422x^2 + 5776x^3) / 4096;
727 // else
728 // voice_mix_factor = 0;
729 if (corr_coefficient > 7875) {
730 int16_t x1, x2, x3;
731 x1 = corr_coefficient; // |corr_coefficient| is in Q14.
732 x2 = (x1 * x1) >> 14; // Shift 14 to keep result in Q14.
733 x3 = (x1 * x2) >> 14;
734 static const int kCoefficients[4] = { -5179, 19931, -16422, 5776 };
735 int32_t temp_sum = kCoefficients[0] << 14;
736 temp_sum += kCoefficients[1] * x1;
737 temp_sum += kCoefficients[2] * x2;
738 temp_sum += kCoefficients[3] * x3;
739 parameters.voice_mix_factor = temp_sum / 4096;
740 parameters.voice_mix_factor = std::min(parameters.voice_mix_factor,
741 static_cast<int16_t>(16384));
742 parameters.voice_mix_factor = std::max(parameters.voice_mix_factor,
743 static_cast<int16_t>(0));
744 } else {
745 parameters.voice_mix_factor = 0;
746 }
747
748 // Calculate muting slope. Reuse value from earlier scaling of
749 // |expand_vector0| and |expand_vector1|.
750 int16_t slope = amplitude_ratio;
751 if (slope > 12288) {
752 // slope > 1.5.
753 // Calculate (1 - (1 / slope)) / distortion_lag =
754 // (slope - 1) / (distortion_lag * slope).
755 // |slope| is in Q13, so 1 corresponds to 8192. Shift up to Q25 before
756 // the division.
757 // Shift the denominator from Q13 to Q5 before the division. The result of
758 // the division will then be in Q20.
759 int16_t temp_ratio = WebRtcSpl_DivW32W16((slope - 8192) << 12,
760 (distortion_lag * slope) >> 8);
761 if (slope > 14746) {
762 // slope > 1.8.
763 // Divide by 2, with proper rounding.
764 parameters.mute_slope = (temp_ratio + 1) / 2;
765 } else {
766 // Divide by 8, with proper rounding.
767 parameters.mute_slope = (temp_ratio + 4) / 8;
768 }
769 parameters.onset = true;
770 } else {
771 // Calculate (1 - slope) / distortion_lag.
772 // Shift |slope| by 7 to Q20 before the division. The result is in Q20.
773 parameters.mute_slope = WebRtcSpl_DivW32W16((8192 - slope) << 7,
774 distortion_lag);
775 if (parameters.voice_mix_factor <= 13107) {
776 // Make sure the mute factor decreases from 1.0 to 0.9 in no more than
777 // 6.25 ms.
778 // mute_slope >= 0.005 / fs_mult in Q20.
779 parameters.mute_slope = std::max(static_cast<int16_t>(5243 / fs_mult),
780 parameters.mute_slope);
781 } else if (slope > 8028) {
782 parameters.mute_slope = 0;
783 }
784 parameters.onset = false;
785 }
786 }
787}
788
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000789int16_t Expand::Correlation(const int16_t* input, size_t input_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000790 int16_t* output, int16_t* output_scale) const {
791 // Set parameters depending on sample rate.
792 const int16_t* filter_coefficients;
793 int16_t num_coefficients;
794 int16_t downsampling_factor;
795 if (fs_hz_ == 8000) {
796 num_coefficients = 3;
797 downsampling_factor = 2;
798 filter_coefficients = DspHelper::kDownsample8kHzTbl;
799 } else if (fs_hz_ == 16000) {
800 num_coefficients = 5;
801 downsampling_factor = 4;
802 filter_coefficients = DspHelper::kDownsample16kHzTbl;
803 } else if (fs_hz_ == 32000) {
804 num_coefficients = 7;
805 downsampling_factor = 8;
806 filter_coefficients = DspHelper::kDownsample32kHzTbl;
807 } else { // fs_hz_ == 48000.
808 num_coefficients = 7;
809 downsampling_factor = 12;
810 filter_coefficients = DspHelper::kDownsample48kHzTbl;
811 }
812
813 // Correlate from lag 10 to lag 60 in downsampled domain.
814 // (Corresponds to 20-120 for narrow-band, 40-240 for wide-band, and so on.)
815 static const int kCorrelationStartLag = 10;
816 static const int kNumCorrelationLags = 54;
817 static const int kCorrelationLength = 60;
818 // Downsample to 4 kHz sample rate.
819 static const int kDownsampledLength = kCorrelationStartLag
820 + kNumCorrelationLags + kCorrelationLength;
821 int16_t downsampled_input[kDownsampledLength];
822 static const int kFilterDelay = 0;
823 WebRtcSpl_DownsampleFast(
824 input + input_length - kDownsampledLength * downsampling_factor,
825 kDownsampledLength * downsampling_factor, downsampled_input,
826 kDownsampledLength, filter_coefficients, num_coefficients,
827 downsampling_factor, kFilterDelay);
828
829 // Normalize |downsampled_input| to using all 16 bits.
830 int16_t max_value = WebRtcSpl_MaxAbsValueW16(downsampled_input,
831 kDownsampledLength);
832 int16_t norm_shift = 16 - WebRtcSpl_NormW32(max_value);
833 WebRtcSpl_VectorBitShiftW16(downsampled_input, kDownsampledLength,
834 downsampled_input, norm_shift);
835
836 int32_t correlation[kNumCorrelationLags];
837 static const int kCorrelationShift = 6;
838 WebRtcSpl_CrossCorrelation(
839 correlation,
840 &downsampled_input[kDownsampledLength - kCorrelationLength],
841 &downsampled_input[kDownsampledLength - kCorrelationLength
842 - kCorrelationStartLag],
843 kCorrelationLength, kNumCorrelationLags, kCorrelationShift, -1);
844
845 // Normalize and move data from 32-bit to 16-bit vector.
846 int32_t max_correlation = WebRtcSpl_MaxAbsValueW32(correlation,
847 kNumCorrelationLags);
848 int16_t norm_shift2 = std::max(18 - WebRtcSpl_NormW32(max_correlation), 0);
849 WebRtcSpl_VectorBitShiftW32ToW16(output, kNumCorrelationLags, correlation,
850 norm_shift2);
851 // Total scale factor (right shifts) of correlation value.
852 *output_scale = 2 * norm_shift + kCorrelationShift + norm_shift2;
853 return kNumCorrelationLags;
854}
855
856void Expand::UpdateLagIndex() {
857 current_lag_index_ = current_lag_index_ + lag_index_direction_;
858 // Change direction if needed.
859 if (current_lag_index_ <= 0) {
860 lag_index_direction_ = 1;
861 }
862 if (current_lag_index_ >= kNumLags - 1) {
863 lag_index_direction_ = -1;
864 }
865}
866
867} // namespace webrtc