SoftAAC2.cpp revision 41914becfd019c619783d875c61ef71db0e67400
1/*
2 * Copyright (C) 2012 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_TAG "SoftAAC2"
18#include <utils/Log.h>
19
20#include "SoftAAC2.h"
21
22#include <media/stagefright/foundation/ADebug.h>
23#include <media/stagefright/foundation/hexdump.h>
24
25#define FILEREAD_MAX_LAYERS 2
26
27namespace android {
28
29template<class T>
30static void InitOMXParams(T *params) {
31    params->nSize = sizeof(T);
32    params->nVersion.s.nVersionMajor = 1;
33    params->nVersion.s.nVersionMinor = 0;
34    params->nVersion.s.nRevision = 0;
35    params->nVersion.s.nStep = 0;
36}
37
38SoftAAC2::SoftAAC2(
39        const char *name,
40        const OMX_CALLBACKTYPE *callbacks,
41        OMX_PTR appData,
42        OMX_COMPONENTTYPE **component)
43    : SimpleSoftOMXComponent(name, callbacks, appData, component),
44      mAACDecoder(NULL),
45      mStreamInfo(NULL),
46      mIsADTS(false),
47      mInputBufferCount(0),
48      mSignalledError(false),
49      mInputDiscontinuity(false),
50      mAnchorTimeUs(0),
51      mNumSamplesOutput(0),
52      mOutputPortSettingsChange(NONE) {
53    initPorts();
54    CHECK_EQ(initDecoder(), (status_t)OK);
55}
56
57SoftAAC2::~SoftAAC2() {
58    aacDecoder_Close(mAACDecoder);
59}
60
61void SoftAAC2::initPorts() {
62    OMX_PARAM_PORTDEFINITIONTYPE def;
63    InitOMXParams(&def);
64
65    def.nPortIndex = 0;
66    def.eDir = OMX_DirInput;
67    def.nBufferCountMin = kNumBuffers;
68    def.nBufferCountActual = def.nBufferCountMin;
69    def.nBufferSize = 8192;
70    def.bEnabled = OMX_TRUE;
71    def.bPopulated = OMX_FALSE;
72    def.eDomain = OMX_PortDomainAudio;
73    def.bBuffersContiguous = OMX_FALSE;
74    def.nBufferAlignment = 1;
75
76    def.format.audio.cMIMEType = const_cast<char *>("audio/aac");
77    def.format.audio.pNativeRender = NULL;
78    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
79    def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
80
81    addPort(def);
82
83    def.nPortIndex = 1;
84    def.eDir = OMX_DirOutput;
85    def.nBufferCountMin = kNumBuffers;
86    def.nBufferCountActual = def.nBufferCountMin;
87    def.nBufferSize = 8192 * 2;
88    def.bEnabled = OMX_TRUE;
89    def.bPopulated = OMX_FALSE;
90    def.eDomain = OMX_PortDomainAudio;
91    def.bBuffersContiguous = OMX_FALSE;
92    def.nBufferAlignment = 2;
93
94    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
95    def.format.audio.pNativeRender = NULL;
96    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
97    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
98
99    addPort(def);
100}
101
102status_t SoftAAC2::initDecoder() {
103    status_t status = UNKNOWN_ERROR;
104    mAACDecoder = aacDecoder_Open(TT_MP4_RAW, /* num layers */ 1);
105    if (mAACDecoder != NULL) {
106        mStreamInfo = aacDecoder_GetStreamInfo(mAACDecoder);
107        if (mStreamInfo != NULL) {
108            status = OK;
109        }
110    }
111    mIsFirst = true;
112    return status;
113}
114
115OMX_ERRORTYPE SoftAAC2::internalGetParameter(
116        OMX_INDEXTYPE index, OMX_PTR params) {
117    switch (index) {
118        case OMX_IndexParamAudioAac:
119        {
120            OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
121                (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
122
123            if (aacParams->nPortIndex != 0) {
124                return OMX_ErrorUndefined;
125            }
126
127            aacParams->nBitRate = 0;
128            aacParams->nAudioBandWidth = 0;
129            aacParams->nAACtools = 0;
130            aacParams->nAACERtools = 0;
131            aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
132
133            aacParams->eAACStreamFormat =
134                mIsADTS
135                    ? OMX_AUDIO_AACStreamFormatMP4ADTS
136                    : OMX_AUDIO_AACStreamFormatMP4FF;
137
138            aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
139
140            if (!isConfigured()) {
141                aacParams->nChannels = 1;
142                aacParams->nSampleRate = 44100;
143                aacParams->nFrameLength = 0;
144            } else {
145                aacParams->nChannels = mStreamInfo->channelConfig;
146                aacParams->nSampleRate = mStreamInfo->aacSampleRate;
147                aacParams->nFrameLength = mStreamInfo->aacSamplesPerFrame;
148            }
149
150            return OMX_ErrorNone;
151        }
152
153        case OMX_IndexParamAudioPcm:
154        {
155            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
156                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
157
158            if (pcmParams->nPortIndex != 1) {
159                return OMX_ErrorUndefined;
160            }
161
162            pcmParams->eNumData = OMX_NumericalDataSigned;
163            pcmParams->eEndian = OMX_EndianBig;
164            pcmParams->bInterleaved = OMX_TRUE;
165            pcmParams->nBitPerSample = 16;
166            pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
167            pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
168            pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
169            pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF;
170            pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE;
171            pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS;
172            pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS;
173
174            if (!isConfigured()) {
175                pcmParams->nChannels = 1;
176                pcmParams->nSamplingRate = 44100;
177            } else {
178                pcmParams->nChannels = mStreamInfo->channelConfig;
179                pcmParams->nSamplingRate = mStreamInfo->sampleRate;
180            }
181
182            return OMX_ErrorNone;
183        }
184
185        default:
186            return SimpleSoftOMXComponent::internalGetParameter(index, params);
187    }
188}
189
190OMX_ERRORTYPE SoftAAC2::internalSetParameter(
191        OMX_INDEXTYPE index, const OMX_PTR params) {
192    switch (index) {
193        case OMX_IndexParamStandardComponentRole:
194        {
195            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
196                (const OMX_PARAM_COMPONENTROLETYPE *)params;
197
198            if (strncmp((const char *)roleParams->cRole,
199                        "audio_decoder.aac",
200                        OMX_MAX_STRINGNAME_SIZE - 1)) {
201                return OMX_ErrorUndefined;
202            }
203
204            return OMX_ErrorNone;
205        }
206
207        case OMX_IndexParamAudioAac:
208        {
209            const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
210                (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
211
212            if (aacParams->nPortIndex != 0) {
213                return OMX_ErrorUndefined;
214            }
215
216            if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) {
217                mIsADTS = false;
218            } else if (aacParams->eAACStreamFormat
219                        == OMX_AUDIO_AACStreamFormatMP4ADTS) {
220                mIsADTS = true;
221            } else {
222                return OMX_ErrorUndefined;
223            }
224
225            return OMX_ErrorNone;
226        }
227
228        case OMX_IndexParamAudioPcm:
229        {
230            const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
231                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
232
233            if (pcmParams->nPortIndex != 1) {
234                return OMX_ErrorUndefined;
235            }
236
237            return OMX_ErrorNone;
238        }
239
240        default:
241            return SimpleSoftOMXComponent::internalSetParameter(index, params);
242    }
243}
244
245bool SoftAAC2::isConfigured() const {
246    return mInputBufferCount > 0;
247}
248
249void SoftAAC2::onQueueFilled(OMX_U32 portIndex) {
250    if (mSignalledError || mOutputPortSettingsChange != NONE) {
251        return;
252    }
253
254    UCHAR* inBuffer[FILEREAD_MAX_LAYERS];
255    UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0};
256    UINT bytesValid[FILEREAD_MAX_LAYERS] = {0};
257    AAC_DECODER_ERROR decoderErr;
258
259    List<BufferInfo *> &inQueue = getPortQueue(0);
260    List<BufferInfo *> &outQueue = getPortQueue(1);
261
262    if (portIndex == 0 && mInputBufferCount == 0) {
263        ++mInputBufferCount;
264        BufferInfo *info = *inQueue.begin();
265        OMX_BUFFERHEADERTYPE *header = info->mHeader;
266
267        inBuffer[0] = header->pBuffer + header->nOffset;
268        inBufferLength[0] = header->nFilledLen;
269
270        AAC_DECODER_ERROR decoderErr =
271            aacDecoder_ConfigRaw(mAACDecoder,
272                                 inBuffer,
273                                 inBufferLength);
274
275        if (decoderErr != AAC_DEC_OK) {
276            mSignalledError = true;
277            notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
278            return;
279        }
280
281        inQueue.erase(inQueue.begin());
282        info->mOwnedByUs = false;
283        notifyEmptyBufferDone(header);
284
285        notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
286        mOutputPortSettingsChange = AWAITING_DISABLED;
287        return;
288    }
289
290    while (!inQueue.empty() && !outQueue.empty()) {
291        BufferInfo *inInfo = *inQueue.begin();
292        OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
293
294        BufferInfo *outInfo = *outQueue.begin();
295        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
296
297        if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
298            inQueue.erase(inQueue.begin());
299            inInfo->mOwnedByUs = false;
300            notifyEmptyBufferDone(inHeader);
301
302            // flush out the decoder's delayed data by calling DecodeFrame one more time, with
303            // the AACDEC_FLUSH flag set
304            INT_PCM *outBuffer =
305                    reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset);
306            decoderErr = aacDecoder_DecodeFrame(mAACDecoder,
307                                                outBuffer,
308                                                outHeader->nAllocLen,
309                                                AACDEC_FLUSH);
310            outHeader->nFilledLen =
311                    mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels;
312            outHeader->nFlags = OMX_BUFFERFLAG_EOS;
313
314            outQueue.erase(outQueue.begin());
315            outInfo->mOwnedByUs = false;
316            notifyFillBufferDone(outHeader);
317            return;
318        }
319
320        if (inHeader->nOffset == 0) {
321            mAnchorTimeUs = inHeader->nTimeStamp;
322            mNumSamplesOutput = 0;
323        }
324
325        size_t adtsHeaderSize = 0;
326        if (mIsADTS) {
327            // skip 30 bits, aac_frame_length follows.
328            // ssssssss ssssiiip ppffffPc ccohCCll llllllll lll?????
329
330            const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset;
331
332            CHECK_GE(inHeader->nFilledLen, 7);
333
334            bool protectionAbsent = (adtsHeader[1] & 1);
335
336            unsigned aac_frame_length =
337                ((adtsHeader[3] & 3) << 11)
338                | (adtsHeader[4] << 3)
339                | (adtsHeader[5] >> 5);
340
341            CHECK_GE(inHeader->nFilledLen, aac_frame_length);
342
343            adtsHeaderSize = (protectionAbsent ? 7 : 9);
344
345            inBuffer[0] = (UCHAR *)adtsHeader + adtsHeaderSize;
346            inBufferLength[0] = aac_frame_length - adtsHeaderSize;
347
348            inHeader->nOffset += adtsHeaderSize;
349            inHeader->nFilledLen -= adtsHeaderSize;
350        } else {
351            inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
352            inBufferLength[0] = inHeader->nFilledLen;
353        }
354
355
356        // Fill and decode
357        INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset);
358        bytesValid[0] = inBufferLength[0];
359
360        int flags = mInputDiscontinuity ? AACDEC_INTR : 0;
361        int prevSampleRate = mStreamInfo->sampleRate;
362        decoderErr = aacDecoder_Fill(mAACDecoder,
363                                     inBuffer,
364                                     inBufferLength,
365                                     bytesValid);
366
367        decoderErr = aacDecoder_DecodeFrame(mAACDecoder,
368                                            outBuffer,
369                                            outHeader->nAllocLen,
370                                            flags);
371
372        mInputDiscontinuity = false;
373
374        /*
375         * AAC+/eAAC+ streams can be signalled in two ways: either explicitly
376         * or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual
377         * rate system and the sampling rate in the final output is actually
378         * doubled compared with the core AAC decoder sampling rate.
379         *
380         * Explicit signalling is done by explicitly defining SBR audio object
381         * type in the bitstream. Implicit signalling is done by embedding
382         * SBR content in AAC extension payload specific to SBR, and hence
383         * requires an AAC decoder to perform pre-checks on actual audio frames.
384         *
385         * Thus, we could not say for sure whether a stream is
386         * AAC+/eAAC+ until the first data frame is decoded.
387         */
388        if (mInputBufferCount <= 2) {
389            if (mStreamInfo->sampleRate != prevSampleRate) {
390                // We're going to want to revisit this input buffer, but
391                // may have already advanced the offset. Undo that if
392                // necessary.
393                inHeader->nOffset -= adtsHeaderSize;
394                inHeader->nFilledLen += adtsHeaderSize;
395
396                notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
397                mOutputPortSettingsChange = AWAITING_DISABLED;
398                return;
399            }
400        }
401
402        size_t numOutBytes =
403            mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels;
404
405        if (decoderErr == AAC_DEC_OK) {
406            UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0];
407            inHeader->nFilledLen -= inBufferUsedLength;
408            inHeader->nOffset += inBufferUsedLength;
409        } else {
410            ALOGW("AAC decoder returned error %d, substituting silence",
411                  decoderErr);
412
413            memset(outHeader->pBuffer + outHeader->nOffset, 0, numOutBytes);
414
415            // Discard input buffer.
416            inHeader->nFilledLen = 0;
417
418            // fall through
419        }
420
421        if (decoderErr == AAC_DEC_OK || mNumSamplesOutput > 0) {
422            // We'll only output data if we successfully decoded it or
423            // we've previously decoded valid data, in the latter case
424            // (decode failed) we'll output a silent frame.
425            if (mIsFirst) {
426                mIsFirst = false;
427                // the first decoded frame should be discarded to account for decoder delay
428                numOutBytes = 0;
429            }
430
431            outHeader->nFilledLen = numOutBytes;
432            outHeader->nFlags = 0;
433
434            outHeader->nTimeStamp =
435                mAnchorTimeUs
436                    + (mNumSamplesOutput * 1000000ll) / mStreamInfo->sampleRate;
437
438            mNumSamplesOutput += mStreamInfo->frameSize;
439
440            outInfo->mOwnedByUs = false;
441            outQueue.erase(outQueue.begin());
442            outInfo = NULL;
443            notifyFillBufferDone(outHeader);
444            outHeader = NULL;
445        }
446
447        if (inHeader->nFilledLen == 0) {
448            inInfo->mOwnedByUs = false;
449            inQueue.erase(inQueue.begin());
450            inInfo = NULL;
451            notifyEmptyBufferDone(inHeader);
452            inHeader = NULL;
453        }
454
455        if (decoderErr == AAC_DEC_OK) {
456            ++mInputBufferCount;
457        }
458    }
459}
460
461void SoftAAC2::onPortFlushCompleted(OMX_U32 portIndex) {
462    if (portIndex == 0) {
463        // Make sure that the next buffer output does not still
464        // depend on fragments from the last one decoded.
465        mInputDiscontinuity = true;
466        mIsFirst = true;
467    }
468}
469
470void SoftAAC2::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
471    if (portIndex != 1) {
472        return;
473    }
474
475    switch (mOutputPortSettingsChange) {
476        case NONE:
477            break;
478
479        case AWAITING_DISABLED:
480        {
481            CHECK(!enabled);
482            mOutputPortSettingsChange = AWAITING_ENABLED;
483            break;
484        }
485
486        default:
487        {
488            CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
489            CHECK(enabled);
490            mOutputPortSettingsChange = NONE;
491            break;
492        }
493    }
494}
495
496}  // namespace android
497
498android::SoftOMXComponent *createSoftOMXComponent(
499        const char *name, const OMX_CALLBACKTYPE *callbacks,
500        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
501    return new android::SoftAAC2(name, callbacks, appData, component);
502}
503