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