blob: c0395a80e16af35f61dde460f773e3fc42638afe [file] [log] [blame]
Eric Laurent6d607012021-07-05 11:54:40 +02001/*
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#ifndef ANDROID_MEDIA_SPATIALIZER_H
18#define ANDROID_MEDIA_SPATIALIZER_H
19
Shunkai Yaoafc0c2e2022-07-22 18:42:27 +000020#include <android-base/stringprintf.h>
Eric Laurent6d607012021-07-05 11:54:40 +020021#include <android/media/BnEffect.h>
22#include <android/media/BnSpatializer.h>
Eric Laurent6d607012021-07-05 11:54:40 +020023#include <android/media/SpatializationLevel.h>
Eric Laurent2be8b292021-08-23 09:44:33 -070024#include <android/media/SpatializationMode.h>
25#include <android/media/SpatializerHeadTrackingMode.h>
Shunkai Yaoafc0c2e2022-07-22 18:42:27 +000026#include <audio_utils/SimpleLog.h>
27#include <math.h>
28#include <media/AudioEffect.h>
Eric Laurent2be8b292021-08-23 09:44:33 -070029#include <media/audiohal/EffectHalInterface.h>
Eric Laurent8a4259f2021-09-14 16:04:00 +020030#include <media/stagefright/foundation/ALooper.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020031#include <system/audio_effects/effect_spatializer.h>
Shunkai Yaoafc0c2e2022-07-22 18:42:27 +000032#include <string>
Eric Laurent6d607012021-07-05 11:54:40 +020033
Eric Laurent2be8b292021-08-23 09:44:33 -070034#include "SpatializerPoseController.h"
Eric Laurent6d607012021-07-05 11:54:40 +020035
36namespace android {
37
38
39// ----------------------------------------------------------------------------
40
41/**
42 * A callback interface from the Spatializer object or its parent AudioPolicyService.
43 * This is implemented by the audio policy service hosting the Spatializer to perform
44 * actions needed when a state change inside the Spatializer requires some audio system
45 * changes that cannot be performed by the Spatializer. For instance opening or closing a
46 * spatializer output stream when the spatializer is enabled or disabled
47 */
48class SpatializerPolicyCallback {
49public:
50 /** Called when a stage change occurs that requires the parent audio policy service to take
51 * some action.
52 */
53 virtual void onCheckSpatializer() = 0;
54
55 virtual ~SpatializerPolicyCallback() = default;
56};
57/**
58 * The Spatializer class implements all functional controlling the multichannel spatializer
59 * with head tracking implementation in the native audio service: audio policy and audio flinger.
60 * It presents an AIDL interface available to the java audio service to discover the availability
61 * of the feature and options, control its state and register an active head tracking sensor.
62 * It maintains the current state of the platform spatializer and applies the stored parameters
63 * when the spatializer engine is created and enabled.
64 * Based on the requested spatializer level, it will request the creation of a specialized output
65 * mixer to the audio policy service which will in turn notify the Spatializer of the output
66 * stream on which a spatializer engine should be created, configured and enabled.
67 * The spatializer also hosts the head tracking management logic. This logic receives the
68 * desired head tracking mode and selected head tracking sensor, registers a sensor event listener
69 * and derives the compounded head pose information to the spatializer engine.
70 *
71 * Workflow:
72 * - Initialization: when the audio policy service starts, it checks if a spatializer effect
73 * engine exists and if the audio policy manager reports a dedicated spatializer output profile.
74 * If both conditions are met, a Spatializer object is created
75 * - Capabilities discovery: AudioService will call AudioSystem::canBeSpatialized() and if true,
76 * acquire an ISpatializer interface with AudioSystem::getSpatializer(). This interface
77 * will be used to query the implementation capabilities and configure the spatializer.
78 * - Enabling: when ISpatializer::setLevel() sets a level different from NONE the spatializer
79 * is considered enabled. The audio policy callback onCheckSpatializer() is called. This
80 * triggers a request to audio policy manager to open a spatialization output stream and a
81 * spatializer mixer is created in audio flinger. When an output is returned by audio policy
82 * manager, Spatializer::attachOutput() is called which creates and enables the spatializer
83 * stage engine on the specified output.
84 * - Disabling: when the spatialization level is set to NONE, the spatializer is considered
85 * disabled. The audio policy callback onCheckSpatializer() is called. This triggers a call
86 * to Spatializer::detachOutput() and the spatializer engine is released. Then a request is
87 * made to audio policy manager to release and close the spatializer output stream and the
88 * spatializer mixer thread is destroyed.
89 */
Eric Laurent2be8b292021-08-23 09:44:33 -070090class Spatializer : public media::BnSpatializer,
Atneya Nair20e6cc82022-05-17 20:12:37 -040091 public AudioEffect::IAudioEffectCallback,
Eric Laurent2be8b292021-08-23 09:44:33 -070092 public IBinder::DeathRecipient,
Eric Laurentee398ad2022-05-03 18:19:35 +020093 private SpatializerPoseController::Listener,
94 public virtual AudioSystem::SupportedLatencyModesCallback {
Eric Laurent2be8b292021-08-23 09:44:33 -070095 public:
Eric Laurent6d607012021-07-05 11:54:40 +020096 static sp<Spatializer> create(SpatializerPolicyCallback *callback);
97
98 ~Spatializer() override;
99
Eric Laurent8a4259f2021-09-14 16:04:00 +0200100 /** RefBase */
101 void onFirstRef();
102
Eric Laurent6d607012021-07-05 11:54:40 +0200103 /** ISpatializer, see ISpatializer.aidl */
104 binder::Status release() override;
105 binder::Status getSupportedLevels(std::vector<media::SpatializationLevel>* levels) override;
106 binder::Status setLevel(media::SpatializationLevel level) override;
107 binder::Status getLevel(media::SpatializationLevel *level) override;
Eric Laurentc87402b2021-09-17 16:49:42 +0200108 binder::Status isHeadTrackingSupported(bool *supports);
Eric Laurent6d607012021-07-05 11:54:40 +0200109 binder::Status getSupportedHeadTrackingModes(
Ytai Ben-Tsvia16a9df2021-08-05 08:57:06 -0700110 std::vector<media::SpatializerHeadTrackingMode>* modes) override;
111 binder::Status setDesiredHeadTrackingMode(
112 media::SpatializerHeadTrackingMode mode) override;
113 binder::Status getActualHeadTrackingMode(
114 media::SpatializerHeadTrackingMode* mode) override;
115 binder::Status recenterHeadTracker() override;
Eric Laurent6d607012021-07-05 11:54:40 +0200116 binder::Status setGlobalTransform(const std::vector<float>& screenToStage) override;
Eric Laurent2be8b292021-08-23 09:44:33 -0700117 binder::Status setHeadSensor(int sensorHandle) override;
118 binder::Status setScreenSensor(int sensorHandle) override;
119 binder::Status setDisplayOrientation(float physicalToLogicalAngle) override;
120 binder::Status setHingeAngle(float hingeAngle) override;
121 binder::Status getSupportedModes(std::vector<media::SpatializationMode>* modes) override;
Eric Laurent67816e32021-09-16 15:18:40 +0200122 binder::Status registerHeadTrackingCallback(
123 const sp<media::ISpatializerHeadTrackingCallback>& callback) override;
Eric Laurentc87402b2021-09-17 16:49:42 +0200124 binder::Status setParameter(int key, const std::vector<unsigned char>& value) override;
125 binder::Status getParameter(int key, std::vector<unsigned char> *value) override;
126 binder::Status getOutput(int *output);
Eric Laurent6d607012021-07-05 11:54:40 +0200127
128 /** IBinder::DeathRecipient. Listen to the death of the INativeSpatializerCallback. */
129 virtual void binderDied(const wp<IBinder>& who);
130
Eric Laurentee398ad2022-05-03 18:19:35 +0200131 /** SupportedLatencyModesCallback */
132 void onSupportedLatencyModesChanged(
133 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) override;
134
Eric Laurent6d607012021-07-05 11:54:40 +0200135 /** Registers a INativeSpatializerCallback when a client is attached to this Spatializer
136 * by audio policy service.
137 */
138 status_t registerCallback(const sp<media::INativeSpatializerCallback>& callback);
139
Eric Laurent2be8b292021-08-23 09:44:33 -0700140 status_t loadEngineConfiguration(sp<EffectHalInterface> effect);
141
Eric Laurent6d607012021-07-05 11:54:40 +0200142 /** Level getter for use by local classes. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700143 media::SpatializationLevel getLevel() const { std::lock_guard lock(mLock); return mLevel; }
Eric Laurent6d607012021-07-05 11:54:40 +0200144
145 /** Called by audio policy service when the special output mixer dedicated to spatialization
146 * is opened and the spatializer engine must be created.
147 */
Eric Laurent15903592022-02-24 20:44:36 +0100148 status_t attachOutput(audio_io_handle_t output, size_t numActiveTracks);
Eric Laurent6d607012021-07-05 11:54:40 +0200149 /** Called by audio policy service when the special output mixer dedicated to spatialization
150 * is closed and the spatializer engine must be release.
151 */
152 audio_io_handle_t detachOutput();
153 /** Returns the output stream the spatializer is attached to. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700154 audio_io_handle_t getOutput() const { std::lock_guard lock(mLock); return mOutput; }
Eric Laurent6d607012021-07-05 11:54:40 +0200155
Eric Laurent15903592022-02-24 20:44:36 +0100156 void updateActiveTracks(size_t numActiveTracks);
157
Eric Laurent6d607012021-07-05 11:54:40 +0200158 /** Gets the channel mask, sampling rate and format set for the spatializer input. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700159 audio_config_base_t getAudioInConfig() const;
Eric Laurent6d607012021-07-05 11:54:40 +0200160
Eric Laurent8a4259f2021-09-14 16:04:00 +0200161 void calculateHeadPose();
162
Shunkai Yaoafc0c2e2022-07-22 18:42:27 +0000163 /** Convert fields in Spatializer and sub-modules to a string. Disable thread-safety-analysis
164 * here because we want to dump mutex guarded members even try_lock failed to provide as much
165 * information as possible for debugging purpose. */
166 std::string toString(unsigned level) const NO_THREAD_SAFETY_ANALYSIS;
167
168 static std::string toString(audio_latency_mode_t mode) {
169 switch (mode) {
170 case AUDIO_LATENCY_MODE_FREE:
171 return "LATENCY_MODE_FREE";
172 case AUDIO_LATENCY_MODE_LOW:
173 return "LATENCY_MODE_LOW";
174 }
175 return "EnumNotImplemented";
176 };
177
178 /**
179 * Format head to stage vector to a string, [0.00, 0.00, 0.00, -1.29, -0.50, 15.27].
180 */
181 template <typename T>
182 static std::string toString(const std::vector<T>& vec, bool radianToDegree = false) {
183 if (vec.size() == 0) {
184 return "[]";
185 }
186
187 std::string ss = "[";
188 for (const auto& f : vec) {
189 if (radianToDegree) {
190 base::StringAppendF(&ss, "%0.2f, ",
191 HeadToStagePoseRecorder::getDegreeWithRadian(f));
192 } else {
193 base::StringAppendF(&ss, "%f, ", f);
194 }
195 }
196 ss.replace(ss.end() - 2, ss.end(), "]");
197 return ss;
198 };
199
Eric Laurent6d607012021-07-05 11:54:40 +0200200private:
Eric Laurent6d607012021-07-05 11:54:40 +0200201 Spatializer(effect_descriptor_t engineDescriptor,
202 SpatializerPolicyCallback *callback);
203
Eric Laurent6d607012021-07-05 11:54:40 +0200204 static void engineCallback(int32_t event, void* user, void *info);
205
Eric Laurent2be8b292021-08-23 09:44:33 -0700206 // From VirtualizerStageController::Listener
207 void onHeadToStagePose(const media::Pose3f& headToStage) override;
208 void onActualModeChange(media::HeadTrackingMode mode) override;
209
Eric Laurent8a4259f2021-09-14 16:04:00 +0200210 void onHeadToStagePoseMsg(const std::vector<float>& headToStage);
211 void onActualModeChangeMsg(media::HeadTrackingMode mode);
Eric Laurent9c04de92022-07-20 13:49:47 +0200212 void onSupportedLatencyModesChangedMsg(
213 audio_io_handle_t output, std::vector<audio_latency_mode_t>&& modes);
Eric Laurent8a4259f2021-09-14 16:04:00 +0200214
Eric Laurent2be8b292021-08-23 09:44:33 -0700215 static constexpr int kMaxEffectParamValues = 10;
216 /**
217 * Get a parameter from spatializer engine by calling the effect HAL command method directly.
218 * To be used when the engine instance mEngine is not yet created in the effect framework.
219 * When MULTI_VALUES is false, the expected reply is only one value of type T.
220 * When MULTI_VALUES is true, the expected reply is made of a number (of type T) indicating
221 * how many values are returned, followed by this number for values of type T.
222 */
223 template<bool MULTI_VALUES, typename T>
224 status_t getHalParameter(sp<EffectHalInterface> effect, uint32_t type,
225 std::vector<T> *values) {
226 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
227
228 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1];
229 uint32_t reply[sizeof(effect_param_t) / sizeof(uint32_t) + 2 + kMaxEffectParamValues];
230
231 effect_param_t *p = (effect_param_t *)cmd;
232 p->psize = sizeof(uint32_t);
233 if (MULTI_VALUES) {
234 p->vsize = (kMaxEffectParamValues + 1) * sizeof(T);
235 } else {
236 p->vsize = sizeof(T);
237 }
238 *(uint32_t *)p->data = type;
239 uint32_t replySize = sizeof(effect_param_t) + p->psize + p->vsize;
240
241 status_t status = effect->command(EFFECT_CMD_GET_PARAM,
242 sizeof(effect_param_t) + sizeof(uint32_t), cmd,
243 &replySize, reply);
244 if (status != NO_ERROR) {
245 return status;
246 }
247 if (p->status != NO_ERROR) {
248 return p->status;
249 }
250 if (replySize <
251 sizeof(effect_param_t) + sizeof(uint32_t) + (MULTI_VALUES ? 2 : 1) * sizeof(T)) {
252 return BAD_VALUE;
253 }
254
255 T *params = (T *)((uint8_t *)reply + sizeof(effect_param_t) + sizeof(uint32_t));
256 int numParams = 1;
257 if (MULTI_VALUES) {
258 numParams = (int)*params++;
259 }
260 if (numParams > kMaxEffectParamValues) {
261 return BAD_VALUE;
262 }
Eric Laurentc87402b2021-09-17 16:49:42 +0200263 (*values).clear();
Eric Laurent2be8b292021-08-23 09:44:33 -0700264 std::copy(&params[0], &params[numParams], back_inserter(*values));
265 return NO_ERROR;
266 }
267
268 /**
269 * Set a parameter to spatializer engine by calling setParameter on mEngine AudioEffect object.
270 * It is possible to pass more than one value of type T according to the parameter type
271 * according to values vector size.
272 */
273 template<typename T>
274 status_t setEffectParameter_l(uint32_t type, const std::vector<T>& values) REQUIRES(mLock) {
275 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
276
277 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values.size()];
278 effect_param_t *p = (effect_param_t *)cmd;
279 p->psize = sizeof(uint32_t);
280 p->vsize = sizeof(T) * values.size();
281 *(uint32_t *)p->data = type;
282 memcpy((uint32_t *)p->data + 1, values.data(), sizeof(T) * values.size());
283
Eric Laurentc87402b2021-09-17 16:49:42 +0200284 status_t status = mEngine->setParameter(p);
285 if (status != NO_ERROR) {
286 return status;
287 }
288 if (p->status != NO_ERROR) {
289 return p->status;
290 }
291 return NO_ERROR;
292 }
293
294 /**
295 * Get a parameter from spatializer engine by calling getParameter on AudioEffect object.
296 * It is possible to read more than one value of type T according to the parameter type
297 * by specifying values vector size.
298 */
299 template<typename T>
300 status_t getEffectParameter_l(uint32_t type, std::vector<T> *values) REQUIRES(mLock) {
301 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
302
303 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values->size()];
304 effect_param_t *p = (effect_param_t *)cmd;
305 p->psize = sizeof(uint32_t);
306 p->vsize = sizeof(T) * values->size();
307 *(uint32_t *)p->data = type;
308
309 status_t status = mEngine->getParameter(p);
310
311 if (status != NO_ERROR) {
312 return status;
313 }
314 if (p->status != NO_ERROR) {
315 return p->status;
316 }
317
318 int numValues = std::min(p->vsize / sizeof(T), values->size());
319 (*values).clear();
320 T *retValues = (T *)((uint8_t *)p->data + sizeof(uint32_t));
321 std::copy(&retValues[0], &retValues[numValues], back_inserter(*values));
322
323 return NO_ERROR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700324 }
325
Atneya Nair20e6cc82022-05-17 20:12:37 -0400326 virtual void onFramesProcessed(int32_t framesProcessed) override;
Eric Laurent8a4259f2021-09-14 16:04:00 +0200327
Eric Laurent9249d342022-03-18 11:55:56 +0100328 /**
329 * Checks if head and screen sensors must be actively monitored based on
330 * spatializer state and playback activity and configures the pose controller
331 * accordingly.
332 */
333 void checkSensorsState_l() REQUIRES(mLock);
Eric Laurent15903592022-02-24 20:44:36 +0100334
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200335 /**
Eric Laurent11094172022-04-05 18:27:42 +0200336 * Checks if the head pose controller should be created or destroyed according
337 * to desired head tracking mode.
338 */
339 void checkPoseController_l() REQUIRES(mLock);
340
341 /**
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200342 * Checks if the spatializer effect should be enabled based on
343 * playback activity and requested level.
344 */
345 void checkEngineState_l() REQUIRES(mLock);
346
Eric Laurent6d607012021-07-05 11:54:40 +0200347 /** Effect engine descriptor */
348 const effect_descriptor_t mEngineDescriptor;
349 /** Callback interface to parent audio policy service */
Andy Hunga461a002022-05-17 10:36:02 -0700350 SpatializerPolicyCallback* const mPolicyCallback;
351
352 /** Currently there is only one version of the spatializer running */
353 const std::string mMetricsId = AMEDIAMETRICS_KEY_PREFIX_AUDIO_SPATIALIZER "0";
Eric Laurent6d607012021-07-05 11:54:40 +0200354
355 /** Mutex protecting internal state */
Eric Laurent2be8b292021-08-23 09:44:33 -0700356 mutable std::mutex mLock;
Eric Laurent6d607012021-07-05 11:54:40 +0200357
358 /** Client AudioEffect for the engine */
359 sp<AudioEffect> mEngine GUARDED_BY(mLock);
360 /** Output stream the spatializer mixer thread is attached to */
361 audio_io_handle_t mOutput GUARDED_BY(mLock) = AUDIO_IO_HANDLE_NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200362
363 /** Callback interface to the client (AudioService) controlling this`Spatializer */
364 sp<media::INativeSpatializerCallback> mSpatializerCallback GUARDED_BY(mLock);
365
Eric Laurent67816e32021-09-16 15:18:40 +0200366 /** Callback interface for head tracking */
367 sp<media::ISpatializerHeadTrackingCallback> mHeadTrackingCallback GUARDED_BY(mLock);
368
Eric Laurent6d607012021-07-05 11:54:40 +0200369 /** Requested spatialization level */
370 media::SpatializationLevel mLevel GUARDED_BY(mLock) = media::SpatializationLevel::NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200371
Eric Laurent2be8b292021-08-23 09:44:33 -0700372 /** Control logic for head-tracking, etc. */
373 std::shared_ptr<SpatializerPoseController> mPoseController GUARDED_BY(mLock);
374
375 /** Last requested head tracking mode */
376 media::HeadTrackingMode mDesiredHeadTrackingMode GUARDED_BY(mLock)
377 = media::HeadTrackingMode::STATIC;
378
379 /** Last-reported actual head-tracking mode. */
380 media::SpatializerHeadTrackingMode mActualHeadTrackingMode GUARDED_BY(mLock)
381 = media::SpatializerHeadTrackingMode::DISABLED;
382
383 /** Selected Head pose sensor */
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700384 int32_t mHeadSensor GUARDED_BY(mLock) = SpatializerPoseController::INVALID_SENSOR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700385
386 /** Selected Screen pose sensor */
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700387 int32_t mScreenSensor GUARDED_BY(mLock) = SpatializerPoseController::INVALID_SENSOR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700388
389 /** Last display orientation received */
390 static constexpr float kDisplayOrientationInvalid = 1000;
391 float mDisplayOrientation GUARDED_BY(mLock) = kDisplayOrientationInvalid;
392
393 std::vector<media::SpatializationLevel> mLevels;
Andy Hunga461a002022-05-17 10:36:02 -0700394 std::vector<media::SpatializerHeadTrackingMode> mHeadTrackingModes;
Eric Laurent2be8b292021-08-23 09:44:33 -0700395 std::vector<media::SpatializationMode> mSpatializationModes;
396 std::vector<audio_channel_mask_t> mChannelMasks;
397 bool mSupportsHeadTracking;
Eric Laurent8a4259f2021-09-14 16:04:00 +0200398
399 // Looper thread for mEngine callbacks
400 class EngineCallbackHandler;
401
402 sp<ALooper> mLooper;
403 sp<EngineCallbackHandler> mHandler;
404
Eric Laurent15903592022-02-24 20:44:36 +0100405 size_t mNumActiveTracks GUARDED_BY(mLock) = 0;
Eric Laurentee398ad2022-05-03 18:19:35 +0200406 std::vector<audio_latency_mode_t> mSupportedLatencyModes GUARDED_BY(mLock);
Eric Laurent15903592022-02-24 20:44:36 +0100407
Shunkai Yaoafc0c2e2022-07-22 18:42:27 +0000408 static const std::vector<const char*> sHeadPoseKeys;
Eric Laurent6d607012021-07-05 11:54:40 +0200409
Shunkai Yaoafc0c2e2022-07-22 18:42:27 +0000410 // Local log for command messages.
411 static constexpr int mMaxLocalLogLine = 10;
412 SimpleLog mLocalLog{mMaxLocalLogLine};
413
414 /**
415 * @brief Calculate and record sensor data.
416 * Dump to local log with max/average pose angle every mPoseRecordThreshold.
417 * TODO: log azimuth/elevation angles obtained for debugging actual orientation.
418 */
419 class HeadToStagePoseRecorder {
420 public:
421 /** Convert recorded sensor data to string with level indentation */
422 std::string toString_l(unsigned level) const;
423 /**
424 * @brief Calculate sensor data, record into local log when it is time.
425 *
426 * @param headToStage The vector from Pose3f::toVector().
427 */
428 void record_l(const std::vector<float>& headToStage);
429
430 static constexpr float getDegreeWithRadian(const float radian) {
431 float radianToDegreeRatio = (180 / PI);
432 return (radian * radianToDegreeRatio);
433 }
434
435 private:
436 static constexpr float PI = M_PI;
437 /**
438 * Pose recorder time threshold to record sensor data in local log.
439 * Sensor data will be recorded at least every mPoseRecordThreshold.
440 */
441 // TODO: add another history log to record longer period of sensor data.
442 static constexpr std::chrono::duration<double> mPoseRecordThreshold =
443 std::chrono::seconds(1);
444 /**
445 * According to frameworks/av/media/libheadtracking/include/media/Pose.h
446 * "The vector will have exactly 6 elements, where the first three are a translation vector
447 * and the last three are a rotation vector."
448 */
449 static constexpr size_t mPoseVectorSize = 6;
450 /**
451 * Timestamp of last sensor data record in local log.
452 */
453 std::chrono::time_point<std::chrono::steady_clock> mFirstSampleTimestamp;
454 // Last pose recorded, vector obtained from Pose3f::toVector().
455 std::vector<float> mLastPoseRecorded{mPoseVectorSize};
456 /**
457 * Number of sensor samples received since last record, sample rate is ~100Hz which produce
458 * ~6k samples/minute.
459 */
460 uint32_t mNumOfSampleSinceLastRecord = 0;
461 /* The sum of pose angle represented by radian since last dump, div
462 * mNumOfSampleSinceLastRecord to get arithmetic mean. Largest possible value: 2PI * 100Hz *
463 * mPoseRecordThreshold.
464 */
465 std::vector<double> mPoseRadianSum{mPoseVectorSize};
466 std::vector<float> mMaxPoseAngle{mPoseVectorSize};
467 std::vector<float> mMinPoseAngle{mPoseVectorSize};
468 // Local log for history sensor data.
469 SimpleLog mPoseRecordLog{mMaxLocalLogLine};
470
471 bool shouldRecordLog() const {
472 return std::chrono::duration_cast<std::chrono::seconds>(
473 std::chrono::steady_clock::now() - mFirstSampleTimestamp) >=
474 mPoseRecordThreshold;
475 }
476
477 void resetRecord(const std::vector<float>& headToStage) {
478 mPoseRadianSum.assign(mPoseVectorSize, 0);
479 mMaxPoseAngle.assign(mPoseVectorSize, 0);
480 mMinPoseAngle.assign(mPoseVectorSize, 0);
481 mNumOfSampleSinceLastRecord = 0;
482 mLastPoseRecorded = headToStage;
483 }
484
485 // Add each sample to sum and only calculate when record.
486 void poseSumToAverage() {
487 if (mNumOfSampleSinceLastRecord == 0) return;
488 for (auto& p : mPoseRadianSum) {
489 const float reciprocal = 1.f / mNumOfSampleSinceLastRecord;
490 p *= reciprocal;
491 }
492 }
493 }; // HeadToStagePoseRecorder
494 HeadToStagePoseRecorder mPoseRecorder;
495}; // Spatializer
Eric Laurent6d607012021-07-05 11:54:40 +0200496
497}; // namespace android
498
499#endif // ANDROID_MEDIA_SPATIALIZER_H