blob: e5e1521cb96c053d85ab26468d4beb1a269f2b96 [file] [log] [blame]
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -07001/*
2 * Copyright (C) 2021 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#include <media/SensorPoseProvider.h>
18
19#define LOG_TAG "SensorPoseProvider"
20
21#include <inttypes.h>
22
23#include <future>
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070024#include <map>
25#include <thread>
26
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -070027#include <android-base/thread_annotations.h>
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070028#include <log/log_main.h>
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070029#include <sensor/SensorEventQueue.h>
30#include <sensor/SensorManager.h>
31#include <utils/Looper.h>
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070032
Ytai Ben-Tsvi54f07582021-09-13 12:09:42 -070033#include "QuaternionUtil.h"
34
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070035namespace android {
36namespace media {
37namespace {
38
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070039// Identifier to use for our event queue on the loop.
40// The number 19 is arbitrary, only useful if using multiple objects on the same looper.
41constexpr int kIdent = 19;
42
43static inline Looper* ALooper_to_Looper(ALooper* alooper) {
44 return reinterpret_cast<Looper*>(alooper);
45}
46
47static inline ALooper* Looper_to_ALooper(Looper* looper) {
48 return reinterpret_cast<ALooper*>(looper);
49}
50
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070051/**
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070052 * RAII-wrapper around SensorEventQueue, which unregisters it on destruction.
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070053 */
54class EventQueueGuard {
55 public:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070056 EventQueueGuard(const sp<SensorEventQueue>& queue, Looper* looper) : mQueue(queue) {
57 mQueue->looper = Looper_to_ALooper(looper);
58 mQueue->requestAdditionalInfo = false;
59 looper->addFd(mQueue->getFd(), kIdent, ALOOPER_EVENT_INPUT, nullptr, nullptr);
60 }
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070061
62 ~EventQueueGuard() {
63 if (mQueue) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070064 ALooper_to_Looper(mQueue->looper)->removeFd(mQueue->getFd());
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070065 }
66 }
67
68 EventQueueGuard(const EventQueueGuard&) = delete;
69 EventQueueGuard& operator=(const EventQueueGuard&) = delete;
70
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070071 [[nodiscard]] SensorEventQueue* get() const { return mQueue.get(); }
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070072
73 private:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070074 sp<SensorEventQueue> mQueue;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070075};
76
77/**
78 * RAII-wrapper around an enabled sensor, which disables it upon destruction.
79 */
80class SensorEnableGuard {
81 public:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070082 SensorEnableGuard(const sp<SensorEventQueue>& queue, int32_t sensor)
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070083 : mQueue(queue), mSensor(sensor) {}
84
85 ~SensorEnableGuard() {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070086 if (mSensor != SensorPoseProvider::INVALID_HANDLE) {
87 int ret = mQueue->disableSensor(mSensor);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070088 if (ret) {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -070089 ALOGE("Failed to disable sensor: %s", strerror(ret));
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070090 }
91 }
92 }
93
94 SensorEnableGuard(const SensorEnableGuard&) = delete;
95 SensorEnableGuard& operator=(const SensorEnableGuard&) = delete;
96
97 // Enable moving.
98 SensorEnableGuard(SensorEnableGuard&& other) : mQueue(other.mQueue), mSensor(other.mSensor) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070099 other.mSensor = SensorPoseProvider::INVALID_HANDLE;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700100 }
101
102 private:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700103 sp<SensorEventQueue> const mQueue;
104 int32_t mSensor;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700105};
106
107/**
108 * Streams the required events to a PoseListener, based on events originating from the Sensor stack.
109 */
110class SensorPoseProviderImpl : public SensorPoseProvider {
111 public:
112 static std::unique_ptr<SensorPoseProvider> create(const char* packageName, Listener* listener) {
113 std::unique_ptr<SensorPoseProviderImpl> result(
114 new SensorPoseProviderImpl(packageName, listener));
115 return result->waitInitFinished() ? std::move(result) : nullptr;
116 }
117
118 ~SensorPoseProviderImpl() override {
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700119 // Disable all active sensors.
120 mEnabledSensors.clear();
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700121 mLooper->wake();
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700122 mThread.join();
123 }
124
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700125 bool startSensor(int32_t sensor, std::chrono::microseconds samplingPeriod) override {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700126 // Figure out the sensor's data format.
127 DataFormat format = getSensorFormat(sensor);
128 if (format == DataFormat::kUnknown) {
129 ALOGE("Unknown format for sensor %" PRId32, sensor);
130 return false;
131 }
132
133 {
134 std::lock_guard lock(mMutex);
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800135 mEnabledSensorsExtra.emplace(sensor, SensorExtra{ .format = format });
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700136 }
137
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700138 // Enable the sensor.
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700139 if (mQueue->enableSensor(sensor, samplingPeriod.count(), 0, 0)) {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700140 ALOGE("Failed to enable sensor");
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700141 std::lock_guard lock(mMutex);
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800142 mEnabledSensorsExtra.erase(sensor);
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700143 return false;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700144 }
145
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700146 mEnabledSensors.emplace(sensor, SensorEnableGuard(mQueue.get(), sensor));
147 return true;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700148 }
149
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700150 void stopSensor(int handle) override {
151 mEnabledSensors.erase(handle);
152 std::lock_guard lock(mMutex);
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800153 mEnabledSensorsExtra.erase(handle);
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700154 }
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700155
156 private:
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700157 enum DataFormat {
158 kUnknown,
159 kQuaternion,
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800160 kRotationVectorsAndDiscontinuityCount,
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700161 };
162
163 struct PoseEvent {
164 Pose3f pose;
165 std::optional<Twist3f> twist;
166 bool isNewReference;
167 };
168
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800169 struct SensorExtra {
170 DataFormat format;
171 std::optional<int32_t> discontinuityCount;
172 };
173
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700174 sp<Looper> mLooper;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700175 Listener* const mListener;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700176 SensorManager* const mSensorManager;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700177 std::mutex mMutex;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700178 std::map<int32_t, SensorEnableGuard> mEnabledSensors;
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800179 std::map<int32_t, SensorExtra> mEnabledSensorsExtra GUARDED_BY(mMutex);
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700180 sp<SensorEventQueue> mQueue;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700181
182 // We must do some of the initialization operations on the worker thread, because the API relies
183 // on the thread-local looper. In addition, as a matter of convenience, we store some of the
184 // state on the stack.
185 // For that reason, we use a two-step initialization approach, where the ctor mostly just starts
186 // the worker thread and that thread would notify, via the promise below whenever initialization
187 // is finished, and whether it was successful.
188 std::promise<bool> mInitPromise;
Keith Mok674f7352022-06-06 21:40:11 +0000189 std::thread mThread;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700190
191 SensorPoseProviderImpl(const char* packageName, Listener* listener)
192 : mListener(listener),
Keith Mok674f7352022-06-06 21:40:11 +0000193 mSensorManager(&SensorManager::getInstanceForPackage(String16(packageName))) {
194 mThread = std::thread([this] { threadFunc(); });
195 }
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700196
197 void initFinished(bool success) { mInitPromise.set_value(success); }
198
199 bool waitInitFinished() { return mInitPromise.get_future().get(); }
200
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700201 void threadFunc() {
Ytai Ben-Tsvid9125692021-08-24 08:53:38 -0700202 // Obtain looper.
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700203 mLooper = Looper::prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700204
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700205 // Create event queue.
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700206 mQueue = mSensorManager->createEventQueue();
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700207
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700208 if (mQueue == nullptr) {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700209 ALOGE("Failed to create a sensor event queue");
210 initFinished(false);
211 return;
212 }
213
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700214 EventQueueGuard eventQueueGuard(mQueue, mLooper.get());
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700215
216 initFinished(true);
217
218 while (true) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700219 int ret = mLooper->pollOnce(-1 /* no timeout */, nullptr, nullptr, nullptr);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700220
221 switch (ret) {
222 case ALOOPER_POLL_WAKE:
223 // Normal way to exit.
224 return;
225
226 case kIdent:
227 // Possible events on our queue.
228 break;
229
230 default:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700231 ALOGE("Unexpected status out of Looper::pollOnce: %d", ret);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700232 }
233
234 // Process an event.
235 ASensorEvent event;
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700236 ssize_t actual = mQueue->read(&event, 1);
237 if (actual > 0) {
238 mQueue->sendAck(&event, actual);
239 }
240 ssize_t size = mQueue->filterEvents(&event, actual);
241
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700242 if (size < 0 || size > 1) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700243 ALOGE("Unexpected return value from SensorEventQueue::filterEvents: %zd", size);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700244 break;
245 }
246 if (size == 0) {
247 // No events.
248 continue;
249 }
250
251 handleEvent(event);
252 }
253 }
254
255 void handleEvent(const ASensorEvent& event) {
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800256 PoseEvent value;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700257 {
258 std::lock_guard lock(mMutex);
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800259 auto iter = mEnabledSensorsExtra.find(event.sensor);
260 if (iter == mEnabledSensorsExtra.end()) {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700261 // This can happen if we have any pending events shortly after stopping.
262 return;
263 }
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800264 value = parseEvent(event, iter->second.format, &iter->second.discontinuityCount);
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700265 }
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700266 mListener->onPose(event.timestamp, event.sensor, value.pose, value.twist,
267 value.isNewReference);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700268 }
269
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700270 DataFormat getSensorFormat(int32_t handle) {
271 std::optional<const Sensor> sensor = getSensorByHandle(handle);
272 if (!sensor) {
273 ALOGE("Sensor not found: %d", handle);
274 return DataFormat::kUnknown;
275 }
276 if (sensor->getType() == ASENSOR_TYPE_ROTATION_VECTOR ||
277 sensor->getType() == ASENSOR_TYPE_GAME_ROTATION_VECTOR) {
278 return DataFormat::kQuaternion;
279 }
280
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800281 if (sensor->getType() == ASENSOR_TYPE_HEAD_TRACKER) {
282 return DataFormat::kRotationVectorsAndDiscontinuityCount;
283 }
284
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700285 return DataFormat::kUnknown;
286 }
287
Andy Hunga461a002022-05-17 10:36:02 -0700288 std::optional<const Sensor> getSensorByHandle(int32_t handle) override {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700289 const Sensor* const* list;
290 ssize_t size;
291
292 // Search static sensor list.
293 size = mSensorManager->getSensorList(&list);
294 if (size < 0) {
295 ALOGE("getSensorList failed with error code %zd", size);
296 return std::nullopt;
297 }
298 for (size_t i = 0; i < size; ++i) {
299 if (list[i]->getHandle() == handle) {
300 return *list[i];
301 }
302 }
303
304 // Search dynamic sensor list.
305 Vector<Sensor> dynList;
306 size = mSensorManager->getDynamicSensorList(dynList);
307 if (size < 0) {
308 ALOGE("getDynamicSensorList failed with error code %zd", size);
309 return std::nullopt;
310 }
311 for (size_t i = 0; i < size; ++i) {
312 if (dynList[i].getHandle() == handle) {
313 return dynList[i];
314 }
315 }
316
317 return std::nullopt;
318 }
319
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800320 static PoseEvent parseEvent(const ASensorEvent& event, DataFormat format,
321 std::optional<int32_t>* discontinutyCount) {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700322 switch (format) {
323 case DataFormat::kQuaternion: {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700324 Eigen::Quaternionf quat(event.data[3], event.data[0], event.data[1], event.data[2]);
Ytai Ben-Tsvi54f07582021-09-13 12:09:42 -0700325 // Adapt to different frame convention.
326 quat *= rotateX(-M_PI_2);
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700327 return PoseEvent{Pose3f(quat), std::optional<Twist3f>(), false};
328 }
329
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800330 case DataFormat::kRotationVectorsAndDiscontinuityCount: {
331 Eigen::Vector3f rotation = {event.head_tracker.rx, event.head_tracker.ry,
332 event.head_tracker.rz};
333 Eigen::Vector3f twist = {event.head_tracker.vx, event.head_tracker.vy,
Ytai Ben-Tsvi27bbea32022-01-28 18:01:06 -0800334 event.head_tracker.vz};
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800335 Eigen::Quaternionf quat = rotationVectorToQuaternion(rotation);
336 bool isNewReference =
337 !discontinutyCount->has_value() ||
338 discontinutyCount->value() != event.head_tracker.discontinuity_count;
339 *discontinutyCount = event.head_tracker.discontinuity_count;
340
341 return PoseEvent{Pose3f(quat), Twist3f(Eigen::Vector3f::Zero(), twist),
342 isNewReference};
343 }
344
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700345 default:
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700346 LOG_ALWAYS_FATAL("Unexpected sensor type: %d", static_cast<int>(format));
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700347 }
348 }
349};
350
351} // namespace
352
353std::unique_ptr<SensorPoseProvider> SensorPoseProvider::create(const char* packageName,
354 Listener* listener) {
355 return SensorPoseProviderImpl::create(packageName, listener);
356}
357
358} // namespace media
359} // namespace android