blob: cfa23d0459b093b6dc31c9691654d139cd2d45ee [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
27#include <android/looper.h>
28#include <log/log_main.h>
29
Ytai Ben-Tsvi54f07582021-09-13 12:09:42 -070030#include "QuaternionUtil.h"
31
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -070032namespace android {
33namespace media {
34namespace {
35
36/**
37 * RAII-wrapper around ASensorEventQueue, which destroys it on destruction.
38 */
39class EventQueueGuard {
40 public:
41 EventQueueGuard(ASensorManager* manager, ASensorEventQueue* queue)
42 : mManager(manager), mQueue(queue) {}
43
44 ~EventQueueGuard() {
45 if (mQueue) {
46 int ret = ASensorManager_destroyEventQueue(mManager, mQueue);
47 if (ret) {
48 ALOGE("Failed to destroy event queue: %s\n", strerror(ret));
49 }
50 }
51 }
52
53 EventQueueGuard(const EventQueueGuard&) = delete;
54 EventQueueGuard& operator=(const EventQueueGuard&) = delete;
55
56 [[nodiscard]] ASensorEventQueue* get() const { return mQueue; }
57
58 private:
59 ASensorManager* const mManager;
60 ASensorEventQueue* mQueue;
61};
62
63/**
64 * RAII-wrapper around an enabled sensor, which disables it upon destruction.
65 */
66class SensorEnableGuard {
67 public:
68 SensorEnableGuard(ASensorEventQueue* queue, const ASensor* sensor)
69 : mQueue(queue), mSensor(sensor) {}
70
71 ~SensorEnableGuard() {
72 if (mSensor) {
73 int ret = ASensorEventQueue_disableSensor(mQueue, mSensor);
74 if (ret) {
75 ALOGE("Failed to disable sensor: %s\n", strerror(ret));
76 }
77 }
78 }
79
80 SensorEnableGuard(const SensorEnableGuard&) = delete;
81 SensorEnableGuard& operator=(const SensorEnableGuard&) = delete;
82
83 // Enable moving.
84 SensorEnableGuard(SensorEnableGuard&& other) : mQueue(other.mQueue), mSensor(other.mSensor) {
85 other.mSensor = nullptr;
86 }
87
88 private:
89 ASensorEventQueue* const mQueue;
90 const ASensor* mSensor;
91};
92
93/**
94 * Streams the required events to a PoseListener, based on events originating from the Sensor stack.
95 */
96class SensorPoseProviderImpl : public SensorPoseProvider {
97 public:
98 static std::unique_ptr<SensorPoseProvider> create(const char* packageName, Listener* listener) {
99 std::unique_ptr<SensorPoseProviderImpl> result(
100 new SensorPoseProviderImpl(packageName, listener));
101 return result->waitInitFinished() ? std::move(result) : nullptr;
102 }
103
104 ~SensorPoseProviderImpl() override {
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700105 // Disable all active sensors.
106 mEnabledSensors.clear();
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700107 ALooper_wake(mLooper);
108 mThread.join();
109 }
110
111 int32_t startSensor(const ASensor* sensor, std::chrono::microseconds samplingPeriod) override {
112 int32_t handle = ASensor_getHandle(sensor);
113
114 // Enable the sensor.
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700115 if (ASensorEventQueue_registerSensor(mQueue, sensor, samplingPeriod.count(), 0)) {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700116 ALOGE("Failed to enable sensor");
117 return INVALID_HANDLE;
118 }
119
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700120 mEnabledSensors.emplace(handle, SensorEnableGuard(mQueue, sensor));
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700121 return handle;
122 }
123
124 void stopSensor(int handle) override { mEnabledSensors.erase(handle); }
125
126 private:
127 ALooper* mLooper;
128 Listener* const mListener;
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700129
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700130 std::thread mThread;
131 std::map<int32_t, SensorEnableGuard> mEnabledSensors;
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700132 ASensorEventQueue* mQueue;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700133
134 // We must do some of the initialization operations on the worker thread, because the API relies
135 // on the thread-local looper. In addition, as a matter of convenience, we store some of the
136 // state on the stack.
137 // For that reason, we use a two-step initialization approach, where the ctor mostly just starts
138 // the worker thread and that thread would notify, via the promise below whenever initialization
139 // is finished, and whether it was successful.
140 std::promise<bool> mInitPromise;
141
142 SensorPoseProviderImpl(const char* packageName, Listener* listener)
143 : mListener(listener),
144 mThread([this, p = std::string(packageName)] { threadFunc(p.c_str()); }) {}
145
146 void initFinished(bool success) { mInitPromise.set_value(success); }
147
148 bool waitInitFinished() { return mInitPromise.get_future().get(); }
149
150 void threadFunc(const char* packageName) {
Ytai Ben-Tsvid9125692021-08-24 08:53:38 -0700151 // Obtain looper.
152 mLooper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
153
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700154 // The number 19 is arbitrary, only useful if using multiple objects on the same looper.
155 constexpr int kIdent = 19;
156
157 // Obtain sensor manager.
158 ASensorManager* sensor_manager = ASensorManager_getInstanceForPackage(packageName);
159 if (!sensor_manager) {
160 ALOGE("Failed to get a sensor manager");
161 initFinished(false);
162 return;
163 }
164
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700165 // Create event queue.
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700166 mQueue = ASensorManager_createEventQueue(sensor_manager, mLooper, kIdent, nullptr, nullptr);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700167
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700168 if (mQueue == nullptr) {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700169 ALOGE("Failed to create a sensor event queue");
170 initFinished(false);
171 return;
172 }
173
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700174 EventQueueGuard eventQueueGuard(sensor_manager, mQueue);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700175
176 initFinished(true);
177
178 while (true) {
179 int ret = ALooper_pollOnce(-1 /* no timeout */, nullptr, nullptr, nullptr);
180
181 switch (ret) {
182 case ALOOPER_POLL_WAKE:
183 // Normal way to exit.
184 return;
185
186 case kIdent:
187 // Possible events on our queue.
188 break;
189
190 default:
191 ALOGE("Unexpected status out of ALooper_pollOnce: %d", ret);
192 }
193
194 // Process an event.
195 ASensorEvent event;
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700196 ssize_t size = ASensorEventQueue_getEvents(mQueue, &event, 1);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700197 if (size < 0 || size > 1) {
198 ALOGE("Unexpected return value from ASensorEventQueue_getEvents: %zd", size);
199 break;
200 }
201 if (size == 0) {
202 // No events.
203 continue;
204 }
205
206 handleEvent(event);
207 }
208 }
209
210 void handleEvent(const ASensorEvent& event) {
211 auto value = parseEvent(event);
212 mListener->onPose(event.timestamp, event.sensor, std::get<0>(value), std::get<1>(value));
213 }
214
215 static std::tuple<Pose3f, std::optional<Twist3f>> parseEvent(const ASensorEvent& event) {
216 // TODO(ytai): Add more types.
217 switch (event.type) {
218 case ASENSOR_TYPE_ROTATION_VECTOR:
219 case ASENSOR_TYPE_GAME_ROTATION_VECTOR: {
220 Eigen::Quaternionf quat(event.data[3], event.data[0], event.data[1], event.data[2]);
Ytai Ben-Tsvi54f07582021-09-13 12:09:42 -0700221 // Adapt to different frame convention.
222 quat *= rotateX(-M_PI_2);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700223 return std::make_tuple(Pose3f(quat), std::optional<Twist3f>());
224 }
225
226 default:
227 ALOGE("Unsupported sensor type: %" PRId32, event.type);
228 return std::make_tuple(Pose3f(), std::optional<Twist3f>());
229 }
230 }
231};
232
233} // namespace
234
235std::unique_ptr<SensorPoseProvider> SensorPoseProvider::create(const char* packageName,
236 Listener* listener) {
237 return SensorPoseProviderImpl::create(packageName, listener);
238}
239
240} // namespace media
241} // namespace android