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