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