blob: 9ddcb5ddb8dfcc88aaf9272cffb898ee29c42944 [file] [log] [blame]
alexander3c798932021-03-26 21:42:19 +00001/*
2 * Copyright (c) 2021 Arm Limited. All rights reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17#include "Mfcc.hpp"
18
19#include "PlatformMath.hpp"
20
21#include <cfloat>
22
23namespace arm {
24namespace app {
25namespace audio {
26
27 MfccParams::MfccParams(
28 const float samplingFreq,
29 const uint32_t numFbankBins,
30 const float melLoFreq,
31 const float melHiFreq,
32 const uint32_t numMfccFeats,
33 const uint32_t frameLen,
34 const bool useHtkMethod):
35 m_samplingFreq(samplingFreq),
36 m_numFbankBins(numFbankBins),
37 m_melLoFreq(melLoFreq),
38 m_melHiFreq(melHiFreq),
39 m_numMfccFeatures(numMfccFeats),
40 m_frameLen(frameLen),
41
42 /* Smallest power of 2 >= frame length. */
43 m_frameLenPadded(pow(2, ceil((log(frameLen)/log(2))))),
44 m_useHtkMethod(useHtkMethod)
45 {}
46
alexanderc350cdc2021-04-29 20:36:09 +010047 std::string MfccParams::Str() const
alexander3c798932021-03-26 21:42:19 +000048 {
49 char strC[1024];
50 snprintf(strC, sizeof(strC) - 1, "\n \
51 \n\t Sampling frequency: %f\
52 \n\t Number of filter banks: %u\
53 \n\t Mel frequency limit (low): %f\
54 \n\t Mel frequency limit (high): %f\
55 \n\t Number of MFCC features: %u\
56 \n\t Frame length: %u\
57 \n\t Padded frame length: %u\
58 \n\t Using HTK for Mel scale: %s\n",
59 this->m_samplingFreq, this->m_numFbankBins, this->m_melLoFreq,
60 this->m_melHiFreq, this->m_numMfccFeatures, this->m_frameLen,
61 this->m_frameLenPadded, this->m_useHtkMethod ? "yes" : "no");
62 return std::string{strC};
63 }
64
65 MFCC::MFCC(const MfccParams& params):
66 _m_params(params),
67 _m_filterBankInitialised(false)
68 {
69 this->_m_buffer = std::vector<float>(
70 this->_m_params.m_frameLenPadded, 0.0);
71 this->_m_frame = std::vector<float>(
72 this->_m_params.m_frameLenPadded, 0.0);
73 this->_m_melEnergies = std::vector<float>(
74 this->_m_params.m_numFbankBins, 0.0);
75
76 this->_m_windowFunc = std::vector<float>(this->_m_params.m_frameLen);
alexanderc350cdc2021-04-29 20:36:09 +010077 const auto multiplier = static_cast<float>(2 * M_PI / this->_m_params.m_frameLen);
alexander3c798932021-03-26 21:42:19 +000078
79 /* Create window function. */
80 for (size_t i = 0; i < this->_m_params.m_frameLen; i++) {
81 this->_m_windowFunc[i] = (0.5 - (0.5 *
82 math::MathUtils::CosineF32(static_cast<float>(i) * multiplier)));
83 }
84
85 math::MathUtils::FftInitF32(this->_m_params.m_frameLenPadded, this->_m_fftInstance);
86 debug("Instantiated MFCC object: %s\n", this->_m_params.Str().c_str());
87 }
88
89 void MFCC::Init()
90 {
alexanderc350cdc2021-04-29 20:36:09 +010091 this->InitMelFilterBank();
alexander3c798932021-03-26 21:42:19 +000092 }
93
94 float MFCC::MelScale(const float freq, const bool useHTKMethod)
95 {
96 if (useHTKMethod) {
97 return 1127.0f * logf (1.0f + freq / 700.0f);
98 } else {
99 /* Slaney formula for mel scale. */
100
101 float mel = freq / ms_freqStep;
102
103 if (freq >= ms_minLogHz) {
104 mel = ms_minLogMel + logf(freq / ms_minLogHz) / ms_logStep;
105 }
106 return mel;
107 }
108 }
109
110 float MFCC::InverseMelScale(const float melFreq, const bool useHTKMethod)
111 {
112 if (useHTKMethod) {
113 return 700.0f * (expf (melFreq / 1127.0f) - 1.0f);
114 } else {
115 /* Slaney formula for mel scale. */
116 float freq = ms_freqStep * melFreq;
117
118 if (melFreq >= ms_minLogMel) {
119 freq = ms_minLogHz * expf(ms_logStep * (melFreq - ms_minLogMel));
120 }
121 return freq;
122 }
123 }
124
125
126 bool MFCC::ApplyMelFilterBank(
127 std::vector<float>& fftVec,
128 std::vector<std::vector<float>>& melFilterBank,
alexanderc350cdc2021-04-29 20:36:09 +0100129 std::vector<uint32_t>& filterBankFilterFirst,
130 std::vector<uint32_t>& filterBankFilterLast,
alexander3c798932021-03-26 21:42:19 +0000131 std::vector<float>& melEnergies)
132 {
133 const size_t numBanks = melEnergies.size();
134
135 if (numBanks != filterBankFilterFirst.size() ||
136 numBanks != filterBankFilterLast.size()) {
137 printf_err("unexpected filter bank lengths\n");
138 return false;
139 }
140
141 for (size_t bin = 0; bin < numBanks; ++bin) {
142 auto filterBankIter = melFilterBank[bin].begin();
alexanderc350cdc2021-04-29 20:36:09 +0100143 auto end = melFilterBank[bin].end();
alexander3c798932021-03-26 21:42:19 +0000144 float melEnergy = FLT_MIN; /* Avoid log of zero at later stages */
alexanderc350cdc2021-04-29 20:36:09 +0100145 const uint32_t firstIndex = filterBankFilterFirst[bin];
146 const uint32_t lastIndex = std::min<uint32_t>(filterBankFilterLast[bin], fftVec.size() - 1);
alexander3c798932021-03-26 21:42:19 +0000147
alexanderc350cdc2021-04-29 20:36:09 +0100148 for (uint32_t i = firstIndex; i <= lastIndex && filterBankIter != end; i++) {
alexander3c798932021-03-26 21:42:19 +0000149 float energyRep = math::MathUtils::SqrtF32(fftVec[i]);
150 melEnergy += (*filterBankIter++ * energyRep);
151 }
152
153 melEnergies[bin] = melEnergy;
154 }
155
156 return true;
157 }
158
159 void MFCC::ConvertToLogarithmicScale(std::vector<float>& melEnergies)
160 {
alexanderc350cdc2021-04-29 20:36:09 +0100161 for (float& melEnergy : melEnergies) {
162 melEnergy = logf(melEnergy);
alexander3c798932021-03-26 21:42:19 +0000163 }
164 }
165
alexanderc350cdc2021-04-29 20:36:09 +0100166 void MFCC::ConvertToPowerSpectrum()
alexander3c798932021-03-26 21:42:19 +0000167 {
alexanderc350cdc2021-04-29 20:36:09 +0100168 const uint32_t halfDim = this->_m_buffer.size() / 2;
alexander3c798932021-03-26 21:42:19 +0000169
170 /* Handle this special case. */
171 float firstEnergy = this->_m_buffer[0] * this->_m_buffer[0];
172 float lastEnergy = this->_m_buffer[1] * this->_m_buffer[1];
173
174 math::MathUtils::ComplexMagnitudeSquaredF32(
175 this->_m_buffer.data(),
176 this->_m_buffer.size(),
177 this->_m_buffer.data(),
178 this->_m_buffer.size()/2);
179
180 this->_m_buffer[0] = firstEnergy;
181 this->_m_buffer[halfDim] = lastEnergy;
182 }
183
184 std::vector<float> MFCC::CreateDCTMatrix(
185 const int32_t inputLength,
186 const int32_t coefficientCount)
187 {
188 std::vector<float> dctMatix(inputLength * coefficientCount);
189
190 const float normalizer = math::MathUtils::SqrtF32(2.0f/inputLength);
191 const float angleIncr = M_PI/inputLength;
192 float angle = 0;
193
194 for (int32_t k = 0, m = 0; k < coefficientCount; k++, m += inputLength) {
195 for (int32_t n = 0; n < inputLength; n++) {
196 dctMatix[m+n] = normalizer *
alexanderc350cdc2021-04-29 20:36:09 +0100197 math::MathUtils::CosineF32((n + 0.5f) * angle);
alexander3c798932021-03-26 21:42:19 +0000198 }
199 angle += angleIncr;
200 }
201
202 return dctMatix;
203 }
204
205 float MFCC::GetMelFilterBankNormaliser(
206 const float& leftMel,
207 const float& rightMel,
208 const bool useHTKMethod)
209 {
210 UNUSED(leftMel);
211 UNUSED(rightMel);
212 UNUSED(useHTKMethod);
213
214 /* By default, no normalisation => return 1 */
215 return 1.f;
216 }
217
alexanderc350cdc2021-04-29 20:36:09 +0100218 void MFCC::InitMelFilterBank()
alexander3c798932021-03-26 21:42:19 +0000219 {
alexanderc350cdc2021-04-29 20:36:09 +0100220 if (!this->IsMelFilterBankInited()) {
221 this->_m_melFilterBank = this->CreateMelFilterBank();
alexander3c798932021-03-26 21:42:19 +0000222 this->_m_dctMatrix = this->CreateDCTMatrix(
223 this->_m_params.m_numFbankBins,
224 this->_m_params.m_numMfccFeatures);
225 this->_m_filterBankInitialised = true;
226 }
227 }
228
alexanderc350cdc2021-04-29 20:36:09 +0100229 bool MFCC::IsMelFilterBankInited() const
alexander3c798932021-03-26 21:42:19 +0000230 {
231 return this->_m_filterBankInitialised;
232 }
233
alexanderc350cdc2021-04-29 20:36:09 +0100234 void MFCC::MfccComputePreFeature(const std::vector<int16_t>& audioData)
alexander3c798932021-03-26 21:42:19 +0000235 {
alexanderc350cdc2021-04-29 20:36:09 +0100236 this->InitMelFilterBank();
alexander3c798932021-03-26 21:42:19 +0000237
238 /* TensorFlow way of normalizing .wav data to (-1, 1). */
alexanderc350cdc2021-04-29 20:36:09 +0100239 constexpr float normaliser = 1.0/(1u<<15u);
alexander3c798932021-03-26 21:42:19 +0000240 for (size_t i = 0; i < this->_m_params.m_frameLen; i++) {
241 this->_m_frame[i] = static_cast<float>(audioData[i]) * normaliser;
242 }
243
244 /* Apply window function to input frame. */
245 for(size_t i = 0; i < this->_m_params.m_frameLen; i++) {
246 this->_m_frame[i] *= this->_m_windowFunc[i];
247 }
248
249 /* Set remaining frame values to 0. */
250 std::fill(this->_m_frame.begin() + this->_m_params.m_frameLen,this->_m_frame.end(), 0);
251
252 /* Compute FFT. */
253 math::MathUtils::FftF32(this->_m_frame, this->_m_buffer, this->_m_fftInstance);
254
255 /* Convert to power spectrum. */
alexanderc350cdc2021-04-29 20:36:09 +0100256 this->ConvertToPowerSpectrum();
alexander3c798932021-03-26 21:42:19 +0000257
258 /* Apply mel filterbanks. */
259 if (!this->ApplyMelFilterBank(this->_m_buffer,
260 this->_m_melFilterBank,
261 this->_m_filterBankFilterFirst,
262 this->_m_filterBankFilterLast,
263 this->_m_melEnergies)) {
264 printf_err("Failed to apply MEL filter banks\n");
265 }
266
267 /* Convert to logarithmic scale. */
268 this->ConvertToLogarithmicScale(this->_m_melEnergies);
269 }
270
271 std::vector<float> MFCC::MfccCompute(const std::vector<int16_t>& audioData)
272 {
alexanderc350cdc2021-04-29 20:36:09 +0100273 this->MfccComputePreFeature(audioData);
alexander3c798932021-03-26 21:42:19 +0000274
275 std::vector<float> mfccOut(this->_m_params.m_numMfccFeatures);
276
277 float * ptrMel = this->_m_melEnergies.data();
278 float * ptrDct = this->_m_dctMatrix.data();
279 float * ptrMfcc = mfccOut.data();
280
281 /* Take DCT. Uses matrix mul. */
282 for (size_t i = 0, j = 0; i < mfccOut.size();
283 ++i, j += this->_m_params.m_numFbankBins) {
284 *ptrMfcc++ = math::MathUtils::DotProductF32(
285 ptrDct + j,
286 ptrMel,
287 this->_m_params.m_numFbankBins);
288 }
289 return mfccOut;
290 }
291
alexanderc350cdc2021-04-29 20:36:09 +0100292 std::vector<std::vector<float>> MFCC::CreateMelFilterBank()
alexander3c798932021-03-26 21:42:19 +0000293 {
294 size_t numFftBins = this->_m_params.m_frameLenPadded / 2;
295 float fftBinWidth = static_cast<float>(this->_m_params.m_samplingFreq) / this->_m_params.m_frameLenPadded;
296
297 float melLowFreq = MFCC::MelScale(this->_m_params.m_melLoFreq,
298 this->_m_params.m_useHtkMethod);
299 float melHighFreq = MFCC::MelScale(this->_m_params.m_melHiFreq,
300 this->_m_params.m_useHtkMethod);
301 float melFreqDelta = (melHighFreq - melLowFreq) / (this->_m_params.m_numFbankBins + 1);
302
303 std::vector<float> thisBin = std::vector<float>(numFftBins);
304 std::vector<std::vector<float>> melFilterBank(
305 this->_m_params.m_numFbankBins);
306 this->_m_filterBankFilterFirst =
alexanderc350cdc2021-04-29 20:36:09 +0100307 std::vector<uint32_t>(this->_m_params.m_numFbankBins);
alexander3c798932021-03-26 21:42:19 +0000308 this->_m_filterBankFilterLast =
alexanderc350cdc2021-04-29 20:36:09 +0100309 std::vector<uint32_t>(this->_m_params.m_numFbankBins);
alexander3c798932021-03-26 21:42:19 +0000310
311 for (size_t bin = 0; bin < this->_m_params.m_numFbankBins; bin++) {
312 float leftMel = melLowFreq + bin * melFreqDelta;
313 float centerMel = melLowFreq + (bin + 1) * melFreqDelta;
314 float rightMel = melLowFreq + (bin + 2) * melFreqDelta;
315
alexanderc350cdc2021-04-29 20:36:09 +0100316 uint32_t firstIndex = 0;
317 uint32_t lastIndex = 0;
318 bool firstIndexFound = false;
alexander3c798932021-03-26 21:42:19 +0000319 const float normaliser = this->GetMelFilterBankNormaliser(leftMel, rightMel, this->_m_params.m_useHtkMethod);
320
321 for (size_t i = 0; i < numFftBins; i++) {
322 float freq = (fftBinWidth * i); /* Center freq of this fft bin. */
323 float mel = MFCC::MelScale(freq, this->_m_params.m_useHtkMethod);
324 thisBin[i] = 0.0;
325
326 if (mel > leftMel && mel < rightMel) {
327 float weight;
328 if (mel <= centerMel) {
329 weight = (mel - leftMel) / (centerMel - leftMel);
330 } else {
331 weight = (rightMel - mel) / (rightMel - centerMel);
332 }
333
334 thisBin[i] = weight * normaliser;
alexanderc350cdc2021-04-29 20:36:09 +0100335 if (!firstIndexFound) {
alexander3c798932021-03-26 21:42:19 +0000336 firstIndex = i;
alexanderc350cdc2021-04-29 20:36:09 +0100337 firstIndexFound = true;
alexander3c798932021-03-26 21:42:19 +0000338 }
339 lastIndex = i;
340 }
341 }
342
343 this->_m_filterBankFilterFirst[bin] = firstIndex;
344 this->_m_filterBankFilterLast[bin] = lastIndex;
345
346 /* Copy the part we care about. */
alexanderc350cdc2021-04-29 20:36:09 +0100347 for (uint32_t i = firstIndex; i <= lastIndex; i++) {
alexander3c798932021-03-26 21:42:19 +0000348 melFilterBank[bin].push_back(thisBin[i]);
349 }
350 }
351
352 return melFilterBank;
353 }
354
355} /* namespace audio */
356} /* namespace app */
357} /* namespace arm */