blob: 8085af780ca92ed54e5b7f7d8d97e233715d3109 [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 "UseCaseHandler.hpp"
18
19#include "InputFiles.hpp"
20#include "Classifier.hpp"
Kshitij Sisodia76a15802021-12-24 11:05:11 +000021#include "MicroNetKwsModel.hpp"
alexander3c798932021-03-26 21:42:19 +000022#include "hal.h"
Kshitij Sisodia76a15802021-12-24 11:05:11 +000023#include "MicroNetKwsMfcc.hpp"
alexander3c798932021-03-26 21:42:19 +000024#include "AudioUtils.hpp"
25#include "UseCaseCommonUtils.hpp"
26#include "KwsResult.hpp"
27
28#include <vector>
29#include <functional>
30
31using KwsClassifier = arm::app::Classifier;
32
33namespace arm {
34namespace app {
35
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010036
alexander3c798932021-03-26 21:42:19 +000037 /**
38 * @brief Presents inference results using the data presentation
39 * object.
40 * @param[in] platform Reference to the hal platform object.
41 * @param[in] results Vector of classification results to be displayed.
alexander3c798932021-03-26 21:42:19 +000042 * @return true if successful, false otherwise.
43 **/
alexanderc350cdc2021-04-29 20:36:09 +010044 static bool PresentInferenceResult(hal_platform& platform,
45 const std::vector<arm::app::kws::KwsResult>& results);
alexander3c798932021-03-26 21:42:19 +000046
47 /**
48 * @brief Returns a function to perform feature calculation and populates input tensor data with
49 * MFCC data.
50 *
51 * Input tensor data type check is performed to choose correct MFCC feature data type.
52 * If tensor has an integer data type then original features are quantised.
53 *
54 * Warning: MFCC calculator provided as input must have the same life scope as returned function.
55 *
56 * @param[in] mfcc MFCC feature calculator.
57 * @param[in,out] inputTensor Input tensor pointer to store calculated features.
58 * @param[in] cacheSize Size of the feature vectors cache (number of feature vectors).
59 * @return Function to be called providing audio sample and sliding window index.
60 */
61 static std::function<void (std::vector<int16_t>&, int, bool, size_t)>
Kshitij Sisodia76a15802021-12-24 11:05:11 +000062 GetFeatureCalculator(audio::MicroNetKwsMFCC& mfcc,
alexander3c798932021-03-26 21:42:19 +000063 TfLiteTensor* inputTensor,
64 size_t cacheSize);
65
66 /* Audio inference handler. */
67 bool ClassifyAudioHandler(ApplicationContext& ctx, uint32_t clipIndex, bool runAll)
68 {
69 auto& platform = ctx.Get<hal_platform&>("platform");
Isabella Gottardi8df12f32021-04-07 17:15:31 +010070 auto& profiler = ctx.Get<Profiler&>("profiler");
alexander3c798932021-03-26 21:42:19 +000071
72 constexpr uint32_t dataPsnTxtInfStartX = 20;
73 constexpr uint32_t dataPsnTxtInfStartY = 40;
74 constexpr int minTensorDims = static_cast<int>(
Kshitij Sisodia76a15802021-12-24 11:05:11 +000075 (arm::app::MicroNetKwsModel::ms_inputRowsIdx > arm::app::MicroNetKwsModel::ms_inputColsIdx)?
76 arm::app::MicroNetKwsModel::ms_inputRowsIdx : arm::app::MicroNetKwsModel::ms_inputColsIdx);
alexander3c798932021-03-26 21:42:19 +000077
alexander3c798932021-03-26 21:42:19 +000078 auto& model = ctx.Get<Model&>("model");
79
80 /* If the request has a valid size, set the audio index. */
81 if (clipIndex < NUMBER_OF_FILES) {
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010082 if (!SetAppCtxIfmIdx(ctx, clipIndex,"clipIndex")) {
alexander3c798932021-03-26 21:42:19 +000083 return false;
84 }
85 }
86 if (!model.IsInited()) {
87 printf_err("Model is not initialised! Terminating processing.\n");
88 return false;
89 }
90
91 const auto frameLength = ctx.Get<int>("frameLength");
92 const auto frameStride = ctx.Get<int>("frameStride");
93 const auto scoreThreshold = ctx.Get<float>("scoreThreshold");
94 auto startClipIdx = ctx.Get<uint32_t>("clipIndex");
95
96 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
97 TfLiteTensor* inputTensor = model.GetInputTensor(0);
98
99 if (!inputTensor->dims) {
100 printf_err("Invalid input tensor dims\n");
101 return false;
102 } else if (inputTensor->dims->size < minTensorDims) {
103 printf_err("Input tensor dimension should be >= %d\n", minTensorDims);
104 return false;
105 }
106
107 TfLiteIntArray* inputShape = model.GetInputShape(0);
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000108 const uint32_t kNumCols = inputShape->data[arm::app::MicroNetKwsModel::ms_inputColsIdx];
109 const uint32_t kNumRows = inputShape->data[arm::app::MicroNetKwsModel::ms_inputRowsIdx];
alexander3c798932021-03-26 21:42:19 +0000110
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000111 audio::MicroNetKwsMFCC mfcc = audio::MicroNetKwsMFCC(kNumCols, frameLength);
alexander3c798932021-03-26 21:42:19 +0000112 mfcc.Init();
113
114 /* Deduce the data length required for 1 inference from the network parameters. */
115 auto audioDataWindowSize = kNumRows * frameStride + (frameLength - frameStride);
116 auto mfccWindowSize = frameLength;
117 auto mfccWindowStride = frameStride;
118
119 /* We choose to move by half the window size => for a 1 second window size
120 * there is an overlap of 0.5 seconds. */
121 auto audioDataStride = audioDataWindowSize / 2;
122
123 /* To have the previously calculated features re-usable, stride must be multiple
124 * of MFCC features window stride. */
125 if (0 != audioDataStride % mfccWindowStride) {
126
127 /* Reduce the stride. */
128 audioDataStride -= audioDataStride % mfccWindowStride;
129 }
130
131 auto nMfccVectorsInAudioStride = audioDataStride/mfccWindowStride;
132
133 /* We expect to be sampling 1 second worth of data at a time.
134 * NOTE: This is only used for time stamp calculation. */
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000135 const float secondsPerSample = 1.0/audio::MicroNetKwsMFCC::ms_defaultSamplingFreq;
alexander3c798932021-03-26 21:42:19 +0000136
137 do {
Richard Burton9b8d67a2021-12-10 12:32:51 +0000138 platform.data_psn->clear(COLOR_BLACK);
139
alexander3c798932021-03-26 21:42:19 +0000140 auto currentIndex = ctx.Get<uint32_t>("clipIndex");
141
142 /* Creating a mfcc features sliding window for the data required for 1 inference. */
143 auto audioMFCCWindowSlider = audio::SlidingWindow<const int16_t>(
144 get_audio_array(currentIndex),
145 audioDataWindowSize, mfccWindowSize,
146 mfccWindowStride);
147
148 /* Creating a sliding window through the whole audio clip. */
149 auto audioDataSlider = audio::SlidingWindow<const int16_t>(
150 get_audio_array(currentIndex),
151 get_audio_array_size(currentIndex),
152 audioDataWindowSize, audioDataStride);
153
154 /* Calculate number of the feature vectors in the window overlap region.
155 * These feature vectors will be reused.*/
156 auto numberOfReusedFeatureVectors = audioMFCCWindowSlider.TotalStrides() + 1
157 - nMfccVectorsInAudioStride;
158
159 /* Construct feature calculation function. */
160 auto mfccFeatureCalc = GetFeatureCalculator(mfcc, inputTensor,
161 numberOfReusedFeatureVectors);
162
163 if (!mfccFeatureCalc){
164 return false;
165 }
166
167 /* Declare a container for results. */
168 std::vector<arm::app::kws::KwsResult> results;
169
170 /* Display message on the LCD - inference running. */
171 std::string str_inf{"Running inference... "};
172 platform.data_psn->present_data_text(
173 str_inf.c_str(), str_inf.size(),
174 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100175 info("Running inference on audio clip %" PRIu32 " => %s\n", currentIndex,
alexander3c798932021-03-26 21:42:19 +0000176 get_filename(currentIndex));
177
178 /* Start sliding through audio clip. */
179 while (audioDataSlider.HasNext()) {
180 const int16_t *inferenceWindow = audioDataSlider.Next();
181
182 /* We moved to the next window - set the features sliding to the new address. */
183 audioMFCCWindowSlider.Reset(inferenceWindow);
184
185 /* The first window does not have cache ready. */
186 bool useCache = audioDataSlider.Index() > 0 && numberOfReusedFeatureVectors > 0;
187
188 /* Start calculating features inside one audio sliding window. */
189 while (audioMFCCWindowSlider.HasNext()) {
190 const int16_t *mfccWindow = audioMFCCWindowSlider.Next();
191 std::vector<int16_t> mfccAudioData = std::vector<int16_t>(mfccWindow,
192 mfccWindow + mfccWindowSize);
193 /* Compute features for this window and write them to input tensor. */
194 mfccFeatureCalc(mfccAudioData,
195 audioMFCCWindowSlider.Index(),
196 useCache,
197 nMfccVectorsInAudioStride);
198 }
199
200 info("Inference %zu/%zu\n", audioDataSlider.Index() + 1,
201 audioDataSlider.TotalStrides() + 1);
202
203 /* Run inference over this audio clip sliding window. */
alexander27b62d92021-05-04 20:46:08 +0100204 if (!RunInference(model, profiler)) {
205 return false;
206 }
alexander3c798932021-03-26 21:42:19 +0000207
208 std::vector<ClassificationResult> classificationResult;
209 auto& classifier = ctx.Get<KwsClassifier&>("classifier");
210 classifier.GetClassificationResults(outputTensor, classificationResult,
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000211 ctx.Get<std::vector<std::string>&>("labels"), 1, true);
alexander3c798932021-03-26 21:42:19 +0000212
213 results.emplace_back(kws::KwsResult(classificationResult,
214 audioDataSlider.Index() * secondsPerSample * audioDataStride,
215 audioDataSlider.Index(), scoreThreshold));
216
217#if VERIFY_TEST_OUTPUT
218 arm::app::DumpTensor(outputTensor);
219#endif /* VERIFY_TEST_OUTPUT */
220 } /* while (audioDataSlider.HasNext()) */
221
222 /* Erase. */
223 str_inf = std::string(str_inf.size(), ' ');
224 platform.data_psn->present_data_text(
225 str_inf.c_str(), str_inf.size(),
226 dataPsnTxtInfStartX, dataPsnTxtInfStartY, false);
227
228 ctx.Set<std::vector<arm::app::kws::KwsResult>>("results", results);
229
alexanderc350cdc2021-04-29 20:36:09 +0100230 if (!PresentInferenceResult(platform, results)) {
alexander3c798932021-03-26 21:42:19 +0000231 return false;
232 }
233
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100234 profiler.PrintProfilingResult();
235
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100236 IncrementAppCtxIfmIdx(ctx,"clipIndex");
alexander3c798932021-03-26 21:42:19 +0000237
238 } while (runAll && ctx.Get<uint32_t>("clipIndex") != startClipIdx);
239
240 return true;
241 }
242
alexanderc350cdc2021-04-29 20:36:09 +0100243 static bool PresentInferenceResult(hal_platform& platform,
244 const std::vector<arm::app::kws::KwsResult>& results)
alexander3c798932021-03-26 21:42:19 +0000245 {
246 constexpr uint32_t dataPsnTxtStartX1 = 20;
247 constexpr uint32_t dataPsnTxtStartY1 = 30;
248 constexpr uint32_t dataPsnTxtYIncr = 16; /* Row index increment. */
249
250 platform.data_psn->set_text_color(COLOR_GREEN);
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100251 info("Final results:\n");
252 info("Total number of inferences: %zu\n", results.size());
alexander3c798932021-03-26 21:42:19 +0000253
254 /* Display each result */
255 uint32_t rowIdx1 = dataPsnTxtStartY1 + 2 * dataPsnTxtYIncr;
256
257 for (uint32_t i = 0; i < results.size(); ++i) {
258
259 std::string topKeyword{"<none>"};
260 float score = 0.f;
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100261 if (!results[i].m_resultVec.empty()) {
alexander3c798932021-03-26 21:42:19 +0000262 topKeyword = results[i].m_resultVec[0].m_label;
263 score = results[i].m_resultVec[0].m_normalisedVal;
264 }
265
266 std::string resultStr =
267 std::string{"@"} + std::to_string(results[i].m_timeStamp) +
268 std::string{"s: "} + topKeyword + std::string{" ("} +
269 std::to_string(static_cast<int>(score * 100)) + std::string{"%)"};
270
271 platform.data_psn->present_data_text(
272 resultStr.c_str(), resultStr.size(),
273 dataPsnTxtStartX1, rowIdx1, false);
274 rowIdx1 += dataPsnTxtYIncr;
275
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100276 if (results[i].m_resultVec.empty()) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100277 info("For timestamp: %f (inference #: %" PRIu32
278 "); label: %s; threshold: %f\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100279 results[i].m_timeStamp, results[i].m_inferenceNumber,
280 topKeyword.c_str(),
281 results[i].m_threshold);
282 } else {
283 for (uint32_t j = 0; j < results[i].m_resultVec.size(); ++j) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100284 info("For timestamp: %f (inference #: %" PRIu32
285 "); label: %s, score: %f; threshold: %f\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100286 results[i].m_timeStamp,
287 results[i].m_inferenceNumber,
288 results[i].m_resultVec[j].m_label.c_str(),
289 results[i].m_resultVec[j].m_normalisedVal,
290 results[i].m_threshold);
291 }
alexander3c798932021-03-26 21:42:19 +0000292 }
293 }
294
295 return true;
296 }
297
298 /**
299 * @brief Generic feature calculator factory.
300 *
301 * Returns lambda function to compute features using features cache.
302 * Real features math is done by a lambda function provided as a parameter.
303 * Features are written to input tensor memory.
304 *
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100305 * @tparam T Feature vector type.
306 * @param[in] inputTensor Model input tensor pointer.
307 * @param[in] cacheSize Number of feature vectors to cache. Defined by the sliding window overlap.
308 * @param[in] compute Features calculator function.
309 * @return Lambda function to compute features.
alexander3c798932021-03-26 21:42:19 +0000310 */
311 template<class T>
312 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100313 FeatureCalc(TfLiteTensor* inputTensor, size_t cacheSize,
314 std::function<std::vector<T> (std::vector<int16_t>& )> compute)
alexander3c798932021-03-26 21:42:19 +0000315 {
316 /* Feature cache to be captured by lambda function. */
317 static std::vector<std::vector<T>> featureCache = std::vector<std::vector<T>>(cacheSize);
318
319 return [=](std::vector<int16_t>& audioDataWindow,
320 size_t index,
321 bool useCache,
322 size_t featuresOverlapIndex)
323 {
324 T *tensorData = tflite::GetTensorData<T>(inputTensor);
325 std::vector<T> features;
326
327 /* Reuse features from cache if cache is ready and sliding windows overlap.
328 * Overlap is in the beginning of sliding window with a size of a feature cache. */
329 if (useCache && index < featureCache.size()) {
330 features = std::move(featureCache[index]);
331 } else {
332 features = std::move(compute(audioDataWindow));
333 }
334 auto size = features.size();
335 auto sizeBytes = sizeof(T) * size;
336 std::memcpy(tensorData + (index * size), features.data(), sizeBytes);
337
338 /* Start renewing cache as soon iteration goes out of the windows overlap. */
339 if (index >= featuresOverlapIndex) {
340 featureCache[index - featuresOverlapIndex] = std::move(features);
341 }
342 };
343 }
344
345 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100346 FeatureCalc<int8_t>(TfLiteTensor* inputTensor,
alexander3c798932021-03-26 21:42:19 +0000347 size_t cacheSize,
348 std::function<std::vector<int8_t> (std::vector<int16_t>& )> compute);
349
350 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100351 FeatureCalc<uint8_t>(TfLiteTensor* inputTensor,
352 size_t cacheSize,
353 std::function<std::vector<uint8_t> (std::vector<int16_t>& )> compute);
alexander3c798932021-03-26 21:42:19 +0000354
355 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100356 FeatureCalc<int16_t>(TfLiteTensor* inputTensor,
357 size_t cacheSize,
358 std::function<std::vector<int16_t> (std::vector<int16_t>& )> compute);
alexander3c798932021-03-26 21:42:19 +0000359
360 template std::function<void(std::vector<int16_t>&, size_t, bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100361 FeatureCalc<float>(TfLiteTensor* inputTensor,
362 size_t cacheSize,
363 std::function<std::vector<float>(std::vector<int16_t>&)> compute);
alexander3c798932021-03-26 21:42:19 +0000364
365
366 static std::function<void (std::vector<int16_t>&, int, bool, size_t)>
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000367 GetFeatureCalculator(audio::MicroNetKwsMFCC& mfcc, TfLiteTensor* inputTensor, size_t cacheSize)
alexander3c798932021-03-26 21:42:19 +0000368 {
369 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)> mfccFeatureCalc;
370
371 TfLiteQuantization quant = inputTensor->quantization;
372
373 if (kTfLiteAffineQuantization == quant.type) {
374
375 auto *quantParams = (TfLiteAffineQuantization *) quant.params;
376 const float quantScale = quantParams->scale->data[0];
377 const int quantOffset = quantParams->zero_point->data[0];
378
379 switch (inputTensor->type) {
380 case kTfLiteInt8: {
alexanderc350cdc2021-04-29 20:36:09 +0100381 mfccFeatureCalc = FeatureCalc<int8_t>(inputTensor,
382 cacheSize,
383 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
384 return mfcc.MfccComputeQuant<int8_t>(audioDataWindow,
385 quantScale,
386 quantOffset);
387 }
alexander3c798932021-03-26 21:42:19 +0000388 );
389 break;
390 }
391 case kTfLiteUInt8: {
alexanderc350cdc2021-04-29 20:36:09 +0100392 mfccFeatureCalc = FeatureCalc<uint8_t>(inputTensor,
393 cacheSize,
alexander3c798932021-03-26 21:42:19 +0000394 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
395 return mfcc.MfccComputeQuant<uint8_t>(audioDataWindow,
396 quantScale,
397 quantOffset);
398 }
399 );
400 break;
401 }
402 case kTfLiteInt16: {
alexanderc350cdc2021-04-29 20:36:09 +0100403 mfccFeatureCalc = FeatureCalc<int16_t>(inputTensor,
404 cacheSize,
405 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
406 return mfcc.MfccComputeQuant<int16_t>(audioDataWindow,
407 quantScale,
408 quantOffset);
409 }
alexander3c798932021-03-26 21:42:19 +0000410 );
411 break;
412 }
413 default:
414 printf_err("Tensor type %s not supported\n", TfLiteTypeGetName(inputTensor->type));
415 }
416
417
418 } else {
alexanderc350cdc2021-04-29 20:36:09 +0100419 mfccFeatureCalc = mfccFeatureCalc = FeatureCalc<float>(inputTensor,
420 cacheSize,
421 [&mfcc](std::vector<int16_t>& audioDataWindow) {
422 return mfcc.MfccCompute(audioDataWindow);
423 });
alexander3c798932021-03-26 21:42:19 +0000424 }
425 return mfccFeatureCalc;
426 }
427
428} /* namespace app */
429} /* namespace arm */