SoftAAC2.cpp revision eb61431af13741aa8b7e57a39f69bba5a6c190dc
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 = kNumInputBuffers;
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 = kNumOutputBuffers;
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->numChannels;
146                aacParams->nSampleRate = mStreamInfo->sampleRate;
147                aacParams->nFrameLength = mStreamInfo->frameSize;
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->numChannels;
179                pcmParams->nSamplingRate = mStreamInfo->sampleRate;
180            }
181
182            return OMX_ErrorNone;
183        }
184
185        default:
186            return SimpleSoftOMXComponent::internalGetParameter(index, params);
187    }
188
189}
190
191OMX_ERRORTYPE SoftAAC2::internalSetParameter(
192        OMX_INDEXTYPE index, const OMX_PTR params) {
193    switch (index) {
194        case OMX_IndexParamStandardComponentRole:
195        {
196            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
197                (const OMX_PARAM_COMPONENTROLETYPE *)params;
198
199            if (strncmp((const char *)roleParams->cRole,
200                        "audio_decoder.aac",
201                        OMX_MAX_STRINGNAME_SIZE - 1)) {
202                return OMX_ErrorUndefined;
203            }
204
205            return OMX_ErrorNone;
206        }
207
208        case OMX_IndexParamAudioAac:
209        {
210            const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
211                (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
212
213            if (aacParams->nPortIndex != 0) {
214                return OMX_ErrorUndefined;
215            }
216
217            if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) {
218                mIsADTS = false;
219            } else if (aacParams->eAACStreamFormat
220                        == OMX_AUDIO_AACStreamFormatMP4ADTS) {
221                mIsADTS = true;
222            } else {
223                return OMX_ErrorUndefined;
224            }
225
226            return OMX_ErrorNone;
227        }
228
229        case OMX_IndexParamAudioPcm:
230        {
231            const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
232                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
233
234            if (pcmParams->nPortIndex != 1) {
235                return OMX_ErrorUndefined;
236            }
237
238            return OMX_ErrorNone;
239        }
240
241        default:
242            return SimpleSoftOMXComponent::internalSetParameter(index, params);
243    }
244}
245
246bool SoftAAC2::isConfigured() const {
247    return mInputBufferCount > 0;
248}
249
250void SoftAAC2::onQueueFilled(OMX_U32 portIndex) {
251    if (mSignalledError || mOutputPortSettingsChange != NONE) {
252        return;
253    }
254
255    UCHAR* inBuffer[FILEREAD_MAX_LAYERS];
256    UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0};
257    UINT bytesValid[FILEREAD_MAX_LAYERS] = {0};
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        // Make the decoder more robust by pruning explicit backward compatible
271        // extension for LC, HE-AACv1 (SBR), HE-AACv2 (SBR + PS). We'll depend
272        // on implicit configuration.
273        if (inBufferLength[0] > 2) {
274            UCHAR aot = inBuffer[0][0] >> 3;
275            if (aot == 2 | aot == 5 | aot == 29) {
276                inBufferLength[0] = 2;
277            }
278        }
279        AAC_DECODER_ERROR decoderErr =
280            aacDecoder_ConfigRaw(mAACDecoder,
281                                 inBuffer,
282                                 inBufferLength);
283
284        if (decoderErr != AAC_DEC_OK) {
285            mSignalledError = true;
286            notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
287            return;
288        }
289        inQueue.erase(inQueue.begin());
290        info->mOwnedByUs = false;
291        notifyEmptyBufferDone(header);
292
293        notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
294        mOutputPortSettingsChange = AWAITING_DISABLED;
295        return;
296    }
297
298    while (!inQueue.empty() && !outQueue.empty()) {
299        BufferInfo *inInfo = *inQueue.begin();
300        OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
301
302        BufferInfo *outInfo = *outQueue.begin();
303        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
304
305        if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
306            inQueue.erase(inQueue.begin());
307            inInfo->mOwnedByUs = false;
308            notifyEmptyBufferDone(inHeader);
309
310            // flush out the decoder's delayed data by calling DecodeFrame one more time, with
311            // the AACDEC_FLUSH flag set
312            INT_PCM *outBuffer =
313                    reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset);
314            AAC_DECODER_ERROR decoderErr = aacDecoder_DecodeFrame(mAACDecoder,
315                                                                  outBuffer,
316                                                                  outHeader->nAllocLen,
317                                                                  AACDEC_FLUSH);
318            if (decoderErr != AAC_DEC_OK) {
319                mSignalledError = true;
320                notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
321                return;
322            }
323
324            outHeader->nFilledLen =
325                    mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels;
326            outHeader->nFlags = OMX_BUFFERFLAG_EOS;
327
328            outQueue.erase(outQueue.begin());
329            outInfo->mOwnedByUs = false;
330            notifyFillBufferDone(outHeader);
331            return;
332        }
333
334        if (inHeader->nOffset == 0) {
335            mAnchorTimeUs = inHeader->nTimeStamp;
336            mNumSamplesOutput = 0;
337        }
338
339        size_t adtsHeaderSize = 0;
340        if (mIsADTS) {
341            // skip 30 bits, aac_frame_length follows.
342            // ssssssss ssssiiip ppffffPc ccohCCll llllllll lll?????
343
344            const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset;
345
346            CHECK_GE(inHeader->nFilledLen, 7);
347
348            bool protectionAbsent = (adtsHeader[1] & 1);
349
350            unsigned aac_frame_length =
351                ((adtsHeader[3] & 3) << 11)
352                | (adtsHeader[4] << 3)
353                | (adtsHeader[5] >> 5);
354
355            CHECK_GE(inHeader->nFilledLen, aac_frame_length);
356
357            adtsHeaderSize = (protectionAbsent ? 7 : 9);
358
359            inBuffer[0] = (UCHAR *)adtsHeader + adtsHeaderSize;
360            inBufferLength[0] = aac_frame_length - adtsHeaderSize;
361
362            inHeader->nOffset += adtsHeaderSize;
363            inHeader->nFilledLen -= adtsHeaderSize;
364        } else {
365            inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
366            inBufferLength[0] = inHeader->nFilledLen;
367        }
368
369        // Fill and decode
370        INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset);
371        bytesValid[0] = inBufferLength[0];
372
373        int flags = mInputDiscontinuity ? AACDEC_INTR : 0;
374        int prevSampleRate = mStreamInfo->sampleRate;
375        int prevNumChannels = mStreamInfo->numChannels;
376
377        AAC_DECODER_ERROR decoderErr = AAC_DEC_NOT_ENOUGH_BITS;
378        while (bytesValid[0] > 0 && decoderErr == AAC_DEC_NOT_ENOUGH_BITS) {
379            aacDecoder_Fill(mAACDecoder,
380                            inBuffer,
381                            inBufferLength,
382                            bytesValid);
383
384            decoderErr = aacDecoder_DecodeFrame(mAACDecoder,
385                                                outBuffer,
386                                                outHeader->nAllocLen,
387                                                flags);
388
389        }
390        mInputDiscontinuity = false;
391
392        /*
393         * AAC+/eAAC+ streams can be signalled in two ways: either explicitly
394         * or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual
395         * rate system and the sampling rate in the final output is actually
396         * doubled compared with the core AAC decoder sampling rate.
397         *
398         * Explicit signalling is done by explicitly defining SBR audio object
399         * type in the bitstream. Implicit signalling is done by embedding
400         * SBR content in AAC extension payload specific to SBR, and hence
401         * requires an AAC decoder to perform pre-checks on actual audio frames.
402         *
403         * Thus, we could not say for sure whether a stream is
404         * AAC+/eAAC+ until the first data frame is decoded.
405         */
406        if (mInputBufferCount <= 2) {
407            if (mStreamInfo->sampleRate != prevSampleRate ||
408                mStreamInfo->numChannels != prevNumChannels) {
409                // We're going to want to revisit this input buffer, but
410                // may have already advanced the offset. Undo that if
411                // necessary.
412                inHeader->nOffset -= adtsHeaderSize;
413                inHeader->nFilledLen += adtsHeaderSize;
414
415                notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
416                mOutputPortSettingsChange = AWAITING_DISABLED;
417                return;
418            }
419        }
420
421        size_t numOutBytes =
422            mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels;
423
424        if (decoderErr == AAC_DEC_OK) {
425            UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0];
426            inHeader->nFilledLen -= inBufferUsedLength;
427            inHeader->nOffset += inBufferUsedLength;
428        } else {
429            ALOGW("AAC decoder returned error %d, substituting silence",
430                  decoderErr);
431
432            memset(outHeader->pBuffer + outHeader->nOffset, 0, numOutBytes);
433
434            // Discard input buffer.
435            inHeader->nFilledLen = 0;
436
437            // fall through
438        }
439
440        if (decoderErr == AAC_DEC_OK || mNumSamplesOutput > 0) {
441            // We'll only output data if we successfully decoded it or
442            // we've previously decoded valid data, in the latter case
443            // (decode failed) we'll output a silent frame.
444            if (mIsFirst) {
445                mIsFirst = false;
446                // the first decoded frame should be discarded to account for decoder delay
447                numOutBytes = 0;
448            }
449
450            outHeader->nFilledLen = numOutBytes;
451            outHeader->nFlags = 0;
452
453            outHeader->nTimeStamp =
454                mAnchorTimeUs
455                    + (mNumSamplesOutput * 1000000ll) / mStreamInfo->sampleRate;
456
457            mNumSamplesOutput += mStreamInfo->frameSize;
458
459            outInfo->mOwnedByUs = false;
460            outQueue.erase(outQueue.begin());
461            outInfo = NULL;
462            notifyFillBufferDone(outHeader);
463            outHeader = NULL;
464        }
465
466        if (inHeader->nFilledLen == 0) {
467            inInfo->mOwnedByUs = false;
468            inQueue.erase(inQueue.begin());
469            inInfo = NULL;
470            notifyEmptyBufferDone(inHeader);
471            inHeader = NULL;
472        }
473
474        if (decoderErr == AAC_DEC_OK) {
475            ++mInputBufferCount;
476        }
477    }
478}
479
480void SoftAAC2::onPortFlushCompleted(OMX_U32 portIndex) {
481    if (portIndex == 0) {
482        // Make sure that the next buffer output does not still
483        // depend on fragments from the last one decoded.
484        mInputDiscontinuity = true;
485        mIsFirst = true;
486    }
487}
488
489void SoftAAC2::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
490    if (portIndex != 1) {
491        return;
492    }
493
494    switch (mOutputPortSettingsChange) {
495        case NONE:
496            break;
497
498        case AWAITING_DISABLED:
499        {
500            CHECK(!enabled);
501            mOutputPortSettingsChange = AWAITING_ENABLED;
502            break;
503        }
504
505        default:
506        {
507            CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
508            CHECK(enabled);
509            mOutputPortSettingsChange = NONE;
510            break;
511        }
512    }
513}
514
515}  // namespace android
516
517android::SoftOMXComponent *createSoftOMXComponent(
518        const char *name, const OMX_CALLBACKTYPE *callbacks,
519        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
520    return new android::SoftAAC2(name, callbacks, appData, component);
521}
522