xref: /aosp_15_r20/external/webrtc/modules/audio_coding/neteq/cross_correlation.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2016 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/cross_correlation.h"
12 
13 #include <cstdlib>
14 #include <limits>
15 
16 #include "common_audio/signal_processing/include/signal_processing_library.h"
17 
18 namespace webrtc {
19 
20 // This function decides the overflow-protecting scaling and calls
21 // WebRtcSpl_CrossCorrelation.
CrossCorrelationWithAutoShift(const int16_t * sequence_1,const int16_t * sequence_2,size_t sequence_1_length,size_t cross_correlation_length,int cross_correlation_step,int32_t * cross_correlation)22 int CrossCorrelationWithAutoShift(const int16_t* sequence_1,
23                                   const int16_t* sequence_2,
24                                   size_t sequence_1_length,
25                                   size_t cross_correlation_length,
26                                   int cross_correlation_step,
27                                   int32_t* cross_correlation) {
28   // Find the element that has the maximum absolute value of sequence_1 and 2.
29   // Note that these values may be negative.
30   const int16_t max_1 =
31       WebRtcSpl_MaxAbsElementW16(sequence_1, sequence_1_length);
32   const int sequence_2_shift =
33       cross_correlation_step * (static_cast<int>(cross_correlation_length) - 1);
34   const int16_t* sequence_2_start =
35       sequence_2_shift >= 0 ? sequence_2 : sequence_2 + sequence_2_shift;
36   const size_t sequence_2_length =
37       sequence_1_length + std::abs(sequence_2_shift);
38   const int16_t max_2 =
39       WebRtcSpl_MaxAbsElementW16(sequence_2_start, sequence_2_length);
40 
41   // In order to avoid overflow when computing the sum we should scale the
42   // samples so that (in_vector_length * max_1 * max_2) will not overflow.
43   const int64_t max_value =
44       abs(max_1 * max_2) * static_cast<int64_t>(sequence_1_length);
45   const int32_t factor = max_value >> 31;
46   const int scaling = factor == 0 ? 0 : 31 - WebRtcSpl_NormW32(factor);
47 
48   WebRtcSpl_CrossCorrelation(cross_correlation, sequence_1, sequence_2,
49                              sequence_1_length, cross_correlation_length,
50                              scaling, cross_correlation_step);
51 
52   return scaling;
53 }
54 
55 }  // namespace webrtc
56