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