1 /*
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
22 #include "Effects.h"
23
24 #include "Client.h"
25 #include "EffectConfiguration.h"
26
27 #include <afutils/FallibleLockGuard.h>
28 #include <audio_utils/channels.h>
29 #include <audio_utils/primitives.h>
30 #include <media/AudioCommonTypes.h>
31 #include <media/AudioContainers.h>
32 #include <media/AudioDeviceTypeAddr.h>
33 #include <media/AudioEffect.h>
34 #include <media/EffectClientAsyncProxy.h>
35 #include <media/ShmemCompat.h>
36 #include <media/TypeConverter.h>
37 #include <media/audiohal/EffectHalInterface.h>
38 #include <media/audiohal/EffectsFactoryHalInterface.h>
39 #include <mediautils/MethodStatistics.h>
40 #include <mediautils/ServiceUtilities.h>
41 #include <mediautils/TimeCheck.h>
42 #include <system/audio_effects/audio_effects_utils.h>
43 #include <system/audio_effects/effect_aec.h>
44 #include <system/audio_effects/effect_downmix.h>
45 #include <system/audio_effects/effect_dynamicsprocessing.h>
46 #include <system/audio_effects/effect_hapticgenerator.h>
47 #include <system/audio_effects/effect_ns.h>
48 #include <system/audio_effects/effect_spatializer.h>
49 #include <system/audio_effects/effect_visualizer.h>
50 #include <utils/Log.h>
51
52 #include <algorithm>
53
54 // ----------------------------------------------------------------------------
55
56 // Note: the following macro is used for extremely verbose logging message. In
57 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
58 // 0; but one side effect of this is to turn all LOGV's as well. Some messages
59 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
60 // turned on. Do not uncomment the #def below unless you really know what you
61 // are doing and want to see all of the extremely verbose messages.
62 //#define VERY_VERY_VERBOSE_LOGGING
63 #ifdef VERY_VERY_VERBOSE_LOGGING
64 #define ALOGVV ALOGV
65 #else
66 #define ALOGVV(a...) do { } while(0)
67 #endif
68
69 #define DEFAULT_OUTPUT_SAMPLE_RATE 48000
70
71 namespace android {
72
73 using aidl_utils::statusTFromBinderStatus;
74 using android::effect::utils::EffectParamWriter;
75 using audioflinger::EffectConfiguration;
76 using binder::Status;
77
78 namespace {
79
80 // Append a POD value into a vector of bytes.
81 template<typename T>
appendToBuffer(const T & value,std::vector<uint8_t> * buffer)82 void appendToBuffer(const T& value, std::vector<uint8_t>* buffer) {
83 const uint8_t* ar(reinterpret_cast<const uint8_t*>(&value));
84 buffer->insert(buffer->end(), ar, ar + sizeof(T));
85 }
86
87 // Write a POD value into a vector of bytes (clears the previous buffer
88 // content).
89 template<typename T>
writeToBuffer(const T & value,std::vector<uint8_t> * buffer)90 void writeToBuffer(const T& value, std::vector<uint8_t>* buffer) {
91 buffer->clear();
92 appendToBuffer(value, buffer);
93 }
94
95 } // namespace
96
97 // ----------------------------------------------------------------------------
98 // EffectBase implementation
99 // ----------------------------------------------------------------------------
100
101 #undef LOG_TAG
102 #define LOG_TAG "EffectBase"
103
EffectBase(const sp<EffectCallbackInterface> & callback,effect_descriptor_t * desc,int id,audio_session_t sessionId,bool pinned)104 EffectBase::EffectBase(const sp<EffectCallbackInterface>& callback,
105 effect_descriptor_t *desc,
106 int id,
107 audio_session_t sessionId,
108 bool pinned)
109 : mPinned(pinned),
110 mCallback(callback), mId(id), mSessionId(sessionId),
111 mDescriptor(*desc)
112 {
113 }
114
115 // must be called with EffectModule::mutex() held
setEnabled_l(bool enabled)116 status_t EffectBase::setEnabled_l(bool enabled)
117 {
118
119 ALOGV("setEnabled %p enabled %d", this, enabled);
120
121 if (enabled != isEnabled()) {
122 switch (mState) {
123 // going from disabled to enabled
124 case IDLE:
125 mState = STARTING;
126 break;
127 case STOPPED:
128 mState = RESTART;
129 break;
130 case STOPPING:
131 mState = ACTIVE;
132 break;
133
134 // going from enabled to disabled
135 case RESTART:
136 mState = STOPPED;
137 break;
138 case STARTING:
139 mState = IDLE;
140 break;
141 case ACTIVE:
142 mState = STOPPING;
143 break;
144 case DESTROYED:
145 return NO_ERROR; // simply ignore as we are being destroyed
146 }
147 for (size_t i = 1; i < mHandles.size(); i++) {
148 IAfEffectHandle *h = mHandles[i];
149 if (h != NULL && !h->disconnected()) {
150 h->setEnabled(enabled);
151 }
152 }
153 }
154 return NO_ERROR;
155 }
156
setEnabled(bool enabled,bool fromHandle)157 status_t EffectBase::setEnabled(bool enabled, bool fromHandle)
158 {
159 status_t status;
160 {
161 audio_utils::lock_guard _l(mutex());
162 status = setEnabled_l(enabled);
163 }
164 if (fromHandle) {
165 if (enabled) {
166 if (status != NO_ERROR) {
167 getCallback()->checkSuspendOnEffectEnabled(this, false, false /*threadLocked*/);
168 } else {
169 getCallback()->onEffectEnable(this);
170 }
171 } else {
172 getCallback()->onEffectDisable(this);
173 }
174 }
175 return status;
176 }
177
isEnabled() const178 bool EffectBase::isEnabled() const
179 {
180 switch (mState) {
181 case RESTART:
182 case STARTING:
183 case ACTIVE:
184 return true;
185 case IDLE:
186 case STOPPING:
187 case STOPPED:
188 case DESTROYED:
189 default:
190 return false;
191 }
192 }
193
setSuspended(bool suspended)194 void EffectBase::setSuspended(bool suspended)
195 {
196 audio_utils::lock_guard _l(mutex());
197 mSuspended = suspended;
198 }
199
suspended() const200 bool EffectBase::suspended() const
201 {
202 audio_utils::lock_guard _l(mutex());
203 return mSuspended;
204 }
205
addHandle(IAfEffectHandle * handle)206 status_t EffectBase::addHandle(IAfEffectHandle *handle)
207 {
208 status_t status;
209
210 audio_utils::lock_guard _l(mutex());
211 int priority = handle->priority();
212 size_t size = mHandles.size();
213 IAfEffectHandle *controlHandle = nullptr;
214 size_t i;
215 for (i = 0; i < size; i++) {
216 IAfEffectHandle *h = mHandles[i];
217 if (h == NULL || h->disconnected()) {
218 continue;
219 }
220 // first non destroyed handle is considered in control
221 if (controlHandle == NULL) {
222 controlHandle = h;
223 }
224 if (h->priority() <= priority) {
225 break;
226 }
227 }
228 // if inserted in first place, move effect control from previous owner to this handle
229 if (i == 0) {
230 bool enabled = false;
231 if (controlHandle != NULL) {
232 enabled = controlHandle->enabled();
233 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
234 }
235 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
236 status = NO_ERROR;
237 } else {
238 status = ALREADY_EXISTS;
239 }
240 ALOGV("addHandle() %p added handle %p in position %zu", this, handle, i);
241 mHandles.insertAt(handle, i);
242 return status;
243 }
244
updatePolicyState()245 status_t EffectBase::updatePolicyState()
246 {
247 status_t status = NO_ERROR;
248 bool doRegister = false;
249 bool registered = false;
250 bool doEnable = false;
251 bool enabled = false;
252 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
253 product_strategy_t strategy = PRODUCT_STRATEGY_NONE;
254
255 {
256 audio_utils::lock_guard _l(mutex());
257
258 if ((isInternal_l() && !mPolicyRegistered)
259 || !getCallback()->isAudioPolicyReady()) {
260 return NO_ERROR;
261 }
262
263 // register effect when first handle is attached and unregister when last handle is removed
264 if (mPolicyRegistered != mHandles.size() > 0) {
265 doRegister = true;
266 mPolicyRegistered = mHandles.size() > 0;
267 if (mPolicyRegistered) {
268 const auto callback = getCallback();
269 io = callback->io();
270 strategy = callback->strategy();
271 }
272 }
273 // enable effect when registered according to enable state requested by controlling handle
274 if (mHandles.size() > 0) {
275 IAfEffectHandle *handle = controlHandle_l();
276 if (handle != nullptr && mPolicyEnabled != handle->enabled()) {
277 doEnable = true;
278 mPolicyEnabled = handle->enabled();
279 }
280 }
281 registered = mPolicyRegistered;
282 enabled = mPolicyEnabled;
283 // The simultaneous release of two EffectHandles with the same EffectModule
284 // may cause us to call this method at the same time.
285 // This may deadlock under some circumstances (b/180941720). Avoid this.
286 if (!doRegister && !(registered && doEnable)) {
287 return NO_ERROR;
288 }
289 }
290 policyMutex().lock();
291 ALOGV("%s name %s id %d session %d doRegister %d registered %d doEnable %d enabled %d",
292 __func__, mDescriptor.name, mId, mSessionId, doRegister, registered, doEnable, enabled);
293 if (doRegister) {
294 if (registered) {
295 status = AudioSystem::registerEffect(
296 &mDescriptor,
297 io,
298 strategy,
299 mSessionId,
300 mId);
301 } else {
302 status = AudioSystem::unregisterEffect(mId);
303 }
304 }
305 if (registered && doEnable) {
306 status = AudioSystem::setEffectEnabled(mId, enabled);
307 }
308 policyMutex().unlock();
309
310 return status;
311 }
312
313
removeHandle(IAfEffectHandle * handle)314 ssize_t EffectBase::removeHandle(IAfEffectHandle *handle)
315 {
316 audio_utils::lock_guard _l(mutex());
317 return removeHandle_l(handle);
318 }
319
removeHandle_l(IAfEffectHandle * handle)320 ssize_t EffectBase::removeHandle_l(IAfEffectHandle *handle)
321 {
322 size_t size = mHandles.size();
323 size_t i;
324 for (i = 0; i < size; i++) {
325 if (mHandles[i] == handle) {
326 break;
327 }
328 }
329 if (i == size) {
330 ALOGW("%s %p handle not found %p", __FUNCTION__, this, handle);
331 return BAD_VALUE;
332 }
333 ALOGV("removeHandle_l() %p removed handle %p in position %zu", this, handle, i);
334
335 mHandles.removeAt(i);
336 // if removed from first place, move effect control from this handle to next in line
337 if (i == 0) {
338 IAfEffectHandle *h = controlHandle_l();
339 if (h != NULL) {
340 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
341 }
342 }
343
344 // Prevent calls to process() and other functions on effect interface from now on.
345 // The effect engine will be released by the destructor when the last strong reference on
346 // this object is released which can happen after next process is called.
347 if (mHandles.size() == 0 && !mPinned) {
348 mState = DESTROYED;
349 }
350
351 return mHandles.size();
352 }
353
354 // must be called with EffectModule::mutex() held
controlHandle_l()355 IAfEffectHandle *EffectBase::controlHandle_l()
356 {
357 // the first valid handle in the list has control over the module
358 for (size_t i = 0; i < mHandles.size(); i++) {
359 IAfEffectHandle *h = mHandles[i];
360 if (h != NULL && !h->disconnected()) {
361 return h;
362 }
363 }
364
365 return NULL;
366 }
367
368 // unsafe method called when the effect parent thread has been destroyed
disconnectHandle(IAfEffectHandle * handle,bool unpinIfLast)369 ssize_t EffectBase::disconnectHandle(IAfEffectHandle *handle, bool unpinIfLast)
370 {
371 const auto callback = getCallback();
372 ALOGV("disconnect() %p handle %p", this, handle);
373 if (callback->disconnectEffectHandle(handle, unpinIfLast)) {
374 return mHandles.size();
375 }
376
377 audio_utils::lock_guard _l(mutex());
378 ssize_t numHandles = removeHandle_l(handle);
379 if ((numHandles == 0) && (!mPinned || unpinIfLast)) {
380 mutex().unlock();
381 callback->updateOrphanEffectChains(this);
382 mutex().lock();
383 }
384 return numHandles;
385 }
386
purgeHandles()387 bool EffectBase::purgeHandles()
388 {
389 bool enabled = false;
390 audio_utils::lock_guard _l(mutex());
391 IAfEffectHandle *handle = controlHandle_l();
392 if (handle != NULL) {
393 enabled = handle->enabled();
394 }
395 mHandles.clear();
396 return enabled;
397 }
398
checkSuspendOnEffectEnabled(bool enabled,bool threadLocked)399 void EffectBase::checkSuspendOnEffectEnabled(bool enabled, bool threadLocked) {
400 getCallback()->checkSuspendOnEffectEnabled(this, enabled, threadLocked);
401 }
402
effectFlagsToString(uint32_t flags)403 static String8 effectFlagsToString(uint32_t flags) {
404 String8 s;
405
406 s.append("conn. mode: ");
407 switch (flags & EFFECT_FLAG_TYPE_MASK) {
408 case EFFECT_FLAG_TYPE_INSERT: s.append("insert"); break;
409 case EFFECT_FLAG_TYPE_AUXILIARY: s.append("auxiliary"); break;
410 case EFFECT_FLAG_TYPE_REPLACE: s.append("replace"); break;
411 case EFFECT_FLAG_TYPE_PRE_PROC: s.append("preproc"); break;
412 case EFFECT_FLAG_TYPE_POST_PROC: s.append("postproc"); break;
413 default: s.append("unknown/reserved"); break;
414 }
415 s.append(", ");
416
417 s.append("insert pref: ");
418 switch (flags & EFFECT_FLAG_INSERT_MASK) {
419 case EFFECT_FLAG_INSERT_ANY: s.append("any"); break;
420 case EFFECT_FLAG_INSERT_FIRST: s.append("first"); break;
421 case EFFECT_FLAG_INSERT_LAST: s.append("last"); break;
422 case EFFECT_FLAG_INSERT_EXCLUSIVE: s.append("exclusive"); break;
423 default: s.append("unknown/reserved"); break;
424 }
425 s.append(", ");
426
427 s.append("volume mgmt: ");
428 switch (flags & EFFECT_FLAG_VOLUME_MASK) {
429 case EFFECT_FLAG_VOLUME_NONE: s.append("none"); break;
430 case EFFECT_FLAG_VOLUME_CTRL: s.append("implements control"); break;
431 case EFFECT_FLAG_VOLUME_IND: s.append("requires indication"); break;
432 case EFFECT_FLAG_VOLUME_MONITOR: s.append("monitors volume"); break;
433 default: s.append("unknown/reserved"); break;
434 }
435 s.append(", ");
436
437 uint32_t devind = flags & EFFECT_FLAG_DEVICE_MASK;
438 if (devind) {
439 s.append("device indication: ");
440 switch (devind) {
441 case EFFECT_FLAG_DEVICE_IND: s.append("requires updates"); break;
442 default: s.append("unknown/reserved"); break;
443 }
444 s.append(", ");
445 }
446
447 s.append("input mode: ");
448 switch (flags & EFFECT_FLAG_INPUT_MASK) {
449 case EFFECT_FLAG_INPUT_DIRECT: s.append("direct"); break;
450 case EFFECT_FLAG_INPUT_PROVIDER: s.append("provider"); break;
451 case EFFECT_FLAG_INPUT_BOTH: s.append("direct+provider"); break;
452 default: s.append("not set"); break;
453 }
454 s.append(", ");
455
456 s.append("output mode: ");
457 switch (flags & EFFECT_FLAG_OUTPUT_MASK) {
458 case EFFECT_FLAG_OUTPUT_DIRECT: s.append("direct"); break;
459 case EFFECT_FLAG_OUTPUT_PROVIDER: s.append("provider"); break;
460 case EFFECT_FLAG_OUTPUT_BOTH: s.append("direct+provider"); break;
461 default: s.append("not set"); break;
462 }
463 s.append(", ");
464
465 uint32_t accel = flags & EFFECT_FLAG_HW_ACC_MASK;
466 if (accel) {
467 s.append("hardware acceleration: ");
468 switch (accel) {
469 case EFFECT_FLAG_HW_ACC_SIMPLE: s.append("non-tunneled"); break;
470 case EFFECT_FLAG_HW_ACC_TUNNEL: s.append("tunneled"); break;
471 default: s.append("unknown/reserved"); break;
472 }
473 s.append(", ");
474 }
475
476 uint32_t modeind = flags & EFFECT_FLAG_AUDIO_MODE_MASK;
477 if (modeind) {
478 s.append("mode indication: ");
479 switch (modeind) {
480 case EFFECT_FLAG_AUDIO_MODE_IND: s.append("required"); break;
481 default: s.append("unknown/reserved"); break;
482 }
483 s.append(", ");
484 }
485
486 uint32_t srcind = flags & EFFECT_FLAG_AUDIO_SOURCE_MASK;
487 if (srcind) {
488 s.append("source indication: ");
489 switch (srcind) {
490 case EFFECT_FLAG_AUDIO_SOURCE_IND: s.append("required"); break;
491 default: s.append("unknown/reserved"); break;
492 }
493 s.append(", ");
494 }
495
496 if (flags & EFFECT_FLAG_OFFLOAD_MASK) {
497 s.append("offloadable, ");
498 }
499
500 int len = s.length();
501 if (s.length() > 2) {
502 (void) s.lockBuffer(len);
503 s.unlockBuffer(len - 2);
504 }
505 return s;
506 }
507
dump(int fd,const Vector<String16> & args __unused) const508 void EffectBase::dump(int fd, const Vector<String16>& args __unused) const
509 {
510 String8 result;
511
512 result.appendFormat("\tEffect ID %d:\n", mId);
513
514 {
515 afutils::FallibleLockGuard l{mutex()};
516 // failed to lock - AudioFlinger is probably deadlocked
517 if (!l) {
518 result.append("\t\tCould not lock Fx mutex:\n");
519 }
520 bool isInternal = isInternal_l();
521 result.append("\t\tSession State Registered Internal Enabled Suspended:\n");
522 result.appendFormat("\t\t%05d %03d %s %s %s %s\n",
523 mSessionId, mState, mPolicyRegistered ? "y" : "n", isInternal ? "y" : "n",
524 ((isInternal && isEnabled()) || (!isInternal && mPolicyEnabled)) ? "y" : "n",
525 mSuspended ? "y" : "n");
526
527 result.append("\t\tDescriptor:\n");
528 char uuidStr[64];
529 AudioEffect::guidToString(&mDescriptor.uuid, uuidStr, sizeof(uuidStr));
530 result.appendFormat("\t\t- UUID: %s\n", uuidStr);
531 AudioEffect::guidToString(&mDescriptor.type, uuidStr, sizeof(uuidStr));
532 result.appendFormat("\t\t- TYPE: %s\n", uuidStr);
533 result.appendFormat("\t\t- apiVersion: %08X\n\t\t- flags: %08X (%s)\n",
534 mDescriptor.apiVersion,
535 mDescriptor.flags,
536 effectFlagsToString(mDescriptor.flags).c_str());
537 result.appendFormat("\t\t- name: %s\n",
538 mDescriptor.name);
539
540 result.appendFormat("\t\t- implementor: %s\n",
541 mDescriptor.implementor);
542
543 result.appendFormat("\t\t%zu Clients:\n", mHandles.size());
544 result.append("\t\t\t Pid Priority Ctrl Locked client server\n");
545 char buffer[256];
546 for (size_t i = 0; i < mHandles.size(); ++i) {
547 IAfEffectHandle *handle = mHandles[i];
548 if (handle != NULL && !handle->disconnected()) {
549 handle->dumpToBuffer(buffer, sizeof(buffer));
550 result.append(buffer);
551 }
552 }
553 }
554
555 write(fd, result.c_str(), result.length());
556 }
557
558 // ----------------------------------------------------------------------------
559 // EffectModule implementation
560 // ----------------------------------------------------------------------------
561
562 #undef LOG_TAG
563 #define LOG_TAG "EffectModule"
564
EffectModule(const sp<EffectCallbackInterface> & callback,effect_descriptor_t * desc,int id,audio_session_t sessionId,bool pinned,audio_port_handle_t deviceId)565 EffectModule::EffectModule(const sp<EffectCallbackInterface>& callback, effect_descriptor_t* desc,
566 int id, audio_session_t sessionId, bool pinned,
567 audio_port_handle_t deviceId)
568 : EffectBase(callback, desc, id, sessionId, pinned),
569 // clear mConfig to ensure consistent initial value of buffer framecount
570 // in case buffers are associated by setInBuffer() or setOutBuffer()
571 // prior to configure_l().
572 mConfig{{}, {}},
573 mStatus(NO_INIT),
574 mMaxDisableWaitCnt(1), // set by configure_l(), should be >= 1
575 mDisableWaitCnt(0), // set by process() and updateState()
576 mOffloaded(false),
577 mIsOutput(false),
578 mSupportsFloat(false),
579 mEffectInterfaceDebug(desc->name) {
580 ALOGV("Constructor %p pinned %d", this, pinned);
581 int lStatus;
582
583 // create effect engine from effect factory
584 mStatus = callback->createEffectHal(
585 &desc->uuid, sessionId, deviceId, &mEffectInterface);
586 if (mStatus != NO_ERROR) {
587 ALOGE("%s createEffectHal failed: %d", __func__, mStatus);
588 return;
589 }
590 lStatus = init_l();
591 if (lStatus < 0) {
592 mStatus = lStatus;
593 goto Error;
594 }
595
596 setOffloaded_l(callback->isOffload(), callback->io());
597 ALOGV("%s Constructor success name %s, Interface %p", __func__, mDescriptor.name,
598 mEffectInterface.get());
599
600 return;
601 Error:
602 mEffectInterface.clear();
603 mEffectInterfaceDebug += " init failed:" + std::to_string(lStatus);
604 ALOGE("%s Constructor Error %d", __func__, mStatus);
605 }
606
~EffectModule()607 EffectModule::~EffectModule()
608 {
609 ALOGV("Destructor %p", this);
610 if (mEffectInterface != 0) {
611 char uuidStr[64];
612 AudioEffect::guidToString(&mDescriptor.uuid, uuidStr, sizeof(uuidStr));
613 ALOGW("EffectModule %p destructor called with unreleased interface, effect %s",
614 this, uuidStr);
615 release_l("~EffectModule");
616 }
617
618 }
619
620 // return true if any effect started or stopped
updateState_l()621 bool EffectModule::updateState_l() {
622 audio_utils::lock_guard _l(mutex());
623
624 bool startedOrStopped = false;
625 switch (mState) {
626 case RESTART:
627 reset_l();
628 FALLTHROUGH_INTENDED;
629
630 case STARTING:
631 // clear auxiliary effect input buffer for next accumulation
632 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
633 memset(mConfig.inputCfg.buffer.raw,
634 0,
635 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
636 }
637 if (start_ll() == NO_ERROR) {
638 mState = ACTIVE;
639 startedOrStopped = true;
640 } else {
641 mState = IDLE;
642 }
643 break;
644 case STOPPING:
645 // volume control for offload and direct threads must take effect immediately.
646 if (stop_ll() == NO_ERROR
647 && !(isVolumeControl() && isOffloadedOrDirect_l())) {
648 mDisableWaitCnt = mMaxDisableWaitCnt;
649 } else {
650 mDisableWaitCnt = 1; // will cause immediate transition to IDLE
651 }
652 mState = STOPPED;
653 break;
654 case STOPPED:
655 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
656 // turn off sequence.
657 if (--mDisableWaitCnt == 0) {
658 reset_l();
659 startedOrStopped = true;
660 mState = IDLE;
661 }
662 break;
663 case ACTIVE:
664 for (size_t i = 0; i < mHandles.size(); i++) {
665 if (!mHandles[i]->disconnected()) {
666 mHandles[i]->framesProcessed(mConfig.inputCfg.buffer.frameCount);
667 }
668 }
669 break;
670 default: //IDLE , ACTIVE, DESTROYED
671 break;
672 }
673
674 return startedOrStopped;
675 }
676
process()677 void EffectModule::process()
678 {
679 audio_utils::lock_guard _l(mutex());
680
681 if (mState == DESTROYED || mEffectInterface == 0 || mInBuffer == 0 || mOutBuffer == 0) {
682 return;
683 }
684
685 const uint32_t inChannelCount =
686 audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
687 const uint32_t outChannelCount =
688 audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
689 const bool auxType =
690 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY;
691
692 // safeInputOutputSampleCount is 0 if the channel count between input and output
693 // buffers do not match. This prevents automatic accumulation or copying between the
694 // input and output effect buffers without an intermediary effect process.
695 // TODO: consider implementing channel conversion.
696 const size_t safeInputOutputSampleCount =
697 mInChannelCountRequested != mOutChannelCountRequested ? 0
698 : mOutChannelCountRequested * std::min(
699 mConfig.inputCfg.buffer.frameCount,
700 mConfig.outputCfg.buffer.frameCount);
701 const auto accumulateInputToOutput = [this, safeInputOutputSampleCount]() {
702 accumulate_float(
703 mConfig.outputCfg.buffer.f32,
704 mConfig.inputCfg.buffer.f32,
705 safeInputOutputSampleCount);
706 };
707 const auto copyInputToOutput = [this, safeInputOutputSampleCount]() {
708 memcpy(
709 mConfig.outputCfg.buffer.f32,
710 mConfig.inputCfg.buffer.f32,
711 safeInputOutputSampleCount * sizeof(*mConfig.outputCfg.buffer.f32));
712 };
713
714 if (isProcessEnabled()) {
715 int ret;
716 if (isProcessImplemented()) {
717 if (auxType) {
718 // We overwrite the aux input buffer here and clear after processing.
719 // aux input is always mono.
720
721 if (!mSupportsFloat) {
722 memcpy_to_i16_from_float(
723 mConfig.inputCfg.buffer.s16,
724 mConfig.inputCfg.buffer.f32,
725 mConfig.inputCfg.buffer.frameCount);
726 }
727 }
728 sp<EffectBufferHalInterface> inBuffer = mInBuffer;
729 sp<EffectBufferHalInterface> outBuffer = mOutBuffer;
730
731 if (!auxType && mInChannelCountRequested != inChannelCount) {
732 adjust_channels(
733 inBuffer->audioBuffer()->f32, mInChannelCountRequested,
734 mInConversionBuffer->audioBuffer()->f32, inChannelCount,
735 sizeof(float),
736 sizeof(float)
737 * mInChannelCountRequested * mConfig.inputCfg.buffer.frameCount);
738 inBuffer = mInConversionBuffer;
739 }
740 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE
741 && mOutChannelCountRequested != outChannelCount) {
742 adjust_selected_channels(
743 outBuffer->audioBuffer()->f32, mOutChannelCountRequested,
744 mOutConversionBuffer->audioBuffer()->f32, outChannelCount,
745 sizeof(float),
746 sizeof(float)
747 * mOutChannelCountRequested * mConfig.outputCfg.buffer.frameCount);
748 outBuffer = mOutConversionBuffer;
749 }
750 if (!mSupportsFloat) { // convert input to int16_t as effect doesn't support float.
751 if (!auxType) {
752 if (mInConversionBuffer == nullptr) {
753 ALOGW("%s: mInConversionBuffer is null, bypassing", __func__);
754 goto data_bypass;
755 }
756 memcpy_to_i16_from_float(
757 mInConversionBuffer->audioBuffer()->s16,
758 inBuffer->audioBuffer()->f32,
759 inChannelCount * mConfig.inputCfg.buffer.frameCount);
760 inBuffer = mInConversionBuffer;
761 }
762 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
763 if (mOutConversionBuffer == nullptr) {
764 ALOGW("%s: mOutConversionBuffer is null, bypassing", __func__);
765 goto data_bypass;
766 }
767 memcpy_to_i16_from_float(
768 mOutConversionBuffer->audioBuffer()->s16,
769 outBuffer->audioBuffer()->f32,
770 outChannelCount * mConfig.outputCfg.buffer.frameCount);
771 outBuffer = mOutConversionBuffer;
772 }
773 }
774 ret = mEffectInterface->process();
775 if (!mSupportsFloat) { // convert output int16_t back to float.
776 sp<EffectBufferHalInterface> target =
777 mOutChannelCountRequested != outChannelCount
778 ? mOutConversionBuffer : mOutBuffer;
779
780 memcpy_to_float_from_i16(
781 target->audioBuffer()->f32,
782 mOutConversionBuffer->audioBuffer()->s16,
783 outChannelCount * mConfig.outputCfg.buffer.frameCount);
784 }
785 if (mOutChannelCountRequested != outChannelCount) {
786 adjust_selected_channels(mOutConversionBuffer->audioBuffer()->f32, outChannelCount,
787 mOutBuffer->audioBuffer()->f32, mOutChannelCountRequested,
788 sizeof(float),
789 sizeof(float) * outChannelCount * mConfig.outputCfg.buffer.frameCount);
790 }
791 } else {
792 data_bypass:
793 if (!auxType /* aux effects do not require data bypass */
794 && mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
795 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
796 accumulateInputToOutput();
797 } else {
798 copyInputToOutput();
799 }
800 }
801 ret = -ENODATA;
802 }
803
804 // force transition to IDLE state when engine is ready
805 if (mState == STOPPED && ret == -ENODATA) {
806 mDisableWaitCnt = 1;
807 }
808
809 // clear auxiliary effect input buffer for next accumulation
810 if (auxType) {
811 const size_t size =
812 mConfig.inputCfg.buffer.frameCount * inChannelCount * sizeof(float);
813 memset(mConfig.inputCfg.buffer.raw, 0, size);
814 }
815 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
816 // mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw
817 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
818 // If an insert effect is idle and input buffer is different from output buffer,
819 // accumulate input onto output
820 if (getCallback()->activeTrackCnt() != 0) {
821 // similar handling with data_bypass above.
822 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
823 accumulateInputToOutput();
824 } else { // EFFECT_BUFFER_ACCESS_WRITE
825 copyInputToOutput();
826 }
827 }
828 }
829 }
830
reset_l()831 void EffectModule::reset_l()
832 {
833 if (mStatus != NO_ERROR || mEffectInterface == 0) {
834 return;
835 }
836
837 int reply = 0;
838 uint32_t replySize = sizeof(reply);
839 mEffectInterface->command(EFFECT_CMD_RESET, 0, NULL, &replySize, &reply);
840 }
841
configure_l()842 status_t EffectModule::configure_l()
843 {
844 ALOGVV("%s started", __func__);
845 status_t status;
846 uint32_t size;
847 audio_channel_mask_t channelMask;
848 sp<EffectCallbackInterface> callback;
849
850 if (mEffectInterface == 0) {
851 status = NO_INIT;
852 goto exit;
853 }
854
855 // TODO: handle configuration of effects replacing track process
856 // TODO: handle configuration of input (record) SW effects above the HAL,
857 // similar to output EFFECT_FLAG_TYPE_INSERT/REPLACE,
858 // in which case input channel masks should be used here.
859 callback = getCallback();
860 channelMask = callback->inChannelMask(mId);
861 mConfig.inputCfg.channels = channelMask;
862 mConfig.outputCfg.channels = callback->outChannelMask();
863
864 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
865 if (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_MONO) {
866 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
867 ALOGV("Overriding auxiliary effect input channels %#x as MONO",
868 mConfig.inputCfg.channels);
869 }
870 }
871 if (isHapticGenerator()) {
872 audio_channel_mask_t hapticChannelMask = callback->hapticChannelMask();
873 mConfig.inputCfg.channels |= hapticChannelMask;
874 mConfig.outputCfg.channels |= hapticChannelMask;
875 }
876 mInChannelCountRequested =
877 audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
878 mOutChannelCountRequested =
879 audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
880
881 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_FLOAT;
882 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_FLOAT;
883
884 // Don't use sample rate for thread if effect isn't offloadable.
885 if (callback->isOffloadOrDirect() && !isOffloaded_l()) {
886 mConfig.inputCfg.samplingRate = DEFAULT_OUTPUT_SAMPLE_RATE;
887 ALOGV("Overriding effect input as 48kHz");
888 } else {
889 mConfig.inputCfg.samplingRate = callback->sampleRate();
890 }
891 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
892 mConfig.inputCfg.bufferProvider.cookie = NULL;
893 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
894 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
895 mConfig.outputCfg.bufferProvider.cookie = NULL;
896 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
897 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
898 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
899 // Insert effect:
900 // - in global sessions (e.g AUDIO_SESSION_OUTPUT_MIX),
901 // always overwrites output buffer: input buffer == output buffer
902 // - in other sessions:
903 // last effect in the chain accumulates in output buffer: input buffer != output buffer
904 // other effect: overwrites output buffer: input buffer == output buffer
905 // Auxiliary effect:
906 // accumulates in output buffer: input buffer != output buffer
907 // Therefore: accumulate <=> input buffer != output buffer
908 mConfig.outputCfg.accessMode = requiredEffectBufferAccessMode();
909 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
910 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
911 mConfig.inputCfg.buffer.frameCount = callback->frameCount();
912 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
913 mIsOutput = callback->isOutput();
914
915 ALOGV("%s %p chain %p buffer %p framecount %zu", __func__, this,
916 callback->chain().promote().get(), mConfig.inputCfg.buffer.raw,
917 mConfig.inputCfg.buffer.frameCount);
918
919 status_t cmdStatus;
920 size = sizeof(int);
921 status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
922 sizeof(mConfig),
923 &mConfig,
924 &size,
925 &cmdStatus);
926 if (status == NO_ERROR) {
927 status = cmdStatus;
928 }
929
930 if (status != NO_ERROR &&
931 EffectConfiguration::isHidl() && // only HIDL effects support channel conversion
932 mIsOutput &&
933 (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_STEREO
934 || mConfig.outputCfg.channels != AUDIO_CHANNEL_OUT_STEREO)) {
935 // Older effects may require exact STEREO position mask.
936 if (mConfig.inputCfg.channels != AUDIO_CHANNEL_OUT_STEREO
937 && (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
938 ALOGV("Overriding effect input channels %#x as STEREO", mConfig.inputCfg.channels);
939 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
940 }
941 if (mConfig.outputCfg.channels != AUDIO_CHANNEL_OUT_STEREO) {
942 ALOGV("Overriding effect output channels %#x as STEREO", mConfig.outputCfg.channels);
943 mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
944 }
945 size = sizeof(int);
946 status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
947 sizeof(mConfig),
948 &mConfig,
949 &size,
950 &cmdStatus);
951 if (status == NO_ERROR) {
952 status = cmdStatus;
953 }
954 }
955
956 if (status == NO_ERROR) {
957 mSupportsFloat = true;
958 }
959
960 // only HIDL effects support integer conversion.
961 if (status != NO_ERROR && EffectConfiguration::isHidl()) {
962 ALOGV("EFFECT_CMD_SET_CONFIG failed with float format, retry with int16_t.");
963 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
964 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
965 size = sizeof(int);
966 status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
967 sizeof(mConfig),
968 &mConfig,
969 &size,
970 &cmdStatus);
971 if (status == NO_ERROR) {
972 status = cmdStatus;
973 }
974 if (status == NO_ERROR) {
975 mSupportsFloat = false;
976 ALOGVV("config worked with 16 bit");
977 } else {
978 ALOGE("%s failed %d with int16_t (as well as float)", __func__, status);
979 }
980 }
981
982 if (status == NO_ERROR) {
983 // Establish Buffer strategy
984 setInBuffer(mInBuffer);
985 setOutBuffer(mOutBuffer);
986
987 // Update visualizer latency
988 if (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) {
989 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
990 effect_param_t *p = (effect_param_t *)buf32;
991
992 p->psize = sizeof(uint32_t);
993 p->vsize = sizeof(uint32_t);
994 size = sizeof(int);
995 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
996
997 uint32_t latency = callback->latency();
998
999 *((int32_t *)p->data + 1)= latency;
1000 mEffectInterface->command(EFFECT_CMD_SET_PARAM,
1001 sizeof(effect_param_t) + 8,
1002 &buf32,
1003 &size,
1004 &cmdStatus);
1005 }
1006 }
1007
1008 // mConfig.outputCfg.buffer.frameCount cannot be zero.
1009 mMaxDisableWaitCnt = (uint32_t)std::max(
1010 (uint64_t)1, // mMaxDisableWaitCnt must be greater than zero.
1011 (uint64_t)mConfig.outputCfg.buffer.frameCount == 0 ? 1
1012 : (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate
1013 / ((uint64_t)1000 * mConfig.outputCfg.buffer.frameCount)));
1014
1015 exit:
1016 // TODO: consider clearing mConfig on error.
1017 mStatus = status;
1018 ALOGVV("%s ended", __func__);
1019 return status;
1020 }
1021
init_l()1022 status_t EffectModule::init_l()
1023 {
1024 audio_utils::lock_guard _l(mutex());
1025 if (mEffectInterface == 0) {
1026 return NO_INIT;
1027 }
1028 status_t cmdStatus;
1029 uint32_t size = sizeof(status_t);
1030 status_t status = mEffectInterface->command(EFFECT_CMD_INIT,
1031 0,
1032 NULL,
1033 &size,
1034 &cmdStatus);
1035 if (status == 0) {
1036 status = cmdStatus;
1037 }
1038 return status;
1039 }
1040
addEffectToHal_l()1041 void EffectModule::addEffectToHal_l()
1042 {
1043 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
1044 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1045 if (mCurrentHalStream == getCallback()->io()) {
1046 return;
1047 }
1048
1049 status_t status = getCallback()->addEffectToHal(mEffectInterface);
1050 if (status == NO_ERROR) {
1051 mCurrentHalStream = getCallback()->io();
1052 }
1053 }
1054 }
1055
addEffectToHal_l()1056 void HwAccDeviceEffectModule::addEffectToHal_l()
1057 {
1058 if (mAddedToHal) {
1059 return;
1060 }
1061 status_t status = getCallback()->addEffectToHal(mEffectInterface);
1062 if (status == NO_ERROR) {
1063 mAddedToHal = true;
1064 }
1065 }
1066
1067 // start_l() must be called with EffectChain::mutex() held
start_l()1068 status_t EffectModule::start_l()
1069 {
1070 status_t status;
1071 {
1072 audio_utils::lock_guard _l(mutex());
1073 status = start_ll();
1074 }
1075 if (status == NO_ERROR) {
1076 getCallback()->resetVolume_l();
1077 }
1078 return status;
1079 }
1080
start_ll()1081 status_t EffectModule::start_ll()
1082 {
1083 if (mEffectInterface == 0) {
1084 return NO_INIT;
1085 }
1086 if (mStatus != NO_ERROR) {
1087 return mStatus;
1088 }
1089 status_t cmdStatus;
1090 uint32_t size = sizeof(status_t);
1091 status_t status = mEffectInterface->command(EFFECT_CMD_ENABLE,
1092 0,
1093 NULL,
1094 &size,
1095 &cmdStatus);
1096 if (status == 0) {
1097 status = cmdStatus;
1098 }
1099 if (status == 0) {
1100 addEffectToHal_l();
1101 }
1102 return status;
1103 }
1104
stop_l()1105 status_t EffectModule::stop_l()
1106 {
1107 audio_utils::lock_guard _l(mutex());
1108 return stop_ll();
1109 }
1110
stop_ll()1111 status_t EffectModule::stop_ll()
1112 {
1113 if (mEffectInterface == 0) {
1114 return NO_INIT;
1115 }
1116 if (mStatus != NO_ERROR) {
1117 return mStatus;
1118 }
1119 status_t cmdStatus = NO_ERROR;
1120 uint32_t size = sizeof(status_t);
1121
1122 if (isVolumeControl() && isOffloadedOrDirect_l()) {
1123 // We have the EffectChain and EffectModule lock, permit a reentrant call to setVolume:
1124 // resetVolume_l --> setVolume_l --> EffectModule::setVolume
1125 mSetVolumeReentrantTid = gettid();
1126 getCallback()->resetVolume_l();
1127 mSetVolumeReentrantTid = INVALID_PID;
1128 }
1129
1130 status_t status = mEffectInterface->command(EFFECT_CMD_DISABLE,
1131 0,
1132 NULL,
1133 &size,
1134 &cmdStatus);
1135 if (status == NO_ERROR) {
1136 status = cmdStatus;
1137 }
1138 if (status == NO_ERROR) {
1139 status = removeEffectFromHal_l();
1140 }
1141 return status;
1142 }
1143
1144 // must be called with EffectChain::mutex() held
release_l(const std::string & from)1145 void EffectModule::release_l(const std::string& from)
1146 {
1147 if (mEffectInterface != 0) {
1148 removeEffectFromHal_l();
1149 // release effect engine
1150 mEffectInterface->close();
1151 mEffectInterface.clear();
1152 mEffectInterfaceDebug += " released by: " + from;
1153 }
1154 }
1155
removeEffectFromHal_l()1156 status_t EffectModule::removeEffectFromHal_l()
1157 {
1158 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
1159 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1160 if (mCurrentHalStream != getCallback()->io()) {
1161 return (mCurrentHalStream == AUDIO_IO_HANDLE_NONE) ? NO_ERROR : INVALID_OPERATION;
1162 }
1163 getCallback()->removeEffectFromHal(mEffectInterface);
1164 mCurrentHalStream = AUDIO_IO_HANDLE_NONE;
1165 }
1166 return NO_ERROR;
1167 }
1168
removeEffectFromHal_l()1169 status_t HwAccDeviceEffectModule::removeEffectFromHal_l()
1170 {
1171 if (!mAddedToHal) {
1172 return NO_ERROR;
1173 }
1174 getCallback()->removeEffectFromHal(mEffectInterface);
1175 mAddedToHal = false;
1176 return NO_ERROR;
1177 }
1178
1179 // round up delta valid if value and divisor are positive.
1180 template <typename T>
roundUpDelta(const T & value,const T & divisor)1181 static T roundUpDelta(const T &value, const T &divisor) {
1182 T remainder = value % divisor;
1183 return remainder == 0 ? 0 : divisor - remainder;
1184 }
1185
command(int32_t cmdCode,const std::vector<uint8_t> & cmdData,int32_t maxReplySize,std::vector<uint8_t> * reply)1186 status_t EffectModule::command(int32_t cmdCode,
1187 const std::vector<uint8_t>& cmdData,
1188 int32_t maxReplySize,
1189 std::vector<uint8_t>* reply)
1190 {
1191 audio_utils::lock_guard _l(mutex());
1192 ALOGVV("%s, cmdCode: %d, mEffectInterface: %p", __func__, cmdCode, mEffectInterface.get());
1193
1194 if (mState == DESTROYED || mEffectInterface == 0) {
1195 return NO_INIT;
1196 }
1197 if (mStatus != NO_ERROR) {
1198 return mStatus;
1199 }
1200 if (maxReplySize < 0 || maxReplySize > EFFECT_PARAM_SIZE_MAX) {
1201 return -EINVAL;
1202 }
1203 size_t cmdSize = cmdData.size();
1204 const effect_param_t* param = cmdSize >= sizeof(effect_param_t)
1205 ? reinterpret_cast<const effect_param_t*>(cmdData.data())
1206 : nullptr;
1207 if (cmdCode == EFFECT_CMD_GET_PARAM &&
1208 (param == nullptr || param->psize > cmdSize - sizeof(effect_param_t))) {
1209 android_errorWriteLog(0x534e4554, "32438594");
1210 android_errorWriteLog(0x534e4554, "33003822");
1211 return -EINVAL;
1212 }
1213 if (cmdCode == EFFECT_CMD_GET_PARAM &&
1214 (maxReplySize < static_cast<signed>(sizeof(effect_param_t)) ||
1215 param->psize > maxReplySize - sizeof(effect_param_t))) {
1216 android_errorWriteLog(0x534e4554, "29251553");
1217 return -EINVAL;
1218 }
1219 if (cmdCode == EFFECT_CMD_GET_PARAM &&
1220 (static_cast<signed>(sizeof(effect_param_t)) > maxReplySize
1221 || param->psize > maxReplySize - sizeof(effect_param_t)
1222 || param->vsize > maxReplySize - sizeof(effect_param_t)
1223 - param->psize
1224 || roundUpDelta(param->psize, (uint32_t) sizeof(int)) >
1225 maxReplySize
1226 - sizeof(effect_param_t)
1227 - param->psize
1228 - param->vsize)) {
1229 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: reply size inconsistent");
1230 android_errorWriteLog(0x534e4554, "32705438");
1231 return -EINVAL;
1232 }
1233 if ((cmdCode == EFFECT_CMD_SET_PARAM
1234 || cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED)
1235 && // DEFERRED not generally used
1236 (param == nullptr
1237 || param->psize > cmdSize - sizeof(effect_param_t)
1238 || param->vsize > cmdSize - sizeof(effect_param_t)
1239 - param->psize
1240 || roundUpDelta(param->psize,
1241 (uint32_t) sizeof(int)) >
1242 cmdSize
1243 - sizeof(effect_param_t)
1244 - param->psize
1245 - param->vsize)) {
1246 android_errorWriteLog(0x534e4554, "30204301");
1247 return -EINVAL;
1248 }
1249 uint32_t replySize = maxReplySize;
1250 reply->resize(replySize);
1251 status_t status = mEffectInterface->command(cmdCode,
1252 cmdSize,
1253 const_cast<uint8_t*>(cmdData.data()),
1254 &replySize,
1255 reply->data());
1256 reply->resize(status == NO_ERROR ? replySize : 0);
1257 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
1258 for (size_t i = 1; i < mHandles.size(); i++) {
1259 IAfEffectHandle *h = mHandles[i];
1260 if (h != NULL && !h->disconnected()) {
1261 h->commandExecuted(cmdCode, cmdData, *reply);
1262 }
1263 }
1264 }
1265 return status;
1266 }
1267
isProcessEnabled() const1268 bool EffectModule::isProcessEnabled() const
1269 {
1270 if (mStatus != NO_ERROR) {
1271 return false;
1272 }
1273
1274 switch (mState) {
1275 case RESTART:
1276 case ACTIVE:
1277 case STOPPING:
1278 case STOPPED:
1279 return true;
1280 case IDLE:
1281 case STARTING:
1282 case DESTROYED:
1283 default:
1284 return false;
1285 }
1286 }
1287
isOffloadedOrDirect_l() const1288 bool EffectModule::isOffloadedOrDirect_l() const
1289 {
1290 return getCallback()->isOffloadOrDirect();
1291 }
1292
isVolumeControlEnabled_l() const1293 bool EffectModule::isVolumeControlEnabled_l() const
1294 {
1295 return (isVolumeControl() && (isOffloadedOrDirect_l() ? isEnabled() : isProcessEnabled()));
1296 }
1297
setInBuffer(const sp<EffectBufferHalInterface> & buffer)1298 void EffectModule::setInBuffer(const sp<EffectBufferHalInterface>& buffer) {
1299 ALOGVV("setInBuffer %p",(&buffer));
1300
1301 // mConfig.inputCfg.buffer.frameCount may be zero if configure_l() is not called yet.
1302 if (buffer != 0) {
1303 mConfig.inputCfg.buffer.raw = buffer->audioBuffer()->raw;
1304 buffer->setFrameCount(mConfig.inputCfg.buffer.frameCount);
1305 } else {
1306 mConfig.inputCfg.buffer.raw = NULL;
1307 }
1308 mInBuffer = buffer;
1309 mEffectInterface->setInBuffer(buffer);
1310
1311 // aux effects do in place conversion to float - we don't allocate mInConversionBuffer.
1312 // Theoretically insert effects can also do in-place conversions (destroying
1313 // the original buffer) when the output buffer is identical to the input buffer,
1314 // but we don't optimize for it here.
1315 const bool auxType = (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY;
1316 const uint32_t inChannelCount =
1317 audio_channel_count_from_out_mask(mConfig.inputCfg.channels);
1318 const bool formatMismatch = !mSupportsFloat || mInChannelCountRequested != inChannelCount;
1319 if (!auxType && formatMismatch && mInBuffer != nullptr) {
1320 // we need to translate - create hidl shared buffer and intercept
1321 const size_t inFrameCount = mConfig.inputCfg.buffer.frameCount;
1322 // Use FCC_2 in case mInChannelCountRequested is mono and the effect is stereo.
1323 const uint32_t inChannels = std::max((uint32_t)FCC_2, mInChannelCountRequested);
1324 const size_t size = inChannels * inFrameCount * std::max(sizeof(int16_t), sizeof(float));
1325
1326 ALOGV("%s: setInBuffer updating for inChannels:%d inFrameCount:%zu total size:%zu",
1327 __func__, inChannels, inFrameCount, size);
1328
1329 if (size > 0 && (mInConversionBuffer == nullptr
1330 || size > mInConversionBuffer->getSize())) {
1331 mInConversionBuffer.clear();
1332 ALOGV("%s: allocating mInConversionBuffer %zu", __func__, size);
1333 (void)getCallback()->allocateHalBuffer(size, &mInConversionBuffer);
1334 }
1335 if (mInConversionBuffer != nullptr) {
1336 mInConversionBuffer->setFrameCount(inFrameCount);
1337 mEffectInterface->setInBuffer(mInConversionBuffer);
1338 } else if (size > 0) {
1339 ALOGE("%s cannot create mInConversionBuffer", __func__);
1340 }
1341 }
1342 }
1343
setOutBuffer(const sp<EffectBufferHalInterface> & buffer)1344 void EffectModule::setOutBuffer(const sp<EffectBufferHalInterface>& buffer) {
1345 ALOGVV("setOutBuffer %p",(&buffer));
1346
1347 // mConfig.outputCfg.buffer.frameCount may be zero if configure_l() is not called yet.
1348 if (buffer != 0) {
1349 mConfig.outputCfg.buffer.raw = buffer->audioBuffer()->raw;
1350 buffer->setFrameCount(mConfig.outputCfg.buffer.frameCount);
1351 } else {
1352 mConfig.outputCfg.buffer.raw = NULL;
1353 }
1354 mOutBuffer = buffer;
1355 mEffectInterface->setOutBuffer(buffer);
1356
1357 // Note: Any effect that does not accumulate does not need mOutConversionBuffer and
1358 // can do in-place conversion from int16_t to float. We don't optimize here.
1359 const uint32_t outChannelCount =
1360 audio_channel_count_from_out_mask(mConfig.outputCfg.channels);
1361 const bool formatMismatch = !mSupportsFloat || mOutChannelCountRequested != outChannelCount;
1362 if (formatMismatch && mOutBuffer != nullptr) {
1363 const size_t outFrameCount = mConfig.outputCfg.buffer.frameCount;
1364 // Use FCC_2 in case mOutChannelCountRequested is mono and the effect is stereo.
1365 const uint32_t outChannels = std::max((uint32_t)FCC_2, mOutChannelCountRequested);
1366 const size_t size = outChannels * outFrameCount * std::max(sizeof(int16_t), sizeof(float));
1367
1368 ALOGV("%s: setOutBuffer updating for outChannels:%d outFrameCount:%zu total size:%zu",
1369 __func__, outChannels, outFrameCount, size);
1370
1371 if (size > 0 && (mOutConversionBuffer == nullptr
1372 || size > mOutConversionBuffer->getSize())) {
1373 mOutConversionBuffer.clear();
1374 ALOGV("%s: allocating mOutConversionBuffer %zu", __func__, size);
1375 (void)getCallback()->allocateHalBuffer(size, &mOutConversionBuffer);
1376 }
1377 if (mOutConversionBuffer != nullptr) {
1378 mOutConversionBuffer->setFrameCount(outFrameCount);
1379 mEffectInterface->setOutBuffer(mOutConversionBuffer);
1380 } else if (size > 0) {
1381 ALOGE("%s cannot create mOutConversionBuffer", __func__);
1382 }
1383 }
1384 }
1385
setVolume_l(uint32_t * left,uint32_t * right,bool controller,bool force)1386 status_t EffectModule::setVolume_l(uint32_t* left, uint32_t* right, bool controller, bool force) {
1387 AutoLockReentrant _l(mutex(), mSetVolumeReentrantTid);
1388 if (mStatus != NO_ERROR) {
1389 return mStatus;
1390 }
1391 status_t status = NO_ERROR;
1392 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
1393 // if controller flag is set (Note that controller == TRUE => the volume controller effect in
1394 // the effect chain)
1395 if (((isOffloadedOrDirect_l() ? isEnabled() : isProcessEnabled()) || force) &&
1396 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
1397 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND ||
1398 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_MONITOR)) {
1399 status = setVolumeInternal_ll(left, right, controller);
1400 }
1401 return status;
1402 }
1403
setVolumeInternal_ll(uint32_t * left,uint32_t * right,bool controller)1404 status_t EffectModule::setVolumeInternal_ll(
1405 uint32_t *left, uint32_t *right, bool controller) {
1406 if (mVolume.has_value() && *left == mVolume.value()[0] && *right == mVolume.value()[1] &&
1407 !controller) {
1408 LOG_ALWAYS_FATAL_IF(
1409 !mReturnedVolume.has_value(),
1410 "The cached returned volume must not be null when the cached volume has value");
1411 *left = mReturnedVolume.value()[0];
1412 *right = mReturnedVolume.value()[1];
1413 return NO_ERROR;
1414 }
1415 LOG_ALWAYS_FATAL_IF(mEffectInterface == nullptr, "%s", mEffectInterfaceDebug.c_str());
1416 uint32_t volume[2] = {*left, *right};
1417 uint32_t* pVolume = isVolumeControl() ? volume : nullptr;
1418 uint32_t size = sizeof(volume);
1419 status_t status = mEffectInterface->command(EFFECT_CMD_SET_VOLUME,
1420 size,
1421 volume,
1422 &size,
1423 pVolume);
1424 if (pVolume && status == NO_ERROR && size == sizeof(volume)) {
1425 mVolume = {*left, *right}; // Cache the value that has been set
1426 *left = volume[0];
1427 *right = volume[1];
1428 mReturnedVolume = {*left, *right};
1429 }
1430 return status;
1431 }
1432
setVolumeForOutput_l(uint32_t left,uint32_t right)1433 void EffectChain::setVolumeForOutput_l(uint32_t left, uint32_t right)
1434 {
1435 // for offload or direct thread, if the effect chain has non-offloadable
1436 // effect and any effect module within the chain has volume control, then
1437 // volume control is delegated to effect, otherwise, set volume to hal.
1438 if (mEffectCallback->isOffloadOrDirect() &&
1439 !(isNonOffloadableEnabled_l() && hasVolumeControlEnabled_l())) {
1440 float vol_l = (float)left / (1 << 24);
1441 float vol_r = (float)right / (1 << 24);
1442 mEffectCallback->setVolumeForOutput(vol_l, vol_r);
1443 }
1444 }
1445
sendSetAudioDevicesCommand(const AudioDeviceTypeAddrVector & devices,uint32_t cmdCode)1446 status_t EffectModule::sendSetAudioDevicesCommand(
1447 const AudioDeviceTypeAddrVector &devices, uint32_t cmdCode)
1448 {
1449 audio_devices_t deviceType = deviceTypesToBitMask(getAudioDeviceTypes(devices));
1450 if (deviceType == AUDIO_DEVICE_NONE) {
1451 return NO_ERROR;
1452 }
1453
1454 audio_utils::lock_guard _l(mutex());
1455 if (mStatus != NO_ERROR) {
1456 return mStatus;
1457 }
1458 status_t status = NO_ERROR;
1459 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
1460 status_t cmdStatus;
1461 uint32_t size = sizeof(status_t);
1462 // FIXME: use audio device types and addresses when the hal interface is ready.
1463 status = mEffectInterface->command(cmdCode,
1464 sizeof(uint32_t),
1465 &deviceType,
1466 &size,
1467 &cmdStatus);
1468 }
1469 return status;
1470 }
1471
setDevices(const AudioDeviceTypeAddrVector & devices)1472 status_t EffectModule::setDevices(const AudioDeviceTypeAddrVector &devices)
1473 {
1474 return sendSetAudioDevicesCommand(devices, EFFECT_CMD_SET_DEVICE);
1475 }
1476
setInputDevice(const AudioDeviceTypeAddr & device)1477 status_t EffectModule::setInputDevice(const AudioDeviceTypeAddr &device)
1478 {
1479 return sendSetAudioDevicesCommand({device}, EFFECT_CMD_SET_INPUT_DEVICE);
1480 }
1481
setMode(audio_mode_t mode)1482 status_t EffectModule::setMode(audio_mode_t mode)
1483 {
1484 audio_utils::lock_guard _l(mutex());
1485 if (mStatus != NO_ERROR) {
1486 return mStatus;
1487 }
1488 status_t status = NO_ERROR;
1489 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
1490 status_t cmdStatus;
1491 uint32_t size = sizeof(status_t);
1492 status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_MODE,
1493 sizeof(audio_mode_t),
1494 &mode,
1495 &size,
1496 &cmdStatus);
1497 if (status == NO_ERROR) {
1498 status = cmdStatus;
1499 }
1500 }
1501 return status;
1502 }
1503
setAudioSource(audio_source_t source)1504 status_t EffectModule::setAudioSource(audio_source_t source)
1505 {
1506 audio_utils::lock_guard _l(mutex());
1507 if (mStatus != NO_ERROR) {
1508 return mStatus;
1509 }
1510 status_t status = NO_ERROR;
1511 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
1512 uint32_t size = 0;
1513 status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_SOURCE,
1514 sizeof(audio_source_t),
1515 &source,
1516 &size,
1517 NULL);
1518 }
1519 return status;
1520 }
1521
setOffloaded_l(bool offloaded,audio_io_handle_t io)1522 status_t EffectModule::setOffloaded_l(bool offloaded, audio_io_handle_t io)
1523 {
1524 audio_utils::lock_guard _l(mutex());
1525 if (mStatus != NO_ERROR) {
1526 return mStatus;
1527 }
1528 status_t status = NO_ERROR;
1529 if ((mDescriptor.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) != 0) {
1530 status_t cmdStatus;
1531 uint32_t size = sizeof(status_t);
1532 effect_offload_param_t cmd;
1533
1534 cmd.isOffload = offloaded;
1535 cmd.ioHandle = io;
1536 status = mEffectInterface->command(EFFECT_CMD_OFFLOAD,
1537 sizeof(effect_offload_param_t),
1538 &cmd,
1539 &size,
1540 &cmdStatus);
1541 if (status == NO_ERROR) {
1542 status = cmdStatus;
1543 }
1544 mOffloaded = (status == NO_ERROR) ? offloaded : false;
1545 } else {
1546 if (offloaded) {
1547 status = INVALID_OPERATION;
1548 }
1549 mOffloaded = false;
1550 }
1551 ALOGV("%s offloaded %d io %d status %d", __func__, offloaded, io, status);
1552 return status;
1553 }
1554
isOffloaded_l() const1555 bool EffectModule::isOffloaded_l() const
1556 {
1557 audio_utils::lock_guard _l(mutex());
1558 return mOffloaded;
1559 }
1560
1561 /*static*/
isHapticGenerator(const effect_uuid_t * type)1562 bool IAfEffectModule::isHapticGenerator(const effect_uuid_t *type) {
1563 return memcmp(type, FX_IID_HAPTICGENERATOR, sizeof(effect_uuid_t)) == 0;
1564 }
1565
isHapticGenerator() const1566 bool EffectModule::isHapticGenerator() const {
1567 return IAfEffectModule::isHapticGenerator(&mDescriptor.type);
1568 }
1569
1570 /*static*/
isSpatializer(const effect_uuid_t * type)1571 bool IAfEffectModule::isSpatializer(const effect_uuid_t *type) {
1572 return memcmp(type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0;
1573 }
1574
isSpatializer() const1575 bool EffectModule::isSpatializer() const {
1576 return IAfEffectModule::isSpatializer(&mDescriptor.type);
1577 }
1578
setHapticScale_l(int id,os::HapticScale hapticScale)1579 status_t EffectModule::setHapticScale_l(int id, os::HapticScale hapticScale) {
1580 if (mStatus != NO_ERROR) {
1581 return mStatus;
1582 }
1583 if (!isHapticGenerator()) {
1584 ALOGW("Should not set haptic intensity for effects that are not HapticGenerator");
1585 return INVALID_OPERATION;
1586 }
1587
1588 // Scale param fields
1589 int32_t intensityParam = static_cast<int32_t>(HG_PARAM_HAPTIC_INTENSITY);
1590 int32_t scaleLevel = static_cast<int32_t>(hapticScale.getLevel());
1591 float scaleFactor = hapticScale.getScaleFactor();
1592 float adaptiveScaleFactor = hapticScale.getAdaptiveScaleFactor();
1593
1594 size_t psize = sizeof(int32_t); // HG_PARAM_HAPTIC_INTENSITY
1595 size_t vsize = 2 * sizeof(int32_t) + 2 * sizeof(float); // id + scale fields
1596 std::vector<uint8_t> request(sizeof(effect_param_t) + psize + vsize);
1597 effect_param_t *effectParam = (effect_param_t*) request.data();
1598 effectParam->psize = psize;
1599 effectParam->vsize = vsize;
1600
1601 EffectParamWriter writer(*effectParam);
1602 writer.writeToParameter(&intensityParam);
1603 writer.writeToValue(&id);
1604 writer.writeToValue(&scaleLevel);
1605 writer.writeToValue(&scaleFactor);
1606 writer.writeToValue(&adaptiveScaleFactor);
1607 writer.finishValueWrite();
1608
1609 std::vector<uint8_t> response;
1610 status_t status = command(EFFECT_CMD_SET_PARAM, request, sizeof(int32_t), &response);
1611 if (status == NO_ERROR) {
1612 LOG_ALWAYS_FATAL_IF(response.size() != 4);
1613 status = *reinterpret_cast<const status_t*>(response.data());
1614 }
1615 return status;
1616 }
1617
setVibratorInfo_l(const media::AudioVibratorInfo & vibratorInfo)1618 status_t EffectModule::setVibratorInfo_l(const media::AudioVibratorInfo& vibratorInfo) {
1619 if (mStatus != NO_ERROR) {
1620 return mStatus;
1621 }
1622 if (!isHapticGenerator()) {
1623 ALOGW("Should not set vibrator info for effects that are not HapticGenerator");
1624 return INVALID_OPERATION;
1625 }
1626
1627 size_t psize = sizeof(int32_t); // HG_PARAM_VIBRATOR_INFO
1628 size_t vsize = 3 * sizeof(float); // resonantFrequency + qFactor + maxAmplitude
1629 std::vector<uint8_t> request(sizeof(effect_param_t) + psize + vsize);
1630 effect_param_t *effectParam = (effect_param_t*) request.data();
1631 effectParam->psize = psize;
1632 effectParam->vsize = vsize;
1633
1634 int32_t infoParam = static_cast<int32_t>(HG_PARAM_VIBRATOR_INFO);
1635 EffectParamWriter writer(*effectParam);
1636 writer.writeToParameter(&infoParam);
1637 writer.writeToValue(&vibratorInfo.resonantFrequency);
1638 writer.writeToValue(&vibratorInfo.qFactor);
1639 writer.writeToValue(&vibratorInfo.maxAmplitude);
1640 writer.finishValueWrite();
1641
1642 std::vector<uint8_t> response;
1643 status_t status = command(EFFECT_CMD_SET_PARAM, request, sizeof(int32_t), &response);
1644 if (status == NO_ERROR) {
1645 LOG_ALWAYS_FATAL_IF(response.size() != sizeof(status_t));
1646 status = *reinterpret_cast<const status_t*>(response.data());
1647 }
1648 return status;
1649 }
1650
getConfigs_l(audio_config_base_t * inputCfg,audio_config_base_t * outputCfg,bool * isOutput) const1651 status_t EffectModule::getConfigs_l(audio_config_base_t* inputCfg, audio_config_base_t* outputCfg,
1652 bool* isOutput) const {
1653 audio_utils::lock_guard _l(mutex());
1654 if (mConfig.inputCfg.mask == 0 || mConfig.outputCfg.mask == 0) {
1655 return NO_INIT;
1656 }
1657 inputCfg->sample_rate = mConfig.inputCfg.samplingRate;
1658 inputCfg->channel_mask = static_cast<audio_channel_mask_t>(mConfig.inputCfg.channels);
1659 inputCfg->format = static_cast<audio_format_t>(mConfig.inputCfg.format);
1660 outputCfg->sample_rate = mConfig.outputCfg.samplingRate;
1661 outputCfg->channel_mask = static_cast<audio_channel_mask_t>(mConfig.outputCfg.channels);
1662 outputCfg->format = static_cast<audio_format_t>(mConfig.outputCfg.format);
1663 *isOutput = mIsOutput;
1664 return NO_ERROR;
1665 }
1666
sendMetadata_ll(const std::vector<playback_track_metadata_v7_t> & metadata)1667 status_t EffectModule::sendMetadata_ll(const std::vector<playback_track_metadata_v7_t>& metadata) {
1668 if (mStatus != NO_ERROR) {
1669 return mStatus;
1670 }
1671 // TODO b/307368176: send all metadata to effects if requested by the implementation.
1672 // For now only send channel mask to Spatializer.
1673 if (!isSpatializer()) {
1674 return INVALID_OPERATION;
1675 }
1676
1677 std::vector<uint8_t> request(
1678 sizeof(effect_param_t) + sizeof(int32_t) + metadata.size() * sizeof(uint32_t));
1679 effect_param_t *param = (effect_param_t*) request.data();
1680 param->psize = sizeof(int32_t);
1681 param->vsize = metadata.size() * sizeof(uint32_t);
1682 *(int32_t*)param->data = SPATIALIZER_PARAM_INPUT_CHANNEL_MASK;
1683 uint32_t* channelMasks = reinterpret_cast<uint32_t*>(param->data + sizeof(int32_t));
1684 for (auto m : metadata) {
1685 *channelMasks++ = m.channel_mask;
1686 }
1687 std::vector<uint8_t> response;
1688 status_t status = command(EFFECT_CMD_SET_PARAM, request, sizeof(int32_t), &response);
1689 if (status == NO_ERROR) {
1690 LOG_ALWAYS_FATAL_IF(response.size() != sizeof(status_t));
1691 status = *reinterpret_cast<const status_t*>(response.data());
1692 }
1693 return status;
1694 }
1695
dumpInOutBuffer(bool isInput,const sp<EffectBufferHalInterface> & buffer)1696 static std::string dumpInOutBuffer(bool isInput, const sp<EffectBufferHalInterface> &buffer) {
1697 std::stringstream ss;
1698
1699 if (buffer == nullptr) {
1700 return "nullptr"; // make different than below
1701 } else if (buffer->externalData() != nullptr) {
1702 ss << (isInput ? buffer->externalData() : buffer->audioBuffer()->raw)
1703 << " -> "
1704 << (isInput ? buffer->audioBuffer()->raw : buffer->externalData());
1705 } else {
1706 ss << buffer->audioBuffer()->raw;
1707 }
1708 return ss.str();
1709 }
1710
dump(int fd,const Vector<String16> & args) const1711 void EffectModule::dump(int fd, const Vector<String16>& args) const {
1712 EffectBase::dump(fd, args);
1713
1714 String8 result;
1715 afutils::FallibleLockGuard l{mutex()};
1716
1717 result.append("\t\tStatus Engine:\n");
1718 result.appendFormat("\t\t%03d %p\n",
1719 mStatus, mEffectInterface.get());
1720
1721 result.appendFormat("\t\t- data: %s\n", mSupportsFloat ? "float" : "int16");
1722
1723 result.append("\t\t- Input configuration:\n");
1724 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
1725 result.appendFormat("\t\t\t%p %05zu %05d %08x %6d (%s)\n",
1726 mConfig.inputCfg.buffer.raw,
1727 mConfig.inputCfg.buffer.frameCount,
1728 mConfig.inputCfg.samplingRate,
1729 mConfig.inputCfg.channels,
1730 mConfig.inputCfg.format,
1731 toString(static_cast<audio_format_t>(mConfig.inputCfg.format)).c_str());
1732
1733 result.append("\t\t- Output configuration:\n");
1734 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
1735 result.appendFormat("\t\t\t%p %05zu %05d %08x %6d (%s)\n",
1736 mConfig.outputCfg.buffer.raw,
1737 mConfig.outputCfg.buffer.frameCount,
1738 mConfig.outputCfg.samplingRate,
1739 mConfig.outputCfg.channels,
1740 mConfig.outputCfg.format,
1741 toString(static_cast<audio_format_t>(mConfig.outputCfg.format)).c_str());
1742
1743 result.appendFormat("\t\t- HAL buffers:\n"
1744 "\t\t\tIn(%s) InConversion(%s) Out(%s) OutConversion(%s)\n",
1745 dumpInOutBuffer(true /* isInput */, mInBuffer).c_str(),
1746 dumpInOutBuffer(true /* isInput */, mInConversionBuffer).c_str(),
1747 dumpInOutBuffer(false /* isInput */, mOutBuffer).c_str(),
1748 dumpInOutBuffer(false /* isInput */, mOutConversionBuffer).c_str());
1749
1750 write(fd, result.c_str(), result.length());
1751
1752 if (mEffectInterface != 0) {
1753 dprintf(fd, "\tEffect ID %d HAL dump:\n", mId);
1754 (void)mEffectInterface->dump(fd);
1755 }
1756
1757 }
1758
1759 // ----------------------------------------------------------------------------
1760 // EffectHandle implementation
1761 // ----------------------------------------------------------------------------
1762
1763 #undef LOG_TAG
1764 #define LOG_TAG "EffectHandle"
1765
1766 /* static */
create(const sp<IAfEffectBase> & effect,const sp<Client> & client,const sp<media::IEffectClient> & effectClient,int32_t priority,bool notifyFramesProcessed)1767 sp<IAfEffectHandle> IAfEffectHandle::create(
1768 const sp<IAfEffectBase>& effect,
1769 const sp<Client>& client,
1770 const sp<media::IEffectClient>& effectClient,
1771 int32_t priority, bool notifyFramesProcessed)
1772 {
1773 if (client == nullptr && effectClient == nullptr) {
1774 return sp<InternalEffectHandle>::make(effect, notifyFramesProcessed);
1775 }
1776 return sp<EffectHandle>::make(
1777 effect, client, effectClient, priority, notifyFramesProcessed);
1778 }
1779
EffectHandle(const sp<IAfEffectBase> & effect,const sp<Client> & client,const sp<media::IEffectClient> & effectClient,int32_t priority,bool notifyFramesProcessed,bool isInternal,audio_utils::MutexOrder mutexOrder)1780 EffectHandle::EffectHandle(const sp<IAfEffectBase>& effect,
1781 const sp<Client>& client,
1782 const sp<media::IEffectClient>& effectClient,
1783 int32_t priority, bool notifyFramesProcessed,
1784 bool isInternal,
1785 audio_utils::MutexOrder mutexOrder)
1786 : BnEffect(), mMutex(mutexOrder),
1787 mEffect(effect), mEffectClient(media::EffectClientAsyncProxy::makeIfNeeded(effectClient)),
1788 mClient(client), mCblk(nullptr),
1789 mPriority(priority), mHasControl(false), mEnabled(false), mDisconnected(false),
1790 mNotifyFramesProcessed(notifyFramesProcessed), mIsInternal(isInternal)
1791 {
1792 ALOGV("constructor %p client %p", this, client.get());
1793 setMinSchedulerPolicy(SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
1794 setInheritRt(true);
1795
1796 if (client == 0) {
1797 return;
1798 }
1799 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
1800 mCblkMemory = client->allocator().allocate(mediautils::NamedAllocRequest{
1801 {static_cast<size_t>(EFFECT_PARAM_BUFFER_SIZE + bufOffset)},
1802 std::string("Effect ID: ")
1803 .append(std::to_string(effect->id()))
1804 .append(" Session ID: ")
1805 .append(std::to_string(static_cast<int>(effect->sessionId())))
1806 .append(" \n")
1807 });
1808 if (mCblkMemory == 0 ||
1809 (mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->unsecurePointer())) == NULL) {
1810 ALOGE("not enough memory for Effect size=%zu", EFFECT_PARAM_BUFFER_SIZE +
1811 sizeof(effect_param_cblk_t));
1812 mCblkMemory.clear();
1813 return;
1814 }
1815 new(mCblk) effect_param_cblk_t();
1816 mBuffer = (uint8_t *)mCblk + bufOffset;
1817 }
1818
~EffectHandle()1819 EffectHandle::~EffectHandle()
1820 {
1821 ALOGV("Destructor %p", this);
1822 disconnect(false);
1823 }
1824
1825 // Creates an association between Binder code to name for IEffect.
1826 #define IEFFECT_BINDER_METHOD_MACRO_LIST \
1827 BINDER_METHOD_ENTRY(enable) \
1828 BINDER_METHOD_ENTRY(disable) \
1829 BINDER_METHOD_ENTRY(command) \
1830 BINDER_METHOD_ENTRY(disconnect) \
1831 BINDER_METHOD_ENTRY(getCblk) \
1832 BINDER_METHOD_ENTRY(getConfig) \
1833
1834 // singleton for Binder Method Statistics for IEffect
getIEffectStatistics()1835 mediautils::MethodStatistics<int>& getIEffectStatistics() {
1836 using Code = int;
1837
1838 #pragma push_macro("BINDER_METHOD_ENTRY")
1839 #undef BINDER_METHOD_ENTRY
1840 #define BINDER_METHOD_ENTRY(ENTRY) \
1841 {(Code)media::BnEffect::TRANSACTION_##ENTRY, #ENTRY},
1842
1843 static mediautils::MethodStatistics<Code> methodStatistics{
1844 IEFFECT_BINDER_METHOD_MACRO_LIST
1845 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
1846 };
1847 #pragma pop_macro("BINDER_METHOD_ENTRY")
1848
1849 return methodStatistics;
1850 }
1851
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1852 status_t EffectHandle::onTransact(
1853 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
1854 const std::string methodName = getIEffectStatistics().getMethodForCode(code);
1855 mediautils::TimeCheck check(
1856 std::string("IEffect::").append(methodName),
1857 [code](bool timeout, float elapsedMs) {
1858 if (timeout) {
1859 ; // we don't timeout right now on the effect interface.
1860 } else {
1861 getIEffectStatistics().event(code, elapsedMs);
1862 }
1863 }, {} /* timeoutDuration */, {} /* secondChanceDuration */, false /* crashOnTimeout */);
1864 return BnEffect::onTransact(code, data, reply, flags);
1865 }
1866
initCheck() const1867 status_t EffectHandle::initCheck() const
1868 {
1869 return mClient == 0 || mCblkMemory != 0 ? OK : NO_MEMORY;
1870 }
1871
1872 #define RETURN(code) \
1873 *_aidl_return = (code); \
1874 return Status::ok();
1875
1876 #define VALUE_OR_RETURN_STATUS_AS_OUT(exp) \
1877 ({ \
1878 auto _tmp = (exp); \
1879 if (!_tmp.ok()) { RETURN(_tmp.error()); } \
1880 std::move(_tmp.value()); \
1881 })
1882
enable(int32_t * _aidl_return)1883 Status EffectHandle::enable(int32_t* _aidl_return)
1884 {
1885 audio_utils::lock_guard _l(mutex());
1886 ALOGV("enable %p", this);
1887 sp<IAfEffectBase> effect = mEffect.promote();
1888 if (effect == 0 || mDisconnected) {
1889 RETURN(DEAD_OBJECT);
1890 }
1891 if (!mHasControl) {
1892 RETURN(INVALID_OPERATION);
1893 }
1894
1895 if (mEnabled) {
1896 RETURN(NO_ERROR);
1897 }
1898
1899 mEnabled = true;
1900
1901 status_t status = effect->updatePolicyState();
1902 if (status != NO_ERROR) {
1903 mEnabled = false;
1904 RETURN(status);
1905 }
1906
1907 effect->checkSuspendOnEffectEnabled(true, false /*threadLocked*/);
1908
1909 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
1910 if (effect->suspended()) {
1911 RETURN(NO_ERROR);
1912 }
1913
1914 status = effect->setEnabled(true, true /*fromHandle*/);
1915 if (status != NO_ERROR) {
1916 mEnabled = false;
1917 }
1918 RETURN(status);
1919 }
1920
disable(int32_t * _aidl_return)1921 Status EffectHandle::disable(int32_t* _aidl_return)
1922 {
1923 ALOGV("disable %p", this);
1924 audio_utils::lock_guard _l(mutex());
1925 sp<IAfEffectBase> effect = mEffect.promote();
1926 if (effect == 0 || mDisconnected) {
1927 RETURN(DEAD_OBJECT);
1928 }
1929 if (!mHasControl) {
1930 RETURN(INVALID_OPERATION);
1931 }
1932
1933 if (!mEnabled) {
1934 RETURN(NO_ERROR);
1935 }
1936 mEnabled = false;
1937
1938 effect->updatePolicyState();
1939
1940 if (effect->suspended()) {
1941 RETURN(NO_ERROR);
1942 }
1943
1944 status_t status = effect->setEnabled(false, true /*fromHandle*/);
1945 RETURN(status);
1946 }
1947
disconnect()1948 Status EffectHandle::disconnect()
1949 {
1950 ALOGV("%s %p", __FUNCTION__, this);
1951 disconnect(true);
1952 return Status::ok();
1953 }
1954
disconnect(bool unpinIfLast)1955 void EffectHandle::disconnect(bool unpinIfLast)
1956 {
1957 audio_utils::unique_lock _l(mutex());
1958 ALOGV("disconnect(%s) %p", unpinIfLast ? "true" : "false", this);
1959 if (mDisconnected) {
1960 if (unpinIfLast) {
1961 android_errorWriteLog(0x534e4554, "32707507");
1962 }
1963 return;
1964 }
1965 mDisconnected = true;
1966 {
1967 sp<IAfEffectBase> effect = mEffect.promote();
1968 if (effect != 0) {
1969 // Unlock e.g. for device effect: may need to acquire AudioFlinger lock
1970 // Also Internal Effect Handle would require Proxy lock (and vice versa).
1971 if (isInternal()) {
1972 _l.unlock();
1973 }
1974 if (effect->disconnectHandle(this, unpinIfLast) > 0) {
1975 ALOGW("%s Effect handle %p disconnected after thread destruction",
1976 __func__, this);
1977 }
1978 effect->updatePolicyState();
1979 if (isInternal()) {
1980 _l.lock();
1981 }
1982 }
1983 }
1984
1985 if (mClient != 0) {
1986 if (mCblk != NULL) {
1987 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
1988 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
1989 }
1990 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
1991 // Client destructor must run with AudioFlinger client mutex locked
1992 audio_utils::lock_guard _l2(mClient->afClientCallback()->clientMutex());
1993 mClient.clear();
1994 }
1995 }
1996
getCblk(media::SharedFileRegion * _aidl_return)1997 Status EffectHandle::getCblk(media::SharedFileRegion* _aidl_return) {
1998 LOG_ALWAYS_FATAL_IF(!convertIMemoryToSharedFileRegion(mCblkMemory, _aidl_return));
1999 return Status::ok();
2000 }
2001
getConfig(media::EffectConfig * _config,int32_t * _aidl_return)2002 Status EffectHandle::getConfig(
2003 media::EffectConfig* _config, int32_t* _aidl_return) {
2004 audio_utils::lock_guard _l(mutex());
2005 sp<IAfEffectBase> effect = mEffect.promote();
2006 if (effect == nullptr || mDisconnected) {
2007 RETURN(DEAD_OBJECT);
2008 }
2009 sp<IAfEffectModule> effectModule = effect->asEffectModule();
2010 if (effectModule == nullptr) {
2011 RETURN(INVALID_OPERATION);
2012 }
2013 audio_config_base_t inputCfg = AUDIO_CONFIG_BASE_INITIALIZER;
2014 audio_config_base_t outputCfg = AUDIO_CONFIG_BASE_INITIALIZER;
2015 bool isOutput;
2016 status_t status = effectModule->getConfigs_l(&inputCfg, &outputCfg, &isOutput);
2017 if (status == NO_ERROR) {
2018 constexpr bool isInput = false; // effects always use 'OUT' channel masks.
2019 _config->inputCfg = VALUE_OR_RETURN_STATUS_AS_OUT(
2020 legacy2aidl_audio_config_base_t_AudioConfigBase(inputCfg, isInput));
2021 _config->outputCfg = VALUE_OR_RETURN_STATUS_AS_OUT(
2022 legacy2aidl_audio_config_base_t_AudioConfigBase(outputCfg, isInput));
2023 _config->isOnInputStream = !isOutput;
2024 }
2025 RETURN(status);
2026 }
2027
command(int32_t cmdCode,const std::vector<uint8_t> & cmdData,int32_t maxResponseSize,std::vector<uint8_t> * response,int32_t * _aidl_return)2028 Status EffectHandle::command(int32_t cmdCode,
2029 const std::vector<uint8_t>& cmdData,
2030 int32_t maxResponseSize,
2031 std::vector<uint8_t>* response,
2032 int32_t* _aidl_return)
2033 {
2034 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
2035 cmdCode, mHasControl, mEffect.unsafe_get());
2036
2037 // reject commands reserved for internal use by audio framework if coming from outside
2038 // of audioserver
2039 switch(cmdCode) {
2040 case EFFECT_CMD_ENABLE:
2041 case EFFECT_CMD_DISABLE:
2042 case EFFECT_CMD_SET_PARAM:
2043 case EFFECT_CMD_SET_PARAM_DEFERRED:
2044 case EFFECT_CMD_SET_PARAM_COMMIT:
2045 case EFFECT_CMD_GET_PARAM:
2046 break;
2047 default:
2048 if (cmdCode >= EFFECT_CMD_FIRST_PROPRIETARY) {
2049 break;
2050 }
2051 android_errorWriteLog(0x534e4554, "62019992");
2052 RETURN(BAD_VALUE);
2053 }
2054
2055 if (cmdCode == EFFECT_CMD_ENABLE) {
2056 if (maxResponseSize < static_cast<signed>(sizeof(int))) {
2057 android_errorWriteLog(0x534e4554, "32095713");
2058 RETURN(BAD_VALUE);
2059 }
2060 writeToBuffer(NO_ERROR, response);
2061 return enable(_aidl_return);
2062 } else if (cmdCode == EFFECT_CMD_DISABLE) {
2063 if (maxResponseSize < static_cast<signed>(sizeof(int))) {
2064 android_errorWriteLog(0x534e4554, "32095713");
2065 RETURN(BAD_VALUE);
2066 }
2067 writeToBuffer(NO_ERROR, response);
2068 return disable(_aidl_return);
2069 }
2070
2071 audio_utils::lock_guard _l(mutex());
2072 sp<IAfEffectBase> effect = mEffect.promote();
2073 if (effect == 0 || mDisconnected) {
2074 RETURN(DEAD_OBJECT);
2075 }
2076 // only get parameter command is permitted for applications not controlling the effect
2077 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
2078 RETURN(INVALID_OPERATION);
2079 }
2080
2081 // handle commands that are not forwarded transparently to effect engine
2082 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
2083 if (mClient == 0) {
2084 RETURN(INVALID_OPERATION);
2085 }
2086
2087 if (maxResponseSize < (signed)sizeof(int)) {
2088 android_errorWriteLog(0x534e4554, "32095713");
2089 RETURN(BAD_VALUE);
2090 }
2091 writeToBuffer(NO_ERROR, response);
2092
2093 // No need to trylock() here as this function is executed in the binder thread serving a
2094 // particular client process: no risk to block the whole media server process or mixer
2095 // threads if we are stuck here
2096 Mutex::Autolock _l2(mCblk->lock);
2097 // keep local copy of index in case of client corruption b/32220769
2098 const uint32_t clientIndex = mCblk->clientIndex;
2099 const uint32_t serverIndex = mCblk->serverIndex;
2100 if (clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
2101 serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
2102 mCblk->serverIndex = 0;
2103 mCblk->clientIndex = 0;
2104 RETURN(BAD_VALUE);
2105 }
2106 status_t status = NO_ERROR;
2107 std::vector<uint8_t> param;
2108 for (uint32_t index = serverIndex; index < clientIndex;) {
2109 int *p = (int *)(mBuffer + index);
2110 const int size = *p++;
2111 if (size < 0
2112 || size > EFFECT_PARAM_BUFFER_SIZE
2113 || ((uint8_t *)p + size) > mBuffer + clientIndex) {
2114 ALOGW("command(): invalid parameter block size");
2115 status = BAD_VALUE;
2116 break;
2117 }
2118
2119 std::copy(reinterpret_cast<const uint8_t*>(p),
2120 reinterpret_cast<const uint8_t*>(p) + size,
2121 std::back_inserter(param));
2122
2123 std::vector<uint8_t> replyBuffer;
2124 status_t ret = effect->command(EFFECT_CMD_SET_PARAM,
2125 param,
2126 sizeof(int),
2127 &replyBuffer);
2128 int reply = *reinterpret_cast<const int*>(replyBuffer.data());
2129
2130 // verify shared memory: server index shouldn't change; client index can't go back.
2131 if (serverIndex != mCblk->serverIndex
2132 || clientIndex > mCblk->clientIndex) {
2133 android_errorWriteLog(0x534e4554, "32220769");
2134 status = BAD_VALUE;
2135 break;
2136 }
2137
2138 // stop at first error encountered
2139 if (ret != NO_ERROR) {
2140 status = ret;
2141 writeToBuffer(reply, response);
2142 break;
2143 } else if (reply != NO_ERROR) {
2144 writeToBuffer(reply, response);
2145 break;
2146 }
2147 index += size;
2148 }
2149 mCblk->serverIndex = 0;
2150 mCblk->clientIndex = 0;
2151 RETURN(status);
2152 }
2153
2154 status_t status = effect->command(cmdCode,
2155 cmdData,
2156 maxResponseSize,
2157 response);
2158 RETURN(status);
2159 }
2160
setControl(bool hasControl,bool signal,bool enabled)2161 void EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
2162 {
2163 ALOGV("setControl %p control %d", this, hasControl);
2164
2165 mHasControl = hasControl;
2166 mEnabled = enabled;
2167
2168 if (signal && mEffectClient != 0) {
2169 mEffectClient->controlStatusChanged(hasControl);
2170 }
2171 }
2172
commandExecuted(uint32_t cmdCode,const std::vector<uint8_t> & cmdData,const std::vector<uint8_t> & replyData)2173 void EffectHandle::commandExecuted(uint32_t cmdCode,
2174 const std::vector<uint8_t>& cmdData,
2175 const std::vector<uint8_t>& replyData)
2176 {
2177 if (mEffectClient != 0) {
2178 mEffectClient->commandExecuted(cmdCode, cmdData, replyData);
2179 }
2180 }
2181
2182
2183
setEnabled(bool enabled)2184 void EffectHandle::setEnabled(bool enabled)
2185 {
2186 if (mEffectClient != 0) {
2187 mEffectClient->enableStatusChanged(enabled);
2188 }
2189 }
2190
framesProcessed(int32_t frames) const2191 void EffectHandle::framesProcessed(int32_t frames) const
2192 {
2193 if (mEffectClient != 0 && mNotifyFramesProcessed) {
2194 mEffectClient->framesProcessed(frames);
2195 }
2196 }
2197
dumpToBuffer(char * buffer,size_t size) const2198 void EffectHandle::dumpToBuffer(char* buffer, size_t size) const
2199 {
2200 std::optional<afutils::FallibleLockGuard> guard;
2201 if (mCblk != nullptr) {
2202 guard.emplace(mCblk->lock);
2203 }
2204
2205 snprintf(buffer, size, "\t\t\t%5d %5d %3s %3s %5u %5u\n",
2206 (mClient == 0) ? getpid() : mClient->pid(),
2207 mPriority,
2208 mHasControl ? "yes" : "no",
2209 guard.has_value() && *guard ? "yes" : "no",
2210 mCblk ? mCblk->clientIndex : 0,
2211 mCblk ? mCblk->serverIndex : 0
2212 );
2213 }
2214
2215 #undef LOG_TAG
2216 #define LOG_TAG "EffectChain"
2217
2218 /* static */
create(const sp<IAfThreadBase> & thread,audio_session_t sessionId,const sp<IAfThreadCallback> & afThreadCallback)2219 sp<IAfEffectChain> IAfEffectChain::create(
2220 const sp<IAfThreadBase>& thread,
2221 audio_session_t sessionId,
2222 const sp<IAfThreadCallback>& afThreadCallback)
2223 {
2224 return sp<EffectChain>::make(thread, sessionId, afThreadCallback);
2225 }
2226
EffectChain(const sp<IAfThreadBase> & thread,audio_session_t sessionId,const sp<IAfThreadCallback> & afThreadCallback)2227 EffectChain::EffectChain(const sp<IAfThreadBase>& thread, audio_session_t sessionId,
2228 const sp<IAfThreadCallback>& afThreadCallback)
2229 : mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
2230 mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
2231 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX),
2232 mEffectCallback(new EffectCallback(wp<EffectChain>(this), thread, afThreadCallback))
2233 {
2234 if (thread != nullptr) {
2235 mStrategy = thread->getStrategyForStream(AUDIO_STREAM_MUSIC);
2236 mMaxTailBuffers =
2237 ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
2238 thread->frameCount();
2239 }
2240 }
2241
getEffectFromDesc(effect_descriptor_t * descriptor) const2242 sp<IAfEffectModule> EffectChain::getEffectFromDesc(
2243 effect_descriptor_t *descriptor) const
2244 {
2245 audio_utils::lock_guard _l(mutex());
2246 size_t size = mEffects.size();
2247
2248 for (size_t i = 0; i < size; i++) {
2249 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
2250 return mEffects[i];
2251 }
2252 }
2253 return 0;
2254 }
2255
2256 // getEffectFromId_l() must be called with IAfThreadBase::mutex() held
getEffectFromId_l(int id) const2257 sp<IAfEffectModule> EffectChain::getEffectFromId_l(int id) const
2258 {
2259 audio_utils::lock_guard _l(mutex());
2260 size_t size = mEffects.size();
2261
2262 for (size_t i = 0; i < size; i++) {
2263 // by convention, return first effect if id provided is 0 (0 is never a valid id)
2264 if (id == 0 || mEffects[i]->id() == id) {
2265 return mEffects[i];
2266 }
2267 }
2268 return 0;
2269 }
2270
2271 // getEffectFromType_l() must be called with IAfThreadBase::mutex() held
getEffectFromType_l(const effect_uuid_t * type) const2272 sp<IAfEffectModule> EffectChain::getEffectFromType_l(
2273 const effect_uuid_t *type) const
2274 {
2275 audio_utils::lock_guard _l(mutex());
2276 size_t size = mEffects.size();
2277
2278 for (size_t i = 0; i < size; i++) {
2279 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
2280 return mEffects[i];
2281 }
2282 }
2283 return 0;
2284 }
2285
getEffectIds_l() const2286 std::vector<int> EffectChain::getEffectIds_l() const
2287 {
2288 std::vector<int> ids;
2289 audio_utils::lock_guard _l(mutex());
2290 for (size_t i = 0; i < mEffects.size(); i++) {
2291 ids.push_back(mEffects[i]->id());
2292 }
2293 return ids;
2294 }
2295
clearInputBuffer()2296 void EffectChain::clearInputBuffer()
2297 {
2298 audio_utils::lock_guard _l(mutex());
2299 clearInputBuffer_l();
2300 }
2301
2302 // Must be called with EffectChain::mutex() locked
clearInputBuffer_l()2303 void EffectChain::clearInputBuffer_l()
2304 {
2305 if (mInBuffer == NULL) {
2306 return;
2307 }
2308 const size_t frameSize = audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT)
2309 * mEffectCallback->inChannelCount(mEffects[0]->id());
2310
2311 memset(mInBuffer->audioBuffer()->raw, 0, mEffectCallback->frameCount() * frameSize);
2312 mInBuffer->commit();
2313 }
2314
2315 // Must be called with EffectChain::mutex() locked
process_l()2316 void EffectChain::process_l() {
2317 // never process effects when:
2318 // - on an OFFLOAD thread
2319 // - no more tracks are on the session and the effect tail has been rendered
2320 bool doProcess = !mEffectCallback->isOffloadOrMmap();
2321 if (!audio_is_global_session(mSessionId)) {
2322 bool tracksOnSession = (trackCnt() != 0);
2323
2324 if (!tracksOnSession && mTailBufferCount == 0) {
2325 doProcess = false;
2326 }
2327
2328 if (activeTrackCnt() == 0) {
2329 // if no track is active and the effect tail has not been rendered,
2330 // the input buffer must be cleared here as the mixer process will not do it
2331 if (tracksOnSession || mTailBufferCount > 0) {
2332 clearInputBuffer_l();
2333 if (mTailBufferCount > 0) {
2334 mTailBufferCount--;
2335 }
2336 }
2337 }
2338 }
2339
2340 size_t size = mEffects.size();
2341 if (doProcess) {
2342 // Only the input and output buffers of the chain can be external,
2343 // and 'update' / 'commit' do nothing for allocated buffers, thus
2344 // it's not needed to consider any other buffers here.
2345 mInBuffer->update();
2346 if (mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw) {
2347 mOutBuffer->update();
2348 }
2349 for (size_t i = 0; i < size; i++) {
2350 mEffects[i]->process();
2351 }
2352 mInBuffer->commit();
2353 if (mInBuffer->audioBuffer()->raw != mOutBuffer->audioBuffer()->raw) {
2354 mOutBuffer->commit();
2355 }
2356 }
2357 bool doResetVolume = false;
2358 for (size_t i = 0; i < size; i++) {
2359 // reset volume when any effect just started or stopped.
2360 // resetVolume_l will check if the volume controller effect in the chain needs update and
2361 // apply the correct volume
2362 doResetVolume = mEffects[i]->updateState_l() || doResetVolume;
2363 }
2364 if (doResetVolume) {
2365 resetVolume_l();
2366 }
2367 }
2368
createEffect(sp<IAfEffectModule> & effect,effect_descriptor_t * desc,int id,audio_session_t sessionId,bool pinned)2369 status_t EffectChain::createEffect(sp<IAfEffectModule>& effect,
2370 effect_descriptor_t *desc,
2371 int id,
2372 audio_session_t sessionId,
2373 bool pinned)
2374 {
2375 audio_utils::lock_guard _l(mutex());
2376 effect = new EffectModule(mEffectCallback, desc, id, sessionId, pinned, AUDIO_PORT_HANDLE_NONE);
2377 status_t lStatus = effect->status();
2378 if (lStatus == NO_ERROR) {
2379 lStatus = addEffect_l(effect);
2380 }
2381 if (lStatus != NO_ERROR) {
2382 effect.clear();
2383 }
2384 return lStatus;
2385 }
2386
addEffect(const sp<IAfEffectModule> & effect)2387 status_t EffectChain::addEffect(const sp<IAfEffectModule>& effect)
2388 {
2389 audio_utils::lock_guard _l(mutex());
2390 return addEffect_l(effect);
2391 }
2392 // addEffect_l() must be called with EffectChain::mutex() held
addEffect_l(const sp<IAfEffectModule> & effect)2393 status_t EffectChain::addEffect_l(const sp<IAfEffectModule>& effect)
2394 {
2395 effect->setCallback(mEffectCallback);
2396
2397 effect_descriptor_t desc = effect->desc();
2398 ssize_t idx_insert = 0;
2399 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2400 // Auxiliary effects are inserted at the beginning of mEffects vector as
2401 // they are processed first and accumulated in chain input buffer
2402 mEffects.insertAt(effect, idx_insert);
2403
2404 // the input buffer for auxiliary effect contains mono samples in
2405 // 32 bit format. This is to avoid saturation in AudoMixer
2406 // accumulation stage. Saturation is done in EffectModule::process() before
2407 // calling the process in effect engine
2408 size_t numSamples = mEffectCallback->frameCount();
2409 sp<EffectBufferHalInterface> halBuffer;
2410
2411 status_t result = mEffectCallback->allocateHalBuffer(
2412 numSamples * sizeof(float), &halBuffer);
2413 if (result != OK) return result;
2414
2415 effect->configure_l();
2416
2417 effect->setInBuffer(halBuffer);
2418 // auxiliary effects output samples to chain input buffer for further processing
2419 // by insert effects
2420 effect->setOutBuffer(mInBuffer);
2421 } else {
2422 idx_insert = getInsertIndex_l(desc);
2423 if (idx_insert < 0) {
2424 return INVALID_OPERATION;
2425 }
2426
2427 size_t previousSize = mEffects.size();
2428 mEffects.insertAt(effect, idx_insert);
2429
2430 effect->configure_l();
2431
2432 // - By default:
2433 // All effects read samples from chain input buffer.
2434 // The last effect in the chain, writes samples to chain output buffer,
2435 // otherwise to chain input buffer
2436 // - In the OUTPUT_STAGE chain of a spatializer mixer thread:
2437 // The spatializer effect (first effect) reads samples from the input buffer
2438 // and writes samples to the output buffer.
2439 // All other effects read and writes samples to the output buffer
2440 if (mEffectCallback->isSpatializer()
2441 && mSessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2442 effect->setOutBuffer(mOutBuffer);
2443 if (idx_insert == 0) {
2444 if (previousSize != 0) {
2445 mEffects[1]->configure_l();
2446 mEffects[1]->setInBuffer(mOutBuffer);
2447 mEffects[1]->updateAccessMode_l(); // reconfig if needed.
2448 }
2449 effect->setInBuffer(mInBuffer);
2450 } else {
2451 effect->setInBuffer(mOutBuffer);
2452 }
2453 } else {
2454 effect->setInBuffer(mInBuffer);
2455 if (idx_insert == static_cast<ssize_t>(previousSize)) {
2456 if (idx_insert != 0) {
2457 mEffects[idx_insert-1]->configure_l();
2458 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
2459 mEffects[idx_insert - 1]->updateAccessMode_l(); // reconfig if needed.
2460 }
2461 effect->setOutBuffer(mOutBuffer);
2462 } else {
2463 effect->setOutBuffer(mInBuffer);
2464 }
2465 }
2466 ALOGV("%s effect %p, added in chain %p at rank %zu",
2467 __func__, effect.get(), this, idx_insert);
2468 }
2469 effect->configure_l();
2470
2471 if (effect->isVolumeControl()) {
2472 const auto volumeControlIndex = findVolumeControl_l(0, mEffects.size());
2473 if (!volumeControlIndex.has_value() || (ssize_t)volumeControlIndex.value() < idx_insert) {
2474 // If this effect will be the new volume control effect when it is enabled, force
2475 // initializing the volume as 0 for volume control effect for safer ramping. The actual
2476 // volume will be set from setVolume_l.
2477 uint32_t left = 0;
2478 uint32_t right = 0;
2479 effect->setVolume_l(&left, &right, true /*controller*/, true /*force*/);
2480 }
2481 }
2482
2483 return NO_ERROR;
2484 }
2485
findVolumeControl_l(size_t from,size_t to) const2486 std::optional<size_t> EffectChain::findVolumeControl_l(size_t from, size_t to) const {
2487 for (size_t i = std::min(to, mEffects.size()); i > from; i--) {
2488 if (mEffects[i - 1]->isVolumeControlEnabled_l()) {
2489 return i - 1;
2490 }
2491 }
2492 return std::nullopt;
2493 }
2494
getInsertIndex_l(const effect_descriptor_t & desc)2495 ssize_t EffectChain::getInsertIndex_l(const effect_descriptor_t& desc) {
2496 // Insert effects are inserted at the end of mEffects vector as they are processed
2497 // after track and auxiliary effects.
2498 // Insert effect order as a function of indicated preference:
2499 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
2500 // another effect is present
2501 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
2502 // last effect claiming first position
2503 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
2504 // first effect claiming last position
2505 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
2506 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
2507 // already present
2508 // Spatializer or Downmixer effects are inserted in first position because
2509 // they adapt the channel count for all other effects in the chain
2510 if (IAfEffectModule::isSpatializer(&desc.type)
2511 || (memcmp(&desc.type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0)) {
2512 return 0;
2513 }
2514
2515 size_t size = mEffects.size();
2516 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
2517 ssize_t idx_insert;
2518 ssize_t idx_insert_first = -1;
2519 ssize_t idx_insert_last = -1;
2520
2521 idx_insert = size;
2522 for (size_t i = 0; i < size; i++) {
2523 effect_descriptor_t d = mEffects[i]->desc();
2524 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
2525 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
2526 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
2527 // check invalid effect chaining combinations
2528 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
2529 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
2530 ALOGW("%s could not insert effect %s: exclusive conflict with %s",
2531 __func__, desc.name, d.name);
2532 return -1;
2533 }
2534 // remember position of first insert effect and by default
2535 // select this as insert position for new effect
2536 if (idx_insert == static_cast<ssize_t>(size)) {
2537 idx_insert = i;
2538 }
2539 // remember position of last insert effect claiming
2540 // first position
2541 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
2542 idx_insert_first = i;
2543 }
2544 // remember position of first insert effect claiming
2545 // last position
2546 if (iPref == EFFECT_FLAG_INSERT_LAST &&
2547 idx_insert_last == -1) {
2548 idx_insert_last = i;
2549 }
2550 }
2551 }
2552
2553 // modify idx_insert from first position if needed
2554 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
2555 if (idx_insert_last != -1) {
2556 idx_insert = idx_insert_last;
2557 } else {
2558 idx_insert = size;
2559 }
2560 } else {
2561 if (idx_insert_first != -1) {
2562 idx_insert = idx_insert_first + 1;
2563 }
2564 }
2565 return idx_insert;
2566 }
2567
removeEffect(const sp<IAfEffectModule> & effect,bool release)2568 size_t EffectChain::removeEffect(const sp<IAfEffectModule>& effect,
2569 bool release)
2570 {
2571 audio_utils::lock_guard _l(mutex());
2572 size_t size = mEffects.size();
2573 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
2574
2575 const bool hasThreadAttached = mEffectCallback->hasThreadAttached();
2576 for (size_t i = 0; i < size; i++) {
2577 if (effect == mEffects[i]) {
2578 // calling stop here will remove pre-processing effect from the audio HAL.
2579 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
2580 // the middle of a read from audio HAL
2581 if (mEffects[i]->state() == EffectModule::ACTIVE ||
2582 mEffects[i]->state() == EffectModule::STOPPING) {
2583 mEffects[i]->stop_l();
2584 }
2585 if (release) {
2586 mEffects[i]->release_l("EffectChain::removeEffect");
2587 }
2588 // Skip operation when no thread attached (could lead to sigfpe as framecount is 0...)
2589 if (hasThreadAttached && type != EFFECT_FLAG_TYPE_AUXILIARY) {
2590 if (i == size - 1 && i != 0) {
2591 mEffects[i - 1]->configure_l();
2592 mEffects[i - 1]->setOutBuffer(mOutBuffer);
2593 mEffects[i - 1]->updateAccessMode_l(); // reconfig if needed.
2594 }
2595 }
2596 mEffects.removeAt(i);
2597
2598 // make sure the input buffer configuration for the new first effect in the chain
2599 // is updated if needed (can switch from HAL channel mask to mixer channel mask)
2600 if (type != EFFECT_FLAG_TYPE_AUXILIARY // TODO(b/284522658) breaks for aux FX, why?
2601 && hasThreadAttached && i == 0 && size > 1) {
2602 mEffects[0]->configure_l();
2603 mEffects[0]->setInBuffer(mInBuffer);
2604 mEffects[0]->updateAccessMode_l(); // reconfig if needed.
2605 }
2606
2607 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %zu", effect.get(),
2608 this, i);
2609 break;
2610 }
2611 }
2612
2613 return mEffects.size();
2614 }
2615
2616 // setDevices_l() must be called with IAfThreadBase::mutex() held
setDevices_l(const AudioDeviceTypeAddrVector & devices)2617 void EffectChain::setDevices_l(const AudioDeviceTypeAddrVector &devices)
2618 {
2619 audio_utils::lock_guard _l(mutex());
2620 size_t size = mEffects.size();
2621 for (size_t i = 0; i < size; i++) {
2622 mEffects[i]->setDevices(devices);
2623 }
2624 }
2625
2626 // setInputDevice_l() must be called with IAfThreadBase::mutex() held
setInputDevice_l(const AudioDeviceTypeAddr & device)2627 void EffectChain::setInputDevice_l(const AudioDeviceTypeAddr &device)
2628 {
2629 audio_utils::lock_guard _l(mutex());
2630 size_t size = mEffects.size();
2631 for (size_t i = 0; i < size; i++) {
2632 mEffects[i]->setInputDevice(device);
2633 }
2634 }
2635
2636 // setMode_l() must be called with IAfThreadBase::mutex() held
setMode_l(audio_mode_t mode)2637 void EffectChain::setMode_l(audio_mode_t mode)
2638 {
2639 audio_utils::lock_guard _l(mutex());
2640 size_t size = mEffects.size();
2641 for (size_t i = 0; i < size; i++) {
2642 mEffects[i]->setMode(mode);
2643 }
2644 }
2645
2646 // setAudioSource_l() must be called with IAfThreadBase::mutex() held
setAudioSource_l(audio_source_t source)2647 void EffectChain::setAudioSource_l(audio_source_t source)
2648 {
2649 audio_utils::lock_guard _l(mutex());
2650 size_t size = mEffects.size();
2651 for (size_t i = 0; i < size; i++) {
2652 mEffects[i]->setAudioSource(source);
2653 }
2654 }
2655
hasVolumeControlEnabled_l() const2656 bool EffectChain::hasVolumeControlEnabled_l() const {
2657 for (const auto &effect : mEffects) {
2658 if (effect->isVolumeControlEnabled_l()) return true;
2659 }
2660 return false;
2661 }
2662
2663 // setVolume() must be called without EffectChain::mutex()
setVolume(uint32_t * left,uint32_t * right,bool force)2664 bool EffectChain::setVolume(uint32_t* left, uint32_t* right, bool force) {
2665 audio_utils::lock_guard _l(mutex());
2666 return setVolume_l(left, right, force);
2667 }
2668
2669 // setVolume_l() must be called with EffectChain::mutex() held
setVolume_l(uint32_t * left,uint32_t * right,bool force)2670 bool EffectChain::setVolume_l(uint32_t* left, uint32_t* right, bool force) {
2671 uint32_t newLeft = *left;
2672 uint32_t newRight = *right;
2673 const size_t size = mEffects.size();
2674
2675 // first update volume controller
2676 const auto volumeControlIndex = findVolumeControl_l(0, size);
2677 // index of the effect chain volume controller
2678 const int ctrlIdx = volumeControlIndex.value_or(-1);
2679 const sp<IAfEffectModule> volumeControlEffect =
2680 volumeControlIndex.has_value() ? mEffects[ctrlIdx] : nullptr;
2681 const sp<IAfEffectModule> cachedVolumeControlEffect = mVolumeControlEffect.promote();
2682
2683 if (!force && volumeControlEffect == cachedVolumeControlEffect &&
2684 *left == mLeftVolume && *right == mRightVolume) {
2685 if (volumeControlIndex.has_value()) {
2686 *left = mNewLeftVolume;
2687 *right = mNewRightVolume;
2688 }
2689 return volumeControlIndex.has_value();
2690 }
2691 mVolumeControlEffect = volumeControlEffect;
2692
2693 for (int i = 0; i < ctrlIdx; ++i) {
2694 // For all effects before the effect that controls volume, they are not controlling the
2695 // effect chain volume, if these effects has the volume control capability, set the volume
2696 // to maximum to avoid double attenuation.
2697 if (mEffects[i]->isVolumeControl()) {
2698 uint32_t leftMax = 1 << 24;
2699 uint32_t rightMax = 1 << 24;
2700 mEffects[i]->setVolume_l(&leftMax, &rightMax,
2701 false /* not an effect chain volume controller */,
2702 true /* force */);
2703 }
2704 }
2705
2706 mLeftVolume = newLeft;
2707 mRightVolume = newRight;
2708
2709 // second get volume update from volume controller
2710 if (ctrlIdx >= 0) {
2711 mEffects[ctrlIdx]->setVolume_l(&newLeft, &newRight,
2712 true /* effect chain volume controller */);
2713 mNewLeftVolume = newLeft;
2714 mNewRightVolume = newRight;
2715 ALOGD("%s sessionId %d volume controller effect %s set (%d, %d), ret (%d, %d)", __func__,
2716 mSessionId, mEffects[ctrlIdx]->desc().name, mLeftVolume, mRightVolume, newLeft,
2717 newRight);
2718 }
2719 // then indicate volume to all other effects in chain.
2720 // Pass altered volume to effects before volume controller
2721 // and requested volume to effects after controller or with volume monitor flag
2722 uint32_t lVol = newLeft;
2723 uint32_t rVol = newRight;
2724
2725 for (size_t i = 0; i < size; i++) {
2726 if ((int)i == ctrlIdx) {
2727 continue;
2728 }
2729 // this also works for ctrlIdx == -1 when there is no volume controller
2730 if ((int)i > ctrlIdx) {
2731 lVol = *left;
2732 rVol = *right;
2733 }
2734 // Pass requested volume directly if this is volume monitor module
2735 if (mEffects[i]->isVolumeMonitor()) {
2736 mEffects[i]->setVolume_l(left, right,
2737 false /* not an effect chain volume controller */);
2738 } else {
2739 mEffects[i]->setVolume_l(&lVol, &rVol,
2740 false /* not an effect chain volume controller */);
2741 }
2742 }
2743 *left = newLeft;
2744 *right = newRight;
2745
2746 setVolumeForOutput_l(*left, *right);
2747
2748 return volumeControlIndex.has_value();
2749 }
2750
2751 // resetVolume_l() must be called with EffectChain::mutex() held
resetVolume_l()2752 void EffectChain::resetVolume_l()
2753 {
2754 if ((mLeftVolume != UINT_MAX) && (mRightVolume != UINT_MAX)) {
2755 uint32_t left = mLeftVolume;
2756 uint32_t right = mRightVolume;
2757 (void)setVolume_l(&left, &right, true);
2758 }
2759 }
2760
containsHapticGeneratingEffect()2761 bool EffectChain::containsHapticGeneratingEffect()
2762 {
2763 audio_utils::lock_guard _l(mutex());
2764 return containsHapticGeneratingEffect_l();
2765 }
2766 // containsHapticGeneratingEffect_l must be called with EffectChain::mutex() held
containsHapticGeneratingEffect_l()2767 bool EffectChain::containsHapticGeneratingEffect_l()
2768 {
2769 for (size_t i = 0; i < mEffects.size(); ++i) {
2770 if (mEffects[i]->isHapticGenerator()) {
2771 return true;
2772 }
2773 }
2774 return false;
2775 }
2776
setHapticScale_l(int id,os::HapticScale hapticScale)2777 void EffectChain::setHapticScale_l(int id, os::HapticScale hapticScale)
2778 {
2779 audio_utils::lock_guard _l(mutex());
2780 for (size_t i = 0; i < mEffects.size(); ++i) {
2781 mEffects[i]->setHapticScale_l(id, hapticScale);
2782 }
2783 }
2784
syncHalEffectsState_l()2785 void EffectChain::syncHalEffectsState_l()
2786 {
2787 audio_utils::lock_guard _l(mutex());
2788 for (size_t i = 0; i < mEffects.size(); i++) {
2789 if (mEffects[i]->state() == EffectModule::ACTIVE ||
2790 mEffects[i]->state() == EffectModule::STOPPING) {
2791 mEffects[i]->addEffectToHal_l();
2792 }
2793 }
2794 }
2795
dump(int fd,const Vector<String16> & args) const2796 void EffectChain::dump(int fd, const Vector<String16>& args) const
2797 {
2798 String8 result;
2799 afutils::FallibleLockGuard l{mutex()};
2800 const size_t numEffects = mEffects.size();
2801 result.appendFormat(" %zu effects for session %d\n", numEffects, mSessionId);
2802 if (numEffects == 0) {
2803 write(fd, result.c_str(), result.size());
2804 return;
2805 }
2806
2807
2808 // failed to lock - AudioFlinger is probably deadlocked
2809 if (!l) {
2810 result.append("\tCould not lock mutex:\n");
2811 }
2812
2813 const std::string inBufferStr = dumpInOutBuffer(true /* isInput */, mInBuffer);
2814 const std::string outBufferStr = dumpInOutBuffer(false /* isInput */, mOutBuffer);
2815 result.appendFormat("\t%-*s%-*s Active tracks:\n",
2816 (int)inBufferStr.size(), "In buffer ",
2817 (int)outBufferStr.size(), "Out buffer ");
2818 result.appendFormat("\t%s %s %d\n",
2819 inBufferStr.c_str(), outBufferStr.c_str(), mActiveTrackCnt);
2820 write(fd, result.c_str(), result.size());
2821
2822 for (size_t i = 0; i < numEffects; ++i) {
2823 sp<IAfEffectModule> effect = mEffects[i];
2824 if (effect != 0) {
2825 effect->dump(fd, args);
2826 }
2827 }
2828 }
2829
2830 // must be called with IAfThreadBase::mutex() held
setEffectSuspended_l(const effect_uuid_t * type,bool suspend)2831 void EffectChain::setEffectSuspended_l(
2832 const effect_uuid_t *type, bool suspend)
2833 {
2834 sp<SuspendedEffectDesc> desc;
2835 // use effect type UUID timelow as key as there is no real risk of identical
2836 // timeLow fields among effect type UUIDs.
2837 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
2838 if (suspend) {
2839 if (index >= 0) {
2840 desc = mSuspendedEffects.valueAt(index);
2841 } else {
2842 desc = new SuspendedEffectDesc();
2843 desc->mType = *type;
2844 mSuspendedEffects.add(type->timeLow, desc);
2845 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
2846 }
2847
2848 if (desc->mRefCount++ == 0) {
2849 sp<IAfEffectModule> effect = getEffectIfEnabled_l(type);
2850 if (effect != 0) {
2851 desc->mEffect = effect;
2852 effect->setSuspended(true);
2853 effect->setEnabled(false, false /*fromHandle*/);
2854 }
2855 }
2856 } else {
2857 if (index < 0) {
2858 return;
2859 }
2860 desc = mSuspendedEffects.valueAt(index);
2861 if (desc->mRefCount <= 0) {
2862 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
2863 desc->mRefCount = 0;
2864 return;
2865 }
2866 if (--desc->mRefCount == 0) {
2867 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
2868 if (desc->mEffect != 0) {
2869 sp<IAfEffectModule> effect = desc->mEffect.promote();
2870 if (effect != 0) {
2871 effect->setSuspended(false);
2872 effect->mutex().lock();
2873 IAfEffectHandle *handle = effect->controlHandle_l();
2874 if (handle != NULL && !handle->disconnected()) {
2875 effect->setEnabled_l(handle->enabled());
2876 }
2877 effect->mutex().unlock();
2878 }
2879 desc->mEffect.clear();
2880 }
2881 mSuspendedEffects.removeItemsAt(index);
2882 }
2883 }
2884 }
2885
2886 // must be called with IAfThreadBase::mutex() held
setEffectSuspendedAll_l(bool suspend)2887 void EffectChain::setEffectSuspendedAll_l(bool suspend)
2888 {
2889 sp<SuspendedEffectDesc> desc;
2890
2891 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
2892 if (suspend) {
2893 if (index >= 0) {
2894 desc = mSuspendedEffects.valueAt(index);
2895 } else {
2896 desc = new SuspendedEffectDesc();
2897 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
2898 ALOGV("setEffectSuspendedAll_l() add entry for 0");
2899 }
2900 if (desc->mRefCount++ == 0) {
2901 Vector< sp<IAfEffectModule> > effects;
2902 getSuspendEligibleEffects(effects);
2903 for (size_t i = 0; i < effects.size(); i++) {
2904 setEffectSuspended_l(&effects[i]->desc().type, true);
2905 }
2906 }
2907 } else {
2908 if (index < 0) {
2909 return;
2910 }
2911 desc = mSuspendedEffects.valueAt(index);
2912 if (desc->mRefCount <= 0) {
2913 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
2914 desc->mRefCount = 1;
2915 }
2916 if (--desc->mRefCount == 0) {
2917 Vector<const effect_uuid_t *> types;
2918 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
2919 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
2920 continue;
2921 }
2922 types.add(&mSuspendedEffects.valueAt(i)->mType);
2923 }
2924 for (size_t i = 0; i < types.size(); i++) {
2925 setEffectSuspended_l(types[i], false);
2926 }
2927 ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
2928 mSuspendedEffects.keyAt(index));
2929 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
2930 }
2931 }
2932 }
2933
2934
2935 // The volume effect is used for automated tests only
2936 #ifndef OPENSL_ES_H_
2937 static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
2938 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
2939 const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
2940 #endif //OPENSL_ES_H_
2941
2942 /* static */
isEffectEligibleForBtNrecSuspend_l(const effect_uuid_t * type)2943 bool EffectChain::isEffectEligibleForBtNrecSuspend_l(const effect_uuid_t* type) {
2944 // Only NS and AEC are suspended when BtNRec is off
2945 if ((memcmp(type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0) ||
2946 (memcmp(type, FX_IID_NS, sizeof(effect_uuid_t)) == 0)) {
2947 return true;
2948 }
2949 return false;
2950 }
2951
isEffectEligibleForSuspend(const effect_descriptor_t & desc)2952 bool EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
2953 {
2954 // auxiliary effects and visualizer are never suspended on output mix
2955 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
2956 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
2957 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
2958 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0) ||
2959 (memcmp(&desc.type, SL_IID_DYNAMICSPROCESSING, sizeof(effect_uuid_t)) == 0))) {
2960 return false;
2961 }
2962 return true;
2963 }
2964
getSuspendEligibleEffects(Vector<sp<IAfEffectModule>> & effects)2965 void EffectChain::getSuspendEligibleEffects(
2966 Vector< sp<IAfEffectModule> > &effects)
2967 {
2968 effects.clear();
2969 audio_utils::lock_guard _l(mutex());
2970 for (size_t i = 0; i < mEffects.size(); i++) {
2971 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
2972 effects.add(mEffects[i]);
2973 }
2974 }
2975 }
2976
getEffectIfEnabled_l(const effect_uuid_t * type)2977 sp<IAfEffectModule> EffectChain::getEffectIfEnabled_l(const effect_uuid_t *type)
2978 {
2979 sp<IAfEffectModule> effect = getEffectFromType_l(type);
2980 return effect != 0 && effect->isEnabled() ? effect : 0;
2981 }
2982
checkSuspendOnEffectEnabled_l(const sp<IAfEffectModule> & effect,bool enabled)2983 void EffectChain::checkSuspendOnEffectEnabled_l(const sp<IAfEffectModule>& effect, bool enabled) {
2984 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
2985 if (enabled) {
2986 if (index < 0) {
2987 // if the effect is not suspend check if all effects are suspended
2988 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
2989 if (index < 0) {
2990 return;
2991 }
2992 if (!isEffectEligibleForSuspend(effect->desc())) {
2993 return;
2994 }
2995 setEffectSuspended_l(&effect->desc().type, enabled);
2996 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
2997 if (index < 0) {
2998 ALOGW("%s Fx should be suspended here!", __func__);
2999 return;
3000 }
3001 }
3002 ALOGV("%s enable suspending fx %08x", __func__, effect->desc().type.timeLow);
3003 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
3004 // if effect is requested to suspended but was not yet enabled, suspend it now.
3005 if (desc->mEffect == 0) {
3006 desc->mEffect = effect;
3007 effect->setEnabled(false, false /*fromHandle*/);
3008 effect->setSuspended(true);
3009 }
3010 } else {
3011 if (index < 0) {
3012 return;
3013 }
3014 ALOGV("%s disable restoring fx %08x", __func__, effect->desc().type.timeLow);
3015 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
3016 desc->mEffect.clear();
3017 effect->setSuspended(false);
3018 }
3019 }
3020
isNonOffloadableEnabled() const3021 bool EffectChain::isNonOffloadableEnabled() const
3022 {
3023 audio_utils::lock_guard _l(mutex());
3024 return isNonOffloadableEnabled_l();
3025 }
3026
isNonOffloadableEnabled_l() const3027 bool EffectChain::isNonOffloadableEnabled_l() const
3028 {
3029 size_t size = mEffects.size();
3030 for (size_t i = 0; i < size; i++) {
3031 if (mEffects[i]->isEnabled() && !mEffects[i]->isOffloadable()) {
3032 return true;
3033 }
3034 }
3035 return false;
3036 }
3037
setThread(const sp<IAfThreadBase> & thread)3038 void EffectChain::setThread(const sp<IAfThreadBase>& thread)
3039 {
3040 if (thread != nullptr) {
3041 mStrategy = thread->getStrategyForStream(AUDIO_STREAM_MUSIC);
3042 mMaxTailBuffers =
3043 ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
3044 thread->frameCount();
3045 }
3046 audio_utils::lock_guard _l(mutex());
3047 mEffectCallback->setThread(thread);
3048 }
3049
checkOutputFlagCompatibility(audio_output_flags_t * flags) const3050 void EffectChain::checkOutputFlagCompatibility(audio_output_flags_t *flags) const
3051 {
3052 if ((*flags & AUDIO_OUTPUT_FLAG_RAW) != 0 && !isRawCompatible()) {
3053 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_RAW);
3054 }
3055 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0 && !isFastCompatible()) {
3056 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
3057 }
3058 if ((*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != 0 && !isBitPerfectCompatible()) {
3059 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_BIT_PERFECT);
3060 }
3061 }
3062
checkInputFlagCompatibility(audio_input_flags_t * flags) const3063 void EffectChain::checkInputFlagCompatibility(audio_input_flags_t *flags) const
3064 {
3065 if ((*flags & AUDIO_INPUT_FLAG_RAW) != 0 && !isRawCompatible()) {
3066 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_RAW);
3067 }
3068 if ((*flags & AUDIO_INPUT_FLAG_FAST) != 0 && !isFastCompatible()) {
3069 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
3070 }
3071 }
3072
isRawCompatible() const3073 bool EffectChain::isRawCompatible() const
3074 {
3075 audio_utils::lock_guard _l(mutex());
3076 for (const auto &effect : mEffects) {
3077 if (effect->isProcessImplemented()) {
3078 return false;
3079 }
3080 }
3081 // Allow effects without processing.
3082 return true;
3083 }
3084
isFastCompatible() const3085 bool EffectChain::isFastCompatible() const
3086 {
3087 audio_utils::lock_guard _l(mutex());
3088 for (const auto &effect : mEffects) {
3089 if (effect->isProcessImplemented()
3090 && effect->isImplementationSoftware()) {
3091 return false;
3092 }
3093 }
3094 // Allow effects without processing or hw accelerated effects.
3095 return true;
3096 }
3097
isBitPerfectCompatible() const3098 bool EffectChain::isBitPerfectCompatible() const {
3099 audio_utils::lock_guard _l(mutex());
3100 for (const auto &effect : mEffects) {
3101 if (effect->isProcessImplemented()
3102 && effect->isImplementationSoftware()) {
3103 return false;
3104 }
3105 }
3106 // Allow effects without processing or hw accelerated effects.
3107 return true;
3108 }
3109
3110 // isCompatibleWithThread_l() must be called with thread->mutex() held
isCompatibleWithThread_l(const sp<IAfThreadBase> & thread) const3111 bool EffectChain::isCompatibleWithThread_l(const sp<IAfThreadBase>& thread) const
3112 {
3113 audio_utils::lock_guard _l(mutex());
3114 for (size_t i = 0; i < mEffects.size(); i++) {
3115 if (thread->checkEffectCompatibility_l(&(mEffects[i]->desc()), mSessionId) != NO_ERROR) {
3116 return false;
3117 }
3118 }
3119 return true;
3120 }
3121
3122 // sendMetadata_l() must be called with thread->mutex() held
sendMetadata_l(const std::vector<playback_track_metadata_v7_t> & allMetadata,const std::optional<const std::vector<playback_track_metadata_v7_t>> spatializedMetadata)3123 void EffectChain::sendMetadata_l(const std::vector<playback_track_metadata_v7_t>& allMetadata,
3124 const std::optional<const std::vector<playback_track_metadata_v7_t>> spatializedMetadata) {
3125 audio_utils::lock_guard _l(mutex());
3126 for (const auto& effect : mEffects) {
3127 if (spatializedMetadata.has_value()
3128 && IAfEffectModule::isSpatializer(&effect->desc().type)) {
3129 effect->sendMetadata_ll(spatializedMetadata.value());
3130 } else {
3131 effect->sendMetadata_ll(allMetadata);
3132 }
3133 }
3134 }
3135
3136 // EffectCallbackInterface implementation
createEffectHal(const effect_uuid_t * pEffectUuid,int32_t sessionId,int32_t deviceId,sp<EffectHalInterface> * effect)3137 status_t EffectChain::EffectCallback::createEffectHal(
3138 const effect_uuid_t *pEffectUuid, int32_t sessionId, int32_t deviceId,
3139 sp<EffectHalInterface> *effect) {
3140 status_t status = NO_INIT;
3141 const sp<EffectsFactoryHalInterface> effectsFactory =
3142 EffectConfiguration::getEffectsFactoryHal();
3143 if (effectsFactory != 0) {
3144 status = effectsFactory->createEffect(pEffectUuid, sessionId, io(), deviceId, effect);
3145 }
3146 return status;
3147 }
3148
updateOrphanEffectChains(const sp<IAfEffectBase> & effect)3149 bool EffectChain::EffectCallback::updateOrphanEffectChains(
3150 const sp<IAfEffectBase>& effect) {
3151 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
3152 return mAfThreadCallback->updateOrphanEffectChains(effect->asEffectModule());
3153 }
3154
allocateHalBuffer(size_t size,sp<EffectBufferHalInterface> * buffer)3155 status_t EffectChain::EffectCallback::allocateHalBuffer(
3156 size_t size, sp<EffectBufferHalInterface>* buffer) {
3157 return mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(size, buffer);
3158 }
3159
addEffectToHal(const sp<EffectHalInterface> & effect)3160 status_t EffectChain::EffectCallback::addEffectToHal(
3161 const sp<EffectHalInterface>& effect) {
3162 status_t result = NO_INIT;
3163 const sp<IAfThreadBase> t = thread().promote();
3164 if (t == nullptr) {
3165 return result;
3166 }
3167 sp <StreamHalInterface> st = t->stream();
3168 if (st == nullptr) {
3169 return result;
3170 }
3171 result = st->addEffect(effect);
3172 ALOGE_IF(result != OK, "Error when adding effect: %d", result);
3173 return result;
3174 }
3175
removeEffectFromHal(const sp<EffectHalInterface> & effect)3176 status_t EffectChain::EffectCallback::removeEffectFromHal(
3177 const sp<EffectHalInterface>& effect) {
3178 status_t result = NO_INIT;
3179 const sp<IAfThreadBase> t = thread().promote();
3180 if (t == nullptr) {
3181 return result;
3182 }
3183 sp <StreamHalInterface> st = t->stream();
3184 if (st == nullptr) {
3185 return result;
3186 }
3187 result = st->removeEffect(effect);
3188 ALOGE_IF(result != OK, "Error when removing effect: %d", result);
3189 return result;
3190 }
3191
io() const3192 audio_io_handle_t EffectChain::EffectCallback::io() const {
3193 const sp<IAfThreadBase> t = thread().promote();
3194 if (t == nullptr) {
3195 return AUDIO_IO_HANDLE_NONE;
3196 }
3197 return t->id();
3198 }
3199
isOutput() const3200 bool EffectChain::EffectCallback::isOutput() const {
3201 const sp<IAfThreadBase> t = thread().promote();
3202 if (t == nullptr) {
3203 return true;
3204 }
3205 return t->isOutput();
3206 }
3207
isOffload() const3208 bool EffectChain::EffectCallback::isOffload() const {
3209 return mThreadType == IAfThreadBase::OFFLOAD;
3210 }
3211
isOffloadOrDirect() const3212 bool EffectChain::EffectCallback::isOffloadOrDirect() const {
3213 return mThreadType == IAfThreadBase::OFFLOAD
3214 || mThreadType == IAfThreadBase::DIRECT;
3215 }
3216
isOffloadOrMmap() const3217 bool EffectChain::EffectCallback::isOffloadOrMmap() const {
3218 switch (mThreadType) {
3219 case IAfThreadBase::OFFLOAD:
3220 case IAfThreadBase::MMAP_PLAYBACK:
3221 case IAfThreadBase::MMAP_CAPTURE:
3222 return true;
3223 default:
3224 return false;
3225 }
3226 }
3227
isSpatializer() const3228 bool EffectChain::EffectCallback::isSpatializer() const {
3229 return mThreadType == IAfThreadBase::SPATIALIZER;
3230 }
3231
sampleRate() const3232 uint32_t EffectChain::EffectCallback::sampleRate() const {
3233 const sp<IAfThreadBase> t = thread().promote();
3234 if (t == nullptr) {
3235 return DEFAULT_OUTPUT_SAMPLE_RATE;
3236 }
3237 return t->sampleRate();
3238 }
3239
inChannelMask(int id) const3240 audio_channel_mask_t EffectChain::EffectCallback::inChannelMask(int id) const
3241 NO_THREAD_SAFETY_ANALYSIS
3242 // calling function 'hasAudioSession_l' requires holding mutex 'ThreadBase_Mutex' exclusively
3243 // calling function 'isFirstEffect_l' requires holding mutex 'EffectChain_Mutex' exclusively
3244 {
3245 const sp<IAfThreadBase> t = thread().promote();
3246 if (t == nullptr) {
3247 return AUDIO_CHANNEL_OUT_STEREO;
3248 }
3249 sp<IAfEffectChain> c = chain().promote();
3250 if (c == nullptr) {
3251 return AUDIO_CHANNEL_OUT_STEREO;
3252 }
3253
3254 if (mThreadType == IAfThreadBase::SPATIALIZER) {
3255 if (c->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
3256 return t->mixerChannelMask();
3257 } else if (c->sessionId() == AUDIO_SESSION_OUTPUT_STAGE) {
3258 if (c->isFirstEffect_l(id)) {
3259 return t->mixerChannelMask();
3260 } else {
3261 return t->channelMask();
3262 }
3263 } else if (!audio_is_global_session(c->sessionId())) {
3264 if ((t->hasAudioSession_l(c->sessionId())
3265 & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3266 return t->mixerChannelMask();
3267 } else {
3268 return t->channelMask();
3269 }
3270 } else {
3271 return t->channelMask();
3272 }
3273 } else {
3274 return t->channelMask();
3275 }
3276 }
3277
inChannelCount(int id) const3278 uint32_t EffectChain::EffectCallback::inChannelCount(int id) const {
3279 return audio_channel_count_from_out_mask(inChannelMask(id));
3280 }
3281
outChannelMask() const3282 audio_channel_mask_t EffectChain::EffectCallback::outChannelMask() const
3283 NO_THREAD_SAFETY_ANALYSIS
3284 // calling function 'hasAudioSession_l' requires holding mutex 'ThreadBase_Mutex' exclusively
3285 {
3286 const sp<IAfThreadBase> t = thread().promote();
3287 if (t == nullptr) {
3288 return AUDIO_CHANNEL_OUT_STEREO;
3289 }
3290 sp<IAfEffectChain> c = chain().promote();
3291 if (c == nullptr) {
3292 return AUDIO_CHANNEL_OUT_STEREO;
3293 }
3294
3295 if (mThreadType == IAfThreadBase::SPATIALIZER) {
3296 if (!audio_is_global_session(c->sessionId())) {
3297 if ((t->hasAudioSession_l(c->sessionId())
3298 & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3299 return t->mixerChannelMask();
3300 } else {
3301 return t->channelMask();
3302 }
3303 } else {
3304 return (c->sessionId() == AUDIO_SESSION_OUTPUT_MIX) ? t->mixerChannelMask()
3305 : t->channelMask();
3306 }
3307 } else {
3308 return t->channelMask();
3309 }
3310 }
3311
outChannelCount() const3312 uint32_t EffectChain::EffectCallback::outChannelCount() const {
3313 return audio_channel_count_from_out_mask(outChannelMask());
3314 }
3315
hapticChannelMask() const3316 audio_channel_mask_t EffectChain::EffectCallback::hapticChannelMask() const {
3317 const sp<IAfThreadBase> t = thread().promote();
3318 if (t == nullptr) {
3319 return AUDIO_CHANNEL_NONE;
3320 }
3321 return t->hapticChannelMask();
3322 }
3323
frameCount() const3324 size_t EffectChain::EffectCallback::frameCount() const {
3325 const sp<IAfThreadBase> t = thread().promote();
3326 if (t == nullptr) {
3327 // frameCount cannot be zero.
3328 return 1;
3329 }
3330 return t->frameCount();
3331 }
3332
latency() const3333 uint32_t EffectChain::EffectCallback::latency() const
3334 NO_THREAD_SAFETY_ANALYSIS // latency_l() access
3335 {
3336 const sp<IAfThreadBase> t = thread().promote();
3337 if (t == nullptr) {
3338 return 0;
3339 }
3340 // TODO(b/275956781) - this requires the thread lock.
3341 return t->latency_l();
3342 }
3343
setVolumeForOutput(float left,float right) const3344 void EffectChain::EffectCallback::setVolumeForOutput(float left, float right) const
3345 NO_THREAD_SAFETY_ANALYSIS // setVolumeForOutput_l() access
3346 {
3347 const sp<IAfThreadBase> t = thread().promote();
3348 if (t == nullptr) {
3349 return;
3350 }
3351 t->setVolumeForOutput_l(left, right);
3352 }
3353
checkSuspendOnEffectEnabled(const sp<IAfEffectBase> & effect,bool enabled,bool threadLocked)3354 void EffectChain::EffectCallback::checkSuspendOnEffectEnabled(const sp<IAfEffectBase>& effect,
3355 bool enabled, bool threadLocked)
3356 NO_THREAD_SAFETY_ANALYSIS {
3357 const sp<IAfThreadBase> t = thread().promote();
3358 if (t == nullptr) {
3359 return;
3360 }
3361 t->checkSuspendOnEffectEnabled(enabled, effect->sessionId(), threadLocked);
3362
3363 sp<IAfEffectChain> c = chain().promote();
3364 if (c == nullptr) {
3365 return;
3366 }
3367 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
3368 c->checkSuspendOnEffectEnabled_l(effect->asEffectModule(), enabled);
3369 }
3370
onEffectEnable(const sp<IAfEffectBase> & effect)3371 void EffectChain::EffectCallback::onEffectEnable(const sp<IAfEffectBase>& effect) {
3372 const sp<IAfThreadBase> t = thread().promote();
3373 if (t == nullptr) {
3374 return;
3375 }
3376 // in EffectChain context, an EffectBase is always from an EffectModule so static cast is safe
3377 t->onEffectEnable(effect->asEffectModule());
3378 }
3379
onEffectDisable(const sp<IAfEffectBase> & effect)3380 void EffectChain::EffectCallback::onEffectDisable(const sp<IAfEffectBase>& effect) {
3381 checkSuspendOnEffectEnabled(effect, false, false /*threadLocked*/);
3382
3383 const sp<IAfThreadBase> t = thread().promote();
3384 if (t == nullptr) {
3385 return;
3386 }
3387 t->onEffectDisable();
3388 }
3389
disconnectEffectHandle(IAfEffectHandle * handle,bool unpinIfLast)3390 bool EffectChain::EffectCallback::disconnectEffectHandle(IAfEffectHandle *handle,
3391 bool unpinIfLast) {
3392 const sp<IAfThreadBase> t = thread().promote();
3393 if (t == nullptr) {
3394 return false;
3395 }
3396 t->disconnectEffectHandle(handle, unpinIfLast);
3397 return true;
3398 }
3399
resetVolume_l()3400 void EffectChain::EffectCallback::resetVolume_l() {
3401 sp<IAfEffectChain> c = chain().promote();
3402 if (c == nullptr) {
3403 return;
3404 }
3405 c->resetVolume_l();
3406
3407 }
3408
strategy() const3409 product_strategy_t EffectChain::EffectCallback::strategy() const {
3410 sp<IAfEffectChain> c = chain().promote();
3411 if (c == nullptr) {
3412 return PRODUCT_STRATEGY_NONE;
3413 }
3414 return c->strategy();
3415 }
3416
activeTrackCnt() const3417 int32_t EffectChain::EffectCallback::activeTrackCnt() const {
3418 sp<IAfEffectChain> c = chain().promote();
3419 if (c == nullptr) {
3420 return 0;
3421 }
3422 return c->activeTrackCnt();
3423 }
3424
3425
3426 #undef LOG_TAG
3427 #define LOG_TAG "DeviceEffectProxy"
3428
3429 /* static */
create(const AudioDeviceTypeAddr & device,const sp<DeviceEffectManagerCallback> & callback,effect_descriptor_t * desc,int id,bool notifyFramesProcessed)3430 sp<IAfDeviceEffectProxy> IAfDeviceEffectProxy::create(
3431 const AudioDeviceTypeAddr& device,
3432 const sp<DeviceEffectManagerCallback>& callback,
3433 effect_descriptor_t *desc, int id, bool notifyFramesProcessed)
3434 {
3435 return sp<DeviceEffectProxy>::make(device,
3436 callback,
3437 desc, id, notifyFramesProcessed);
3438 }
3439
setEnabled(bool enabled,bool fromHandle)3440 status_t DeviceEffectProxy::setEnabled(bool enabled, bool fromHandle)
3441 {
3442 status_t status = EffectBase::setEnabled(enabled, fromHandle);
3443 audio_utils::lock_guard _l(proxyMutex());
3444 if (status == NO_ERROR) {
3445 for (auto& handle : mEffectHandles) {
3446 Status bs;
3447 if (enabled) {
3448 bs = handle.second->asIEffect()->enable(&status);
3449 } else {
3450 bs = handle.second->asIEffect()->disable(&status);
3451 }
3452 if (!bs.isOk()) {
3453 status = statusTFromBinderStatus(bs);
3454 }
3455 }
3456 }
3457 ALOGV("%s enable %d status %d", __func__, enabled, status);
3458 return status;
3459 }
3460
init_l(const std::map<audio_patch_handle_t,IAfPatchPanel::Patch> & patches)3461 status_t DeviceEffectProxy::init_l(
3462 const std::map <audio_patch_handle_t, IAfPatchPanel::Patch>& patches) {
3463 //For all audio patches
3464 //If src or sink device match
3465 //If the effect is HW accelerated
3466 // if no corresponding effect module
3467 // Create EffectModule: mHalEffect
3468 //Create and attach EffectHandle
3469 //If the effect is not HW accelerated and the patch sink or src is a mixer port
3470 // Create Effect on patch input or output thread on session -1
3471 //Add EffectHandle to EffectHandle map of Effect Proxy:
3472 ALOGV("%s device type %d address %s", __func__, mDevice.mType, mDevice.getAddress());
3473 status_t status = NO_ERROR;
3474 for (auto &patch : patches) {
3475 status = onCreatePatch(patch.first, patch.second);
3476 ALOGV("%s onCreatePatch status %d", __func__, status);
3477 if (status == BAD_VALUE) {
3478 return status;
3479 }
3480 }
3481 return status;
3482 }
3483
onUpdatePatch(audio_patch_handle_t oldPatchHandle,audio_patch_handle_t newPatchHandle,const IAfPatchPanel::Patch &)3484 status_t DeviceEffectProxy::onUpdatePatch(audio_patch_handle_t oldPatchHandle,
3485 audio_patch_handle_t newPatchHandle,
3486 const IAfPatchPanel::Patch& /* patch */) {
3487 status_t status = NAME_NOT_FOUND;
3488 ALOGV("%s", __func__);
3489 audio_utils::lock_guard _l(proxyMutex());
3490 if (mEffectHandles.find(oldPatchHandle) != mEffectHandles.end()) {
3491 ALOGV("%s replacing effect from handle %d to handle %d", __func__, oldPatchHandle,
3492 newPatchHandle);
3493 sp<IAfEffectHandle> effect = mEffectHandles.at(oldPatchHandle);
3494 mEffectHandles.erase(oldPatchHandle);
3495 mEffectHandles.emplace(newPatchHandle, effect);
3496 status = NO_ERROR;
3497 }
3498 return status;
3499 }
3500
onCreatePatch(audio_patch_handle_t patchHandle,const IAfPatchPanel::Patch & patch)3501 status_t DeviceEffectProxy::onCreatePatch(
3502 audio_patch_handle_t patchHandle, const IAfPatchPanel::Patch& patch) {
3503 status_t status = NAME_NOT_FOUND;
3504 sp<IAfEffectHandle> handle;
3505 // only consider source[0] as this is the only "true" source of a patch
3506 status = checkPort(patch, &patch.mAudioPatch.sources[0], &handle);
3507 ALOGV("%s source checkPort status %d", __func__, status);
3508 for (uint32_t i = 0; i < patch.mAudioPatch.num_sinks && status == NAME_NOT_FOUND; i++) {
3509 status = checkPort(patch, &patch.mAudioPatch.sinks[i], &handle);
3510 ALOGV("%s sink %d checkPort status %d", __func__, i, status);
3511 }
3512 if (status == NO_ERROR || status == ALREADY_EXISTS) {
3513 audio_utils::lock_guard _l(proxyMutex());
3514 size_t erasedHandle = mEffectHandles.erase(patchHandle);
3515 ALOGV("%s %s effecthandle %p for patch %d",
3516 __func__, (erasedHandle == 0 ? "adding" : "replacing"), handle.get(), patchHandle);
3517 mEffectHandles.emplace(patchHandle, handle);
3518 }
3519 ALOGW_IF(status == BAD_VALUE,
3520 "%s cannot attach effect %s on patch %d", __func__, mDescriptor.name, patchHandle);
3521
3522 return status;
3523 }
3524
checkPort(const IAfPatchPanel::Patch & patch,const struct audio_port_config * port,sp<IAfEffectHandle> * handle)3525 status_t DeviceEffectProxy::checkPort(const IAfPatchPanel::Patch& patch,
3526 const struct audio_port_config *port, sp<IAfEffectHandle> *handle)
3527 NO_THREAD_SAFETY_ANALYSIS
3528 // calling function 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
3529 {
3530
3531 ALOGV("%s type %d device type %d address %s device ID %d patch.isSoftware() %d",
3532 __func__, port->type, port->ext.device.type,
3533 port->ext.device.address, port->id, patch.isSoftware());
3534 if (port->type != AUDIO_PORT_TYPE_DEVICE || port->ext.device.type != mDevice.mType ||
3535 port->ext.device.address != mDevice.address()) {
3536 return NAME_NOT_FOUND;
3537 }
3538 if (((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) &&
3539 (audio_port_config_has_input_direction(port))) {
3540 ALOGI("%s don't create postprocessing effect on record port", __func__);
3541 return NAME_NOT_FOUND;
3542 }
3543 if (((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) &&
3544 (!audio_port_config_has_input_direction(port))) {
3545 ALOGI("%s don't create preprocessing effect on playback port", __func__);
3546 return NAME_NOT_FOUND;
3547 }
3548 status_t status = NAME_NOT_FOUND;
3549
3550 if (mDescriptor.flags & EFFECT_FLAG_HW_ACC_TUNNEL) {
3551 audio_utils::lock_guard _l(proxyMutex());
3552 if (mHalEffect != nullptr && mDevicePort.id == port->id) {
3553 ALOGV("%s reusing HAL effect", __func__);
3554 } else {
3555 mDevicePort = *port;
3556 mHalEffect = sp<HwAccDeviceEffectModule>::make(mMyCallback,
3557 const_cast<effect_descriptor_t *>(&mDescriptor), mMyCallback->newEffectId(),
3558 port->id);
3559 mHalEffect->configure_l();
3560 if (audio_is_input_device(mDevice.mType)) {
3561 mHalEffect->setInputDevice(mDevice);
3562 } else {
3563 mHalEffect->setDevices({mDevice});
3564 }
3565 }
3566 *handle = sp<InternalEffectHandle>::make(mHalEffect, mNotifyFramesProcessed);
3567 status = (*handle)->initCheck();
3568 if (status == OK) {
3569 status = mHalEffect->addHandle((*handle).get());
3570 } else {
3571 mHalEffect.clear();
3572 mDevicePort.id = AUDIO_PORT_HANDLE_NONE;
3573 }
3574 } else if (patch.isSoftware() || patch.thread().promote() != nullptr) {
3575 sp<IAfThreadBase> thread;
3576 if (audio_port_config_has_input_direction(port)) {
3577 if (patch.isSoftware()) {
3578 thread = patch.mRecord.thread();
3579 } else {
3580 thread = patch.thread().promote();
3581 }
3582 } else {
3583 if (patch.isSoftware()) {
3584 thread = patch.mPlayback.thread();
3585 } else {
3586 thread = patch.thread().promote();
3587 }
3588 }
3589 int enabled;
3590 *handle = thread->createEffect_l(nullptr, nullptr, 0, AUDIO_SESSION_DEVICE,
3591 const_cast<effect_descriptor_t *>(&mDescriptor),
3592 &enabled, &status, false, false /*probe*/,
3593 mNotifyFramesProcessed);
3594 ALOGV("%s thread->createEffect_l status %d", __func__, status);
3595 } else {
3596 status = BAD_VALUE;
3597 }
3598
3599 if (status == NO_ERROR || status == ALREADY_EXISTS) {
3600 Status bs;
3601 if (isEnabled()) {
3602 bs = (*handle)->asIEffect()->enable(&status);
3603 } else {
3604 bs = (*handle)->asIEffect()->disable(&status);
3605 }
3606 if (!bs.isOk()) {
3607 status = statusTFromBinderStatus(bs);
3608 }
3609 }
3610 return status;
3611 }
3612
onReleasePatch(audio_patch_handle_t patchHandle)3613 sp<IAfEffectHandle> DeviceEffectProxy::onReleasePatch(audio_patch_handle_t patchHandle) {
3614 sp<IAfEffectHandle> disconnectedHandle;
3615 {
3616 audio_utils::lock_guard _l(proxyMutex());
3617 if (mEffectHandles.find(patchHandle) != mEffectHandles.end()) {
3618 disconnectedHandle = std::move(mEffectHandles.at(patchHandle));
3619 mEffectHandles.erase(patchHandle);
3620 }
3621 }
3622 return disconnectedHandle;
3623 }
3624
3625
removeEffect(const sp<IAfEffectModule> & effect)3626 size_t DeviceEffectProxy::removeEffect(const sp<IAfEffectModule>& effect)
3627 {
3628 audio_utils::lock_guard _l(proxyMutex());
3629 if (effect == mHalEffect) {
3630 mHalEffect->release_l("DeviceEffectProxy::removeEffect");
3631 mHalEffect.clear();
3632 mDevicePort.id = AUDIO_PORT_HANDLE_NONE;
3633 }
3634 return mHalEffect == nullptr ? 0 : 1;
3635 }
3636
addEffectToHal(const sp<EffectHalInterface> & effect)3637 status_t DeviceEffectProxy::addEffectToHal(
3638 const sp<EffectHalInterface>& effect) {
3639 if (mHalEffect == nullptr) {
3640 return NO_INIT;
3641 }
3642 return mManagerCallback->addEffectToHal(&mDevicePort, effect);
3643 }
3644
removeEffectFromHal(const sp<EffectHalInterface> & effect)3645 status_t DeviceEffectProxy::removeEffectFromHal(
3646 const sp<EffectHalInterface>& effect) {
3647 if (mHalEffect == nullptr) {
3648 return NO_INIT;
3649 }
3650 return mManagerCallback->removeEffectFromHal(&mDevicePort, effect);
3651 }
3652
command(int32_t cmdCode,const std::vector<uint8_t> & cmdData,int32_t maxReplySize,std::vector<uint8_t> * reply)3653 status_t DeviceEffectProxy::command(
3654 int32_t cmdCode, const std::vector<uint8_t>& cmdData, int32_t maxReplySize,
3655 std::vector<uint8_t>* reply) {
3656 audio_utils::lock_guard _l(proxyMutex());
3657 status_t status = EffectBase::command(cmdCode, cmdData, maxReplySize, reply);
3658 if (status == NO_ERROR) {
3659 for (auto& handle : mEffectHandles) {
3660 sp<IAfEffectBase> effect = handle.second->effect().promote();
3661 if (effect != nullptr) {
3662 status = effect->command(cmdCode, cmdData, maxReplySize, reply);
3663 }
3664 }
3665 }
3666 ALOGV("%s status %d", __func__, status);
3667 return status;
3668 }
3669
isOutput() const3670 bool DeviceEffectProxy::isOutput() const {
3671 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE) {
3672 return mDevicePort.role == AUDIO_PORT_ROLE_SINK;
3673 }
3674 return true;
3675 }
3676
sampleRate() const3677 uint32_t DeviceEffectProxy::sampleRate() const {
3678 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE &&
3679 (mDevicePort.config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) != 0) {
3680 return mDevicePort.sample_rate;
3681 }
3682 return DEFAULT_OUTPUT_SAMPLE_RATE;
3683 }
3684
channelMask() const3685 audio_channel_mask_t DeviceEffectProxy::channelMask() const {
3686 if (mDevicePort.id != AUDIO_PORT_HANDLE_NONE &&
3687 (mDevicePort.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) != 0) {
3688 return mDevicePort.channel_mask;
3689 }
3690 return AUDIO_CHANNEL_OUT_STEREO;
3691 }
3692
channelCount() const3693 uint32_t DeviceEffectProxy::channelCount() const {
3694 if (isOutput()) {
3695 return audio_channel_count_from_out_mask(channelMask());
3696 }
3697 return audio_channel_count_from_in_mask(channelMask());
3698 }
3699
dump2(int fd,int spaces) const3700 void DeviceEffectProxy::dump2(int fd, int spaces) const
3701 {
3702 const Vector<String16> args;
3703 EffectBase::dump(fd, args);
3704
3705 afutils::FallibleLockGuard l{proxyMutex()};
3706
3707 if (!l) {
3708 String8 result("DeviceEffectProxy may be deadlocked\n");
3709 write(fd, result.c_str(), result.size());
3710 }
3711
3712 String8 outStr;
3713 if (mHalEffect != nullptr) {
3714 outStr.appendFormat("%*sHAL Effect Id: %d\n", spaces, "", mHalEffect->id());
3715 } else {
3716 outStr.appendFormat("%*sNO HAL Effect\n", spaces, "");
3717 }
3718 write(fd, outStr.c_str(), outStr.size());
3719 outStr.clear();
3720
3721 outStr.appendFormat("%*sSub Effects:\n", spaces, "");
3722 write(fd, outStr.c_str(), outStr.size());
3723 outStr.clear();
3724
3725 for (const auto& iter : mEffectHandles) {
3726 outStr.appendFormat("%*sEffect for patch handle %d:\n", spaces + 2, "", iter.first);
3727 write(fd, outStr.c_str(), outStr.size());
3728 outStr.clear();
3729 sp<IAfEffectBase> effect = iter.second->effect().promote();
3730 if (effect != nullptr) {
3731 effect->dump(fd, args);
3732 }
3733 }
3734 }
3735
3736 #undef LOG_TAG
3737 #define LOG_TAG "DeviceEffectProxy::ProxyCallback"
3738
newEffectId()3739 int DeviceEffectProxy::ProxyCallback::newEffectId() {
3740 return mManagerCallback->newEffectId();
3741 }
3742
3743
disconnectEffectHandle(IAfEffectHandle * handle,bool unpinIfLast)3744 bool DeviceEffectProxy::ProxyCallback::disconnectEffectHandle(
3745 IAfEffectHandle *handle, bool unpinIfLast) {
3746 sp<IAfEffectBase> effectBase = handle->effect().promote();
3747 if (effectBase == nullptr) {
3748 return false;
3749 }
3750
3751 sp<IAfEffectModule> effect = effectBase->asEffectModule();
3752 if (effect == nullptr) {
3753 return false;
3754 }
3755
3756 // restore suspended effects if the disconnected handle was enabled and the last one.
3757 bool remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
3758 if (remove) {
3759 sp<DeviceEffectProxy> proxy = mProxy.promote();
3760 if (proxy != nullptr) {
3761 proxy->removeEffect(effect);
3762 }
3763 if (handle->enabled()) {
3764 effectBase->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
3765 }
3766 }
3767 return true;
3768 }
3769
createEffectHal(const effect_uuid_t * pEffectUuid,int32_t sessionId,int32_t deviceId,sp<EffectHalInterface> * effect)3770 status_t DeviceEffectProxy::ProxyCallback::createEffectHal(
3771 const effect_uuid_t *pEffectUuid, int32_t sessionId, int32_t deviceId,
3772 sp<EffectHalInterface> *effect) {
3773 return mManagerCallback->createEffectHal(pEffectUuid, sessionId, deviceId, effect);
3774 }
3775
addEffectToHal(const sp<EffectHalInterface> & effect)3776 status_t DeviceEffectProxy::ProxyCallback::addEffectToHal(
3777 const sp<EffectHalInterface>& effect) {
3778 sp<DeviceEffectProxy> proxy = mProxy.promote();
3779 if (proxy == nullptr) {
3780 return NO_INIT;
3781 }
3782 return proxy->addEffectToHal(effect);
3783 }
3784
removeEffectFromHal(const sp<EffectHalInterface> & effect)3785 status_t DeviceEffectProxy::ProxyCallback::removeEffectFromHal(
3786 const sp<EffectHalInterface>& effect) {
3787 sp<DeviceEffectProxy> proxy = mProxy.promote();
3788 if (proxy == nullptr) {
3789 return NO_INIT;
3790 }
3791 return proxy->removeEffectFromHal(effect);
3792 }
3793
isOutput() const3794 bool DeviceEffectProxy::ProxyCallback::isOutput() const {
3795 sp<DeviceEffectProxy> proxy = mProxy.promote();
3796 if (proxy == nullptr) {
3797 return true;
3798 }
3799 return proxy->isOutput();
3800 }
3801
sampleRate() const3802 uint32_t DeviceEffectProxy::ProxyCallback::sampleRate() const {
3803 sp<DeviceEffectProxy> proxy = mProxy.promote();
3804 if (proxy == nullptr) {
3805 return DEFAULT_OUTPUT_SAMPLE_RATE;
3806 }
3807 return proxy->sampleRate();
3808 }
3809
inChannelMask(int id __unused) const3810 audio_channel_mask_t DeviceEffectProxy::ProxyCallback::inChannelMask(
3811 int id __unused) const {
3812 sp<DeviceEffectProxy> proxy = mProxy.promote();
3813 if (proxy == nullptr) {
3814 return AUDIO_CHANNEL_OUT_STEREO;
3815 }
3816 return proxy->channelMask();
3817 }
3818
inChannelCount(int id __unused) const3819 uint32_t DeviceEffectProxy::ProxyCallback::inChannelCount(int id __unused) const {
3820 sp<DeviceEffectProxy> proxy = mProxy.promote();
3821 if (proxy == nullptr) {
3822 return 2;
3823 }
3824 return proxy->channelCount();
3825 }
3826
outChannelMask() const3827 audio_channel_mask_t DeviceEffectProxy::ProxyCallback::outChannelMask() const {
3828 sp<DeviceEffectProxy> proxy = mProxy.promote();
3829 if (proxy == nullptr) {
3830 return AUDIO_CHANNEL_OUT_STEREO;
3831 }
3832 return proxy->channelMask();
3833 }
3834
outChannelCount() const3835 uint32_t DeviceEffectProxy::ProxyCallback::outChannelCount() const {
3836 sp<DeviceEffectProxy> proxy = mProxy.promote();
3837 if (proxy == nullptr) {
3838 return 2;
3839 }
3840 return proxy->channelCount();
3841 }
3842
onEffectEnable(const sp<IAfEffectBase> & effectBase)3843 void DeviceEffectProxy::ProxyCallback::onEffectEnable(
3844 const sp<IAfEffectBase>& effectBase) {
3845 sp<IAfEffectModule> effect = effectBase->asEffectModule();
3846 if (effect == nullptr) {
3847 return;
3848 }
3849 effect->start_l();
3850 }
3851
onEffectDisable(const sp<IAfEffectBase> & effectBase)3852 void DeviceEffectProxy::ProxyCallback::onEffectDisable(
3853 const sp<IAfEffectBase>& effectBase) {
3854 sp<IAfEffectModule> effect = effectBase->asEffectModule();
3855 if (effect == nullptr) {
3856 return;
3857 }
3858 effect->stop_l();
3859 }
3860
3861 } // namespace android
3862