blob: f3f9b7752dca0093a89bfebd5c0830fcbe7781e4 [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,
161 kRotationVectorsAndFlags,
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800162 kRotationVectorsAndDiscontinuityCount,
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700163 };
164
165 struct PoseEvent {
166 Pose3f pose;
167 std::optional<Twist3f> twist;
168 bool isNewReference;
169 };
170
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800171 struct SensorExtra {
172 DataFormat format;
173 std::optional<int32_t> discontinuityCount;
174 };
175
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700176 sp<Looper> mLooper;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700177 Listener* const mListener;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700178 SensorManager* const mSensorManager;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700179 std::thread mThread;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700180 std::mutex mMutex;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700181 std::map<int32_t, SensorEnableGuard> mEnabledSensors;
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800182 std::map<int32_t, SensorExtra> mEnabledSensorsExtra GUARDED_BY(mMutex);
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700183 sp<SensorEventQueue> mQueue;
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700184
185 // We must do some of the initialization operations on the worker thread, because the API relies
186 // on the thread-local looper. In addition, as a matter of convenience, we store some of the
187 // state on the stack.
188 // For that reason, we use a two-step initialization approach, where the ctor mostly just starts
189 // the worker thread and that thread would notify, via the promise below whenever initialization
190 // is finished, and whether it was successful.
191 std::promise<bool> mInitPromise;
192
193 SensorPoseProviderImpl(const char* packageName, Listener* listener)
194 : mListener(listener),
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700195 mSensorManager(&SensorManager::getInstanceForPackage(String16(packageName))),
196 mThread([this] { threadFunc(); }) {}
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700197
198 void initFinished(bool success) { mInitPromise.set_value(success); }
199
200 bool waitInitFinished() { return mInitPromise.get_future().get(); }
201
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700202 void threadFunc() {
Ytai Ben-Tsvid9125692021-08-24 08:53:38 -0700203 // Obtain looper.
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700204 mLooper = Looper::prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700205
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700206 // Create event queue.
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700207 mQueue = mSensorManager->createEventQueue();
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700208
Ytai Ben-Tsvic29bad62021-09-09 10:22:52 -0700209 if (mQueue == nullptr) {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700210 ALOGE("Failed to create a sensor event queue");
211 initFinished(false);
212 return;
213 }
214
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700215 EventQueueGuard eventQueueGuard(mQueue, mLooper.get());
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700216
217 initFinished(true);
218
219 while (true) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700220 int ret = mLooper->pollOnce(-1 /* no timeout */, nullptr, nullptr, nullptr);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700221
222 switch (ret) {
223 case ALOOPER_POLL_WAKE:
224 // Normal way to exit.
225 return;
226
227 case kIdent:
228 // Possible events on our queue.
229 break;
230
231 default:
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700232 ALOGE("Unexpected status out of Looper::pollOnce: %d", ret);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700233 }
234
235 // Process an event.
236 ASensorEvent event;
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700237 ssize_t actual = mQueue->read(&event, 1);
238 if (actual > 0) {
239 mQueue->sendAck(&event, actual);
240 }
241 ssize_t size = mQueue->filterEvents(&event, actual);
242
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700243 if (size < 0 || size > 1) {
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700244 ALOGE("Unexpected return value from SensorEventQueue::filterEvents: %zd", size);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700245 break;
246 }
247 if (size == 0) {
248 // No events.
249 continue;
250 }
251
252 handleEvent(event);
253 }
254 }
255
256 void handleEvent(const ASensorEvent& event) {
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800257 PoseEvent value;
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700258 {
259 std::lock_guard lock(mMutex);
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800260 auto iter = mEnabledSensorsExtra.find(event.sensor);
261 if (iter == mEnabledSensorsExtra.end()) {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700262 // This can happen if we have any pending events shortly after stopping.
263 return;
264 }
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800265 value = parseEvent(event, iter->second.format, &iter->second.discontinuityCount);
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700266 }
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700267 mListener->onPose(event.timestamp, event.sensor, value.pose, value.twist,
268 value.isNewReference);
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700269 }
270
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700271 DataFormat getSensorFormat(int32_t handle) {
272 std::optional<const Sensor> sensor = getSensorByHandle(handle);
273 if (!sensor) {
274 ALOGE("Sensor not found: %d", handle);
275 return DataFormat::kUnknown;
276 }
277 if (sensor->getType() == ASENSOR_TYPE_ROTATION_VECTOR ||
278 sensor->getType() == ASENSOR_TYPE_GAME_ROTATION_VECTOR) {
279 return DataFormat::kQuaternion;
280 }
281
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800282 if (sensor->getType() == ASENSOR_TYPE_HEAD_TRACKER) {
283 return DataFormat::kRotationVectorsAndDiscontinuityCount;
284 }
285
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700286 if (sensor->getStringType() == "com.google.hardware.sensor.hid_dynamic.headtracker") {
287 return DataFormat::kRotationVectorsAndFlags;
288 }
289
290 return DataFormat::kUnknown;
291 }
292
293 std::optional<const Sensor> getSensorByHandle(int32_t handle) {
294 const Sensor* const* list;
295 ssize_t size;
296
297 // Search static sensor list.
298 size = mSensorManager->getSensorList(&list);
299 if (size < 0) {
300 ALOGE("getSensorList failed with error code %zd", size);
301 return std::nullopt;
302 }
303 for (size_t i = 0; i < size; ++i) {
304 if (list[i]->getHandle() == handle) {
305 return *list[i];
306 }
307 }
308
309 // Search dynamic sensor list.
310 Vector<Sensor> dynList;
311 size = mSensorManager->getDynamicSensorList(dynList);
312 if (size < 0) {
313 ALOGE("getDynamicSensorList failed with error code %zd", size);
314 return std::nullopt;
315 }
316 for (size_t i = 0; i < size; ++i) {
317 if (dynList[i].getHandle() == handle) {
318 return dynList[i];
319 }
320 }
321
322 return std::nullopt;
323 }
324
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800325 static PoseEvent parseEvent(const ASensorEvent& event, DataFormat format,
326 std::optional<int32_t>* discontinutyCount) {
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700327 switch (format) {
328 case DataFormat::kQuaternion: {
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700329 Eigen::Quaternionf quat(event.data[3], event.data[0], event.data[1], event.data[2]);
Ytai Ben-Tsvi54f07582021-09-13 12:09:42 -0700330 // Adapt to different frame convention.
331 quat *= rotateX(-M_PI_2);
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700332 return PoseEvent{Pose3f(quat), std::optional<Twist3f>(), false};
333 }
334
335 case DataFormat::kRotationVectorsAndFlags: {
336 // Custom sensor, assumed to contain:
337 // 3 floats representing orientation as a rotation vector (in rad).
338 // 3 floats representing angular velocity as a rotation vector (in rad/s).
339 // 1 uint32_t of flags, where:
340 // - LSb is '1' iff the given sample is the first one in a new frame of reference.
341 // - The rest of the bits are reserved for future use.
342 Eigen::Vector3f rotation = {event.data[0], event.data[1], event.data[2]};
343 Eigen::Vector3f twist = {event.data[3], event.data[4], event.data[5]};
344 Eigen::Quaternionf quat = rotationVectorToQuaternion(rotation);
345 uint32_t flags = *reinterpret_cast<const uint32_t*>(&event.data[6]);
346 return PoseEvent{Pose3f(quat), Twist3f(Eigen::Vector3f::Zero(), twist),
347 (flags & (1 << 0)) != 0};
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700348 }
349
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800350 case DataFormat::kRotationVectorsAndDiscontinuityCount: {
351 Eigen::Vector3f rotation = {event.head_tracker.rx, event.head_tracker.ry,
352 event.head_tracker.rz};
353 Eigen::Vector3f twist = {event.head_tracker.vx, event.head_tracker.vy,
Ytai Ben-Tsvi27bbea32022-01-28 18:01:06 -0800354 event.head_tracker.vz};
Ytai Ben-Tsvi87b06212022-01-20 16:52:03 -0800355 Eigen::Quaternionf quat = rotationVectorToQuaternion(rotation);
356 bool isNewReference =
357 !discontinutyCount->has_value() ||
358 discontinutyCount->value() != event.head_tracker.discontinuity_count;
359 *discontinutyCount = event.head_tracker.discontinuity_count;
360
361 return PoseEvent{Pose3f(quat), Twist3f(Eigen::Vector3f::Zero(), twist),
362 isNewReference};
363 }
364
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700365 default:
Ytai Ben-Tsvi2c694be2021-10-06 17:12:49 -0700366 LOG_ALWAYS_FATAL("Unexpected sensor type: %d", static_cast<int>(format));
Ytai Ben-Tsvi779d1ee2021-07-27 05:56:22 -0700367 }
368 }
369};
370
371} // namespace
372
373std::unique_ptr<SensorPoseProvider> SensorPoseProvider::create(const char* packageName,
374 Listener* listener) {
375 return SensorPoseProviderImpl::create(packageName, listener);
376}
377
378} // namespace media
379} // namespace android