blob: a45290bea2bc93118fb38492203759534cb8b3d1 [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 Laurent6d607012021-07-05 11:54:40 +020027#include <media/AudioEffect.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020028#include <system/audio_effects/effect_spatializer.h>
Eric Laurent6d607012021-07-05 11:54:40 +020029
Eric Laurent2be8b292021-08-23 09:44:33 -070030#include "SpatializerPoseController.h"
Eric Laurent6d607012021-07-05 11:54:40 +020031
32namespace android {
33
34
35// ----------------------------------------------------------------------------
36
37/**
38 * A callback interface from the Spatializer object or its parent AudioPolicyService.
39 * This is implemented by the audio policy service hosting the Spatializer to perform
40 * actions needed when a state change inside the Spatializer requires some audio system
41 * changes that cannot be performed by the Spatializer. For instance opening or closing a
42 * spatializer output stream when the spatializer is enabled or disabled
43 */
44class SpatializerPolicyCallback {
45public:
46 /** Called when a stage change occurs that requires the parent audio policy service to take
47 * some action.
48 */
49 virtual void onCheckSpatializer() = 0;
50
51 virtual ~SpatializerPolicyCallback() = default;
52};
53/**
54 * The Spatializer class implements all functional controlling the multichannel spatializer
55 * with head tracking implementation in the native audio service: audio policy and audio flinger.
56 * It presents an AIDL interface available to the java audio service to discover the availability
57 * of the feature and options, control its state and register an active head tracking sensor.
58 * It maintains the current state of the platform spatializer and applies the stored parameters
59 * when the spatializer engine is created and enabled.
60 * Based on the requested spatializer level, it will request the creation of a specialized output
61 * mixer to the audio policy service which will in turn notify the Spatializer of the output
62 * stream on which a spatializer engine should be created, configured and enabled.
63 * The spatializer also hosts the head tracking management logic. This logic receives the
64 * desired head tracking mode and selected head tracking sensor, registers a sensor event listener
65 * and derives the compounded head pose information to the spatializer engine.
66 *
67 * Workflow:
68 * - Initialization: when the audio policy service starts, it checks if a spatializer effect
69 * engine exists and if the audio policy manager reports a dedicated spatializer output profile.
70 * If both conditions are met, a Spatializer object is created
71 * - Capabilities discovery: AudioService will call AudioSystem::canBeSpatialized() and if true,
72 * acquire an ISpatializer interface with AudioSystem::getSpatializer(). This interface
73 * will be used to query the implementation capabilities and configure the spatializer.
74 * - Enabling: when ISpatializer::setLevel() sets a level different from NONE the spatializer
75 * is considered enabled. The audio policy callback onCheckSpatializer() is called. This
76 * triggers a request to audio policy manager to open a spatialization output stream and a
77 * spatializer mixer is created in audio flinger. When an output is returned by audio policy
78 * manager, Spatializer::attachOutput() is called which creates and enables the spatializer
79 * stage engine on the specified output.
80 * - Disabling: when the spatialization level is set to NONE, the spatializer is considered
81 * disabled. The audio policy callback onCheckSpatializer() is called. This triggers a call
82 * to Spatializer::detachOutput() and the spatializer engine is released. Then a request is
83 * made to audio policy manager to release and close the spatializer output stream and the
84 * spatializer mixer thread is destroyed.
85 */
Eric Laurent2be8b292021-08-23 09:44:33 -070086class Spatializer : public media::BnSpatializer,
87 public IBinder::DeathRecipient,
88 private SpatializerPoseController::Listener {
89 public:
Eric Laurent6d607012021-07-05 11:54:40 +020090 static sp<Spatializer> create(SpatializerPolicyCallback *callback);
91
92 ~Spatializer() override;
93
94 /** ISpatializer, see ISpatializer.aidl */
95 binder::Status release() override;
96 binder::Status getSupportedLevels(std::vector<media::SpatializationLevel>* levels) override;
97 binder::Status setLevel(media::SpatializationLevel level) override;
98 binder::Status getLevel(media::SpatializationLevel *level) override;
99 binder::Status getSupportedHeadTrackingModes(
Ytai Ben-Tsvia16a9df2021-08-05 08:57:06 -0700100 std::vector<media::SpatializerHeadTrackingMode>* modes) override;
101 binder::Status setDesiredHeadTrackingMode(
102 media::SpatializerHeadTrackingMode mode) override;
103 binder::Status getActualHeadTrackingMode(
104 media::SpatializerHeadTrackingMode* mode) override;
105 binder::Status recenterHeadTracker() override;
Eric Laurent6d607012021-07-05 11:54:40 +0200106 binder::Status setGlobalTransform(const std::vector<float>& screenToStage) override;
Eric Laurent2be8b292021-08-23 09:44:33 -0700107 binder::Status setHeadSensor(int sensorHandle) override;
108 binder::Status setScreenSensor(int sensorHandle) override;
109 binder::Status setDisplayOrientation(float physicalToLogicalAngle) override;
110 binder::Status setHingeAngle(float hingeAngle) override;
111 binder::Status getSupportedModes(std::vector<media::SpatializationMode>* modes) override;
112
Eric Laurent6d607012021-07-05 11:54:40 +0200113
114 /** IBinder::DeathRecipient. Listen to the death of the INativeSpatializerCallback. */
115 virtual void binderDied(const wp<IBinder>& who);
116
117 /** Registers a INativeSpatializerCallback when a client is attached to this Spatializer
118 * by audio policy service.
119 */
120 status_t registerCallback(const sp<media::INativeSpatializerCallback>& callback);
121
Eric Laurent2be8b292021-08-23 09:44:33 -0700122 status_t loadEngineConfiguration(sp<EffectHalInterface> effect);
123
Eric Laurent6d607012021-07-05 11:54:40 +0200124 /** Level getter for use by local classes. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700125 media::SpatializationLevel getLevel() const { std::lock_guard lock(mLock); return mLevel; }
Eric Laurent6d607012021-07-05 11:54:40 +0200126
127 /** Called by audio policy service when the special output mixer dedicated to spatialization
128 * is opened and the spatializer engine must be created.
129 */
130 status_t attachOutput(audio_io_handle_t output);
131 /** Called by audio policy service when the special output mixer dedicated to spatialization
132 * is closed and the spatializer engine must be release.
133 */
134 audio_io_handle_t detachOutput();
135 /** Returns the output stream the spatializer is attached to. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700136 audio_io_handle_t getOutput() const { std::lock_guard lock(mLock); return mOutput; }
Eric Laurent6d607012021-07-05 11:54:40 +0200137
138 /** Gets the channel mask, sampling rate and format set for the spatializer input. */
Eric Laurent2be8b292021-08-23 09:44:33 -0700139 audio_config_base_t getAudioInConfig() const;
Eric Laurent6d607012021-07-05 11:54:40 +0200140
141 /** An implementation of an IEffect interface that can be used to pass advanced parameters to
142 * the spatializer engine. All APis are noop (i.e. the interface cannot be used to control
143 * the effect) except for passing parameters via the command() API. */
144 class EffectClient: public android::media::BnEffect {
145 public:
146
147 EffectClient(const sp<media::IEffectClient>& effectClient,
148 Spatializer& parent);
149 virtual ~EffectClient();
150
151 // IEffect
152 android::binder::Status enable(int32_t* _aidl_return) override;
153 android::binder::Status disable(int32_t* _aidl_return) override;
154 android::binder::Status command(int32_t cmdCode,
155 const std::vector<uint8_t>& cmdData,
156 int32_t maxResponseSize,
157 std::vector<uint8_t>* response,
158 int32_t* _aidl_return) override;
159 android::binder::Status disconnect() override;
160 android::binder::Status getCblk(media::SharedFileRegion* _aidl_return) override;
161
162 private:
163 const sp<media::IEffectClient> mEffectClient;
164 sp<IMemory> mCblkMemory;
165 const Spatializer& mParent;
166 bool mDisconnected = false;
167 };
168
169private:
Eric Laurent6d607012021-07-05 11:54:40 +0200170 Spatializer(effect_descriptor_t engineDescriptor,
171 SpatializerPolicyCallback *callback);
172
Eric Laurent6d607012021-07-05 11:54:40 +0200173 static void engineCallback(int32_t event, void* user, void *info);
174
Eric Laurent2be8b292021-08-23 09:44:33 -0700175 // From VirtualizerStageController::Listener
176 void onHeadToStagePose(const media::Pose3f& headToStage) override;
177 void onActualModeChange(media::HeadTrackingMode mode) override;
178
179 void calculateHeadPose();
180
181 static ConversionResult<ASensorRef> getSensorFromHandle(int handle);
182
183 static constexpr int kMaxEffectParamValues = 10;
184 /**
185 * Get a parameter from spatializer engine by calling the effect HAL command method directly.
186 * To be used when the engine instance mEngine is not yet created in the effect framework.
187 * When MULTI_VALUES is false, the expected reply is only one value of type T.
188 * When MULTI_VALUES is true, the expected reply is made of a number (of type T) indicating
189 * how many values are returned, followed by this number for values of type T.
190 */
191 template<bool MULTI_VALUES, typename T>
192 status_t getHalParameter(sp<EffectHalInterface> effect, uint32_t type,
193 std::vector<T> *values) {
194 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
195
196 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1];
197 uint32_t reply[sizeof(effect_param_t) / sizeof(uint32_t) + 2 + kMaxEffectParamValues];
198
199 effect_param_t *p = (effect_param_t *)cmd;
200 p->psize = sizeof(uint32_t);
201 if (MULTI_VALUES) {
202 p->vsize = (kMaxEffectParamValues + 1) * sizeof(T);
203 } else {
204 p->vsize = sizeof(T);
205 }
206 *(uint32_t *)p->data = type;
207 uint32_t replySize = sizeof(effect_param_t) + p->psize + p->vsize;
208
209 status_t status = effect->command(EFFECT_CMD_GET_PARAM,
210 sizeof(effect_param_t) + sizeof(uint32_t), cmd,
211 &replySize, reply);
212 if (status != NO_ERROR) {
213 return status;
214 }
215 if (p->status != NO_ERROR) {
216 return p->status;
217 }
218 if (replySize <
219 sizeof(effect_param_t) + sizeof(uint32_t) + (MULTI_VALUES ? 2 : 1) * sizeof(T)) {
220 return BAD_VALUE;
221 }
222
223 T *params = (T *)((uint8_t *)reply + sizeof(effect_param_t) + sizeof(uint32_t));
224 int numParams = 1;
225 if (MULTI_VALUES) {
226 numParams = (int)*params++;
227 }
228 if (numParams > kMaxEffectParamValues) {
229 return BAD_VALUE;
230 }
231 std::copy(&params[0], &params[numParams], back_inserter(*values));
232 return NO_ERROR;
233 }
234
235 /**
236 * Set a parameter to spatializer engine by calling setParameter on mEngine AudioEffect object.
237 * It is possible to pass more than one value of type T according to the parameter type
238 * according to values vector size.
239 */
240 template<typename T>
241 status_t setEffectParameter_l(uint32_t type, const std::vector<T>& values) REQUIRES(mLock) {
242 static_assert(sizeof(T) <= sizeof(uint32_t), "The size of T must less than 32 bits");
243
244 uint32_t cmd[sizeof(effect_param_t) / sizeof(uint32_t) + 1 + values.size()];
245 effect_param_t *p = (effect_param_t *)cmd;
246 p->psize = sizeof(uint32_t);
247 p->vsize = sizeof(T) * values.size();
248 *(uint32_t *)p->data = type;
249 memcpy((uint32_t *)p->data + 1, values.data(), sizeof(T) * values.size());
250
251 return mEngine->setParameter(p);
252 }
253
Eric Laurent6d607012021-07-05 11:54:40 +0200254 /** Effect engine descriptor */
255 const effect_descriptor_t mEngineDescriptor;
256 /** Callback interface to parent audio policy service */
257 SpatializerPolicyCallback* mPolicyCallback;
258
259 /** Mutex protecting internal state */
Eric Laurent2be8b292021-08-23 09:44:33 -0700260 mutable std::mutex mLock;
Eric Laurent6d607012021-07-05 11:54:40 +0200261
262 /** Client AudioEffect for the engine */
263 sp<AudioEffect> mEngine GUARDED_BY(mLock);
264 /** Output stream the spatializer mixer thread is attached to */
265 audio_io_handle_t mOutput GUARDED_BY(mLock) = AUDIO_IO_HANDLE_NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200266
267 /** Callback interface to the client (AudioService) controlling this`Spatializer */
268 sp<media::INativeSpatializerCallback> mSpatializerCallback GUARDED_BY(mLock);
269
270 /** Requested spatialization level */
271 media::SpatializationLevel mLevel GUARDED_BY(mLock) = media::SpatializationLevel::NONE;
Eric Laurent6d607012021-07-05 11:54:40 +0200272
273 /** Extended IEffect interface is one has been created */
274 sp<EffectClient> mEffectClient GUARDED_BY(mLock);
Eric Laurent2be8b292021-08-23 09:44:33 -0700275
276 /** Control logic for head-tracking, etc. */
277 std::shared_ptr<SpatializerPoseController> mPoseController GUARDED_BY(mLock);
278
279 /** Last requested head tracking mode */
280 media::HeadTrackingMode mDesiredHeadTrackingMode GUARDED_BY(mLock)
281 = media::HeadTrackingMode::STATIC;
282
283 /** Last-reported actual head-tracking mode. */
284 media::SpatializerHeadTrackingMode mActualHeadTrackingMode GUARDED_BY(mLock)
285 = media::SpatializerHeadTrackingMode::DISABLED;
286
287 /** Selected Head pose sensor */
288 ASensorRef mHeadSensor GUARDED_BY(mLock) = nullptr;
289
290 /** Selected Screen pose sensor */
291 ASensorRef mScreenSensor GUARDED_BY(mLock) = nullptr;
292
293 /** Last display orientation received */
294 static constexpr float kDisplayOrientationInvalid = 1000;
295 float mDisplayOrientation GUARDED_BY(mLock) = kDisplayOrientationInvalid;
296
297 std::vector<media::SpatializationLevel> mLevels;
298 std::vector<media::SpatializationMode> mSpatializationModes;
299 std::vector<audio_channel_mask_t> mChannelMasks;
300 bool mSupportsHeadTracking;
Eric Laurent6d607012021-07-05 11:54:40 +0200301};
302
303
304}; // namespace android
305
306#endif // ANDROID_MEDIA_SPATIALIZER_H