blob: a951e55fe5c8be0f5499b02f4281641e172aca9e [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
É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)>
62 GetFeatureCalculator(audio::DsCnnMFCC& mfcc,
63 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>(
75 (arm::app::DsCnnModel::ms_inputRowsIdx > arm::app::DsCnnModel::ms_inputColsIdx)?
76 arm::app::DsCnnModel::ms_inputRowsIdx : arm::app::DsCnnModel::ms_inputColsIdx);
77
78 platform.data_psn->clear(COLOR_BLACK);
79
80 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);
110 const uint32_t kNumCols = inputShape->data[arm::app::DsCnnModel::ms_inputColsIdx];
111 const uint32_t kNumRows = inputShape->data[arm::app::DsCnnModel::ms_inputRowsIdx];
112
113 audio::DsCnnMFCC mfcc = audio::DsCnnMFCC(kNumCols, frameLength);
114 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. */
137 const float secondsPerSample = 1.0/audio::DsCnnMFCC::ms_defaultSamplingFreq;
138
139 do {
140 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,
211 ctx.Get<std::vector<std::string>&>("labels"), 1);
212
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
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100243
alexanderc350cdc2021-04-29 20:36:09 +0100244 static bool PresentInferenceResult(hal_platform& platform,
245 const std::vector<arm::app::kws::KwsResult>& results)
alexander3c798932021-03-26 21:42:19 +0000246 {
247 constexpr uint32_t dataPsnTxtStartX1 = 20;
248 constexpr uint32_t dataPsnTxtStartY1 = 30;
249 constexpr uint32_t dataPsnTxtYIncr = 16; /* Row index increment. */
250
251 platform.data_psn->set_text_color(COLOR_GREEN);
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100252 info("Final results:\n");
253 info("Total number of inferences: %zu\n", results.size());
alexander3c798932021-03-26 21:42:19 +0000254
255 /* Display each result */
256 uint32_t rowIdx1 = dataPsnTxtStartY1 + 2 * dataPsnTxtYIncr;
257
258 for (uint32_t i = 0; i < results.size(); ++i) {
259
260 std::string topKeyword{"<none>"};
261 float score = 0.f;
262
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)>
369 GetFeatureCalculator(audio::DsCnnMFCC& mfcc, TfLiteTensor* inputTensor, size_t cacheSize)
370 {
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 */