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