1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "SoftG711"
19#include <utils/Log.h>
20
21#include "SoftG711.h"
22
23#include <media/stagefright/foundation/ADebug.h>
24#include <media/stagefright/MediaDefs.h>
25
26namespace android {
27
28template<class T>
29static void InitOMXParams(T *params) {
30    params->nSize = sizeof(T);
31    params->nVersion.s.nVersionMajor = 1;
32    params->nVersion.s.nVersionMinor = 0;
33    params->nVersion.s.nRevision = 0;
34    params->nVersion.s.nStep = 0;
35}
36
37SoftG711::SoftG711(
38        const char *name,
39        const OMX_CALLBACKTYPE *callbacks,
40        OMX_PTR appData,
41        OMX_COMPONENTTYPE **component)
42    : SimpleSoftOMXComponent(name, callbacks, appData, component),
43      mIsMLaw(true),
44      mSignalledError(false),
45      mNumChannels(1),
46      mSamplingRate(8000) {
47    if (!strcmp(name, "OMX.google.g711.alaw.decoder")) {
48        mIsMLaw = false;
49    } else {
50        CHECK(!strcmp(name, "OMX.google.g711.mlaw.decoder"));
51    }
52
53    initPorts();
54}
55
56SoftG711::~SoftG711() {
57}
58
59void SoftG711::initPorts() {
60    OMX_PARAM_PORTDEFINITIONTYPE def;
61    InitOMXParams(&def);
62
63    def.nPortIndex = 0;
64    def.eDir = OMX_DirInput;
65    def.nBufferCountMin = kNumBuffers;
66    def.nBufferCountActual = def.nBufferCountMin;
67    def.nBufferSize = 8192;
68    def.bEnabled = OMX_TRUE;
69    def.bPopulated = OMX_FALSE;
70    def.eDomain = OMX_PortDomainAudio;
71    def.bBuffersContiguous = OMX_FALSE;
72    def.nBufferAlignment = 1;
73
74    def.format.audio.cMIMEType =
75        const_cast<char *>(
76                mIsMLaw
77                    ? MEDIA_MIMETYPE_AUDIO_G711_MLAW
78                    : MEDIA_MIMETYPE_AUDIO_G711_ALAW);
79
80    def.format.audio.pNativeRender = NULL;
81    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
82    def.format.audio.eEncoding = OMX_AUDIO_CodingG711;
83
84    addPort(def);
85
86    def.nPortIndex = 1;
87    def.eDir = OMX_DirOutput;
88    def.nBufferCountMin = kNumBuffers;
89    def.nBufferCountActual = def.nBufferCountMin;
90    def.nBufferSize = kMaxNumSamplesPerFrame * sizeof(int16_t);
91    def.bEnabled = OMX_TRUE;
92    def.bPopulated = OMX_FALSE;
93    def.eDomain = OMX_PortDomainAudio;
94    def.bBuffersContiguous = OMX_FALSE;
95    def.nBufferAlignment = 2;
96
97    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
98    def.format.audio.pNativeRender = NULL;
99    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
100    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
101
102    addPort(def);
103}
104
105OMX_ERRORTYPE SoftG711::internalGetParameter(
106        OMX_INDEXTYPE index, OMX_PTR params) {
107    switch (index) {
108        case OMX_IndexParamAudioPcm:
109        {
110            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
111                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
112
113            if (!isValidOMXParam(pcmParams)) {
114                return OMX_ErrorBadParameter;
115            }
116
117            if (pcmParams->nPortIndex > 1) {
118                return OMX_ErrorUndefined;
119            }
120
121            pcmParams->eNumData = OMX_NumericalDataSigned;
122            pcmParams->eEndian = OMX_EndianBig;
123            pcmParams->bInterleaved = OMX_TRUE;
124            pcmParams->nBitPerSample = 16;
125            if (pcmParams->nPortIndex == 0) {
126                // input port
127                pcmParams->ePCMMode = mIsMLaw ? OMX_AUDIO_PCMModeMULaw
128                                              : OMX_AUDIO_PCMModeALaw;
129            } else {
130                // output port
131                pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
132            }
133            pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
134            pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
135
136            pcmParams->nChannels = mNumChannels;
137            pcmParams->nSamplingRate = mSamplingRate;
138
139            return OMX_ErrorNone;
140        }
141
142        default:
143            return SimpleSoftOMXComponent::internalGetParameter(index, params);
144    }
145}
146
147OMX_ERRORTYPE SoftG711::internalSetParameter(
148        OMX_INDEXTYPE index, const OMX_PTR params) {
149    switch (index) {
150        case OMX_IndexParamAudioPcm:
151        {
152            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
153                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
154
155            if (!isValidOMXParam(pcmParams)) {
156                return OMX_ErrorBadParameter;
157            }
158
159            if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
160                return OMX_ErrorUndefined;
161            }
162
163            if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) {
164                return OMX_ErrorUndefined;
165            }
166
167            if(pcmParams->nPortIndex == 0) {
168                mNumChannels = pcmParams->nChannels;
169            }
170
171            mSamplingRate = pcmParams->nSamplingRate;
172
173            return OMX_ErrorNone;
174        }
175
176        case OMX_IndexParamStandardComponentRole:
177        {
178            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
179                (const OMX_PARAM_COMPONENTROLETYPE *)params;
180
181            if (!isValidOMXParam(roleParams)) {
182                return OMX_ErrorBadParameter;
183            }
184
185            if (mIsMLaw) {
186                if (strncmp((const char *)roleParams->cRole,
187                            "audio_decoder.g711mlaw",
188                            OMX_MAX_STRINGNAME_SIZE - 1)) {
189                    return OMX_ErrorUndefined;
190                }
191            } else {
192                if (strncmp((const char *)roleParams->cRole,
193                            "audio_decoder.g711alaw",
194                            OMX_MAX_STRINGNAME_SIZE - 1)) {
195                    return OMX_ErrorUndefined;
196                }
197            }
198
199            return OMX_ErrorNone;
200        }
201
202        default:
203            return SimpleSoftOMXComponent::internalSetParameter(index, params);
204    }
205}
206
207void SoftG711::onQueueFilled(OMX_U32 /* portIndex */) {
208    if (mSignalledError) {
209        return;
210    }
211
212    List<BufferInfo *> &inQueue = getPortQueue(0);
213    List<BufferInfo *> &outQueue = getPortQueue(1);
214
215    while (!inQueue.empty() && !outQueue.empty()) {
216        BufferInfo *inInfo = *inQueue.begin();
217        OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
218
219        BufferInfo *outInfo = *outQueue.begin();
220        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
221
222        if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
223            inQueue.erase(inQueue.begin());
224            inInfo->mOwnedByUs = false;
225            notifyEmptyBufferDone(inHeader);
226
227            outHeader->nFilledLen = 0;
228            outHeader->nFlags = OMX_BUFFERFLAG_EOS;
229
230            outQueue.erase(outQueue.begin());
231            outInfo->mOwnedByUs = false;
232            notifyFillBufferDone(outHeader);
233            return;
234        }
235
236        if (inHeader->nFilledLen > kMaxNumSamplesPerFrame) {
237            ALOGE("input buffer too large (%d).", inHeader->nFilledLen);
238
239            notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
240            mSignalledError = true;
241        }
242
243        if (inHeader->nFilledLen * sizeof(int16_t) > outHeader->nAllocLen) {
244            ALOGE("output buffer too small (%d).", outHeader->nAllocLen);
245            android_errorWriteLog(0x534e4554, "27793163");
246
247            notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
248            mSignalledError = true;
249            return;
250        }
251
252        const uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset;
253
254        if (mIsMLaw) {
255            DecodeMLaw(
256                    reinterpret_cast<int16_t *>(outHeader->pBuffer),
257                    inputptr, inHeader->nFilledLen);
258        } else {
259            DecodeALaw(
260                    reinterpret_cast<int16_t *>(outHeader->pBuffer),
261                    inputptr, inHeader->nFilledLen);
262        }
263
264        outHeader->nTimeStamp = inHeader->nTimeStamp;
265        outHeader->nOffset = 0;
266        outHeader->nFilledLen = inHeader->nFilledLen * sizeof(int16_t);
267        outHeader->nFlags = 0;
268
269        inInfo->mOwnedByUs = false;
270        inQueue.erase(inQueue.begin());
271        inInfo = NULL;
272        notifyEmptyBufferDone(inHeader);
273        inHeader = NULL;
274
275        outInfo->mOwnedByUs = false;
276        outQueue.erase(outQueue.begin());
277        outInfo = NULL;
278        notifyFillBufferDone(outHeader);
279        outHeader = NULL;
280    }
281}
282
283// static
284void SoftG711::DecodeALaw(
285        int16_t *out, const uint8_t *in, size_t inSize) {
286    while (inSize > 0) {
287        inSize--;
288        int32_t x = *in++;
289
290        int32_t ix = x ^ 0x55;
291        ix &= 0x7f;
292
293        int32_t iexp = ix >> 4;
294        int32_t mant = ix & 0x0f;
295
296        if (iexp > 0) {
297            mant += 16;
298        }
299
300        mant = (mant << 4) + 8;
301
302        if (iexp > 1) {
303            mant = mant << (iexp - 1);
304        }
305
306        *out++ = (x > 127) ? mant : -mant;
307    }
308}
309
310// static
311void SoftG711::DecodeMLaw(
312        int16_t *out, const uint8_t *in, size_t inSize) {
313    while (inSize > 0) {
314        inSize--;
315        int32_t x = *in++;
316
317        int32_t mantissa = ~x;
318        int32_t exponent = (mantissa >> 4) & 7;
319        int32_t segment = exponent + 1;
320        mantissa &= 0x0f;
321
322        int32_t step = 4 << segment;
323
324        int32_t abs = (0x80l << exponent) + step * mantissa + step / 2 - 4 * 33;
325
326        *out++ = (x < 0x80) ? -abs : abs;
327    }
328}
329
330}  // namespace android
331
332android::SoftOMXComponent *createSoftOMXComponent(
333        const char *name, const OMX_CALLBACKTYPE *callbacks,
334        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
335    return new android::SoftG711(name, callbacks, appData, component);
336}
337
338