blob: 8dd7724cf4c70ba4aa93ae5eada192d33838ebf9 [file] [log] [blame]
alexander3c798932021-03-26 21:42:19 +00001/*
Richard Burtoned35a6f2022-02-14 11:55:35 +00002 * Copyright (c) 2021-2022 Arm Limited. All rights reserved.
alexander3c798932021-03-26 21:42:19 +00003 * 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"
Richard Burtoned35a6f2022-02-14 11:55:35 +000025#include "ImageUtils.hpp"
alexander3c798932021-03-26 21:42:19 +000026#include "UseCaseCommonUtils.hpp"
27#include "KwsResult.hpp"
alexander31ae9f02022-02-10 16:15:54 +000028#include "log_macros.h"
alexander3c798932021-03-26 21:42:19 +000029
30#include <vector>
31#include <functional>
32
33using KwsClassifier = arm::app::Classifier;
34
35namespace arm {
36namespace app {
37
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010038
alexander3c798932021-03-26 21:42:19 +000039 /**
40 * @brief Presents inference results using the data presentation
41 * object.
42 * @param[in] platform Reference to the hal platform object.
43 * @param[in] results Vector of classification results to be displayed.
alexander3c798932021-03-26 21:42:19 +000044 * @return true if successful, false otherwise.
45 **/
alexanderc350cdc2021-04-29 20:36:09 +010046 static bool PresentInferenceResult(hal_platform& platform,
47 const std::vector<arm::app::kws::KwsResult>& results);
alexander3c798932021-03-26 21:42:19 +000048
49 /**
50 * @brief Returns a function to perform feature calculation and populates input tensor data with
51 * MFCC data.
52 *
53 * Input tensor data type check is performed to choose correct MFCC feature data type.
54 * If tensor has an integer data type then original features are quantised.
55 *
56 * Warning: MFCC calculator provided as input must have the same life scope as returned function.
57 *
58 * @param[in] mfcc MFCC feature calculator.
59 * @param[in,out] inputTensor Input tensor pointer to store calculated features.
60 * @param[in] cacheSize Size of the feature vectors cache (number of feature vectors).
61 * @return Function to be called providing audio sample and sliding window index.
62 */
63 static std::function<void (std::vector<int16_t>&, int, bool, size_t)>
Kshitij Sisodia76a15802021-12-24 11:05:11 +000064 GetFeatureCalculator(audio::MicroNetKwsMFCC& mfcc,
alexander3c798932021-03-26 21:42:19 +000065 TfLiteTensor* inputTensor,
66 size_t cacheSize);
67
68 /* Audio inference handler. */
69 bool ClassifyAudioHandler(ApplicationContext& ctx, uint32_t clipIndex, bool runAll)
70 {
71 auto& platform = ctx.Get<hal_platform&>("platform");
Isabella Gottardi8df12f32021-04-07 17:15:31 +010072 auto& profiler = ctx.Get<Profiler&>("profiler");
alexander3c798932021-03-26 21:42:19 +000073
74 constexpr uint32_t dataPsnTxtInfStartX = 20;
75 constexpr uint32_t dataPsnTxtInfStartY = 40;
76 constexpr int minTensorDims = static_cast<int>(
Kshitij Sisodia76a15802021-12-24 11:05:11 +000077 (arm::app::MicroNetKwsModel::ms_inputRowsIdx > arm::app::MicroNetKwsModel::ms_inputColsIdx)?
78 arm::app::MicroNetKwsModel::ms_inputRowsIdx : arm::app::MicroNetKwsModel::ms_inputColsIdx);
alexander3c798932021-03-26 21:42:19 +000079
alexander3c798932021-03-26 21:42:19 +000080 auto& model = ctx.Get<Model&>("model");
81
82 /* If the request has a valid size, set the audio index. */
83 if (clipIndex < NUMBER_OF_FILES) {
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010084 if (!SetAppCtxIfmIdx(ctx, clipIndex,"clipIndex")) {
alexander3c798932021-03-26 21:42:19 +000085 return false;
86 }
87 }
88 if (!model.IsInited()) {
89 printf_err("Model is not initialised! Terminating processing.\n");
90 return false;
91 }
92
93 const auto frameLength = ctx.Get<int>("frameLength");
94 const auto frameStride = ctx.Get<int>("frameStride");
95 const auto scoreThreshold = ctx.Get<float>("scoreThreshold");
96 auto startClipIdx = ctx.Get<uint32_t>("clipIndex");
97
98 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
99 TfLiteTensor* inputTensor = model.GetInputTensor(0);
100
101 if (!inputTensor->dims) {
102 printf_err("Invalid input tensor dims\n");
103 return false;
104 } else if (inputTensor->dims->size < minTensorDims) {
105 printf_err("Input tensor dimension should be >= %d\n", minTensorDims);
106 return false;
107 }
108
109 TfLiteIntArray* inputShape = model.GetInputShape(0);
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000110 const uint32_t kNumCols = inputShape->data[arm::app::MicroNetKwsModel::ms_inputColsIdx];
111 const uint32_t kNumRows = inputShape->data[arm::app::MicroNetKwsModel::ms_inputRowsIdx];
alexander3c798932021-03-26 21:42:19 +0000112
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000113 audio::MicroNetKwsMFCC mfcc = audio::MicroNetKwsMFCC(kNumCols, frameLength);
alexander3c798932021-03-26 21:42:19 +0000114 mfcc.Init();
115
116 /* Deduce the data length required for 1 inference from the network parameters. */
117 auto audioDataWindowSize = kNumRows * frameStride + (frameLength - frameStride);
118 auto mfccWindowSize = frameLength;
119 auto mfccWindowStride = frameStride;
120
121 /* We choose to move by half the window size => for a 1 second window size
122 * there is an overlap of 0.5 seconds. */
123 auto audioDataStride = audioDataWindowSize / 2;
124
125 /* To have the previously calculated features re-usable, stride must be multiple
126 * of MFCC features window stride. */
127 if (0 != audioDataStride % mfccWindowStride) {
128
129 /* Reduce the stride. */
130 audioDataStride -= audioDataStride % mfccWindowStride;
131 }
132
133 auto nMfccVectorsInAudioStride = audioDataStride/mfccWindowStride;
134
135 /* We expect to be sampling 1 second worth of data at a time.
136 * NOTE: This is only used for time stamp calculation. */
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000137 const float secondsPerSample = 1.0/audio::MicroNetKwsMFCC::ms_defaultSamplingFreq;
alexander3c798932021-03-26 21:42:19 +0000138
139 do {
Richard Burton9b8d67a2021-12-10 12:32:51 +0000140 platform.data_psn->clear(COLOR_BLACK);
141
alexander3c798932021-03-26 21:42:19 +0000142 auto currentIndex = ctx.Get<uint32_t>("clipIndex");
143
144 /* Creating a mfcc features sliding window for the data required for 1 inference. */
145 auto audioMFCCWindowSlider = audio::SlidingWindow<const int16_t>(
146 get_audio_array(currentIndex),
147 audioDataWindowSize, mfccWindowSize,
148 mfccWindowStride);
149
150 /* Creating a sliding window through the whole audio clip. */
151 auto audioDataSlider = audio::SlidingWindow<const int16_t>(
152 get_audio_array(currentIndex),
153 get_audio_array_size(currentIndex),
154 audioDataWindowSize, audioDataStride);
155
156 /* Calculate number of the feature vectors in the window overlap region.
157 * These feature vectors will be reused.*/
158 auto numberOfReusedFeatureVectors = audioMFCCWindowSlider.TotalStrides() + 1
159 - nMfccVectorsInAudioStride;
160
161 /* Construct feature calculation function. */
162 auto mfccFeatureCalc = GetFeatureCalculator(mfcc, inputTensor,
163 numberOfReusedFeatureVectors);
164
165 if (!mfccFeatureCalc){
166 return false;
167 }
168
169 /* Declare a container for results. */
170 std::vector<arm::app::kws::KwsResult> results;
171
172 /* Display message on the LCD - inference running. */
173 std::string str_inf{"Running inference... "};
174 platform.data_psn->present_data_text(
175 str_inf.c_str(), str_inf.size(),
176 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100177 info("Running inference on audio clip %" PRIu32 " => %s\n", currentIndex,
alexander3c798932021-03-26 21:42:19 +0000178 get_filename(currentIndex));
179
180 /* Start sliding through audio clip. */
181 while (audioDataSlider.HasNext()) {
182 const int16_t *inferenceWindow = audioDataSlider.Next();
183
184 /* We moved to the next window - set the features sliding to the new address. */
185 audioMFCCWindowSlider.Reset(inferenceWindow);
186
187 /* The first window does not have cache ready. */
188 bool useCache = audioDataSlider.Index() > 0 && numberOfReusedFeatureVectors > 0;
189
190 /* Start calculating features inside one audio sliding window. */
191 while (audioMFCCWindowSlider.HasNext()) {
192 const int16_t *mfccWindow = audioMFCCWindowSlider.Next();
193 std::vector<int16_t> mfccAudioData = std::vector<int16_t>(mfccWindow,
194 mfccWindow + mfccWindowSize);
195 /* Compute features for this window and write them to input tensor. */
196 mfccFeatureCalc(mfccAudioData,
197 audioMFCCWindowSlider.Index(),
198 useCache,
199 nMfccVectorsInAudioStride);
200 }
201
202 info("Inference %zu/%zu\n", audioDataSlider.Index() + 1,
203 audioDataSlider.TotalStrides() + 1);
204
205 /* Run inference over this audio clip sliding window. */
alexander27b62d92021-05-04 20:46:08 +0100206 if (!RunInference(model, profiler)) {
207 return false;
208 }
alexander3c798932021-03-26 21:42:19 +0000209
210 std::vector<ClassificationResult> classificationResult;
211 auto& classifier = ctx.Get<KwsClassifier&>("classifier");
212 classifier.GetClassificationResults(outputTensor, classificationResult,
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000213 ctx.Get<std::vector<std::string>&>("labels"), 1, true);
alexander3c798932021-03-26 21:42:19 +0000214
215 results.emplace_back(kws::KwsResult(classificationResult,
216 audioDataSlider.Index() * secondsPerSample * audioDataStride,
217 audioDataSlider.Index(), scoreThreshold));
218
219#if VERIFY_TEST_OUTPUT
220 arm::app::DumpTensor(outputTensor);
221#endif /* VERIFY_TEST_OUTPUT */
222 } /* while (audioDataSlider.HasNext()) */
223
224 /* Erase. */
225 str_inf = std::string(str_inf.size(), ' ');
226 platform.data_psn->present_data_text(
227 str_inf.c_str(), str_inf.size(),
228 dataPsnTxtInfStartX, dataPsnTxtInfStartY, false);
229
230 ctx.Set<std::vector<arm::app::kws::KwsResult>>("results", results);
231
alexanderc350cdc2021-04-29 20:36:09 +0100232 if (!PresentInferenceResult(platform, results)) {
alexander3c798932021-03-26 21:42:19 +0000233 return false;
234 }
235
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100236 profiler.PrintProfilingResult();
237
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100238 IncrementAppCtxIfmIdx(ctx,"clipIndex");
alexander3c798932021-03-26 21:42:19 +0000239
240 } while (runAll && ctx.Get<uint32_t>("clipIndex") != startClipIdx);
241
242 return true;
243 }
244
alexanderc350cdc2021-04-29 20:36:09 +0100245 static bool PresentInferenceResult(hal_platform& platform,
246 const std::vector<arm::app::kws::KwsResult>& results)
alexander3c798932021-03-26 21:42:19 +0000247 {
248 constexpr uint32_t dataPsnTxtStartX1 = 20;
249 constexpr uint32_t dataPsnTxtStartY1 = 30;
250 constexpr uint32_t dataPsnTxtYIncr = 16; /* Row index increment. */
251
252 platform.data_psn->set_text_color(COLOR_GREEN);
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100253 info("Final results:\n");
254 info("Total number of inferences: %zu\n", results.size());
alexander3c798932021-03-26 21:42:19 +0000255
256 /* Display each result */
257 uint32_t rowIdx1 = dataPsnTxtStartY1 + 2 * dataPsnTxtYIncr;
258
259 for (uint32_t i = 0; i < results.size(); ++i) {
260
261 std::string topKeyword{"<none>"};
262 float score = 0.f;
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100263 if (!results[i].m_resultVec.empty()) {
alexander3c798932021-03-26 21:42:19 +0000264 topKeyword = results[i].m_resultVec[0].m_label;
265 score = results[i].m_resultVec[0].m_normalisedVal;
266 }
267
268 std::string resultStr =
269 std::string{"@"} + std::to_string(results[i].m_timeStamp) +
270 std::string{"s: "} + topKeyword + std::string{" ("} +
271 std::to_string(static_cast<int>(score * 100)) + std::string{"%)"};
272
273 platform.data_psn->present_data_text(
274 resultStr.c_str(), resultStr.size(),
275 dataPsnTxtStartX1, rowIdx1, false);
276 rowIdx1 += dataPsnTxtYIncr;
277
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100278 if (results[i].m_resultVec.empty()) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100279 info("For timestamp: %f (inference #: %" PRIu32
280 "); label: %s; threshold: %f\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100281 results[i].m_timeStamp, results[i].m_inferenceNumber,
282 topKeyword.c_str(),
283 results[i].m_threshold);
284 } else {
285 for (uint32_t j = 0; j < results[i].m_resultVec.size(); ++j) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100286 info("For timestamp: %f (inference #: %" PRIu32
287 "); label: %s, score: %f; threshold: %f\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100288 results[i].m_timeStamp,
289 results[i].m_inferenceNumber,
290 results[i].m_resultVec[j].m_label.c_str(),
291 results[i].m_resultVec[j].m_normalisedVal,
292 results[i].m_threshold);
293 }
alexander3c798932021-03-26 21:42:19 +0000294 }
295 }
296
297 return true;
298 }
299
300 /**
301 * @brief Generic feature calculator factory.
302 *
303 * Returns lambda function to compute features using features cache.
304 * Real features math is done by a lambda function provided as a parameter.
305 * Features are written to input tensor memory.
306 *
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100307 * @tparam T Feature vector type.
308 * @param[in] inputTensor Model input tensor pointer.
309 * @param[in] cacheSize Number of feature vectors to cache. Defined by the sliding window overlap.
310 * @param[in] compute Features calculator function.
311 * @return Lambda function to compute features.
alexander3c798932021-03-26 21:42:19 +0000312 */
313 template<class T>
314 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100315 FeatureCalc(TfLiteTensor* inputTensor, size_t cacheSize,
316 std::function<std::vector<T> (std::vector<int16_t>& )> compute)
alexander3c798932021-03-26 21:42:19 +0000317 {
318 /* Feature cache to be captured by lambda function. */
319 static std::vector<std::vector<T>> featureCache = std::vector<std::vector<T>>(cacheSize);
320
321 return [=](std::vector<int16_t>& audioDataWindow,
322 size_t index,
323 bool useCache,
324 size_t featuresOverlapIndex)
325 {
326 T *tensorData = tflite::GetTensorData<T>(inputTensor);
327 std::vector<T> features;
328
329 /* Reuse features from cache if cache is ready and sliding windows overlap.
330 * Overlap is in the beginning of sliding window with a size of a feature cache. */
331 if (useCache && index < featureCache.size()) {
332 features = std::move(featureCache[index]);
333 } else {
334 features = std::move(compute(audioDataWindow));
335 }
336 auto size = features.size();
337 auto sizeBytes = sizeof(T) * size;
338 std::memcpy(tensorData + (index * size), features.data(), sizeBytes);
339
340 /* Start renewing cache as soon iteration goes out of the windows overlap. */
341 if (index >= featuresOverlapIndex) {
342 featureCache[index - featuresOverlapIndex] = std::move(features);
343 }
344 };
345 }
346
347 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100348 FeatureCalc<int8_t>(TfLiteTensor* inputTensor,
alexander3c798932021-03-26 21:42:19 +0000349 size_t cacheSize,
350 std::function<std::vector<int8_t> (std::vector<int16_t>& )> compute);
351
352 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100353 FeatureCalc<uint8_t>(TfLiteTensor* inputTensor,
354 size_t cacheSize,
355 std::function<std::vector<uint8_t> (std::vector<int16_t>& )> compute);
alexander3c798932021-03-26 21:42:19 +0000356
357 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100358 FeatureCalc<int16_t>(TfLiteTensor* inputTensor,
359 size_t cacheSize,
360 std::function<std::vector<int16_t> (std::vector<int16_t>& )> compute);
alexander3c798932021-03-26 21:42:19 +0000361
362 template std::function<void(std::vector<int16_t>&, size_t, bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100363 FeatureCalc<float>(TfLiteTensor* inputTensor,
364 size_t cacheSize,
365 std::function<std::vector<float>(std::vector<int16_t>&)> compute);
alexander3c798932021-03-26 21:42:19 +0000366
367
368 static std::function<void (std::vector<int16_t>&, int, bool, size_t)>
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000369 GetFeatureCalculator(audio::MicroNetKwsMFCC& mfcc, TfLiteTensor* inputTensor, size_t cacheSize)
alexander3c798932021-03-26 21:42:19 +0000370 {
371 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)> mfccFeatureCalc;
372
373 TfLiteQuantization quant = inputTensor->quantization;
374
375 if (kTfLiteAffineQuantization == quant.type) {
376
377 auto *quantParams = (TfLiteAffineQuantization *) quant.params;
378 const float quantScale = quantParams->scale->data[0];
379 const int quantOffset = quantParams->zero_point->data[0];
380
381 switch (inputTensor->type) {
382 case kTfLiteInt8: {
alexanderc350cdc2021-04-29 20:36:09 +0100383 mfccFeatureCalc = FeatureCalc<int8_t>(inputTensor,
384 cacheSize,
385 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
386 return mfcc.MfccComputeQuant<int8_t>(audioDataWindow,
387 quantScale,
388 quantOffset);
389 }
alexander3c798932021-03-26 21:42:19 +0000390 );
391 break;
392 }
393 case kTfLiteUInt8: {
alexanderc350cdc2021-04-29 20:36:09 +0100394 mfccFeatureCalc = FeatureCalc<uint8_t>(inputTensor,
395 cacheSize,
alexander3c798932021-03-26 21:42:19 +0000396 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
397 return mfcc.MfccComputeQuant<uint8_t>(audioDataWindow,
398 quantScale,
399 quantOffset);
400 }
401 );
402 break;
403 }
404 case kTfLiteInt16: {
alexanderc350cdc2021-04-29 20:36:09 +0100405 mfccFeatureCalc = FeatureCalc<int16_t>(inputTensor,
406 cacheSize,
407 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
408 return mfcc.MfccComputeQuant<int16_t>(audioDataWindow,
409 quantScale,
410 quantOffset);
411 }
alexander3c798932021-03-26 21:42:19 +0000412 );
413 break;
414 }
415 default:
416 printf_err("Tensor type %s not supported\n", TfLiteTypeGetName(inputTensor->type));
417 }
418
419
420 } else {
alexanderc350cdc2021-04-29 20:36:09 +0100421 mfccFeatureCalc = mfccFeatureCalc = FeatureCalc<float>(inputTensor,
422 cacheSize,
423 [&mfcc](std::vector<int16_t>& audioDataWindow) {
424 return mfcc.MfccCompute(audioDataWindow);
425 });
alexander3c798932021-03-26 21:42:19 +0000426 }
427 return mfccFeatureCalc;
428 }
429
430} /* namespace app */
431} /* namespace arm */