blob: 3860bbd2028eb793f199c460797f85d45523fed3 [file] [log] [blame]
Eric Laurent6d607012021-07-05 11:54:40 +02001/*
2**
3** Copyright 2021, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
Shunkai Yao5a251df2022-07-22 18:42:27 +000018#include <string>
Eric Laurent6d607012021-07-05 11:54:40 +020019#define LOG_TAG "Spatializer"
20//#define LOG_NDEBUG 0
21#include <utils/Log.h>
22
Shunkai Yao5a251df2022-07-22 18:42:27 +000023#include <inttypes.h>
Eric Laurent6d607012021-07-05 11:54:40 +020024#include <limits.h>
25#include <stdint.h>
26#include <sys/types.h>
27
28#include <android/content/AttributionSourceState.h>
29#include <audio_utils/fixedfft.h>
30#include <cutils/bitops.h>
Eric Laurent2be8b292021-08-23 09:44:33 -070031#include <hardware/sensors.h>
Eric Laurent6d607012021-07-05 11:54:40 +020032#include <media/audiohal/EffectsFactoryHalInterface.h>
Eric Laurent8a4259f2021-09-14 16:04:00 +020033#include <media/stagefright/foundation/AHandler.h>
34#include <media/stagefright/foundation/AMessage.h>
Andy Hunga461a002022-05-17 10:36:02 -070035#include <media/MediaMetricsItem.h>
Eric Laurent8a4259f2021-09-14 16:04:00 +020036#include <media/ShmemCompat.h>
Eric Laurent6d607012021-07-05 11:54:40 +020037#include <mediautils/ServiceUtilities.h>
38#include <utils/Thread.h>
39
40#include "Spatializer.h"
41
42namespace android {
43
44using aidl_utils::statusTFromBinderStatus;
45using aidl_utils::binderStatusFromStatusT;
46using android::content::AttributionSourceState;
47using binder::Status;
Eric Laurent2be8b292021-08-23 09:44:33 -070048using media::HeadTrackingMode;
49using media::Pose3f;
Eric Laurent6d607012021-07-05 11:54:40 +020050using media::SpatializationLevel;
Eric Laurent2be8b292021-08-23 09:44:33 -070051using media::SpatializationMode;
Ytai Ben-Tsvia16a9df2021-08-05 08:57:06 -070052using media::SpatializerHeadTrackingMode;
Eric Laurent2be8b292021-08-23 09:44:33 -070053using media::SensorPoseProvider;
54
Eric Laurent2be8b292021-08-23 09:44:33 -070055using namespace std::chrono_literals;
Eric Laurent6d607012021-07-05 11:54:40 +020056
57#define VALUE_OR_RETURN_BINDER_STATUS(x) \
58 ({ auto _tmp = (x); \
59 if (!_tmp.ok()) return aidl_utils::binderStatusFromStatusT(_tmp.error()); \
60 std::move(_tmp.value()); })
61
Andy Hunga461a002022-05-17 10:36:02 -070062audio_channel_mask_t getMaxChannelMask(std::vector<audio_channel_mask_t> masks) {
63 uint32_t maxCount = 0;
64 audio_channel_mask_t maxMask = AUDIO_CHANNEL_NONE;
65 for (auto mask : masks) {
66 const size_t count = audio_channel_count_from_out_mask(mask);
67 if (count > maxCount) {
68 maxMask = mask;
69 maxCount = count;
70 }
71 }
72 return maxMask;
73}
74
Eric Laurent6d607012021-07-05 11:54:40 +020075// ---------------------------------------------------------------------------
76
Eric Laurent8a4259f2021-09-14 16:04:00 +020077class Spatializer::EngineCallbackHandler : public AHandler {
78public:
79 EngineCallbackHandler(wp<Spatializer> spatializer)
80 : mSpatializer(spatializer) {
81 }
82
83 enum {
84 // Device state callbacks
85 kWhatOnFramesProcessed, // AudioEffect::EVENT_FRAMES_PROCESSED
86 kWhatOnHeadToStagePose, // SpatializerPoseController::Listener::onHeadToStagePose
87 kWhatOnActualModeChange, // SpatializerPoseController::Listener::onActualModeChange
88 };
89 static constexpr const char *kNumFramesKey = "numFrames";
90 static constexpr const char *kModeKey = "mode";
91 static constexpr const char *kTranslation0Key = "translation0";
92 static constexpr const char *kTranslation1Key = "translation1";
93 static constexpr const char *kTranslation2Key = "translation2";
94 static constexpr const char *kRotation0Key = "rotation0";
95 static constexpr const char *kRotation1Key = "rotation1";
96 static constexpr const char *kRotation2Key = "rotation2";
97
98 void onMessageReceived(const sp<AMessage> &msg) override {
99 switch (msg->what()) {
100 case kWhatOnFramesProcessed: {
101 sp<Spatializer> spatializer = mSpatializer.promote();
102 if (spatializer == nullptr) {
103 ALOGW("%s: Cannot promote spatializer", __func__);
104 return;
105 }
106 int numFrames;
107 if (!msg->findInt32(kNumFramesKey, &numFrames)) {
108 ALOGE("%s: Cannot find num frames!", __func__);
109 return;
110 }
111 if (numFrames > 0) {
112 spatializer->calculateHeadPose();
113 }
114 } break;
115 case kWhatOnHeadToStagePose: {
116 sp<Spatializer> spatializer = mSpatializer.promote();
117 if (spatializer == nullptr) {
118 ALOGW("%s: Cannot promote spatializer", __func__);
119 return;
120 }
121 std::vector<float> headToStage(sHeadPoseKeys.size());
122 for (size_t i = 0 ; i < sHeadPoseKeys.size(); i++) {
123 if (!msg->findFloat(sHeadPoseKeys[i], &headToStage[i])) {
124 ALOGE("%s: Cannot find kTranslation0Key!", __func__);
125 return;
126 }
127 }
128 spatializer->onHeadToStagePoseMsg(headToStage);
129 } break;
130 case kWhatOnActualModeChange: {
131 sp<Spatializer> spatializer = mSpatializer.promote();
132 if (spatializer == nullptr) {
133 ALOGW("%s: Cannot promote spatializer", __func__);
134 return;
135 }
136 int mode;
137 if (!msg->findInt32(EngineCallbackHandler::kModeKey, &mode)) {
138 ALOGE("%s: Cannot find actualMode!", __func__);
139 return;
140 }
141 spatializer->onActualModeChangeMsg(static_cast<HeadTrackingMode>(mode));
142 } break;
143 default:
144 LOG_ALWAYS_FATAL("Invalid callback message %d", msg->what());
145 }
146 }
147private:
148 wp<Spatializer> mSpatializer;
149};
150
151const std::vector<const char *> Spatializer::sHeadPoseKeys = {
152 Spatializer::EngineCallbackHandler::kTranslation0Key,
153 Spatializer::EngineCallbackHandler::kTranslation1Key,
154 Spatializer::EngineCallbackHandler::kTranslation2Key,
155 Spatializer::EngineCallbackHandler::kRotation0Key,
156 Spatializer::EngineCallbackHandler::kRotation1Key,
157 Spatializer::EngineCallbackHandler::kRotation2Key,
158};
159
160// ---------------------------------------------------------------------------
Shunkai Yao5a251df2022-07-22 18:42:27 +0000161
162// Convert recorded sensor data to string with level indentation.
Shunkai Yao7de40382022-08-25 00:44:04 +0000163std::string Spatializer::HeadToStagePoseRecorder::toString(unsigned level) const {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000164 std::string prefixSpace(level, ' ');
165 return mPoseRecordLog.dumpToString((prefixSpace + " ").c_str(), Spatializer::mMaxLocalLogLine);
166}
167
168// Compute sensor data, record into local log when it is time.
Shunkai Yao7de40382022-08-25 00:44:04 +0000169void Spatializer::HeadToStagePoseRecorder::record(const std::vector<float>& headToStage) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000170 if (headToStage.size() != mPoseVectorSize) return;
171
172 if (mNumOfSampleSinceLastRecord++ == 0) {
173 mFirstSampleTimestamp = std::chrono::steady_clock::now();
174 }
175 // if it's time, do record and reset.
176 if (shouldRecordLog()) {
177 poseSumToAverage();
178 mPoseRecordLog.log(
Shunkai Yao7de40382022-08-25 00:44:04 +0000179 "mean: %s, min: %s, max %s, calculated %d samples in %0.4f second(s)",
Shunkai Yao5a251df2022-07-22 18:42:27 +0000180 Spatializer::toString<double>(mPoseRadianSum, true /* radianToDegree */).c_str(),
181 Spatializer::toString<float>(mMinPoseAngle, true /* radianToDegree */).c_str(),
182 Spatializer::toString<float>(mMaxPoseAngle, true /* radianToDegree */).c_str(),
Shunkai Yao7de40382022-08-25 00:44:04 +0000183 mNumOfSampleSinceLastRecord, mNumOfSecondsSinceLastRecord.count());
184 resetRecord();
Shunkai Yao5a251df2022-07-22 18:42:27 +0000185 }
186 // update stream average.
187 for (int i = 0; i < mPoseVectorSize; i++) {
188 mPoseRadianSum[i] += headToStage[i];
189 mMaxPoseAngle[i] = std::max(mMaxPoseAngle[i], headToStage[i]);
190 mMinPoseAngle[i] = std::min(mMinPoseAngle[i], headToStage[i]);
191 }
192 return;
193}
194
195// ---------------------------------------------------------------------------
Eric Laurent6d607012021-07-05 11:54:40 +0200196sp<Spatializer> Spatializer::create(SpatializerPolicyCallback *callback) {
197 sp<Spatializer> spatializer;
198
199 sp<EffectsFactoryHalInterface> effectsFactoryHal = EffectsFactoryHalInterface::create();
200 if (effectsFactoryHal == nullptr) {
201 ALOGW("%s failed to create effect factory interface", __func__);
202 return spatializer;
203 }
204
205 std::vector<effect_descriptor_t> descriptors;
206 status_t status =
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200207 effectsFactoryHal->getDescriptors(FX_IID_SPATIALIZER, &descriptors);
Eric Laurent6d607012021-07-05 11:54:40 +0200208 if (status != NO_ERROR) {
209 ALOGW("%s failed to get spatializer descriptor, error %d", __func__, status);
210 return spatializer;
211 }
212 ALOG_ASSERT(!descriptors.empty(),
213 "%s getDescriptors() returned no error but empty list", __func__);
214
Shunkai Yao5a251df2022-07-22 18:42:27 +0000215 // TODO: get supported spatialization modes from FX engine or descriptor
Eric Laurent6d607012021-07-05 11:54:40 +0200216 sp<EffectHalInterface> effect;
217 status = effectsFactoryHal->createEffect(&descriptors[0].uuid, AUDIO_SESSION_OUTPUT_STAGE,
218 AUDIO_IO_HANDLE_NONE, AUDIO_PORT_HANDLE_NONE, &effect);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000219 ALOGI("%s FX create status %d effect ID %" PRId64, __func__, status,
220 effect ? effect->effectId() : 0);
Eric Laurent6d607012021-07-05 11:54:40 +0200221
222 if (status == NO_ERROR && effect != nullptr) {
223 spatializer = new Spatializer(descriptors[0], callback);
Eric Laurent2be8b292021-08-23 09:44:33 -0700224 if (spatializer->loadEngineConfiguration(effect) != NO_ERROR) {
225 spatializer.clear();
226 }
Shunkai Yao5a251df2022-07-22 18:42:27 +0000227 spatializer->mLocalLog.log("%s with effect Id %" PRId64, __func__,
228 effect ? effect->effectId() : 0);
Eric Laurent6d607012021-07-05 11:54:40 +0200229 }
230
231 return spatializer;
232}
233
Eric Laurent2be8b292021-08-23 09:44:33 -0700234Spatializer::Spatializer(effect_descriptor_t engineDescriptor, SpatializerPolicyCallback* callback)
235 : mEngineDescriptor(engineDescriptor),
236 mPolicyCallback(callback) {
Eric Laurent6d607012021-07-05 11:54:40 +0200237 ALOGV("%s", __func__);
238}
239
Eric Laurent8a4259f2021-09-14 16:04:00 +0200240void Spatializer::onFirstRef() {
241 mLooper = new ALooper;
242 mLooper->setName("Spatializer-looper");
243 mLooper->start(
244 /*runOnCallingThread*/false,
245 /*canCallJava*/ false,
246 PRIORITY_AUDIO);
247
248 mHandler = new EngineCallbackHandler(this);
249 mLooper->registerHandler(mHandler);
250}
251
Eric Laurent6d607012021-07-05 11:54:40 +0200252Spatializer::~Spatializer() {
253 ALOGV("%s", __func__);
Eric Laurent8a4259f2021-09-14 16:04:00 +0200254 if (mLooper != nullptr) {
255 mLooper->stop();
256 mLooper->unregisterHandler(mHandler->id());
257 }
258 mLooper.clear();
259 mHandler.clear();
Eric Laurent6d607012021-07-05 11:54:40 +0200260}
261
Eric Laurent2be8b292021-08-23 09:44:33 -0700262status_t Spatializer::loadEngineConfiguration(sp<EffectHalInterface> effect) {
263 ALOGV("%s", __func__);
264
265 std::vector<bool> supportsHeadTracking;
266 status_t status = getHalParameter<false>(effect, SPATIALIZER_PARAM_HEADTRACKING_SUPPORTED,
267 &supportsHeadTracking);
268 if (status != NO_ERROR) {
Andy Hung119dbdb2022-05-11 19:20:13 -0700269 ALOGW("%s: cannot get SPATIALIZER_PARAM_HEADTRACKING_SUPPORTED", __func__);
Eric Laurent2be8b292021-08-23 09:44:33 -0700270 return status;
271 }
272 mSupportsHeadTracking = supportsHeadTracking[0];
273
Andy Hung119dbdb2022-05-11 19:20:13 -0700274 std::vector<media::SpatializationLevel> spatializationLevels;
275 status = getHalParameter<true>(effect, SPATIALIZER_PARAM_SUPPORTED_LEVELS,
276 &spatializationLevels);
Eric Laurent2be8b292021-08-23 09:44:33 -0700277 if (status != NO_ERROR) {
Andy Hung119dbdb2022-05-11 19:20:13 -0700278 ALOGW("%s: cannot get SPATIALIZER_PARAM_SUPPORTED_LEVELS", __func__);
Eric Laurent2be8b292021-08-23 09:44:33 -0700279 return status;
280 }
Andy Hung119dbdb2022-05-11 19:20:13 -0700281 bool noneLevelFound = false;
282 bool activeLevelFound = false;
283 for (const auto spatializationLevel : spatializationLevels) {
284 if (!aidl_utils::isValidEnum(spatializationLevel)) {
285 ALOGW("%s: ignoring spatializationLevel:%d", __func__, (int)spatializationLevel);
286 continue;
287 }
288 if (spatializationLevel == media::SpatializationLevel::NONE) {
289 noneLevelFound = true;
290 } else {
291 activeLevelFound = true;
292 }
293 // we don't detect duplicates.
294 mLevels.emplace_back(spatializationLevel);
295 }
296 if (!noneLevelFound || !activeLevelFound) {
297 ALOGW("%s: SPATIALIZER_PARAM_SUPPORTED_LEVELS must include NONE"
298 " and another valid level", __func__);
299 return BAD_VALUE;
300 }
301
302 std::vector<media::SpatializationMode> spatializationModes;
Eric Laurent2be8b292021-08-23 09:44:33 -0700303 status = getHalParameter<true>(effect, SPATIALIZER_PARAM_SUPPORTED_SPATIALIZATION_MODES,
Andy Hung119dbdb2022-05-11 19:20:13 -0700304 &spatializationModes);
Eric Laurent2be8b292021-08-23 09:44:33 -0700305 if (status != NO_ERROR) {
Andy Hung119dbdb2022-05-11 19:20:13 -0700306 ALOGW("%s: cannot get SPATIALIZER_PARAM_SUPPORTED_SPATIALIZATION_MODES", __func__);
Eric Laurent2be8b292021-08-23 09:44:33 -0700307 return status;
308 }
Shunkai Yao5a251df2022-07-22 18:42:27 +0000309
Andy Hung119dbdb2022-05-11 19:20:13 -0700310 for (const auto spatializationMode : spatializationModes) {
311 if (!aidl_utils::isValidEnum(spatializationMode)) {
312 ALOGW("%s: ignoring spatializationMode:%d", __func__, (int)spatializationMode);
313 continue;
314 }
315 // we don't detect duplicates.
316 mSpatializationModes.emplace_back(spatializationMode);
317 }
318 if (mSpatializationModes.empty()) {
319 ALOGW("%s: SPATIALIZER_PARAM_SUPPORTED_SPATIALIZATION_MODES reports empty", __func__);
320 return BAD_VALUE;
321 }
322
323 std::vector<audio_channel_mask_t> channelMasks;
324 status = getHalParameter<true>(effect, SPATIALIZER_PARAM_SUPPORTED_CHANNEL_MASKS,
325 &channelMasks);
326 if (status != NO_ERROR) {
327 ALOGW("%s: cannot get SPATIALIZER_PARAM_SUPPORTED_CHANNEL_MASKS", __func__);
328 return status;
329 }
330 for (const auto channelMask : channelMasks) {
331 if (!audio_is_channel_mask_spatialized(channelMask)) {
332 ALOGW("%s: ignoring channelMask:%#x", __func__, channelMask);
333 continue;
334 }
335 // we don't detect duplicates.
336 mChannelMasks.emplace_back(channelMask);
337 }
338 if (mChannelMasks.empty()) {
339 ALOGW("%s: SPATIALIZER_PARAM_SUPPORTED_CHANNEL_MASKS reports empty", __func__);
340 return BAD_VALUE;
341 }
Andy Hunga461a002022-05-17 10:36:02 -0700342
343 // Currently we expose only RELATIVE_WORLD.
344 // This is a limitation of the head tracking library based on a UX choice.
345 mHeadTrackingModes.push_back(SpatializerHeadTrackingMode::DISABLED);
346 if (mSupportsHeadTracking) {
347 mHeadTrackingModes.push_back(SpatializerHeadTrackingMode::RELATIVE_WORLD);
348 }
349 mediametrics::LogItem(mMetricsId)
350 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE)
351 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)getMaxChannelMask(mChannelMasks))
352 .set(AMEDIAMETRICS_PROP_LEVELS, aidl_utils::enumsToString(mLevels))
353 .set(AMEDIAMETRICS_PROP_MODES, aidl_utils::enumsToString(mSpatializationModes))
354 .set(AMEDIAMETRICS_PROP_HEADTRACKINGMODES, aidl_utils::enumsToString(mHeadTrackingModes))
355 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
356 .record();
Andy Hung119dbdb2022-05-11 19:20:13 -0700357 return NO_ERROR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700358}
359
360/** Gets the channel mask, sampling rate and format set for the spatializer input. */
361audio_config_base_t Spatializer::getAudioInConfig() const {
362 std::lock_guard lock(mLock);
363 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
364 // For now use highest supported channel count
Andy Hunga461a002022-05-17 10:36:02 -0700365 config.channel_mask = getMaxChannelMask(mChannelMasks);
Eric Laurent2be8b292021-08-23 09:44:33 -0700366 return config;
367}
368
Eric Laurent6d607012021-07-05 11:54:40 +0200369status_t Spatializer::registerCallback(
370 const sp<media::INativeSpatializerCallback>& callback) {
Eric Laurent2be8b292021-08-23 09:44:33 -0700371 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200372 if (callback == nullptr) {
373 return BAD_VALUE;
374 }
375
376 sp<IBinder> binder = IInterface::asBinder(callback);
377 status_t status = binder->linkToDeath(this);
378 if (status == NO_ERROR) {
379 mSpatializerCallback = callback;
380 }
381 ALOGV("%s status %d", __func__, status);
382 return status;
383}
384
385// IBinder::DeathRecipient
386void Spatializer::binderDied(__unused const wp<IBinder> &who) {
387 {
Eric Laurent2be8b292021-08-23 09:44:33 -0700388 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200389 mLevel = SpatializationLevel::NONE;
390 mSpatializerCallback.clear();
391 }
392 ALOGV("%s", __func__);
393 mPolicyCallback->onCheckSpatializer();
394}
395
396// ISpatializer
397Status Spatializer::getSupportedLevels(std::vector<SpatializationLevel> *levels) {
398 ALOGV("%s", __func__);
399 if (levels == nullptr) {
400 return binderStatusFromStatusT(BAD_VALUE);
401 }
Andy Hunga461a002022-05-17 10:36:02 -0700402 // SpatializationLevel::NONE is already required from the effect or we don't load it.
Eric Laurent2be8b292021-08-23 09:44:33 -0700403 levels->insert(levels->end(), mLevels.begin(), mLevels.end());
Eric Laurent6d607012021-07-05 11:54:40 +0200404 return Status::ok();
405}
406
Eric Laurent2be8b292021-08-23 09:44:33 -0700407Status Spatializer::setLevel(SpatializationLevel level) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000408 ALOGV("%s level %s", __func__, media::toString(level).c_str());
409 mLocalLog.log("%s with %s", __func__, media::toString(level).c_str());
Eric Laurent6d607012021-07-05 11:54:40 +0200410 if (level != SpatializationLevel::NONE
Eric Laurent2be8b292021-08-23 09:44:33 -0700411 && std::find(mLevels.begin(), mLevels.end(), level) == mLevels.end()) {
Eric Laurent6d607012021-07-05 11:54:40 +0200412 return binderStatusFromStatusT(BAD_VALUE);
413 }
414 sp<media::INativeSpatializerCallback> callback;
415 bool levelChanged = false;
416 {
Eric Laurent2be8b292021-08-23 09:44:33 -0700417 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200418 levelChanged = mLevel != level;
419 mLevel = level;
420 callback = mSpatializerCallback;
Eric Laurent2be8b292021-08-23 09:44:33 -0700421
422 if (levelChanged && mEngine != nullptr) {
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200423 checkEngineState_l();
Eric Laurent2be8b292021-08-23 09:44:33 -0700424 }
Eric Laurent9249d342022-03-18 11:55:56 +0100425 checkSensorsState_l();
Eric Laurent6d607012021-07-05 11:54:40 +0200426 }
427
428 if (levelChanged) {
429 mPolicyCallback->onCheckSpatializer();
430 if (callback != nullptr) {
431 callback->onLevelChanged(level);
432 }
433 }
434 return Status::ok();
435}
436
Eric Laurent2be8b292021-08-23 09:44:33 -0700437Status Spatializer::getLevel(SpatializationLevel *level) {
Eric Laurent6d607012021-07-05 11:54:40 +0200438 if (level == nullptr) {
439 return binderStatusFromStatusT(BAD_VALUE);
440 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700441 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200442 *level = mLevel;
443 ALOGV("%s level %d", __func__, (int)*level);
444 return Status::ok();
445}
446
Eric Laurentc87402b2021-09-17 16:49:42 +0200447Status Spatializer::isHeadTrackingSupported(bool *supports) {
448 ALOGV("%s mSupportsHeadTracking %d", __func__, mSupportsHeadTracking);
449 if (supports == nullptr) {
450 return binderStatusFromStatusT(BAD_VALUE);
451 }
452 std::lock_guard lock(mLock);
453 *supports = mSupportsHeadTracking;
454 return Status::ok();
455}
456
Eric Laurent6d607012021-07-05 11:54:40 +0200457Status Spatializer::getSupportedHeadTrackingModes(
Eric Laurent2be8b292021-08-23 09:44:33 -0700458 std::vector<SpatializerHeadTrackingMode>* modes) {
459 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200460 ALOGV("%s", __func__);
461 if (modes == nullptr) {
462 return binderStatusFromStatusT(BAD_VALUE);
463 }
Andy Hunga461a002022-05-17 10:36:02 -0700464 modes->insert(modes->end(), mHeadTrackingModes.begin(), mHeadTrackingModes.end());
Eric Laurent6d607012021-07-05 11:54:40 +0200465 return Status::ok();
466}
467
Eric Laurent2be8b292021-08-23 09:44:33 -0700468Status Spatializer::setDesiredHeadTrackingMode(SpatializerHeadTrackingMode mode) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000469 ALOGV("%s mode %s", __func__, media::toString(mode).c_str());
Eric Laurent2be8b292021-08-23 09:44:33 -0700470
471 if (!mSupportsHeadTracking) {
472 return binderStatusFromStatusT(INVALID_OPERATION);
473 }
Shunkai Yao5a251df2022-07-22 18:42:27 +0000474 mLocalLog.log("%s with %s", __func__, media::toString(mode).c_str());
Eric Laurent2be8b292021-08-23 09:44:33 -0700475 std::lock_guard lock(mLock);
476 switch (mode) {
477 case SpatializerHeadTrackingMode::OTHER:
478 return binderStatusFromStatusT(BAD_VALUE);
479 case SpatializerHeadTrackingMode::DISABLED:
480 mDesiredHeadTrackingMode = HeadTrackingMode::STATIC;
481 break;
482 case SpatializerHeadTrackingMode::RELATIVE_WORLD:
483 mDesiredHeadTrackingMode = HeadTrackingMode::WORLD_RELATIVE;
484 break;
485 case SpatializerHeadTrackingMode::RELATIVE_SCREEN:
486 mDesiredHeadTrackingMode = HeadTrackingMode::SCREEN_RELATIVE;
487 break;
488 }
489
Eric Laurent11094172022-04-05 18:27:42 +0200490 checkPoseController_l();
491 checkSensorsState_l();
Eric Laurent2be8b292021-08-23 09:44:33 -0700492
493 return Status::ok();
494}
495
496Status Spatializer::getActualHeadTrackingMode(SpatializerHeadTrackingMode *mode) {
Eric Laurent6d607012021-07-05 11:54:40 +0200497 if (mode == nullptr) {
498 return binderStatusFromStatusT(BAD_VALUE);
499 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700500 std::lock_guard lock(mLock);
501 *mode = mActualHeadTrackingMode;
Eric Laurent6d607012021-07-05 11:54:40 +0200502 ALOGV("%s mode %d", __func__, (int)*mode);
503 return Status::ok();
504}
505
Ytai Ben-Tsvia16a9df2021-08-05 08:57:06 -0700506Status Spatializer::recenterHeadTracker() {
Eric Laurent780be4a2021-09-16 10:44:24 +0200507 if (!mSupportsHeadTracking) {
508 return binderStatusFromStatusT(INVALID_OPERATION);
509 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700510 std::lock_guard lock(mLock);
511 if (mPoseController != nullptr) {
512 mPoseController->recenter();
513 }
Eric Laurent6d607012021-07-05 11:54:40 +0200514 return Status::ok();
515}
516
517Status Spatializer::setGlobalTransform(const std::vector<float>& screenToStage) {
Eric Laurent6d607012021-07-05 11:54:40 +0200518 ALOGV("%s", __func__);
Eric Laurent780be4a2021-09-16 10:44:24 +0200519 if (!mSupportsHeadTracking) {
520 return binderStatusFromStatusT(INVALID_OPERATION);
521 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700522 std::optional<Pose3f> maybePose = Pose3f::fromVector(screenToStage);
523 if (!maybePose.has_value()) {
524 ALOGW("Invalid screenToStage vector.");
525 return binderStatusFromStatusT(BAD_VALUE);
526 }
527 std::lock_guard lock(mLock);
528 if (mPoseController != nullptr) {
Shunkai Yao7de40382022-08-25 00:44:04 +0000529 mLocalLog.log("%s with screenToStage %s", __func__, toString<float>(screenToStage).c_str());
Eric Laurent2be8b292021-08-23 09:44:33 -0700530 mPoseController->setScreenToStagePose(maybePose.value());
531 }
Eric Laurent6d607012021-07-05 11:54:40 +0200532 return Status::ok();
533}
534
535Status Spatializer::release() {
536 ALOGV("%s", __func__);
537 bool levelChanged = false;
538 {
Eric Laurent2be8b292021-08-23 09:44:33 -0700539 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200540 if (mSpatializerCallback == nullptr) {
541 return binderStatusFromStatusT(INVALID_OPERATION);
542 }
543
544 sp<IBinder> binder = IInterface::asBinder(mSpatializerCallback);
545 binder->unlinkToDeath(this);
546 mSpatializerCallback.clear();
547
548 levelChanged = mLevel != SpatializationLevel::NONE;
549 mLevel = SpatializationLevel::NONE;
550 }
551
552 if (levelChanged) {
553 mPolicyCallback->onCheckSpatializer();
554 }
555 return Status::ok();
556}
557
Eric Laurent2be8b292021-08-23 09:44:33 -0700558Status Spatializer::setHeadSensor(int sensorHandle) {
559 ALOGV("%s sensorHandle %d", __func__, sensorHandle);
Eric Laurent780be4a2021-09-16 10:44:24 +0200560 if (!mSupportsHeadTracking) {
561 return binderStatusFromStatusT(INVALID_OPERATION);
562 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700563 std::lock_guard lock(mLock);
Andy Hungba2a61a2022-05-20 12:00:28 -0700564 if (mHeadSensor != sensorHandle) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000565 mLocalLog.log("%s with 0x%08x", __func__, sensorHandle);
Andy Hungba2a61a2022-05-20 12:00:28 -0700566 mHeadSensor = sensorHandle;
567 checkPoseController_l();
568 checkSensorsState_l();
569 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700570 return Status::ok();
571}
572
573Status Spatializer::setScreenSensor(int sensorHandle) {
574 ALOGV("%s sensorHandle %d", __func__, sensorHandle);
Eric Laurent780be4a2021-09-16 10:44:24 +0200575 if (!mSupportsHeadTracking) {
576 return binderStatusFromStatusT(INVALID_OPERATION);
577 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700578 std::lock_guard lock(mLock);
Andy Hungba2a61a2022-05-20 12:00:28 -0700579 if (mScreenSensor != sensorHandle) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000580 mLocalLog.log("%s with 0x%08x", __func__, sensorHandle);
Andy Hungba2a61a2022-05-20 12:00:28 -0700581 mScreenSensor = sensorHandle;
582 // TODO: consider a new method setHeadAndScreenSensor()
583 // because we generally set both at the same time.
584 // This will avoid duplicated work and recentering.
585 checkSensorsState_l();
586 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700587 return Status::ok();
588}
589
590Status Spatializer::setDisplayOrientation(float physicalToLogicalAngle) {
591 ALOGV("%s physicalToLogicalAngle %f", __func__, physicalToLogicalAngle);
Eric Laurent780be4a2021-09-16 10:44:24 +0200592 if (!mSupportsHeadTracking) {
593 return binderStatusFromStatusT(INVALID_OPERATION);
594 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700595 std::lock_guard lock(mLock);
596 mDisplayOrientation = physicalToLogicalAngle;
Shunkai Yao5a251df2022-07-22 18:42:27 +0000597 mLocalLog.log("%s with %f", __func__, physicalToLogicalAngle);
Eric Laurent2be8b292021-08-23 09:44:33 -0700598 if (mPoseController != nullptr) {
599 mPoseController->setDisplayOrientation(mDisplayOrientation);
600 }
Eric Laurent16ddaf42021-09-17 15:00:35 +0200601 if (mEngine != nullptr) {
602 setEffectParameter_l(
603 SPATIALIZER_PARAM_DISPLAY_ORIENTATION, std::vector<float>{physicalToLogicalAngle});
604 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700605 return Status::ok();
606}
607
608Status Spatializer::setHingeAngle(float hingeAngle) {
609 std::lock_guard lock(mLock);
610 ALOGV("%s hingeAngle %f", __func__, hingeAngle);
611 if (mEngine != nullptr) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000612 mLocalLog.log("%s with %f", __func__, hingeAngle);
Eric Laurent2be8b292021-08-23 09:44:33 -0700613 setEffectParameter_l(SPATIALIZER_PARAM_HINGE_ANGLE, std::vector<float>{hingeAngle});
614 }
615 return Status::ok();
616}
617
618Status Spatializer::getSupportedModes(std::vector<SpatializationMode> *modes) {
619 ALOGV("%s", __func__);
620 if (modes == nullptr) {
621 return binderStatusFromStatusT(BAD_VALUE);
622 }
623 *modes = mSpatializationModes;
624 return Status::ok();
625}
626
Eric Laurent67816e32021-09-16 15:18:40 +0200627Status Spatializer::registerHeadTrackingCallback(
628 const sp<media::ISpatializerHeadTrackingCallback>& callback) {
629 ALOGV("%s callback %p", __func__, callback.get());
630 std::lock_guard lock(mLock);
631 if (!mSupportsHeadTracking) {
632 return binderStatusFromStatusT(INVALID_OPERATION);
633 }
634 mHeadTrackingCallback = callback;
635 return Status::ok();
636}
637
Eric Laurentc87402b2021-09-17 16:49:42 +0200638Status Spatializer::setParameter(int key, const std::vector<unsigned char>& value) {
639 ALOGV("%s key %d", __func__, key);
640 std::lock_guard lock(mLock);
641 status_t status = INVALID_OPERATION;
642 if (mEngine != nullptr) {
643 status = setEffectParameter_l(key, value);
644 }
645 return binderStatusFromStatusT(status);
646}
647
648Status Spatializer::getParameter(int key, std::vector<unsigned char> *value) {
Greg Kaiserf7249f82021-09-21 07:10:12 -0700649 ALOGV("%s key %d value size %d", __func__, key,
650 (value != nullptr ? (int)value->size() : -1));
Eric Laurentc87402b2021-09-17 16:49:42 +0200651 if (value == nullptr) {
George Burgess IV22386222021-09-22 12:09:31 -0700652 return binderStatusFromStatusT(BAD_VALUE);
Eric Laurentc87402b2021-09-17 16:49:42 +0200653 }
654 std::lock_guard lock(mLock);
655 status_t status = INVALID_OPERATION;
656 if (mEngine != nullptr) {
657 ALOGV("%s key %d mEngine %p", __func__, key, mEngine.get());
658 status = getEffectParameter_l(key, value);
659 }
660 return binderStatusFromStatusT(status);
661}
662
663Status Spatializer::getOutput(int *output) {
664 ALOGV("%s", __func__);
665 if (output == nullptr) {
666 binderStatusFromStatusT(BAD_VALUE);
667 }
668 std::lock_guard lock(mLock);
669 *output = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_io_handle_t_int32_t(mOutput));
670 ALOGV("%s got output %d", __func__, *output);
671 return Status::ok();
672}
673
Eric Laurent2be8b292021-08-23 09:44:33 -0700674// SpatializerPoseController::Listener
675void Spatializer::onHeadToStagePose(const Pose3f& headToStage) {
676 ALOGV("%s", __func__);
Eric Laurent780be4a2021-09-16 10:44:24 +0200677 LOG_ALWAYS_FATAL_IF(!mSupportsHeadTracking,
678 "onHeadToStagePose() called with no head tracking support!");
679
Eric Laurent2be8b292021-08-23 09:44:33 -0700680 auto vec = headToStage.toVector();
Eric Laurent8a4259f2021-09-14 16:04:00 +0200681 LOG_ALWAYS_FATAL_IF(vec.size() != sHeadPoseKeys.size(),
682 "%s invalid head to stage vector size %zu", __func__, vec.size());
Eric Laurent8a4259f2021-09-14 16:04:00 +0200683 sp<AMessage> msg =
684 new AMessage(EngineCallbackHandler::kWhatOnHeadToStagePose, mHandler);
685 for (size_t i = 0 ; i < sHeadPoseKeys.size(); i++) {
686 msg->setFloat(sHeadPoseKeys[i], vec[i]);
687 }
688 msg->post();
689}
690
691void Spatializer::onHeadToStagePoseMsg(const std::vector<float>& headToStage) {
692 ALOGV("%s", __func__);
Eric Laurent67816e32021-09-16 15:18:40 +0200693 sp<media::ISpatializerHeadTrackingCallback> callback;
Eric Laurent2be8b292021-08-23 09:44:33 -0700694 {
695 std::lock_guard lock(mLock);
Eric Laurent67816e32021-09-16 15:18:40 +0200696 callback = mHeadTrackingCallback;
Eric Laurent2be8b292021-08-23 09:44:33 -0700697 if (mEngine != nullptr) {
Eric Laurent8a4259f2021-09-14 16:04:00 +0200698 setEffectParameter_l(SPATIALIZER_PARAM_HEAD_TO_STAGE, headToStage);
Shunkai Yao7de40382022-08-25 00:44:04 +0000699 mPoseRecorder.record(headToStage);
700 mPoseDurableRecorder.record(headToStage);
Eric Laurent2be8b292021-08-23 09:44:33 -0700701 }
702 }
703
704 if (callback != nullptr) {
Eric Laurent8a4259f2021-09-14 16:04:00 +0200705 callback->onHeadToSoundStagePoseUpdated(headToStage);
Eric Laurent2be8b292021-08-23 09:44:33 -0700706 }
707}
708
709void Spatializer::onActualModeChange(HeadTrackingMode mode) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000710 std::string modeStr = SpatializerPoseController::toString(mode);
711 ALOGV("%s(%s)", __func__, modeStr.c_str());
712 mLocalLog.log("%s with %s", __func__, modeStr.c_str());
Eric Laurent8a4259f2021-09-14 16:04:00 +0200713 sp<AMessage> msg =
714 new AMessage(EngineCallbackHandler::kWhatOnActualModeChange, mHandler);
715 msg->setInt32(EngineCallbackHandler::kModeKey, static_cast<int>(mode));
716 msg->post();
717}
718
719void Spatializer::onActualModeChangeMsg(HeadTrackingMode mode) {
720 ALOGV("%s(%d)", __func__, (int) mode);
Eric Laurent67816e32021-09-16 15:18:40 +0200721 sp<media::ISpatializerHeadTrackingCallback> callback;
Eric Laurent2be8b292021-08-23 09:44:33 -0700722 SpatializerHeadTrackingMode spatializerMode;
723 {
724 std::lock_guard lock(mLock);
725 if (!mSupportsHeadTracking) {
726 spatializerMode = SpatializerHeadTrackingMode::DISABLED;
727 } else {
728 switch (mode) {
729 case HeadTrackingMode::STATIC:
730 spatializerMode = SpatializerHeadTrackingMode::DISABLED;
731 break;
732 case HeadTrackingMode::WORLD_RELATIVE:
733 spatializerMode = SpatializerHeadTrackingMode::RELATIVE_WORLD;
734 break;
735 case HeadTrackingMode::SCREEN_RELATIVE:
736 spatializerMode = SpatializerHeadTrackingMode::RELATIVE_SCREEN;
737 break;
738 default:
739 LOG_ALWAYS_FATAL("Unknown mode: %d", mode);
740 }
741 }
742 mActualHeadTrackingMode = spatializerMode;
Eric Laurente51f80e2022-04-14 10:20:38 +0200743 if (mEngine != nullptr) {
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200744 setEffectParameter_l(SPATIALIZER_PARAM_HEADTRACKING_MODE,
745 std::vector<SpatializerHeadTrackingMode>{spatializerMode});
746 }
Eric Laurent67816e32021-09-16 15:18:40 +0200747 callback = mHeadTrackingCallback;
Shunkai Yao5a251df2022-07-22 18:42:27 +0000748 mLocalLog.log("%s: %s, spatializerMode %s", __func__,
749 SpatializerPoseController::toString(mode).c_str(),
750 media::toString(spatializerMode).c_str());
Eric Laurent2be8b292021-08-23 09:44:33 -0700751 }
Eric Laurente51f80e2022-04-14 10:20:38 +0200752 if (callback != nullptr) {
Eric Laurent2be8b292021-08-23 09:44:33 -0700753 callback->onHeadTrackingModeChanged(spatializerMode);
754 }
755}
756
Eric Laurent15903592022-02-24 20:44:36 +0100757status_t Spatializer::attachOutput(audio_io_handle_t output, size_t numActiveTracks) {
Eric Laurent4a872862021-10-11 17:06:47 +0200758 bool outputChanged = false;
759 sp<media::INativeSpatializerCallback> callback;
760
Eric Laurent2be8b292021-08-23 09:44:33 -0700761 {
762 std::lock_guard lock(mLock);
763 ALOGV("%s output %d mOutput %d", __func__, (int)output, (int)mOutput);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000764 mLocalLog.log("%s with output %d tracks %zu (mOutput %d)", __func__, (int)output,
765 numActiveTracks, (int)mOutput);
Eric Laurent2be8b292021-08-23 09:44:33 -0700766 if (mOutput != AUDIO_IO_HANDLE_NONE) {
767 LOG_ALWAYS_FATAL_IF(mEngine == nullptr, "%s output set without FX engine", __func__);
768 // remove FX instance
769 mEngine->setEnabled(false);
770 mEngine.clear();
Eric Laurent15903592022-02-24 20:44:36 +0100771 mPoseController.reset();
Eric Laurent2be8b292021-08-23 09:44:33 -0700772 }
773 // create FX instance on output
774 AttributionSourceState attributionSource = AttributionSourceState();
775 mEngine = new AudioEffect(attributionSource);
776 mEngine->set(nullptr, &mEngineDescriptor.uuid, 0, Spatializer::engineCallback /* cbf */,
777 this /* user */, AUDIO_SESSION_OUTPUT_STAGE, output, {} /* device */,
778 false /* probe */, true /* notifyFramesProcessed */);
779 status_t status = mEngine->initCheck();
780 ALOGV("%s mEngine create status %d", __func__, (int)status);
781 if (status != NO_ERROR) {
782 return status;
783 }
784
Eric Laurent4a872862021-10-11 17:06:47 +0200785 outputChanged = mOutput != output;
Eric Laurent2be8b292021-08-23 09:44:33 -0700786 mOutput = output;
Eric Laurent11094172022-04-05 18:27:42 +0200787 mNumActiveTracks = numActiveTracks;
Eric Laurent2be8b292021-08-23 09:44:33 -0700788
Eric Laurent11094172022-04-05 18:27:42 +0200789 checkEngineState_l();
Eric Laurent780be4a2021-09-16 10:44:24 +0200790 if (mSupportsHeadTracking) {
Eric Laurent11094172022-04-05 18:27:42 +0200791 checkPoseController_l();
Eric Laurent9249d342022-03-18 11:55:56 +0100792 checkSensorsState_l();
Eric Laurent780be4a2021-09-16 10:44:24 +0200793 }
Eric Laurent4a872862021-10-11 17:06:47 +0200794 callback = mSpatializerCallback;
Eric Laurent6d607012021-07-05 11:54:40 +0200795 }
Eric Laurent4a872862021-10-11 17:06:47 +0200796
797 if (outputChanged && callback != nullptr) {
798 callback->onOutputChanged(output);
799 }
800
Eric Laurent6d607012021-07-05 11:54:40 +0200801 return NO_ERROR;
802}
803
804audio_io_handle_t Spatializer::detachOutput() {
Eric Laurent2be8b292021-08-23 09:44:33 -0700805 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent4a872862021-10-11 17:06:47 +0200806 sp<media::INativeSpatializerCallback> callback;
807
808 {
809 std::lock_guard lock(mLock);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000810 mLocalLog.log("%s with output %d tracks %zu", __func__, (int)mOutput, mNumActiveTracks);
Eric Laurent4a872862021-10-11 17:06:47 +0200811 ALOGV("%s mOutput %d", __func__, (int)mOutput);
812 if (mOutput == AUDIO_IO_HANDLE_NONE) {
813 return output;
814 }
815 // remove FX instance
816 mEngine->setEnabled(false);
817 mEngine.clear();
818 output = mOutput;
819 mOutput = AUDIO_IO_HANDLE_NONE;
820 mPoseController.reset();
Eric Laurent4a872862021-10-11 17:06:47 +0200821 callback = mSpatializerCallback;
Eric Laurent6d607012021-07-05 11:54:40 +0200822 }
Eric Laurent4a872862021-10-11 17:06:47 +0200823
824 if (callback != nullptr) {
825 callback->onOutputChanged(AUDIO_IO_HANDLE_NONE);
826 }
Eric Laurent6d607012021-07-05 11:54:40 +0200827 return output;
828}
829
Eric Laurent15903592022-02-24 20:44:36 +0100830void Spatializer::updateActiveTracks(size_t numActiveTracks) {
831 std::lock_guard lock(mLock);
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200832 if (mNumActiveTracks != numActiveTracks) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000833 mLocalLog.log("%s from %zu to %zu", __func__, mNumActiveTracks, numActiveTracks);
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200834 mNumActiveTracks = numActiveTracks;
835 checkEngineState_l();
836 checkSensorsState_l();
837 }
Eric Laurent15903592022-02-24 20:44:36 +0100838}
839
Eric Laurent9249d342022-03-18 11:55:56 +0100840void Spatializer::checkSensorsState_l() {
Eric Laurent15903592022-02-24 20:44:36 +0100841 if (mSupportsHeadTracking && mPoseController != nullptr) {
Eric Laurent9249d342022-03-18 11:55:56 +0100842 if (mNumActiveTracks > 0 && mLevel != SpatializationLevel::NONE
Eric Laurent15903592022-02-24 20:44:36 +0100843 && mDesiredHeadTrackingMode != HeadTrackingMode::STATIC
844 && mHeadSensor != SpatializerPoseController::INVALID_SENSOR) {
845 mPoseController->setHeadSensor(mHeadSensor);
Eric Laurent9249d342022-03-18 11:55:56 +0100846 mPoseController->setScreenSensor(mScreenSensor);
Eric Laurent15903592022-02-24 20:44:36 +0100847 } else {
848 mPoseController->setHeadSensor(SpatializerPoseController::INVALID_SENSOR);
Eric Laurent9249d342022-03-18 11:55:56 +0100849 mPoseController->setScreenSensor(SpatializerPoseController::INVALID_SENSOR);
Eric Laurent15903592022-02-24 20:44:36 +0100850 }
851 }
852}
853
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200854void Spatializer::checkEngineState_l() {
855 if (mEngine != nullptr) {
856 if (mLevel != SpatializationLevel::NONE && mNumActiveTracks > 0) {
857 mEngine->setEnabled(true);
858 setEffectParameter_l(SPATIALIZER_PARAM_LEVEL,
859 std::vector<SpatializationLevel>{mLevel});
860 setEffectParameter_l(SPATIALIZER_PARAM_HEADTRACKING_MODE,
861 std::vector<SpatializerHeadTrackingMode>{mActualHeadTrackingMode});
862 } else {
863 setEffectParameter_l(SPATIALIZER_PARAM_LEVEL,
864 std::vector<SpatializationLevel>{SpatializationLevel::NONE});
865 mEngine->setEnabled(false);
866 }
867 }
868}
869
Eric Laurent11094172022-04-05 18:27:42 +0200870void Spatializer::checkPoseController_l() {
871 bool isControllerNeeded = mDesiredHeadTrackingMode != HeadTrackingMode::STATIC
872 && mHeadSensor != SpatializerPoseController::INVALID_SENSOR;
873
874 if (isControllerNeeded && mPoseController == nullptr) {
875 mPoseController = std::make_shared<SpatializerPoseController>(
876 static_cast<SpatializerPoseController::Listener*>(this),
Eric Laurente51f80e2022-04-14 10:20:38 +0200877 10ms, std::nullopt);
Eric Laurent11094172022-04-05 18:27:42 +0200878 LOG_ALWAYS_FATAL_IF(mPoseController == nullptr,
879 "%s could not allocate pose controller", __func__);
880 mPoseController->setDisplayOrientation(mDisplayOrientation);
881 } else if (!isControllerNeeded && mPoseController != nullptr) {
882 mPoseController.reset();
883 }
884 if (mPoseController != nullptr) {
885 mPoseController->setDesiredMode(mDesiredHeadTrackingMode);
886 }
887}
888
Eric Laurent2be8b292021-08-23 09:44:33 -0700889void Spatializer::calculateHeadPose() {
890 ALOGV("%s", __func__);
891 std::lock_guard lock(mLock);
892 if (mPoseController != nullptr) {
893 mPoseController->calculateAsync();
894 }
895}
Eric Laurent6d607012021-07-05 11:54:40 +0200896
Eric Laurent2be8b292021-08-23 09:44:33 -0700897void Spatializer::engineCallback(int32_t event, void *user, void *info) {
Eric Laurent6d607012021-07-05 11:54:40 +0200898 if (user == nullptr) {
899 return;
900 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700901 Spatializer* const me = reinterpret_cast<Spatializer *>(user);
Eric Laurent6d607012021-07-05 11:54:40 +0200902 switch (event) {
903 case AudioEffect::EVENT_FRAMES_PROCESSED: {
Eric Laurent2be8b292021-08-23 09:44:33 -0700904 int frames = info == nullptr ? 0 : *(int*)info;
Eric Laurent9249d342022-03-18 11:55:56 +0100905 ALOGV("%s frames processed %d for me %p", __func__, frames, me);
Eric Laurent8a4259f2021-09-14 16:04:00 +0200906 me->postFramesProcessedMsg(frames);
Eric Laurent2be8b292021-08-23 09:44:33 -0700907 } break;
Eric Laurent6d607012021-07-05 11:54:40 +0200908 default:
Eric Laurent9249d342022-03-18 11:55:56 +0100909 ALOGV("%s event %d", __func__, event);
Eric Laurent6d607012021-07-05 11:54:40 +0200910 break;
911 }
912}
913
Eric Laurent8a4259f2021-09-14 16:04:00 +0200914void Spatializer::postFramesProcessedMsg(int frames) {
915 sp<AMessage> msg =
916 new AMessage(EngineCallbackHandler::kWhatOnFramesProcessed, mHandler);
917 msg->setInt32(EngineCallbackHandler::kNumFramesKey, frames);
918 msg->post();
919}
920
Shunkai Yao5a251df2022-07-22 18:42:27 +0000921std::string Spatializer::toString(unsigned level) const {
922 std::string prefixSpace;
923 prefixSpace.append(level, ' ');
924 std::string ss = prefixSpace + "Spatializer:\n";
925 bool needUnlock = false;
926
927 prefixSpace += ' ';
928 if (!mLock.try_lock()) {
929 // dumpsys even try_lock failed, information dump can be useful although may not accurate
930 ss.append(prefixSpace).append("try_lock failed, dumpsys below maybe INACCURATE!\n");
931 } else {
932 needUnlock = true;
933 }
934
935 // Spatializer class information.
936 // 1. Capabilities (mLevels, mHeadTrackingModes, mSpatializationModes, mChannelMasks, etc)
937 ss.append(prefixSpace).append("Supported levels: [");
938 for (auto& level : mLevels) {
939 base::StringAppendF(&ss, " %s", media::toString(level).c_str());
940 }
941 base::StringAppendF(&ss, "], mLevel: %s", media::toString(mLevel).c_str());
942
943 base::StringAppendF(&ss, "\n%smHeadTrackingModes: [", prefixSpace.c_str());
944 for (auto& mode : mHeadTrackingModes) {
945 base::StringAppendF(&ss, " %s", media::toString(mode).c_str());
946 }
947 base::StringAppendF(&ss, "], Desired: %s, Actual %s\n",
948 SpatializerPoseController::toString(mDesiredHeadTrackingMode).c_str(),
949 media::toString(mActualHeadTrackingMode).c_str());
950
951 base::StringAppendF(&ss, "%smSpatializationModes: [", prefixSpace.c_str());
952 for (auto& mode : mSpatializationModes) {
953 base::StringAppendF(&ss, " %s", media::toString(mode).c_str());
954 }
955 ss += "]\n";
956
957 base::StringAppendF(&ss, "%smChannelMasks: ", prefixSpace.c_str());
958 for (auto& mask : mChannelMasks) {
959 base::StringAppendF(&ss, "%s", audio_channel_out_mask_to_string(mask));
960 }
961 base::StringAppendF(&ss, "\n%smSupportsHeadTracking: %s\n", prefixSpace.c_str(),
962 mSupportsHeadTracking ? "true" : "false");
963 // 2. Settings (Output, tracks)
964 base::StringAppendF(&ss, "%smNumActiveTracks: %zu\n", prefixSpace.c_str(), mNumActiveTracks);
965 base::StringAppendF(&ss, "%sOutputStreamHandle: %d\n", prefixSpace.c_str(), (int)mOutput);
966
967 // 3. Sensors, Effect information.
968 base::StringAppendF(&ss, "%sHeadSensorHandle: 0x%08x\n", prefixSpace.c_str(), mHeadSensor);
969 base::StringAppendF(&ss, "%sScreenSensorHandle: 0x%08x\n", prefixSpace.c_str(), mScreenSensor);
970 base::StringAppendF(&ss, "%sEffectHandle: %p\n", prefixSpace.c_str(), mEngine.get());
971 base::StringAppendF(&ss, "%sDisplayOrientation: %f\n", prefixSpace.c_str(),
972 mDisplayOrientation);
973
974 ss.append(prefixSpace + "CommandLog:\n");
975 ss += mLocalLog.dumpToString((prefixSpace + " ").c_str(), mMaxLocalLogLine);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000976
977 // PostController dump.
978 if (mPoseController != nullptr) {
979 ss += mPoseController->toString(level + 1);
Shunkai Yao7de40382022-08-25 00:44:04 +0000980 ss.append(prefixSpace +
981 "Sensor data format - [rx, ry, rz, vx, vy, vz] (units-degree, "
982 "r-transform, v-angular velocity, x-pitch, y-roll, z-yaw):\n");
983 ss.append(prefixSpace + "PerMinuteHistory:\n");
984 ss += mPoseDurableRecorder.toString(level + 1);
985 ss.append(prefixSpace + "PerSecondHistory:\n");
986 ss += mPoseRecorder.toString(level + 1);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000987 } else {
988 ss.append(prefixSpace).append("SpatializerPoseController not exist\n");
989 }
990
991 if (needUnlock) {
992 mLock.unlock();
993 }
994 return ss;
995}
996
Eric Laurent6d607012021-07-05 11:54:40 +0200997} // namespace android