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