blob: 4884ae412888c1166ef6485062f1bbeb0e145460 [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/Sensor.h>
30#include <sensor/SensorEventQueue.h>
31#include <sensor/SensorManager.h>
32#include <utils/Looper.h>
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070033
Ytai Ben-Tsvi54f07582021-09-13 12:09:42 -070034#include "QuaternionUtil.h"
35
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070036namespace android {
37namespace media {
38namespace {
39
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070040// Identifier to use for our event queue on the loop.
41// The number 19 is arbitrary, only useful if using multiple objects on the same looper.
42constexpr int kIdent = 19;
43
44static inline Looper* ALooper_to_Looper(ALooper* alooper) {
45 return reinterpret_cast<Looper*>(alooper);
46}
47
48static inline ALooper* Looper_to_ALooper(Looper* looper) {
49 return reinterpret_cast<ALooper*>(looper);
50}
51
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070052/**
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070053 * RAII-wrapper around SensorEventQueue, which unregisters it on destruction.
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070054 */
55class EventQueueGuard {
56 public:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070057 EventQueueGuard(const sp<SensorEventQueue>& queue, Looper* looper) : mQueue(queue) {
58 mQueue->looper = Looper_to_ALooper(looper);
59 mQueue->requestAdditionalInfo = false;
60 looper->addFd(mQueue->getFd(), kIdent, ALOOPER_EVENT_INPUT, nullptr, nullptr);
61 }
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070062
63 ~EventQueueGuard() {
64 if (mQueue) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070065 ALooper_to_Looper(mQueue->looper)->removeFd(mQueue->getFd());
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070066 }
67 }
68
69 EventQueueGuard(const EventQueueGuard&) = delete;
70 EventQueueGuard& operator=(const EventQueueGuard&) = delete;
71
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070072 [[nodiscard]] SensorEventQueue* get() const { return mQueue.get(); }
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070073
74 private:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070075 sp<SensorEventQueue> mQueue;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070076};
77
78/**
79 * RAII-wrapper around an enabled sensor, which disables it upon destruction.
80 */
81class SensorEnableGuard {
82 public:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070083 SensorEnableGuard(const sp<SensorEventQueue>& queue, int32_t sensor)
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070084 : mQueue(queue), mSensor(sensor) {}
85
86 ~SensorEnableGuard() {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -070087 if (mSensor != SensorPoseProvider::INVALID_HANDLE) {
88 int ret = mQueue->disableSensor(mSensor);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070089 if (ret) {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -070090 ALOGE("Failed to disable sensor: %s", strerror(ret));
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070091 }
92 }
93 }
94
95 SensorEnableGuard(const SensorEnableGuard&) = delete;
96 SensorEnableGuard& operator=(const SensorEnableGuard&) = delete;
97
98 // Enable moving.
99 SensorEnableGuard(SensorEnableGuard&& other) : mQueue(other.mQueue), mSensor(other.mSensor) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700100 other.mSensor = SensorPoseProvider::INVALID_HANDLE;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700101 }
102
103 private:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700104 sp<SensorEventQueue> const mQueue;
105 int32_t mSensor;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700106};
107
108/**
109 * Streams the required events to a PoseListener, based on events originating from the Sensor stack.
110 */
111class SensorPoseProviderImpl : public SensorPoseProvider {
112 public:
113 static std::unique_ptr<SensorPoseProvider> create(const char* packageName, Listener* listener) {
114 std::unique_ptr<SensorPoseProviderImpl> result(
115 new SensorPoseProviderImpl(packageName, listener));
116 return result->waitInitFinished() ? std::move(result) : nullptr;
117 }
118
119 ~SensorPoseProviderImpl() override {
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700120 // Disable all active sensors.
121 mEnabledSensors.clear();
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700122 mLooper->wake();
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700123 mThread.join();
124 }
125
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700126 bool startSensor(int32_t sensor, std::chrono::microseconds samplingPeriod) override {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700127 // Figure out the sensor's data format.
128 DataFormat format = getSensorFormat(sensor);
129 if (format == DataFormat::kUnknown) {
130 ALOGE("Unknown format for sensor %" PRId32, sensor);
131 return false;
132 }
133
134 {
135 std::lock_guard lock(mMutex);
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800136 mEnabledSensorsExtra.emplace(sensor, SensorExtra{ .format = format });
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700137 }
138
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700139 // Enable the sensor.
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700140 if (mQueue->enableSensor(sensor, samplingPeriod.count(), 0, 0)) {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700141 ALOGE("Failed to enable sensor");
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700142 std::lock_guard lock(mMutex);
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800143 mEnabledSensorsExtra.erase(sensor);
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700144 return false;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700145 }
146
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700147 mEnabledSensors.emplace(sensor, SensorEnableGuard(mQueue.get(), sensor));
148 return true;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700149 }
150
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700151 void stopSensor(int handle) override {
152 mEnabledSensors.erase(handle);
153 std::lock_guard lock(mMutex);
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800154 mEnabledSensorsExtra.erase(handle);
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700155 }
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700156
157 private:
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700158 enum DataFormat {
159 kUnknown,
160 kQuaternion,
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800161 kRotationVectorsAndDiscontinuityCount,
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700162 };
163
164 struct PoseEvent {
165 Pose3f pose;
166 std::optional<Twist3f> twist;
167 bool isNewReference;
168 };
169
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800170 struct SensorExtra {
171 DataFormat format;
172 std::optional<int32_t> discontinuityCount;
173 };
174
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700175 sp<Looper> mLooper;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700176 Listener* const mListener;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700177 SensorManager* const mSensorManager;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700178 std::thread mThread;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700179 std::mutex mMutex;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700180 std::map<int32_t, SensorEnableGuard> mEnabledSensors;
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800181 std::map<int32_t, SensorExtra> mEnabledSensorsExtra GUARDED_BY(mMutex);
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700182 sp<SensorEventQueue> mQueue;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700183
184 // We must do some of the initialization operations on the worker thread, because the API relies
185 // on the thread-local looper. In addition, as a matter of convenience, we store some of the
186 // state on the stack.
187 // For that reason, we use a two-step initialization approach, where the ctor mostly just starts
188 // the worker thread and that thread would notify, via the promise below whenever initialization
189 // is finished, and whether it was successful.
190 std::promise<bool> mInitPromise;
191
192 SensorPoseProviderImpl(const char* packageName, Listener* listener)
193 : mListener(listener),
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700194 mSensorManager(&SensorManager::getInstanceForPackage(String16(packageName))),
195 mThread([this] { threadFunc(); }) {}
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
288 std::optional<const Sensor> getSensorByHandle(int32_t handle) {
289 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