SoftAAC2.cpp revision 143a951f1f19161fa12ca97f3dee85094078365a
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//#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
21#include "SoftAAC2.h"
22#include <OMX_AudioExt.h>
23#include <OMX_IndexExt.h>
24
25#include <cutils/properties.h>
26#include <media/stagefright/foundation/ADebug.h>
27#include <media/stagefright/foundation/hexdump.h>
28#include <media/stagefright/MediaErrors.h>
29
30#include <math.h>
31
32#define FILEREAD_MAX_LAYERS 2
33
34#define DRC_DEFAULT_MOBILE_REF_LEVEL 64  /* 64*-0.25dB = -16 dB below full scale for mobile conf */
35#define DRC_DEFAULT_MOBILE_DRC_CUT   127 /* maximum compression of dynamic range for mobile conf */
36#define DRC_DEFAULT_MOBILE_DRC_BOOST 127 /* maximum compression of dynamic range for mobile conf */
37#define DRC_DEFAULT_MOBILE_DRC_HEAVY 1   /* switch for heavy compression for mobile conf */
38#define DRC_DEFAULT_MOBILE_ENC_LEVEL -1 /* encoder target level; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
39#define MAX_CHANNEL_COUNT            8  /* maximum number of audio channels that can be decoded */
40// names of properties that can be used to override the default DRC settings
41#define PROP_DRC_OVERRIDE_REF_LEVEL  "aac_drc_reference_level"
42#define PROP_DRC_OVERRIDE_CUT        "aac_drc_cut"
43#define PROP_DRC_OVERRIDE_BOOST      "aac_drc_boost"
44#define PROP_DRC_OVERRIDE_HEAVY      "aac_drc_heavy"
45#define PROP_DRC_OVERRIDE_ENC_LEVEL "aac_drc_enc_target_level"
46
47namespace android {
48
49template<class T>
50static void InitOMXParams(T *params) {
51    params->nSize = sizeof(T);
52    params->nVersion.s.nVersionMajor = 1;
53    params->nVersion.s.nVersionMinor = 0;
54    params->nVersion.s.nRevision = 0;
55    params->nVersion.s.nStep = 0;
56}
57
58SoftAAC2::SoftAAC2(
59        const char *name,
60        const OMX_CALLBACKTYPE *callbacks,
61        OMX_PTR appData,
62        OMX_COMPONENTTYPE **component)
63    : SimpleSoftOMXComponent(name, callbacks, appData, component),
64      mAACDecoder(NULL),
65      mStreamInfo(NULL),
66      mIsADTS(false),
67      mInputBufferCount(0),
68      mOutputBufferCount(0),
69      mSignalledError(false),
70      mLastInHeader(NULL),
71      mCurrentInputTime(0),
72      mOutputPortSettingsChange(NONE) {
73    initPorts();
74    CHECK_EQ(initDecoder(), (status_t)OK);
75}
76
77SoftAAC2::~SoftAAC2() {
78    aacDecoder_Close(mAACDecoder);
79    delete mOutputDelayRingBuffer;
80}
81
82void SoftAAC2::initPorts() {
83    OMX_PARAM_PORTDEFINITIONTYPE def;
84    InitOMXParams(&def);
85
86    def.nPortIndex = 0;
87    def.eDir = OMX_DirInput;
88    def.nBufferCountMin = kNumInputBuffers;
89    def.nBufferCountActual = def.nBufferCountMin;
90    def.nBufferSize = 8192;
91    def.bEnabled = OMX_TRUE;
92    def.bPopulated = OMX_FALSE;
93    def.eDomain = OMX_PortDomainAudio;
94    def.bBuffersContiguous = OMX_FALSE;
95    def.nBufferAlignment = 1;
96
97    def.format.audio.cMIMEType = const_cast<char *>("audio/aac");
98    def.format.audio.pNativeRender = NULL;
99    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
100    def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
101
102    addPort(def);
103
104    def.nPortIndex = 1;
105    def.eDir = OMX_DirOutput;
106    def.nBufferCountMin = kNumOutputBuffers;
107    def.nBufferCountActual = def.nBufferCountMin;
108    def.nBufferSize = 4096 * MAX_CHANNEL_COUNT;
109    def.bEnabled = OMX_TRUE;
110    def.bPopulated = OMX_FALSE;
111    def.eDomain = OMX_PortDomainAudio;
112    def.bBuffersContiguous = OMX_FALSE;
113    def.nBufferAlignment = 2;
114
115    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
116    def.format.audio.pNativeRender = NULL;
117    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
118    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
119
120    addPort(def);
121}
122
123status_t SoftAAC2::initDecoder() {
124    ALOGV("initDecoder()");
125    status_t status = UNKNOWN_ERROR;
126    mAACDecoder = aacDecoder_Open(TT_MP4_ADIF, /* num layers */ 1);
127    if (mAACDecoder != NULL) {
128        mStreamInfo = aacDecoder_GetStreamInfo(mAACDecoder);
129        if (mStreamInfo != NULL) {
130            status = OK;
131        }
132    }
133
134    mEndOfInput = false;
135    mEndOfOutput = false;
136    mOutputDelayCompensated = 0;
137    mOutputDelayRingBufferSize = 2048 * MAX_CHANNEL_COUNT * kNumDelayBlocksMax;
138    mOutputDelayRingBuffer = new short[mOutputDelayRingBufferSize];
139    mOutputDelayRingBufferWritePos = 0;
140    mOutputDelayRingBufferReadPos = 0;
141
142    if (mAACDecoder == NULL) {
143        ALOGE("AAC decoder is null. TODO: Can not call aacDecoder_SetParam in the following code");
144    }
145
146    //aacDecoder_SetParam(mAACDecoder, AAC_PCM_LIMITER_ENABLE, 0);
147
148    //init DRC wrapper
149    mDrcWrap.setDecoderHandle(mAACDecoder);
150    mDrcWrap.submitStreamData(mStreamInfo);
151
152    // for streams that contain metadata, use the mobile profile DRC settings unless overridden by platform properties
153    // TODO: change the DRC settings depending on audio output device type (HDMI, loadspeaker, headphone)
154    char value[PROPERTY_VALUE_MAX];
155    //  DRC_PRES_MODE_WRAP_DESIRED_TARGET
156    if (property_get(PROP_DRC_OVERRIDE_REF_LEVEL, value, NULL)) {
157        unsigned refLevel = atoi(value);
158        ALOGV("AAC decoder using desired DRC target reference level of %d instead of %d", refLevel,
159                DRC_DEFAULT_MOBILE_REF_LEVEL);
160        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET, refLevel);
161    } else {
162        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET, DRC_DEFAULT_MOBILE_REF_LEVEL);
163    }
164    //  DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR
165    if (property_get(PROP_DRC_OVERRIDE_CUT, value, NULL)) {
166        unsigned cut = atoi(value);
167        ALOGV("AAC decoder using desired DRC attenuation factor of %d instead of %d", cut,
168                DRC_DEFAULT_MOBILE_DRC_CUT);
169        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, cut);
170    } else {
171        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, DRC_DEFAULT_MOBILE_DRC_CUT);
172    }
173    //  DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR
174    if (property_get(PROP_DRC_OVERRIDE_BOOST, value, NULL)) {
175        unsigned boost = atoi(value);
176        ALOGV("AAC decoder using desired DRC boost factor of %d instead of %d", boost,
177                DRC_DEFAULT_MOBILE_DRC_BOOST);
178        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR, boost);
179    } else {
180        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR, DRC_DEFAULT_MOBILE_DRC_BOOST);
181    }
182    //  DRC_PRES_MODE_WRAP_DESIRED_HEAVY
183    if (property_get(PROP_DRC_OVERRIDE_HEAVY, value, NULL)) {
184        unsigned heavy = atoi(value);
185        ALOGV("AAC decoder using desried DRC heavy compression switch of %d instead of %d", heavy,
186                DRC_DEFAULT_MOBILE_DRC_HEAVY);
187        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY, heavy);
188    } else {
189        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY, DRC_DEFAULT_MOBILE_DRC_HEAVY);
190    }
191    // DRC_PRES_MODE_WRAP_ENCODER_TARGET
192    if (property_get(PROP_DRC_OVERRIDE_ENC_LEVEL, value, NULL)) {
193        unsigned encoderRefLevel = atoi(value);
194        ALOGV("AAC decoder using encoder-side DRC reference level of %d instead of %d",
195                encoderRefLevel, DRC_DEFAULT_MOBILE_ENC_LEVEL);
196        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET, encoderRefLevel);
197    } else {
198        mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET, DRC_DEFAULT_MOBILE_ENC_LEVEL);
199    }
200
201    return status;
202}
203
204OMX_ERRORTYPE SoftAAC2::internalGetParameter(
205        OMX_INDEXTYPE index, OMX_PTR params) {
206    switch (index) {
207        case OMX_IndexParamAudioAac:
208        {
209            OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
210                (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
211
212            if (aacParams->nPortIndex != 0) {
213                return OMX_ErrorUndefined;
214            }
215
216            aacParams->nBitRate = 0;
217            aacParams->nAudioBandWidth = 0;
218            aacParams->nAACtools = 0;
219            aacParams->nAACERtools = 0;
220            aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
221
222            aacParams->eAACStreamFormat =
223                mIsADTS
224                    ? OMX_AUDIO_AACStreamFormatMP4ADTS
225                    : OMX_AUDIO_AACStreamFormatMP4FF;
226
227            aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
228
229            if (!isConfigured()) {
230                aacParams->nChannels = 1;
231                aacParams->nSampleRate = 44100;
232                aacParams->nFrameLength = 0;
233            } else {
234                aacParams->nChannels = mStreamInfo->numChannels;
235                aacParams->nSampleRate = mStreamInfo->sampleRate;
236                aacParams->nFrameLength = mStreamInfo->frameSize;
237            }
238
239            return OMX_ErrorNone;
240        }
241
242        case OMX_IndexParamAudioPcm:
243        {
244            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
245                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
246
247            if (pcmParams->nPortIndex != 1) {
248                return OMX_ErrorUndefined;
249            }
250
251            pcmParams->eNumData = OMX_NumericalDataSigned;
252            pcmParams->eEndian = OMX_EndianBig;
253            pcmParams->bInterleaved = OMX_TRUE;
254            pcmParams->nBitPerSample = 16;
255            pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
256            pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
257            pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
258            pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF;
259            pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE;
260            pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS;
261            pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS;
262
263            if (!isConfigured()) {
264                pcmParams->nChannels = 1;
265                pcmParams->nSamplingRate = 44100;
266            } else {
267                pcmParams->nChannels = mStreamInfo->numChannels;
268                pcmParams->nSamplingRate = mStreamInfo->sampleRate;
269            }
270
271            return OMX_ErrorNone;
272        }
273
274        default:
275            return SimpleSoftOMXComponent::internalGetParameter(index, params);
276    }
277}
278
279OMX_ERRORTYPE SoftAAC2::internalSetParameter(
280        OMX_INDEXTYPE index, const OMX_PTR params) {
281    switch ((int)index) {
282        case OMX_IndexParamStandardComponentRole:
283        {
284            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
285                (const OMX_PARAM_COMPONENTROLETYPE *)params;
286
287            if (strncmp((const char *)roleParams->cRole,
288                        "audio_decoder.aac",
289                        OMX_MAX_STRINGNAME_SIZE - 1)) {
290                return OMX_ErrorUndefined;
291            }
292
293            return OMX_ErrorNone;
294        }
295
296        case OMX_IndexParamAudioAac:
297        {
298            const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
299                (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
300
301            if (aacParams->nPortIndex != 0) {
302                return OMX_ErrorUndefined;
303            }
304
305            if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) {
306                mIsADTS = false;
307            } else if (aacParams->eAACStreamFormat
308                        == OMX_AUDIO_AACStreamFormatMP4ADTS) {
309                mIsADTS = true;
310            } else {
311                return OMX_ErrorUndefined;
312            }
313
314            return OMX_ErrorNone;
315        }
316
317        case OMX_IndexParamAudioAndroidAacPresentation:
318        {
319            const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *aacPresParams =
320                    (const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *)params;
321            // for the following parameters of the OMX_AUDIO_PARAM_AACPROFILETYPE structure,
322            // a value of -1 implies the parameter is not set by the application:
323            //   nMaxOutputChannels     uses default platform properties, see configureDownmix()
324            //   nDrcCut                uses default platform properties, see initDecoder()
325            //   nDrcBoost                idem
326            //   nHeavyCompression        idem
327            //   nTargetReferenceLevel    idem
328            //   nEncodedTargetLevel      idem
329            if (aacPresParams->nMaxOutputChannels >= 0) {
330                int max;
331                if (aacPresParams->nMaxOutputChannels >= 8) { max = 8; }
332                else if (aacPresParams->nMaxOutputChannels >= 6) { max = 6; }
333                else if (aacPresParams->nMaxOutputChannels >= 2) { max = 2; }
334                else {
335                    // -1 or 0: disable downmix,  1: mono
336                    max = aacPresParams->nMaxOutputChannels;
337                }
338                ALOGV("set nMaxOutputChannels=%d", max);
339                aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, max);
340            }
341            bool updateDrcWrapper = false;
342            if (aacPresParams->nDrcBoost >= 0) {
343                ALOGV("set nDrcBoost=%d", aacPresParams->nDrcBoost);
344                mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR,
345                        aacPresParams->nDrcBoost);
346                updateDrcWrapper = true;
347            }
348            if (aacPresParams->nDrcCut >= 0) {
349                ALOGV("set nDrcCut=%d", aacPresParams->nDrcCut);
350                mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, aacPresParams->nDrcCut);
351                updateDrcWrapper = true;
352            }
353            if (aacPresParams->nHeavyCompression >= 0) {
354                ALOGV("set nHeavyCompression=%d", aacPresParams->nHeavyCompression);
355                mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY,
356                        aacPresParams->nHeavyCompression);
357                updateDrcWrapper = true;
358            }
359            if (aacPresParams->nTargetReferenceLevel >= 0) {
360                ALOGV("set nTargetReferenceLevel=%d", aacPresParams->nTargetReferenceLevel);
361                mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET,
362                        aacPresParams->nTargetReferenceLevel);
363                updateDrcWrapper = true;
364            }
365            if (aacPresParams->nEncodedTargetLevel >= 0) {
366                ALOGV("set nEncodedTargetLevel=%d", aacPresParams->nEncodedTargetLevel);
367                mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET,
368                        aacPresParams->nEncodedTargetLevel);
369                updateDrcWrapper = true;
370            }
371            if (updateDrcWrapper) {
372                mDrcWrap.update();
373            }
374
375            return OMX_ErrorNone;
376        }
377
378        case OMX_IndexParamAudioPcm:
379        {
380            const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
381                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
382
383            if (pcmParams->nPortIndex != 1) {
384                return OMX_ErrorUndefined;
385            }
386
387            return OMX_ErrorNone;
388        }
389
390        default:
391            return SimpleSoftOMXComponent::internalSetParameter(index, params);
392    }
393}
394
395bool SoftAAC2::isConfigured() const {
396    return mInputBufferCount > 0;
397}
398
399void SoftAAC2::configureDownmix() const {
400    char value[PROPERTY_VALUE_MAX];
401    if (!(property_get("media.aac_51_output_enabled", value, NULL)
402            && (!strcmp(value, "1") || !strcasecmp(value, "true")))) {
403        ALOGI("limiting to stereo output");
404        aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, 2);
405        // By default, the decoder creates a 5.1 channel downmix signal
406        // for seven and eight channel input streams. To enable 6.1 and 7.1 channel output
407        // use aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, -1)
408    }
409}
410
411bool SoftAAC2::outputDelayRingBufferPutSamples(INT_PCM *samples, int32_t numSamples) {
412    if (mOutputDelayRingBufferWritePos + numSamples <= mOutputDelayRingBufferSize
413            && (mOutputDelayRingBufferReadPos <= mOutputDelayRingBufferWritePos
414                    || mOutputDelayRingBufferReadPos > mOutputDelayRingBufferWritePos + numSamples)) {
415        // faster memcopy loop without checks, if the preconditions allow this
416        for (int32_t i = 0; i < numSamples; i++) {
417            mOutputDelayRingBuffer[mOutputDelayRingBufferWritePos++] = samples[i];
418        }
419
420        if (mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferSize) {
421            mOutputDelayRingBufferWritePos -= mOutputDelayRingBufferSize;
422        }
423        if (mOutputDelayRingBufferWritePos == mOutputDelayRingBufferReadPos) {
424            ALOGE("RING BUFFER OVERFLOW");
425            return false;
426        }
427    } else {
428        ALOGV("slow SoftAAC2::outputDelayRingBufferPutSamples()");
429
430        for (int32_t i = 0; i < numSamples; i++) {
431            mOutputDelayRingBuffer[mOutputDelayRingBufferWritePos] = samples[i];
432            mOutputDelayRingBufferWritePos++;
433            if (mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferSize) {
434                mOutputDelayRingBufferWritePos -= mOutputDelayRingBufferSize;
435            }
436            if (mOutputDelayRingBufferWritePos == mOutputDelayRingBufferReadPos) {
437                ALOGE("RING BUFFER OVERFLOW");
438                return false;
439            }
440        }
441    }
442    return true;
443}
444
445int32_t SoftAAC2::outputDelayRingBufferGetSamples(INT_PCM *samples, int32_t numSamples) {
446    if (mOutputDelayRingBufferReadPos + numSamples <= mOutputDelayRingBufferSize
447            && (mOutputDelayRingBufferWritePos < mOutputDelayRingBufferReadPos
448                    || mOutputDelayRingBufferWritePos >= mOutputDelayRingBufferReadPos + numSamples)) {
449        // faster memcopy loop without checks, if the preconditions allow this
450        if (samples != 0) {
451            for (int32_t i = 0; i < numSamples; i++) {
452                samples[i] = mOutputDelayRingBuffer[mOutputDelayRingBufferReadPos++];
453            }
454        } else {
455            mOutputDelayRingBufferReadPos += numSamples;
456        }
457        if (mOutputDelayRingBufferReadPos >= mOutputDelayRingBufferSize) {
458            mOutputDelayRingBufferReadPos -= mOutputDelayRingBufferSize;
459        }
460    } else {
461        ALOGV("slow SoftAAC2::outputDelayRingBufferGetSamples()");
462
463        for (int32_t i = 0; i < numSamples; i++) {
464            if (mOutputDelayRingBufferWritePos == mOutputDelayRingBufferReadPos) {
465                ALOGE("RING BUFFER UNDERRUN");
466                return -1;
467            }
468            if (samples != 0) {
469                samples[i] = mOutputDelayRingBuffer[mOutputDelayRingBufferReadPos];
470            }
471            mOutputDelayRingBufferReadPos++;
472            if (mOutputDelayRingBufferReadPos >= mOutputDelayRingBufferSize) {
473                mOutputDelayRingBufferReadPos -= mOutputDelayRingBufferSize;
474            }
475        }
476    }
477    return numSamples;
478}
479
480int32_t SoftAAC2::outputDelayRingBufferSamplesAvailable() {
481    int32_t available = mOutputDelayRingBufferWritePos - mOutputDelayRingBufferReadPos;
482    if (available < 0) {
483        available += mOutputDelayRingBufferSize;
484    }
485    if (available < 0) {
486        ALOGE("FATAL RING BUFFER ERROR");
487        return 0;
488    }
489    return available;
490}
491
492int32_t SoftAAC2::outputDelayRingBufferSamplesLeft() {
493    return mOutputDelayRingBufferSize - outputDelayRingBufferSamplesAvailable();
494}
495
496void SoftAAC2::onQueueFilled(OMX_U32 portIndex) {
497    if (mSignalledError || mOutputPortSettingsChange != NONE) {
498        return;
499    }
500
501    UCHAR* inBuffer[FILEREAD_MAX_LAYERS];
502    UINT inBufferLength[FILEREAD_MAX_LAYERS] = {0};
503    UINT bytesValid[FILEREAD_MAX_LAYERS] = {0};
504
505    List<BufferInfo *> &inQueue = getPortQueue(0);
506    List<BufferInfo *> &outQueue = getPortQueue(1);
507
508    if (portIndex == 0 && mInputBufferCount == 0) {
509        BufferInfo *inInfo = *inQueue.begin();
510        OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
511
512        inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
513        inBufferLength[0] = inHeader->nFilledLen;
514
515        AAC_DECODER_ERROR decoderErr =
516            aacDecoder_ConfigRaw(mAACDecoder,
517                                 inBuffer,
518                                 inBufferLength);
519
520        if (decoderErr != AAC_DEC_OK) {
521            ALOGW("aacDecoder_ConfigRaw decoderErr = 0x%4.4x", decoderErr);
522            mSignalledError = true;
523            notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
524            return;
525        }
526
527        mInputBufferCount++;
528        mOutputBufferCount++; // fake increase of outputBufferCount to keep the counters aligned
529
530        inInfo->mOwnedByUs = false;
531        inQueue.erase(inQueue.begin());
532        inInfo = NULL;
533        notifyEmptyBufferDone(inHeader);
534        inHeader = NULL;
535
536        configureDownmix();
537        // Only send out port settings changed event if both sample rate
538        // and numChannels are valid.
539        if (mStreamInfo->sampleRate && mStreamInfo->numChannels) {
540            ALOGI("Initially configuring decoder: %d Hz, %d channels",
541                mStreamInfo->sampleRate,
542                mStreamInfo->numChannels);
543
544            notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
545            mOutputPortSettingsChange = AWAITING_DISABLED;
546        }
547
548        return;
549    }
550
551    while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) {
552        if (!inQueue.empty()) {
553            INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
554            BufferInfo *inInfo = *inQueue.begin();
555            OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
556
557            if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
558                mEndOfInput = true;
559            } else {
560                mEndOfInput = false;
561            }
562
563            if (inHeader->nFilledLen == 0) {
564                inInfo->mOwnedByUs = false;
565                inQueue.erase(inQueue.begin());
566                mLastInHeader = NULL;
567                inInfo = NULL;
568                notifyEmptyBufferDone(inHeader);
569                inHeader = NULL;
570            } else {
571                if (mIsADTS) {
572                    size_t adtsHeaderSize = 0;
573                    // skip 30 bits, aac_frame_length follows.
574                    // ssssssss ssssiiip ppffffPc ccohCCll llllllll lll?????
575
576                    const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset;
577
578                    bool signalError = false;
579                    if (inHeader->nFilledLen < 7) {
580                        ALOGE("Audio data too short to contain even the ADTS header. "
581                                "Got %d bytes.", inHeader->nFilledLen);
582                        hexdump(adtsHeader, inHeader->nFilledLen);
583                        signalError = true;
584                    } else {
585                        bool protectionAbsent = (adtsHeader[1] & 1);
586
587                        unsigned aac_frame_length =
588                            ((adtsHeader[3] & 3) << 11)
589                            | (adtsHeader[4] << 3)
590                            | (adtsHeader[5] >> 5);
591
592                        if (inHeader->nFilledLen < aac_frame_length) {
593                            ALOGE("Not enough audio data for the complete frame. "
594                                    "Got %d bytes, frame size according to the ADTS "
595                                    "header is %u bytes.",
596                                    inHeader->nFilledLen, aac_frame_length);
597                            hexdump(adtsHeader, inHeader->nFilledLen);
598                            signalError = true;
599                        } else {
600                            adtsHeaderSize = (protectionAbsent ? 7 : 9);
601
602                            inBuffer[0] = (UCHAR *)adtsHeader + adtsHeaderSize;
603                            inBufferLength[0] = aac_frame_length - adtsHeaderSize;
604
605                            inHeader->nOffset += adtsHeaderSize;
606                            inHeader->nFilledLen -= adtsHeaderSize;
607                        }
608                    }
609
610                    if (signalError) {
611                        mSignalledError = true;
612
613                        notify(OMX_EventError,
614                               OMX_ErrorStreamCorrupt,
615                               ERROR_MALFORMED,
616                               NULL);
617
618                        return;
619                    }
620                } else {
621                    inBuffer[0] = inHeader->pBuffer + inHeader->nOffset;
622                    inBufferLength[0] = inHeader->nFilledLen;
623                }
624
625                // Fill and decode
626                bytesValid[0] = inBufferLength[0];
627
628                INT prevSampleRate = mStreamInfo->sampleRate;
629                INT prevNumChannels = mStreamInfo->numChannels;
630
631                if (inHeader != mLastInHeader) {
632                    mLastInHeader = inHeader;
633                    mCurrentInputTime = inHeader->nTimeStamp;
634                } else {
635                    if (mStreamInfo->sampleRate) {
636                        mCurrentInputTime += mStreamInfo->aacSamplesPerFrame *
637                                1000000ll / mStreamInfo->sampleRate;
638                    } else {
639                        ALOGW("no sample rate yet");
640                    }
641                }
642                mAnchorTimes.add(mCurrentInputTime);
643                aacDecoder_Fill(mAACDecoder,
644                                inBuffer,
645                                inBufferLength,
646                                bytesValid);
647
648                 // run DRC check
649                 mDrcWrap.submitStreamData(mStreamInfo);
650                 mDrcWrap.update();
651
652                AAC_DECODER_ERROR decoderErr =
653                    aacDecoder_DecodeFrame(mAACDecoder,
654                                           tmpOutBuffer,
655                                           2048 * MAX_CHANNEL_COUNT,
656                                           0 /* flags */);
657
658                if (decoderErr != AAC_DEC_OK) {
659                    ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
660                }
661
662                if (decoderErr == AAC_DEC_NOT_ENOUGH_BITS) {
663                    ALOGE("AAC_DEC_NOT_ENOUGH_BITS should never happen");
664                    mSignalledError = true;
665                    notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
666                    return;
667                }
668
669                if (bytesValid[0] != 0) {
670                    ALOGE("bytesValid[0] != 0 should never happen");
671                    mSignalledError = true;
672                    notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
673                    return;
674                }
675
676                size_t numOutBytes =
677                    mStreamInfo->frameSize * sizeof(int16_t) * mStreamInfo->numChannels;
678
679                if (decoderErr == AAC_DEC_OK) {
680                    if (!outputDelayRingBufferPutSamples(tmpOutBuffer,
681                            mStreamInfo->frameSize * mStreamInfo->numChannels)) {
682                        mSignalledError = true;
683                        notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
684                        return;
685                    }
686                    UINT inBufferUsedLength = inBufferLength[0] - bytesValid[0];
687                    inHeader->nFilledLen -= inBufferUsedLength;
688                    inHeader->nOffset += inBufferUsedLength;
689                } else {
690                    ALOGW("AAC decoder returned error 0x%4.4x, substituting silence", decoderErr);
691
692                    memset(tmpOutBuffer, 0, numOutBytes); // TODO: check for overflow
693
694                    if (!outputDelayRingBufferPutSamples(tmpOutBuffer,
695                            mStreamInfo->frameSize * mStreamInfo->numChannels)) {
696                        mSignalledError = true;
697                        notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
698                        return;
699                    }
700
701                    // Discard input buffer.
702                    inHeader->nFilledLen = 0;
703
704                    aacDecoder_SetParam(mAACDecoder, AAC_TPDEC_CLEAR_BUFFER, 1);
705
706                    // fall through
707                }
708
709                /*
710                 * AAC+/eAAC+ streams can be signalled in two ways: either explicitly
711                 * or implicitly, according to MPEG4 spec. AAC+/eAAC+ is a dual
712                 * rate system and the sampling rate in the final output is actually
713                 * doubled compared with the core AAC decoder sampling rate.
714                 *
715                 * Explicit signalling is done by explicitly defining SBR audio object
716                 * type in the bitstream. Implicit signalling is done by embedding
717                 * SBR content in AAC extension payload specific to SBR, and hence
718                 * requires an AAC decoder to perform pre-checks on actual audio frames.
719                 *
720                 * Thus, we could not say for sure whether a stream is
721                 * AAC+/eAAC+ until the first data frame is decoded.
722                 */
723                if (mInputBufferCount <= 2 || mOutputBufferCount > 1) { // TODO: <= 1
724                    if (mStreamInfo->sampleRate != prevSampleRate ||
725                        mStreamInfo->numChannels != prevNumChannels) {
726                        ALOGI("Reconfiguring decoder: %d->%d Hz, %d->%d channels",
727                              prevSampleRate, mStreamInfo->sampleRate,
728                              prevNumChannels, mStreamInfo->numChannels);
729
730                        notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
731                        mOutputPortSettingsChange = AWAITING_DISABLED;
732
733                        if (inHeader->nFilledLen == 0) {
734                            inInfo->mOwnedByUs = false;
735                            mInputBufferCount++;
736                            inQueue.erase(inQueue.begin());
737                            mLastInHeader = NULL;
738                            inInfo = NULL;
739                            notifyEmptyBufferDone(inHeader);
740                            inHeader = NULL;
741                        }
742                        return;
743                    }
744                } else if (!mStreamInfo->sampleRate || !mStreamInfo->numChannels) {
745                    ALOGW("Invalid AAC stream");
746                    mSignalledError = true;
747                    notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
748                    return;
749                }
750                if (inHeader->nFilledLen == 0) {
751                    inInfo->mOwnedByUs = false;
752                    mInputBufferCount++;
753                    inQueue.erase(inQueue.begin());
754                    mLastInHeader = NULL;
755                    inInfo = NULL;
756                    notifyEmptyBufferDone(inHeader);
757                    inHeader = NULL;
758                } else {
759                    ALOGV("inHeader->nFilledLen = %d", inHeader->nFilledLen);
760                }
761            }
762        }
763
764        int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels;
765
766        if (!mEndOfInput && mOutputDelayCompensated < outputDelay) {
767            // discard outputDelay at the beginning
768            int32_t toCompensate = outputDelay - mOutputDelayCompensated;
769            int32_t discard = outputDelayRingBufferSamplesAvailable();
770            if (discard > toCompensate) {
771                discard = toCompensate;
772            }
773            int32_t discarded = outputDelayRingBufferGetSamples(0, discard);
774            mOutputDelayCompensated += discarded;
775            continue;
776        }
777
778        if (mEndOfInput) {
779            while (mOutputDelayCompensated > 0) {
780                // a buffer big enough for MAX_CHANNEL_COUNT channels of decoded HE-AAC
781                INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
782
783                 // run DRC check
784                 mDrcWrap.submitStreamData(mStreamInfo);
785                 mDrcWrap.update();
786
787                AAC_DECODER_ERROR decoderErr =
788                    aacDecoder_DecodeFrame(mAACDecoder,
789                                           tmpOutBuffer,
790                                           2048 * MAX_CHANNEL_COUNT,
791                                           AACDEC_FLUSH);
792                if (decoderErr != AAC_DEC_OK) {
793                    ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
794                }
795
796                int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels;
797                if (tmpOutBufferSamples > mOutputDelayCompensated) {
798                    tmpOutBufferSamples = mOutputDelayCompensated;
799                }
800                outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples);
801                mOutputDelayCompensated -= tmpOutBufferSamples;
802            }
803        }
804
805        while (!outQueue.empty()
806                && outputDelayRingBufferSamplesAvailable()
807                        >= mStreamInfo->frameSize * mStreamInfo->numChannels) {
808            BufferInfo *outInfo = *outQueue.begin();
809            OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
810
811            if (outHeader->nOffset != 0) {
812                ALOGE("outHeader->nOffset != 0 is not handled");
813                mSignalledError = true;
814                notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
815                return;
816            }
817
818            INT_PCM *outBuffer =
819                    reinterpret_cast<INT_PCM *>(outHeader->pBuffer + outHeader->nOffset);
820            if (outHeader->nOffset
821                    + mStreamInfo->frameSize * mStreamInfo->numChannels * sizeof(int16_t)
822                    > outHeader->nAllocLen) {
823                ALOGE("buffer overflow");
824                mSignalledError = true;
825                notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
826                return;
827
828            }
829            int32_t ns = outputDelayRingBufferGetSamples(outBuffer,
830                    mStreamInfo->frameSize * mStreamInfo->numChannels); // TODO: check for overflow
831            if (ns != mStreamInfo->frameSize * mStreamInfo->numChannels) {
832                ALOGE("not a complete frame of samples available");
833                mSignalledError = true;
834                notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
835                return;
836            }
837
838            outHeader->nFilledLen = mStreamInfo->frameSize * mStreamInfo->numChannels
839                    * sizeof(int16_t);
840            if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) {
841                outHeader->nFlags = OMX_BUFFERFLAG_EOS;
842                mEndOfOutput = true;
843            } else {
844                outHeader->nFlags = 0;
845            }
846
847            outHeader->nTimeStamp = mAnchorTimes.isEmpty() ? 0 : mAnchorTimes.itemAt(0);
848            mAnchorTimes.removeAt(0);
849
850            mOutputBufferCount++;
851            outInfo->mOwnedByUs = false;
852            outQueue.erase(outQueue.begin());
853            outInfo = NULL;
854            notifyFillBufferDone(outHeader);
855            outHeader = NULL;
856        }
857
858        if (mEndOfInput) {
859            if (outputDelayRingBufferSamplesAvailable() > 0
860                    && outputDelayRingBufferSamplesAvailable()
861                            < mStreamInfo->frameSize * mStreamInfo->numChannels) {
862                ALOGE("not a complete frame of samples available");
863                mSignalledError = true;
864                notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
865                return;
866            }
867
868            if (mEndOfInput && !outQueue.empty() && outputDelayRingBufferSamplesAvailable() == 0) {
869                if (!mEndOfOutput) {
870                    // send empty block signaling EOS
871                    mEndOfOutput = true;
872                    BufferInfo *outInfo = *outQueue.begin();
873                    OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
874
875                    if (outHeader->nOffset != 0) {
876                        ALOGE("outHeader->nOffset != 0 is not handled");
877                        mSignalledError = true;
878                        notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
879                        return;
880                    }
881
882                    INT_PCM *outBuffer = reinterpret_cast<INT_PCM *>(outHeader->pBuffer
883                            + outHeader->nOffset);
884                    int32_t ns = 0;
885                    outHeader->nFilledLen = 0;
886                    outHeader->nFlags = OMX_BUFFERFLAG_EOS;
887
888                    outHeader->nTimeStamp = mAnchorTimes.itemAt(0);
889                    mAnchorTimes.removeAt(0);
890
891                    mOutputBufferCount++;
892                    outInfo->mOwnedByUs = false;
893                    outQueue.erase(outQueue.begin());
894                    outInfo = NULL;
895                    notifyFillBufferDone(outHeader);
896                    outHeader = NULL;
897                }
898                break; // if outQueue not empty but no more output
899            }
900        }
901    }
902}
903
904void SoftAAC2::onPortFlushCompleted(OMX_U32 portIndex) {
905    if (portIndex == 0) {
906        // Make sure that the next buffer output does not still
907        // depend on fragments from the last one decoded.
908        // drain all existing data
909        drainDecoder();
910        mAnchorTimes.clear();
911        mLastInHeader = NULL;
912    } else {
913        while (outputDelayRingBufferSamplesAvailable() > 0) {
914            int32_t ns = outputDelayRingBufferGetSamples(0,
915                    mStreamInfo->frameSize * mStreamInfo->numChannels);
916            if (ns != mStreamInfo->frameSize * mStreamInfo->numChannels) {
917                ALOGE("not a complete frame of samples available");
918            }
919            mOutputBufferCount++;
920        }
921        mOutputDelayRingBufferReadPos = mOutputDelayRingBufferWritePos;
922    }
923}
924
925void SoftAAC2::drainDecoder() {
926    int32_t outputDelay = mStreamInfo->outputDelay * mStreamInfo->numChannels;
927
928    // flush decoder until outputDelay is compensated
929    while (mOutputDelayCompensated > 0) {
930        // a buffer big enough for MAX_CHANNEL_COUNT channels of decoded HE-AAC
931        INT_PCM tmpOutBuffer[2048 * MAX_CHANNEL_COUNT];
932
933        // run DRC check
934        mDrcWrap.submitStreamData(mStreamInfo);
935        mDrcWrap.update();
936
937        AAC_DECODER_ERROR decoderErr =
938            aacDecoder_DecodeFrame(mAACDecoder,
939                                   tmpOutBuffer,
940                                   2048 * MAX_CHANNEL_COUNT,
941                                   AACDEC_FLUSH);
942        if (decoderErr != AAC_DEC_OK) {
943            ALOGW("aacDecoder_DecodeFrame decoderErr = 0x%4.4x", decoderErr);
944        }
945
946        int32_t tmpOutBufferSamples = mStreamInfo->frameSize * mStreamInfo->numChannels;
947        if (tmpOutBufferSamples > mOutputDelayCompensated) {
948            tmpOutBufferSamples = mOutputDelayCompensated;
949        }
950        outputDelayRingBufferPutSamples(tmpOutBuffer, tmpOutBufferSamples);
951
952        mOutputDelayCompensated -= tmpOutBufferSamples;
953    }
954}
955
956void SoftAAC2::onReset() {
957    drainDecoder();
958    // reset the "configured" state
959    mInputBufferCount = 0;
960    mOutputBufferCount = 0;
961    mOutputDelayCompensated = 0;
962    mOutputDelayRingBufferWritePos = 0;
963    mOutputDelayRingBufferReadPos = 0;
964    mEndOfInput = false;
965    mEndOfOutput = false;
966    mAnchorTimes.clear();
967    mLastInHeader = NULL;
968
969    // To make the codec behave the same before and after a reset, we need to invalidate the
970    // streaminfo struct. This does that:
971    mStreamInfo->sampleRate = 0; // TODO: mStreamInfo is read only
972
973    mSignalledError = false;
974    mOutputPortSettingsChange = NONE;
975}
976
977void SoftAAC2::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
978    if (portIndex != 1) {
979        return;
980    }
981
982    switch (mOutputPortSettingsChange) {
983        case NONE:
984            break;
985
986        case AWAITING_DISABLED:
987        {
988            CHECK(!enabled);
989            mOutputPortSettingsChange = AWAITING_ENABLED;
990            break;
991        }
992
993        default:
994        {
995            CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
996            CHECK(enabled);
997            mOutputPortSettingsChange = NONE;
998            break;
999        }
1000    }
1001}
1002
1003}  // namespace android
1004
1005android::SoftOMXComponent *createSoftOMXComponent(
1006        const char *name, const OMX_CALLBACKTYPE *callbacks,
1007        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
1008    return new android::SoftAAC2(name, callbacks, appData, component);
1009}
1010