blob: 6716d73e3c6b8140508c1fab5163d764d683c9f3 [file] [log] [blame]
Eric Laurentca7cc822012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, 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
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
rago94a1ee82017-07-21 15:11:02 -070022#include <algorithm>
23
Glenn Kasten153b9fe2013-07-15 11:23:36 -070024#include "Configuration.h"
Eric Laurentca7cc822012-11-19 14:55:58 -080025#include <utils/Log.h>
Eric Laurentd8365c52017-07-16 15:27:05 -070026#include <system/audio_effects/effect_aec.h>
Eric Laurentb62d0362021-10-26 17:40:18 +020027#include <system/audio_effects/effect_downmix.h>
Ricardo Garciac2a3a822019-07-17 14:29:12 -070028#include <system/audio_effects/effect_dynamicsprocessing.h>
jiabineb3bda02020-06-30 14:07:03 -070029#include <system/audio_effects/effect_hapticgenerator.h>
Eric Laurentd8365c52017-07-16 15:27:05 -070030#include <system/audio_effects/effect_ns.h>
Eric Laurentb62d0362021-10-26 17:40:18 +020031#include <system/audio_effects/effect_spatializer.h>
Eric Laurentd8365c52017-07-16 15:27:05 -070032#include <system/audio_effects/effect_visualizer.h>
Andy Hung9aad48c2017-11-29 10:29:19 -080033#include <audio_utils/channels.h>
Eric Laurentca7cc822012-11-19 14:55:58 -080034#include <audio_utils/primitives.h>
Mikhail Naganovf698ff22020-03-31 10:07:29 -070035#include <media/AudioCommonTypes.h>
jiabin8f278ee2019-11-11 12:16:27 -080036#include <media/AudioContainers.h>
Mikhail Naganov424c4f52017-07-19 17:54:29 -070037#include <media/AudioEffect.h>
jiabin8f278ee2019-11-11 12:16:27 -080038#include <media/AudioDeviceTypeAddr.h>
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -070039#include <media/ShmemCompat.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070040#include <media/audiohal/EffectHalInterface.h>
41#include <media/audiohal/EffectsFactoryHalInterface.h>
Andy Hungc747c532022-03-07 21:41:14 -080042#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070043#include <mediautils/ServiceUtilities.h>
Andy Hunga2a1ac32022-03-18 16:12:11 -070044#include <mediautils/TimeCheck.h>
Eric Laurentca7cc822012-11-19 14:55:58 -080045
46#include "AudioFlinger.h"
Andy Hungba8e52b2023-05-11 14:33:03 -070047#include "EffectConfiguration.h"
Eric Laurentca7cc822012-11-19 14:55:58 -080048
49// ----------------------------------------------------------------------------
50
51// Note: the following macro is used for extremely verbose logging message. In
52// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
53// 0; but one side effect of this is to turn all LOGV's as well. Some messages
54// are so verbose that we want to suppress them even when we have ALOG_ASSERT
55// turned on. Do not uncomment the #def below unless you really know what you
56// are doing and want to see all of the extremely verbose messages.
57//#define VERY_VERY_VERBOSE_LOGGING
58#ifdef VERY_VERY_VERBOSE_LOGGING
59#define ALOGVV ALOGV
60#else
61#define ALOGVV(a...) do { } while(0)
62#endif
63
Yuuki Yokoyamae17f8312017-05-26 19:06:33 +090064#define DEFAULT_OUTPUT_SAMPLE_RATE 48000
65
Eric Laurentca7cc822012-11-19 14:55:58 -080066namespace android {
67
Andy Hung1131b6e2020-12-08 20:47:45 -080068using aidl_utils::statusTFromBinderStatus;
Andy Hungba8e52b2023-05-11 14:33:03 -070069using audioflinger::EffectConfiguration;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -070070using binder::Status;
71
72namespace {
73
74// Append a POD value into a vector of bytes.
75template<typename T>
76void appendToBuffer(const T& value, std::vector<uint8_t>* buffer) {
77 const uint8_t* ar(reinterpret_cast<const uint8_t*>(&value));
78 buffer->insert(buffer->end(), ar, ar + sizeof(T));
79}
80
81// Write a POD value into a vector of bytes (clears the previous buffer
82// content).
83template<typename T>
84void writeToBuffer(const T& value, std::vector<uint8_t>* buffer) {
85 buffer->clear();
86 appendToBuffer(value, buffer);
87}
88
89} // namespace
90
Eric Laurentca7cc822012-11-19 14:55:58 -080091// ----------------------------------------------------------------------------
Eric Laurent41709552019-12-16 19:34:05 -080092// EffectBase implementation
Eric Laurentca7cc822012-11-19 14:55:58 -080093// ----------------------------------------------------------------------------
94
95#undef LOG_TAG
Eric Laurent41709552019-12-16 19:34:05 -080096#define LOG_TAG "AudioFlinger::EffectBase"
Eric Laurentca7cc822012-11-19 14:55:58 -080097
Eric Laurent41709552019-12-16 19:34:05 -080098AudioFlinger::EffectBase::EffectBase(const sp<AudioFlinger::EffectCallbackInterface>& callback,
Eric Laurentca7cc822012-11-19 14:55:58 -080099 effect_descriptor_t *desc,
100 int id,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800101 audio_session_t sessionId,
102 bool pinned)
103 : mPinned(pinned),
Eric Laurent6b446ce2019-12-13 10:56:31 -0800104 mCallback(callback), mId(id), mSessionId(sessionId),
Eric Laurent41709552019-12-16 19:34:05 -0800105 mDescriptor(*desc)
Eric Laurentca7cc822012-11-19 14:55:58 -0800106{
Eric Laurentca7cc822012-11-19 14:55:58 -0800107}
108
Eric Laurent41709552019-12-16 19:34:05 -0800109// must be called with EffectModule::mLock held
110status_t AudioFlinger::EffectBase::setEnabled_l(bool enabled)
Eric Laurentca7cc822012-11-19 14:55:58 -0800111{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800112
Eric Laurent41709552019-12-16 19:34:05 -0800113 ALOGV("setEnabled %p enabled %d", this, enabled);
114
115 if (enabled != isEnabled()) {
116 switch (mState) {
117 // going from disabled to enabled
118 case IDLE:
119 mState = STARTING;
120 break;
121 case STOPPED:
122 mState = RESTART;
123 break;
124 case STOPPING:
125 mState = ACTIVE;
126 break;
127
128 // going from enabled to disabled
129 case RESTART:
130 mState = STOPPED;
131 break;
132 case STARTING:
133 mState = IDLE;
134 break;
135 case ACTIVE:
136 mState = STOPPING;
137 break;
138 case DESTROYED:
139 return NO_ERROR; // simply ignore as we are being destroyed
140 }
141 for (size_t i = 1; i < mHandles.size(); i++) {
142 EffectHandle *h = mHandles[i];
143 if (h != NULL && !h->disconnected()) {
144 h->setEnabled(enabled);
145 }
146 }
147 }
148 return NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -0800149}
150
Eric Laurent41709552019-12-16 19:34:05 -0800151status_t AudioFlinger::EffectBase::setEnabled(bool enabled, bool fromHandle)
152{
153 status_t status;
154 {
155 Mutex::Autolock _l(mLock);
156 status = setEnabled_l(enabled);
157 }
158 if (fromHandle) {
159 if (enabled) {
160 if (status != NO_ERROR) {
Andy Hungfda44002021-06-03 17:23:16 -0700161 getCallback()->checkSuspendOnEffectEnabled(this, false, false /*threadLocked*/);
Eric Laurent41709552019-12-16 19:34:05 -0800162 } else {
Andy Hungfda44002021-06-03 17:23:16 -0700163 getCallback()->onEffectEnable(this);
Eric Laurent41709552019-12-16 19:34:05 -0800164 }
165 } else {
Andy Hungfda44002021-06-03 17:23:16 -0700166 getCallback()->onEffectDisable(this);
Eric Laurent41709552019-12-16 19:34:05 -0800167 }
168 }
169 return status;
170}
171
172bool AudioFlinger::EffectBase::isEnabled() const
173{
174 switch (mState) {
175 case RESTART:
176 case STARTING:
177 case ACTIVE:
178 return true;
179 case IDLE:
180 case STOPPING:
181 case STOPPED:
182 case DESTROYED:
183 default:
184 return false;
185 }
186}
187
188void AudioFlinger::EffectBase::setSuspended(bool suspended)
189{
190 Mutex::Autolock _l(mLock);
191 mSuspended = suspended;
192}
193
194bool AudioFlinger::EffectBase::suspended() const
195{
196 Mutex::Autolock _l(mLock);
197 return mSuspended;
198}
199
200status_t AudioFlinger::EffectBase::addHandle(EffectHandle *handle)
Eric Laurentca7cc822012-11-19 14:55:58 -0800201{
202 status_t status;
203
204 Mutex::Autolock _l(mLock);
205 int priority = handle->priority();
206 size_t size = mHandles.size();
207 EffectHandle *controlHandle = NULL;
208 size_t i;
209 for (i = 0; i < size; i++) {
210 EffectHandle *h = mHandles[i];
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800211 if (h == NULL || h->disconnected()) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800212 continue;
213 }
214 // first non destroyed handle is considered in control
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700215 if (controlHandle == NULL) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800216 controlHandle = h;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700217 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800218 if (h->priority() <= priority) {
219 break;
220 }
221 }
222 // if inserted in first place, move effect control from previous owner to this handle
223 if (i == 0) {
224 bool enabled = false;
225 if (controlHandle != NULL) {
226 enabled = controlHandle->enabled();
227 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
228 }
229 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
230 status = NO_ERROR;
231 } else {
232 status = ALREADY_EXISTS;
233 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700234 ALOGV("addHandle() %p added handle %p in position %zu", this, handle, i);
Eric Laurentca7cc822012-11-19 14:55:58 -0800235 mHandles.insertAt(handle, i);
236 return status;
237}
238
Eric Laurent41709552019-12-16 19:34:05 -0800239status_t AudioFlinger::EffectBase::updatePolicyState()
Eric Laurent6c796322019-04-09 14:13:17 -0700240{
241 status_t status = NO_ERROR;
242 bool doRegister = false;
243 bool registered = false;
244 bool doEnable = false;
245 bool enabled = false;
Mikhail Naganov379d6872020-03-26 13:04:11 -0700246 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -0800247 product_strategy_t strategy = PRODUCT_STRATEGY_NONE;
Eric Laurent6c796322019-04-09 14:13:17 -0700248
249 {
250 Mutex::Autolock _l(mLock);
Eric Laurentd66d7a12021-07-13 13:35:32 +0200251
252 if ((isInternal_l() && !mPolicyRegistered)
253 || !getCallback()->isAudioPolicyReady()) {
254 return NO_ERROR;
255 }
256
Eric Laurent6c796322019-04-09 14:13:17 -0700257 // register effect when first handle is attached and unregister when last handle is removed
258 if (mPolicyRegistered != mHandles.size() > 0) {
259 doRegister = true;
260 mPolicyRegistered = mHandles.size() > 0;
261 if (mPolicyRegistered) {
Andy Hungfda44002021-06-03 17:23:16 -0700262 const auto callback = getCallback();
263 io = callback->io();
264 strategy = callback->strategy();
Eric Laurent6c796322019-04-09 14:13:17 -0700265 }
266 }
267 // enable effect when registered according to enable state requested by controlling handle
268 if (mHandles.size() > 0) {
269 EffectHandle *handle = controlHandle_l();
270 if (handle != nullptr && mPolicyEnabled != handle->enabled()) {
271 doEnable = true;
272 mPolicyEnabled = handle->enabled();
273 }
274 }
275 registered = mPolicyRegistered;
276 enabled = mPolicyEnabled;
Eric Laurentb9d06642021-03-18 15:52:11 +0100277 // The simultaneous release of two EffectHandles with the same EffectModule
278 // may cause us to call this method at the same time.
279 // This may deadlock under some circumstances (b/180941720). Avoid this.
280 if (!doRegister && !(registered && doEnable)) {
281 return NO_ERROR;
282 }
Eric Laurent6c796322019-04-09 14:13:17 -0700283 }
fengjnlan46407562022-09-07 16:20:01 +0800284 mPolicyLock.lock();
Eric Laurent6c796322019-04-09 14:13:17 -0700285 ALOGV("%s name %s id %d session %d doRegister %d registered %d doEnable %d enabled %d",
286 __func__, mDescriptor.name, mId, mSessionId, doRegister, registered, doEnable, enabled);
287 if (doRegister) {
288 if (registered) {
289 status = AudioSystem::registerEffect(
290 &mDescriptor,
291 io,
292 strategy,
293 mSessionId,
294 mId);
295 } else {
296 status = AudioSystem::unregisterEffect(mId);
297 }
298 }
299 if (registered && doEnable) {
300 status = AudioSystem::setEffectEnabled(mId, enabled);
301 }
302 mPolicyLock.unlock();
303
304 return status;
305}
306
307
Eric Laurent41709552019-12-16 19:34:05 -0800308ssize_t AudioFlinger::EffectBase::removeHandle(EffectHandle *handle)
Eric Laurentca7cc822012-11-19 14:55:58 -0800309{
310 Mutex::Autolock _l(mLock);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800311 return removeHandle_l(handle);
312}
313
Eric Laurent41709552019-12-16 19:34:05 -0800314ssize_t AudioFlinger::EffectBase::removeHandle_l(EffectHandle *handle)
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800315{
Eric Laurentca7cc822012-11-19 14:55:58 -0800316 size_t size = mHandles.size();
317 size_t i;
318 for (i = 0; i < size; i++) {
319 if (mHandles[i] == handle) {
320 break;
321 }
322 }
323 if (i == size) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800324 ALOGW("%s %p handle not found %p", __FUNCTION__, this, handle);
325 return BAD_VALUE;
Eric Laurentca7cc822012-11-19 14:55:58 -0800326 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800327 ALOGV("removeHandle_l() %p removed handle %p in position %zu", this, handle, i);
Eric Laurentca7cc822012-11-19 14:55:58 -0800328
329 mHandles.removeAt(i);
330 // if removed from first place, move effect control from this handle to next in line
331 if (i == 0) {
332 EffectHandle *h = controlHandle_l();
333 if (h != NULL) {
334 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
335 }
336 }
337
Jaideep Sharmaed8688022020-08-07 14:09:16 +0530338 // Prevent calls to process() and other functions on effect interface from now on.
339 // The effect engine will be released by the destructor when the last strong reference on
340 // this object is released which can happen after next process is called.
Eric Laurentca7cc822012-11-19 14:55:58 -0800341 if (mHandles.size() == 0 && !mPinned) {
342 mState = DESTROYED;
343 }
344
345 return mHandles.size();
346}
347
348// must be called with EffectModule::mLock held
Eric Laurent41709552019-12-16 19:34:05 -0800349AudioFlinger::EffectHandle *AudioFlinger::EffectBase::controlHandle_l()
Eric Laurentca7cc822012-11-19 14:55:58 -0800350{
351 // the first valid handle in the list has control over the module
352 for (size_t i = 0; i < mHandles.size(); i++) {
353 EffectHandle *h = mHandles[i];
Eric Laurent0d5a2ed2016-12-01 15:28:29 -0800354 if (h != NULL && !h->disconnected()) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800355 return h;
356 }
357 }
358
359 return NULL;
360}
361
Eric Laurentf10c7092016-12-06 17:09:56 -0800362// unsafe method called when the effect parent thread has been destroyed
Eric Laurent41709552019-12-16 19:34:05 -0800363ssize_t AudioFlinger::EffectBase::disconnectHandle(EffectHandle *handle, bool unpinIfLast)
Eric Laurentf10c7092016-12-06 17:09:56 -0800364{
Andy Hungfda44002021-06-03 17:23:16 -0700365 const auto callback = getCallback();
Eric Laurentf10c7092016-12-06 17:09:56 -0800366 ALOGV("disconnect() %p handle %p", this, handle);
Andy Hungfda44002021-06-03 17:23:16 -0700367 if (callback->disconnectEffectHandle(handle, unpinIfLast)) {
Eric Laurent6b446ce2019-12-13 10:56:31 -0800368 return mHandles.size();
369 }
370
Eric Laurentf10c7092016-12-06 17:09:56 -0800371 Mutex::Autolock _l(mLock);
372 ssize_t numHandles = removeHandle_l(handle);
373 if ((numHandles == 0) && (!mPinned || unpinIfLast)) {
Eric Laurent6b446ce2019-12-13 10:56:31 -0800374 mLock.unlock();
Andy Hungfda44002021-06-03 17:23:16 -0700375 callback->updateOrphanEffectChains(this);
Eric Laurent6b446ce2019-12-13 10:56:31 -0800376 mLock.lock();
Eric Laurentf10c7092016-12-06 17:09:56 -0800377 }
378 return numHandles;
379}
380
Eric Laurent41709552019-12-16 19:34:05 -0800381bool AudioFlinger::EffectBase::purgeHandles()
382{
383 bool enabled = false;
384 Mutex::Autolock _l(mLock);
385 EffectHandle *handle = controlHandle_l();
386 if (handle != NULL) {
387 enabled = handle->enabled();
388 }
389 mHandles.clear();
390 return enabled;
391}
392
393void AudioFlinger::EffectBase::checkSuspendOnEffectEnabled(bool enabled, bool threadLocked) {
Andy Hungfda44002021-06-03 17:23:16 -0700394 getCallback()->checkSuspendOnEffectEnabled(this, enabled, threadLocked);
Eric Laurent41709552019-12-16 19:34:05 -0800395}
396
397static String8 effectFlagsToString(uint32_t flags) {
398 String8 s;
399
400 s.append("conn. mode: ");
401 switch (flags & EFFECT_FLAG_TYPE_MASK) {
402 case EFFECT_FLAG_TYPE_INSERT: s.append("insert"); break;
403 case EFFECT_FLAG_TYPE_AUXILIARY: s.append("auxiliary"); break;
404 case EFFECT_FLAG_TYPE_REPLACE: s.append("replace"); break;
405 case EFFECT_FLAG_TYPE_PRE_PROC: s.append("preproc"); break;
406 case EFFECT_FLAG_TYPE_POST_PROC: s.append("postproc"); break;
407 default: s.append("unknown/reserved"); break;
408 }
409 s.append(", ");
410
411 s.append("insert pref: ");
412 switch (flags & EFFECT_FLAG_INSERT_MASK) {
413 case EFFECT_FLAG_INSERT_ANY: s.append("any"); break;
414 case EFFECT_FLAG_INSERT_FIRST: s.append("first"); break;
415 case EFFECT_FLAG_INSERT_LAST: s.append("last"); break;
416 case EFFECT_FLAG_INSERT_EXCLUSIVE: s.append("exclusive"); break;
417 default: s.append("unknown/reserved"); break;
418 }
419 s.append(", ");
420
421 s.append("volume mgmt: ");
422 switch (flags & EFFECT_FLAG_VOLUME_MASK) {
423 case EFFECT_FLAG_VOLUME_NONE: s.append("none"); break;
424 case EFFECT_FLAG_VOLUME_CTRL: s.append("implements control"); break;
425 case EFFECT_FLAG_VOLUME_IND: s.append("requires indication"); break;
426 case EFFECT_FLAG_VOLUME_MONITOR: s.append("monitors volume"); break;
427 default: s.append("unknown/reserved"); break;
428 }
429 s.append(", ");
430
431 uint32_t devind = flags & EFFECT_FLAG_DEVICE_MASK;
432 if (devind) {
433 s.append("device indication: ");
434 switch (devind) {
435 case EFFECT_FLAG_DEVICE_IND: s.append("requires updates"); break;
436 default: s.append("unknown/reserved"); break;
437 }
438 s.append(", ");
439 }
440
441 s.append("input mode: ");
442 switch (flags & EFFECT_FLAG_INPUT_MASK) {
443 case EFFECT_FLAG_INPUT_DIRECT: s.append("direct"); break;
444 case EFFECT_FLAG_INPUT_PROVIDER: s.append("provider"); break;
445 case EFFECT_FLAG_INPUT_BOTH: s.append("direct+provider"); break;
446 default: s.append("not set"); break;
447 }
448 s.append(", ");
449
450 s.append("output mode: ");
451 switch (flags & EFFECT_FLAG_OUTPUT_MASK) {
452 case EFFECT_FLAG_OUTPUT_DIRECT: s.append("direct"); break;
453 case EFFECT_FLAG_OUTPUT_PROVIDER: s.append("provider"); break;
454 case EFFECT_FLAG_OUTPUT_BOTH: s.append("direct+provider"); break;
455 default: s.append("not set"); break;
456 }
457 s.append(", ");
458
459 uint32_t accel = flags & EFFECT_FLAG_HW_ACC_MASK;
460 if (accel) {
461 s.append("hardware acceleration: ");
462 switch (accel) {
463 case EFFECT_FLAG_HW_ACC_SIMPLE: s.append("non-tunneled"); break;
464 case EFFECT_FLAG_HW_ACC_TUNNEL: s.append("tunneled"); break;
465 default: s.append("unknown/reserved"); break;
466 }
467 s.append(", ");
468 }
469
470 uint32_t modeind = flags & EFFECT_FLAG_AUDIO_MODE_MASK;
471 if (modeind) {
472 s.append("mode indication: ");
473 switch (modeind) {
474 case EFFECT_FLAG_AUDIO_MODE_IND: s.append("required"); break;
475 default: s.append("unknown/reserved"); break;
476 }
477 s.append(", ");
478 }
479
480 uint32_t srcind = flags & EFFECT_FLAG_AUDIO_SOURCE_MASK;
481 if (srcind) {
482 s.append("source indication: ");
483 switch (srcind) {
484 case EFFECT_FLAG_AUDIO_SOURCE_IND: s.append("required"); break;
485 default: s.append("unknown/reserved"); break;
486 }
487 s.append(", ");
488 }
489
490 if (flags & EFFECT_FLAG_OFFLOAD_MASK) {
491 s.append("offloadable, ");
492 }
493
494 int len = s.length();
495 if (s.length() > 2) {
496 (void) s.lockBuffer(len);
497 s.unlockBuffer(len - 2);
498 }
499 return s;
500}
501
502void AudioFlinger::EffectBase::dump(int fd, const Vector<String16>& args __unused)
Andy Hung920f6572022-10-06 12:09:49 -0700503NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent41709552019-12-16 19:34:05 -0800504{
505 String8 result;
506
507 result.appendFormat("\tEffect ID %d:\n", mId);
508
509 bool locked = AudioFlinger::dumpTryLock(mLock);
510 // failed to lock - AudioFlinger is probably deadlocked
511 if (!locked) {
512 result.append("\t\tCould not lock Fx mutex:\n");
513 }
514
515 result.append("\t\tSession State Registered Enabled Suspended:\n");
516 result.appendFormat("\t\t%05d %03d %s %s %s\n",
517 mSessionId, mState, mPolicyRegistered ? "y" : "n",
518 mPolicyEnabled ? "y" : "n", mSuspended ? "y" : "n");
519
520 result.append("\t\tDescriptor:\n");
521 char uuidStr[64];
522 AudioEffect::guidToString(&mDescriptor.uuid, uuidStr, sizeof(uuidStr));
523 result.appendFormat("\t\t- UUID: %s\n", uuidStr);
524 AudioEffect::guidToString(&mDescriptor.type, uuidStr, sizeof(uuidStr));
525 result.appendFormat("\t\t- TYPE: %s\n", uuidStr);
526 result.appendFormat("\t\t- apiVersion: %08X\n\t\t- flags: %08X (%s)\n",
527 mDescriptor.apiVersion,
528 mDescriptor.flags,
529 effectFlagsToString(mDescriptor.flags).string());
530 result.appendFormat("\t\t- name: %s\n",
531 mDescriptor.name);
532
533 result.appendFormat("\t\t- implementor: %s\n",
534 mDescriptor.implementor);
535
536 result.appendFormat("\t\t%zu Clients:\n", mHandles.size());
537 result.append("\t\t\t Pid Priority Ctrl Locked client server\n");
538 char buffer[256];
539 for (size_t i = 0; i < mHandles.size(); ++i) {
540 EffectHandle *handle = mHandles[i];
541 if (handle != NULL && !handle->disconnected()) {
542 handle->dumpToBuffer(buffer, sizeof(buffer));
543 result.append(buffer);
544 }
545 }
546 if (locked) {
547 mLock.unlock();
548 }
549
550 write(fd, result.string(), result.length());
551}
552
553// ----------------------------------------------------------------------------
554// EffectModule implementation
555// ----------------------------------------------------------------------------
556
557#undef LOG_TAG
558#define LOG_TAG "AudioFlinger::EffectModule"
559
560AudioFlinger::EffectModule::EffectModule(const sp<AudioFlinger::EffectCallbackInterface>& callback,
561 effect_descriptor_t *desc,
562 int id,
563 audio_session_t sessionId,
Eric Laurentb82e6b72019-11-22 17:25:04 -0800564 bool pinned,
565 audio_port_handle_t deviceId)
Eric Laurent41709552019-12-16 19:34:05 -0800566 : EffectBase(callback, desc, id, sessionId, pinned),
567 // clear mConfig to ensure consistent initial value of buffer framecount
568 // in case buffers are associated by setInBuffer() or setOutBuffer()
569 // prior to configure().
570 mConfig{{}, {}},
571 mStatus(NO_INIT),
572 mMaxDisableWaitCnt(1), // set by configure(), should be >= 1
573 mDisableWaitCnt(0), // set by process() and updateState()
David Li6c8ac4b2021-06-22 22:17:52 +0800574 mOffloaded(false),
Mikhail Naganov8d7da002022-04-19 21:21:23 +0000575 mIsOutput(false)
Eric Laurent41709552019-12-16 19:34:05 -0800576 , mSupportsFloat(false)
Eric Laurent41709552019-12-16 19:34:05 -0800577{
578 ALOGV("Constructor %p pinned %d", this, pinned);
579 int lStatus;
580
581 // create effect engine from effect factory
582 mStatus = callback->createEffectHal(
Eric Laurentb82e6b72019-11-22 17:25:04 -0800583 &desc->uuid, sessionId, deviceId, &mEffectInterface);
Eric Laurent41709552019-12-16 19:34:05 -0800584 if (mStatus != NO_ERROR) {
585 return;
586 }
587 lStatus = init();
588 if (lStatus < 0) {
589 mStatus = lStatus;
590 goto Error;
591 }
592
593 setOffloaded(callback->isOffload(), callback->io());
594 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface.get());
595
596 return;
597Error:
598 mEffectInterface.clear();
599 ALOGV("Constructor Error %d", mStatus);
600}
601
602AudioFlinger::EffectModule::~EffectModule()
603{
604 ALOGV("Destructor %p", this);
605 if (mEffectInterface != 0) {
606 char uuidStr[64];
607 AudioEffect::guidToString(&mDescriptor.uuid, uuidStr, sizeof(uuidStr));
608 ALOGW("EffectModule %p destructor called with unreleased interface, effect %s",
609 this, uuidStr);
610 release_l();
611 }
612
613}
614
Eric Laurentfa1e1232016-08-02 19:01:49 -0700615bool AudioFlinger::EffectModule::updateState() {
Eric Laurentca7cc822012-11-19 14:55:58 -0800616 Mutex::Autolock _l(mLock);
617
Eric Laurentfa1e1232016-08-02 19:01:49 -0700618 bool started = false;
Eric Laurentca7cc822012-11-19 14:55:58 -0800619 switch (mState) {
620 case RESTART:
621 reset_l();
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -0700622 FALLTHROUGH_INTENDED;
Eric Laurentca7cc822012-11-19 14:55:58 -0800623
624 case STARTING:
625 // clear auxiliary effect input buffer for next accumulation
626 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
627 memset(mConfig.inputCfg.buffer.raw,
628 0,
629 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
630 }
Eric Laurentd0ebb532013-04-02 16:41:41 -0700631 if (start_l() == NO_ERROR) {
632 mState = ACTIVE;
Eric Laurentfa1e1232016-08-02 19:01:49 -0700633 started = true;
Eric Laurentd0ebb532013-04-02 16:41:41 -0700634 } else {
635 mState = IDLE;
636 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800637 break;
638 case STOPPING:
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +0900639 // volume control for offload and direct threads must take effect immediately.
640 if (stop_l() == NO_ERROR
641 && !(isVolumeControl() && isOffloadedOrDirect())) {
Eric Laurentd0ebb532013-04-02 16:41:41 -0700642 mDisableWaitCnt = mMaxDisableWaitCnt;
643 } else {
644 mDisableWaitCnt = 1; // will cause immediate transition to IDLE
645 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800646 mState = STOPPED;
647 break;
648 case STOPPED:
649 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
650 // turn off sequence.
651 if (--mDisableWaitCnt == 0) {
652 reset_l();
653 mState = IDLE;
654 }
655 break;
Eric Laurentde8caf42021-08-11 17:19:25 +0200656 case ACTIVE:
657 for (size_t i = 0; i < mHandles.size(); i++) {
658 if (!mHandles[i]->disconnected()) {
659 mHandles[i]->framesProcessed(mConfig.inputCfg.buffer.frameCount);
660 }
661 }
662 break;
Eric Laurentca7cc822012-11-19 14:55:58 -0800663 default: //IDLE , ACTIVE, DESTROYED
664 break;
665 }
Eric Laurentfa1e1232016-08-02 19:01:49 -0700666
667 return started;
Eric Laurentca7cc822012-11-19 14:55:58 -0800668}
669
670void AudioFlinger::EffectModule::process()
671{
672 Mutex::Autolock _l(mLock);
673
Mikhail Naganov022b9952017-01-04 16:36:51 -0800674 if (mState == DESTROYED || mEffectInterface == 0 || mInBuffer == 0 || mOutBuffer == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800675 return;
676 }
677
rago94a1ee82017-07-21 15:11:02 -0700678 const uint32_t inChannelCount =
679 audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
680 const uint32_t outChannelCount =
681 audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
682 const bool auxType =
683 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY;
684
Andy Hungfa69ca32017-11-30 10:07:53 -0800685 // safeInputOutputSampleCount is 0 if the channel count between input and output
686 // buffers do not match. This prevents automatic accumulation or copying between the
687 // input and output effect buffers without an intermediary effect process.
688 // TODO: consider implementing channel conversion.
689 const size_t safeInputOutputSampleCount =
Andy Hungdd2e7a82018-10-31 14:19:13 -0700690 mInChannelCountRequested != mOutChannelCountRequested ? 0
691 : mOutChannelCountRequested * std::min(
Andy Hungfa69ca32017-11-30 10:07:53 -0800692 mConfig.inputCfg.buffer.frameCount,
693 mConfig.outputCfg.buffer.frameCount);
694 const auto accumulateInputToOutput = [this, safeInputOutputSampleCount]() {
Andy Hungfa69ca32017-11-30 10:07:53 -0800695 accumulate_float(
696 mConfig.outputCfg.buffer.f32,
697 mConfig.inputCfg.buffer.f32,
698 safeInputOutputSampleCount);
Andy Hungfa69ca32017-11-30 10:07:53 -0800699 };
700 const auto copyInputToOutput = [this, safeInputOutputSampleCount]() {
Andy Hungfa69ca32017-11-30 10:07:53 -0800701 memcpy(
702 mConfig.outputCfg.buffer.f32,
703 mConfig.inputCfg.buffer.f32,
704 safeInputOutputSampleCount * sizeof(*mConfig.outputCfg.buffer.f32));
Andy Hungfa69ca32017-11-30 10:07:53 -0800705 };
706
Eric Laurentca7cc822012-11-19 14:55:58 -0800707 if (isProcessEnabled()) {
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700708 int ret;
709 if (isProcessImplemented()) {
rago94a1ee82017-07-21 15:11:02 -0700710 if (auxType) {
711 // We overwrite the aux input buffer here and clear after processing.
Andy Hung9aad48c2017-11-29 10:29:19 -0800712 // aux input is always mono.
rago94a1ee82017-07-21 15:11:02 -0700713
Andy Hung26836922023-05-22 17:31:57 -0700714 if (!mSupportsFloat) {
Andy Hung116a4982017-11-30 10:15:08 -0800715 memcpy_to_i16_from_float(
716 mConfig.inputCfg.buffer.s16,
717 mConfig.inputCfg.buffer.f32,
718 mConfig.inputCfg.buffer.frameCount);
rago94a1ee82017-07-21 15:11:02 -0700719 }
rago94a1ee82017-07-21 15:11:02 -0700720 }
Andy Hung9aad48c2017-11-29 10:29:19 -0800721 sp<EffectBufferHalInterface> inBuffer = mInBuffer;
722 sp<EffectBufferHalInterface> outBuffer = mOutBuffer;
723
724 if (!auxType && mInChannelCountRequested != inChannelCount) {
725 adjust_channels(
726 inBuffer->audioBuffer()->f32, mInChannelCountRequested,
727 mInConversionBuffer->audioBuffer()->f32, inChannelCount,
728 sizeof(float),
729 sizeof(float)
730 * mInChannelCountRequested * mConfig.inputCfg.buffer.frameCount);
731 inBuffer = mInConversionBuffer;
732 }
733 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE
734 && mOutChannelCountRequested != outChannelCount) {
735 adjust_selected_channels(
736 outBuffer->audioBuffer()->f32, mOutChannelCountRequested,
737 mOutConversionBuffer->audioBuffer()->f32, outChannelCount,
738 sizeof(float),
739 sizeof(float)
740 * mOutChannelCountRequested * mConfig.outputCfg.buffer.frameCount);
741 outBuffer = mOutConversionBuffer;
742 }
Andy Hungfa69ca32017-11-30 10:07:53 -0800743 if (!mSupportsFloat) { // convert input to int16_t as effect doesn't support float.
744 if (!auxType) {
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -0800745 if (mInConversionBuffer == nullptr) {
Andy Hungfa69ca32017-11-30 10:07:53 -0800746 ALOGW("%s: mInConversionBuffer is null, bypassing", __func__);
747 goto data_bypass;
rago94a1ee82017-07-21 15:11:02 -0700748 }
Andy Hungfa69ca32017-11-30 10:07:53 -0800749 memcpy_to_i16_from_float(
750 mInConversionBuffer->audioBuffer()->s16,
Andy Hung9aad48c2017-11-29 10:29:19 -0800751 inBuffer->audioBuffer()->f32,
Andy Hungfa69ca32017-11-30 10:07:53 -0800752 inChannelCount * mConfig.inputCfg.buffer.frameCount);
Andy Hung9aad48c2017-11-29 10:29:19 -0800753 inBuffer = mInConversionBuffer;
rago94a1ee82017-07-21 15:11:02 -0700754 }
Andy Hungfa69ca32017-11-30 10:07:53 -0800755 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -0800756 if (mOutConversionBuffer == nullptr) {
Andy Hungfa69ca32017-11-30 10:07:53 -0800757 ALOGW("%s: mOutConversionBuffer is null, bypassing", __func__);
758 goto data_bypass;
759 }
760 memcpy_to_i16_from_float(
761 mOutConversionBuffer->audioBuffer()->s16,
Andy Hung9aad48c2017-11-29 10:29:19 -0800762 outBuffer->audioBuffer()->f32,
Andy Hungfa69ca32017-11-30 10:07:53 -0800763 outChannelCount * mConfig.outputCfg.buffer.frameCount);
Andy Hung9aad48c2017-11-29 10:29:19 -0800764 outBuffer = mOutConversionBuffer;
rago94a1ee82017-07-21 15:11:02 -0700765 }
766 }
Mikhail Naganov022b9952017-01-04 16:36:51 -0800767 ret = mEffectInterface->process();
Andy Hungfa69ca32017-11-30 10:07:53 -0800768 if (!mSupportsFloat) { // convert output int16_t back to float.
Andy Hung9aad48c2017-11-29 10:29:19 -0800769 sp<EffectBufferHalInterface> target =
770 mOutChannelCountRequested != outChannelCount
771 ? mOutConversionBuffer : mOutBuffer;
772
Andy Hungfa69ca32017-11-30 10:07:53 -0800773 memcpy_to_float_from_i16(
Andy Hung9aad48c2017-11-29 10:29:19 -0800774 target->audioBuffer()->f32,
Andy Hungfa69ca32017-11-30 10:07:53 -0800775 mOutConversionBuffer->audioBuffer()->s16,
776 outChannelCount * mConfig.outputCfg.buffer.frameCount);
777 }
Andy Hung9aad48c2017-11-29 10:29:19 -0800778 if (mOutChannelCountRequested != outChannelCount) {
779 adjust_selected_channels(mOutConversionBuffer->audioBuffer()->f32, outChannelCount,
780 mOutBuffer->audioBuffer()->f32, mOutChannelCountRequested,
781 sizeof(float),
782 sizeof(float) * outChannelCount * mConfig.outputCfg.buffer.frameCount);
783 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700784 } else {
rago94a1ee82017-07-21 15:11:02 -0700785 data_bypass:
rago94a1ee82017-07-21 15:11:02 -0700786 if (!auxType /* aux effects do not require data bypass */
Andy Hungfa69ca32017-11-30 10:07:53 -0800787 && mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700788 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
Andy Hungfa69ca32017-11-30 10:07:53 -0800789 accumulateInputToOutput();
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700790 } else {
Andy Hungfa69ca32017-11-30 10:07:53 -0800791 copyInputToOutput();
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700792 }
793 }
794 ret = -ENODATA;
795 }
Andy Hungfa69ca32017-11-30 10:07:53 -0800796
Eric Laurentca7cc822012-11-19 14:55:58 -0800797 // force transition to IDLE state when engine is ready
798 if (mState == STOPPED && ret == -ENODATA) {
799 mDisableWaitCnt = 1;
800 }
801
802 // clear auxiliary effect input buffer for next accumulation
rago94a1ee82017-07-21 15:11:02 -0700803 if (auxType) {
Andy Hung116a4982017-11-30 10:15:08 -0800804 const size_t size =
805 mConfig.inputCfg.buffer.frameCount * inChannelCount * sizeof(float);
rago94a1ee82017-07-21 15:11:02 -0700806 memset(mConfig.inputCfg.buffer.raw, 0, size);
Eric Laurentca7cc822012-11-19 14:55:58 -0800807 }
808 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
rago94a1ee82017-07-21 15:11:02 -0700809 // mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw
Eric Laurentca7cc822012-11-19 14:55:58 -0800810 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
811 // If an insert effect is idle and input buffer is different from output buffer,
812 // accumulate input onto output
Andy Hungfda44002021-06-03 17:23:16 -0700813 if (getCallback()->activeTrackCnt() != 0) {
Andy Hunge8ac1b22018-10-31 14:22:35 -0700814 // similar handling with data_bypass above.
815 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
816 accumulateInputToOutput();
817 } else { // EFFECT_BUFFER_ACCESS_WRITE
818 copyInputToOutput();
819 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800820 }
821 }
822}
823
824void AudioFlinger::EffectModule::reset_l()
825{
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700826 if (mStatus != NO_ERROR || mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800827 return;
828 }
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700829 mEffectInterface->command(EFFECT_CMD_RESET, 0, NULL, 0, NULL);
Eric Laurentca7cc822012-11-19 14:55:58 -0800830}
831
832status_t AudioFlinger::EffectModule::configure()
833{
rago94a1ee82017-07-21 15:11:02 -0700834 ALOGVV("configure() started");
Eric Laurentd0ebb532013-04-02 16:41:41 -0700835 status_t status;
Eric Laurentd0ebb532013-04-02 16:41:41 -0700836 uint32_t size;
837 audio_channel_mask_t channelMask;
Andy Hungfda44002021-06-03 17:23:16 -0700838 sp<EffectCallbackInterface> callback;
Eric Laurentd0ebb532013-04-02 16:41:41 -0700839
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700840 if (mEffectInterface == 0) {
Eric Laurentd0ebb532013-04-02 16:41:41 -0700841 status = NO_INIT;
842 goto exit;
Eric Laurentca7cc822012-11-19 14:55:58 -0800843 }
844
Eric Laurentca7cc822012-11-19 14:55:58 -0800845 // TODO: handle configuration of effects replacing track process
Andy Hung9aad48c2017-11-29 10:29:19 -0800846 // TODO: handle configuration of input (record) SW effects above the HAL,
847 // similar to output EFFECT_FLAG_TYPE_INSERT/REPLACE,
848 // in which case input channel masks should be used here.
Andy Hungfda44002021-06-03 17:23:16 -0700849 callback = getCallback();
Eric Laurentf1f22e72021-07-13 14:04:14 +0200850 channelMask = callback->inChannelMask(mId);
Andy Hung9aad48c2017-11-29 10:29:19 -0800851 mConfig.inputCfg.channels = channelMask;
Eric Laurentf1f22e72021-07-13 14:04:14 +0200852 mConfig.outputCfg.channels = callback->outChannelMask();
Eric Laurentca7cc822012-11-19 14:55:58 -0800853
854 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Andy Hung9aad48c2017-11-29 10:29:19 -0800855 if (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_MONO) {
856 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
857 ALOGV("Overriding auxiliary effect input channels %#x as MONO",
858 mConfig.inputCfg.channels);
859 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800860 }
jiabineb3bda02020-06-30 14:07:03 -0700861 if (isHapticGenerator()) {
Andy Hungfda44002021-06-03 17:23:16 -0700862 audio_channel_mask_t hapticChannelMask = callback->hapticChannelMask();
jiabineb3bda02020-06-30 14:07:03 -0700863 mConfig.inputCfg.channels |= hapticChannelMask;
864 mConfig.outputCfg.channels |= hapticChannelMask;
865 }
Andy Hung9aad48c2017-11-29 10:29:19 -0800866 mInChannelCountRequested =
867 audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
868 mOutChannelCountRequested =
869 audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
Ricardo Garciad11da702015-05-28 12:14:12 -0700870
Andy Hung319587b2023-05-23 14:01:03 -0700871 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_FLOAT;
872 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_FLOAT;
Yuuki Yokoyamae17f8312017-05-26 19:06:33 +0900873
874 // Don't use sample rate for thread if effect isn't offloadable.
Andy Hungfda44002021-06-03 17:23:16 -0700875 if (callback->isOffloadOrDirect() && !isOffloaded()) {
Yuuki Yokoyamae17f8312017-05-26 19:06:33 +0900876 mConfig.inputCfg.samplingRate = DEFAULT_OUTPUT_SAMPLE_RATE;
877 ALOGV("Overriding effect input as 48kHz");
878 } else {
Andy Hungfda44002021-06-03 17:23:16 -0700879 mConfig.inputCfg.samplingRate = callback->sampleRate();
Yuuki Yokoyamae17f8312017-05-26 19:06:33 +0900880 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800881 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
882 mConfig.inputCfg.bufferProvider.cookie = NULL;
883 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
884 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
885 mConfig.outputCfg.bufferProvider.cookie = NULL;
886 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
887 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
888 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
889 // Insert effect:
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800890 // - in global sessions (e.g AUDIO_SESSION_OUTPUT_MIX),
Eric Laurentca7cc822012-11-19 14:55:58 -0800891 // always overwrites output buffer: input buffer == output buffer
892 // - in other sessions:
893 // last effect in the chain accumulates in output buffer: input buffer != output buffer
894 // other effect: overwrites output buffer: input buffer == output buffer
895 // Auxiliary effect:
896 // accumulates in output buffer: input buffer != output buffer
897 // Therefore: accumulate <=> input buffer != output buffer
Andy Hung799c8d02021-10-28 17:05:40 -0700898 mConfig.outputCfg.accessMode = requiredEffectBufferAccessMode();
Eric Laurentca7cc822012-11-19 14:55:58 -0800899 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
900 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
Andy Hungfda44002021-06-03 17:23:16 -0700901 mConfig.inputCfg.buffer.frameCount = callback->frameCount();
Eric Laurentca7cc822012-11-19 14:55:58 -0800902 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
Mikhail Naganov8d7da002022-04-19 21:21:23 +0000903 mIsOutput = callback->isOutput();
Eric Laurentca7cc822012-11-19 14:55:58 -0800904
Eric Laurent6b446ce2019-12-13 10:56:31 -0800905 ALOGV("configure() %p chain %p buffer %p framecount %zu",
Andy Hungfda44002021-06-03 17:23:16 -0700906 this, callback->chain().promote().get(),
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -0800907 mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
Eric Laurentca7cc822012-11-19 14:55:58 -0800908
909 status_t cmdStatus;
Eric Laurentd0ebb532013-04-02 16:41:41 -0700910 size = sizeof(int);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700911 status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
Andy Hung9aad48c2017-11-29 10:29:19 -0800912 sizeof(mConfig),
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700913 &mConfig,
914 &size,
915 &cmdStatus);
rago94a1ee82017-07-21 15:11:02 -0700916 if (status == NO_ERROR) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800917 status = cmdStatus;
918 }
Andy Hung9aad48c2017-11-29 10:29:19 -0800919
Andy Hung9aad48c2017-11-29 10:29:19 -0800920 if (status != NO_ERROR &&
Andy Hungba8e52b2023-05-11 14:33:03 -0700921 EffectConfiguration::isHidl() && // only HIDL effects support channel conversion
Mikhail Naganov8d7da002022-04-19 21:21:23 +0000922 mIsOutput &&
Andy Hung9aad48c2017-11-29 10:29:19 -0800923 (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_STEREO
924 || mConfig.outputCfg.channels != AUDIO_CHANNEL_OUT_STEREO)) {
925 // Older effects may require exact STEREO position mask.
Andy Hung01b32722018-05-18 13:52:02 -0700926 if (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_STEREO
927 && (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Andy Hung9aad48c2017-11-29 10:29:19 -0800928 ALOGV("Overriding effect input channels %#x as STEREO", mConfig.inputCfg.channels);
929 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
930 }
931 if (mConfig.outputCfg.channels != AUDIO_CHANNEL_OUT_STEREO) {
932 ALOGV("Overriding effect output channels %#x as STEREO", mConfig.outputCfg.channels);
933 mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
934 }
935 size = sizeof(int);
rago94a1ee82017-07-21 15:11:02 -0700936 status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
Andy Hung9aad48c2017-11-29 10:29:19 -0800937 sizeof(mConfig),
rago94a1ee82017-07-21 15:11:02 -0700938 &mConfig,
939 &size,
940 &cmdStatus);
941 if (status == NO_ERROR) {
942 status = cmdStatus;
Andy Hung9aad48c2017-11-29 10:29:19 -0800943 }
944 }
Andy Hung9aad48c2017-11-29 10:29:19 -0800945
Andy Hung9aad48c2017-11-29 10:29:19 -0800946 if (status == NO_ERROR) {
947 mSupportsFloat = true;
948 }
949
Andy Hungba8e52b2023-05-11 14:33:03 -0700950 // only HIDL effects support integer conversion.
951 if (status != NO_ERROR && EffectConfiguration::isHidl()) {
Andy Hung9aad48c2017-11-29 10:29:19 -0800952 ALOGV("EFFECT_CMD_SET_CONFIG failed with float format, retry with int16_t.");
953 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
954 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
955 size = sizeof(int);
956 status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
957 sizeof(mConfig),
958 &mConfig,
959 &size,
960 &cmdStatus);
961 if (status == NO_ERROR) {
962 status = cmdStatus;
963 }
964 if (status == NO_ERROR) {
rago94a1ee82017-07-21 15:11:02 -0700965 mSupportsFloat = false;
966 ALOGVV("config worked with 16 bit");
967 } else {
968 ALOGE("%s failed %d with int16_t (as well as float)", __func__, status);
Eric Laurentca7cc822012-11-19 14:55:58 -0800969 }
rago94a1ee82017-07-21 15:11:02 -0700970 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800971
rago94a1ee82017-07-21 15:11:02 -0700972 if (status == NO_ERROR) {
973 // Establish Buffer strategy
974 setInBuffer(mInBuffer);
975 setOutBuffer(mOutBuffer);
976
977 // Update visualizer latency
978 if (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) {
979 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
980 effect_param_t *p = (effect_param_t *)buf32;
981
982 p->psize = sizeof(uint32_t);
983 p->vsize = sizeof(uint32_t);
984 size = sizeof(int);
985 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
986
Andy Hungfda44002021-06-03 17:23:16 -0700987 uint32_t latency = callback->latency();
rago94a1ee82017-07-21 15:11:02 -0700988
989 *((int32_t *)p->data + 1)= latency;
990 mEffectInterface->command(EFFECT_CMD_SET_PARAM,
991 sizeof(effect_param_t) + 8,
992 &buf32,
993 &size,
994 &cmdStatus);
995 }
jiabin4e246532022-08-23 16:37:30 -0700996
997 if (isVolumeControl()) {
998 // Force initializing the volume as 0 for volume control effect for safer ramping
999 uint32_t left = 0;
1000 uint32_t right = 0;
1001 setVolumeInternal(&left, &right, true /*controller*/);
1002 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001003 }
1004
Andy Hung05083ac2017-12-14 15:00:28 -08001005 // mConfig.outputCfg.buffer.frameCount cannot be zero.
1006 mMaxDisableWaitCnt = (uint32_t)std::max(
1007 (uint64_t)1, // mMaxDisableWaitCnt must be greater than zero.
François Gaffieb8551f62023-02-15 11:36:35 +01001008 (uint64_t)mConfig.outputCfg.buffer.frameCount == 0 ? 1
1009 : (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate
1010 / ((uint64_t)1000 * mConfig.outputCfg.buffer.frameCount)));
Eric Laurentca7cc822012-11-19 14:55:58 -08001011
Eric Laurentd0ebb532013-04-02 16:41:41 -07001012exit:
Andy Hung6f88dc42017-12-13 16:19:39 -08001013 // TODO: consider clearing mConfig on error.
Eric Laurentd0ebb532013-04-02 16:41:41 -07001014 mStatus = status;
rago94a1ee82017-07-21 15:11:02 -07001015 ALOGVV("configure ended");
Eric Laurentca7cc822012-11-19 14:55:58 -08001016 return status;
1017}
1018
1019status_t AudioFlinger::EffectModule::init()
1020{
1021 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001022 if (mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001023 return NO_INIT;
1024 }
1025 status_t cmdStatus;
1026 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001027 status_t status = mEffectInterface->command(EFFECT_CMD_INIT,
1028 0,
1029 NULL,
1030 &size,
1031 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -08001032 if (status == 0) {
1033 status = cmdStatus;
1034 }
1035 return status;
1036}
1037
Eric Laurent1b928682014-10-02 19:41:47 -07001038void AudioFlinger::EffectModule::addEffectToHal_l()
1039{
1040 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
1041 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurent9f57aa82023-03-17 19:28:37 +01001042 if (mCurrentHalStream == getCallback()->io()) {
David Li6c8ac4b2021-06-22 22:17:52 +08001043 return;
1044 }
1045
Andy Hungfda44002021-06-03 17:23:16 -07001046 (void)getCallback()->addEffectToHal(mEffectInterface);
Eric Laurent9f57aa82023-03-17 19:28:37 +01001047 mCurrentHalStream = getCallback()->io();
Eric Laurent1b928682014-10-02 19:41:47 -07001048 }
1049}
1050
Eric Laurentfa1e1232016-08-02 19:01:49 -07001051// start() must be called with PlaybackThread::mLock or EffectChain::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -08001052status_t AudioFlinger::EffectModule::start()
1053{
Eric Laurentfa1e1232016-08-02 19:01:49 -07001054 status_t status;
1055 {
1056 Mutex::Autolock _l(mLock);
1057 status = start_l();
Eric Laurentfa1e1232016-08-02 19:01:49 -07001058 }
Eric Laurent6b446ce2019-12-13 10:56:31 -08001059 if (status == NO_ERROR) {
Andy Hungfda44002021-06-03 17:23:16 -07001060 getCallback()->resetVolume();
Eric Laurentfa1e1232016-08-02 19:01:49 -07001061 }
1062 return status;
Eric Laurentca7cc822012-11-19 14:55:58 -08001063}
1064
1065status_t AudioFlinger::EffectModule::start_l()
1066{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001067 if (mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001068 return NO_INIT;
1069 }
Eric Laurentd0ebb532013-04-02 16:41:41 -07001070 if (mStatus != NO_ERROR) {
1071 return mStatus;
1072 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001073 status_t cmdStatus;
1074 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001075 status_t status = mEffectInterface->command(EFFECT_CMD_ENABLE,
1076 0,
1077 NULL,
1078 &size,
1079 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -08001080 if (status == 0) {
1081 status = cmdStatus;
1082 }
Eric Laurentcb4b6e92014-10-01 14:26:10 -07001083 if (status == 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07001084 addEffectToHal_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08001085 }
1086 return status;
1087}
1088
1089status_t AudioFlinger::EffectModule::stop()
1090{
1091 Mutex::Autolock _l(mLock);
1092 return stop_l();
1093}
1094
1095status_t AudioFlinger::EffectModule::stop_l()
1096{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001097 if (mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001098 return NO_INIT;
1099 }
Eric Laurentd0ebb532013-04-02 16:41:41 -07001100 if (mStatus != NO_ERROR) {
1101 return mStatus;
1102 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001103 status_t cmdStatus = NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -08001104 uint32_t size = sizeof(status_t);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001105
1106 if (isVolumeControl() && isOffloadedOrDirect()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001107 // We have the EffectChain and EffectModule lock, permit a reentrant call to setVolume:
1108 // resetVolume_l --> setVolume_l --> EffectModule::setVolume
1109 mSetVolumeReentrantTid = gettid();
Andy Hungfda44002021-06-03 17:23:16 -07001110 getCallback()->resetVolume();
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001111 mSetVolumeReentrantTid = INVALID_PID;
1112 }
1113
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001114 status_t status = mEffectInterface->command(EFFECT_CMD_DISABLE,
1115 0,
1116 NULL,
1117 &size,
1118 &cmdStatus);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001119 if (status == NO_ERROR) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001120 status = cmdStatus;
1121 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001122 if (status == NO_ERROR) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001123 status = removeEffectFromHal_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001124 }
1125 return status;
1126}
1127
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001128// must be called with EffectChain::mLock held
1129void AudioFlinger::EffectModule::release_l()
1130{
1131 if (mEffectInterface != 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001132 removeEffectFromHal_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001133 // release effect engine
Mikhail Naganov022b9952017-01-04 16:36:51 -08001134 mEffectInterface->close();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001135 mEffectInterface.clear();
1136 }
1137}
1138
Eric Laurent6b446ce2019-12-13 10:56:31 -08001139status_t AudioFlinger::EffectModule::removeEffectFromHal_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001140{
1141 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
1142 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurent9f57aa82023-03-17 19:28:37 +01001143 if (mCurrentHalStream != getCallback()->io()) {
1144 return (mCurrentHalStream == AUDIO_IO_HANDLE_NONE) ? NO_ERROR : INVALID_OPERATION;
David Li6c8ac4b2021-06-22 22:17:52 +08001145 }
Andy Hungfda44002021-06-03 17:23:16 -07001146 getCallback()->removeEffectFromHal(mEffectInterface);
Eric Laurent9f57aa82023-03-17 19:28:37 +01001147 mCurrentHalStream = AUDIO_IO_HANDLE_NONE;
Eric Laurentca7cc822012-11-19 14:55:58 -08001148 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001149 return NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -08001150}
1151
Andy Hunge4a1d912016-08-17 14:11:13 -07001152// round up delta valid if value and divisor are positive.
1153template <typename T>
1154static T roundUpDelta(const T &value, const T &divisor) {
1155 T remainder = value % divisor;
1156 return remainder == 0 ? 0 : divisor - remainder;
1157}
1158
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001159status_t AudioFlinger::EffectModule::command(int32_t cmdCode,
1160 const std::vector<uint8_t>& cmdData,
1161 int32_t maxReplySize,
1162 std::vector<uint8_t>* reply)
Eric Laurentca7cc822012-11-19 14:55:58 -08001163{
1164 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001165 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface.get());
Eric Laurentca7cc822012-11-19 14:55:58 -08001166
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001167 if (mState == DESTROYED || mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001168 return NO_INIT;
1169 }
Eric Laurentd0ebb532013-04-02 16:41:41 -07001170 if (mStatus != NO_ERROR) {
1171 return mStatus;
1172 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001173 if (maxReplySize < 0 || maxReplySize > EFFECT_PARAM_SIZE_MAX) {
1174 return -EINVAL;
1175 }
1176 size_t cmdSize = cmdData.size();
1177 const effect_param_t* param = cmdSize >= sizeof(effect_param_t)
1178 ? reinterpret_cast<const effect_param_t*>(cmdData.data())
1179 : nullptr;
Andy Hung110bc952016-06-20 15:22:52 -07001180 if (cmdCode == EFFECT_CMD_GET_PARAM &&
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001181 (param == nullptr || param->psize > cmdSize - sizeof(effect_param_t))) {
Andy Hung6660f122016-11-04 19:40:53 -07001182 android_errorWriteLog(0x534e4554, "32438594");
Andy Hungb3456642016-11-28 13:50:21 -08001183 android_errorWriteLog(0x534e4554, "33003822");
1184 return -EINVAL;
1185 }
1186 if (cmdCode == EFFECT_CMD_GET_PARAM &&
Andy Hung920f6572022-10-06 12:09:49 -07001187 (maxReplySize < static_cast<signed>(sizeof(effect_param_t)) ||
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001188 param->psize > maxReplySize - sizeof(effect_param_t))) {
Andy Hungb3456642016-11-28 13:50:21 -08001189 android_errorWriteLog(0x534e4554, "29251553");
Andy Hung6660f122016-11-04 19:40:53 -07001190 return -EINVAL;
1191 }
ragoe2759072016-11-22 18:02:48 -08001192 if (cmdCode == EFFECT_CMD_GET_PARAM &&
Andy Hung920f6572022-10-06 12:09:49 -07001193 (static_cast<signed>(sizeof(effect_param_t)) > maxReplySize
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001194 || param->psize > maxReplySize - sizeof(effect_param_t)
1195 || param->vsize > maxReplySize - sizeof(effect_param_t)
1196 - param->psize
1197 || roundUpDelta(param->psize, (uint32_t) sizeof(int)) >
1198 maxReplySize
1199 - sizeof(effect_param_t)
1200 - param->psize
1201 - param->vsize)) {
ragoe2759072016-11-22 18:02:48 -08001202 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: reply size inconsistent");
1203 android_errorWriteLog(0x534e4554, "32705438");
1204 return -EINVAL;
1205 }
Andy Hunge4a1d912016-08-17 14:11:13 -07001206 if ((cmdCode == EFFECT_CMD_SET_PARAM
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001207 || cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED)
1208 && // DEFERRED not generally used
1209 (param == nullptr
1210 || param->psize > cmdSize - sizeof(effect_param_t)
1211 || param->vsize > cmdSize - sizeof(effect_param_t)
1212 - param->psize
1213 || roundUpDelta(param->psize,
1214 (uint32_t) sizeof(int)) >
1215 cmdSize
1216 - sizeof(effect_param_t)
1217 - param->psize
1218 - param->vsize)) {
Andy Hunge4a1d912016-08-17 14:11:13 -07001219 android_errorWriteLog(0x534e4554, "30204301");
1220 return -EINVAL;
1221 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001222 uint32_t replySize = maxReplySize;
1223 reply->resize(replySize);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001224 status_t status = mEffectInterface->command(cmdCode,
1225 cmdSize,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001226 const_cast<uint8_t*>(cmdData.data()),
1227 &replySize,
1228 reply->data());
1229 reply->resize(status == NO_ERROR ? replySize : 0);
Eric Laurentca7cc822012-11-19 14:55:58 -08001230 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001231 for (size_t i = 1; i < mHandles.size(); i++) {
1232 EffectHandle *h = mHandles[i];
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001233 if (h != NULL && !h->disconnected()) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001234 h->commandExecuted(cmdCode, cmdData, *reply);
Eric Laurentca7cc822012-11-19 14:55:58 -08001235 }
1236 }
1237 }
1238 return status;
1239}
1240
Eric Laurentca7cc822012-11-19 14:55:58 -08001241bool AudioFlinger::EffectModule::isProcessEnabled() const
1242{
Eric Laurentd0ebb532013-04-02 16:41:41 -07001243 if (mStatus != NO_ERROR) {
1244 return false;
1245 }
1246
Eric Laurentca7cc822012-11-19 14:55:58 -08001247 switch (mState) {
1248 case RESTART:
1249 case ACTIVE:
1250 case STOPPING:
1251 case STOPPED:
1252 return true;
1253 case IDLE:
1254 case STARTING:
1255 case DESTROYED:
1256 default:
1257 return false;
1258 }
1259}
1260
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001261bool AudioFlinger::EffectModule::isOffloadedOrDirect() const
1262{
Andy Hungfda44002021-06-03 17:23:16 -07001263 return getCallback()->isOffloadOrDirect();
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001264}
1265
1266bool AudioFlinger::EffectModule::isVolumeControlEnabled() const
1267{
1268 return (isVolumeControl() && (isOffloadedOrDirect() ? isEnabled() : isProcessEnabled()));
1269}
1270
Mikhail Naganov022b9952017-01-04 16:36:51 -08001271void AudioFlinger::EffectModule::setInBuffer(const sp<EffectBufferHalInterface>& buffer) {
rago94a1ee82017-07-21 15:11:02 -07001272 ALOGVV("setInBuffer %p",(&buffer));
Andy Hung6f88dc42017-12-13 16:19:39 -08001273
1274 // mConfig.inputCfg.buffer.frameCount may be zero if configure() is not called yet.
Mikhail Naganov022b9952017-01-04 16:36:51 -08001275 if (buffer != 0) {
1276 mConfig.inputCfg.buffer.raw = buffer->audioBuffer()->raw;
1277 buffer->setFrameCount(mConfig.inputCfg.buffer.frameCount);
1278 } else {
1279 mConfig.inputCfg.buffer.raw = NULL;
1280 }
1281 mInBuffer = buffer;
Andy Hungc15aaee2017-11-27 17:02:40 -08001282 mEffectInterface->setInBuffer(buffer);
rago94a1ee82017-07-21 15:11:02 -07001283
Andy Hungbded9c82017-11-30 18:47:35 -08001284 // aux effects do in place conversion to float - we don't allocate mInConversionBuffer.
rago94a1ee82017-07-21 15:11:02 -07001285 // Theoretically insert effects can also do in-place conversions (destroying
1286 // the original buffer) when the output buffer is identical to the input buffer,
1287 // but we don't optimize for it here.
1288 const bool auxType = (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY;
Andy Hung9aad48c2017-11-29 10:29:19 -08001289 const uint32_t inChannelCount =
1290 audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
1291 const bool formatMismatch = !mSupportsFloat || mInChannelCountRequested != inChannelCount;
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001292 if (!auxType && formatMismatch && mInBuffer != nullptr) {
rago94a1ee82017-07-21 15:11:02 -07001293 // we need to translate - create hidl shared buffer and intercept
1294 const size_t inFrameCount = mConfig.inputCfg.buffer.frameCount;
Andy Hung9aad48c2017-11-29 10:29:19 -08001295 // Use FCC_2 in case mInChannelCountRequested is mono and the effect is stereo.
1296 const uint32_t inChannels = std::max((uint32_t)FCC_2, mInChannelCountRequested);
1297 const size_t size = inChannels * inFrameCount * std::max(sizeof(int16_t), sizeof(float));
rago94a1ee82017-07-21 15:11:02 -07001298
1299 ALOGV("%s: setInBuffer updating for inChannels:%d inFrameCount:%zu total size:%zu",
1300 __func__, inChannels, inFrameCount, size);
1301
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001302 if (size > 0 && (mInConversionBuffer == nullptr
Andy Hungbded9c82017-11-30 18:47:35 -08001303 || size > mInConversionBuffer->getSize())) {
1304 mInConversionBuffer.clear();
1305 ALOGV("%s: allocating mInConversionBuffer %zu", __func__, size);
Andy Hungfda44002021-06-03 17:23:16 -07001306 (void)getCallback()->allocateHalBuffer(size, &mInConversionBuffer);
rago94a1ee82017-07-21 15:11:02 -07001307 }
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001308 if (mInConversionBuffer != nullptr) {
Andy Hungbded9c82017-11-30 18:47:35 -08001309 mInConversionBuffer->setFrameCount(inFrameCount);
1310 mEffectInterface->setInBuffer(mInConversionBuffer);
rago94a1ee82017-07-21 15:11:02 -07001311 } else if (size > 0) {
Andy Hungbded9c82017-11-30 18:47:35 -08001312 ALOGE("%s cannot create mInConversionBuffer", __func__);
rago94a1ee82017-07-21 15:11:02 -07001313 }
1314 }
Mikhail Naganov022b9952017-01-04 16:36:51 -08001315}
1316
1317void AudioFlinger::EffectModule::setOutBuffer(const sp<EffectBufferHalInterface>& buffer) {
rago94a1ee82017-07-21 15:11:02 -07001318 ALOGVV("setOutBuffer %p",(&buffer));
Andy Hung6f88dc42017-12-13 16:19:39 -08001319
1320 // mConfig.outputCfg.buffer.frameCount may be zero if configure() is not called yet.
Mikhail Naganov022b9952017-01-04 16:36:51 -08001321 if (buffer != 0) {
1322 mConfig.outputCfg.buffer.raw = buffer->audioBuffer()->raw;
1323 buffer->setFrameCount(mConfig.outputCfg.buffer.frameCount);
1324 } else {
1325 mConfig.outputCfg.buffer.raw = NULL;
1326 }
1327 mOutBuffer = buffer;
Andy Hungc15aaee2017-11-27 17:02:40 -08001328 mEffectInterface->setOutBuffer(buffer);
rago94a1ee82017-07-21 15:11:02 -07001329
Andy Hungbded9c82017-11-30 18:47:35 -08001330 // Note: Any effect that does not accumulate does not need mOutConversionBuffer and
rago94a1ee82017-07-21 15:11:02 -07001331 // can do in-place conversion from int16_t to float. We don't optimize here.
Andy Hung9aad48c2017-11-29 10:29:19 -08001332 const uint32_t outChannelCount =
1333 audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
1334 const bool formatMismatch = !mSupportsFloat || mOutChannelCountRequested != outChannelCount;
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001335 if (formatMismatch && mOutBuffer != nullptr) {
rago94a1ee82017-07-21 15:11:02 -07001336 const size_t outFrameCount = mConfig.outputCfg.buffer.frameCount;
Andy Hung9aad48c2017-11-29 10:29:19 -08001337 // Use FCC_2 in case mOutChannelCountRequested is mono and the effect is stereo.
1338 const uint32_t outChannels = std::max((uint32_t)FCC_2, mOutChannelCountRequested);
1339 const size_t size = outChannels * outFrameCount * std::max(sizeof(int16_t), sizeof(float));
rago94a1ee82017-07-21 15:11:02 -07001340
1341 ALOGV("%s: setOutBuffer updating for outChannels:%d outFrameCount:%zu total size:%zu",
1342 __func__, outChannels, outFrameCount, size);
1343
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001344 if (size > 0 && (mOutConversionBuffer == nullptr
Andy Hungbded9c82017-11-30 18:47:35 -08001345 || size > mOutConversionBuffer->getSize())) {
1346 mOutConversionBuffer.clear();
1347 ALOGV("%s: allocating mOutConversionBuffer %zu", __func__, size);
Andy Hungfda44002021-06-03 17:23:16 -07001348 (void)getCallback()->allocateHalBuffer(size, &mOutConversionBuffer);
rago94a1ee82017-07-21 15:11:02 -07001349 }
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001350 if (mOutConversionBuffer != nullptr) {
Andy Hungbded9c82017-11-30 18:47:35 -08001351 mOutConversionBuffer->setFrameCount(outFrameCount);
1352 mEffectInterface->setOutBuffer(mOutConversionBuffer);
rago94a1ee82017-07-21 15:11:02 -07001353 } else if (size > 0) {
Andy Hungbded9c82017-11-30 18:47:35 -08001354 ALOGE("%s cannot create mOutConversionBuffer", __func__);
rago94a1ee82017-07-21 15:11:02 -07001355 }
1356 }
Mikhail Naganov022b9952017-01-04 16:36:51 -08001357}
1358
Eric Laurentca7cc822012-11-19 14:55:58 -08001359status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
1360{
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001361 AutoLockReentrant _l(mLock, mSetVolumeReentrantTid);
Eric Laurentd0ebb532013-04-02 16:41:41 -07001362 if (mStatus != NO_ERROR) {
1363 return mStatus;
1364 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001365 status_t status = NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -08001366 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
1367 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
1368 if (isProcessEnabled() &&
1369 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
Jasmine Cha934ecfb2019-01-23 18:19:14 +08001370 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND ||
1371 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_MONITOR)) {
jiabin4e246532022-08-23 16:37:30 -07001372 status = setVolumeInternal(left, right, controller);
1373 }
1374 return status;
1375}
1376
1377status_t AudioFlinger::EffectModule::setVolumeInternal(
1378 uint32_t *left, uint32_t *right, bool controller) {
1379 uint32_t volume[2] = {*left, *right};
1380 uint32_t *pVolume = controller ? volume : nullptr;
1381 uint32_t size = sizeof(volume);
1382 status_t status = mEffectInterface->command(EFFECT_CMD_SET_VOLUME,
1383 size,
1384 volume,
1385 &size,
1386 pVolume);
1387 if (controller && status == NO_ERROR && size == sizeof(volume)) {
1388 *left = volume[0];
1389 *right = volume[1];
Eric Laurentca7cc822012-11-19 14:55:58 -08001390 }
1391 return status;
1392}
1393
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001394void AudioFlinger::EffectChain::setVolumeForOutput_l(uint32_t left, uint32_t right)
1395{
Zhou Songd505c642020-02-20 16:35:37 +08001396 // for offload or direct thread, if the effect chain has non-offloadable
1397 // effect and any effect module within the chain has volume control, then
1398 // volume control is delegated to effect, otherwise, set volume to hal.
1399 if (mEffectCallback->isOffloadOrDirect() &&
1400 !(isNonOffloadableEnabled_l() && hasVolumeControlEnabled_l())) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001401 float vol_l = (float)left / (1 << 24);
1402 float vol_r = (float)right / (1 << 24);
Eric Laurent6b446ce2019-12-13 10:56:31 -08001403 mEffectCallback->setVolumeForOutput(vol_l, vol_r);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001404 }
1405}
1406
jiabin8f278ee2019-11-11 12:16:27 -08001407status_t AudioFlinger::EffectModule::sendSetAudioDevicesCommand(
1408 const AudioDeviceTypeAddrVector &devices, uint32_t cmdCode)
Eric Laurentca7cc822012-11-19 14:55:58 -08001409{
jiabin8f278ee2019-11-11 12:16:27 -08001410 audio_devices_t deviceType = deviceTypesToBitMask(getAudioDeviceTypes(devices));
1411 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001412 return NO_ERROR;
1413 }
1414
1415 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -07001416 if (mStatus != NO_ERROR) {
1417 return mStatus;
1418 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001419 status_t status = NO_ERROR;
Eric Laurent7e1139c2013-06-06 18:29:01 -07001420 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001421 status_t cmdStatus;
1422 uint32_t size = sizeof(status_t);
jiabin8f278ee2019-11-11 12:16:27 -08001423 // FIXME: use audio device types and addresses when the hal interface is ready.
1424 status = mEffectInterface->command(cmdCode,
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001425 sizeof(uint32_t),
jiabin8f278ee2019-11-11 12:16:27 -08001426 &deviceType,
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001427 &size,
1428 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -08001429 }
1430 return status;
1431}
1432
jiabin8f278ee2019-11-11 12:16:27 -08001433status_t AudioFlinger::EffectModule::setDevices(const AudioDeviceTypeAddrVector &devices)
1434{
1435 return sendSetAudioDevicesCommand(devices, EFFECT_CMD_SET_DEVICE);
1436}
1437
1438status_t AudioFlinger::EffectModule::setInputDevice(const AudioDeviceTypeAddr &device)
1439{
1440 return sendSetAudioDevicesCommand({device}, EFFECT_CMD_SET_INPUT_DEVICE);
1441}
1442
Eric Laurentca7cc822012-11-19 14:55:58 -08001443status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
1444{
1445 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -07001446 if (mStatus != NO_ERROR) {
1447 return mStatus;
1448 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001449 status_t status = NO_ERROR;
1450 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
1451 status_t cmdStatus;
1452 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001453 status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_MODE,
1454 sizeof(audio_mode_t),
1455 &mode,
1456 &size,
1457 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -08001458 if (status == NO_ERROR) {
1459 status = cmdStatus;
1460 }
1461 }
1462 return status;
1463}
1464
1465status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
1466{
1467 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -07001468 if (mStatus != NO_ERROR) {
1469 return mStatus;
1470 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001471 status_t status = NO_ERROR;
1472 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
1473 uint32_t size = 0;
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001474 status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_SOURCE,
1475 sizeof(audio_source_t),
1476 &source,
1477 &size,
1478 NULL);
Eric Laurentca7cc822012-11-19 14:55:58 -08001479 }
1480 return status;
1481}
1482
Eric Laurent5baf2af2013-09-12 17:37:00 -07001483status_t AudioFlinger::EffectModule::setOffloaded(bool offloaded, audio_io_handle_t io)
1484{
1485 Mutex::Autolock _l(mLock);
1486 if (mStatus != NO_ERROR) {
1487 return mStatus;
1488 }
1489 status_t status = NO_ERROR;
1490 if ((mDescriptor.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) != 0) {
1491 status_t cmdStatus;
1492 uint32_t size = sizeof(status_t);
1493 effect_offload_param_t cmd;
1494
1495 cmd.isOffload = offloaded;
1496 cmd.ioHandle = io;
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001497 status = mEffectInterface->command(EFFECT_CMD_OFFLOAD,
1498 sizeof(effect_offload_param_t),
1499 &cmd,
1500 &size,
1501 &cmdStatus);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001502 if (status == NO_ERROR) {
1503 status = cmdStatus;
1504 }
1505 mOffloaded = (status == NO_ERROR) ? offloaded : false;
1506 } else {
1507 if (offloaded) {
1508 status = INVALID_OPERATION;
1509 }
1510 mOffloaded = false;
1511 }
1512 ALOGV("setOffloaded() offloaded %d io %d status %d", offloaded, io, status);
1513 return status;
1514}
1515
1516bool AudioFlinger::EffectModule::isOffloaded() const
1517{
1518 Mutex::Autolock _l(mLock);
1519 return mOffloaded;
1520}
1521
jiabineb3bda02020-06-30 14:07:03 -07001522/*static*/
1523bool AudioFlinger::EffectModule::isHapticGenerator(const effect_uuid_t *type) {
1524 return memcmp(type, FX_IID_HAPTICGENERATOR, sizeof(effect_uuid_t)) == 0;
1525}
1526
1527bool AudioFlinger::EffectModule::isHapticGenerator() const {
1528 return isHapticGenerator(&mDescriptor.type);
1529}
1530
Simon Bowden62823412022-10-17 14:52:26 +00001531status_t AudioFlinger::EffectModule::setHapticIntensity(int id, os::HapticScale intensity)
jiabine70bc7f2020-06-30 22:07:55 -07001532{
1533 if (mStatus != NO_ERROR) {
1534 return mStatus;
1535 }
1536 if (!isHapticGenerator()) {
1537 ALOGW("Should not set haptic intensity for effects that are not HapticGenerator");
1538 return INVALID_OPERATION;
1539 }
1540
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001541 std::vector<uint8_t> request(sizeof(effect_param_t) + 3 * sizeof(uint32_t));
1542 effect_param_t *param = (effect_param_t*) request.data();
jiabine70bc7f2020-06-30 22:07:55 -07001543 param->psize = sizeof(int32_t);
1544 param->vsize = sizeof(int32_t) * 2;
1545 *(int32_t*)param->data = HG_PARAM_HAPTIC_INTENSITY;
1546 *((int32_t*)param->data + 1) = id;
Simon Bowden62823412022-10-17 14:52:26 +00001547 *((int32_t*)param->data + 2) = static_cast<int32_t>(intensity);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001548 std::vector<uint8_t> response;
1549 status_t status = command(EFFECT_CMD_SET_PARAM, request, sizeof(int32_t), &response);
jiabine70bc7f2020-06-30 22:07:55 -07001550 if (status == NO_ERROR) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001551 LOG_ALWAYS_FATAL_IF(response.size() != 4);
1552 status = *reinterpret_cast<const status_t*>(response.data());
jiabine70bc7f2020-06-30 22:07:55 -07001553 }
1554 return status;
1555}
1556
Lais Andradebc3f37a2021-07-02 00:13:19 +01001557status_t AudioFlinger::EffectModule::setVibratorInfo(const media::AudioVibratorInfo& vibratorInfo)
jiabin1319f5a2021-03-30 22:21:24 +00001558{
1559 if (mStatus != NO_ERROR) {
1560 return mStatus;
1561 }
1562 if (!isHapticGenerator()) {
1563 ALOGW("Should not set vibrator info for effects that are not HapticGenerator");
1564 return INVALID_OPERATION;
1565 }
1566
Lais Andradebc3f37a2021-07-02 00:13:19 +01001567 const size_t paramCount = 3;
jiabin1319f5a2021-03-30 22:21:24 +00001568 std::vector<uint8_t> request(
Lais Andradebc3f37a2021-07-02 00:13:19 +01001569 sizeof(effect_param_t) + sizeof(int32_t) + paramCount * sizeof(float));
jiabin1319f5a2021-03-30 22:21:24 +00001570 effect_param_t *param = (effect_param_t*) request.data();
1571 param->psize = sizeof(int32_t);
Lais Andradebc3f37a2021-07-02 00:13:19 +01001572 param->vsize = paramCount * sizeof(float);
jiabin1319f5a2021-03-30 22:21:24 +00001573 *(int32_t*)param->data = HG_PARAM_VIBRATOR_INFO;
1574 float* vibratorInfoPtr = reinterpret_cast<float*>(param->data + sizeof(int32_t));
Lais Andradebc3f37a2021-07-02 00:13:19 +01001575 vibratorInfoPtr[0] = vibratorInfo.resonantFrequency;
1576 vibratorInfoPtr[1] = vibratorInfo.qFactor;
1577 vibratorInfoPtr[2] = vibratorInfo.maxAmplitude;
jiabin1319f5a2021-03-30 22:21:24 +00001578 std::vector<uint8_t> response;
1579 status_t status = command(EFFECT_CMD_SET_PARAM, request, sizeof(int32_t), &response);
1580 if (status == NO_ERROR) {
1581 LOG_ALWAYS_FATAL_IF(response.size() != sizeof(status_t));
1582 status = *reinterpret_cast<const status_t*>(response.data());
1583 }
1584 return status;
1585}
1586
Mikhail Naganov8d7da002022-04-19 21:21:23 +00001587status_t AudioFlinger::EffectModule::getConfigs(
1588 audio_config_base_t* inputCfg, audio_config_base_t* outputCfg, bool* isOutput) const {
1589 Mutex::Autolock _l(mLock);
1590 if (mConfig.inputCfg.mask == 0 || mConfig.outputCfg.mask == 0) {
1591 return NO_INIT;
1592 }
1593 inputCfg->sample_rate = mConfig.inputCfg.samplingRate;
1594 inputCfg->channel_mask = static_cast<audio_channel_mask_t>(mConfig.inputCfg.channels);
1595 inputCfg->format = static_cast<audio_format_t>(mConfig.inputCfg.format);
1596 outputCfg->sample_rate = mConfig.outputCfg.samplingRate;
1597 outputCfg->channel_mask = static_cast<audio_channel_mask_t>(mConfig.outputCfg.channels);
1598 outputCfg->format = static_cast<audio_format_t>(mConfig.outputCfg.format);
1599 *isOutput = mIsOutput;
1600 return NO_ERROR;
1601}
1602
Andy Hungbded9c82017-11-30 18:47:35 -08001603static std::string dumpInOutBuffer(bool isInput, const sp<EffectBufferHalInterface> &buffer) {
1604 std::stringstream ss;
1605
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001606 if (buffer == nullptr) {
Andy Hungbded9c82017-11-30 18:47:35 -08001607 return "nullptr"; // make different than below
1608 } else if (buffer->externalData() != nullptr) {
1609 ss << (isInput ? buffer->externalData() : buffer->audioBuffer()->raw)
1610 << " -> "
1611 << (isInput ? buffer->audioBuffer()->raw : buffer->externalData());
1612 } else {
1613 ss << buffer->audioBuffer()->raw;
1614 }
1615 return ss.str();
1616}
Marco Nelissenb2208842014-02-07 14:00:50 -08001617
Eric Laurent41709552019-12-16 19:34:05 -08001618void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001619NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurentca7cc822012-11-19 14:55:58 -08001620{
Eric Laurent41709552019-12-16 19:34:05 -08001621 EffectBase::dump(fd, args);
1622
Eric Laurentca7cc822012-11-19 14:55:58 -08001623 String8 result;
Eric Laurentca7cc822012-11-19 14:55:58 -08001624 bool locked = AudioFlinger::dumpTryLock(mLock);
Eric Laurentca7cc822012-11-19 14:55:58 -08001625
Eric Laurent41709552019-12-16 19:34:05 -08001626 result.append("\t\tStatus Engine:\n");
1627 result.appendFormat("\t\t%03d %p\n",
1628 mStatus, mEffectInterface.get());
Andy Hung9718d662017-12-22 17:57:39 -08001629
1630 result.appendFormat("\t\t- data: %s\n", mSupportsFloat ? "float" : "int16");
Eric Laurentca7cc822012-11-19 14:55:58 -08001631
1632 result.append("\t\t- Input configuration:\n");
Andy Hung9718d662017-12-22 17:57:39 -08001633 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
1634 result.appendFormat("\t\t\t%p %05zu %05d %08x %6d (%s)\n",
1635 mConfig.inputCfg.buffer.raw,
Eric Laurentca7cc822012-11-19 14:55:58 -08001636 mConfig.inputCfg.buffer.frameCount,
1637 mConfig.inputCfg.samplingRate,
1638 mConfig.inputCfg.channels,
Marco Nelissenb2208842014-02-07 14:00:50 -08001639 mConfig.inputCfg.format,
Andy Hung9718d662017-12-22 17:57:39 -08001640 formatToString((audio_format_t)mConfig.inputCfg.format).c_str());
Eric Laurentca7cc822012-11-19 14:55:58 -08001641
1642 result.append("\t\t- Output configuration:\n");
1643 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
Andy Hung9718d662017-12-22 17:57:39 -08001644 result.appendFormat("\t\t\t%p %05zu %05d %08x %6d (%s)\n",
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001645 mConfig.outputCfg.buffer.raw,
Eric Laurentca7cc822012-11-19 14:55:58 -08001646 mConfig.outputCfg.buffer.frameCount,
1647 mConfig.outputCfg.samplingRate,
1648 mConfig.outputCfg.channels,
Marco Nelissenb2208842014-02-07 14:00:50 -08001649 mConfig.outputCfg.format,
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001650 formatToString((audio_format_t)mConfig.outputCfg.format).c_str());
Eric Laurentca7cc822012-11-19 14:55:58 -08001651
Andy Hungbded9c82017-11-30 18:47:35 -08001652 result.appendFormat("\t\t- HAL buffers:\n"
1653 "\t\t\tIn(%s) InConversion(%s) Out(%s) OutConversion(%s)\n",
1654 dumpInOutBuffer(true /* isInput */, mInBuffer).c_str(),
1655 dumpInOutBuffer(true /* isInput */, mInConversionBuffer).c_str(),
1656 dumpInOutBuffer(false /* isInput */, mOutBuffer).c_str(),
1657 dumpInOutBuffer(false /* isInput */, mOutConversionBuffer).c_str());
rago94a1ee82017-07-21 15:11:02 -07001658
Eric Laurentca7cc822012-11-19 14:55:58 -08001659 write(fd, result.string(), result.length());
1660
Mikhail Naganov4d547672019-02-22 14:19:19 -08001661 if (mEffectInterface != 0) {
1662 dprintf(fd, "\tEffect ID %d HAL dump:\n", mId);
1663 (void)mEffectInterface->dump(fd);
1664 }
1665
Eric Laurentca7cc822012-11-19 14:55:58 -08001666 if (locked) {
1667 mLock.unlock();
1668 }
1669}
1670
1671// ----------------------------------------------------------------------------
1672// EffectHandle implementation
1673// ----------------------------------------------------------------------------
1674
1675#undef LOG_TAG
1676#define LOG_TAG "AudioFlinger::EffectHandle"
1677
Eric Laurent41709552019-12-16 19:34:05 -08001678AudioFlinger::EffectHandle::EffectHandle(const sp<EffectBase>& effect,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001679 const sp<AudioFlinger::Client>& client,
1680 const sp<media::IEffectClient>& effectClient,
Eric Laurentde8caf42021-08-11 17:19:25 +02001681 int32_t priority, bool notifyFramesProcessed)
Eric Laurentca7cc822012-11-19 14:55:58 -08001682 : BnEffect(),
1683 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentde8caf42021-08-11 17:19:25 +02001684 mPriority(priority), mHasControl(false), mEnabled(false), mDisconnected(false),
1685 mNotifyFramesProcessed(notifyFramesProcessed)
Eric Laurentca7cc822012-11-19 14:55:58 -08001686{
Eric Laurentb82e6b72019-11-22 17:25:04 -08001687 ALOGV("constructor %p client %p", this, client.get());
Andy Hung225aef62022-12-06 16:33:20 -08001688 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Eric Laurentca7cc822012-11-19 14:55:58 -08001689
1690 if (client == 0) {
1691 return;
1692 }
1693 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
Atneya3c61d882021-09-20 14:52:15 -04001694 mCblkMemory = client->allocator().allocate(mediautils::NamedAllocRequest{
1695 {static_cast<size_t>(EFFECT_PARAM_BUFFER_SIZE + bufOffset)},
1696 std::string("Effect ID: ")
1697 .append(std::to_string(effect->id()))
1698 .append(" Session ID: ")
1699 .append(std::to_string(static_cast<int>(effect->sessionId())))
1700 .append(" \n")
1701 });
Glenn Kastene75da402013-11-20 13:54:52 -08001702 if (mCblkMemory == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001703 (mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->unsecurePointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001704 ALOGE("not enough memory for Effect size=%zu", EFFECT_PARAM_BUFFER_SIZE +
Eric Laurentca7cc822012-11-19 14:55:58 -08001705 sizeof(effect_param_cblk_t));
Glenn Kastene75da402013-11-20 13:54:52 -08001706 mCblkMemory.clear();
Eric Laurentca7cc822012-11-19 14:55:58 -08001707 return;
1708 }
Glenn Kastene75da402013-11-20 13:54:52 -08001709 new(mCblk) effect_param_cblk_t();
1710 mBuffer = (uint8_t *)mCblk + bufOffset;
Eric Laurentca7cc822012-11-19 14:55:58 -08001711}
1712
1713AudioFlinger::EffectHandle::~EffectHandle()
1714{
1715 ALOGV("Destructor %p", this);
Eric Laurentca7cc822012-11-19 14:55:58 -08001716 disconnect(false);
1717}
1718
Andy Hungc747c532022-03-07 21:41:14 -08001719// Creates an association between Binder code to name for IEffect.
1720#define IEFFECT_BINDER_METHOD_MACRO_LIST \
1721BINDER_METHOD_ENTRY(enable) \
1722BINDER_METHOD_ENTRY(disable) \
1723BINDER_METHOD_ENTRY(command) \
1724BINDER_METHOD_ENTRY(disconnect) \
1725BINDER_METHOD_ENTRY(getCblk) \
Mikhail Naganov8d7da002022-04-19 21:21:23 +00001726BINDER_METHOD_ENTRY(getConfig) \
Andy Hungc747c532022-03-07 21:41:14 -08001727
1728// singleton for Binder Method Statistics for IEffect
1729mediautils::MethodStatistics<int>& getIEffectStatistics() {
1730 using Code = int;
1731
1732#pragma push_macro("BINDER_METHOD_ENTRY")
1733#undef BINDER_METHOD_ENTRY
1734#define BINDER_METHOD_ENTRY(ENTRY) \
1735 {(Code)media::BnEffect::TRANSACTION_##ENTRY, #ENTRY},
1736
1737 static mediautils::MethodStatistics<Code> methodStatistics{
1738 IEFFECT_BINDER_METHOD_MACRO_LIST
1739 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
1740 };
1741#pragma pop_macro("BINDER_METHOD_ENTRY")
1742
1743 return methodStatistics;
1744}
1745
1746status_t AudioFlinger::EffectHandle::onTransact(
1747 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Andy Hunga2a1ac32022-03-18 16:12:11 -07001748 const std::string methodName = getIEffectStatistics().getMethodForCode(code);
1749 mediautils::TimeCheck check(
1750 std::string("IEffect::").append(methodName),
1751 [code](bool timeout, float elapsedMs) {
1752 if (timeout) {
1753 ; // we don't timeout right now on the effect interface.
1754 } else {
1755 getIEffectStatistics().event(code, elapsedMs);
1756 }
Andy Hungf8ab0932022-06-13 19:49:43 -07001757 }, {} /* timeoutDuration */, {} /* secondChanceDuration */, false /* crashOnTimeout */);
Andy Hungc747c532022-03-07 21:41:14 -08001758 return BnEffect::onTransact(code, data, reply, flags);
1759}
1760
Glenn Kastene75da402013-11-20 13:54:52 -08001761status_t AudioFlinger::EffectHandle::initCheck()
1762{
1763 return mClient == 0 || mCblkMemory != 0 ? OK : NO_MEMORY;
1764}
1765
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001766#define RETURN(code) \
1767 *_aidl_return = (code); \
1768 return Status::ok();
1769
Mikhail Naganov8d7da002022-04-19 21:21:23 +00001770#define VALUE_OR_RETURN_STATUS_AS_OUT(exp) \
1771 ({ \
1772 auto _tmp = (exp); \
1773 if (!_tmp.ok()) { RETURN(_tmp.error()); } \
1774 std::move(_tmp.value()); \
1775 })
1776
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001777Status AudioFlinger::EffectHandle::enable(int32_t* _aidl_return)
Eric Laurentca7cc822012-11-19 14:55:58 -08001778{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001779 AutoMutex _l(mLock);
Eric Laurentca7cc822012-11-19 14:55:58 -08001780 ALOGV("enable %p", this);
Eric Laurent41709552019-12-16 19:34:05 -08001781 sp<EffectBase> effect = mEffect.promote();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001782 if (effect == 0 || mDisconnected) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001783 RETURN(DEAD_OBJECT);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001784 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001785 if (!mHasControl) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001786 RETURN(INVALID_OPERATION);
Eric Laurentca7cc822012-11-19 14:55:58 -08001787 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001788
1789 if (mEnabled) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001790 RETURN(NO_ERROR);
Eric Laurentca7cc822012-11-19 14:55:58 -08001791 }
1792
1793 mEnabled = true;
1794
Eric Laurent6c796322019-04-09 14:13:17 -07001795 status_t status = effect->updatePolicyState();
1796 if (status != NO_ERROR) {
1797 mEnabled = false;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001798 RETURN(status);
Eric Laurent6c796322019-04-09 14:13:17 -07001799 }
1800
Eric Laurent6b446ce2019-12-13 10:56:31 -08001801 effect->checkSuspendOnEffectEnabled(true, false /*threadLocked*/);
Eric Laurentca7cc822012-11-19 14:55:58 -08001802
1803 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001804 if (effect->suspended()) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001805 RETURN(NO_ERROR);
Eric Laurentca7cc822012-11-19 14:55:58 -08001806 }
1807
Eric Laurent6b446ce2019-12-13 10:56:31 -08001808 status = effect->setEnabled(true, true /*fromHandle*/);
Eric Laurentca7cc822012-11-19 14:55:58 -08001809 if (status != NO_ERROR) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001810 mEnabled = false;
1811 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001812 RETURN(status);
Eric Laurentca7cc822012-11-19 14:55:58 -08001813}
1814
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001815Status AudioFlinger::EffectHandle::disable(int32_t* _aidl_return)
Eric Laurentca7cc822012-11-19 14:55:58 -08001816{
1817 ALOGV("disable %p", this);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001818 AutoMutex _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001819 sp<EffectBase> effect = mEffect.promote();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001820 if (effect == 0 || mDisconnected) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001821 RETURN(DEAD_OBJECT);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001822 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001823 if (!mHasControl) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001824 RETURN(INVALID_OPERATION);
Eric Laurentca7cc822012-11-19 14:55:58 -08001825 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001826
1827 if (!mEnabled) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001828 RETURN(NO_ERROR);
Eric Laurentca7cc822012-11-19 14:55:58 -08001829 }
1830 mEnabled = false;
1831
Eric Laurent6c796322019-04-09 14:13:17 -07001832 effect->updatePolicyState();
1833
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001834 if (effect->suspended()) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001835 RETURN(NO_ERROR);
Eric Laurentca7cc822012-11-19 14:55:58 -08001836 }
1837
Eric Laurent6b446ce2019-12-13 10:56:31 -08001838 status_t status = effect->setEnabled(false, true /*fromHandle*/);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001839 RETURN(status);
Eric Laurentca7cc822012-11-19 14:55:58 -08001840}
1841
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001842Status AudioFlinger::EffectHandle::disconnect()
Eric Laurentca7cc822012-11-19 14:55:58 -08001843{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001844 ALOGV("%s %p", __FUNCTION__, this);
Eric Laurentca7cc822012-11-19 14:55:58 -08001845 disconnect(true);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001846 return Status::ok();
Eric Laurentca7cc822012-11-19 14:55:58 -08001847}
1848
1849void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
1850{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001851 AutoMutex _l(mLock);
1852 ALOGV("disconnect(%s) %p", unpinIfLast ? "true" : "false", this);
1853 if (mDisconnected) {
1854 if (unpinIfLast) {
1855 android_errorWriteLog(0x534e4554, "32707507");
1856 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001857 return;
1858 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001859 mDisconnected = true;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001860 {
Eric Laurent41709552019-12-16 19:34:05 -08001861 sp<EffectBase> effect = mEffect.promote();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001862 if (effect != 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001863 if (effect->disconnectHandle(this, unpinIfLast) > 0) {
Eric Laurent6c796322019-04-09 14:13:17 -07001864 ALOGW("%s Effect handle %p disconnected after thread destruction",
1865 __func__, this);
1866 }
1867 effect->updatePolicyState();
Eric Laurentf10c7092016-12-06 17:09:56 -08001868 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001869 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001870
Eric Laurentca7cc822012-11-19 14:55:58 -08001871 if (mClient != 0) {
1872 if (mCblk != NULL) {
1873 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
1874 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
1875 }
1876 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Eric Laurent021cf962014-05-13 10:18:14 -07001877 // Client destructor must run with AudioFlinger client mutex locked
Andy Hung920f6572022-10-06 12:09:49 -07001878 Mutex::Autolock _l2(mClient->audioFlinger()->mClientLock);
Eric Laurentca7cc822012-11-19 14:55:58 -08001879 mClient.clear();
1880 }
1881}
1882
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001883Status AudioFlinger::EffectHandle::getCblk(media::SharedFileRegion* _aidl_return) {
1884 LOG_ALWAYS_FATAL_IF(!convertIMemoryToSharedFileRegion(mCblkMemory, _aidl_return));
1885 return Status::ok();
1886}
1887
Mikhail Naganov8d7da002022-04-19 21:21:23 +00001888Status AudioFlinger::EffectHandle::getConfig(
1889 media::EffectConfig* _config, int32_t* _aidl_return) {
1890 AutoMutex _l(mLock);
1891 sp<EffectBase> effect = mEffect.promote();
1892 if (effect == nullptr || mDisconnected) {
1893 RETURN(DEAD_OBJECT);
1894 }
1895 sp<EffectModule> effectModule = effect->asEffectModule();
1896 if (effectModule == nullptr) {
1897 RETURN(INVALID_OPERATION);
1898 }
1899 audio_config_base_t inputCfg = AUDIO_CONFIG_BASE_INITIALIZER;
1900 audio_config_base_t outputCfg = AUDIO_CONFIG_BASE_INITIALIZER;
1901 bool isOutput;
1902 status_t status = effectModule->getConfigs(&inputCfg, &outputCfg, &isOutput);
1903 if (status == NO_ERROR) {
1904 constexpr bool isInput = false; // effects always use 'OUT' channel masks.
1905 _config->inputCfg = VALUE_OR_RETURN_STATUS_AS_OUT(
1906 legacy2aidl_audio_config_base_t_AudioConfigBase(inputCfg, isInput));
1907 _config->outputCfg = VALUE_OR_RETURN_STATUS_AS_OUT(
1908 legacy2aidl_audio_config_base_t_AudioConfigBase(outputCfg, isInput));
1909 _config->isOnInputStream = !isOutput;
1910 }
1911 RETURN(status);
1912}
1913
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001914Status AudioFlinger::EffectHandle::command(int32_t cmdCode,
1915 const std::vector<uint8_t>& cmdData,
1916 int32_t maxResponseSize,
1917 std::vector<uint8_t>* response,
1918 int32_t* _aidl_return)
Eric Laurentca7cc822012-11-19 14:55:58 -08001919{
1920 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001921 cmdCode, mHasControl, mEffect.unsafe_get());
Eric Laurentca7cc822012-11-19 14:55:58 -08001922
Eric Laurentc7ab3092017-06-15 18:43:46 -07001923 // reject commands reserved for internal use by audio framework if coming from outside
1924 // of audioserver
1925 switch(cmdCode) {
1926 case EFFECT_CMD_ENABLE:
1927 case EFFECT_CMD_DISABLE:
1928 case EFFECT_CMD_SET_PARAM:
1929 case EFFECT_CMD_SET_PARAM_DEFERRED:
1930 case EFFECT_CMD_SET_PARAM_COMMIT:
1931 case EFFECT_CMD_GET_PARAM:
1932 break;
1933 default:
1934 if (cmdCode >= EFFECT_CMD_FIRST_PROPRIETARY) {
1935 break;
1936 }
1937 android_errorWriteLog(0x534e4554, "62019992");
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001938 RETURN(BAD_VALUE);
Eric Laurentc7ab3092017-06-15 18:43:46 -07001939 }
1940
Eric Laurent1ffc5852016-12-15 14:46:09 -08001941 if (cmdCode == EFFECT_CMD_ENABLE) {
Andy Hung920f6572022-10-06 12:09:49 -07001942 if (maxResponseSize < static_cast<signed>(sizeof(int))) {
Eric Laurent1ffc5852016-12-15 14:46:09 -08001943 android_errorWriteLog(0x534e4554, "32095713");
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001944 RETURN(BAD_VALUE);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001945 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001946 writeToBuffer(NO_ERROR, response);
1947 return enable(_aidl_return);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001948 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Andy Hung920f6572022-10-06 12:09:49 -07001949 if (maxResponseSize < static_cast<signed>(sizeof(int))) {
Eric Laurent1ffc5852016-12-15 14:46:09 -08001950 android_errorWriteLog(0x534e4554, "32095713");
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001951 RETURN(BAD_VALUE);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001952 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001953 writeToBuffer(NO_ERROR, response);
1954 return disable(_aidl_return);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001955 }
1956
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001957 AutoMutex _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001958 sp<EffectBase> effect = mEffect.promote();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001959 if (effect == 0 || mDisconnected) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001960 RETURN(DEAD_OBJECT);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001961 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001962 // only get parameter command is permitted for applications not controlling the effect
1963 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001964 RETURN(INVALID_OPERATION);
Eric Laurentca7cc822012-11-19 14:55:58 -08001965 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001966
1967 // handle commands that are not forwarded transparently to effect engine
1968 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08001969 if (mClient == 0) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001970 RETURN(INVALID_OPERATION);
Eric Laurentb82e6b72019-11-22 17:25:04 -08001971 }
1972
Andy Hung920f6572022-10-06 12:09:49 -07001973 if (maxResponseSize < (signed)sizeof(int)) {
Eric Laurent1ffc5852016-12-15 14:46:09 -08001974 android_errorWriteLog(0x534e4554, "32095713");
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001975 RETURN(BAD_VALUE);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001976 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001977 writeToBuffer(NO_ERROR, response);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001978
Eric Laurentca7cc822012-11-19 14:55:58 -08001979 // No need to trylock() here as this function is executed in the binder thread serving a
1980 // particular client process: no risk to block the whole media server process or mixer
1981 // threads if we are stuck here
Andy Hung920f6572022-10-06 12:09:49 -07001982 Mutex::Autolock _l2(mCblk->lock);
Andy Hunga447a0f2016-11-15 17:19:58 -08001983 // keep local copy of index in case of client corruption b/32220769
1984 const uint32_t clientIndex = mCblk->clientIndex;
1985 const uint32_t serverIndex = mCblk->serverIndex;
1986 if (clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
1987 serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001988 mCblk->serverIndex = 0;
1989 mCblk->clientIndex = 0;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001990 RETURN(BAD_VALUE);
Eric Laurentca7cc822012-11-19 14:55:58 -08001991 }
1992 status_t status = NO_ERROR;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001993 std::vector<uint8_t> param;
Andy Hunga447a0f2016-11-15 17:19:58 -08001994 for (uint32_t index = serverIndex; index < clientIndex;) {
1995 int *p = (int *)(mBuffer + index);
1996 const int size = *p++;
1997 if (size < 0
1998 || size > EFFECT_PARAM_BUFFER_SIZE
1999 || ((uint8_t *)p + size) > mBuffer + clientIndex) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002000 ALOGW("command(): invalid parameter block size");
Andy Hunga447a0f2016-11-15 17:19:58 -08002001 status = BAD_VALUE;
Eric Laurentca7cc822012-11-19 14:55:58 -08002002 break;
2003 }
Andy Hunga447a0f2016-11-15 17:19:58 -08002004
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002005 std::copy(reinterpret_cast<const uint8_t*>(p),
2006 reinterpret_cast<const uint8_t*>(p) + size,
2007 std::back_inserter(param));
Andy Hunga447a0f2016-11-15 17:19:58 -08002008
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002009 std::vector<uint8_t> replyBuffer;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002010 status_t ret = effect->command(EFFECT_CMD_SET_PARAM,
Andy Hunga447a0f2016-11-15 17:19:58 -08002011 param,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002012 sizeof(int),
2013 &replyBuffer);
2014 int reply = *reinterpret_cast<const int*>(replyBuffer.data());
Andy Hunga447a0f2016-11-15 17:19:58 -08002015
2016 // verify shared memory: server index shouldn't change; client index can't go back.
2017 if (serverIndex != mCblk->serverIndex
2018 || clientIndex > mCblk->clientIndex) {
2019 android_errorWriteLog(0x534e4554, "32220769");
2020 status = BAD_VALUE;
2021 break;
2022 }
2023
Eric Laurentca7cc822012-11-19 14:55:58 -08002024 // stop at first error encountered
2025 if (ret != NO_ERROR) {
2026 status = ret;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002027 writeToBuffer(reply, response);
Eric Laurentca7cc822012-11-19 14:55:58 -08002028 break;
2029 } else if (reply != NO_ERROR) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002030 writeToBuffer(reply, response);
Eric Laurentca7cc822012-11-19 14:55:58 -08002031 break;
2032 }
Andy Hunga447a0f2016-11-15 17:19:58 -08002033 index += size;
Eric Laurentca7cc822012-11-19 14:55:58 -08002034 }
2035 mCblk->serverIndex = 0;
2036 mCblk->clientIndex = 0;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002037 RETURN(status);
Eric Laurentca7cc822012-11-19 14:55:58 -08002038 }
2039
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002040 status_t status = effect->command(cmdCode,
2041 cmdData,
2042 maxResponseSize,
2043 response);
2044 RETURN(status);
Eric Laurentca7cc822012-11-19 14:55:58 -08002045}
2046
2047void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
2048{
2049 ALOGV("setControl %p control %d", this, hasControl);
2050
2051 mHasControl = hasControl;
2052 mEnabled = enabled;
2053
2054 if (signal && mEffectClient != 0) {
2055 mEffectClient->controlStatusChanged(hasControl);
2056 }
2057}
2058
2059void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002060 const std::vector<uint8_t>& cmdData,
2061 const std::vector<uint8_t>& replyData)
Eric Laurentca7cc822012-11-19 14:55:58 -08002062{
2063 if (mEffectClient != 0) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002064 mEffectClient->commandExecuted(cmdCode, cmdData, replyData);
Eric Laurentca7cc822012-11-19 14:55:58 -08002065 }
2066}
2067
2068
2069
2070void AudioFlinger::EffectHandle::setEnabled(bool enabled)
2071{
2072 if (mEffectClient != 0) {
2073 mEffectClient->enableStatusChanged(enabled);
2074 }
2075}
2076
Eric Laurentde8caf42021-08-11 17:19:25 +02002077void AudioFlinger::EffectHandle::framesProcessed(int32_t frames) const
2078{
2079 if (mEffectClient != 0 && mNotifyFramesProcessed) {
2080 mEffectClient->framesProcessed(frames);
2081 }
2082}
2083
Glenn Kasten01d3acb2014-02-06 08:24:07 -08002084void AudioFlinger::EffectHandle::dumpToBuffer(char* buffer, size_t size)
Andy Hung920f6572022-10-06 12:09:49 -07002085NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurentca7cc822012-11-19 14:55:58 -08002086{
2087 bool locked = mCblk != NULL && AudioFlinger::dumpTryLock(mCblk->lock);
2088
Marco Nelissenb2208842014-02-07 14:00:50 -08002089 snprintf(buffer, size, "\t\t\t%5d %5d %3s %3s %5u %5u\n",
Andy Hung4ef19fa2018-05-15 19:35:29 -07002090 (mClient == 0) ? getpid() : mClient->pid(),
Eric Laurentca7cc822012-11-19 14:55:58 -08002091 mPriority,
Marco Nelissenb2208842014-02-07 14:00:50 -08002092 mHasControl ? "yes" : "no",
2093 locked ? "yes" : "no",
Eric Laurentca7cc822012-11-19 14:55:58 -08002094 mCblk ? mCblk->clientIndex : 0,
2095 mCblk ? mCblk->serverIndex : 0
2096 );
2097
2098 if (locked) {
2099 mCblk->lock.unlock();
2100 }
2101}
2102
2103#undef LOG_TAG
2104#define LOG_TAG "AudioFlinger::EffectChain"
2105
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002106AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& thread,
2107 audio_session_t sessionId)
Eric Laurent6b446ce2019-12-13 10:56:31 -08002108 : mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002109 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
Eric Laurent6b446ce2019-12-13 10:56:31 -08002110 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX),
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002111 mEffectCallback(new EffectCallback(wp<EffectChain>(this), thread))
Eric Laurentca7cc822012-11-19 14:55:58 -08002112{
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002113 sp<ThreadBase> p = thread.promote();
2114 if (p == nullptr) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002115 return;
2116 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02002117 mStrategy = p->getStrategyForStream(AUDIO_STREAM_MUSIC);
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002118 mMaxTailBuffers = ((kProcessTailDurationMs * p->sampleRate()) / 1000) /
2119 p->frameCount();
Eric Laurentca7cc822012-11-19 14:55:58 -08002120}
2121
2122AudioFlinger::EffectChain::~EffectChain()
2123{
Eric Laurentca7cc822012-11-19 14:55:58 -08002124}
2125
2126// getEffectFromDesc_l() must be called with ThreadBase::mLock held
2127sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
2128 effect_descriptor_t *descriptor)
2129{
2130 size_t size = mEffects.size();
2131
2132 for (size_t i = 0; i < size; i++) {
2133 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
2134 return mEffects[i];
2135 }
2136 }
2137 return 0;
2138}
2139
2140// getEffectFromId_l() must be called with ThreadBase::mLock held
2141sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
2142{
2143 size_t size = mEffects.size();
2144
2145 for (size_t i = 0; i < size; i++) {
2146 // by convention, return first effect if id provided is 0 (0 is never a valid id)
2147 if (id == 0 || mEffects[i]->id() == id) {
2148 return mEffects[i];
2149 }
2150 }
2151 return 0;
2152}
2153
2154// getEffectFromType_l() must be called with ThreadBase::mLock held
2155sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
2156 const effect_uuid_t *type)
2157{
2158 size_t size = mEffects.size();
2159
2160 for (size_t i = 0; i < size; i++) {
2161 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
2162 return mEffects[i];
2163 }
2164 }
2165 return 0;
2166}
2167
Eric Laurent6c796322019-04-09 14:13:17 -07002168std::vector<int> AudioFlinger::EffectChain::getEffectIds()
2169{
2170 std::vector<int> ids;
2171 Mutex::Autolock _l(mLock);
2172 for (size_t i = 0; i < mEffects.size(); i++) {
2173 ids.push_back(mEffects[i]->id());
2174 }
2175 return ids;
2176}
2177
Eric Laurentca7cc822012-11-19 14:55:58 -08002178void AudioFlinger::EffectChain::clearInputBuffer()
2179{
2180 Mutex::Autolock _l(mLock);
Eric Laurent6b446ce2019-12-13 10:56:31 -08002181 clearInputBuffer_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08002182}
2183
2184// Must be called with EffectChain::mLock locked
Eric Laurent6b446ce2019-12-13 10:56:31 -08002185void AudioFlinger::EffectChain::clearInputBuffer_l()
Eric Laurentca7cc822012-11-19 14:55:58 -08002186{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002187 if (mInBuffer == NULL) {
2188 return;
2189 }
Andy Hung319587b2023-05-23 14:01:03 -07002190 const size_t frameSize = audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002191 * mEffectCallback->inChannelCount(mEffects[0]->id());
rago94a1ee82017-07-21 15:11:02 -07002192
Eric Laurent6b446ce2019-12-13 10:56:31 -08002193 memset(mInBuffer->audioBuffer()->raw, 0, mEffectCallback->frameCount() * frameSize);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002194 mInBuffer->commit();
Eric Laurentca7cc822012-11-19 14:55:58 -08002195}
2196
2197// Must be called with EffectChain::mLock locked
2198void AudioFlinger::EffectChain::process_l()
2199{
Jean-Michel Trivifed62922013-09-25 18:50:33 -07002200 // never process effects when:
2201 // - on an OFFLOAD thread
2202 // - no more tracks are on the session and the effect tail has been rendered
Eric Laurent6b446ce2019-12-13 10:56:31 -08002203 bool doProcess = !mEffectCallback->isOffloadOrMmap();
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002204 if (!audio_is_global_session(mSessionId)) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002205 bool tracksOnSession = (trackCnt() != 0);
2206
2207 if (!tracksOnSession && mTailBufferCount == 0) {
2208 doProcess = false;
2209 }
2210
2211 if (activeTrackCnt() == 0) {
2212 // if no track is active and the effect tail has not been rendered,
2213 // the input buffer must be cleared here as the mixer process will not do it
2214 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08002215 clearInputBuffer_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08002216 if (mTailBufferCount > 0) {
2217 mTailBufferCount--;
2218 }
2219 }
2220 }
2221 }
2222
2223 size_t size = mEffects.size();
2224 if (doProcess) {
Mikhail Naganov022b9952017-01-04 16:36:51 -08002225 // Only the input and output buffers of the chain can be external,
2226 // and 'update' / 'commit' do nothing for allocated buffers, thus
2227 // it's not needed to consider any other buffers here.
2228 mInBuffer->update();
Mikhail Naganov06888802017-01-19 12:47:55 -08002229 if (mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw) {
2230 mOutBuffer->update();
2231 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002232 for (size_t i = 0; i < size; i++) {
2233 mEffects[i]->process();
2234 }
Mikhail Naganov06888802017-01-19 12:47:55 -08002235 mInBuffer->commit();
2236 if (mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw) {
2237 mOutBuffer->commit();
2238 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002239 }
Eric Laurentfa1e1232016-08-02 19:01:49 -07002240 bool doResetVolume = false;
Eric Laurentca7cc822012-11-19 14:55:58 -08002241 for (size_t i = 0; i < size; i++) {
Eric Laurentfa1e1232016-08-02 19:01:49 -07002242 doResetVolume = mEffects[i]->updateState() || doResetVolume;
2243 }
2244 if (doResetVolume) {
2245 resetVolume_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08002246 }
2247}
2248
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002249// createEffect_l() must be called with ThreadBase::mLock held
2250status_t AudioFlinger::EffectChain::createEffect_l(sp<EffectModule>& effect,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002251 effect_descriptor_t *desc,
2252 int id,
2253 audio_session_t sessionId,
2254 bool pinned)
2255{
2256 Mutex::Autolock _l(mLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -08002257 effect = new EffectModule(mEffectCallback, desc, id, sessionId, pinned, AUDIO_PORT_HANDLE_NONE);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002258 status_t lStatus = effect->status();
2259 if (lStatus == NO_ERROR) {
2260 lStatus = addEffect_ll(effect);
2261 }
2262 if (lStatus != NO_ERROR) {
2263 effect.clear();
2264 }
2265 return lStatus;
2266}
2267
2268// addEffect_l() must be called with ThreadBase::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -08002269status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
2270{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002271 Mutex::Autolock _l(mLock);
2272 return addEffect_ll(effect);
2273}
2274// addEffect_l() must be called with ThreadBase::mLock and EffectChain::mLock held
2275status_t AudioFlinger::EffectChain::addEffect_ll(const sp<EffectModule>& effect)
2276{
Eric Laurent6b446ce2019-12-13 10:56:31 -08002277 effect->setCallback(mEffectCallback);
Eric Laurentca7cc822012-11-19 14:55:58 -08002278
Eric Laurentb62d0362021-10-26 17:40:18 +02002279 effect_descriptor_t desc = effect->desc();
Eric Laurentca7cc822012-11-19 14:55:58 -08002280 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2281 // Auxiliary effects are inserted at the beginning of mEffects vector as
2282 // they are processed first and accumulated in chain input buffer
2283 mEffects.insertAt(effect, 0);
2284
2285 // the input buffer for auxiliary effect contains mono samples in
2286 // 32 bit format. This is to avoid saturation in AudoMixer
2287 // accumulation stage. Saturation is done in EffectModule::process() before
2288 // calling the process in effect engine
Eric Laurent6b446ce2019-12-13 10:56:31 -08002289 size_t numSamples = mEffectCallback->frameCount();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002290 sp<EffectBufferHalInterface> halBuffer;
Andy Hung26836922023-05-22 17:31:57 -07002291
Eric Laurent6b446ce2019-12-13 10:56:31 -08002292 status_t result = mEffectCallback->allocateHalBuffer(
rago94a1ee82017-07-21 15:11:02 -07002293 numSamples * sizeof(float), &halBuffer);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002294 if (result != OK) return result;
Eric Laurentf1f22e72021-07-13 14:04:14 +02002295
2296 effect->configure();
2297
Mikhail Naganov022b9952017-01-04 16:36:51 -08002298 effect->setInBuffer(halBuffer);
Eric Laurentca7cc822012-11-19 14:55:58 -08002299 // auxiliary effects output samples to chain input buffer for further processing
2300 // by insert effects
2301 effect->setOutBuffer(mInBuffer);
2302 } else {
Eric Laurentb62d0362021-10-26 17:40:18 +02002303 ssize_t idx_insert = getInsertIndex(desc);
2304 if (idx_insert < 0) {
2305 return INVALID_OPERATION;
Eric Laurentca7cc822012-11-19 14:55:58 -08002306 }
2307
Eric Laurentb62d0362021-10-26 17:40:18 +02002308 size_t previousSize = mEffects.size();
Eric Laurentf1f22e72021-07-13 14:04:14 +02002309 mEffects.insertAt(effect, idx_insert);
2310
2311 effect->configure();
2312
Eric Laurentb62d0362021-10-26 17:40:18 +02002313 // - By default:
2314 // All effects read samples from chain input buffer.
2315 // The last effect in the chain, writes samples to chain output buffer,
2316 // otherwise to chain input buffer
2317 // - In the OUTPUT_STAGE chain of a spatializer mixer thread:
2318 // The spatializer effect (first effect) reads samples from the input buffer
2319 // and writes samples to the output buffer.
2320 // All other effects read and writes samples to the output buffer
2321 if (mEffectCallback->isSpatializer()
2322 && mSessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002323 effect->setOutBuffer(mOutBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002324 if (idx_insert == 0) {
2325 if (previousSize != 0) {
2326 mEffects[1]->configure();
2327 mEffects[1]->setInBuffer(mOutBuffer);
2328 mEffects[1]->updateAccessMode(); // reconfig if neeeded.
2329 }
2330 effect->setInBuffer(mInBuffer);
2331 } else {
2332 effect->setInBuffer(mOutBuffer);
2333 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002334 } else {
Eric Laurentb62d0362021-10-26 17:40:18 +02002335 effect->setInBuffer(mInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07002336 if (idx_insert == static_cast<ssize_t>(previousSize)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02002337 if (idx_insert != 0) {
2338 mEffects[idx_insert-1]->configure();
2339 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
2340 mEffects[idx_insert - 1]->updateAccessMode(); // reconfig if neeeded.
2341 }
2342 effect->setOutBuffer(mOutBuffer);
2343 } else {
2344 effect->setOutBuffer(mInBuffer);
2345 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002346 }
Eric Laurentb62d0362021-10-26 17:40:18 +02002347 ALOGV("%s effect %p, added in chain %p at rank %zu",
2348 __func__, effect.get(), this, idx_insert);
Eric Laurentca7cc822012-11-19 14:55:58 -08002349 }
2350 effect->configure();
Eric Laurentd8365c52017-07-16 15:27:05 -07002351
Eric Laurentca7cc822012-11-19 14:55:58 -08002352 return NO_ERROR;
2353}
2354
Eric Laurentb62d0362021-10-26 17:40:18 +02002355ssize_t AudioFlinger::EffectChain::getInsertIndex(const effect_descriptor_t& desc) {
2356 // Insert effects are inserted at the end of mEffects vector as they are processed
2357 // after track and auxiliary effects.
2358 // Insert effect order as a function of indicated preference:
2359 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
2360 // another effect is present
2361 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
2362 // last effect claiming first position
2363 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
2364 // first effect claiming last position
2365 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
2366 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
2367 // already present
2368 // Spatializer or Downmixer effects are inserted in first position because
2369 // they adapt the channel count for all other effects in the chain
2370 if ((memcmp(&desc.type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0)
2371 || (memcmp(&desc.type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0)) {
2372 return 0;
2373 }
2374
2375 size_t size = mEffects.size();
2376 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
2377 ssize_t idx_insert;
2378 ssize_t idx_insert_first = -1;
2379 ssize_t idx_insert_last = -1;
2380
2381 idx_insert = size;
2382 for (size_t i = 0; i < size; i++) {
2383 effect_descriptor_t d = mEffects[i]->desc();
2384 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
2385 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
2386 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
2387 // check invalid effect chaining combinations
2388 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
2389 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
2390 ALOGW("%s could not insert effect %s: exclusive conflict with %s",
2391 __func__, desc.name, d.name);
2392 return -1;
2393 }
2394 // remember position of first insert effect and by default
2395 // select this as insert position for new effect
Andy Hung920f6572022-10-06 12:09:49 -07002396 if (idx_insert == static_cast<ssize_t>(size)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02002397 idx_insert = i;
2398 }
2399 // remember position of last insert effect claiming
2400 // first position
2401 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
2402 idx_insert_first = i;
2403 }
2404 // remember position of first insert effect claiming
2405 // last position
2406 if (iPref == EFFECT_FLAG_INSERT_LAST &&
2407 idx_insert_last == -1) {
2408 idx_insert_last = i;
2409 }
2410 }
2411 }
2412
2413 // modify idx_insert from first position if needed
2414 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
2415 if (idx_insert_last != -1) {
2416 idx_insert = idx_insert_last;
2417 } else {
2418 idx_insert = size;
2419 }
2420 } else {
2421 if (idx_insert_first != -1) {
2422 idx_insert = idx_insert_first + 1;
2423 }
2424 }
2425 return idx_insert;
2426}
2427
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002428// removeEffect_l() must be called with ThreadBase::mLock held
2429size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect,
2430 bool release)
Eric Laurentca7cc822012-11-19 14:55:58 -08002431{
2432 Mutex::Autolock _l(mLock);
2433 size_t size = mEffects.size();
2434 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
2435
2436 for (size_t i = 0; i < size; i++) {
2437 if (effect == mEffects[i]) {
2438 // calling stop here will remove pre-processing effect from the audio HAL.
2439 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
2440 // the middle of a read from audio HAL
2441 if (mEffects[i]->state() == EffectModule::ACTIVE ||
2442 mEffects[i]->state() == EffectModule::STOPPING) {
2443 mEffects[i]->stop();
2444 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002445 if (release) {
2446 mEffects[i]->release_l();
2447 }
2448
Mikhail Naganov022b9952017-01-04 16:36:51 -08002449 if (type != EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002450 if (i == size - 1 && i != 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002451 mEffects[i - 1]->configure();
Eric Laurentf1f22e72021-07-13 14:04:14 +02002452 mEffects[i - 1]->setOutBuffer(mOutBuffer);
Eric Laurent6bb7dbe2021-12-23 15:39:36 +01002453 mEffects[i - 1]->updateAccessMode(); // reconfig if neeeded.
Eric Laurentca7cc822012-11-19 14:55:58 -08002454 }
2455 }
2456 mEffects.removeAt(i);
Eric Laurentf1f22e72021-07-13 14:04:14 +02002457
2458 // make sure the input buffer configuration for the new first effect in the chain
2459 // is updated if needed (can switch from HAL channel mask to mixer channel mask)
Nie Wei Feng4d2cb592023-05-26 15:18:04 -07002460 if (type != EFFECT_FLAG_TYPE_AUXILIARY // TODO(b/284522658) breaks for aux FX, why?
2461 && i == 0 && size > 1) {
Eric Laurentf1f22e72021-07-13 14:04:14 +02002462 mEffects[0]->configure();
2463 mEffects[0]->setInBuffer(mInBuffer);
Eric Laurent6bb7dbe2021-12-23 15:39:36 +01002464 mEffects[0]->updateAccessMode(); // reconfig if neeeded.
Eric Laurentf1f22e72021-07-13 14:04:14 +02002465 }
2466
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002467 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %zu", effect.get(),
Eric Laurentca7cc822012-11-19 14:55:58 -08002468 this, i);
2469 break;
2470 }
2471 }
2472
2473 return mEffects.size();
2474}
2475
jiabin8f278ee2019-11-11 12:16:27 -08002476// setDevices_l() must be called with ThreadBase::mLock held
2477void AudioFlinger::EffectChain::setDevices_l(const AudioDeviceTypeAddrVector &devices)
Eric Laurentca7cc822012-11-19 14:55:58 -08002478{
2479 size_t size = mEffects.size();
2480 for (size_t i = 0; i < size; i++) {
jiabin8f278ee2019-11-11 12:16:27 -08002481 mEffects[i]->setDevices(devices);
2482 }
2483}
2484
2485// setInputDevice_l() must be called with ThreadBase::mLock held
2486void AudioFlinger::EffectChain::setInputDevice_l(const AudioDeviceTypeAddr &device)
2487{
2488 size_t size = mEffects.size();
2489 for (size_t i = 0; i < size; i++) {
2490 mEffects[i]->setInputDevice(device);
Eric Laurentca7cc822012-11-19 14:55:58 -08002491 }
2492}
2493
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002494// setMode_l() must be called with ThreadBase::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -08002495void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
2496{
2497 size_t size = mEffects.size();
2498 for (size_t i = 0; i < size; i++) {
2499 mEffects[i]->setMode(mode);
2500 }
2501}
2502
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002503// setAudioSource_l() must be called with ThreadBase::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -08002504void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
2505{
2506 size_t size = mEffects.size();
2507 for (size_t i = 0; i < size; i++) {
2508 mEffects[i]->setAudioSource(source);
2509 }
2510}
2511
Zhou Songd505c642020-02-20 16:35:37 +08002512bool AudioFlinger::EffectChain::hasVolumeControlEnabled_l() const {
2513 for (const auto &effect : mEffects) {
2514 if (effect->isVolumeControlEnabled()) return true;
2515 }
2516 return false;
2517}
2518
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002519// setVolume_l() must be called with ThreadBase::mLock or EffectChain::mLock held
Eric Laurentfa1e1232016-08-02 19:01:49 -07002520bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right, bool force)
Eric Laurentca7cc822012-11-19 14:55:58 -08002521{
2522 uint32_t newLeft = *left;
2523 uint32_t newRight = *right;
2524 bool hasControl = false;
2525 int ctrlIdx = -1;
2526 size_t size = mEffects.size();
2527
2528 // first update volume controller
2529 for (size_t i = size; i > 0; i--) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002530 if (mEffects[i - 1]->isVolumeControlEnabled()) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002531 ctrlIdx = i - 1;
2532 hasControl = true;
2533 break;
2534 }
2535 }
2536
Eric Laurentfa1e1232016-08-02 19:01:49 -07002537 if (!force && ctrlIdx == mVolumeCtrlIdx &&
Eric Laurentcb4b6e92014-10-01 14:26:10 -07002538 *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002539 if (hasControl) {
2540 *left = mNewLeftVolume;
2541 *right = mNewRightVolume;
2542 }
2543 return hasControl;
2544 }
2545
2546 mVolumeCtrlIdx = ctrlIdx;
2547 mLeftVolume = newLeft;
2548 mRightVolume = newRight;
2549
2550 // second get volume update from volume controller
2551 if (ctrlIdx >= 0) {
2552 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
2553 mNewLeftVolume = newLeft;
2554 mNewRightVolume = newRight;
2555 }
2556 // then indicate volume to all other effects in chain.
2557 // Pass altered volume to effects before volume controller
Jasmine Cha934ecfb2019-01-23 18:19:14 +08002558 // and requested volume to effects after controller or with volume monitor flag
Eric Laurentca7cc822012-11-19 14:55:58 -08002559 uint32_t lVol = newLeft;
2560 uint32_t rVol = newRight;
2561
2562 for (size_t i = 0; i < size; i++) {
2563 if ((int)i == ctrlIdx) {
2564 continue;
2565 }
2566 // this also works for ctrlIdx == -1 when there is no volume controller
2567 if ((int)i > ctrlIdx) {
2568 lVol = *left;
2569 rVol = *right;
2570 }
Jasmine Cha934ecfb2019-01-23 18:19:14 +08002571 // Pass requested volume directly if this is volume monitor module
2572 if (mEffects[i]->isVolumeMonitor()) {
2573 mEffects[i]->setVolume(left, right, false);
2574 } else {
2575 mEffects[i]->setVolume(&lVol, &rVol, false);
2576 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002577 }
2578 *left = newLeft;
2579 *right = newRight;
2580
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002581 setVolumeForOutput_l(*left, *right);
2582
Eric Laurentca7cc822012-11-19 14:55:58 -08002583 return hasControl;
2584}
2585
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002586// resetVolume_l() must be called with ThreadBase::mLock or EffectChain::mLock held
Eric Laurentfa1e1232016-08-02 19:01:49 -07002587void AudioFlinger::EffectChain::resetVolume_l()
2588{
Eric Laurente7449bf2016-08-03 18:44:07 -07002589 if ((mLeftVolume != UINT_MAX) && (mRightVolume != UINT_MAX)) {
2590 uint32_t left = mLeftVolume;
2591 uint32_t right = mRightVolume;
2592 (void)setVolume_l(&left, &right, true);
2593 }
Eric Laurentfa1e1232016-08-02 19:01:49 -07002594}
2595
jiabineb3bda02020-06-30 14:07:03 -07002596// containsHapticGeneratingEffect_l must be called with ThreadBase::mLock or EffectChain::mLock held
2597bool AudioFlinger::EffectChain::containsHapticGeneratingEffect_l()
2598{
2599 for (size_t i = 0; i < mEffects.size(); ++i) {
2600 if (mEffects[i]->isHapticGenerator()) {
2601 return true;
2602 }
2603 }
2604 return false;
2605}
2606
Simon Bowden62823412022-10-17 14:52:26 +00002607void AudioFlinger::EffectChain::setHapticIntensity_l(int id, os::HapticScale intensity)
jiabine70bc7f2020-06-30 22:07:55 -07002608{
2609 Mutex::Autolock _l(mLock);
2610 for (size_t i = 0; i < mEffects.size(); ++i) {
2611 mEffects[i]->setHapticIntensity(id, intensity);
2612 }
2613}
2614
Eric Laurent1b928682014-10-02 19:41:47 -07002615void AudioFlinger::EffectChain::syncHalEffectsState()
2616{
2617 Mutex::Autolock _l(mLock);
2618 for (size_t i = 0; i < mEffects.size(); i++) {
2619 if (mEffects[i]->state() == EffectModule::ACTIVE ||
2620 mEffects[i]->state() == EffectModule::STOPPING) {
2621 mEffects[i]->addEffectToHal_l();
2622 }
2623 }
2624}
2625
Eric Laurentca7cc822012-11-19 14:55:58 -08002626void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07002627NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurentca7cc822012-11-19 14:55:58 -08002628{
Eric Laurentca7cc822012-11-19 14:55:58 -08002629 String8 result;
2630
Mikhail Naganov19740ca2019-03-28 12:25:01 -07002631 const size_t numEffects = mEffects.size();
2632 result.appendFormat(" %zu effects for session %d\n", numEffects, mSessionId);
Eric Laurentca7cc822012-11-19 14:55:58 -08002633
Marco Nelissenb2208842014-02-07 14:00:50 -08002634 if (numEffects) {
2635 bool locked = AudioFlinger::dumpTryLock(mLock);
2636 // failed to lock - AudioFlinger is probably deadlocked
2637 if (!locked) {
2638 result.append("\tCould not lock mutex:\n");
Eric Laurentca7cc822012-11-19 14:55:58 -08002639 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002640
Andy Hungbded9c82017-11-30 18:47:35 -08002641 const std::string inBufferStr = dumpInOutBuffer(true /* isInput */, mInBuffer);
2642 const std::string outBufferStr = dumpInOutBuffer(false /* isInput */, mOutBuffer);
2643 result.appendFormat("\t%-*s%-*s Active tracks:\n",
2644 (int)inBufferStr.size(), "In buffer ",
2645 (int)outBufferStr.size(), "Out buffer ");
2646 result.appendFormat("\t%s %s %d\n",
2647 inBufferStr.c_str(), outBufferStr.c_str(), mActiveTrackCnt);
Marco Nelissenb2208842014-02-07 14:00:50 -08002648 write(fd, result.string(), result.size());
2649
2650 for (size_t i = 0; i < numEffects; ++i) {
2651 sp<EffectModule> effect = mEffects[i];
2652 if (effect != 0) {
2653 effect->dump(fd, args);
2654 }
2655 }
2656
2657 if (locked) {
2658 mLock.unlock();
2659 }
Mikhail Naganov19740ca2019-03-28 12:25:01 -07002660 } else {
2661 write(fd, result.string(), result.size());
Eric Laurentca7cc822012-11-19 14:55:58 -08002662 }
2663}
2664
2665// must be called with ThreadBase::mLock held
2666void AudioFlinger::EffectChain::setEffectSuspended_l(
2667 const effect_uuid_t *type, bool suspend)
2668{
2669 sp<SuspendedEffectDesc> desc;
2670 // use effect type UUID timelow as key as there is no real risk of identical
2671 // timeLow fields among effect type UUIDs.
2672 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
2673 if (suspend) {
2674 if (index >= 0) {
2675 desc = mSuspendedEffects.valueAt(index);
2676 } else {
2677 desc = new SuspendedEffectDesc();
2678 desc->mType = *type;
2679 mSuspendedEffects.add(type->timeLow, desc);
2680 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
2681 }
Eric Laurentd8365c52017-07-16 15:27:05 -07002682
Eric Laurentca7cc822012-11-19 14:55:58 -08002683 if (desc->mRefCount++ == 0) {
2684 sp<EffectModule> effect = getEffectIfEnabled(type);
2685 if (effect != 0) {
2686 desc->mEffect = effect;
2687 effect->setSuspended(true);
Eric Laurent6b446ce2019-12-13 10:56:31 -08002688 effect->setEnabled(false, false /*fromHandle*/);
Eric Laurentca7cc822012-11-19 14:55:58 -08002689 }
2690 }
2691 } else {
2692 if (index < 0) {
2693 return;
2694 }
2695 desc = mSuspendedEffects.valueAt(index);
2696 if (desc->mRefCount <= 0) {
2697 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentd8365c52017-07-16 15:27:05 -07002698 desc->mRefCount = 0;
2699 return;
Eric Laurentca7cc822012-11-19 14:55:58 -08002700 }
2701 if (--desc->mRefCount == 0) {
2702 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
2703 if (desc->mEffect != 0) {
2704 sp<EffectModule> effect = desc->mEffect.promote();
2705 if (effect != 0) {
2706 effect->setSuspended(false);
2707 effect->lock();
2708 EffectHandle *handle = effect->controlHandle_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002709 if (handle != NULL && !handle->disconnected()) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002710 effect->setEnabled_l(handle->enabled());
2711 }
2712 effect->unlock();
2713 }
2714 desc->mEffect.clear();
2715 }
2716 mSuspendedEffects.removeItemsAt(index);
2717 }
2718 }
2719}
2720
2721// must be called with ThreadBase::mLock held
2722void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
2723{
2724 sp<SuspendedEffectDesc> desc;
2725
2726 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
2727 if (suspend) {
2728 if (index >= 0) {
2729 desc = mSuspendedEffects.valueAt(index);
2730 } else {
2731 desc = new SuspendedEffectDesc();
2732 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
2733 ALOGV("setEffectSuspendedAll_l() add entry for 0");
2734 }
2735 if (desc->mRefCount++ == 0) {
2736 Vector< sp<EffectModule> > effects;
2737 getSuspendEligibleEffects(effects);
2738 for (size_t i = 0; i < effects.size(); i++) {
2739 setEffectSuspended_l(&effects[i]->desc().type, true);
2740 }
2741 }
2742 } else {
2743 if (index < 0) {
2744 return;
2745 }
2746 desc = mSuspendedEffects.valueAt(index);
2747 if (desc->mRefCount <= 0) {
2748 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
2749 desc->mRefCount = 1;
2750 }
2751 if (--desc->mRefCount == 0) {
2752 Vector<const effect_uuid_t *> types;
2753 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
2754 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
2755 continue;
2756 }
2757 types.add(&mSuspendedEffects.valueAt(i)->mType);
2758 }
2759 for (size_t i = 0; i < types.size(); i++) {
2760 setEffectSuspended_l(types[i], false);
2761 }
2762 ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
2763 mSuspendedEffects.keyAt(index));
2764 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
2765 }
2766 }
2767}
2768
2769
2770// The volume effect is used for automated tests only
2771#ifndef OPENSL_ES_H_
2772static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
2773 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
2774const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
2775#endif //OPENSL_ES_H_
2776
Eric Laurentd8365c52017-07-16 15:27:05 -07002777/* static */
2778bool AudioFlinger::EffectChain::isEffectEligibleForBtNrecSuspend(const effect_uuid_t *type)
2779{
2780 // Only NS and AEC are suspended when BtNRec is off
2781 if ((memcmp(type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) ||
2782 (memcmp(type, FX_IID_NS, sizeof(effect_uuid_t)) == 0)) {
2783 return true;
2784 }
2785 return false;
2786}
2787
Eric Laurentca7cc822012-11-19 14:55:58 -08002788bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
2789{
2790 // auxiliary effects and visualizer are never suspended on output mix
2791 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
2792 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
2793 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
Ricardo Garciac2a3a822019-07-17 14:29:12 -07002794 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0) ||
2795 (memcmp(&desc.type, SL_IID_DYNAMICSPROCESSING, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002796 return false;
2797 }
2798 return true;
2799}
2800
2801void AudioFlinger::EffectChain::getSuspendEligibleEffects(
2802 Vector< sp<AudioFlinger::EffectModule> > &effects)
2803{
2804 effects.clear();
2805 for (size_t i = 0; i < mEffects.size(); i++) {
2806 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
2807 effects.add(mEffects[i]);
2808 }
2809 }
2810}
2811
2812sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
2813 const effect_uuid_t *type)
2814{
2815 sp<EffectModule> effect = getEffectFromType_l(type);
2816 return effect != 0 && effect->isEnabled() ? effect : 0;
2817}
2818
2819void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
2820 bool enabled)
2821{
2822 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
2823 if (enabled) {
2824 if (index < 0) {
2825 // if the effect is not suspend check if all effects are suspended
2826 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
2827 if (index < 0) {
2828 return;
2829 }
2830 if (!isEffectEligibleForSuspend(effect->desc())) {
2831 return;
2832 }
2833 setEffectSuspended_l(&effect->desc().type, enabled);
2834 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
2835 if (index < 0) {
2836 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
2837 return;
2838 }
2839 }
2840 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
2841 effect->desc().type.timeLow);
2842 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
Eric Laurentd8365c52017-07-16 15:27:05 -07002843 // if effect is requested to suspended but was not yet enabled, suspend it now.
Eric Laurentca7cc822012-11-19 14:55:58 -08002844 if (desc->mEffect == 0) {
2845 desc->mEffect = effect;
Eric Laurent6b446ce2019-12-13 10:56:31 -08002846 effect->setEnabled(false, false /*fromHandle*/);
Eric Laurentca7cc822012-11-19 14:55:58 -08002847 effect->setSuspended(true);
2848 }
2849 } else {
2850 if (index < 0) {
2851 return;
2852 }
2853 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
2854 effect->desc().type.timeLow);
2855 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
2856 desc->mEffect.clear();
2857 effect->setSuspended(false);
2858 }
2859}
2860
Eric Laurent5baf2af2013-09-12 17:37:00 -07002861bool AudioFlinger::EffectChain::isNonOffloadableEnabled()
Eric Laurent813e2a72013-08-31 12:59:48 -07002862{
2863 Mutex::Autolock _l(mLock);
Shingo Kitajima1f8df9a2018-05-29 11:35:06 +09002864 return isNonOffloadableEnabled_l();
2865}
2866
2867bool AudioFlinger::EffectChain::isNonOffloadableEnabled_l()
2868{
Eric Laurent813e2a72013-08-31 12:59:48 -07002869 size_t size = mEffects.size();
2870 for (size_t i = 0; i < size; i++) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002871 if (mEffects[i]->isEnabled() && !mEffects[i]->isOffloadable()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002872 return true;
2873 }
2874 }
2875 return false;
2876}
2877
Eric Laurentaaa44472014-09-12 17:41:50 -07002878void AudioFlinger::EffectChain::setThread(const sp<ThreadBase>& thread)
2879{
2880 Mutex::Autolock _l(mLock);
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002881 mEffectCallback->setThread(thread);
Eric Laurentaaa44472014-09-12 17:41:50 -07002882}
2883
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002884void AudioFlinger::EffectChain::checkOutputFlagCompatibility(audio_output_flags_t *flags) const
2885{
2886 if ((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0 && !isRawCompatible()) {
2887 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
2888 }
2889 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0 && !isFastCompatible()) {
2890 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
2891 }
jiabinc658e452022-10-21 20:52:21 +00002892 if ((*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != 0 && !isBitPerfectCompatible()) {
2893 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2894 }
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002895}
2896
2897void AudioFlinger::EffectChain::checkInputFlagCompatibility(audio_input_flags_t *flags) const
2898{
2899 if ((*flags & AUDIO_INPUT_FLAG_RAW) != 0 && !isRawCompatible()) {
2900 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
2901 }
2902 if ((*flags & AUDIO_INPUT_FLAG_FAST) != 0 && !isFastCompatible()) {
2903 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
2904 }
2905}
2906
2907bool AudioFlinger::EffectChain::isRawCompatible() const
Eric Laurent4c415062016-06-17 16:14:16 -07002908{
2909 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002910 for (const auto &effect : mEffects) {
2911 if (effect->isProcessImplemented()) {
2912 return false;
Eric Laurent4c415062016-06-17 16:14:16 -07002913 }
2914 }
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002915 // Allow effects without processing.
2916 return true;
2917}
2918
2919bool AudioFlinger::EffectChain::isFastCompatible() const
2920{
2921 Mutex::Autolock _l(mLock);
2922 for (const auto &effect : mEffects) {
2923 if (effect->isProcessImplemented()
2924 && effect->isImplementationSoftware()) {
2925 return false;
2926 }
2927 }
2928 // Allow effects without processing or hw accelerated effects.
2929 return true;
Eric Laurent4c415062016-06-17 16:14:16 -07002930}
2931
jiabinc658e452022-10-21 20:52:21 +00002932bool AudioFlinger::EffectChain::isBitPerfectCompatible() const {
2933 Mutex::Autolock _l(mLock);
2934 for (const auto &effect : mEffects) {
2935 if (effect->isProcessImplemented()
2936 && effect->isImplementationSoftware()) {
2937 return false;
2938 }
2939 }
2940 // Allow effects without processing or hw accelerated effects.
2941 return true;
2942}
2943
Eric Laurent4c415062016-06-17 16:14:16 -07002944// isCompatibleWithThread_l() must be called with thread->mLock held
2945bool AudioFlinger::EffectChain::isCompatibleWithThread_l(const sp<ThreadBase>& thread) const
2946{
2947 Mutex::Autolock _l(mLock);
2948 for (size_t i = 0; i < mEffects.size(); i++) {
2949 if (thread->checkEffectCompatibility_l(&(mEffects[i]->desc()), mSessionId) != NO_ERROR) {
2950 return false;
2951 }
2952 }
2953 return true;
2954}
2955
Eric Laurent6b446ce2019-12-13 10:56:31 -08002956// EffectCallbackInterface implementation
2957status_t AudioFlinger::EffectChain::EffectCallback::createEffectHal(
2958 const effect_uuid_t *pEffectUuid, int32_t sessionId, int32_t deviceId,
2959 sp<EffectHalInterface> *effect) {
2960 status_t status = NO_INIT;
Andy Hungba8e52b2023-05-11 14:33:03 -07002961 const sp<EffectsFactoryHalInterface> effectsFactory =
2962 EffectConfiguration::getEffectsFactoryHal();
Eric Laurent6b446ce2019-12-13 10:56:31 -08002963 if (effectsFactory != 0) {
2964 status = effectsFactory->createEffect(pEffectUuid, sessionId, io(), deviceId, effect);
2965 }
2966 return status;
2967}
2968
2969bool AudioFlinger::EffectChain::EffectCallback::updateOrphanEffectChains(
Eric Laurent41709552019-12-16 19:34:05 -08002970 const sp<AudioFlinger::EffectBase>& effect) {
Eric Laurent41709552019-12-16 19:34:05 -08002971 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
Andy Hung6626a012021-01-12 13:38:00 -08002972 return mAudioFlinger.updateOrphanEffectChains(effect->asEffectModule());
Eric Laurent6b446ce2019-12-13 10:56:31 -08002973}
2974
2975status_t AudioFlinger::EffectChain::EffectCallback::allocateHalBuffer(
2976 size_t size, sp<EffectBufferHalInterface>* buffer) {
Andy Hung6626a012021-01-12 13:38:00 -08002977 return mAudioFlinger.mEffectsFactoryHal->allocateBuffer(size, buffer);
Eric Laurent6b446ce2019-12-13 10:56:31 -08002978}
2979
2980status_t AudioFlinger::EffectChain::EffectCallback::addEffectToHal(
Andy Hung920f6572022-10-06 12:09:49 -07002981 const sp<EffectHalInterface>& effect) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08002982 status_t result = NO_INIT;
Andy Hung328d6772021-01-12 12:32:21 -08002983 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08002984 if (t == nullptr) {
2985 return result;
2986 }
2987 sp <StreamHalInterface> st = t->stream();
2988 if (st == nullptr) {
2989 return result;
2990 }
2991 result = st->addEffect(effect);
2992 ALOGE_IF(result != OK, "Error when adding effect: %d", result);
2993 return result;
2994}
2995
2996status_t AudioFlinger::EffectChain::EffectCallback::removeEffectFromHal(
Andy Hung920f6572022-10-06 12:09:49 -07002997 const sp<EffectHalInterface>& effect) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08002998 status_t result = NO_INIT;
Andy Hung328d6772021-01-12 12:32:21 -08002999 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003000 if (t == nullptr) {
3001 return result;
3002 }
3003 sp <StreamHalInterface> st = t->stream();
3004 if (st == nullptr) {
3005 return result;
3006 }
3007 result = st->removeEffect(effect);
3008 ALOGE_IF(result != OK, "Error when removing effect: %d", result);
3009 return result;
3010}
3011
3012audio_io_handle_t AudioFlinger::EffectChain::EffectCallback::io() const {
Andy Hung328d6772021-01-12 12:32:21 -08003013 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003014 if (t == nullptr) {
3015 return AUDIO_IO_HANDLE_NONE;
3016 }
3017 return t->id();
3018}
3019
3020bool AudioFlinger::EffectChain::EffectCallback::isOutput() const {
Andy Hung328d6772021-01-12 12:32:21 -08003021 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003022 if (t == nullptr) {
3023 return true;
3024 }
3025 return t->isOutput();
3026}
3027
3028bool AudioFlinger::EffectChain::EffectCallback::isOffload() const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003029 return mThreadType == ThreadBase::OFFLOAD;
Eric Laurent6b446ce2019-12-13 10:56:31 -08003030}
3031
3032bool AudioFlinger::EffectChain::EffectCallback::isOffloadOrDirect() const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003033 return mThreadType == ThreadBase::OFFLOAD || mThreadType == ThreadBase::DIRECT;
Eric Laurent6b446ce2019-12-13 10:56:31 -08003034}
3035
3036bool AudioFlinger::EffectChain::EffectCallback::isOffloadOrMmap() const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003037 switch (mThreadType) {
3038 case ThreadBase::OFFLOAD:
3039 case ThreadBase::MMAP_PLAYBACK:
3040 case ThreadBase::MMAP_CAPTURE:
3041 return true;
3042 default:
Eric Laurent6b446ce2019-12-13 10:56:31 -08003043 return false;
3044 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003045}
3046
3047bool AudioFlinger::EffectChain::EffectCallback::isSpatializer() const {
3048 return mThreadType == ThreadBase::SPATIALIZER;
Eric Laurent6b446ce2019-12-13 10:56:31 -08003049}
3050
3051uint32_t AudioFlinger::EffectChain::EffectCallback::sampleRate() const {
Andy Hung328d6772021-01-12 12:32:21 -08003052 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003053 if (t == nullptr) {
3054 return 0;
3055 }
3056 return t->sampleRate();
3057}
3058
Eric Laurentf1f22e72021-07-13 14:04:14 +02003059audio_channel_mask_t AudioFlinger::EffectChain::EffectCallback::inChannelMask(int id) const {
3060 sp<ThreadBase> t = thread().promote();
3061 if (t == nullptr) {
3062 return AUDIO_CHANNEL_NONE;
3063 }
3064 sp<EffectChain> c = chain().promote();
3065 if (c == nullptr) {
3066 return AUDIO_CHANNEL_NONE;
3067 }
3068
Eric Laurentb62d0362021-10-26 17:40:18 +02003069 if (mThreadType == ThreadBase::SPATIALIZER) {
3070 if (c->sessionId() == AUDIO_SESSION_OUTPUT_STAGE) {
3071 if (c->isFirstEffect(id)) {
3072 return t->mixerChannelMask();
3073 } else {
3074 return t->channelMask();
3075 }
3076 } else if (!audio_is_global_session(c->sessionId())) {
3077 if ((t->hasAudioSession_l(c->sessionId()) & ThreadBase::SPATIALIZED_SESSION) != 0) {
3078 return t->mixerChannelMask();
3079 } else {
3080 return t->channelMask();
3081 }
3082 } else {
3083 return t->channelMask();
3084 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003085 } else {
3086 return t->channelMask();
3087 }
3088}
3089
3090uint32_t AudioFlinger::EffectChain::EffectCallback::inChannelCount(int id) const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003091 return audio_channel_count_from_out_mask(inChannelMask(id));
Eric Laurentf1f22e72021-07-13 14:04:14 +02003092}
3093
3094audio_channel_mask_t AudioFlinger::EffectChain::EffectCallback::outChannelMask() const {
Andy Hung328d6772021-01-12 12:32:21 -08003095 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003096 if (t == nullptr) {
3097 return AUDIO_CHANNEL_NONE;
3098 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003099 sp<EffectChain> c = chain().promote();
3100 if (c == nullptr) {
3101 return AUDIO_CHANNEL_NONE;
3102 }
3103
3104 if (mThreadType == ThreadBase::SPATIALIZER) {
3105 if (!audio_is_global_session(c->sessionId())) {
3106 if ((t->hasAudioSession_l(c->sessionId()) & ThreadBase::SPATIALIZED_SESSION) != 0) {
3107 return t->mixerChannelMask();
3108 } else {
3109 return t->channelMask();
3110 }
3111 } else {
3112 return t->channelMask();
3113 }
3114 } else {
3115 return t->channelMask();
3116 }
Eric Laurent6b446ce2019-12-13 10:56:31 -08003117}
3118
Eric Laurentf1f22e72021-07-13 14:04:14 +02003119uint32_t AudioFlinger::EffectChain::EffectCallback::outChannelCount() const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003120 return audio_channel_count_from_out_mask(outChannelMask());
Eric Laurent6b446ce2019-12-13 10:56:31 -08003121}
3122
jiabineb3bda02020-06-30 14:07:03 -07003123audio_channel_mask_t AudioFlinger::EffectChain::EffectCallback::hapticChannelMask() const {
Andy Hung328d6772021-01-12 12:32:21 -08003124 sp<ThreadBase> t = thread().promote();
jiabineb3bda02020-06-30 14:07:03 -07003125 if (t == nullptr) {
3126 return AUDIO_CHANNEL_NONE;
3127 }
3128 return t->hapticChannelMask();
3129}
3130
Eric Laurent6b446ce2019-12-13 10:56:31 -08003131size_t AudioFlinger::EffectChain::EffectCallback::frameCount() const {
Andy Hung328d6772021-01-12 12:32:21 -08003132 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003133 if (t == nullptr) {
3134 return 0;
3135 }
3136 return t->frameCount();
3137}
3138
Andy Hung920f6572022-10-06 12:09:49 -07003139uint32_t AudioFlinger::EffectChain::EffectCallback::latency() const
3140NO_THREAD_SAFETY_ANALYSIS // latency_l() access
3141{
Andy Hung328d6772021-01-12 12:32:21 -08003142 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003143 if (t == nullptr) {
3144 return 0;
3145 }
Andy Hung920f6572022-10-06 12:09:49 -07003146 // TODO(b/275956781) - this requires the thread lock.
Eric Laurent6b446ce2019-12-13 10:56:31 -08003147 return t->latency_l();
3148}
3149
Andy Hung920f6572022-10-06 12:09:49 -07003150void AudioFlinger::EffectChain::EffectCallback::setVolumeForOutput(float left, float right) const
3151NO_THREAD_SAFETY_ANALYSIS // setVolumeForOutput_l() access
3152{
Andy Hung328d6772021-01-12 12:32:21 -08003153 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003154 if (t == nullptr) {
3155 return;
3156 }
3157 t->setVolumeForOutput_l(left, right);
3158}
3159
3160void AudioFlinger::EffectChain::EffectCallback::checkSuspendOnEffectEnabled(
Eric Laurent41709552019-12-16 19:34:05 -08003161 const sp<EffectBase>& effect, bool enabled, bool threadLocked) {
Andy Hung328d6772021-01-12 12:32:21 -08003162 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003163 if (t == nullptr) {
3164 return;
3165 }
3166 t->checkSuspendOnEffectEnabled(enabled, effect->sessionId(), threadLocked);
3167
Andy Hung328d6772021-01-12 12:32:21 -08003168 sp<EffectChain> c = chain().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003169 if (c == nullptr) {
3170 return;
3171 }
Eric Laurent41709552019-12-16 19:34:05 -08003172 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
3173 c->checkSuspendOnEffectEnabled(effect->asEffectModule(), enabled);
Eric Laurent6b446ce2019-12-13 10:56:31 -08003174}
3175
Eric Laurent41709552019-12-16 19:34:05 -08003176void AudioFlinger::EffectChain::EffectCallback::onEffectEnable(const sp<EffectBase>& effect) {
Andy Hung328d6772021-01-12 12:32:21 -08003177 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003178 if (t == nullptr) {
3179 return;
3180 }
Eric Laurent41709552019-12-16 19:34:05 -08003181 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
3182 t->onEffectEnable(effect->asEffectModule());
Eric Laurent6b446ce2019-12-13 10:56:31 -08003183}
3184
Eric Laurent41709552019-12-16 19:34:05 -08003185void AudioFlinger::EffectChain::EffectCallback::onEffectDisable(const sp<EffectBase>& effect) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003186 checkSuspendOnEffectEnabled(effect, false, false /*threadLocked*/);
3187
Andy Hung328d6772021-01-12 12:32:21 -08003188 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003189 if (t == nullptr) {
3190 return;
3191 }
3192 t->onEffectDisable();
3193}
3194
3195bool AudioFlinger::EffectChain::EffectCallback::disconnectEffectHandle(EffectHandle *handle,
3196 bool unpinIfLast) {
Andy Hung328d6772021-01-12 12:32:21 -08003197 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003198 if (t == nullptr) {
3199 return false;
3200 }
3201 t->disconnectEffectHandle(handle, unpinIfLast);
3202 return true;
3203}
3204
3205void AudioFlinger::EffectChain::EffectCallback::resetVolume() {
Andy Hung328d6772021-01-12 12:32:21 -08003206 sp<EffectChain> c = chain().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003207 if (c == nullptr) {
3208 return;
3209 }
3210 c->resetVolume_l();
3211
3212}
3213
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003214product_strategy_t AudioFlinger::EffectChain::EffectCallback::strategy() const {
Andy Hung328d6772021-01-12 12:32:21 -08003215 sp<EffectChain> c = chain().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003216 if (c == nullptr) {
3217 return PRODUCT_STRATEGY_NONE;
3218 }
3219 return c->strategy();
3220}
3221
3222int32_t AudioFlinger::EffectChain::EffectCallback::activeTrackCnt() const {
Andy Hung328d6772021-01-12 12:32:21 -08003223 sp<EffectChain> c = chain().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003224 if (c == nullptr) {
3225 return 0;
3226 }
3227 return c->activeTrackCnt();
3228}
3229
Eric Laurentb82e6b72019-11-22 17:25:04 -08003230
3231#undef LOG_TAG
3232#define LOG_TAG "AudioFlinger::DeviceEffectProxy"
3233
3234status_t AudioFlinger::DeviceEffectProxy::setEnabled(bool enabled, bool fromHandle)
3235{
3236 status_t status = EffectBase::setEnabled(enabled, fromHandle);
3237 Mutex::Autolock _l(mProxyLock);
3238 if (status == NO_ERROR) {
3239 for (auto& handle : mEffectHandles) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003240 Status bs;
Eric Laurentb82e6b72019-11-22 17:25:04 -08003241 if (enabled) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003242 bs = handle.second->enable(&status);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003243 } else {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003244 bs = handle.second->disable(&status);
3245 }
3246 if (!bs.isOk()) {
Andy Hung1131b6e2020-12-08 20:47:45 -08003247 status = statusTFromBinderStatus(bs);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003248 }
3249 }
3250 }
3251 ALOGV("%s enable %d status %d", __func__, enabled, status);
3252 return status;
3253}
3254
3255status_t AudioFlinger::DeviceEffectProxy::init(
3256 const std::map <audio_patch_handle_t, PatchPanel::Patch>& patches) {
3257//For all audio patches
3258//If src or sink device match
3259//If the effect is HW accelerated
3260// if no corresponding effect module
3261// Create EffectModule: mHalEffect
3262//Create and attach EffectHandle
3263//If the effect is not HW accelerated and the patch sink or src is a mixer port
3264// Create Effect on patch input or output thread on session -1
3265//Add EffectHandle to EffectHandle map of Effect Proxy:
3266 ALOGV("%s device type %d address %s", __func__, mDevice.mType, mDevice.getAddress());
3267 status_t status = NO_ERROR;
3268 for (auto &patch : patches) {
3269 status = onCreatePatch(patch.first, patch.second);
3270 ALOGV("%s onCreatePatch status %d", __func__, status);
3271 if (status == BAD_VALUE) {
3272 return status;
3273 }
3274 }
3275 return status;
3276}
3277
3278status_t AudioFlinger::DeviceEffectProxy::onCreatePatch(
3279 audio_patch_handle_t patchHandle, const AudioFlinger::PatchPanel::Patch& patch) {
3280 status_t status = NAME_NOT_FOUND;
3281 sp<EffectHandle> handle;
3282 // only consider source[0] as this is the only "true" source of a patch
3283 status = checkPort(patch, &patch.mAudioPatch.sources[0], &handle);
3284 ALOGV("%s source checkPort status %d", __func__, status);
3285 for (uint32_t i = 0; i < patch.mAudioPatch.num_sinks && status == NAME_NOT_FOUND; i++) {
3286 status = checkPort(patch, &patch.mAudioPatch.sinks[i], &handle);
3287 ALOGV("%s sink %d checkPort status %d", __func__, i, status);
3288 }
3289 if (status == NO_ERROR || status == ALREADY_EXISTS) {
3290 Mutex::Autolock _l(mProxyLock);
3291 mEffectHandles.emplace(patchHandle, handle);
3292 }
3293 ALOGW_IF(status == BAD_VALUE,
3294 "%s cannot attach effect %s on patch %d", __func__, mDescriptor.name, patchHandle);
3295
3296 return status;
3297}
3298
3299status_t AudioFlinger::DeviceEffectProxy::checkPort(const PatchPanel::Patch& patch,
3300 const struct audio_port_config *port, sp <EffectHandle> *handle) {
3301
3302 ALOGV("%s type %d device type %d address %s device ID %d patch.isSoftware() %d",
3303 __func__, port->type, port->ext.device.type,
3304 port->ext.device.address, port->id, patch.isSoftware());
Shunkai Yaob009ad52023-05-05 22:43:24 +00003305 if (port->type != AUDIO_PORT_TYPE_DEVICE || port->ext.device.type != mDevice.mType ||
3306 port->ext.device.address != mDevice.address()) {
3307 return NAME_NOT_FOUND;
3308 }
3309 if (((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) &&
3310 (audio_port_config_has_input_direction(port))) {
3311 ALOGI("%s don't create postprocessing effect on record port", __func__);
3312 return NAME_NOT_FOUND;
3313 }
3314 if (((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) &&
3315 (!audio_port_config_has_input_direction(port))) {
3316 ALOGI("%s don't create preprocessing effect on playback port", __func__);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003317 return NAME_NOT_FOUND;
3318 }
3319 status_t status = NAME_NOT_FOUND;
3320
3321 if (mDescriptor.flags & EFFECT_FLAG_HW_ACC_TUNNEL) {
3322 Mutex::Autolock _l(mProxyLock);
3323 mDevicePort = *port;
3324 mHalEffect = new EffectModule(mMyCallback,
3325 const_cast<effect_descriptor_t *>(&mDescriptor),
3326 mMyCallback->newEffectId(), AUDIO_SESSION_DEVICE,
3327 false /* pinned */, port->id);
3328 if (audio_is_input_device(mDevice.mType)) {
3329 mHalEffect->setInputDevice(mDevice);
3330 } else {
3331 mHalEffect->setDevices({mDevice});
3332 }
Eric Laurent76c89f32021-12-03 17:13:23 +01003333 mHalEffect->configure();
3334
Eric Laurentde8caf42021-08-11 17:19:25 +02003335 *handle = new EffectHandle(mHalEffect, nullptr, nullptr, 0 /*priority*/,
3336 mNotifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003337 status = (*handle)->initCheck();
3338 if (status == OK) {
3339 status = mHalEffect->addHandle((*handle).get());
3340 } else {
3341 mHalEffect.clear();
3342 mDevicePort.id = AUDIO_PORT_HANDLE_NONE;
3343 }
3344 } else if (patch.isSoftware() || patch.thread().promote() != nullptr) {
3345 sp <ThreadBase> thread;
3346 if (audio_port_config_has_input_direction(port)) {
3347 if (patch.isSoftware()) {
3348 thread = patch.mRecord.thread();
3349 } else {
3350 thread = patch.thread().promote();
3351 }
3352 } else {
3353 if (patch.isSoftware()) {
3354 thread = patch.mPlayback.thread();
3355 } else {
3356 thread = patch.thread().promote();
3357 }
3358 }
3359 int enabled;
3360 *handle = thread->createEffect_l(nullptr, nullptr, 0, AUDIO_SESSION_DEVICE,
3361 const_cast<effect_descriptor_t *>(&mDescriptor),
Eric Laurentde8caf42021-08-11 17:19:25 +02003362 &enabled, &status, false, false /*probe*/,
3363 mNotifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003364 ALOGV("%s thread->createEffect_l status %d", __func__, status);
3365 } else {
3366 status = BAD_VALUE;
3367 }
Shunkai Yaob009ad52023-05-05 22:43:24 +00003368
Eric Laurentb82e6b72019-11-22 17:25:04 -08003369 if (status == NO_ERROR || status == ALREADY_EXISTS) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003370 Status bs;
Eric Laurentb82e6b72019-11-22 17:25:04 -08003371 if (isEnabled()) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003372 bs = (*handle)->enable(&status);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003373 } else {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003374 bs = (*handle)->disable(&status);
3375 }
3376 if (!bs.isOk()) {
Andy Hung1131b6e2020-12-08 20:47:45 -08003377 status = statusTFromBinderStatus(bs);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003378 }
3379 }
3380 return status;
3381}
3382
3383void AudioFlinger::DeviceEffectProxy::onReleasePatch(audio_patch_handle_t patchHandle) {
Eric Laurent76c89f32021-12-03 17:13:23 +01003384 sp<EffectHandle> effect;
3385 {
3386 Mutex::Autolock _l(mProxyLock);
3387 if (mEffectHandles.find(patchHandle) != mEffectHandles.end()) {
3388 effect = mEffectHandles.at(patchHandle);
3389 mEffectHandles.erase(patchHandle);
3390 }
3391 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08003392}
3393
3394
3395size_t AudioFlinger::DeviceEffectProxy::removeEffect(const sp<EffectModule>& effect)
3396{
3397 Mutex::Autolock _l(mProxyLock);
3398 if (effect == mHalEffect) {
Eric Laurent76c89f32021-12-03 17:13:23 +01003399 mHalEffect->release_l();
Eric Laurentb82e6b72019-11-22 17:25:04 -08003400 mHalEffect.clear();
3401 mDevicePort.id = AUDIO_PORT_HANDLE_NONE;
3402 }
3403 return mHalEffect == nullptr ? 0 : 1;
3404}
3405
3406status_t AudioFlinger::DeviceEffectProxy::addEffectToHal(
Andy Hung920f6572022-10-06 12:09:49 -07003407 const sp<EffectHalInterface>& effect) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003408 if (mHalEffect == nullptr) {
3409 return NO_INIT;
3410 }
Mikhail Naganovd2c7f852023-06-14 18:00:13 -07003411 return mManagerCallback->addEffectToHal(&mDevicePort, effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003412}
3413
3414status_t AudioFlinger::DeviceEffectProxy::removeEffectFromHal(
Andy Hung920f6572022-10-06 12:09:49 -07003415 const sp<EffectHalInterface>& effect) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003416 if (mHalEffect == nullptr) {
3417 return NO_INIT;
3418 }
Mikhail Naganovd2c7f852023-06-14 18:00:13 -07003419 return mManagerCallback->removeEffectFromHal(&mDevicePort, effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003420}
3421
3422bool AudioFlinger::DeviceEffectProxy::isOutput() const {
3423 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE) {
3424 return mDevicePort.role == AUDIO_PORT_ROLE_SINK;
3425 }
3426 return true;
3427}
3428
3429uint32_t AudioFlinger::DeviceEffectProxy::sampleRate() const {
3430 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE &&
3431 (mDevicePort.config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) != 0) {
3432 return mDevicePort.sample_rate;
3433 }
3434 return DEFAULT_OUTPUT_SAMPLE_RATE;
3435}
3436
3437audio_channel_mask_t AudioFlinger::DeviceEffectProxy::channelMask() const {
3438 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE &&
3439 (mDevicePort.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) != 0) {
3440 return mDevicePort.channel_mask;
3441 }
3442 return AUDIO_CHANNEL_OUT_STEREO;
3443}
3444
3445uint32_t AudioFlinger::DeviceEffectProxy::channelCount() const {
3446 if (isOutput()) {
3447 return audio_channel_count_from_out_mask(channelMask());
3448 }
3449 return audio_channel_count_from_in_mask(channelMask());
3450}
3451
Andy Hung920f6572022-10-06 12:09:49 -07003452void AudioFlinger::DeviceEffectProxy::dump(int fd, int spaces)
3453NO_THREAD_SAFETY_ANALYSIS // conditional try lock
3454{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003455 const Vector<String16> args;
3456 EffectBase::dump(fd, args);
3457
3458 const bool locked = dumpTryLock(mProxyLock);
3459 if (!locked) {
3460 String8 result("DeviceEffectProxy may be deadlocked\n");
3461 write(fd, result.string(), result.size());
3462 }
3463
3464 String8 outStr;
3465 if (mHalEffect != nullptr) {
3466 outStr.appendFormat("%*sHAL Effect Id: %d\n", spaces, "", mHalEffect->id());
3467 } else {
3468 outStr.appendFormat("%*sNO HAL Effect\n", spaces, "");
3469 }
3470 write(fd, outStr.string(), outStr.size());
3471 outStr.clear();
3472
3473 outStr.appendFormat("%*sSub Effects:\n", spaces, "");
3474 write(fd, outStr.string(), outStr.size());
3475 outStr.clear();
3476
3477 for (const auto& iter : mEffectHandles) {
3478 outStr.appendFormat("%*sEffect for patch handle %d:\n", spaces + 2, "", iter.first);
3479 write(fd, outStr.string(), outStr.size());
3480 outStr.clear();
3481 sp<EffectBase> effect = iter.second->effect().promote();
3482 if (effect != nullptr) {
3483 effect->dump(fd, args);
3484 }
3485 }
3486
3487 if (locked) {
François Gaffiefcf15bf2023-02-15 11:37:43 +01003488 mProxyLock.unlock();
Eric Laurentb82e6b72019-11-22 17:25:04 -08003489 }
3490}
3491
3492#undef LOG_TAG
3493#define LOG_TAG "AudioFlinger::DeviceEffectProxy::ProxyCallback"
3494
3495int AudioFlinger::DeviceEffectProxy::ProxyCallback::newEffectId() {
3496 return mManagerCallback->newEffectId();
3497}
3498
3499
3500bool AudioFlinger::DeviceEffectProxy::ProxyCallback::disconnectEffectHandle(
3501 EffectHandle *handle, bool unpinIfLast) {
3502 sp<EffectBase> effectBase = handle->effect().promote();
3503 if (effectBase == nullptr) {
3504 return false;
3505 }
3506
3507 sp<EffectModule> effect = effectBase->asEffectModule();
3508 if (effect == nullptr) {
3509 return false;
3510 }
3511
3512 // restore suspended effects if the disconnected handle was enabled and the last one.
3513 bool remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
3514 if (remove) {
3515 sp<DeviceEffectProxy> proxy = mProxy.promote();
3516 if (proxy != nullptr) {
3517 proxy->removeEffect(effect);
3518 }
3519 if (handle->enabled()) {
3520 effectBase->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
3521 }
3522 }
3523 return true;
3524}
3525
3526status_t AudioFlinger::DeviceEffectProxy::ProxyCallback::createEffectHal(
3527 const effect_uuid_t *pEffectUuid, int32_t sessionId, int32_t deviceId,
3528 sp<EffectHalInterface> *effect) {
3529 return mManagerCallback->createEffectHal(pEffectUuid, sessionId, deviceId, effect);
3530}
3531
3532status_t AudioFlinger::DeviceEffectProxy::ProxyCallback::addEffectToHal(
Andy Hung920f6572022-10-06 12:09:49 -07003533 const sp<EffectHalInterface>& effect) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003534 sp<DeviceEffectProxy> proxy = mProxy.promote();
3535 if (proxy == nullptr) {
3536 return NO_INIT;
3537 }
3538 return proxy->addEffectToHal(effect);
3539}
3540
3541status_t AudioFlinger::DeviceEffectProxy::ProxyCallback::removeEffectFromHal(
Andy Hung920f6572022-10-06 12:09:49 -07003542 const sp<EffectHalInterface>& effect) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003543 sp<DeviceEffectProxy> proxy = mProxy.promote();
3544 if (proxy == nullptr) {
3545 return NO_INIT;
3546 }
Eric Laurent76c89f32021-12-03 17:13:23 +01003547 return proxy->removeEffectFromHal(effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003548}
3549
3550bool AudioFlinger::DeviceEffectProxy::ProxyCallback::isOutput() const {
3551 sp<DeviceEffectProxy> proxy = mProxy.promote();
3552 if (proxy == nullptr) {
3553 return true;
3554 }
3555 return proxy->isOutput();
3556}
3557
3558uint32_t AudioFlinger::DeviceEffectProxy::ProxyCallback::sampleRate() const {
3559 sp<DeviceEffectProxy> proxy = mProxy.promote();
3560 if (proxy == nullptr) {
3561 return DEFAULT_OUTPUT_SAMPLE_RATE;
3562 }
3563 return proxy->sampleRate();
3564}
3565
Eric Laurentf1f22e72021-07-13 14:04:14 +02003566audio_channel_mask_t AudioFlinger::DeviceEffectProxy::ProxyCallback::inChannelMask(
3567 int id __unused) const {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003568 sp<DeviceEffectProxy> proxy = mProxy.promote();
3569 if (proxy == nullptr) {
3570 return AUDIO_CHANNEL_OUT_STEREO;
3571 }
3572 return proxy->channelMask();
3573}
3574
Eric Laurentf1f22e72021-07-13 14:04:14 +02003575uint32_t AudioFlinger::DeviceEffectProxy::ProxyCallback::inChannelCount(int id __unused) const {
3576 sp<DeviceEffectProxy> proxy = mProxy.promote();
3577 if (proxy == nullptr) {
3578 return 2;
3579 }
3580 return proxy->channelCount();
3581}
3582
3583audio_channel_mask_t AudioFlinger::DeviceEffectProxy::ProxyCallback::outChannelMask() const {
3584 sp<DeviceEffectProxy> proxy = mProxy.promote();
3585 if (proxy == nullptr) {
3586 return AUDIO_CHANNEL_OUT_STEREO;
3587 }
3588 return proxy->channelMask();
3589}
3590
3591uint32_t AudioFlinger::DeviceEffectProxy::ProxyCallback::outChannelCount() const {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003592 sp<DeviceEffectProxy> proxy = mProxy.promote();
3593 if (proxy == nullptr) {
3594 return 2;
3595 }
3596 return proxy->channelCount();
3597}
3598
Eric Laurent76c89f32021-12-03 17:13:23 +01003599void AudioFlinger::DeviceEffectProxy::ProxyCallback::onEffectEnable(
3600 const sp<EffectBase>& effectBase) {
3601 sp<EffectModule> effect = effectBase->asEffectModule();
3602 if (effect == nullptr) {
3603 return;
3604 }
3605 effect->start();
3606}
3607
3608void AudioFlinger::DeviceEffectProxy::ProxyCallback::onEffectDisable(
3609 const sp<EffectBase>& effectBase) {
3610 sp<EffectModule> effect = effectBase->asEffectModule();
3611 if (effect == nullptr) {
3612 return;
3613 }
3614 effect->stop();
3615}
3616
Glenn Kasten63238ef2015-03-02 15:50:29 -08003617} // namespace android