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