blob: 0f6bafe7adc999deda174d4402a59cfcfd0355da [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 Yao5a251df2022-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>
Andy Hung5d8618d2022-11-17 17:21:45 -080026#include <android/media/audio/common/AudioLatencyMode.h>
Shunkai Yao5a251df2022-07-22 18:42:27 +000027#include <audio_utils/SimpleLog.h>
28#include <math.h>
29#include <media/AudioEffect.h>
Eric Laurent2be8b292021-08-23 09:44:33 -070030#include <media/audiohal/EffectHalInterface.h>
Eric Laurent8a4259f2021-09-14 16:04:00 +020031#include <media/stagefright/foundation/ALooper.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020032#include <system/audio_effects/effect_spatializer.h>
Shunkai Yao5a251df2022-07-22 18:42:27 +000033#include <string>
Eric Laurent6d607012021-07-05 11:54:40 +020034
Eric Laurent2be8b292021-08-23 09:44:33 -070035#include "SpatializerPoseController.h"
Eric Laurent6d607012021-07-05 11:54:40 +020036
37namespace android {
38
39
40// ----------------------------------------------------------------------------
41
42/**
43 * A callback interface from the Spatializer object or its parent AudioPolicyService.
44 * This is implemented by the audio policy service hosting the Spatializer to perform
45 * actions needed when a state change inside the Spatializer requires some audio system
46 * changes that cannot be performed by the Spatializer. For instance opening or closing a
47 * spatializer output stream when the spatializer is enabled or disabled
48 */
49class SpatializerPolicyCallback {
50public:
51 /** Called when a stage change occurs that requires the parent audio policy service to take
52 * some action.
53 */
54 virtual void onCheckSpatializer() = 0;
55
56 virtual ~SpatializerPolicyCallback() = default;
57};
58/**
59 * The Spatializer class implements all functional controlling the multichannel spatializer
60 * with head tracking implementation in the native audio service: audio policy and audio flinger.
61 * It presents an AIDL interface available to the java audio service to discover the availability
62 * of the feature and options, control its state and register an active head tracking sensor.
63 * It maintains the current state of the platform spatializer and applies the stored parameters
64 * when the spatializer engine is created and enabled.
65 * Based on the requested spatializer level, it will request the creation of a specialized output
66 * mixer to the audio policy service which will in turn notify the Spatializer of the output
67 * stream on which a spatializer engine should be created, configured and enabled.
68 * The spatializer also hosts the head tracking management logic. This logic receives the
69 * desired head tracking mode and selected head tracking sensor, registers a sensor event listener
70 * and derives the compounded head pose information to the spatializer engine.
71 *
72 * Workflow:
73 * - Initialization: when the audio policy service starts, it checks if a spatializer effect
74 * engine exists and if the audio policy manager reports a dedicated spatializer output profile.
75 * If both conditions are met, a Spatializer object is created
76 * - Capabilities discovery: AudioService will call AudioSystem::canBeSpatialized() and if true,
77 * acquire an ISpatializer interface with AudioSystem::getSpatializer(). This interface
78 * will be used to query the implementation capabilities and configure the spatializer.
79 * - Enabling: when ISpatializer::setLevel() sets a level different from NONE the spatializer
80 * is considered enabled. The audio policy callback onCheckSpatializer() is called. This
81 * triggers a request to audio policy manager to open a spatialization output stream and a
82 * spatializer mixer is created in audio flinger. When an output is returned by audio policy
83 * manager, Spatializer::attachOutput() is called which creates and enables the spatializer
84 * stage engine on the specified output.
85 * - Disabling: when the spatialization level is set to NONE, the spatializer is considered
86 * disabled. The audio policy callback onCheckSpatializer() is called. This triggers a call
87 * to Spatializer::detachOutput() and the spatializer engine is released. Then a request is
88 * made to audio policy manager to release and close the spatializer output stream and the
89 * spatializer mixer thread is destroyed.
90 */
Eric Laurent2be8b292021-08-23 09:44:33 -070091class Spatializer : public media::BnSpatializer,
92 public IBinder::DeathRecipient,
Eric Laurentb387fb42022-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 Laurentb387fb42022-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 Yao5a251df2022-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) {
Andy Hung5d8618d2022-11-17 17:21:45 -0800169 // We convert to the AIDL type to print (eventually the legacy type will be removed).
170 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
171 return result.has_value() ?
172 media::audio::common::toString(*result) : "unknown_latency_mode";
173 }
Shunkai Yao5a251df2022-07-22 18:42:27 +0000174
175 /**
176 * Format head to stage vector to a string, [0.00, 0.00, 0.00, -1.29, -0.50, 15.27].
177 */
178 template <typename T>
179 static std::string toString(const std::vector<T>& vec, bool radianToDegree = false) {
180 if (vec.size() == 0) {
181 return "[]";
182 }
183
184 std::string ss = "[";
Shunkai Yao7de40382022-08-25 00:44:04 +0000185 for (auto f = vec.begin(); f != vec.end(); ++f) {
186 if (f != vec.begin()) {
187 ss .append(", ");
188 }
Shunkai Yao5a251df2022-07-22 18:42:27 +0000189 if (radianToDegree) {
Shunkai Yao7de40382022-08-25 00:44:04 +0000190 base::StringAppendF(&ss, "%0.2f", HeadToStagePoseRecorder::getDegreeWithRadian(*f));
Shunkai Yao5a251df2022-07-22 18:42:27 +0000191 } else {
Shunkai Yao7de40382022-08-25 00:44:04 +0000192 base::StringAppendF(&ss, "%f", *f);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000193 }
194 }
Shunkai Yao7de40382022-08-25 00:44:04 +0000195 ss.append("]");
Shunkai Yao5a251df2022-07-22 18:42:27 +0000196 return ss;
197 };
198
Andy Hung757bc812022-09-13 18:53:06 -0700199 // If the Spatializer is not created, we send the status for metrics purposes.
200 // OK: Spatializer not expected to be created.
201 // NO_INIT: Spatializer creation failed.
202 static void sendEmptyCreateSpatializerMetricWithStatus(status_t status);
203
Eric Laurent6d607012021-07-05 11:54:40 +0200204private:
Eric Laurent6d607012021-07-05 11:54:40 +0200205 Spatializer(effect_descriptor_t engineDescriptor,
206 SpatializerPolicyCallback *callback);
207
Eric Laurent6d607012021-07-05 11:54:40 +0200208 static void engineCallback(int32_t event, void* user, void *info);
209
Eric Laurent2be8b292021-08-23 09:44:33 -0700210 // From VirtualizerStageController::Listener
211 void onHeadToStagePose(const media::Pose3f& headToStage) override;
212 void onActualModeChange(media::HeadTrackingMode mode) override;
213
Eric Laurent8a4259f2021-09-14 16:04:00 +0200214 void onHeadToStagePoseMsg(const std::vector<float>& headToStage);
215 void onActualModeChangeMsg(media::HeadTrackingMode mode);
Eric Laurentdf2ece42022-07-20 13:49:47 +0200216 void onSupportedLatencyModesChangedMsg(
217 audio_io_handle_t output, std::vector<audio_latency_mode_t>&& modes);
Eric Laurent8a4259f2021-09-14 16:04:00 +0200218
Eric Laurent2be8b292021-08-23 09:44:33 -0700219 static constexpr int kMaxEffectParamValues = 10;
220 /**
221 * Get a parameter from spatializer engine by calling the effect HAL command method directly.
222 * To be used when the engine instance mEngine is not yet created in the effect framework.
223 * When MULTI_VALUES is false, the expected reply is only one value of type T.
224 * When MULTI_VALUES is true, the expected reply is made of a number (of type T) indicating
225 * how many values are returned, followed by this number for values of type T.
226 */
227 template<bool MULTI_VALUES, typename T>
228 status_t getHalParameter(sp<EffectHalInterface> effect, uint32_t type,
229 std::vector<T> *values) {
230 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
231
232 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1];
233 uint32_t reply[sizeof(effect_param_t) / sizeof(uint32_t) + 2 + kMaxEffectParamValues];
234
235 effect_param_t *p = (effect_param_t *)cmd;
236 p->psize = sizeof(uint32_t);
237 if (MULTI_VALUES) {
238 p->vsize = (kMaxEffectParamValues + 1) * sizeof(T);
239 } else {
240 p->vsize = sizeof(T);
241 }
242 *(uint32_t *)p->data = type;
243 uint32_t replySize = sizeof(effect_param_t) + p->psize + p->vsize;
244
245 status_t status = effect->command(EFFECT_CMD_GET_PARAM,
246 sizeof(effect_param_t) + sizeof(uint32_t), cmd,
247 &replySize, reply);
248 if (status != NO_ERROR) {
249 return status;
250 }
251 if (p->status != NO_ERROR) {
252 return p->status;
253 }
254 if (replySize <
255 sizeof(effect_param_t) + sizeof(uint32_t) + (MULTI_VALUES ? 2 : 1) * sizeof(T)) {
256 return BAD_VALUE;
257 }
258
259 T *params = (T *)((uint8_t *)reply + sizeof(effect_param_t) + sizeof(uint32_t));
260 int numParams = 1;
261 if (MULTI_VALUES) {
262 numParams = (int)*params++;
263 }
264 if (numParams > kMaxEffectParamValues) {
265 return BAD_VALUE;
266 }
Eric Laurentc87402b2021-09-17 16:49:42 +0200267 (*values).clear();
Eric Laurent2be8b292021-08-23 09:44:33 -0700268 std::copy(&params[0], &params[numParams], back_inserter(*values));
269 return NO_ERROR;
270 }
271
272 /**
273 * Set a parameter to spatializer engine by calling setParameter on mEngine AudioEffect object.
274 * It is possible to pass more than one value of type T according to the parameter type
275 * according to values vector size.
276 */
277 template<typename T>
278 status_t setEffectParameter_l(uint32_t type, const std::vector<T>& values) REQUIRES(mLock) {
279 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
280
281 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values.size()];
282 effect_param_t *p = (effect_param_t *)cmd;
283 p->psize = sizeof(uint32_t);
284 p->vsize = sizeof(T) * values.size();
285 *(uint32_t *)p->data = type;
286 memcpy((uint32_t *)p->data + 1, values.data(), sizeof(T) * values.size());
287
Eric Laurentc87402b2021-09-17 16:49:42 +0200288 status_t status = mEngine->setParameter(p);
289 if (status != NO_ERROR) {
290 return status;
291 }
292 if (p->status != NO_ERROR) {
293 return p->status;
294 }
295 return NO_ERROR;
296 }
297
298 /**
299 * Get a parameter from spatializer engine by calling getParameter on AudioEffect object.
300 * It is possible to read more than one value of type T according to the parameter type
301 * by specifying values vector size.
302 */
303 template<typename T>
304 status_t getEffectParameter_l(uint32_t type, std::vector<T> *values) REQUIRES(mLock) {
305 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
306
307 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values->size()];
308 effect_param_t *p = (effect_param_t *)cmd;
309 p->psize = sizeof(uint32_t);
310 p->vsize = sizeof(T) * values->size();
311 *(uint32_t *)p->data = type;
312
313 status_t status = mEngine->getParameter(p);
314
315 if (status != NO_ERROR) {
316 return status;
317 }
318 if (p->status != NO_ERROR) {
319 return p->status;
320 }
321
322 int numValues = std::min(p->vsize / sizeof(T), values->size());
323 (*values).clear();
324 T *retValues = (T *)((uint8_t *)p->data + sizeof(uint32_t));
325 std::copy(&retValues[0], &retValues[numValues], back_inserter(*values));
326
327 return NO_ERROR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700328 }
329
Eric Laurent8a4259f2021-09-14 16:04:00 +0200330 void postFramesProcessedMsg(int frames);
331
Eric Laurent9249d342022-03-18 11:55:56 +0100332 /**
333 * Checks if head and screen sensors must be actively monitored based on
334 * spatializer state and playback activity and configures the pose controller
335 * accordingly.
336 */
337 void checkSensorsState_l() REQUIRES(mLock);
Eric Laurent15903592022-02-24 20:44:36 +0100338
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200339 /**
Eric Laurent11094172022-04-05 18:27:42 +0200340 * Checks if the head pose controller should be created or destroyed according
341 * to desired head tracking mode.
342 */
343 void checkPoseController_l() REQUIRES(mLock);
344
345 /**
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200346 * Checks if the spatializer effect should be enabled based on
347 * playback activity and requested level.
348 */
349 void checkEngineState_l() REQUIRES(mLock);
350
Eric Laurent3c48ad92022-10-21 11:28:32 +0200351 /**
352 * Reset head tracking mode and recenter pose in engine: Called when the head tracking
353 * is disabled.
354 */
355 void resetEngineHeadPose_l() REQUIRES(mLock);
356
Eric Laurent6d607012021-07-05 11:54:40 +0200357 /** Effect engine descriptor */
358 const effect_descriptor_t mEngineDescriptor;
359 /** Callback interface to parent audio policy service */
Andy Hunga461a002022-05-17 10:36:02 -0700360 SpatializerPolicyCallback* const mPolicyCallback;
361
362 /** Currently there is only one version of the spatializer running */
Andy Hung757bc812022-09-13 18:53:06 -0700363 static constexpr const char* kDefaultMetricsId =
364 AMEDIAMETRICS_KEY_PREFIX_AUDIO_SPATIALIZER "0";
365 const std::string mMetricsId = kDefaultMetricsId;
Eric Laurent6d607012021-07-05 11:54:40 +0200366
367 /** Mutex protecting internal state */
Eric Laurent2be8b292021-08-23 09:44:33 -0700368 mutable std::mutex mLock;
Eric Laurent6d607012021-07-05 11:54:40 +0200369
370 /** Client AudioEffect for the engine */
371 sp<AudioEffect> mEngine GUARDED_BY(mLock);
372 /** Output stream the spatializer mixer thread is attached to */
373 audio_io_handle_t mOutput GUARDED_BY(mLock) = AUDIO_IO_HANDLE_NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200374
375 /** Callback interface to the client (AudioService) controlling this`Spatializer */
376 sp<media::INativeSpatializerCallback> mSpatializerCallback GUARDED_BY(mLock);
377
Eric Laurent67816e32021-09-16 15:18:40 +0200378 /** Callback interface for head tracking */
379 sp<media::ISpatializerHeadTrackingCallback> mHeadTrackingCallback GUARDED_BY(mLock);
380
Eric Laurent6d607012021-07-05 11:54:40 +0200381 /** Requested spatialization level */
382 media::SpatializationLevel mLevel GUARDED_BY(mLock) = media::SpatializationLevel::NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200383
Eric Laurent2be8b292021-08-23 09:44:33 -0700384 /** Control logic for head-tracking, etc. */
385 std::shared_ptr<SpatializerPoseController> mPoseController GUARDED_BY(mLock);
386
387 /** Last requested head tracking mode */
388 media::HeadTrackingMode mDesiredHeadTrackingMode GUARDED_BY(mLock)
389 = media::HeadTrackingMode::STATIC;
390
391 /** Last-reported actual head-tracking mode. */
392 media::SpatializerHeadTrackingMode mActualHeadTrackingMode GUARDED_BY(mLock)
393 = media::SpatializerHeadTrackingMode::DISABLED;
394
395 /** Selected Head pose sensor */
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700396 int32_t mHeadSensor GUARDED_BY(mLock) = SpatializerPoseController::INVALID_SENSOR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700397
398 /** Selected Screen pose sensor */
Ytai Ben-Tsvi9f12f172021-09-23 16:47:25 -0700399 int32_t mScreenSensor GUARDED_BY(mLock) = SpatializerPoseController::INVALID_SENSOR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700400
401 /** Last display orientation received */
402 static constexpr float kDisplayOrientationInvalid = 1000;
403 float mDisplayOrientation GUARDED_BY(mLock) = kDisplayOrientationInvalid;
404
405 std::vector<media::SpatializationLevel> mLevels;
Andy Hunga461a002022-05-17 10:36:02 -0700406 std::vector<media::SpatializerHeadTrackingMode> mHeadTrackingModes;
Eric Laurent2be8b292021-08-23 09:44:33 -0700407 std::vector<media::SpatializationMode> mSpatializationModes;
408 std::vector<audio_channel_mask_t> mChannelMasks;
409 bool mSupportsHeadTracking;
Eric Laurent8a4259f2021-09-14 16:04:00 +0200410
411 // Looper thread for mEngine callbacks
412 class EngineCallbackHandler;
413
414 sp<ALooper> mLooper;
415 sp<EngineCallbackHandler> mHandler;
416
Eric Laurent15903592022-02-24 20:44:36 +0100417 size_t mNumActiveTracks GUARDED_BY(mLock) = 0;
Eric Laurentb387fb42022-05-03 18:19:35 +0200418 std::vector<audio_latency_mode_t> mSupportedLatencyModes GUARDED_BY(mLock);
Eric Laurent15903592022-02-24 20:44:36 +0100419
Shunkai Yao5a251df2022-07-22 18:42:27 +0000420 static const std::vector<const char*> sHeadPoseKeys;
Eric Laurent6d607012021-07-05 11:54:40 +0200421
Shunkai Yao5a251df2022-07-22 18:42:27 +0000422 // Local log for command messages.
423 static constexpr int mMaxLocalLogLine = 10;
424 SimpleLog mLocalLog{mMaxLocalLogLine};
425
426 /**
427 * @brief Calculate and record sensor data.
428 * Dump to local log with max/average pose angle every mPoseRecordThreshold.
Shunkai Yao5a251df2022-07-22 18:42:27 +0000429 */
430 class HeadToStagePoseRecorder {
431 public:
Shunkai Yao7de40382022-08-25 00:44:04 +0000432 HeadToStagePoseRecorder(std::chrono::duration<double> threshold, int maxLogLine)
433 : mPoseRecordThreshold(threshold), mPoseRecordLog(maxLogLine) {
434 resetRecord();
435 }
436
Shunkai Yao5a251df2022-07-22 18:42:27 +0000437 /** Convert recorded sensor data to string with level indentation */
Shunkai Yao7de40382022-08-25 00:44:04 +0000438 std::string toString(unsigned level) const;
439
Shunkai Yao5a251df2022-07-22 18:42:27 +0000440 /**
441 * @brief Calculate sensor data, record into local log when it is time.
442 *
443 * @param headToStage The vector from Pose3f::toVector().
444 */
Shunkai Yao7de40382022-08-25 00:44:04 +0000445 void record(const std::vector<float>& headToStage);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000446
447 static constexpr float getDegreeWithRadian(const float radian) {
448 float radianToDegreeRatio = (180 / PI);
449 return (radian * radianToDegreeRatio);
450 }
451
452 private:
453 static constexpr float PI = M_PI;
454 /**
455 * Pose recorder time threshold to record sensor data in local log.
Shunkai Yao7de40382022-08-25 00:44:04 +0000456 * Sensor data will be recorded into log at least every mPoseRecordThreshold.
Shunkai Yao5a251df2022-07-22 18:42:27 +0000457 */
Shunkai Yao7de40382022-08-25 00:44:04 +0000458 std::chrono::duration<double> mPoseRecordThreshold;
459 // Number of seconds pass since last record.
460 std::chrono::duration<double> mNumOfSecondsSinceLastRecord;
Shunkai Yao5a251df2022-07-22 18:42:27 +0000461 /**
462 * According to frameworks/av/media/libheadtracking/include/media/Pose.h
463 * "The vector will have exactly 6 elements, where the first three are a translation vector
464 * and the last three are a rotation vector."
465 */
466 static constexpr size_t mPoseVectorSize = 6;
467 /**
468 * Timestamp of last sensor data record in local log.
469 */
470 std::chrono::time_point<std::chrono::steady_clock> mFirstSampleTimestamp;
Shunkai Yao5a251df2022-07-22 18:42:27 +0000471 /**
472 * Number of sensor samples received since last record, sample rate is ~100Hz which produce
473 * ~6k samples/minute.
474 */
475 uint32_t mNumOfSampleSinceLastRecord = 0;
476 /* The sum of pose angle represented by radian since last dump, div
477 * mNumOfSampleSinceLastRecord to get arithmetic mean. Largest possible value: 2PI * 100Hz *
478 * mPoseRecordThreshold.
479 */
Shunkai Yao7de40382022-08-25 00:44:04 +0000480 std::vector<double> mPoseRadianSum;
481 std::vector<float> mMaxPoseAngle;
482 std::vector<float> mMinPoseAngle;
Shunkai Yao5a251df2022-07-22 18:42:27 +0000483 // Local log for history sensor data.
484 SimpleLog mPoseRecordLog{mMaxLocalLogLine};
485
Shunkai Yao7de40382022-08-25 00:44:04 +0000486 bool shouldRecordLog() {
487 mNumOfSecondsSinceLastRecord = std::chrono::duration_cast<std::chrono::seconds>(
488 std::chrono::steady_clock::now() - mFirstSampleTimestamp);
489 return mNumOfSecondsSinceLastRecord >= mPoseRecordThreshold;
Shunkai Yao5a251df2022-07-22 18:42:27 +0000490 }
491
Shunkai Yao7de40382022-08-25 00:44:04 +0000492 void resetRecord() {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000493 mPoseRadianSum.assign(mPoseVectorSize, 0);
Shunkai Yao7de40382022-08-25 00:44:04 +0000494 mMaxPoseAngle.assign(mPoseVectorSize, -PI);
495 mMinPoseAngle.assign(mPoseVectorSize, PI);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000496 mNumOfSampleSinceLastRecord = 0;
Shunkai Yao7de40382022-08-25 00:44:04 +0000497 mNumOfSecondsSinceLastRecord = std::chrono::seconds(0);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000498 }
499
500 // Add each sample to sum and only calculate when record.
501 void poseSumToAverage() {
502 if (mNumOfSampleSinceLastRecord == 0) return;
503 for (auto& p : mPoseRadianSum) {
504 const float reciprocal = 1.f / mNumOfSampleSinceLastRecord;
505 p *= reciprocal;
506 }
507 }
508 }; // HeadToStagePoseRecorder
Shunkai Yao7de40382022-08-25 00:44:04 +0000509
510 // Record one log line per second (up to mMaxLocalLogLine) to capture most recent sensor data.
511 HeadToStagePoseRecorder mPoseRecorder GUARDED_BY(mLock) =
512 HeadToStagePoseRecorder(std::chrono::seconds(1), mMaxLocalLogLine);
513 // Record one log line per minute (up to mMaxLocalLogLine) to capture durable sensor data.
514 HeadToStagePoseRecorder mPoseDurableRecorder GUARDED_BY(mLock) =
515 HeadToStagePoseRecorder(std::chrono::minutes(1), mMaxLocalLogLine);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000516}; // Spatializer
Eric Laurent6d607012021-07-05 11:54:40 +0200517
518}; // namespace android
519
520#endif // ANDROID_MEDIA_SPATIALIZER_H