summaryrefslogtreecommitdiffstats
path: root/media/libeffects/loudness/EffectLoudnessEnhancer.cpp
blob: 3c2b32016fe6c1169f96fdcc92d58a9cb76f37df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "EffectLE"
//#define LOG_NDEBUG 0
#include <cutils/log.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <new>
#include <time.h>
#include <math.h>
#include <audio_effects/effect_loudnessenhancer.h>
#include "dsp/core/dynamic_range_compression.h"

extern "C" {

// effect_handle_t interface implementation for LE effect
extern const struct effect_interface_s gLEInterface;

// AOSP Loudness Enhancer UUID: fa415329-2034-4bea-b5dc-5b381c8d1e2c
const effect_descriptor_t gLEDescriptor = {
        {0xfe3199be, 0xaed0, 0x413f, 0x87bb, {0x11, 0x26, 0x0e, 0xb6, 0x3c, 0xf1}}, // type
        {0xfa415329, 0x2034, 0x4bea, 0xb5dc, {0x5b, 0x38, 0x1c, 0x8d, 0x1e, 0x2c}}, // uuid
        EFFECT_CONTROL_API_VERSION,
        (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_FIRST),
        0, // TODO
        1,
        "Loudness Enhancer",
        "The Android Open Source Project",
};

enum le_state_e {
    LOUDNESS_ENHANCER_STATE_UNINITIALIZED,
    LOUDNESS_ENHANCER_STATE_INITIALIZED,
    LOUDNESS_ENHANCER_STATE_ACTIVE,
};

struct LoudnessEnhancerContext {
    const struct effect_interface_s *mItfe;
    effect_config_t mConfig;
    uint8_t mState;
    int32_t mTargetGainmB;// target gain in mB
    // in this implementation, there is no coupling between the compression on the left and right
    // channels
    le_fx::AdaptiveDynamicRangeCompression* mCompressor;
};

//
//--- Local functions (not directly used by effect interface)
//

void LE_reset(LoudnessEnhancerContext *pContext)
{
    ALOGV("  > LE_reset(%p)", pContext);

    if (pContext->mCompressor != NULL) {
        float targetAmp = pow(10, pContext->mTargetGainmB/2000.0f); // mB to linear amplification
        ALOGV("LE_reset(): Target gain=%dmB <=> factor=%.2fX", pContext->mTargetGainmB, targetAmp);
        pContext->mCompressor->Initialize(targetAmp, pContext->mConfig.inputCfg.samplingRate);
    } else {
        ALOGE("LE_reset(%p): null compressors, can't apply target gain", pContext);
    }
}

static inline int16_t clamp16(int32_t sample)
{
    if ((sample>>15) ^ (sample>>31))
        sample = 0x7FFF ^ (sample>>31);
    return sample;
}

//----------------------------------------------------------------------------
// LE_setConfig()
//----------------------------------------------------------------------------
// Purpose: Set input and output audio configuration.
//
// Inputs:
//  pContext:   effect engine context
//  pConfig:    pointer to effect_config_t structure holding input and output
//      configuration parameters
//
// Outputs:
//
//----------------------------------------------------------------------------

int LE_setConfig(LoudnessEnhancerContext *pContext, effect_config_t *pConfig)
{
    ALOGV("LE_setConfig(%p)", pContext);

    if (pConfig->inputCfg.samplingRate != pConfig->outputCfg.samplingRate) return -EINVAL;
    if (pConfig->inputCfg.channels != pConfig->outputCfg.channels) return -EINVAL;
    if (pConfig->inputCfg.format != pConfig->outputCfg.format) return -EINVAL;
    if (pConfig->inputCfg.channels != AUDIO_CHANNEL_OUT_STEREO) return -EINVAL;
    if (pConfig->outputCfg.accessMode != EFFECT_BUFFER_ACCESS_WRITE &&
            pConfig->outputCfg.accessMode != EFFECT_BUFFER_ACCESS_ACCUMULATE) return -EINVAL;
    if (pConfig->inputCfg.format != AUDIO_FORMAT_PCM_16_BIT) return -EINVAL;

    pContext->mConfig = *pConfig;

    LE_reset(pContext);

    return 0;
}


//----------------------------------------------------------------------------
// LE_getConfig()
//----------------------------------------------------------------------------
// Purpose: Get input and output audio configuration.
//
// Inputs:
//  pContext:   effect engine context
//  pConfig:    pointer to effect_config_t structure holding input and output
//      configuration parameters
//
// Outputs:
//
//----------------------------------------------------------------------------

void LE_getConfig(LoudnessEnhancerContext *pContext, effect_config_t *pConfig)
{
    *pConfig = pContext->mConfig;
}


//----------------------------------------------------------------------------
// LE_init()
//----------------------------------------------------------------------------
// Purpose: Initialize engine with default configuration.
//
// Inputs:
//  pContext:   effect engine context
//
// Outputs:
//
//----------------------------------------------------------------------------

int LE_init(LoudnessEnhancerContext *pContext)
{
    ALOGV("LE_init(%p)", pContext);

    pContext->mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
    pContext->mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
    pContext->mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
    pContext->mConfig.inputCfg.samplingRate = 44100;
    pContext->mConfig.inputCfg.bufferProvider.getBuffer = NULL;
    pContext->mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
    pContext->mConfig.inputCfg.bufferProvider.cookie = NULL;
    pContext->mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
    pContext->mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
    pContext->mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
    pContext->mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
    pContext->mConfig.outputCfg.samplingRate = 44100;
    pContext->mConfig.outputCfg.bufferProvider.getBuffer = NULL;
    pContext->mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
    pContext->mConfig.outputCfg.bufferProvider.cookie = NULL;
    pContext->mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;

    pContext->mTargetGainmB = LOUDNESS_ENHANCER_DEFAULT_TARGET_GAIN_MB;
    float targetAmp = pow(10, pContext->mTargetGainmB/2000.0f); // mB to linear amplification
    ALOGV("LE_init(): Target gain=%dmB <=> factor=%.2fX", pContext->mTargetGainmB, targetAmp);

    if (pContext->mCompressor == NULL) {
        pContext->mCompressor = new le_fx::AdaptiveDynamicRangeCompression();
        pContext->mCompressor->Initialize(targetAmp, pContext->mConfig.inputCfg.samplingRate);
    }

    LE_setConfig(pContext, &pContext->mConfig);

    return 0;
}

//
//--- Effect Library Interface Implementation
//

int LELib_Create(const effect_uuid_t *uuid,
                         int32_t sessionId,
                         int32_t ioId,
                         effect_handle_t *pHandle) {
    ALOGV("LELib_Create()");
    int ret;
    int i;

    if (pHandle == NULL || uuid == NULL) {
        return -EINVAL;
    }

    if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) {
        return -EINVAL;
    }

    LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext;

    pContext->mItfe = &gLEInterface;
    pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;

    pContext->mCompressor = NULL;
    ret = LE_init(pContext);
    if (ret < 0) {
        ALOGW("LELib_Create() init failed");
        delete pContext;
        return ret;
    }

    *pHandle = (effect_handle_t)pContext;

    pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;

    ALOGV("  LELib_Create context is %p", pContext);

    return 0;

}

