• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "Configuration.h"
23 #include <utils/Log.h>
24 #include <audio_effects/effect_visualizer.h>
25 #include <audio_utils/primitives.h>
26 #include <private/media/AudioEffectShared.h>
27 #include <media/EffectsFactoryApi.h>
28 
29 #include "AudioFlinger.h"
30 #include "ServiceUtilities.h"
31 
32 // ----------------------------------------------------------------------------
33 
34 // Note: the following macro is used for extremely verbose logging message.  In
35 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
36 // 0; but one side effect of this is to turn all LOGV's as well.  Some messages
37 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
38 // turned on.  Do not uncomment the #def below unless you really know what you
39 // are doing and want to see all of the extremely verbose messages.
40 //#define VERY_VERY_VERBOSE_LOGGING
41 #ifdef VERY_VERY_VERBOSE_LOGGING
42 #define ALOGVV ALOGV
43 #else
44 #define ALOGVV(a...) do { } while(0)
45 #endif
46 
47 #define min(a, b) ((a) < (b) ? (a) : (b))
48 
49 namespace android {
50 
51 // ----------------------------------------------------------------------------
52 //  EffectModule implementation
53 // ----------------------------------------------------------------------------
54 
55 #undef LOG_TAG
56 #define LOG_TAG "AudioFlinger::EffectModule"
57 
EffectModule(ThreadBase * thread,const wp<AudioFlinger::EffectChain> & chain,effect_descriptor_t * desc,int id,int sessionId)58 AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
59                                         const wp<AudioFlinger::EffectChain>& chain,
60                                         effect_descriptor_t *desc,
61                                         int id,
62                                         int sessionId)
63     : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
64       mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
65       mDescriptor(*desc),
66       // mConfig is set by configure() and not used before then
67       mEffectInterface(NULL),
68       mStatus(NO_INIT), mState(IDLE),
69       // mMaxDisableWaitCnt is set by configure() and not used before then
70       // mDisableWaitCnt is set by process() and updateState() and not used before then
71       mSuspended(false),
72       mAudioFlinger(thread->mAudioFlinger)
73 {
74     ALOGV("Constructor %p", this);
75     int lStatus;
76 
77     // create effect engine from effect factory
78     mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
79 
80     if (mStatus != NO_ERROR) {
81         return;
82     }
83     lStatus = init();
84     if (lStatus < 0) {
85         mStatus = lStatus;
86         goto Error;
87     }
88 
89     ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
90     return;
91 Error:
92     EffectRelease(mEffectInterface);
93     mEffectInterface = NULL;
94     ALOGV("Constructor Error %d", mStatus);
95 }
96 
~EffectModule()97 AudioFlinger::EffectModule::~EffectModule()
98 {
99     ALOGV("Destructor %p", this);
100     if (mEffectInterface != NULL) {
101         remove_effect_from_hal_l();
102         // release effect engine
103         EffectRelease(mEffectInterface);
104     }
105 }
106 
addHandle(EffectHandle * handle)107 status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
108 {
109     status_t status;
110 
111     Mutex::Autolock _l(mLock);
112     int priority = handle->priority();
113     size_t size = mHandles.size();
114     EffectHandle *controlHandle = NULL;
115     size_t i;
116     for (i = 0; i < size; i++) {
117         EffectHandle *h = mHandles[i];
118         if (h == NULL || h->destroyed_l()) {
119             continue;
120         }
121         // first non destroyed handle is considered in control
122         if (controlHandle == NULL) {
123             controlHandle = h;
124         }
125         if (h->priority() <= priority) {
126             break;
127         }
128     }
129     // if inserted in first place, move effect control from previous owner to this handle
130     if (i == 0) {
131         bool enabled = false;
132         if (controlHandle != NULL) {
133             enabled = controlHandle->enabled();
134             controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
135         }
136         handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
137         status = NO_ERROR;
138     } else {
139         status = ALREADY_EXISTS;
140     }
141     ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
142     mHandles.insertAt(handle, i);
143     return status;
144 }
145 
removeHandle(EffectHandle * handle)146 size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
147 {
148     Mutex::Autolock _l(mLock);
149     size_t size = mHandles.size();
150     size_t i;
151     for (i = 0; i < size; i++) {
152         if (mHandles[i] == handle) {
153             break;
154         }
155     }
156     if (i == size) {
157         return size;
158     }
159     ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
160 
161     mHandles.removeAt(i);
162     // if removed from first place, move effect control from this handle to next in line
163     if (i == 0) {
164         EffectHandle *h = controlHandle_l();
165         if (h != NULL) {
166             h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
167         }
168     }
169 
170     // Prevent calls to process() and other functions on effect interface from now on.
171     // The effect engine will be released by the destructor when the last strong reference on
172     // this object is released which can happen after next process is called.
173     if (mHandles.size() == 0 && !mPinned) {
174         mState = DESTROYED;
175     }
176 
177     return mHandles.size();
178 }
179 
180 // must be called with EffectModule::mLock held
controlHandle_l()181 AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
182 {
183     // the first valid handle in the list has control over the module
184     for (size_t i = 0; i < mHandles.size(); i++) {
185         EffectHandle *h = mHandles[i];
186         if (h != NULL && !h->destroyed_l()) {
187             return h;
188         }
189     }
190 
191     return NULL;
192 }
193 
disconnect(EffectHandle * handle,bool unpinIfLast)194 size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
195 {
196     ALOGV("disconnect() %p handle %p", this, handle);
197     // keep a strong reference on this EffectModule to avoid calling the
198     // destructor before we exit
199     sp<EffectModule> keep(this);
200     {
201         if (removeHandle(handle) == 0) {
202             if (!isPinned() || unpinIfLast) {
203                 sp<ThreadBase> thread = mThread.promote();
204                 if (thread != 0) {
205                     Mutex::Autolock _l(thread->mLock);
206                     thread->removeEffect_l(this);
207                 }
208                 sp<AudioFlinger> af = mAudioFlinger.promote();
209                 if (af != 0) {
210                     af->updateOrphanEffectChains(this);
211                 }
212                 AudioSystem::unregisterEffect(mId);
213             }
214         }
215     }
216     return mHandles.size();
217 }
218 
updateState()219 void AudioFlinger::EffectModule::updateState() {
220     Mutex::Autolock _l(mLock);
221 
222     switch (mState) {
223     case RESTART:
224         reset_l();
225         // FALL THROUGH
226 
227     case STARTING:
228         // clear auxiliary effect input buffer for next accumulation
229         if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
230             memset(mConfig.inputCfg.buffer.raw,
231                    0,
232                    mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
233         }
234         if (start_l() == NO_ERROR) {
235             mState = ACTIVE;
236         } else {
237             mState = IDLE;
238         }
239         break;
240     case STOPPING:
241         if (stop_l() == NO_ERROR) {
242             mDisableWaitCnt = mMaxDisableWaitCnt;
243         } else {
244             mDisableWaitCnt = 1; // will cause immediate transition to IDLE
245         }
246         mState = STOPPED;
247         break;
248     case STOPPED:
249         // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
250         // turn off sequence.
251         if (--mDisableWaitCnt == 0) {
252             reset_l();
253             mState = IDLE;
254         }
255         break;
256     default: //IDLE , ACTIVE, DESTROYED
257         break;
258     }
259 }
260 
process()261 void AudioFlinger::EffectModule::process()
262 {
263     Mutex::Autolock _l(mLock);
264 
265     if (mState == DESTROYED || mEffectInterface == NULL ||
266             mConfig.inputCfg.buffer.raw == NULL ||
267             mConfig.outputCfg.buffer.raw == NULL) {
268         return;
269     }
270 
271     if (isProcessEnabled()) {
272         // do 32 bit to 16 bit conversion for auxiliary effect input buffer
273         if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
274             ditherAndClamp(mConfig.inputCfg.buffer.s32,
275                                         mConfig.inputCfg.buffer.s32,
276                                         mConfig.inputCfg.buffer.frameCount/2);
277         }
278 
279         // do the actual processing in the effect engine
280         int ret = (*mEffectInterface)->process(mEffectInterface,
281                                                &mConfig.inputCfg.buffer,
282                                                &mConfig.outputCfg.buffer);
283 
284         // force transition to IDLE state when engine is ready
285         if (mState == STOPPED && ret == -ENODATA) {
286             mDisableWaitCnt = 1;
287         }
288 
289         // clear auxiliary effect input buffer for next accumulation
290         if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
291             memset(mConfig.inputCfg.buffer.raw, 0,
292                    mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
293         }
294     } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
295                 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
296         // If an insert effect is idle and input buffer is different from output buffer,
297         // accumulate input onto output
298         sp<EffectChain> chain = mChain.promote();
299         if (chain != 0 && chain->activeTrackCnt() != 0) {
300             size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
301             int16_t *in = mConfig.inputCfg.buffer.s16;
302             int16_t *out = mConfig.outputCfg.buffer.s16;
303             for (size_t i = 0; i < frameCnt; i++) {
304                 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
305             }
306         }
307     }
308 }
309 
reset_l()310 void AudioFlinger::EffectModule::reset_l()
311 {
312     if (mStatus != NO_ERROR || mEffectInterface == NULL) {
313         return;
314     }
315     (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
316 }
317 
configure()318 status_t AudioFlinger::EffectModule::configure()
319 {
320     status_t status;
321     sp<ThreadBase> thread;
322     uint32_t size;
323     audio_channel_mask_t channelMask;
324 
325     if (mEffectInterface == NULL) {
326         status = NO_INIT;
327         goto exit;
328     }
329 
330     thread = mThread.promote();
331     if (thread == 0) {
332         status = DEAD_OBJECT;
333         goto exit;
334     }
335 
336     // TODO: handle configuration of effects replacing track process
337     channelMask = thread->channelMask();
338     mConfig.outputCfg.channels = channelMask;
339 
340     if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
341         mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
342     } else {
343         mConfig.inputCfg.channels = channelMask;
344         // TODO: Update this logic when multichannel effects are implemented.
345         // For offloaded tracks consider mono output as stereo for proper effect initialization
346         if (channelMask == AUDIO_CHANNEL_OUT_MONO) {
347             mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
348             mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
349             ALOGV("Overriding effect input and output as STEREO");
350         }
351     }
352 
353     mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
354     mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
355     mConfig.inputCfg.samplingRate = thread->sampleRate();
356     mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
357     mConfig.inputCfg.bufferProvider.cookie = NULL;
358     mConfig.inputCfg.bufferProvider.getBuffer = NULL;
359     mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
360     mConfig.outputCfg.bufferProvider.cookie = NULL;
361     mConfig.outputCfg.bufferProvider.getBuffer = NULL;
362     mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
363     mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
364     // Insert effect:
365     // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
366     // always overwrites output buffer: input buffer == output buffer
367     // - in other sessions:
368     //      last effect in the chain accumulates in output buffer: input buffer != output buffer
369     //      other effect: overwrites output buffer: input buffer == output buffer
370     // Auxiliary effect:
371     //      accumulates in output buffer: input buffer != output buffer
372     // Therefore: accumulate <=> input buffer != output buffer
373     if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
374         mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
375     } else {
376         mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
377     }
378     mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
379     mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
380     mConfig.inputCfg.buffer.frameCount = thread->frameCount();
381     mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
382 
383     ALOGV("configure() %p thread %p buffer %p framecount %d",
384             this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
385 
386     status_t cmdStatus;
387     size = sizeof(int);
388     status = (*mEffectInterface)->command(mEffectInterface,
389                                                    EFFECT_CMD_SET_CONFIG,
390                                                    sizeof(effect_config_t),
391                                                    &mConfig,
392                                                    &size,
393                                                    &cmdStatus);
394     if (status == 0) {
395         status = cmdStatus;
396     }
397 
398     if (status == 0 &&
399             (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
400         uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
401         effect_param_t *p = (effect_param_t *)buf32;
402 
403         p->psize = sizeof(uint32_t);
404         p->vsize = sizeof(uint32_t);
405         size = sizeof(int);
406         *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
407 
408         uint32_t latency = 0;
409         PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
410         if (pbt != NULL) {
411             latency = pbt->latency_l();
412         }
413 
414         *((int32_t *)p->data + 1)= latency;
415         (*mEffectInterface)->command(mEffectInterface,
416                                      EFFECT_CMD_SET_PARAM,
417                                      sizeof(effect_param_t) + 8,
418                                      &buf32,
419                                      &size,
420                                      &cmdStatus);
421     }
422 
423     mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
424             (1000 * mConfig.outputCfg.buffer.frameCount);
425 
426 exit:
427     mStatus = status;
428     return status;
429 }
430 
init()431 status_t AudioFlinger::EffectModule::init()
432 {
433     Mutex::Autolock _l(mLock);
434     if (mEffectInterface == NULL) {
435         return NO_INIT;
436     }
437     status_t cmdStatus;
438     uint32_t size = sizeof(status_t);
439     status_t status = (*mEffectInterface)->command(mEffectInterface,
440                                                    EFFECT_CMD_INIT,
441                                                    0,
442                                                    NULL,
443                                                    &size,
444                                                    &cmdStatus);
445     if (status == 0) {
446         status = cmdStatus;
447     }
448     return status;
449 }
450 
addEffectToHal_l()451 void AudioFlinger::EffectModule::addEffectToHal_l()
452 {
453     if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
454          (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
455         sp<ThreadBase> thread = mThread.promote();
456         if (thread != 0) {
457             audio_stream_t *stream = thread->stream();
458             if (stream != NULL) {
459                 stream->add_audio_effect(stream, mEffectInterface);
460             }
461         }
462     }
463 }
464 
start()465 status_t AudioFlinger::EffectModule::start()
466 {
467     Mutex::Autolock _l(mLock);
468     return start_l();
469 }
470 
start_l()471 status_t AudioFlinger::EffectModule::start_l()
472 {
473     if (mEffectInterface == NULL) {
474         return NO_INIT;
475     }
476     if (mStatus != NO_ERROR) {
477         return mStatus;
478     }
479     status_t cmdStatus;
480     uint32_t size = sizeof(status_t);
481     status_t status = (*mEffectInterface)->command(mEffectInterface,
482                                                    EFFECT_CMD_ENABLE,
483                                                    0,
484                                                    NULL,
485                                                    &size,
486                                                    &cmdStatus);
487     if (status == 0) {
488         status = cmdStatus;
489     }
490     if (status == 0) {
491         addEffectToHal_l();
492         sp<EffectChain> chain = mChain.promote();
493         if (chain != 0) {
494             chain->forceVolume();
495         }
496     }
497     return status;
498 }
499 
stop()500 status_t AudioFlinger::EffectModule::stop()
501 {
502     Mutex::Autolock _l(mLock);
503     return stop_l();
504 }
505 
stop_l()506 status_t AudioFlinger::EffectModule::stop_l()
507 {
508     if (mEffectInterface == NULL) {
509         return NO_INIT;
510     }
511     if (mStatus != NO_ERROR) {
512         return mStatus;
513     }
514     status_t cmdStatus = NO_ERROR;
515     uint32_t size = sizeof(status_t);
516     status_t status = (*mEffectInterface)->command(mEffectInterface,
517                                                    EFFECT_CMD_DISABLE,
518                                                    0,
519                                                    NULL,
520                                                    &size,
521                                                    &cmdStatus);
522     if (status == NO_ERROR) {
523         status = cmdStatus;
524     }
525     if (status == NO_ERROR) {
526         status = remove_effect_from_hal_l();
527     }
528     return status;
529 }
530 
remove_effect_from_hal_l()531 status_t AudioFlinger::EffectModule::remove_effect_from_hal_l()
532 {
533     if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
534              (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
535         sp<ThreadBase> thread = mThread.promote();
536         if (thread != 0) {
537             audio_stream_t *stream = thread->stream();
538             if (stream != NULL) {
539                 stream->remove_audio_effect(stream, mEffectInterface);
540             }
541         }
542     }
543     return NO_ERROR;
544 }
545 
command(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)546 status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
547                                              uint32_t cmdSize,
548                                              void *pCmdData,
549                                              uint32_t *replySize,
550                                              void *pReplyData)
551 {
552     Mutex::Autolock _l(mLock);
553     ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
554 
555     if (mState == DESTROYED || mEffectInterface == NULL) {
556         return NO_INIT;
557     }
558     if (mStatus != NO_ERROR) {
559         return mStatus;
560     }
561     if (cmdCode == EFFECT_CMD_GET_PARAM &&
562             (*replySize < sizeof(effect_param_t) ||
563                     ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) {
564         android_errorWriteLog(0x534e4554, "29251553");
565         return -EINVAL;
566     }
567     status_t status = (*mEffectInterface)->command(mEffectInterface,
568                                                    cmdCode,
569                                                    cmdSize,
570                                                    pCmdData,
571                                                    replySize,
572                                                    pReplyData);
573     if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
574         uint32_t size = (replySize == NULL) ? 0 : *replySize;
575         for (size_t i = 1; i < mHandles.size(); i++) {
576             EffectHandle *h = mHandles[i];
577             if (h != NULL && !h->destroyed_l()) {
578                 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
579             }
580         }
581     }
582     return status;
583 }
584 
setEnabled(bool enabled)585 status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
586 {
587     Mutex::Autolock _l(mLock);
588     return setEnabled_l(enabled);
589 }
590 
591 // must be called with EffectModule::mLock held
setEnabled_l(bool enabled)592 status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
593 {
594 
595     ALOGV("setEnabled %p enabled %d", this, enabled);
596 
597     if (enabled != isEnabled()) {
598         status_t status = AudioSystem::setEffectEnabled(mId, enabled);
599         if (enabled && status != NO_ERROR) {
600             return status;
601         }
602 
603         switch (mState) {
604         // going from disabled to enabled
605         case IDLE:
606             mState = STARTING;
607             break;
608         case STOPPED:
609             mState = RESTART;
610             break;
611         case STOPPING:
612             mState = ACTIVE;
613             break;
614 
615         // going from enabled to disabled
616         case RESTART:
617             mState = STOPPED;
618             break;
619         case STARTING:
620             mState = IDLE;
621             break;
622         case ACTIVE:
623             mState = STOPPING;
624             break;
625         case DESTROYED:
626             return NO_ERROR; // simply ignore as we are being destroyed
627         }
628         for (size_t i = 1; i < mHandles.size(); i++) {
629             EffectHandle *h = mHandles[i];
630             if (h != NULL && !h->destroyed_l()) {
631                 h->setEnabled(enabled);
632             }
633         }
634     }
635     return NO_ERROR;
636 }
637 
isEnabled() const638 bool AudioFlinger::EffectModule::isEnabled() const
639 {
640     switch (mState) {
641     case RESTART:
642     case STARTING:
643     case ACTIVE:
644         return true;
645     case IDLE:
646     case STOPPING:
647     case STOPPED:
648     case DESTROYED:
649     default:
650         return false;
651     }
652 }
653 
isProcessEnabled() const654 bool AudioFlinger::EffectModule::isProcessEnabled() const
655 {
656     if (mStatus != NO_ERROR) {
657         return false;
658     }
659 
660     switch (mState) {
661     case RESTART:
662     case ACTIVE:
663     case STOPPING:
664     case STOPPED:
665         return true;
666     case IDLE:
667     case STARTING:
668     case DESTROYED:
669     default:
670         return false;
671     }
672 }
673 
setVolume(uint32_t * left,uint32_t * right,bool controller)674 status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
675 {
676     Mutex::Autolock _l(mLock);
677     if (mStatus != NO_ERROR) {
678         return mStatus;
679     }
680     status_t status = NO_ERROR;
681     // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
682     // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
683     if (isProcessEnabled() &&
684             ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
685             (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
686         status_t cmdStatus;
687         uint32_t volume[2];
688         uint32_t *pVolume = NULL;
689         uint32_t size = sizeof(volume);
690         volume[0] = *left;
691         volume[1] = *right;
692         if (controller) {
693             pVolume = volume;
694         }
695         status = (*mEffectInterface)->command(mEffectInterface,
696                                               EFFECT_CMD_SET_VOLUME,
697                                               size,
698                                               volume,
699                                               &size,
700                                               pVolume);
701         if (controller && status == NO_ERROR && size == sizeof(volume)) {
702             *left = volume[0];
703             *right = volume[1];
704         }
705     }
706     return status;
707 }
708 
setDevice(audio_devices_t device)709 status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
710 {
711     if (device == AUDIO_DEVICE_NONE) {
712         return NO_ERROR;
713     }
714 
715     Mutex::Autolock _l(mLock);
716     if (mStatus != NO_ERROR) {
717         return mStatus;
718     }
719     status_t status = NO_ERROR;
720     if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
721         status_t cmdStatus;
722         uint32_t size = sizeof(status_t);
723         uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
724                             EFFECT_CMD_SET_INPUT_DEVICE;
725         status = (*mEffectInterface)->command(mEffectInterface,
726                                               cmd,
727                                               sizeof(uint32_t),
728                                               &device,
729                                               &size,
730                                               &cmdStatus);
731     }
732     return status;
733 }
734 
setMode(audio_mode_t mode)735 status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
736 {
737     Mutex::Autolock _l(mLock);
738     if (mStatus != NO_ERROR) {
739         return mStatus;
740     }
741     status_t status = NO_ERROR;
742     if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
743         status_t cmdStatus;
744         uint32_t size = sizeof(status_t);
745         status = (*mEffectInterface)->command(mEffectInterface,
746                                               EFFECT_CMD_SET_AUDIO_MODE,
747                                               sizeof(audio_mode_t),
748                                               &mode,
749                                               &size,
750                                               &cmdStatus);
751         if (status == NO_ERROR) {
752             status = cmdStatus;
753         }
754     }
755     return status;
756 }
757 
setAudioSource(audio_source_t source)758 status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
759 {
760     Mutex::Autolock _l(mLock);
761     if (mStatus != NO_ERROR) {
762         return mStatus;
763     }
764     status_t status = NO_ERROR;
765     if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
766         uint32_t size = 0;
767         status = (*mEffectInterface)->command(mEffectInterface,
768                                               EFFECT_CMD_SET_AUDIO_SOURCE,
769                                               sizeof(audio_source_t),
770                                               &source,
771                                               &size,
772                                               NULL);
773     }
774     return status;
775 }
776 
setSuspended(bool suspended)777 void AudioFlinger::EffectModule::setSuspended(bool suspended)
778 {
779     Mutex::Autolock _l(mLock);
780     mSuspended = suspended;
781 }
782 
suspended() const783 bool AudioFlinger::EffectModule::suspended() const
784 {
785     Mutex::Autolock _l(mLock);
786     return mSuspended;
787 }
788 
purgeHandles()789 bool AudioFlinger::EffectModule::purgeHandles()
790 {
791     bool enabled = false;
792     Mutex::Autolock _l(mLock);
793     for (size_t i = 0; i < mHandles.size(); i++) {
794         EffectHandle *handle = mHandles[i];
795         if (handle != NULL && !handle->destroyed_l()) {
796             handle->effect().clear();
797             if (handle->hasControl()) {
798                 enabled = handle->enabled();
799             }
800         }
801     }
802     return enabled;
803 }
804 
setOffloaded(bool offloaded,audio_io_handle_t io)805 status_t AudioFlinger::EffectModule::setOffloaded(bool offloaded, audio_io_handle_t io)
806 {
807     Mutex::Autolock _l(mLock);
808     if (mStatus != NO_ERROR) {
809         return mStatus;
810     }
811     status_t status = NO_ERROR;
812     if ((mDescriptor.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) != 0) {
813         status_t cmdStatus;
814         uint32_t size = sizeof(status_t);
815         effect_offload_param_t cmd;
816 
817         cmd.isOffload = offloaded;
818         cmd.ioHandle = io;
819         status = (*mEffectInterface)->command(mEffectInterface,
820                                               EFFECT_CMD_OFFLOAD,
821                                               sizeof(effect_offload_param_t),
822                                               &cmd,
823                                               &size,
824                                               &cmdStatus);
825         if (status == NO_ERROR) {
826             status = cmdStatus;
827         }
828         mOffloaded = (status == NO_ERROR) ? offloaded : false;
829     } else {
830         if (offloaded) {
831             status = INVALID_OPERATION;
832         }
833         mOffloaded = false;
834     }
835     ALOGV("setOffloaded() offloaded %d io %d status %d", offloaded, io, status);
836     return status;
837 }
838 
isOffloaded() const839 bool AudioFlinger::EffectModule::isOffloaded() const
840 {
841     Mutex::Autolock _l(mLock);
842     return mOffloaded;
843 }
844 
effectFlagsToString(uint32_t flags)845 String8 effectFlagsToString(uint32_t flags) {
846     String8 s;
847 
848     s.append("conn. mode: ");
849     switch (flags & EFFECT_FLAG_TYPE_MASK) {
850     case EFFECT_FLAG_TYPE_INSERT: s.append("insert"); break;
851     case EFFECT_FLAG_TYPE_AUXILIARY: s.append("auxiliary"); break;
852     case EFFECT_FLAG_TYPE_REPLACE: s.append("replace"); break;
853     case EFFECT_FLAG_TYPE_PRE_PROC: s.append("preproc"); break;
854     case EFFECT_FLAG_TYPE_POST_PROC: s.append("postproc"); break;
855     default: s.append("unknown/reserved"); break;
856     }
857     s.append(", ");
858 
859     s.append("insert pref: ");
860     switch (flags & EFFECT_FLAG_INSERT_MASK) {
861     case EFFECT_FLAG_INSERT_ANY: s.append("any"); break;
862     case EFFECT_FLAG_INSERT_FIRST: s.append("first"); break;
863     case EFFECT_FLAG_INSERT_LAST: s.append("last"); break;
864     case EFFECT_FLAG_INSERT_EXCLUSIVE: s.append("exclusive"); break;
865     default: s.append("unknown/reserved"); break;
866     }
867     s.append(", ");
868 
869     s.append("volume mgmt: ");
870     switch (flags & EFFECT_FLAG_VOLUME_MASK) {
871     case EFFECT_FLAG_VOLUME_NONE: s.append("none"); break;
872     case EFFECT_FLAG_VOLUME_CTRL: s.append("implements control"); break;
873     case EFFECT_FLAG_VOLUME_IND: s.append("requires indication"); break;
874     default: s.append("unknown/reserved"); break;
875     }
876     s.append(", ");
877 
878     uint32_t devind = flags & EFFECT_FLAG_DEVICE_MASK;
879     if (devind) {
880         s.append("device indication: ");
881         switch (devind) {
882         case EFFECT_FLAG_DEVICE_IND: s.append("requires updates"); break;
883         default: s.append("unknown/reserved"); break;
884         }
885         s.append(", ");
886     }
887 
888     s.append("input mode: ");
889     switch (flags & EFFECT_FLAG_INPUT_MASK) {
890     case EFFECT_FLAG_INPUT_DIRECT: s.append("direct"); break;
891     case EFFECT_FLAG_INPUT_PROVIDER: s.append("provider"); break;
892     case EFFECT_FLAG_INPUT_BOTH: s.append("direct+provider"); break;
893     default: s.append("not set"); break;
894     }
895     s.append(", ");
896 
897     s.append("output mode: ");
898     switch (flags & EFFECT_FLAG_OUTPUT_MASK) {
899     case EFFECT_FLAG_OUTPUT_DIRECT: s.append("direct"); break;
900     case EFFECT_FLAG_OUTPUT_PROVIDER: s.append("provider"); break;
901     case EFFECT_FLAG_OUTPUT_BOTH: s.append("direct+provider"); break;
902     default: s.append("not set"); break;
903     }
904     s.append(", ");
905 
906     uint32_t accel = flags & EFFECT_FLAG_HW_ACC_MASK;
907     if (accel) {
908         s.append("hardware acceleration: ");
909         switch (accel) {
910         case EFFECT_FLAG_HW_ACC_SIMPLE: s.append("non-tunneled"); break;
911         case EFFECT_FLAG_HW_ACC_TUNNEL: s.append("tunneled"); break;
912         default: s.append("unknown/reserved"); break;
913         }
914         s.append(", ");
915     }
916 
917     uint32_t modeind = flags & EFFECT_FLAG_AUDIO_MODE_MASK;
918     if (modeind) {
919         s.append("mode indication: ");
920         switch (modeind) {
921         case EFFECT_FLAG_AUDIO_MODE_IND: s.append("required"); break;
922         default: s.append("unknown/reserved"); break;
923         }
924         s.append(", ");
925     }
926 
927     uint32_t srcind = flags & EFFECT_FLAG_AUDIO_SOURCE_MASK;
928     if (srcind) {
929         s.append("source indication: ");
930         switch (srcind) {
931         case EFFECT_FLAG_AUDIO_SOURCE_IND: s.append("required"); break;
932         default: s.append("unknown/reserved"); break;
933         }
934         s.append(", ");
935     }
936 
937     if (flags & EFFECT_FLAG_OFFLOAD_MASK) {
938         s.append("offloadable, ");
939     }
940 
941     int len = s.length();
942     if (s.length() > 2) {
943         char *str = s.lockBuffer(len);
944         s.unlockBuffer(len - 2);
945     }
946     return s;
947 }
948 
949 
dump(int fd,const Vector<String16> & args __unused)950 void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args __unused)
951 {
952     const size_t SIZE = 256;
953     char buffer[SIZE];
954     String8 result;
955 
956     snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
957     result.append(buffer);
958 
959     bool locked = AudioFlinger::dumpTryLock(mLock);
960     // failed to lock - AudioFlinger is probably deadlocked
961     if (!locked) {
962         result.append("\t\tCould not lock Fx mutex:\n");
963     }
964 
965     result.append("\t\tSession Status State Engine:\n");
966     snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   %p\n",
967             mSessionId, mStatus, mState, mEffectInterface);
968     result.append(buffer);
969 
970     result.append("\t\tDescriptor:\n");
971     snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
972             mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
973             mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],
974                     mDescriptor.uuid.node[2],
975             mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
976     result.append(buffer);
977     snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
978                 mDescriptor.type.timeLow, mDescriptor.type.timeMid,
979                     mDescriptor.type.timeHiAndVersion,
980                 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],
981                     mDescriptor.type.node[2],
982                 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
983     result.append(buffer);
984     snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X (%s)\n",
985             mDescriptor.apiVersion,
986             mDescriptor.flags,
987             effectFlagsToString(mDescriptor.flags).string());
988     result.append(buffer);
989     snprintf(buffer, SIZE, "\t\t- name: %s\n",
990             mDescriptor.name);
991     result.append(buffer);
992     snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
993             mDescriptor.implementor);
994     result.append(buffer);
995 
996     result.append("\t\t- Input configuration:\n");
997     result.append("\t\t\tFrames  Smp rate Channels Format Buffer\n");
998     snprintf(buffer, SIZE, "\t\t\t%05zu   %05d    %08x %6d (%s) %p\n",
999             mConfig.inputCfg.buffer.frameCount,
1000             mConfig.inputCfg.samplingRate,
1001             mConfig.inputCfg.channels,
1002             mConfig.inputCfg.format,
1003             formatToString((audio_format_t)mConfig.inputCfg.format),
1004             mConfig.inputCfg.buffer.raw);
1005     result.append(buffer);
1006 
1007     result.append("\t\t- Output configuration:\n");
1008     result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
1009     snprintf(buffer, SIZE, "\t\t\t%p %05zu   %05d    %08x %d (%s)\n",
1010             mConfig.outputCfg.buffer.raw,
1011             mConfig.outputCfg.buffer.frameCount,
1012             mConfig.outputCfg.samplingRate,
1013             mConfig.outputCfg.channels,
1014             mConfig.outputCfg.format,
1015             formatToString((audio_format_t)mConfig.outputCfg.format));
1016     result.append(buffer);
1017 
1018     snprintf(buffer, SIZE, "\t\t%zu Clients:\n", mHandles.size());
1019     result.append(buffer);
1020     result.append("\t\t\t  Pid Priority Ctrl Locked client server\n");
1021     for (size_t i = 0; i < mHandles.size(); ++i) {
1022         EffectHandle *handle = mHandles[i];
1023         if (handle != NULL && !handle->destroyed_l()) {
1024             handle->dumpToBuffer(buffer, SIZE);
1025             result.append(buffer);
1026         }
1027     }
1028 
1029     write(fd, result.string(), result.length());
1030 
1031     if (locked) {
1032         mLock.unlock();
1033     }
1034 }
1035 
1036 // ----------------------------------------------------------------------------
1037 //  EffectHandle implementation
1038 // ----------------------------------------------------------------------------
1039 
1040 #undef LOG_TAG
1041 #define LOG_TAG "AudioFlinger::EffectHandle"
1042 
EffectHandle(const sp<EffectModule> & effect,const sp<AudioFlinger::Client> & client,const sp<IEffectClient> & effectClient,int32_t priority)1043 AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
1044                                         const sp<AudioFlinger::Client>& client,
1045                                         const sp<IEffectClient>& effectClient,
1046                                         int32_t priority)
1047     : BnEffect(),
1048     mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
1049     mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
1050 {
1051     ALOGV("constructor %p", this);
1052 
1053     if (client == 0) {
1054         return;
1055     }
1056     int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
1057     mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
1058     if (mCblkMemory == 0 ||
1059             (mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer())) == NULL) {
1060         ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE +
1061                 sizeof(effect_param_cblk_t));
1062         mCblkMemory.clear();
1063         return;
1064     }
1065     new(mCblk) effect_param_cblk_t();
1066     mBuffer = (uint8_t *)mCblk + bufOffset;
1067 }
1068 
~EffectHandle()1069 AudioFlinger::EffectHandle::~EffectHandle()
1070 {
1071     ALOGV("Destructor %p", this);
1072 
1073     if (mEffect == 0) {
1074         mDestroyed = true;
1075         return;
1076     }
1077     mEffect->lock();
1078     mDestroyed = true;
1079     mEffect->unlock();
1080     disconnect(false);
1081 }
1082 
initCheck()1083 status_t AudioFlinger::EffectHandle::initCheck()
1084 {
1085     return mClient == 0 || mCblkMemory != 0 ? OK : NO_MEMORY;
1086 }
1087 
enable()1088 status_t AudioFlinger::EffectHandle::enable()
1089 {
1090     ALOGV("enable %p", this);
1091     if (!mHasControl) {
1092         return INVALID_OPERATION;
1093     }
1094     if (mEffect == 0) {
1095         return DEAD_OBJECT;
1096     }
1097 
1098     if (mEnabled) {
1099         return NO_ERROR;
1100     }
1101 
1102     mEnabled = true;
1103 
1104     sp<ThreadBase> thread = mEffect->thread().promote();
1105     if (thread != 0) {
1106         thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
1107     }
1108 
1109     // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
1110     if (mEffect->suspended()) {
1111         return NO_ERROR;
1112     }
1113 
1114     status_t status = mEffect->setEnabled(true);
1115     if (status != NO_ERROR) {
1116         if (thread != 0) {
1117             thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
1118         }
1119         mEnabled = false;
1120     } else {
1121         if (thread != 0) {
1122             if (thread->type() == ThreadBase::OFFLOAD) {
1123                 PlaybackThread *t = (PlaybackThread *)thread.get();
1124                 Mutex::Autolock _l(t->mLock);
1125                 t->broadcast_l();
1126             }
1127             if (!mEffect->isOffloadable()) {
1128                 if (thread->type() == ThreadBase::OFFLOAD) {
1129                     PlaybackThread *t = (PlaybackThread *)thread.get();
1130                     t->invalidateTracks(AUDIO_STREAM_MUSIC);
1131                 }
1132                 if (mEffect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1133                     thread->mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1134                 }
1135             }
1136         }
1137     }
1138     return status;
1139 }
1140 
disable()1141 status_t AudioFlinger::EffectHandle::disable()
1142 {
1143     ALOGV("disable %p", this);
1144     if (!mHasControl) {
1145         return INVALID_OPERATION;
1146     }
1147     if (mEffect == 0) {
1148         return DEAD_OBJECT;
1149     }
1150 
1151     if (!mEnabled) {
1152         return NO_ERROR;
1153     }
1154     mEnabled = false;
1155 
1156     if (mEffect->suspended()) {
1157         return NO_ERROR;
1158     }
1159 
1160     status_t status = mEffect->setEnabled(false);
1161 
1162     sp<ThreadBase> thread = mEffect->thread().promote();
1163     if (thread != 0) {
1164         thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
1165         if (thread->type() == ThreadBase::OFFLOAD) {
1166             PlaybackThread *t = (PlaybackThread *)thread.get();
1167             Mutex::Autolock _l(t->mLock);
1168             t->broadcast_l();
1169         }
1170     }
1171 
1172     return status;
1173 }
1174 
disconnect()1175 void AudioFlinger::EffectHandle::disconnect()
1176 {
1177     disconnect(true);
1178 }
1179 
disconnect(bool unpinIfLast)1180 void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
1181 {
1182     ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
1183     if (mEffect == 0) {
1184         return;
1185     }
1186     // restore suspended effects if the disconnected handle was enabled and the last one.
1187     if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
1188         sp<ThreadBase> thread = mEffect->thread().promote();
1189         if (thread != 0) {
1190             thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
1191         }
1192     }
1193 
1194     // release sp on module => module destructor can be called now
1195     mEffect.clear();
1196     if (mClient != 0) {
1197         if (mCblk != NULL) {
1198             // unlike ~TrackBase(), mCblk is never a local new, so don't delete
1199             mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
1200         }
1201         mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
1202         // Client destructor must run with AudioFlinger client mutex locked
1203         Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
1204         mClient.clear();
1205     }
1206 }
1207 
command(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)1208 status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
1209                                              uint32_t cmdSize,
1210                                              void *pCmdData,
1211                                              uint32_t *replySize,
1212                                              void *pReplyData)
1213 {
1214     ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
1215             cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
1216 
1217     // only get parameter command is permitted for applications not controlling the effect
1218     if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
1219         return INVALID_OPERATION;
1220     }
1221     if (mEffect == 0) {
1222         return DEAD_OBJECT;
1223     }
1224     if (mClient == 0) {
1225         return INVALID_OPERATION;
1226     }
1227 
1228     // handle commands that are not forwarded transparently to effect engine
1229     if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
1230         // No need to trylock() here as this function is executed in the binder thread serving a
1231         // particular client process:  no risk to block the whole media server process or mixer
1232         // threads if we are stuck here
1233         Mutex::Autolock _l(mCblk->lock);
1234         if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
1235             mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
1236             mCblk->serverIndex = 0;
1237             mCblk->clientIndex = 0;
1238             return BAD_VALUE;
1239         }
1240         status_t status = NO_ERROR;
1241         while (mCblk->serverIndex < mCblk->clientIndex) {
1242             int reply;
1243             uint32_t rsize = sizeof(int);
1244             int *p = (int *)(mBuffer + mCblk->serverIndex);
1245             int size = *p++;
1246             if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
1247                 ALOGW("command(): invalid parameter block size");
1248                 break;
1249             }
1250             effect_param_t *param = (effect_param_t *)p;
1251             if (param->psize == 0 || param->vsize == 0) {
1252                 ALOGW("command(): null parameter or value size");
1253                 mCblk->serverIndex += size;
1254                 continue;
1255             }
1256             uint32_t psize = sizeof(effect_param_t) +
1257                              ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
1258                              param->vsize;
1259             status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
1260                                             psize,
1261                                             p,
1262                                             &rsize,
1263                                             &reply);
1264             // stop at first error encountered
1265             if (ret != NO_ERROR) {
1266                 status = ret;
1267                 *(int *)pReplyData = reply;
1268                 break;
1269             } else if (reply != NO_ERROR) {
1270                 *(int *)pReplyData = reply;
1271                 break;
1272             }
1273             mCblk->serverIndex += size;
1274         }
1275         mCblk->serverIndex = 0;
1276         mCblk->clientIndex = 0;
1277         return status;
1278     } else if (cmdCode == EFFECT_CMD_ENABLE) {
1279         *(int *)pReplyData = NO_ERROR;
1280         return enable();
1281     } else if (cmdCode == EFFECT_CMD_DISABLE) {
1282         *(int *)pReplyData = NO_ERROR;
1283         return disable();
1284     }
1285 
1286     return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
1287 }
1288 
setControl(bool hasControl,bool signal,bool enabled)1289 void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
1290 {
1291     ALOGV("setControl %p control %d", this, hasControl);
1292 
1293     mHasControl = hasControl;
1294     mEnabled = enabled;
1295 
1296     if (signal && mEffectClient != 0) {
1297         mEffectClient->controlStatusChanged(hasControl);
1298     }
1299 }
1300 
commandExecuted(uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t replySize,void * pReplyData)1301 void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
1302                                                  uint32_t cmdSize,
1303                                                  void *pCmdData,
1304                                                  uint32_t replySize,
1305                                                  void *pReplyData)
1306 {
1307     if (mEffectClient != 0) {
1308         mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
1309     }
1310 }
1311 
1312 
1313 
setEnabled(bool enabled)1314 void AudioFlinger::EffectHandle::setEnabled(bool enabled)
1315 {
1316     if (mEffectClient != 0) {
1317         mEffectClient->enableStatusChanged(enabled);
1318     }
1319 }
1320 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1321 status_t AudioFlinger::EffectHandle::onTransact(
1322     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1323 {
1324     return BnEffect::onTransact(code, data, reply, flags);
1325 }
1326 
1327 
dumpToBuffer(char * buffer,size_t size)1328 void AudioFlinger::EffectHandle::dumpToBuffer(char* buffer, size_t size)
1329 {
1330     bool locked = mCblk != NULL && AudioFlinger::dumpTryLock(mCblk->lock);
1331 
1332     snprintf(buffer, size, "\t\t\t%5d    %5d  %3s    %3s  %5u  %5u\n",
1333             (mClient == 0) ? getpid_cached : mClient->pid(),
1334             mPriority,
1335             mHasControl ? "yes" : "no",
1336             locked ? "yes" : "no",
1337             mCblk ? mCblk->clientIndex : 0,
1338             mCblk ? mCblk->serverIndex : 0
1339             );
1340 
1341     if (locked) {
1342         mCblk->lock.unlock();
1343     }
1344 }
1345 
1346 #undef LOG_TAG
1347 #define LOG_TAG "AudioFlinger::EffectChain"
1348 
EffectChain(ThreadBase * thread,int sessionId)1349 AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
1350                                         int sessionId)
1351     : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
1352       mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
1353       mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX), mForceVolume(false)
1354 {
1355     mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1356     if (thread == NULL) {
1357         return;
1358     }
1359     mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
1360                                     thread->frameCount();
1361 }
1362 
~EffectChain()1363 AudioFlinger::EffectChain::~EffectChain()
1364 {
1365     if (mOwnInBuffer) {
1366         delete mInBuffer;
1367     }
1368 
1369 }
1370 
1371 // getEffectFromDesc_l() must be called with ThreadBase::mLock held
getEffectFromDesc_l(effect_descriptor_t * descriptor)1372 sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
1373         effect_descriptor_t *descriptor)
1374 {
1375     size_t size = mEffects.size();
1376 
1377     for (size_t i = 0; i < size; i++) {
1378         if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
1379             return mEffects[i];
1380         }
1381     }
1382     return 0;
1383 }
1384 
1385 // getEffectFromId_l() must be called with ThreadBase::mLock held
getEffectFromId_l(int id)1386 sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
1387 {
1388     size_t size = mEffects.size();
1389 
1390     for (size_t i = 0; i < size; i++) {
1391         // by convention, return first effect if id provided is 0 (0 is never a valid id)
1392         if (id == 0 || mEffects[i]->id() == id) {
1393             return mEffects[i];
1394         }
1395     }
1396     return 0;
1397 }
1398 
1399 // getEffectFromType_l() must be called with ThreadBase::mLock held
getEffectFromType_l(const effect_uuid_t * type)1400 sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
1401         const effect_uuid_t *type)
1402 {
1403     size_t size = mEffects.size();
1404 
1405     for (size_t i = 0; i < size; i++) {
1406         if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
1407             return mEffects[i];
1408         }
1409     }
1410     return 0;
1411 }
1412 
clearInputBuffer()1413 void AudioFlinger::EffectChain::clearInputBuffer()
1414 {
1415     Mutex::Autolock _l(mLock);
1416     sp<ThreadBase> thread = mThread.promote();
1417     if (thread == 0) {
1418         ALOGW("clearInputBuffer(): cannot promote mixer thread");
1419         return;
1420     }
1421     clearInputBuffer_l(thread);
1422 }
1423 
1424 // Must be called with EffectChain::mLock locked
clearInputBuffer_l(sp<ThreadBase> thread)1425 void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
1426 {
1427     // TODO: This will change in the future, depending on multichannel
1428     // and sample format changes for effects.
1429     // Currently effects processing is only available for stereo, AUDIO_FORMAT_PCM_16_BIT
1430     // (4 bytes frame size)
1431     const size_t frameSize =
1432             audio_bytes_per_sample(AUDIO_FORMAT_PCM_16_BIT) * min(FCC_2, thread->channelCount());
1433     memset(mInBuffer, 0, thread->frameCount() * frameSize);
1434 }
1435 
1436 // Must be called with EffectChain::mLock locked
process_l()1437 void AudioFlinger::EffectChain::process_l()
1438 {
1439     sp<ThreadBase> thread = mThread.promote();
1440     if (thread == 0) {
1441         ALOGW("process_l(): cannot promote mixer thread");
1442         return;
1443     }
1444     bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
1445             (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
1446     // never process effects when:
1447     // - on an OFFLOAD thread
1448     // - no more tracks are on the session and the effect tail has been rendered
1449     bool doProcess = (thread->type() != ThreadBase::OFFLOAD);
1450     if (!isGlobalSession) {
1451         bool tracksOnSession = (trackCnt() != 0);
1452 
1453         if (!tracksOnSession && mTailBufferCount == 0) {
1454             doProcess = false;
1455         }
1456 
1457         if (activeTrackCnt() == 0) {
1458             // if no track is active and the effect tail has not been rendered,
1459             // the input buffer must be cleared here as the mixer process will not do it
1460             if (tracksOnSession || mTailBufferCount > 0) {
1461                 clearInputBuffer_l(thread);
1462                 if (mTailBufferCount > 0) {
1463                     mTailBufferCount--;
1464                 }
1465             }
1466         }
1467     }
1468 
1469     size_t size = mEffects.size();
1470     if (doProcess) {
1471         for (size_t i = 0; i < size; i++) {
1472             mEffects[i]->process();
1473         }
1474     }
1475     for (size_t i = 0; i < size; i++) {
1476         mEffects[i]->updateState();
1477     }
1478 }
1479 
1480 // addEffect_l() must be called with PlaybackThread::mLock held
addEffect_l(const sp<EffectModule> & effect)1481 status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
1482 {
1483     effect_descriptor_t desc = effect->desc();
1484     uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
1485 
1486     Mutex::Autolock _l(mLock);
1487     effect->setChain(this);
1488     sp<ThreadBase> thread = mThread.promote();
1489     if (thread == 0) {
1490         return NO_INIT;
1491     }
1492     effect->setThread(thread);
1493 
1494     if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1495         // Auxiliary effects are inserted at the beginning of mEffects vector as
1496         // they are processed first and accumulated in chain input buffer
1497         mEffects.insertAt(effect, 0);
1498 
1499         // the input buffer for auxiliary effect contains mono samples in
1500         // 32 bit format. This is to avoid saturation in AudoMixer
1501         // accumulation stage. Saturation is done in EffectModule::process() before
1502         // calling the process in effect engine
1503         size_t numSamples = thread->frameCount();
1504         int32_t *buffer = new int32_t[numSamples];
1505         memset(buffer, 0, numSamples * sizeof(int32_t));
1506         effect->setInBuffer((int16_t *)buffer);
1507         // auxiliary effects output samples to chain input buffer for further processing
1508         // by insert effects
1509         effect->setOutBuffer(mInBuffer);
1510     } else {
1511         // Insert effects are inserted at the end of mEffects vector as they are processed
1512         //  after track and auxiliary effects.
1513         // Insert effect order as a function of indicated preference:
1514         //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
1515         //  another effect is present
1516         //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
1517         //  last effect claiming first position
1518         //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
1519         //  first effect claiming last position
1520         //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
1521         // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
1522         // already present
1523 
1524         size_t size = mEffects.size();
1525         size_t idx_insert = size;
1526         ssize_t idx_insert_first = -1;
1527         ssize_t idx_insert_last = -1;
1528 
1529         for (size_t i = 0; i < size; i++) {
1530             effect_descriptor_t d = mEffects[i]->desc();
1531             uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
1532             uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
1533             if (iMode == EFFECT_FLAG_TYPE_INSERT) {
1534                 // check invalid effect chaining combinations
1535                 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
1536                     iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
1537                     ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s",
1538                             desc.name, d.name);
1539                     return INVALID_OPERATION;
1540                 }
1541                 // remember position of first insert effect and by default
1542                 // select this as insert position for new effect
1543                 if (idx_insert == size) {
1544                     idx_insert = i;
1545                 }
1546                 // remember position of last insert effect claiming
1547                 // first position
1548                 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
1549                     idx_insert_first = i;
1550                 }
1551                 // remember position of first insert effect claiming
1552                 // last position
1553                 if (iPref == EFFECT_FLAG_INSERT_LAST &&
1554                     idx_insert_last == -1) {
1555                     idx_insert_last = i;
1556                 }
1557             }
1558         }
1559 
1560         // modify idx_insert from first position if needed
1561         if (insertPref == EFFECT_FLAG_INSERT_LAST) {
1562             if (idx_insert_last != -1) {
1563                 idx_insert = idx_insert_last;
1564             } else {
1565                 idx_insert = size;
1566             }
1567         } else {
1568             if (idx_insert_first != -1) {
1569                 idx_insert = idx_insert_first + 1;
1570             }
1571         }
1572 
1573         // always read samples from chain input buffer
1574         effect->setInBuffer(mInBuffer);
1575 
1576         // if last effect in the chain, output samples to chain
1577         // output buffer, otherwise to chain input buffer
1578         if (idx_insert == size) {
1579             if (idx_insert != 0) {
1580                 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
1581                 mEffects[idx_insert-1]->configure();
1582             }
1583             effect->setOutBuffer(mOutBuffer);
1584         } else {
1585             effect->setOutBuffer(mInBuffer);
1586         }
1587         mEffects.insertAt(effect, idx_insert);
1588 
1589         ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this,
1590                 idx_insert);
1591     }
1592     effect->configure();
1593     return NO_ERROR;
1594 }
1595 
1596 // removeEffect_l() must be called with PlaybackThread::mLock held
removeEffect_l(const sp<EffectModule> & effect)1597 size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
1598 {
1599     Mutex::Autolock _l(mLock);
1600     size_t size = mEffects.size();
1601     uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
1602 
1603     for (size_t i = 0; i < size; i++) {
1604         if (effect == mEffects[i]) {
1605             // calling stop here will remove pre-processing effect from the audio HAL.
1606             // This is safe as we hold the EffectChain mutex which guarantees that we are not in
1607             // the middle of a read from audio HAL
1608             if (mEffects[i]->state() == EffectModule::ACTIVE ||
1609                     mEffects[i]->state() == EffectModule::STOPPING) {
1610                 mEffects[i]->stop();
1611             }
1612             if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
1613                 delete[] effect->inBuffer();
1614             } else {
1615                 if (i == size - 1 && i != 0) {
1616                     mEffects[i - 1]->setOutBuffer(mOutBuffer);
1617                     mEffects[i - 1]->configure();
1618                 }
1619             }
1620             mEffects.removeAt(i);
1621             ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(),
1622                     this, i);
1623             break;
1624         }
1625     }
1626 
1627     return mEffects.size();
1628 }
1629 
1630 // setDevice_l() must be called with PlaybackThread::mLock held
setDevice_l(audio_devices_t device)1631 void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
1632 {
1633     size_t size = mEffects.size();
1634     for (size_t i = 0; i < size; i++) {
1635         mEffects[i]->setDevice(device);
1636     }
1637 }
1638 
1639 // setMode_l() must be called with PlaybackThread::mLock held
setMode_l(audio_mode_t mode)1640 void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
1641 {
1642     size_t size = mEffects.size();
1643     for (size_t i = 0; i < size; i++) {
1644         mEffects[i]->setMode(mode);
1645     }
1646 }
1647 
1648 // setAudioSource_l() must be called with PlaybackThread::mLock held
setAudioSource_l(audio_source_t source)1649 void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
1650 {
1651     size_t size = mEffects.size();
1652     for (size_t i = 0; i < size; i++) {
1653         mEffects[i]->setAudioSource(source);
1654     }
1655 }
1656 
1657 // setVolume_l() must be called with PlaybackThread::mLock held
setVolume_l(uint32_t * left,uint32_t * right)1658 bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
1659 {
1660     uint32_t newLeft = *left;
1661     uint32_t newRight = *right;
1662     bool hasControl = false;
1663     int ctrlIdx = -1;
1664     size_t size = mEffects.size();
1665 
1666     // first update volume controller
1667     for (size_t i = size; i > 0; i--) {
1668         if (mEffects[i - 1]->isProcessEnabled() &&
1669             (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
1670             ctrlIdx = i - 1;
1671             hasControl = true;
1672             break;
1673         }
1674     }
1675 
1676     if (!isVolumeForced() && ctrlIdx == mVolumeCtrlIdx &&
1677             *left == mLeftVolume && *right == mRightVolume) {
1678         if (hasControl) {
1679             *left = mNewLeftVolume;
1680             *right = mNewRightVolume;
1681         }
1682         return hasControl;
1683     }
1684 
1685     mVolumeCtrlIdx = ctrlIdx;
1686     mLeftVolume = newLeft;
1687     mRightVolume = newRight;
1688 
1689     // second get volume update from volume controller
1690     if (ctrlIdx >= 0) {
1691         mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
1692         mNewLeftVolume = newLeft;
1693         mNewRightVolume = newRight;
1694     }
1695     // then indicate volume to all other effects in chain.
1696     // Pass altered volume to effects before volume controller
1697     // and requested volume to effects after controller
1698     uint32_t lVol = newLeft;
1699     uint32_t rVol = newRight;
1700 
1701     for (size_t i = 0; i < size; i++) {
1702         if ((int)i == ctrlIdx) {
1703             continue;
1704         }
1705         // this also works for ctrlIdx == -1 when there is no volume controller
1706         if ((int)i > ctrlIdx) {
1707             lVol = *left;
1708             rVol = *right;
1709         }
1710         mEffects[i]->setVolume(&lVol, &rVol, false);
1711     }
1712     *left = newLeft;
1713     *right = newRight;
1714 
1715     return hasControl;
1716 }
1717 
syncHalEffectsState()1718 void AudioFlinger::EffectChain::syncHalEffectsState()
1719 {
1720     Mutex::Autolock _l(mLock);
1721     for (size_t i = 0; i < mEffects.size(); i++) {
1722         if (mEffects[i]->state() == EffectModule::ACTIVE ||
1723                 mEffects[i]->state() == EffectModule::STOPPING) {
1724             mEffects[i]->addEffectToHal_l();
1725         }
1726     }
1727 }
1728 
dump(int fd,const Vector<String16> & args)1729 void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
1730 {
1731     const size_t SIZE = 256;
1732     char buffer[SIZE];
1733     String8 result;
1734 
1735     size_t numEffects = mEffects.size();
1736     snprintf(buffer, SIZE, "    %d effects for session %d\n", numEffects, mSessionId);
1737     result.append(buffer);
1738 
1739     if (numEffects) {
1740         bool locked = AudioFlinger::dumpTryLock(mLock);
1741         // failed to lock - AudioFlinger is probably deadlocked
1742         if (!locked) {
1743             result.append("\tCould not lock mutex:\n");
1744         }
1745 
1746         result.append("\tIn buffer   Out buffer   Active tracks:\n");
1747         snprintf(buffer, SIZE, "\t%p  %p   %d\n",
1748                 mInBuffer,
1749                 mOutBuffer,
1750                 mActiveTrackCnt);
1751         result.append(buffer);
1752         write(fd, result.string(), result.size());
1753 
1754         for (size_t i = 0; i < numEffects; ++i) {
1755             sp<EffectModule> effect = mEffects[i];
1756             if (effect != 0) {
1757                 effect->dump(fd, args);
1758             }
1759         }
1760 
1761         if (locked) {
1762             mLock.unlock();
1763         }
1764     }
1765 }
1766 
1767 // must be called with ThreadBase::mLock held
setEffectSuspended_l(const effect_uuid_t * type,bool suspend)1768 void AudioFlinger::EffectChain::setEffectSuspended_l(
1769         const effect_uuid_t *type, bool suspend)
1770 {
1771     sp<SuspendedEffectDesc> desc;
1772     // use effect type UUID timelow as key as there is no real risk of identical
1773     // timeLow fields among effect type UUIDs.
1774     ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
1775     if (suspend) {
1776         if (index >= 0) {
1777             desc = mSuspendedEffects.valueAt(index);
1778         } else {
1779             desc = new SuspendedEffectDesc();
1780             desc->mType = *type;
1781             mSuspendedEffects.add(type->timeLow, desc);
1782             ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
1783         }
1784         if (desc->mRefCount++ == 0) {
1785             sp<EffectModule> effect = getEffectIfEnabled(type);
1786             if (effect != 0) {
1787                 desc->mEffect = effect;
1788                 effect->setSuspended(true);
1789                 effect->setEnabled(false);
1790             }
1791         }
1792     } else {
1793         if (index < 0) {
1794             return;
1795         }
1796         desc = mSuspendedEffects.valueAt(index);
1797         if (desc->mRefCount <= 0) {
1798             ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
1799             desc->mRefCount = 1;
1800         }
1801         if (--desc->mRefCount == 0) {
1802             ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
1803             if (desc->mEffect != 0) {
1804                 sp<EffectModule> effect = desc->mEffect.promote();
1805                 if (effect != 0) {
1806                     effect->setSuspended(false);
1807                     effect->lock();
1808                     EffectHandle *handle = effect->controlHandle_l();
1809                     if (handle != NULL && !handle->destroyed_l()) {
1810                         effect->setEnabled_l(handle->enabled());
1811                     }
1812                     effect->unlock();
1813                 }
1814                 desc->mEffect.clear();
1815             }
1816             mSuspendedEffects.removeItemsAt(index);
1817         }
1818     }
1819 }
1820 
1821 // must be called with ThreadBase::mLock held
setEffectSuspendedAll_l(bool suspend)1822 void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
1823 {
1824     sp<SuspendedEffectDesc> desc;
1825 
1826     ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
1827     if (suspend) {
1828         if (index >= 0) {
1829             desc = mSuspendedEffects.valueAt(index);
1830         } else {
1831             desc = new SuspendedEffectDesc();
1832             mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
1833             ALOGV("setEffectSuspendedAll_l() add entry for 0");
1834         }
1835         if (desc->mRefCount++ == 0) {
1836             Vector< sp<EffectModule> > effects;
1837             getSuspendEligibleEffects(effects);
1838             for (size_t i = 0; i < effects.size(); i++) {
1839                 setEffectSuspended_l(&effects[i]->desc().type, true);
1840             }
1841         }
1842     } else {
1843         if (index < 0) {
1844             return;
1845         }
1846         desc = mSuspendedEffects.valueAt(index);
1847         if (desc->mRefCount <= 0) {
1848             ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
1849             desc->mRefCount = 1;
1850         }
1851         if (--desc->mRefCount == 0) {
1852             Vector<const effect_uuid_t *> types;
1853             for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
1854                 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
1855                     continue;
1856                 }
1857                 types.add(&mSuspendedEffects.valueAt(i)->mType);
1858             }
1859             for (size_t i = 0; i < types.size(); i++) {
1860                 setEffectSuspended_l(types[i], false);
1861             }
1862             ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
1863                     mSuspendedEffects.keyAt(index));
1864             mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
1865         }
1866     }
1867 }
1868 
1869 
1870 // The volume effect is used for automated tests only
1871 #ifndef OPENSL_ES_H_
1872 static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
1873                                             { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
1874 const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
1875 #endif //OPENSL_ES_H_
1876 
isEffectEligibleForSuspend(const effect_descriptor_t & desc)1877 bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
1878 {
1879     // auxiliary effects and visualizer are never suspended on output mix
1880     if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
1881         (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
1882          (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
1883          (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
1884         return false;
1885     }
1886     return true;
1887 }
1888 
getSuspendEligibleEffects(Vector<sp<AudioFlinger::EffectModule>> & effects)1889 void AudioFlinger::EffectChain::getSuspendEligibleEffects(
1890         Vector< sp<AudioFlinger::EffectModule> > &effects)
1891 {
1892     effects.clear();
1893     for (size_t i = 0; i < mEffects.size(); i++) {
1894         if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
1895             effects.add(mEffects[i]);
1896         }
1897     }
1898 }
1899 
getEffectIfEnabled(const effect_uuid_t * type)1900 sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
1901                                                             const effect_uuid_t *type)
1902 {
1903     sp<EffectModule> effect = getEffectFromType_l(type);
1904     return effect != 0 && effect->isEnabled() ? effect : 0;
1905 }
1906 
checkSuspendOnEffectEnabled(const sp<EffectModule> & effect,bool enabled)1907 void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1908                                                             bool enabled)
1909 {
1910     ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
1911     if (enabled) {
1912         if (index < 0) {
1913             // if the effect is not suspend check if all effects are suspended
1914             index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
1915             if (index < 0) {
1916                 return;
1917             }
1918             if (!isEffectEligibleForSuspend(effect->desc())) {
1919                 return;
1920             }
1921             setEffectSuspended_l(&effect->desc().type, enabled);
1922             index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
1923             if (index < 0) {
1924                 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
1925                 return;
1926             }
1927         }
1928         ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
1929             effect->desc().type.timeLow);
1930         sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
1931         // if effect is requested to suspended but was not yet enabled, supend it now.
1932         if (desc->mEffect == 0) {
1933             desc->mEffect = effect;
1934             effect->setEnabled(false);
1935             effect->setSuspended(true);
1936         }
1937     } else {
1938         if (index < 0) {
1939             return;
1940         }
1941         ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
1942             effect->desc().type.timeLow);
1943         sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
1944         desc->mEffect.clear();
1945         effect->setSuspended(false);
1946     }
1947 }
1948 
isNonOffloadableEnabled()1949 bool AudioFlinger::EffectChain::isNonOffloadableEnabled()
1950 {
1951     Mutex::Autolock _l(mLock);
1952     size_t size = mEffects.size();
1953     for (size_t i = 0; i < size; i++) {
1954         if (mEffects[i]->isEnabled() && !mEffects[i]->isOffloadable()) {
1955             return true;
1956         }
1957     }
1958     return false;
1959 }
1960 
setThread(const sp<ThreadBase> & thread)1961 void AudioFlinger::EffectChain::setThread(const sp<ThreadBase>& thread)
1962 {
1963     Mutex::Autolock _l(mLock);
1964     mThread = thread;
1965     for (size_t i = 0; i < mEffects.size(); i++) {
1966         mEffects[i]->setThread(thread);
1967     }
1968 }
1969 
1970 } // namespace android
1971