blob: 822ea93284786fe17055934cca1eb7e1ee6e9c28 [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.
1008 (uint64_t)MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate
1009 / ((uint64_t)1000 * mConfig.outputCfg.buffer.frameCount));
Eric Laurentca7cc822012-11-19 14:55:58 -08001010
Eric Laurentd0ebb532013-04-02 16:41:41 -07001011exit:
Andy Hung6f88dc42017-12-13 16:19:39 -08001012 // TODO: consider clearing mConfig on error.
Eric Laurentd0ebb532013-04-02 16:41:41 -07001013 mStatus = status;
rago94a1ee82017-07-21 15:11:02 -07001014 ALOGVV("configure ended");
Eric Laurentca7cc822012-11-19 14:55:58 -08001015 return status;
1016}
1017
1018status_t AudioFlinger::EffectModule::init()
1019{
1020 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001021 if (mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001022 return NO_INIT;
1023 }
1024 status_t cmdStatus;
1025 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001026 status_t status = mEffectInterface->command(EFFECT_CMD_INIT,
1027 0,
1028 NULL,
1029 &size,
1030 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -08001031 if (status == 0) {
1032 status = cmdStatus;
1033 }
1034 return status;
1035}
1036
Eric Laurent1b928682014-10-02 19:41:47 -07001037void AudioFlinger::EffectModule::addEffectToHal_l()
1038{
1039 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
1040 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurent9f57aa82023-03-17 19:28:37 +01001041 if (mCurrentHalStream == getCallback()->io()) {
David Li6c8ac4b2021-06-22 22:17:52 +08001042 return;
1043 }
1044
Andy Hungfda44002021-06-03 17:23:16 -07001045 (void)getCallback()->addEffectToHal(mEffectInterface);
Eric Laurent9f57aa82023-03-17 19:28:37 +01001046 mCurrentHalStream = getCallback()->io();
Eric Laurent1b928682014-10-02 19:41:47 -07001047 }
1048}
1049
Eric Laurentfa1e1232016-08-02 19:01:49 -07001050// start() must be called with PlaybackThread::mLock or EffectChain::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -08001051status_t AudioFlinger::EffectModule::start()
1052{
Eric Laurentfa1e1232016-08-02 19:01:49 -07001053 status_t status;
1054 {
1055 Mutex::Autolock _l(mLock);
1056 status = start_l();
Eric Laurentfa1e1232016-08-02 19:01:49 -07001057 }
Eric Laurent6b446ce2019-12-13 10:56:31 -08001058 if (status == NO_ERROR) {
Andy Hungfda44002021-06-03 17:23:16 -07001059 getCallback()->resetVolume();
Eric Laurentfa1e1232016-08-02 19:01:49 -07001060 }
1061 return status;
Eric Laurentca7cc822012-11-19 14:55:58 -08001062}
1063
1064status_t AudioFlinger::EffectModule::start_l()
1065{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001066 if (mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001067 return NO_INIT;
1068 }
Eric Laurentd0ebb532013-04-02 16:41:41 -07001069 if (mStatus != NO_ERROR) {
1070 return mStatus;
1071 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001072 status_t cmdStatus;
1073 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001074 status_t status = mEffectInterface->command(EFFECT_CMD_ENABLE,
1075 0,
1076 NULL,
1077 &size,
1078 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -08001079 if (status == 0) {
1080 status = cmdStatus;
1081 }
Eric Laurentcb4b6e92014-10-01 14:26:10 -07001082 if (status == 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07001083 addEffectToHal_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08001084 }
1085 return status;
1086}
1087
1088status_t AudioFlinger::EffectModule::stop()
1089{
1090 Mutex::Autolock _l(mLock);
1091 return stop_l();
1092}
1093
1094status_t AudioFlinger::EffectModule::stop_l()
1095{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001096 if (mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001097 return NO_INIT;
1098 }
Eric Laurentd0ebb532013-04-02 16:41:41 -07001099 if (mStatus != NO_ERROR) {
1100 return mStatus;
1101 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001102 status_t cmdStatus = NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -08001103 uint32_t size = sizeof(status_t);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001104
1105 if (isVolumeControl() && isOffloadedOrDirect()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001106 // We have the EffectChain and EffectModule lock, permit a reentrant call to setVolume:
1107 // resetVolume_l --> setVolume_l --> EffectModule::setVolume
1108 mSetVolumeReentrantTid = gettid();
Andy Hungfda44002021-06-03 17:23:16 -07001109 getCallback()->resetVolume();
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001110 mSetVolumeReentrantTid = INVALID_PID;
1111 }
1112
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001113 status_t status = mEffectInterface->command(EFFECT_CMD_DISABLE,
1114 0,
1115 NULL,
1116 &size,
1117 &cmdStatus);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001118 if (status == NO_ERROR) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001119 status = cmdStatus;
1120 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001121 if (status == NO_ERROR) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001122 status = removeEffectFromHal_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08001123 }
1124 return status;
1125}
1126
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001127// must be called with EffectChain::mLock held
1128void AudioFlinger::EffectModule::release_l()
1129{
1130 if (mEffectInterface != 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001131 removeEffectFromHal_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001132 // release effect engine
Mikhail Naganov022b9952017-01-04 16:36:51 -08001133 mEffectInterface->close();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001134 mEffectInterface.clear();
1135 }
1136}
1137
Eric Laurent6b446ce2019-12-13 10:56:31 -08001138status_t AudioFlinger::EffectModule::removeEffectFromHal_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08001139{
1140 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
1141 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurent9f57aa82023-03-17 19:28:37 +01001142 if (mCurrentHalStream != getCallback()->io()) {
1143 return (mCurrentHalStream == AUDIO_IO_HANDLE_NONE) ? NO_ERROR : INVALID_OPERATION;
David Li6c8ac4b2021-06-22 22:17:52 +08001144 }
Andy Hungfda44002021-06-03 17:23:16 -07001145 getCallback()->removeEffectFromHal(mEffectInterface);
Eric Laurent9f57aa82023-03-17 19:28:37 +01001146 mCurrentHalStream = AUDIO_IO_HANDLE_NONE;
Eric Laurentca7cc822012-11-19 14:55:58 -08001147 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08001148 return NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -08001149}
1150
Andy Hunge4a1d912016-08-17 14:11:13 -07001151// round up delta valid if value and divisor are positive.
1152template <typename T>
1153static T roundUpDelta(const T &value, const T &divisor) {
1154 T remainder = value % divisor;
1155 return remainder == 0 ? 0 : divisor - remainder;
1156}
1157
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001158status_t AudioFlinger::EffectModule::command(int32_t cmdCode,
1159 const std::vector<uint8_t>& cmdData,
1160 int32_t maxReplySize,
1161 std::vector<uint8_t>* reply)
Eric Laurentca7cc822012-11-19 14:55:58 -08001162{
1163 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001164 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface.get());
Eric Laurentca7cc822012-11-19 14:55:58 -08001165
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001166 if (mState == DESTROYED || mEffectInterface == 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001167 return NO_INIT;
1168 }
Eric Laurentd0ebb532013-04-02 16:41:41 -07001169 if (mStatus != NO_ERROR) {
1170 return mStatus;
1171 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001172 if (maxReplySize < 0 || maxReplySize > EFFECT_PARAM_SIZE_MAX) {
1173 return -EINVAL;
1174 }
1175 size_t cmdSize = cmdData.size();
1176 const effect_param_t* param = cmdSize >= sizeof(effect_param_t)
1177 ? reinterpret_cast<const effect_param_t*>(cmdData.data())
1178 : nullptr;
Andy Hung110bc952016-06-20 15:22:52 -07001179 if (cmdCode == EFFECT_CMD_GET_PARAM &&
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001180 (param == nullptr || param->psize > cmdSize - sizeof(effect_param_t))) {
Andy Hung6660f122016-11-04 19:40:53 -07001181 android_errorWriteLog(0x534e4554, "32438594");
Andy Hungb3456642016-11-28 13:50:21 -08001182 android_errorWriteLog(0x534e4554, "33003822");
1183 return -EINVAL;
1184 }
1185 if (cmdCode == EFFECT_CMD_GET_PARAM &&
Andy Hung920f6572022-10-06 12:09:49 -07001186 (maxReplySize < static_cast<signed>(sizeof(effect_param_t)) ||
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001187 param->psize > maxReplySize - sizeof(effect_param_t))) {
Andy Hungb3456642016-11-28 13:50:21 -08001188 android_errorWriteLog(0x534e4554, "29251553");
Andy Hung6660f122016-11-04 19:40:53 -07001189 return -EINVAL;
1190 }
ragoe2759072016-11-22 18:02:48 -08001191 if (cmdCode == EFFECT_CMD_GET_PARAM &&
Andy Hung920f6572022-10-06 12:09:49 -07001192 (static_cast<signed>(sizeof(effect_param_t)) > maxReplySize
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001193 || param->psize > maxReplySize - sizeof(effect_param_t)
1194 || param->vsize > maxReplySize - sizeof(effect_param_t)
1195 - param->psize
1196 || roundUpDelta(param->psize, (uint32_t) sizeof(int)) >
1197 maxReplySize
1198 - sizeof(effect_param_t)
1199 - param->psize
1200 - param->vsize)) {
ragoe2759072016-11-22 18:02:48 -08001201 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: reply size inconsistent");
1202 android_errorWriteLog(0x534e4554, "32705438");
1203 return -EINVAL;
1204 }
Andy Hunge4a1d912016-08-17 14:11:13 -07001205 if ((cmdCode == EFFECT_CMD_SET_PARAM
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001206 || cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED)
1207 && // DEFERRED not generally used
1208 (param == nullptr
1209 || param->psize > cmdSize - sizeof(effect_param_t)
1210 || param->vsize > cmdSize - sizeof(effect_param_t)
1211 - param->psize
1212 || roundUpDelta(param->psize,
1213 (uint32_t) sizeof(int)) >
1214 cmdSize
1215 - sizeof(effect_param_t)
1216 - param->psize
1217 - param->vsize)) {
Andy Hunge4a1d912016-08-17 14:11:13 -07001218 android_errorWriteLog(0x534e4554, "30204301");
1219 return -EINVAL;
1220 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001221 uint32_t replySize = maxReplySize;
1222 reply->resize(replySize);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001223 status_t status = mEffectInterface->command(cmdCode,
1224 cmdSize,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001225 const_cast<uint8_t*>(cmdData.data()),
1226 &replySize,
1227 reply->data());
1228 reply->resize(status == NO_ERROR ? replySize : 0);
Eric Laurentca7cc822012-11-19 14:55:58 -08001229 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001230 for (size_t i = 1; i < mHandles.size(); i++) {
1231 EffectHandle *h = mHandles[i];
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001232 if (h != NULL && !h->disconnected()) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001233 h->commandExecuted(cmdCode, cmdData, *reply);
Eric Laurentca7cc822012-11-19 14:55:58 -08001234 }
1235 }
1236 }
1237 return status;
1238}
1239
Eric Laurentca7cc822012-11-19 14:55:58 -08001240bool AudioFlinger::EffectModule::isProcessEnabled() const
1241{
Eric Laurentd0ebb532013-04-02 16:41:41 -07001242 if (mStatus != NO_ERROR) {
1243 return false;
1244 }
1245
Eric Laurentca7cc822012-11-19 14:55:58 -08001246 switch (mState) {
1247 case RESTART:
1248 case ACTIVE:
1249 case STOPPING:
1250 case STOPPED:
1251 return true;
1252 case IDLE:
1253 case STARTING:
1254 case DESTROYED:
1255 default:
1256 return false;
1257 }
1258}
1259
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001260bool AudioFlinger::EffectModule::isOffloadedOrDirect() const
1261{
Andy Hungfda44002021-06-03 17:23:16 -07001262 return getCallback()->isOffloadOrDirect();
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001263}
1264
1265bool AudioFlinger::EffectModule::isVolumeControlEnabled() const
1266{
1267 return (isVolumeControl() && (isOffloadedOrDirect() ? isEnabled() : isProcessEnabled()));
1268}
1269
Mikhail Naganov022b9952017-01-04 16:36:51 -08001270void AudioFlinger::EffectModule::setInBuffer(const sp<EffectBufferHalInterface>& buffer) {
rago94a1ee82017-07-21 15:11:02 -07001271 ALOGVV("setInBuffer %p",(&buffer));
Andy Hung6f88dc42017-12-13 16:19:39 -08001272
1273 // mConfig.inputCfg.buffer.frameCount may be zero if configure() is not called yet.
Mikhail Naganov022b9952017-01-04 16:36:51 -08001274 if (buffer != 0) {
1275 mConfig.inputCfg.buffer.raw = buffer->audioBuffer()->raw;
1276 buffer->setFrameCount(mConfig.inputCfg.buffer.frameCount);
1277 } else {
1278 mConfig.inputCfg.buffer.raw = NULL;
1279 }
1280 mInBuffer = buffer;
Andy Hungc15aaee2017-11-27 17:02:40 -08001281 mEffectInterface->setInBuffer(buffer);
rago94a1ee82017-07-21 15:11:02 -07001282
Andy Hungbded9c82017-11-30 18:47:35 -08001283 // aux effects do in place conversion to float - we don't allocate mInConversionBuffer.
rago94a1ee82017-07-21 15:11:02 -07001284 // Theoretically insert effects can also do in-place conversions (destroying
1285 // the original buffer) when the output buffer is identical to the input buffer,
1286 // but we don't optimize for it here.
1287 const bool auxType = (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY;
Andy Hung9aad48c2017-11-29 10:29:19 -08001288 const uint32_t inChannelCount =
1289 audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
1290 const bool formatMismatch = !mSupportsFloat || mInChannelCountRequested != inChannelCount;
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001291 if (!auxType && formatMismatch && mInBuffer != nullptr) {
rago94a1ee82017-07-21 15:11:02 -07001292 // we need to translate - create hidl shared buffer and intercept
1293 const size_t inFrameCount = mConfig.inputCfg.buffer.frameCount;
Andy Hung9aad48c2017-11-29 10:29:19 -08001294 // Use FCC_2 in case mInChannelCountRequested is mono and the effect is stereo.
1295 const uint32_t inChannels = std::max((uint32_t)FCC_2, mInChannelCountRequested);
1296 const size_t size = inChannels * inFrameCount * std::max(sizeof(int16_t), sizeof(float));
rago94a1ee82017-07-21 15:11:02 -07001297
1298 ALOGV("%s: setInBuffer updating for inChannels:%d inFrameCount:%zu total size:%zu",
1299 __func__, inChannels, inFrameCount, size);
1300
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001301 if (size > 0 && (mInConversionBuffer == nullptr
Andy Hungbded9c82017-11-30 18:47:35 -08001302 || size > mInConversionBuffer->getSize())) {
1303 mInConversionBuffer.clear();
1304 ALOGV("%s: allocating mInConversionBuffer %zu", __func__, size);
Andy Hungfda44002021-06-03 17:23:16 -07001305 (void)getCallback()->allocateHalBuffer(size, &mInConversionBuffer);
rago94a1ee82017-07-21 15:11:02 -07001306 }
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001307 if (mInConversionBuffer != nullptr) {
Andy Hungbded9c82017-11-30 18:47:35 -08001308 mInConversionBuffer->setFrameCount(inFrameCount);
1309 mEffectInterface->setInBuffer(mInConversionBuffer);
rago94a1ee82017-07-21 15:11:02 -07001310 } else if (size > 0) {
Andy Hungbded9c82017-11-30 18:47:35 -08001311 ALOGE("%s cannot create mInConversionBuffer", __func__);
rago94a1ee82017-07-21 15:11:02 -07001312 }
1313 }
Mikhail Naganov022b9952017-01-04 16:36:51 -08001314}
1315
1316void AudioFlinger::EffectModule::setOutBuffer(const sp<EffectBufferHalInterface>& buffer) {
rago94a1ee82017-07-21 15:11:02 -07001317 ALOGVV("setOutBuffer %p",(&buffer));
Andy Hung6f88dc42017-12-13 16:19:39 -08001318
1319 // mConfig.outputCfg.buffer.frameCount may be zero if configure() is not called yet.
Mikhail Naganov022b9952017-01-04 16:36:51 -08001320 if (buffer != 0) {
1321 mConfig.outputCfg.buffer.raw = buffer->audioBuffer()->raw;
1322 buffer->setFrameCount(mConfig.outputCfg.buffer.frameCount);
1323 } else {
1324 mConfig.outputCfg.buffer.raw = NULL;
1325 }
1326 mOutBuffer = buffer;
Andy Hungc15aaee2017-11-27 17:02:40 -08001327 mEffectInterface->setOutBuffer(buffer);
rago94a1ee82017-07-21 15:11:02 -07001328
Andy Hungbded9c82017-11-30 18:47:35 -08001329 // Note: Any effect that does not accumulate does not need mOutConversionBuffer and
rago94a1ee82017-07-21 15:11:02 -07001330 // can do in-place conversion from int16_t to float. We don't optimize here.
Andy Hung9aad48c2017-11-29 10:29:19 -08001331 const uint32_t outChannelCount =
1332 audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
1333 const bool formatMismatch = !mSupportsFloat || mOutChannelCountRequested != outChannelCount;
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001334 if (formatMismatch && mOutBuffer != nullptr) {
rago94a1ee82017-07-21 15:11:02 -07001335 const size_t outFrameCount = mConfig.outputCfg.buffer.frameCount;
Andy Hung9aad48c2017-11-29 10:29:19 -08001336 // Use FCC_2 in case mOutChannelCountRequested is mono and the effect is stereo.
1337 const uint32_t outChannels = std::max((uint32_t)FCC_2, mOutChannelCountRequested);
1338 const size_t size = outChannels * outFrameCount * std::max(sizeof(int16_t), sizeof(float));
rago94a1ee82017-07-21 15:11:02 -07001339
1340 ALOGV("%s: setOutBuffer updating for outChannels:%d outFrameCount:%zu total size:%zu",
1341 __func__, outChannels, outFrameCount, size);
1342
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001343 if (size > 0 && (mOutConversionBuffer == nullptr
Andy Hungbded9c82017-11-30 18:47:35 -08001344 || size > mOutConversionBuffer->getSize())) {
1345 mOutConversionBuffer.clear();
1346 ALOGV("%s: allocating mOutConversionBuffer %zu", __func__, size);
Andy Hungfda44002021-06-03 17:23:16 -07001347 (void)getCallback()->allocateHalBuffer(size, &mOutConversionBuffer);
rago94a1ee82017-07-21 15:11:02 -07001348 }
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001349 if (mOutConversionBuffer != nullptr) {
Andy Hungbded9c82017-11-30 18:47:35 -08001350 mOutConversionBuffer->setFrameCount(outFrameCount);
1351 mEffectInterface->setOutBuffer(mOutConversionBuffer);
rago94a1ee82017-07-21 15:11:02 -07001352 } else if (size > 0) {
Andy Hungbded9c82017-11-30 18:47:35 -08001353 ALOGE("%s cannot create mOutConversionBuffer", __func__);
rago94a1ee82017-07-21 15:11:02 -07001354 }
1355 }
Mikhail Naganov022b9952017-01-04 16:36:51 -08001356}
1357
Eric Laurentca7cc822012-11-19 14:55:58 -08001358status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
1359{
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001360 AutoLockReentrant _l(mLock, mSetVolumeReentrantTid);
Eric Laurentd0ebb532013-04-02 16:41:41 -07001361 if (mStatus != NO_ERROR) {
1362 return mStatus;
1363 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001364 status_t status = NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -08001365 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
1366 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
1367 if (isProcessEnabled() &&
1368 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
Jasmine Cha934ecfb2019-01-23 18:19:14 +08001369 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND ||
1370 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_MONITOR)) {
jiabin4e246532022-08-23 16:37:30 -07001371 status = setVolumeInternal(left, right, controller);
1372 }
1373 return status;
1374}
1375
1376status_t AudioFlinger::EffectModule::setVolumeInternal(
1377 uint32_t *left, uint32_t *right, bool controller) {
1378 uint32_t volume[2] = {*left, *right};
1379 uint32_t *pVolume = controller ? volume : nullptr;
1380 uint32_t size = sizeof(volume);
1381 status_t status = mEffectInterface->command(EFFECT_CMD_SET_VOLUME,
1382 size,
1383 volume,
1384 &size,
1385 pVolume);
1386 if (controller && status == NO_ERROR && size == sizeof(volume)) {
1387 *left = volume[0];
1388 *right = volume[1];
Eric Laurentca7cc822012-11-19 14:55:58 -08001389 }
1390 return status;
1391}
1392
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001393void AudioFlinger::EffectChain::setVolumeForOutput_l(uint32_t left, uint32_t right)
1394{
Zhou Songd505c642020-02-20 16:35:37 +08001395 // for offload or direct thread, if the effect chain has non-offloadable
1396 // effect and any effect module within the chain has volume control, then
1397 // volume control is delegated to effect, otherwise, set volume to hal.
1398 if (mEffectCallback->isOffloadOrDirect() &&
1399 !(isNonOffloadableEnabled_l() && hasVolumeControlEnabled_l())) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001400 float vol_l = (float)left / (1 << 24);
1401 float vol_r = (float)right / (1 << 24);
Eric Laurent6b446ce2019-12-13 10:56:31 -08001402 mEffectCallback->setVolumeForOutput(vol_l, vol_r);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09001403 }
1404}
1405
jiabin8f278ee2019-11-11 12:16:27 -08001406status_t AudioFlinger::EffectModule::sendSetAudioDevicesCommand(
1407 const AudioDeviceTypeAddrVector &devices, uint32_t cmdCode)
Eric Laurentca7cc822012-11-19 14:55:58 -08001408{
jiabin8f278ee2019-11-11 12:16:27 -08001409 audio_devices_t deviceType = deviceTypesToBitMask(getAudioDeviceTypes(devices));
1410 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001411 return NO_ERROR;
1412 }
1413
1414 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -07001415 if (mStatus != NO_ERROR) {
1416 return mStatus;
1417 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001418 status_t status = NO_ERROR;
Eric Laurent7e1139c2013-06-06 18:29:01 -07001419 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001420 status_t cmdStatus;
1421 uint32_t size = sizeof(status_t);
jiabin8f278ee2019-11-11 12:16:27 -08001422 // FIXME: use audio device types and addresses when the hal interface is ready.
1423 status = mEffectInterface->command(cmdCode,
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001424 sizeof(uint32_t),
jiabin8f278ee2019-11-11 12:16:27 -08001425 &deviceType,
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001426 &size,
1427 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -08001428 }
1429 return status;
1430}
1431
jiabin8f278ee2019-11-11 12:16:27 -08001432status_t AudioFlinger::EffectModule::setDevices(const AudioDeviceTypeAddrVector &devices)
1433{
1434 return sendSetAudioDevicesCommand(devices, EFFECT_CMD_SET_DEVICE);
1435}
1436
1437status_t AudioFlinger::EffectModule::setInputDevice(const AudioDeviceTypeAddr &device)
1438{
1439 return sendSetAudioDevicesCommand({device}, EFFECT_CMD_SET_INPUT_DEVICE);
1440}
1441
Eric Laurentca7cc822012-11-19 14:55:58 -08001442status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
1443{
1444 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -07001445 if (mStatus != NO_ERROR) {
1446 return mStatus;
1447 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001448 status_t status = NO_ERROR;
1449 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
1450 status_t cmdStatus;
1451 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001452 status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_MODE,
1453 sizeof(audio_mode_t),
1454 &mode,
1455 &size,
1456 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -08001457 if (status == NO_ERROR) {
1458 status = cmdStatus;
1459 }
1460 }
1461 return status;
1462}
1463
1464status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
1465{
1466 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -07001467 if (mStatus != NO_ERROR) {
1468 return mStatus;
1469 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001470 status_t status = NO_ERROR;
1471 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
1472 uint32_t size = 0;
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001473 status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_SOURCE,
1474 sizeof(audio_source_t),
1475 &source,
1476 &size,
1477 NULL);
Eric Laurentca7cc822012-11-19 14:55:58 -08001478 }
1479 return status;
1480}
1481
Eric Laurent5baf2af2013-09-12 17:37:00 -07001482status_t AudioFlinger::EffectModule::setOffloaded(bool offloaded, audio_io_handle_t io)
1483{
1484 Mutex::Autolock _l(mLock);
1485 if (mStatus != NO_ERROR) {
1486 return mStatus;
1487 }
1488 status_t status = NO_ERROR;
1489 if ((mDescriptor.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) != 0) {
1490 status_t cmdStatus;
1491 uint32_t size = sizeof(status_t);
1492 effect_offload_param_t cmd;
1493
1494 cmd.isOffload = offloaded;
1495 cmd.ioHandle = io;
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001496 status = mEffectInterface->command(EFFECT_CMD_OFFLOAD,
1497 sizeof(effect_offload_param_t),
1498 &cmd,
1499 &size,
1500 &cmdStatus);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001501 if (status == NO_ERROR) {
1502 status = cmdStatus;
1503 }
1504 mOffloaded = (status == NO_ERROR) ? offloaded : false;
1505 } else {
1506 if (offloaded) {
1507 status = INVALID_OPERATION;
1508 }
1509 mOffloaded = false;
1510 }
1511 ALOGV("setOffloaded() offloaded %d io %d status %d", offloaded, io, status);
1512 return status;
1513}
1514
1515bool AudioFlinger::EffectModule::isOffloaded() const
1516{
1517 Mutex::Autolock _l(mLock);
1518 return mOffloaded;
1519}
1520
jiabineb3bda02020-06-30 14:07:03 -07001521/*static*/
1522bool AudioFlinger::EffectModule::isHapticGenerator(const effect_uuid_t *type) {
1523 return memcmp(type, FX_IID_HAPTICGENERATOR, sizeof(effect_uuid_t)) == 0;
1524}
1525
1526bool AudioFlinger::EffectModule::isHapticGenerator() const {
1527 return isHapticGenerator(&mDescriptor.type);
1528}
1529
Simon Bowden62823412022-10-17 14:52:26 +00001530status_t AudioFlinger::EffectModule::setHapticIntensity(int id, os::HapticScale intensity)
jiabine70bc7f2020-06-30 22:07:55 -07001531{
1532 if (mStatus != NO_ERROR) {
1533 return mStatus;
1534 }
1535 if (!isHapticGenerator()) {
1536 ALOGW("Should not set haptic intensity for effects that are not HapticGenerator");
1537 return INVALID_OPERATION;
1538 }
1539
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001540 std::vector<uint8_t> request(sizeof(effect_param_t) + 3 * sizeof(uint32_t));
1541 effect_param_t *param = (effect_param_t*) request.data();
jiabine70bc7f2020-06-30 22:07:55 -07001542 param->psize = sizeof(int32_t);
1543 param->vsize = sizeof(int32_t) * 2;
1544 *(int32_t*)param->data = HG_PARAM_HAPTIC_INTENSITY;
1545 *((int32_t*)param->data + 1) = id;
Simon Bowden62823412022-10-17 14:52:26 +00001546 *((int32_t*)param->data + 2) = static_cast<int32_t>(intensity);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001547 std::vector<uint8_t> response;
1548 status_t status = command(EFFECT_CMD_SET_PARAM, request, sizeof(int32_t), &response);
jiabine70bc7f2020-06-30 22:07:55 -07001549 if (status == NO_ERROR) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001550 LOG_ALWAYS_FATAL_IF(response.size() != 4);
1551 status = *reinterpret_cast<const status_t*>(response.data());
jiabine70bc7f2020-06-30 22:07:55 -07001552 }
1553 return status;
1554}
1555
Lais Andradebc3f37a2021-07-02 00:13:19 +01001556status_t AudioFlinger::EffectModule::setVibratorInfo(const media::AudioVibratorInfo& vibratorInfo)
jiabin1319f5a2021-03-30 22:21:24 +00001557{
1558 if (mStatus != NO_ERROR) {
1559 return mStatus;
1560 }
1561 if (!isHapticGenerator()) {
1562 ALOGW("Should not set vibrator info for effects that are not HapticGenerator");
1563 return INVALID_OPERATION;
1564 }
1565
Lais Andradebc3f37a2021-07-02 00:13:19 +01001566 const size_t paramCount = 3;
jiabin1319f5a2021-03-30 22:21:24 +00001567 std::vector<uint8_t> request(
Lais Andradebc3f37a2021-07-02 00:13:19 +01001568 sizeof(effect_param_t) + sizeof(int32_t) + paramCount * sizeof(float));
jiabin1319f5a2021-03-30 22:21:24 +00001569 effect_param_t *param = (effect_param_t*) request.data();
1570 param->psize = sizeof(int32_t);
Lais Andradebc3f37a2021-07-02 00:13:19 +01001571 param->vsize = paramCount * sizeof(float);
jiabin1319f5a2021-03-30 22:21:24 +00001572 *(int32_t*)param->data = HG_PARAM_VIBRATOR_INFO;
1573 float* vibratorInfoPtr = reinterpret_cast<float*>(param->data + sizeof(int32_t));
Lais Andradebc3f37a2021-07-02 00:13:19 +01001574 vibratorInfoPtr[0] = vibratorInfo.resonantFrequency;
1575 vibratorInfoPtr[1] = vibratorInfo.qFactor;
1576 vibratorInfoPtr[2] = vibratorInfo.maxAmplitude;
jiabin1319f5a2021-03-30 22:21:24 +00001577 std::vector<uint8_t> response;
1578 status_t status = command(EFFECT_CMD_SET_PARAM, request, sizeof(int32_t), &response);
1579 if (status == NO_ERROR) {
1580 LOG_ALWAYS_FATAL_IF(response.size() != sizeof(status_t));
1581 status = *reinterpret_cast<const status_t*>(response.data());
1582 }
1583 return status;
1584}
1585
Mikhail Naganov8d7da002022-04-19 21:21:23 +00001586status_t AudioFlinger::EffectModule::getConfigs(
1587 audio_config_base_t* inputCfg, audio_config_base_t* outputCfg, bool* isOutput) const {
1588 Mutex::Autolock _l(mLock);
1589 if (mConfig.inputCfg.mask == 0 || mConfig.outputCfg.mask == 0) {
1590 return NO_INIT;
1591 }
1592 inputCfg->sample_rate = mConfig.inputCfg.samplingRate;
1593 inputCfg->channel_mask = static_cast<audio_channel_mask_t>(mConfig.inputCfg.channels);
1594 inputCfg->format = static_cast<audio_format_t>(mConfig.inputCfg.format);
1595 outputCfg->sample_rate = mConfig.outputCfg.samplingRate;
1596 outputCfg->channel_mask = static_cast<audio_channel_mask_t>(mConfig.outputCfg.channels);
1597 outputCfg->format = static_cast<audio_format_t>(mConfig.outputCfg.format);
1598 *isOutput = mIsOutput;
1599 return NO_ERROR;
1600}
1601
Andy Hungbded9c82017-11-30 18:47:35 -08001602static std::string dumpInOutBuffer(bool isInput, const sp<EffectBufferHalInterface> &buffer) {
1603 std::stringstream ss;
1604
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08001605 if (buffer == nullptr) {
Andy Hungbded9c82017-11-30 18:47:35 -08001606 return "nullptr"; // make different than below
1607 } else if (buffer->externalData() != nullptr) {
1608 ss << (isInput ? buffer->externalData() : buffer->audioBuffer()->raw)
1609 << " -> "
1610 << (isInput ? buffer->audioBuffer()->raw : buffer->externalData());
1611 } else {
1612 ss << buffer->audioBuffer()->raw;
1613 }
1614 return ss.str();
1615}
Marco Nelissenb2208842014-02-07 14:00:50 -08001616
Eric Laurent41709552019-12-16 19:34:05 -08001617void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001618NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurentca7cc822012-11-19 14:55:58 -08001619{
Eric Laurent41709552019-12-16 19:34:05 -08001620 EffectBase::dump(fd, args);
1621
Eric Laurentca7cc822012-11-19 14:55:58 -08001622 String8 result;
Eric Laurentca7cc822012-11-19 14:55:58 -08001623 bool locked = AudioFlinger::dumpTryLock(mLock);
Eric Laurentca7cc822012-11-19 14:55:58 -08001624
Eric Laurent41709552019-12-16 19:34:05 -08001625 result.append("\t\tStatus Engine:\n");
1626 result.appendFormat("\t\t%03d %p\n",
1627 mStatus, mEffectInterface.get());
Andy Hung9718d662017-12-22 17:57:39 -08001628
1629 result.appendFormat("\t\t- data: %s\n", mSupportsFloat ? "float" : "int16");
Eric Laurentca7cc822012-11-19 14:55:58 -08001630
1631 result.append("\t\t- Input configuration:\n");
Andy Hung9718d662017-12-22 17:57:39 -08001632 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
1633 result.appendFormat("\t\t\t%p %05zu %05d %08x %6d (%s)\n",
1634 mConfig.inputCfg.buffer.raw,
Eric Laurentca7cc822012-11-19 14:55:58 -08001635 mConfig.inputCfg.buffer.frameCount,
1636 mConfig.inputCfg.samplingRate,
1637 mConfig.inputCfg.channels,
Marco Nelissenb2208842014-02-07 14:00:50 -08001638 mConfig.inputCfg.format,
Andy Hung9718d662017-12-22 17:57:39 -08001639 formatToString((audio_format_t)mConfig.inputCfg.format).c_str());
Eric Laurentca7cc822012-11-19 14:55:58 -08001640
1641 result.append("\t\t- Output configuration:\n");
1642 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
Andy Hung9718d662017-12-22 17:57:39 -08001643 result.appendFormat("\t\t\t%p %05zu %05d %08x %6d (%s)\n",
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001644 mConfig.outputCfg.buffer.raw,
Eric Laurentca7cc822012-11-19 14:55:58 -08001645 mConfig.outputCfg.buffer.frameCount,
1646 mConfig.outputCfg.samplingRate,
1647 mConfig.outputCfg.channels,
Marco Nelissenb2208842014-02-07 14:00:50 -08001648 mConfig.outputCfg.format,
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001649 formatToString((audio_format_t)mConfig.outputCfg.format).c_str());
Eric Laurentca7cc822012-11-19 14:55:58 -08001650
Andy Hungbded9c82017-11-30 18:47:35 -08001651 result.appendFormat("\t\t- HAL buffers:\n"
1652 "\t\t\tIn(%s) InConversion(%s) Out(%s) OutConversion(%s)\n",
1653 dumpInOutBuffer(true /* isInput */, mInBuffer).c_str(),
1654 dumpInOutBuffer(true /* isInput */, mInConversionBuffer).c_str(),
1655 dumpInOutBuffer(false /* isInput */, mOutBuffer).c_str(),
1656 dumpInOutBuffer(false /* isInput */, mOutConversionBuffer).c_str());
rago94a1ee82017-07-21 15:11:02 -07001657
Eric Laurentca7cc822012-11-19 14:55:58 -08001658 write(fd, result.string(), result.length());
1659
Mikhail Naganov4d547672019-02-22 14:19:19 -08001660 if (mEffectInterface != 0) {
1661 dprintf(fd, "\tEffect ID %d HAL dump:\n", mId);
1662 (void)mEffectInterface->dump(fd);
1663 }
1664
Eric Laurentca7cc822012-11-19 14:55:58 -08001665 if (locked) {
1666 mLock.unlock();
1667 }
1668}
1669
1670// ----------------------------------------------------------------------------
1671// EffectHandle implementation
1672// ----------------------------------------------------------------------------
1673
1674#undef LOG_TAG
1675#define LOG_TAG "AudioFlinger::EffectHandle"
1676
Eric Laurent41709552019-12-16 19:34:05 -08001677AudioFlinger::EffectHandle::EffectHandle(const sp<EffectBase>& effect,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001678 const sp<AudioFlinger::Client>& client,
1679 const sp<media::IEffectClient>& effectClient,
Eric Laurentde8caf42021-08-11 17:19:25 +02001680 int32_t priority, bool notifyFramesProcessed)
Eric Laurentca7cc822012-11-19 14:55:58 -08001681 : BnEffect(),
1682 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurentde8caf42021-08-11 17:19:25 +02001683 mPriority(priority), mHasControl(false), mEnabled(false), mDisconnected(false),
1684 mNotifyFramesProcessed(notifyFramesProcessed)
Eric Laurentca7cc822012-11-19 14:55:58 -08001685{
Eric Laurentb82e6b72019-11-22 17:25:04 -08001686 ALOGV("constructor %p client %p", this, client.get());
Andy Hung225aef62022-12-06 16:33:20 -08001687 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
Eric Laurentca7cc822012-11-19 14:55:58 -08001688
1689 if (client == 0) {
1690 return;
1691 }
1692 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
Atneya3c61d882021-09-20 14:52:15 -04001693 mCblkMemory = client->allocator().allocate(mediautils::NamedAllocRequest{
1694 {static_cast<size_t>(EFFECT_PARAM_BUFFER_SIZE + bufOffset)},
1695 std::string("Effect ID: ")
1696 .append(std::to_string(effect->id()))
1697 .append(" Session ID: ")
1698 .append(std::to_string(static_cast<int>(effect->sessionId())))
1699 .append(" \n")
1700 });
Glenn Kastene75da402013-11-20 13:54:52 -08001701 if (mCblkMemory == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001702 (mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->unsecurePointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001703 ALOGE("not enough memory for Effect size=%zu", EFFECT_PARAM_BUFFER_SIZE +
Eric Laurentca7cc822012-11-19 14:55:58 -08001704 sizeof(effect_param_cblk_t));
Glenn Kastene75da402013-11-20 13:54:52 -08001705 mCblkMemory.clear();
Eric Laurentca7cc822012-11-19 14:55:58 -08001706 return;
1707 }
Glenn Kastene75da402013-11-20 13:54:52 -08001708 new(mCblk) effect_param_cblk_t();
1709 mBuffer = (uint8_t *)mCblk + bufOffset;
Eric Laurentca7cc822012-11-19 14:55:58 -08001710}
1711
1712AudioFlinger::EffectHandle::~EffectHandle()
1713{
1714 ALOGV("Destructor %p", this);
Eric Laurentca7cc822012-11-19 14:55:58 -08001715 disconnect(false);
1716}
1717
Andy Hungc747c532022-03-07 21:41:14 -08001718// Creates an association between Binder code to name for IEffect.
1719#define IEFFECT_BINDER_METHOD_MACRO_LIST \
1720BINDER_METHOD_ENTRY(enable) \
1721BINDER_METHOD_ENTRY(disable) \
1722BINDER_METHOD_ENTRY(command) \
1723BINDER_METHOD_ENTRY(disconnect) \
1724BINDER_METHOD_ENTRY(getCblk) \
Mikhail Naganov8d7da002022-04-19 21:21:23 +00001725BINDER_METHOD_ENTRY(getConfig) \
Andy Hungc747c532022-03-07 21:41:14 -08001726
1727// singleton for Binder Method Statistics for IEffect
1728mediautils::MethodStatistics<int>& getIEffectStatistics() {
1729 using Code = int;
1730
1731#pragma push_macro("BINDER_METHOD_ENTRY")
1732#undef BINDER_METHOD_ENTRY
1733#define BINDER_METHOD_ENTRY(ENTRY) \
1734 {(Code)media::BnEffect::TRANSACTION_##ENTRY, #ENTRY},
1735
1736 static mediautils::MethodStatistics<Code> methodStatistics{
1737 IEFFECT_BINDER_METHOD_MACRO_LIST
1738 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
1739 };
1740#pragma pop_macro("BINDER_METHOD_ENTRY")
1741
1742 return methodStatistics;
1743}
1744
1745status_t AudioFlinger::EffectHandle::onTransact(
1746 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
Andy Hunga2a1ac32022-03-18 16:12:11 -07001747 const std::string methodName = getIEffectStatistics().getMethodForCode(code);
1748 mediautils::TimeCheck check(
1749 std::string("IEffect::").append(methodName),
1750 [code](bool timeout, float elapsedMs) {
1751 if (timeout) {
1752 ; // we don't timeout right now on the effect interface.
1753 } else {
1754 getIEffectStatistics().event(code, elapsedMs);
1755 }
Andy Hungf8ab0932022-06-13 19:49:43 -07001756 }, {} /* timeoutDuration */, {} /* secondChanceDuration */, false /* crashOnTimeout */);
Andy Hungc747c532022-03-07 21:41:14 -08001757 return BnEffect::onTransact(code, data, reply, flags);
1758}
1759
Glenn Kastene75da402013-11-20 13:54:52 -08001760status_t AudioFlinger::EffectHandle::initCheck()
1761{
1762 return mClient == 0 || mCblkMemory != 0 ? OK : NO_MEMORY;
1763}
1764
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001765#define RETURN(code) \
1766 *_aidl_return = (code); \
1767 return Status::ok();
1768
Mikhail Naganov8d7da002022-04-19 21:21:23 +00001769#define VALUE_OR_RETURN_STATUS_AS_OUT(exp) \
1770 ({ \
1771 auto _tmp = (exp); \
1772 if (!_tmp.ok()) { RETURN(_tmp.error()); } \
1773 std::move(_tmp.value()); \
1774 })
1775
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001776Status AudioFlinger::EffectHandle::enable(int32_t* _aidl_return)
Eric Laurentca7cc822012-11-19 14:55:58 -08001777{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001778 AutoMutex _l(mLock);
Eric Laurentca7cc822012-11-19 14:55:58 -08001779 ALOGV("enable %p", this);
Eric Laurent41709552019-12-16 19:34:05 -08001780 sp<EffectBase> effect = mEffect.promote();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001781 if (effect == 0 || mDisconnected) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001782 RETURN(DEAD_OBJECT);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001783 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001784 if (!mHasControl) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001785 RETURN(INVALID_OPERATION);
Eric Laurentca7cc822012-11-19 14:55:58 -08001786 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001787
1788 if (mEnabled) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001789 RETURN(NO_ERROR);
Eric Laurentca7cc822012-11-19 14:55:58 -08001790 }
1791
1792 mEnabled = true;
1793
Eric Laurent6c796322019-04-09 14:13:17 -07001794 status_t status = effect->updatePolicyState();
1795 if (status != NO_ERROR) {
1796 mEnabled = false;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001797 RETURN(status);
Eric Laurent6c796322019-04-09 14:13:17 -07001798 }
1799
Eric Laurent6b446ce2019-12-13 10:56:31 -08001800 effect->checkSuspendOnEffectEnabled(true, false /*threadLocked*/);
Eric Laurentca7cc822012-11-19 14:55:58 -08001801
1802 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001803 if (effect->suspended()) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001804 RETURN(NO_ERROR);
Eric Laurentca7cc822012-11-19 14:55:58 -08001805 }
1806
Eric Laurent6b446ce2019-12-13 10:56:31 -08001807 status = effect->setEnabled(true, true /*fromHandle*/);
Eric Laurentca7cc822012-11-19 14:55:58 -08001808 if (status != NO_ERROR) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001809 mEnabled = false;
1810 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001811 RETURN(status);
Eric Laurentca7cc822012-11-19 14:55:58 -08001812}
1813
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001814Status AudioFlinger::EffectHandle::disable(int32_t* _aidl_return)
Eric Laurentca7cc822012-11-19 14:55:58 -08001815{
1816 ALOGV("disable %p", this);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001817 AutoMutex _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001818 sp<EffectBase> effect = mEffect.promote();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001819 if (effect == 0 || mDisconnected) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001820 RETURN(DEAD_OBJECT);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001821 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001822 if (!mHasControl) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001823 RETURN(INVALID_OPERATION);
Eric Laurentca7cc822012-11-19 14:55:58 -08001824 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001825
1826 if (!mEnabled) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001827 RETURN(NO_ERROR);
Eric Laurentca7cc822012-11-19 14:55:58 -08001828 }
1829 mEnabled = false;
1830
Eric Laurent6c796322019-04-09 14:13:17 -07001831 effect->updatePolicyState();
1832
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001833 if (effect->suspended()) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001834 RETURN(NO_ERROR);
Eric Laurentca7cc822012-11-19 14:55:58 -08001835 }
1836
Eric Laurent6b446ce2019-12-13 10:56:31 -08001837 status_t status = effect->setEnabled(false, true /*fromHandle*/);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001838 RETURN(status);
Eric Laurentca7cc822012-11-19 14:55:58 -08001839}
1840
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001841Status AudioFlinger::EffectHandle::disconnect()
Eric Laurentca7cc822012-11-19 14:55:58 -08001842{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001843 ALOGV("%s %p", __FUNCTION__, this);
Eric Laurentca7cc822012-11-19 14:55:58 -08001844 disconnect(true);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001845 return Status::ok();
Eric Laurentca7cc822012-11-19 14:55:58 -08001846}
1847
1848void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
1849{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001850 AutoMutex _l(mLock);
1851 ALOGV("disconnect(%s) %p", unpinIfLast ? "true" : "false", this);
1852 if (mDisconnected) {
1853 if (unpinIfLast) {
1854 android_errorWriteLog(0x534e4554, "32707507");
1855 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001856 return;
1857 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001858 mDisconnected = true;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001859 {
Eric Laurent41709552019-12-16 19:34:05 -08001860 sp<EffectBase> effect = mEffect.promote();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001861 if (effect != 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001862 if (effect->disconnectHandle(this, unpinIfLast) > 0) {
Eric Laurent6c796322019-04-09 14:13:17 -07001863 ALOGW("%s Effect handle %p disconnected after thread destruction",
1864 __func__, this);
1865 }
1866 effect->updatePolicyState();
Eric Laurentf10c7092016-12-06 17:09:56 -08001867 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001868 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001869
Eric Laurentca7cc822012-11-19 14:55:58 -08001870 if (mClient != 0) {
1871 if (mCblk != NULL) {
1872 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
1873 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
1874 }
1875 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Eric Laurent021cf962014-05-13 10:18:14 -07001876 // Client destructor must run with AudioFlinger client mutex locked
Andy Hung920f6572022-10-06 12:09:49 -07001877 Mutex::Autolock _l2(mClient->audioFlinger()->mClientLock);
Eric Laurentca7cc822012-11-19 14:55:58 -08001878 mClient.clear();
1879 }
1880}
1881
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001882Status AudioFlinger::EffectHandle::getCblk(media::SharedFileRegion* _aidl_return) {
1883 LOG_ALWAYS_FATAL_IF(!convertIMemoryToSharedFileRegion(mCblkMemory, _aidl_return));
1884 return Status::ok();
1885}
1886
Mikhail Naganov8d7da002022-04-19 21:21:23 +00001887Status AudioFlinger::EffectHandle::getConfig(
1888 media::EffectConfig* _config, int32_t* _aidl_return) {
1889 AutoMutex _l(mLock);
1890 sp<EffectBase> effect = mEffect.promote();
1891 if (effect == nullptr || mDisconnected) {
1892 RETURN(DEAD_OBJECT);
1893 }
1894 sp<EffectModule> effectModule = effect->asEffectModule();
1895 if (effectModule == nullptr) {
1896 RETURN(INVALID_OPERATION);
1897 }
1898 audio_config_base_t inputCfg = AUDIO_CONFIG_BASE_INITIALIZER;
1899 audio_config_base_t outputCfg = AUDIO_CONFIG_BASE_INITIALIZER;
1900 bool isOutput;
1901 status_t status = effectModule->getConfigs(&inputCfg, &outputCfg, &isOutput);
1902 if (status == NO_ERROR) {
1903 constexpr bool isInput = false; // effects always use 'OUT' channel masks.
1904 _config->inputCfg = VALUE_OR_RETURN_STATUS_AS_OUT(
1905 legacy2aidl_audio_config_base_t_AudioConfigBase(inputCfg, isInput));
1906 _config->outputCfg = VALUE_OR_RETURN_STATUS_AS_OUT(
1907 legacy2aidl_audio_config_base_t_AudioConfigBase(outputCfg, isInput));
1908 _config->isOnInputStream = !isOutput;
1909 }
1910 RETURN(status);
1911}
1912
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001913Status AudioFlinger::EffectHandle::command(int32_t cmdCode,
1914 const std::vector<uint8_t>& cmdData,
1915 int32_t maxResponseSize,
1916 std::vector<uint8_t>* response,
1917 int32_t* _aidl_return)
Eric Laurentca7cc822012-11-19 14:55:58 -08001918{
1919 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001920 cmdCode, mHasControl, mEffect.unsafe_get());
Eric Laurentca7cc822012-11-19 14:55:58 -08001921
Eric Laurentc7ab3092017-06-15 18:43:46 -07001922 // reject commands reserved for internal use by audio framework if coming from outside
1923 // of audioserver
1924 switch(cmdCode) {
1925 case EFFECT_CMD_ENABLE:
1926 case EFFECT_CMD_DISABLE:
1927 case EFFECT_CMD_SET_PARAM:
1928 case EFFECT_CMD_SET_PARAM_DEFERRED:
1929 case EFFECT_CMD_SET_PARAM_COMMIT:
1930 case EFFECT_CMD_GET_PARAM:
1931 break;
1932 default:
1933 if (cmdCode >= EFFECT_CMD_FIRST_PROPRIETARY) {
1934 break;
1935 }
1936 android_errorWriteLog(0x534e4554, "62019992");
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001937 RETURN(BAD_VALUE);
Eric Laurentc7ab3092017-06-15 18:43:46 -07001938 }
1939
Eric Laurent1ffc5852016-12-15 14:46:09 -08001940 if (cmdCode == EFFECT_CMD_ENABLE) {
Andy Hung920f6572022-10-06 12:09:49 -07001941 if (maxResponseSize < static_cast<signed>(sizeof(int))) {
Eric Laurent1ffc5852016-12-15 14:46:09 -08001942 android_errorWriteLog(0x534e4554, "32095713");
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001943 RETURN(BAD_VALUE);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001944 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001945 writeToBuffer(NO_ERROR, response);
1946 return enable(_aidl_return);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001947 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Andy Hung920f6572022-10-06 12:09:49 -07001948 if (maxResponseSize < static_cast<signed>(sizeof(int))) {
Eric Laurent1ffc5852016-12-15 14:46:09 -08001949 android_errorWriteLog(0x534e4554, "32095713");
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001950 RETURN(BAD_VALUE);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001951 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001952 writeToBuffer(NO_ERROR, response);
1953 return disable(_aidl_return);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001954 }
1955
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001956 AutoMutex _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001957 sp<EffectBase> effect = mEffect.promote();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001958 if (effect == 0 || mDisconnected) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001959 RETURN(DEAD_OBJECT);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001960 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001961 // only get parameter command is permitted for applications not controlling the effect
1962 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001963 RETURN(INVALID_OPERATION);
Eric Laurentca7cc822012-11-19 14:55:58 -08001964 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001965
1966 // handle commands that are not forwarded transparently to effect engine
1967 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08001968 if (mClient == 0) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001969 RETURN(INVALID_OPERATION);
Eric Laurentb82e6b72019-11-22 17:25:04 -08001970 }
1971
Andy Hung920f6572022-10-06 12:09:49 -07001972 if (maxResponseSize < (signed)sizeof(int)) {
Eric Laurent1ffc5852016-12-15 14:46:09 -08001973 android_errorWriteLog(0x534e4554, "32095713");
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001974 RETURN(BAD_VALUE);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001975 }
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001976 writeToBuffer(NO_ERROR, response);
Eric Laurent1ffc5852016-12-15 14:46:09 -08001977
Eric Laurentca7cc822012-11-19 14:55:58 -08001978 // No need to trylock() here as this function is executed in the binder thread serving a
1979 // particular client process: no risk to block the whole media server process or mixer
1980 // threads if we are stuck here
Andy Hung920f6572022-10-06 12:09:49 -07001981 Mutex::Autolock _l2(mCblk->lock);
Andy Hunga447a0f2016-11-15 17:19:58 -08001982 // keep local copy of index in case of client corruption b/32220769
1983 const uint32_t clientIndex = mCblk->clientIndex;
1984 const uint32_t serverIndex = mCblk->serverIndex;
1985 if (clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
1986 serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001987 mCblk->serverIndex = 0;
1988 mCblk->clientIndex = 0;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001989 RETURN(BAD_VALUE);
Eric Laurentca7cc822012-11-19 14:55:58 -08001990 }
1991 status_t status = NO_ERROR;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07001992 std::vector<uint8_t> param;
Andy Hunga447a0f2016-11-15 17:19:58 -08001993 for (uint32_t index = serverIndex; index < clientIndex;) {
1994 int *p = (int *)(mBuffer + index);
1995 const int size = *p++;
1996 if (size < 0
1997 || size > EFFECT_PARAM_BUFFER_SIZE
1998 || ((uint8_t *)p + size) > mBuffer + clientIndex) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001999 ALOGW("command(): invalid parameter block size");
Andy Hunga447a0f2016-11-15 17:19:58 -08002000 status = BAD_VALUE;
Eric Laurentca7cc822012-11-19 14:55:58 -08002001 break;
2002 }
Andy Hunga447a0f2016-11-15 17:19:58 -08002003
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002004 std::copy(reinterpret_cast<const uint8_t*>(p),
2005 reinterpret_cast<const uint8_t*>(p) + size,
2006 std::back_inserter(param));
Andy Hunga447a0f2016-11-15 17:19:58 -08002007
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002008 std::vector<uint8_t> replyBuffer;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002009 status_t ret = effect->command(EFFECT_CMD_SET_PARAM,
Andy Hunga447a0f2016-11-15 17:19:58 -08002010 param,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002011 sizeof(int),
2012 &replyBuffer);
2013 int reply = *reinterpret_cast<const int*>(replyBuffer.data());
Andy Hunga447a0f2016-11-15 17:19:58 -08002014
2015 // verify shared memory: server index shouldn't change; client index can't go back.
2016 if (serverIndex != mCblk->serverIndex
2017 || clientIndex > mCblk->clientIndex) {
2018 android_errorWriteLog(0x534e4554, "32220769");
2019 status = BAD_VALUE;
2020 break;
2021 }
2022
Eric Laurentca7cc822012-11-19 14:55:58 -08002023 // stop at first error encountered
2024 if (ret != NO_ERROR) {
2025 status = ret;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002026 writeToBuffer(reply, response);
Eric Laurentca7cc822012-11-19 14:55:58 -08002027 break;
2028 } else if (reply != NO_ERROR) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002029 writeToBuffer(reply, response);
Eric Laurentca7cc822012-11-19 14:55:58 -08002030 break;
2031 }
Andy Hunga447a0f2016-11-15 17:19:58 -08002032 index += size;
Eric Laurentca7cc822012-11-19 14:55:58 -08002033 }
2034 mCblk->serverIndex = 0;
2035 mCblk->clientIndex = 0;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002036 RETURN(status);
Eric Laurentca7cc822012-11-19 14:55:58 -08002037 }
2038
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002039 status_t status = effect->command(cmdCode,
2040 cmdData,
2041 maxResponseSize,
2042 response);
2043 RETURN(status);
Eric Laurentca7cc822012-11-19 14:55:58 -08002044}
2045
2046void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
2047{
2048 ALOGV("setControl %p control %d", this, hasControl);
2049
2050 mHasControl = hasControl;
2051 mEnabled = enabled;
2052
2053 if (signal && mEffectClient != 0) {
2054 mEffectClient->controlStatusChanged(hasControl);
2055 }
2056}
2057
2058void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002059 const std::vector<uint8_t>& cmdData,
2060 const std::vector<uint8_t>& replyData)
Eric Laurentca7cc822012-11-19 14:55:58 -08002061{
2062 if (mEffectClient != 0) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07002063 mEffectClient->commandExecuted(cmdCode, cmdData, replyData);
Eric Laurentca7cc822012-11-19 14:55:58 -08002064 }
2065}
2066
2067
2068
2069void AudioFlinger::EffectHandle::setEnabled(bool enabled)
2070{
2071 if (mEffectClient != 0) {
2072 mEffectClient->enableStatusChanged(enabled);
2073 }
2074}
2075
Eric Laurentde8caf42021-08-11 17:19:25 +02002076void AudioFlinger::EffectHandle::framesProcessed(int32_t frames) const
2077{
2078 if (mEffectClient != 0 && mNotifyFramesProcessed) {
2079 mEffectClient->framesProcessed(frames);
2080 }
2081}
2082
Glenn Kasten01d3acb2014-02-06 08:24:07 -08002083void AudioFlinger::EffectHandle::dumpToBuffer(char* buffer, size_t size)
Andy Hung920f6572022-10-06 12:09:49 -07002084NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurentca7cc822012-11-19 14:55:58 -08002085{
2086 bool locked = mCblk != NULL && AudioFlinger::dumpTryLock(mCblk->lock);
2087
Marco Nelissenb2208842014-02-07 14:00:50 -08002088 snprintf(buffer, size, "\t\t\t%5d %5d %3s %3s %5u %5u\n",
Andy Hung4ef19fa2018-05-15 19:35:29 -07002089 (mClient == 0) ? getpid() : mClient->pid(),
Eric Laurentca7cc822012-11-19 14:55:58 -08002090 mPriority,
Marco Nelissenb2208842014-02-07 14:00:50 -08002091 mHasControl ? "yes" : "no",
2092 locked ? "yes" : "no",
Eric Laurentca7cc822012-11-19 14:55:58 -08002093 mCblk ? mCblk->clientIndex : 0,
2094 mCblk ? mCblk->serverIndex : 0
2095 );
2096
2097 if (locked) {
2098 mCblk->lock.unlock();
2099 }
2100}
2101
2102#undef LOG_TAG
2103#define LOG_TAG "AudioFlinger::EffectChain"
2104
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002105AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& thread,
2106 audio_session_t sessionId)
Eric Laurent6b446ce2019-12-13 10:56:31 -08002107 : mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002108 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
Eric Laurent6b446ce2019-12-13 10:56:31 -08002109 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX),
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002110 mEffectCallback(new EffectCallback(wp<EffectChain>(this), thread))
Eric Laurentca7cc822012-11-19 14:55:58 -08002111{
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002112 sp<ThreadBase> p = thread.promote();
2113 if (p == nullptr) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002114 return;
2115 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02002116 mStrategy = p->getStrategyForStream(AUDIO_STREAM_MUSIC);
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002117 mMaxTailBuffers = ((kProcessTailDurationMs * p->sampleRate()) / 1000) /
2118 p->frameCount();
Eric Laurentca7cc822012-11-19 14:55:58 -08002119}
2120
2121AudioFlinger::EffectChain::~EffectChain()
2122{
Eric Laurentca7cc822012-11-19 14:55:58 -08002123}
2124
2125// getEffectFromDesc_l() must be called with ThreadBase::mLock held
2126sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
2127 effect_descriptor_t *descriptor)
2128{
2129 size_t size = mEffects.size();
2130
2131 for (size_t i = 0; i < size; i++) {
2132 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
2133 return mEffects[i];
2134 }
2135 }
2136 return 0;
2137}
2138
2139// getEffectFromId_l() must be called with ThreadBase::mLock held
2140sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
2141{
2142 size_t size = mEffects.size();
2143
2144 for (size_t i = 0; i < size; i++) {
2145 // by convention, return first effect if id provided is 0 (0 is never a valid id)
2146 if (id == 0 || mEffects[i]->id() == id) {
2147 return mEffects[i];
2148 }
2149 }
2150 return 0;
2151}
2152
2153// getEffectFromType_l() must be called with ThreadBase::mLock held
2154sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
2155 const effect_uuid_t *type)
2156{
2157 size_t size = mEffects.size();
2158
2159 for (size_t i = 0; i < size; i++) {
2160 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
2161 return mEffects[i];
2162 }
2163 }
2164 return 0;
2165}
2166
Eric Laurent6c796322019-04-09 14:13:17 -07002167std::vector<int> AudioFlinger::EffectChain::getEffectIds()
2168{
2169 std::vector<int> ids;
2170 Mutex::Autolock _l(mLock);
2171 for (size_t i = 0; i < mEffects.size(); i++) {
2172 ids.push_back(mEffects[i]->id());
2173 }
2174 return ids;
2175}
2176
Eric Laurentca7cc822012-11-19 14:55:58 -08002177void AudioFlinger::EffectChain::clearInputBuffer()
2178{
2179 Mutex::Autolock _l(mLock);
Eric Laurent6b446ce2019-12-13 10:56:31 -08002180 clearInputBuffer_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08002181}
2182
2183// Must be called with EffectChain::mLock locked
Eric Laurent6b446ce2019-12-13 10:56:31 -08002184void AudioFlinger::EffectChain::clearInputBuffer_l()
Eric Laurentca7cc822012-11-19 14:55:58 -08002185{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002186 if (mInBuffer == NULL) {
2187 return;
2188 }
Andy Hung319587b2023-05-23 14:01:03 -07002189 const size_t frameSize = audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT)
Eric Laurentf1f22e72021-07-13 14:04:14 +02002190 * mEffectCallback->inChannelCount(mEffects[0]->id());
rago94a1ee82017-07-21 15:11:02 -07002191
Eric Laurent6b446ce2019-12-13 10:56:31 -08002192 memset(mInBuffer->audioBuffer()->raw, 0, mEffectCallback->frameCount() * frameSize);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002193 mInBuffer->commit();
Eric Laurentca7cc822012-11-19 14:55:58 -08002194}
2195
2196// Must be called with EffectChain::mLock locked
2197void AudioFlinger::EffectChain::process_l()
2198{
Jean-Michel Trivifed62922013-09-25 18:50:33 -07002199 // never process effects when:
2200 // - on an OFFLOAD thread
2201 // - no more tracks are on the session and the effect tail has been rendered
Eric Laurent6b446ce2019-12-13 10:56:31 -08002202 bool doProcess = !mEffectCallback->isOffloadOrMmap();
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002203 if (!audio_is_global_session(mSessionId)) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002204 bool tracksOnSession = (trackCnt() != 0);
2205
2206 if (!tracksOnSession && mTailBufferCount == 0) {
2207 doProcess = false;
2208 }
2209
2210 if (activeTrackCnt() == 0) {
2211 // if no track is active and the effect tail has not been rendered,
2212 // the input buffer must be cleared here as the mixer process will not do it
2213 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08002214 clearInputBuffer_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08002215 if (mTailBufferCount > 0) {
2216 mTailBufferCount--;
2217 }
2218 }
2219 }
2220 }
2221
2222 size_t size = mEffects.size();
2223 if (doProcess) {
Mikhail Naganov022b9952017-01-04 16:36:51 -08002224 // Only the input and output buffers of the chain can be external,
2225 // and 'update' / 'commit' do nothing for allocated buffers, thus
2226 // it's not needed to consider any other buffers here.
2227 mInBuffer->update();
Mikhail Naganov06888802017-01-19 12:47:55 -08002228 if (mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw) {
2229 mOutBuffer->update();
2230 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002231 for (size_t i = 0; i < size; i++) {
2232 mEffects[i]->process();
2233 }
Mikhail Naganov06888802017-01-19 12:47:55 -08002234 mInBuffer->commit();
2235 if (mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw) {
2236 mOutBuffer->commit();
2237 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002238 }
Eric Laurentfa1e1232016-08-02 19:01:49 -07002239 bool doResetVolume = false;
Eric Laurentca7cc822012-11-19 14:55:58 -08002240 for (size_t i = 0; i < size; i++) {
Eric Laurentfa1e1232016-08-02 19:01:49 -07002241 doResetVolume = mEffects[i]->updateState() || doResetVolume;
2242 }
2243 if (doResetVolume) {
2244 resetVolume_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08002245 }
2246}
2247
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002248// createEffect_l() must be called with ThreadBase::mLock held
2249status_t AudioFlinger::EffectChain::createEffect_l(sp<EffectModule>& effect,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002250 effect_descriptor_t *desc,
2251 int id,
2252 audio_session_t sessionId,
2253 bool pinned)
2254{
2255 Mutex::Autolock _l(mLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -08002256 effect = new EffectModule(mEffectCallback, desc, id, sessionId, pinned, AUDIO_PORT_HANDLE_NONE);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002257 status_t lStatus = effect->status();
2258 if (lStatus == NO_ERROR) {
2259 lStatus = addEffect_ll(effect);
2260 }
2261 if (lStatus != NO_ERROR) {
2262 effect.clear();
2263 }
2264 return lStatus;
2265}
2266
2267// addEffect_l() must be called with ThreadBase::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -08002268status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
2269{
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002270 Mutex::Autolock _l(mLock);
2271 return addEffect_ll(effect);
2272}
2273// addEffect_l() must be called with ThreadBase::mLock and EffectChain::mLock held
2274status_t AudioFlinger::EffectChain::addEffect_ll(const sp<EffectModule>& effect)
2275{
Eric Laurent6b446ce2019-12-13 10:56:31 -08002276 effect->setCallback(mEffectCallback);
Eric Laurentca7cc822012-11-19 14:55:58 -08002277
Eric Laurentb62d0362021-10-26 17:40:18 +02002278 effect_descriptor_t desc = effect->desc();
Eric Laurentca7cc822012-11-19 14:55:58 -08002279 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2280 // Auxiliary effects are inserted at the beginning of mEffects vector as
2281 // they are processed first and accumulated in chain input buffer
2282 mEffects.insertAt(effect, 0);
2283
2284 // the input buffer for auxiliary effect contains mono samples in
2285 // 32 bit format. This is to avoid saturation in AudoMixer
2286 // accumulation stage. Saturation is done in EffectModule::process() before
2287 // calling the process in effect engine
Eric Laurent6b446ce2019-12-13 10:56:31 -08002288 size_t numSamples = mEffectCallback->frameCount();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002289 sp<EffectBufferHalInterface> halBuffer;
Andy Hung26836922023-05-22 17:31:57 -07002290
Eric Laurent6b446ce2019-12-13 10:56:31 -08002291 status_t result = mEffectCallback->allocateHalBuffer(
rago94a1ee82017-07-21 15:11:02 -07002292 numSamples * sizeof(float), &halBuffer);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002293 if (result != OK) return result;
Eric Laurentf1f22e72021-07-13 14:04:14 +02002294
2295 effect->configure();
2296
Mikhail Naganov022b9952017-01-04 16:36:51 -08002297 effect->setInBuffer(halBuffer);
Eric Laurentca7cc822012-11-19 14:55:58 -08002298 // auxiliary effects output samples to chain input buffer for further processing
2299 // by insert effects
2300 effect->setOutBuffer(mInBuffer);
2301 } else {
Eric Laurentb62d0362021-10-26 17:40:18 +02002302 ssize_t idx_insert = getInsertIndex(desc);
2303 if (idx_insert < 0) {
2304 return INVALID_OPERATION;
Eric Laurentca7cc822012-11-19 14:55:58 -08002305 }
2306
Eric Laurentb62d0362021-10-26 17:40:18 +02002307 size_t previousSize = mEffects.size();
Eric Laurentf1f22e72021-07-13 14:04:14 +02002308 mEffects.insertAt(effect, idx_insert);
2309
2310 effect->configure();
2311
Eric Laurentb62d0362021-10-26 17:40:18 +02002312 // - By default:
2313 // All effects read samples from chain input buffer.
2314 // The last effect in the chain, writes samples to chain output buffer,
2315 // otherwise to chain input buffer
2316 // - In the OUTPUT_STAGE chain of a spatializer mixer thread:
2317 // The spatializer effect (first effect) reads samples from the input buffer
2318 // and writes samples to the output buffer.
2319 // All other effects read and writes samples to the output buffer
2320 if (mEffectCallback->isSpatializer()
2321 && mSessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002322 effect->setOutBuffer(mOutBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002323 if (idx_insert == 0) {
2324 if (previousSize != 0) {
2325 mEffects[1]->configure();
2326 mEffects[1]->setInBuffer(mOutBuffer);
2327 mEffects[1]->updateAccessMode(); // reconfig if neeeded.
2328 }
2329 effect->setInBuffer(mInBuffer);
2330 } else {
2331 effect->setInBuffer(mOutBuffer);
2332 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002333 } else {
Eric Laurentb62d0362021-10-26 17:40:18 +02002334 effect->setInBuffer(mInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07002335 if (idx_insert == static_cast<ssize_t>(previousSize)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02002336 if (idx_insert != 0) {
2337 mEffects[idx_insert-1]->configure();
2338 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
2339 mEffects[idx_insert - 1]->updateAccessMode(); // reconfig if neeeded.
2340 }
2341 effect->setOutBuffer(mOutBuffer);
2342 } else {
2343 effect->setOutBuffer(mInBuffer);
2344 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002345 }
Eric Laurentb62d0362021-10-26 17:40:18 +02002346 ALOGV("%s effect %p, added in chain %p at rank %zu",
2347 __func__, effect.get(), this, idx_insert);
Eric Laurentca7cc822012-11-19 14:55:58 -08002348 }
2349 effect->configure();
Eric Laurentd8365c52017-07-16 15:27:05 -07002350
Eric Laurentca7cc822012-11-19 14:55:58 -08002351 return NO_ERROR;
2352}
2353
Eric Laurentb62d0362021-10-26 17:40:18 +02002354ssize_t AudioFlinger::EffectChain::getInsertIndex(const effect_descriptor_t& desc) {
2355 // Insert effects are inserted at the end of mEffects vector as they are processed
2356 // after track and auxiliary effects.
2357 // Insert effect order as a function of indicated preference:
2358 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
2359 // another effect is present
2360 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
2361 // last effect claiming first position
2362 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
2363 // first effect claiming last position
2364 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
2365 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
2366 // already present
2367 // Spatializer or Downmixer effects are inserted in first position because
2368 // they adapt the channel count for all other effects in the chain
2369 if ((memcmp(&desc.type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0)
2370 || (memcmp(&desc.type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0)) {
2371 return 0;
2372 }
2373
2374 size_t size = mEffects.size();
2375 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
2376 ssize_t idx_insert;
2377 ssize_t idx_insert_first = -1;
2378 ssize_t idx_insert_last = -1;
2379
2380 idx_insert = size;
2381 for (size_t i = 0; i < size; i++) {
2382 effect_descriptor_t d = mEffects[i]->desc();
2383 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
2384 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
2385 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
2386 // check invalid effect chaining combinations
2387 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
2388 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
2389 ALOGW("%s could not insert effect %s: exclusive conflict with %s",
2390 __func__, desc.name, d.name);
2391 return -1;
2392 }
2393 // remember position of first insert effect and by default
2394 // select this as insert position for new effect
Andy Hung920f6572022-10-06 12:09:49 -07002395 if (idx_insert == static_cast<ssize_t>(size)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02002396 idx_insert = i;
2397 }
2398 // remember position of last insert effect claiming
2399 // first position
2400 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
2401 idx_insert_first = i;
2402 }
2403 // remember position of first insert effect claiming
2404 // last position
2405 if (iPref == EFFECT_FLAG_INSERT_LAST &&
2406 idx_insert_last == -1) {
2407 idx_insert_last = i;
2408 }
2409 }
2410 }
2411
2412 // modify idx_insert from first position if needed
2413 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
2414 if (idx_insert_last != -1) {
2415 idx_insert = idx_insert_last;
2416 } else {
2417 idx_insert = size;
2418 }
2419 } else {
2420 if (idx_insert_first != -1) {
2421 idx_insert = idx_insert_first + 1;
2422 }
2423 }
2424 return idx_insert;
2425}
2426
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002427// removeEffect_l() must be called with ThreadBase::mLock held
2428size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect,
2429 bool release)
Eric Laurentca7cc822012-11-19 14:55:58 -08002430{
2431 Mutex::Autolock _l(mLock);
2432 size_t size = mEffects.size();
2433 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
2434
2435 for (size_t i = 0; i < size; i++) {
2436 if (effect == mEffects[i]) {
2437 // calling stop here will remove pre-processing effect from the audio HAL.
2438 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
2439 // the middle of a read from audio HAL
2440 if (mEffects[i]->state() == EffectModule::ACTIVE ||
2441 mEffects[i]->state() == EffectModule::STOPPING) {
2442 mEffects[i]->stop();
2443 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002444 if (release) {
2445 mEffects[i]->release_l();
2446 }
2447
Mikhail Naganov022b9952017-01-04 16:36:51 -08002448 if (type != EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002449 if (i == size - 1 && i != 0) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002450 mEffects[i - 1]->configure();
Eric Laurentf1f22e72021-07-13 14:04:14 +02002451 mEffects[i - 1]->setOutBuffer(mOutBuffer);
Eric Laurent6bb7dbe2021-12-23 15:39:36 +01002452 mEffects[i - 1]->updateAccessMode(); // reconfig if neeeded.
Eric Laurentca7cc822012-11-19 14:55:58 -08002453 }
2454 }
2455 mEffects.removeAt(i);
Eric Laurentf1f22e72021-07-13 14:04:14 +02002456
2457 // make sure the input buffer configuration for the new first effect in the chain
2458 // is updated if needed (can switch from HAL channel mask to mixer channel mask)
Nie Wei Feng4d2cb592023-05-26 15:18:04 -07002459 if (type != EFFECT_FLAG_TYPE_AUXILIARY // TODO(b/284522658) breaks for aux FX, why?
2460 && i == 0 && size > 1) {
Eric Laurentf1f22e72021-07-13 14:04:14 +02002461 mEffects[0]->configure();
2462 mEffects[0]->setInBuffer(mInBuffer);
Eric Laurent6bb7dbe2021-12-23 15:39:36 +01002463 mEffects[0]->updateAccessMode(); // reconfig if neeeded.
Eric Laurentf1f22e72021-07-13 14:04:14 +02002464 }
2465
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002466 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %zu", effect.get(),
Eric Laurentca7cc822012-11-19 14:55:58 -08002467 this, i);
2468 break;
2469 }
2470 }
2471
2472 return mEffects.size();
2473}
2474
jiabin8f278ee2019-11-11 12:16:27 -08002475// setDevices_l() must be called with ThreadBase::mLock held
2476void AudioFlinger::EffectChain::setDevices_l(const AudioDeviceTypeAddrVector &devices)
Eric Laurentca7cc822012-11-19 14:55:58 -08002477{
2478 size_t size = mEffects.size();
2479 for (size_t i = 0; i < size; i++) {
jiabin8f278ee2019-11-11 12:16:27 -08002480 mEffects[i]->setDevices(devices);
2481 }
2482}
2483
2484// setInputDevice_l() must be called with ThreadBase::mLock held
2485void AudioFlinger::EffectChain::setInputDevice_l(const AudioDeviceTypeAddr &device)
2486{
2487 size_t size = mEffects.size();
2488 for (size_t i = 0; i < size; i++) {
2489 mEffects[i]->setInputDevice(device);
Eric Laurentca7cc822012-11-19 14:55:58 -08002490 }
2491}
2492
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002493// setMode_l() must be called with ThreadBase::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -08002494void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
2495{
2496 size_t size = mEffects.size();
2497 for (size_t i = 0; i < size; i++) {
2498 mEffects[i]->setMode(mode);
2499 }
2500}
2501
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002502// setAudioSource_l() must be called with ThreadBase::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -08002503void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
2504{
2505 size_t size = mEffects.size();
2506 for (size_t i = 0; i < size; i++) {
2507 mEffects[i]->setAudioSource(source);
2508 }
2509}
2510
Zhou Songd505c642020-02-20 16:35:37 +08002511bool AudioFlinger::EffectChain::hasVolumeControlEnabled_l() const {
2512 for (const auto &effect : mEffects) {
2513 if (effect->isVolumeControlEnabled()) return true;
2514 }
2515 return false;
2516}
2517
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002518// setVolume_l() must be called with ThreadBase::mLock or EffectChain::mLock held
Eric Laurentfa1e1232016-08-02 19:01:49 -07002519bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right, bool force)
Eric Laurentca7cc822012-11-19 14:55:58 -08002520{
2521 uint32_t newLeft = *left;
2522 uint32_t newRight = *right;
2523 bool hasControl = false;
2524 int ctrlIdx = -1;
2525 size_t size = mEffects.size();
2526
2527 // first update volume controller
2528 for (size_t i = size; i > 0; i--) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002529 if (mEffects[i - 1]->isVolumeControlEnabled()) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002530 ctrlIdx = i - 1;
2531 hasControl = true;
2532 break;
2533 }
2534 }
2535
Eric Laurentfa1e1232016-08-02 19:01:49 -07002536 if (!force && ctrlIdx == mVolumeCtrlIdx &&
Eric Laurentcb4b6e92014-10-01 14:26:10 -07002537 *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002538 if (hasControl) {
2539 *left = mNewLeftVolume;
2540 *right = mNewRightVolume;
2541 }
2542 return hasControl;
2543 }
2544
2545 mVolumeCtrlIdx = ctrlIdx;
2546 mLeftVolume = newLeft;
2547 mRightVolume = newRight;
2548
2549 // second get volume update from volume controller
2550 if (ctrlIdx >= 0) {
2551 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
2552 mNewLeftVolume = newLeft;
2553 mNewRightVolume = newRight;
2554 }
2555 // then indicate volume to all other effects in chain.
2556 // Pass altered volume to effects before volume controller
Jasmine Cha934ecfb2019-01-23 18:19:14 +08002557 // and requested volume to effects after controller or with volume monitor flag
Eric Laurentca7cc822012-11-19 14:55:58 -08002558 uint32_t lVol = newLeft;
2559 uint32_t rVol = newRight;
2560
2561 for (size_t i = 0; i < size; i++) {
2562 if ((int)i == ctrlIdx) {
2563 continue;
2564 }
2565 // this also works for ctrlIdx == -1 when there is no volume controller
2566 if ((int)i > ctrlIdx) {
2567 lVol = *left;
2568 rVol = *right;
2569 }
Jasmine Cha934ecfb2019-01-23 18:19:14 +08002570 // Pass requested volume directly if this is volume monitor module
2571 if (mEffects[i]->isVolumeMonitor()) {
2572 mEffects[i]->setVolume(left, right, false);
2573 } else {
2574 mEffects[i]->setVolume(&lVol, &rVol, false);
2575 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002576 }
2577 *left = newLeft;
2578 *right = newRight;
2579
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002580 setVolumeForOutput_l(*left, *right);
2581
Eric Laurentca7cc822012-11-19 14:55:58 -08002582 return hasControl;
2583}
2584
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002585// resetVolume_l() must be called with ThreadBase::mLock or EffectChain::mLock held
Eric Laurentfa1e1232016-08-02 19:01:49 -07002586void AudioFlinger::EffectChain::resetVolume_l()
2587{
Eric Laurente7449bf2016-08-03 18:44:07 -07002588 if ((mLeftVolume != UINT_MAX) && (mRightVolume != UINT_MAX)) {
2589 uint32_t left = mLeftVolume;
2590 uint32_t right = mRightVolume;
2591 (void)setVolume_l(&left, &right, true);
2592 }
Eric Laurentfa1e1232016-08-02 19:01:49 -07002593}
2594
jiabineb3bda02020-06-30 14:07:03 -07002595// containsHapticGeneratingEffect_l must be called with ThreadBase::mLock or EffectChain::mLock held
2596bool AudioFlinger::EffectChain::containsHapticGeneratingEffect_l()
2597{
2598 for (size_t i = 0; i < mEffects.size(); ++i) {
2599 if (mEffects[i]->isHapticGenerator()) {
2600 return true;
2601 }
2602 }
2603 return false;
2604}
2605
Simon Bowden62823412022-10-17 14:52:26 +00002606void AudioFlinger::EffectChain::setHapticIntensity_l(int id, os::HapticScale intensity)
jiabine70bc7f2020-06-30 22:07:55 -07002607{
2608 Mutex::Autolock _l(mLock);
2609 for (size_t i = 0; i < mEffects.size(); ++i) {
2610 mEffects[i]->setHapticIntensity(id, intensity);
2611 }
2612}
2613
Eric Laurent1b928682014-10-02 19:41:47 -07002614void AudioFlinger::EffectChain::syncHalEffectsState()
2615{
2616 Mutex::Autolock _l(mLock);
2617 for (size_t i = 0; i < mEffects.size(); i++) {
2618 if (mEffects[i]->state() == EffectModule::ACTIVE ||
2619 mEffects[i]->state() == EffectModule::STOPPING) {
2620 mEffects[i]->addEffectToHal_l();
2621 }
2622 }
2623}
2624
Eric Laurentca7cc822012-11-19 14:55:58 -08002625void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07002626NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurentca7cc822012-11-19 14:55:58 -08002627{
Eric Laurentca7cc822012-11-19 14:55:58 -08002628 String8 result;
2629
Mikhail Naganov19740ca2019-03-28 12:25:01 -07002630 const size_t numEffects = mEffects.size();
2631 result.appendFormat(" %zu effects for session %d\n", numEffects, mSessionId);
Eric Laurentca7cc822012-11-19 14:55:58 -08002632
Marco Nelissenb2208842014-02-07 14:00:50 -08002633 if (numEffects) {
2634 bool locked = AudioFlinger::dumpTryLock(mLock);
2635 // failed to lock - AudioFlinger is probably deadlocked
2636 if (!locked) {
2637 result.append("\tCould not lock mutex:\n");
Eric Laurentca7cc822012-11-19 14:55:58 -08002638 }
Eric Laurentca7cc822012-11-19 14:55:58 -08002639
Andy Hungbded9c82017-11-30 18:47:35 -08002640 const std::string inBufferStr = dumpInOutBuffer(true /* isInput */, mInBuffer);
2641 const std::string outBufferStr = dumpInOutBuffer(false /* isInput */, mOutBuffer);
2642 result.appendFormat("\t%-*s%-*s Active tracks:\n",
2643 (int)inBufferStr.size(), "In buffer ",
2644 (int)outBufferStr.size(), "Out buffer ");
2645 result.appendFormat("\t%s %s %d\n",
2646 inBufferStr.c_str(), outBufferStr.c_str(), mActiveTrackCnt);
Marco Nelissenb2208842014-02-07 14:00:50 -08002647 write(fd, result.string(), result.size());
2648
2649 for (size_t i = 0; i < numEffects; ++i) {
2650 sp<EffectModule> effect = mEffects[i];
2651 if (effect != 0) {
2652 effect->dump(fd, args);
2653 }
2654 }
2655
2656 if (locked) {
2657 mLock.unlock();
2658 }
Mikhail Naganov19740ca2019-03-28 12:25:01 -07002659 } else {
2660 write(fd, result.string(), result.size());
Eric Laurentca7cc822012-11-19 14:55:58 -08002661 }
2662}
2663
2664// must be called with ThreadBase::mLock held
2665void AudioFlinger::EffectChain::setEffectSuspended_l(
2666 const effect_uuid_t *type, bool suspend)
2667{
2668 sp<SuspendedEffectDesc> desc;
2669 // use effect type UUID timelow as key as there is no real risk of identical
2670 // timeLow fields among effect type UUIDs.
2671 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
2672 if (suspend) {
2673 if (index >= 0) {
2674 desc = mSuspendedEffects.valueAt(index);
2675 } else {
2676 desc = new SuspendedEffectDesc();
2677 desc->mType = *type;
2678 mSuspendedEffects.add(type->timeLow, desc);
2679 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
2680 }
Eric Laurentd8365c52017-07-16 15:27:05 -07002681
Eric Laurentca7cc822012-11-19 14:55:58 -08002682 if (desc->mRefCount++ == 0) {
2683 sp<EffectModule> effect = getEffectIfEnabled(type);
2684 if (effect != 0) {
2685 desc->mEffect = effect;
2686 effect->setSuspended(true);
Eric Laurent6b446ce2019-12-13 10:56:31 -08002687 effect->setEnabled(false, false /*fromHandle*/);
Eric Laurentca7cc822012-11-19 14:55:58 -08002688 }
2689 }
2690 } else {
2691 if (index < 0) {
2692 return;
2693 }
2694 desc = mSuspendedEffects.valueAt(index);
2695 if (desc->mRefCount <= 0) {
2696 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurentd8365c52017-07-16 15:27:05 -07002697 desc->mRefCount = 0;
2698 return;
Eric Laurentca7cc822012-11-19 14:55:58 -08002699 }
2700 if (--desc->mRefCount == 0) {
2701 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
2702 if (desc->mEffect != 0) {
2703 sp<EffectModule> effect = desc->mEffect.promote();
2704 if (effect != 0) {
2705 effect->setSuspended(false);
2706 effect->lock();
2707 EffectHandle *handle = effect->controlHandle_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002708 if (handle != NULL && !handle->disconnected()) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002709 effect->setEnabled_l(handle->enabled());
2710 }
2711 effect->unlock();
2712 }
2713 desc->mEffect.clear();
2714 }
2715 mSuspendedEffects.removeItemsAt(index);
2716 }
2717 }
2718}
2719
2720// must be called with ThreadBase::mLock held
2721void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
2722{
2723 sp<SuspendedEffectDesc> desc;
2724
2725 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
2726 if (suspend) {
2727 if (index >= 0) {
2728 desc = mSuspendedEffects.valueAt(index);
2729 } else {
2730 desc = new SuspendedEffectDesc();
2731 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
2732 ALOGV("setEffectSuspendedAll_l() add entry for 0");
2733 }
2734 if (desc->mRefCount++ == 0) {
2735 Vector< sp<EffectModule> > effects;
2736 getSuspendEligibleEffects(effects);
2737 for (size_t i = 0; i < effects.size(); i++) {
2738 setEffectSuspended_l(&effects[i]->desc().type, true);
2739 }
2740 }
2741 } else {
2742 if (index < 0) {
2743 return;
2744 }
2745 desc = mSuspendedEffects.valueAt(index);
2746 if (desc->mRefCount <= 0) {
2747 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
2748 desc->mRefCount = 1;
2749 }
2750 if (--desc->mRefCount == 0) {
2751 Vector<const effect_uuid_t *> types;
2752 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
2753 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
2754 continue;
2755 }
2756 types.add(&mSuspendedEffects.valueAt(i)->mType);
2757 }
2758 for (size_t i = 0; i < types.size(); i++) {
2759 setEffectSuspended_l(types[i], false);
2760 }
2761 ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
2762 mSuspendedEffects.keyAt(index));
2763 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
2764 }
2765 }
2766}
2767
2768
2769// The volume effect is used for automated tests only
2770#ifndef OPENSL_ES_H_
2771static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
2772 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
2773const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
2774#endif //OPENSL_ES_H_
2775
Eric Laurentd8365c52017-07-16 15:27:05 -07002776/* static */
2777bool AudioFlinger::EffectChain::isEffectEligibleForBtNrecSuspend(const effect_uuid_t *type)
2778{
2779 // Only NS and AEC are suspended when BtNRec is off
2780 if ((memcmp(type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) ||
2781 (memcmp(type, FX_IID_NS, sizeof(effect_uuid_t)) == 0)) {
2782 return true;
2783 }
2784 return false;
2785}
2786
Eric Laurentca7cc822012-11-19 14:55:58 -08002787bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
2788{
2789 // auxiliary effects and visualizer are never suspended on output mix
2790 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
2791 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
2792 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
Ricardo Garciac2a3a822019-07-17 14:29:12 -07002793 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0) ||
2794 (memcmp(&desc.type, SL_IID_DYNAMICSPROCESSING, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentca7cc822012-11-19 14:55:58 -08002795 return false;
2796 }
2797 return true;
2798}
2799
2800void AudioFlinger::EffectChain::getSuspendEligibleEffects(
2801 Vector< sp<AudioFlinger::EffectModule> > &effects)
2802{
2803 effects.clear();
2804 for (size_t i = 0; i < mEffects.size(); i++) {
2805 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
2806 effects.add(mEffects[i]);
2807 }
2808 }
2809}
2810
2811sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
2812 const effect_uuid_t *type)
2813{
2814 sp<EffectModule> effect = getEffectFromType_l(type);
2815 return effect != 0 && effect->isEnabled() ? effect : 0;
2816}
2817
2818void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
2819 bool enabled)
2820{
2821 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
2822 if (enabled) {
2823 if (index < 0) {
2824 // if the effect is not suspend check if all effects are suspended
2825 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
2826 if (index < 0) {
2827 return;
2828 }
2829 if (!isEffectEligibleForSuspend(effect->desc())) {
2830 return;
2831 }
2832 setEffectSuspended_l(&effect->desc().type, enabled);
2833 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
2834 if (index < 0) {
2835 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
2836 return;
2837 }
2838 }
2839 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
2840 effect->desc().type.timeLow);
2841 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
Eric Laurentd8365c52017-07-16 15:27:05 -07002842 // if effect is requested to suspended but was not yet enabled, suspend it now.
Eric Laurentca7cc822012-11-19 14:55:58 -08002843 if (desc->mEffect == 0) {
2844 desc->mEffect = effect;
Eric Laurent6b446ce2019-12-13 10:56:31 -08002845 effect->setEnabled(false, false /*fromHandle*/);
Eric Laurentca7cc822012-11-19 14:55:58 -08002846 effect->setSuspended(true);
2847 }
2848 } else {
2849 if (index < 0) {
2850 return;
2851 }
2852 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
2853 effect->desc().type.timeLow);
2854 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
2855 desc->mEffect.clear();
2856 effect->setSuspended(false);
2857 }
2858}
2859
Eric Laurent5baf2af2013-09-12 17:37:00 -07002860bool AudioFlinger::EffectChain::isNonOffloadableEnabled()
Eric Laurent813e2a72013-08-31 12:59:48 -07002861{
2862 Mutex::Autolock _l(mLock);
Shingo Kitajima1f8df9a2018-05-29 11:35:06 +09002863 return isNonOffloadableEnabled_l();
2864}
2865
2866bool AudioFlinger::EffectChain::isNonOffloadableEnabled_l()
2867{
Eric Laurent813e2a72013-08-31 12:59:48 -07002868 size_t size = mEffects.size();
2869 for (size_t i = 0; i < size; i++) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002870 if (mEffects[i]->isEnabled() && !mEffects[i]->isOffloadable()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002871 return true;
2872 }
2873 }
2874 return false;
2875}
2876
Eric Laurentaaa44472014-09-12 17:41:50 -07002877void AudioFlinger::EffectChain::setThread(const sp<ThreadBase>& thread)
2878{
2879 Mutex::Autolock _l(mLock);
Ytai Ben-Tsvi3de1bbf2020-01-21 16:41:17 -08002880 mEffectCallback->setThread(thread);
Eric Laurentaaa44472014-09-12 17:41:50 -07002881}
2882
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002883void AudioFlinger::EffectChain::checkOutputFlagCompatibility(audio_output_flags_t *flags) const
2884{
2885 if ((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0 && !isRawCompatible()) {
2886 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
2887 }
2888 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0 && !isFastCompatible()) {
2889 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
2890 }
jiabinc658e452022-10-21 20:52:21 +00002891 if ((*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != 0 && !isBitPerfectCompatible()) {
2892 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2893 }
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002894}
2895
2896void AudioFlinger::EffectChain::checkInputFlagCompatibility(audio_input_flags_t *flags) const
2897{
2898 if ((*flags & AUDIO_INPUT_FLAG_RAW) != 0 && !isRawCompatible()) {
2899 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
2900 }
2901 if ((*flags & AUDIO_INPUT_FLAG_FAST) != 0 && !isFastCompatible()) {
2902 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
2903 }
2904}
2905
2906bool AudioFlinger::EffectChain::isRawCompatible() const
Eric Laurent4c415062016-06-17 16:14:16 -07002907{
2908 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002909 for (const auto &effect : mEffects) {
2910 if (effect->isProcessImplemented()) {
2911 return false;
Eric Laurent4c415062016-06-17 16:14:16 -07002912 }
2913 }
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002914 // Allow effects without processing.
2915 return true;
2916}
2917
2918bool AudioFlinger::EffectChain::isFastCompatible() const
2919{
2920 Mutex::Autolock _l(mLock);
2921 for (const auto &effect : mEffects) {
2922 if (effect->isProcessImplemented()
2923 && effect->isImplementationSoftware()) {
2924 return false;
2925 }
2926 }
2927 // Allow effects without processing or hw accelerated effects.
2928 return true;
Eric Laurent4c415062016-06-17 16:14:16 -07002929}
2930
jiabinc658e452022-10-21 20:52:21 +00002931bool AudioFlinger::EffectChain::isBitPerfectCompatible() const {
2932 Mutex::Autolock _l(mLock);
2933 for (const auto &effect : mEffects) {
2934 if (effect->isProcessImplemented()
2935 && effect->isImplementationSoftware()) {
2936 return false;
2937 }
2938 }
2939 // Allow effects without processing or hw accelerated effects.
2940 return true;
2941}
2942
Eric Laurent4c415062016-06-17 16:14:16 -07002943// isCompatibleWithThread_l() must be called with thread->mLock held
2944bool AudioFlinger::EffectChain::isCompatibleWithThread_l(const sp<ThreadBase>& thread) const
2945{
2946 Mutex::Autolock _l(mLock);
2947 for (size_t i = 0; i < mEffects.size(); i++) {
2948 if (thread->checkEffectCompatibility_l(&(mEffects[i]->desc()), mSessionId) != NO_ERROR) {
2949 return false;
2950 }
2951 }
2952 return true;
2953}
2954
Eric Laurent6b446ce2019-12-13 10:56:31 -08002955// EffectCallbackInterface implementation
2956status_t AudioFlinger::EffectChain::EffectCallback::createEffectHal(
2957 const effect_uuid_t *pEffectUuid, int32_t sessionId, int32_t deviceId,
2958 sp<EffectHalInterface> *effect) {
2959 status_t status = NO_INIT;
Andy Hungba8e52b2023-05-11 14:33:03 -07002960 const sp<EffectsFactoryHalInterface> effectsFactory =
2961 EffectConfiguration::getEffectsFactoryHal();
Eric Laurent6b446ce2019-12-13 10:56:31 -08002962 if (effectsFactory != 0) {
2963 status = effectsFactory->createEffect(pEffectUuid, sessionId, io(), deviceId, effect);
2964 }
2965 return status;
2966}
2967
2968bool AudioFlinger::EffectChain::EffectCallback::updateOrphanEffectChains(
Eric Laurent41709552019-12-16 19:34:05 -08002969 const sp<AudioFlinger::EffectBase>& effect) {
Eric Laurent41709552019-12-16 19:34:05 -08002970 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
Andy Hung6626a012021-01-12 13:38:00 -08002971 return mAudioFlinger.updateOrphanEffectChains(effect->asEffectModule());
Eric Laurent6b446ce2019-12-13 10:56:31 -08002972}
2973
2974status_t AudioFlinger::EffectChain::EffectCallback::allocateHalBuffer(
2975 size_t size, sp<EffectBufferHalInterface>* buffer) {
Andy Hung6626a012021-01-12 13:38:00 -08002976 return mAudioFlinger.mEffectsFactoryHal->allocateBuffer(size, buffer);
Eric Laurent6b446ce2019-12-13 10:56:31 -08002977}
2978
2979status_t AudioFlinger::EffectChain::EffectCallback::addEffectToHal(
Andy Hung920f6572022-10-06 12:09:49 -07002980 const sp<EffectHalInterface>& effect) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08002981 status_t result = NO_INIT;
Andy Hung328d6772021-01-12 12:32:21 -08002982 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08002983 if (t == nullptr) {
2984 return result;
2985 }
2986 sp <StreamHalInterface> st = t->stream();
2987 if (st == nullptr) {
2988 return result;
2989 }
2990 result = st->addEffect(effect);
2991 ALOGE_IF(result != OK, "Error when adding effect: %d", result);
2992 return result;
2993}
2994
2995status_t AudioFlinger::EffectChain::EffectCallback::removeEffectFromHal(
Andy Hung920f6572022-10-06 12:09:49 -07002996 const sp<EffectHalInterface>& effect) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08002997 status_t result = NO_INIT;
Andy Hung328d6772021-01-12 12:32:21 -08002998 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08002999 if (t == nullptr) {
3000 return result;
3001 }
3002 sp <StreamHalInterface> st = t->stream();
3003 if (st == nullptr) {
3004 return result;
3005 }
3006 result = st->removeEffect(effect);
3007 ALOGE_IF(result != OK, "Error when removing effect: %d", result);
3008 return result;
3009}
3010
3011audio_io_handle_t AudioFlinger::EffectChain::EffectCallback::io() const {
Andy Hung328d6772021-01-12 12:32:21 -08003012 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003013 if (t == nullptr) {
3014 return AUDIO_IO_HANDLE_NONE;
3015 }
3016 return t->id();
3017}
3018
3019bool AudioFlinger::EffectChain::EffectCallback::isOutput() const {
Andy Hung328d6772021-01-12 12:32:21 -08003020 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003021 if (t == nullptr) {
3022 return true;
3023 }
3024 return t->isOutput();
3025}
3026
3027bool AudioFlinger::EffectChain::EffectCallback::isOffload() const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003028 return mThreadType == ThreadBase::OFFLOAD;
Eric Laurent6b446ce2019-12-13 10:56:31 -08003029}
3030
3031bool AudioFlinger::EffectChain::EffectCallback::isOffloadOrDirect() const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003032 return mThreadType == ThreadBase::OFFLOAD || mThreadType == ThreadBase::DIRECT;
Eric Laurent6b446ce2019-12-13 10:56:31 -08003033}
3034
3035bool AudioFlinger::EffectChain::EffectCallback::isOffloadOrMmap() const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003036 switch (mThreadType) {
3037 case ThreadBase::OFFLOAD:
3038 case ThreadBase::MMAP_PLAYBACK:
3039 case ThreadBase::MMAP_CAPTURE:
3040 return true;
3041 default:
Eric Laurent6b446ce2019-12-13 10:56:31 -08003042 return false;
3043 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003044}
3045
3046bool AudioFlinger::EffectChain::EffectCallback::isSpatializer() const {
3047 return mThreadType == ThreadBase::SPATIALIZER;
Eric Laurent6b446ce2019-12-13 10:56:31 -08003048}
3049
3050uint32_t AudioFlinger::EffectChain::EffectCallback::sampleRate() const {
Andy Hung328d6772021-01-12 12:32:21 -08003051 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003052 if (t == nullptr) {
3053 return 0;
3054 }
3055 return t->sampleRate();
3056}
3057
Eric Laurentf1f22e72021-07-13 14:04:14 +02003058audio_channel_mask_t AudioFlinger::EffectChain::EffectCallback::inChannelMask(int id) const {
3059 sp<ThreadBase> t = thread().promote();
3060 if (t == nullptr) {
3061 return AUDIO_CHANNEL_NONE;
3062 }
3063 sp<EffectChain> c = chain().promote();
3064 if (c == nullptr) {
3065 return AUDIO_CHANNEL_NONE;
3066 }
3067
Eric Laurentb62d0362021-10-26 17:40:18 +02003068 if (mThreadType == ThreadBase::SPATIALIZER) {
3069 if (c->sessionId() == AUDIO_SESSION_OUTPUT_STAGE) {
3070 if (c->isFirstEffect(id)) {
3071 return t->mixerChannelMask();
3072 } else {
3073 return t->channelMask();
3074 }
3075 } else if (!audio_is_global_session(c->sessionId())) {
3076 if ((t->hasAudioSession_l(c->sessionId()) & ThreadBase::SPATIALIZED_SESSION) != 0) {
3077 return t->mixerChannelMask();
3078 } else {
3079 return t->channelMask();
3080 }
3081 } else {
3082 return t->channelMask();
3083 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003084 } else {
3085 return t->channelMask();
3086 }
3087}
3088
3089uint32_t AudioFlinger::EffectChain::EffectCallback::inChannelCount(int id) const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003090 return audio_channel_count_from_out_mask(inChannelMask(id));
Eric Laurentf1f22e72021-07-13 14:04:14 +02003091}
3092
3093audio_channel_mask_t AudioFlinger::EffectChain::EffectCallback::outChannelMask() const {
Andy Hung328d6772021-01-12 12:32:21 -08003094 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003095 if (t == nullptr) {
3096 return AUDIO_CHANNEL_NONE;
3097 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003098 sp<EffectChain> c = chain().promote();
3099 if (c == nullptr) {
3100 return AUDIO_CHANNEL_NONE;
3101 }
3102
3103 if (mThreadType == ThreadBase::SPATIALIZER) {
3104 if (!audio_is_global_session(c->sessionId())) {
3105 if ((t->hasAudioSession_l(c->sessionId()) & ThreadBase::SPATIALIZED_SESSION) != 0) {
3106 return t->mixerChannelMask();
3107 } else {
3108 return t->channelMask();
3109 }
3110 } else {
3111 return t->channelMask();
3112 }
3113 } else {
3114 return t->channelMask();
3115 }
Eric Laurent6b446ce2019-12-13 10:56:31 -08003116}
3117
Eric Laurentf1f22e72021-07-13 14:04:14 +02003118uint32_t AudioFlinger::EffectChain::EffectCallback::outChannelCount() const {
Eric Laurentb62d0362021-10-26 17:40:18 +02003119 return audio_channel_count_from_out_mask(outChannelMask());
Eric Laurent6b446ce2019-12-13 10:56:31 -08003120}
3121
jiabineb3bda02020-06-30 14:07:03 -07003122audio_channel_mask_t AudioFlinger::EffectChain::EffectCallback::hapticChannelMask() const {
Andy Hung328d6772021-01-12 12:32:21 -08003123 sp<ThreadBase> t = thread().promote();
jiabineb3bda02020-06-30 14:07:03 -07003124 if (t == nullptr) {
3125 return AUDIO_CHANNEL_NONE;
3126 }
3127 return t->hapticChannelMask();
3128}
3129
Eric Laurent6b446ce2019-12-13 10:56:31 -08003130size_t AudioFlinger::EffectChain::EffectCallback::frameCount() const {
Andy Hung328d6772021-01-12 12:32:21 -08003131 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003132 if (t == nullptr) {
3133 return 0;
3134 }
3135 return t->frameCount();
3136}
3137
Andy Hung920f6572022-10-06 12:09:49 -07003138uint32_t AudioFlinger::EffectChain::EffectCallback::latency() const
3139NO_THREAD_SAFETY_ANALYSIS // latency_l() access
3140{
Andy Hung328d6772021-01-12 12:32:21 -08003141 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003142 if (t == nullptr) {
3143 return 0;
3144 }
Andy Hung920f6572022-10-06 12:09:49 -07003145 // TODO(b/275956781) - this requires the thread lock.
Eric Laurent6b446ce2019-12-13 10:56:31 -08003146 return t->latency_l();
3147}
3148
Andy Hung920f6572022-10-06 12:09:49 -07003149void AudioFlinger::EffectChain::EffectCallback::setVolumeForOutput(float left, float right) const
3150NO_THREAD_SAFETY_ANALYSIS // setVolumeForOutput_l() access
3151{
Andy Hung328d6772021-01-12 12:32:21 -08003152 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003153 if (t == nullptr) {
3154 return;
3155 }
3156 t->setVolumeForOutput_l(left, right);
3157}
3158
3159void AudioFlinger::EffectChain::EffectCallback::checkSuspendOnEffectEnabled(
Eric Laurent41709552019-12-16 19:34:05 -08003160 const sp<EffectBase>& effect, bool enabled, bool threadLocked) {
Andy Hung328d6772021-01-12 12:32:21 -08003161 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003162 if (t == nullptr) {
3163 return;
3164 }
3165 t->checkSuspendOnEffectEnabled(enabled, effect->sessionId(), threadLocked);
3166
Andy Hung328d6772021-01-12 12:32:21 -08003167 sp<EffectChain> c = chain().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003168 if (c == nullptr) {
3169 return;
3170 }
Eric Laurent41709552019-12-16 19:34:05 -08003171 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
3172 c->checkSuspendOnEffectEnabled(effect->asEffectModule(), enabled);
Eric Laurent6b446ce2019-12-13 10:56:31 -08003173}
3174
Eric Laurent41709552019-12-16 19:34:05 -08003175void AudioFlinger::EffectChain::EffectCallback::onEffectEnable(const sp<EffectBase>& effect) {
Andy Hung328d6772021-01-12 12:32:21 -08003176 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003177 if (t == nullptr) {
3178 return;
3179 }
Eric Laurent41709552019-12-16 19:34:05 -08003180 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
3181 t->onEffectEnable(effect->asEffectModule());
Eric Laurent6b446ce2019-12-13 10:56:31 -08003182}
3183
Eric Laurent41709552019-12-16 19:34:05 -08003184void AudioFlinger::EffectChain::EffectCallback::onEffectDisable(const sp<EffectBase>& effect) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003185 checkSuspendOnEffectEnabled(effect, false, false /*threadLocked*/);
3186
Andy Hung328d6772021-01-12 12:32:21 -08003187 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003188 if (t == nullptr) {
3189 return;
3190 }
3191 t->onEffectDisable();
3192}
3193
3194bool AudioFlinger::EffectChain::EffectCallback::disconnectEffectHandle(EffectHandle *handle,
3195 bool unpinIfLast) {
Andy Hung328d6772021-01-12 12:32:21 -08003196 sp<ThreadBase> t = thread().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003197 if (t == nullptr) {
3198 return false;
3199 }
3200 t->disconnectEffectHandle(handle, unpinIfLast);
3201 return true;
3202}
3203
3204void AudioFlinger::EffectChain::EffectCallback::resetVolume() {
Andy Hung328d6772021-01-12 12:32:21 -08003205 sp<EffectChain> c = chain().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003206 if (c == nullptr) {
3207 return;
3208 }
3209 c->resetVolume_l();
3210
3211}
3212
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003213product_strategy_t AudioFlinger::EffectChain::EffectCallback::strategy() const {
Andy Hung328d6772021-01-12 12:32:21 -08003214 sp<EffectChain> c = chain().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003215 if (c == nullptr) {
3216 return PRODUCT_STRATEGY_NONE;
3217 }
3218 return c->strategy();
3219}
3220
3221int32_t AudioFlinger::EffectChain::EffectCallback::activeTrackCnt() const {
Andy Hung328d6772021-01-12 12:32:21 -08003222 sp<EffectChain> c = chain().promote();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003223 if (c == nullptr) {
3224 return 0;
3225 }
3226 return c->activeTrackCnt();
3227}
3228
Eric Laurentb82e6b72019-11-22 17:25:04 -08003229
3230#undef LOG_TAG
3231#define LOG_TAG "AudioFlinger::DeviceEffectProxy"
3232
3233status_t AudioFlinger::DeviceEffectProxy::setEnabled(bool enabled, bool fromHandle)
3234{
3235 status_t status = EffectBase::setEnabled(enabled, fromHandle);
3236 Mutex::Autolock _l(mProxyLock);
3237 if (status == NO_ERROR) {
3238 for (auto& handle : mEffectHandles) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003239 Status bs;
Eric Laurentb82e6b72019-11-22 17:25:04 -08003240 if (enabled) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003241 bs = handle.second->enable(&status);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003242 } else {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003243 bs = handle.second->disable(&status);
3244 }
3245 if (!bs.isOk()) {
Andy Hung1131b6e2020-12-08 20:47:45 -08003246 status = statusTFromBinderStatus(bs);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003247 }
3248 }
3249 }
3250 ALOGV("%s enable %d status %d", __func__, enabled, status);
3251 return status;
3252}
3253
3254status_t AudioFlinger::DeviceEffectProxy::init(
3255 const std::map <audio_patch_handle_t, PatchPanel::Patch>& patches) {
3256//For all audio patches
3257//If src or sink device match
3258//If the effect is HW accelerated
3259// if no corresponding effect module
3260// Create EffectModule: mHalEffect
3261//Create and attach EffectHandle
3262//If the effect is not HW accelerated and the patch sink or src is a mixer port
3263// Create Effect on patch input or output thread on session -1
3264//Add EffectHandle to EffectHandle map of Effect Proxy:
3265 ALOGV("%s device type %d address %s", __func__, mDevice.mType, mDevice.getAddress());
3266 status_t status = NO_ERROR;
3267 for (auto &patch : patches) {
3268 status = onCreatePatch(patch.first, patch.second);
3269 ALOGV("%s onCreatePatch status %d", __func__, status);
3270 if (status == BAD_VALUE) {
3271 return status;
3272 }
3273 }
3274 return status;
3275}
3276
3277status_t AudioFlinger::DeviceEffectProxy::onCreatePatch(
3278 audio_patch_handle_t patchHandle, const AudioFlinger::PatchPanel::Patch& patch) {
3279 status_t status = NAME_NOT_FOUND;
3280 sp<EffectHandle> handle;
3281 // only consider source[0] as this is the only "true" source of a patch
3282 status = checkPort(patch, &patch.mAudioPatch.sources[0], &handle);
3283 ALOGV("%s source checkPort status %d", __func__, status);
3284 for (uint32_t i = 0; i < patch.mAudioPatch.num_sinks && status == NAME_NOT_FOUND; i++) {
3285 status = checkPort(patch, &patch.mAudioPatch.sinks[i], &handle);
3286 ALOGV("%s sink %d checkPort status %d", __func__, i, status);
3287 }
3288 if (status == NO_ERROR || status == ALREADY_EXISTS) {
3289 Mutex::Autolock _l(mProxyLock);
3290 mEffectHandles.emplace(patchHandle, handle);
3291 }
3292 ALOGW_IF(status == BAD_VALUE,
3293 "%s cannot attach effect %s on patch %d", __func__, mDescriptor.name, patchHandle);
3294
3295 return status;
3296}
3297
3298status_t AudioFlinger::DeviceEffectProxy::checkPort(const PatchPanel::Patch& patch,
3299 const struct audio_port_config *port, sp <EffectHandle> *handle) {
3300
3301 ALOGV("%s type %d device type %d address %s device ID %d patch.isSoftware() %d",
3302 __func__, port->type, port->ext.device.type,
3303 port->ext.device.address, port->id, patch.isSoftware());
Shunkai Yaob009ad52023-05-05 22:43:24 +00003304 if (port->type != AUDIO_PORT_TYPE_DEVICE || port->ext.device.type != mDevice.mType ||
3305 port->ext.device.address != mDevice.address()) {
3306 return NAME_NOT_FOUND;
3307 }
3308 if (((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) &&
3309 (audio_port_config_has_input_direction(port))) {
3310 ALOGI("%s don't create postprocessing effect on record port", __func__);
3311 return NAME_NOT_FOUND;
3312 }
3313 if (((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) &&
3314 (!audio_port_config_has_input_direction(port))) {
3315 ALOGI("%s don't create preprocessing effect on playback port", __func__);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003316 return NAME_NOT_FOUND;
3317 }
3318 status_t status = NAME_NOT_FOUND;
3319
3320 if (mDescriptor.flags & EFFECT_FLAG_HW_ACC_TUNNEL) {
3321 Mutex::Autolock _l(mProxyLock);
3322 mDevicePort = *port;
3323 mHalEffect = new EffectModule(mMyCallback,
3324 const_cast<effect_descriptor_t *>(&mDescriptor),
3325 mMyCallback->newEffectId(), AUDIO_SESSION_DEVICE,
3326 false /* pinned */, port->id);
3327 if (audio_is_input_device(mDevice.mType)) {
3328 mHalEffect->setInputDevice(mDevice);
3329 } else {
3330 mHalEffect->setDevices({mDevice});
3331 }
Eric Laurent76c89f32021-12-03 17:13:23 +01003332 mHalEffect->configure();
3333
Eric Laurentde8caf42021-08-11 17:19:25 +02003334 *handle = new EffectHandle(mHalEffect, nullptr, nullptr, 0 /*priority*/,
3335 mNotifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003336 status = (*handle)->initCheck();
3337 if (status == OK) {
3338 status = mHalEffect->addHandle((*handle).get());
3339 } else {
3340 mHalEffect.clear();
3341 mDevicePort.id = AUDIO_PORT_HANDLE_NONE;
3342 }
3343 } else if (patch.isSoftware() || patch.thread().promote() != nullptr) {
3344 sp <ThreadBase> thread;
3345 if (audio_port_config_has_input_direction(port)) {
3346 if (patch.isSoftware()) {
3347 thread = patch.mRecord.thread();
3348 } else {
3349 thread = patch.thread().promote();
3350 }
3351 } else {
3352 if (patch.isSoftware()) {
3353 thread = patch.mPlayback.thread();
3354 } else {
3355 thread = patch.thread().promote();
3356 }
3357 }
3358 int enabled;
3359 *handle = thread->createEffect_l(nullptr, nullptr, 0, AUDIO_SESSION_DEVICE,
3360 const_cast<effect_descriptor_t *>(&mDescriptor),
Eric Laurentde8caf42021-08-11 17:19:25 +02003361 &enabled, &status, false, false /*probe*/,
3362 mNotifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003363 ALOGV("%s thread->createEffect_l status %d", __func__, status);
3364 } else {
3365 status = BAD_VALUE;
3366 }
Shunkai Yaob009ad52023-05-05 22:43:24 +00003367
Eric Laurentb82e6b72019-11-22 17:25:04 -08003368 if (status == NO_ERROR || status == ALREADY_EXISTS) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003369 Status bs;
Eric Laurentb82e6b72019-11-22 17:25:04 -08003370 if (isEnabled()) {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003371 bs = (*handle)->enable(&status);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003372 } else {
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003373 bs = (*handle)->disable(&status);
3374 }
3375 if (!bs.isOk()) {
Andy Hung1131b6e2020-12-08 20:47:45 -08003376 status = statusTFromBinderStatus(bs);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003377 }
3378 }
3379 return status;
3380}
3381
3382void AudioFlinger::DeviceEffectProxy::onReleasePatch(audio_patch_handle_t patchHandle) {
Eric Laurent76c89f32021-12-03 17:13:23 +01003383 sp<EffectHandle> effect;
3384 {
3385 Mutex::Autolock _l(mProxyLock);
3386 if (mEffectHandles.find(patchHandle) != mEffectHandles.end()) {
3387 effect = mEffectHandles.at(patchHandle);
3388 mEffectHandles.erase(patchHandle);
3389 }
3390 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08003391}
3392
3393
3394size_t AudioFlinger::DeviceEffectProxy::removeEffect(const sp<EffectModule>& effect)
3395{
3396 Mutex::Autolock _l(mProxyLock);
3397 if (effect == mHalEffect) {
Eric Laurent76c89f32021-12-03 17:13:23 +01003398 mHalEffect->release_l();
Eric Laurentb82e6b72019-11-22 17:25:04 -08003399 mHalEffect.clear();
3400 mDevicePort.id = AUDIO_PORT_HANDLE_NONE;
3401 }
3402 return mHalEffect == nullptr ? 0 : 1;
3403}
3404
3405status_t AudioFlinger::DeviceEffectProxy::addEffectToHal(
Andy Hung920f6572022-10-06 12:09:49 -07003406 const sp<EffectHalInterface>& effect) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003407 if (mHalEffect == nullptr) {
3408 return NO_INIT;
3409 }
Mikhail Naganovd2c7f852023-06-14 18:00:13 -07003410 return mManagerCallback->addEffectToHal(&mDevicePort, effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003411}
3412
3413status_t AudioFlinger::DeviceEffectProxy::removeEffectFromHal(
Andy Hung920f6572022-10-06 12:09:49 -07003414 const sp<EffectHalInterface>& effect) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003415 if (mHalEffect == nullptr) {
3416 return NO_INIT;
3417 }
Mikhail Naganovd2c7f852023-06-14 18:00:13 -07003418 return mManagerCallback->removeEffectFromHal(&mDevicePort, effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003419}
3420
3421bool AudioFlinger::DeviceEffectProxy::isOutput() const {
3422 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE) {
3423 return mDevicePort.role == AUDIO_PORT_ROLE_SINK;
3424 }
3425 return true;
3426}
3427
3428uint32_t AudioFlinger::DeviceEffectProxy::sampleRate() const {
3429 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE &&
3430 (mDevicePort.config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) != 0) {
3431 return mDevicePort.sample_rate;
3432 }
3433 return DEFAULT_OUTPUT_SAMPLE_RATE;
3434}
3435
3436audio_channel_mask_t AudioFlinger::DeviceEffectProxy::channelMask() const {
3437 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE &&
3438 (mDevicePort.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) != 0) {
3439 return mDevicePort.channel_mask;
3440 }
3441 return AUDIO_CHANNEL_OUT_STEREO;
3442}
3443
3444uint32_t AudioFlinger::DeviceEffectProxy::channelCount() const {
3445 if (isOutput()) {
3446 return audio_channel_count_from_out_mask(channelMask());
3447 }
3448 return audio_channel_count_from_in_mask(channelMask());
3449}
3450
Andy Hung920f6572022-10-06 12:09:49 -07003451void AudioFlinger::DeviceEffectProxy::dump(int fd, int spaces)
3452NO_THREAD_SAFETY_ANALYSIS // conditional try lock
3453{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003454 const Vector<String16> args;
3455 EffectBase::dump(fd, args);
3456
3457 const bool locked = dumpTryLock(mProxyLock);
3458 if (!locked) {
3459 String8 result("DeviceEffectProxy may be deadlocked\n");
3460 write(fd, result.string(), result.size());
3461 }
3462
3463 String8 outStr;
3464 if (mHalEffect != nullptr) {
3465 outStr.appendFormat("%*sHAL Effect Id: %d\n", spaces, "", mHalEffect->id());
3466 } else {
3467 outStr.appendFormat("%*sNO HAL Effect\n", spaces, "");
3468 }
3469 write(fd, outStr.string(), outStr.size());
3470 outStr.clear();
3471
3472 outStr.appendFormat("%*sSub Effects:\n", spaces, "");
3473 write(fd, outStr.string(), outStr.size());
3474 outStr.clear();
3475
3476 for (const auto& iter : mEffectHandles) {
3477 outStr.appendFormat("%*sEffect for patch handle %d:\n", spaces + 2, "", iter.first);
3478 write(fd, outStr.string(), outStr.size());
3479 outStr.clear();
3480 sp<EffectBase> effect = iter.second->effect().promote();
3481 if (effect != nullptr) {
3482 effect->dump(fd, args);
3483 }
3484 }
3485
3486 if (locked) {
3487 mLock.unlock();
3488 }
3489}
3490
3491#undef LOG_TAG
3492#define LOG_TAG "AudioFlinger::DeviceEffectProxy::ProxyCallback"
3493
3494int AudioFlinger::DeviceEffectProxy::ProxyCallback::newEffectId() {
3495 return mManagerCallback->newEffectId();
3496}
3497
3498
3499bool AudioFlinger::DeviceEffectProxy::ProxyCallback::disconnectEffectHandle(
3500 EffectHandle *handle, bool unpinIfLast) {
3501 sp<EffectBase> effectBase = handle->effect().promote();
3502 if (effectBase == nullptr) {
3503 return false;
3504 }
3505
3506 sp<EffectModule> effect = effectBase->asEffectModule();
3507 if (effect == nullptr) {
3508 return false;
3509 }
3510
3511 // restore suspended effects if the disconnected handle was enabled and the last one.
3512 bool remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
3513 if (remove) {
3514 sp<DeviceEffectProxy> proxy = mProxy.promote();
3515 if (proxy != nullptr) {
3516 proxy->removeEffect(effect);
3517 }
3518 if (handle->enabled()) {
3519 effectBase->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
3520 }
3521 }
3522 return true;
3523}
3524
3525status_t AudioFlinger::DeviceEffectProxy::ProxyCallback::createEffectHal(
3526 const effect_uuid_t *pEffectUuid, int32_t sessionId, int32_t deviceId,
3527 sp<EffectHalInterface> *effect) {
3528 return mManagerCallback->createEffectHal(pEffectUuid, sessionId, deviceId, effect);
3529}
3530
3531status_t AudioFlinger::DeviceEffectProxy::ProxyCallback::addEffectToHal(
Andy Hung920f6572022-10-06 12:09:49 -07003532 const sp<EffectHalInterface>& effect) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003533 sp<DeviceEffectProxy> proxy = mProxy.promote();
3534 if (proxy == nullptr) {
3535 return NO_INIT;
3536 }
3537 return proxy->addEffectToHal(effect);
3538}
3539
3540status_t AudioFlinger::DeviceEffectProxy::ProxyCallback::removeEffectFromHal(
Andy Hung920f6572022-10-06 12:09:49 -07003541 const sp<EffectHalInterface>& effect) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003542 sp<DeviceEffectProxy> proxy = mProxy.promote();
3543 if (proxy == nullptr) {
3544 return NO_INIT;
3545 }
Eric Laurent76c89f32021-12-03 17:13:23 +01003546 return proxy->removeEffectFromHal(effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003547}
3548
3549bool AudioFlinger::DeviceEffectProxy::ProxyCallback::isOutput() const {
3550 sp<DeviceEffectProxy> proxy = mProxy.promote();
3551 if (proxy == nullptr) {
3552 return true;
3553 }
3554 return proxy->isOutput();
3555}
3556
3557uint32_t AudioFlinger::DeviceEffectProxy::ProxyCallback::sampleRate() const {
3558 sp<DeviceEffectProxy> proxy = mProxy.promote();
3559 if (proxy == nullptr) {
3560 return DEFAULT_OUTPUT_SAMPLE_RATE;
3561 }
3562 return proxy->sampleRate();
3563}
3564
Eric Laurentf1f22e72021-07-13 14:04:14 +02003565audio_channel_mask_t AudioFlinger::DeviceEffectProxy::ProxyCallback::inChannelMask(
3566 int id __unused) const {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003567 sp<DeviceEffectProxy> proxy = mProxy.promote();
3568 if (proxy == nullptr) {
3569 return AUDIO_CHANNEL_OUT_STEREO;
3570 }
3571 return proxy->channelMask();
3572}
3573
Eric Laurentf1f22e72021-07-13 14:04:14 +02003574uint32_t AudioFlinger::DeviceEffectProxy::ProxyCallback::inChannelCount(int id __unused) const {
3575 sp<DeviceEffectProxy> proxy = mProxy.promote();
3576 if (proxy == nullptr) {
3577 return 2;
3578 }
3579 return proxy->channelCount();
3580}
3581
3582audio_channel_mask_t AudioFlinger::DeviceEffectProxy::ProxyCallback::outChannelMask() const {
3583 sp<DeviceEffectProxy> proxy = mProxy.promote();
3584 if (proxy == nullptr) {
3585 return AUDIO_CHANNEL_OUT_STEREO;
3586 }
3587 return proxy->channelMask();
3588}
3589
3590uint32_t AudioFlinger::DeviceEffectProxy::ProxyCallback::outChannelCount() const {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003591 sp<DeviceEffectProxy> proxy = mProxy.promote();
3592 if (proxy == nullptr) {
3593 return 2;
3594 }
3595 return proxy->channelCount();
3596}
3597
Eric Laurent76c89f32021-12-03 17:13:23 +01003598void AudioFlinger::DeviceEffectProxy::ProxyCallback::onEffectEnable(
3599 const sp<EffectBase>& effectBase) {
3600 sp<EffectModule> effect = effectBase->asEffectModule();
3601 if (effect == nullptr) {
3602 return;
3603 }
3604 effect->start();
3605}
3606
3607void AudioFlinger::DeviceEffectProxy::ProxyCallback::onEffectDisable(
3608 const sp<EffectBase>& effectBase) {
3609 sp<EffectModule> effect = effectBase->asEffectModule();
3610 if (effect == nullptr) {
3611 return;
3612 }
3613 effect->stop();
3614}
3615
Glenn Kasten63238ef2015-03-02 15:50:29 -08003616} // namespace android