blob: ae7ded86cea7b83d192b862caa1205703cc6c98c [file] [log] [blame]
Eric Laurent6d607012021-07-05 11:54:40 +02001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_MEDIA_SPATIALIZER_H
18#define ANDROID_MEDIA_SPATIALIZER_H
19
20#include <android/media/BnEffect.h>
21#include <android/media/BnSpatializer.h>
Eric Laurent6d607012021-07-05 11:54:40 +020022#include <android/media/SpatializationLevel.h>
Eric Laurent2be8b292021-08-23 09:44:33 -070023#include <android/media/SpatializationMode.h>
24#include <android/media/SpatializerHeadTrackingMode.h>
25#include <android/sensor.h>
26#include <media/audiohal/EffectHalInterface.h>
Eric Laurent8a4259f2021-09-14 16:04:00 +020027#include <media/stagefright/foundation/ALooper.h>
Eric Laurent6d607012021-07-05 11:54:40 +020028#include <media/AudioEffect.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020029#include <system/audio_effects/effect_spatializer.h>
Eric Laurent6d607012021-07-05 11:54:40 +020030
Eric Laurent2be8b292021-08-23 09:44:33 -070031#include "SpatializerPoseController.h"
Eric Laurent6d607012021-07-05 11:54:40 +020032
33namespace android {
34
35
36// ----------------------------------------------------------------------------
37
38/**
39 * A callback interface from the Spatializer object or its parent AudioPolicyService.
40 * This is implemented by the audio policy service hosting the Spatializer to perform
41 * actions needed when a state change inside the Spatializer requires some audio system
42 * changes that cannot be performed by the Spatializer. For instance opening or closing a
43 * spatializer output stream when the spatializer is enabled or disabled
44 */
45class SpatializerPolicyCallback {
46public:
47 /** Called when a stage change occurs that requires the parent audio policy service to take
48 * some action.
49 */
50 virtual void onCheckSpatializer() = 0;
51
52 virtual ~SpatializerPolicyCallback() = default;
53};
54/**
55 * The Spatializer class implements all functional controlling the multichannel spatializer
56 * with head tracking implementation in the native audio service: audio policy and audio flinger.
57 * It presents an AIDL interface available to the java audio service to discover the availability
58 * of the feature and options, control its state and register an active head tracking sensor.
59 * It maintains the current state of the platform spatializer and applies the stored parameters
60 * when the spatializer engine is created and enabled.
61 * Based on the requested spatializer level, it will request the creation of a specialized output
62 * mixer to the audio policy service which will in turn notify the Spatializer of the output
63 * stream on which a spatializer engine should be created, configured and enabled.
64 * The spatializer also hosts the head tracking management logic. This logic receives the
65 * desired head tracking mode and selected head tracking sensor, registers a sensor event listener
66 * and derives the compounded head pose information to the spatializer engine.
67 *
68 * Workflow:
69 * - Initialization: when the audio policy service starts, it checks if a spatializer effect
70 * engine exists and if the audio policy manager reports a dedicated spatializer output profile.
71 * If both conditions are met, a Spatializer object is created
72 * - Capabilities discovery: AudioService will call AudioSystem::canBeSpatialized() and if true,
73 * acquire an ISpatializer interface with AudioSystem::getSpatializer(). This interface
74 * will be used to query the implementation capabilities and configure the spatializer.
75 * - Enabling: when ISpatializer::setLevel() sets a level different from NONE the spatializer
76 * is considered enabled. The audio policy callback onCheckSpatializer() is called. This
77 * triggers a request to audio policy manager to open a spatialization output stream and a
78 * spatializer mixer is created in audio flinger. When an output is returned by audio policy
79 * manager, Spatializer::attachOutput() is called which creates and enables the spatializer
80 * stage engine on the specified output.
81 * - Disabling: when the spatialization level is set to NONE, the spatializer is considered
82 * disabled. The audio policy callback onCheckSpatializer() is called. This triggers a call
83 * to Spatializer::detachOutput() and the spatializer engine is released. Then a request is
84 * made to audio policy manager to release and close the spatializer output stream and the
85 * spatializer mixer thread is destroyed.
86 */
Eric Laurent2be8b292021-08-23 09:44:33 -070087class Spatializer : public media::BnSpatializer,
88 public IBinder::DeathRecipient,
89 private SpatializerPoseController::Listener {
90 public:
Eric Laurent6d607012021-07-05 11:54:40 +020091 static sp<Spatializer> create(SpatializerPolicyCallback *callback);
92
93 ~Spatializer() override;
94
Eric Laurent8a4259f2021-09-14 16:04:00 +020095 /** RefBase */
96 void onFirstRef();
97
Eric Laurent6d607012021-07-05 11:54:40 +020098 /** ISpatializer, see ISpatializer.aidl */
99 binder::Status release() override;
100 binder::Status getSupportedLevels(std::vector<media::SpatializationLevel>* levels) override;
101 binder::Status setLevel(media::SpatializationLevel level) override;
102 binder::Status getLevel(media::SpatializationLevel *level) override;
103 binder::Status getSupportedHeadTrackingModes(
Ytai Ben-Tsvia16a9df2021-08-05 08:57:06 -0700104 std::vector<media::SpatializerHeadTrackingMode>* modes) override;
105 binder::Status setDesiredHeadTrackingMode(
106 media::SpatializerHeadTrackingMode mode) override;
107 binder::Status getActualHeadTrackingMode(
108 media::SpatializerHeadTrackingMode* mode) override;
109 binder::Status recenterHeadTracker() override;
Eric Laurent6d607012021-07-05 11:54:40 +0200110 binder::Status setGlobalTransform(const std::vector<float>& screenToStage) override;
Eric Laurent2be8b292021-08-23 09:44:33 -0700111 binder::Status setHeadSensor(int sensorHandle) override;
112 binder::Status setScreenSensor(int sensorHandle) override;
113 binder::Status setDisplayOrientation(float physicalToLogicalAngle) override;
114 binder::Status setHingeAngle(float hingeAngle) override;
115 binder::Status getSupportedModes(std::vector<media::SpatializationMode>* modes) override;
116
Eric Laurent6d607012021-07-05 11:54:40 +0200117
118 /** IBinder::DeathRecipient. Listen to the death of the INativeSpatializerCallback. */
119 virtual void binderDied(const wp<IBinder>& who);
120
121 /** Registers a INativeSpatializerCallback when a client is attached to this Spatializer
122 * by audio policy service.
123 */
124 status_t registerCallback(const sp<media::INativeSpatializerCallback>& callback);
125
Eric Laurent2be8b292021-08-23 09:44:33 -0700126 status_t loadEngineConfiguration(sp<EffectHalInterface> effect);
127
Eric Laurent6d607012021-07-05 11:54:40 +0200128 /** Level getter for use by local classes. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700129 media::SpatializationLevel getLevel() const { std::lock_guard lock(mLock); return mLevel; }
Eric Laurent6d607012021-07-05 11:54:40 +0200130
131 /** Called by audio policy service when the special output mixer dedicated to spatialization
132 * is opened and the spatializer engine must be created.
133 */
134 status_t attachOutput(audio_io_handle_t output);
135 /** Called by audio policy service when the special output mixer dedicated to spatialization
136 * is closed and the spatializer engine must be release.
137 */
138 audio_io_handle_t detachOutput();
139 /** Returns the output stream the spatializer is attached to. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700140 audio_io_handle_t getOutput() const { std::lock_guard lock(mLock); return mOutput; }
Eric Laurent6d607012021-07-05 11:54:40 +0200141
142 /** Gets the channel mask, sampling rate and format set for the spatializer input. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700143 audio_config_base_t getAudioInConfig() const;
Eric Laurent6d607012021-07-05 11:54:40 +0200144
Eric Laurent8a4259f2021-09-14 16:04:00 +0200145 void calculateHeadPose();
146
Eric Laurent6d607012021-07-05 11:54:40 +0200147 /** An implementation of an IEffect interface that can be used to pass advanced parameters to
148 * the spatializer engine. All APis are noop (i.e. the interface cannot be used to control
149 * the effect) except for passing parameters via the command() API. */
150 class EffectClient: public android::media::BnEffect {
151 public:
152
153 EffectClient(const sp<media::IEffectClient>& effectClient,
154 Spatializer& parent);
155 virtual ~EffectClient();
156
157 // IEffect
158 android::binder::Status enable(int32_t* _aidl_return) override;
159 android::binder::Status disable(int32_t* _aidl_return) override;
160 android::binder::Status command(int32_t cmdCode,
161 const std::vector<uint8_t>& cmdData,
162 int32_t maxResponseSize,
163 std::vector<uint8_t>* response,
164 int32_t* _aidl_return) override;
165 android::binder::Status disconnect() override;
166 android::binder::Status getCblk(media::SharedFileRegion* _aidl_return) override;
167
168 private:
169 const sp<media::IEffectClient> mEffectClient;
170 sp<IMemory> mCblkMemory;
171 const Spatializer& mParent;
172 bool mDisconnected = false;
173 };
174
175private:
Eric Laurent6d607012021-07-05 11:54:40 +0200176 Spatializer(effect_descriptor_t engineDescriptor,
177 SpatializerPolicyCallback *callback);
178
Eric Laurent6d607012021-07-05 11:54:40 +0200179 static void engineCallback(int32_t event, void* user, void *info);
180
Eric Laurent2be8b292021-08-23 09:44:33 -0700181 // From VirtualizerStageController::Listener
182 void onHeadToStagePose(const media::Pose3f& headToStage) override;
183 void onActualModeChange(media::HeadTrackingMode mode) override;
184
Eric Laurent8a4259f2021-09-14 16:04:00 +0200185 void onHeadToStagePoseMsg(const std::vector<float>& headToStage);
186 void onActualModeChangeMsg(media::HeadTrackingMode mode);
187
Eric Laurent2be8b292021-08-23 09:44:33 -0700188
189 static ConversionResult<ASensorRef> getSensorFromHandle(int handle);
190
191 static constexpr int kMaxEffectParamValues = 10;
192 /**
193 * Get a parameter from spatializer engine by calling the effect HAL command method directly.
194 * To be used when the engine instance mEngine is not yet created in the effect framework.
195 * When MULTI_VALUES is false, the expected reply is only one value of type T.
196 * When MULTI_VALUES is true, the expected reply is made of a number (of type T) indicating
197 * how many values are returned, followed by this number for values of type T.
198 */
199 template<bool MULTI_VALUES, typename T>
200 status_t getHalParameter(sp<EffectHalInterface> effect, uint32_t type,
201 std::vector<T> *values) {
202 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
203
204 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1];
205 uint32_t reply[sizeof(effect_param_t) / sizeof(uint32_t) + 2 + kMaxEffectParamValues];
206
207 effect_param_t *p = (effect_param_t *)cmd;
208 p->psize = sizeof(uint32_t);
209 if (MULTI_VALUES) {
210 p->vsize = (kMaxEffectParamValues + 1) * sizeof(T);
211 } else {
212 p->vsize = sizeof(T);
213 }
214 *(uint32_t *)p->data = type;
215 uint32_t replySize = sizeof(effect_param_t) + p->psize + p->vsize;
216
217 status_t status = effect->command(EFFECT_CMD_GET_PARAM,
218 sizeof(effect_param_t) + sizeof(uint32_t), cmd,
219 &replySize, reply);
220 if (status != NO_ERROR) {
221 return status;
222 }
223 if (p->status != NO_ERROR) {
224 return p->status;
225 }
226 if (replySize <
227 sizeof(effect_param_t) + sizeof(uint32_t) + (MULTI_VALUES ? 2 : 1) * sizeof(T)) {
228 return BAD_VALUE;
229 }
230
231 T *params = (T *)((uint8_t *)reply + sizeof(effect_param_t) + sizeof(uint32_t));
232 int numParams = 1;
233 if (MULTI_VALUES) {
234 numParams = (int)*params++;
235 }
236 if (numParams > kMaxEffectParamValues) {
237 return BAD_VALUE;
238 }
239 std::copy(&params[0], &params[numParams], back_inserter(*values));
240 return NO_ERROR;
241 }
242
243 /**
244 * Set a parameter to spatializer engine by calling setParameter on mEngine AudioEffect object.
245 * It is possible to pass more than one value of type T according to the parameter type
246 * according to values vector size.
247 */
248 template<typename T>
249 status_t setEffectParameter_l(uint32_t type, const std::vector<T>& values) REQUIRES(mLock) {
250 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
251
252 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values.size()];
253 effect_param_t *p = (effect_param_t *)cmd;
254 p->psize = sizeof(uint32_t);
255 p->vsize = sizeof(T) * values.size();
256 *(uint32_t *)p->data = type;
257 memcpy((uint32_t *)p->data + 1, values.data(), sizeof(T) * values.size());
258
259 return mEngine->setParameter(p);
260 }
261
Eric Laurent8a4259f2021-09-14 16:04:00 +0200262 void postFramesProcessedMsg(int frames);
263
Eric Laurent6d607012021-07-05 11:54:40 +0200264 /** Effect engine descriptor */
265 const effect_descriptor_t mEngineDescriptor;
266 /** Callback interface to parent audio policy service */
267 SpatializerPolicyCallback* mPolicyCallback;
268
269 /** Mutex protecting internal state */
Eric Laurent2be8b292021-08-23 09:44:33 -0700270 mutable std::mutex mLock;
Eric Laurent6d607012021-07-05 11:54:40 +0200271
272 /** Client AudioEffect for the engine */
273 sp<AudioEffect> mEngine GUARDED_BY(mLock);
274 /** Output stream the spatializer mixer thread is attached to */
275 audio_io_handle_t mOutput GUARDED_BY(mLock) = AUDIO_IO_HANDLE_NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200276
277 /** Callback interface to the client (AudioService) controlling this`Spatializer */
278 sp<media::INativeSpatializerCallback> mSpatializerCallback GUARDED_BY(mLock);
279
280 /** Requested spatialization level */
281 media::SpatializationLevel mLevel GUARDED_BY(mLock) = media::SpatializationLevel::NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200282
283 /** Extended IEffect interface is one has been created */
284 sp<EffectClient> mEffectClient GUARDED_BY(mLock);
Eric Laurent2be8b292021-08-23 09:44:33 -0700285
286 /** Control logic for head-tracking, etc. */
287 std::shared_ptr<SpatializerPoseController> mPoseController GUARDED_BY(mLock);
288
289 /** Last requested head tracking mode */
290 media::HeadTrackingMode mDesiredHeadTrackingMode GUARDED_BY(mLock)
291 = media::HeadTrackingMode::STATIC;
292
293 /** Last-reported actual head-tracking mode. */
294 media::SpatializerHeadTrackingMode mActualHeadTrackingMode GUARDED_BY(mLock)
295 = media::SpatializerHeadTrackingMode::DISABLED;
296
297 /** Selected Head pose sensor */
298 ASensorRef mHeadSensor GUARDED_BY(mLock) = nullptr;
299
300 /** Selected Screen pose sensor */
301 ASensorRef mScreenSensor GUARDED_BY(mLock) = nullptr;
302
303 /** Last display orientation received */
304 static constexpr float kDisplayOrientationInvalid = 1000;
305 float mDisplayOrientation GUARDED_BY(mLock) = kDisplayOrientationInvalid;
306
307 std::vector<media::SpatializationLevel> mLevels;
308 std::vector<media::SpatializationMode> mSpatializationModes;
309 std::vector<audio_channel_mask_t> mChannelMasks;
310 bool mSupportsHeadTracking;
Eric Laurent8a4259f2021-09-14 16:04:00 +0200311
312 // Looper thread for mEngine callbacks
313 class EngineCallbackHandler;
314
315 sp<ALooper> mLooper;
316 sp<EngineCallbackHandler> mHandler;
317
318 static const std::vector<const char *> sHeadPoseKeys;
Eric Laurent6d607012021-07-05 11:54:40 +0200319};
320
321
322}; // namespace android
323
324#endif // ANDROID_MEDIA_SPATIALIZER_H