• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 <algorithm>
22 #include <future>
23 #include <inttypes.h>
24 #include <limits>
25 #include <map>
26 #include <thread>
27 
28 #include <android-base/stringprintf.h>
29 #include <android-base/thread_annotations.h>
30 #include <log/log_main.h>
31 #include <sensor/SensorEventQueue.h>
32 #include <sensor/SensorManager.h>
33 #include <utils/Looper.h>
34 
35 #include "media/QuaternionUtil.h"
36 
37 namespace android {
38 namespace media {
39 namespace {
40 
41 using android::base::StringAppendF;
42 
43 // Identifier to use for our event queue on the loop.
44 // The number 19 is arbitrary, only useful if using multiple objects on the same looper.
45 // Note: Instead of a fixed number, the SensorEventQueue's fd could be used instead.
46 constexpr int kIdent = 19;
47 
ALooper_to_Looper(ALooper * alooper)48 static inline Looper* ALooper_to_Looper(ALooper* alooper) {
49     return reinterpret_cast<Looper*>(alooper);
50 }
51 
Looper_to_ALooper(Looper * looper)52 static inline ALooper* Looper_to_ALooper(Looper* looper) {
53     return reinterpret_cast<ALooper*>(looper);
54 }
55 
56 /**
57  * RAII-wrapper around SensorEventQueue, which unregisters it on destruction.
58  */
59 class EventQueueGuard {
60   public:
EventQueueGuard(const sp<SensorEventQueue> & queue,Looper * looper)61     EventQueueGuard(const sp<SensorEventQueue>& queue, Looper* looper) : mQueue(queue) {
62         mQueue->looper = Looper_to_ALooper(looper);
63         mQueue->requestAdditionalInfo = false;
64         looper->addFd(mQueue->getFd(), kIdent, ALOOPER_EVENT_INPUT,
65                 nullptr /* callback */, nullptr /* data */);
66     }
67 
~EventQueueGuard()68     ~EventQueueGuard() {
69         if (mQueue) {
70             ALooper_to_Looper(mQueue->looper)->removeFd(mQueue->getFd());
71         }
72     }
73 
74     EventQueueGuard(const EventQueueGuard&) = delete;
75     EventQueueGuard& operator=(const EventQueueGuard&) = delete;
76 
get() const77     [[nodiscard]] SensorEventQueue* get() const { return mQueue.get(); }
78 
79   private:
80     const sp<SensorEventQueue> mQueue;
81 };
82 
83 /**
84  * RAII-wrapper around an enabled sensor, which disables it upon destruction.
85  */
86 class SensorEnableGuard {
87   public:
SensorEnableGuard(const sp<SensorEventQueue> & queue,int32_t sensor)88     SensorEnableGuard(const sp<SensorEventQueue>& queue, int32_t sensor)
89         : mQueue(queue), mSensor(sensor) {}
90 
~SensorEnableGuard()91     ~SensorEnableGuard() {
92         if (mSensor != SensorPoseProvider::INVALID_HANDLE) {
93             int ret = mQueue->disableSensor(mSensor);
94             if (ret) {
95                 ALOGE("Failed to disable sensor: %s", strerror(ret));
96             }
97         }
98     }
99 
100     // Enable move and delete default copy-ctor/copy-assignment.
SensorEnableGuard(SensorEnableGuard && other)101     SensorEnableGuard(SensorEnableGuard&& other) : mQueue(other.mQueue), mSensor(other.mSensor) {
102         other.mSensor = SensorPoseProvider::INVALID_HANDLE;
103     }
104 
105   private:
106     sp<SensorEventQueue> const mQueue;
107     int32_t mSensor;
108 };
109 
110 /**
111  * Streams the required events to a PoseListener, based on events originating from the Sensor stack.
112  */
113 class SensorPoseProviderImpl : public SensorPoseProvider {
114   public:
create(const char * packageName,Listener * listener)115     static std::unique_ptr<SensorPoseProvider> create(const char* packageName, Listener* listener) {
116         std::unique_ptr<SensorPoseProviderImpl> result(
117                 new SensorPoseProviderImpl(packageName, listener));
118         return result->waitInitFinished() ? std::move(result) : nullptr;
119     }
120 
~SensorPoseProviderImpl()121     ~SensorPoseProviderImpl() override {
122         // Disable all active sensors.
123         mEnabledSensors.clear();
124         mQuit = true;
125         mLooper->wake();
126         mThread.join();
127     }
128 
startSensor(int32_t sensor,std::chrono::microseconds samplingPeriod)129     bool startSensor(int32_t sensor, std::chrono::microseconds samplingPeriod) override {
130         // Figure out the sensor's data format.
131         DataFormat format = getSensorFormat(sensor);
132         if (format == DataFormat::kUnknown) {
133             ALOGE("%s: Unknown format for sensor %" PRId32, __func__, sensor);
134             return false;
135         }
136 
137         {
138             std::lock_guard lock(mMutex);
139             mEnabledSensorsExtra.emplace(
140                     sensor,
141                     SensorExtra{.format = format,
142                                 .samplingPeriod = static_cast<int32_t>(samplingPeriod.count())});
143         }
144 
145         // Enable the sensor.
146         if (mQueue->enableSensor(sensor, samplingPeriod.count(), 0, 0)) {
147             ALOGE("%s: Failed to enable sensor %" PRId32, __func__, sensor);
148             std::lock_guard lock(mMutex);
149             mEnabledSensorsExtra.erase(sensor);
150             return false;
151         }
152 
153         mEnabledSensors.emplace(sensor, SensorEnableGuard(mQueue, sensor));
154         ALOGD("%s: Sensor %" PRId32 " started", __func__, sensor);
155         return true;
156     }
157 
stopSensor(int handle)158     void stopSensor(int handle) override {
159         ALOGD("%s: Sensor %" PRId32 " stopped", __func__, handle);
160         mEnabledSensors.erase(handle);
161         std::lock_guard lock(mMutex);
162         mEnabledSensorsExtra.erase(handle);
163     }
164 
toString(unsigned level)165     std::string toString(unsigned level) override {
166         std::string prefixSpace(level, ' ');
167         std::string ss = prefixSpace + "SensorPoseProvider:\n";
168         bool needUnlock = false;
169 
170         prefixSpace += " ";
171         auto now = std::chrono::steady_clock::now();
172         if (!mMutex.try_lock_until(now + media::kSpatializerDumpSysTimeOutInSecond)) {
173             ss.append(prefixSpace).append("try_lock failed, dumpsys below maybe INACCURATE!\n");
174         } else {
175             needUnlock = true;
176         }
177 
178         // Enabled sensor information
179         StringAppendF(&ss, "%sSensors total number %zu:\n", prefixSpace.c_str(),
180                       mEnabledSensorsExtra.size());
181         for (auto sensor : mEnabledSensorsExtra) {
182             StringAppendF(&ss,
183                           "%s[Handle: 0x%08x, Format %s Period (set %d max %0.4f min %0.4f) ms",
184                           prefixSpace.c_str(), sensor.first, toString(sensor.second.format).c_str(),
185                           sensor.second.samplingPeriod, media::nsToFloatMs(sensor.second.maxPeriod),
186                           media::nsToFloatMs(sensor.second.minPeriod));
187             if (sensor.second.discontinuityCount.has_value()) {
188                 StringAppendF(&ss, ", DiscontinuityCount: %d",
189                               sensor.second.discontinuityCount.value());
190             }
191             ss += "]\n";
192         }
193 
194         if (needUnlock) {
195             mMutex.unlock();
196         }
197         return ss;
198     }
199 
200   private:
201     enum DataFormat {
202         kUnknown,
203         kQuaternion,
204         kRotationVectorsAndDiscontinuityCount,
205     };
206 
207     struct PoseEvent {
208         Pose3f pose;
209         std::optional<Twist3f> twist;
210         bool isNewReference;
211     };
212 
213     struct SensorExtra {
214         DataFormat format = DataFormat::kUnknown;
215         int32_t samplingPeriod = 0;
216         int64_t latestTimestamp = 0;
217         int64_t maxPeriod = 0;
218         int64_t minPeriod = std::numeric_limits<int64_t>::max();
219         std::optional<int32_t> discontinuityCount;
220     };
221 
222     bool mQuit = false;
223     sp<Looper> mLooper;
224     Listener* const mListener;
225     SensorManager* const mSensorManager;
226     std::timed_mutex mMutex;
227     sp<SensorEventQueue> mQueue;
228     std::map<int32_t, SensorEnableGuard> mEnabledSensors;
229     std::map<int32_t, SensorExtra> mEnabledSensorsExtra GUARDED_BY(mMutex);
230 
231     // We must do some of the initialization operations on the worker thread, because the API relies
232     // on the thread-local looper. In addition, as a matter of convenience, we store some of the
233     // state on the stack.
234     // For that reason, we use a two-step initialization approach, where the ctor mostly just starts
235     // the worker thread and that thread would notify, via the promise below whenever initialization
236     // is finished, and whether it was successful.
237     std::promise<bool> mInitPromise;
238     std::thread mThread;
239 
SensorPoseProviderImpl(const char * packageName,Listener * listener)240     SensorPoseProviderImpl(const char* packageName, Listener* listener)
241         : mListener(listener),
242           mSensorManager(&SensorManager::getInstanceForPackage(String16(packageName))) {
243         mThread = std::thread([this] { threadFunc(); });
244     }
initFinished(bool success)245     void initFinished(bool success) { mInitPromise.set_value(success); }
246 
waitInitFinished()247     bool waitInitFinished() { return mInitPromise.get_future().get(); }
248 
threadFunc()249     void threadFunc() {
250         // Name our std::thread to help identification.  As is, canCallJava == false.
251         androidSetThreadName("SensorPoseProvider-looper");
252 
253         // Run at the highest non-realtime priority.
254         androidSetThreadPriority(gettid(), PRIORITY_URGENT_AUDIO);
255 
256         // The looper is started on the created std::thread.
257         mLooper = Looper::prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
258 
259         // Create event queue.
260         mQueue = mSensorManager->createEventQueue();
261 
262         if (mQueue == nullptr) {
263             ALOGE("Failed to create a sensor event queue");
264             initFinished(false);
265             return;
266         }
267 
268         EventQueueGuard eventQueueGuard(mQueue, mLooper.get());
269 
270         initFinished(true);
271 
272         while (!mQuit) {
273             const int ret = mLooper->pollOnce(-1 /* no timeout */, nullptr /* outFd */,
274                     nullptr /* outEvents */, nullptr /* outData */);
275 
276             switch (ret) {
277                 case ALOOPER_POLL_WAKE:
278                     // Continue to see if mQuit flag is set.
279                     // This can be spurious (due to bugreport being taken).
280                     continue;
281 
282                 case kIdent:
283                     // Possible events on our queue.
284                     break;
285 
286                 default:
287                     // Besides WAKE and kIdent, there should be no timeouts, callbacks,
288                     // ALOOPER_POLL_ERROR, or other events.
289                     // Exit now to avoid high frequency log spam on error,
290                     // e.g. if the fd becomes invalid (b/31093485).
291                     ALOGE("%s: Unexpected status out of Looper::pollOnce: %d", __func__, ret);
292                     mQuit = true;
293                     continue;
294             }
295 
296             // Process an event.
297             ASensorEvent event;
298             ssize_t actual = mQueue->read(&event, 1);
299             if (actual > 0) {
300                 mQueue->sendAck(&event, actual);
301             }
302             ssize_t size = mQueue->filterEvents(&event, actual);
303 
304             if (size < 0 || size > 1) {
305                 ALOGE("%s: Unexpected return value from SensorEventQueue::filterEvents: %zd",
306                         __func__, size);
307                 break;
308             }
309             if (size == 0) {
310                 // No events.
311                 continue;
312             }
313 
314             handleEvent(event);
315         }
316         ALOGD("%s: Exiting sensor event loop", __func__);
317     }
318 
handleEvent(const ASensorEvent & event)319     void handleEvent(const ASensorEvent& event) {
320         PoseEvent value;
321         {
322             std::lock_guard lock(mMutex);
323             auto iter = mEnabledSensorsExtra.find(event.sensor);
324             if (iter == mEnabledSensorsExtra.end()) {
325                 // This can happen if we have any pending events shortly after stopping.
326                 return;
327             }
328             value = parseEvent(event, iter->second.format, &iter->second.discontinuityCount);
329             updateEventTimestamp(event, iter->second);
330         }
331         mListener->onPose(event.timestamp, event.sensor, value.pose, value.twist,
332                           value.isNewReference);
333     }
334 
getSensorFormat(int32_t handle)335     DataFormat getSensorFormat(int32_t handle) {
336         std::optional<const Sensor> sensor = getSensorByHandle(handle);
337         if (!sensor) {
338             ALOGE("Sensor not found: %d", handle);
339             return DataFormat::kUnknown;
340         }
341         if (sensor->getType() == ASENSOR_TYPE_ROTATION_VECTOR ||
342             sensor->getType() == ASENSOR_TYPE_GAME_ROTATION_VECTOR) {
343             return DataFormat::kQuaternion;
344         }
345 
346         if (sensor->getType() == ASENSOR_TYPE_HEAD_TRACKER) {
347             return DataFormat::kRotationVectorsAndDiscontinuityCount;
348         }
349 
350         return DataFormat::kUnknown;
351     }
352 
getSensorByHandle(int32_t handle)353     std::optional<const Sensor> getSensorByHandle(int32_t handle) override {
354         const Sensor* const* list;
355         ssize_t size;
356 
357         // Search static sensor list.
358         size = mSensorManager->getSensorList(&list);
359         if (size < 0) {
360             ALOGE("getSensorList failed with error code %zd", size);
361             return std::nullopt;
362         }
363         for (size_t i = 0; i < size; ++i) {
364             if (list[i]->getHandle() == handle) {
365                 return *list[i];
366             }
367         }
368 
369         // Search dynamic sensor list.
370         Vector<Sensor> dynList;
371         size = mSensorManager->getDynamicSensorList(dynList);
372         if (size < 0) {
373             ALOGE("getDynamicSensorList failed with error code %zd", size);
374             return std::nullopt;
375         }
376         for (size_t i = 0; i < size; ++i) {
377             if (dynList[i].getHandle() == handle) {
378                 return dynList[i];
379             }
380         }
381 
382         return std::nullopt;
383     }
384 
updateEventTimestamp(const ASensorEvent & event,SensorExtra & extra)385     void updateEventTimestamp(const ASensorEvent& event, SensorExtra& extra) {
386         if (extra.latestTimestamp != 0) {
387             int64_t gap = event.timestamp - extra.latestTimestamp;
388             extra.maxPeriod = std::max(gap, extra.maxPeriod);
389             extra.minPeriod = std::min(gap, extra.minPeriod);
390         }
391         extra.latestTimestamp = event.timestamp;
392     }
393 
parseEvent(const ASensorEvent & event,DataFormat format,std::optional<int32_t> * discontinutyCount)394     static PoseEvent parseEvent(const ASensorEvent& event, DataFormat format,
395                                 std::optional<int32_t>* discontinutyCount) {
396         switch (format) {
397             case DataFormat::kQuaternion: {
398                 Eigen::Quaternionf quat(event.data[3], event.data[0], event.data[1], event.data[2]);
399                 // Adapt to different frame convention.
400                 quat *= rotateX(-M_PI_2);
401                 return PoseEvent{Pose3f(quat), std::optional<Twist3f>(), false};
402             }
403 
404             case DataFormat::kRotationVectorsAndDiscontinuityCount: {
405                 Eigen::Vector3f rotation = {event.head_tracker.rx, event.head_tracker.ry,
406                                             event.head_tracker.rz};
407                 Eigen::Vector3f twist = {event.head_tracker.vx, event.head_tracker.vy,
408                                          event.head_tracker.vz};
409                 Eigen::Quaternionf quat = rotationVectorToQuaternion(rotation);
410                 bool isNewReference =
411                         !discontinutyCount->has_value() ||
412                         discontinutyCount->value() != event.head_tracker.discontinuity_count;
413                 *discontinutyCount = event.head_tracker.discontinuity_count;
414 
415                 return PoseEvent{Pose3f(quat), Twist3f(Eigen::Vector3f::Zero(), twist),
416                                  isNewReference};
417             }
418 
419             default:
420                 LOG_ALWAYS_FATAL("Unexpected sensor type: %d", static_cast<int>(format));
421         }
422     }
423 
toString(DataFormat format)424     const static std::string toString(DataFormat format) {
425         switch (format) {
426             case DataFormat::kUnknown:
427                 return "kUnknown";
428             case DataFormat::kQuaternion:
429                 return "kQuaternion";
430             case DataFormat::kRotationVectorsAndDiscontinuityCount:
431                 return "kRotationVectorsAndDiscontinuityCount";
432             default:
433                 return "NotImplemented";
434         }
435     }
436 };
437 
438 }  // namespace
439 
create(const char * packageName,Listener * listener)440 std::unique_ptr<SensorPoseProvider> SensorPoseProvider::create(const char* packageName,
441                                                                Listener* listener) {
442     return SensorPoseProviderImpl::create(packageName, listener);
443 }
444 
445 }  // namespace media
446 }  // namespace android
447