blob: c9071d44958c06257c660be0fbc9f09750878897 [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 Yao59b27bc2022-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 Yao59b27bc2022-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 Yao59b27bc2022-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,
91 public IBinder::DeathRecipient,
Eric Laurentee398ad2022-05-03 18:19:35 +020092 private SpatializerPoseController::Listener,
93 public virtual AudioSystem::SupportedLatencyModesCallback {
Eric Laurent2be8b292021-08-23 09:44:33 -070094 public:
Eric Laurent6d607012021-07-05 11:54:40 +020095 static sp<Spatializer> create(SpatializerPolicyCallback *callback);
96
97 ~Spatializer() override;
98
Eric Laurent8a4259f2021-09-14 16:04:00 +020099 /** RefBase */
100 void onFirstRef();
101
Eric Laurent6d607012021-07-05 11:54:40 +0200102 /** ISpatializer, see ISpatializer.aidl */
103 binder::Status release() override;
104 binder::Status getSupportedLevels(std::vector<media::SpatializationLevel>* levels) override;
105 binder::Status setLevel(media::SpatializationLevel level) override;
106 binder::Status getLevel(media::SpatializationLevel *level) override;
Eric Laurentc87402b2021-09-17 16:49:42 +0200107 binder::Status isHeadTrackingSupported(bool *supports);
Eric Laurent6d607012021-07-05 11:54:40 +0200108 binder::Status getSupportedHeadTrackingModes(
Ytai Ben-Tsvia16a9df2021-08-05 08:57:06 -0700109 std::vector<media::SpatializerHeadTrackingMode>* modes) override;
110 binder::Status setDesiredHeadTrackingMode(
111 media::SpatializerHeadTrackingMode mode) override;
112 binder::Status getActualHeadTrackingMode(
113 media::SpatializerHeadTrackingMode* mode) override;
114 binder::Status recenterHeadTracker() override;
Eric Laurent6d607012021-07-05 11:54:40 +0200115 binder::Status setGlobalTransform(const std::vector<float>& screenToStage) override;
Eric Laurent2be8b292021-08-23 09:44:33 -0700116 binder::Status setHeadSensor(int sensorHandle) override;
117 binder::Status setScreenSensor(int sensorHandle) override;
118 binder::Status setDisplayOrientation(float physicalToLogicalAngle) override;
119 binder::Status setHingeAngle(float hingeAngle) override;
120 binder::Status getSupportedModes(std::vector<media::SpatializationMode>* modes) override;
Eric Laurent67816e32021-09-16 15:18:40 +0200121 binder::Status registerHeadTrackingCallback(
122 const sp<media::ISpatializerHeadTrackingCallback>& callback) override;
Eric Laurentc87402b2021-09-17 16:49:42 +0200123 binder::Status setParameter(int key, const std::vector<unsigned char>& value) override;
124 binder::Status getParameter(int key, std::vector<unsigned char> *value) override;
125 binder::Status getOutput(int *output);
Eric Laurent6d607012021-07-05 11:54:40 +0200126
127 /** IBinder::DeathRecipient. Listen to the death of the INativeSpatializerCallback. */
128 virtual void binderDied(const wp<IBinder>& who);
129
Eric Laurentee398ad2022-05-03 18:19:35 +0200130 /** SupportedLatencyModesCallback */
131 void onSupportedLatencyModesChanged(
132 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) override;
133
Eric Laurent6d607012021-07-05 11:54:40 +0200134 /** Registers a INativeSpatializerCallback when a client is attached to this Spatializer
135 * by audio policy service.
136 */
137 status_t registerCallback(const sp<media::INativeSpatializerCallback>& callback);
138
Eric Laurent2be8b292021-08-23 09:44:33 -0700139 status_t loadEngineConfiguration(sp<EffectHalInterface> effect);
140
Eric Laurent6d607012021-07-05 11:54:40 +0200141 /** Level getter for use by local classes. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700142 media::SpatializationLevel getLevel() const { std::lock_guard lock(mLock); return mLevel; }
Eric Laurent6d607012021-07-05 11:54:40 +0200143
144 /** Called by audio policy service when the special output mixer dedicated to spatialization
145 * is opened and the spatializer engine must be created.
146 */
Eric Laurent15903592022-02-24 20:44:36 +0100147 status_t attachOutput(audio_io_handle_t output, size_t numActiveTracks);
Eric Laurent6d607012021-07-05 11:54:40 +0200148 /** Called by audio policy service when the special output mixer dedicated to spatialization
149 * is closed and the spatializer engine must be release.
150 */
151 audio_io_handle_t detachOutput();
152 /** Returns the output stream the spatializer is attached to. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700153 audio_io_handle_t getOutput() const { std::lock_guard lock(mLock); return mOutput; }
Eric Laurent6d607012021-07-05 11:54:40 +0200154
Eric Laurent15903592022-02-24 20:44:36 +0100155 void updateActiveTracks(size_t numActiveTracks);
156
Eric Laurent6d607012021-07-05 11:54:40 +0200157 /** Gets the channel mask, sampling rate and format set for the spatializer input. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700158 audio_config_base_t getAudioInConfig() const;
Eric Laurent6d607012021-07-05 11:54:40 +0200159
Eric Laurent8a4259f2021-09-14 16:04:00 +0200160 void calculateHeadPose();
161
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000162 /** Convert fields in Spatializer and sub-modules to a string. Disable thread-safety-analysis
163 * here because we want to dump mutex guarded members even try_lock failed to provide as much
164 * information as possible for debugging purpose. */
165 std::string toString(unsigned level) const NO_THREAD_SAFETY_ANALYSIS;
166
167 static std::string toString(audio_latency_mode_t mode) {
168 switch (mode) {
169 case AUDIO_LATENCY_MODE_FREE:
170 return "LATENCY_MODE_FREE";
171 case AUDIO_LATENCY_MODE_LOW:
172 return "LATENCY_MODE_LOW";
173 }
174 return "EnumNotImplemented";
175 };
176
177 /**
178 * Format head to stage vector to a string, [0.00, 0.00, 0.00, -1.29, -0.50, 15.27].
179 */
180 template <typename T>
181 static std::string toString(const std::vector<T>& vec, bool radianToDegree = false) {
182 if (vec.size() == 0) {
183 return "[]";
184 }
185
186 std::string ss = "[";
Shunkai Yao20e23732022-08-25 00:44:04 +0000187 for (auto f = vec.begin(); f != vec.end(); ++f) {
188 if (f != vec.begin()) {
189 ss .append(", ");
190 }
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000191 if (radianToDegree) {
Shunkai Yao20e23732022-08-25 00:44:04 +0000192 base::StringAppendF(&ss, "%0.2f", HeadToStagePoseRecorder::getDegreeWithRadian(*f));
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000193 } else {
Shunkai Yao20e23732022-08-25 00:44:04 +0000194 base::StringAppendF(&ss, "%f", *f);
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000195 }
196 }
Shunkai Yao20e23732022-08-25 00:44:04 +0000197 ss.append("]");
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000198 return ss;
199 };
200
Eric Laurent6d607012021-07-05 11:54:40 +0200201private:
Eric Laurent6d607012021-07-05 11:54:40 +0200202 Spatializer(effect_descriptor_t engineDescriptor,
203 SpatializerPolicyCallback *callback);
204
Eric Laurent6d607012021-07-05 11:54:40 +0200205 static void engineCallback(int32_t event, void* user, void *info);
206
Eric Laurent2be8b292021-08-23 09:44:33 -0700207 // From VirtualizerStageController::Listener
208 void onHeadToStagePose(const media::Pose3f& headToStage) override;
209 void onActualModeChange(media::HeadTrackingMode mode) override;
210
Eric Laurent8a4259f2021-09-14 16:04:00 +0200211 void onHeadToStagePoseMsg(const std::vector<float>& headToStage);
212 void onActualModeChangeMsg(media::HeadTrackingMode mode);
Eric Laurent9c04de92022-07-20 13:49:47 +0200213 void onSupportedLatencyModesChangedMsg(
214 audio_io_handle_t output, std::vector<audio_latency_mode_t>&& modes);
Eric Laurent8a4259f2021-09-14 16:04:00 +0200215
Eric Laurent2be8b292021-08-23 09:44:33 -0700216 static constexpr int kMaxEffectParamValues = 10;
217 /**
218 * Get a parameter from spatializer engine by calling the effect HAL command method directly.
219 * To be used when the engine instance mEngine is not yet created in the effect framework.
220 * When MULTI_VALUES is false, the expected reply is only one value of type T.
221 * When MULTI_VALUES is true, the expected reply is made of a number (of type T) indicating
222 * how many values are returned, followed by this number for values of type T.
223 */
224 template<bool MULTI_VALUES, typename T>
225 status_t getHalParameter(sp<EffectHalInterface> effect, uint32_t type,
226 std::vector<T> *values) {
227 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
228
229 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1];
230 uint32_t reply[sizeof(effect_param_t) / sizeof(uint32_t) + 2 + kMaxEffectParamValues];
231
232 effect_param_t *p = (effect_param_t *)cmd;
233 p->psize = sizeof(uint32_t);
234 if (MULTI_VALUES) {
235 p->vsize = (kMaxEffectParamValues + 1) * sizeof(T);
236 } else {
237 p->vsize = sizeof(T);
238 }
239 *(uint32_t *)p->data = type;
240 uint32_t replySize = sizeof(effect_param_t) + p->psize + p->vsize;
241
242 status_t status = effect->command(EFFECT_CMD_GET_PARAM,
243 sizeof(effect_param_t) + sizeof(uint32_t), cmd,
244 &replySize, reply);
245 if (status != NO_ERROR) {
246 return status;
247 }
248 if (p->status != NO_ERROR) {
249 return p->status;
250 }
251 if (replySize <
252 sizeof(effect_param_t) + sizeof(uint32_t) + (MULTI_VALUES ? 2 : 1) * sizeof(T)) {
253 return BAD_VALUE;
254 }
255
256 T *params = (T *)((uint8_t *)reply + sizeof(effect_param_t) + sizeof(uint32_t));
257 int numParams = 1;
258 if (MULTI_VALUES) {
259 numParams = (int)*params++;
260 }
261 if (numParams > kMaxEffectParamValues) {
262 return BAD_VALUE;
263 }
Eric Laurentc87402b2021-09-17 16:49:42 +0200264 (*values).clear();
Eric Laurent2be8b292021-08-23 09:44:33 -0700265 std::copy(&params[0], &params[numParams], back_inserter(*values));
266 return NO_ERROR;
267 }
268
269 /**
270 * Set a parameter to spatializer engine by calling setParameter on mEngine AudioEffect object.
271 * It is possible to pass more than one value of type T according to the parameter type
272 * according to values vector size.
273 */
274 template<typename T>
275 status_t setEffectParameter_l(uint32_t type, const std::vector<T>& values) REQUIRES(mLock) {
276 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
277
278 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values.size()];
279 effect_param_t *p = (effect_param_t *)cmd;
280 p->psize = sizeof(uint32_t);
281 p->vsize = sizeof(T) * values.size();
282 *(uint32_t *)p->data = type;
283 memcpy((uint32_t *)p->data + 1, values.data(), sizeof(T) * values.size());
284
Eric Laurentc87402b2021-09-17 16:49:42 +0200285 status_t status = mEngine->setParameter(p);
286 if (status != NO_ERROR) {
287 return status;
288 }
289 if (p->status != NO_ERROR) {
290 return p->status;
291 }
292 return NO_ERROR;
293 }
294
295 /**
296 * Get a parameter from spatializer engine by calling getParameter on AudioEffect object.
297 * It is possible to read more than one value of type T according to the parameter type
298 * by specifying values vector size.
299 */
300 template<typename T>
301 status_t getEffectParameter_l(uint32_t type, std::vector<T> *values) REQUIRES(mLock) {
302 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
303
304 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values->size()];
305 effect_param_t *p = (effect_param_t *)cmd;
306 p->psize = sizeof(uint32_t);
307 p->vsize = sizeof(T) * values->size();
308 *(uint32_t *)p->data = type;
309
310 status_t status = mEngine->getParameter(p);
311
312 if (status != NO_ERROR) {
313 return status;
314 }
315 if (p->status != NO_ERROR) {
316 return p->status;
317 }
318
319 int numValues = std::min(p->vsize / sizeof(T), values->size());
320 (*values).clear();
321 T *retValues = (T *)((uint8_t *)p->data + sizeof(uint32_t));
322 std::copy(&retValues[0], &retValues[numValues], back_inserter(*values));
323
324 return NO_ERROR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700325 }
326
Eric Laurent8a4259f2021-09-14 16:04:00 +0200327 void postFramesProcessedMsg(int frames);
328
Eric Laurent9249d342022-03-18 11:55:56 +0100329 /**
330 * Checks if head and screen sensors must be actively monitored based on
331 * spatializer state and playback activity and configures the pose controller
332 * accordingly.
333 */
334 void checkSensorsState_l() REQUIRES(mLock);
Eric Laurent15903592022-02-24 20:44:36 +0100335
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200336 /**
Eric Laurent11094172022-04-05 18:27:42 +0200337 * Checks if the head pose controller should be created or destroyed according
338 * to desired head tracking mode.
339 */
340 void checkPoseController_l() REQUIRES(mLock);
341
342 /**
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200343 * Checks if the spatializer effect should be enabled based on
344 * playback activity and requested level.
345 */
346 void checkEngineState_l() REQUIRES(mLock);
347
Eric Laurent6d607012021-07-05 11:54:40 +0200348 /** Effect engine descriptor */
349 const effect_descriptor_t mEngineDescriptor;
350 /** Callback interface to parent audio policy service */
Andy Hunga461a002022-05-17 10:36:02 -0700351 SpatializerPolicyCallback* const mPolicyCallback;
352
353 /** Currently there is only one version of the spatializer running */
354 const std::string mMetricsId = AMEDIAMETRICS_KEY_PREFIX_AUDIO_SPATIALIZER "0";
Eric Laurent6d607012021-07-05 11:54:40 +0200355
356 /** Mutex protecting internal state */
Eric Laurent2be8b292021-08-23 09:44:33 -0700357 mutable std::mutex mLock;
Eric Laurent6d607012021-07-05 11:54:40 +0200358
359 /** Client AudioEffect for the engine */
360 sp<AudioEffect> mEngine GUARDED_BY(mLock);
361 /** Output stream the spatializer mixer thread is attached to */
362 audio_io_handle_t mOutput GUARDED_BY(mLock) = AUDIO_IO_HANDLE_NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200363
364 /** Callback interface to the client (AudioService) controlling this`Spatializer */
365 sp<media::INativeSpatializerCallback> mSpatializerCallback GUARDED_BY(mLock);
366
Eric Laurent67816e32021-09-16 15:18:40 +0200367 /** Callback interface for head tracking */
368 sp<media::ISpatializerHeadTrackingCallback> mHeadTrackingCallback GUARDED_BY(mLock);
369
Eric Laurent6d607012021-07-05 11:54:40 +0200370 /** Requested spatialization level */
371 media::SpatializationLevel mLevel GUARDED_BY(mLock) = media::SpatializationLevel::NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200372
Eric Laurent2be8b292021-08-23 09:44:33 -0700373 /** Control logic for head-tracking, etc. */
374 std::shared_ptr<SpatializerPoseController> mPoseController GUARDED_BY(mLock);
375
376 /** Last requested head tracking mode */
377 media::HeadTrackingMode mDesiredHeadTrackingMode GUARDED_BY(mLock)
378 = media::HeadTrackingMode::STATIC;
379
380 /** Last-reported actual head-tracking mode. */
381 media::SpatializerHeadTrackingMode mActualHeadTrackingMode GUARDED_BY(mLock)
382 = media::SpatializerHeadTrackingMode::DISABLED;
383
384 /** Selected Head pose sensor */
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700385 int32_t mHeadSensor GUARDED_BY(mLock) = SpatializerPoseController::INVALID_SENSOR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700386
387 /** Selected Screen pose sensor */
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700388 int32_t mScreenSensor GUARDED_BY(mLock) = SpatializerPoseController::INVALID_SENSOR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700389
390 /** Last display orientation received */
391 static constexpr float kDisplayOrientationInvalid = 1000;
392 float mDisplayOrientation GUARDED_BY(mLock) = kDisplayOrientationInvalid;
393
394 std::vector<media::SpatializationLevel> mLevels;
Andy Hunga461a002022-05-17 10:36:02 -0700395 std::vector<media::SpatializerHeadTrackingMode> mHeadTrackingModes;
Eric Laurent2be8b292021-08-23 09:44:33 -0700396 std::vector<media::SpatializationMode> mSpatializationModes;
397 std::vector<audio_channel_mask_t> mChannelMasks;
398 bool mSupportsHeadTracking;
Eric Laurent8a4259f2021-09-14 16:04:00 +0200399
400 // Looper thread for mEngine callbacks
401 class EngineCallbackHandler;
402
403 sp<ALooper> mLooper;
404 sp<EngineCallbackHandler> mHandler;
405
Eric Laurent15903592022-02-24 20:44:36 +0100406 size_t mNumActiveTracks GUARDED_BY(mLock) = 0;
Eric Laurentee398ad2022-05-03 18:19:35 +0200407 std::vector<audio_latency_mode_t> mSupportedLatencyModes GUARDED_BY(mLock);
Eric Laurent15903592022-02-24 20:44:36 +0100408
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000409 static const std::vector<const char*> sHeadPoseKeys;
Eric Laurent6d607012021-07-05 11:54:40 +0200410
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000411 // Local log for command messages.
412 static constexpr int mMaxLocalLogLine = 10;
413 SimpleLog mLocalLog{mMaxLocalLogLine};
414
415 /**
416 * @brief Calculate and record sensor data.
417 * Dump to local log with max/average pose angle every mPoseRecordThreshold.
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000418 */
419 class HeadToStagePoseRecorder {
420 public:
Shunkai Yao20e23732022-08-25 00:44:04 +0000421 HeadToStagePoseRecorder(std::chrono::duration<double> threshold, int maxLogLine)
422 : mPoseRecordThreshold(threshold), mPoseRecordLog(maxLogLine) {
423 resetRecord();
424 }
425
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000426 /** Convert recorded sensor data to string with level indentation */
Shunkai Yao20e23732022-08-25 00:44:04 +0000427 std::string toString(unsigned level) const;
428
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000429 /**
430 * @brief Calculate sensor data, record into local log when it is time.
431 *
432 * @param headToStage The vector from Pose3f::toVector().
433 */
Shunkai Yao20e23732022-08-25 00:44:04 +0000434 void record(const std::vector<float>& headToStage);
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000435
436 static constexpr float getDegreeWithRadian(const float radian) {
437 float radianToDegreeRatio = (180 / PI);
438 return (radian * radianToDegreeRatio);
439 }
440
441 private:
442 static constexpr float PI = M_PI;
443 /**
444 * Pose recorder time threshold to record sensor data in local log.
Shunkai Yao20e23732022-08-25 00:44:04 +0000445 * Sensor data will be recorded into log at least every mPoseRecordThreshold.
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000446 */
Shunkai Yao20e23732022-08-25 00:44:04 +0000447 std::chrono::duration<double> mPoseRecordThreshold;
448 // Number of seconds pass since last record.
449 std::chrono::duration<double> mNumOfSecondsSinceLastRecord;
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000450 /**
451 * According to frameworks/av/media/libheadtracking/include/media/Pose.h
452 * "The vector will have exactly 6 elements, where the first three are a translation vector
453 * and the last three are a rotation vector."
454 */
455 static constexpr size_t mPoseVectorSize = 6;
456 /**
457 * Timestamp of last sensor data record in local log.
458 */
459 std::chrono::time_point<std::chrono::steady_clock> mFirstSampleTimestamp;
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000460 /**
461 * Number of sensor samples received since last record, sample rate is ~100Hz which produce
462 * ~6k samples/minute.
463 */
464 uint32_t mNumOfSampleSinceLastRecord = 0;
465 /* The sum of pose angle represented by radian since last dump, div
466 * mNumOfSampleSinceLastRecord to get arithmetic mean. Largest possible value: 2PI * 100Hz *
467 * mPoseRecordThreshold.
468 */
Shunkai Yao20e23732022-08-25 00:44:04 +0000469 std::vector<double> mPoseRadianSum;
470 std::vector<float> mMaxPoseAngle;
471 std::vector<float> mMinPoseAngle;
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000472 // Local log for history sensor data.
473 SimpleLog mPoseRecordLog{mMaxLocalLogLine};
474
Shunkai Yao20e23732022-08-25 00:44:04 +0000475 bool shouldRecordLog() {
476 mNumOfSecondsSinceLastRecord = std::chrono::duration_cast<std::chrono::seconds>(
477 std::chrono::steady_clock::now() - mFirstSampleTimestamp);
478 return mNumOfSecondsSinceLastRecord >= mPoseRecordThreshold;
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000479 }
480
Shunkai Yao20e23732022-08-25 00:44:04 +0000481 void resetRecord() {
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000482 mPoseRadianSum.assign(mPoseVectorSize, 0);
Shunkai Yao20e23732022-08-25 00:44:04 +0000483 mMaxPoseAngle.assign(mPoseVectorSize, -PI);
484 mMinPoseAngle.assign(mPoseVectorSize, PI);
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000485 mNumOfSampleSinceLastRecord = 0;
Shunkai Yao20e23732022-08-25 00:44:04 +0000486 mNumOfSecondsSinceLastRecord = std::chrono::seconds(0);
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000487 }
488
489 // Add each sample to sum and only calculate when record.
490 void poseSumToAverage() {
491 if (mNumOfSampleSinceLastRecord == 0) return;
492 for (auto& p : mPoseRadianSum) {
493 const float reciprocal = 1.f / mNumOfSampleSinceLastRecord;
494 p *= reciprocal;
495 }
496 }
497 }; // HeadToStagePoseRecorder
Shunkai Yao20e23732022-08-25 00:44:04 +0000498
499 // Record one log line per second (up to mMaxLocalLogLine) to capture most recent sensor data.
500 HeadToStagePoseRecorder mPoseRecorder GUARDED_BY(mLock) =
501 HeadToStagePoseRecorder(std::chrono::seconds(1), mMaxLocalLogLine);
502 // Record one log line per minute (up to mMaxLocalLogLine) to capture durable sensor data.
503 HeadToStagePoseRecorder mPoseDurableRecorder GUARDED_BY(mLock) =
504 HeadToStagePoseRecorder(std::chrono::minutes(1), mMaxLocalLogLine);
Shunkai Yao59b27bc2022-07-22 18:42:27 +0000505}; // Spatializer
Eric Laurent6d607012021-07-05 11:54:40 +0200506
507}; // namespace android
508
509#endif // ANDROID_MEDIA_SPATIALIZER_H