blob: 86d57e66c848f235a0c23d88f69dcd20c28f13b2 [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>
22
23namespace arm {
24namespace app {
25namespace audio {
26
27 MelSpecParams::MelSpecParams(
28 const float samplingFreq,
29 const uint32_t numFbankBins,
30 const float melLoFreq,
31 const float melHiFreq,
32 const uint32_t frameLen,
33 const bool useHtkMethod):
34 m_samplingFreq(samplingFreq),
35 m_numFbankBins(numFbankBins),
36 m_melLoFreq(melLoFreq),
37 m_melHiFreq(melHiFreq),
38 m_frameLen(frameLen),
39
40 /* Smallest power of 2 >= frame length. */
41 m_frameLenPadded(pow(2, ceil((log(frameLen)/log(2))))),
42 m_useHtkMethod(useHtkMethod)
43 {}
44
45 std::string MelSpecParams::Str()
46 {
47 char strC[1024];
48 snprintf(strC, sizeof(strC) - 1, "\n \
49 \n\t Sampling frequency: %f\
50 \n\t Number of filter banks: %u\
51 \n\t Mel frequency limit (low): %f\
52 \n\t Mel frequency limit (high): %f\
53 \n\t Frame length: %u\
54 \n\t Padded frame length: %u\
55 \n\t Using HTK for Mel scale: %s\n",
56 this->m_samplingFreq, this->m_numFbankBins, this->m_melLoFreq,
57 this->m_melHiFreq, this->m_frameLen,
58 this->m_frameLenPadded, this->m_useHtkMethod ? "yes" : "no");
59 return std::string{strC};
60 }
61
62 MelSpectrogram::MelSpectrogram(const MelSpecParams& params):
63 _m_params(params),
64 _m_filterBankInitialised(false)
65 {
66 this->_m_buffer = std::vector<float>(
67 this->_m_params.m_frameLenPadded, 0.0);
68 this->_m_frame = std::vector<float>(
69 this->_m_params.m_frameLenPadded, 0.0);
70 this->_m_melEnergies = std::vector<float>(
71 this->_m_params.m_numFbankBins, 0.0);
72
73 this->_m_windowFunc = std::vector<float>(this->_m_params.m_frameLen);
74 const float multiplier = 2 * M_PI / this->_m_params.m_frameLen;
75
76 /* Create window function. */
77 for (size_t i = 0; i < this->_m_params.m_frameLen; ++i) {
78 this->_m_windowFunc[i] = (0.5 - (0.5 *
79 math::MathUtils::CosineF32(static_cast<float>(i) * multiplier)));
80 }
81
82 math::MathUtils::FftInitF32(this->_m_params.m_frameLenPadded, this->_m_fftInstance);
83 debug("Instantiated Mel Spectrogram object: %s\n", this->_m_params.Str().c_str());
84 }
85
86 void MelSpectrogram::Init()
87 {
88 this->_InitMelFilterBank();
89 }
90
91 float MelSpectrogram::MelScale(const float freq, const bool useHTKMethod)
92 {
93 if (useHTKMethod) {
94 return 1127.0f * logf (1.0f + freq / 700.0f);
95 } else {
96 /* Slaney formula for mel scale. */
97 float mel = freq / ms_freqStep;
98
99 if (freq >= ms_minLogHz) {
100 mel = ms_minLogMel + logf(freq / ms_minLogHz) / ms_logStep;
101 }
102 return mel;
103 }
104 }
105
106 float MelSpectrogram::InverseMelScale(const float melFreq, const bool useHTKMethod)
107 {
108 if (useHTKMethod) {
109 return 700.0f * (expf (melFreq / 1127.0f) - 1.0f);
110 } else {
111 /* Slaney formula for inverse mel scale. */
112 float freq = ms_freqStep * melFreq;
113
114 if (melFreq >= ms_minLogMel) {
115 freq = ms_minLogHz * expf(ms_logStep * (melFreq - ms_minLogMel));
116 }
117 return freq;
118 }
119 }
120
121 bool MelSpectrogram::ApplyMelFilterBank(
122 std::vector<float>& fftVec,
123 std::vector<std::vector<float>>& melFilterBank,
124 std::vector<int32_t>& filterBankFilterFirst,
125 std::vector<int32_t>& filterBankFilterLast,
126 std::vector<float>& melEnergies)
127 {
128 const size_t numBanks = melEnergies.size();
129
130 if (numBanks != filterBankFilterFirst.size() ||
131 numBanks != filterBankFilterLast.size()) {
132 printf_err("unexpected filter bank lengths\n");
133 return false;
134 }
135
136 for (size_t bin = 0; bin < numBanks; ++bin) {
137 auto filterBankIter = melFilterBank[bin].begin();
138 float melEnergy = FLT_MIN; /* Avoid log of zero at later stages */
139 int32_t firstIndex = filterBankFilterFirst[bin];
140 int32_t lastIndex = filterBankFilterLast[bin];
141
142 for (int i = firstIndex; i <= lastIndex; ++i) {
143 float energyRep = math::MathUtils::SqrtF32(fftVec[i]);
144 melEnergy += (*filterBankIter++ * energyRep);
145 }
146
147 melEnergies[bin] = melEnergy;
148 }
149
150 return true;
151 }
152
153 void MelSpectrogram::ConvertToLogarithmicScale(std::vector<float>& melEnergies)
154 {
155 for (size_t bin = 0; bin < melEnergies.size(); ++bin) {
156 melEnergies[bin] = logf(melEnergies[bin]);
157 }
158 }
159
160 void MelSpectrogram::_ConvertToPowerSpectrum()
161 {
162 const uint32_t halfDim = this->_m_params.m_frameLenPadded / 2;
163
164 /* Handle this special case. */
165 float firstEnergy = this->_m_buffer[0] * this->_m_buffer[0];
166 float lastEnergy = this->_m_buffer[1] * this->_m_buffer[1];
167
168 math::MathUtils::ComplexMagnitudeSquaredF32(
169 this->_m_buffer.data(),
170 this->_m_buffer.size(),
171 this->_m_buffer.data(),
172 this->_m_buffer.size()/2);
173
174 this->_m_buffer[0] = firstEnergy;
175 this->_m_buffer[halfDim] = lastEnergy;
176 }
177
178 float MelSpectrogram::GetMelFilterBankNormaliser(
179 const float& leftMel,
180 const float& rightMel,
181 const bool useHTKMethod)
182 {
183 UNUSED(leftMel);
184 UNUSED(rightMel);
185 UNUSED(useHTKMethod);
186
187 /* By default, no normalisation => return 1 */
188 return 1.f;
189 }
190
191 void MelSpectrogram::_InitMelFilterBank()
192 {
193 if (!this->_IsMelFilterBankInited()) {
194 this->_m_melFilterBank = this->_CreateMelFilterBank();
195 this->_m_filterBankInitialised = true;
196 }
197 }
198
199 bool MelSpectrogram::_IsMelFilterBankInited()
200 {
201 return this->_m_filterBankInitialised;
202 }
203
204 std::vector<float> MelSpectrogram::ComputeMelSpec(const std::vector<int16_t>& audioData, float trainingMean)
205 {
206 this->_InitMelFilterBank();
207
208 /* TensorFlow way of normalizing .wav data to (-1, 1). */
209 constexpr float normaliser = 1.0/(1<<15);
210 for (size_t i = 0; i < this->_m_params.m_frameLen; ++i) {
211 this->_m_frame[i] = static_cast<float>(audioData[i]) * normaliser;
212 }
213
214 /* Apply window function to input frame. */
215 for(size_t i = 0; i < this->_m_params.m_frameLen; ++i) {
216 this->_m_frame[i] *= this->_m_windowFunc[i];
217 }
218
219 /* Set remaining frame values to 0. */
220 std::fill(this->_m_frame.begin() + this->_m_params.m_frameLen,this->_m_frame.end(), 0);
221
222 /* Compute FFT. */
223 math::MathUtils::FftF32(this->_m_frame, this->_m_buffer, this->_m_fftInstance);
224
225 /* Convert to power spectrum. */
226 this->_ConvertToPowerSpectrum();
227
228 /* Apply mel filterbanks. */
229 if (!this->ApplyMelFilterBank(this->_m_buffer,
230 this->_m_melFilterBank,
231 this->_m_filterBankFilterFirst,
232 this->_m_filterBankFilterLast,
233 this->_m_melEnergies)) {
234 printf_err("Failed to apply MEL filter banks\n");
235 }
236
237 /* Convert to logarithmic scale */
238 this->ConvertToLogarithmicScale(this->_m_melEnergies);
239
240 /* Perform mean subtraction. */
241 for (auto& energy:this->_m_melEnergies) {
242 energy -= trainingMean;
243 }
244
245 return this->_m_melEnergies;
246 }
247
248 std::vector<std::vector<float>> MelSpectrogram::_CreateMelFilterBank()
249 {
250 size_t numFftBins = this->_m_params.m_frameLenPadded / 2;
251 float fftBinWidth = static_cast<float>(this->_m_params.m_samplingFreq) / this->_m_params.m_frameLenPadded;
252
253 float melLowFreq = MelSpectrogram::MelScale(this->_m_params.m_melLoFreq,
254 this->_m_params.m_useHtkMethod);
255 float melHighFreq = MelSpectrogram::MelScale(this->_m_params.m_melHiFreq,
256 this->_m_params.m_useHtkMethod);
257 float melFreqDelta = (melHighFreq - melLowFreq) / (this->_m_params.m_numFbankBins + 1);
258
259 std::vector<float> thisBin = std::vector<float>(numFftBins);
260 std::vector<std::vector<float>> melFilterBank(
261 this->_m_params.m_numFbankBins);
262 this->_m_filterBankFilterFirst =
263 std::vector<int32_t>(this->_m_params.m_numFbankBins);
264 this->_m_filterBankFilterLast =
265 std::vector<int32_t>(this->_m_params.m_numFbankBins);
266
267 for (size_t bin = 0; bin < this->_m_params.m_numFbankBins; bin++) {
268 float leftMel = melLowFreq + bin * melFreqDelta;
269 float centerMel = melLowFreq + (bin + 1) * melFreqDelta;
270 float rightMel = melLowFreq + (bin + 2) * melFreqDelta;
271
272 int32_t firstIndex = -1;
273 int32_t lastIndex = -1;
274 const float normaliser = this->GetMelFilterBankNormaliser(leftMel, rightMel, this->_m_params.m_useHtkMethod);
275
276 for (size_t i = 0; i < numFftBins; ++i) {
277 float freq = (fftBinWidth * i); /* Center freq of this fft bin. */
278 float mel = MelSpectrogram::MelScale(freq, this->_m_params.m_useHtkMethod);
279 thisBin[i] = 0.0;
280
281 if (mel > leftMel && mel < rightMel) {
282 float weight;
283 if (mel <= centerMel) {
284 weight = (mel - leftMel) / (centerMel - leftMel);
285 } else {
286 weight = (rightMel - mel) / (rightMel - centerMel);
287 }
288
289 thisBin[i] = weight * normaliser;
290 if (firstIndex == -1) {
291 firstIndex = i;
292 }
293 lastIndex = i;
294 }
295 }
296
297 this->_m_filterBankFilterFirst[bin] = firstIndex;
298 this->_m_filterBankFilterLast[bin] = lastIndex;
299
300 /* Copy the part we care about. */
301 for (int32_t i = firstIndex; i <= lastIndex; ++i) {
302 melFilterBank[bin].push_back(thisBin[i]);
303 }
304 }
305
306 return melFilterBank;
307 }
308
309} /* namespace audio */
310} /* namespace app */
311} /* namespace arm */