blob: 843ac583ca72a950700a88e7b711328e87951a77 [file] [log] [blame]
Richard Burtone6398cd2022-04-13 11:58:28 +01001/*
2 * Copyright (c) 2022 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 "KwsProcessing.hpp"
Richard Burtone6398cd2022-04-13 11:58:28 +010018#include "log_macros.h"
19#include "MicroNetKwsModel.hpp"
20
21namespace arm {
22namespace app {
23
Richard Burtonb40ecf82022-04-22 16:14:57 +010024 KwsPreProcess::KwsPreProcess(TfLiteTensor* inputTensor, size_t numFeatures, size_t numMfccFrames,
25 int mfccFrameLength, int mfccFrameStride
26 ):
27 m_inputTensor{inputTensor},
Richard Burtone6398cd2022-04-13 11:58:28 +010028 m_mfccFrameLength{mfccFrameLength},
29 m_mfccFrameStride{mfccFrameStride},
Richard Burtonb40ecf82022-04-22 16:14:57 +010030 m_numMfccFrames{numMfccFrames},
Richard Burtone6398cd2022-04-13 11:58:28 +010031 m_mfcc{audio::MicroNetKwsMFCC(numFeatures, mfccFrameLength)}
32 {
Richard Burtone6398cd2022-04-13 11:58:28 +010033 this->m_mfcc.Init();
34
Richard Burtone6398cd2022-04-13 11:58:28 +010035 /* Deduce the data length required for 1 inference from the network parameters. */
Richard Burtonb40ecf82022-04-22 16:14:57 +010036 this->m_audioDataWindowSize = this->m_numMfccFrames * this->m_mfccFrameStride +
Richard Burtone6398cd2022-04-13 11:58:28 +010037 (this->m_mfccFrameLength - this->m_mfccFrameStride);
38
39 /* Creating an MFCC feature sliding window for the data required for 1 inference. */
40 this->m_mfccSlidingWindow = audio::SlidingWindow<const int16_t>(nullptr, this->m_audioDataWindowSize,
41 this->m_mfccFrameLength, this->m_mfccFrameStride);
42
43 /* For longer audio clips we choose to move by half the audio window size
44 * => for a 1 second window size there is an overlap of 0.5 seconds. */
45 this->m_audioDataStride = this->m_audioDataWindowSize / 2;
46
47 /* To have the previously calculated features re-usable, stride must be multiple
48 * of MFCC features window stride. Reduce stride through audio if needed. */
49 if (0 != this->m_audioDataStride % this->m_mfccFrameStride) {
50 this->m_audioDataStride -= this->m_audioDataStride % this->m_mfccFrameStride;
51 }
52
53 this->m_numMfccVectorsInAudioStride = this->m_audioDataStride / this->m_mfccFrameStride;
54
55 /* Calculate number of the feature vectors in the window overlap region.
56 * These feature vectors will be reused.*/
57 this->m_numReusedMfccVectors = this->m_mfccSlidingWindow.TotalStrides() + 1
58 - this->m_numMfccVectorsInAudioStride;
59
60 /* Construct feature calculation function. */
Richard Burtonb40ecf82022-04-22 16:14:57 +010061 this->m_mfccFeatureCalculator = GetFeatureCalculator(this->m_mfcc, this->m_inputTensor,
Richard Burtone6398cd2022-04-13 11:58:28 +010062 this->m_numReusedMfccVectors);
63
64 if (!this->m_mfccFeatureCalculator) {
65 printf_err("Feature calculator not initialized.");
66 }
67 }
68
Richard Burtonec5e99b2022-10-05 11:00:37 +010069 bool KwsPreProcess::DoPreProcess(const void* data, size_t inferenceIndex)
Richard Burtone6398cd2022-04-13 11:58:28 +010070 {
Richard Burtone6398cd2022-04-13 11:58:28 +010071 if (data == nullptr) {
72 printf_err("Data pointer is null");
73 }
74
75 /* Set the features sliding window to the new address. */
76 auto input = static_cast<const int16_t*>(data);
77 this->m_mfccSlidingWindow.Reset(input);
78
Richard Burtonec5e99b2022-10-05 11:00:37 +010079 /* Cache is only usable if we have more than 1 inference to do and it's not the first inference. */
80 bool useCache = inferenceIndex > 0 && this->m_numReusedMfccVectors > 0;
Richard Burtone6398cd2022-04-13 11:58:28 +010081
82 /* Use a sliding window to calculate MFCC features frame by frame. */
83 while (this->m_mfccSlidingWindow.HasNext()) {
84 const int16_t* mfccWindow = this->m_mfccSlidingWindow.Next();
85
86 std::vector<int16_t> mfccFrameAudioData = std::vector<int16_t>(mfccWindow,
87 mfccWindow + this->m_mfccFrameLength);
88
89 /* Compute features for this window and write them to input tensor. */
90 this->m_mfccFeatureCalculator(mfccFrameAudioData, this->m_mfccSlidingWindow.Index(),
91 useCache, this->m_numMfccVectorsInAudioStride);
92 }
93
94 debug("Input tensor populated \n");
95
96 return true;
97 }
98
99 /**
100 * @brief Generic feature calculator factory.
101 *
102 * Returns lambda function to compute features using features cache.
103 * Real features math is done by a lambda function provided as a parameter.
104 * Features are written to input tensor memory.
105 *
106 * @tparam T Feature vector type.
107 * @param[in] inputTensor Model input tensor pointer.
108 * @param[in] cacheSize Number of feature vectors to cache. Defined by the sliding window overlap.
109 * @param[in] compute Features calculator function.
110 * @return Lambda function to compute features.
111 */
112 template<class T>
113 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)>
Richard Burtonb40ecf82022-04-22 16:14:57 +0100114 KwsPreProcess::FeatureCalc(TfLiteTensor* inputTensor, size_t cacheSize,
115 std::function<std::vector<T> (std::vector<int16_t>& )> compute)
Richard Burtone6398cd2022-04-13 11:58:28 +0100116 {
117 /* Feature cache to be captured by lambda function. */
118 static std::vector<std::vector<T>> featureCache = std::vector<std::vector<T>>(cacheSize);
119
120 return [=](std::vector<int16_t>& audioDataWindow,
121 size_t index,
122 bool useCache,
123 size_t featuresOverlapIndex)
124 {
125 T* tensorData = tflite::GetTensorData<T>(inputTensor);
126 std::vector<T> features;
127
128 /* Reuse features from cache if cache is ready and sliding windows overlap.
129 * Overlap is in the beginning of sliding window with a size of a feature cache. */
130 if (useCache && index < featureCache.size()) {
131 features = std::move(featureCache[index]);
132 } else {
133 features = std::move(compute(audioDataWindow));
134 }
135 auto size = features.size();
136 auto sizeBytes = sizeof(T) * size;
137 std::memcpy(tensorData + (index * size), features.data(), sizeBytes);
138
139 /* Start renewing cache as soon iteration goes out of the windows overlap. */
140 if (index >= featuresOverlapIndex) {
141 featureCache[index - featuresOverlapIndex] = std::move(features);
142 }
143 };
144 }
145
146 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
Richard Burtonb40ecf82022-04-22 16:14:57 +0100147 KwsPreProcess::FeatureCalc<int8_t>(TfLiteTensor* inputTensor,
148 size_t cacheSize,
149 std::function<std::vector<int8_t> (std::vector<int16_t>&)> compute);
Richard Burtone6398cd2022-04-13 11:58:28 +0100150
151 template std::function<void(std::vector<int16_t>&, size_t, bool, size_t)>
Richard Burtonb40ecf82022-04-22 16:14:57 +0100152 KwsPreProcess::FeatureCalc<float>(TfLiteTensor* inputTensor,
153 size_t cacheSize,
154 std::function<std::vector<float>(std::vector<int16_t>&)> compute);
Richard Burtone6398cd2022-04-13 11:58:28 +0100155
156
157 std::function<void (std::vector<int16_t>&, int, bool, size_t)>
Richard Burtonb40ecf82022-04-22 16:14:57 +0100158 KwsPreProcess::GetFeatureCalculator(audio::MicroNetKwsMFCC& mfcc, TfLiteTensor* inputTensor, size_t cacheSize)
Richard Burtone6398cd2022-04-13 11:58:28 +0100159 {
Maksims Svecovs154a2b12022-08-30 11:53:19 +0100160 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)> mfccFeatureCalc = nullptr;
Richard Burtone6398cd2022-04-13 11:58:28 +0100161
162 TfLiteQuantization quant = inputTensor->quantization;
163
164 if (kTfLiteAffineQuantization == quant.type) {
Richard Burtonec5e99b2022-10-05 11:00:37 +0100165 auto* quantParams = (TfLiteAffineQuantization*) quant.params;
Richard Burtone6398cd2022-04-13 11:58:28 +0100166 const float quantScale = quantParams->scale->data[0];
167 const int quantOffset = quantParams->zero_point->data[0];
168
169 switch (inputTensor->type) {
170 case kTfLiteInt8: {
171 mfccFeatureCalc = this->FeatureCalc<int8_t>(inputTensor,
172 cacheSize,
173 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
174 return mfcc.MfccComputeQuant<int8_t>(audioDataWindow,
175 quantScale,
176 quantOffset);
177 }
178 );
179 break;
180 }
181 default:
182 printf_err("Tensor type %s not supported\n", TfLiteTypeGetName(inputTensor->type));
183 }
184 } else {
185 mfccFeatureCalc = this->FeatureCalc<float>(inputTensor, cacheSize,
186 [&mfcc](std::vector<int16_t>& audioDataWindow) {
187 return mfcc.MfccCompute(audioDataWindow); }
188 );
189 }
190 return mfccFeatureCalc;
191 }
192
Richard Burtonec5e99b2022-10-05 11:00:37 +0100193 KwsPostProcess::KwsPostProcess(TfLiteTensor* outputTensor, KwsClassifier& classifier,
Richard Burtone6398cd2022-04-13 11:58:28 +0100194 const std::vector<std::string>& labels,
Richard Burtonec5e99b2022-10-05 11:00:37 +0100195 std::vector<ClassificationResult>& results, size_t averagingWindowLen)
Richard Burtonb40ecf82022-04-22 16:14:57 +0100196 :m_outputTensor{outputTensor},
197 m_kwsClassifier{classifier},
Richard Burtone6398cd2022-04-13 11:58:28 +0100198 m_labels{labels},
Richard Burtonc2911442022-04-22 09:08:21 +0100199 m_results{results}
Richard Burtonec5e99b2022-10-05 11:00:37 +0100200 {
201 this->m_resultHistory = {averagingWindowLen, std::vector<float>(labels.size())};
202 }
Richard Burtone6398cd2022-04-13 11:58:28 +0100203
Richard Burtonb40ecf82022-04-22 16:14:57 +0100204 bool KwsPostProcess::DoPostProcess()
Richard Burtone6398cd2022-04-13 11:58:28 +0100205 {
206 return this->m_kwsClassifier.GetClassificationResults(
Richard Burtonb40ecf82022-04-22 16:14:57 +0100207 this->m_outputTensor, this->m_results,
Richard Burtonec5e99b2022-10-05 11:00:37 +0100208 this->m_labels, 1, true, this->m_resultHistory);
Richard Burtone6398cd2022-04-13 11:58:28 +0100209 }
210
211} /* namespace app */
212} /* namespace arm */