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