blob: ec5e1ec6ab909dc00d3f0e82946020bfded74467 [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);
136 mEnabledSensorFormats.emplace(sensor, format);
137 }
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);
143 mEnabledSensorFormats.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);
154 mEnabledSensorFormats.erase(handle);
155 }
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,
161 kRotationVectorsAndFlags,
162 };
163
164 struct PoseEvent {
165 Pose3f pose;
166 std::optional<Twist3f> twist;
167 bool isNewReference;
168 };
169
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700170 sp<Looper> mLooper;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700171 Listener* const mListener;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700172 SensorManager* const mSensorManager;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700173 std::thread mThread;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700174 std::mutex mMutex;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700175 std::map<int32_t, SensorEnableGuard> mEnabledSensors;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700176 std::map<int32_t, DataFormat> mEnabledSensorFormats GUARDED_BY(mMutex);
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700177 sp<SensorEventQueue> mQueue;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700178
179 // We must do some of the initialization operations on the worker thread, because the API relies
180 // on the thread-local looper. In addition, as a matter of convenience, we store some of the
181 // state on the stack.
182 // For that reason, we use a two-step initialization approach, where the ctor mostly just starts
183 // the worker thread and that thread would notify, via the promise below whenever initialization
184 // is finished, and whether it was successful.
185 std::promise<bool> mInitPromise;
186
187 SensorPoseProviderImpl(const char* packageName, Listener* listener)
188 : mListener(listener),
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700189 mSensorManager(&SensorManager::getInstanceForPackage(String16(packageName))),
190 mThread([this] { threadFunc(); }) {}
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700191
192 void initFinished(bool success) { mInitPromise.set_value(success); }
193
194 bool waitInitFinished() { return mInitPromise.get_future().get(); }
195
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700196 void threadFunc() {
Ytai Ben-Tsvid9125692021-08-24 08:53:38 -0700197 // Obtain looper.
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700198 mLooper = Looper::prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700199
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700200 // Create event queue.
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700201 mQueue = mSensorManager->createEventQueue();
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700202
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700203 if (mQueue == nullptr) {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700204 ALOGE("Failed to create a sensor event queue");
205 initFinished(false);
206 return;
207 }
208
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700209 EventQueueGuard eventQueueGuard(mQueue, mLooper.get());
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700210
211 initFinished(true);
212
213 while (true) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700214 int ret = mLooper->pollOnce(-1 /* no timeout */, nullptr, nullptr, nullptr);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700215
216 switch (ret) {
217 case ALOOPER_POLL_WAKE:
218 // Normal way to exit.
219 return;
220
221 case kIdent:
222 // Possible events on our queue.
223 break;
224
225 default:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700226 ALOGE("Unexpected status out of Looper::pollOnce: %d", ret);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700227 }
228
229 // Process an event.
230 ASensorEvent event;
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700231 ssize_t actual = mQueue->read(&event, 1);
232 if (actual > 0) {
233 mQueue->sendAck(&event, actual);
234 }
235 ssize_t size = mQueue->filterEvents(&event, actual);
236
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700237 if (size < 0 || size > 1) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700238 ALOGE("Unexpected return value from SensorEventQueue::filterEvents: %zd", size);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700239 break;
240 }
241 if (size == 0) {
242 // No events.
243 continue;
244 }
245
246 handleEvent(event);
247 }
248 }
249
250 void handleEvent(const ASensorEvent& event) {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700251 DataFormat format;
252 {
253 std::lock_guard lock(mMutex);
254 auto iter = mEnabledSensorFormats.find(event.sensor);
255 if (iter == mEnabledSensorFormats.end()) {
256 // This can happen if we have any pending events shortly after stopping.
257 return;
258 }
259 format = iter->second;
260 }
261 auto value = parseEvent(event, format);
262 mListener->onPose(event.timestamp, event.sensor, value.pose, value.twist,
263 value.isNewReference);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700264 }
265
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700266 DataFormat getSensorFormat(int32_t handle) {
267 std::optional<const Sensor> sensor = getSensorByHandle(handle);
268 if (!sensor) {
269 ALOGE("Sensor not found: %d", handle);
270 return DataFormat::kUnknown;
271 }
272 if (sensor->getType() == ASENSOR_TYPE_ROTATION_VECTOR ||
273 sensor->getType() == ASENSOR_TYPE_GAME_ROTATION_VECTOR) {
274 return DataFormat::kQuaternion;
275 }
276
277 if (sensor->getStringType() == "com.google.hardware.sensor.hid_dynamic.headtracker") {
278 return DataFormat::kRotationVectorsAndFlags;
279 }
280
281 return DataFormat::kUnknown;
282 }
283
284 std::optional<const Sensor> getSensorByHandle(int32_t handle) {
285 const Sensor* const* list;
286 ssize_t size;
287
288 // Search static sensor list.
289 size = mSensorManager->getSensorList(&list);
290 if (size < 0) {
291 ALOGE("getSensorList failed with error code %zd", size);
292 return std::nullopt;
293 }
294 for (size_t i = 0; i < size; ++i) {
295 if (list[i]->getHandle() == handle) {
296 return *list[i];
297 }
298 }
299
300 // Search dynamic sensor list.
301 Vector<Sensor> dynList;
302 size = mSensorManager->getDynamicSensorList(dynList);
303 if (size < 0) {
304 ALOGE("getDynamicSensorList failed with error code %zd", size);
305 return std::nullopt;
306 }
307 for (size_t i = 0; i < size; ++i) {
308 if (dynList[i].getHandle() == handle) {
309 return dynList[i];
310 }
311 }
312
313 return std::nullopt;
314 }
315
316 static PoseEvent parseEvent(const ASensorEvent& event, DataFormat format) {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700317 // TODO(ytai): Add more types.
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700318 switch (format) {
319 case DataFormat::kQuaternion: {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700320 Eigen::Quaternionf quat(event.data[3], event.data[0], event.data[1], event.data[2]);
Ytai Ben-Tsvi54f07582021-09-13 12:09:42 -0700321 // Adapt to different frame convention.
322 quat *= rotateX(-M_PI_2);
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700323 return PoseEvent{Pose3f(quat), std::optional<Twist3f>(), false};
324 }
325
326 case DataFormat::kRotationVectorsAndFlags: {
327 // Custom sensor, assumed to contain:
328 // 3 floats representing orientation as a rotation vector (in rad).
329 // 3 floats representing angular velocity as a rotation vector (in rad/s).
330 // 1 uint32_t of flags, where:
331 // - LSb is '1' iff the given sample is the first one in a new frame of reference.
332 // - The rest of the bits are reserved for future use.
333 Eigen::Vector3f rotation = {event.data[0], event.data[1], event.data[2]};
334 Eigen::Vector3f twist = {event.data[3], event.data[4], event.data[5]};
335 Eigen::Quaternionf quat = rotationVectorToQuaternion(rotation);
336 uint32_t flags = *reinterpret_cast<const uint32_t*>(&event.data[6]);
337 return PoseEvent{Pose3f(quat), Twist3f(Eigen::Vector3f::Zero(), twist),
338 (flags & (1 << 0)) != 0};
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700339 }
340
341 default:
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700342 LOG_ALWAYS_FATAL("Unexpected sensor type: %d", static_cast<int>(format));
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700343 }
344 }
345};
346
347} // namespace
348
349std::unique_ptr<SensorPoseProvider> SensorPoseProvider::create(const char* packageName,
350 Listener* listener) {
351 return SensorPoseProviderImpl::create(packageName, listener);
352}
353
354} // namespace media
355} // namespace android