blob: 25c1dbb7be1b701d60094feb864c16f928496243 [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"
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070030#include "EffectHalInterface.h"
31// FIXME: Remove after converting the main audio HAL
32#include "EffectHalLocal.h"
33#include "EffectsFactoryHalInterface.h"
Eric Laurentca7cc822012-11-19 14:55:58 -080034#include "ServiceUtilities.h"
35
36// ----------------------------------------------------------------------------
37
38// Note: the following macro is used for extremely verbose logging message. In
39// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
40// 0; but one side effect of this is to turn all LOGV's as well. Some messages
41// are so verbose that we want to suppress them even when we have ALOG_ASSERT
42// turned on. Do not uncomment the #def below unless you really know what you
43// are doing and want to see all of the extremely verbose messages.
44//#define VERY_VERY_VERBOSE_LOGGING
45#ifdef VERY_VERY_VERBOSE_LOGGING
46#define ALOGVV ALOGV
47#else
48#define ALOGVV(a...) do { } while(0)
49#endif
50
Ricardo Garcia726b6a72014-08-11 12:04:54 -070051#define min(a, b) ((a) < (b) ? (a) : (b))
52
Eric Laurentca7cc822012-11-19 14:55:58 -080053namespace android {
54
55// ----------------------------------------------------------------------------
56// EffectModule implementation
57// ----------------------------------------------------------------------------
58
59#undef LOG_TAG
60#define LOG_TAG "AudioFlinger::EffectModule"
61
62AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
63 const wp<AudioFlinger::EffectChain>& chain,
64 effect_descriptor_t *desc,
65 int id,
Glenn Kastend848eb42016-03-08 13:42:11 -080066 audio_session_t sessionId)
Eric Laurentca7cc822012-11-19 14:55:58 -080067 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
68 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
69 mDescriptor(*desc),
70 // mConfig is set by configure() and not used before then
Eric Laurentca7cc822012-11-19 14:55:58 -080071 mStatus(NO_INIT), mState(IDLE),
72 // mMaxDisableWaitCnt is set by configure() and not used before then
73 // mDisableWaitCnt is set by process() and updateState() and not used before then
Eric Laurentaaa44472014-09-12 17:41:50 -070074 mSuspended(false),
75 mAudioFlinger(thread->mAudioFlinger)
Eric Laurentca7cc822012-11-19 14:55:58 -080076{
77 ALOGV("Constructor %p", this);
78 int lStatus;
79
80 // create effect engine from effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070081 mStatus = -ENODEV;
82 sp<AudioFlinger> audioFlinger = mAudioFlinger.promote();
83 if (audioFlinger.get() != NULL) {
84 sp<EffectsFactoryHalInterface> effectsFactory = audioFlinger->getEffectsFactory();
85 if (effectsFactory.get() != NULL) {
86 mStatus = effectsFactory->createEffect(
87 &desc->uuid, sessionId, thread->id(), &mEffectInterface);
88 }
89 }
Eric Laurentca7cc822012-11-19 14:55:58 -080090
91 if (mStatus != NO_ERROR) {
92 return;
93 }
94 lStatus = init();
95 if (lStatus < 0) {
96 mStatus = lStatus;
97 goto Error;
98 }
99
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700100 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface.get());
Eric Laurentca7cc822012-11-19 14:55:58 -0800101 return;
102Error:
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700103 mEffectInterface.clear();
Eric Laurentca7cc822012-11-19 14:55:58 -0800104 ALOGV("Constructor Error %d", mStatus);
105}
106
107AudioFlinger::EffectModule::~EffectModule()
108{
109 ALOGV("Destructor %p", this);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700110 if (mEffectInterface.get() != NULL) {
Eric Laurentbfb1b832013-01-07 09:53:42 -0800111 remove_effect_from_hal_l();
Eric Laurentca7cc822012-11-19 14:55:58 -0800112 // release effect engine
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700113 mEffectInterface.clear();
Eric Laurentca7cc822012-11-19 14:55:58 -0800114 }
115}
116
117status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
118{
119 status_t status;
120
121 Mutex::Autolock _l(mLock);
122 int priority = handle->priority();
123 size_t size = mHandles.size();
124 EffectHandle *controlHandle = NULL;
125 size_t i;
126 for (i = 0; i < size; i++) {
127 EffectHandle *h = mHandles[i];
128 if (h == NULL || h->destroyed_l()) {
129 continue;
130 }
131 // first non destroyed handle is considered in control
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700132 if (controlHandle == NULL) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800133 controlHandle = h;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700134 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800135 if (h->priority() <= priority) {
136 break;
137 }
138 }
139 // if inserted in first place, move effect control from previous owner to this handle
140 if (i == 0) {
141 bool enabled = false;
142 if (controlHandle != NULL) {
143 enabled = controlHandle->enabled();
144 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
145 }
146 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
147 status = NO_ERROR;
148 } else {
149 status = ALREADY_EXISTS;
150 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700151 ALOGV("addHandle() %p added handle %p in position %zu", this, handle, i);
Eric Laurentca7cc822012-11-19 14:55:58 -0800152 mHandles.insertAt(handle, i);
153 return status;
154}
155
156size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
157{
158 Mutex::Autolock _l(mLock);
159 size_t size = mHandles.size();
160 size_t i;
161 for (i = 0; i < size; i++) {
162 if (mHandles[i] == handle) {
163 break;
164 }
165 }
166 if (i == size) {
167 return size;
168 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700169 ALOGV("removeHandle() %p removed handle %p in position %zu", this, handle, i);
Eric Laurentca7cc822012-11-19 14:55:58 -0800170
171 mHandles.removeAt(i);
172 // if removed from first place, move effect control from this handle to next in line
173 if (i == 0) {
174 EffectHandle *h = controlHandle_l();
175 if (h != NULL) {
176 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
177 }
178 }
179
180 // Prevent calls to process() and other functions on effect interface from now on.
181 // The effect engine will be released by the destructor when the last strong reference on
182 // this object is released which can happen after next process is called.
183 if (mHandles.size() == 0 && !mPinned) {
184 mState = DESTROYED;
185 }
186
187 return mHandles.size();
188}
189
190// must be called with EffectModule::mLock held
191AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
192{
193 // the first valid handle in the list has control over the module
194 for (size_t i = 0; i < mHandles.size(); i++) {
195 EffectHandle *h = mHandles[i];
196 if (h != NULL && !h->destroyed_l()) {
197 return h;
198 }
199 }
200
201 return NULL;
202}
203
204size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
205{
206 ALOGV("disconnect() %p handle %p", this, handle);
207 // keep a strong reference on this EffectModule to avoid calling the
208 // destructor before we exit
209 sp<EffectModule> keep(this);
210 {
Eric Laurentaaa44472014-09-12 17:41:50 -0700211 if (removeHandle(handle) == 0) {
212 if (!isPinned() || unpinIfLast) {
213 sp<ThreadBase> thread = mThread.promote();
214 if (thread != 0) {
215 Mutex::Autolock _l(thread->mLock);
216 thread->removeEffect_l(this);
217 }
218 sp<AudioFlinger> af = mAudioFlinger.promote();
219 if (af != 0) {
220 af->updateOrphanEffectChains(this);
221 }
222 AudioSystem::unregisterEffect(mId);
223 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800224 }
225 }
226 return mHandles.size();
227}
228
Eric Laurentfa1e1232016-08-02 19:01:49 -0700229bool AudioFlinger::EffectModule::updateState() {
Eric Laurentca7cc822012-11-19 14:55:58 -0800230 Mutex::Autolock _l(mLock);
231
Eric Laurentfa1e1232016-08-02 19:01:49 -0700232 bool started = false;
Eric Laurentca7cc822012-11-19 14:55:58 -0800233 switch (mState) {
234 case RESTART:
235 reset_l();
236 // FALL THROUGH
237
238 case STARTING:
239 // clear auxiliary effect input buffer for next accumulation
240 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
241 memset(mConfig.inputCfg.buffer.raw,
242 0,
243 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
244 }
Eric Laurentd0ebb532013-04-02 16:41:41 -0700245 if (start_l() == NO_ERROR) {
246 mState = ACTIVE;
Eric Laurentfa1e1232016-08-02 19:01:49 -0700247 started = true;
Eric Laurentd0ebb532013-04-02 16:41:41 -0700248 } else {
249 mState = IDLE;
250 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800251 break;
252 case STOPPING:
Eric Laurentd0ebb532013-04-02 16:41:41 -0700253 if (stop_l() == NO_ERROR) {
254 mDisableWaitCnt = mMaxDisableWaitCnt;
255 } else {
256 mDisableWaitCnt = 1; // will cause immediate transition to IDLE
257 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800258 mState = STOPPED;
259 break;
260 case STOPPED:
261 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
262 // turn off sequence.
263 if (--mDisableWaitCnt == 0) {
264 reset_l();
265 mState = IDLE;
266 }
267 break;
268 default: //IDLE , ACTIVE, DESTROYED
269 break;
270 }
Eric Laurentfa1e1232016-08-02 19:01:49 -0700271
272 return started;
Eric Laurentca7cc822012-11-19 14:55:58 -0800273}
274
275void AudioFlinger::EffectModule::process()
276{
277 Mutex::Autolock _l(mLock);
278
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700279 if (mState == DESTROYED || mEffectInterface.get() == NULL ||
Eric Laurentca7cc822012-11-19 14:55:58 -0800280 mConfig.inputCfg.buffer.raw == NULL ||
281 mConfig.outputCfg.buffer.raw == NULL) {
282 return;
283 }
284
285 if (isProcessEnabled()) {
286 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
287 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
288 ditherAndClamp(mConfig.inputCfg.buffer.s32,
289 mConfig.inputCfg.buffer.s32,
290 mConfig.inputCfg.buffer.frameCount/2);
291 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700292 int ret;
293 if (isProcessImplemented()) {
294 // do the actual processing in the effect engine
Eric Laurentdb0fd692016-09-16 10:26:09 -0700295 ret = mEffectInterface->process(&mConfig.inputCfg.buffer, &mConfig.outputCfg.buffer);
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700296 } else {
297 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
298 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * FCC_2; //always stereo here
299 int16_t *in = mConfig.inputCfg.buffer.s16;
300 int16_t *out = mConfig.outputCfg.buffer.s16;
Eric Laurentca7cc822012-11-19 14:55:58 -0800301
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700302 if (mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
303 for (size_t i = 0; i < frameCnt; i++) {
304 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
305 }
306 } else {
307 memcpy(mConfig.outputCfg.buffer.raw, mConfig.inputCfg.buffer.raw,
308 frameCnt * sizeof(int16_t));
309 }
310 }
311 ret = -ENODATA;
312 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800313 // force transition to IDLE state when engine is ready
314 if (mState == STOPPED && ret == -ENODATA) {
315 mDisableWaitCnt = 1;
316 }
317
318 // clear auxiliary effect input buffer for next accumulation
319 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
320 memset(mConfig.inputCfg.buffer.raw, 0,
321 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
322 }
323 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
324 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
325 // If an insert effect is idle and input buffer is different from output buffer,
326 // accumulate input onto output
327 sp<EffectChain> chain = mChain.promote();
328 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent6dd0fd92016-09-15 12:44:53 -0700329 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * FCC_2; //always stereo here
Eric Laurentca7cc822012-11-19 14:55:58 -0800330 int16_t *in = mConfig.inputCfg.buffer.s16;
331 int16_t *out = mConfig.outputCfg.buffer.s16;
332 for (size_t i = 0; i < frameCnt; i++) {
333 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
334 }
335 }
336 }
337}
338
339void AudioFlinger::EffectModule::reset_l()
340{
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700341 if (mStatus != NO_ERROR || mEffectInterface.get() == NULL) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800342 return;
343 }
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700344 mEffectInterface->command(EFFECT_CMD_RESET, 0, NULL, 0, NULL);
Eric Laurentca7cc822012-11-19 14:55:58 -0800345}
346
347status_t AudioFlinger::EffectModule::configure()
348{
Eric Laurentd0ebb532013-04-02 16:41:41 -0700349 status_t status;
350 sp<ThreadBase> thread;
351 uint32_t size;
352 audio_channel_mask_t channelMask;
353
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700354 if (mEffectInterface.get() == NULL) {
Eric Laurentd0ebb532013-04-02 16:41:41 -0700355 status = NO_INIT;
356 goto exit;
Eric Laurentca7cc822012-11-19 14:55:58 -0800357 }
358
Eric Laurentd0ebb532013-04-02 16:41:41 -0700359 thread = mThread.promote();
Eric Laurentca7cc822012-11-19 14:55:58 -0800360 if (thread == 0) {
Eric Laurentd0ebb532013-04-02 16:41:41 -0700361 status = DEAD_OBJECT;
362 goto exit;
Eric Laurentca7cc822012-11-19 14:55:58 -0800363 }
364
365 // TODO: handle configuration of effects replacing track process
Eric Laurentd0ebb532013-04-02 16:41:41 -0700366 channelMask = thread->channelMask();
Ricardo Garciad11da702015-05-28 12:14:12 -0700367 mConfig.outputCfg.channels = channelMask;
Eric Laurentca7cc822012-11-19 14:55:58 -0800368
369 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
370 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
371 } else {
372 mConfig.inputCfg.channels = channelMask;
Ricardo Garciad11da702015-05-28 12:14:12 -0700373 // TODO: Update this logic when multichannel effects are implemented.
374 // For offloaded tracks consider mono output as stereo for proper effect initialization
375 if (channelMask == AUDIO_CHANNEL_OUT_MONO) {
376 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
377 mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
378 ALOGV("Overriding effect input and output as STEREO");
379 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800380 }
Ricardo Garciad11da702015-05-28 12:14:12 -0700381
Eric Laurentca7cc822012-11-19 14:55:58 -0800382 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
383 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
384 mConfig.inputCfg.samplingRate = thread->sampleRate();
385 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
386 mConfig.inputCfg.bufferProvider.cookie = NULL;
387 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
388 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
389 mConfig.outputCfg.bufferProvider.cookie = NULL;
390 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
391 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
392 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
393 // Insert effect:
394 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
395 // always overwrites output buffer: input buffer == output buffer
396 // - in other sessions:
397 // last effect in the chain accumulates in output buffer: input buffer != output buffer
398 // other effect: overwrites output buffer: input buffer == output buffer
399 // Auxiliary effect:
400 // accumulates in output buffer: input buffer != output buffer
401 // Therefore: accumulate <=> input buffer != output buffer
402 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
403 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
404 } else {
405 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
406 }
407 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
408 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
409 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
410 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
411
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700412 ALOGV("configure() %p thread %p buffer %p framecount %zu",
Eric Laurentca7cc822012-11-19 14:55:58 -0800413 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
414
415 status_t cmdStatus;
Eric Laurentd0ebb532013-04-02 16:41:41 -0700416 size = sizeof(int);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700417 status = mEffectInterface->command(EFFECT_CMD_SET_CONFIG,
418 sizeof(effect_config_t),
419 &mConfig,
420 &size,
421 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -0800422 if (status == 0) {
423 status = cmdStatus;
424 }
425
426 if (status == 0 &&
427 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
428 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
429 effect_param_t *p = (effect_param_t *)buf32;
430
431 p->psize = sizeof(uint32_t);
432 p->vsize = sizeof(uint32_t);
433 size = sizeof(int);
434 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
435
436 uint32_t latency = 0;
437 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
438 if (pbt != NULL) {
439 latency = pbt->latency_l();
440 }
441
442 *((int32_t *)p->data + 1)= latency;
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700443 mEffectInterface->command(EFFECT_CMD_SET_PARAM,
444 sizeof(effect_param_t) + 8,
445 &buf32,
446 &size,
447 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -0800448 }
449
450 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
451 (1000 * mConfig.outputCfg.buffer.frameCount);
452
Eric Laurentd0ebb532013-04-02 16:41:41 -0700453exit:
454 mStatus = status;
Eric Laurentca7cc822012-11-19 14:55:58 -0800455 return status;
456}
457
458status_t AudioFlinger::EffectModule::init()
459{
460 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700461 if (mEffectInterface.get() == NULL) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800462 return NO_INIT;
463 }
464 status_t cmdStatus;
465 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700466 status_t status = mEffectInterface->command(EFFECT_CMD_INIT,
467 0,
468 NULL,
469 &size,
470 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -0800471 if (status == 0) {
472 status = cmdStatus;
473 }
474 return status;
475}
476
Eric Laurent1b928682014-10-02 19:41:47 -0700477void AudioFlinger::EffectModule::addEffectToHal_l()
478{
479 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
480 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
481 sp<ThreadBase> thread = mThread.promote();
482 if (thread != 0) {
483 audio_stream_t *stream = thread->stream();
484 if (stream != NULL) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700485 stream->add_audio_effect(stream,
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700486 static_cast<EffectHalLocal*>(mEffectInterface.get())->handle());
Eric Laurent1b928682014-10-02 19:41:47 -0700487 }
488 }
489 }
490}
491
Eric Laurentfa1e1232016-08-02 19:01:49 -0700492// start() must be called with PlaybackThread::mLock or EffectChain::mLock held
Eric Laurentca7cc822012-11-19 14:55:58 -0800493status_t AudioFlinger::EffectModule::start()
494{
Eric Laurentfa1e1232016-08-02 19:01:49 -0700495 sp<EffectChain> chain;
496 status_t status;
497 {
498 Mutex::Autolock _l(mLock);
499 status = start_l();
500 if (status == NO_ERROR) {
501 chain = mChain.promote();
502 }
503 }
504 if (chain != 0) {
505 chain->resetVolume_l();
506 }
507 return status;
Eric Laurentca7cc822012-11-19 14:55:58 -0800508}
509
510status_t AudioFlinger::EffectModule::start_l()
511{
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700512 if (mEffectInterface.get() == NULL) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800513 return NO_INIT;
514 }
Eric Laurentd0ebb532013-04-02 16:41:41 -0700515 if (mStatus != NO_ERROR) {
516 return mStatus;
517 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800518 status_t cmdStatus;
519 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700520 status_t status = mEffectInterface->command(EFFECT_CMD_ENABLE,
521 0,
522 NULL,
523 &size,
524 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -0800525 if (status == 0) {
526 status = cmdStatus;
527 }
Eric Laurentcb4b6e92014-10-01 14:26:10 -0700528 if (status == 0) {
Eric Laurent1b928682014-10-02 19:41:47 -0700529 addEffectToHal_l();
Eric Laurentca7cc822012-11-19 14:55:58 -0800530 }
531 return status;
532}
533
534status_t AudioFlinger::EffectModule::stop()
535{
536 Mutex::Autolock _l(mLock);
537 return stop_l();
538}
539
540status_t AudioFlinger::EffectModule::stop_l()
541{
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700542 if (mEffectInterface.get() == NULL) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800543 return NO_INIT;
544 }
Eric Laurentd0ebb532013-04-02 16:41:41 -0700545 if (mStatus != NO_ERROR) {
546 return mStatus;
547 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800548 status_t cmdStatus = NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -0800549 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700550 status_t status = mEffectInterface->command(EFFECT_CMD_DISABLE,
551 0,
552 NULL,
553 &size,
554 &cmdStatus);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800555 if (status == NO_ERROR) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800556 status = cmdStatus;
557 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800558 if (status == NO_ERROR) {
559 status = remove_effect_from_hal_l();
560 }
561 return status;
562}
563
564status_t AudioFlinger::EffectModule::remove_effect_from_hal_l()
565{
566 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
567 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800568 sp<ThreadBase> thread = mThread.promote();
569 if (thread != 0) {
570 audio_stream_t *stream = thread->stream();
571 if (stream != NULL) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700572 stream->remove_audio_effect(stream,
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700573 static_cast<EffectHalLocal*>(mEffectInterface.get())->handle());
Eric Laurentca7cc822012-11-19 14:55:58 -0800574 }
575 }
576 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800577 return NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -0800578}
579
Andy Hunge4a1d912016-08-17 14:11:13 -0700580// round up delta valid if value and divisor are positive.
581template <typename T>
582static T roundUpDelta(const T &value, const T &divisor) {
583 T remainder = value % divisor;
584 return remainder == 0 ? 0 : divisor - remainder;
585}
586
Eric Laurentca7cc822012-11-19 14:55:58 -0800587status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
588 uint32_t cmdSize,
589 void *pCmdData,
590 uint32_t *replySize,
591 void *pReplyData)
592{
593 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700594 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface.get());
Eric Laurentca7cc822012-11-19 14:55:58 -0800595
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700596 if (mState == DESTROYED || mEffectInterface.get() == NULL) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800597 return NO_INIT;
598 }
Eric Laurentd0ebb532013-04-02 16:41:41 -0700599 if (mStatus != NO_ERROR) {
600 return mStatus;
601 }
Andy Hung110bc952016-06-20 15:22:52 -0700602 if (cmdCode == EFFECT_CMD_GET_PARAM &&
603 (*replySize < sizeof(effect_param_t) ||
604 ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) {
605 android_errorWriteLog(0x534e4554, "29251553");
606 return -EINVAL;
607 }
Andy Hunge4a1d912016-08-17 14:11:13 -0700608 if ((cmdCode == EFFECT_CMD_SET_PARAM
609 || cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) && // DEFERRED not generally used
610 (sizeof(effect_param_t) > cmdSize
611 || ((effect_param_t *)pCmdData)->psize > cmdSize
612 - sizeof(effect_param_t)
613 || ((effect_param_t *)pCmdData)->vsize > cmdSize
614 - sizeof(effect_param_t)
615 - ((effect_param_t *)pCmdData)->psize
616 || roundUpDelta(((effect_param_t *)pCmdData)->psize, (uint32_t)sizeof(int)) >
617 cmdSize
618 - sizeof(effect_param_t)
619 - ((effect_param_t *)pCmdData)->psize
620 - ((effect_param_t *)pCmdData)->vsize)) {
621 android_errorWriteLog(0x534e4554, "30204301");
622 return -EINVAL;
623 }
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700624 status_t status = mEffectInterface->command(cmdCode,
625 cmdSize,
626 pCmdData,
627 replySize,
628 pReplyData);
Eric Laurentca7cc822012-11-19 14:55:58 -0800629 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
630 uint32_t size = (replySize == NULL) ? 0 : *replySize;
631 for (size_t i = 1; i < mHandles.size(); i++) {
632 EffectHandle *h = mHandles[i];
633 if (h != NULL && !h->destroyed_l()) {
634 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
635 }
636 }
637 }
638 return status;
639}
640
641status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
642{
643 Mutex::Autolock _l(mLock);
644 return setEnabled_l(enabled);
645}
646
647// must be called with EffectModule::mLock held
648status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
649{
650
651 ALOGV("setEnabled %p enabled %d", this, enabled);
652
653 if (enabled != isEnabled()) {
654 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
655 if (enabled && status != NO_ERROR) {
656 return status;
657 }
658
659 switch (mState) {
660 // going from disabled to enabled
661 case IDLE:
662 mState = STARTING;
663 break;
664 case STOPPED:
665 mState = RESTART;
666 break;
667 case STOPPING:
668 mState = ACTIVE;
669 break;
670
671 // going from enabled to disabled
672 case RESTART:
673 mState = STOPPED;
674 break;
675 case STARTING:
676 mState = IDLE;
677 break;
678 case ACTIVE:
679 mState = STOPPING;
680 break;
681 case DESTROYED:
682 return NO_ERROR; // simply ignore as we are being destroyed
683 }
684 for (size_t i = 1; i < mHandles.size(); i++) {
685 EffectHandle *h = mHandles[i];
686 if (h != NULL && !h->destroyed_l()) {
687 h->setEnabled(enabled);
688 }
689 }
690 }
691 return NO_ERROR;
692}
693
694bool AudioFlinger::EffectModule::isEnabled() const
695{
696 switch (mState) {
697 case RESTART:
698 case STARTING:
699 case ACTIVE:
700 return true;
701 case IDLE:
702 case STOPPING:
703 case STOPPED:
704 case DESTROYED:
705 default:
706 return false;
707 }
708}
709
710bool AudioFlinger::EffectModule::isProcessEnabled() const
711{
Eric Laurentd0ebb532013-04-02 16:41:41 -0700712 if (mStatus != NO_ERROR) {
713 return false;
714 }
715
Eric Laurentca7cc822012-11-19 14:55:58 -0800716 switch (mState) {
717 case RESTART:
718 case ACTIVE:
719 case STOPPING:
720 case STOPPED:
721 return true;
722 case IDLE:
723 case STARTING:
724 case DESTROYED:
725 default:
726 return false;
727 }
728}
729
730status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
731{
732 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -0700733 if (mStatus != NO_ERROR) {
734 return mStatus;
735 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800736 status_t status = NO_ERROR;
Eric Laurentca7cc822012-11-19 14:55:58 -0800737 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
738 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
739 if (isProcessEnabled() &&
740 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
741 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800742 uint32_t volume[2];
743 uint32_t *pVolume = NULL;
744 uint32_t size = sizeof(volume);
745 volume[0] = *left;
746 volume[1] = *right;
747 if (controller) {
748 pVolume = volume;
749 }
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700750 status = mEffectInterface->command(EFFECT_CMD_SET_VOLUME,
751 size,
752 volume,
753 &size,
754 pVolume);
Eric Laurentca7cc822012-11-19 14:55:58 -0800755 if (controller && status == NO_ERROR && size == sizeof(volume)) {
756 *left = volume[0];
757 *right = volume[1];
758 }
759 }
760 return status;
761}
762
763status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
764{
765 if (device == AUDIO_DEVICE_NONE) {
766 return NO_ERROR;
767 }
768
769 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -0700770 if (mStatus != NO_ERROR) {
771 return mStatus;
772 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800773 status_t status = NO_ERROR;
Eric Laurent7e1139c2013-06-06 18:29:01 -0700774 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentca7cc822012-11-19 14:55:58 -0800775 status_t cmdStatus;
776 uint32_t size = sizeof(status_t);
777 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
778 EFFECT_CMD_SET_INPUT_DEVICE;
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700779 status = mEffectInterface->command(cmd,
780 sizeof(uint32_t),
781 &device,
782 &size,
783 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -0800784 }
785 return status;
786}
787
788status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
789{
790 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -0700791 if (mStatus != NO_ERROR) {
792 return mStatus;
793 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800794 status_t status = NO_ERROR;
795 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
796 status_t cmdStatus;
797 uint32_t size = sizeof(status_t);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700798 status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_MODE,
799 sizeof(audio_mode_t),
800 &mode,
801 &size,
802 &cmdStatus);
Eric Laurentca7cc822012-11-19 14:55:58 -0800803 if (status == NO_ERROR) {
804 status = cmdStatus;
805 }
806 }
807 return status;
808}
809
810status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
811{
812 Mutex::Autolock _l(mLock);
Eric Laurentd0ebb532013-04-02 16:41:41 -0700813 if (mStatus != NO_ERROR) {
814 return mStatus;
815 }
Eric Laurentca7cc822012-11-19 14:55:58 -0800816 status_t status = NO_ERROR;
817 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
818 uint32_t size = 0;
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700819 status = mEffectInterface->command(EFFECT_CMD_SET_AUDIO_SOURCE,
820 sizeof(audio_source_t),
821 &source,
822 &size,
823 NULL);
Eric Laurentca7cc822012-11-19 14:55:58 -0800824 }
825 return status;
826}
827
828void AudioFlinger::EffectModule::setSuspended(bool suspended)
829{
830 Mutex::Autolock _l(mLock);
831 mSuspended = suspended;
832}
833
834bool AudioFlinger::EffectModule::suspended() const
835{
836 Mutex::Autolock _l(mLock);
837 return mSuspended;
838}
839
840bool AudioFlinger::EffectModule::purgeHandles()
841{
842 bool enabled = false;
843 Mutex::Autolock _l(mLock);
844 for (size_t i = 0; i < mHandles.size(); i++) {
845 EffectHandle *handle = mHandles[i];
846 if (handle != NULL && !handle->destroyed_l()) {
847 handle->effect().clear();
848 if (handle->hasControl()) {
849 enabled = handle->enabled();
850 }
851 }
852 }
853 return enabled;
854}
855
Eric Laurent5baf2af2013-09-12 17:37:00 -0700856status_t AudioFlinger::EffectModule::setOffloaded(bool offloaded, audio_io_handle_t io)
857{
858 Mutex::Autolock _l(mLock);
859 if (mStatus != NO_ERROR) {
860 return mStatus;
861 }
862 status_t status = NO_ERROR;
863 if ((mDescriptor.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) != 0) {
864 status_t cmdStatus;
865 uint32_t size = sizeof(status_t);
866 effect_offload_param_t cmd;
867
868 cmd.isOffload = offloaded;
869 cmd.ioHandle = io;
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700870 status = mEffectInterface->command(EFFECT_CMD_OFFLOAD,
871 sizeof(effect_offload_param_t),
872 &cmd,
873 &size,
874 &cmdStatus);
Eric Laurent5baf2af2013-09-12 17:37:00 -0700875 if (status == NO_ERROR) {
876 status = cmdStatus;
877 }
878 mOffloaded = (status == NO_ERROR) ? offloaded : false;
879 } else {
880 if (offloaded) {
881 status = INVALID_OPERATION;
882 }
883 mOffloaded = false;
884 }
885 ALOGV("setOffloaded() offloaded %d io %d status %d", offloaded, io, status);
886 return status;
887}
888
889bool AudioFlinger::EffectModule::isOffloaded() const
890{
891 Mutex::Autolock _l(mLock);
892 return mOffloaded;
893}
894
Marco Nelissenb2208842014-02-07 14:00:50 -0800895String8 effectFlagsToString(uint32_t flags) {
896 String8 s;
897
898 s.append("conn. mode: ");
899 switch (flags & EFFECT_FLAG_TYPE_MASK) {
900 case EFFECT_FLAG_TYPE_INSERT: s.append("insert"); break;
901 case EFFECT_FLAG_TYPE_AUXILIARY: s.append("auxiliary"); break;
902 case EFFECT_FLAG_TYPE_REPLACE: s.append("replace"); break;
903 case EFFECT_FLAG_TYPE_PRE_PROC: s.append("preproc"); break;
904 case EFFECT_FLAG_TYPE_POST_PROC: s.append("postproc"); break;
905 default: s.append("unknown/reserved"); break;
906 }
907 s.append(", ");
908
909 s.append("insert pref: ");
910 switch (flags & EFFECT_FLAG_INSERT_MASK) {
911 case EFFECT_FLAG_INSERT_ANY: s.append("any"); break;
912 case EFFECT_FLAG_INSERT_FIRST: s.append("first"); break;
913 case EFFECT_FLAG_INSERT_LAST: s.append("last"); break;
914 case EFFECT_FLAG_INSERT_EXCLUSIVE: s.append("exclusive"); break;
915 default: s.append("unknown/reserved"); break;
916 }
917 s.append(", ");
918
919 s.append("volume mgmt: ");
920 switch (flags & EFFECT_FLAG_VOLUME_MASK) {
921 case EFFECT_FLAG_VOLUME_NONE: s.append("none"); break;
922 case EFFECT_FLAG_VOLUME_CTRL: s.append("implements control"); break;
923 case EFFECT_FLAG_VOLUME_IND: s.append("requires indication"); break;
924 default: s.append("unknown/reserved"); break;
925 }
926 s.append(", ");
927
928 uint32_t devind = flags & EFFECT_FLAG_DEVICE_MASK;
929 if (devind) {
930 s.append("device indication: ");
931 switch (devind) {
932 case EFFECT_FLAG_DEVICE_IND: s.append("requires updates"); break;
933 default: s.append("unknown/reserved"); break;
934 }
935 s.append(", ");
936 }
937
938 s.append("input mode: ");
939 switch (flags & EFFECT_FLAG_INPUT_MASK) {
940 case EFFECT_FLAG_INPUT_DIRECT: s.append("direct"); break;
941 case EFFECT_FLAG_INPUT_PROVIDER: s.append("provider"); break;
942 case EFFECT_FLAG_INPUT_BOTH: s.append("direct+provider"); break;
943 default: s.append("not set"); break;
944 }
945 s.append(", ");
946
947 s.append("output mode: ");
948 switch (flags & EFFECT_FLAG_OUTPUT_MASK) {
949 case EFFECT_FLAG_OUTPUT_DIRECT: s.append("direct"); break;
950 case EFFECT_FLAG_OUTPUT_PROVIDER: s.append("provider"); break;
951 case EFFECT_FLAG_OUTPUT_BOTH: s.append("direct+provider"); break;
952 default: s.append("not set"); break;
953 }
954 s.append(", ");
955
956 uint32_t accel = flags & EFFECT_FLAG_HW_ACC_MASK;
957 if (accel) {
958 s.append("hardware acceleration: ");
959 switch (accel) {
960 case EFFECT_FLAG_HW_ACC_SIMPLE: s.append("non-tunneled"); break;
961 case EFFECT_FLAG_HW_ACC_TUNNEL: s.append("tunneled"); break;
962 default: s.append("unknown/reserved"); break;
963 }
964 s.append(", ");
965 }
966
967 uint32_t modeind = flags & EFFECT_FLAG_AUDIO_MODE_MASK;
968 if (modeind) {
969 s.append("mode indication: ");
970 switch (modeind) {
971 case EFFECT_FLAG_AUDIO_MODE_IND: s.append("required"); break;
972 default: s.append("unknown/reserved"); break;
973 }
974 s.append(", ");
975 }
976
977 uint32_t srcind = flags & EFFECT_FLAG_AUDIO_SOURCE_MASK;
978 if (srcind) {
979 s.append("source indication: ");
980 switch (srcind) {
981 case EFFECT_FLAG_AUDIO_SOURCE_IND: s.append("required"); break;
982 default: s.append("unknown/reserved"); break;
983 }
984 s.append(", ");
985 }
986
987 if (flags & EFFECT_FLAG_OFFLOAD_MASK) {
988 s.append("offloadable, ");
989 }
990
991 int len = s.length();
992 if (s.length() > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700993 (void) s.lockBuffer(len);
Marco Nelissenb2208842014-02-07 14:00:50 -0800994 s.unlockBuffer(len - 2);
995 }
996 return s;
997}
998
999
Glenn Kasten0f11b512014-01-31 16:18:54 -08001000void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args __unused)
Eric Laurentca7cc822012-11-19 14:55:58 -08001001{
1002 const size_t SIZE = 256;
1003 char buffer[SIZE];
1004 String8 result;
1005
1006 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
1007 result.append(buffer);
1008
1009 bool locked = AudioFlinger::dumpTryLock(mLock);
1010 // failed to lock - AudioFlinger is probably deadlocked
1011 if (!locked) {
1012 result.append("\t\tCould not lock Fx mutex:\n");
1013 }
1014
1015 result.append("\t\tSession Status State Engine:\n");
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001016 snprintf(buffer, SIZE, "\t\t%05d %03d %03d %p\n",
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07001017 mSessionId, mStatus, mState, mEffectInterface.get());
Eric Laurentca7cc822012-11-19 14:55:58 -08001018 result.append(buffer);
1019
1020 result.append("\t\tDescriptor:\n");
1021 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
1022 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
1023 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],
1024 mDescriptor.uuid.node[2],
1025 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
1026 result.append(buffer);
1027 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
1028 mDescriptor.type.timeLow, mDescriptor.type.timeMid,
1029 mDescriptor.type.timeHiAndVersion,
1030 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],
1031 mDescriptor.type.node[2],
1032 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
1033 result.append(buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001034 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X (%s)\n",
Eric Laurentca7cc822012-11-19 14:55:58 -08001035 mDescriptor.apiVersion,
Marco Nelissenb2208842014-02-07 14:00:50 -08001036 mDescriptor.flags,
1037 effectFlagsToString(mDescriptor.flags).string());
Eric Laurentca7cc822012-11-19 14:55:58 -08001038 result.append(buffer);
1039 snprintf(buffer, SIZE, "\t\t- name: %s\n",
1040 mDescriptor.name);
1041 result.append(buffer);
1042 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
1043 mDescriptor.implementor);
1044 result.append(buffer);
1045
1046 result.append("\t\t- Input configuration:\n");
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001047 result.append("\t\t\tFrames Smp rate Channels Format Buffer\n");
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001048 snprintf(buffer, SIZE, "\t\t\t%05zu %05d %08x %6d (%s) %p\n",
Eric Laurentca7cc822012-11-19 14:55:58 -08001049 mConfig.inputCfg.buffer.frameCount,
1050 mConfig.inputCfg.samplingRate,
1051 mConfig.inputCfg.channels,
Marco Nelissenb2208842014-02-07 14:00:50 -08001052 mConfig.inputCfg.format,
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001053 formatToString((audio_format_t)mConfig.inputCfg.format),
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001054 mConfig.inputCfg.buffer.raw);
Eric Laurentca7cc822012-11-19 14:55:58 -08001055 result.append(buffer);
1056
1057 result.append("\t\t- Output configuration:\n");
1058 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001059 snprintf(buffer, SIZE, "\t\t\t%p %05zu %05d %08x %d (%s)\n",
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001060 mConfig.outputCfg.buffer.raw,
Eric Laurentca7cc822012-11-19 14:55:58 -08001061 mConfig.outputCfg.buffer.frameCount,
1062 mConfig.outputCfg.samplingRate,
1063 mConfig.outputCfg.channels,
Marco Nelissenb2208842014-02-07 14:00:50 -08001064 mConfig.outputCfg.format,
1065 formatToString((audio_format_t)mConfig.outputCfg.format));
Eric Laurentca7cc822012-11-19 14:55:58 -08001066 result.append(buffer);
1067
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001068 snprintf(buffer, SIZE, "\t\t%zu Clients:\n", mHandles.size());
Eric Laurentca7cc822012-11-19 14:55:58 -08001069 result.append(buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001070 result.append("\t\t\t Pid Priority Ctrl Locked client server\n");
Eric Laurentca7cc822012-11-19 14:55:58 -08001071 for (size_t i = 0; i < mHandles.size(); ++i) {
1072 EffectHandle *handle = mHandles[i];
1073 if (handle != NULL && !handle->destroyed_l()) {
Glenn Kasten01d3acb2014-02-06 08:24:07 -08001074 handle->dumpToBuffer(buffer, SIZE);
Eric Laurentca7cc822012-11-19 14:55:58 -08001075 result.append(buffer);
1076 }
1077 }
1078
Eric Laurentca7cc822012-11-19 14:55:58 -08001079 write(fd, result.string(), result.length());
1080
1081 if (locked) {
1082 mLock.unlock();
1083 }
1084}
1085
1086// ----------------------------------------------------------------------------
1087// EffectHandle implementation
1088// ----------------------------------------------------------------------------
1089
1090#undef LOG_TAG
1091#define LOG_TAG "AudioFlinger::EffectHandle"
1092
1093AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
1094 const sp<AudioFlinger::Client>& client,
1095 const sp<IEffectClient>& effectClient,
1096 int32_t priority)
1097 : BnEffect(),
1098 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
1099 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
1100{
1101 ALOGV("constructor %p", this);
1102
1103 if (client == 0) {
1104 return;
1105 }
1106 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
1107 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
Glenn Kastene75da402013-11-20 13:54:52 -08001108 if (mCblkMemory == 0 ||
1109 (mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer())) == NULL) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001110 ALOGE("not enough memory for Effect size=%zu", EFFECT_PARAM_BUFFER_SIZE +
Eric Laurentca7cc822012-11-19 14:55:58 -08001111 sizeof(effect_param_cblk_t));
Glenn Kastene75da402013-11-20 13:54:52 -08001112 mCblkMemory.clear();
Eric Laurentca7cc822012-11-19 14:55:58 -08001113 return;
1114 }
Glenn Kastene75da402013-11-20 13:54:52 -08001115 new(mCblk) effect_param_cblk_t();
1116 mBuffer = (uint8_t *)mCblk + bufOffset;
Eric Laurentca7cc822012-11-19 14:55:58 -08001117}
1118
1119AudioFlinger::EffectHandle::~EffectHandle()
1120{
1121 ALOGV("Destructor %p", this);
1122
1123 if (mEffect == 0) {
1124 mDestroyed = true;
1125 return;
1126 }
1127 mEffect->lock();
1128 mDestroyed = true;
1129 mEffect->unlock();
1130 disconnect(false);
1131}
1132
Glenn Kastene75da402013-11-20 13:54:52 -08001133status_t AudioFlinger::EffectHandle::initCheck()
1134{
1135 return mClient == 0 || mCblkMemory != 0 ? OK : NO_MEMORY;
1136}
1137
Eric Laurentca7cc822012-11-19 14:55:58 -08001138status_t AudioFlinger::EffectHandle::enable()
1139{
1140 ALOGV("enable %p", this);
1141 if (!mHasControl) {
1142 return INVALID_OPERATION;
1143 }
1144 if (mEffect == 0) {
1145 return DEAD_OBJECT;
1146 }
1147
1148 if (mEnabled) {
1149 return NO_ERROR;
1150 }
1151
1152 mEnabled = true;
1153
1154 sp<ThreadBase> thread = mEffect->thread().promote();
1155 if (thread != 0) {
1156 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
1157 }
1158
1159 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
1160 if (mEffect->suspended()) {
1161 return NO_ERROR;
1162 }
1163
1164 status_t status = mEffect->setEnabled(true);
1165 if (status != NO_ERROR) {
1166 if (thread != 0) {
1167 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
1168 }
1169 mEnabled = false;
Eric Laurent813e2a72013-08-31 12:59:48 -07001170 } else {
Eric Laurent59fe0102013-09-27 18:48:26 -07001171 if (thread != 0) {
1172 if (thread->type() == ThreadBase::OFFLOAD) {
Eric Laurent813e2a72013-08-31 12:59:48 -07001173 PlaybackThread *t = (PlaybackThread *)thread.get();
Eric Laurent59fe0102013-09-27 18:48:26 -07001174 Mutex::Autolock _l(t->mLock);
1175 t->broadcast_l();
Eric Laurent813e2a72013-08-31 12:59:48 -07001176 }
Eric Laurent59fe0102013-09-27 18:48:26 -07001177 if (!mEffect->isOffloadable()) {
1178 if (thread->type() == ThreadBase::OFFLOAD) {
1179 PlaybackThread *t = (PlaybackThread *)thread.get();
1180 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1181 }
1182 if (mEffect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1183 thread->mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1184 }
Eric Laurent813e2a72013-08-31 12:59:48 -07001185 }
1186 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001187 }
1188 return status;
1189}
1190
1191status_t AudioFlinger::EffectHandle::disable()
1192{
1193 ALOGV("disable %p", this);
1194 if (!mHasControl) {
1195 return INVALID_OPERATION;
1196 }
1197 if (mEffect == 0) {
1198 return DEAD_OBJECT;
1199 }
1200
1201 if (!mEnabled) {
1202 return NO_ERROR;
1203 }
1204 mEnabled = false;
1205
1206 if (mEffect->suspended()) {
1207 return NO_ERROR;
1208 }
1209
1210 status_t status = mEffect->setEnabled(false);
1211
1212 sp<ThreadBase> thread = mEffect->thread().promote();
1213 if (thread != 0) {
1214 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
Eric Laurent59fe0102013-09-27 18:48:26 -07001215 if (thread->type() == ThreadBase::OFFLOAD) {
1216 PlaybackThread *t = (PlaybackThread *)thread.get();
1217 Mutex::Autolock _l(t->mLock);
1218 t->broadcast_l();
1219 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001220 }
1221
1222 return status;
1223}
1224
1225void AudioFlinger::EffectHandle::disconnect()
1226{
1227 disconnect(true);
1228}
1229
1230void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
1231{
1232 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
1233 if (mEffect == 0) {
1234 return;
1235 }
1236 // restore suspended effects if the disconnected handle was enabled and the last one.
1237 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
1238 sp<ThreadBase> thread = mEffect->thread().promote();
1239 if (thread != 0) {
1240 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
1241 }
1242 }
1243
1244 // release sp on module => module destructor can be called now
1245 mEffect.clear();
1246 if (mClient != 0) {
1247 if (mCblk != NULL) {
1248 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
1249 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
1250 }
1251 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Eric Laurent021cf962014-05-13 10:18:14 -07001252 // Client destructor must run with AudioFlinger client mutex locked
1253 Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
Eric Laurentca7cc822012-11-19 14:55:58 -08001254 mClient.clear();
1255 }
1256}
1257
1258status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
1259 uint32_t cmdSize,
1260 void *pCmdData,
1261 uint32_t *replySize,
1262 void *pReplyData)
1263{
1264 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
1265 cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
1266
1267 // only get parameter command is permitted for applications not controlling the effect
1268 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
1269 return INVALID_OPERATION;
1270 }
1271 if (mEffect == 0) {
1272 return DEAD_OBJECT;
1273 }
1274 if (mClient == 0) {
1275 return INVALID_OPERATION;
1276 }
1277
1278 // handle commands that are not forwarded transparently to effect engine
1279 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
1280 // No need to trylock() here as this function is executed in the binder thread serving a
1281 // particular client process: no risk to block the whole media server process or mixer
1282 // threads if we are stuck here
1283 Mutex::Autolock _l(mCblk->lock);
1284 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
1285 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
1286 mCblk->serverIndex = 0;
1287 mCblk->clientIndex = 0;
1288 return BAD_VALUE;
1289 }
1290 status_t status = NO_ERROR;
1291 while (mCblk->serverIndex < mCblk->clientIndex) {
1292 int reply;
1293 uint32_t rsize = sizeof(int);
1294 int *p = (int *)(mBuffer + mCblk->serverIndex);
1295 int size = *p++;
1296 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
1297 ALOGW("command(): invalid parameter block size");
1298 break;
1299 }
1300 effect_param_t *param = (effect_param_t *)p;
1301 if (param->psize == 0 || param->vsize == 0) {
1302 ALOGW("command(): null parameter or value size");
1303 mCblk->serverIndex += size;
1304 continue;
1305 }
1306 uint32_t psize = sizeof(effect_param_t) +
1307 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
1308 param->vsize;
1309 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
1310 psize,
1311 p,
1312 &rsize,
1313 &reply);
1314 // stop at first error encountered
1315 if (ret != NO_ERROR) {
1316 status = ret;
1317 *(int *)pReplyData = reply;
1318 break;
1319 } else if (reply != NO_ERROR) {
1320 *(int *)pReplyData = reply;
1321 break;
1322 }
1323 mCblk->serverIndex += size;
1324 }
1325 mCblk->serverIndex = 0;
1326 mCblk->clientIndex = 0;
1327 return status;
1328 } else if (cmdCode == EFFECT_CMD_ENABLE) {
1329 *(int *)pReplyData = NO_ERROR;
1330 return enable();
1331 } else if (cmdCode == EFFECT_CMD_DISABLE) {
1332 *(int *)pReplyData = NO_ERROR;
1333 return disable();
1334 }
1335
1336 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
1337}
1338
1339void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
1340{
1341 ALOGV("setControl %p control %d", this, hasControl);
1342
1343 mHasControl = hasControl;
1344 mEnabled = enabled;
1345
1346 if (signal && mEffectClient != 0) {
1347 mEffectClient->controlStatusChanged(hasControl);
1348 }
1349}
1350
1351void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
1352 uint32_t cmdSize,
1353 void *pCmdData,
1354 uint32_t replySize,
1355 void *pReplyData)
1356{
1357 if (mEffectClient != 0) {
1358 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
1359 }
1360}
1361
1362
1363
1364void AudioFlinger::EffectHandle::setEnabled(bool enabled)
1365{
1366 if (mEffectClient != 0) {
1367 mEffectClient->enableStatusChanged(enabled);
1368 }
1369}
1370
1371status_t AudioFlinger::EffectHandle::onTransact(
1372 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1373{
1374 return BnEffect::onTransact(code, data, reply, flags);
1375}
1376
1377
Glenn Kasten01d3acb2014-02-06 08:24:07 -08001378void AudioFlinger::EffectHandle::dumpToBuffer(char* buffer, size_t size)
Eric Laurentca7cc822012-11-19 14:55:58 -08001379{
1380 bool locked = mCblk != NULL && AudioFlinger::dumpTryLock(mCblk->lock);
1381
Marco Nelissenb2208842014-02-07 14:00:50 -08001382 snprintf(buffer, size, "\t\t\t%5d %5d %3s %3s %5u %5u\n",
Eric Laurentca7cc822012-11-19 14:55:58 -08001383 (mClient == 0) ? getpid_cached : mClient->pid(),
1384 mPriority,
Marco Nelissenb2208842014-02-07 14:00:50 -08001385 mHasControl ? "yes" : "no",
1386 locked ? "yes" : "no",
Eric Laurentca7cc822012-11-19 14:55:58 -08001387 mCblk ? mCblk->clientIndex : 0,
1388 mCblk ? mCblk->serverIndex : 0
1389 );
1390
1391 if (locked) {
1392 mCblk->lock.unlock();
1393 }
1394}
1395
1396#undef LOG_TAG
1397#define LOG_TAG "AudioFlinger::EffectChain"
1398
1399AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Glenn Kastend848eb42016-03-08 13:42:11 -08001400 audio_session_t sessionId)
Eric Laurentca7cc822012-11-19 14:55:58 -08001401 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
1402 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
Eric Laurentfa1e1232016-08-02 19:01:49 -07001403 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Eric Laurentca7cc822012-11-19 14:55:58 -08001404{
1405 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1406 if (thread == NULL) {
1407 return;
1408 }
1409 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
1410 thread->frameCount();
1411}
1412
1413AudioFlinger::EffectChain::~EffectChain()
1414{
1415 if (mOwnInBuffer) {
1416 delete mInBuffer;
1417 }
1418
1419}
1420
1421// getEffectFromDesc_l() must be called with ThreadBase::mLock held
1422sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
1423 effect_descriptor_t *descriptor)
1424{
1425 size_t size = mEffects.size();
1426
1427 for (size_t i = 0; i < size; i++) {
1428 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
1429 return mEffects[i];
1430 }
1431 }
1432 return 0;
1433}
1434
1435// getEffectFromId_l() must be called with ThreadBase::mLock held
1436sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
1437{
1438 size_t size = mEffects.size();
1439
1440 for (size_t i = 0; i < size; i++) {
1441 // by convention, return first effect if id provided is 0 (0 is never a valid id)
1442 if (id == 0 || mEffects[i]->id() == id) {
1443 return mEffects[i];
1444 }
1445 }
1446 return 0;
1447}
1448
1449// getEffectFromType_l() must be called with ThreadBase::mLock held
1450sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
1451 const effect_uuid_t *type)
1452{
1453 size_t size = mEffects.size();
1454
1455 for (size_t i = 0; i < size; i++) {
1456 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
1457 return mEffects[i];
1458 }
1459 }
1460 return 0;
1461}
1462
1463void AudioFlinger::EffectChain::clearInputBuffer()
1464{
1465 Mutex::Autolock _l(mLock);
1466 sp<ThreadBase> thread = mThread.promote();
1467 if (thread == 0) {
1468 ALOGW("clearInputBuffer(): cannot promote mixer thread");
1469 return;
1470 }
1471 clearInputBuffer_l(thread);
1472}
1473
1474// Must be called with EffectChain::mLock locked
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001475void AudioFlinger::EffectChain::clearInputBuffer_l(const sp<ThreadBase>& thread)
Eric Laurentca7cc822012-11-19 14:55:58 -08001476{
Ricardo Garcia322bab22014-08-06 11:43:46 -07001477 // TODO: This will change in the future, depending on multichannel
1478 // and sample format changes for effects.
1479 // Currently effects processing is only available for stereo, AUDIO_FORMAT_PCM_16_BIT
1480 // (4 bytes frame size)
Ricardo Garcia726b6a72014-08-11 12:04:54 -07001481 const size_t frameSize =
1482 audio_bytes_per_sample(AUDIO_FORMAT_PCM_16_BIT) * min(FCC_2, thread->channelCount());
Ricardo Garcia322bab22014-08-06 11:43:46 -07001483 memset(mInBuffer, 0, thread->frameCount() * frameSize);
Eric Laurentca7cc822012-11-19 14:55:58 -08001484}
1485
1486// Must be called with EffectChain::mLock locked
1487void AudioFlinger::EffectChain::process_l()
1488{
1489 sp<ThreadBase> thread = mThread.promote();
1490 if (thread == 0) {
1491 ALOGW("process_l(): cannot promote mixer thread");
1492 return;
1493 }
1494 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
1495 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Jean-Michel Trivifed62922013-09-25 18:50:33 -07001496 // never process effects when:
1497 // - on an OFFLOAD thread
1498 // - no more tracks are on the session and the effect tail has been rendered
1499 bool doProcess = (thread->type() != ThreadBase::OFFLOAD);
Eric Laurentca7cc822012-11-19 14:55:58 -08001500 if (!isGlobalSession) {
1501 bool tracksOnSession = (trackCnt() != 0);
1502
1503 if (!tracksOnSession && mTailBufferCount == 0) {
1504 doProcess = false;
1505 }
1506
1507 if (activeTrackCnt() == 0) {
1508 // if no track is active and the effect tail has not been rendered,
1509 // the input buffer must be cleared here as the mixer process will not do it
1510 if (tracksOnSession || mTailBufferCount > 0) {
1511 clearInputBuffer_l(thread);
1512 if (mTailBufferCount > 0) {
1513 mTailBufferCount--;
1514 }
1515 }
1516 }
1517 }
1518
1519 size_t size = mEffects.size();
1520 if (doProcess) {
1521 for (size_t i = 0; i < size; i++) {
1522 mEffects[i]->process();
1523 }
1524 }
Eric Laurentfa1e1232016-08-02 19:01:49 -07001525 bool doResetVolume = false;
Eric Laurentca7cc822012-11-19 14:55:58 -08001526 for (size_t i = 0; i < size; i++) {
Eric Laurentfa1e1232016-08-02 19:01:49 -07001527 doResetVolume = mEffects[i]->updateState() || doResetVolume;
1528 }
1529 if (doResetVolume) {
1530 resetVolume_l();
Eric Laurentca7cc822012-11-19 14:55:58 -08001531 }
1532}
1533
1534// addEffect_l() must be called with PlaybackThread::mLock held
1535status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
1536{
1537 effect_descriptor_t desc = effect->desc();
1538 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
1539
1540 Mutex::Autolock _l(mLock);
1541 effect->setChain(this);
1542 sp<ThreadBase> thread = mThread.promote();
1543 if (thread == 0) {
1544 return NO_INIT;
1545 }
1546 effect->setThread(thread);
1547
1548 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1549 // Auxiliary effects are inserted at the beginning of mEffects vector as
1550 // they are processed first and accumulated in chain input buffer
1551 mEffects.insertAt(effect, 0);
1552
1553 // the input buffer for auxiliary effect contains mono samples in
1554 // 32 bit format. This is to avoid saturation in AudoMixer
1555 // accumulation stage. Saturation is done in EffectModule::process() before
1556 // calling the process in effect engine
1557 size_t numSamples = thread->frameCount();
1558 int32_t *buffer = new int32_t[numSamples];
1559 memset(buffer, 0, numSamples * sizeof(int32_t));
1560 effect->setInBuffer((int16_t *)buffer);
1561 // auxiliary effects output samples to chain input buffer for further processing
1562 // by insert effects
1563 effect->setOutBuffer(mInBuffer);
1564 } else {
1565 // Insert effects are inserted at the end of mEffects vector as they are processed
1566 // after track and auxiliary effects.
1567 // Insert effect order as a function of indicated preference:
1568 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
1569 // another effect is present
1570 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
1571 // last effect claiming first position
1572 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
1573 // first effect claiming last position
1574 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
1575 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
1576 // already present
1577
1578 size_t size = mEffects.size();
1579 size_t idx_insert = size;
1580 ssize_t idx_insert_first = -1;
1581 ssize_t idx_insert_last = -1;
1582
1583 for (size_t i = 0; i < size; i++) {
1584 effect_descriptor_t d = mEffects[i]->desc();
1585 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
1586 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
1587 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
1588 // check invalid effect chaining combinations
1589 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
1590 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
1591 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s",
1592 desc.name, d.name);
1593 return INVALID_OPERATION;
1594 }
1595 // remember position of first insert effect and by default
1596 // select this as insert position for new effect
1597 if (idx_insert == size) {
1598 idx_insert = i;
1599 }
1600 // remember position of last insert effect claiming
1601 // first position
1602 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
1603 idx_insert_first = i;
1604 }
1605 // remember position of first insert effect claiming
1606 // last position
1607 if (iPref == EFFECT_FLAG_INSERT_LAST &&
1608 idx_insert_last == -1) {
1609 idx_insert_last = i;
1610 }
1611 }
1612 }
1613
1614 // modify idx_insert from first position if needed
1615 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
1616 if (idx_insert_last != -1) {
1617 idx_insert = idx_insert_last;
1618 } else {
1619 idx_insert = size;
1620 }
1621 } else {
1622 if (idx_insert_first != -1) {
1623 idx_insert = idx_insert_first + 1;
1624 }
1625 }
1626
1627 // always read samples from chain input buffer
1628 effect->setInBuffer(mInBuffer);
1629
1630 // if last effect in the chain, output samples to chain
1631 // output buffer, otherwise to chain input buffer
1632 if (idx_insert == size) {
1633 if (idx_insert != 0) {
1634 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
1635 mEffects[idx_insert-1]->configure();
1636 }
1637 effect->setOutBuffer(mOutBuffer);
1638 } else {
1639 effect->setOutBuffer(mInBuffer);
1640 }
1641 mEffects.insertAt(effect, idx_insert);
1642
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001643 ALOGV("addEffect_l() effect %p, added in chain %p at rank %zu", effect.get(), this,
Eric Laurentca7cc822012-11-19 14:55:58 -08001644 idx_insert);
1645 }
1646 effect->configure();
1647 return NO_ERROR;
1648}
1649
1650// removeEffect_l() must be called with PlaybackThread::mLock held
1651size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
1652{
1653 Mutex::Autolock _l(mLock);
1654 size_t size = mEffects.size();
1655 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
1656
1657 for (size_t i = 0; i < size; i++) {
1658 if (effect == mEffects[i]) {
1659 // calling stop here will remove pre-processing effect from the audio HAL.
1660 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
1661 // the middle of a read from audio HAL
1662 if (mEffects[i]->state() == EffectModule::ACTIVE ||
1663 mEffects[i]->state() == EffectModule::STOPPING) {
1664 mEffects[i]->stop();
1665 }
1666 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
1667 delete[] effect->inBuffer();
1668 } else {
1669 if (i == size - 1 && i != 0) {
1670 mEffects[i - 1]->setOutBuffer(mOutBuffer);
1671 mEffects[i - 1]->configure();
1672 }
1673 }
1674 mEffects.removeAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001675 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %zu", effect.get(),
Eric Laurentca7cc822012-11-19 14:55:58 -08001676 this, i);
1677 break;
1678 }
1679 }
1680
1681 return mEffects.size();
1682}
1683
1684// setDevice_l() must be called with PlaybackThread::mLock held
1685void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
1686{
1687 size_t size = mEffects.size();
1688 for (size_t i = 0; i < size; i++) {
1689 mEffects[i]->setDevice(device);
1690 }
1691}
1692
1693// setMode_l() must be called with PlaybackThread::mLock held
1694void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
1695{
1696 size_t size = mEffects.size();
1697 for (size_t i = 0; i < size; i++) {
1698 mEffects[i]->setMode(mode);
1699 }
1700}
1701
1702// setAudioSource_l() must be called with PlaybackThread::mLock held
1703void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
1704{
1705 size_t size = mEffects.size();
1706 for (size_t i = 0; i < size; i++) {
1707 mEffects[i]->setAudioSource(source);
1708 }
1709}
1710
Eric Laurentfa1e1232016-08-02 19:01:49 -07001711// setVolume_l() must be called with PlaybackThread::mLock or EffectChain::mLock held
1712bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right, bool force)
Eric Laurentca7cc822012-11-19 14:55:58 -08001713{
1714 uint32_t newLeft = *left;
1715 uint32_t newRight = *right;
1716 bool hasControl = false;
1717 int ctrlIdx = -1;
1718 size_t size = mEffects.size();
1719
1720 // first update volume controller
1721 for (size_t i = size; i > 0; i--) {
1722 if (mEffects[i - 1]->isProcessEnabled() &&
1723 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
1724 ctrlIdx = i - 1;
1725 hasControl = true;
1726 break;
1727 }
1728 }
1729
Eric Laurentfa1e1232016-08-02 19:01:49 -07001730 if (!force && ctrlIdx == mVolumeCtrlIdx &&
Eric Laurentcb4b6e92014-10-01 14:26:10 -07001731 *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentca7cc822012-11-19 14:55:58 -08001732 if (hasControl) {
1733 *left = mNewLeftVolume;
1734 *right = mNewRightVolume;
1735 }
1736 return hasControl;
1737 }
1738
1739 mVolumeCtrlIdx = ctrlIdx;
1740 mLeftVolume = newLeft;
1741 mRightVolume = newRight;
1742
1743 // second get volume update from volume controller
1744 if (ctrlIdx >= 0) {
1745 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
1746 mNewLeftVolume = newLeft;
1747 mNewRightVolume = newRight;
1748 }
1749 // then indicate volume to all other effects in chain.
1750 // Pass altered volume to effects before volume controller
1751 // and requested volume to effects after controller
1752 uint32_t lVol = newLeft;
1753 uint32_t rVol = newRight;
1754
1755 for (size_t i = 0; i < size; i++) {
1756 if ((int)i == ctrlIdx) {
1757 continue;
1758 }
1759 // this also works for ctrlIdx == -1 when there is no volume controller
1760 if ((int)i > ctrlIdx) {
1761 lVol = *left;
1762 rVol = *right;
1763 }
1764 mEffects[i]->setVolume(&lVol, &rVol, false);
1765 }
1766 *left = newLeft;
1767 *right = newRight;
1768
1769 return hasControl;
1770}
1771
Eric Laurentfa1e1232016-08-02 19:01:49 -07001772// resetVolume_l() must be called with PlaybackThread::mLock or EffectChain::mLock held
1773void AudioFlinger::EffectChain::resetVolume_l()
1774{
Eric Laurente7449bf2016-08-03 18:44:07 -07001775 if ((mLeftVolume != UINT_MAX) && (mRightVolume != UINT_MAX)) {
1776 uint32_t left = mLeftVolume;
1777 uint32_t right = mRightVolume;
1778 (void)setVolume_l(&left, &right, true);
1779 }
Eric Laurentfa1e1232016-08-02 19:01:49 -07001780}
1781
Eric Laurent1b928682014-10-02 19:41:47 -07001782void AudioFlinger::EffectChain::syncHalEffectsState()
1783{
1784 Mutex::Autolock _l(mLock);
1785 for (size_t i = 0; i < mEffects.size(); i++) {
1786 if (mEffects[i]->state() == EffectModule::ACTIVE ||
1787 mEffects[i]->state() == EffectModule::STOPPING) {
1788 mEffects[i]->addEffectToHal_l();
1789 }
1790 }
1791}
1792
Eric Laurentca7cc822012-11-19 14:55:58 -08001793void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
1794{
1795 const size_t SIZE = 256;
1796 char buffer[SIZE];
1797 String8 result;
1798
Marco Nelissenb2208842014-02-07 14:00:50 -08001799 size_t numEffects = mEffects.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001800 snprintf(buffer, SIZE, " %zu effects for session %d\n", numEffects, mSessionId);
Eric Laurentca7cc822012-11-19 14:55:58 -08001801 result.append(buffer);
1802
Marco Nelissenb2208842014-02-07 14:00:50 -08001803 if (numEffects) {
1804 bool locked = AudioFlinger::dumpTryLock(mLock);
1805 // failed to lock - AudioFlinger is probably deadlocked
1806 if (!locked) {
1807 result.append("\tCould not lock mutex:\n");
Eric Laurentca7cc822012-11-19 14:55:58 -08001808 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001809
Marco Nelissenb2208842014-02-07 14:00:50 -08001810 result.append("\tIn buffer Out buffer Active tracks:\n");
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001811 snprintf(buffer, SIZE, "\t%p %p %d\n",
1812 mInBuffer,
1813 mOutBuffer,
Marco Nelissenb2208842014-02-07 14:00:50 -08001814 mActiveTrackCnt);
1815 result.append(buffer);
1816 write(fd, result.string(), result.size());
1817
1818 for (size_t i = 0; i < numEffects; ++i) {
1819 sp<EffectModule> effect = mEffects[i];
1820 if (effect != 0) {
1821 effect->dump(fd, args);
1822 }
1823 }
1824
1825 if (locked) {
1826 mLock.unlock();
1827 }
Eric Laurentca7cc822012-11-19 14:55:58 -08001828 }
1829}
1830
1831// must be called with ThreadBase::mLock held
1832void AudioFlinger::EffectChain::setEffectSuspended_l(
1833 const effect_uuid_t *type, bool suspend)
1834{
1835 sp<SuspendedEffectDesc> desc;
1836 // use effect type UUID timelow as key as there is no real risk of identical
1837 // timeLow fields among effect type UUIDs.
1838 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
1839 if (suspend) {
1840 if (index >= 0) {
1841 desc = mSuspendedEffects.valueAt(index);
1842 } else {
1843 desc = new SuspendedEffectDesc();
1844 desc->mType = *type;
1845 mSuspendedEffects.add(type->timeLow, desc);
1846 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
1847 }
1848 if (desc->mRefCount++ == 0) {
1849 sp<EffectModule> effect = getEffectIfEnabled(type);
1850 if (effect != 0) {
1851 desc->mEffect = effect;
1852 effect->setSuspended(true);
1853 effect->setEnabled(false);
1854 }
1855 }
1856 } else {
1857 if (index < 0) {
1858 return;
1859 }
1860 desc = mSuspendedEffects.valueAt(index);
1861 if (desc->mRefCount <= 0) {
1862 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
1863 desc->mRefCount = 1;
1864 }
1865 if (--desc->mRefCount == 0) {
1866 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
1867 if (desc->mEffect != 0) {
1868 sp<EffectModule> effect = desc->mEffect.promote();
1869 if (effect != 0) {
1870 effect->setSuspended(false);
1871 effect->lock();
1872 EffectHandle *handle = effect->controlHandle_l();
1873 if (handle != NULL && !handle->destroyed_l()) {
1874 effect->setEnabled_l(handle->enabled());
1875 }
1876 effect->unlock();
1877 }
1878 desc->mEffect.clear();
1879 }
1880 mSuspendedEffects.removeItemsAt(index);
1881 }
1882 }
1883}
1884
1885// must be called with ThreadBase::mLock held
1886void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
1887{
1888 sp<SuspendedEffectDesc> desc;
1889
1890 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
1891 if (suspend) {
1892 if (index >= 0) {
1893 desc = mSuspendedEffects.valueAt(index);
1894 } else {
1895 desc = new SuspendedEffectDesc();
1896 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
1897 ALOGV("setEffectSuspendedAll_l() add entry for 0");
1898 }
1899 if (desc->mRefCount++ == 0) {
1900 Vector< sp<EffectModule> > effects;
1901 getSuspendEligibleEffects(effects);
1902 for (size_t i = 0; i < effects.size(); i++) {
1903 setEffectSuspended_l(&effects[i]->desc().type, true);
1904 }
1905 }
1906 } else {
1907 if (index < 0) {
1908 return;
1909 }
1910 desc = mSuspendedEffects.valueAt(index);
1911 if (desc->mRefCount <= 0) {
1912 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
1913 desc->mRefCount = 1;
1914 }
1915 if (--desc->mRefCount == 0) {
1916 Vector<const effect_uuid_t *> types;
1917 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
1918 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
1919 continue;
1920 }
1921 types.add(&mSuspendedEffects.valueAt(i)->mType);
1922 }
1923 for (size_t i = 0; i < types.size(); i++) {
1924 setEffectSuspended_l(types[i], false);
1925 }
1926 ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
1927 mSuspendedEffects.keyAt(index));
1928 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
1929 }
1930 }
1931}
1932
1933
1934// The volume effect is used for automated tests only
1935#ifndef OPENSL_ES_H_
1936static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
1937 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
1938const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
1939#endif //OPENSL_ES_H_
1940
1941bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
1942{
1943 // auxiliary effects and visualizer are never suspended on output mix
1944 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
1945 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
1946 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
1947 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
1948 return false;
1949 }
1950 return true;
1951}
1952
1953void AudioFlinger::EffectChain::getSuspendEligibleEffects(
1954 Vector< sp<AudioFlinger::EffectModule> > &effects)
1955{
1956 effects.clear();
1957 for (size_t i = 0; i < mEffects.size(); i++) {
1958 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
1959 effects.add(mEffects[i]);
1960 }
1961 }
1962}
1963
1964sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
1965 const effect_uuid_t *type)
1966{
1967 sp<EffectModule> effect = getEffectFromType_l(type);
1968 return effect != 0 && effect->isEnabled() ? effect : 0;
1969}
1970
1971void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1972 bool enabled)
1973{
1974 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
1975 if (enabled) {
1976 if (index < 0) {
1977 // if the effect is not suspend check if all effects are suspended
1978 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
1979 if (index < 0) {
1980 return;
1981 }
1982 if (!isEffectEligibleForSuspend(effect->desc())) {
1983 return;
1984 }
1985 setEffectSuspended_l(&effect->desc().type, enabled);
1986 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
1987 if (index < 0) {
1988 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
1989 return;
1990 }
1991 }
1992 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
1993 effect->desc().type.timeLow);
1994 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
1995 // if effect is requested to suspended but was not yet enabled, supend it now.
1996 if (desc->mEffect == 0) {
1997 desc->mEffect = effect;
1998 effect->setEnabled(false);
1999 effect->setSuspended(true);
2000 }
2001 } else {
2002 if (index < 0) {
2003 return;
2004 }
2005 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
2006 effect->desc().type.timeLow);
2007 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
2008 desc->mEffect.clear();
2009 effect->setSuspended(false);
2010 }
2011}
2012
Eric Laurent5baf2af2013-09-12 17:37:00 -07002013bool AudioFlinger::EffectChain::isNonOffloadableEnabled()
Eric Laurent813e2a72013-08-31 12:59:48 -07002014{
2015 Mutex::Autolock _l(mLock);
2016 size_t size = mEffects.size();
2017 for (size_t i = 0; i < size; i++) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002018 if (mEffects[i]->isEnabled() && !mEffects[i]->isOffloadable()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002019 return true;
2020 }
2021 }
2022 return false;
2023}
2024
Eric Laurentaaa44472014-09-12 17:41:50 -07002025void AudioFlinger::EffectChain::setThread(const sp<ThreadBase>& thread)
2026{
2027 Mutex::Autolock _l(mLock);
2028 mThread = thread;
2029 for (size_t i = 0; i < mEffects.size(); i++) {
2030 mEffects[i]->setThread(thread);
2031 }
2032}
2033
Eric Laurent4c415062016-06-17 16:14:16 -07002034bool AudioFlinger::EffectChain::hasSoftwareEffect() const
2035{
2036 Mutex::Autolock _l(mLock);
2037 for (size_t i = 0; i < mEffects.size(); i++) {
2038 if (mEffects[i]->isImplementationSoftware()) {
2039 return true;
2040 }
2041 }
2042 return false;
2043}
2044
2045// isCompatibleWithThread_l() must be called with thread->mLock held
2046bool AudioFlinger::EffectChain::isCompatibleWithThread_l(const sp<ThreadBase>& thread) const
2047{
2048 Mutex::Autolock _l(mLock);
2049 for (size_t i = 0; i < mEffects.size(); i++) {
2050 if (thread->checkEffectCompatibility_l(&(mEffects[i]->desc()), mSessionId) != NO_ERROR) {
2051 return false;
2052 }
2053 }
2054 return true;
2055}
2056
Glenn Kasten63238ef2015-03-02 15:50:29 -08002057} // namespace android