int LELib_Release(effect_handle_t handle) {
    LoudnessEnhancerContext * pContext = (LoudnessEnhancerContext *)handle;

    ALOGV("LELib_Release %p", handle);
    if (pContext == NULL) {
        return -EINVAL;
    }
    pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;
    if (pContext->mCompressor != NULL) {
        delete pContext->mCompressor;
        pContext->mCompressor = NULL;
    }
    delete pContext;

    return 0;
}

int LELib_GetDescriptor(const effect_uuid_t *uuid,
                                effect_descriptor_t *pDescriptor) {

    if (pDescriptor == NULL || uuid == NULL){
        ALOGV("LELib_GetDescriptor() called with NULL pointer");
        return -EINVAL;
    }

    if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
        *pDescriptor = gLEDescriptor;
        return 0;
    }

    return  -EINVAL;
} /* end LELib_GetDescriptor */

//
//--- Effect Control Interface Implementation
//
int LE_process(
        effect_handle_t self, audio_buffer_t *inBuffer, audio_buffer_t *outBuffer)
{
    LoudnessEnhancerContext * pContext = (LoudnessEnhancerContext *)self;

    if (pContext == NULL) {
        return -EINVAL;
    }

    if (inBuffer == NULL || inBuffer->raw == NULL ||
        outBuffer == NULL || outBuffer->raw == NULL ||
        inBuffer->frameCount != outBuffer->frameCount ||
        inBuffer->frameCount == 0) {
        return -EINVAL;
    }

    //ALOGV("LE about to process %d samples", inBuffer->frameCount);
    uint16_t inIdx;
    float inputAmp = pow(10, pContext->mTargetGainmB/2000.0f);
    float leftSample, rightSample;
    for (inIdx = 0 ; inIdx < inBuffer->frameCount ; inIdx++) {
        // makeup gain is applied on the input of the compressor
        leftSample  = inputAmp * (float)inBuffer->s16[2*inIdx];
        rightSample = inputAmp * (float)inBuffer->s16[2*inIdx +1];
        pContext->mCompressor->Compress(&leftSample, &rightSample);
        inBuffer->s16[2*inIdx]    = (int16_t) leftSample;
        inBuffer->s16[2*inIdx +1] = (int16_t) rightSample;
    }

    if (inBuffer->raw != outBuffer->raw) {
        if (pContext->mConfig.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
            for (size_t i = 0; i < outBuffer->frameCount*2; i++) {
                outBuffer->s16[i] = clamp16(outBuffer->s16[i] + inBuffer->s16[i]);
            }
        } else {
            memcpy(outBuffer->raw, inBuffer->raw, outBuffer->frameCount * 2 * sizeof(int16_t));
        }
    }
    if (pContext->mState != LOUDNESS_ENHANCER_STATE_ACTIVE) {
        return -ENODATA;
    }
    return 0;
}

