SoftMP3.cpp revision 6fc72b01a3b67903b52f1d33b1ad5c960b5365f1
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            if (!mIsFirst) {
195                // pad the end of the stream with 529 samples, since that many samples
196                // were trimmed off the beginning when decoding started
197                outHeader->nFilledLen =
198                    kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
199
200                memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
201            } else {
202                // Since we never discarded frames from the start, we won't have
203                // to add any padding at the end either.
204                outHeader->nFilledLen = 0;
205            }
206
207            outHeader->nFlags = OMX_BUFFERFLAG_EOS;
208
209            outQueue.erase(outQueue.begin());
210            outInfo->mOwnedByUs = false;
211            notifyFillBufferDone(outHeader);
212            return;
213        }
214
215        if (inHeader->nOffset == 0) {
216            mAnchorTimeUs = inHeader->nTimeStamp;
217            mNumFramesOutput = 0;
218        }
219
220        mConfig->pInputBuffer =
221            inHeader->pBuffer + inHeader->nOffset;
222
223        mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
224        mConfig->inputBufferMaxLength = 0;
225        mConfig->inputBufferUsedLength = 0;
226
227        mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
228
229        mConfig->pOutputBuffer =
230            reinterpret_cast<int16_t *>(outHeader->pBuffer);
231
232        ERROR_CODE decoderErr;
233        if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
234                != NO_DECODING_ERROR) {
235            ALOGV("mp3 decoder returned error %d", decoderErr);
236
237            if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
238                        && decoderErr != SIDE_INFO_ERROR) {
239                ALOGE("mp3 decoder returned error %d", decoderErr);
240
241                notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
242                mSignalledError = true;
243                return;
244            }
245
246            if (mConfig->outputFrameSize == 0) {
247                mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
248            }
249
250            // This is recoverable, just ignore the current frame and
251            // play silence instead.
252            memset(outHeader->pBuffer,
253                   0,
254                   mConfig->outputFrameSize * sizeof(int16_t));
255
256            mConfig->inputBufferUsedLength = inHeader->nFilledLen;
257        } else if (mConfig->samplingRate != mSamplingRate
258                || mConfig->num_channels != mNumChannels) {
259            mSamplingRate = mConfig->samplingRate;
260            mNumChannels = mConfig->num_channels;
261
262            notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
263            mOutputPortSettingsChange = AWAITING_DISABLED;
264            return;
265        }
266
267        if (mIsFirst) {
268            mIsFirst = false;
269            // The decoder delay is 529 samples, so trim that many samples off
270            // the start of the first output buffer. This essentially makes this
271            // decoder have zero delay, which the rest of the pipeline assumes.
272            outHeader->nOffset =
273                kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
274
275            outHeader->nFilledLen =
276                mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
277        } else {
278            outHeader->nOffset = 0;
279            outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
280        }
281
282        outHeader->nTimeStamp =
283            mAnchorTimeUs
284                + (mNumFramesOutput * 1000000ll) / mConfig->samplingRate;
285
286        outHeader->nFlags = 0;
287
288        CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
289
290        inHeader->nOffset += mConfig->inputBufferUsedLength;
291        inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
292
293        mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
294
295        if (inHeader->nFilledLen == 0) {
296            inInfo->mOwnedByUs = false;
297            inQueue.erase(inQueue.begin());
298            inInfo = NULL;
299            notifyEmptyBufferDone(inHeader);
300            inHeader = NULL;
301        }
302
303        outInfo->mOwnedByUs = false;
304        outQueue.erase(outQueue.begin());
305        outInfo = NULL;
306        notifyFillBufferDone(outHeader);
307        outHeader = NULL;
308    }
309}
310
311void SoftMP3::onPortFlushCompleted(OMX_U32 portIndex) {
312    if (portIndex == 0) {
313        // Make sure that the next buffer output does not still
314        // depend on fragments from the last one decoded.
315        pvmp3_InitDecoder(mConfig, mDecoderBuf);
316        mIsFirst = true;
317    }
318}
319
320void SoftMP3::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
321    if (portIndex != 1) {
322        return;
323    }
324
325    switch (mOutputPortSettingsChange) {
326        case NONE:
327            break;
328
329        case AWAITING_DISABLED:
330        {
331            CHECK(!enabled);
332            mOutputPortSettingsChange = AWAITING_ENABLED;
333            break;
334        }
335
336        default:
337        {
338            CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
339            CHECK(enabled);
340            mOutputPortSettingsChange = NONE;
341            break;
342        }
343    }
344}
345
346void SoftMP3::onReset() {
347    pvmp3_InitDecoder(mConfig, mDecoderBuf);
348    mIsFirst = true;
349}
350
351}  // namespace android
352
353android::SoftOMXComponent *createSoftOMXComponent(
354        const char *name, const OMX_CALLBACKTYPE *callbacks,
355        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
356    return new android::SoftMP3(name, callbacks, appData, component);
357}
358