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