blob: d61985d9450bfaf205e9dfce53c624277dcd11b0 [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);
190 info("Running inference on audio clip %u => %s\n", currentIndex,
191 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) {
273 printf_err("Invalid idx %u (expected less than %u)\n",
274 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()) {
316 info("For timestamp: %f (inference #: %u); label: %s; threshold: %f\n",
317 results[i].m_timeStamp, results[i].m_inferenceNumber,
318 topKeyword.c_str(),
319 results[i].m_threshold);
320 } else {
321 for (uint32_t j = 0; j < results[i].m_resultVec.size(); ++j) {
322 info("For timestamp: %f (inference #: %u); label: %s, score: %f; threshold: %f\n",
323 results[i].m_timeStamp,
324 results[i].m_inferenceNumber,
325 results[i].m_resultVec[j].m_label.c_str(),
326 results[i].m_resultVec[j].m_normalisedVal,
327 results[i].m_threshold);
328 }
alexander3c798932021-03-26 21:42:19 +0000329 }
330 }
331
332 return true;
333 }
334
335 /**
336 * @brief Generic feature calculator factory.
337 *
338 * Returns lambda function to compute features using features cache.
339 * Real features math is done by a lambda function provided as a parameter.
340 * Features are written to input tensor memory.
341 *
342 * @tparam T Feature vector type.
343 * @param inputTensor Model input tensor pointer.
344 * @param cacheSize Number of feature vectors to cache. Defined by the sliding window overlap.
345 * @param compute Features calculator function.
346 * @return Lambda function to compute features.
347 */
348 template<class T>
349 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100350 FeatureCalc(TfLiteTensor* inputTensor, size_t cacheSize,
351 std::function<std::vector<T> (std::vector<int16_t>& )> compute)
alexander3c798932021-03-26 21:42:19 +0000352 {
353 /* Feature cache to be captured by lambda function. */
354 static std::vector<std::vector<T>> featureCache = std::vector<std::vector<T>>(cacheSize);
355
356 return [=](std::vector<int16_t>& audioDataWindow,
357 size_t index,
358 bool useCache,
359 size_t featuresOverlapIndex)
360 {
361 T *tensorData = tflite::GetTensorData<T>(inputTensor);
362 std::vector<T> features;
363
364 /* Reuse features from cache if cache is ready and sliding windows overlap.
365 * Overlap is in the beginning of sliding window with a size of a feature cache. */
366 if (useCache && index < featureCache.size()) {
367 features = std::move(featureCache[index]);
368 } else {
369 features = std::move(compute(audioDataWindow));
370 }
371 auto size = features.size();
372 auto sizeBytes = sizeof(T) * size;
373 std::memcpy(tensorData + (index * size), features.data(), sizeBytes);
374
375 /* Start renewing cache as soon iteration goes out of the windows overlap. */
376 if (index >= featuresOverlapIndex) {
377 featureCache[index - featuresOverlapIndex] = std::move(features);
378 }
379 };
380 }
381
382 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100383 FeatureCalc<int8_t>(TfLiteTensor* inputTensor,
alexander3c798932021-03-26 21:42:19 +0000384 size_t cacheSize,
385 std::function<std::vector<int8_t> (std::vector<int16_t>& )> compute);
386
387 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100388 FeatureCalc<uint8_t>(TfLiteTensor* inputTensor,
389 size_t cacheSize,
390 std::function<std::vector<uint8_t> (std::vector<int16_t>& )> compute);
alexander3c798932021-03-26 21:42:19 +0000391
392 template std::function<void (std::vector<int16_t>&, size_t , bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100393 FeatureCalc<int16_t>(TfLiteTensor* inputTensor,
394 size_t cacheSize,
395 std::function<std::vector<int16_t> (std::vector<int16_t>& )> compute);
alexander3c798932021-03-26 21:42:19 +0000396
397 template std::function<void(std::vector<int16_t>&, size_t, bool, size_t)>
alexanderc350cdc2021-04-29 20:36:09 +0100398 FeatureCalc<float>(TfLiteTensor* inputTensor,
399 size_t cacheSize,
400 std::function<std::vector<float>(std::vector<int16_t>&)> compute);
alexander3c798932021-03-26 21:42:19 +0000401
402
403 static std::function<void (std::vector<int16_t>&, int, bool, size_t)>
404 GetFeatureCalculator(audio::DsCnnMFCC& mfcc, TfLiteTensor* inputTensor, size_t cacheSize)
405 {
406 std::function<void (std::vector<int16_t>&, size_t, bool, size_t)> mfccFeatureCalc;
407
408 TfLiteQuantization quant = inputTensor->quantization;
409
410 if (kTfLiteAffineQuantization == quant.type) {
411
412 auto *quantParams = (TfLiteAffineQuantization *) quant.params;
413 const float quantScale = quantParams->scale->data[0];
414 const int quantOffset = quantParams->zero_point->data[0];
415
416 switch (inputTensor->type) {
417 case kTfLiteInt8: {
alexanderc350cdc2021-04-29 20:36:09 +0100418 mfccFeatureCalc = FeatureCalc<int8_t>(inputTensor,
419 cacheSize,
420 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
421 return mfcc.MfccComputeQuant<int8_t>(audioDataWindow,
422 quantScale,
423 quantOffset);
424 }
alexander3c798932021-03-26 21:42:19 +0000425 );
426 break;
427 }
428 case kTfLiteUInt8: {
alexanderc350cdc2021-04-29 20:36:09 +0100429 mfccFeatureCalc = FeatureCalc<uint8_t>(inputTensor,
430 cacheSize,
alexander3c798932021-03-26 21:42:19 +0000431 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
432 return mfcc.MfccComputeQuant<uint8_t>(audioDataWindow,
433 quantScale,
434 quantOffset);
435 }
436 );
437 break;
438 }
439 case kTfLiteInt16: {
alexanderc350cdc2021-04-29 20:36:09 +0100440 mfccFeatureCalc = FeatureCalc<int16_t>(inputTensor,
441 cacheSize,
442 [=, &mfcc](std::vector<int16_t>& audioDataWindow) {
443 return mfcc.MfccComputeQuant<int16_t>(audioDataWindow,
444 quantScale,
445 quantOffset);
446 }
alexander3c798932021-03-26 21:42:19 +0000447 );
448 break;
449 }
450 default:
451 printf_err("Tensor type %s not supported\n", TfLiteTypeGetName(inputTensor->type));
452 }
453
454
455 } else {
alexanderc350cdc2021-04-29 20:36:09 +0100456 mfccFeatureCalc = mfccFeatureCalc = FeatureCalc<float>(inputTensor,
457 cacheSize,
458 [&mfcc](std::vector<int16_t>& audioDataWindow) {
459 return mfcc.MfccCompute(audioDataWindow);
460 });
alexander3c798932021-03-26 21:42:19 +0000461 }
462 return mfccFeatureCalc;
463 }
464
465} /* namespace app */
466} /* namespace arm */