blob: eaf53c1485b9011e2559cfbab097e4bfc34c50b1 [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"
21#include "DsCnnModel.hpp"
22#include "hal.h"
23#include "DsCnnMfcc.hpp"
24#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
36 /**
37 * @brief Helper function to increment current audio clip index.
38 * @param[in,out] ctx Pointer to the application context object.
39 **/
alexanderc350cdc2021-04-29 20:36:09 +010040 static void IncrementAppCtxClipIdx(ApplicationContext& ctx);
alexander3c798932021-03-26 21:42:19 +000041
42 /**
43 * @brief Helper function to set the audio clip index.
44 * @param[in,out] ctx Pointer to the application context object.
45 * @param[in] idx Value to be set.
46 * @return true if index is set, false otherwise.
47 **/
alexanderc350cdc2021-04-29 20:36:09 +010048 static bool SetAppCtxClipIdx(ApplicationContext& ctx, uint32_t idx);
alexander3c798932021-03-26 21:42:19 +000049
50 /**
51 * @brief Presents inference results using the data presentation
52 * object.
53 * @param[in] platform Reference to the hal platform object.
54 * @param[in] results Vector of classification results to be displayed.
55 * @param[in] infTimeMs Inference time in milliseconds, if available,
56 * otherwise, this can be passed in as 0.
57 * @return true if successful, false otherwise.
58 **/
alexanderc350cdc2021-04-29 20:36:09 +010059 static bool PresentInferenceResult(hal_platform& platform,
60 const std::vector<arm::app::kws::KwsResult>& results);
alexander3c798932021-03-26 21:42:19 +000061
62 /**
63 * @brief Returns a function to perform feature calculation and populates input tensor data with
64 * MFCC data.
65 *
66 * Input tensor data type check is performed to choose correct MFCC feature data type.
67 * If tensor has an integer data type then original features are quantised.
68 *
69 * Warning: MFCC calculator provided as input must have the same life scope as returned function.
70 *
71 * @param[in] mfcc MFCC feature calculator.
72 * @param[in,out] inputTensor Input tensor pointer to store calculated features.
73 * @param[in] cacheSize Size of the feature vectors cache (number of feature vectors).
74 * @return Function to be called providing audio sample and sliding window index.
75 */
76 static std::function<void (std::vector<int16_t>&, int, bool, size_t)>
77 GetFeatureCalculator(audio::DsCnnMFCC& mfcc,
78 TfLiteTensor* inputTensor,
79 size_t cacheSize);
80
81 /* Audio inference handler. */
82 bool ClassifyAudioHandler(ApplicationContext& ctx, uint32_t clipIndex, bool runAll)
83 {
84 auto& platform = ctx.Get<hal_platform&>("platform");
Isabella Gottardi8df12f32021-04-07 17:15:31 +010085 auto& profiler = ctx.Get<Profiler&>("profiler");
alexander3c798932021-03-26 21:42:19 +000086
87 constexpr uint32_t dataPsnTxtInfStartX = 20;
88 constexpr uint32_t dataPsnTxtInfStartY = 40;
89 constexpr int minTensorDims = static_cast<int>(
90 (arm::app::DsCnnModel::ms_inputRowsIdx > arm::app::DsCnnModel::ms_inputColsIdx)?
91 arm::app::DsCnnModel::ms_inputRowsIdx : arm::app::DsCnnModel::ms_inputColsIdx);
92
93 platform.data_psn->clear(COLOR_BLACK);
94
95 auto& model = ctx.Get<Model&>("model");
96
97 /* If the request has a valid size, set the audio index. */
98 if (clipIndex < NUMBER_OF_FILES) {
alexanderc350cdc2021-04-29 20:36:09 +010099 if (!SetAppCtxClipIdx(ctx, clipIndex)) {
alexander3c798932021-03-26 21:42:19 +0000100 return false;
101 }
102 }
103 if (!model.IsInited()) {
104 printf_err("Model is not initialised! Terminating processing.\n");
105 return false;
106 }
107
108 const auto frameLength = ctx.Get<int>("frameLength");
109 const auto frameStride = ctx.Get<int>("frameStride");
110 const auto scoreThreshold = ctx.Get<float>("scoreThreshold");
111 auto startClipIdx = ctx.Get<uint32_t>("clipIndex");
112
113 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
114 TfLiteTensor* inputTensor = model.GetInputTensor(0);
115
116 if (!inputTensor->dims) {
117 printf_err("Invalid input tensor dims\n");
118 return false;
119 } else if (inputTensor->dims->size < minTensorDims) {
120 printf_err("Input tensor dimension should be >= %d\n", minTensorDims);
121 return false;
122 }
123
124 TfLiteIntArray* inputShape = model.GetInputShape(0);
125 const uint32_t kNumCols = inputShape->data[arm::app::DsCnnModel::ms_inputColsIdx];
126 const uint32_t kNumRows = inputShape->data[arm::app::DsCnnModel::ms_inputRowsIdx];
127
128 audio::DsCnnMFCC mfcc = audio::DsCnnMFCC(kNumCols, frameLength);
129 mfcc.Init();
130
131 /* Deduce the data length required for 1 inference from the network parameters. */
132 auto audioDataWindowSize = kNumRows * frameStride + (frameLength - frameStride);
133 auto mfccWindowSize = frameLength;
134 auto mfccWindowStride = frameStride;
135
136 /* We choose to move by half the window size => for a 1 second window size
137 * there is an overlap of 0.5 seconds. */
138 auto audioDataStride = audioDataWindowSize / 2;
139
140 /* To have the previously calculated features re-usable, stride must be multiple
141 * of MFCC features window stride. */
142 if (0 != audioDataStride % mfccWindowStride) {
143
144 /* Reduce the stride. */
145 audioDataStride -= audioDataStride % mfccWindowStride;
146 }
147
148 auto nMfccVectorsInAudioStride = audioDataStride/mfccWindowStride;
149
150 /* We expect to be sampling 1 second worth of data at a time.
151 * NOTE: This is only used for time stamp calculation. */
152 const float secondsPerSample = 1.0/audio::DsCnnMFCC::ms_defaultSamplingFreq;
153
154 do {
155 auto currentIndex = ctx.Get<uint32_t>("clipIndex");
156
157 /* Creating a mfcc features sliding window for the data required for 1 inference. */
158 auto audioMFCCWindowSlider = audio::SlidingWindow<const int16_t>(
159 get_audio_array(currentIndex),
160 audioDataWindowSize, mfccWindowSize,
161 mfccWindowStride);
162
163 /* Creating a sliding window through the whole audio clip. */
164 auto audioDataSlider = audio::SlidingWindow<const int16_t>(
165 get_audio_array(currentIndex),
166 get_audio_array_size(currentIndex),
167 audioDataWindowSize, audioDataStride);
168
169 /* Calculate number of the feature vectors in the window overlap region.
170 * These feature vectors will be reused.*/
171 auto numberOfReusedFeatureVectors = audioMFCCWindowSlider.TotalStrides() + 1
172 - nMfccVectorsInAudioStride;
173
174 /* Construct feature calculation function. */
175 auto mfccFeatureCalc = GetFeatureCalculator(mfcc, inputTensor,
176 numberOfReusedFeatureVectors);
177
178 if (!mfccFeatureCalc){
179 return false;
180 }
181
182 /* Declare a container for results. */
183 std::vector<arm::app::kws::KwsResult> results;
184
185 /* Display message on the LCD - inference running. */
186 std::string str_inf{"Running inference... "};
187 platform.data_psn->present_data_text(
188 str_inf.c_str(), str_inf.size(),
189 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100190 info("Running inference on audio clip %" PRIu32 " => %s\n", currentIndex,
alexander3c798932021-03-26 21:42:19 +0000191 get_filename(currentIndex));
192
193 /* Start sliding through audio clip. */
194 while (audioDataSlider.HasNext()) {
195 const int16_t *inferenceWindow = audioDataSlider.Next();
196
197 /* We moved to the next window - set the features sliding to the new address. */
198 audioMFCCWindowSlider.Reset(inferenceWindow);
199
200 /* The first window does not have cache ready. */
201 bool useCache = audioDataSlider.Index() > 0 && numberOfReusedFeatureVectors > 0;
202
203 /* Start calculating features inside one audio sliding window. */
204 while (audioMFCCWindowSlider.HasNext()) {
205 const int16_t *mfccWindow = audioMFCCWindowSlider.Next();
206 std::vector<int16_t> mfccAudioData = std::vector<int16_t>(mfccWindow,
207 mfccWindow + mfccWindowSize);
208 /* Compute features for this window and write them to input tensor. */
209 mfccFeatureCalc(mfccAudioData,
210 audioMFCCWindowSlider.Index(),
211 useCache,
212 nMfccVectorsInAudioStride);
213 }
214
215 info("Inference %zu/%zu\n", audioDataSlider.Index() + 1,
216 audioDataSlider.TotalStrides() + 1);
217
218 /* Run inference over this audio clip sliding window. */
alexander27b62d92021-05-04 20:46:08 +0100219 if (!RunInference(model, profiler)) {
220 return false;
221 }
alexander3c798932021-03-26 21:42:19 +0000222
223 std::vector<ClassificationResult> classificationResult;
224 auto& classifier = ctx.Get<KwsClassifier&>("classifier");
225 classifier.GetClassificationResults(outputTensor, classificationResult,
226 ctx.Get<std::vector<std::string>&>("labels"), 1);
227
228 results.emplace_back(kws::KwsResult(classificationResult,
229 audioDataSlider.Index() * secondsPerSample * audioDataStride,
230 audioDataSlider.Index(), scoreThreshold));
231
232#if VERIFY_TEST_OUTPUT
233 arm::app::DumpTensor(outputTensor);
234#endif /* VERIFY_TEST_OUTPUT */
235 } /* while (audioDataSlider.HasNext()) */
236
237 /* Erase. */
238 str_inf = std::string(str_inf.size(), ' ');
239 platform.data_psn->present_data_text(
240 str_inf.c_str(), str_inf.size(),
241 dataPsnTxtInfStartX, dataPsnTxtInfStartY, false);
242
243 ctx.Set<std::vector<arm::app::kws::KwsResult>>("results", results);
244
alexanderc350cdc2021-04-29 20:36:09 +0100245 if (!PresentInferenceResult(platform, results)) {
alexander3c798932021-03-26 21:42:19 +0000246 return false;
247 }
248
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100249 profiler.PrintProfilingResult();
250
alexanderc350cdc2021-04-29 20:36:09 +0100251 IncrementAppCtxClipIdx(ctx);
alexander3c798932021-03-26 21:42:19 +0000252
253 } while (runAll && ctx.Get<uint32_t>("clipIndex") != startClipIdx);
254
255 return true;
256 }
257
alexanderc350cdc2021-04-29 20:36:09 +0100258 static void IncrementAppCtxClipIdx(ApplicationContext& ctx)
alexander3c798932021-03-26 21:42:19 +0000259 {
260 auto curAudioIdx = ctx.Get<uint32_t>("clipIndex");
261
262 if (curAudioIdx + 1 >= NUMBER_OF_FILES) {
263 ctx.Set<uint32_t>("clipIndex", 0);
264 return;
265 }
266 ++curAudioIdx;
267 ctx.Set<uint32_t>("clipIndex", curAudioIdx);
268 }
269
alexanderc350cdc2021-04-29 20:36:09 +0100270 static bool SetAppCtxClipIdx(ApplicationContext& ctx, uint32_t idx)
alexander3c798932021-03-26 21:42:19 +0000271 {
272 if (idx >= NUMBER_OF_FILES) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100273 printf_err("Invalid idx %" PRIu32 " (expected less than %u)\n",
alexander3c798932021-03-26 21:42:19 +0000274 idx, NUMBER_OF_FILES);
275 return false;
276 }
277 ctx.Set<uint32_t>("clipIndex", idx);
278 return true;
279 }
280
alexanderc350cdc2021-04-29 20:36:09 +0100281 static bool PresentInferenceResult(hal_platform& platform,
282 const std::vector<arm::app::kws::KwsResult>& results)
alexander3c798932021-03-26 21:42:19 +0000283 {
284 constexpr uint32_t dataPsnTxtStartX1 = 20;
285 constexpr uint32_t dataPsnTxtStartY1 = 30;
286 constexpr uint32_t dataPsnTxtYIncr = 16; /* Row index increment. */
287
288 platform.data_psn->set_text_color(COLOR_GREEN);
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100289 info("Final results:\n");
290 info("Total number of inferences: %zu\n", results.size());
alexander3c798932021-03-26 21:42:19 +0000291
292 /* Display each result */
293 uint32_t rowIdx1 = dataPsnTxtStartY1 + 2 * dataPsnTxtYIncr;
294
295 for (uint32_t i = 0; i < results.size(); ++i) {
296
297 std::string topKeyword{"<none>"};
298 float score = 0.f;
299
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100300 if (!results[i].m_resultVec.empty()) {
alexander3c798932021-03-26 21:42:19 +0000301 topKeyword = results[i].m_resultVec[0].m_label;
302 score = results[i].m_resultVec[0].m_normalisedVal;
303 }
304
305 std::string resultStr =
306 std::string{"@"} + std::to_string(results[i].m_timeStamp) +
307 std::string{"s: "} + topKeyword + std::string{" ("} +
308 std::to_string(static_cast<int>(score * 100)) + std::string{"%)"};
309
310 platform.data_psn->present_data_text(
311 resultStr.c_str(), resultStr.size(),
312 dataPsnTxtStartX1, rowIdx1, false);
313 rowIdx1 += dataPsnTxtYIncr;
314
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100315 if (results[i].m_resultVec.empty()) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100316 info("For timestamp: %f (inference #: %" PRIu32
317 "); label: %s; threshold: %f\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100318 results[i].m_timeStamp, results[i].m_inferenceNumber,
319 topKeyword.c_str(),
320 results[i].m_threshold);
321 } else {
322 for (uint32_t j = 0; j < results[i].m_resultVec.size(); ++j) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100323 info("For timestamp: %f (inference #: %" PRIu32
324 "); label: %s, score: %f; threshold: %f\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100325 results[i].m_timeStamp,
326 results[i].m_inferenceNumber,
327 results[i].m_resultVec[j].m_label.c_str(),
328 results[i].m_resultVec[j].m_normalisedVal,
329 results[i].m_threshold);
330 }
alexander3c798932021-03-26 21:42:19 +0000331 }
332 }
333
334 return true;
335 }
336
337 /**
338 * @brief Generic feature calculator factory.
339 *
340 * Returns lambda function to compute features using features cache.
341 * Real features math is done by a lambda function provided as a parameter.
342 * Features are written to input tensor memory.
343 *
344 * @tparam T Feature vector type.
345 * @param inputTensor Model input tensor pointer.
346 * @param cacheSize Number of feature vectors to cache. Defined by the sliding window overlap.
347 * @param compute Features calculator function.
348 * @return Lambda function to compute features.
349 */
350 template<class T>
351 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100352 FeatureCalc(TfLiteTensor* inputTensor, size_t cacheSize,
353 std::function<std::vector<T> (std::vector<int16_t>& )> compute)
alexander3c798932021-03-26 21:42:19 +0000354 {
355 /* Feature cache to be captured by lambda function. */
356 static std::vector<std::vector<T>> featureCache = std::vector<std::vector<T>>(cacheSize);
357
358 return [=](std::vector<int16_t>& audioDataWindow,
359 size_t index,
360 bool useCache,
361 size_t featuresOverlapIndex)
362 {
363 T *tensorData = tflite::GetTensorData<T>(inputTensor);
364 std::vector<T> features;
365
366 /* Reuse features from cache if cache is ready and sliding windows overlap.
367 * Overlap is in the beginning of sliding window with a size of a feature cache. */
368 if (useCache && index < featureCache.size()) {
369 features = std::move(featureCache[index]);
370 } else {
371 features = std::move(compute(audioDataWindow));
372 }
373 auto size = features.size();
374 auto sizeBytes = sizeof(T) * size;
375 std::memcpy(tensorData + (index * size), features.data(), sizeBytes);
376
377 /* Start renewing cache as soon iteration goes out of the windows overlap. */
378 if (index >= featuresOverlapIndex) {
379 featureCache[index - featuresOverlapIndex] = std::move(features);
380 }
381 };
382 }
383
384 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100385 FeatureCalc<int8_t>(TfLiteTensor* inputTensor,
alexander3c798932021-03-26 21:42:19 +0000386 size_t cacheSize,
387 std::function<std::vector<int8_t> (std::vector<int16_t>& )> compute);
388
389 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100390 FeatureCalc<uint8_t>(TfLiteTensor* inputTensor,
391 size_t cacheSize,
392 std::function<std::vector<uint8_t> (std::vector<int16_t>& )> compute);
alexander3c798932021-03-26 21:42:19 +0000393
394 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100395 FeatureCalc<int16_t>(TfLiteTensor* inputTensor,
396 size_t cacheSize,
397 std::function<std::vector<int16_t> (std::vector<int16_t>& )> compute);
alexander3c798932021-03-26 21:42:19 +0000398
399 template std::function<void(std::vector<int16_t>&, size_t, bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100400 FeatureCalc<float>(TfLiteTensor* inputTensor,
401 size_t cacheSize,
402 std::function<std::vector<float>(std::vector<int16_t>&)> compute);
alexander3c798932021-03-26 21:42:19 +0000403
404
405 static std::function<void (std::vector<int16_t>&, int, bool, size_t)>
406 GetFeatureCalculator(audio::DsCnnMFCC& mfcc, TfLiteTensor* inputTensor, size_t cacheSize)
407 {
408 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)> mfccFeatureCalc;
409
410 TfLiteQuantization quant = inputTensor->quantization;
411
412 if (kTfLiteAffineQuantization == quant.type) {
413
414 auto *quantParams = (TfLiteAffineQuantization *) quant.params;
415 const float quantScale = quantParams->scale->data[0];
416 const int quantOffset = quantParams->zero_point->data[0];
417
418 switch (inputTensor->type) {
419 case kTfLiteInt8: {
alexanderc350cdc2021-04-29 20:36:09 +0100420 mfccFeatureCalc = FeatureCalc<int8_t>(inputTensor,
421 cacheSize,
422 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
423 return mfcc.MfccComputeQuant<int8_t>(audioDataWindow,
424 quantScale,
425 quantOffset);
426 }
alexander3c798932021-03-26 21:42:19 +0000427 );
428 break;
429 }
430 case kTfLiteUInt8: {
alexanderc350cdc2021-04-29 20:36:09 +0100431 mfccFeatureCalc = FeatureCalc<uint8_t>(inputTensor,
432 cacheSize,
alexander3c798932021-03-26 21:42:19 +0000433 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
434 return mfcc.MfccComputeQuant<uint8_t>(audioDataWindow,
435 quantScale,
436 quantOffset);
437 }
438 );
439 break;
440 }
441 case kTfLiteInt16: {
alexanderc350cdc2021-04-29 20:36:09 +0100442 mfccFeatureCalc = FeatureCalc<int16_t>(inputTensor,
443 cacheSize,
444 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
445 return mfcc.MfccComputeQuant<int16_t>(audioDataWindow,
446 quantScale,
447 quantOffset);
448 }
alexander3c798932021-03-26 21:42:19 +0000449 );
450 break;
451 }
452 default:
453 printf_err("Tensor type %s not supported\n", TfLiteTypeGetName(inputTensor->type));
454 }
455
456
457 } else {
alexanderc350cdc2021-04-29 20:36:09 +0100458 mfccFeatureCalc = mfccFeatureCalc = FeatureCalc<float>(inputTensor,
459 cacheSize,
460 [&mfcc](std::vector<int16_t>& audioDataWindow) {
461 return mfcc.MfccCompute(audioDataWindow);
462 });
alexander3c798932021-03-26 21:42:19 +0000463 }
464 return mfccFeatureCalc;
465 }
466
467} /* namespace app */
468} /* namespace arm */