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