• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010-2010 NXP Software
3  * Copyright (C) 2009 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 #ifndef LVM_FLOAT
18 typedef float LVM_FLOAT;
19 #endif
20 #define LOG_TAG "Bundle"
21 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array)[0])
22 //#define LOG_NDEBUG 0
23 
24 #include <assert.h>
25 #include <inttypes.h>
26 #include <new>
27 #include <stdlib.h>
28 #include <string.h>
29 
30 #include <audio_utils/primitives.h>
31 #include <log/log.h>
32 
33 #include "EffectBundle.h"
34 #include "math.h"
35 
36 // effect_handle_t interface implementation for bass boost
37 extern "C" const struct effect_interface_s gLvmEffectInterface;
38 
39 // Turn on VERY_VERY_VERBOSE_LOGGING to log parameter get and set for effects.
40 
41 //#define VERY_VERY_VERBOSE_LOGGING
42 #ifdef VERY_VERY_VERBOSE_LOGGING
43 #define ALOGVV ALOGV
44 #else
45 #define ALOGVV(a...) \
46     do {             \
47     } while (false)
48 #endif
49 
50 #define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc)             \
51     {                                                                   \
52         if ((LvmStatus) == LVM_NULLADDRESS) {                           \
53             ALOGV("\tLVM_ERROR : Parameter error - "                    \
54                   "null pointer returned by %s in %s\n\n\n\n",          \
55                   callingFunc, calledFunc);                             \
56         }                                                               \
57         if ((LvmStatus) == LVM_ALIGNMENTERROR) {                        \
58             ALOGV("\tLVM_ERROR : Parameter error - "                    \
59                   "bad alignment returned by %s in %s\n\n\n\n",         \
60                   callingFunc, calledFunc);                             \
61         }                                                               \
62         if ((LvmStatus) == LVM_INVALIDNUMSAMPLES) {                     \
63             ALOGV("\tLVM_ERROR : Parameter error - "                    \
64                   "bad number of samples returned by %s in %s\n\n\n\n", \
65                   callingFunc, calledFunc);                             \
66         }                                                               \
67         if ((LvmStatus) == LVM_OUTOFRANGE) {                            \
68             ALOGV("\tLVM_ERROR : Parameter error - "                    \
69                   "out of range returned by %s in %s\n",                \
70                   callingFunc, calledFunc);                             \
71         }                                                               \
72     }
73 
74 // Namespaces
75 namespace android {
76 namespace {
77 
78 // Flag to allow a one time init of global memory, only happens on first call ever
79 int LvmInitFlag = LVM_FALSE;
80 SessionContext GlobalSessionMemory[LVM_MAX_SESSIONS];
81 int SessionIndex[LVM_MAX_SESSIONS];
82 
83 /* local functions */
84 #define CHECK_ARG(cond)                                      \
85     {                                                        \
86         if (!(cond)) {                                       \
87             ALOGV("\tLVM_ERROR : Invalid argument: " #cond); \
88             return -EINVAL;                                  \
89         }                                                    \
90     }
91 
92 // NXP SW BassBoost UUID
93 const effect_descriptor_t gBassBoostDescriptor = {
94         {0x0634f220, 0xddd4, 0x11db, 0xa0fc, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
95         {0x8631f300, 0x72e2, 0x11df, 0xb57e, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid
96         EFFECT_CONTROL_API_VERSION,
97         (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_FIRST | EFFECT_FLAG_DEVICE_IND |
98          EFFECT_FLAG_VOLUME_CTRL),
99         BASS_BOOST_CUP_LOAD_ARM9E,
100         BUNDLE_MEM_USAGE,
101         "Dynamic Bass Boost",
102         "NXP Software Ltd.",
103 };
104 
105 // NXP SW Virtualizer UUID
106 const effect_descriptor_t gVirtualizerDescriptor = {
107         {0x37cc2c00, 0xdddd, 0x11db, 0x8577, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
108         {0x1d4033c0, 0x8557, 0x11df, 0x9f2d, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
109         EFFECT_CONTROL_API_VERSION,
110         (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_LAST | EFFECT_FLAG_DEVICE_IND |
111          EFFECT_FLAG_VOLUME_CTRL),
112         VIRTUALIZER_CUP_LOAD_ARM9E,
113         BUNDLE_MEM_USAGE,
114         "Virtualizer",
115         "NXP Software Ltd.",
116 };
117 
118 // NXP SW Equalizer UUID
119 const effect_descriptor_t gEqualizerDescriptor = {
120         {0x0bed4300, 0xddd6, 0x11db, 0x8f34, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // type
121         {0xce772f20, 0x847d, 0x11df, 0xbb17, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid Eq NXP
122         EFFECT_CONTROL_API_VERSION,
123         (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_FIRST | EFFECT_FLAG_VOLUME_CTRL),
124         EQUALIZER_CUP_LOAD_ARM9E,
125         BUNDLE_MEM_USAGE,
126         "Equalizer",
127         "NXP Software Ltd.",
128 };
129 
130 // NXP SW Volume UUID
131 const effect_descriptor_t gVolumeDescriptor = {
132         {0x09e8ede0, 0xddde, 0x11db, 0xb4f6, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
133         {0x119341a0, 0x8469, 0x11df, 0x81f9, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid VOL NXP
134         EFFECT_CONTROL_API_VERSION,
135         (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_LAST | EFFECT_FLAG_VOLUME_CTRL),
136         VOLUME_CUP_LOAD_ARM9E,
137         BUNDLE_MEM_USAGE,
138         "Volume",
139         "NXP Software Ltd.",
140 };
141 
142 //--- local function prototypes
143 void LvmGlobalBundle_init(void);
144 int LvmBundle_init(EffectContext* pContext);
145 int LvmEffect_enable(EffectContext* pContext);
146 int LvmEffect_disable(EffectContext* pContext);
147 int Effect_setConfig(EffectContext* pContext, effect_config_t* pConfig);
148 void Effect_getConfig(EffectContext* pContext, effect_config_t* pConfig);
149 int BassBoost_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
150                            uint32_t valueSize, void* pValue);
151 int BassBoost_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
152                            uint32_t* pValueSize, void* pValue);
153 int Virtualizer_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
154                              uint32_t valueSize, void* pValue);
155 int Virtualizer_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
156                              uint32_t* pValueSize, void* pValue);
157 int Equalizer_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
158                            uint32_t valueSize, void* pValue);
159 int Equalizer_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
160                            uint32_t* pValueSize, void* pValue);
161 int Volume_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
162                         uint32_t valueSize, void* pValue);
163 int Volume_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
164                         uint32_t* pValueSize, void* pValue);
165 int Effect_setEnabled(EffectContext* pContext, bool enabled);
166 
167 /* Effect Library Interface Implementation */
168 
EffectCreate(const effect_uuid_t * uuid,int32_t sessionId,int32_t,effect_handle_t * pHandle)169 extern "C" int EffectCreate(const effect_uuid_t* uuid, int32_t sessionId,
170                             int32_t /* ioId __unused */, effect_handle_t* pHandle) {
171     int ret = 0;
172     int sessionNo = -1;
173     int i;
174     EffectContext* pContext = NULL;
175     bool newBundle = false;
176     SessionContext* pSessionContext;
177 
178     ALOGV("\n\tEffectCreate start session %d", sessionId);
179 
180     if (pHandle == NULL || uuid == NULL) {
181         ALOGV("\tLVM_ERROR : EffectCreate() called with NULL pointer");
182         ret = -EINVAL;
183         goto exit;
184     }
185 
186     if (LvmInitFlag == LVM_FALSE) {
187         LvmInitFlag = LVM_TRUE;
188         ALOGV("\tEffectCreate - Initializing all global memory");
189         LvmGlobalBundle_init();
190     }
191 
192     // Find sessionNo: if one already exists for the sessionId use it,
193     // otherwise choose the first available empty slot.
194     for (i = 0; i < LVM_MAX_SESSIONS; i++) {
195         if (SessionIndex[i] == sessionId) {
196             sessionNo = i;
197             break;
198         }
199         if (sessionNo < 0 && SessionIndex[i] == LVM_UNUSED_SESSION) {
200             sessionNo = i;
201             // do not break; allow loop to continue to search for a sessionId match.
202         }
203     }
204     if (sessionNo < 0) {
205         ALOGV("\tLVM_ERROR : Cannot find memory to allocate for current session");
206         ret = -EINVAL;
207         goto exit;
208     }
209 
210     SessionIndex[sessionNo] = sessionId;
211     ALOGV("\tEffectCreate: Allocating sessionNo %d for sessionId %d\n", sessionNo, sessionId);
212 
213     pContext = new EffectContext;
214 
215     // If this is the first create in this session
216     if (GlobalSessionMemory[sessionNo].bBundledEffectsEnabled == LVM_FALSE) {
217         ALOGV("\tEffectCreate - This is the first effect in current sessionId %d sessionNo %d",
218               sessionId, sessionNo);
219 
220         GlobalSessionMemory[sessionNo].bBundledEffectsEnabled = LVM_TRUE;
221         GlobalSessionMemory[sessionNo].pBundledContext = new BundledEffectContext;
222         newBundle = true;
223 
224         pContext->pBundledContext = GlobalSessionMemory[sessionNo].pBundledContext;
225         pContext->pBundledContext->SessionNo = sessionNo;
226         pContext->pBundledContext->SessionId = sessionId;
227         pContext->pBundledContext->hInstance = NULL;
228         pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
229         pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
230         pContext->pBundledContext->bBassEnabled = LVM_FALSE;
231         pContext->pBundledContext->bBassTempDisabled = LVM_FALSE;
232         pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
233         pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE;
234         pContext->pBundledContext->nOutputDevice = AUDIO_DEVICE_NONE;
235         pContext->pBundledContext->nVirtualizerForcedDevice = AUDIO_DEVICE_NONE;
236         pContext->pBundledContext->NumberEffectsEnabled = 0;
237         pContext->pBundledContext->NumberEffectsCalled = 0;
238         pContext->pBundledContext->firstVolume = LVM_TRUE;
239         pContext->pBundledContext->volume = 0;
240 
241         /* Saved strength is used to return the exact strength that was used in the set to the get
242          * because we map the original strength range of 0:1000 to 1:15, and this will avoid
243          * quantisation like effect when returning
244          */
245         pContext->pBundledContext->BassStrengthSaved = 0;
246         pContext->pBundledContext->VirtStrengthSaved = 0;
247         pContext->pBundledContext->CurPreset = PRESET_CUSTOM;
248         pContext->pBundledContext->levelSaved = 0;
249         pContext->pBundledContext->bMuteEnabled = LVM_FALSE;
250         pContext->pBundledContext->bStereoPositionEnabled = LVM_FALSE;
251         pContext->pBundledContext->positionSaved = 0;
252         pContext->pBundledContext->workBuffer = NULL;
253         pContext->pBundledContext->frameCount = -1;
254         pContext->pBundledContext->SamplesToExitCountVirt = 0;
255         pContext->pBundledContext->SamplesToExitCountBb = 0;
256         pContext->pBundledContext->SamplesToExitCountEq = 0;
257         for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
258             pContext->pBundledContext->bandGaindB[i] = EQNB_5BandSoftPresets[i];
259         }
260         pContext->pBundledContext->effectProcessCalled = 0;
261         pContext->pBundledContext->effectInDrain = 0;
262 
263         ALOGV("\tEffectCreate - Calling LvmBundle_init");
264         ret = LvmBundle_init(pContext);
265 
266         if (ret < 0) {
267             ALOGV("\tLVM_ERROR : EffectCreate() Bundle init failed");
268             goto exit;
269         }
270     } else {
271         ALOGV("\tEffectCreate - Assigning memory for previously created effect on sessionNo %d",
272               sessionNo);
273         pContext->pBundledContext = GlobalSessionMemory[sessionNo].pBundledContext;
274     }
275     ALOGV("\tEffectCreate - pBundledContext is %p", pContext->pBundledContext);
276 
277     pSessionContext = &GlobalSessionMemory[pContext->pBundledContext->SessionNo];
278 
279     // Create each Effect
280     if (memcmp(uuid, &gBassBoostDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
281         // Create Bass Boost
282         ALOGV("\tEffectCreate - Effect to be created is LVM_BASS_BOOST");
283         pSessionContext->bBassInstantiated = LVM_TRUE;
284         pContext->pBundledContext->SamplesToExitCountBb = 0;
285 
286         pContext->itfe = &gLvmEffectInterface;
287         pContext->EffectType = LVM_BASS_BOOST;
288     } else if (memcmp(uuid, &gVirtualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
289         // Create Virtualizer
290         ALOGV("\tEffectCreate - Effect to be created is LVM_VIRTUALIZER");
291         pSessionContext->bVirtualizerInstantiated = LVM_TRUE;
292         pContext->pBundledContext->SamplesToExitCountVirt = 0;
293 
294         pContext->itfe = &gLvmEffectInterface;
295         pContext->EffectType = LVM_VIRTUALIZER;
296     } else if (memcmp(uuid, &gEqualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
297         // Create Equalizer
298         ALOGV("\tEffectCreate - Effect to be created is LVM_EQUALIZER");
299         pSessionContext->bEqualizerInstantiated = LVM_TRUE;
300         pContext->pBundledContext->SamplesToExitCountEq = 0;
301 
302         pContext->itfe = &gLvmEffectInterface;
303         pContext->EffectType = LVM_EQUALIZER;
304     } else if (memcmp(uuid, &gVolumeDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
305         // Create Volume
306         ALOGV("\tEffectCreate - Effect to be created is LVM_VOLUME");
307         pSessionContext->bVolumeInstantiated = LVM_TRUE;
308 
309         pContext->itfe = &gLvmEffectInterface;
310         pContext->EffectType = LVM_VOLUME;
311     } else {
312         ALOGV("\tLVM_ERROR : EffectCreate() invalid UUID");
313         ret = -EINVAL;
314         goto exit;
315     }
316 
317 exit:
318     if (ret != 0) {
319         if (pContext != NULL) {
320             if (newBundle) {
321                 GlobalSessionMemory[sessionNo].bBundledEffectsEnabled = LVM_FALSE;
322                 SessionIndex[sessionNo] = LVM_UNUSED_SESSION;
323                 delete pContext->pBundledContext;
324             }
325             delete pContext;
326         }
327         if (pHandle != NULL) *pHandle = (effect_handle_t)NULL;
328     } else {
329         if (pHandle != NULL) *pHandle = (effect_handle_t)pContext;
330     }
331     ALOGV("\tEffectCreate end..\n\n");
332     return ret;
333 } /* end EffectCreate */
334 
EffectRelease(effect_handle_t handle)335 extern "C" int EffectRelease(effect_handle_t handle) {
336     ALOGV("\n\tEffectRelease start %p", handle);
337     EffectContext* pContext = (EffectContext*)handle;
338 
339     ALOGV("\tEffectRelease start handle: %p, context %p", handle, pContext->pBundledContext);
340     if (pContext == NULL) {
341         ALOGV("\tLVM_ERROR : EffectRelease called with NULL pointer");
342         return -EINVAL;
343     }
344 
345     SessionContext* pSessionContext = &GlobalSessionMemory[pContext->pBundledContext->SessionNo];
346 
347     // Clear the instantiated flag for the effect
348     // protect agains the case where an effect is un-instantiated without being disabled
349 
350     int& effectInDrain = pContext->pBundledContext->effectInDrain;
351     if (pContext->EffectType == LVM_BASS_BOOST) {
352         ALOGV("\tEffectRelease LVM_BASS_BOOST Clearing global intstantiated flag");
353         pSessionContext->bBassInstantiated = LVM_FALSE;
354         if (pContext->pBundledContext->SamplesToExitCountBb > 0) {
355             pContext->pBundledContext->NumberEffectsEnabled--;
356         }
357         pContext->pBundledContext->SamplesToExitCountBb = 0;
358     } else if (pContext->EffectType == LVM_VIRTUALIZER) {
359         ALOGV("\tEffectRelease LVM_VIRTUALIZER Clearing global intstantiated flag");
360         pSessionContext->bVirtualizerInstantiated = LVM_FALSE;
361         if (pContext->pBundledContext->SamplesToExitCountVirt > 0) {
362             pContext->pBundledContext->NumberEffectsEnabled--;
363         }
364         pContext->pBundledContext->SamplesToExitCountVirt = 0;
365     } else if (pContext->EffectType == LVM_EQUALIZER) {
366         ALOGV("\tEffectRelease LVM_EQUALIZER Clearing global intstantiated flag");
367         pSessionContext->bEqualizerInstantiated = LVM_FALSE;
368         if (pContext->pBundledContext->SamplesToExitCountEq > 0) {
369             pContext->pBundledContext->NumberEffectsEnabled--;
370         }
371         pContext->pBundledContext->SamplesToExitCountEq = 0;
372     } else if (pContext->EffectType == LVM_VOLUME) {
373         ALOGV("\tEffectRelease LVM_VOLUME Clearing global intstantiated flag");
374         pSessionContext->bVolumeInstantiated = LVM_FALSE;
375         // There is no samplesToExitCount for volume so we also use the drain flag to check
376         // if we should decrement the effects enabled.
377         if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE ||
378             (effectInDrain & 1 << LVM_VOLUME) != 0) {
379             pContext->pBundledContext->NumberEffectsEnabled--;
380         }
381     } else {
382         ALOGV("\tLVM_ERROR : EffectRelease : Unsupported effect\n\n\n\n\n\n\n");
383     }
384     effectInDrain &= ~(1 << pContext->EffectType);  // no need to drain if released
385 
386     // Disable effect, in this case ignore errors (return codes)
387     // if an effect has already been disabled
388     Effect_setEnabled(pContext, LVM_FALSE);
389 
390     // if all effects are no longer instantiaed free the lvm memory and delete BundledEffectContext
391     if ((pSessionContext->bBassInstantiated == LVM_FALSE) &&
392         (pSessionContext->bVolumeInstantiated == LVM_FALSE) &&
393         (pSessionContext->bEqualizerInstantiated == LVM_FALSE) &&
394         (pSessionContext->bVirtualizerInstantiated == LVM_FALSE)) {
395         // Clear the SessionIndex
396         for (int i = 0; i < LVM_MAX_SESSIONS; i++) {
397             if (SessionIndex[i] == pContext->pBundledContext->SessionId) {
398                 SessionIndex[i] = LVM_UNUSED_SESSION;
399                 ALOGV("\tEffectRelease: Clearing SessionIndex SessionNo %d for SessionId %d\n", i,
400                       pContext->pBundledContext->SessionId);
401                 break;
402             }
403         }
404 
405         ALOGV("\tEffectRelease: All effects are no longer instantiated\n");
406         pSessionContext->bBundledEffectsEnabled = LVM_FALSE;
407         pSessionContext->pBundledContext = LVM_NULL;
408         ALOGV("\tEffectRelease: Freeing LVM Bundle memory\n");
409         LVM_DelInstanceHandle(&pContext->pBundledContext->hInstance);
410         ALOGV("\tEffectRelease: Deleting LVM Bundle context %p\n", pContext->pBundledContext);
411         if (pContext->pBundledContext->workBuffer != NULL) {
412             free(pContext->pBundledContext->workBuffer);
413         }
414         delete pContext->pBundledContext;
415         pContext->pBundledContext = LVM_NULL;
416     }
417     // free the effect context for current effect
418     delete pContext;
419 
420     ALOGV("\tEffectRelease end\n");
421     return 0;
422 
423 } /* end EffectRelease */
424 
EffectGetDescriptor(const effect_uuid_t * uuid,effect_descriptor_t * pDescriptor)425 extern "C" int EffectGetDescriptor(const effect_uuid_t* uuid, effect_descriptor_t* pDescriptor) {
426     const effect_descriptor_t* desc = NULL;
427 
428     if (pDescriptor == NULL || uuid == NULL) {
429         ALOGV("EffectGetDescriptor() called with NULL pointer");
430         return -EINVAL;
431     }
432 
433     if (memcmp(uuid, &gBassBoostDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
434         desc = &gBassBoostDescriptor;
435     } else if (memcmp(uuid, &gVirtualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
436         desc = &gVirtualizerDescriptor;
437     } else if (memcmp(uuid, &gEqualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
438         desc = &gEqualizerDescriptor;
439     } else if (memcmp(uuid, &gVolumeDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
440         desc = &gVolumeDescriptor;
441     }
442 
443     if (desc == NULL) {
444         return -EINVAL;
445     }
446 
447     *pDescriptor = *desc;
448 
449     return 0;
450 } /* end EffectGetDescriptor */
451 
LvmGlobalBundle_init()452 void LvmGlobalBundle_init() {
453     ALOGV("\tLvmGlobalBundle_init start");
454     for (int i = 0; i < LVM_MAX_SESSIONS; i++) {
455         GlobalSessionMemory[i].bBundledEffectsEnabled = LVM_FALSE;
456         GlobalSessionMemory[i].bVolumeInstantiated = LVM_FALSE;
457         GlobalSessionMemory[i].bEqualizerInstantiated = LVM_FALSE;
458         GlobalSessionMemory[i].bBassInstantiated = LVM_FALSE;
459         GlobalSessionMemory[i].bVirtualizerInstantiated = LVM_FALSE;
460         GlobalSessionMemory[i].pBundledContext = LVM_NULL;
461 
462         SessionIndex[i] = LVM_UNUSED_SESSION;
463     }
464     return;
465 }
466 //----------------------------------------------------------------------------
467 // LvmBundle_init()
468 //----------------------------------------------------------------------------
469 // Purpose: Initialize engine with default configuration, creates instance
470 // with all effects disabled.
471 //
472 // Inputs:
473 //  pContext:   effect engine context
474 //
475 // Outputs:
476 //
477 //----------------------------------------------------------------------------
478 
LvmBundle_init(EffectContext * pContext)479 int LvmBundle_init(EffectContext* pContext) {
480     ALOGV("\tLvmBundle_init start");
481 
482     pContext->config.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
483     pContext->config.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
484     pContext->config.inputCfg.format = EFFECT_BUFFER_FORMAT;
485     pContext->config.inputCfg.samplingRate = 44100;
486     pContext->config.inputCfg.bufferProvider.getBuffer = NULL;
487     pContext->config.inputCfg.bufferProvider.releaseBuffer = NULL;
488     pContext->config.inputCfg.bufferProvider.cookie = NULL;
489     pContext->config.inputCfg.mask = EFFECT_CONFIG_ALL;
490     pContext->config.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
491     pContext->config.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
492     pContext->config.outputCfg.format = EFFECT_BUFFER_FORMAT;
493     pContext->config.outputCfg.samplingRate = 44100;
494     pContext->config.outputCfg.bufferProvider.getBuffer = NULL;
495     pContext->config.outputCfg.bufferProvider.releaseBuffer = NULL;
496     pContext->config.outputCfg.bufferProvider.cookie = NULL;
497     pContext->config.outputCfg.mask = EFFECT_CONFIG_ALL;
498 
499     CHECK_ARG(pContext != NULL);
500 
501     if (pContext->pBundledContext->hInstance != NULL) {
502         ALOGV("\tLvmBundle_init pContext->pBassBoost != NULL "
503               "-> Calling pContext->pBassBoost->free()");
504         LVM_DelInstanceHandle(&pContext->pBundledContext->hInstance);
505 
506         ALOGV("\tLvmBundle_init pContext->pBassBoost != NULL "
507               "-> Called pContext->pBassBoost->free()");
508     }
509 
510     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
511     LVM_ControlParams_t params;                  /* Control Parameters */
512     LVM_InstParams_t InstParams;                 /* Instance parameters */
513     LVM_EQNB_BandDef_t BandDefs[MAX_NUM_BANDS];  /* Equaliser band definitions */
514     LVM_HeadroomParams_t HeadroomParams;         /* Headroom parameters */
515     LVM_HeadroomBandDef_t HeadroomBandDef[LVM_HEADROOM_MAX_NBANDS];
516 
517     /* Set the capabilities */
518     InstParams.BufferMode = LVM_UNMANAGED_BUFFERS;
519     InstParams.MaxBlockSize = MAX_CALL_SIZE;
520     InstParams.EQNB_NumBands = MAX_NUM_BANDS;
521     InstParams.PSA_Included = LVM_PSA_ON;
522 
523     LvmStatus = LVM_GetInstanceHandle(&pContext->pBundledContext->hInstance, &InstParams);
524 
525     LVM_ERROR_CHECK(LvmStatus, "LVM_GetInstanceHandle", "LvmBundle_init")
526     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
527 
528     ALOGV("\tLvmBundle_init CreateInstance Successfully called LVM_GetInstanceHandle\n");
529 
530     /* Set the initial process parameters */
531     /* General parameters */
532     params.OperatingMode = LVM_MODE_ON;
533     params.SampleRate = LVM_FS_44100;
534     params.SourceFormat = LVM_STEREO;
535     params.SpeakerType = LVM_HEADPHONES;
536 
537     pContext->pBundledContext->SampleRate = LVM_FS_44100;
538     pContext->pBundledContext->ChMask = AUDIO_CHANNEL_OUT_STEREO;
539 
540     /* Concert Sound parameters */
541     params.VirtualizerOperatingMode = LVM_MODE_OFF;
542     params.VirtualizerType = LVM_CONCERTSOUND;
543     params.VirtualizerReverbLevel = 100;
544     params.CS_EffectLevel = LVM_CS_EFFECT_NONE;
545 
546     /* N-Band Equaliser parameters */
547     params.EQNB_OperatingMode = LVM_EQNB_OFF;
548     params.EQNB_NBands = FIVEBAND_NUMBANDS;
549     params.pEQNB_BandDefinition = &BandDefs[0];
550 
551     for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
552         BandDefs[i].Frequency = EQNB_5BandPresetsFrequencies[i];
553         BandDefs[i].QFactor = EQNB_5BandPresetsQFactors[i];
554         BandDefs[i].Gain = EQNB_5BandSoftPresets[i];
555     }
556 
557     /* Volume Control parameters */
558     params.VC_EffectLevel = 0;
559     params.VC_Balance = 0;
560 
561     /* Treble Enhancement parameters */
562     params.TE_OperatingMode = LVM_TE_OFF;
563     params.TE_EffectLevel = 0;
564 
565     /* PSA Control parameters */
566     params.PSA_Enable = LVM_PSA_OFF;
567     params.PSA_PeakDecayRate = (LVM_PSA_DecaySpeed_en)0;
568 
569     /* Bass Enhancement parameters */
570     params.BE_OperatingMode = LVM_BE_OFF;
571     params.BE_EffectLevel = 0;
572     params.BE_CentreFreq = LVM_BE_CENTRE_90Hz;
573     params.BE_HPF = LVM_BE_HPF_ON;
574 
575     /* PSA Control parameters */
576     params.PSA_Enable = LVM_PSA_OFF;
577     params.PSA_PeakDecayRate = LVM_PSA_SPEED_MEDIUM;
578 
579     /* TE Control parameters */
580     params.TE_OperatingMode = LVM_TE_OFF;
581     params.TE_EffectLevel = 0;
582 
583     params.NrChannels = audio_channel_count_from_out_mask(AUDIO_CHANNEL_OUT_STEREO);
584     params.ChMask = AUDIO_CHANNEL_OUT_STEREO;
585     /* Activate the initial settings */
586     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &params);
587 
588     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmBundle_init")
589     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
590 
591     ALOGV("\tLvmBundle_init CreateInstance Successfully called LVM_SetControlParameters\n");
592 
593     /* Set the headroom parameters */
594     HeadroomBandDef[0].Limit_Low = 20;
595     HeadroomBandDef[0].Limit_High = 4999;
596     HeadroomBandDef[0].Headroom_Offset = 0;
597     HeadroomBandDef[1].Limit_Low = 5000;
598     HeadroomBandDef[1].Limit_High = 24000;
599     HeadroomBandDef[1].Headroom_Offset = 0;
600     HeadroomParams.pHeadroomDefinition = &HeadroomBandDef[0];
601     HeadroomParams.Headroom_OperatingMode = LVM_HEADROOM_ON;
602     HeadroomParams.NHeadroomBands = 2;
603 
604     LvmStatus = LVM_SetHeadroomParams(pContext->pBundledContext->hInstance, &HeadroomParams);
605 
606     LVM_ERROR_CHECK(LvmStatus, "LVM_SetHeadroomParams", "LvmBundle_init")
607     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
608 
609     ALOGV("\tLvmBundle_init CreateInstance Successfully called LVM_SetHeadroomParams\n");
610     ALOGV("\tLvmBundle_init End");
611     return 0;
612 } /* end LvmBundle_init */
613 
614 //----------------------------------------------------------------------------
615 // LvmBundle_process()
616 //----------------------------------------------------------------------------
617 // Purpose:
618 // Apply LVM Bundle effects
619 //
620 // Inputs:
621 //  pIn:        pointer to stereo float or 16 bit input data
622 //  pOut:       pointer to stereo float or 16 bit output data
623 //  frameCount: Frames to process
624 //  pContext:   effect engine context
625 //  strength    strength to be applied
626 //
627 //  Outputs:
628 //  pOut:       pointer to updated stereo 16 bit output data
629 //
630 //----------------------------------------------------------------------------
LvmBundle_process(effect_buffer_t * pIn,effect_buffer_t * pOut,int frameCount,EffectContext * pContext)631 int LvmBundle_process(effect_buffer_t* pIn, effect_buffer_t* pOut, int frameCount,
632                       EffectContext* pContext) {
633     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
634     effect_buffer_t* pOutTmp;
635     const LVM_INT32 NrChannels =
636             audio_channel_count_from_out_mask(pContext->config.inputCfg.channels);
637 
638     if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE) {
639         pOutTmp = pOut;
640     } else if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
641         if (pContext->pBundledContext->frameCount != frameCount) {
642             if (pContext->pBundledContext->workBuffer != NULL) {
643                 free(pContext->pBundledContext->workBuffer);
644             }
645             pContext->pBundledContext->workBuffer =
646                     (effect_buffer_t*)calloc(frameCount, sizeof(effect_buffer_t) * NrChannels);
647             if (pContext->pBundledContext->workBuffer == NULL) {
648                 return -ENOMEM;
649             }
650             pContext->pBundledContext->frameCount = frameCount;
651         }
652         pOutTmp = pContext->pBundledContext->workBuffer;
653     } else {
654         ALOGV("LVM_ERROR : LvmBundle_process invalid access mode");
655         return -EINVAL;
656     }
657 
658     /* Process the samples */
659     LvmStatus = LVM_Process(pContext->pBundledContext->hInstance, /* Instance handle */
660                             pIn,                                  /* Input buffer */
661                             pOutTmp,                              /* Output buffer */
662                             (LVM_UINT16)frameCount,               /* Number of samples to read */
663                             0);                                   /* Audio Time */
664     LVM_ERROR_CHECK(LvmStatus, "LVM_Process", "LvmBundle_process")
665     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
666 
667     if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
668         for (int i = 0; i < frameCount * NrChannels; i++) {
669             pOut[i] = pOut[i] + pOutTmp[i];
670         }
671     }
672     return 0;
673 } /* end LvmBundle_process */
674 
675 //----------------------------------------------------------------------------
676 // EqualizerUpdateActiveParams()
677 //----------------------------------------------------------------------------
678 // Purpose: Update ActiveParams for Equalizer
679 //
680 // Inputs:
681 //  pContext:   effect engine context
682 //
683 // Outputs:
684 //
685 //----------------------------------------------------------------------------
EqualizerUpdateActiveParams(EffectContext * pContext)686 void EqualizerUpdateActiveParams(EffectContext* pContext) {
687     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
688     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
689 
690     /* Get the current settings */
691     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
692     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "EqualizerUpdateActiveParams")
693     // ALOGV("\tEqualizerUpdateActiveParams Successfully returned from LVM_GetControlParameters\n");
694     // ALOGV("\tEqualizerUpdateActiveParams just Got -> %d\n",
695     //          ActiveParams.pEQNB_BandDefinition[band].Gain);
696 
697     for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
698         ActiveParams.pEQNB_BandDefinition[i].Frequency = EQNB_5BandPresetsFrequencies[i];
699         ActiveParams.pEQNB_BandDefinition[i].QFactor = EQNB_5BandPresetsQFactors[i];
700         ActiveParams.pEQNB_BandDefinition[i].Gain = pContext->pBundledContext->bandGaindB[i];
701     }
702 
703     /* Activate the initial settings */
704     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
705     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "EqualizerUpdateActiveParams")
706     // ALOGV("\tEqualizerUpdateActiveParams just Set -> %d\n",
707     //          ActiveParams.pEQNB_BandDefinition[band].Gain);
708 }
709 
710 //----------------------------------------------------------------------------
711 // LvmEffect_limitLevel()
712 //----------------------------------------------------------------------------
713 // Purpose: limit the overall level to a value less than 0 dB preserving
714 //          the overall EQ band gain and BassBoost relative levels.
715 //
716 // Inputs:
717 //  pContext:   effect engine context
718 //
719 // Outputs:
720 //
721 //----------------------------------------------------------------------------
LvmEffect_limitLevel(EffectContext * pContext)722 void LvmEffect_limitLevel(EffectContext* pContext) {
723     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
724     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
725 
726     /* Get the current settings */
727     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
728     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "LvmEffect_limitLevel")
729     // ALOGV("\tLvmEffect_limitLevel Successfully returned from LVM_GetControlParameters\n");
730     // ALOGV("\tLvmEffect_limitLevel just Got -> %d\n",
731     //          ActiveParams.pEQNB_BandDefinition[band].Gain);
732 
733     int gainCorrection = 0;
734     // Count the energy contribution per band for EQ and BassBoost only if they are active.
735     float energyContribution = 0;
736     float energyCross = 0;
737     float energyBassBoost = 0;
738     float crossCorrection = 0;
739 
740     bool eqEnabled = pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE;
741     bool bbEnabled = pContext->pBundledContext->bBassEnabled == LVM_TRUE;
742     bool viEnabled = pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE;
743 
744     // EQ contribution
745     if (eqEnabled) {
746         for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
747             float bandFactor = pContext->pBundledContext->bandGaindB[i] / 15.0;
748             float bandCoefficient = LimitLevel_bandEnergyCoefficient[i];
749             float bandEnergy = bandFactor * bandCoefficient * bandCoefficient;
750             if (bandEnergy > 0) energyContribution += bandEnergy;
751         }
752 
753         // cross EQ coefficients
754         float bandFactorSum = 0;
755         for (int i = 0; i < FIVEBAND_NUMBANDS - 1; i++) {
756             float bandFactor1 = pContext->pBundledContext->bandGaindB[i] / 15.0;
757             float bandFactor2 = pContext->pBundledContext->bandGaindB[i + 1] / 15.0;
758 
759             if (bandFactor1 > 0 && bandFactor2 > 0) {
760                 float crossEnergy =
761                         bandFactor1 * bandFactor2 * LimitLevel_bandEnergyCrossCoefficient[i];
762                 bandFactorSum += bandFactor1 * bandFactor2;
763 
764                 if (crossEnergy > 0) energyCross += crossEnergy;
765             }
766         }
767         bandFactorSum -= 1.0;
768         if (bandFactorSum > 0) crossCorrection = bandFactorSum * 0.7;
769     }
770 
771     // BassBoost contribution
772     if (bbEnabled) {
773         float boostFactor = (pContext->pBundledContext->BassStrengthSaved) / 1000.0;
774         float boostCoefficient = LimitLevel_bassBoostEnergyCoefficient;
775 
776         energyContribution += boostFactor * boostCoefficient * boostCoefficient;
777 
778         if (eqEnabled) {
779             for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
780                 float bandFactor = pContext->pBundledContext->bandGaindB[i] / 15.0;
781                 float bandCrossCoefficient = LimitLevel_bassBoostEnergyCrossCoefficient[i];
782                 float bandEnergy = boostFactor * bandFactor * bandCrossCoefficient;
783                 if (bandEnergy > 0) energyBassBoost += bandEnergy;
784             }
785         }
786     }
787 
788     // Virtualizer contribution
789     if (viEnabled) {
790         energyContribution +=
791                 LimitLevel_virtualizerContribution * LimitLevel_virtualizerContribution;
792     }
793 
794     double totalEnergyEstimation =
795             sqrt(energyContribution + energyCross + energyBassBoost) - crossCorrection;
796     ALOGV(" TOTAL energy estimation: %0.2f dB", totalEnergyEstimation);
797 
798     // roundoff
799     int maxLevelRound = (int)(totalEnergyEstimation + 0.99);
800     if (maxLevelRound + pContext->pBundledContext->volume > 0) {
801         gainCorrection = maxLevelRound + pContext->pBundledContext->volume;
802     }
803 
804     ActiveParams.VC_EffectLevel = pContext->pBundledContext->volume - gainCorrection;
805     if (ActiveParams.VC_EffectLevel < -96) {
806         ActiveParams.VC_EffectLevel = -96;
807     }
808     ALOGV("\tVol:%d, GainCorrection: %d, Actual vol: %d", pContext->pBundledContext->volume,
809           gainCorrection, ActiveParams.VC_EffectLevel);
810 
811     /* Activate the initial settings */
812     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
813     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmEffect_limitLevel")
814 
815     ALOGV("LVM_SetControlParameters return:%d", (int)LvmStatus);
816     // ALOGV("\tLvmEffect_limitLevel just Set -> %d\n",
817     //          ActiveParams.pEQNB_BandDefinition[band].Gain);
818 
819     // ALOGV("\tLvmEffect_limitLevel just set (-96dB -> 0dB) -> %d\n",ActiveParams.VC_EffectLevel );
820     if (pContext->pBundledContext->firstVolume == LVM_TRUE) {
821         LvmStatus = LVM_SetVolumeNoSmoothing(pContext->pBundledContext->hInstance, &ActiveParams);
822         LVM_ERROR_CHECK(LvmStatus, "LVM_SetVolumeNoSmoothing", "LvmBundle_process")
823         ALOGV("\tLVM_VOLUME: Disabling Smoothing for first volume change to remove spikes/clicks");
824         pContext->pBundledContext->firstVolume = LVM_FALSE;
825     }
826 }
827 
828 //----------------------------------------------------------------------------
829 // LvmEffect_enable()
830 //----------------------------------------------------------------------------
831 // Purpose: Enable the effect in the bundle
832 //
833 // Inputs:
834 //  pContext:   effect engine context
835 //
836 // Outputs:
837 //
838 //----------------------------------------------------------------------------
839 
LvmEffect_enable(EffectContext * pContext)840 int LvmEffect_enable(EffectContext* pContext) {
841     // ALOGV("\tLvmEffect_enable start");
842 
843     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
844     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
845 
846     /* Get the current settings */
847     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
848 
849     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "LvmEffect_enable")
850     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
851     // ALOGV("\tLvmEffect_enable Successfully called LVM_GetControlParameters\n");
852 
853     if (pContext->EffectType == LVM_BASS_BOOST) {
854         ALOGV("\tLvmEffect_enable : Enabling LVM_BASS_BOOST");
855         ActiveParams.BE_OperatingMode = LVM_BE_ON;
856     }
857     if (pContext->EffectType == LVM_VIRTUALIZER) {
858         ALOGV("\tLvmEffect_enable : Enabling LVM_VIRTUALIZER");
859         ActiveParams.VirtualizerOperatingMode = LVM_MODE_ON;
860     }
861     if (pContext->EffectType == LVM_EQUALIZER) {
862         ALOGV("\tLvmEffect_enable : Enabling LVM_EQUALIZER");
863         ActiveParams.EQNB_OperatingMode = LVM_EQNB_ON;
864     }
865     if (pContext->EffectType == LVM_VOLUME) {
866         ALOGV("\tLvmEffect_enable : Enabling LVM_VOLUME");
867     }
868 
869     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
870     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmEffect_enable")
871     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
872 
873     // ALOGV("\tLvmEffect_enable Successfully called LVM_SetControlParameters\n");
874     // ALOGV("\tLvmEffect_enable end");
875     LvmEffect_limitLevel(pContext);
876     return 0;
877 }
878 
879 //----------------------------------------------------------------------------
880 // LvmEffect_disable()
881 //----------------------------------------------------------------------------
882 // Purpose: Disable the effect in the bundle
883 //
884 // Inputs:
885 //  pContext:   effect engine context
886 //
887 // Outputs:
888 //
889 //----------------------------------------------------------------------------
890 
LvmEffect_disable(EffectContext * pContext)891 int LvmEffect_disable(EffectContext* pContext) {
892     // ALOGV("\tLvmEffect_disable start");
893 
894     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
895     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
896     /* Get the current settings */
897     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
898 
899     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "LvmEffect_disable")
900     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
901     // ALOGV("\tLvmEffect_disable Successfully called LVM_GetControlParameters\n");
902 
903     if (pContext->EffectType == LVM_BASS_BOOST) {
904         ALOGV("\tLvmEffect_disable : Disabling LVM_BASS_BOOST");
905         ActiveParams.BE_OperatingMode = LVM_BE_OFF;
906     }
907     if (pContext->EffectType == LVM_VIRTUALIZER) {
908         ALOGV("\tLvmEffect_disable : Disabling LVM_VIRTUALIZER");
909         ActiveParams.VirtualizerOperatingMode = LVM_MODE_OFF;
910     }
911     if (pContext->EffectType == LVM_EQUALIZER) {
912         ALOGV("\tLvmEffect_disable : Disabling LVM_EQUALIZER");
913         ActiveParams.EQNB_OperatingMode = LVM_EQNB_OFF;
914     }
915     if (pContext->EffectType == LVM_VOLUME) {
916         ALOGV("\tLvmEffect_disable : Disabling LVM_VOLUME");
917     }
918 
919     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
920     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmEffect_disable")
921     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
922 
923     // ALOGV("\tLvmEffect_disable Successfully called LVM_SetControlParameters\n");
924     // ALOGV("\tLvmEffect_disable end");
925     LvmEffect_limitLevel(pContext);
926     return 0;
927 }
928 
929 //----------------------------------------------------------------------------
930 // Effect_setConfig()
931 //----------------------------------------------------------------------------
932 // Purpose: Set input and output audio configuration.
933 //
934 // Inputs:
935 //  pContext:   effect engine context
936 //  pConfig:    pointer to effect_config_t structure holding input and output
937 //      configuration parameters
938 //
939 // Outputs:
940 //
941 //----------------------------------------------------------------------------
942 
Effect_setConfig(EffectContext * pContext,effect_config_t * pConfig)943 int Effect_setConfig(EffectContext* pContext, effect_config_t* pConfig) {
944     LVM_Fs_en SampleRate;
945     // ALOGV("\tEffect_setConfig start");
946 
947     CHECK_ARG(pContext != NULL);
948     CHECK_ARG(pConfig != NULL);
949 
950     CHECK_ARG(pConfig->inputCfg.samplingRate == pConfig->outputCfg.samplingRate);
951     CHECK_ARG(pConfig->inputCfg.channels == pConfig->outputCfg.channels);
952     CHECK_ARG(pConfig->inputCfg.format == pConfig->outputCfg.format);
953     CHECK_ARG(audio_channel_count_from_out_mask(pConfig->inputCfg.channels) <= LVM_MAX_CHANNELS);
954     CHECK_ARG(pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE ||
955               pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE);
956     CHECK_ARG(pConfig->inputCfg.format == EFFECT_BUFFER_FORMAT);
957     pContext->config = *pConfig;
958     const LVM_INT16 NrChannels = audio_channel_count_from_out_mask(pConfig->inputCfg.channels);
959 
960     SampleRate = lvmFsForSampleRate(pConfig->inputCfg.samplingRate);
961     if (SampleRate == LVM_FS_INVALID) {
962         ALOGV("Effect_setConfig invalid sampling rate %d", pConfig->inputCfg.samplingRate);
963         return -EINVAL;
964     }
965     pContext->pBundledContext->SamplesPerSecond = pConfig->inputCfg.samplingRate * NrChannels;
966 
967     if (pContext->pBundledContext->SampleRate != SampleRate ||
968         pContext->pBundledContext->ChMask != pConfig->inputCfg.channels) {
969         LVM_ControlParams_t ActiveParams;
970         LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS;
971 
972         ALOGV("\tEffect_setConfig change sampling rate to %d", SampleRate);
973 
974         /* Get the current settings */
975         LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
976 
977         LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "Effect_setConfig")
978         if (LvmStatus != LVM_SUCCESS) return -EINVAL;
979 
980         ActiveParams.SampleRate = SampleRate;
981 
982         ActiveParams.NrChannels = NrChannels;
983         ActiveParams.ChMask = pConfig->inputCfg.channels;
984 
985         if (NrChannels == 1) {
986             ActiveParams.SourceFormat = LVM_MONO;
987         } else if (NrChannels == 2) {
988             ActiveParams.SourceFormat = LVM_STEREO;
989         } else if (NrChannels > 2 && NrChannels <= LVM_MAX_CHANNELS) {
990             ActiveParams.SourceFormat = LVM_MULTICHANNEL;
991         } else {
992             return -EINVAL;
993         }
994 
995         LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
996 
997         LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "Effect_setConfig")
998         ALOGV("\tEffect_setConfig Successfully called LVM_SetControlParameters\n");
999         pContext->pBundledContext->SampleRate = SampleRate;
1000         pContext->pBundledContext->ChMask = pConfig->inputCfg.channels;
1001 
1002         LvmEffect_limitLevel(pContext);
1003 
1004     } else {
1005         // ALOGV("\tEffect_setConfig keep sampling rate at %d", SampleRate);
1006     }
1007 
1008     // ALOGV("\tEffect_setConfig End....");
1009     return 0;
1010 } /* end Effect_setConfig */
1011 
1012 //----------------------------------------------------------------------------
1013 // Effect_getConfig()
1014 //----------------------------------------------------------------------------
1015 // Purpose: Get input and output audio configuration.
1016 //
1017 // Inputs:
1018 //  pContext:   effect engine context
1019 //  pConfig:    pointer to effect_config_t structure holding input and output
1020 //      configuration parameters
1021 //
1022 // Outputs:
1023 //
1024 //----------------------------------------------------------------------------
1025 
Effect_getConfig(EffectContext * pContext,effect_config_t * pConfig)1026 void Effect_getConfig(EffectContext* pContext, effect_config_t* pConfig) {
1027     *pConfig = pContext->config;
1028 } /* end Effect_getConfig */
1029 
1030 //----------------------------------------------------------------------------
1031 // BassGetStrength()
1032 //----------------------------------------------------------------------------
1033 // Purpose:
1034 // get the effect strength currently being used, what is actually returned is the strengh that was
1035 // previously used in the set, this is because the app uses a strength in the range 0-1000 while
1036 // the bassboost uses 1-15, so to avoid a quantisation the original set value is used. However the
1037 // actual used value is checked to make sure it corresponds to the one being returned
1038 //
1039 // Inputs:
1040 //  pContext:   effect engine context
1041 //
1042 //----------------------------------------------------------------------------
1043 
BassGetStrength(EffectContext * pContext)1044 uint32_t BassGetStrength(EffectContext* pContext) {
1045     // ALOGV("\tBassGetStrength() (0-1000) -> %d\n", pContext->pBundledContext->BassStrengthSaved);
1046 
1047     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
1048     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
1049     /* Get the current settings */
1050     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1051 
1052     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "BassGetStrength")
1053     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
1054 
1055     // ALOGV("\tBassGetStrength Successfully returned from LVM_GetControlParameters\n");
1056 
1057     /* Check that the strength returned matches the strength that was set earlier */
1058     if (ActiveParams.BE_EffectLevel !=
1059         (LVM_INT16)((15 * pContext->pBundledContext->BassStrengthSaved) / 1000)) {
1060         ALOGV("\tLVM_ERROR : BassGetStrength module strength does not match savedStrength %d %d\n",
1061               ActiveParams.BE_EffectLevel, pContext->pBundledContext->BassStrengthSaved);
1062         return -EINVAL;
1063     }
1064 
1065     // ALOGV("\tBassGetStrength() (0-15)   -> %d\n", ActiveParams.BE_EffectLevel );
1066     // ALOGV("\tBassGetStrength() (saved)  -> %d\n", pContext->pBundledContext->BassStrengthSaved );
1067     return pContext->pBundledContext->BassStrengthSaved;
1068 } /* end BassGetStrength */
1069 
1070 //----------------------------------------------------------------------------
1071 // BassSetStrength()
1072 //----------------------------------------------------------------------------
1073 // Purpose:
1074 // Apply the strength to the BassBosst. Must first be converted from the range 0-1000 to 1-15
1075 //
1076 // Inputs:
1077 //  pContext:   effect engine context
1078 //  strength    strength to be applied
1079 //
1080 //----------------------------------------------------------------------------
1081 
BassSetStrength(EffectContext * pContext,uint32_t strength)1082 void BassSetStrength(EffectContext* pContext, uint32_t strength) {
1083     // ALOGV("\tBassSetStrength(%d)", strength);
1084 
1085     pContext->pBundledContext->BassStrengthSaved = (int)strength;
1086 
1087     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
1088     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
1089 
1090     /* Get the current settings */
1091     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1092 
1093     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "BassSetStrength")
1094     // ALOGV("\tBassSetStrength Successfully returned from LVM_GetControlParameters\n");
1095 
1096     /* Bass Enhancement parameters */
1097     ActiveParams.BE_EffectLevel = (LVM_INT16)((15 * strength) / 1000);
1098     ActiveParams.BE_CentreFreq = LVM_BE_CENTRE_90Hz;
1099 
1100     // ALOGV("\tBassSetStrength() (0-15)   -> %d\n", ActiveParams.BE_EffectLevel );
1101 
1102     /* Activate the initial settings */
1103     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1104 
1105     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "BassSetStrength")
1106     // ALOGV("\tBassSetStrength Successfully called LVM_SetControlParameters\n");
1107 
1108     LvmEffect_limitLevel(pContext);
1109 } /* end BassSetStrength */
1110 
1111 //----------------------------------------------------------------------------
1112 // VirtualizerGetStrength()
1113 //----------------------------------------------------------------------------
1114 // Purpose:
1115 // get the effect strength currently being used, what is actually returned is the strengh that was
1116 // previously used in the set, this is because the app uses a strength in the range 0-1000 while
1117 // the Virtualizer uses 1-100, so to avoid a quantisation the original set value is used.However the
1118 // actual used value is checked to make sure it corresponds to the one being returned
1119 //
1120 // Inputs:
1121 //  pContext:   effect engine context
1122 //
1123 //----------------------------------------------------------------------------
1124 
VirtualizerGetStrength(EffectContext * pContext)1125 uint32_t VirtualizerGetStrength(EffectContext* pContext) {
1126     // ALOGV("\tVirtualizerGetStrength (0-1000) ->
1127     // %d\n",pContext->pBundledContext->VirtStrengthSaved);
1128 
1129     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
1130     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
1131 
1132     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1133 
1134     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VirtualizerGetStrength")
1135     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
1136 
1137     // ALOGV("\tVirtualizerGetStrength Successfully returned from LVM_GetControlParameters\n");
1138     // ALOGV("\tVirtualizerGetStrength() (0-100)   -> %d\n",
1139     // ActiveParams.VirtualizerReverbLevel*10);
1140     return pContext->pBundledContext->VirtStrengthSaved;
1141 } /* end getStrength */
1142 
1143 //----------------------------------------------------------------------------
1144 // VirtualizerSetStrength()
1145 //----------------------------------------------------------------------------
1146 // Purpose:
1147 // Apply the strength to the Virtualizer. Must first be converted from the range 0-1000 to 1-15
1148 //
1149 // Inputs:
1150 //  pContext:   effect engine context
1151 //  strength    strength to be applied
1152 //
1153 //----------------------------------------------------------------------------
1154 
VirtualizerSetStrength(EffectContext * pContext,uint32_t strength)1155 void VirtualizerSetStrength(EffectContext* pContext, uint32_t strength) {
1156     // ALOGV("\tVirtualizerSetStrength(%d)", strength);
1157     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
1158     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
1159 
1160     pContext->pBundledContext->VirtStrengthSaved = (int)strength;
1161 
1162     /* Get the current settings */
1163     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1164 
1165     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VirtualizerSetStrength")
1166     // ALOGV("\tVirtualizerSetStrength Successfully returned from LVM_GetControlParameters\n");
1167 
1168     /* Virtualizer parameters */
1169     ActiveParams.CS_EffectLevel = (int)((strength * 32767) / 1000);
1170 
1171     ALOGV("\tVirtualizerSetStrength() (0-1000)   -> %d\n", strength);
1172     ALOGV("\tVirtualizerSetStrength() (0- 100)   -> %d\n", ActiveParams.CS_EffectLevel);
1173 
1174     /* Activate the initial settings */
1175     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1176     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VirtualizerSetStrength")
1177     // ALOGV("\tVirtualizerSetStrength Successfully called LVM_SetControlParameters\n\n");
1178     LvmEffect_limitLevel(pContext);
1179 } /* end setStrength */
1180 
1181 //----------------------------------------------------------------------------
1182 // VirtualizerIsDeviceSupported()
1183 //----------------------------------------------------------------------------
1184 // Purpose:
1185 // Check if an audio device type is supported by this implementation
1186 //
1187 // Inputs:
1188 //  deviceType   the type of device that affects the processing (e.g. for binaural vs transaural)
1189 // Output:
1190 //  -EINVAL      if the configuration is not supported or it is unknown
1191 //  0            if the configuration is supported
1192 //----------------------------------------------------------------------------
VirtualizerIsDeviceSupported(audio_devices_t deviceType)1193 int VirtualizerIsDeviceSupported(audio_devices_t deviceType) {
1194     switch (deviceType) {
1195         case AUDIO_DEVICE_OUT_WIRED_HEADSET:
1196         case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
1197         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
1198         case AUDIO_DEVICE_OUT_USB_HEADSET:
1199             // case AUDIO_DEVICE_OUT_USB_DEVICE:  // For USB testing of the virtualizer only.
1200             return 0;
1201         default:
1202             return -EINVAL;
1203     }
1204 }
1205 
1206 //----------------------------------------------------------------------------
1207 // VirtualizerIsConfigurationSupported()
1208 //----------------------------------------------------------------------------
1209 // Purpose:
1210 // Check if a channel mask + audio device type is supported by this implementation
1211 //
1212 // Inputs:
1213 //  channelMask  the channel mask of the input to virtualize
1214 //  deviceType   the type of device that affects the processing (e.g. for binaural vs transaural)
1215 // Output:
1216 //  -EINVAL      if the configuration is not supported or it is unknown
1217 //  0            if the configuration is supported
1218 //----------------------------------------------------------------------------
VirtualizerIsConfigurationSupported(audio_channel_mask_t channelMask,audio_devices_t deviceType)1219 int VirtualizerIsConfigurationSupported(audio_channel_mask_t channelMask,
1220                                         audio_devices_t deviceType) {
1221     uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1222     if (channelCount < 1 || channelCount > FCC_2) {  // TODO: update to 8 channels when supported.
1223         return -EINVAL;
1224     }
1225     return VirtualizerIsDeviceSupported(deviceType);
1226 }
1227 
1228 //----------------------------------------------------------------------------
1229 // VirtualizerForceVirtualizationMode()
1230 //----------------------------------------------------------------------------
1231 // Purpose:
1232 // Force the virtualization mode to that of the given audio device
1233 //
1234 // Inputs:
1235 //  pContext     effect engine context
1236 //  forcedDevice the type of device whose virtualization mode we'll always use
1237 // Output:
1238 //  -EINVAL      if the device is not supported or is unknown
1239 //  0            if the device is supported and the virtualization mode forced
1240 //
1241 //----------------------------------------------------------------------------
VirtualizerForceVirtualizationMode(EffectContext * pContext,audio_devices_t forcedDevice)1242 int VirtualizerForceVirtualizationMode(EffectContext* pContext, audio_devices_t forcedDevice) {
1243     ALOGV("VirtualizerForceVirtualizationMode: forcedDev=0x%x enabled=%d tmpDisabled=%d",
1244           forcedDevice, pContext->pBundledContext->bVirtualizerEnabled,
1245           pContext->pBundledContext->bVirtualizerTempDisabled);
1246     int status = 0;
1247     bool useVirtualizer = false;
1248 
1249     if (VirtualizerIsDeviceSupported(forcedDevice) != 0) {
1250         if (forcedDevice != AUDIO_DEVICE_NONE) {
1251             // forced device is not supported, make it behave as a reset of forced mode
1252             forcedDevice = AUDIO_DEVICE_NONE;
1253             // but return an error
1254             status = -EINVAL;
1255         }
1256     }
1257 
1258     if (forcedDevice == AUDIO_DEVICE_NONE) {
1259         // disabling forced virtualization mode:
1260         // verify whether the virtualization should be enabled or disabled
1261         if (VirtualizerIsDeviceSupported(pContext->pBundledContext->nOutputDevice) == 0) {
1262             useVirtualizer = (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE);
1263         }
1264         pContext->pBundledContext->nVirtualizerForcedDevice = AUDIO_DEVICE_NONE;
1265     } else {
1266         // forcing virtualization mode: here we already know the device is supported
1267         pContext->pBundledContext->nVirtualizerForcedDevice = AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
1268         // only enable for a supported mode, when the effect is enabled
1269         useVirtualizer = (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE);
1270     }
1271 
1272     if (useVirtualizer) {
1273         if (pContext->pBundledContext->bVirtualizerTempDisabled == LVM_TRUE) {
1274             ALOGV("\tVirtualizerForceVirtualizationMode re-enable LVM_VIRTUALIZER");
1275             android::LvmEffect_enable(pContext);
1276             pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE;
1277         } else {
1278             ALOGV("\tVirtualizerForceVirtualizationMode leaving LVM_VIRTUALIZER enabled");
1279         }
1280     } else {
1281         if (pContext->pBundledContext->bVirtualizerTempDisabled == LVM_FALSE) {
1282             ALOGV("\tVirtualizerForceVirtualizationMode disable LVM_VIRTUALIZER");
1283             android::LvmEffect_disable(pContext);
1284             pContext->pBundledContext->bVirtualizerTempDisabled = LVM_TRUE;
1285         } else {
1286             ALOGV("\tVirtualizerForceVirtualizationMode leaving LVM_VIRTUALIZER disabled");
1287         }
1288     }
1289 
1290     ALOGV("\tafter VirtualizerForceVirtualizationMode: enabled=%d tmpDisabled=%d",
1291           pContext->pBundledContext->bVirtualizerEnabled,
1292           pContext->pBundledContext->bVirtualizerTempDisabled);
1293 
1294     return status;
1295 }
1296 //----------------------------------------------------------------------------
1297 // VirtualizerGetSpeakerAngles()
1298 //----------------------------------------------------------------------------
1299 // Purpose:
1300 // Get the virtual speaker angles for a channel mask + audio device type
1301 // configuration which is guaranteed to be supported by this implementation
1302 //
1303 // Inputs:
1304 //  channelMask:   the channel mask of the input to virtualize
1305 //  deviceType     the type of device that affects the processing (e.g. for binaural vs transaural)
1306 // Input/Output:
1307 //  pSpeakerAngles the array of integer where each speaker angle is written as a triplet in the
1308 //                 following format:
1309 //                    int32_t a bit mask with a single value selected for each speaker, following
1310 //                            the convention of the audio_channel_mask_t type
1311 //                    int32_t a value in degrees expressing the speaker azimuth, where 0 is in front
1312 //                            of the user, 180 behind, -90 to the left, 90 to the right of the user
1313 //                    int32_t a value in degrees expressing the speaker elevation, where 0 is the
1314 //                            horizontal plane, +90 is directly above the user, -90 below
1315 //
1316 //----------------------------------------------------------------------------
VirtualizerGetSpeakerAngles(audio_channel_mask_t channelMask,audio_devices_t,int32_t * pSpeakerAngles)1317 void VirtualizerGetSpeakerAngles(audio_channel_mask_t channelMask,
1318                                  audio_devices_t /* deviceType __unused */,
1319                                  int32_t* pSpeakerAngles) {
1320     // the channel count is guaranteed to be 1 or 2
1321     // the device is guaranteed to be of type headphone
1322     // this virtualizer is always using 2 virtual speakers at -90 and 90deg of azimuth, 0deg of
1323     // elevation but the return information is sized for nbChannels * 3, so we have to consider
1324     // the (false here) case of a single channel, and return only 3 fields.
1325     if (audio_channel_count_from_out_mask(channelMask) == 1) {
1326         *pSpeakerAngles++ = (int32_t)AUDIO_CHANNEL_OUT_MONO;  // same as FRONT_LEFT
1327         *pSpeakerAngles++ = 0;                                // azimuth
1328         *pSpeakerAngles = 0;                                  // elevation
1329     } else {
1330         *pSpeakerAngles++ = (int32_t)AUDIO_CHANNEL_OUT_FRONT_LEFT;
1331         *pSpeakerAngles++ = -90;  // azimuth
1332         *pSpeakerAngles++ = 0;    // elevation
1333         *pSpeakerAngles++ = (int32_t)AUDIO_CHANNEL_OUT_FRONT_RIGHT;
1334         *pSpeakerAngles++ = 90;  // azimuth
1335         *pSpeakerAngles = 0;     // elevation
1336     }
1337 }
1338 
1339 //----------------------------------------------------------------------------
1340 // VirtualizerGetVirtualizationMode()
1341 //----------------------------------------------------------------------------
1342 // Purpose:
1343 // Retrieve the current device whose processing mode is used by this effect
1344 //
1345 // Output:
1346 //   AUDIO_DEVICE_NONE if the effect is not virtualizing
1347 //   or the device type if the effect is virtualizing
1348 //----------------------------------------------------------------------------
VirtualizerGetVirtualizationMode(EffectContext * pContext)1349 audio_devices_t VirtualizerGetVirtualizationMode(EffectContext* pContext) {
1350     audio_devices_t virtDevice = AUDIO_DEVICE_NONE;
1351     if ((pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) &&
1352         (pContext->pBundledContext->bVirtualizerTempDisabled == LVM_FALSE)) {
1353         if (pContext->pBundledContext->nVirtualizerForcedDevice != AUDIO_DEVICE_NONE) {
1354             // virtualization mode is forced, return that device
1355             virtDevice = pContext->pBundledContext->nVirtualizerForcedDevice;
1356         } else {
1357             // no forced mode, return the current device
1358             virtDevice = pContext->pBundledContext->nOutputDevice;
1359         }
1360     }
1361     ALOGV("VirtualizerGetVirtualizationMode() returning 0x%x", virtDevice);
1362     return virtDevice;
1363 }
1364 
1365 //----------------------------------------------------------------------------
1366 // EqualizerGetBandLevel()
1367 //----------------------------------------------------------------------------
1368 // Purpose: Retrieve the gain currently being used for the band passed in
1369 //
1370 // Inputs:
1371 //  band:       band number
1372 //  pContext:   effect engine context
1373 //
1374 // Outputs:
1375 //
1376 //----------------------------------------------------------------------------
EqualizerGetBandLevel(EffectContext * pContext,int32_t band)1377 int32_t EqualizerGetBandLevel(EffectContext* pContext, int32_t band) {
1378     // ALOGV("\tEqualizerGetBandLevel -> %d\n", pContext->pBundledContext->bandGaindB[band] );
1379     return pContext->pBundledContext->bandGaindB[band] * 100;
1380 }
1381 
1382 //----------------------------------------------------------------------------
1383 // EqualizerSetBandLevel()
1384 //----------------------------------------------------------------------------
1385 // Purpose:
1386 //  Sets gain value for the given band.
1387 //
1388 // Inputs:
1389 //  band:       band number
1390 //  Gain:       Gain to be applied in millibels
1391 //  pContext:   effect engine context
1392 //
1393 // Outputs:
1394 //
1395 //---------------------------------------------------------------------------
EqualizerSetBandLevel(EffectContext * pContext,int band,short Gain)1396 void EqualizerSetBandLevel(EffectContext* pContext, int band, short Gain) {
1397     int gainRounded;
1398     if (Gain > 0) {
1399         gainRounded = (int)((Gain + 50) / 100);
1400     } else {
1401         gainRounded = (int)((Gain - 50) / 100);
1402     }
1403     // ALOGV("\tEqualizerSetBandLevel(%d)->(%d)", Gain, gainRounded);
1404     pContext->pBundledContext->bandGaindB[band] = gainRounded;
1405     pContext->pBundledContext->CurPreset = PRESET_CUSTOM;
1406 
1407     EqualizerUpdateActiveParams(pContext);
1408     LvmEffect_limitLevel(pContext);
1409 }
1410 
1411 //----------------------------------------------------------------------------
1412 // EqualizerGetCentreFrequency()
1413 //----------------------------------------------------------------------------
1414 // Purpose: Retrieve the frequency being used for the band passed in
1415 //
1416 // Inputs:
1417 //  band:       band number
1418 //  pContext:   effect engine context
1419 //
1420 // Outputs:
1421 //
1422 //----------------------------------------------------------------------------
EqualizerGetCentreFrequency(EffectContext * pContext,int32_t band)1423 int32_t EqualizerGetCentreFrequency(EffectContext* pContext, int32_t band) {
1424     int32_t Frequency = 0;
1425 
1426     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
1427     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
1428     LVM_EQNB_BandDef_t* BandDef;
1429     /* Get the current settings */
1430     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1431 
1432     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "EqualizerGetCentreFrequency")
1433 
1434     BandDef = ActiveParams.pEQNB_BandDefinition;
1435     Frequency = (int32_t)BandDef[band].Frequency * 1000;  // Convert to millibels
1436 
1437     // ALOGV("\tEqualizerGetCentreFrequency -> %d\n", Frequency );
1438     // ALOGV("\tEqualizerGetCentreFrequency Successfully returned from LVM_GetControlParameters\n");
1439     return Frequency;
1440 }
1441 
1442 //----------------------------------------------------------------------------
1443 // EqualizerGetBandFreqRange(
1444 //----------------------------------------------------------------------------
1445 // Purpose:
1446 //
1447 // Gets lower and upper boundaries of a band.
1448 // For the high shelf, the low bound is the band frequency and the high
1449 // bound is Nyquist.
1450 // For the peaking filters, they are the gain[dB]/2 points.
1451 //
1452 // Inputs:
1453 //  band:       band number
1454 //  pContext:   effect engine context
1455 //
1456 // Outputs:
1457 //  pLow:       lower band range
1458 //  pLow:       upper band range
1459 //----------------------------------------------------------------------------
EqualizerGetBandFreqRange(EffectContext *,int32_t band,uint32_t * pLow,uint32_t * pHi)1460 int32_t EqualizerGetBandFreqRange(EffectContext* /* pContext __unused */, int32_t band,
1461                                   uint32_t* pLow, uint32_t* pHi) {
1462     *pLow = bandFreqRange[band][0];
1463     *pHi = bandFreqRange[band][1];
1464     return 0;
1465 }
1466 
1467 //----------------------------------------------------------------------------
1468 // EqualizerGetBand(
1469 //----------------------------------------------------------------------------
1470 // Purpose:
1471 //
1472 // Returns the band with the maximum influence on a given frequency.
1473 // Result is unaffected by whether EQ is enabled or not, or by whether
1474 // changes have been committed or not.
1475 //
1476 // Inputs:
1477 //  targetFreq   The target frequency, in millihertz.
1478 //  pContext:    effect engine context
1479 //
1480 // Outputs:
1481 //  pLow:       lower band range
1482 //  pLow:       upper band range
1483 //----------------------------------------------------------------------------
EqualizerGetBand(EffectContext *,uint32_t targetFreq)1484 int32_t EqualizerGetBand(EffectContext* /* pContext __unused */, uint32_t targetFreq) {
1485     int band = 0;
1486 
1487     if (targetFreq < bandFreqRange[0][0]) {
1488         return -EINVAL;
1489     } else if (targetFreq == bandFreqRange[0][0]) {
1490         return 0;
1491     }
1492     for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
1493         if ((targetFreq > bandFreqRange[i][0]) && (targetFreq <= bandFreqRange[i][1])) {
1494             band = i;
1495         }
1496     }
1497     return band;
1498 }
1499 
1500 //----------------------------------------------------------------------------
1501 // EqualizerGetPreset(
1502 //----------------------------------------------------------------------------
1503 // Purpose:
1504 //
1505 // Gets the currently set preset ID.
1506 // Will return PRESET_CUSTOM in case the EQ parameters have been modified
1507 // manually since a preset was set.
1508 //
1509 // Inputs:
1510 //  pContext:    effect engine context
1511 //
1512 //----------------------------------------------------------------------------
EqualizerGetPreset(EffectContext * pContext)1513 int32_t EqualizerGetPreset(EffectContext* pContext) {
1514     return pContext->pBundledContext->CurPreset;
1515 }
1516 
1517 //----------------------------------------------------------------------------
1518 // EqualizerSetPreset(
1519 //----------------------------------------------------------------------------
1520 // Purpose:
1521 //
1522 // Sets the current preset by ID.
1523 // All the band parameters will be overridden.
1524 //
1525 // Inputs:
1526 //  pContext:    effect engine context
1527 //  preset       The preset ID.
1528 //
1529 //----------------------------------------------------------------------------
EqualizerSetPreset(EffectContext * pContext,int preset)1530 void EqualizerSetPreset(EffectContext* pContext, int preset) {
1531     // ALOGV("\tEqualizerSetPreset(%d)", preset);
1532     pContext->pBundledContext->CurPreset = preset;
1533 
1534     // ActiveParams.pEQNB_BandDefinition = &BandDefs[0];
1535     for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
1536         pContext->pBundledContext->bandGaindB[i] =
1537                 EQNB_5BandSoftPresets[i + preset * FIVEBAND_NUMBANDS];
1538     }
1539 
1540     EqualizerUpdateActiveParams(pContext);
1541     LvmEffect_limitLevel(pContext);
1542 
1543     // ALOGV("\tEqualizerSetPreset Successfully called LVM_SetControlParameters\n");
1544     return;
1545 }
1546 
EqualizerGetNumPresets()1547 int32_t EqualizerGetNumPresets() {
1548     return sizeof(gEqualizerPresets) / sizeof(PresetConfig);
1549 }
1550 
1551 //----------------------------------------------------------------------------
1552 // EqualizerGetPresetName(
1553 //----------------------------------------------------------------------------
1554 // Purpose:
1555 // Gets a human-readable name for a preset ID. Will return "Custom" if
1556 // PRESET_CUSTOM is passed.
1557 //
1558 // Inputs:
1559 // preset       The preset ID. Must be less than number of presets.
1560 //
1561 //-------------------------------------------------------------------------
EqualizerGetPresetName(int32_t preset)1562 const char* EqualizerGetPresetName(int32_t preset) {
1563     // ALOGV("\tEqualizerGetPresetName start(%d)", preset);
1564     if (preset == PRESET_CUSTOM) {
1565         return "Custom";
1566     } else {
1567         return gEqualizerPresets[preset].name;
1568     }
1569     // ALOGV("\tEqualizerGetPresetName end(%d)", preset);
1570     return 0;
1571 }
1572 
1573 //----------------------------------------------------------------------------
1574 // VolumeSetVolumeLevel()
1575 //----------------------------------------------------------------------------
1576 // Purpose:
1577 //
1578 // Inputs:
1579 //  pContext:   effect engine context
1580 //  level       level to be applied
1581 //
1582 //----------------------------------------------------------------------------
1583 
VolumeSetVolumeLevel(EffectContext * pContext,int16_t level)1584 int VolumeSetVolumeLevel(EffectContext* pContext, int16_t level) {
1585     if (level > 0 || level < -9600) {
1586         return -EINVAL;
1587     }
1588 
1589     if (pContext->pBundledContext->bMuteEnabled == LVM_TRUE) {
1590         pContext->pBundledContext->levelSaved = level / 100;
1591     } else {
1592         pContext->pBundledContext->volume = level / 100;
1593     }
1594 
1595     LvmEffect_limitLevel(pContext);
1596 
1597     return 0;
1598 } /* end VolumeSetVolumeLevel */
1599 
1600 //----------------------------------------------------------------------------
1601 // VolumeGetVolumeLevel()
1602 //----------------------------------------------------------------------------
1603 // Purpose:
1604 //
1605 // Inputs:
1606 //  pContext:   effect engine context
1607 //
1608 //----------------------------------------------------------------------------
1609 
VolumeGetVolumeLevel(EffectContext * pContext,int16_t * level)1610 int VolumeGetVolumeLevel(EffectContext* pContext, int16_t* level) {
1611     if (pContext->pBundledContext->bMuteEnabled == LVM_TRUE) {
1612         *level = pContext->pBundledContext->levelSaved * 100;
1613     } else {
1614         *level = pContext->pBundledContext->volume * 100;
1615     }
1616     return 0;
1617 } /* end VolumeGetVolumeLevel */
1618 
1619 //----------------------------------------------------------------------------
1620 // VolumeSetMute()
1621 //----------------------------------------------------------------------------
1622 // Purpose:
1623 //
1624 // Inputs:
1625 //  pContext:   effect engine context
1626 //  mute:       enable/disable flag
1627 //
1628 //----------------------------------------------------------------------------
1629 
VolumeSetMute(EffectContext * pContext,uint32_t mute)1630 int32_t VolumeSetMute(EffectContext* pContext, uint32_t mute) {
1631     // ALOGV("\tVolumeSetMute start(%d)", mute);
1632 
1633     pContext->pBundledContext->bMuteEnabled = mute;
1634 
1635     /* Set appropriate volume level */
1636     if (pContext->pBundledContext->bMuteEnabled == LVM_TRUE) {
1637         pContext->pBundledContext->levelSaved = pContext->pBundledContext->volume;
1638         pContext->pBundledContext->volume = -96;
1639     } else {
1640         pContext->pBundledContext->volume = pContext->pBundledContext->levelSaved;
1641     }
1642 
1643     LvmEffect_limitLevel(pContext);
1644 
1645     return 0;
1646 } /* end setMute */
1647 
1648 //----------------------------------------------------------------------------
1649 // VolumeGetMute()
1650 //----------------------------------------------------------------------------
1651 // Purpose:
1652 //
1653 // Inputs:
1654 //  pContext:   effect engine context
1655 //
1656 // Ourputs:
1657 //  mute:       enable/disable flag
1658 //----------------------------------------------------------------------------
1659 
VolumeGetMute(EffectContext * pContext,uint32_t * mute)1660 int32_t VolumeGetMute(EffectContext* pContext, uint32_t* mute) {
1661     // ALOGV("\tVolumeGetMute start");
1662     if ((pContext->pBundledContext->bMuteEnabled == LVM_FALSE) ||
1663         (pContext->pBundledContext->bMuteEnabled == LVM_TRUE)) {
1664         *mute = pContext->pBundledContext->bMuteEnabled;
1665         return 0;
1666     } else {
1667         ALOGV("\tLVM_ERROR : VolumeGetMute read an invalid value from context %d",
1668               pContext->pBundledContext->bMuteEnabled);
1669         return -EINVAL;
1670     }
1671     // ALOGV("\tVolumeGetMute end");
1672 } /* end getMute */
1673 
VolumeConvertStereoPosition(int16_t position)1674 int16_t VolumeConvertStereoPosition(int16_t position) {
1675     int16_t convertedPosition = 0;
1676 
1677     convertedPosition = (int16_t)(((float)position / 1000) * 96);
1678     return convertedPosition;
1679 }
1680 
1681 //----------------------------------------------------------------------------
1682 // VolumeSetStereoPosition()
1683 //----------------------------------------------------------------------------
1684 // Purpose:
1685 //
1686 // Inputs:
1687 //  pContext:       effect engine context
1688 //  position:       stereo position
1689 //
1690 // Outputs:
1691 //----------------------------------------------------------------------------
1692 
VolumeSetStereoPosition(EffectContext * pContext,int16_t position)1693 int VolumeSetStereoPosition(EffectContext* pContext, int16_t position) {
1694     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
1695     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
1696     LVM_INT16 Balance = 0;
1697 
1698     pContext->pBundledContext->positionSaved = position;
1699     Balance = VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved);
1700 
1701     // ALOGV("\tVolumeSetStereoPosition start pContext->pBundledContext->positionSaved = %d",
1702     // pContext->pBundledContext->positionSaved);
1703 
1704     if (pContext->pBundledContext->bStereoPositionEnabled == LVM_TRUE) {
1705         // ALOGV("\tVolumeSetStereoPosition Position to be set is %d %d\n", position, Balance);
1706         pContext->pBundledContext->positionSaved = position;
1707         /* Get the current settings */
1708         LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1709         LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeSetStereoPosition")
1710         if (LvmStatus != LVM_SUCCESS) return -EINVAL;
1711         // ALOGV("\tVolumeSetStereoPosition Successfully returned from LVM_GetControlParameters
1712         // got:"
1713         //     " %d\n", ActiveParams.VC_Balance);
1714 
1715         /* Volume parameters */
1716         ActiveParams.VC_Balance = Balance;
1717         // ALOGV("\tVolumeSetStereoPosition() (-96dB -> +96dB)   -> %d\n", ActiveParams.VC_Balance
1718         // );
1719 
1720         /* Activate the initial settings */
1721         LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1722         LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VolumeSetStereoPosition")
1723         if (LvmStatus != LVM_SUCCESS) return -EINVAL;
1724 
1725         // ALOGV("\tVolumeSetStereoPosition Successfully called LVM_SetControlParameters\n");
1726 
1727         /* Get the current settings */
1728         LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1729         LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeSetStereoPosition")
1730         if (LvmStatus != LVM_SUCCESS) return -EINVAL;
1731         // ALOGV("\tVolumeSetStereoPosition Successfully returned from LVM_GetControlParameters got:
1732         // "
1733         //     "%d\n", ActiveParams.VC_Balance);
1734     } else {
1735         // ALOGV("\tVolumeSetStereoPosition Position attempting to set, but not enabled %d %d\n",
1736         // position, Balance);
1737     }
1738     // ALOGV("\tVolumeSetStereoPosition end pContext->pBundledContext->positionSaved = %d\n",
1739     // pContext->pBundledContext->positionSaved);
1740     return 0;
1741 } /* end VolumeSetStereoPosition */
1742 
1743 //----------------------------------------------------------------------------
1744 // VolumeGetStereoPosition()
1745 //----------------------------------------------------------------------------
1746 // Purpose:
1747 //
1748 // Inputs:
1749 //  pContext:       effect engine context
1750 //
1751 // Outputs:
1752 //  position:       stereo position
1753 //----------------------------------------------------------------------------
1754 
VolumeGetStereoPosition(EffectContext * pContext,int16_t * position)1755 int32_t VolumeGetStereoPosition(EffectContext* pContext, int16_t* position) {
1756     // ALOGV("\tVolumeGetStereoPosition start");
1757 
1758     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
1759     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
1760     LVM_INT16 balance;
1761 
1762     // ALOGV("\tVolumeGetStereoPosition start pContext->pBundledContext->positionSaved = %d",
1763     // pContext->pBundledContext->positionSaved);
1764 
1765     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1766     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeGetStereoPosition")
1767     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
1768 
1769     // ALOGV("\tVolumeGetStereoPosition -> %d\n", ActiveParams.VC_Balance);
1770     // ALOGV("\tVolumeGetStereoPosition Successfully returned from LVM_GetControlParameters\n");
1771 
1772     balance = VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved);
1773 
1774     if (pContext->pBundledContext->bStereoPositionEnabled == LVM_TRUE) {
1775         if (balance != ActiveParams.VC_Balance) {
1776             return -EINVAL;
1777         }
1778     }
1779     *position = (LVM_INT16)pContext->pBundledContext->positionSaved;  // Convert dB to millibels
1780     // ALOGV("\tVolumeGetStereoPosition end returning pContext->pBundledContext->positionSaved
1781     // =%d\n", pContext->pBundledContext->positionSaved);
1782     return 0;
1783 } /* end VolumeGetStereoPosition */
1784 
1785 //----------------------------------------------------------------------------
1786 // VolumeEnableStereoPosition()
1787 //----------------------------------------------------------------------------
1788 // Purpose:
1789 //
1790 // Inputs:
1791 //  pContext:   effect engine context
1792 //  mute:       enable/disable flag
1793 //
1794 //----------------------------------------------------------------------------
1795 
VolumeEnableStereoPosition(EffectContext * pContext,uint32_t enabled)1796 int32_t VolumeEnableStereoPosition(EffectContext* pContext, uint32_t enabled) {
1797     // ALOGV("\tVolumeEnableStereoPosition start()");
1798 
1799     pContext->pBundledContext->bStereoPositionEnabled = enabled;
1800 
1801     LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
1802     LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
1803 
1804     /* Get the current settings */
1805     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1806     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeEnableStereoPosition")
1807     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
1808 
1809     // ALOGV("\tVolumeEnableStereoPosition Successfully returned from LVM_GetControlParameters\n");
1810     // ALOGV("\tVolumeEnableStereoPosition to %d, position was %d\n",
1811     //     enabled, ActiveParams.VC_Balance );
1812 
1813     /* Set appropriate stereo position */
1814     if (pContext->pBundledContext->bStereoPositionEnabled == LVM_FALSE) {
1815         ActiveParams.VC_Balance = 0;
1816     } else {
1817         ActiveParams.VC_Balance =
1818                 VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved);
1819     }
1820 
1821     /* Activate the initial settings */
1822     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
1823     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VolumeEnableStereoPosition")
1824     if (LvmStatus != LVM_SUCCESS) return -EINVAL;
1825 
1826     // ALOGV("\tVolumeEnableStereoPosition Successfully called LVM_SetControlParameters\n");
1827     // ALOGV("\tVolumeEnableStereoPosition end()\n");
1828     return 0;
1829 } /* end VolumeEnableStereoPosition */
1830 
1831 //----------------------------------------------------------------------------
1832 // BassBoost_getParameter()
1833 //----------------------------------------------------------------------------
1834 // Purpose:
1835 // Get a BassBoost parameter
1836 //
1837 // Inputs:
1838 //  pBassBoost       - handle to instance data
1839 //  pParam           - pointer to parameter
1840 //  pValue           - pointer to variable to hold retrieved value
1841 //  pValueSize       - pointer to value size: maximum size as input
1842 //
1843 // Outputs:
1844 //  *pValue updated with parameter value
1845 //  *pValueSize updated with actual value size
1846 //
1847 //
1848 // Side Effects:
1849 //
1850 //----------------------------------------------------------------------------
1851 
BassBoost_getParameter(EffectContext * pContext,uint32_t paramSize,void * pParam,uint32_t * pValueSize,void * pValue)1852 int BassBoost_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
1853                            uint32_t* pValueSize, void* pValue) {
1854     int status = 0;
1855     int32_t* params = (int32_t*)pParam;
1856 
1857     ALOGVV("%s start", __func__);
1858 
1859     if (paramSize < sizeof(int32_t)) {
1860         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
1861         return -EINVAL;
1862     }
1863     switch (params[0]) {
1864         case BASSBOOST_PARAM_STRENGTH_SUPPORTED:
1865             if (*pValueSize != sizeof(uint32_t)) {  // legacy: check equality here.
1866                 ALOGV("%s BASSBOOST_PARAM_STRENGTH_SUPPORTED invalid *pValueSize %u", __func__,
1867                       *pValueSize);
1868                 status = -EINVAL;
1869                 break;
1870             }
1871             // no need to set *pValueSize
1872 
1873             *(uint32_t*)pValue = 1;
1874             ALOGVV("%s BASSBOOST_PARAM_STRENGTH_SUPPORTED %u", __func__, *(uint32_t*)pValue);
1875             break;
1876 
1877         case BASSBOOST_PARAM_STRENGTH:
1878             if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
1879                 ALOGV("%s BASSBOOST_PARAM_STRENGTH invalid *pValueSize %u", __func__, *pValueSize);
1880                 status = -EINVAL;
1881                 break;
1882             }
1883             // no need to set *pValueSize
1884 
1885             *(int16_t*)pValue = BassGetStrength(pContext);
1886             ALOGVV("%s BASSBOOST_PARAM_STRENGTH %d", __func__, *(int16_t*)pValue);
1887             break;
1888 
1889         default:
1890             ALOGV("%s invalid param %d", __func__, params[0]);
1891             status = -EINVAL;
1892             break;
1893     }
1894 
1895     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
1896     return status;
1897 } /* end BassBoost_getParameter */
1898 
1899 //----------------------------------------------------------------------------
1900 // BassBoost_setParameter()
1901 //----------------------------------------------------------------------------
1902 // Purpose:
1903 // Set a BassBoost parameter
1904 //
1905 // Inputs:
1906 //  pBassBoost       - handle to instance data
1907 //  pParam           - pointer to parameter
1908 //  pValue           - pointer to value
1909 //
1910 // Outputs:
1911 //
1912 //----------------------------------------------------------------------------
1913 
BassBoost_setParameter(EffectContext * pContext,uint32_t paramSize,void * pParam,uint32_t valueSize,void * pValue)1914 int BassBoost_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
1915                            uint32_t valueSize, void* pValue) {
1916     int status = 0;
1917     int32_t* params = (int32_t*)pParam;
1918 
1919     ALOGVV("%s start", __func__);
1920 
1921     if (paramSize != sizeof(int32_t)) {  // legacy: check equality here.
1922         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
1923         return -EINVAL;
1924     }
1925     switch (params[0]) {
1926         case BASSBOOST_PARAM_STRENGTH: {
1927             if (valueSize < sizeof(int16_t)) {
1928                 ALOGV("%s BASSBOOST_PARAM_STRENGTH invalid valueSize: %u", __func__, valueSize);
1929                 status = -EINVAL;
1930                 break;
1931             }
1932 
1933             const int16_t strength = *(int16_t*)pValue;
1934             ALOGVV("%s BASSBOOST_PARAM_STRENGTH %d", __func__, strength);
1935             ALOGVV("%s BASSBOOST_PARAM_STRENGTH Calling BassSetStrength", __func__);
1936             BassSetStrength(pContext, (int32_t)strength);
1937             ALOGVV("%s BASSBOOST_PARAM_STRENGTH Called BassSetStrength", __func__);
1938         } break;
1939 
1940         default:
1941             ALOGV("%s invalid param %d", __func__, params[0]);
1942             status = -EINVAL;
1943             break;
1944     }
1945 
1946     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
1947     return status;
1948 } /* end BassBoost_setParameter */
1949 
1950 //----------------------------------------------------------------------------
1951 // Virtualizer_getParameter()
1952 //----------------------------------------------------------------------------
1953 // Purpose:
1954 // Get a Virtualizer parameter
1955 //
1956 // Inputs:
1957 //  pVirtualizer     - handle to instance data
1958 //  pParam           - pointer to parameter
1959 //  pValue           - pointer to variable to hold retrieved value
1960 //  pValueSize       - pointer to value size: maximum size as input
1961 //
1962 // Outputs:
1963 //  *pValue updated with parameter value
1964 //  *pValueSize updated with actual value size
1965 //
1966 //
1967 // Side Effects:
1968 //
1969 //----------------------------------------------------------------------------
1970 
Virtualizer_getParameter(EffectContext * pContext,uint32_t paramSize,void * pParam,uint32_t * pValueSize,void * pValue)1971 int Virtualizer_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
1972                              uint32_t* pValueSize, void* pValue) {
1973     int status = 0;
1974     int32_t* params = (int32_t*)pParam;
1975 
1976     ALOGVV("%s start", __func__);
1977 
1978     if (paramSize < sizeof(int32_t)) {
1979         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
1980         return -EINVAL;
1981     }
1982     switch (params[0]) {
1983         case VIRTUALIZER_PARAM_STRENGTH_SUPPORTED:
1984             if (*pValueSize != sizeof(uint32_t)) {  // legacy: check equality here.
1985                 ALOGV("%s VIRTUALIZER_PARAM_STRENGTH_SUPPORTED invalid *pValueSize %u", __func__,
1986                       *pValueSize);
1987                 status = -EINVAL;
1988                 break;
1989             }
1990             // no need to set *pValueSize
1991 
1992             *(uint32_t*)pValue = 1;
1993             ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH_SUPPORTED %d", __func__, *(uint32_t*)pValue);
1994             break;
1995 
1996         case VIRTUALIZER_PARAM_STRENGTH:
1997             if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
1998                 ALOGV("%s VIRTUALIZER_PARAM_STRENGTH invalid *pValueSize %u", __func__,
1999                       *pValueSize);
2000                 status = -EINVAL;
2001                 break;
2002             }
2003             // no need to set *pValueSize
2004 
2005             *(int16_t*)pValue = VirtualizerGetStrength(pContext);
2006 
2007             ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH %d", __func__, *(int16_t*)pValue);
2008             break;
2009 
2010         case VIRTUALIZER_PARAM_VIRTUAL_SPEAKER_ANGLES: {
2011             if (paramSize < 3 * sizeof(int32_t)) {
2012                 ALOGV("%s VIRTUALIZER_PARAM_SPEAKER_ANGLES invalid paramSize: %u", __func__,
2013                       paramSize);
2014                 status = -EINVAL;
2015                 break;
2016             }
2017 
2018             const audio_channel_mask_t channelMask = (audio_channel_mask_t)params[1];
2019             const audio_devices_t deviceType = (audio_devices_t)params[2];
2020             const uint32_t nbChannels = audio_channel_count_from_out_mask(channelMask);
2021             const uint32_t valueSizeRequired = 3 * nbChannels * sizeof(int32_t);
2022             if (*pValueSize < valueSizeRequired) {
2023                 ALOGV("%s VIRTUALIZER_PARAM_SPEAKER_ANGLES invalid *pValueSize %u", __func__,
2024                       *pValueSize);
2025                 status = -EINVAL;
2026                 break;
2027             }
2028             *pValueSize = valueSizeRequired;
2029 
2030             // verify the configuration is supported
2031             status = VirtualizerIsConfigurationSupported(channelMask, deviceType);
2032             if (status == 0) {
2033                 ALOGV("%s VIRTUALIZER_PARAM_VIRTUAL_SPEAKER_ANGLES mask=0x%x device=0x%x", __func__,
2034                       channelMask, deviceType);
2035                 // configuration is supported, get the angles
2036                 VirtualizerGetSpeakerAngles(channelMask, deviceType, (int32_t*)pValue);
2037             }
2038         } break;
2039 
2040         case VIRTUALIZER_PARAM_VIRTUALIZATION_MODE:
2041             if (*pValueSize != sizeof(uint32_t)) {  // legacy: check equality here.
2042                 ALOGV("%s VIRTUALIZER_PARAM_VIRTUALIZATION_MODE invalid *pValueSize %u", __func__,
2043                       *pValueSize);
2044                 status = -EINVAL;
2045                 break;
2046             }
2047             // no need to set *pValueSize
2048 
2049             *(uint32_t*)pValue = (uint32_t)VirtualizerGetVirtualizationMode(pContext);
2050             break;
2051 
2052         default:
2053             ALOGV("%s invalid param %d", __func__, params[0]);
2054             status = -EINVAL;
2055             break;
2056     }
2057 
2058     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
2059     return status;
2060 } /* end Virtualizer_getParameter */
2061 
2062 //----------------------------------------------------------------------------
2063 // Virtualizer_setParameter()
2064 //----------------------------------------------------------------------------
2065 // Purpose:
2066 // Set a Virtualizer parameter
2067 //
2068 // Inputs:
2069 //  pVirtualizer     - handle to instance data
2070 //  pParam           - pointer to parameter
2071 //  pValue           - pointer to value
2072 //
2073 // Outputs:
2074 //
2075 //----------------------------------------------------------------------------
2076 
Virtualizer_setParameter(EffectContext * pContext,uint32_t paramSize,void * pParam,uint32_t valueSize,void * pValue)2077 int Virtualizer_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
2078                              uint32_t valueSize, void* pValue) {
2079     int status = 0;
2080     int32_t* params = (int32_t*)pParam;
2081 
2082     ALOGVV("%s start", __func__);
2083 
2084     if (paramSize != sizeof(int32_t)) {  // legacy: check equality here.
2085         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
2086         return -EINVAL;
2087     }
2088     switch (params[0]) {
2089         case VIRTUALIZER_PARAM_STRENGTH: {
2090             if (valueSize < sizeof(int16_t)) {
2091                 ALOGV("%s VIRTUALIZER_PARAM_STRENGTH invalid valueSize: %u", __func__, valueSize);
2092                 status = -EINVAL;
2093                 break;
2094             }
2095 
2096             const int16_t strength = *(int16_t*)pValue;
2097             ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH %d", __func__, strength);
2098             ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH Calling VirtualizerSetStrength", __func__);
2099             VirtualizerSetStrength(pContext, (int32_t)strength);
2100             ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH Called VirtualizerSetStrength", __func__);
2101         } break;
2102 
2103         case VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE: {
2104             if (valueSize < sizeof(int32_t)) {
2105                 ALOGV("%s VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE invalid valueSize: %u",
2106                       __func__, valueSize);
2107                 android_errorWriteLog(0x534e4554, "64478003");
2108                 status = -EINVAL;
2109                 break;
2110             }
2111 
2112             const audio_devices_t deviceType = (audio_devices_t) * (int32_t*)pValue;
2113             status = VirtualizerForceVirtualizationMode(pContext, deviceType);
2114             ALOGVV("%s VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE device=%#x result=%d", __func__,
2115                    deviceType, status);
2116         } break;
2117 
2118         default:
2119             ALOGV("%s invalid param %d", __func__, params[0]);
2120             status = -EINVAL;
2121             break;
2122     }
2123 
2124     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
2125     return status;
2126 } /* end Virtualizer_setParameter */
2127 
2128 //----------------------------------------------------------------------------
2129 // Equalizer_getParameter()
2130 //----------------------------------------------------------------------------
2131 // Purpose:
2132 // Get a Equalizer parameter
2133 //
2134 // Inputs:
2135 //  pEqualizer       - handle to instance data
2136 //  pParam           - pointer to parameter
2137 //  pValue           - pointer to variable to hold retrieved value
2138 //  pValueSize       - pointer to value size: maximum size as input
2139 //
2140 // Outputs:
2141 //  *pValue updated with parameter value
2142 //  *pValueSize updated with actual value size
2143 //
2144 //
2145 // Side Effects:
2146 //
2147 //----------------------------------------------------------------------------
Equalizer_getParameter(EffectContext * pContext,uint32_t paramSize,void * pParam,uint32_t * pValueSize,void * pValue)2148 int Equalizer_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
2149                            uint32_t* pValueSize, void* pValue) {
2150     int status = 0;
2151     int32_t* params = (int32_t*)pParam;
2152 
2153     ALOGVV("%s start", __func__);
2154 
2155     if (paramSize < sizeof(int32_t)) {
2156         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
2157         return -EINVAL;
2158     }
2159     switch (params[0]) {
2160         case EQ_PARAM_NUM_BANDS:
2161             if (*pValueSize < sizeof(uint16_t)) {
2162                 ALOGV("%s EQ_PARAM_NUM_BANDS invalid *pValueSize %u", __func__, *pValueSize);
2163                 status = -EINVAL;
2164                 break;
2165             }
2166             *pValueSize = sizeof(uint16_t);
2167 
2168             *(uint16_t*)pValue = (uint16_t)FIVEBAND_NUMBANDS;
2169             ALOGVV("%s EQ_PARAM_NUM_BANDS %u", __func__, *(uint16_t*)pValue);
2170             break;
2171 
2172         case EQ_PARAM_CUR_PRESET:
2173             if (*pValueSize < sizeof(uint16_t)) {
2174                 ALOGV("%s EQ_PARAM_CUR_PRESET invalid *pValueSize %u", __func__, *pValueSize);
2175                 status = -EINVAL;
2176                 break;
2177             }
2178             *pValueSize = sizeof(uint16_t);
2179 
2180             *(uint16_t*)pValue = (uint16_t)EqualizerGetPreset(pContext);
2181             ALOGVV("%s EQ_PARAM_CUR_PRESET %u", __func__, *(uint16_t*)pValue);
2182             break;
2183 
2184         case EQ_PARAM_GET_NUM_OF_PRESETS:
2185             if (*pValueSize < sizeof(uint16_t)) {
2186                 ALOGV("%s EQ_PARAM_GET_NUM_OF_PRESETS invalid *pValueSize %u", __func__,
2187                       *pValueSize);
2188                 status = -EINVAL;
2189                 break;
2190             }
2191             *pValueSize = sizeof(uint16_t);
2192 
2193             *(uint16_t*)pValue = (uint16_t)EqualizerGetNumPresets();
2194             ALOGVV("%s EQ_PARAM_GET_NUM_OF_PRESETS %u", __func__, *(uint16_t*)pValue);
2195             break;
2196 
2197         case EQ_PARAM_GET_BAND: {
2198             if (paramSize < 2 * sizeof(int32_t)) {
2199                 ALOGV("%s EQ_PARAM_GET_BAND invalid paramSize: %u", __func__, paramSize);
2200                 status = -EINVAL;
2201                 break;
2202             }
2203             if (*pValueSize < sizeof(uint16_t)) {
2204                 ALOGV("%s EQ_PARAM_GET_BAND invalid *pValueSize %u", __func__, *pValueSize);
2205                 status = -EINVAL;
2206                 break;
2207             }
2208             *pValueSize = sizeof(uint16_t);
2209 
2210             const int32_t frequency = params[1];
2211             *(uint16_t*)pValue = (uint16_t)EqualizerGetBand(pContext, frequency);
2212             ALOGVV("%s EQ_PARAM_GET_BAND frequency %d, band %u", __func__, frequency,
2213                    *(uint16_t*)pValue);
2214         } break;
2215 
2216         case EQ_PARAM_BAND_LEVEL: {
2217             if (paramSize < 2 * sizeof(int32_t)) {
2218                 ALOGV("%s EQ_PARAM_BAND_LEVEL invalid paramSize %u", __func__, paramSize);
2219                 status = -EINVAL;
2220                 break;
2221             }
2222             if (*pValueSize < sizeof(int16_t)) {
2223                 ALOGV("%s EQ_PARAM_BAND_LEVEL invalid *pValueSize %u", __func__, *pValueSize);
2224                 status = -EINVAL;
2225                 break;
2226             }
2227             *pValueSize = sizeof(int16_t);
2228 
2229             const int32_t band = params[1];
2230             if (band < 0 || band >= FIVEBAND_NUMBANDS) {
2231                 if (band < 0) {
2232                     android_errorWriteLog(0x534e4554, "32438598");
2233                     ALOGW("%s EQ_PARAM_BAND_LEVEL invalid band %d", __func__, band);
2234                 }
2235                 status = -EINVAL;
2236                 break;
2237             }
2238             *(int16_t*)pValue = (int16_t)EqualizerGetBandLevel(pContext, band);
2239             ALOGVV("%s EQ_PARAM_BAND_LEVEL band %d, level %d", __func__, band, *(int16_t*)pValue);
2240         } break;
2241 
2242         case EQ_PARAM_LEVEL_RANGE:
2243             if (*pValueSize < 2 * sizeof(int16_t)) {
2244                 ALOGV("%s EQ_PARAM_LEVEL_RANGE invalid *pValueSize %u", __func__, *pValueSize);
2245                 status = -EINVAL;
2246                 break;
2247             }
2248             *pValueSize = 2 * sizeof(int16_t);
2249 
2250             *(int16_t*)pValue = -1500;
2251             *((int16_t*)pValue + 1) = 1500;
2252             ALOGVV("%s EQ_PARAM_LEVEL_RANGE min %d, max %d", __func__, *(int16_t*)pValue,
2253                    *((int16_t*)pValue + 1));
2254             break;
2255 
2256         case EQ_PARAM_BAND_FREQ_RANGE: {
2257             if (paramSize < 2 * sizeof(int32_t)) {
2258                 ALOGV("%s EQ_PARAM_BAND_FREQ_RANGE invalid paramSize: %u", __func__, paramSize);
2259                 status = -EINVAL;
2260                 break;
2261             }
2262             if (*pValueSize < 2 * sizeof(int32_t)) {
2263                 ALOGV("%s EQ_PARAM_BAND_FREQ_RANGE invalid *pValueSize %u", __func__, *pValueSize);
2264                 status = -EINVAL;
2265                 break;
2266             }
2267             *pValueSize = 2 * sizeof(int32_t);
2268 
2269             const int32_t band = params[1];
2270             if (band < 0 || band >= FIVEBAND_NUMBANDS) {
2271                 if (band < 0) {
2272                     android_errorWriteLog(0x534e4554, "32247948");
2273                     ALOGW("%s EQ_PARAM_BAND_FREQ_RANGE invalid band %d", __func__, band);
2274                 }
2275                 status = -EINVAL;
2276                 break;
2277             }
2278             EqualizerGetBandFreqRange(pContext, band, (uint32_t*)pValue, ((uint32_t*)pValue + 1));
2279             ALOGVV("%s EQ_PARAM_BAND_FREQ_RANGE band %d, min %d, max %d", __func__, band,
2280                    *(int32_t*)pValue, *((int32_t*)pValue + 1));
2281 
2282         } break;
2283 
2284         case EQ_PARAM_CENTER_FREQ: {
2285             if (paramSize < 2 * sizeof(int32_t)) {
2286                 ALOGV("%s EQ_PARAM_CENTER_FREQ invalid paramSize: %u", __func__, paramSize);
2287                 status = -EINVAL;
2288                 break;
2289             }
2290             if (*pValueSize < sizeof(int32_t)) {
2291                 ALOGV("%s EQ_PARAM_CENTER_FREQ invalid *pValueSize %u", __func__, *pValueSize);
2292                 status = -EINVAL;
2293                 break;
2294             }
2295             *pValueSize = sizeof(int32_t);
2296 
2297             const int32_t band = params[1];
2298             if (band < 0 || band >= FIVEBAND_NUMBANDS) {
2299                 status = -EINVAL;
2300                 if (band < 0) {
2301                     android_errorWriteLog(0x534e4554, "32436341");
2302                     ALOGW("%s EQ_PARAM_CENTER_FREQ invalid band %d", __func__, band);
2303                 }
2304                 break;
2305             }
2306             *(int32_t*)pValue = EqualizerGetCentreFrequency(pContext, band);
2307             ALOGVV("%s EQ_PARAM_CENTER_FREQ band %d, frequency %d", __func__, band,
2308                    *(int32_t*)pValue);
2309         } break;
2310 
2311         case EQ_PARAM_GET_PRESET_NAME: {
2312             if (paramSize < 2 * sizeof(int32_t)) {
2313                 ALOGV("%s EQ_PARAM_PRESET_NAME invalid paramSize: %u", __func__, paramSize);
2314                 status = -EINVAL;
2315                 break;
2316             }
2317             if (*pValueSize < 1) {
2318                 android_errorWriteLog(0x534e4554, "37536407");
2319                 status = -EINVAL;
2320                 break;
2321             }
2322 
2323             const int32_t preset = params[1];
2324             if ((preset < 0 && preset != PRESET_CUSTOM) || preset >= EqualizerGetNumPresets()) {
2325                 if (preset < 0) {
2326                     android_errorWriteLog(0x534e4554, "32448258");
2327                     ALOGE("%s EQ_PARAM_GET_PRESET_NAME preset %d", __func__, preset);
2328                 }
2329                 status = -EINVAL;
2330                 break;
2331             }
2332 
2333             char* const name = (char*)pValue;
2334             strncpy(name, EqualizerGetPresetName(preset), *pValueSize - 1);
2335             name[*pValueSize - 1] = 0;
2336             *pValueSize = strlen(name) + 1;
2337             ALOGVV("%s EQ_PARAM_GET_PRESET_NAME preset %d, name %s len %d", __func__, preset, name,
2338                    *pValueSize);
2339 
2340         } break;
2341 
2342         case EQ_PARAM_PROPERTIES: {
2343             constexpr uint32_t requiredValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t);
2344             if (*pValueSize < requiredValueSize) {
2345                 ALOGV("%s EQ_PARAM_PROPERTIES invalid *pValueSize %u", __func__, *pValueSize);
2346                 status = -EINVAL;
2347                 break;
2348             }
2349             *pValueSize = requiredValueSize;
2350 
2351             int16_t* p = (int16_t*)pValue;
2352             ALOGV("%s EQ_PARAM_PROPERTIES", __func__);
2353             p[0] = (int16_t)EqualizerGetPreset(pContext);
2354             p[1] = (int16_t)FIVEBAND_NUMBANDS;
2355             for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
2356                 p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i);
2357             }
2358         } break;
2359 
2360         default:
2361             ALOGV("%s invalid param %d", __func__, params[0]);
2362             status = -EINVAL;
2363             break;
2364     }
2365 
2366     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
2367     return status;
2368 } /* end Equalizer_getParameter */
2369 
2370 //----------------------------------------------------------------------------
2371 // Equalizer_setParameter()
2372 //----------------------------------------------------------------------------
2373 // Purpose:
2374 // Set a Equalizer parameter
2375 //
2376 // Inputs:
2377 //  pEqualizer    - handle to instance data
2378 //  pParam        - pointer to parameter
2379 //  valueSize     - value size
2380 //  pValue        - pointer to value
2381 
2382 //
2383 // Outputs:
2384 //
2385 //----------------------------------------------------------------------------
Equalizer_setParameter(EffectContext * pContext,uint32_t paramSize,void * pParam,uint32_t valueSize,void * pValue)2386 int Equalizer_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
2387                            uint32_t valueSize, void* pValue) {
2388     int status = 0;
2389     int32_t* params = (int32_t*)pParam;
2390 
2391     ALOGVV("%s start", __func__);
2392 
2393     if (paramSize < sizeof(int32_t)) {
2394         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
2395         return -EINVAL;
2396     }
2397     switch (params[0]) {
2398         case EQ_PARAM_CUR_PRESET: {
2399             if (valueSize < sizeof(int16_t)) {
2400                 ALOGV("%s EQ_PARAM_CUR_PRESET invalid valueSize %u", __func__, valueSize);
2401                 status = -EINVAL;
2402                 break;
2403             }
2404             const int32_t preset = (int32_t) * (uint16_t*)pValue;
2405 
2406             ALOGVV("%s EQ_PARAM_CUR_PRESET %d", __func__, preset);
2407             if (preset >= EqualizerGetNumPresets() || preset < 0) {
2408                 ALOGV("%s EQ_PARAM_CUR_PRESET invalid preset %d", __func__, preset);
2409                 status = -EINVAL;
2410                 break;
2411             }
2412             EqualizerSetPreset(pContext, preset);
2413         } break;
2414 
2415         case EQ_PARAM_BAND_LEVEL: {
2416             if (paramSize < 2 * sizeof(int32_t)) {
2417                 ALOGV("%s EQ_PARAM_BAND_LEVEL invalid paramSize: %u", __func__, paramSize);
2418                 status = -EINVAL;
2419                 break;
2420             }
2421             if (valueSize < sizeof(int16_t)) {
2422                 ALOGV("%s EQ_PARAM_BAND_LEVEL invalid valueSize %u", __func__, valueSize);
2423                 status = -EINVAL;
2424                 break;
2425             }
2426             const int32_t band = params[1];
2427             const int32_t level = (int32_t) * (int16_t*)pValue;
2428             ALOGVV("%s EQ_PARAM_BAND_LEVEL band %d, level %d", __func__, band, level);
2429             if (band < 0 || band >= FIVEBAND_NUMBANDS) {
2430                 if (band < 0) {
2431                     android_errorWriteLog(0x534e4554, "32095626");
2432                     ALOGE("%s EQ_PARAM_BAND_LEVEL invalid band %d", __func__, band);
2433                 }
2434                 status = -EINVAL;
2435                 break;
2436             }
2437             EqualizerSetBandLevel(pContext, band, level);
2438         } break;
2439 
2440         case EQ_PARAM_PROPERTIES: {
2441             ALOGVV("%s EQ_PARAM_PROPERTIES", __func__);
2442             if (valueSize < sizeof(int16_t)) {
2443                 ALOGV("%s EQ_PARAM_PROPERTIES invalid valueSize %u", __func__, valueSize);
2444                 status = -EINVAL;
2445                 break;
2446             }
2447             int16_t* p = (int16_t*)pValue;
2448             if ((int)p[0] >= EqualizerGetNumPresets()) {
2449                 ALOGV("%s EQ_PARAM_PROPERTIES invalid preset %d", __func__, (int)p[0]);
2450                 status = -EINVAL;
2451                 break;
2452             }
2453             if (p[0] >= 0) {
2454                 EqualizerSetPreset(pContext, (int)p[0]);
2455             } else {
2456                 constexpr uint32_t valueSizeRequired = (2 + FIVEBAND_NUMBANDS) * sizeof(int16_t);
2457                 if (valueSize < valueSizeRequired) {
2458                     android_errorWriteLog(0x534e4554, "37563371");
2459                     ALOGE("%s EQ_PARAM_PROPERTIES invalid valueSize %u < %u", __func__, valueSize,
2460                           valueSizeRequired);
2461                     status = -EINVAL;
2462                     break;
2463                 }
2464                 if ((int)p[1] != FIVEBAND_NUMBANDS) {
2465                     ALOGV("%s EQ_PARAM_PROPERTIES invalid bands %d", __func__, (int)p[1]);
2466                     status = -EINVAL;
2467                     break;
2468                 }
2469                 for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
2470                     EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
2471                 }
2472             }
2473         } break;
2474 
2475         default:
2476             ALOGV("%s invalid param %d", __func__, params[0]);
2477             status = -EINVAL;
2478             break;
2479     }
2480 
2481     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
2482     return status;
2483 } /* end Equalizer_setParameter */
2484 
2485 //----------------------------------------------------------------------------
2486 // Volume_getParameter()
2487 //----------------------------------------------------------------------------
2488 // Purpose:
2489 // Get a Volume parameter
2490 //
2491 // Inputs:
2492 //  pVolume          - handle to instance data
2493 //  pParam           - pointer to parameter
2494 //  pValue           - pointer to variable to hold retrieved value
2495 //  pValueSize       - pointer to value size: maximum size as input
2496 //
2497 // Outputs:
2498 //  *pValue updated with parameter value
2499 //  *pValueSize updated with actual value size
2500 //
2501 //
2502 // Side Effects:
2503 //
2504 //----------------------------------------------------------------------------
2505 
Volume_getParameter(EffectContext * pContext,uint32_t paramSize,void * pParam,uint32_t * pValueSize,void * pValue)2506 int Volume_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
2507                         uint32_t* pValueSize, void* pValue) {
2508     int status = 0;
2509     int32_t* params = (int32_t*)pParam;
2510 
2511     ALOGVV("%s start", __func__);
2512 
2513     if (paramSize < sizeof(int32_t)) {
2514         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
2515         return -EINVAL;
2516     }
2517     switch (params[0]) {
2518         case VOLUME_PARAM_LEVEL:
2519             if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
2520                 ALOGV("%s VOLUME_PARAM_LEVEL invalid *pValueSize %u", __func__, *pValueSize);
2521                 status = -EINVAL;
2522                 break;
2523             }
2524             // no need to set *pValueSize
2525 
2526             status = VolumeGetVolumeLevel(pContext, (int16_t*)(pValue));
2527             ALOGVV("%s VOLUME_PARAM_LEVEL %d", __func__, *(int16_t*)pValue);
2528             break;
2529 
2530         case VOLUME_PARAM_MAXLEVEL:
2531             if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
2532                 ALOGV("%s VOLUME_PARAM_MAXLEVEL invalid *pValueSize %u", __func__, *pValueSize);
2533                 status = -EINVAL;
2534                 break;
2535             }
2536             // no need to set *pValueSize
2537 
2538             // in millibel
2539             *(int16_t*)pValue = 0;
2540             ALOGVV("%s VOLUME_PARAM_MAXLEVEL %d", __func__, *(int16_t*)pValue);
2541             break;
2542 
2543         case VOLUME_PARAM_STEREOPOSITION:
2544             if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
2545                 ALOGV("%s VOLUME_PARAM_STEREOPOSITION invalid *pValueSize %u", __func__,
2546                       *pValueSize);
2547                 status = -EINVAL;
2548                 break;
2549             }
2550             // no need to set *pValueSize
2551 
2552             VolumeGetStereoPosition(pContext, (int16_t*)pValue);
2553             ALOGVV("%s VOLUME_PARAM_STEREOPOSITION %d", __func__, *(int16_t*)pValue);
2554             break;
2555 
2556         case VOLUME_PARAM_MUTE:
2557             if (*pValueSize < sizeof(uint32_t)) {
2558                 ALOGV("%s VOLUME_PARAM_MUTE invalid *pValueSize %u", __func__, *pValueSize);
2559                 status = -EINVAL;
2560                 break;
2561             }
2562             *pValueSize = sizeof(uint32_t);
2563 
2564             status = VolumeGetMute(pContext, (uint32_t*)pValue);
2565             ALOGV("%s VOLUME_PARAM_MUTE %u", __func__, *(uint32_t*)pValue);
2566             break;
2567 
2568         case VOLUME_PARAM_ENABLESTEREOPOSITION:
2569             if (*pValueSize < sizeof(int32_t)) {
2570                 ALOGV("%s VOLUME_PARAM_ENABLESTEREOPOSITION invalid *pValueSize %u", __func__,
2571                       *pValueSize);
2572                 status = -EINVAL;
2573                 break;
2574             }
2575             *pValueSize = sizeof(int32_t);
2576 
2577             *(int32_t*)pValue = pContext->pBundledContext->bStereoPositionEnabled;
2578             ALOGVV("%s VOLUME_PARAM_ENABLESTEREOPOSITION %d", __func__, *(int32_t*)pValue);
2579 
2580             break;
2581 
2582         default:
2583             ALOGV("%s invalid param %d", __func__, params[0]);
2584             status = -EINVAL;
2585             break;
2586     }
2587 
2588     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
2589     return status;
2590 } /* end Volume_getParameter */
2591 
2592 //----------------------------------------------------------------------------
2593 // Volume_setParameter()
2594 //----------------------------------------------------------------------------
2595 // Purpose:
2596 // Set a Volume parameter
2597 //
2598 // Inputs:
2599 //  pVolume       - handle to instance data
2600 //  pParam        - pointer to parameter
2601 //  pValue        - pointer to value
2602 //
2603 // Outputs:
2604 //
2605 //----------------------------------------------------------------------------
2606 
Volume_setParameter(EffectContext * pContext,uint32_t paramSize,void * pParam,uint32_t valueSize,void * pValue)2607 int Volume_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
2608                         uint32_t valueSize, void* pValue) {
2609     int status = 0;
2610     int32_t* params = (int32_t*)pParam;
2611 
2612     ALOGVV("%s start", __func__);
2613 
2614     if (paramSize < sizeof(int32_t)) {
2615         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
2616         return -EINVAL;
2617     }
2618     switch (params[0]) {
2619         case VOLUME_PARAM_LEVEL: {
2620             if (valueSize < sizeof(int16_t)) {
2621                 ALOGV("%s VOLUME_PARAM_LEVEL invalid valueSize %u", __func__, valueSize);
2622                 status = -EINVAL;
2623                 break;
2624             }
2625 
2626             const int16_t level = *(int16_t*)pValue;
2627             ALOGVV("%s VOLUME_PARAM_LEVEL %d", __func__, level);
2628             ALOGVV("%s VOLUME_PARAM_LEVEL Calling VolumeSetVolumeLevel", __func__);
2629             status = VolumeSetVolumeLevel(pContext, level);
2630             ALOGVV("%s VOLUME_PARAM_LEVEL Called VolumeSetVolumeLevel", __func__);
2631         } break;
2632 
2633         case VOLUME_PARAM_MUTE: {
2634             if (valueSize < sizeof(uint32_t)) {
2635                 ALOGV("%s VOLUME_PARAM_MUTE invalid valueSize %u", __func__, valueSize);
2636                 android_errorWriteLog(0x534e4554, "64477217");
2637                 status = -EINVAL;
2638                 break;
2639             }
2640 
2641             const uint32_t mute = *(uint32_t*)pValue;
2642             ALOGVV("%s VOLUME_PARAM_MUTE %d", __func__, mute);
2643             ALOGVV("%s VOLUME_PARAM_MUTE Calling VolumeSetMute", __func__);
2644             status = VolumeSetMute(pContext, mute);
2645             ALOGVV("%s VOLUME_PARAM_MUTE Called VolumeSetMute", __func__);
2646         } break;
2647 
2648         case VOLUME_PARAM_ENABLESTEREOPOSITION: {
2649             if (valueSize < sizeof(uint32_t)) {
2650                 ALOGV("%s VOLUME_PARAM_ENABLESTEREOPOSITION invalid valueSize %u", __func__,
2651                       valueSize);
2652                 status = -EINVAL;
2653                 break;
2654             }
2655 
2656             const uint32_t positionEnabled = *(uint32_t*)pValue;
2657             status = VolumeEnableStereoPosition(pContext, positionEnabled)
2658                              ?: VolumeSetStereoPosition(pContext,
2659                                                         pContext->pBundledContext->positionSaved);
2660             ALOGVV("%s VOLUME_PARAM_ENABLESTEREOPOSITION called", __func__);
2661         } break;
2662 
2663         case VOLUME_PARAM_STEREOPOSITION: {
2664             if (valueSize < sizeof(int16_t)) {
2665                 ALOGV("%s VOLUME_PARAM_STEREOPOSITION invalid valueSize %u", __func__, valueSize);
2666                 status = -EINVAL;
2667                 break;
2668             }
2669 
2670             const int16_t position = *(int16_t*)pValue;
2671             ALOGVV("%s VOLUME_PARAM_STEREOPOSITION %d", __func__, position);
2672             ALOGVV("%s VOLUME_PARAM_STEREOPOSITION Calling VolumeSetStereoPosition", __func__);
2673             status = VolumeSetStereoPosition(pContext, position);
2674             ALOGVV("%s VOLUME_PARAM_STEREOPOSITION Called VolumeSetStereoPosition", __func__);
2675         } break;
2676 
2677         default:
2678             ALOGV("%s invalid param %d", __func__, params[0]);
2679             status = -EINVAL;
2680             break;
2681     }
2682 
2683     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
2684     return status;
2685 } /* end Volume_setParameter */
2686 
2687 /****************************************************************************************
2688  * Name : LVC_ToDB_s32Tos16()
2689  *  Input       : Signed 32-bit integer
2690  *  Output      : Signed 16-bit integer
2691  *                  MSB (16) = sign bit
2692  *                  (15->05) = integer part
2693  *                  (04->01) = decimal part
2694  *  Returns     : Db value with respect to full scale
2695  *  Description :
2696  *  Remarks     :
2697  ****************************************************************************************/
2698 
LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix)2699 LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix) {
2700     LVM_INT16 db_fix;
2701     LVM_INT16 Shift;
2702     LVM_INT16 SmallRemainder;
2703     LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix;
2704 
2705     /* Count leading bits, 1 cycle in assembly*/
2706     for (Shift = 0; Shift < 32; Shift++) {
2707         if ((Remainder & 0x80000000U) != 0) {
2708             break;
2709         }
2710         Remainder = Remainder << 1;
2711     }
2712 
2713     /*
2714      * Based on the approximation equation (for Q11.4 format):
2715      *
2716      * dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2)
2717      */
2718     db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/
2719     SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24);
2720     db_fix = (LVM_INT16)(db_fix + SmallRemainder);
2721     SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder);
2722     db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9));
2723 
2724     /* Correct for small offset */
2725     db_fix = (LVM_INT16)(db_fix - 5);
2726 
2727     return db_fix;
2728 }
2729 
2730 //----------------------------------------------------------------------------
2731 // Effect_setEnabled()
2732 //----------------------------------------------------------------------------
2733 // Purpose:
2734 // Enable or disable effect
2735 //
2736 // Inputs:
2737 //  pContext      - pointer to effect context
2738 //  enabled       - true if enabling the effect, false otherwise
2739 //
2740 // Outputs:
2741 //
2742 //----------------------------------------------------------------------------
2743 
Effect_setEnabled(EffectContext * pContext,bool enabled)2744 int Effect_setEnabled(EffectContext* pContext, bool enabled) {
2745     ALOGV("%s effectType %d, enabled %d, currently enabled %d", __func__, pContext->EffectType,
2746           enabled, pContext->pBundledContext->NumberEffectsEnabled);
2747     int& effectInDrain = pContext->pBundledContext->effectInDrain;
2748     if (enabled) {
2749         // Bass boost or Virtualizer can be temporarily disabled if playing over device speaker due
2750         // to their nature.
2751         bool tempDisabled = false;
2752         switch (pContext->EffectType) {
2753             case LVM_BASS_BOOST:
2754                 if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
2755                     ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled");
2756                     return -EINVAL;
2757                 }
2758                 if (pContext->pBundledContext->SamplesToExitCountBb <= 0) {
2759                     pContext->pBundledContext->NumberEffectsEnabled++;
2760                 }
2761                 effectInDrain &= ~(1 << LVM_BASS_BOOST);
2762                 pContext->pBundledContext->SamplesToExitCountBb =
2763                         (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond * 0.1);
2764                 pContext->pBundledContext->bBassEnabled = LVM_TRUE;
2765                 tempDisabled = pContext->pBundledContext->bBassTempDisabled;
2766                 break;
2767             case LVM_EQUALIZER:
2768                 if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) {
2769                     ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled");
2770                     return -EINVAL;
2771                 }
2772                 if (pContext->pBundledContext->SamplesToExitCountEq <= 0) {
2773                     pContext->pBundledContext->NumberEffectsEnabled++;
2774                 }
2775                 effectInDrain &= ~(1 << LVM_EQUALIZER);
2776                 pContext->pBundledContext->SamplesToExitCountEq =
2777                         (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond * 0.1);
2778                 pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE;
2779                 break;
2780             case LVM_VIRTUALIZER:
2781                 if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
2782                     ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled");
2783                     return -EINVAL;
2784                 }
2785                 if (pContext->pBundledContext->SamplesToExitCountVirt <= 0) {
2786                     pContext->pBundledContext->NumberEffectsEnabled++;
2787                 }
2788                 effectInDrain &= ~(1 << LVM_VIRTUALIZER);
2789                 pContext->pBundledContext->SamplesToExitCountVirt =
2790                         (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond * 0.1);
2791                 pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE;
2792                 tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled;
2793                 break;
2794             case LVM_VOLUME:
2795                 if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) {
2796                     ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled");
2797                     return -EINVAL;
2798                 }
2799                 if ((effectInDrain & 1 << LVM_VOLUME) == 0) {
2800                     pContext->pBundledContext->NumberEffectsEnabled++;
2801                 }
2802                 effectInDrain &= ~(1 << LVM_VOLUME);
2803                 pContext->pBundledContext->bVolumeEnabled = LVM_TRUE;
2804                 break;
2805             default:
2806                 ALOGV("\tEffect_setEnabled() invalid effect type");
2807                 return -EINVAL;
2808         }
2809         if (!tempDisabled) {
2810             LvmEffect_enable(pContext);
2811         }
2812     } else {
2813         switch (pContext->EffectType) {
2814             case LVM_BASS_BOOST:
2815                 if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) {
2816                     ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled");
2817                     return -EINVAL;
2818                 }
2819                 pContext->pBundledContext->bBassEnabled = LVM_FALSE;
2820                 effectInDrain |= 1 << LVM_BASS_BOOST;
2821                 break;
2822             case LVM_EQUALIZER:
2823                 if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) {
2824                     ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled");
2825                     return -EINVAL;
2826                 }
2827                 pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
2828                 effectInDrain |= 1 << LVM_EQUALIZER;
2829                 break;
2830             case LVM_VIRTUALIZER:
2831                 if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) {
2832                     ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled");
2833                     return -EINVAL;
2834                 }
2835                 pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
2836                 effectInDrain |= 1 << LVM_VIRTUALIZER;
2837                 break;
2838             case LVM_VOLUME:
2839                 if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) {
2840                     ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled");
2841                     return -EINVAL;
2842                 }
2843                 pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
2844                 effectInDrain |= 1 << LVM_VOLUME;
2845                 break;
2846             default:
2847                 ALOGV("\tEffect_setEnabled() invalid effect type");
2848                 return -EINVAL;
2849         }
2850         LvmEffect_disable(pContext);
2851     }
2852 
2853     return 0;
2854 }
2855 
2856 //----------------------------------------------------------------------------
2857 // LVC_Convert_VolToDb()
2858 //----------------------------------------------------------------------------
2859 // Purpose:
2860 // Convery volume in Q24 to dB
2861 //
2862 // Inputs:
2863 //  vol:   Q.24 volume dB
2864 //
2865 //-----------------------------------------------------------------------
2866 
LVC_Convert_VolToDb(uint32_t vol)2867 int16_t LVC_Convert_VolToDb(uint32_t vol) {
2868     int16_t dB;
2869 
2870     dB = LVC_ToDB_s32Tos16(vol << 7);
2871     dB = (dB + 8) >> 4;
2872     dB = (dB < -96) ? -96 : dB;
2873 
2874     return dB;
2875 }
2876 
2877 }  // namespace
2878 }  // namespace android
2879 
2880 extern "C" {
2881 /* Effect Control Interface Implementation: Process */
Effect_process(effect_handle_t self,audio_buffer_t * inBuffer,audio_buffer_t * outBuffer)2882 int Effect_process(effect_handle_t self, audio_buffer_t* inBuffer, audio_buffer_t* outBuffer) {
2883     EffectContext* pContext = (EffectContext*)self;
2884     int status = 0;
2885     int processStatus = 0;
2886     const int NrChannels = audio_channel_count_from_out_mask(pContext->config.inputCfg.channels);
2887 
2888     // ALOGV("\tEffect_process Start : Enabled = %d     Called = %d (%8d %8d %8d)",
2889     // pContext->pBundledContext->NumberEffectsEnabled,pContext->pBundledContext->NumberEffectsCalled,
2890     //    pContext->pBundledContext->SamplesToExitCountBb,
2891     //    pContext->pBundledContext->SamplesToExitCountVirt,
2892     //    pContext->pBundledContext->SamplesToExitCountEq);
2893 
2894     if (pContext == NULL) {
2895         ALOGV("\tLVM_ERROR : Effect_process() ERROR pContext == NULL");
2896         return -EINVAL;
2897     }
2898 
2899     // if(pContext->EffectType == LVM_BASS_BOOST){
2900     //  ALOGV("\tEffect_process: Effect type is BASS_BOOST");
2901     //}else if(pContext->EffectType == LVM_EQUALIZER){
2902     //  ALOGV("\tEffect_process: Effect type is LVM_EQUALIZER");
2903     //}else if(pContext->EffectType == LVM_VIRTUALIZER){
2904     //  ALOGV("\tEffect_process: Effect type is LVM_VIRTUALIZER");
2905     //}
2906 
2907     if (inBuffer == NULL || inBuffer->raw == NULL || outBuffer == NULL || outBuffer->raw == NULL ||
2908         inBuffer->frameCount != outBuffer->frameCount) {
2909         ALOGV("\tLVM_ERROR : Effect_process() ERROR NULL INPUT POINTER OR FRAME COUNT IS WRONG");
2910         return -EINVAL;
2911     }
2912 
2913     int& effectProcessCalled = pContext->pBundledContext->effectProcessCalled;
2914     int& effectInDrain = pContext->pBundledContext->effectInDrain;
2915     if ((effectProcessCalled & 1 << pContext->EffectType) != 0) {
2916         ALOGW("Effect %d already called", pContext->EffectType);
2917         const int undrainedEffects = effectInDrain & ~effectProcessCalled;
2918         if ((undrainedEffects & 1 << LVM_BASS_BOOST) != 0) {
2919             ALOGW("Draining BASS_BOOST");
2920             pContext->pBundledContext->SamplesToExitCountBb = 0;
2921             --pContext->pBundledContext->NumberEffectsEnabled;
2922             effectInDrain &= ~(1 << LVM_BASS_BOOST);
2923         }
2924         if ((undrainedEffects & 1 << LVM_EQUALIZER) != 0) {
2925             ALOGW("Draining EQUALIZER");
2926             pContext->pBundledContext->SamplesToExitCountEq = 0;
2927             --pContext->pBundledContext->NumberEffectsEnabled;
2928             effectInDrain &= ~(1 << LVM_EQUALIZER);
2929         }
2930         if ((undrainedEffects & 1 << LVM_VIRTUALIZER) != 0) {
2931             ALOGW("Draining VIRTUALIZER");
2932             pContext->pBundledContext->SamplesToExitCountVirt = 0;
2933             --pContext->pBundledContext->NumberEffectsEnabled;
2934             effectInDrain &= ~(1 << LVM_VIRTUALIZER);
2935         }
2936         if ((undrainedEffects & 1 << LVM_VOLUME) != 0) {
2937             ALOGW("Draining VOLUME");
2938             --pContext->pBundledContext->NumberEffectsEnabled;
2939             effectInDrain &= ~(1 << LVM_VOLUME);
2940         }
2941     }
2942     effectProcessCalled |= 1 << pContext->EffectType;
2943 
2944     if ((pContext->pBundledContext->bBassEnabled == LVM_FALSE) &&
2945         (pContext->EffectType == LVM_BASS_BOOST)) {
2946         // ALOGV("\tEffect_process() LVM_BASS_BOOST Effect is not enabled");
2947         if (pContext->pBundledContext->SamplesToExitCountBb > 0) {
2948             pContext->pBundledContext->SamplesToExitCountBb -= outBuffer->frameCount * NrChannels;
2949             // ALOGV("\tEffect_process: Waiting to turn off BASS_BOOST, %d samples left",
2950             //    pContext->pBundledContext->SamplesToExitCountBb);
2951         }
2952         if (pContext->pBundledContext->SamplesToExitCountBb <= 0) {
2953             status = -ENODATA;
2954             if ((effectInDrain & 1 << LVM_BASS_BOOST) != 0) {
2955                 pContext->pBundledContext->NumberEffectsEnabled--;
2956                 effectInDrain &= ~(1 << LVM_BASS_BOOST);
2957             }
2958             ALOGV("\tEffect_process() this is the last frame for LVM_BASS_BOOST");
2959         }
2960     }
2961     if ((pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) &&
2962         (pContext->EffectType == LVM_VOLUME)) {
2963         // ALOGV("\tEffect_process() LVM_VOLUME Effect is not enabled");
2964         status = -ENODATA;
2965         if ((effectInDrain & 1 << LVM_VOLUME) != 0) {
2966             pContext->pBundledContext->NumberEffectsEnabled--;
2967             effectInDrain &= ~(1 << LVM_VOLUME);
2968         }
2969     }
2970     if ((pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) &&
2971         (pContext->EffectType == LVM_EQUALIZER)) {
2972         // ALOGV("\tEffect_process() LVM_EQUALIZER Effect is not enabled");
2973         if (pContext->pBundledContext->SamplesToExitCountEq > 0) {
2974             pContext->pBundledContext->SamplesToExitCountEq -= outBuffer->frameCount * NrChannels;
2975             // ALOGV("\tEffect_process: Waiting to turn off EQUALIZER, %d samples left",
2976             //    pContext->pBundledContext->SamplesToExitCountEq);
2977         }
2978         if (pContext->pBundledContext->SamplesToExitCountEq <= 0) {
2979             status = -ENODATA;
2980             if ((effectInDrain & 1 << LVM_EQUALIZER) != 0) {
2981                 pContext->pBundledContext->NumberEffectsEnabled--;
2982                 effectInDrain &= ~(1 << LVM_EQUALIZER);
2983             }
2984             ALOGV("\tEffect_process() this is the last frame for LVM_EQUALIZER");
2985         }
2986     }
2987     if ((pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) &&
2988         (pContext->EffectType == LVM_VIRTUALIZER)) {
2989         // ALOGV("\tEffect_process() LVM_VIRTUALIZER Effect is not enabled");
2990         if (pContext->pBundledContext->SamplesToExitCountVirt > 0) {
2991             pContext->pBundledContext->SamplesToExitCountVirt -= outBuffer->frameCount * NrChannels;
2992             // ALOGV("\tEffect_process: Waiting for to turn off VIRTUALIZER, %d samples left",
2993             //    pContext->pBundledContext->SamplesToExitCountVirt);
2994         }
2995         if (pContext->pBundledContext->SamplesToExitCountVirt <= 0) {
2996             status = -ENODATA;
2997             if ((effectInDrain & 1 << LVM_VIRTUALIZER) != 0) {
2998                 pContext->pBundledContext->NumberEffectsEnabled--;
2999                 effectInDrain &= ~(1 << LVM_VIRTUALIZER);
3000             }
3001             ALOGV("\tEffect_process() this is the last frame for LVM_VIRTUALIZER");
3002         }
3003     }
3004 
3005     if (status != -ENODATA) {
3006         pContext->pBundledContext->NumberEffectsCalled++;
3007     }
3008 
3009     if (pContext->pBundledContext->NumberEffectsCalled >=
3010         pContext->pBundledContext->NumberEffectsEnabled) {
3011         // We expect the # effects called to be equal to # effects enabled in sequence (including
3012         // draining effects).  Warn if this is not the case due to inconsistent calls.
3013         ALOGW_IF(pContext->pBundledContext->NumberEffectsCalled >
3014                          pContext->pBundledContext->NumberEffectsEnabled,
3015                  "%s Number of effects called %d is greater than number of effects enabled %d",
3016                  __func__, pContext->pBundledContext->NumberEffectsCalled,
3017                  pContext->pBundledContext->NumberEffectsEnabled);
3018         effectProcessCalled = 0;  // reset our consistency check.
3019 
3020         // ALOGV("\tEffect_process     Calling process with %d effects enabled, %d called: Effect
3021         // %d", pContext->pBundledContext->NumberEffectsEnabled,
3022         // pContext->pBundledContext->NumberEffectsCalled, pContext->EffectType);
3023 
3024         if (status == -ENODATA) {
3025             ALOGV("\tEffect_process() processing last frame");
3026         }
3027         pContext->pBundledContext->NumberEffectsCalled = 0;
3028         /* Process all the available frames, block processing is
3029            handled internalLY by the LVM bundle */
3030         processStatus = android::LvmBundle_process(inBuffer->f32, outBuffer->f32,
3031                                                    outBuffer->frameCount, pContext);
3032         if (processStatus != 0) {
3033             ALOGV("\tLVM_ERROR : LvmBundle_process returned error %d", processStatus);
3034             if (status == 0) {
3035                 status = processStatus;
3036             }
3037             return status;
3038         }
3039     } else {
3040         // ALOGV("\tEffect_process Not Calling process with %d effects enabled, %d called: Effect
3041         // %d", pContext->pBundledContext->NumberEffectsEnabled,
3042         // pContext->pBundledContext->NumberEffectsCalled, pContext->EffectType);
3043 
3044         if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
3045             for (size_t i = 0; i < outBuffer->frameCount * NrChannels; ++i) {
3046                 outBuffer->f32[i] += inBuffer->f32[i];
3047             }
3048         } else if (outBuffer->raw != inBuffer->raw) {
3049             memcpy(outBuffer->raw, inBuffer->raw,
3050                    outBuffer->frameCount * sizeof(effect_buffer_t) * FCC_2);
3051         }
3052     }
3053 
3054     return status;
3055 } /* end Effect_process */
3056 
3057 // The value offset of an effect parameter is computed by rounding up
3058 // the parameter size to the next 32 bit alignment.
computeParamVOffset(const effect_param_t * p)3059 static inline uint32_t computeParamVOffset(const effect_param_t* p) {
3060     return ((p->psize + sizeof(int32_t) - 1) / sizeof(int32_t)) * sizeof(int32_t);
3061 }
3062 
3063 /* Effect Control Interface Implementation: Command */
Effect_command(effect_handle_t self,uint32_t cmdCode,uint32_t cmdSize,void * pCmdData,uint32_t * replySize,void * pReplyData)3064 int Effect_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void* pCmdData,
3065                    uint32_t* replySize, void* pReplyData) {
3066     EffectContext* pContext = (EffectContext*)self;
3067 
3068     // ALOGV("\t\nEffect_command start");
3069 
3070     if (pContext->EffectType == LVM_BASS_BOOST) {
3071         // ALOGV("\tEffect_command setting command for LVM_BASS_BOOST");
3072     }
3073     if (pContext->EffectType == LVM_VIRTUALIZER) {
3074         // ALOGV("\tEffect_command setting command for LVM_VIRTUALIZER");
3075     }
3076     if (pContext->EffectType == LVM_EQUALIZER) {
3077         // ALOGV("\tEffect_command setting command for LVM_EQUALIZER");
3078     }
3079     if (pContext->EffectType == LVM_VOLUME) {
3080         // ALOGV("\tEffect_command setting command for LVM_VOLUME");
3081     }
3082 
3083     if (pContext == NULL) {
3084         ALOGV("\tLVM_ERROR : Effect_command ERROR pContext == NULL");
3085         return -EINVAL;
3086     }
3087 
3088     // ALOGV("\tEffect_command INPUTS are: command %d cmdSize %d",cmdCode, cmdSize);
3089 
3090     // Incase we disable an effect, next time process is
3091     // called the number of effect called could be greater
3092     // pContext->pBundledContext->NumberEffectsCalled = 0;
3093 
3094     // ALOGV("\tEffect_command NumberEffectsCalled = %d, NumberEffectsEnabled = %d",
3095     //        pContext->pBundledContext->NumberEffectsCalled,
3096     //        pContext->pBundledContext->NumberEffectsEnabled);
3097 
3098     switch (cmdCode) {
3099         case EFFECT_CMD_INIT:
3100             if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
3101                 ALOGV("\tLVM_ERROR, EFFECT_CMD_INIT: ERROR for effect type %d",
3102                       pContext->EffectType);
3103                 return -EINVAL;
3104             }
3105             *(int*)pReplyData = 0;
3106             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT start");
3107             if (pContext->EffectType == LVM_BASS_BOOST) {
3108                 // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_BASS_BOOST");
3109                 android::BassSetStrength(pContext, 0);
3110             }
3111             if (pContext->EffectType == LVM_VIRTUALIZER) {
3112                 // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_VIRTUALIZER");
3113                 android::VirtualizerSetStrength(pContext, 0);
3114             }
3115             if (pContext->EffectType == LVM_EQUALIZER) {
3116                 // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_EQUALIZER");
3117                 android::EqualizerSetPreset(pContext, 0);
3118             }
3119             if (pContext->EffectType == LVM_VOLUME) {
3120                 // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_VOLUME");
3121                 *(int*)pReplyData = android::VolumeSetVolumeLevel(pContext, 0);
3122             }
3123             break;
3124 
3125         case EFFECT_CMD_SET_CONFIG:
3126             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_CONFIG start");
3127             if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL ||
3128                 replySize == NULL || *replySize != sizeof(int)) {
3129                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: "
3130                       "EFFECT_CMD_SET_CONFIG: ERROR");
3131                 return -EINVAL;
3132             }
3133             *(int*)pReplyData = android::Effect_setConfig(pContext, (effect_config_t*)pCmdData);
3134             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_CONFIG end");
3135             break;
3136 
3137         case EFFECT_CMD_GET_CONFIG:
3138             if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) {
3139                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: "
3140                       "EFFECT_CMD_GET_CONFIG: ERROR");
3141                 return -EINVAL;
3142             }
3143 
3144             android::Effect_getConfig(pContext, (effect_config_t*)pReplyData);
3145             break;
3146 
3147         case EFFECT_CMD_RESET:
3148             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_RESET start");
3149             android::Effect_setConfig(pContext, &pContext->config);
3150             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_RESET end");
3151             break;
3152 
3153         case EFFECT_CMD_GET_PARAM: {
3154             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_GET_PARAM start");
3155 
3156             effect_param_t* p = (effect_param_t*)pCmdData;
3157             if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
3158                 cmdSize < (sizeof(effect_param_t) + p->psize) || pReplyData == NULL ||
3159                 replySize == NULL || *replySize < (sizeof(effect_param_t) + p->psize)) {
3160                 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: ERROR");
3161                 return -EINVAL;
3162             }
3163             if (EFFECT_PARAM_SIZE_MAX - sizeof(effect_param_t) < (size_t)p->psize) {
3164                 android_errorWriteLog(0x534e4554, "26347509");
3165                 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: psize too big");
3166                 return -EINVAL;
3167             }
3168             const uint32_t paddedParamSize = computeParamVOffset(p);
3169             if ((EFFECT_PARAM_SIZE_MAX - sizeof(effect_param_t) < paddedParamSize) ||
3170                 (EFFECT_PARAM_SIZE_MAX - sizeof(effect_param_t) - paddedParamSize < p->vsize)) {
3171                 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: padded_psize or vsize too big");
3172                 return -EINVAL;
3173             }
3174             uint32_t expectedReplySize = sizeof(effect_param_t) + paddedParamSize + p->vsize;
3175             if (*replySize < expectedReplySize) {
3176                 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: min. replySize %u, got %u bytes",
3177                       expectedReplySize, *replySize);
3178                 android_errorWriteLog(0x534e4554, "32705438");
3179                 return -EINVAL;
3180             }
3181 
3182             memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
3183 
3184             p = (effect_param_t*)pReplyData;
3185 
3186             uint32_t voffset = paddedParamSize;
3187             if (pContext->EffectType == LVM_BASS_BOOST) {
3188                 p->status = android::BassBoost_getParameter(pContext, p->psize, p->data, &p->vsize,
3189                                                             p->data + voffset);
3190                 // ALOGV("\tBassBoost_command EFFECT_CMD_GET_PARAM "
3191                 //        "*pCmdData %d, *replySize %d, *pReplyData %d ",
3192                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
3193                 //        *replySize,
3194                 //        *(int16_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset));
3195             }
3196 
3197             if (pContext->EffectType == LVM_VIRTUALIZER) {
3198                 p->status = android::Virtualizer_getParameter(pContext, p->psize, (void*)p->data,
3199                                                               &p->vsize, p->data + voffset);
3200 
3201                 // ALOGV("\tVirtualizer_command EFFECT_CMD_GET_PARAM "
3202                 //        "*pCmdData %d, *replySize %d, *pReplyData %d ",
3203                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
3204                 //        *replySize,
3205                 //        *(int16_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset));
3206             }
3207             if (pContext->EffectType == LVM_EQUALIZER) {
3208                 // ALOGV("\tEqualizer_command cmdCode Case: "
3209                 //        "EFFECT_CMD_GET_PARAM start");
3210                 p->status = android::Equalizer_getParameter(pContext, p->psize, p->data, &p->vsize,
3211                                                             p->data + voffset);
3212 
3213                 // ALOGV("\tEqualizer_command EFFECT_CMD_GET_PARAM *pCmdData %d, *replySize %d, "
3214                 //       "*pReplyData %08x %08x",
3215                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)), *replySize,
3216                 //        *(int32_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset),
3217                 //        *(int32_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset +
3218                 //        sizeof(int32_t)));
3219             }
3220             if (pContext->EffectType == LVM_VOLUME) {
3221                 // ALOGV("\tVolume_command cmdCode Case: EFFECT_CMD_GET_PARAM start");
3222                 p->status = android::Volume_getParameter(pContext, p->psize, (void*)p->data,
3223                                                          &p->vsize, p->data + voffset);
3224 
3225                 // ALOGV("\tVolume_command EFFECT_CMD_GET_PARAM "
3226                 //        "*pCmdData %d, *replySize %d, *pReplyData %d ",
3227                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
3228                 //        *replySize,
3229                 //        *(int16_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset));
3230             }
3231             *replySize = sizeof(effect_param_t) + voffset + p->vsize;
3232 
3233             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_GET_PARAM end");
3234         } break;
3235         case EFFECT_CMD_SET_PARAM: {
3236             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_PARAM start");
3237             if (pContext->EffectType == LVM_BASS_BOOST) {
3238                 // ALOGV("\tBassBoost_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value
3239                 // %d",
3240                 //       *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
3241                 //       *replySize,
3242                 //       *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) + sizeof(int32_t)));
3243 
3244                 if (pCmdData == NULL ||
3245                     cmdSize != (sizeof(effect_param_t) + sizeof(int32_t) + sizeof(int16_t)) ||
3246                     pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
3247                     ALOGV("\tLVM_ERROR : BassBoost_command cmdCode Case: "
3248                           "EFFECT_CMD_SET_PARAM: ERROR");
3249                     return -EINVAL;
3250                 }
3251 
3252                 effect_param_t* const p = (effect_param_t*)pCmdData;
3253                 const uint32_t voffset = computeParamVOffset(p);
3254 
3255                 // ALOGV("\tnBassBoost_command cmdSize is %d\n"
3256                 //        "\tsizeof(effect_param_t) is  %d\n"
3257                 //        "\tp->psize is %d\n"
3258                 //        "\tp->vsize is %d"
3259                 //        "\n",
3260                 //        cmdSize, sizeof(effect_param_t), p->psize, p->vsize );
3261 
3262                 *(int*)pReplyData = android::BassBoost_setParameter(
3263                         pContext, p->psize, (void*)p->data, p->vsize, p->data + voffset);
3264             }
3265             if (pContext->EffectType == LVM_VIRTUALIZER) {
3266                 // Warning this log will fail to properly read an int32_t value, assumes int16_t
3267                 // ALOGV("\tVirtualizer_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value
3268                 // %d",
3269                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
3270                 //        *replySize,
3271                 //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) +
3272                 //        sizeof(int32_t)));
3273 
3274                 if (pCmdData == NULL ||
3275                     // legal parameters are int16_t or int32_t
3276                     cmdSize > (sizeof(effect_param_t) + sizeof(int32_t) + sizeof(int32_t)) ||
3277                     cmdSize < (sizeof(effect_param_t) + sizeof(int32_t) + sizeof(int16_t)) ||
3278                     pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
3279                     ALOGV("\tLVM_ERROR : Virtualizer_command cmdCode Case: "
3280                           "EFFECT_CMD_SET_PARAM: ERROR");
3281                     return -EINVAL;
3282                 }
3283 
3284                 effect_param_t* const p = (effect_param_t*)pCmdData;
3285                 const uint32_t voffset = computeParamVOffset(p);
3286 
3287                 // ALOGV("\tnVirtualizer_command cmdSize is %d\n"
3288                 //        "\tsizeof(effect_param_t) is  %d\n"
3289                 //        "\tp->psize is %d\n"
3290                 //        "\tp->vsize is %d"
3291                 //        "\n",
3292                 //        cmdSize, sizeof(effect_param_t), p->psize, p->vsize );
3293 
3294                 *(int*)pReplyData = android::Virtualizer_setParameter(
3295                         pContext, p->psize, (void*)p->data, p->vsize, p->data + voffset);
3296             }
3297             if (pContext->EffectType == LVM_EQUALIZER) {
3298                 // ALOGV("\tEqualizer_command cmdCode Case: "
3299                 //        "EFFECT_CMD_SET_PARAM start");
3300                 // ALOGV("\tEqualizer_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d
3301                 // ",
3302                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
3303                 //        *replySize,
3304                 //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) +
3305                 //        sizeof(int32_t)));
3306 
3307                 if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) ||
3308                     pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
3309                     ALOGV("\tLVM_ERROR : Equalizer_command cmdCode Case: "
3310                           "EFFECT_CMD_SET_PARAM: ERROR");
3311                     return -EINVAL;
3312                 }
3313 
3314                 effect_param_t* const p = (effect_param_t*)pCmdData;
3315                 const uint32_t voffset = computeParamVOffset(p);
3316 
3317                 *(int*)pReplyData = android::Equalizer_setParameter(
3318                         pContext, p->psize, (void*)p->data, p->vsize, p->data + voffset);
3319             }
3320             if (pContext->EffectType == LVM_VOLUME) {
3321                 // ALOGV("\tVolume_command cmdCode Case: EFFECT_CMD_SET_PARAM start");
3322                 // ALOGV("\tVolume_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d ",
3323                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
3324                 //        *replySize,
3325                 //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) +sizeof(int32_t)));
3326 
3327                 if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) ||
3328                     pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
3329                     ALOGV("\tLVM_ERROR : Volume_command cmdCode Case: "
3330                           "EFFECT_CMD_SET_PARAM: ERROR");
3331                     return -EINVAL;
3332                 }
3333 
3334                 effect_param_t* const p = (effect_param_t*)pCmdData;
3335                 const uint32_t voffset = computeParamVOffset(p);
3336 
3337                 *(int*)pReplyData = android::Volume_setParameter(pContext, p->psize, (void*)p->data,
3338                                                                  p->vsize, p->data + voffset);
3339             }
3340             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_PARAM end");
3341         } break;
3342 
3343         case EFFECT_CMD_ENABLE:
3344             ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_ENABLE start");
3345             if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
3346                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_ENABLE: ERROR");
3347                 return -EINVAL;
3348             }
3349 
3350             *(int*)pReplyData = android::Effect_setEnabled(pContext, LVM_TRUE);
3351             break;
3352 
3353         case EFFECT_CMD_DISABLE:
3354             // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_DISABLE start");
3355             if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
3356                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_DISABLE: ERROR");
3357                 return -EINVAL;
3358             }
3359             *(int*)pReplyData = android::Effect_setEnabled(pContext, LVM_FALSE);
3360             break;
3361 
3362         case EFFECT_CMD_SET_DEVICE: {
3363             ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_DEVICE start");
3364             if (pCmdData == NULL) {
3365                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_SET_DEVICE: ERROR");
3366                 return -EINVAL;
3367             }
3368 
3369             audio_devices_t device = *(audio_devices_t *)pCmdData;
3370             pContext->pBundledContext->nOutputDevice = device;
3371 
3372             if (pContext->EffectType == LVM_BASS_BOOST) {
3373                 if ((device == AUDIO_DEVICE_OUT_SPEAKER) ||
3374                     (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) ||
3375                     (device == AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER)) {
3376                     ALOGV("\tEFFECT_CMD_SET_DEVICE device is invalid for LVM_BASS_BOOST %d",
3377                           *(int32_t*)pCmdData);
3378                     ALOGV("\tEFFECT_CMD_SET_DEVICE temporary disable LVM_BAS_BOOST");
3379 
3380                     // If a device doesn't support bassboost the effect must be temporarily disabled
3381                     // the effect must still report its original state as this can only be changed
3382                     // by the ENABLE/DISABLE command
3383 
3384                     if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
3385                         ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_BASS_BOOST %d",
3386                               *(int32_t*)pCmdData);
3387                         android::LvmEffect_disable(pContext);
3388                     }
3389                     pContext->pBundledContext->bBassTempDisabled = LVM_TRUE;
3390                 } else {
3391                     ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_BASS_BOOST %d",
3392                           *(int32_t*)pCmdData);
3393 
3394                     // If a device supports bassboost and the effect has been temporarily disabled
3395                     // previously then re-enable it
3396 
3397                     if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
3398                         ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_BASS_BOOST %d",
3399                               *(int32_t*)pCmdData);
3400                         android::LvmEffect_enable(pContext);
3401                     }
3402                     pContext->pBundledContext->bBassTempDisabled = LVM_FALSE;
3403                 }
3404             }
3405             if (pContext->EffectType == LVM_VIRTUALIZER) {
3406                 if (pContext->pBundledContext->nVirtualizerForcedDevice == AUDIO_DEVICE_NONE) {
3407                     // default case unless configuration is forced
3408                     if (android::VirtualizerIsDeviceSupported(device) != 0) {
3409                         ALOGV("\tEFFECT_CMD_SET_DEVICE device is invalid for LVM_VIRTUALIZER %d",
3410                               *(int32_t*)pCmdData);
3411                         ALOGV("\tEFFECT_CMD_SET_DEVICE temporary disable LVM_VIRTUALIZER");
3412 
3413                         // If a device doesn't support virtualizer the effect must be temporarily
3414                         // disabled the effect must still report its original state as this can
3415                         // only be changed by the ENABLE/DISABLE command
3416 
3417                         if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
3418                             ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_VIRTUALIZER %d",
3419                                   *(int32_t*)pCmdData);
3420                             android::LvmEffect_disable(pContext);
3421                         }
3422                         pContext->pBundledContext->bVirtualizerTempDisabled = LVM_TRUE;
3423                     } else {
3424                         ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_VIRTUALIZER %d",
3425                               *(int32_t*)pCmdData);
3426 
3427                         // If a device supports virtualizer and the effect has been temporarily
3428                         // disabled previously then re-enable it
3429 
3430                         if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
3431                             ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_VIRTUALIZER %d",
3432                                   *(int32_t*)pCmdData);
3433                             android::LvmEffect_enable(pContext);
3434                         }
3435                         pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE;
3436                     }
3437                 }  // else virtualization mode is forced to a certain device, nothing to do
3438             }
3439             ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_DEVICE end");
3440             break;
3441         }
3442         case EFFECT_CMD_SET_VOLUME: {
3443             uint32_t leftVolume, rightVolume;
3444             int16_t leftdB, rightdB;
3445             int16_t maxdB, pandB;
3446             int32_t vol_ret[2] = {1 << 24, 1 << 24};     // Apply no volume
3447             LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
3448             LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
3449 
3450             // if pReplyData is NULL, VOL_CTRL is delegated to another effect
3451             if (pReplyData == LVM_NULL) {
3452                 break;
3453             }
3454 
3455             if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t) || pReplyData == NULL ||
3456                 replySize == NULL || *replySize < 2 * sizeof(int32_t)) {
3457                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: "
3458                       "EFFECT_CMD_SET_VOLUME: ERROR");
3459                 return -EINVAL;
3460             }
3461 
3462             leftVolume = ((*(uint32_t*)pCmdData));
3463             rightVolume = ((*((uint32_t*)pCmdData + 1)));
3464 
3465             if (leftVolume == 0x1000000) {
3466                 leftVolume -= 1;
3467             }
3468             if (rightVolume == 0x1000000) {
3469                 rightVolume -= 1;
3470             }
3471 
3472             // Convert volume to dB
3473             leftdB = android::LVC_Convert_VolToDb(leftVolume);
3474             rightdB = android::LVC_Convert_VolToDb(rightVolume);
3475 
3476             pandB = rightdB - leftdB;
3477 
3478             // Calculate max volume in dB
3479             maxdB = leftdB;
3480             if (rightdB > maxdB) {
3481                 maxdB = rightdB;
3482             }
3483             // ALOGV("\tEFFECT_CMD_SET_VOLUME Session: %d, SessionID: %d VOLUME is %d dB, "
3484             //      "effect is %d",
3485             // pContext->pBundledContext->SessionNo, pContext->pBundledContext->SessionId,
3486             //(int32_t)maxdB, pContext->EffectType);
3487             // ALOGV("\tEFFECT_CMD_SET_VOLUME: Left is %d, Right is %d", leftVolume, rightVolume);
3488             // ALOGV("\tEFFECT_CMD_SET_VOLUME: Left %ddB, Right %ddB, Position %ddB",
3489             //        leftdB, rightdB, pandB);
3490 
3491             memcpy(pReplyData, vol_ret, sizeof(int32_t) * 2);
3492             android::VolumeSetVolumeLevel(pContext, (int16_t)(maxdB * 100));
3493 
3494             /* Get the current settings */
3495             LvmStatus =
3496                     LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
3497             LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeSetStereoPosition")
3498             if (LvmStatus != LVM_SUCCESS) return -EINVAL;
3499 
3500             /* Volume parameters */
3501             ActiveParams.VC_Balance = pandB;
3502             ALOGV("\t\tVolumeSetStereoPosition() (-96dB -> +96dB)-> %d\n", ActiveParams.VC_Balance);
3503 
3504             /* Activate the initial settings */
3505             LvmStatus =
3506                     LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
3507             LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VolumeSetStereoPosition")
3508             if (LvmStatus != LVM_SUCCESS) return -EINVAL;
3509             break;
3510         }
3511         case EFFECT_CMD_SET_AUDIO_MODE:
3512             break;
3513         default:
3514             return -EINVAL;
3515     }
3516 
3517     // ALOGV("\tEffect_command end...\n\n");
3518     return 0;
3519 } /* end Effect_command */
3520 
3521 /* Effect Control Interface Implementation: get_descriptor */
Effect_getDescriptor(effect_handle_t self,effect_descriptor_t * pDescriptor)3522 int Effect_getDescriptor(effect_handle_t self, effect_descriptor_t* pDescriptor) {
3523     EffectContext* pContext = (EffectContext*)self;
3524     const effect_descriptor_t* desc;
3525 
3526     if (pContext == NULL || pDescriptor == NULL) {
3527         ALOGV("Effect_getDescriptor() invalid param");
3528         return -EINVAL;
3529     }
3530 
3531     switch (pContext->EffectType) {
3532         case LVM_BASS_BOOST:
3533             desc = &android::gBassBoostDescriptor;
3534             break;
3535         case LVM_VIRTUALIZER:
3536             desc = &android::gVirtualizerDescriptor;
3537             break;
3538         case LVM_EQUALIZER:
3539             desc = &android::gEqualizerDescriptor;
3540             break;
3541         case LVM_VOLUME:
3542             desc = &android::gVolumeDescriptor;
3543             break;
3544         default:
3545             return -EINVAL;
3546     }
3547 
3548     *pDescriptor = *desc;
3549 
3550     return 0;
3551 } /* end Effect_getDescriptor */
3552 
3553 // effect_handle_t interface implementation for effect
3554 const struct effect_interface_s gLvmEffectInterface = {
3555         Effect_process,
3556         Effect_command,
3557         Effect_getDescriptor,
3558         NULL,
3559 }; /* end gLvmEffectInterface */
3560 
3561 // This is the only symbol that needs to be exported
3562 __attribute__((visibility("default"))) audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM = {
3563         .tag = AUDIO_EFFECT_LIBRARY_TAG,
3564         .version = EFFECT_LIBRARY_API_VERSION,
3565         .name = "Effect Bundle Library",
3566         .implementor = "NXP Software Ltd.",
3567         .create_effect = android::EffectCreate,
3568         .release_effect = android::EffectRelease,
3569         .get_descriptor = android::EffectGetDescriptor,
3570 };
3571 }
3572