blob: c8ad1389cbdf90b32d119916097940a868bd7a8f [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>
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +010022#include <inttypes.h>
alexander3c798932021-03-26 21:42:19 +000023
24namespace arm {
25namespace app {
26namespace audio {
27
28 MfccParams::MfccParams(
29 const float samplingFreq,
30 const uint32_t numFbankBins,
31 const float melLoFreq,
32 const float melHiFreq,
33 const uint32_t numMfccFeats,
34 const uint32_t frameLen,
35 const bool useHtkMethod):
36 m_samplingFreq(samplingFreq),
37 m_numFbankBins(numFbankBins),
38 m_melLoFreq(melLoFreq),
39 m_melHiFreq(melHiFreq),
40 m_numMfccFeatures(numMfccFeats),
41 m_frameLen(frameLen),
42
43 /* Smallest power of 2 >= frame length. */
44 m_frameLenPadded(pow(2, ceil((log(frameLen)/log(2))))),
45 m_useHtkMethod(useHtkMethod)
46 {}
47
alexanderc350cdc2021-04-29 20:36:09 +010048 std::string MfccParams::Str() const
alexander3c798932021-03-26 21:42:19 +000049 {
50 char strC[1024];
51 snprintf(strC, sizeof(strC) - 1, "\n \
52 \n\t Sampling frequency: %f\
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +010053 \n\t Number of filter banks: %" PRIu32 "\
alexander3c798932021-03-26 21:42:19 +000054 \n\t Mel frequency limit (low): %f\
55 \n\t Mel frequency limit (high): %f\
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +010056 \n\t Number of MFCC features: %" PRIu32 "\
57 \n\t Frame length: %" PRIu32 "\
58 \n\t Padded frame length: %" PRIu32 "\
alexander3c798932021-03-26 21:42:19 +000059 \n\t Using HTK for Mel scale: %s\n",
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +010060 this->m_samplingFreq, this->m_numFbankBins, this->m_melLoFreq,
61 this->m_melHiFreq, this->m_numMfccFeatures, this->m_frameLen,
62 this->m_frameLenPadded, this->m_useHtkMethod ? "yes" : "no");
alexander3c798932021-03-26 21:42:19 +000063 return std::string{strC};
64 }
65
66 MFCC::MFCC(const MfccParams& params):
67 _m_params(params),
68 _m_filterBankInitialised(false)
69 {
70 this->_m_buffer = std::vector<float>(
71 this->_m_params.m_frameLenPadded, 0.0);
72 this->_m_frame = std::vector<float>(
73 this->_m_params.m_frameLenPadded, 0.0);
74 this->_m_melEnergies = std::vector<float>(
75 this->_m_params.m_numFbankBins, 0.0);
76
77 this->_m_windowFunc = std::vector<float>(this->_m_params.m_frameLen);
alexanderc350cdc2021-04-29 20:36:09 +010078 const auto multiplier = static_cast<float>(2 * M_PI / this->_m_params.m_frameLen);
alexander3c798932021-03-26 21:42:19 +000079
80 /* Create window function. */
81 for (size_t i = 0; i < this->_m_params.m_frameLen; i++) {
82 this->_m_windowFunc[i] = (0.5 - (0.5 *
83 math::MathUtils::CosineF32(static_cast<float>(i) * multiplier)));
84 }
85
86 math::MathUtils::FftInitF32(this->_m_params.m_frameLenPadded, this->_m_fftInstance);
87 debug("Instantiated MFCC object: %s\n", this->_m_params.Str().c_str());
88 }
89
90 void MFCC::Init()
91 {
alexanderc350cdc2021-04-29 20:36:09 +010092 this->InitMelFilterBank();
alexander3c798932021-03-26 21:42:19 +000093 }
94
95 float MFCC::MelScale(const float freq, const bool useHTKMethod)
96 {
97 if (useHTKMethod) {
98 return 1127.0f * logf (1.0f + freq / 700.0f);
99 } else {
100 /* Slaney formula for mel scale. */
101
102 float mel = freq / ms_freqStep;
103
104 if (freq >= ms_minLogHz) {
105 mel = ms_minLogMel + logf(freq / ms_minLogHz) / ms_logStep;
106 }
107 return mel;
108 }
109 }
110
111 float MFCC::InverseMelScale(const float melFreq, const bool useHTKMethod)
112 {
113 if (useHTKMethod) {
114 return 700.0f * (expf (melFreq / 1127.0f) - 1.0f);
115 } else {
116 /* Slaney formula for mel scale. */
117 float freq = ms_freqStep * melFreq;
118
119 if (melFreq >= ms_minLogMel) {
120 freq = ms_minLogHz * expf(ms_logStep * (melFreq - ms_minLogMel));
121 }
122 return freq;
123 }
124 }
125
126
127 bool MFCC::ApplyMelFilterBank(
128 std::vector<float>& fftVec,
129 std::vector<std::vector<float>>& melFilterBank,
alexanderc350cdc2021-04-29 20:36:09 +0100130 std::vector<uint32_t>& filterBankFilterFirst,
131 std::vector<uint32_t>& filterBankFilterLast,
alexander3c798932021-03-26 21:42:19 +0000132 std::vector<float>& melEnergies)
133 {
134 const size_t numBanks = melEnergies.size();
135
136 if (numBanks != filterBankFilterFirst.size() ||
137 numBanks != filterBankFilterLast.size()) {
138 printf_err("unexpected filter bank lengths\n");
139 return false;
140 }
141
142 for (size_t bin = 0; bin < numBanks; ++bin) {
143 auto filterBankIter = melFilterBank[bin].begin();
alexanderc350cdc2021-04-29 20:36:09 +0100144 auto end = melFilterBank[bin].end();
alexander3c798932021-03-26 21:42:19 +0000145 float melEnergy = FLT_MIN; /* Avoid log of zero at later stages */
alexanderc350cdc2021-04-29 20:36:09 +0100146 const uint32_t firstIndex = filterBankFilterFirst[bin];
147 const uint32_t lastIndex = std::min<uint32_t>(filterBankFilterLast[bin], fftVec.size() - 1);
alexander3c798932021-03-26 21:42:19 +0000148
alexanderc350cdc2021-04-29 20:36:09 +0100149 for (uint32_t i = firstIndex; i <= lastIndex && filterBankIter != end; i++) {
alexander3c798932021-03-26 21:42:19 +0000150 float energyRep = math::MathUtils::SqrtF32(fftVec[i]);
151 melEnergy += (*filterBankIter++ * energyRep);
152 }
153
154 melEnergies[bin] = melEnergy;
155 }
156
157 return true;
158 }
159
160 void MFCC::ConvertToLogarithmicScale(std::vector<float>& melEnergies)
161 {
alexanderc350cdc2021-04-29 20:36:09 +0100162 for (float& melEnergy : melEnergies) {
163 melEnergy = logf(melEnergy);
alexander3c798932021-03-26 21:42:19 +0000164 }
165 }
166
alexanderc350cdc2021-04-29 20:36:09 +0100167 void MFCC::ConvertToPowerSpectrum()
alexander3c798932021-03-26 21:42:19 +0000168 {
alexanderc350cdc2021-04-29 20:36:09 +0100169 const uint32_t halfDim = this->_m_buffer.size() / 2;
alexander3c798932021-03-26 21:42:19 +0000170
171 /* Handle this special case. */
172 float firstEnergy = this->_m_buffer[0] * this->_m_buffer[0];
173 float lastEnergy = this->_m_buffer[1] * this->_m_buffer[1];
174
175 math::MathUtils::ComplexMagnitudeSquaredF32(
176 this->_m_buffer.data(),
177 this->_m_buffer.size(),
178 this->_m_buffer.data(),
179 this->_m_buffer.size()/2);
180
181 this->_m_buffer[0] = firstEnergy;
182 this->_m_buffer[halfDim] = lastEnergy;
183 }
184
185 std::vector<float> MFCC::CreateDCTMatrix(
186 const int32_t inputLength,
187 const int32_t coefficientCount)
188 {
189 std::vector<float> dctMatix(inputLength * coefficientCount);
190
191 const float normalizer = math::MathUtils::SqrtF32(2.0f/inputLength);
192 const float angleIncr = M_PI/inputLength;
193 float angle = 0;
194
195 for (int32_t k = 0, m = 0; k < coefficientCount; k++, m += inputLength) {
196 for (int32_t n = 0; n < inputLength; n++) {
197 dctMatix[m+n] = normalizer *
alexanderc350cdc2021-04-29 20:36:09 +0100198 math::MathUtils::CosineF32((n + 0.5f) * angle);
alexander3c798932021-03-26 21:42:19 +0000199 }
200 angle += angleIncr;
201 }
202
203 return dctMatix;
204 }
205
206 float MFCC::GetMelFilterBankNormaliser(
207 const float& leftMel,
208 const float& rightMel,
209 const bool useHTKMethod)
210 {
211 UNUSED(leftMel);
212 UNUSED(rightMel);
213 UNUSED(useHTKMethod);
214
215 /* By default, no normalisation => return 1 */
216 return 1.f;
217 }
218
alexanderc350cdc2021-04-29 20:36:09 +0100219 void MFCC::InitMelFilterBank()
alexander3c798932021-03-26 21:42:19 +0000220 {
alexanderc350cdc2021-04-29 20:36:09 +0100221 if (!this->IsMelFilterBankInited()) {
222 this->_m_melFilterBank = this->CreateMelFilterBank();
alexander3c798932021-03-26 21:42:19 +0000223 this->_m_dctMatrix = this->CreateDCTMatrix(
224 this->_m_params.m_numFbankBins,
225 this->_m_params.m_numMfccFeatures);
226 this->_m_filterBankInitialised = true;
227 }
228 }
229
alexanderc350cdc2021-04-29 20:36:09 +0100230 bool MFCC::IsMelFilterBankInited() const
alexander3c798932021-03-26 21:42:19 +0000231 {
232 return this->_m_filterBankInitialised;
233 }
234
alexanderc350cdc2021-04-29 20:36:09 +0100235 void MFCC::MfccComputePreFeature(const std::vector<int16_t>& audioData)
alexander3c798932021-03-26 21:42:19 +0000236 {
alexanderc350cdc2021-04-29 20:36:09 +0100237 this->InitMelFilterBank();
alexander3c798932021-03-26 21:42:19 +0000238
239 /* TensorFlow way of normalizing .wav data to (-1, 1). */
alexanderc350cdc2021-04-29 20:36:09 +0100240 constexpr float normaliser = 1.0/(1u<<15u);
alexander3c798932021-03-26 21:42:19 +0000241 for (size_t i = 0; i < this->_m_params.m_frameLen; i++) {
242 this->_m_frame[i] = static_cast<float>(audioData[i]) * normaliser;
243 }
244
245 /* Apply window function to input frame. */
246 for(size_t i = 0; i < this->_m_params.m_frameLen; i++) {
247 this->_m_frame[i] *= this->_m_windowFunc[i];
248 }
249
250 /* Set remaining frame values to 0. */
251 std::fill(this->_m_frame.begin() + this->_m_params.m_frameLen,this->_m_frame.end(), 0);
252
253 /* Compute FFT. */
254 math::MathUtils::FftF32(this->_m_frame, this->_m_buffer, this->_m_fftInstance);
255
256 /* Convert to power spectrum. */
alexanderc350cdc2021-04-29 20:36:09 +0100257 this->ConvertToPowerSpectrum();
alexander3c798932021-03-26 21:42:19 +0000258
259 /* Apply mel filterbanks. */
260 if (!this->ApplyMelFilterBank(this->_m_buffer,
261 this->_m_melFilterBank,
262 this->_m_filterBankFilterFirst,
263 this->_m_filterBankFilterLast,
264 this->_m_melEnergies)) {
265 printf_err("Failed to apply MEL filter banks\n");
266 }
267
268 /* Convert to logarithmic scale. */
269 this->ConvertToLogarithmicScale(this->_m_melEnergies);
270 }
271
272 std::vector<float> MFCC::MfccCompute(const std::vector<int16_t>& audioData)
273 {
alexanderc350cdc2021-04-29 20:36:09 +0100274 this->MfccComputePreFeature(audioData);
alexander3c798932021-03-26 21:42:19 +0000275
276 std::vector<float> mfccOut(this->_m_params.m_numMfccFeatures);
277
278 float * ptrMel = this->_m_melEnergies.data();
279 float * ptrDct = this->_m_dctMatrix.data();
280 float * ptrMfcc = mfccOut.data();
281
282 /* Take DCT. Uses matrix mul. */
283 for (size_t i = 0, j = 0; i < mfccOut.size();
284 ++i, j += this->_m_params.m_numFbankBins) {
285 *ptrMfcc++ = math::MathUtils::DotProductF32(
286 ptrDct + j,
287 ptrMel,
288 this->_m_params.m_numFbankBins);
289 }
290 return mfccOut;
291 }
292
alexanderc350cdc2021-04-29 20:36:09 +0100293 std::vector<std::vector<float>> MFCC::CreateMelFilterBank()
alexander3c798932021-03-26 21:42:19 +0000294 {
295 size_t numFftBins = this->_m_params.m_frameLenPadded / 2;
296 float fftBinWidth = static_cast<float>(this->_m_params.m_samplingFreq) / this->_m_params.m_frameLenPadded;
297
298 float melLowFreq = MFCC::MelScale(this->_m_params.m_melLoFreq,
299 this->_m_params.m_useHtkMethod);
300 float melHighFreq = MFCC::MelScale(this->_m_params.m_melHiFreq,
301 this->_m_params.m_useHtkMethod);
302 float melFreqDelta = (melHighFreq - melLowFreq) / (this->_m_params.m_numFbankBins + 1);
303
304 std::vector<float> thisBin = std::vector<float>(numFftBins);
305 std::vector<std::vector<float>> melFilterBank(
306 this->_m_params.m_numFbankBins);
307 this->_m_filterBankFilterFirst =
alexanderc350cdc2021-04-29 20:36:09 +0100308 std::vector<uint32_t>(this->_m_params.m_numFbankBins);
alexander3c798932021-03-26 21:42:19 +0000309 this->_m_filterBankFilterLast =
alexanderc350cdc2021-04-29 20:36:09 +0100310 std::vector<uint32_t>(this->_m_params.m_numFbankBins);
alexander3c798932021-03-26 21:42:19 +0000311
312 for (size_t bin = 0; bin < this->_m_params.m_numFbankBins; bin++) {
313 float leftMel = melLowFreq + bin * melFreqDelta;
314 float centerMel = melLowFreq + (bin + 1) * melFreqDelta;
315 float rightMel = melLowFreq + (bin + 2) * melFreqDelta;
316
alexanderc350cdc2021-04-29 20:36:09 +0100317 uint32_t firstIndex = 0;
318 uint32_t lastIndex = 0;
319 bool firstIndexFound = false;
alexander3c798932021-03-26 21:42:19 +0000320 const float normaliser = this->GetMelFilterBankNormaliser(leftMel, rightMel, this->_m_params.m_useHtkMethod);
321
322 for (size_t i = 0; i < numFftBins; i++) {
323 float freq = (fftBinWidth * i); /* Center freq of this fft bin. */
324 float mel = MFCC::MelScale(freq, this->_m_params.m_useHtkMethod);
325 thisBin[i] = 0.0;
326
327 if (mel > leftMel && mel < rightMel) {
328 float weight;
329 if (mel <= centerMel) {
330 weight = (mel - leftMel) / (centerMel - leftMel);
331 } else {
332 weight = (rightMel - mel) / (rightMel - centerMel);
333 }
334
335 thisBin[i] = weight * normaliser;
alexanderc350cdc2021-04-29 20:36:09 +0100336 if (!firstIndexFound) {
alexander3c798932021-03-26 21:42:19 +0000337 firstIndex = i;
alexanderc350cdc2021-04-29 20:36:09 +0100338 firstIndexFound = true;
alexander3c798932021-03-26 21:42:19 +0000339 }
340 lastIndex = i;
341 }
342 }
343
344 this->_m_filterBankFilterFirst[bin] = firstIndex;
345 this->_m_filterBankFilterLast[bin] = lastIndex;
346
347 /* Copy the part we care about. */
alexanderc350cdc2021-04-29 20:36:09 +0100348 for (uint32_t i = firstIndex; i <= lastIndex; i++) {
alexander3c798932021-03-26 21:42:19 +0000349 melFilterBank[bin].push_back(thisBin[i]);
350 }
351 }
352
353 return melFilterBank;
354 }
355
356} /* namespace audio */
357} /* namespace app */
358} /* namespace arm */