alexander | 3c79893 | 2021-03-26 21:42:19 +0000 | [diff] [blame^] | 1 | /* |
| 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 | |
| 23 | namespace arm { |
| 24 | namespace app { |
| 25 | namespace 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 | |
| 47 | std::string MfccParams::Str() |
| 48 | { |
| 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); |
| 77 | const float multiplier = 2 * M_PI / this->_m_params.m_frameLen; |
| 78 | |
| 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 | { |
| 91 | this->_InitMelFilterBank(); |
| 92 | } |
| 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, |
| 129 | std::vector<int32_t>& filterBankFilterFirst, |
| 130 | std::vector<int32_t>& filterBankFilterLast, |
| 131 | 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(); |
| 143 | float melEnergy = FLT_MIN; /* Avoid log of zero at later stages */ |
| 144 | int32_t firstIndex = filterBankFilterFirst[bin]; |
| 145 | int32_t lastIndex = filterBankFilterLast[bin]; |
| 146 | |
| 147 | for (int i = firstIndex; i <= lastIndex; i++) { |
| 148 | float energyRep = math::MathUtils::SqrtF32(fftVec[i]); |
| 149 | melEnergy += (*filterBankIter++ * energyRep); |
| 150 | } |
| 151 | |
| 152 | melEnergies[bin] = melEnergy; |
| 153 | } |
| 154 | |
| 155 | return true; |
| 156 | } |
| 157 | |
| 158 | void MFCC::ConvertToLogarithmicScale(std::vector<float>& melEnergies) |
| 159 | { |
| 160 | for (size_t bin = 0; bin < melEnergies.size(); ++bin) { |
| 161 | melEnergies[bin] = logf(melEnergies[bin]); |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | void MFCC::_ConvertToPowerSpectrum() |
| 166 | { |
| 167 | const uint32_t halfDim = this->_m_params.m_frameLenPadded / 2; |
| 168 | |
| 169 | /* Handle this special case. */ |
| 170 | float firstEnergy = this->_m_buffer[0] * this->_m_buffer[0]; |
| 171 | float lastEnergy = this->_m_buffer[1] * this->_m_buffer[1]; |
| 172 | |
| 173 | math::MathUtils::ComplexMagnitudeSquaredF32( |
| 174 | this->_m_buffer.data(), |
| 175 | this->_m_buffer.size(), |
| 176 | this->_m_buffer.data(), |
| 177 | this->_m_buffer.size()/2); |
| 178 | |
| 179 | this->_m_buffer[0] = firstEnergy; |
| 180 | this->_m_buffer[halfDim] = lastEnergy; |
| 181 | } |
| 182 | |
| 183 | std::vector<float> MFCC::CreateDCTMatrix( |
| 184 | const int32_t inputLength, |
| 185 | const int32_t coefficientCount) |
| 186 | { |
| 187 | std::vector<float> dctMatix(inputLength * coefficientCount); |
| 188 | |
| 189 | const float normalizer = math::MathUtils::SqrtF32(2.0f/inputLength); |
| 190 | const float angleIncr = M_PI/inputLength; |
| 191 | float angle = 0; |
| 192 | |
| 193 | for (int32_t k = 0, m = 0; k < coefficientCount; k++, m += inputLength) { |
| 194 | for (int32_t n = 0; n < inputLength; n++) { |
| 195 | dctMatix[m+n] = normalizer * |
| 196 | math::MathUtils::CosineF32((n + 0.5) * angle); |
| 197 | } |
| 198 | angle += angleIncr; |
| 199 | } |
| 200 | |
| 201 | return dctMatix; |
| 202 | } |
| 203 | |
| 204 | float MFCC::GetMelFilterBankNormaliser( |
| 205 | const float& leftMel, |
| 206 | const float& rightMel, |
| 207 | const bool useHTKMethod) |
| 208 | { |
| 209 | UNUSED(leftMel); |
| 210 | UNUSED(rightMel); |
| 211 | UNUSED(useHTKMethod); |
| 212 | |
| 213 | /* By default, no normalisation => return 1 */ |
| 214 | return 1.f; |
| 215 | } |
| 216 | |
| 217 | void MFCC::_InitMelFilterBank() |
| 218 | { |
| 219 | if (!this->_IsMelFilterBankInited()) { |
| 220 | this->_m_melFilterBank = this->_CreateMelFilterBank(); |
| 221 | this->_m_dctMatrix = this->CreateDCTMatrix( |
| 222 | this->_m_params.m_numFbankBins, |
| 223 | this->_m_params.m_numMfccFeatures); |
| 224 | this->_m_filterBankInitialised = true; |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | bool MFCC::_IsMelFilterBankInited() |
| 229 | { |
| 230 | return this->_m_filterBankInitialised; |
| 231 | } |
| 232 | |
| 233 | void MFCC::_MfccComputePreFeature(const std::vector<int16_t>& audioData) |
| 234 | { |
| 235 | this->_InitMelFilterBank(); |
| 236 | |
| 237 | /* TensorFlow way of normalizing .wav data to (-1, 1). */ |
| 238 | constexpr float normaliser = 1.0/(1<<15); |
| 239 | for (size_t i = 0; i < this->_m_params.m_frameLen; i++) { |
| 240 | this->_m_frame[i] = static_cast<float>(audioData[i]) * normaliser; |
| 241 | } |
| 242 | |
| 243 | /* Apply window function to input frame. */ |
| 244 | for(size_t i = 0; i < this->_m_params.m_frameLen; i++) { |
| 245 | this->_m_frame[i] *= this->_m_windowFunc[i]; |
| 246 | } |
| 247 | |
| 248 | /* Set remaining frame values to 0. */ |
| 249 | std::fill(this->_m_frame.begin() + this->_m_params.m_frameLen,this->_m_frame.end(), 0); |
| 250 | |
| 251 | /* Compute FFT. */ |
| 252 | math::MathUtils::FftF32(this->_m_frame, this->_m_buffer, this->_m_fftInstance); |
| 253 | |
| 254 | /* Convert to power spectrum. */ |
| 255 | this->_ConvertToPowerSpectrum(); |
| 256 | |
| 257 | /* Apply mel filterbanks. */ |
| 258 | if (!this->ApplyMelFilterBank(this->_m_buffer, |
| 259 | this->_m_melFilterBank, |
| 260 | this->_m_filterBankFilterFirst, |
| 261 | this->_m_filterBankFilterLast, |
| 262 | this->_m_melEnergies)) { |
| 263 | printf_err("Failed to apply MEL filter banks\n"); |
| 264 | } |
| 265 | |
| 266 | /* Convert to logarithmic scale. */ |
| 267 | this->ConvertToLogarithmicScale(this->_m_melEnergies); |
| 268 | } |
| 269 | |
| 270 | std::vector<float> MFCC::MfccCompute(const std::vector<int16_t>& audioData) |
| 271 | { |
| 272 | this->_MfccComputePreFeature(audioData); |
| 273 | |
| 274 | std::vector<float> mfccOut(this->_m_params.m_numMfccFeatures); |
| 275 | |
| 276 | float * ptrMel = this->_m_melEnergies.data(); |
| 277 | float * ptrDct = this->_m_dctMatrix.data(); |
| 278 | float * ptrMfcc = mfccOut.data(); |
| 279 | |
| 280 | /* Take DCT. Uses matrix mul. */ |
| 281 | for (size_t i = 0, j = 0; i < mfccOut.size(); |
| 282 | ++i, j += this->_m_params.m_numFbankBins) { |
| 283 | *ptrMfcc++ = math::MathUtils::DotProductF32( |
| 284 | ptrDct + j, |
| 285 | ptrMel, |
| 286 | this->_m_params.m_numFbankBins); |
| 287 | } |
| 288 | return mfccOut; |
| 289 | } |
| 290 | |
| 291 | std::vector<std::vector<float>> MFCC::_CreateMelFilterBank() |
| 292 | { |
| 293 | size_t numFftBins = this->_m_params.m_frameLenPadded / 2; |
| 294 | float fftBinWidth = static_cast<float>(this->_m_params.m_samplingFreq) / this->_m_params.m_frameLenPadded; |
| 295 | |
| 296 | float melLowFreq = MFCC::MelScale(this->_m_params.m_melLoFreq, |
| 297 | this->_m_params.m_useHtkMethod); |
| 298 | float melHighFreq = MFCC::MelScale(this->_m_params.m_melHiFreq, |
| 299 | this->_m_params.m_useHtkMethod); |
| 300 | float melFreqDelta = (melHighFreq - melLowFreq) / (this->_m_params.m_numFbankBins + 1); |
| 301 | |
| 302 | std::vector<float> thisBin = std::vector<float>(numFftBins); |
| 303 | std::vector<std::vector<float>> melFilterBank( |
| 304 | this->_m_params.m_numFbankBins); |
| 305 | this->_m_filterBankFilterFirst = |
| 306 | std::vector<int32_t>(this->_m_params.m_numFbankBins); |
| 307 | this->_m_filterBankFilterLast = |
| 308 | std::vector<int32_t>(this->_m_params.m_numFbankBins); |
| 309 | |
| 310 | for (size_t bin = 0; bin < this->_m_params.m_numFbankBins; bin++) { |
| 311 | float leftMel = melLowFreq + bin * melFreqDelta; |
| 312 | float centerMel = melLowFreq + (bin + 1) * melFreqDelta; |
| 313 | float rightMel = melLowFreq + (bin + 2) * melFreqDelta; |
| 314 | |
| 315 | int32_t firstIndex = -1; |
| 316 | int32_t lastIndex = -1; |
| 317 | const float normaliser = this->GetMelFilterBankNormaliser(leftMel, rightMel, this->_m_params.m_useHtkMethod); |
| 318 | |
| 319 | for (size_t i = 0; i < numFftBins; i++) { |
| 320 | float freq = (fftBinWidth * i); /* Center freq of this fft bin. */ |
| 321 | float mel = MFCC::MelScale(freq, this->_m_params.m_useHtkMethod); |
| 322 | thisBin[i] = 0.0; |
| 323 | |
| 324 | if (mel > leftMel && mel < rightMel) { |
| 325 | float weight; |
| 326 | if (mel <= centerMel) { |
| 327 | weight = (mel - leftMel) / (centerMel - leftMel); |
| 328 | } else { |
| 329 | weight = (rightMel - mel) / (rightMel - centerMel); |
| 330 | } |
| 331 | |
| 332 | thisBin[i] = weight * normaliser; |
| 333 | if (firstIndex == -1) { |
| 334 | firstIndex = i; |
| 335 | } |
| 336 | lastIndex = i; |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | this->_m_filterBankFilterFirst[bin] = firstIndex; |
| 341 | this->_m_filterBankFilterLast[bin] = lastIndex; |
| 342 | |
| 343 | /* Copy the part we care about. */ |
| 344 | for (int32_t i = firstIndex; i <= lastIndex; i++) { |
| 345 | melFilterBank[bin].push_back(thisBin[i]); |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | return melFilterBank; |
| 350 | } |
| 351 | |
| 352 | } /* namespace audio */ |
| 353 | } /* namespace app */ |
| 354 | } /* namespace arm */ |