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