blob: 5250a9d2db2b6ddf4efdff8740a7bd603e3e0f71 [file] [log] [blame]
Philip Quinn8f953ab2022-12-06 15:37:07 -08001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "TfLiteMotionPredictor"
18#include <input/TfLiteMotionPredictor.h>
19
Philip Quinncb3229a2023-02-08 22:50:59 -080020#include <fcntl.h>
21#include <sys/mman.h>
22#include <unistd.h>
23
Philip Quinn8f953ab2022-12-06 15:37:07 -080024#include <algorithm>
25#include <cmath>
26#include <cstddef>
27#include <cstdint>
Philip Quinn8f953ab2022-12-06 15:37:07 -080028#include <memory>
29#include <span>
Philip Quinn8f953ab2022-12-06 15:37:07 -080030#include <type_traits>
31#include <utility>
32
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080033#include <android-base/file.h>
Philip Quinncb3229a2023-02-08 22:50:59 -080034#include <android-base/logging.h>
35#include <android-base/mapped_file.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080036#define ATRACE_TAG ATRACE_TAG_INPUT
37#include <cutils/trace.h>
38#include <log/log.h>
Philip Quinnf84fa492023-06-26 14:15:15 -070039#include <utils/Timers.h>
Philip Quinn8f953ab2022-12-06 15:37:07 -080040
41#include "tensorflow/lite/core/api/error_reporter.h"
Philip Quinnda6a4482023-02-07 10:09:57 -080042#include "tensorflow/lite/core/api/op_resolver.h"
Philip Quinn8f953ab2022-12-06 15:37:07 -080043#include "tensorflow/lite/interpreter.h"
Philip Quinnda6a4482023-02-07 10:09:57 -080044#include "tensorflow/lite/kernels/builtin_op_kernels.h"
Philip Quinn8f953ab2022-12-06 15:37:07 -080045#include "tensorflow/lite/model.h"
Philip Quinnda6a4482023-02-07 10:09:57 -080046#include "tensorflow/lite/mutable_op_resolver.h"
Philip Quinn8f953ab2022-12-06 15:37:07 -080047
Philip Quinnf84fa492023-06-26 14:15:15 -070048#include "tinyxml2.h"
49
Philip Quinn8f953ab2022-12-06 15:37:07 -080050namespace android {
51namespace {
52
53constexpr char SIGNATURE_KEY[] = "serving_default";
54
55// Input tensor names.
56constexpr char INPUT_R[] = "r";
57constexpr char INPUT_PHI[] = "phi";
58constexpr char INPUT_PRESSURE[] = "pressure";
59constexpr char INPUT_TILT[] = "tilt";
60constexpr char INPUT_ORIENTATION[] = "orientation";
61
62// Output tensor names.
63constexpr char OUTPUT_R[] = "r";
64constexpr char OUTPUT_PHI[] = "phi";
65constexpr char OUTPUT_PRESSURE[] = "pressure";
66
Siarhei Vishniakouc065d7b2023-03-02 14:06:29 -080067// Ideally, we would just use std::filesystem::exists here, but it requires libc++fs, which causes
68// build issues in other parts of the system.
69#if defined(__ANDROID__)
70bool fileExists(const char* filename) {
71 struct stat buffer;
72 return stat(filename, &buffer) == 0;
73}
74#endif
75
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080076std::string getModelPath() {
77#if defined(__ANDROID__)
Philip Quinnf84fa492023-06-26 14:15:15 -070078 static const char* oemModel = "/vendor/etc/motion_predictor_model.tflite";
Siarhei Vishniakouc065d7b2023-03-02 14:06:29 -080079 if (fileExists(oemModel)) {
80 return oemModel;
81 }
Philip Quinnf84fa492023-06-26 14:15:15 -070082 return "/system/etc/motion_predictor_model.tflite";
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080083#else
Philip Quinnf84fa492023-06-26 14:15:15 -070084 return base::GetExecutableDirectory() + "/motion_predictor_model.tflite";
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -080085#endif
86}
87
Philip Quinnf84fa492023-06-26 14:15:15 -070088std::string getConfigPath() {
89 // The config file should be alongside the model file.
90 return base::Dirname(getModelPath()) + "/motion_predictor_config.xml";
91}
92
93int64_t parseXMLInt64(const tinyxml2::XMLElement& configRoot, const char* elementName) {
94 const tinyxml2::XMLElement* element = configRoot.FirstChildElement(elementName);
95 LOG_ALWAYS_FATAL_IF(!element, "Could not find '%s' element", elementName);
96
97 int64_t value = 0;
98 LOG_ALWAYS_FATAL_IF(element->QueryInt64Text(&value) != tinyxml2::XML_SUCCESS,
99 "Failed to parse %s: %s", elementName, element->GetText());
100 return value;
101}
102
Philip Quinn107ce702023-07-14 13:07:13 -0700103float parseXMLFloat(const tinyxml2::XMLElement& configRoot, const char* elementName) {
104 const tinyxml2::XMLElement* element = configRoot.FirstChildElement(elementName);
105 LOG_ALWAYS_FATAL_IF(!element, "Could not find '%s' element", elementName);
106
107 float value = 0;
108 LOG_ALWAYS_FATAL_IF(element->QueryFloatText(&value) != tinyxml2::XML_SUCCESS,
109 "Failed to parse %s: %s", elementName, element->GetText());
110 return value;
111}
112
Philip Quinn8f953ab2022-12-06 15:37:07 -0800113// A TFLite ErrorReporter that logs to logcat.
114class LoggingErrorReporter : public tflite::ErrorReporter {
115public:
116 int Report(const char* format, va_list args) override {
117 return LOG_PRI_VA(ANDROID_LOG_ERROR, LOG_TAG, format, args);
118 }
119};
120
121// Searches a runner for an input tensor.
122TfLiteTensor* findInputTensor(const char* name, tflite::SignatureRunner* runner) {
123 TfLiteTensor* tensor = runner->input_tensor(name);
124 LOG_ALWAYS_FATAL_IF(!tensor, "Failed to find input tensor '%s'", name);
125 return tensor;
126}
127
128// Searches a runner for an output tensor.
129const TfLiteTensor* findOutputTensor(const char* name, tflite::SignatureRunner* runner) {
130 const TfLiteTensor* tensor = runner->output_tensor(name);
131 LOG_ALWAYS_FATAL_IF(!tensor, "Failed to find output tensor '%s'", name);
132 return tensor;
133}
134
135// Returns the buffer for a tensor of type T.
136template <typename T>
137std::span<T> getTensorBuffer(typename std::conditional<std::is_const<T>::value, const TfLiteTensor*,
138 TfLiteTensor*>::type tensor) {
139 LOG_ALWAYS_FATAL_IF(!tensor);
140
141 const TfLiteType type = tflite::typeToTfLiteType<typename std::remove_cv<T>::type>();
142 LOG_ALWAYS_FATAL_IF(tensor->type != type, "Unexpected type for '%s' tensor: %s (expected %s)",
143 tensor->name, TfLiteTypeGetName(tensor->type), TfLiteTypeGetName(type));
144
145 LOG_ALWAYS_FATAL_IF(!tensor->data.data);
Ryan Prichard5a8af502023-08-31 00:00:47 -0700146 return std::span<T>(reinterpret_cast<T*>(tensor->data.data), tensor->bytes / sizeof(T));
Philip Quinn8f953ab2022-12-06 15:37:07 -0800147}
148
149// Verifies that a tensor exists and has an underlying buffer of type T.
150template <typename T>
151void checkTensor(const TfLiteTensor* tensor) {
152 LOG_ALWAYS_FATAL_IF(!tensor);
153
154 const auto buffer = getTensorBuffer<const T>(tensor);
155 LOG_ALWAYS_FATAL_IF(buffer.empty(), "No buffer for tensor '%s'", tensor->name);
156}
157
Philip Quinnda6a4482023-02-07 10:09:57 -0800158std::unique_ptr<tflite::OpResolver> createOpResolver() {
159 auto resolver = std::make_unique<tflite::MutableOpResolver>();
160 resolver->AddBuiltin(::tflite::BuiltinOperator_CONCATENATION,
161 ::tflite::ops::builtin::Register_CONCATENATION());
162 resolver->AddBuiltin(::tflite::BuiltinOperator_FULLY_CONNECTED,
163 ::tflite::ops::builtin::Register_FULLY_CONNECTED());
Philip Quinn107ce702023-07-14 13:07:13 -0700164 resolver->AddBuiltin(::tflite::BuiltinOperator_GELU, ::tflite::ops::builtin::Register_GELU());
Philip Quinnda6a4482023-02-07 10:09:57 -0800165 return resolver;
166}
167
Philip Quinn8f953ab2022-12-06 15:37:07 -0800168} // namespace
169
Philip Quinn9b8926e2023-01-31 14:50:02 -0800170TfLiteMotionPredictorBuffers::TfLiteMotionPredictorBuffers(size_t inputLength)
171 : mInputR(inputLength, 0),
172 mInputPhi(inputLength, 0),
173 mInputPressure(inputLength, 0),
174 mInputTilt(inputLength, 0),
175 mInputOrientation(inputLength, 0) {
Philip Quinn8f953ab2022-12-06 15:37:07 -0800176 LOG_ALWAYS_FATAL_IF(inputLength == 0, "Buffer input size must be greater than 0");
Philip Quinn8f953ab2022-12-06 15:37:07 -0800177}
178
179void TfLiteMotionPredictorBuffers::reset() {
180 std::fill(mInputR.begin(), mInputR.end(), 0);
181 std::fill(mInputPhi.begin(), mInputPhi.end(), 0);
182 std::fill(mInputPressure.begin(), mInputPressure.end(), 0);
183 std::fill(mInputTilt.begin(), mInputTilt.end(), 0);
184 std::fill(mInputOrientation.begin(), mInputOrientation.end(), 0);
185 mAxisFrom.reset();
186 mAxisTo.reset();
187}
188
189void TfLiteMotionPredictorBuffers::copyTo(TfLiteMotionPredictorModel& model) const {
190 LOG_ALWAYS_FATAL_IF(mInputR.size() != model.inputLength(),
191 "Buffer length %zu doesn't match model input length %zu", mInputR.size(),
192 model.inputLength());
193 LOG_ALWAYS_FATAL_IF(!isReady(), "Buffers are incomplete");
194
195 std::copy(mInputR.begin(), mInputR.end(), model.inputR().begin());
196 std::copy(mInputPhi.begin(), mInputPhi.end(), model.inputPhi().begin());
197 std::copy(mInputPressure.begin(), mInputPressure.end(), model.inputPressure().begin());
198 std::copy(mInputTilt.begin(), mInputTilt.end(), model.inputTilt().begin());
199 std::copy(mInputOrientation.begin(), mInputOrientation.end(), model.inputOrientation().begin());
200}
201
202void TfLiteMotionPredictorBuffers::pushSample(int64_t timestamp,
203 const TfLiteMotionPredictorSample sample) {
204 // Convert the sample (x, y) into polar (r, φ) based on a reference axis
205 // from the preceding two points (mAxisFrom/mAxisTo).
206
207 mTimestamp = timestamp;
208
209 if (!mAxisTo) { // First point.
210 mAxisTo = sample;
211 return;
212 }
213
214 // Vector from the last point to the current sample point.
215 const TfLiteMotionPredictorSample::Point v = sample.position - mAxisTo->position;
216
217 const float r = std::hypot(v.x, v.y);
218 float phi = 0;
219 float orientation = 0;
220
Philip Quinn107ce702023-07-14 13:07:13 -0700221 if (!mAxisFrom && r > 0) { // Second point.
Philip Quinn8f953ab2022-12-06 15:37:07 -0800222 // We can only determine the distance from the first point, and not any
223 // angle. However, if the second point forms an axis, the orientation can
224 // be transformed relative to that axis.
225 const float axisPhi = std::atan2(v.y, v.x);
226 // A MotionEvent's orientation is measured clockwise from the vertical
227 // axis, but axisPhi is measured counter-clockwise from the horizontal
228 // axis.
229 orientation = M_PI_2 - sample.orientation - axisPhi;
230 } else {
231 const TfLiteMotionPredictorSample::Point axis = mAxisTo->position - mAxisFrom->position;
232 const float axisPhi = std::atan2(axis.y, axis.x);
233 phi = std::atan2(v.y, v.x) - axisPhi;
234
235 if (std::hypot(axis.x, axis.y) > 0) {
236 // See note above.
237 orientation = M_PI_2 - sample.orientation - axisPhi;
238 }
239 }
240
241 // Update the axis for the next point.
Philip Quinn107ce702023-07-14 13:07:13 -0700242 if (r > 0) {
243 mAxisFrom = mAxisTo;
244 mAxisTo = sample;
245 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800246
247 // Push the current sample onto the end of the input buffers.
Philip Quinn9b8926e2023-01-31 14:50:02 -0800248 mInputR.pushBack(r);
249 mInputPhi.pushBack(phi);
250 mInputPressure.pushBack(sample.pressure);
251 mInputTilt.pushBack(sample.tilt);
252 mInputOrientation.pushBack(orientation);
Philip Quinn8f953ab2022-12-06 15:37:07 -0800253}
254
Siarhei Vishniakoufd0a68e2023-02-28 13:25:36 -0800255std::unique_ptr<TfLiteMotionPredictorModel> TfLiteMotionPredictorModel::create() {
256 const std::string modelPath = getModelPath();
Siarhei Vishniakouc065d7b2023-03-02 14:06:29 -0800257 android::base::unique_fd fd(open(modelPath.c_str(), O_RDONLY));
Philip Quinncb3229a2023-02-08 22:50:59 -0800258 if (fd == -1) {
259 PLOG(FATAL) << "Could not read model from " << modelPath;
260 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800261
Philip Quinncb3229a2023-02-08 22:50:59 -0800262 const off_t fdSize = lseek(fd, 0, SEEK_END);
263 if (fdSize == -1) {
264 PLOG(FATAL) << "Failed to determine file size";
265 }
266
267 std::unique_ptr<android::base::MappedFile> modelBuffer =
268 android::base::MappedFile::FromFd(fd, /*offset=*/0, fdSize, PROT_READ);
269 if (!modelBuffer) {
270 PLOG(FATAL) << "Failed to mmap model";
271 }
Philip Quinn8f953ab2022-12-06 15:37:07 -0800272
Philip Quinnf84fa492023-06-26 14:15:15 -0700273 const std::string configPath = getConfigPath();
274 tinyxml2::XMLDocument configDocument;
275 LOG_ALWAYS_FATAL_IF(configDocument.LoadFile(configPath.c_str()) != tinyxml2::XML_SUCCESS,
276 "Failed to load config file from %s", configPath.c_str());
277
278 // Parse configuration file.
279 const tinyxml2::XMLElement* configRoot = configDocument.FirstChildElement("motion-predictor");
280 LOG_ALWAYS_FATAL_IF(!configRoot);
Philip Quinn107ce702023-07-14 13:07:13 -0700281 Config config{
282 .predictionInterval = parseXMLInt64(*configRoot, "prediction-interval"),
283 .distanceNoiseFloor = parseXMLFloat(*configRoot, "distance-noise-floor"),
Derek Wuaaa47312024-03-26 15:53:44 -0700284 .lowJerk = parseXMLFloat(*configRoot, "low-jerk"),
285 .highJerk = parseXMLFloat(*configRoot, "high-jerk"),
Derek Wucc6aec52024-07-30 11:59:56 +0000286 .jerkAlpha = parseXMLFloat(*configRoot, "jerk-alpha"),
Philip Quinn107ce702023-07-14 13:07:13 -0700287 };
Philip Quinnf84fa492023-06-26 14:15:15 -0700288
Philip Quinn8f953ab2022-12-06 15:37:07 -0800289 return std::unique_ptr<TfLiteMotionPredictorModel>(
Philip Quinn107ce702023-07-14 13:07:13 -0700290 new TfLiteMotionPredictorModel(std::move(modelBuffer), std::move(config)));
Philip Quinn8f953ab2022-12-06 15:37:07 -0800291}
292
Philip Quinncb3229a2023-02-08 22:50:59 -0800293TfLiteMotionPredictorModel::TfLiteMotionPredictorModel(
Philip Quinn107ce702023-07-14 13:07:13 -0700294 std::unique_ptr<android::base::MappedFile> model, Config config)
295 : mFlatBuffer(std::move(model)), mConfig(std::move(config)) {
Philip Quinncb3229a2023-02-08 22:50:59 -0800296 CHECK(mFlatBuffer);
Philip Quinn8f953ab2022-12-06 15:37:07 -0800297 mErrorReporter = std::make_unique<LoggingErrorReporter>();
Philip Quinncb3229a2023-02-08 22:50:59 -0800298 mModel = tflite::FlatBufferModel::VerifyAndBuildFromBuffer(mFlatBuffer->data(),
299 mFlatBuffer->size(),
Philip Quinn8f953ab2022-12-06 15:37:07 -0800300 /*extra_verifier=*/nullptr,
301 mErrorReporter.get());
302 LOG_ALWAYS_FATAL_IF(!mModel);
303
Philip Quinnda6a4482023-02-07 10:09:57 -0800304 auto resolver = createOpResolver();
305 tflite::InterpreterBuilder builder(*mModel, *resolver);
Philip Quinn8f953ab2022-12-06 15:37:07 -0800306
307 if (builder(&mInterpreter) != kTfLiteOk || !mInterpreter) {
308 LOG_ALWAYS_FATAL("Failed to build interpreter");
309 }
310
311 mRunner = mInterpreter->GetSignatureRunner(SIGNATURE_KEY);
312 LOG_ALWAYS_FATAL_IF(!mRunner, "Failed to find runner for signature '%s'", SIGNATURE_KEY);
313
314 allocateTensors();
315}
316
Philip Quinnda6a4482023-02-07 10:09:57 -0800317TfLiteMotionPredictorModel::~TfLiteMotionPredictorModel() {}
318
Philip Quinn8f953ab2022-12-06 15:37:07 -0800319void TfLiteMotionPredictorModel::allocateTensors() {
320 if (mRunner->AllocateTensors() != kTfLiteOk) {
321 LOG_ALWAYS_FATAL("Failed to allocate tensors");
322 }
323
324 attachInputTensors();
325 attachOutputTensors();
326
327 checkTensor<float>(mInputR);
328 checkTensor<float>(mInputPhi);
329 checkTensor<float>(mInputPressure);
330 checkTensor<float>(mInputTilt);
331 checkTensor<float>(mInputOrientation);
332 checkTensor<float>(mOutputR);
333 checkTensor<float>(mOutputPhi);
334 checkTensor<float>(mOutputPressure);
335
336 const auto checkInputTensorSize = [this](const TfLiteTensor* tensor) {
337 const size_t size = getTensorBuffer<const float>(tensor).size();
338 LOG_ALWAYS_FATAL_IF(size != inputLength(),
339 "Tensor '%s' length %zu does not match input length %zu", tensor->name,
340 size, inputLength());
341 };
342
343 checkInputTensorSize(mInputR);
344 checkInputTensorSize(mInputPhi);
345 checkInputTensorSize(mInputPressure);
346 checkInputTensorSize(mInputTilt);
347 checkInputTensorSize(mInputOrientation);
348}
349
350void TfLiteMotionPredictorModel::attachInputTensors() {
351 mInputR = findInputTensor(INPUT_R, mRunner);
352 mInputPhi = findInputTensor(INPUT_PHI, mRunner);
353 mInputPressure = findInputTensor(INPUT_PRESSURE, mRunner);
354 mInputTilt = findInputTensor(INPUT_TILT, mRunner);
355 mInputOrientation = findInputTensor(INPUT_ORIENTATION, mRunner);
356}
357
358void TfLiteMotionPredictorModel::attachOutputTensors() {
359 mOutputR = findOutputTensor(OUTPUT_R, mRunner);
360 mOutputPhi = findOutputTensor(OUTPUT_PHI, mRunner);
361 mOutputPressure = findOutputTensor(OUTPUT_PRESSURE, mRunner);
362}
363
364bool TfLiteMotionPredictorModel::invoke() {
365 ATRACE_BEGIN("TfLiteMotionPredictorModel::invoke");
366 TfLiteStatus result = mRunner->Invoke();
367 ATRACE_END();
368
369 if (result != kTfLiteOk) {
370 return false;
371 }
372
373 // Invoke() might reallocate tensors, so they need to be reattached.
374 attachInputTensors();
375 attachOutputTensors();
376
377 if (outputR().size() != outputPhi().size() || outputR().size() != outputPressure().size()) {
378 LOG_ALWAYS_FATAL("Output size mismatch: (r: %zu, phi: %zu, pressure: %zu)",
379 outputR().size(), outputPhi().size(), outputPressure().size());
380 }
381
382 return true;
383}
384
385size_t TfLiteMotionPredictorModel::inputLength() const {
386 return getTensorBuffer<const float>(mInputR).size();
387}
388
Cody Heinerdbd14eb2023-03-30 18:41:45 -0700389size_t TfLiteMotionPredictorModel::outputLength() const {
390 return getTensorBuffer<const float>(mOutputR).size();
391}
392
Philip Quinn8f953ab2022-12-06 15:37:07 -0800393std::span<float> TfLiteMotionPredictorModel::inputR() {
394 return getTensorBuffer<float>(mInputR);
395}
396
397std::span<float> TfLiteMotionPredictorModel::inputPhi() {
398 return getTensorBuffer<float>(mInputPhi);
399}
400
401std::span<float> TfLiteMotionPredictorModel::inputPressure() {
402 return getTensorBuffer<float>(mInputPressure);
403}
404
405std::span<float> TfLiteMotionPredictorModel::inputTilt() {
406 return getTensorBuffer<float>(mInputTilt);
407}
408
409std::span<float> TfLiteMotionPredictorModel::inputOrientation() {
410 return getTensorBuffer<float>(mInputOrientation);
411}
412
413std::span<const float> TfLiteMotionPredictorModel::outputR() const {
414 return getTensorBuffer<const float>(mOutputR);
415}
416
417std::span<const float> TfLiteMotionPredictorModel::outputPhi() const {
418 return getTensorBuffer<const float>(mOutputPhi);
419}
420
421std::span<const float> TfLiteMotionPredictorModel::outputPressure() const {
422 return getTensorBuffer<const float>(mOutputPressure);
423}
424
425} // namespace android