blob: 08c974dce385d8194387743082d0cd5dc027bbd3 [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
Andy Hungcd6c1062023-03-09 20:45:36 -080023#include <algorithm>
Shunkai Yao5a251df2022-07-22 18:42:27 +000024#include <inttypes.h>
Eric Laurent6d607012021-07-05 11:54:40 +020025#include <limits.h>
26#include <stdint.h>
27#include <sys/types.h>
28
29#include <android/content/AttributionSourceState.h>
30#include <audio_utils/fixedfft.h>
31#include <cutils/bitops.h>
Eric Laurent2be8b292021-08-23 09:44:33 -070032#include <hardware/sensors.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>
Andy Hung2a390db2023-01-30 11:58:44 -080036#include <media/QuaternionUtil.h>
Eric Laurent8a4259f2021-09-14 16:04:00 +020037#include <media/ShmemCompat.h>
Andy Hungb725c692022-12-14 14:25:49 -080038#include <mediautils/SchedulingPolicyService.h>
Eric Laurent6d607012021-07-05 11:54:40 +020039#include <mediautils/ServiceUtilities.h>
40#include <utils/Thread.h>
41
42#include "Spatializer.h"
43
44namespace android {
45
46using aidl_utils::statusTFromBinderStatus;
47using aidl_utils::binderStatusFromStatusT;
48using android::content::AttributionSourceState;
49using binder::Status;
Eric Laurent2be8b292021-08-23 09:44:33 -070050using media::HeadTrackingMode;
51using media::Pose3f;
Eric Laurent6d607012021-07-05 11:54:40 +020052using media::SpatializationLevel;
Eric Laurent2be8b292021-08-23 09:44:33 -070053using media::SpatializationMode;
Ytai Ben-Tsvia16a9df2021-08-05 08:57:06 -070054using media::SpatializerHeadTrackingMode;
Eric Laurent2be8b292021-08-23 09:44:33 -070055using media::SensorPoseProvider;
56
Eric Laurent2be8b292021-08-23 09:44:33 -070057using namespace std::chrono_literals;
Eric Laurent6d607012021-07-05 11:54:40 +020058
59#define VALUE_OR_RETURN_BINDER_STATUS(x) \
60 ({ auto _tmp = (x); \
61 if (!_tmp.ok()) return aidl_utils::binderStatusFromStatusT(_tmp.error()); \
62 std::move(_tmp.value()); })
63
Andy Hung0e3205d2022-08-29 14:14:58 -070064static audio_channel_mask_t getMaxChannelMask(
65 const std::vector<audio_channel_mask_t>& masks, size_t channelLimit = SIZE_MAX) {
Andy Hunga461a002022-05-17 10:36:02 -070066 uint32_t maxCount = 0;
67 audio_channel_mask_t maxMask = AUDIO_CHANNEL_NONE;
68 for (auto mask : masks) {
69 const size_t count = audio_channel_count_from_out_mask(mask);
Andy Hung0e3205d2022-08-29 14:14:58 -070070 if (count > channelLimit) continue; // ignore masks greater than channelLimit
Andy Hunga461a002022-05-17 10:36:02 -070071 if (count > maxCount) {
72 maxMask = mask;
73 maxCount = count;
74 }
75 }
76 return maxMask;
77}
78
Andy Hung2a390db2023-01-30 11:58:44 -080079static std::vector<float> recordFromTranslationRotationVector(
80 const std::vector<float>& trVector) {
81 auto headToStageOpt = Pose3f::fromVector(trVector);
82 if (!headToStageOpt) return {};
83
84 const auto stageToHead = headToStageOpt.value().inverse();
85 const auto stageToHeadTranslation = stageToHead.translation();
Andy Hung82a4eab2023-01-30 11:58:44 -080086 constexpr float RAD_TO_DEGREE = 180.f / M_PI;
87 std::vector<float> record{
Andy Hung2a390db2023-01-30 11:58:44 -080088 stageToHeadTranslation[0], stageToHeadTranslation[1], stageToHeadTranslation[2],
89 0.f, 0.f, 0.f};
90 media::quaternionToAngles(stageToHead.rotation(), &record[3], &record[4], &record[5]);
91 record[3] *= RAD_TO_DEGREE;
92 record[4] *= RAD_TO_DEGREE;
93 record[5] *= RAD_TO_DEGREE;
Andy Hung82a4eab2023-01-30 11:58:44 -080094 return record;
95}
96
Andy Hungcd6c1062023-03-09 20:45:36 -080097template<typename T>
98static constexpr const T& safe_clamp(const T& value, const T& low, const T& high) {
99 if constexpr (std::is_floating_point_v<T>) {
100 return value != value /* constexpr isnan */
101 ? low : std::clamp(value, low, high);
102 } else /* constexpr */ {
103 return std::clamp(value, low, high);
104 }
105}
106
Eric Laurent6d607012021-07-05 11:54:40 +0200107// ---------------------------------------------------------------------------
108
Eric Laurent8a4259f2021-09-14 16:04:00 +0200109class Spatializer::EngineCallbackHandler : public AHandler {
110public:
111 EngineCallbackHandler(wp<Spatializer> spatializer)
112 : mSpatializer(spatializer) {
113 }
114
115 enum {
116 // Device state callbacks
117 kWhatOnFramesProcessed, // AudioEffect::EVENT_FRAMES_PROCESSED
118 kWhatOnHeadToStagePose, // SpatializerPoseController::Listener::onHeadToStagePose
119 kWhatOnActualModeChange, // SpatializerPoseController::Listener::onActualModeChange
Eric Laurentdf2ece42022-07-20 13:49:47 +0200120 kWhatOnLatencyModesChanged, // Spatializer::onSupportedLatencyModesChanged
Eric Laurent8a4259f2021-09-14 16:04:00 +0200121 };
122 static constexpr const char *kNumFramesKey = "numFrames";
123 static constexpr const char *kModeKey = "mode";
124 static constexpr const char *kTranslation0Key = "translation0";
125 static constexpr const char *kTranslation1Key = "translation1";
126 static constexpr const char *kTranslation2Key = "translation2";
127 static constexpr const char *kRotation0Key = "rotation0";
128 static constexpr const char *kRotation1Key = "rotation1";
129 static constexpr const char *kRotation2Key = "rotation2";
Eric Laurentdf2ece42022-07-20 13:49:47 +0200130 static constexpr const char *kLatencyModesKey = "latencyModes";
131
132 class LatencyModes : public RefBase {
133 public:
134 LatencyModes(audio_io_handle_t output,
135 const std::vector<audio_latency_mode_t>& latencyModes)
136 : mOutput(output), mLatencyModes(latencyModes) {}
137 ~LatencyModes() = default;
138
139 audio_io_handle_t mOutput;
140 std::vector<audio_latency_mode_t> mLatencyModes;
141 };
Eric Laurent8a4259f2021-09-14 16:04:00 +0200142
143 void onMessageReceived(const sp<AMessage> &msg) override {
Andy Hungb725c692022-12-14 14:25:49 -0800144 // No ALooper method to get the tid so update
145 // Spatializer priority on the first message received.
146 std::call_once(mPrioritySetFlag, [](){
147 const pid_t pid = getpid();
148 const pid_t tid = gettid();
149 (void)requestSpatializerPriority(pid, tid);
150 });
151
Eric Laurentdf2ece42022-07-20 13:49:47 +0200152 sp<Spatializer> spatializer = mSpatializer.promote();
153 if (spatializer == nullptr) {
154 ALOGW("%s: Cannot promote spatializer", __func__);
155 return;
156 }
Eric Laurent8a4259f2021-09-14 16:04:00 +0200157 switch (msg->what()) {
158 case kWhatOnFramesProcessed: {
Eric Laurent8a4259f2021-09-14 16:04:00 +0200159 int numFrames;
160 if (!msg->findInt32(kNumFramesKey, &numFrames)) {
161 ALOGE("%s: Cannot find num frames!", __func__);
162 return;
163 }
164 if (numFrames > 0) {
165 spatializer->calculateHeadPose();
166 }
167 } break;
168 case kWhatOnHeadToStagePose: {
Eric Laurent8a4259f2021-09-14 16:04:00 +0200169 std::vector<float> headToStage(sHeadPoseKeys.size());
170 for (size_t i = 0 ; i < sHeadPoseKeys.size(); i++) {
171 if (!msg->findFloat(sHeadPoseKeys[i], &headToStage[i])) {
172 ALOGE("%s: Cannot find kTranslation0Key!", __func__);
173 return;
174 }
175 }
176 spatializer->onHeadToStagePoseMsg(headToStage);
177 } break;
178 case kWhatOnActualModeChange: {
Eric Laurent8a4259f2021-09-14 16:04:00 +0200179 int mode;
Eric Laurentdf2ece42022-07-20 13:49:47 +0200180 if (!msg->findInt32(kModeKey, &mode)) {
Eric Laurent8a4259f2021-09-14 16:04:00 +0200181 ALOGE("%s: Cannot find actualMode!", __func__);
182 return;
183 }
184 spatializer->onActualModeChangeMsg(static_cast<HeadTrackingMode>(mode));
185 } break;
Eric Laurentdf2ece42022-07-20 13:49:47 +0200186
187 case kWhatOnLatencyModesChanged: {
188 sp<RefBase> object;
189 if (!msg->findObject(kLatencyModesKey, &object)) {
190 ALOGE("%s: Cannot find latency modes!", __func__);
191 return;
192 }
193 sp<LatencyModes> latencyModes = static_cast<LatencyModes*>(object.get());
194 spatializer->onSupportedLatencyModesChangedMsg(
195 latencyModes->mOutput, std::move(latencyModes->mLatencyModes));
196 } break;
197
Eric Laurent8a4259f2021-09-14 16:04:00 +0200198 default:
199 LOG_ALWAYS_FATAL("Invalid callback message %d", msg->what());
200 }
201 }
202private:
203 wp<Spatializer> mSpatializer;
Andy Hungb725c692022-12-14 14:25:49 -0800204 std::once_flag mPrioritySetFlag;
Eric Laurent8a4259f2021-09-14 16:04:00 +0200205};
206
207const std::vector<const char *> Spatializer::sHeadPoseKeys = {
208 Spatializer::EngineCallbackHandler::kTranslation0Key,
209 Spatializer::EngineCallbackHandler::kTranslation1Key,
210 Spatializer::EngineCallbackHandler::kTranslation2Key,
211 Spatializer::EngineCallbackHandler::kRotation0Key,
212 Spatializer::EngineCallbackHandler::kRotation1Key,
213 Spatializer::EngineCallbackHandler::kRotation2Key,
214};
215
216// ---------------------------------------------------------------------------
Shunkai Yao8f6ad0f2023-04-18 23:14:25 +0000217sp<Spatializer> Spatializer::create(SpatializerPolicyCallback* callback,
218 const sp<EffectsFactoryHalInterface>& effectsFactoryHal) {
Eric Laurent6d607012021-07-05 11:54:40 +0200219 sp<Spatializer> spatializer;
220
Eric Laurent6d607012021-07-05 11:54:40 +0200221 if (effectsFactoryHal == nullptr) {
222 ALOGW("%s failed to create effect factory interface", __func__);
223 return spatializer;
224 }
225
226 std::vector<effect_descriptor_t> descriptors;
Shunkai Yao8f6ad0f2023-04-18 23:14:25 +0000227 status_t status = effectsFactoryHal->getDescriptors(FX_IID_SPATIALIZER, &descriptors);
Eric Laurent6d607012021-07-05 11:54:40 +0200228 if (status != NO_ERROR) {
229 ALOGW("%s failed to get spatializer descriptor, error %d", __func__, status);
230 return spatializer;
231 }
232 ALOG_ASSERT(!descriptors.empty(),
233 "%s getDescriptors() returned no error but empty list", __func__);
234
Shunkai Yao5a251df2022-07-22 18:42:27 +0000235 // TODO: get supported spatialization modes from FX engine or descriptor
Eric Laurent6d607012021-07-05 11:54:40 +0200236 sp<EffectHalInterface> effect;
237 status = effectsFactoryHal->createEffect(&descriptors[0].uuid, AUDIO_SESSION_OUTPUT_STAGE,
238 AUDIO_IO_HANDLE_NONE, AUDIO_PORT_HANDLE_NONE, &effect);
Mikhail Naganov89c22e42023-06-14 15:49:59 -0700239 ALOGI("%s FX create status %d effect %p", __func__, status, effect.get());
Eric Laurent6d607012021-07-05 11:54:40 +0200240
241 if (status == NO_ERROR && effect != nullptr) {
242 spatializer = new Spatializer(descriptors[0], callback);
Eric Laurent2be8b292021-08-23 09:44:33 -0700243 if (spatializer->loadEngineConfiguration(effect) != NO_ERROR) {
244 spatializer.clear();
Mikhail Naganov89c22e42023-06-14 15:49:59 -0700245 ALOGW("%s loadEngine error: %d effect %p", __func__, status, effect.get());
Andy Hung0e3205d2022-08-29 14:14:58 -0700246 } else {
Mikhail Naganov89c22e42023-06-14 15:49:59 -0700247 spatializer->mLocalLog.log("%s with effect Id %p", __func__, effect.get());
Eric Laurent2be8b292021-08-23 09:44:33 -0700248 }
Eric Laurent6d607012021-07-05 11:54:40 +0200249 }
250
251 return spatializer;
252}
253
Eric Laurent2be8b292021-08-23 09:44:33 -0700254Spatializer::Spatializer(effect_descriptor_t engineDescriptor, SpatializerPolicyCallback* callback)
255 : mEngineDescriptor(engineDescriptor),
256 mPolicyCallback(callback) {
Eric Laurent6d607012021-07-05 11:54:40 +0200257 ALOGV("%s", __func__);
Andy Hung393de3a2022-12-06 16:33:20 -0800258 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Eric Laurent6d607012021-07-05 11:54:40 +0200259}
260
Eric Laurent8a4259f2021-09-14 16:04:00 +0200261void Spatializer::onFirstRef() {
262 mLooper = new ALooper;
263 mLooper->setName("Spatializer-looper");
264 mLooper->start(
265 /*runOnCallingThread*/false,
266 /*canCallJava*/ false,
Andy Hung898a39f2022-11-07 20:09:20 -0800267 PRIORITY_URGENT_AUDIO);
Eric Laurent8a4259f2021-09-14 16:04:00 +0200268
269 mHandler = new EngineCallbackHandler(this);
270 mLooper->registerHandler(mHandler);
271}
272
Eric Laurent6d607012021-07-05 11:54:40 +0200273Spatializer::~Spatializer() {
274 ALOGV("%s", __func__);
Eric Laurent8a4259f2021-09-14 16:04:00 +0200275 if (mLooper != nullptr) {
276 mLooper->stop();
277 mLooper->unregisterHandler(mHandler->id());
278 }
279 mLooper.clear();
280 mHandler.clear();
Eric Laurent6d607012021-07-05 11:54:40 +0200281}
282
Andy Hung4442d042022-08-17 17:27:32 -0700283static std::string channelMaskVectorToString(
284 const std::vector<audio_channel_mask_t>& masks) {
285 std::stringstream ss;
286 for (const auto &mask : masks) {
287 if (ss.tellp() != 0) ss << "|";
288 ss << mask;
289 }
290 return ss.str();
291}
292
Eric Laurent2be8b292021-08-23 09:44:33 -0700293status_t Spatializer::loadEngineConfiguration(sp<EffectHalInterface> effect) {
294 ALOGV("%s", __func__);
295
296 std::vector<bool> supportsHeadTracking;
297 status_t status = getHalParameter<false>(effect, SPATIALIZER_PARAM_HEADTRACKING_SUPPORTED,
298 &supportsHeadTracking);
299 if (status != NO_ERROR) {
Andy Hung119dbdb2022-05-11 19:20:13 -0700300 ALOGW("%s: cannot get SPATIALIZER_PARAM_HEADTRACKING_SUPPORTED", __func__);
Eric Laurent2be8b292021-08-23 09:44:33 -0700301 return status;
302 }
303 mSupportsHeadTracking = supportsHeadTracking[0];
304
Andy Hung119dbdb2022-05-11 19:20:13 -0700305 std::vector<media::SpatializationLevel> spatializationLevels;
306 status = getHalParameter<true>(effect, SPATIALIZER_PARAM_SUPPORTED_LEVELS,
307 &spatializationLevels);
Eric Laurent2be8b292021-08-23 09:44:33 -0700308 if (status != NO_ERROR) {
Andy Hung119dbdb2022-05-11 19:20:13 -0700309 ALOGW("%s: cannot get SPATIALIZER_PARAM_SUPPORTED_LEVELS", __func__);
Eric Laurent2be8b292021-08-23 09:44:33 -0700310 return status;
311 }
Andy Hung119dbdb2022-05-11 19:20:13 -0700312 bool noneLevelFound = false;
313 bool activeLevelFound = false;
314 for (const auto spatializationLevel : spatializationLevels) {
315 if (!aidl_utils::isValidEnum(spatializationLevel)) {
316 ALOGW("%s: ignoring spatializationLevel:%d", __func__, (int)spatializationLevel);
317 continue;
318 }
319 if (spatializationLevel == media::SpatializationLevel::NONE) {
320 noneLevelFound = true;
321 } else {
322 activeLevelFound = true;
323 }
324 // we don't detect duplicates.
325 mLevels.emplace_back(spatializationLevel);
326 }
327 if (!noneLevelFound || !activeLevelFound) {
328 ALOGW("%s: SPATIALIZER_PARAM_SUPPORTED_LEVELS must include NONE"
329 " and another valid level", __func__);
330 return BAD_VALUE;
331 }
332
333 std::vector<media::SpatializationMode> spatializationModes;
Eric Laurent2be8b292021-08-23 09:44:33 -0700334 status = getHalParameter<true>(effect, SPATIALIZER_PARAM_SUPPORTED_SPATIALIZATION_MODES,
Andy Hung119dbdb2022-05-11 19:20:13 -0700335 &spatializationModes);
Eric Laurent2be8b292021-08-23 09:44:33 -0700336 if (status != NO_ERROR) {
Andy Hung119dbdb2022-05-11 19:20:13 -0700337 ALOGW("%s: cannot get SPATIALIZER_PARAM_SUPPORTED_SPATIALIZATION_MODES", __func__);
Eric Laurent2be8b292021-08-23 09:44:33 -0700338 return status;
339 }
Shunkai Yao5a251df2022-07-22 18:42:27 +0000340
Andy Hung119dbdb2022-05-11 19:20:13 -0700341 for (const auto spatializationMode : spatializationModes) {
342 if (!aidl_utils::isValidEnum(spatializationMode)) {
343 ALOGW("%s: ignoring spatializationMode:%d", __func__, (int)spatializationMode);
344 continue;
345 }
346 // we don't detect duplicates.
347 mSpatializationModes.emplace_back(spatializationMode);
348 }
349 if (mSpatializationModes.empty()) {
350 ALOGW("%s: SPATIALIZER_PARAM_SUPPORTED_SPATIALIZATION_MODES reports empty", __func__);
351 return BAD_VALUE;
352 }
353
354 std::vector<audio_channel_mask_t> channelMasks;
355 status = getHalParameter<true>(effect, SPATIALIZER_PARAM_SUPPORTED_CHANNEL_MASKS,
356 &channelMasks);
357 if (status != NO_ERROR) {
358 ALOGW("%s: cannot get SPATIALIZER_PARAM_SUPPORTED_CHANNEL_MASKS", __func__);
359 return status;
360 }
361 for (const auto channelMask : channelMasks) {
362 if (!audio_is_channel_mask_spatialized(channelMask)) {
363 ALOGW("%s: ignoring channelMask:%#x", __func__, channelMask);
364 continue;
365 }
366 // we don't detect duplicates.
367 mChannelMasks.emplace_back(channelMask);
368 }
369 if (mChannelMasks.empty()) {
370 ALOGW("%s: SPATIALIZER_PARAM_SUPPORTED_CHANNEL_MASKS reports empty", __func__);
371 return BAD_VALUE;
372 }
Andy Hunga461a002022-05-17 10:36:02 -0700373
374 // Currently we expose only RELATIVE_WORLD.
375 // This is a limitation of the head tracking library based on a UX choice.
376 mHeadTrackingModes.push_back(SpatializerHeadTrackingMode::DISABLED);
377 if (mSupportsHeadTracking) {
378 mHeadTrackingModes.push_back(SpatializerHeadTrackingMode::RELATIVE_WORLD);
379 }
380 mediametrics::LogItem(mMetricsId)
381 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE)
Andy Hung4442d042022-08-17 17:27:32 -0700382 .set(AMEDIAMETRICS_PROP_CHANNELMASKS, channelMaskVectorToString(mChannelMasks))
Andy Hunga461a002022-05-17 10:36:02 -0700383 .set(AMEDIAMETRICS_PROP_LEVELS, aidl_utils::enumsToString(mLevels))
384 .set(AMEDIAMETRICS_PROP_MODES, aidl_utils::enumsToString(mSpatializationModes))
385 .set(AMEDIAMETRICS_PROP_HEADTRACKINGMODES, aidl_utils::enumsToString(mHeadTrackingModes))
386 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
387 .record();
Andy Hung119dbdb2022-05-11 19:20:13 -0700388 return NO_ERROR;
Eric Laurent2be8b292021-08-23 09:44:33 -0700389}
390
Andy Hung757bc812022-09-13 18:53:06 -0700391/* static */
392void Spatializer::sendEmptyCreateSpatializerMetricWithStatus(status_t status) {
393 mediametrics::LogItem(kDefaultMetricsId)
394 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CREATE)
395 .set(AMEDIAMETRICS_PROP_CHANNELMASKS, "")
396 .set(AMEDIAMETRICS_PROP_LEVELS, "")
397 .set(AMEDIAMETRICS_PROP_MODES, "")
398 .set(AMEDIAMETRICS_PROP_HEADTRACKINGMODES, "")
399 .set(AMEDIAMETRICS_PROP_STATUS, (int32_t)status)
400 .record();
401}
402
Eric Laurent2be8b292021-08-23 09:44:33 -0700403/** Gets the channel mask, sampling rate and format set for the spatializer input. */
404audio_config_base_t Spatializer::getAudioInConfig() const {
405 std::lock_guard lock(mLock);
406 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
407 // For now use highest supported channel count
Andy Hung0e3205d2022-08-29 14:14:58 -0700408 config.channel_mask = getMaxChannelMask(mChannelMasks, FCC_LIMIT);
Eric Laurent2be8b292021-08-23 09:44:33 -0700409 return config;
410}
411
Eric Laurent6d607012021-07-05 11:54:40 +0200412status_t Spatializer::registerCallback(
413 const sp<media::INativeSpatializerCallback>& callback) {
Eric Laurent2be8b292021-08-23 09:44:33 -0700414 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200415 if (callback == nullptr) {
416 return BAD_VALUE;
417 }
418
Eric Laurentb57604f2022-08-31 16:07:50 +0200419 if (mSpatializerCallback != nullptr) {
420 if (IInterface::asBinder(callback) == IInterface::asBinder(mSpatializerCallback)) {
421 ALOGW("%s: Registering callback %p again",
422 __func__, mSpatializerCallback.get());
423 return NO_ERROR;
424 }
425 ALOGE("%s: Already one client registered with callback %p",
426 __func__, mSpatializerCallback.get());
427 return INVALID_OPERATION;
428 }
429
Eric Laurent6d607012021-07-05 11:54:40 +0200430 sp<IBinder> binder = IInterface::asBinder(callback);
431 status_t status = binder->linkToDeath(this);
432 if (status == NO_ERROR) {
433 mSpatializerCallback = callback;
434 }
435 ALOGV("%s status %d", __func__, status);
436 return status;
437}
438
439// IBinder::DeathRecipient
440void Spatializer::binderDied(__unused const wp<IBinder> &who) {
441 {
Eric Laurent2be8b292021-08-23 09:44:33 -0700442 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200443 mLevel = SpatializationLevel::NONE;
444 mSpatializerCallback.clear();
445 }
446 ALOGV("%s", __func__);
447 mPolicyCallback->onCheckSpatializer();
448}
449
450// ISpatializer
451Status Spatializer::getSupportedLevels(std::vector<SpatializationLevel> *levels) {
452 ALOGV("%s", __func__);
453 if (levels == nullptr) {
454 return binderStatusFromStatusT(BAD_VALUE);
455 }
Andy Hunga461a002022-05-17 10:36:02 -0700456 // SpatializationLevel::NONE is already required from the effect or we don't load it.
Eric Laurent2be8b292021-08-23 09:44:33 -0700457 levels->insert(levels->end(), mLevels.begin(), mLevels.end());
Eric Laurent6d607012021-07-05 11:54:40 +0200458 return Status::ok();
459}
460
Eric Laurent2be8b292021-08-23 09:44:33 -0700461Status Spatializer::setLevel(SpatializationLevel level) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000462 ALOGV("%s level %s", __func__, media::toString(level).c_str());
463 mLocalLog.log("%s with %s", __func__, media::toString(level).c_str());
Eric Laurent6d607012021-07-05 11:54:40 +0200464 if (level != SpatializationLevel::NONE
Eric Laurent2be8b292021-08-23 09:44:33 -0700465 && std::find(mLevels.begin(), mLevels.end(), level) == mLevels.end()) {
Eric Laurent6d607012021-07-05 11:54:40 +0200466 return binderStatusFromStatusT(BAD_VALUE);
467 }
468 sp<media::INativeSpatializerCallback> callback;
469 bool levelChanged = false;
470 {
Eric Laurent2be8b292021-08-23 09:44:33 -0700471 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200472 levelChanged = mLevel != level;
473 mLevel = level;
474 callback = mSpatializerCallback;
Eric Laurent2be8b292021-08-23 09:44:33 -0700475
476 if (levelChanged && mEngine != nullptr) {
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200477 checkEngineState_l();
Eric Laurent2be8b292021-08-23 09:44:33 -0700478 }
Eric Laurent9249d342022-03-18 11:55:56 +0100479 checkSensorsState_l();
Eric Laurent6d607012021-07-05 11:54:40 +0200480 }
481
482 if (levelChanged) {
483 mPolicyCallback->onCheckSpatializer();
484 if (callback != nullptr) {
485 callback->onLevelChanged(level);
486 }
487 }
488 return Status::ok();
489}
490
Eric Laurent2be8b292021-08-23 09:44:33 -0700491Status Spatializer::getLevel(SpatializationLevel *level) {
Eric Laurent6d607012021-07-05 11:54:40 +0200492 if (level == nullptr) {
493 return binderStatusFromStatusT(BAD_VALUE);
494 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700495 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200496 *level = mLevel;
497 ALOGV("%s level %d", __func__, (int)*level);
498 return Status::ok();
499}
500
Eric Laurentc87402b2021-09-17 16:49:42 +0200501Status Spatializer::isHeadTrackingSupported(bool *supports) {
502 ALOGV("%s mSupportsHeadTracking %d", __func__, mSupportsHeadTracking);
503 if (supports == nullptr) {
504 return binderStatusFromStatusT(BAD_VALUE);
505 }
506 std::lock_guard lock(mLock);
507 *supports = mSupportsHeadTracking;
508 return Status::ok();
509}
510
Eric Laurent6d607012021-07-05 11:54:40 +0200511Status Spatializer::getSupportedHeadTrackingModes(
Eric Laurent2be8b292021-08-23 09:44:33 -0700512 std::vector<SpatializerHeadTrackingMode>* modes) {
513 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200514 ALOGV("%s", __func__);
515 if (modes == nullptr) {
516 return binderStatusFromStatusT(BAD_VALUE);
517 }
Andy Hunga461a002022-05-17 10:36:02 -0700518 modes->insert(modes->end(), mHeadTrackingModes.begin(), mHeadTrackingModes.end());
Eric Laurent6d607012021-07-05 11:54:40 +0200519 return Status::ok();
520}
521
Eric Laurent2be8b292021-08-23 09:44:33 -0700522Status Spatializer::setDesiredHeadTrackingMode(SpatializerHeadTrackingMode mode) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000523 ALOGV("%s mode %s", __func__, media::toString(mode).c_str());
Eric Laurent2be8b292021-08-23 09:44:33 -0700524
525 if (!mSupportsHeadTracking) {
526 return binderStatusFromStatusT(INVALID_OPERATION);
527 }
Shunkai Yao5a251df2022-07-22 18:42:27 +0000528 mLocalLog.log("%s with %s", __func__, media::toString(mode).c_str());
Eric Laurent2be8b292021-08-23 09:44:33 -0700529 std::lock_guard lock(mLock);
530 switch (mode) {
531 case SpatializerHeadTrackingMode::OTHER:
532 return binderStatusFromStatusT(BAD_VALUE);
533 case SpatializerHeadTrackingMode::DISABLED:
534 mDesiredHeadTrackingMode = HeadTrackingMode::STATIC;
535 break;
536 case SpatializerHeadTrackingMode::RELATIVE_WORLD:
537 mDesiredHeadTrackingMode = HeadTrackingMode::WORLD_RELATIVE;
538 break;
539 case SpatializerHeadTrackingMode::RELATIVE_SCREEN:
540 mDesiredHeadTrackingMode = HeadTrackingMode::SCREEN_RELATIVE;
541 break;
542 }
543
Eric Laurent11094172022-04-05 18:27:42 +0200544 checkPoseController_l();
545 checkSensorsState_l();
Eric Laurent2be8b292021-08-23 09:44:33 -0700546
547 return Status::ok();
548}
549
550Status Spatializer::getActualHeadTrackingMode(SpatializerHeadTrackingMode *mode) {
Eric Laurent6d607012021-07-05 11:54:40 +0200551 if (mode == nullptr) {
552 return binderStatusFromStatusT(BAD_VALUE);
553 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700554 std::lock_guard lock(mLock);
555 *mode = mActualHeadTrackingMode;
Eric Laurent6d607012021-07-05 11:54:40 +0200556 ALOGV("%s mode %d", __func__, (int)*mode);
557 return Status::ok();
558}
559
Ytai Ben-Tsvia16a9df2021-08-05 08:57:06 -0700560Status Spatializer::recenterHeadTracker() {
Eric Laurent780be4a2021-09-16 10:44:24 +0200561 if (!mSupportsHeadTracking) {
562 return binderStatusFromStatusT(INVALID_OPERATION);
563 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700564 std::lock_guard lock(mLock);
565 if (mPoseController != nullptr) {
566 mPoseController->recenter();
567 }
Eric Laurent6d607012021-07-05 11:54:40 +0200568 return Status::ok();
569}
570
571Status Spatializer::setGlobalTransform(const std::vector<float>& screenToStage) {
Eric Laurent6d607012021-07-05 11:54:40 +0200572 ALOGV("%s", __func__);
Eric Laurent780be4a2021-09-16 10:44:24 +0200573 if (!mSupportsHeadTracking) {
574 return binderStatusFromStatusT(INVALID_OPERATION);
575 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700576 std::optional<Pose3f> maybePose = Pose3f::fromVector(screenToStage);
577 if (!maybePose.has_value()) {
578 ALOGW("Invalid screenToStage vector.");
579 return binderStatusFromStatusT(BAD_VALUE);
580 }
581 std::lock_guard lock(mLock);
582 if (mPoseController != nullptr) {
Andy Hung82a4eab2023-01-30 11:58:44 -0800583 mLocalLog.log("%s with screenToStage %s", __func__,
584 media::VectorRecorder::toString<float>(screenToStage).c_str());
Eric Laurent2be8b292021-08-23 09:44:33 -0700585 mPoseController->setScreenToStagePose(maybePose.value());
586 }
Eric Laurent6d607012021-07-05 11:54:40 +0200587 return Status::ok();
588}
589
590Status Spatializer::release() {
591 ALOGV("%s", __func__);
592 bool levelChanged = false;
593 {
Eric Laurent2be8b292021-08-23 09:44:33 -0700594 std::lock_guard lock(mLock);
Eric Laurent6d607012021-07-05 11:54:40 +0200595 if (mSpatializerCallback == nullptr) {
596 return binderStatusFromStatusT(INVALID_OPERATION);
597 }
598
599 sp<IBinder> binder = IInterface::asBinder(mSpatializerCallback);
600 binder->unlinkToDeath(this);
601 mSpatializerCallback.clear();
602
603 levelChanged = mLevel != SpatializationLevel::NONE;
604 mLevel = SpatializationLevel::NONE;
605 }
606
607 if (levelChanged) {
608 mPolicyCallback->onCheckSpatializer();
609 }
610 return Status::ok();
611}
612
Eric Laurent2be8b292021-08-23 09:44:33 -0700613Status Spatializer::setHeadSensor(int sensorHandle) {
614 ALOGV("%s sensorHandle %d", __func__, sensorHandle);
Eric Laurent780be4a2021-09-16 10:44:24 +0200615 if (!mSupportsHeadTracking) {
616 return binderStatusFromStatusT(INVALID_OPERATION);
617 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700618 std::lock_guard lock(mLock);
Andy Hungba2a61a2022-05-20 12:00:28 -0700619 if (mHeadSensor != sensorHandle) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000620 mLocalLog.log("%s with 0x%08x", __func__, sensorHandle);
Andy Hungba2a61a2022-05-20 12:00:28 -0700621 mHeadSensor = sensorHandle;
622 checkPoseController_l();
623 checkSensorsState_l();
624 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700625 return Status::ok();
626}
627
628Status Spatializer::setScreenSensor(int sensorHandle) {
629 ALOGV("%s sensorHandle %d", __func__, sensorHandle);
Eric Laurent780be4a2021-09-16 10:44:24 +0200630 if (!mSupportsHeadTracking) {
631 return binderStatusFromStatusT(INVALID_OPERATION);
632 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700633 std::lock_guard lock(mLock);
Andy Hungba2a61a2022-05-20 12:00:28 -0700634 if (mScreenSensor != sensorHandle) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000635 mLocalLog.log("%s with 0x%08x", __func__, sensorHandle);
Andy Hungba2a61a2022-05-20 12:00:28 -0700636 mScreenSensor = sensorHandle;
637 // TODO: consider a new method setHeadAndScreenSensor()
638 // because we generally set both at the same time.
639 // This will avoid duplicated work and recentering.
640 checkSensorsState_l();
641 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700642 return Status::ok();
643}
644
645Status Spatializer::setDisplayOrientation(float physicalToLogicalAngle) {
646 ALOGV("%s physicalToLogicalAngle %f", __func__, physicalToLogicalAngle);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000647 mLocalLog.log("%s with %f", __func__, physicalToLogicalAngle);
Andy Hungcd6c1062023-03-09 20:45:36 -0800648 const float angle = safe_clamp(physicalToLogicalAngle, 0.f, (float)(2. * M_PI));
649 // It is possible due to numerical inaccuracies to exceed the boundaries of 0 to 2 * M_PI.
650 ALOGI_IF(angle != physicalToLogicalAngle,
651 "%s: clamping %f to %f", __func__, physicalToLogicalAngle, angle);
652 std::lock_guard lock(mLock);
653 mDisplayOrientation = angle;
Eric Laurent2be8b292021-08-23 09:44:33 -0700654 if (mPoseController != nullptr) {
Andy Hungcd6c1062023-03-09 20:45:36 -0800655 // This turns on the rate-limiter.
656 mPoseController->setDisplayOrientation(angle);
Eric Laurent2be8b292021-08-23 09:44:33 -0700657 }
Eric Laurent16ddaf42021-09-17 15:00:35 +0200658 if (mEngine != nullptr) {
659 setEffectParameter_l(
Andy Hungcd6c1062023-03-09 20:45:36 -0800660 SPATIALIZER_PARAM_DISPLAY_ORIENTATION, std::vector<float>{angle});
Eric Laurent16ddaf42021-09-17 15:00:35 +0200661 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700662 return Status::ok();
663}
664
665Status Spatializer::setHingeAngle(float hingeAngle) {
Eric Laurent2be8b292021-08-23 09:44:33 -0700666 ALOGV("%s hingeAngle %f", __func__, hingeAngle);
Andy Hungcd6c1062023-03-09 20:45:36 -0800667 mLocalLog.log("%s with %f", __func__, hingeAngle);
668 const float angle = safe_clamp(hingeAngle, 0.f, (float)(2. * M_PI));
669 // It is possible due to numerical inaccuracies to exceed the boundaries of 0 to 2 * M_PI.
670 ALOGI_IF(angle != hingeAngle,
671 "%s: clamping %f to %f", __func__, hingeAngle, angle);
672 std::lock_guard lock(mLock);
673 mHingeAngle = angle;
Eric Laurent2be8b292021-08-23 09:44:33 -0700674 if (mEngine != nullptr) {
Andy Hungcd6c1062023-03-09 20:45:36 -0800675 setEffectParameter_l(SPATIALIZER_PARAM_HINGE_ANGLE, std::vector<float>{angle});
676 }
677 return Status::ok();
678}
679
680Status Spatializer::setFoldState(bool folded) {
681 ALOGV("%s foldState %d", __func__, (int)folded);
682 mLocalLog.log("%s with %d", __func__, (int)folded);
683 std::lock_guard lock(mLock);
684 mFoldedState = folded;
685 if (mEngine != nullptr) {
686 // we don't suppress multiple calls with the same folded state - that's
687 // done at the caller.
688 setEffectParameter_l(SPATIALIZER_PARAM_FOLD_STATE, std::vector<uint8_t>{mFoldedState});
Eric Laurent2be8b292021-08-23 09:44:33 -0700689 }
690 return Status::ok();
691}
692
693Status Spatializer::getSupportedModes(std::vector<SpatializationMode> *modes) {
694 ALOGV("%s", __func__);
695 if (modes == nullptr) {
696 return binderStatusFromStatusT(BAD_VALUE);
697 }
698 *modes = mSpatializationModes;
699 return Status::ok();
700}
701
Eric Laurent67816e32021-09-16 15:18:40 +0200702Status Spatializer::registerHeadTrackingCallback(
703 const sp<media::ISpatializerHeadTrackingCallback>& callback) {
704 ALOGV("%s callback %p", __func__, callback.get());
705 std::lock_guard lock(mLock);
706 if (!mSupportsHeadTracking) {
707 return binderStatusFromStatusT(INVALID_OPERATION);
708 }
709 mHeadTrackingCallback = callback;
710 return Status::ok();
711}
712
Eric Laurentc87402b2021-09-17 16:49:42 +0200713Status Spatializer::setParameter(int key, const std::vector<unsigned char>& value) {
714 ALOGV("%s key %d", __func__, key);
715 std::lock_guard lock(mLock);
716 status_t status = INVALID_OPERATION;
717 if (mEngine != nullptr) {
718 status = setEffectParameter_l(key, value);
719 }
720 return binderStatusFromStatusT(status);
721}
722
723Status Spatializer::getParameter(int key, std::vector<unsigned char> *value) {
Greg Kaiserf7249f82021-09-21 07:10:12 -0700724 ALOGV("%s key %d value size %d", __func__, key,
725 (value != nullptr ? (int)value->size() : -1));
Eric Laurentc87402b2021-09-17 16:49:42 +0200726 if (value == nullptr) {
George Burgess IV22386222021-09-22 12:09:31 -0700727 return binderStatusFromStatusT(BAD_VALUE);
Eric Laurentc87402b2021-09-17 16:49:42 +0200728 }
729 std::lock_guard lock(mLock);
730 status_t status = INVALID_OPERATION;
731 if (mEngine != nullptr) {
732 ALOGV("%s key %d mEngine %p", __func__, key, mEngine.get());
733 status = getEffectParameter_l(key, value);
734 }
735 return binderStatusFromStatusT(status);
736}
737
738Status Spatializer::getOutput(int *output) {
739 ALOGV("%s", __func__);
740 if (output == nullptr) {
741 binderStatusFromStatusT(BAD_VALUE);
742 }
743 std::lock_guard lock(mLock);
744 *output = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_io_handle_t_int32_t(mOutput));
745 ALOGV("%s got output %d", __func__, *output);
746 return Status::ok();
747}
748
Eric Laurent2be8b292021-08-23 09:44:33 -0700749// SpatializerPoseController::Listener
750void Spatializer::onHeadToStagePose(const Pose3f& headToStage) {
751 ALOGV("%s", __func__);
Eric Laurent780be4a2021-09-16 10:44:24 +0200752 LOG_ALWAYS_FATAL_IF(!mSupportsHeadTracking,
753 "onHeadToStagePose() called with no head tracking support!");
754
Eric Laurent2be8b292021-08-23 09:44:33 -0700755 auto vec = headToStage.toVector();
Eric Laurent8a4259f2021-09-14 16:04:00 +0200756 LOG_ALWAYS_FATAL_IF(vec.size() != sHeadPoseKeys.size(),
757 "%s invalid head to stage vector size %zu", __func__, vec.size());
Eric Laurent8a4259f2021-09-14 16:04:00 +0200758 sp<AMessage> msg =
759 new AMessage(EngineCallbackHandler::kWhatOnHeadToStagePose, mHandler);
760 for (size_t i = 0 ; i < sHeadPoseKeys.size(); i++) {
761 msg->setFloat(sHeadPoseKeys[i], vec[i]);
762 }
763 msg->post();
764}
765
Eric Laurent3c48ad92022-10-21 11:28:32 +0200766void Spatializer::resetEngineHeadPose_l() {
767 ALOGV("%s mEngine %p", __func__, mEngine.get());
768 if (mEngine == nullptr) {
769 return;
770 }
771 const std::vector<float> headToStage(6, 0.0);
772 setEffectParameter_l(SPATIALIZER_PARAM_HEAD_TO_STAGE, headToStage);
773 setEffectParameter_l(SPATIALIZER_PARAM_HEADTRACKING_MODE,
774 std::vector<SpatializerHeadTrackingMode>{SpatializerHeadTrackingMode::DISABLED});
775}
776
Eric Laurent8a4259f2021-09-14 16:04:00 +0200777void Spatializer::onHeadToStagePoseMsg(const std::vector<float>& headToStage) {
778 ALOGV("%s", __func__);
Eric Laurent67816e32021-09-16 15:18:40 +0200779 sp<media::ISpatializerHeadTrackingCallback> callback;
Eric Laurent2be8b292021-08-23 09:44:33 -0700780 {
781 std::lock_guard lock(mLock);
Eric Laurent67816e32021-09-16 15:18:40 +0200782 callback = mHeadTrackingCallback;
Eric Laurent2be8b292021-08-23 09:44:33 -0700783 if (mEngine != nullptr) {
Eric Laurent8a4259f2021-09-14 16:04:00 +0200784 setEffectParameter_l(SPATIALIZER_PARAM_HEAD_TO_STAGE, headToStage);
Andy Hung2a390db2023-01-30 11:58:44 -0800785 const auto record = recordFromTranslationRotationVector(headToStage);
786 mPoseRecorder.record(record);
787 mPoseDurableRecorder.record(record);
Eric Laurent2be8b292021-08-23 09:44:33 -0700788 }
789 }
790
791 if (callback != nullptr) {
Eric Laurent8a4259f2021-09-14 16:04:00 +0200792 callback->onHeadToSoundStagePoseUpdated(headToStage);
Eric Laurent2be8b292021-08-23 09:44:33 -0700793 }
794}
795
796void Spatializer::onActualModeChange(HeadTrackingMode mode) {
Shunkai Yao51379452022-08-30 03:14:50 +0000797 std::string modeStr = media::toString(mode);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000798 ALOGV("%s(%s)", __func__, modeStr.c_str());
Shunkai Yao51379452022-08-30 03:14:50 +0000799 sp<AMessage> msg = new AMessage(EngineCallbackHandler::kWhatOnActualModeChange, mHandler);
Eric Laurent8a4259f2021-09-14 16:04:00 +0200800 msg->setInt32(EngineCallbackHandler::kModeKey, static_cast<int>(mode));
801 msg->post();
802}
803
804void Spatializer::onActualModeChangeMsg(HeadTrackingMode mode) {
805 ALOGV("%s(%d)", __func__, (int) mode);
Eric Laurent67816e32021-09-16 15:18:40 +0200806 sp<media::ISpatializerHeadTrackingCallback> callback;
Eric Laurent2be8b292021-08-23 09:44:33 -0700807 SpatializerHeadTrackingMode spatializerMode;
808 {
809 std::lock_guard lock(mLock);
810 if (!mSupportsHeadTracking) {
811 spatializerMode = SpatializerHeadTrackingMode::DISABLED;
812 } else {
813 switch (mode) {
814 case HeadTrackingMode::STATIC:
815 spatializerMode = SpatializerHeadTrackingMode::DISABLED;
816 break;
817 case HeadTrackingMode::WORLD_RELATIVE:
818 spatializerMode = SpatializerHeadTrackingMode::RELATIVE_WORLD;
819 break;
820 case HeadTrackingMode::SCREEN_RELATIVE:
821 spatializerMode = SpatializerHeadTrackingMode::RELATIVE_SCREEN;
822 break;
823 default:
824 LOG_ALWAYS_FATAL("Unknown mode: %d", mode);
825 }
826 }
827 mActualHeadTrackingMode = spatializerMode;
Eric Laurente51f80e2022-04-14 10:20:38 +0200828 if (mEngine != nullptr) {
Eric Laurent3c48ad92022-10-21 11:28:32 +0200829 if (spatializerMode == SpatializerHeadTrackingMode::DISABLED) {
830 resetEngineHeadPose_l();
831 } else {
832 setEffectParameter_l(SPATIALIZER_PARAM_HEADTRACKING_MODE,
833 std::vector<SpatializerHeadTrackingMode>{spatializerMode});
834 }
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200835 }
Eric Laurent67816e32021-09-16 15:18:40 +0200836 callback = mHeadTrackingCallback;
Andy Hung79ccfda2023-01-30 11:58:44 -0800837 mLocalLog.log("%s: updating mode to %s", __func__, media::toString(mode).c_str());
Eric Laurent2be8b292021-08-23 09:44:33 -0700838 }
Eric Laurente51f80e2022-04-14 10:20:38 +0200839 if (callback != nullptr) {
Eric Laurent2be8b292021-08-23 09:44:33 -0700840 callback->onHeadTrackingModeChanged(spatializerMode);
841 }
842}
843
Eric Laurent15903592022-02-24 20:44:36 +0100844status_t Spatializer::attachOutput(audio_io_handle_t output, size_t numActiveTracks) {
Eric Laurent4a872862021-10-11 17:06:47 +0200845 bool outputChanged = false;
846 sp<media::INativeSpatializerCallback> callback;
847
Eric Laurent2be8b292021-08-23 09:44:33 -0700848 {
849 std::lock_guard lock(mLock);
850 ALOGV("%s output %d mOutput %d", __func__, (int)output, (int)mOutput);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000851 mLocalLog.log("%s with output %d tracks %zu (mOutput %d)", __func__, (int)output,
852 numActiveTracks, (int)mOutput);
Eric Laurent2be8b292021-08-23 09:44:33 -0700853 if (mOutput != AUDIO_IO_HANDLE_NONE) {
854 LOG_ALWAYS_FATAL_IF(mEngine == nullptr, "%s output set without FX engine", __func__);
855 // remove FX instance
856 mEngine->setEnabled(false);
857 mEngine.clear();
Eric Laurent15903592022-02-24 20:44:36 +0100858 mPoseController.reset();
Eric Laurentb387fb42022-05-03 18:19:35 +0200859 AudioSystem::removeSupportedLatencyModesCallback(this);
Eric Laurent2be8b292021-08-23 09:44:33 -0700860 }
Eric Laurentb387fb42022-05-03 18:19:35 +0200861
Eric Laurent2be8b292021-08-23 09:44:33 -0700862 // create FX instance on output
863 AttributionSourceState attributionSource = AttributionSourceState();
864 mEngine = new AudioEffect(attributionSource);
865 mEngine->set(nullptr, &mEngineDescriptor.uuid, 0, Spatializer::engineCallback /* cbf */,
866 this /* user */, AUDIO_SESSION_OUTPUT_STAGE, output, {} /* device */,
867 false /* probe */, true /* notifyFramesProcessed */);
868 status_t status = mEngine->initCheck();
869 ALOGV("%s mEngine create status %d", __func__, (int)status);
870 if (status != NO_ERROR) {
871 return status;
872 }
873
Eric Laurent4a872862021-10-11 17:06:47 +0200874 outputChanged = mOutput != output;
Eric Laurent2be8b292021-08-23 09:44:33 -0700875 mOutput = output;
Eric Laurent11094172022-04-05 18:27:42 +0200876 mNumActiveTracks = numActiveTracks;
Eric Laurentb387fb42022-05-03 18:19:35 +0200877 AudioSystem::addSupportedLatencyModesCallback(this);
878
879 std::vector<audio_latency_mode_t> latencyModes;
880 status = AudioSystem::getSupportedLatencyModes(mOutput, &latencyModes);
881 if (status == OK) {
882 mSupportedLatencyModes = latencyModes;
883 }
Eric Laurent2be8b292021-08-23 09:44:33 -0700884
Eric Laurent11094172022-04-05 18:27:42 +0200885 checkEngineState_l();
Eric Laurent780be4a2021-09-16 10:44:24 +0200886 if (mSupportsHeadTracking) {
Eric Laurent11094172022-04-05 18:27:42 +0200887 checkPoseController_l();
Eric Laurent9249d342022-03-18 11:55:56 +0100888 checkSensorsState_l();
Eric Laurent780be4a2021-09-16 10:44:24 +0200889 }
Eric Laurent4a872862021-10-11 17:06:47 +0200890 callback = mSpatializerCallback;
Andy Hungcd6c1062023-03-09 20:45:36 -0800891
892 // Restore common effect state.
893 setEffectParameter_l(SPATIALIZER_PARAM_DISPLAY_ORIENTATION,
894 std::vector<float>{mDisplayOrientation});
895 setEffectParameter_l(SPATIALIZER_PARAM_FOLD_STATE,
896 std::vector<uint8_t>{mFoldedState});
897 setEffectParameter_l(SPATIALIZER_PARAM_HINGE_ANGLE,
898 std::vector<float>{mHingeAngle});
Eric Laurent6d607012021-07-05 11:54:40 +0200899 }
Eric Laurent4a872862021-10-11 17:06:47 +0200900
901 if (outputChanged && callback != nullptr) {
902 callback->onOutputChanged(output);
903 }
904
Eric Laurent6d607012021-07-05 11:54:40 +0200905 return NO_ERROR;
906}
907
908audio_io_handle_t Spatializer::detachOutput() {
Eric Laurent2be8b292021-08-23 09:44:33 -0700909 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent4a872862021-10-11 17:06:47 +0200910 sp<media::INativeSpatializerCallback> callback;
911
912 {
913 std::lock_guard lock(mLock);
Shunkai Yao5a251df2022-07-22 18:42:27 +0000914 mLocalLog.log("%s with output %d tracks %zu", __func__, (int)mOutput, mNumActiveTracks);
Eric Laurent4a872862021-10-11 17:06:47 +0200915 ALOGV("%s mOutput %d", __func__, (int)mOutput);
916 if (mOutput == AUDIO_IO_HANDLE_NONE) {
917 return output;
918 }
919 // remove FX instance
920 mEngine->setEnabled(false);
921 mEngine.clear();
Eric Laurentb387fb42022-05-03 18:19:35 +0200922 AudioSystem::removeSupportedLatencyModesCallback(this);
Eric Laurent4a872862021-10-11 17:06:47 +0200923 output = mOutput;
924 mOutput = AUDIO_IO_HANDLE_NONE;
925 mPoseController.reset();
Eric Laurent4a872862021-10-11 17:06:47 +0200926 callback = mSpatializerCallback;
Eric Laurent6d607012021-07-05 11:54:40 +0200927 }
Eric Laurent4a872862021-10-11 17:06:47 +0200928
929 if (callback != nullptr) {
930 callback->onOutputChanged(AUDIO_IO_HANDLE_NONE);
931 }
Eric Laurent6d607012021-07-05 11:54:40 +0200932 return output;
933}
934
Eric Laurentb387fb42022-05-03 18:19:35 +0200935void Spatializer::onSupportedLatencyModesChanged(
936 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) {
Eric Laurentdf2ece42022-07-20 13:49:47 +0200937 ALOGV("%s output %d num modes %zu", __func__, (int)output, modes.size());
938 sp<AMessage> msg =
939 new AMessage(EngineCallbackHandler::kWhatOnLatencyModesChanged, mHandler);
940 msg->setObject(EngineCallbackHandler::kLatencyModesKey,
941 sp<EngineCallbackHandler::LatencyModes>::make(output, modes));
942 msg->post();
943}
944
945void Spatializer::onSupportedLatencyModesChangedMsg(
946 audio_io_handle_t output, std::vector<audio_latency_mode_t>&& modes) {
Eric Laurentb387fb42022-05-03 18:19:35 +0200947 std::lock_guard lock(mLock);
Eric Laurentdf2ece42022-07-20 13:49:47 +0200948 ALOGV("%s output %d mOutput %d num modes %zu",
949 __func__, (int)output, (int)mOutput, modes.size());
Eric Laurentb387fb42022-05-03 18:19:35 +0200950 if (output == mOutput) {
Eric Laurentdf2ece42022-07-20 13:49:47 +0200951 mSupportedLatencyModes = std::move(modes);
Eric Laurentb387fb42022-05-03 18:19:35 +0200952 checkSensorsState_l();
953 }
954}
955
Eric Laurent15903592022-02-24 20:44:36 +0100956void Spatializer::updateActiveTracks(size_t numActiveTracks) {
957 std::lock_guard lock(mLock);
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200958 if (mNumActiveTracks != numActiveTracks) {
Shunkai Yao5a251df2022-07-22 18:42:27 +0000959 mLocalLog.log("%s from %zu to %zu", __func__, mNumActiveTracks, numActiveTracks);
Eric Laurent7ea0d1b2022-04-01 14:23:44 +0200960 mNumActiveTracks = numActiveTracks;
961 checkEngineState_l();
962 checkSensorsState_l();
963 }
Eric Laurent15903592022-02-24 20:44:36 +0100964}
965
Eric Laurent9249d342022-03-18 11:55:56 +0100966void Spatializer::checkSensorsState_l() {
Eric Laurentb387fb42022-05-03 18:19:35 +0200967 audio_latency_mode_t requestedLatencyMode = AUDIO_LATENCY_MODE_FREE;
Andy Hungc0896c72022-10-21 17:30:30 -0700968 const bool supportsSetLatencyMode = !mSupportedLatencyModes.empty();
969 const bool supportsLowLatencyMode = supportsSetLatencyMode && std::find(
970 mSupportedLatencyModes.begin(), mSupportedLatencyModes.end(),
971 AUDIO_LATENCY_MODE_LOW) != mSupportedLatencyModes.end();
Eric Laurent3c48ad92022-10-21 11:28:32 +0200972 if (mSupportsHeadTracking) {
973 if (mPoseController != nullptr) {
Andy Hungc0896c72022-10-21 17:30:30 -0700974 // TODO(b/253297301, b/255433067) reenable low latency condition check
975 // for Head Tracking after Bluetooth HAL supports it correctly.
976 if (mNumActiveTracks > 0 && mLevel != SpatializationLevel::NONE
Eric Laurent3c48ad92022-10-21 11:28:32 +0200977 && mDesiredHeadTrackingMode != HeadTrackingMode::STATIC
978 && mHeadSensor != SpatializerPoseController::INVALID_SENSOR) {
979 if (mEngine != nullptr) {
980 setEffectParameter_l(SPATIALIZER_PARAM_HEADTRACKING_MODE,
981 std::vector<SpatializerHeadTrackingMode>{mActualHeadTrackingMode});
982 }
983 mPoseController->setHeadSensor(mHeadSensor);
984 mPoseController->setScreenSensor(mScreenSensor);
Andy Hungc0896c72022-10-21 17:30:30 -0700985 if (supportsLowLatencyMode) requestedLatencyMode = AUDIO_LATENCY_MODE_LOW;
Eric Laurent3c48ad92022-10-21 11:28:32 +0200986 } else {
987 mPoseController->setHeadSensor(SpatializerPoseController::INVALID_SENSOR);
988 mPoseController->setScreenSensor(SpatializerPoseController::INVALID_SENSOR);
989 resetEngineHeadPose_l();
990 }
Eric Laurent15903592022-02-24 20:44:36 +0100991 } else {
Eric Laurent3c48ad92022-10-21 11:28:32 +0200992 resetEngineHeadPose_l();
Eric Laurent15903592022-02-24 20:44:36 +0100993 }
994 }
Andy Hungc0896c72022-10-21 17:30:30 -0700995 if (mOutput != AUDIO_IO_HANDLE_NONE && supportsSetLatencyMode) {
Andy Hung5d8618d2022-11-17 17:21:45 -0800996 const status_t status =
997 AudioSystem::setRequestedLatencyMode(mOutput, requestedLatencyMode);
998 ALOGD("%s: setRequestedLatencyMode for output thread(%d) to %s returned %d",
999 __func__, mOutput, toString(requestedLatencyMode).c_str(), status);
Eric Laurentb387fb42022-05-03 18:19:35 +02001000 }
Eric Laurent15903592022-02-24 20:44:36 +01001001}
1002
Eric Laurent7ea0d1b2022-04-01 14:23:44 +02001003void Spatializer::checkEngineState_l() {
1004 if (mEngine != nullptr) {
1005 if (mLevel != SpatializationLevel::NONE && mNumActiveTracks > 0) {
1006 mEngine->setEnabled(true);
1007 setEffectParameter_l(SPATIALIZER_PARAM_LEVEL,
1008 std::vector<SpatializationLevel>{mLevel});
Eric Laurent7ea0d1b2022-04-01 14:23:44 +02001009 } else {
1010 setEffectParameter_l(SPATIALIZER_PARAM_LEVEL,
1011 std::vector<SpatializationLevel>{SpatializationLevel::NONE});
1012 mEngine->setEnabled(false);
1013 }
1014 }
1015}
1016
Eric Laurent11094172022-04-05 18:27:42 +02001017void Spatializer::checkPoseController_l() {
1018 bool isControllerNeeded = mDesiredHeadTrackingMode != HeadTrackingMode::STATIC
1019 && mHeadSensor != SpatializerPoseController::INVALID_SENSOR;
1020
1021 if (isControllerNeeded && mPoseController == nullptr) {
1022 mPoseController = std::make_shared<SpatializerPoseController>(
1023 static_cast<SpatializerPoseController::Listener*>(this),
Eric Laurente51f80e2022-04-14 10:20:38 +02001024 10ms, std::nullopt);
Eric Laurent11094172022-04-05 18:27:42 +02001025 LOG_ALWAYS_FATAL_IF(mPoseController == nullptr,
1026 "%s could not allocate pose controller", __func__);
1027 mPoseController->setDisplayOrientation(mDisplayOrientation);
1028 } else if (!isControllerNeeded && mPoseController != nullptr) {
1029 mPoseController.reset();
Eric Laurent3c48ad92022-10-21 11:28:32 +02001030 resetEngineHeadPose_l();
Eric Laurent11094172022-04-05 18:27:42 +02001031 }
1032 if (mPoseController != nullptr) {
1033 mPoseController->setDesiredMode(mDesiredHeadTrackingMode);
1034 }
1035}
1036
Eric Laurent2be8b292021-08-23 09:44:33 -07001037void Spatializer::calculateHeadPose() {
1038 ALOGV("%s", __func__);
1039 std::lock_guard lock(mLock);
1040 if (mPoseController != nullptr) {
1041 mPoseController->calculateAsync();
1042 }
1043}
Eric Laurent6d607012021-07-05 11:54:40 +02001044
Eric Laurent2be8b292021-08-23 09:44:33 -07001045void Spatializer::engineCallback(int32_t event, void *user, void *info) {
Eric Laurent6d607012021-07-05 11:54:40 +02001046 if (user == nullptr) {
1047 return;
1048 }
Eric Laurent2be8b292021-08-23 09:44:33 -07001049 Spatializer* const me = reinterpret_cast<Spatializer *>(user);
Eric Laurent6d607012021-07-05 11:54:40 +02001050 switch (event) {
1051 case AudioEffect::EVENT_FRAMES_PROCESSED: {
Eric Laurent2be8b292021-08-23 09:44:33 -07001052 int frames = info == nullptr ? 0 : *(int*)info;
Eric Laurent9249d342022-03-18 11:55:56 +01001053 ALOGV("%s frames processed %d for me %p", __func__, frames, me);
Eric Laurent8a4259f2021-09-14 16:04:00 +02001054 me->postFramesProcessedMsg(frames);
Eric Laurent2be8b292021-08-23 09:44:33 -07001055 } break;
Eric Laurent6d607012021-07-05 11:54:40 +02001056 default:
Eric Laurent9249d342022-03-18 11:55:56 +01001057 ALOGV("%s event %d", __func__, event);
Eric Laurent6d607012021-07-05 11:54:40 +02001058 break;
1059 }
1060}
1061
Eric Laurent8a4259f2021-09-14 16:04:00 +02001062void Spatializer::postFramesProcessedMsg(int frames) {
1063 sp<AMessage> msg =
1064 new AMessage(EngineCallbackHandler::kWhatOnFramesProcessed, mHandler);
1065 msg->setInt32(EngineCallbackHandler::kNumFramesKey, frames);
1066 msg->post();
1067}
1068
Shunkai Yao5a251df2022-07-22 18:42:27 +00001069std::string Spatializer::toString(unsigned level) const {
Andy Hung2a390db2023-01-30 11:58:44 -08001070 std::string prefixSpace(level, ' ');
Shunkai Yao5a251df2022-07-22 18:42:27 +00001071 std::string ss = prefixSpace + "Spatializer:\n";
1072 bool needUnlock = false;
1073
1074 prefixSpace += ' ';
1075 if (!mLock.try_lock()) {
1076 // dumpsys even try_lock failed, information dump can be useful although may not accurate
1077 ss.append(prefixSpace).append("try_lock failed, dumpsys below maybe INACCURATE!\n");
1078 } else {
1079 needUnlock = true;
1080 }
1081
1082 // Spatializer class information.
1083 // 1. Capabilities (mLevels, mHeadTrackingModes, mSpatializationModes, mChannelMasks, etc)
1084 ss.append(prefixSpace).append("Supported levels: [");
1085 for (auto& level : mLevels) {
1086 base::StringAppendF(&ss, " %s", media::toString(level).c_str());
1087 }
1088 base::StringAppendF(&ss, "], mLevel: %s", media::toString(mLevel).c_str());
1089
1090 base::StringAppendF(&ss, "\n%smHeadTrackingModes: [", prefixSpace.c_str());
1091 for (auto& mode : mHeadTrackingModes) {
1092 base::StringAppendF(&ss, " %s", media::toString(mode).c_str());
1093 }
1094 base::StringAppendF(&ss, "], Desired: %s, Actual %s\n",
Shunkai Yao51379452022-08-30 03:14:50 +00001095 media::toString(mDesiredHeadTrackingMode).c_str(),
Shunkai Yao5a251df2022-07-22 18:42:27 +00001096 media::toString(mActualHeadTrackingMode).c_str());
1097
1098 base::StringAppendF(&ss, "%smSpatializationModes: [", prefixSpace.c_str());
1099 for (auto& mode : mSpatializationModes) {
1100 base::StringAppendF(&ss, " %s", media::toString(mode).c_str());
1101 }
1102 ss += "]\n";
1103
1104 base::StringAppendF(&ss, "%smChannelMasks: ", prefixSpace.c_str());
1105 for (auto& mask : mChannelMasks) {
1106 base::StringAppendF(&ss, "%s", audio_channel_out_mask_to_string(mask));
1107 }
1108 base::StringAppendF(&ss, "\n%smSupportsHeadTracking: %s\n", prefixSpace.c_str(),
1109 mSupportsHeadTracking ? "true" : "false");
1110 // 2. Settings (Output, tracks)
1111 base::StringAppendF(&ss, "%smNumActiveTracks: %zu\n", prefixSpace.c_str(), mNumActiveTracks);
1112 base::StringAppendF(&ss, "%sOutputStreamHandle: %d\n", prefixSpace.c_str(), (int)mOutput);
1113
1114 // 3. Sensors, Effect information.
1115 base::StringAppendF(&ss, "%sHeadSensorHandle: 0x%08x\n", prefixSpace.c_str(), mHeadSensor);
1116 base::StringAppendF(&ss, "%sScreenSensorHandle: 0x%08x\n", prefixSpace.c_str(), mScreenSensor);
1117 base::StringAppendF(&ss, "%sEffectHandle: %p\n", prefixSpace.c_str(), mEngine.get());
1118 base::StringAppendF(&ss, "%sDisplayOrientation: %f\n", prefixSpace.c_str(),
1119 mDisplayOrientation);
1120
1121 ss.append(prefixSpace + "CommandLog:\n");
1122 ss += mLocalLog.dumpToString((prefixSpace + " ").c_str(), mMaxLocalLogLine);
Shunkai Yao5a251df2022-07-22 18:42:27 +00001123
1124 // PostController dump.
1125 if (mPoseController != nullptr) {
Andy Hung2a390db2023-01-30 11:58:44 -08001126 ss.append(mPoseController->toString(level + 1))
1127 .append(prefixSpace)
Andy Hung9bcf4252023-02-27 13:36:23 -08001128 .append("Pose (active stage-to-head) [tx, ty, tz : pitch, roll, yaw]:\n")
Andy Hung2a390db2023-01-30 11:58:44 -08001129 .append(prefixSpace)
1130 .append(" PerMinuteHistory:\n")
Andy Hung9bcf4252023-02-27 13:36:23 -08001131 .append(mPoseDurableRecorder.toString(level + 3))
Andy Hung2a390db2023-01-30 11:58:44 -08001132 .append(prefixSpace)
1133 .append(" PerSecondHistory:\n")
Andy Hung9bcf4252023-02-27 13:36:23 -08001134 .append(mPoseRecorder.toString(level + 3));
Shunkai Yao5a251df2022-07-22 18:42:27 +00001135 } else {
1136 ss.append(prefixSpace).append("SpatializerPoseController not exist\n");
1137 }
1138
1139 if (needUnlock) {
1140 mLock.unlock();
1141 }
1142 return ss;
1143}
1144
Eric Laurent6d607012021-07-05 11:54:40 +02001145} // namespace android