blob: afcb6e4d35241464dc8aac108573bc6fbfac9a22 [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 "AsrClassifier.hpp"
21#include "Wav2LetterModel.hpp"
22#include "hal.h"
23#include "Wav2LetterMfcc.hpp"
24#include "AudioUtils.hpp"
25#include "UseCaseCommonUtils.hpp"
26#include "AsrResult.hpp"
27#include "Wav2LetterPreprocess.hpp"
28#include "Wav2LetterPostprocess.hpp"
29#include "OutputDecode.hpp"
alexander31ae9f02022-02-10 16:15:54 +000030#include "log_macros.h"
alexander3c798932021-03-26 21:42:19 +000031
32namespace arm {
33namespace app {
34
35 /**
alexander3c798932021-03-26 21:42:19 +000036 * @brief Presents inference results using the data presentation
37 * object.
38 * @param[in] platform Reference to the hal platform object.
39 * @param[in] results Vector of classification results to be displayed.
alexander3c798932021-03-26 21:42:19 +000040 * @return true if successful, false otherwise.
41 **/
alexanderc350cdc2021-04-29 20:36:09 +010042 static bool PresentInferenceResult(
alexander3c798932021-03-26 21:42:19 +000043 hal_platform& platform,
44 const std::vector<arm::app::asr::AsrResult>& results);
45
46 /* Audio inference classification handler. */
47 bool ClassifyAudioHandler(ApplicationContext& ctx, uint32_t clipIndex, bool runAll)
48 {
49 constexpr uint32_t dataPsnTxtInfStartX = 20;
50 constexpr uint32_t dataPsnTxtInfStartY = 40;
51
52 auto& platform = ctx.Get<hal_platform&>("platform");
53 platform.data_psn->clear(COLOR_BLACK);
54
Isabella Gottardi8df12f32021-04-07 17:15:31 +010055 auto& profiler = ctx.Get<Profiler&>("profiler");
56
alexander3c798932021-03-26 21:42:19 +000057 /* If the request has a valid size, set the audio index. */
58 if (clipIndex < NUMBER_OF_FILES) {
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010059 if (!SetAppCtxIfmIdx(ctx, clipIndex,"clipIndex")) {
alexander3c798932021-03-26 21:42:19 +000060 return false;
61 }
62 }
63
64 /* Get model reference. */
65 auto& model = ctx.Get<Model&>("model");
66 if (!model.IsInited()) {
67 printf_err("Model is not initialised! Terminating processing.\n");
68 return false;
69 }
70
71 /* Get score threshold to be applied for the classifier (post-inference). */
72 auto scoreThreshold = ctx.Get<float>("scoreThreshold");
73
74 /* Get tensors. Dimensions of the tensor should have been verified by
75 * the callee. */
76 TfLiteTensor* inputTensor = model.GetInputTensor(0);
77 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
78 const uint32_t inputRows = inputTensor->dims->data[arm::app::Wav2LetterModel::ms_inputRowsIdx];
79
80 /* Populate MFCC related parameters. */
81 auto mfccParamsWinLen = ctx.Get<uint32_t>("frameLength");
82 auto mfccParamsWinStride = ctx.Get<uint32_t>("frameStride");
83
84 /* Populate ASR inference context and inner lengths for input. */
85 auto inputCtxLen = ctx.Get<uint32_t>("ctxLen");
86 const uint32_t inputInnerLen = inputRows - (2 * inputCtxLen);
87
88 /* Audio data stride corresponds to inputInnerLen feature vectors. */
89 const uint32_t audioParamsWinLen = (inputRows - 1) * mfccParamsWinStride + (mfccParamsWinLen);
90 const uint32_t audioParamsWinStride = inputInnerLen * mfccParamsWinStride;
91 const float audioParamsSecondsPerSample = (1.0/audio::Wav2LetterMFCC::ms_defaultSamplingFreq);
92
93 /* Get pre/post-processing objects. */
94 auto& prep = ctx.Get<audio::asr::Preprocess&>("preprocess");
95 auto& postp = ctx.Get<audio::asr::Postprocess&>("postprocess");
96
97 /* Set default reduction axis for post-processing. */
98 const uint32_t reductionAxis = arm::app::Wav2LetterModel::ms_outputRowsIdx;
99
100 /* Audio clip start index. */
101 auto startClipIdx = ctx.Get<uint32_t>("clipIndex");
102
103 /* Loop to process audio clips. */
104 do {
Richard Burton9b8d67a2021-12-10 12:32:51 +0000105 platform.data_psn->clear(COLOR_BLACK);
106
alexander3c798932021-03-26 21:42:19 +0000107 /* Get current audio clip index. */
108 auto currentIndex = ctx.Get<uint32_t>("clipIndex");
109
110 /* Get the current audio buffer and respective size. */
111 const int16_t* audioArr = get_audio_array(currentIndex);
112 const uint32_t audioArrSize = get_audio_array_size(currentIndex);
113
114 if (!audioArr) {
115 printf_err("Invalid audio array pointer\n");
116 return false;
117 }
118
119 /* Audio clip must have enough samples to produce 1 MFCC feature. */
120 if (audioArrSize < mfccParamsWinLen) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100121 printf_err("Not enough audio samples, minimum needed is %" PRIu32 "\n",
122 mfccParamsWinLen);
alexander3c798932021-03-26 21:42:19 +0000123 return false;
124 }
125
126 /* Initialise an audio slider. */
alexander80eecfb2021-07-06 19:47:59 +0100127 auto audioDataSlider = audio::FractionalSlidingWindow<const int16_t>(
alexander3c798932021-03-26 21:42:19 +0000128 audioArr,
129 audioArrSize,
130 audioParamsWinLen,
131 audioParamsWinStride);
132
133 /* Declare a container for results. */
134 std::vector<arm::app::asr::AsrResult> results;
135
136 /* Display message on the LCD - inference running. */
137 std::string str_inf{"Running inference... "};
138 platform.data_psn->present_data_text(
139 str_inf.c_str(), str_inf.size(),
140 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
141
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100142 info("Running inference on audio clip %" PRIu32 " => %s\n", currentIndex,
alexander3c798932021-03-26 21:42:19 +0000143 get_filename(currentIndex));
144
145 size_t inferenceWindowLen = audioParamsWinLen;
146
147 /* Start sliding through audio clip. */
148 while (audioDataSlider.HasNext()) {
149
150 /* If not enough audio see how much can be sent for processing. */
151 size_t nextStartIndex = audioDataSlider.NextWindowStartIndex();
152 if (nextStartIndex + audioParamsWinLen > audioArrSize) {
153 inferenceWindowLen = audioArrSize - nextStartIndex;
154 }
155
156 const int16_t* inferenceWindow = audioDataSlider.Next();
157
158 info("Inference %zu/%zu\n", audioDataSlider.Index() + 1,
159 static_cast<size_t>(ceilf(audioDataSlider.FractionalTotalStrides() + 1)));
160
alexander3c798932021-03-26 21:42:19 +0000161 /* Calculate MFCCs, deltas and populate the input tensor. */
162 prep.Invoke(inferenceWindow, inferenceWindowLen, inputTensor);
163
alexander3c798932021-03-26 21:42:19 +0000164 /* Run inference over this audio clip sliding window. */
alexander27b62d92021-05-04 20:46:08 +0100165 if (!RunInference(model, profiler)) {
166 return false;
167 }
alexander3c798932021-03-26 21:42:19 +0000168
169 /* Post-process. */
170 postp.Invoke(outputTensor, reductionAxis, !audioDataSlider.HasNext());
171
172 /* Get results. */
173 std::vector<ClassificationResult> classificationResult;
174 auto& classifier = ctx.Get<AsrClassifier&>("classifier");
175 classifier.GetClassificationResults(
176 outputTensor, classificationResult,
177 ctx.Get<std::vector<std::string>&>("labels"), 1);
178
179 results.emplace_back(asr::AsrResult(classificationResult,
180 (audioDataSlider.Index() *
181 audioParamsSecondsPerSample *
182 audioParamsWinStride),
183 audioDataSlider.Index(), scoreThreshold));
184
185#if VERIFY_TEST_OUTPUT
186 arm::app::DumpTensor(outputTensor,
187 outputTensor->dims->data[arm::app::Wav2LetterModel::ms_outputColsIdx]);
188#endif /* VERIFY_TEST_OUTPUT */
189
190 }
191
192 /* Erase. */
193 str_inf = std::string(str_inf.size(), ' ');
194 platform.data_psn->present_data_text(
195 str_inf.c_str(), str_inf.size(),
196 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
197
198 ctx.Set<std::vector<arm::app::asr::AsrResult>>("results", results);
199
alexanderc350cdc2021-04-29 20:36:09 +0100200 if (!PresentInferenceResult(platform, results)) {
alexander3c798932021-03-26 21:42:19 +0000201 return false;
202 }
203
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100204 profiler.PrintProfilingResult();
205
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100206 IncrementAppCtxIfmIdx(ctx,"clipIndex");
alexander3c798932021-03-26 21:42:19 +0000207
208 } while (runAll && ctx.Get<uint32_t>("clipIndex") != startClipIdx);
209
210 return true;
211 }
212
alexander3c798932021-03-26 21:42:19 +0000213
alexanderc350cdc2021-04-29 20:36:09 +0100214 static bool PresentInferenceResult(hal_platform& platform,
215 const std::vector<arm::app::asr::AsrResult>& results)
alexander3c798932021-03-26 21:42:19 +0000216 {
217 constexpr uint32_t dataPsnTxtStartX1 = 20;
218 constexpr uint32_t dataPsnTxtStartY1 = 60;
219 constexpr bool allow_multiple_lines = true;
220
221 platform.data_psn->set_text_color(COLOR_GREEN);
222
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100223 info("Final results:\n");
224 info("Total number of inferences: %zu\n", results.size());
alexander3c798932021-03-26 21:42:19 +0000225 /* Results from multiple inferences should be combined before processing. */
226 std::vector<arm::app::ClassificationResult> combinedResults;
227 for (auto& result : results) {
228 combinedResults.insert(combinedResults.end(),
229 result.m_resultVec.begin(),
230 result.m_resultVec.end());
231 }
232
233 /* Get each inference result string using the decoder. */
234 for (const auto & result : results) {
235 std::string infResultStr = audio::asr::DecodeOutput(result.m_resultVec);
236
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100237 info("For timestamp: %f (inference #: %" PRIu32 "); label: %s\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100238 result.m_timeStamp, result.m_inferenceNumber,
239 infResultStr.c_str());
alexander3c798932021-03-26 21:42:19 +0000240 }
241
242 /* Get the decoded result for the combined result. */
243 std::string finalResultStr = audio::asr::DecodeOutput(combinedResults);
244
245 platform.data_psn->present_data_text(
246 finalResultStr.c_str(), finalResultStr.size(),
247 dataPsnTxtStartX1, dataPsnTxtStartY1,
248 allow_multiple_lines);
249
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100250 info("Complete recognition: %s\n", finalResultStr.c_str());
alexander3c798932021-03-26 21:42:19 +0000251 return true;
252 }
253
254} /* namespace app */
255} /* namespace arm */