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