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