1 /*
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 "modules/audio_coding/neteq/merge.h"
12
13 #include <assert.h>
14 #include <string.h> // memmove, memcpy, memset, size_t
15
16 #include <algorithm> // min, max
17 #include <memory>
18
19 #include "common_audio/signal_processing/include/signal_processing_library.h"
20 #include "modules/audio_coding/neteq/audio_multi_vector.h"
21 #include "modules/audio_coding/neteq/cross_correlation.h"
22 #include "modules/audio_coding/neteq/dsp_helper.h"
23 #include "modules/audio_coding/neteq/expand.h"
24 #include "modules/audio_coding/neteq/sync_buffer.h"
25 #include "rtc_base/numerics/safe_conversions.h"
26 #include "rtc_base/numerics/safe_minmax.h"
27
28 namespace webrtc {
29
Merge(int fs_hz,size_t num_channels,Expand * expand,SyncBuffer * sync_buffer)30 Merge::Merge(int fs_hz,
31 size_t num_channels,
32 Expand* expand,
33 SyncBuffer* sync_buffer)
34 : fs_hz_(fs_hz),
35 num_channels_(num_channels),
36 fs_mult_(fs_hz_ / 8000),
37 timestamps_per_call_(static_cast<size_t>(fs_hz_ / 100)),
38 expand_(expand),
39 sync_buffer_(sync_buffer),
40 expanded_(num_channels_) {
41 assert(num_channels_ > 0);
42 }
43
44 Merge::~Merge() = default;
45
Process(int16_t * input,size_t input_length,AudioMultiVector * output)46 size_t Merge::Process(int16_t* input,
47 size_t input_length,
48 AudioMultiVector* output) {
49 // TODO(hlundin): Change to an enumerator and skip assert.
50 assert(fs_hz_ == 8000 || fs_hz_ == 16000 || fs_hz_ == 32000 ||
51 fs_hz_ == 48000);
52 assert(fs_hz_ <= kMaxSampleRate); // Should not be possible.
53
54 size_t old_length;
55 size_t expand_period;
56 // Get expansion data to overlap and mix with.
57 size_t expanded_length = GetExpandedSignal(&old_length, &expand_period);
58
59 // Transfer input signal to an AudioMultiVector.
60 AudioMultiVector input_vector(num_channels_);
61 input_vector.PushBackInterleaved(
62 rtc::ArrayView<const int16_t>(input, input_length));
63 size_t input_length_per_channel = input_vector.Size();
64 assert(input_length_per_channel == input_length / num_channels_);
65
66 size_t best_correlation_index = 0;
67 size_t output_length = 0;
68
69 std::unique_ptr<int16_t[]> input_channel(
70 new int16_t[input_length_per_channel]);
71 std::unique_ptr<int16_t[]> expanded_channel(new int16_t[expanded_length]);
72 for (size_t channel = 0; channel < num_channels_; ++channel) {
73 input_vector[channel].CopyTo(input_length_per_channel, 0,
74 input_channel.get());
75 expanded_[channel].CopyTo(expanded_length, 0, expanded_channel.get());
76
77 const int16_t new_mute_factor = std::min<int16_t>(
78 16384, SignalScaling(input_channel.get(), input_length_per_channel,
79 expanded_channel.get()));
80
81 if (channel == 0) {
82 // Downsample, correlate, and find strongest correlation period for the
83 // reference (i.e., first) channel only.
84 // Downsample to 4kHz sample rate.
85 Downsample(input_channel.get(), input_length_per_channel,
86 expanded_channel.get(), expanded_length);
87
88 // Calculate the lag of the strongest correlation period.
89 best_correlation_index = CorrelateAndPeakSearch(
90 old_length, input_length_per_channel, expand_period);
91 }
92
93 temp_data_.resize(input_length_per_channel + best_correlation_index);
94 int16_t* decoded_output = temp_data_.data() + best_correlation_index;
95
96 // Mute the new decoded data if needed (and unmute it linearly).
97 // This is the overlapping part of expanded_signal.
98 size_t interpolation_length =
99 std::min(kMaxCorrelationLength * fs_mult_,
100 expanded_length - best_correlation_index);
101 interpolation_length =
102 std::min(interpolation_length, input_length_per_channel);
103
104 RTC_DCHECK_LE(new_mute_factor, 16384);
105 int16_t mute_factor =
106 std::max(expand_->MuteFactor(channel), new_mute_factor);
107 RTC_DCHECK_GE(mute_factor, 0);
108
109 if (mute_factor < 16384) {
110 // Set a suitable muting slope (Q20). 0.004 for NB, 0.002 for WB,
111 // and so on, or as fast as it takes to come back to full gain within the
112 // frame length.
113 const int back_to_fullscale_inc = static_cast<int>(
114 ((16384 - mute_factor) << 6) / input_length_per_channel);
115 const int increment = std::max(4194 / fs_mult_, back_to_fullscale_inc);
116 mute_factor = static_cast<int16_t>(DspHelper::RampSignal(
117 input_channel.get(), interpolation_length, mute_factor, increment));
118 DspHelper::UnmuteSignal(&input_channel[interpolation_length],
119 input_length_per_channel - interpolation_length,
120 &mute_factor, increment,
121 &decoded_output[interpolation_length]);
122 } else {
123 // No muting needed.
124 memmove(
125 &decoded_output[interpolation_length],
126 &input_channel[interpolation_length],
127 sizeof(int16_t) * (input_length_per_channel - interpolation_length));
128 }
129
130 // Do overlap and mix linearly.
131 int16_t increment =
132 static_cast<int16_t>(16384 / (interpolation_length + 1)); // In Q14.
133 int16_t local_mute_factor = 16384 - increment;
134 memmove(temp_data_.data(), expanded_channel.get(),
135 sizeof(int16_t) * best_correlation_index);
136 DspHelper::CrossFade(&expanded_channel[best_correlation_index],
137 input_channel.get(), interpolation_length,
138 &local_mute_factor, increment, decoded_output);
139
140 output_length = best_correlation_index + input_length_per_channel;
141 if (channel == 0) {
142 assert(output->Empty()); // Output should be empty at this point.
143 output->AssertSize(output_length);
144 } else {
145 assert(output->Size() == output_length);
146 }
147 (*output)[channel].OverwriteAt(temp_data_.data(), output_length, 0);
148 }
149
150 // Copy back the first part of the data to |sync_buffer_| and remove it from
151 // |output|.
152 sync_buffer_->ReplaceAtIndex(*output, old_length, sync_buffer_->next_index());
153 output->PopFront(old_length);
154
155 // Return new added length. |old_length| samples were borrowed from
156 // |sync_buffer_|.
157 RTC_DCHECK_GE(output_length, old_length);
158 return output_length - old_length;
159 }
160
GetExpandedSignal(size_t * old_length,size_t * expand_period)161 size_t Merge::GetExpandedSignal(size_t* old_length, size_t* expand_period) {
162 // Check how much data that is left since earlier.
163 *old_length = sync_buffer_->FutureLength();
164 // Should never be less than overlap_length.
165 assert(*old_length >= expand_->overlap_length());
166 // Generate data to merge the overlap with using expand.
167 expand_->SetParametersForMergeAfterExpand();
168
169 if (*old_length >= 210 * kMaxSampleRate / 8000) {
170 // TODO(hlundin): Write test case for this.
171 // The number of samples available in the sync buffer is more than what fits
172 // in expanded_signal. Keep the first 210 * kMaxSampleRate / 8000 samples,
173 // but shift them towards the end of the buffer. This is ok, since all of
174 // the buffer will be expand data anyway, so as long as the beginning is
175 // left untouched, we're fine.
176 size_t length_diff = *old_length - 210 * kMaxSampleRate / 8000;
177 sync_buffer_->InsertZerosAtIndex(length_diff, sync_buffer_->next_index());
178 *old_length = 210 * kMaxSampleRate / 8000;
179 // This is the truncated length.
180 }
181 // This assert should always be true thanks to the if statement above.
182 assert(210 * kMaxSampleRate / 8000 >= *old_length);
183
184 AudioMultiVector expanded_temp(num_channels_);
185 expand_->Process(&expanded_temp);
186 *expand_period = expanded_temp.Size(); // Samples per channel.
187
188 expanded_.Clear();
189 // Copy what is left since earlier into the expanded vector.
190 expanded_.PushBackFromIndex(*sync_buffer_, sync_buffer_->next_index());
191 assert(expanded_.Size() == *old_length);
192 assert(expanded_temp.Size() > 0);
193 // Do "ugly" copy and paste from the expanded in order to generate more data
194 // to correlate (but not interpolate) with.
195 const size_t required_length = static_cast<size_t>((120 + 80 + 2) * fs_mult_);
196 if (expanded_.Size() < required_length) {
197 while (expanded_.Size() < required_length) {
198 // Append one more pitch period each time.
199 expanded_.PushBack(expanded_temp);
200 }
201 // Trim the length to exactly |required_length|.
202 expanded_.PopBack(expanded_.Size() - required_length);
203 }
204 assert(expanded_.Size() >= required_length);
205 return required_length;
206 }
207
SignalScaling(const int16_t * input,size_t input_length,const int16_t * expanded_signal) const208 int16_t Merge::SignalScaling(const int16_t* input,
209 size_t input_length,
210 const int16_t* expanded_signal) const {
211 // Adjust muting factor if new vector is more or less of the BGN energy.
212 const auto mod_input_length = rtc::SafeMin<size_t>(
213 64 * rtc::dchecked_cast<size_t>(fs_mult_), input_length);
214 const int16_t expanded_max =
215 WebRtcSpl_MaxAbsValueW16(expanded_signal, mod_input_length);
216 int32_t factor =
217 (expanded_max * expanded_max) / (std::numeric_limits<int32_t>::max() /
218 static_cast<int32_t>(mod_input_length));
219 const int expanded_shift = factor == 0 ? 0 : 31 - WebRtcSpl_NormW32(factor);
220 int32_t energy_expanded = WebRtcSpl_DotProductWithScale(
221 expanded_signal, expanded_signal, mod_input_length, expanded_shift);
222
223 // Calculate energy of input signal.
224 const int16_t input_max = WebRtcSpl_MaxAbsValueW16(input, mod_input_length);
225 factor = (input_max * input_max) / (std::numeric_limits<int32_t>::max() /
226 static_cast<int32_t>(mod_input_length));
227 const int input_shift = factor == 0 ? 0 : 31 - WebRtcSpl_NormW32(factor);
228 int32_t energy_input = WebRtcSpl_DotProductWithScale(
229 input, input, mod_input_length, input_shift);
230
231 // Align to the same Q-domain.
232 if (input_shift > expanded_shift) {
233 energy_expanded = energy_expanded >> (input_shift - expanded_shift);
234 } else {
235 energy_input = energy_input >> (expanded_shift - input_shift);
236 }
237
238 // Calculate muting factor to use for new frame.
239 int16_t mute_factor;
240 if (energy_input > energy_expanded) {
241 // Normalize |energy_input| to 14 bits.
242 int16_t temp_shift = WebRtcSpl_NormW32(energy_input) - 17;
243 energy_input = WEBRTC_SPL_SHIFT_W32(energy_input, temp_shift);
244 // Put |energy_expanded| in a domain 14 higher, so that
245 // energy_expanded / energy_input is in Q14.
246 energy_expanded = WEBRTC_SPL_SHIFT_W32(energy_expanded, temp_shift + 14);
247 // Calculate sqrt(energy_expanded / energy_input) in Q14.
248 mute_factor = static_cast<int16_t>(
249 WebRtcSpl_SqrtFloor((energy_expanded / energy_input) << 14));
250 } else {
251 // Set to 1 (in Q14) when |expanded| has higher energy than |input|.
252 mute_factor = 16384;
253 }
254
255 return mute_factor;
256 }
257
258 // TODO(hlundin): There are some parameter values in this method that seem
259 // strange. Compare with Expand::Correlation.
Downsample(const int16_t * input,size_t input_length,const int16_t * expanded_signal,size_t expanded_length)260 void Merge::Downsample(const int16_t* input,
261 size_t input_length,
262 const int16_t* expanded_signal,
263 size_t expanded_length) {
264 const int16_t* filter_coefficients;
265 size_t num_coefficients;
266 int decimation_factor = fs_hz_ / 4000;
267 static const size_t kCompensateDelay = 0;
268 size_t length_limit = static_cast<size_t>(fs_hz_ / 100); // 10 ms in samples.
269 if (fs_hz_ == 8000) {
270 filter_coefficients = DspHelper::kDownsample8kHzTbl;
271 num_coefficients = 3;
272 } else if (fs_hz_ == 16000) {
273 filter_coefficients = DspHelper::kDownsample16kHzTbl;
274 num_coefficients = 5;
275 } else if (fs_hz_ == 32000) {
276 filter_coefficients = DspHelper::kDownsample32kHzTbl;
277 num_coefficients = 7;
278 } else { // fs_hz_ == 48000
279 filter_coefficients = DspHelper::kDownsample48kHzTbl;
280 num_coefficients = 7;
281 }
282 size_t signal_offset = num_coefficients - 1;
283 WebRtcSpl_DownsampleFast(
284 &expanded_signal[signal_offset], expanded_length - signal_offset,
285 expanded_downsampled_, kExpandDownsampLength, filter_coefficients,
286 num_coefficients, decimation_factor, kCompensateDelay);
287 if (input_length <= length_limit) {
288 // Not quite long enough, so we have to cheat a bit.
289 // If the input is shorter than the offset, we consider the input to be 0
290 // length. This will cause us to skip the downsampling since it makes no
291 // sense anyway, and input_downsampled_ will be filled with zeros. This is
292 // clearly a pathological case, and the signal quality will suffer, but
293 // there is not much we can do.
294 const size_t temp_len =
295 input_length > signal_offset ? input_length - signal_offset : 0;
296 // TODO(hlundin): Should |downsamp_temp_len| be corrected for round-off
297 // errors? I.e., (temp_len + decimation_factor - 1) / decimation_factor?
298 size_t downsamp_temp_len = temp_len / decimation_factor;
299 if (downsamp_temp_len > 0) {
300 WebRtcSpl_DownsampleFast(&input[signal_offset], temp_len,
301 input_downsampled_, downsamp_temp_len,
302 filter_coefficients, num_coefficients,
303 decimation_factor, kCompensateDelay);
304 }
305 memset(&input_downsampled_[downsamp_temp_len], 0,
306 sizeof(int16_t) * (kInputDownsampLength - downsamp_temp_len));
307 } else {
308 WebRtcSpl_DownsampleFast(
309 &input[signal_offset], input_length - signal_offset, input_downsampled_,
310 kInputDownsampLength, filter_coefficients, num_coefficients,
311 decimation_factor, kCompensateDelay);
312 }
313 }
314
CorrelateAndPeakSearch(size_t start_position,size_t input_length,size_t expand_period) const315 size_t Merge::CorrelateAndPeakSearch(size_t start_position,
316 size_t input_length,
317 size_t expand_period) const {
318 // Calculate correlation without any normalization.
319 const size_t max_corr_length = kMaxCorrelationLength;
320 size_t stop_position_downsamp =
321 std::min(max_corr_length, expand_->max_lag() / (fs_mult_ * 2) + 1);
322
323 int32_t correlation[kMaxCorrelationLength];
324 CrossCorrelationWithAutoShift(input_downsampled_, expanded_downsampled_,
325 kInputDownsampLength, stop_position_downsamp, 1,
326 correlation);
327
328 // Normalize correlation to 14 bits and copy to a 16-bit array.
329 const size_t pad_length = expand_->overlap_length() - 1;
330 const size_t correlation_buffer_size = 2 * pad_length + kMaxCorrelationLength;
331 std::unique_ptr<int16_t[]> correlation16(
332 new int16_t[correlation_buffer_size]);
333 memset(correlation16.get(), 0, correlation_buffer_size * sizeof(int16_t));
334 int16_t* correlation_ptr = &correlation16[pad_length];
335 int32_t max_correlation =
336 WebRtcSpl_MaxAbsValueW32(correlation, stop_position_downsamp);
337 int norm_shift = std::max(0, 17 - WebRtcSpl_NormW32(max_correlation));
338 WebRtcSpl_VectorBitShiftW32ToW16(correlation_ptr, stop_position_downsamp,
339 correlation, norm_shift);
340
341 // Calculate allowed starting point for peak finding.
342 // The peak location bestIndex must fulfill two criteria:
343 // (1) w16_bestIndex + input_length <
344 // timestamps_per_call_ + expand_->overlap_length();
345 // (2) w16_bestIndex + input_length < start_position.
346 size_t start_index = timestamps_per_call_ + expand_->overlap_length();
347 start_index = std::max(start_position, start_index);
348 start_index = (input_length > start_index) ? 0 : (start_index - input_length);
349 // Downscale starting index to 4kHz domain. (fs_mult_ * 2 = fs_hz_ / 4000.)
350 size_t start_index_downsamp = start_index / (fs_mult_ * 2);
351
352 // Calculate a modified |stop_position_downsamp| to account for the increased
353 // start index |start_index_downsamp| and the effective array length.
354 size_t modified_stop_pos =
355 std::min(stop_position_downsamp,
356 kMaxCorrelationLength + pad_length - start_index_downsamp);
357 size_t best_correlation_index;
358 int16_t best_correlation;
359 static const size_t kNumCorrelationCandidates = 1;
360 DspHelper::PeakDetection(&correlation_ptr[start_index_downsamp],
361 modified_stop_pos, kNumCorrelationCandidates,
362 fs_mult_, &best_correlation_index,
363 &best_correlation);
364 // Compensate for modified start index.
365 best_correlation_index += start_index;
366
367 // Ensure that underrun does not occur for 10ms case => we have to get at
368 // least 10ms + overlap . (This should never happen thanks to the above
369 // modification of peak-finding starting point.)
370 while (((best_correlation_index + input_length) <
371 (timestamps_per_call_ + expand_->overlap_length())) ||
372 ((best_correlation_index + input_length) < start_position)) {
373 assert(false); // Should never happen.
374 best_correlation_index += expand_period; // Jump one lag ahead.
375 }
376 return best_correlation_index;
377 }
378
RequiredFutureSamples()379 size_t Merge::RequiredFutureSamples() {
380 return fs_hz_ / 100 * num_channels_; // 10 ms.
381 }
382
383 } // namespace webrtc
384