int LE_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
        void *pCmdData, uint32_t *replySize, void *pReplyData) {

    LoudnessEnhancerContext * pContext = (LoudnessEnhancerContext *)self;
    int retsize;

    if (pContext == NULL || pContext->mState == LOUDNESS_ENHANCER_STATE_UNINITIALIZED) {
        return -EINVAL;
    }

//    ALOGV("LE_command command %d cmdSize %d",cmdCode, cmdSize);
    switch (cmdCode) {
    case EFFECT_CMD_INIT:
        if (pReplyData == NULL || *replySize != sizeof(int)) {
            return -EINVAL;
        }
        *(int *) pReplyData = LE_init(pContext);
        break;
    case EFFECT_CMD_SET_CONFIG:
        if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
                || pReplyData == NULL || *replySize != sizeof(int)) {
            return -EINVAL;
        }
        *(int *) pReplyData = LE_setConfig(pContext,
                (effect_config_t *) pCmdData);
        break;
    case EFFECT_CMD_GET_CONFIG:
        if (pReplyData == NULL ||
            *replySize != sizeof(effect_config_t)) {
            return -EINVAL;
        }
        LE_getConfig(pContext, (effect_config_t *)pReplyData);
        break;
    case EFFECT_CMD_RESET:
        LE_reset(pContext);
        break;
    case EFFECT_CMD_ENABLE:
        if (pReplyData == NULL || *replySize != sizeof(int)) {
            return -EINVAL;
        }
        if (pContext->mState != LOUDNESS_ENHANCER_STATE_INITIALIZED) {
            return -ENOSYS;
        }
        pContext->mState = LOUDNESS_ENHANCER_STATE_ACTIVE;
        ALOGV("EFFECT_CMD_ENABLE() OK");
        *(int *)pReplyData = 0;
        break;
    case EFFECT_CMD_DISABLE:
        if (pReplyData == NULL || *replySize != sizeof(int)) {
            return -EINVAL;
        }
        if (pContext->mState != LOUDNESS_ENHANCER_STATE_ACTIVE) {
            return -ENOSYS;
        }
        pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;
        ALOGV("EFFECT_CMD_DISABLE() OK");
        *(int *)pReplyData = 0;
        break;
    case EFFECT_CMD_GET_PARAM: {
        if (pCmdData == NULL ||
            cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t)) ||
            pReplyData == NULL ||
            *replySize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t))) {
            return -EINVAL;
        }
        memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(uint32_t));
        effect_param_t *p = (effect_param_t *)pReplyData;
        p->status = 0;
        *replySize = sizeof(effect_param_t) + sizeof(uint32_t);
        if (p->psize != sizeof(uint32_t)) {
            p->status = -EINVAL;
            break;
        }
        switch (*(uint32_t *)p->data) {
        case LOUDNESS_ENHANCER_PARAM_TARGET_GAIN_MB:
            ALOGV("get target gain(mB) = %d", pContext->mTargetGainmB);
            *((int32_t *)p->data + 1) = pContext->mTargetGainmB;
            p->vsize = sizeof(int32_t);
            *replySize += sizeof(int32_t);
            break;
        default:
            p->status = -EINVAL;
        }
        } break;
    case EFFECT_CMD_SET_PARAM: {
        if (pCmdData == NULL ||
            cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t)) ||
            pReplyData == NULL || *replySize != sizeof(int32_t)) {
            return -EINVAL;
        }
        *(int32_t *)pReplyData = 0;
        effect_param_t *p = (effect_param_t *)pCmdData;
        if (p->psize != sizeof(uint32_t) || p->vsize != sizeof(uint32_t)) {
            *(int32_t *)pReplyData = -EINVAL;
            break;
        }
        switch (*(uint32_t *)p->data) {
        case LOUDNESS_ENHANCER_PARAM_TARGET_GAIN_MB:
            pContext->mTargetGainmB = *((int32_t *)p->data + 1);
            ALOGV("set target gain(mB) = %d", pContext->mTargetGainmB);
            LE_reset(pContext); // apply parameter update
            break;
        default:
            *(int32_t *)pReplyData = -EINVAL;
        }
        } break;
    case EFFECT_CMD_SET_DEVICE:
    case EFFECT_CMD_SET_VOLUME:
    case EFFECT_CMD_SET_AUDIO_MODE:
        break;

    default:
        ALOGW("LE_command invalid command %d",cmdCode);
        return -EINVAL;
    }

    return 0;
}

/* Effect Control Interface Implementation: get_descriptor */
int LE_getDescriptor(effect_handle_t   self,
                                    effect_descriptor_t *pDescriptor)
{
    LoudnessEnhancerContext * pContext = (LoudnessEnhancerContext *) self;

    if (pContext == NULL || pDescriptor == NULL) {
        ALOGV("LE_getDescriptor() invalid param");
        return -EINVAL;
    }

    *pDescriptor = gLEDescriptor;

    return 0;
}   /* end LE_getDescriptor */

// effect_handle_t interface implementation for DRC effect
const struct effect_interface_s gLEInterface = {
        LE_process,
        LE_command,
        LE_getDescriptor,
        NULL,
};

// This is the only symbol that needs to be exported
__attribute__ ((visibility ("default")))
audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM = {
    .tag = AUDIO_EFFECT_LIBRARY_TAG,
    .version = EFFECT_LIBRARY_API_VERSION,
    .name = "Loudness Enhancer Library",
    .implementor = "The Android Open Source Project",
    .create_effect = LELib_Create,
    .release_effect = LELib_Release,
    .get_descriptor = LELib_GetDescriptor,
};

}; // extern "C"