• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <iostream>
18 #include <vector>
19 
20 constexpr int kMinLoopLimitValue = 1;
21 constexpr int kNumPeaks = 3;
22 
23 /*!
24   \brief           Compute the length normalized correlation of two signals
25 
26   \sigX            Pointer to signal 1
27   \sigY            Pointer to signal 2
28   \len             Length of signals
29   \enableCrossCorr Flag to be set to 1 if cross-correlation is needed
30 
31   \return          First value is vector of correlation peak indices
32                    Second value is vector of correlation peak values
33 */
34 
correlation(const int16_t * sigX,const int16_t * sigY,int len,int16_t enableCrossCorr)35 static std::pair<std::vector<int>, std::vector<float>> correlation(const int16_t* sigX,
36                                                                    const int16_t* sigY, int len,
37                                                                    int16_t enableCrossCorr) {
38     float maxCorrVal = 0.f, prevCorrVal = 0.f;
39     int delay = 0, peakIndex = 0, flag = 0;
40     int loopLim = (1 == enableCrossCorr) ? len : kMinLoopLimitValue;
41     std::vector<int> peakIndexVect(kNumPeaks, 0);
42     std::vector<float> peakValueVect(kNumPeaks, 0.f);
43     for (int i = 0; i < loopLim; i++) {
44         float corrVal = 0.f;
45         for (int j = i; j < len; j++) {
46             corrVal += (float)(sigX[j] * sigY[j - i]);
47         }
48         corrVal /= len - i;
49         if (corrVal > maxCorrVal) {
50             delay = i;
51             maxCorrVal = corrVal;
52         }
53         // Correlation peaks are expected to be observed at equal intervals. The interval length is
54         // expected to match with wave period.
55         // The following block of code saves the first kNumPeaks number of peaks and the index at
56         // which they occur.
57         if (peakIndex < kNumPeaks) {
58             if (corrVal > prevCorrVal) {
59                 peakIndexVect[peakIndex] = i;
60                 peakValueVect[peakIndex] = corrVal;
61                 flag = 0;
62             } else if (0 == flag) {
63                 peakIndex++;
64                 flag = 1;
65             }
66         }
67         if (peakIndex == kNumPeaks) break;
68         prevCorrVal = corrVal;
69     }
70     return {peakIndexVect, peakValueVect};
71 }
72 
printUsage()73 void printUsage() {
74     printf("\nUsage: ");
75     printf("\n     correlation <firstFile> <secondFile> [enableCrossCorr]\n");
76     printf("\nwhere, \n     <firstFile>       is the first file name");
77     printf("\n     <secondFile>      is the second file name");
78     printf("\n     [enableCrossCorr] is flag to set for cross-correlation (Default 1)\n\n");
79 }
80 
main(int argc,const char * argv[])81 int main(int argc, const char* argv[]) {
82     if (argc < 3) {
83         printUsage();
84         return EXIT_FAILURE;
85     }
86 
87     std::unique_ptr<FILE, decltype(&fclose)> fInput1(fopen(argv[1], "rb"), &fclose);
88     if (fInput1.get() == NULL) {
89         printf("\nError: missing file %s\n", argv[1]);
90         return EXIT_FAILURE;
91     }
92     std::unique_ptr<FILE, decltype(&fclose)> fInput2(fopen(argv[2], "rb"), &fclose);
93     if (fInput2.get() == NULL) {
94         printf("\nError: missing file %s\n", argv[2]);
95         return EXIT_FAILURE;
96     }
97     int16_t enableCrossCorr = (4 == argc) ? atoi(argv[3]) : 1;
98 
99     fseek(fInput1.get(), 0L, SEEK_END);
100     unsigned int fileSize1 = ftell(fInput1.get());
101     rewind(fInput1.get());
102     fseek(fInput2.get(), 0L, SEEK_END);
103     unsigned int fileSize2 = ftell(fInput2.get());
104     rewind(fInput2.get());
105     if (fileSize1 != fileSize2) {
106         printf("\nError: File sizes different\n");
107         return EXIT_FAILURE;
108     }
109 
110     size_t numFrames = fileSize1 / sizeof(int16_t);
111     std::unique_ptr<int16_t[]> inBuffer1(new int16_t[numFrames]());
112     std::unique_ptr<int16_t[]> inBuffer2(new int16_t[numFrames]());
113 
114     if (numFrames != fread(inBuffer1.get(), sizeof(int16_t), numFrames, fInput1.get())) {
115         printf("\nError: Unable to read %zu samples from file %s\n", numFrames, argv[1]);
116         return EXIT_FAILURE;
117     }
118 
119     if (numFrames != fread(inBuffer2.get(), sizeof(int16_t), numFrames, fInput2.get())) {
120         printf("\nError: Unable to read %zu samples from file %s\n", numFrames, argv[2]);
121         return EXIT_FAILURE;
122     }
123 
124     auto pairAutoCorr1 = correlation(inBuffer1.get(), inBuffer1.get(), numFrames, enableCrossCorr);
125     auto pairAutoCorr2 = correlation(inBuffer2.get(), inBuffer2.get(), numFrames, enableCrossCorr);
126 
127     // Following code block checks pitch period difference between two input signals. They must
128     // match as AGC applies only gain, no frequency related computation is done.
129     bool pitchMatch = false;
130     for (unsigned i = 0; i < pairAutoCorr1.first.size() - 1; i++) {
131         if (pairAutoCorr1.first[i + 1] - pairAutoCorr1.first[i] !=
132             pairAutoCorr2.first[i + 1] - pairAutoCorr2.first[i]) {
133             pitchMatch = false;
134             break;
135         }
136         pitchMatch = true;
137     }
138     if (pitchMatch) {
139         printf("Auto-correlation  : Pitch matched\n");
140     } else {
141         printf("Auto-correlation  : Pitch mismatch\n");
142         return EXIT_FAILURE;
143     }
144 
145     if (enableCrossCorr) {
146         auto pairCrossCorr =
147                 correlation(inBuffer1.get(), inBuffer2.get(), numFrames, enableCrossCorr);
148 
149         // Since AGC applies only gain, the pitch information obtained from cross correlation data
150         // of input and output is expected to be same as the input signal's pitch information.
151         pitchMatch = false;
152         for (unsigned i = 0; i < pairCrossCorr.first.size() - 1; i++) {
153             if (pairAutoCorr1.first[i + 1] - pairAutoCorr1.first[i] !=
154                 pairCrossCorr.first[i + 1] - pairCrossCorr.first[i]) {
155                 pitchMatch = false;
156                 break;
157             }
158             pitchMatch = true;
159         }
160         if (pitchMatch) {
161             printf("Cross-correlation : Pitch matched for AGC\n");
162             if (pairAutoCorr1.second[0]) {
163                 printf("Expected gain     : (maxCrossCorr / maxAutoCorr1) = %f\n",
164                        pairCrossCorr.second[0] / pairAutoCorr1.second[0]);
165             }
166         } else {
167             printf("Cross-correlation : Pitch mismatch\n");
168             return EXIT_FAILURE;
169         }
170     }
171 
172     return EXIT_SUCCESS;
173 }
174