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