SoftMP3.cpp revision 259b39cbfc03cb94c48e66d752836e153e9a2f8b
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 "SoftMP3"
19#include <utils/Log.h>
20
21#include "SoftMP3.h"
22
23#include <media/stagefright/foundation/ADebug.h>
24#include <media/stagefright/MediaDefs.h>
25
26#include "include/pvmp3decoder_api.h"
27
28namespace android {
29
30template<class T>
31static void InitOMXParams(T *params) {
32    params->nSize = sizeof(T);
33    params->nVersion.s.nVersionMajor = 1;
34    params->nVersion.s.nVersionMinor = 0;
35    params->nVersion.s.nRevision = 0;
36    params->nVersion.s.nStep = 0;
37}
38
39SoftMP3::SoftMP3(
40        const char *name,
41        const OMX_CALLBACKTYPE *callbacks,
42        OMX_PTR appData,
43        OMX_COMPONENTTYPE **component)
44    : SimpleSoftOMXComponent(name, callbacks, appData, component),
45      mConfig(new tPVMP3DecoderExternal),
46      mDecoderBuf(NULL),
47      mAnchorTimeUs(0),
48      mNumFramesOutput(0),
49      mNumChannels(2),
50      mSamplingRate(44100),
51      mSignalledError(false),
52      mOutputPortSettingsChange(NONE) {
53    initPorts();
54    initDecoder();
55}
56
57SoftMP3::~SoftMP3() {
58    if (mDecoderBuf != NULL) {
59        free(mDecoderBuf);
60        mDecoderBuf = NULL;
61    }
62
63    delete mConfig;
64    mConfig = NULL;
65}
66
67void SoftMP3::initPorts() {
68    OMX_PARAM_PORTDEFINITIONTYPE def;
69    InitOMXParams(&def);
70
71    def.nPortIndex = 0;
72    def.eDir = OMX_DirInput;
73    def.nBufferCountMin = kNumBuffers;
74    def.nBufferCountActual = def.nBufferCountMin;
75    def.nBufferSize = 8192;
76    def.bEnabled = OMX_TRUE;
77    def.bPopulated = OMX_FALSE;
78    def.eDomain = OMX_PortDomainAudio;
79    def.bBuffersContiguous = OMX_FALSE;
80    def.nBufferAlignment = 1;
81
82    def.format.audio.cMIMEType =
83        const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
84
85    def.format.audio.pNativeRender = NULL;
86    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
87    def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
88
89    addPort(def);
90
91    def.nPortIndex = 1;
92    def.eDir = OMX_DirOutput;
93    def.nBufferCountMin = kNumBuffers;
94    def.nBufferCountActual = def.nBufferCountMin;
95    def.nBufferSize = kOutputBufferSize;
96    def.bEnabled = OMX_TRUE;
97    def.bPopulated = OMX_FALSE;
98    def.eDomain = OMX_PortDomainAudio;
99    def.bBuffersContiguous = OMX_FALSE;
100    def.nBufferAlignment = 2;
101
102    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
103    def.format.audio.pNativeRender = NULL;
104    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
105    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
106
107    addPort(def);
108}
109
110void SoftMP3::initDecoder() {
111    mConfig->equalizerType = flat;
112    mConfig->crcEnabled = false;
113
114    uint32_t memRequirements = pvmp3_decoderMemRequirements();
115    mDecoderBuf = malloc(memRequirements);
116
117    pvmp3_InitDecoder(mConfig, mDecoderBuf);
118    mIsFirst = true;
119}
120
121OMX_ERRORTYPE SoftMP3::internalGetParameter(
122        OMX_INDEXTYPE index, OMX_PTR params) {
123    switch (index) {
124        case OMX_IndexParamAudioPcm:
125        {
126            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
127                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
128
129            if (pcmParams->nPortIndex > 1) {
130                return OMX_ErrorUndefined;
131            }
132
133            pcmParams->eNumData = OMX_NumericalDataSigned;
134            pcmParams->eEndian = OMX_EndianBig;
135            pcmParams->bInterleaved = OMX_TRUE;
136            pcmParams->nBitPerSample = 16;
137            pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
138            pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
139            pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
140
141            pcmParams->nChannels = mNumChannels;
142            pcmParams->nSamplingRate = mSamplingRate;
143
144            return OMX_ErrorNone;
145        }
146
147        default:
148            return SimpleSoftOMXComponent::internalGetParameter(index, params);
149    }
150}
151
152OMX_ERRORTYPE SoftMP3::internalSetParameter(
153        OMX_INDEXTYPE index, const OMX_PTR params) {
154    switch (index) {
155        case OMX_IndexParamStandardComponentRole:
156        {
157            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
158                (const OMX_PARAM_COMPONENTROLETYPE *)params;
159
160            if (strncmp((const char *)roleParams->cRole,
161                        "audio_decoder.mp3",
162                        OMX_MAX_STRINGNAME_SIZE - 1)) {
163                return OMX_ErrorUndefined;
164            }
165
166            return OMX_ErrorNone;
167        }
168
169        default:
170            return SimpleSoftOMXComponent::internalSetParameter(index, params);
171    }
172}
173
174void SoftMP3::onQueueFilled(OMX_U32 portIndex) {
175    if (mSignalledError || mOutputPortSettingsChange != NONE) {
176        return;
177    }
178
179    List<BufferInfo *> &inQueue = getPortQueue(0);
180    List<BufferInfo *> &outQueue = getPortQueue(1);
181
182    while (!inQueue.empty() && !outQueue.empty()) {
183        BufferInfo *inInfo = *inQueue.begin();
184        OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
185
186        BufferInfo *outInfo = *outQueue.begin();
187        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
188
189        if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
190            inQueue.erase(inQueue.begin());
191            inInfo->mOwnedByUs = false;
192            notifyEmptyBufferDone(inHeader);
193
194            // pad the end of the stream with 529 samples, since that many samples
195            // were trimmed off the beginning when decoding started
196            outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
197            memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
198            outHeader->nFlags = OMX_BUFFERFLAG_EOS;
199
200            outQueue.erase(outQueue.begin());
201            outInfo->mOwnedByUs = false;
202            notifyFillBufferDone(outHeader);
203            return;
204        }
205
206        if (inHeader->nOffset == 0) {
207            mAnchorTimeUs = inHeader->nTimeStamp;
208            mNumFramesOutput = 0;
209        }
210
211        mConfig->pInputBuffer =
212            inHeader->pBuffer + inHeader->nOffset;
213
214        mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
215        mConfig->inputBufferMaxLength = 0;
216        mConfig->inputBufferUsedLength = 0;
217
218        mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
219
220        mConfig->pOutputBuffer =
221            reinterpret_cast<int16_t *>(outHeader->pBuffer);
222
223        ERROR_CODE decoderErr;
224        if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
225                != NO_DECODING_ERROR) {
226            ALOGV("mp3 decoder returned error %d", decoderErr);
227
228            if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
229                        && decoderErr != SIDE_INFO_ERROR) {
230                ALOGE("mp3 decoder returned error %d", decoderErr);
231
232                notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
233                mSignalledError = true;
234                return;
235            }
236
237            if (mConfig->outputFrameSize == 0) {
238                mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
239            }
240
241            // This is recoverable, just ignore the current frame and
242            // play silence instead.
243            memset(outHeader->pBuffer,
244                   0,
245                   mConfig->outputFrameSize * sizeof(int16_t));
246
247            mConfig->inputBufferUsedLength = inHeader->nFilledLen;
248        } else if (mConfig->samplingRate != mSamplingRate
249                || mConfig->num_channels != mNumChannels) {
250            mSamplingRate = mConfig->samplingRate;
251            mNumChannels = mConfig->num_channels;
252
253            notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
254            mOutputPortSettingsChange = AWAITING_DISABLED;
255            return;
256        }
257
258        if (mIsFirst) {
259            mIsFirst = false;
260            // The decoder delay is 529 samples, so trim that many samples off
261            // the start of the first output buffer. This essentially makes this
262            // decoder have zero delay, which the rest of the pipeline assumes.
263            outHeader->nOffset = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
264            outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
265        } else {
266            outHeader->nOffset = 0;
267            outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
268        }
269
270        outHeader->nTimeStamp =
271            mAnchorTimeUs
272                + (mNumFramesOutput * 1000000ll) / mConfig->samplingRate;
273
274        outHeader->nFlags = 0;
275
276        CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
277
278        inHeader->nOffset += mConfig->inputBufferUsedLength;
279        inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
280
281        mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
282
283        if (inHeader->nFilledLen == 0) {
284            inInfo->mOwnedByUs = false;
285            inQueue.erase(inQueue.begin());
286            inInfo = NULL;
287            notifyEmptyBufferDone(inHeader);
288            inHeader = NULL;
289        }
290
291        outInfo->mOwnedByUs = false;
292        outQueue.erase(outQueue.begin());
293        outInfo = NULL;
294        notifyFillBufferDone(outHeader);
295        outHeader = NULL;
296    }
297}
298
299void SoftMP3::onPortFlushCompleted(OMX_U32 portIndex) {
300    if (portIndex == 0) {
301        // Make sure that the next buffer output does not still
302        // depend on fragments from the last one decoded.
303        pvmp3_InitDecoder(mConfig, mDecoderBuf);
304        mIsFirst = true;
305    }
306}
307
308void SoftMP3::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
309    if (portIndex != 1) {
310        return;
311    }
312
313    switch (mOutputPortSettingsChange) {
314        case NONE:
315            break;
316
317        case AWAITING_DISABLED:
318        {
319            CHECK(!enabled);
320            mOutputPortSettingsChange = AWAITING_ENABLED;
321            break;
322        }
323
324        default:
325        {
326            CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
327            CHECK(enabled);
328            mOutputPortSettingsChange = NONE;
329            break;
330        }
331    }
332}
333
334}  // namespace android
335
336android::SoftOMXComponent *createSoftOMXComponent(
337        const char *name, const OMX_CALLBACKTYPE *callbacks,
338        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
339    return new android::SoftMP3(name, callbacks, appData, component);
340}
341