blob: f1752e1fa10cbd01416825d748344af3bd63a164 [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 "MelSpectrogram.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 MelSpecParams::MelSpecParams(
29 const float samplingFreq,
30 const uint32_t numFbankBins,
31 const float melLoFreq,
32 const float melHiFreq,
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_frameLen(frameLen),
40
41 /* Smallest power of 2 >= frame length. */
42 m_frameLenPadded(pow(2, ceil((log(frameLen)/log(2))))),
43 m_useHtkMethod(useHtkMethod)
44 {}
45
alexanderc350cdc2021-04-29 20:36:09 +010046 std::string MelSpecParams::Str() const
alexander3c798932021-03-26 21:42:19 +000047 {
48 char strC[1024];
49 snprintf(strC, sizeof(strC) - 1, "\n \
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +010050 \n\t Sampling frequency: %f\
51 \n\t Number of filter banks: %" PRIu32 "\
52 \n\t Mel frequency limit (low): %f\
53 \n\t Mel frequency limit (high): %f\
54 \n\t Frame length: %" PRIu32 "\
55 \n\t Padded frame length: %" PRIu32 "\
56 \n\t Using HTK for Mel scale: %s\n",
57 this->m_samplingFreq, this->m_numFbankBins, this->m_melLoFreq,
58 this->m_melHiFreq, this->m_frameLen,
59 this->m_frameLenPadded, this->m_useHtkMethod ? "yes" : "no");
alexander3c798932021-03-26 21:42:19 +000060 return std::string{strC};
61 }
62
63 MelSpectrogram::MelSpectrogram(const MelSpecParams& params):
64 _m_params(params),
65 _m_filterBankInitialised(false)
66 {
67 this->_m_buffer = std::vector<float>(
68 this->_m_params.m_frameLenPadded, 0.0);
69 this->_m_frame = std::vector<float>(
70 this->_m_params.m_frameLenPadded, 0.0);
71 this->_m_melEnergies = std::vector<float>(
72 this->_m_params.m_numFbankBins, 0.0);
73
74 this->_m_windowFunc = std::vector<float>(this->_m_params.m_frameLen);
alexanderc350cdc2021-04-29 20:36:09 +010075 const auto multiplier = static_cast<float>(2 * M_PI / this->_m_params.m_frameLen);
alexander3c798932021-03-26 21:42:19 +000076
77 /* Create window function. */
78 for (size_t i = 0; i < this->_m_params.m_frameLen; ++i) {
79 this->_m_windowFunc[i] = (0.5 - (0.5 *
80 math::MathUtils::CosineF32(static_cast<float>(i) * multiplier)));
81 }
82
83 math::MathUtils::FftInitF32(this->_m_params.m_frameLenPadded, this->_m_fftInstance);
84 debug("Instantiated Mel Spectrogram object: %s\n", this->_m_params.Str().c_str());
85 }
86
87 void MelSpectrogram::Init()
88 {
alexanderc350cdc2021-04-29 20:36:09 +010089 this->InitMelFilterBank();
alexander3c798932021-03-26 21:42:19 +000090 }
91
92 float MelSpectrogram::MelScale(const float freq, const bool useHTKMethod)
93 {
94 if (useHTKMethod) {
95 return 1127.0f * logf (1.0f + freq / 700.0f);
96 } else {
97 /* Slaney formula for mel scale. */
98 float mel = freq / ms_freqStep;
99
100 if (freq >= ms_minLogHz) {
101 mel = ms_minLogMel + logf(freq / ms_minLogHz) / ms_logStep;
102 }
103 return mel;
104 }
105 }
106
107 float MelSpectrogram::InverseMelScale(const float melFreq, const bool useHTKMethod)
108 {
109 if (useHTKMethod) {
110 return 700.0f * (expf (melFreq / 1127.0f) - 1.0f);
111 } else {
112 /* Slaney formula for inverse mel scale. */
113 float freq = ms_freqStep * melFreq;
114
115 if (melFreq >= ms_minLogMel) {
116 freq = ms_minLogHz * expf(ms_logStep * (melFreq - ms_minLogMel));
117 }
118 return freq;
119 }
120 }
121
122 bool MelSpectrogram::ApplyMelFilterBank(
123 std::vector<float>& fftVec,
124 std::vector<std::vector<float>>& melFilterBank,
alexanderc350cdc2021-04-29 20:36:09 +0100125 std::vector<uint32_t>& filterBankFilterFirst,
126 std::vector<uint32_t>& filterBankFilterLast,
alexander3c798932021-03-26 21:42:19 +0000127 std::vector<float>& melEnergies)
128 {
129 const size_t numBanks = melEnergies.size();
130
131 if (numBanks != filterBankFilterFirst.size() ||
132 numBanks != filterBankFilterLast.size()) {
133 printf_err("unexpected filter bank lengths\n");
134 return false;
135 }
136
137 for (size_t bin = 0; bin < numBanks; ++bin) {
138 auto filterBankIter = melFilterBank[bin].begin();
alexanderc350cdc2021-04-29 20:36:09 +0100139 auto end = melFilterBank[bin].end();
alexander3c798932021-03-26 21:42:19 +0000140 float melEnergy = FLT_MIN; /* Avoid log of zero at later stages */
alexanderc350cdc2021-04-29 20:36:09 +0100141 const uint32_t firstIndex = filterBankFilterFirst[bin];
142 const uint32_t lastIndex = std::min<int32_t>(filterBankFilterLast[bin], fftVec.size() - 1);
alexander3c798932021-03-26 21:42:19 +0000143
alexanderc350cdc2021-04-29 20:36:09 +0100144 for (uint32_t i = firstIndex; i <= lastIndex && filterBankIter != end; ++i) {
alexander3c798932021-03-26 21:42:19 +0000145 float energyRep = math::MathUtils::SqrtF32(fftVec[i]);
146 melEnergy += (*filterBankIter++ * energyRep);
147 }
148
149 melEnergies[bin] = melEnergy;
150 }
151
152 return true;
153 }
154
155 void MelSpectrogram::ConvertToLogarithmicScale(std::vector<float>& melEnergies)
156 {
alexanderc350cdc2021-04-29 20:36:09 +0100157 for (float& melEnergy : melEnergies) {
158 melEnergy = logf(melEnergy);
alexander3c798932021-03-26 21:42:19 +0000159 }
160 }
161
alexanderc350cdc2021-04-29 20:36:09 +0100162 void MelSpectrogram::ConvertToPowerSpectrum()
alexander3c798932021-03-26 21:42:19 +0000163 {
alexanderc350cdc2021-04-29 20:36:09 +0100164 const uint32_t halfDim = this->_m_buffer.size() / 2;
alexander3c798932021-03-26 21:42:19 +0000165
166 /* Handle this special case. */
167 float firstEnergy = this->_m_buffer[0] * this->_m_buffer[0];
168 float lastEnergy = this->_m_buffer[1] * this->_m_buffer[1];
169
170 math::MathUtils::ComplexMagnitudeSquaredF32(
171 this->_m_buffer.data(),
172 this->_m_buffer.size(),
173 this->_m_buffer.data(),
174 this->_m_buffer.size()/2);
175
176 this->_m_buffer[0] = firstEnergy;
177 this->_m_buffer[halfDim] = lastEnergy;
178 }
179
180 float MelSpectrogram::GetMelFilterBankNormaliser(
181 const float& leftMel,
182 const float& rightMel,
183 const bool useHTKMethod)
184 {
185 UNUSED(leftMel);
186 UNUSED(rightMel);
187 UNUSED(useHTKMethod);
188
189 /* By default, no normalisation => return 1 */
190 return 1.f;
191 }
192
alexanderc350cdc2021-04-29 20:36:09 +0100193 void MelSpectrogram::InitMelFilterBank()
alexander3c798932021-03-26 21:42:19 +0000194 {
alexanderc350cdc2021-04-29 20:36:09 +0100195 if (!this->IsMelFilterBankInited()) {
196 this->_m_melFilterBank = this->CreateMelFilterBank();
alexander3c798932021-03-26 21:42:19 +0000197 this->_m_filterBankInitialised = true;
198 }
199 }
200
alexanderc350cdc2021-04-29 20:36:09 +0100201 bool MelSpectrogram::IsMelFilterBankInited() const
alexander3c798932021-03-26 21:42:19 +0000202 {
203 return this->_m_filterBankInitialised;
204 }
205
206 std::vector<float> MelSpectrogram::ComputeMelSpec(const std::vector<int16_t>& audioData, float trainingMean)
207 {
alexanderc350cdc2021-04-29 20:36:09 +0100208 this->InitMelFilterBank();
alexander3c798932021-03-26 21:42:19 +0000209
210 /* TensorFlow way of normalizing .wav data to (-1, 1). */
211 constexpr float normaliser = 1.0/(1<<15);
212 for (size_t i = 0; i < this->_m_params.m_frameLen; ++i) {
213 this->_m_frame[i] = static_cast<float>(audioData[i]) * normaliser;
214 }
215
216 /* Apply window function to input frame. */
217 for(size_t i = 0; i < this->_m_params.m_frameLen; ++i) {
218 this->_m_frame[i] *= this->_m_windowFunc[i];
219 }
220
221 /* Set remaining frame values to 0. */
222 std::fill(this->_m_frame.begin() + this->_m_params.m_frameLen,this->_m_frame.end(), 0);
223
224 /* Compute FFT. */
225 math::MathUtils::FftF32(this->_m_frame, this->_m_buffer, this->_m_fftInstance);
226
227 /* Convert to power spectrum. */
alexanderc350cdc2021-04-29 20:36:09 +0100228 this->ConvertToPowerSpectrum();
alexander3c798932021-03-26 21:42:19 +0000229
230 /* Apply mel filterbanks. */
231 if (!this->ApplyMelFilterBank(this->_m_buffer,
232 this->_m_melFilterBank,
233 this->_m_filterBankFilterFirst,
234 this->_m_filterBankFilterLast,
235 this->_m_melEnergies)) {
236 printf_err("Failed to apply MEL filter banks\n");
237 }
238
239 /* Convert to logarithmic scale */
240 this->ConvertToLogarithmicScale(this->_m_melEnergies);
241
242 /* Perform mean subtraction. */
243 for (auto& energy:this->_m_melEnergies) {
244 energy -= trainingMean;
245 }
246
247 return this->_m_melEnergies;
248 }
249
alexanderc350cdc2021-04-29 20:36:09 +0100250 std::vector<std::vector<float>> MelSpectrogram::CreateMelFilterBank()
alexander3c798932021-03-26 21:42:19 +0000251 {
252 size_t numFftBins = this->_m_params.m_frameLenPadded / 2;
253 float fftBinWidth = static_cast<float>(this->_m_params.m_samplingFreq) / this->_m_params.m_frameLenPadded;
254
255 float melLowFreq = MelSpectrogram::MelScale(this->_m_params.m_melLoFreq,
256 this->_m_params.m_useHtkMethod);
257 float melHighFreq = MelSpectrogram::MelScale(this->_m_params.m_melHiFreq,
258 this->_m_params.m_useHtkMethod);
259 float melFreqDelta = (melHighFreq - melLowFreq) / (this->_m_params.m_numFbankBins + 1);
260
261 std::vector<float> thisBin = std::vector<float>(numFftBins);
262 std::vector<std::vector<float>> melFilterBank(
263 this->_m_params.m_numFbankBins);
264 this->_m_filterBankFilterFirst =
alexanderc350cdc2021-04-29 20:36:09 +0100265 std::vector<uint32_t>(this->_m_params.m_numFbankBins);
alexander3c798932021-03-26 21:42:19 +0000266 this->_m_filterBankFilterLast =
alexanderc350cdc2021-04-29 20:36:09 +0100267 std::vector<uint32_t>(this->_m_params.m_numFbankBins);
alexander3c798932021-03-26 21:42:19 +0000268
269 for (size_t bin = 0; bin < this->_m_params.m_numFbankBins; bin++) {
270 float leftMel = melLowFreq + bin * melFreqDelta;
271 float centerMel = melLowFreq + (bin + 1) * melFreqDelta;
272 float rightMel = melLowFreq + (bin + 2) * melFreqDelta;
273
alexanderc350cdc2021-04-29 20:36:09 +0100274 uint32_t firstIndex = 0;
275 uint32_t lastIndex = 0;
276 bool firstIndexFound = false;
alexander3c798932021-03-26 21:42:19 +0000277 const float normaliser = this->GetMelFilterBankNormaliser(leftMel, rightMel, this->_m_params.m_useHtkMethod);
278
279 for (size_t i = 0; i < numFftBins; ++i) {
280 float freq = (fftBinWidth * i); /* Center freq of this fft bin. */
281 float mel = MelSpectrogram::MelScale(freq, this->_m_params.m_useHtkMethod);
282 thisBin[i] = 0.0;
283
284 if (mel > leftMel && mel < rightMel) {
285 float weight;
286 if (mel <= centerMel) {
287 weight = (mel - leftMel) / (centerMel - leftMel);
288 } else {
289 weight = (rightMel - mel) / (rightMel - centerMel);
290 }
291
292 thisBin[i] = weight * normaliser;
alexanderc350cdc2021-04-29 20:36:09 +0100293 if (!firstIndexFound) {
alexander3c798932021-03-26 21:42:19 +0000294 firstIndex = i;
alexanderc350cdc2021-04-29 20:36:09 +0100295 firstIndexFound = true;
alexander3c798932021-03-26 21:42:19 +0000296 }
297 lastIndex = i;
298 }
299 }
300
301 this->_m_filterBankFilterFirst[bin] = firstIndex;
302 this->_m_filterBankFilterLast[bin] = lastIndex;
303
304 /* Copy the part we care about. */
alexanderc350cdc2021-04-29 20:36:09 +0100305 for (uint32_t i = firstIndex; i <= lastIndex; ++i) {
alexander3c798932021-03-26 21:42:19 +0000306 melFilterBank[bin].push_back(thisBin[i]);
307 }
308 }
309
310 return melFilterBank;
311 }
312
313} /* namespace audio */
314} /* namespace app */
315} /* namespace arm */